"use client"; import React, { useRef, useState, useCallback, useEffect, useMemo } from "react"; import { createPortal } from "react-dom"; import { useReactTable, getCoreRowModel, getSortedRowModel, getFilteredRowModel, flexRender, ColumnDef, SortingState, RowSelectionState, } from "@tanstack/react-table"; import { useVirtualizer } from "@tanstack/react-virtual"; import { ChevronUp, ChevronDown, ChevronsUpDown, Copy, Check, Store, SlidersHorizontal, ShoppingCart, PackageOpen, Warehouse, AlertTriangle } from "lucide-react"; import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { useGridStore } from "@/features/grid/store/use-grid-store"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { GammeSelect } from "@/features/grid/components/gamme-select"; import { HeatmapCell } from "@/features/grid/components/heatmap-cell"; import type { ProductRow, GammeCode } from "@/types/grid"; import { cn } from "@/lib/utils"; function getLast12Months(): string[] { const months: string[] = []; const now = new Date(); // On commence à i=12 (il y a 12 mois) et on finit à i=1 (le mois dernier) // pour exclure le mois en cours (i=0) for (let i = 12; i >= 1; i--) { const d = new Date(now.getFullYear(), now.getMonth() - i, 1); months.push(`${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}`); } return months; } // La constante est supprimée d'ici pour éviter le mismatch d'hydratation (new Date() au runtime module) function formatMonthLabel(key: string): string { const m = parseInt(key.slice(4, 6), 10); const names = ["Jan", "Fév", "Mar", "Avr", "Mai", "Jun", "Jul", "Aoû", "Sep", "Oct", "Nov", "Déc"]; return `${names[m - 1]} ${key.slice(2, 4)}`; } function formatDate(iso?: string): string { if (!iso) return "—"; return new Date(iso).toLocaleDateString("fr-FR", { day: "2-digit", month: "2-digit", year: "numeric" }); } /** * Returns premium styling and color for stores based on the store name's hash. * This guarantees a consistent color for a given store, regardless of its position in the list. */ const SITE_LABELS: Record = { "292": { label: "F", nom: "Frouard (Nancy)" }, "579": { label: "H", nom: "Houdemont" }, }; function getStoreConfig(name: string) { const known = SITE_LABELS[name]; const words = (known?.nom ?? name).trim().split(/\s+/); let label = known?.label ?? words[0].charAt(0).toUpperCase(); if (!known && words.length > 1) { label += words[1].charAt(0).toUpperCase(); } let hash = 0; for (let i = 0; i < name.length; i++) { hash = name.charCodeAt(i) + ((hash << 5) - hash); } const colorInt = Math.abs(hash) % 5; switch (colorInt) { case 0: return { bg: "rgba(99, 102, 241, 0.1)", text: "#818cf8", border: "rgba(99, 102, 241, 0.2)", label }; // Indigo case 1: return { bg: "rgba(245, 158, 11, 0.1)", text: "#fbbf24", border: "rgba(245, 158, 11, 0.2)", label }; // Amber case 2: return { bg: "rgba(16, 185, 129, 0.1)", text: "#10b981", border: "rgba(16, 185, 129, 0.2)", label }; // Emerald case 3: return { bg: "rgba(236, 72, 153, 0.1)", text: "#ec4899", border: "rgba(236, 72, 153, 0.2)", label }; // Pink case 4: return { bg: "rgba(14, 165, 233, 0.1)", text: "#0ea5e9", border: "rgba(14, 165, 233, 0.2)", label }; // Sky default: return { bg: "var(--bg-elevated)", text: "var(--text-muted)", border: "var(--border)", label }; } } interface HeatmapGridProps { onSelectionChange?: (codeins: string[]) => void; isAdmin?: boolean; } const EMPTY_DRAFT_CHANGES: Record = {}; // ========================================================================= // OPTIMISATION PERFORMANCES (React.memo + Zustand Selectors granulaires) // ========================================================================= // 1. Composant isolé pour la Cellule Gamme (évite le re-render des colonnes) const GammeCell = React.memo(({ row, isAdmin }: { row: ProductRow; isAdmin?: boolean }) => { // Abonnement ultra-ciblé : la cellule ne re-render que si SA valeur change const codein = row.codein; const isDraft = useGridStore((s) => s.draftChanges[codein] !== undefined); const effectiveGamme = useGridStore((s) => s.draftChanges[codein] ?? row.codeGamme); const setDraftGamme = useGridStore((s) => s.setDraftGamme); const isModified = row.codeGamme !== row.codeGammeInit && row.codeGammeInit !== null; const displayValue = (!effectiveGamme || effectiveGamme.trim() === "") ? "Aucune" : effectiveGamme; if (!isAdmin) { return (
{displayValue === "Aucune" ? "—" : displayValue}
); } return (
setDraftGamme(codein, g)} /> {isModified && !isDraft && (
)}
); }); GammeCell.displayName = "GammeCell"; import { Cell, Column, Row } from "@tanstack/react-table"; import { VirtualItem } from "@tanstack/react-virtual"; // 2. Composant isolé pour la Ligne Virtuelle // (Gère l'état grisé "Z" localement sans faire re-render toute la grid) interface VirtualRowProps { virtualRow: VirtualItem; row: Row; rowHeight: number; isSelected: boolean; columnVisibility: Record; columnSizing: Record; } const GridRow = React.memo(({ virtualRow, row, rowHeight, isSelected, columnVisibility, columnSizing }: VirtualRowProps) => { // Uniquement la ligne concernée écoute son propre changement pour l'effet visuel const effectiveGamme = useGridStore((s) => s.draftChanges[row.original.codein] ?? row.original.codeGamme); void columnVisibility; // Force re-render via React.memo when visibility changes void columnSizing; // Force re-render via React.memo when resizing columns return ( row.toggleSelected()} className={cn( "absolute w-full flex items-center cursor-pointer transition-all duration-200 group/row", effectiveGamme === "Z" && "opacity-40 grayscale-[0.5] hover:grayscale-0 hover:opacity-100" )} style={{ height: `${rowHeight}px`, transform: `translateY(${virtualRow.start}px)`, borderBottom: "1px solid var(--border)", background: isSelected ? "var(--accent-bg)" : "transparent", borderLeft: isSelected ? "3px solid var(--accent)" : "3px solid transparent", }} > {row.getVisibleCells().map((cell: Cell) => { const isFlexible = cell.column.id === "libelle1" || cell.column.id === "libelle3"; const isCenter = cell.column.id === "totalQuantite" || cell.column.id === "totalCa" || cell.column.id === "totalMarge" || cell.column.id.startsWith("month_") || cell.column.id === "gammeInitial" || cell.column.id === "caReseau" || cell.column.id === "qteReseau" || cell.column.id === "nbMagasinsReseau" || cell.column.id === "caParMagasinReseau" || cell.column.id === "margePctReseau" || cell.column.id === "tauxPresenceReseau" || cell.column.id === "gamme"; const size = cell.column.getSize(); return ( {flexRender(cell.column.columnDef.cell, cell.getContext())} ); })} ); }); GridRow.displayName = "GridRow"; // ========================================================================= // Composant modal pour le détail d'une cellule mensuelle // ========================================================================= interface CellDetailData { row: ProductRow; monthKey: string; qty: number | null; stock: number | null; receptions: number | null; } function CellDetailModal({ d, activeMagasin, onClose }: { d: CellDetailData; activeMagasin: string; onClose: () => void }) { const hasReceptions = (d.receptions ?? 0) > 0; const storeLabel = activeMagasin === "TOTAL" ? "Total réseau" : (SITE_LABELS[activeMagasin]?.nom ?? activeMagasin); return ( {d.row.libelle1}

