Files
Craze-Data-check/src/components/ProductDescriptions.tsx
T

464 lines
22 KiB
TypeScript
Raw Normal View History

import React, { useState, useMemo } from 'react';
import { ExcelRow } from '../types';
import { useColumns } from '../contexts/ColumnsContext';
import { Search, Filter, Edit2, ChevronDown, ChevronUp, X, Maximize2 } from 'lucide-react';
import { cn } from '../lib/utils';
import { ColumnFilterPopover } from './ColumnFilterPopover';
import { usePersistentState } from '../contexts/FilterContext';
type TabType = 'all' | 'missingLongDE' | 'missingLongEN' | 'missingShortDE' | 'missingShortEN' | 'complete' | 'incomplete';
interface ProductDescriptionsProps {
data: ExcelRow[];
headers: string[];
asinColumnIndex: number | null;
onEdit: (index: number) => void;
rowStatuses: Record<string, string>;
}
export function ProductDescriptions({ data, headers, asinColumnIndex, onEdit, rowStatuses }: ProductDescriptionsProps) {
const COLUMNS = useColumns();
const [isFullscreen, setIsFullscreen] = useState(false);
// Description columns that should only have Present/Missing filters
const DESCRIPTION_COLUMNS = [COLUMNS.LONG_DE, COLUMNS.LONG_EN, COLUMNS.SHORT_DE, COLUMNS.SHORT_EN, COLUMNS.DETAILS_DE, COLUMNS.DETAILS_EN];
const [activeTab, setActiveTab] = usePersistentState<string>('descriptions-tab', 'all');
const [search, setSearch] = usePersistentState('descriptions-search', '');
const [lineFilter, setLineFilter] = usePersistentState('descriptions-lineFilter', '');
const [licenseFilter, setLicenseFilter] = usePersistentState('descriptions-licenseFilter', '');
const [sortCol, setSortCol] = usePersistentState<number | null>('descriptions-sortCol', null);
const [sortDesc, setSortDesc] = usePersistentState('descriptions-sortDesc', false);
const [pageSize, setPageSize] = usePersistentState('descriptions-pageSize', 100);
const [page, setPage] = useState(1);
const [columnFilters, setColumnFilters] = usePersistentState<Record<number, string[]>>('descriptions-columnFilters', {});
const [openFilterCol, setOpenFilterCol] = useState<number | null>(null);
const [columnWidths, setColumnWidths] = useState<Record<number, number>>({
[COLUMNS.ARTICLE_NO]: 110,
[COLUMNS.ARTICLE_NAME]: 450, // More flexible space for name
...(asinColumnIndex !== null ? { [asinColumnIndex]: 100 } : {}),
[COLUMNS.LINE]: 80,
[COLUMNS.LICENSE]: 120,
[COLUMNS.CLASSIFICATION]: 100,
[COLUMNS.LONG_DE]: 110,
[COLUMNS.LONG_EN]: 110,
[COLUMNS.SHORT_DE]: 110,
[COLUMNS.SHORT_EN]: 110,
});
const lines = useMemo(() => Array.from(new Set(data.map(r => r[COLUMNS.LINE]).filter(Boolean))), [data]);
const licenses = useMemo(() => Array.from(new Set(data.map(r => r[COLUMNS.LICENSE]).filter(Boolean))), [data]);
const filteredData = useMemo(() => {
let result = data.map((row, index) => ({ row, index }));
// Tab filter
if (activeTab === 'missingLongDE') result = result.filter(r => !r.row[COLUMNS.LONG_DE]);
if (activeTab === 'missingLongEN') result = result.filter(r => !r.row[COLUMNS.LONG_EN]);
if (activeTab === 'missingShortDE') result = result.filter(r => !r.row[COLUMNS.SHORT_DE]);
if (activeTab === 'missingShortEN') result = result.filter(r => !r.row[COLUMNS.SHORT_EN]);
if (activeTab === 'complete') result = result.filter(r =>
r.row[COLUMNS.LONG_DE] && r.row[COLUMNS.LONG_EN] &&
r.row[COLUMNS.SHORT_DE] && r.row[COLUMNS.SHORT_EN]
);
if (activeTab === 'incomplete') result = result.filter(r =>
!r.row[COLUMNS.LONG_DE] || !r.row[COLUMNS.LONG_EN] ||
!r.row[COLUMNS.SHORT_DE] || !r.row[COLUMNS.SHORT_EN]
);
// Search filter
if (search) {
const terms = search.toLowerCase().split(/\s+/).filter(Boolean);
if (terms.length > 0) {
result = result.filter(r => {
const articleNo = String(r.row[COLUMNS.ARTICLE_NO] || '').toLowerCase();
const articleName = String(r.row[COLUMNS.ARTICLE_NAME] || '').toLowerCase();
return terms.every(term => articleNo.includes(term) || articleName.includes(term));
});
}
}
// Dropdown filters
if (lineFilter) result = result.filter(r => r.row[COLUMNS.LINE] === lineFilter);
if (licenseFilter) result = result.filter(r => r.row[COLUMNS.LICENSE] === licenseFilter);
// Column-specific filters (Excel-like)
Object.entries(columnFilters).forEach(([colIdx, selectedValues]) => {
const col = Number(colIdx);
const vals = selectedValues as string[];
if (vals.length > 0) {
result = result.filter(r => {
const cellVal = r.row[col];
if (DESCRIPTION_COLUMNS.includes(col)) {
// For description columns, we match synthetic 'Present'/'Missing' values
const hasValue = cellVal !== undefined && cellVal !== null && String(cellVal).trim() !== '';
const matchPresent = vals.includes('Present') && hasValue;
const matchMissing = vals.includes('Missing') && !hasValue;
return matchPresent || matchMissing;
} else {
// For other columns, use regular value matching with improved empty value handling
const cellStr = String(cellVal ?? '').trim();
// If the cell is empty/null/undefined, it matches if 'Empty' or '' is selected
return vals.some(v => {
const filterVal = String(v ?? '').trim();
return filterVal === cellStr;
});
}
});
}
});
// Sorting
if (sortCol !== null) {
result.sort((a, b) => {
const valA = String(a.row[sortCol] || '');
const valB = String(b.row[sortCol] || '');
return sortDesc ? valB.localeCompare(valA) : valA.localeCompare(valB);
});
}
return result;
}, [data, activeTab, search, lineFilter, licenseFilter, columnFilters, sortCol, sortDesc]);
const paginatedData = useMemo(() => {
const start = (page - 1) * pageSize;
return filteredData.slice(start, start + pageSize);
}, [filteredData, page, pageSize]);
const totalPages = Math.ceil(filteredData.length / pageSize);
const handleSort = (col: number) => {
if (sortCol === col) {
setSortDesc(!sortDesc);
} else {
setSortCol(col);
setSortDesc(false);
}
};
const handleResize = (colIndex: number, e: React.MouseEvent) => {
e.preventDefault();
const startX = e.pageX;
const startWidth = columnWidths[colIndex] || 100;
const onMouseMove = (moveEvent: MouseEvent) => {
const newWidth = Math.max(60, startWidth + (moveEvent.pageX - startX));
setColumnWidths(prev => ({ ...prev, [colIndex]: newWidth }));
};
const onMouseUp = () => {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
};
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
};
const getUniqueValues = (col: number) => {
// For description columns, return only 'Present' and 'Missing'
if (DESCRIPTION_COLUMNS.includes(col)) {
return ['Present', 'Missing'];
}
// For other columns, return actual unique values
const values = data.map(r => String(r[col] || ''));
return Array.from(new Set(values)).sort();
};
const toggleColumnFilter = (col: number, value: string) => {
console.log('[Filter] toggleColumnFilter called, col:', col, 'value:', JSON.stringify(value));
setColumnFilters(prev => {
const current = prev[col] || [];
const next = current.includes(value)
? current.filter(v => v !== value)
: [...current, value];
const updated = { ...prev, [col]: next };
console.log('[Filter] new columnFilters:', updated);
return updated;
});
setPage(1);
};
const setBatchColumnFilter = (col: number, values: string[]) => {
setColumnFilters(prev => ({ ...prev, [col]: values }));
setPage(1);
};
const getRowColor = (row: ExcelRow) => {
const fields = [
row[COLUMNS.LONG_DE], row[COLUMNS.LONG_EN],
row[COLUMNS.SHORT_DE], row[COLUMNS.SHORT_EN]
];
const filled = fields.filter(Boolean).length;
if (filled === 4) return 'bg-green-900/10 hover:bg-green-900/20';
return '';
};
const Badge = ({ content, row }: { content: any, row: ExcelRow }) => {
2026-04-10 12:50:15 +02:00
if (content !== undefined && content !== null && content !== '') return <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-500/20 text-green-400 border border-green-500/30"></span>;
return <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-500/20 text-red-400 border border-red-500/30"> Missing</span>;
};
const tabs: { id: TabType; label: string }[] = [
{ id: 'all', label: 'All Products' },
{ id: 'missingLongDE', label: 'Missing Long DE' },
{ id: 'missingLongEN', label: 'Missing Long EN' },
{ id: 'missingShortDE', label: 'Missing Short DE' },
{ id: 'missingShortEN', label: 'Missing Short EN' },
{ id: 'complete', label: 'Complete' },
{ id: 'incomplete', label: 'Incomplete' },
];
return (
<div className={isFullscreen ? "fixed inset-0 z-40 bg-[#041021] p-6 overflow-auto" : "flex flex-col h-full"}>
{isFullscreen && (
<button
onClick={() => setIsFullscreen(false)}
className="fixed top-4 right-4 z-50 w-10 h-10 flex items-center justify-center bg-slate-800/90 backdrop-blur border border-slate-600 text-white rounded hover:bg-slate-700 hover:scale-105 transition-all"
title="Exit fullscreen"
>
<X className="w-5 h-5" />
</button>
)}
<div className="flex flex-wrap gap-2 mb-6">
{tabs.map(tab => (
<button
key={tab.id}
onClick={() => { setActiveTab(tab.id); setPage(1); }}
className={cn(
"px-4 py-2 rounded-md text-sm font-medium transition-colors",
activeTab === tab.id
? "bg-blue-600 text-white shadow-md"
: "bg-slate-800 text-slate-400 hover:bg-slate-700 hover:text-white"
)}
>
{tab.label}
</button>
))}
<button
onClick={() => setIsFullscreen(true)}
className="ml-auto p-2 text-slate-400 hover:text-white hover:bg-slate-700 rounded transition-colors"
title="Fullscreen"
>
<Maximize2 className="w-5 h-5" />
</button>
</div>
<div className="flex flex-wrap gap-4 mb-6 bg-slate-800 p-4 rounded-xl border border-slate-700 shadow-sm">
<div className="flex-1 min-w-[200px] relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
<input
type="text"
placeholder="Search Article Name or No..."
value={search}
onChange={e => { setSearch(e.target.value); setPage(1); }}
className="w-full pl-9 pr-10 py-2 bg-slate-900 border border-slate-700 rounded-md text-sm text-white focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
/>
{search && (
<button
onClick={() => { setSearch(''); setPage(1); }}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white"
>
<X className="w-4 h-4" />
</button>
)}
</div>
{(Object.values(columnFilters) as string[][]).some(v => v.length > 0) && (
<button
onClick={() => {
setColumnFilters({});
setPage(1);
}}
className="flex items-center gap-2 px-4 py-2 bg-red-600/10 text-red-400 hover:bg-red-600 hover:text-white rounded-md text-sm font-medium transition-colors border border-red-600/20"
>
<X className="w-4 h-4" />
Clear All Column Filters
</button>
)}
<select
value={lineFilter}
onChange={e => { setLineFilter(e.target.value); setPage(1); }}
className="bg-slate-900 border border-slate-700 rounded-md px-4 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
>
<option value="">All Lines</option>
{lines.map(l => <option key={l} value={String(l)}>{String(l)}</option>)}
</select>
<select
value={licenseFilter}
onChange={e => { setLicenseFilter(e.target.value); setPage(1); }}
className="bg-slate-900 border border-slate-700 rounded-md px-4 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
>
<option value="">All Licenses</option>
{licenses.map(l => <option key={l} value={String(l)}>{String(l)}</option>)}
</select>
</div>
<div className="flex-1 bg-slate-800 rounded-xl border border-slate-700 shadow-xl overflow-hidden flex flex-col">
<div className="overflow-x-auto flex-1">
<table className="w-full text-left text-sm" style={{ tableLayout: 'fixed' }}>
<thead className="bg-slate-900/50 text-slate-400 sticky top-0 z-10">
<tr>
{[
{ col: COLUMNS.ARTICLE_NO, label: 'Article No.' },
{ col: COLUMNS.ARTICLE_NAME, label: 'Article Name' },
...(asinColumnIndex !== null ? [{ col: asinColumnIndex, label: 'ASIN' }] : []),
{ col: COLUMNS.LINE, label: 'Line' },
{ col: COLUMNS.LICENSE, label: 'License' },
{ col: COLUMNS.CLASSIFICATION, label: 'Classification' },
{ col: COLUMNS.LONG_DE, label: 'Long DE' },
{ col: COLUMNS.LONG_EN, label: 'Long EN' },
{ col: COLUMNS.SHORT_DE, label: 'Short DE' },
{ col: COLUMNS.SHORT_EN, label: 'Short EN' },
].map(({ col, label }) => (
<th
key={col}
className="px-4 py-3 font-medium transition-colors select-none group relative border-r border-slate-700/30"
style={{ width: columnWidths[col] || 'auto', minWidth: columnWidths[col] || 'auto' }}
>
<div className="flex items-center overflow-hidden">
<span className="flex items-center gap-1 cursor-pointer hover:text-white truncate" onClick={() => handleSort(col)}>
{label}
{sortCol === col && (
sortDesc ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />
)}
</span>
<button
id={`desc-filter-trigger-${col}`}
onClick={(e) => {
e.stopPropagation();
setOpenFilterCol(openFilterCol === col ? null : col);
}}
className={cn(
"p-0.5 rounded hover:bg-slate-700 transition-colors -my-1",
(columnFilters[col]?.length || 0) > 0 ? "text-blue-400 bg-blue-400/10" : "text-slate-500 opacity-0 group-hover:opacity-100"
)}
>
<Filter className="w-3.5 h-3.5" />
</button>
</div>
{/* Resizer handle */}
<div
onMouseDown={(e) => handleResize(col, e)}
className="absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/50 group-hover:bg-slate-700/50 transition-colors z-20"
/>
{openFilterCol === col && (
<ColumnFilterPopover
triggerId={`desc-filter-trigger-${col}`}
uniqueValues={getUniqueValues(col)}
selectedValues={columnFilters[col] || []}
onToggle={(val) => toggleColumnFilter(col, val)}
onSelectAll={(vals) => setBatchColumnFilter(col, vals)}
onClear={() => {
setColumnFilters(prev => {
const next = { ...prev };
delete next[col];
return next;
});
setOpenFilterCol(null);
}}
onClose={() => setOpenFilterCol(null)}
/>
)}
</th>
))}
<th className="px-4 py-3 font-medium text-right" style={{ width: 100 }}>Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-700/50">
{paginatedData.map(({ row, index }) => {
const saveStatus = rowStatuses[String(row[COLUMNS.ARTICLE_NO])];
return (
<tr
key={index}
className={cn(
"transition-colors",
getRowColor(row),
""
)}
>
<td className="px-4 py-3 font-mono text-slate-300 text-xs truncate" style={{ width: columnWidths[COLUMNS.ARTICLE_NO] }}>{row[COLUMNS.ARTICLE_NO]}</td>
<td className="px-4 py-3 font-medium text-white truncate" style={{ width: columnWidths[COLUMNS.ARTICLE_NAME] }} title={row[COLUMNS.ARTICLE_NAME]}>{row[COLUMNS.ARTICLE_NAME]}</td>
{asinColumnIndex !== null && (
<td className="px-4 py-3 font-mono text-slate-300 text-xs truncate" style={{ width: columnWidths[asinColumnIndex] || 100 }} title={row[asinColumnIndex]}>{row[asinColumnIndex] || '—'}</td>
)}
<td className="px-4 py-3 text-slate-300 text-xs truncate" style={{ width: columnWidths[COLUMNS.LINE] }}>{row[COLUMNS.LINE]}</td>
<td className="px-4 py-3 text-slate-300 text-xs truncate" style={{ width: columnWidths[COLUMNS.LICENSE] }} title={row[COLUMNS.LICENSE]}>{row[COLUMNS.LICENSE] || '—'}</td>
<td className="px-4 py-3 truncate" style={{ width: columnWidths[COLUMNS.CLASSIFICATION] }}>
<span className={cn(
"px-2 py-0.5 rounded text-[10px] font-bold border",
String(row[COLUMNS.CLASSIFICATION]).includes('OOC')
? "bg-amber-500/10 text-amber-500 border-amber-500/20"
: "bg-slate-700/50 text-slate-400 border-slate-600/50"
)}>
{row[COLUMNS.CLASSIFICATION] || '—'}
</span>
</td>
<td className="px-4 py-3" style={{ width: columnWidths[COLUMNS.LONG_DE] }}><Badge content={row[COLUMNS.LONG_DE]} row={row} /></td>
<td className="px-4 py-3" style={{ width: columnWidths[COLUMNS.LONG_EN] }}><Badge content={row[COLUMNS.LONG_EN]} row={row} /></td>
<td className="px-4 py-3" style={{ width: columnWidths[COLUMNS.SHORT_DE] }}><Badge content={row[COLUMNS.SHORT_DE]} row={row} /></td>
<td className="px-4 py-3" style={{ width: columnWidths[COLUMNS.SHORT_EN] }}><Badge content={row[COLUMNS.SHORT_EN]} row={row} /></td>
<td className="px-4 py-3 text-right">
<button
onClick={() => onEdit(index)}
className="inline-flex items-center gap-2 px-3 py-1.5 bg-blue-600/10 text-blue-400 hover:bg-blue-600 hover:text-white rounded-md transition-colors font-medium"
>
<Edit2 className="w-4 h-4" />
Edit
</button>
</td>
</tr>
);
})}
{paginatedData.length === 0 && (
<tr>
<td colSpan={asinColumnIndex !== null ? 10 : 9} className="px-4 py-8 text-center text-slate-500">
No products found matching the criteria.
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="bg-slate-900 border-t border-slate-700 p-4 flex items-center justify-between text-sm text-slate-400">
<div className="flex items-center gap-4">
<span>Showing {Math.min((page - 1) * pageSize + 1, filteredData.length)} to {Math.min(page * pageSize, filteredData.length)} of {filteredData.length} entries</span>
<select
value={pageSize}
onChange={e => { setPageSize(Number(e.target.value)); setPage(1); }}
className="bg-slate-800 border border-slate-700 rounded px-2 py-1 focus:outline-none focus:border-blue-500"
>
<option value={25}>25 per page</option>
<option value={50}>50 per page</option>
<option value={100}>100 per page</option>
</select>
</div>
<div className="flex items-center gap-2">
<button
disabled={page === 1}
onClick={() => setPage(p => p - 1)}
className="px-3 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Previous
</button>
<span className="px-3 py-1 font-medium text-white">Page {page} of {totalPages || 1}</span>
<button
disabled={page === totalPages || totalPages === 0}
onClick={() => setPage(p => p + 1)}
className="px-3 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Next
</button>
</div>
</div>
</div>
</div>
);
}