1453 lines
60 KiB
TypeScript
1453 lines
60 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useEffect, useMemo, useRef, type ReactNode } from 'react';
|
|
import {
|
|
Sliders,
|
|
Plus,
|
|
Search,
|
|
RefreshCw,
|
|
ChevronDown,
|
|
ChevronRight,
|
|
Trash2,
|
|
Filter,
|
|
X,
|
|
Box,
|
|
FileSpreadsheet,
|
|
FileText,
|
|
Columns3,
|
|
GripVertical,
|
|
ArrowUpDown,
|
|
Calendar,
|
|
AlertTriangle,
|
|
} from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
import { format, subDays } from 'date-fns';
|
|
import { AnimatePresence, motion } from '@/lib/motion';
|
|
import { catalogService, AttributeTypeResponse } from '@/services/api/catalogService';
|
|
import { SlideOver } from '@/components/ui/SlideOver';
|
|
import { RowActionsMenu } from '@/components/ui/RowActionsMenu';
|
|
import { ViewModeToggle } from '@/components/ui/ViewModeToggle';
|
|
import { TablePagination, useClientPagination } from '@/components/ui/TablePagination';
|
|
|
|
type StatusFilter = 'active' | 'inactive';
|
|
type PresetFilter = 'with' | 'without';
|
|
type SortField = 'name' | 'code' | 'presets' | 'status';
|
|
type SortDir = 'asc' | 'desc';
|
|
type SortConfig = { field: SortField; dir: SortDir };
|
|
type FilterSection = 'name' | 'presets' | 'status';
|
|
|
|
type AttributeFilters = {
|
|
attributeIds: string[];
|
|
presets: PresetFilter[];
|
|
statuses: StatusFilter[];
|
|
};
|
|
|
|
const EMPTY_FILTERS: AttributeFilters = {
|
|
attributeIds: [],
|
|
presets: [],
|
|
statuses: [],
|
|
};
|
|
|
|
const FILTER_PAGE_SIZE = 5;
|
|
|
|
const EMPTY_COLUMNS = {
|
|
attributeName: true,
|
|
code: true,
|
|
presetValues: true,
|
|
status: true,
|
|
actions: true,
|
|
};
|
|
|
|
const COLUMN_OPTIONS = [
|
|
{ key: 'attributeName' as const, label: 'Attribute Name', locked: true },
|
|
{ key: 'code' as const, label: 'System Code', locked: false },
|
|
{ key: 'presetValues' as const, label: 'Preset Values', locked: false },
|
|
{ key: 'status' as const, label: 'Status', locked: false },
|
|
{ key: 'actions' as const, label: 'Actions', locked: false },
|
|
];
|
|
|
|
const SORT_OPTIONS: { field: SortField; dir: SortDir; label: string }[] = [
|
|
{ field: 'name', dir: 'asc', label: 'Name A-Z' },
|
|
{ field: 'name', dir: 'desc', label: 'Name Z-A' },
|
|
{ field: 'code', dir: 'asc', label: 'Code A-Z' },
|
|
{ field: 'code', dir: 'desc', label: 'Code Z-A' },
|
|
{ field: 'presets', dir: 'asc', label: 'Preset Count Ascending' },
|
|
{ field: 'presets', dir: 'desc', label: 'Preset Count Descending' },
|
|
{ field: 'status', dir: 'asc', label: 'Status Active first' },
|
|
{ field: 'status', dir: 'desc', label: 'Status Inactive first' },
|
|
];
|
|
|
|
const DEFAULT_SORT: SortConfig = { field: 'name', dir: 'asc' };
|
|
const DEFAULT_DATE_FROM = format(subDays(new Date(), 30), 'yyyy-MM-dd');
|
|
const DEFAULT_DATE_TO = format(new Date(), 'yyyy-MM-dd');
|
|
|
|
function normalizeId(value: unknown): string {
|
|
if (value == null) return '';
|
|
return String(value).trim();
|
|
}
|
|
|
|
function coerceFlag(value: unknown): boolean {
|
|
if (typeof value === 'boolean') return value;
|
|
if (typeof value === 'number') return value !== 0;
|
|
if (value == null) return false;
|
|
const normalized = String(value).trim().toLowerCase();
|
|
if (['true', '1', 'yes', 'enabled', 'active'].includes(normalized)) return true;
|
|
if (['false', '0', 'no', 'disabled', 'inactive', '', 'null', 'undefined'].includes(normalized)) return false;
|
|
return false;
|
|
}
|
|
|
|
function isAttributeActive(status?: string): boolean {
|
|
if (status == null || String(status).trim() === '') return true;
|
|
return coerceFlag(status);
|
|
}
|
|
|
|
function presetList(attribute: AttributeTypeResponse): string[] {
|
|
return (attribute.preset_values || []).filter((value) => String(value).trim() !== '');
|
|
}
|
|
|
|
function dayStartMs(isoDate: string): number {
|
|
const [year, month, day] = isoDate.split('-').map(Number);
|
|
if (!year || !month || !day) return NaN;
|
|
return new Date(year, month - 1, day, 0, 0, 0, 0).getTime();
|
|
}
|
|
|
|
function dayEndMs(isoDate: string): number {
|
|
const [year, month, day] = isoDate.split('-').map(Number);
|
|
if (!year || !month || !day) return NaN;
|
|
return new Date(year, month - 1, day, 23, 59, 59, 999).getTime();
|
|
}
|
|
|
|
export default function AttributesPage() {
|
|
const [attributes, setAttributes] = useState<AttributeTypeResponse[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [searchQuery, setSearchQuery] = useState('');
|
|
const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
|
|
const [openActionId, setOpenActionId] = useState<string | null>(null);
|
|
const [showFilterPanel, setShowFilterPanel] = useState(false);
|
|
const [showExportMenu, setShowExportMenu] = useState(false);
|
|
const [showColumnsPanel, setShowColumnsPanel] = useState(false);
|
|
const [showSortPanel, setShowSortPanel] = useState(false);
|
|
const [showDatePanel, setShowDatePanel] = useState(false);
|
|
const [draftFilters, setDraftFilters] = useState<AttributeFilters>(EMPTY_FILTERS);
|
|
const [activeFilters, setActiveFilters] = useState<AttributeFilters>(EMPTY_FILTERS);
|
|
const [expandedFilterSections, setExpandedFilterSections] = useState<Record<FilterSection, boolean>>({
|
|
name: false,
|
|
presets: true,
|
|
status: false,
|
|
});
|
|
const [filterSectionSearch, setFilterSectionSearch] = useState({ name: '' });
|
|
const [filterVisibleCounts, setFilterVisibleCounts] = useState({ name: FILTER_PAGE_SIZE });
|
|
const [visibleColumns, setVisibleColumns] = useState(EMPTY_COLUMNS);
|
|
const [sortConfig, setSortConfig] = useState<SortConfig>(DEFAULT_SORT);
|
|
const [dateFrom, setDateFrom] = useState(DEFAULT_DATE_FROM);
|
|
const [dateTo, setDateTo] = useState(DEFAULT_DATE_TO);
|
|
const [draftDateFrom, setDraftDateFrom] = useState(DEFAULT_DATE_FROM);
|
|
const [draftDateTo, setDraftDateTo] = useState(DEFAULT_DATE_TO);
|
|
const [dateFilterEnabled, setDateFilterEnabled] = useState(false);
|
|
const filterRef = useRef<HTMLDivElement>(null);
|
|
const exportRef = useRef<HTMLDivElement>(null);
|
|
const columnsRef = useRef<HTMLDivElement>(null);
|
|
const sortRef = useRef<HTMLDivElement>(null);
|
|
const dateRef = useRef<HTMLDivElement>(null);
|
|
|
|
const [showAttributeModal, setShowAttributeModal] = useState(false);
|
|
const [editingAttribute, setEditingAttribute] = useState<AttributeTypeResponse | null>(null);
|
|
const [attrName, setAttrName] = useState('');
|
|
const [attrCode, setAttrCode] = useState('');
|
|
const [presetValues, setPresetValues] = useState<string[]>([]);
|
|
const [newPresetInput, setNewPresetInput] = useState('');
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);
|
|
const [isDeleting, setIsDeleting] = useState(false);
|
|
|
|
const fetchData = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const fetchedAttrs = await catalogService.getAttributes();
|
|
setAttributes(fetchedAttrs);
|
|
} catch (err: any) {
|
|
toast.error(err?.message || 'Failed to load master attributes');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
fetchData();
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!showFilterPanel) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!filterRef.current?.contains(event.target as Node)) setShowFilterPanel(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowFilterPanel(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showFilterPanel]);
|
|
|
|
useEffect(() => {
|
|
if (!showExportMenu) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!exportRef.current?.contains(event.target as Node)) setShowExportMenu(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowExportMenu(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showExportMenu]);
|
|
|
|
useEffect(() => {
|
|
if (!showColumnsPanel) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!columnsRef.current?.contains(event.target as Node)) setShowColumnsPanel(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowColumnsPanel(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showColumnsPanel]);
|
|
|
|
useEffect(() => {
|
|
if (!showSortPanel) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!sortRef.current?.contains(event.target as Node)) setShowSortPanel(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowSortPanel(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showSortPanel]);
|
|
|
|
useEffect(() => {
|
|
if (!showDatePanel) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!dateRef.current?.contains(event.target as Node)) setShowDatePanel(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowDatePanel(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showDatePanel]);
|
|
|
|
const closeOverlays = () => {
|
|
setShowFilterPanel(false);
|
|
setShowColumnsPanel(false);
|
|
setShowSortPanel(false);
|
|
setShowDatePanel(false);
|
|
};
|
|
|
|
const handleViewModeChange = (mode: 'table' | 'grid') => {
|
|
setViewMode(mode);
|
|
setOpenActionId(null);
|
|
closeOverlays();
|
|
};
|
|
|
|
const handleOpenCreate = () => {
|
|
setEditingAttribute(null);
|
|
setAttrName('');
|
|
setAttrCode('');
|
|
setPresetValues([]);
|
|
setNewPresetInput('');
|
|
setShowAttributeModal(true);
|
|
};
|
|
|
|
const handleOpenEdit = (attribute: AttributeTypeResponse) => {
|
|
setEditingAttribute(attribute);
|
|
setAttrName(attribute.name);
|
|
setAttrCode(attribute.code);
|
|
setPresetValues(attribute.preset_values || []);
|
|
setNewPresetInput('');
|
|
setShowAttributeModal(true);
|
|
};
|
|
|
|
const closeAttributeDrawer = () => {
|
|
if (isSubmitting) return;
|
|
setShowAttributeModal(false);
|
|
};
|
|
|
|
const handleAddPresetValue = () => {
|
|
const val = newPresetInput.trim();
|
|
if (!val) return;
|
|
if (presetValues.some((item) => item.toLowerCase() === val.toLowerCase())) {
|
|
toast.error('Value already added');
|
|
return;
|
|
}
|
|
setPresetValues([...presetValues, val]);
|
|
setNewPresetInput('');
|
|
};
|
|
|
|
const handleRemovePresetValue = (idx: number) => {
|
|
setPresetValues(presetValues.filter((_, i) => i !== idx));
|
|
};
|
|
|
|
const handleSubmitAttribute = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (!attrName.trim() || !attrCode.trim()) {
|
|
toast.error('Both Attribute Name and System Code are required');
|
|
return;
|
|
}
|
|
setIsSubmitting(true);
|
|
try {
|
|
if (editingAttribute) {
|
|
const updated = await catalogService.updateAttribute(editingAttribute.attribute_id, {
|
|
name: attrName.trim(),
|
|
code: attrCode.trim().toLowerCase(),
|
|
preset_values: presetValues,
|
|
});
|
|
setAttributes(attributes.map((a) => (a.attribute_id === updated.attribute_id ? updated : a)));
|
|
toast.success(`Attribute "${updated.name}" updated successfully`);
|
|
} else {
|
|
const created = await catalogService.createAttribute({
|
|
name: attrName.trim(),
|
|
code: attrCode.trim().toLowerCase(),
|
|
preset_values: presetValues,
|
|
});
|
|
setAttributes([...attributes, created]);
|
|
toast.success(`Attribute "${created.name}" created successfully`);
|
|
}
|
|
setAttrName('');
|
|
setAttrCode('');
|
|
setPresetValues([]);
|
|
setNewPresetInput('');
|
|
setEditingAttribute(null);
|
|
setShowAttributeModal(false);
|
|
} catch (err: any) {
|
|
toast.error(err?.message || `Failed to ${editingAttribute ? 'update' : 'create'} attribute`);
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
};
|
|
|
|
const openDeleteModal = (id: string, name: string) => {
|
|
setOpenActionId(null);
|
|
setDeleteTarget({ id, name });
|
|
};
|
|
|
|
const closeDeleteModal = () => {
|
|
if (isDeleting) return;
|
|
setDeleteTarget(null);
|
|
};
|
|
|
|
const handleConfirmDelete = async () => {
|
|
if (!deleteTarget) return;
|
|
const { id, name } = deleteTarget;
|
|
setIsDeleting(true);
|
|
try {
|
|
setAttributes((prev) => prev.filter((a) => a.attribute_id !== id));
|
|
await catalogService.deleteAttribute(id);
|
|
toast.success(`Master attribute "${name}" deleted successfully`);
|
|
setDeleteTarget(null);
|
|
fetchData();
|
|
} catch (err: any) {
|
|
toast.error(err?.message || 'Failed to delete master attribute');
|
|
fetchData();
|
|
} finally {
|
|
setIsDeleting(false);
|
|
}
|
|
};
|
|
|
|
const filteredAttributes = useMemo(() => {
|
|
const q = searchQuery.trim().toLowerCase();
|
|
const fromTs = dateFilterEnabled && dateFrom ? dayStartMs(dateFrom) : null;
|
|
const toTs = dateFilterEnabled && dateTo ? dayEndMs(dateTo) : null;
|
|
|
|
const result = attributes.filter((a) => {
|
|
const values = presetList(a);
|
|
const searchMatch =
|
|
!q ||
|
|
(a.name || '').toLowerCase().includes(q) ||
|
|
(a.code || '').toLowerCase().includes(q) ||
|
|
values.some((value) => value.toLowerCase().includes(q));
|
|
|
|
const isActive = isAttributeActive(a.status);
|
|
const statusMatch =
|
|
activeFilters.statuses.length === 0 ||
|
|
(activeFilters.statuses.includes('active') && isActive) ||
|
|
(activeFilters.statuses.includes('inactive') && !isActive);
|
|
|
|
const attributeMatch =
|
|
activeFilters.attributeIds.length === 0 ||
|
|
activeFilters.attributeIds.includes(normalizeId(a.attribute_id));
|
|
|
|
const hasPresets = values.length > 0;
|
|
const presetMatch =
|
|
activeFilters.presets.length === 0 ||
|
|
(activeFilters.presets.includes('with') && hasPresets) ||
|
|
(activeFilters.presets.includes('without') && !hasPresets);
|
|
|
|
let dateMatch = true;
|
|
if (fromTs != null && toTs != null && !Number.isNaN(fromTs) && !Number.isNaN(toTs) && a.created_at) {
|
|
const createdTs = new Date(a.created_at).getTime();
|
|
if (!Number.isNaN(createdTs)) {
|
|
dateMatch = createdTs >= fromTs && createdTs <= toTs;
|
|
}
|
|
}
|
|
|
|
return searchMatch && attributeMatch && statusMatch && presetMatch && dateMatch;
|
|
});
|
|
|
|
const dir = sortConfig.dir === 'asc' ? 1 : -1;
|
|
return [...result].sort((a, b) => {
|
|
if (sortConfig.field === 'status') {
|
|
return (Number(isAttributeActive(a.status)) - Number(isAttributeActive(b.status))) * dir;
|
|
}
|
|
if (sortConfig.field === 'presets') {
|
|
return (presetList(a).length - presetList(b).length) * dir;
|
|
}
|
|
const left = sortConfig.field === 'code' ? a.code || '' : a.name || '';
|
|
const right = sortConfig.field === 'code' ? b.code || '' : b.name || '';
|
|
return left.localeCompare(right, undefined, { sensitivity: 'base' }) * dir;
|
|
});
|
|
}, [attributes, searchQuery, activeFilters, dateFrom, dateTo, dateFilterEnabled, sortConfig]);
|
|
|
|
const pager = useClientPagination(filteredAttributes);
|
|
|
|
const filtersActive =
|
|
activeFilters.attributeIds.length > 0 ||
|
|
activeFilters.presets.length > 0 ||
|
|
activeFilters.statuses.length > 0;
|
|
|
|
const sortedAttributeFilterOptions = useMemo(
|
|
() => [...attributes].sort((a, b) => a.name.localeCompare(b.name)),
|
|
[attributes]
|
|
);
|
|
|
|
const toggleFilterSection = (section: FilterSection) => {
|
|
setExpandedFilterSections((prev) => ({ ...prev, [section]: !prev[section] }));
|
|
};
|
|
|
|
const toggleDraftListValue = <T extends string>(
|
|
key: keyof Pick<AttributeFilters, 'attributeIds' | 'presets' | 'statuses'>,
|
|
value: T
|
|
) => {
|
|
setDraftFilters((prev) => {
|
|
const current = prev[key] as T[];
|
|
return {
|
|
...prev,
|
|
[key]: current.includes(value) ? current.filter((item) => item !== value) : [...current, value],
|
|
};
|
|
});
|
|
};
|
|
|
|
const openFilterPanel = () => {
|
|
setDraftFilters(activeFilters);
|
|
setFilterSectionSearch({ name: '' });
|
|
setFilterVisibleCounts({ name: FILTER_PAGE_SIZE });
|
|
setShowColumnsPanel(false);
|
|
setShowSortPanel(false);
|
|
setShowDatePanel(false);
|
|
setShowFilterPanel(true);
|
|
};
|
|
|
|
const visibleColumnCount = Object.values(visibleColumns).filter(Boolean).length;
|
|
|
|
const toggleColumn = (key: keyof typeof EMPTY_COLUMNS) => {
|
|
if (key === 'attributeName') return;
|
|
setVisibleColumns((prev) => ({ ...prev, [key]: !prev[key] }));
|
|
};
|
|
|
|
const handleExportExcel = () => {
|
|
if (filteredAttributes.length === 0) {
|
|
toast.warning('No attributes to export');
|
|
return;
|
|
}
|
|
const headers = ['S.No', 'Attribute Name', 'System Code', 'Preset Values', 'Status'];
|
|
const rows = filteredAttributes.map((a, i) => [
|
|
i + 1,
|
|
a.name,
|
|
a.code || '',
|
|
presetList(a).join(', ') || 'None',
|
|
isAttributeActive(a.status) ? 'Active' : 'Inactive',
|
|
]);
|
|
const csvContent = [headers.join(','), ...rows.map((row) => row.map((val) => `"${String(val).replace(/"/g, '""')}"`).join(','))].join('\n');
|
|
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
|
const url = URL.createObjectURL(blob);
|
|
const link = document.createElement('a');
|
|
link.href = url;
|
|
link.download = `ifixkart_attributes_${format(new Date(), 'yyyyMMdd')}.csv`;
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
document.body.removeChild(link);
|
|
URL.revokeObjectURL(url);
|
|
setShowExportMenu(false);
|
|
toast.success(`Downloaded ${filteredAttributes.length} ${filteredAttributes.length === 1 ? 'attribute' : 'attributes'} as CSV`);
|
|
};
|
|
|
|
const handleExportPDF = () => {
|
|
if (filteredAttributes.length === 0) {
|
|
toast.warning('No attributes to export');
|
|
return;
|
|
}
|
|
const printWindow = window.open('', '_blank');
|
|
if (!printWindow) {
|
|
toast.error('Allow pop-ups to open the attributes print preview');
|
|
return;
|
|
}
|
|
const html = `
|
|
<html>
|
|
<head>
|
|
<title>iFixKart Master Attributes PDF Export</title>
|
|
<style>
|
|
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 20px; color: #1e293b; }
|
|
h2 { color: #0f172a; border-bottom: 2px solid #e2e8f0; padding-bottom: 10px; }
|
|
table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 11px; }
|
|
th { background-color: #0f172a; color: white; padding: 10px; text-align: left; }
|
|
td { padding: 10px; border-bottom: 1px solid #e2e8f0; }
|
|
tr:nth-child(even) { background-color: #f8fafc; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h2>iFixKart Master Attributes (${filteredAttributes.length} Records)</h2>
|
|
<p>Exported on: ${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}</p>
|
|
<table>
|
|
<thead>
|
|
<tr>
|
|
<th>S.No</th>
|
|
<th>Attribute Name</th>
|
|
<th>System Code</th>
|
|
<th>Preset Values</th>
|
|
<th>Status</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${filteredAttributes.map((a, i) => `
|
|
<tr>
|
|
<td>${i + 1}</td>
|
|
<td>${a.name}</td>
|
|
<td>${a.code || ''}</td>
|
|
<td>${presetList(a).join(', ') || 'None'}</td>
|
|
<td>${isAttributeActive(a.status) ? 'Active' : 'Inactive'}</td>
|
|
</tr>
|
|
`).join('')}
|
|
</tbody>
|
|
</table>
|
|
<script>window.onload = function() { window.print(); }</script>
|
|
</body>
|
|
</html>
|
|
`;
|
|
printWindow.document.write(html);
|
|
printWindow.document.close();
|
|
setShowExportMenu(false);
|
|
toast.success(`Print preview opened for ${filteredAttributes.length} ${filteredAttributes.length === 1 ? 'attribute' : 'attributes'}`);
|
|
};
|
|
|
|
const dataCardShell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] overflow-hidden min-w-0';
|
|
|
|
const renderSortLabel = (label: string, field?: SortField, showIcon = true) => {
|
|
const active = field != null && sortConfig.field === field;
|
|
return (
|
|
<span className="inline-flex items-center gap-1.5">
|
|
{label}
|
|
{showIcon && (
|
|
<ArrowUpDown className={`w-3.5 h-3.5 shrink-0 ${active ? 'text-gray-700' : 'text-gray-400'}`} />
|
|
)}
|
|
</span>
|
|
);
|
|
};
|
|
|
|
const renderStatusBadge = (active: boolean) => (
|
|
<span
|
|
className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
|
|
active ? 'bg-success text-white' : 'bg-destructive text-white'
|
|
}`}
|
|
>
|
|
{active ? 'Active' : 'Inactive'}
|
|
</span>
|
|
);
|
|
|
|
const renderPresetBadges = (values: string[], limit?: number) => {
|
|
if (values.length === 0) {
|
|
return <span className="text-[13px] text-muted-foreground italic">No preset values</span>;
|
|
}
|
|
const shown = limit != null ? values.slice(0, limit) : values;
|
|
const remaining = limit != null ? Math.max(values.length - shown.length, 0) : 0;
|
|
return (
|
|
<div className="flex flex-wrap gap-1.5">
|
|
{shown.map((value) => (
|
|
<span
|
|
key={value}
|
|
className="inline-flex items-center px-2 py-0.5 crm-radius-badge text-[11px] font-semibold bg-muted text-muted-foreground"
|
|
>
|
|
{value}
|
|
</span>
|
|
))}
|
|
{remaining > 0 && (
|
|
<span className="inline-flex items-center px-2 py-0.5 crm-radius-badge text-[11px] font-semibold bg-primary/10 text-primary">
|
|
+{remaining}
|
|
</span>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const searchField = (
|
|
<div className="relative flex-1 min-w-[180px] max-w-[480px]">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none" />
|
|
<input
|
|
type="text"
|
|
placeholder="Search"
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
className="w-full h-9 pl-9 pr-3 crm-radius-control border border-border bg-card text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary transition-colors"
|
|
/>
|
|
</div>
|
|
);
|
|
|
|
const addAttributeButton = (
|
|
<button
|
|
type="button"
|
|
onClick={handleOpenCreate}
|
|
className="inline-flex items-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer shrink-0"
|
|
>
|
|
<span className="w-[18px] h-[18px] rounded-full bg-white text-primary flex items-center justify-center">
|
|
<Plus className="w-3 h-3" strokeWidth={3} />
|
|
</span>
|
|
Add Attribute
|
|
</button>
|
|
);
|
|
|
|
const viewToggle = <ViewModeToggle value={viewMode} onChange={handleViewModeChange} />;
|
|
|
|
const renderFilterControl = (align: 'left' | 'right') => {
|
|
const nameQuery = filterSectionSearch.name.trim().toLowerCase();
|
|
const filteredNameOptions = sortedAttributeFilterOptions.filter(
|
|
(attribute) =>
|
|
!nameQuery ||
|
|
attribute.name.toLowerCase().includes(nameQuery) ||
|
|
(attribute.code || '').toLowerCase().includes(nameQuery)
|
|
);
|
|
const visibleNameOptions = filteredNameOptions.slice(0, filterVisibleCounts.name);
|
|
|
|
const renderSectionSearch = (value: string, onChange: (next: string) => void) => (
|
|
<div className="relative">
|
|
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" />
|
|
<input
|
|
type="text"
|
|
placeholder="Search"
|
|
value={value}
|
|
onChange={(e) => {
|
|
onChange(e.target.value);
|
|
setFilterVisibleCounts({ name: FILTER_PAGE_SIZE });
|
|
}}
|
|
className="w-full h-8 pl-8 pr-3 crm-radius-control border border-border bg-card text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary"
|
|
/>
|
|
</div>
|
|
);
|
|
|
|
const renderCheckboxOption = (checked: boolean, onToggle: () => void, label: string, icon?: ReactNode) => (
|
|
<label className="flex items-center gap-2.5 py-1.5 cursor-pointer">
|
|
<input
|
|
type="checkbox"
|
|
checked={checked}
|
|
onChange={onToggle}
|
|
className="w-3.5 h-3.5 rounded-[3px] border-border text-primary focus:ring-primary cursor-pointer"
|
|
/>
|
|
{icon}
|
|
<span className="text-[13px] text-muted-foreground">{label}</span>
|
|
</label>
|
|
);
|
|
|
|
return (
|
|
<div className="relative shrink-0" ref={filterRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => (showFilterPanel ? setShowFilterPanel(false) : openFilterPanel())}
|
|
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-medium cursor-pointer transition-colors ${
|
|
showFilterPanel || filtersActive
|
|
? 'bg-primary text-white'
|
|
: 'border border-border bg-card text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
<Filter className="w-3.5 h-3.5" />
|
|
Filter
|
|
{filtersActive && !showFilterPanel && <span className="w-1.5 h-1.5 rounded-full bg-white" />}
|
|
<ChevronDown
|
|
className={`w-3.5 h-3.5 transition-transform ${showFilterPanel ? 'rotate-180' : ''} ${
|
|
showFilterPanel || filtersActive ? 'text-white/80' : 'text-muted-foreground'
|
|
}`}
|
|
/>
|
|
</button>
|
|
<AnimatePresence>
|
|
{showFilterPanel && (
|
|
<motion.div
|
|
initial={{ opacity: 0, y: -6 }}
|
|
animate={{ opacity: 1, y: 0 }}
|
|
exit={{ opacity: 0, y: -6 }}
|
|
transition={{ duration: 0.16, ease: 'easeOut' }}
|
|
className={`absolute ${align === 'right' ? 'right-0' : 'left-0'} top-full mt-1.5 z-50 w-[320px] max-w-[calc(100vw-2rem)] crm-radius-card border border-border bg-card shadow-lg overflow-hidden`}
|
|
>
|
|
<div className="flex items-center justify-between px-4 py-3 border-b border-border">
|
|
<span className="inline-flex items-center gap-2 text-[14px] font-semibold text-foreground">
|
|
<Filter className="w-4 h-4" />
|
|
Filter
|
|
</span>
|
|
<button
|
|
type="button"
|
|
aria-label="Close filters"
|
|
onClick={() => setShowFilterPanel(false)}
|
|
className="w-7 h-7 rounded-full bg-primary/10 text-primary hover:bg-primary hover:text-white cursor-pointer transition-colors flex items-center justify-center"
|
|
>
|
|
<X className="w-3.5 h-3.5" />
|
|
</button>
|
|
</div>
|
|
|
|
<div className="max-h-[420px] overflow-y-auto">
|
|
<div className="border-b border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => toggleFilterSection('name')}
|
|
className="w-full flex items-center gap-2 px-4 py-3 text-[13px] font-semibold text-foreground hover:bg-muted/20 cursor-pointer"
|
|
>
|
|
<ChevronRight className={`w-3.5 h-3.5 transition-transform ${expandedFilterSections.name ? 'rotate-90' : ''}`} />
|
|
Attribute Name
|
|
</button>
|
|
{expandedFilterSections.name && (
|
|
<div className="px-4 pb-4">
|
|
<div className="crm-radius-control border border-border bg-muted/20 p-3 space-y-2">
|
|
{renderSectionSearch(filterSectionSearch.name, (value) =>
|
|
setFilterSectionSearch({ name: value })
|
|
)}
|
|
<div className="space-y-0.5">
|
|
{visibleNameOptions.length === 0 ? (
|
|
<p className="py-2 text-[12px] text-muted-foreground">No attributes found.</p>
|
|
) : (
|
|
visibleNameOptions.map((attribute) => {
|
|
const id = normalizeId(attribute.attribute_id);
|
|
return renderCheckboxOption(
|
|
draftFilters.attributeIds.includes(id),
|
|
() => toggleDraftListValue('attributeIds', id),
|
|
attribute.name,
|
|
(
|
|
<div className="w-7 h-7 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
|
|
<Sliders className="w-3.5 h-3.5" />
|
|
</div>
|
|
)
|
|
);
|
|
})
|
|
)}
|
|
</div>
|
|
{filteredNameOptions.length > visibleNameOptions.length && (
|
|
<button
|
|
type="button"
|
|
onClick={() =>
|
|
setFilterVisibleCounts((prev) => ({ name: prev.name + FILTER_PAGE_SIZE }))
|
|
}
|
|
className="text-[12px] font-medium text-primary underline underline-offset-2 cursor-pointer"
|
|
>
|
|
Load More
|
|
</button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="border-b border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => toggleFilterSection('presets')}
|
|
className="w-full flex items-center gap-2 px-4 py-3 text-[13px] font-semibold text-foreground hover:bg-muted/20 cursor-pointer"
|
|
>
|
|
<ChevronRight className={`w-3.5 h-3.5 transition-transform ${expandedFilterSections.presets ? 'rotate-90' : ''}`} />
|
|
Preset Values
|
|
</button>
|
|
{expandedFilterSections.presets && (
|
|
<div className="px-4 pb-4">
|
|
<div className="crm-radius-control border border-border bg-muted/20 p-3 space-y-1">
|
|
{renderCheckboxOption(
|
|
draftFilters.presets.includes('with'),
|
|
() => toggleDraftListValue('presets', 'with'),
|
|
'With presets'
|
|
)}
|
|
{renderCheckboxOption(
|
|
draftFilters.presets.includes('without'),
|
|
() => toggleDraftListValue('presets', 'without'),
|
|
'Without presets'
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div>
|
|
<button
|
|
type="button"
|
|
onClick={() => toggleFilterSection('status')}
|
|
className="w-full flex items-center gap-2 px-4 py-3 text-[13px] font-semibold text-foreground hover:bg-muted/20 cursor-pointer"
|
|
>
|
|
<ChevronRight className={`w-3.5 h-3.5 transition-transform ${expandedFilterSections.status ? 'rotate-90' : ''}`} />
|
|
Status
|
|
</button>
|
|
{expandedFilterSections.status && (
|
|
<div className="px-4 pb-4">
|
|
<div className="crm-radius-control border border-border bg-muted/20 p-3 space-y-1">
|
|
{renderCheckboxOption(
|
|
draftFilters.statuses.includes('active'),
|
|
() => toggleDraftListValue('statuses', 'active'),
|
|
'Active'
|
|
)}
|
|
{renderCheckboxOption(
|
|
draftFilters.statuses.includes('inactive'),
|
|
() => toggleDraftListValue('statuses', 'inactive'),
|
|
'Inactive'
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3 px-4 py-3 border-t border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setDraftFilters(EMPTY_FILTERS);
|
|
setActiveFilters(EMPTY_FILTERS);
|
|
setShowFilterPanel(false);
|
|
}}
|
|
className="flex-1 h-9 crm-radius-control border border-border bg-card text-[13px] font-medium text-foreground hover:bg-muted cursor-pointer"
|
|
>
|
|
Reset
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setActiveFilters(draftFilters);
|
|
setShowFilterPanel(false);
|
|
}}
|
|
className="flex-1 h-9 crm-radius-control bg-primary text-white text-[13px] font-semibold cursor-pointer hover:bg-primary/90"
|
|
>
|
|
Filter
|
|
</button>
|
|
</div>
|
|
</motion.div>
|
|
)}
|
|
</AnimatePresence>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const manageColumnsControl = (
|
|
<div className="relative shrink-0" ref={columnsRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
const next = !showColumnsPanel;
|
|
setShowFilterPanel(false);
|
|
setShowSortPanel(false);
|
|
setShowDatePanel(false);
|
|
setShowColumnsPanel(next);
|
|
}}
|
|
className="inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-medium cursor-pointer transition-colors bg-primary/10 text-primary border border-primary/25 hover:bg-primary/15"
|
|
>
|
|
<Columns3 className="w-3.5 h-3.5" />
|
|
Manage Columns
|
|
</button>
|
|
{showColumnsPanel && (
|
|
<div className="absolute right-0 top-full mt-1.5 z-50 w-[240px] crm-radius-card border border-border bg-card shadow-lg py-1.5 overflow-hidden">
|
|
{COLUMN_OPTIONS.map((col) => (
|
|
<div key={col.key} className="flex items-center gap-2 px-3 py-1.5">
|
|
<GripVertical className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
|
|
<span className="flex-1 text-[13px] text-foreground truncate">{col.label}</span>
|
|
<button
|
|
type="button"
|
|
role="switch"
|
|
aria-checked={visibleColumns[col.key]}
|
|
aria-label={`Toggle ${col.label}`}
|
|
disabled={col.locked}
|
|
title={col.locked ? 'Attribute Name stays visible' : `Toggle ${col.label}`}
|
|
onClick={() => toggleColumn(col.key)}
|
|
className={`relative w-8 h-[18px] rounded-full shrink-0 transition-colors ${
|
|
visibleColumns[col.key] ? 'bg-primary' : 'bg-muted'
|
|
} ${col.locked ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
|
|
>
|
|
<span
|
|
className={`absolute top-[2px] w-3.5 h-3.5 rounded-full bg-white shadow-xs transition-all ${
|
|
visibleColumns[col.key] ? 'left-[14px]' : 'left-[2px]'
|
|
}`}
|
|
/>
|
|
</button>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
|
|
const sortControl = (
|
|
<div className="relative shrink-0" ref={sortRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
const next = !showSortPanel;
|
|
setShowFilterPanel(false);
|
|
setShowColumnsPanel(false);
|
|
setShowDatePanel(false);
|
|
setShowSortPanel(next);
|
|
}}
|
|
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control border border-border text-[13px] font-medium cursor-pointer transition-colors ${
|
|
showSortPanel || sortConfig.field !== DEFAULT_SORT.field || sortConfig.dir !== DEFAULT_SORT.dir
|
|
? 'bg-muted text-foreground'
|
|
: 'bg-card text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
<ArrowUpDown className="w-3.5 h-3.5" />
|
|
Sort By
|
|
<ChevronDown className={`w-3.5 h-3.5 text-muted-foreground transition-transform ${showSortPanel ? 'rotate-180' : ''}`} />
|
|
</button>
|
|
{showSortPanel && (
|
|
<div className="absolute left-0 top-full mt-1.5 z-50 w-56 crm-radius-card border border-border bg-card shadow-lg py-1 overflow-hidden">
|
|
{SORT_OPTIONS.map((option) => {
|
|
const active = option.field === sortConfig.field && option.dir === sortConfig.dir;
|
|
return (
|
|
<button
|
|
key={`${option.field}-${option.dir}`}
|
|
type="button"
|
|
onClick={() => {
|
|
setSortConfig({ field: option.field, dir: option.dir });
|
|
setShowSortPanel(false);
|
|
}}
|
|
className={`w-full text-left px-3 py-1.5 text-[13px] cursor-pointer ${
|
|
active ? 'bg-primary/10 text-primary font-medium' : 'text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
{option.label}
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
|
|
const dateRangeLabel = `${format(new Date(dayStartMs(dateFrom || DEFAULT_DATE_FROM)), 'd MMM yy')} - ${format(new Date(dayStartMs(dateTo || DEFAULT_DATE_TO)), 'd MMM yy')}`;
|
|
|
|
const dateControl = (
|
|
<div className="relative shrink-0" ref={dateRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
const next = !showDatePanel;
|
|
setShowFilterPanel(false);
|
|
setShowColumnsPanel(false);
|
|
setShowSortPanel(false);
|
|
if (next) {
|
|
setDraftDateFrom(dateFrom || DEFAULT_DATE_FROM);
|
|
setDraftDateTo(dateTo || DEFAULT_DATE_TO);
|
|
setShowDatePanel(true);
|
|
} else {
|
|
setShowDatePanel(false);
|
|
}
|
|
}}
|
|
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control border border-border text-[13px] font-medium cursor-pointer transition-colors ${
|
|
showDatePanel || dateFilterEnabled
|
|
? 'bg-muted text-foreground'
|
|
: 'bg-card text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
<Calendar className="w-3.5 h-3.5" />
|
|
{dateRangeLabel}
|
|
</button>
|
|
{showDatePanel && (
|
|
<div className="absolute left-0 top-full mt-1.5 z-50 w-72 crm-radius-card border border-border bg-card shadow-lg overflow-hidden">
|
|
<div className="px-3.5 py-3 space-y-2.5">
|
|
<div>
|
|
<label className="block text-[10px] font-semibold tracking-wide text-muted-foreground uppercase mb-1">From</label>
|
|
<input
|
|
type="date"
|
|
value={draftDateFrom}
|
|
onChange={(e) => setDraftDateFrom(e.target.value)}
|
|
className="w-full h-8 px-2.5 crm-radius-control border border-border bg-card text-[13px] text-foreground outline-none focus:border-primary"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label className="block text-[10px] font-semibold tracking-wide text-muted-foreground uppercase mb-1">To</label>
|
|
<input
|
|
type="date"
|
|
value={draftDateTo}
|
|
onChange={(e) => setDraftDateTo(e.target.value)}
|
|
className="w-full h-8 px-2.5 crm-radius-control border border-border bg-card text-[13px] text-foreground outline-none focus:border-primary"
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="flex items-center justify-between gap-2 px-3.5 py-2.5 border-t border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setDateFrom(DEFAULT_DATE_FROM);
|
|
setDateTo(DEFAULT_DATE_TO);
|
|
setDraftDateFrom(DEFAULT_DATE_FROM);
|
|
setDraftDateTo(DEFAULT_DATE_TO);
|
|
setDateFilterEnabled(false);
|
|
setShowDatePanel(false);
|
|
}}
|
|
className="h-8 px-3 crm-radius-control border border-border bg-card text-[12px] font-medium text-foreground hover:bg-muted cursor-pointer"
|
|
>
|
|
Clear
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
if (!draftDateFrom || !draftDateTo) {
|
|
toast.error('Choose a start date and an end date');
|
|
return;
|
|
}
|
|
if (draftDateFrom > draftDateTo) {
|
|
toast.error('Start date must be earlier than the end date');
|
|
return;
|
|
}
|
|
setDateFrom(draftDateFrom);
|
|
setDateTo(draftDateTo);
|
|
setDateFilterEnabled(true);
|
|
setShowDatePanel(false);
|
|
}}
|
|
className="h-8 px-3 crm-radius-control bg-primary text-primary-foreground text-[12px] font-medium cursor-pointer hover:bg-primary/90"
|
|
>
|
|
Apply
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
|
|
const emptyMessage =
|
|
searchQuery || filtersActive || dateFilterEnabled ? 'No attributes match your search.' : 'No master attributes found.';
|
|
|
|
return (
|
|
<div className="flex flex-col gap-5 min-w-0">
|
|
<div className="flex flex-wrap items-start justify-between gap-3 min-w-0">
|
|
<div className="min-w-0">
|
|
<div className="flex items-center gap-2">
|
|
<h1 className="text-lg font-semibold text-foreground">Master Attributes</h1>
|
|
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
|
|
{attributes.length}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3 shrink-0">
|
|
<div className="relative" ref={exportRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => setShowExportMenu((open) => !open)}
|
|
className="inline-flex items-center gap-1.5 h-8 px-2.5 crm-radius-control border border-border bg-card text-[13px] font-medium text-foreground hover:bg-muted cursor-pointer"
|
|
>
|
|
<Box className="w-3.5 h-3.5" />
|
|
Export
|
|
<ChevronDown className="w-3.5 h-3.5 text-muted-foreground" />
|
|
</button>
|
|
{showExportMenu && (
|
|
<div className="absolute right-0 top-full mt-1.5 z-50 w-48 crm-radius-card border border-border bg-card shadow-lg py-1 overflow-hidden">
|
|
<button
|
|
type="button"
|
|
onClick={handleExportPDF}
|
|
className="w-full flex items-center gap-2 px-3 py-2 text-[13px] text-muted-foreground hover:bg-muted hover:text-foreground cursor-pointer"
|
|
>
|
|
<FileText className="w-4 h-4 text-destructive" />
|
|
Export as PDF
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleExportExcel}
|
|
className="w-full flex items-center gap-2 px-3 py-2 text-[13px] text-muted-foreground hover:bg-muted hover:text-foreground cursor-pointer"
|
|
>
|
|
<FileSpreadsheet className="w-4 h-4 text-green-600" />
|
|
Export as Excel
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<button
|
|
type="button"
|
|
onClick={fetchData}
|
|
className="w-8 h-8 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer transition-colors flex items-center justify-center"
|
|
title="Reload Data"
|
|
>
|
|
<RefreshCw className="w-3.5 h-3.5" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{viewMode === 'grid' ? (
|
|
<div className={dataCardShell}>
|
|
<div className="px-5 pt-5">
|
|
<div className="-mx-5 px-5 flex flex-wrap items-center justify-between gap-3 min-w-0 pb-4 border-b border-border">
|
|
<div className="flex flex-wrap items-center gap-3 min-w-0 flex-1">
|
|
{renderFilterControl('left')}
|
|
{searchField}
|
|
</div>
|
|
<div className="flex items-center gap-3 shrink-0">
|
|
{viewToggle}
|
|
{addAttributeButton}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<div className="flex flex-col items-center justify-center py-16 gap-2.5">
|
|
<RefreshCw className="w-6 h-6 text-primary animate-spin" />
|
|
<span className="text-[13px] text-muted-foreground">Loading master attributes...</span>
|
|
</div>
|
|
) : filteredAttributes.length === 0 ? (
|
|
<div className="py-12 text-center text-[13px] text-muted-foreground">{emptyMessage}</div>
|
|
) : (
|
|
<div className="p-5 mt-4">
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
|
{pager.items.map((a) => (
|
|
<div
|
|
key={a.attribute_id}
|
|
className="relative crm-radius-section border border-border bg-card p-5 min-w-0 shadow-sm hover:shadow-md transition-shadow"
|
|
>
|
|
<div className="absolute top-4 right-4 z-10">
|
|
<RowActionsMenu
|
|
open={openActionId === a.attribute_id}
|
|
onOpenChange={(open) => setOpenActionId(open ? a.attribute_id : null)}
|
|
onEdit={() => handleOpenEdit(a)}
|
|
onDelete={() => openDeleteModal(a.attribute_id, a.name)}
|
|
/>
|
|
</div>
|
|
<div className="flex items-start gap-3 pr-8 min-w-0">
|
|
<div className="w-10 h-10 crm-radius-icon bg-primary/10 text-primary flex items-center justify-center shrink-0">
|
|
<Sliders className="w-4 h-4" />
|
|
</div>
|
|
<div className="min-w-0">
|
|
<p className="text-[14px] font-semibold text-foreground truncate">{a.name}</p>
|
|
<p className="text-[12px] text-muted-foreground truncate mt-0.5">{a.code}</p>
|
|
</div>
|
|
</div>
|
|
<div className="mt-4">{renderPresetBadges(presetList(a), 4)}</div>
|
|
<div className="mt-4 flex flex-wrap items-center gap-2">
|
|
{renderStatusBadge(isAttributeActive(a.status))}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
<TablePagination {...pager} />
|
|
</div>
|
|
) : (
|
|
<div className={dataCardShell}>
|
|
<div className="px-5 pt-5">
|
|
<div className="flex flex-wrap items-center justify-between gap-4 w-full min-w-0 pb-4 border-b border-border">
|
|
{searchField}
|
|
{addAttributeButton}
|
|
</div>
|
|
<div className="flex flex-wrap lg:flex-nowrap items-center justify-between gap-3 w-full min-w-0 py-4">
|
|
<div className="flex flex-wrap items-center gap-2 min-w-0">
|
|
{sortControl}
|
|
{dateControl}
|
|
</div>
|
|
<div className="flex flex-wrap items-center gap-2 shrink-0">
|
|
{renderFilterControl('right')}
|
|
{manageColumnsControl}
|
|
{viewToggle}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<div className="flex flex-col items-center justify-center py-16 gap-2.5 border-t border-border">
|
|
<RefreshCw className="w-6 h-6 text-primary animate-spin" />
|
|
<span className="text-[13px] text-muted-foreground">Loading master attributes...</span>
|
|
</div>
|
|
) : (
|
|
<div className="overflow-x-auto border-t border-border">
|
|
<table className="crm-data-table min-w-[760px]">
|
|
<thead>
|
|
<tr className="bg-gray-50 border-y border-gray-200">
|
|
{visibleColumns.attributeName && (
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Attribute Name', 'name')}
|
|
</th>
|
|
)}
|
|
{visibleColumns.code && (
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('System Code', 'code')}
|
|
</th>
|
|
)}
|
|
{visibleColumns.presetValues && (
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Preset Values', 'presets')}
|
|
</th>
|
|
)}
|
|
{visibleColumns.status && (
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Status', 'status')}
|
|
</th>
|
|
)}
|
|
{visibleColumns.actions && (
|
|
<th className="px-5 py-3 text-center text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Action')}
|
|
</th>
|
|
)}
|
|
</tr>
|
|
</thead>
|
|
<tbody className="bg-card">
|
|
{filteredAttributes.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={Math.max(visibleColumnCount, 1)} className="text-center py-12 text-[13px] text-muted-foreground">
|
|
{emptyMessage}
|
|
</td>
|
|
</tr>
|
|
) : (
|
|
pager.items.map((a) => (
|
|
<tr key={a.attribute_id} className="border-t border-border hover:bg-muted/10 transition-colors">
|
|
{visibleColumns.attributeName && (
|
|
<td className="px-5 py-3.5">
|
|
<div className="flex items-center gap-3 min-w-0">
|
|
<div className="w-9 h-9 crm-radius-icon bg-primary/10 text-primary flex items-center justify-center shrink-0">
|
|
<Sliders className="w-4 h-4" />
|
|
</div>
|
|
<div className="min-w-0">
|
|
<p className="text-[13px] font-semibold text-foreground truncate">{a.name}</p>
|
|
<p className="text-[11px] text-muted-foreground truncate">{a.code}</p>
|
|
</div>
|
|
</div>
|
|
</td>
|
|
)}
|
|
{visibleColumns.code && (
|
|
<td className="px-5 py-3.5 text-[13px] font-mono text-muted-foreground">{a.code}</td>
|
|
)}
|
|
{visibleColumns.presetValues && (
|
|
<td className="px-5 py-3.5">{renderPresetBadges(presetList(a), 5)}</td>
|
|
)}
|
|
{visibleColumns.status && (
|
|
<td className="px-5 py-3.5">{renderStatusBadge(isAttributeActive(a.status))}</td>
|
|
)}
|
|
{visibleColumns.actions && (
|
|
<td className="px-5 py-3.5">
|
|
<div className="flex items-center justify-center">
|
|
<RowActionsMenu
|
|
open={openActionId === a.attribute_id}
|
|
onOpenChange={(open) => setOpenActionId(open ? a.attribute_id : null)}
|
|
onEdit={() => handleOpenEdit(a)}
|
|
onDelete={() => openDeleteModal(a.attribute_id, a.name)}
|
|
/>
|
|
</div>
|
|
</td>
|
|
)}
|
|
</tr>
|
|
))
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
<TablePagination {...pager} />
|
|
</div>
|
|
)}
|
|
|
|
{deleteTarget && (
|
|
<div
|
|
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 p-4"
|
|
onClick={closeDeleteModal}
|
|
>
|
|
<div
|
|
role="dialog"
|
|
aria-modal="true"
|
|
aria-labelledby="delete-attribute-title"
|
|
className="bg-card border border-border shadow-2xl w-full max-w-sm overflow-hidden crm-radius-none"
|
|
onClick={(e) => e.stopPropagation()}
|
|
>
|
|
<div className="flex items-start justify-between gap-3 px-5 pt-5 pb-2">
|
|
<div className="flex items-start gap-3 min-w-0">
|
|
<div className="w-10 h-10 rounded-full bg-destructive/10 text-destructive flex items-center justify-center shrink-0">
|
|
<AlertTriangle className="w-5 h-5" />
|
|
</div>
|
|
<div className="min-w-0">
|
|
<h3 id="delete-attribute-title" className="text-[15px] font-semibold text-foreground">
|
|
Delete Attribute
|
|
</h3>
|
|
<p className="text-[13px] text-muted-foreground mt-1 leading-relaxed">
|
|
Are you sure you want to delete{' '}
|
|
<span className="font-semibold text-foreground">"{deleteTarget.name}"</span>? Products
|
|
using this attribute may lose these preset values.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
aria-label="Close delete dialog"
|
|
onClick={closeDeleteModal}
|
|
disabled={isDeleting}
|
|
className="w-8 h-8 rounded-full border border-border text-muted-foreground hover:bg-muted cursor-pointer transition-colors flex items-center justify-center shrink-0 disabled:opacity-50"
|
|
>
|
|
<X className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
<div className="flex items-center justify-end gap-2 px-5 pb-5 pt-3">
|
|
<button
|
|
type="button"
|
|
onClick={closeDeleteModal}
|
|
disabled={isDeleting}
|
|
className="h-9 px-4 crm-radius-control border border-border bg-card text-[13px] font-medium text-foreground hover:bg-muted cursor-pointer transition-colors disabled:opacity-50"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleConfirmDelete}
|
|
disabled={isDeleting}
|
|
className="h-9 px-4 crm-radius-control bg-destructive hover:bg-destructive/90 text-white text-[13px] font-semibold cursor-pointer transition-colors disabled:opacity-50 inline-flex items-center gap-2"
|
|
>
|
|
{isDeleting ? (
|
|
<>
|
|
<RefreshCw className="w-3.5 h-3.5 animate-spin" />
|
|
Deleting...
|
|
</>
|
|
) : (
|
|
<>
|
|
<Trash2 className="w-3.5 h-3.5" />
|
|
Delete Attribute
|
|
</>
|
|
)}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<SlideOver
|
|
open={showAttributeModal}
|
|
onClose={closeAttributeDrawer}
|
|
title={editingAttribute ? 'Edit Master Attribute' : 'Create Master Attribute'}
|
|
icon={<Sliders className="w-4 h-4 text-primary shrink-0" />}
|
|
>
|
|
<form onSubmit={handleSubmitAttribute} className="flex min-h-0 flex-1 flex-col">
|
|
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4">
|
|
<div>
|
|
<label className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">
|
|
Attribute Name <span className="text-primary">*</span>
|
|
</label>
|
|
<input
|
|
type="text"
|
|
placeholder="e.g. Storage Capacity, Color"
|
|
value={attrName}
|
|
onChange={(e) => setAttrName(e.target.value)}
|
|
className="w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary transition-colors"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">
|
|
System Code <span className="text-primary">*</span>
|
|
</label>
|
|
<input
|
|
type="text"
|
|
placeholder="e.g. storage, color"
|
|
value={attrCode}
|
|
onChange={(e) => setAttrCode(e.target.value)}
|
|
disabled={editingAttribute !== null}
|
|
className="w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary transition-colors disabled:opacity-60 disabled:bg-muted/40"
|
|
/>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<label className="block text-[11px] font-semibold text-muted-foreground uppercase">
|
|
Pre-stored Values
|
|
</label>
|
|
<p className="text-[12px] text-muted-foreground">
|
|
These values appear as dropdown choices when creating or editing products.
|
|
</p>
|
|
<div className="flex gap-2">
|
|
<input
|
|
type="text"
|
|
placeholder="e.g. 128GB, Midnight, Blue..."
|
|
value={newPresetInput}
|
|
onChange={(e) => setNewPresetInput(e.target.value)}
|
|
onKeyDown={(e) => {
|
|
if (e.key === 'Enter') {
|
|
e.preventDefault();
|
|
handleAddPresetValue();
|
|
}
|
|
}}
|
|
className="flex-1 h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground outline-none focus:border-primary"
|
|
/>
|
|
<button
|
|
type="button"
|
|
onClick={handleAddPresetValue}
|
|
className="h-9 px-3 bg-primary hover:bg-primary/90 text-white crm-radius-control text-[13px] font-semibold cursor-pointer shrink-0"
|
|
>
|
|
Add Value
|
|
</button>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap gap-1.5 min-h-[40px] p-3 bg-muted/20 border border-border crm-radius-control items-center">
|
|
{presetValues.length === 0 ? (
|
|
<span className="text-[12px] text-muted-foreground italic">
|
|
No preset values added yet. Type a value above and click Add.
|
|
</span>
|
|
) : (
|
|
presetValues.map((val, idx) => (
|
|
<span
|
|
key={`${val}-${idx}`}
|
|
className="inline-flex items-center gap-1.5 px-2 py-0.5 crm-radius-badge text-[11px] font-semibold bg-muted text-foreground"
|
|
>
|
|
<span>{val}</span>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleRemovePresetValue(idx)}
|
|
className="text-muted-foreground hover:text-destructive cursor-pointer"
|
|
aria-label={`Remove ${val}`}
|
|
>
|
|
<X className="w-3 h-3" />
|
|
</button>
|
|
</span>
|
|
))
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="shrink-0 border-t border-border px-5 py-3 flex items-center justify-end gap-2 bg-card">
|
|
<button
|
|
type="button"
|
|
onClick={closeAttributeDrawer}
|
|
disabled={isSubmitting}
|
|
className="h-8 px-3.5 bg-card hover:bg-muted border border-border text-foreground crm-radius-control text-[13px] font-medium transition-colors cursor-pointer disabled:opacity-50"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
type="submit"
|
|
disabled={isSubmitting}
|
|
className="h-8 px-3.5 bg-primary hover:bg-primary/90 text-primary-foreground crm-radius-control text-[13px] font-medium transition-colors cursor-pointer disabled:opacity-60"
|
|
>
|
|
{isSubmitting ? 'Saving...' : editingAttribute ? 'Save Changes' : 'Create Attribute'}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</SlideOver>
|
|
</div>
|
|
);
|
|
}
|