{formatMonthLabel(d.monthKey)}{" · "} {storeLabel}

{/* Ventes */}
{d.qty != null ? Math.round(d.qty).toLocaleString("fr-FR") : "—"} Ventes
{/* Entrées */}
{hasReceptions ? `+${Math.round(d.receptions!).toLocaleString("fr-FR")}` : "—"} Entrées
{/* Stock fin de mois */}
{d.stock != null ? Math.round(d.stock).toLocaleString("fr-FR") : "—"} Stock fin mois
); } // ========================================================================= export function HeatmapGrid({ onSelectionChange, isAdmin }: HeatmapGridProps) { // L'abonnement doit être minimal ici ! PAS de draftChanges ni de setDraftGamme. const rows = useGridStore((s) => s.rows); const filters = useGridStore((s) => s.filters); const displayDensity = useGridStore((s) => s.displayDensity); const draftChanges = useGridStore((s) => s.filters.codeGamme ? s.draftChanges : EMPTY_DRAFT_CHANGES); const activeMagasin = useGridStore((s) => s.activeMagasin); // Filtre client-side par code3 (famille) et codeGamme const filteredData = useMemo(() => { const { code3, codeGamme } = filters; if (!code3 && !codeGamme) return rows; return rows.filter(r => { if (code3 && r.code3 !== code3) return false; if (codeGamme) { const g = draftChanges[r.codein] ?? r.codeGamme ?? ""; const norm = g.trim() === "" ? "Aucune" : g; if (norm !== codeGamme) return false; } return true; }); }, [rows, filters, draftChanges]); const [sorting, setSorting] = useState([]); const [rowSelection, setRowSelection] = useState({}); const columnVisibility = useGridStore((s) => s.columnVisibility); const setColumnVisibility = useGridStore((s) => s.setColumnVisibility); const columnSizing = useGridStore((s) => s.columnSizing); const setColumnSizing = useGridStore((s) => s.setColumnSizing); const [isMounted, setIsMounted] = useState(false); const [portalContainer, setPortalContainer] = useState(null); // État pour le détail d'une cellule mensuelle (modal) const [cellDetail, setCellDetail] = useState(null); const tableContainerRef = useRef(null); // Calculer les mois dynamiquement pour éviter le mismatch entre serveur et client const MONTHS_12 = useMemo(() => getLast12Months(), []); useEffect(() => { setIsMounted(true); const container = document.getElementById('grid-toolbar-actions'); setPortalContainer(container); }, []); const rowHeight = displayDensity === "compact" ? 32 : displayDensity === "normal" ? 40 : 48; const handleRowSelectionChange = useCallback( (updater: React.SetStateAction) => { setRowSelection(updater); }, [] ); // Reset selection when rows change (e.g. supplier change) useEffect(() => { setRowSelection({}); }, [rows]); const prevSelectionRef = useRef([]); // Propagate selection changes via useEffect to avoid "update during render" error useEffect(() => { if (!onSelectionChange) return; const selectedIdxs = Object.keys(rowSelection).filter((k) => rowSelection[k]); const selectedCodeins = selectedIdxs .map((idx) => filteredData[parseInt(idx)]?.codein ?? "") .filter(Boolean); // Only update if selection actually changed to avoid re-render loops & console warnings const currentString = JSON.stringify(selectedCodeins); const prevString = JSON.stringify(prevSelectionRef.current); if (currentString !== prevString) { prevSelectionRef.current = selectedCodeins; // Delay update to next tick to ensure we're out of any render cycles setTimeout(() => onSelectionChange(selectedCodeins), 0); } }, [rowSelection, onSelectionChange, filteredData]); const columns = React.useMemo[]>(() => [ { id: "select", size: 36, header: ({ table }) => ( { if (el) el.indeterminate = table.getIsSomeRowsSelected(); }} onChange={table.getToggleAllRowsSelectedHandler()} className="accent-emerald-500 cursor-pointer" /> ), cell: ({ row }) => ( e.stopPropagation()} className="accent-emerald-500 cursor-pointer" /> ), }, { accessorKey: "codein", header: "Code interne", size: 90, cell: ({ getValue }) => { const value = getValue(); // eslint-disable-next-line react-hooks/rules-of-hooks const [copied, setCopied] = useState(false); const handleCopy = (e: React.MouseEvent) => { e.stopPropagation(); navigator.clipboard.writeText(value); setCopied(true); setTimeout(() => setCopied(false), 2000); }; return (
{value}
{copied ? ( ) : ( )}
); }, }, { accessorKey: "reference", header: "Référence", size: 110, cell: ({ getValue }) => { const val = getValue(); return ( {val || "-"} ); }, }, { accessorKey: "gtin", header: "EAN / GTIN", size: 120, cell: ({ getValue }) => { const val = getValue(); return ( {val || "-"} ); }, }, { accessorKey: "libelle1", header: "Désignation", size: 280, cell: ({ row }) => { const r = row.original; const isDifferentSupplier = r.fournisseurPrincipalCode && r.fournisseurPrincipalCode !== r.codeFournisseur; const warnTitle = isDifferentSupplier ? `Dernier fournisseur enregistré : ${r.fournisseurPrincipalNom ?? r.fournisseurPrincipalCode} (${r.fournisseurPrincipalCode}) — les ventes sont à attribuer à ce fournisseur` : undefined; return (
{isDifferentSupplier && ( )} {r.libelle1}
{r.workingStores.map((magasin) => { const config = getStoreConfig(magasin); const lastLivDate = r.derniereLivraisonByStore?.[magasin]; const storeName = SITE_LABELS[magasin]?.nom ?? magasin; const tooltipTitle = `Magasin : ${storeName}\n${ lastLivDate ? `Dernière entrée en stock : ${formatDate(lastLivDate)}` : "Aucune entrée enregistrée" }`; return (
{config.label}
); })}
); }, }, { accessorKey: "libelle3", header: "Famille", size: 200, cell: ({ row }) => { const code = row.original.code3; const label = row.original.libelle3; const display = code && label ? `${code} — ${label}` : (label || code || ""); return ( {display} ); }, }, { accessorKey: "caReseau", header: () =>
CA
Réseau
, size: 90, cell: ({ getValue }) => { const val = getValue(); return (
{val != null ? val.toLocaleString("fr-FR", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }) : "-"}
); }, }, { accessorKey: "qteReseau", header: () =>
Qté
Réseau
, size: 80, cell: ({ getValue }) => { const val = getValue(); return (
{val != null ? Math.round(val).toLocaleString("fr-FR") : "-"}
); }, }, { accessorKey: "nbMagasinsReseau", header: () =>
Magasins
/ 270
, size: 80, cell: ({ getValue }) => { const val = getValue(); return (
{val != null ? val : "-"}
); }, }, { accessorKey: "tauxPresenceReseau", header: () =>
% Prés.
Réseau
, size: 70, cell: ({ getValue }) => { const val = getValue(); if (val == null) return
-
; const pct = Math.round(val * 100); const color = pct >= 66 ? "text-emerald-500" : pct >= 33 ? "text-amber-500" : "text-rose-500"; return (
{pct}%
); }, }, { accessorKey: "caParMagasinReseau", header: () =>
CA / Mag
Réseau
, size: 85, cell: ({ getValue }) => { const val = getValue(); return (
{val != null ? val.toLocaleString("fr-FR", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }) : "-"}
); }, }, { accessorKey: "margePctReseau", header: () =>
Marge %
Réseau
, size: 75, cell: ({ getValue }) => { const val = getValue(); if (val == null) return
-
; const pct = Math.abs(val) <= 1 ? val * 100 : val; const color = pct >= 30 ? "text-emerald-500" : pct >= 15 ? "text-amber-500" : "text-rose-500"; return (
{pct.toLocaleString("fr-FR", { maximumFractionDigits: 1 })}%
); }, }, ...MONTHS_12.map((monthKey) => ({ id: `month_${monthKey}`, header: () =>
{formatMonthLabel(monthKey)}
, size: 68, enableSorting: false, cell: ({ row }: { row: { original: ProductRow } }) => { const qty = activeMagasin === "TOTAL" ? (row.original.sales12m[monthKey] ?? null) : (row.original.sales12mByStore?.[activeMagasin]?.[monthKey] ?? null); const stock = activeMagasin === "TOTAL" ? (row.original.stock12m[monthKey] ?? null) : (row.original.stock12mByStore?.[activeMagasin]?.[monthKey] ?? null); const receptions = activeMagasin === "TOTAL" ? (row.original.receptions12m[monthKey] ?? null) : (row.original.receptions12mByStore?.[activeMagasin]?.[monthKey] ?? null); return ( { e.stopPropagation(); setCellDetail({ row: row.original, monthKey, qty, stock, receptions }); }} /> ); }, })), { id: "totalQuantite", accessorFn: (row: ProductRow) => activeMagasin === "TOTAL" ? row.totalQuantite : (row.quantiteByStore?.[activeMagasin] ?? 0), header: () =>
Tot. 12m
, size: 90, cell: ({ row }: { row: { original: ProductRow } }) => { const qty = activeMagasin === "TOTAL" ? row.original.totalQuantite : (row.original.quantiteByStore?.[activeMagasin] ?? 0); return (
{Math.round(qty).toLocaleString("fr-FR")}
); }, }, { id: "totalCa", accessorFn: (row: ProductRow) => activeMagasin === "TOTAL" ? row.totalCa : (row.caByStore?.[activeMagasin] ?? 0), header: () =>
CA
, size: 90, cell: ({ row }: { row: { original: ProductRow } }) => { const ca = activeMagasin === "TOTAL" ? row.original.totalCa : (row.original.caByStore?.[activeMagasin] ?? 0); return (
{Math.round(ca).toLocaleString("fr-FR")} €
); }, }, { id: "totalMarge", accessorFn: (row: ProductRow) => activeMagasin === "TOTAL" ? row.totalMarge : (row.margeByStore?.[activeMagasin] ?? 0), header: () =>
Marge
, size: 110, cell: ({ row }: { row: { original: ProductRow } }) => { const marge = activeMagasin === "TOTAL" ? row.original.totalMarge : (row.original.margeByStore?.[activeMagasin] ?? 0); const ca = activeMagasin === "TOTAL" ? row.original.totalCa : (row.original.caByStore?.[activeMagasin] ?? 0); const taux = ca > 0 ? (marge / ca) * 100 : 0; return (
{Math.round(marge).toLocaleString("fr-FR")} € = 40 ? "var(--accent-success)" : taux >= 25 ? "var(--accent-warning)" : "var(--accent-error)" }}> {taux.toFixed(1)}%
); }, }, { id: "gammeInitial", header: () =>
Init.
, size: 56, cell: ({ row }) => (
{row.original.codeGammeInit || "-"}
), }, { id: "gamme", header: () =>
Gamme
, size: 110, cell: ({ row }) => , }, ], [MONTHS_12, activeMagasin, isAdmin]); // activeMagasin déclenche re-render des cellules mensuelles et totaux const table = useReactTable({ data: filteredData, columns, state: { sorting, globalFilter: filters.search, rowSelection, columnVisibility, columnSizing }, onSortingChange: setSorting, onRowSelectionChange: handleRowSelectionChange, onColumnVisibilityChange: setColumnVisibility, onColumnSizingChange: setColumnSizing, columnResizeMode: "onChange", getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), enableRowSelection: true, globalFilterFn: (row, _columnId, filterValue) => { const search = String(filterValue).toLowerCase(); const libelle = String(row.original.libelle1 || "").toLowerCase(); const code = String(row.original.codein || "").toLowerCase(); const reference = String(row.original.reference || "").toLowerCase(); const gtin = String(row.original.gtin || "").toLowerCase(); return libelle.includes(search) || code.includes(search) || reference.includes(search) || gtin.includes(search); }, }); const { rows: tableRows } = table.getRowModel(); const rowVirtualizer = useVirtualizer({ count: tableRows.length, getScrollElement: () => tableContainerRef.current, estimateSize: () => rowHeight, overscan: 8, }); const visibleColumns = table.getVisibleLeafColumns(); const totalWidth = visibleColumns.reduce((s, c) => s + ((c.columnDef as { size?: number }).size ?? 150), 0); if (!isMounted) { return (
Chargement de la grille...
); } return ( <>
{portalContainer && createPortal( {table .getAllLeafColumns() .filter((column: Column) => column.getCanHide()) .map((column: Column) => { return ( column.toggleVisibility(!!value)} onSelect={(e: Event) => e.preventDefault()} > {typeof column.columnDef.header === 'string' ? column.columnDef.header : column.id.startsWith('month_') ? formatMonthLabel(column.id.replace('month_', '')) : column.id} ); })} , portalContainer )}
{table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => { const isFlexible = header.column.id === "libelle1" || header.column.id === "libelle3"; const isCenter = header.column.id === "totalQuantite" || header.column.id === "totalCa" || header.column.id === "totalMarge" || header.column.id.startsWith("month_") || header.column.id === "gammeInitial" || header.column.id === "caReseau" || header.column.id === "qteReseau" || header.column.id === "nbMagasinsReseau" || header.column.id === "caParMagasinReseau" || header.column.id === "margePctReseau" || header.column.id === "tauxPresenceReseau" || header.column.id === "gamme"; const size = header.getSize(); return ( ); })} ))} {rowVirtualizer.getVirtualItems().map((virtualRow) => { const row = tableRows[virtualRow.index]; const isSelected = row.getIsSelected(); return (
); })}
{flexRender(header.column.columnDef.header, header.getContext())} {header.column.getCanSort() && (
{header.column.getIsSorted() === "asc" ? : header.column.getIsSorted() === "desc" ? : }
)}
{/* Handle de redimensionnement de la colonne */} {header.column.getCanResize() && (
e.stopPropagation()} className={`absolute right-0 top-0 h-full w-1.5 cursor-col-resize user-select-none touch-none hover:bg-emerald-500/50 ${header.column.getIsResizing() ? "bg-emerald-500" : ""}`} /> )}
{/* Modal détail cellule mensuelle */} { if (!open) setCellDetail(null); }}> {cellDetail !== null && setCellDetail(null)} />} ); }