"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"; import { getLast12Months, formatMonthLabel, formatDate, SITE_LABELS, getStoreConfig, } from "@/features/grid/lib/months"; import { computeNetworkTrend, computeStoresSeries, trendLabel, TREND_COLOR, } from "@/features/grid/lib/network-trend"; import { TrendSparkline, NetworkLineChart } from "@/features/grid/components/network-charts"; interface HeatmapGridProps { onSelectionChange?: (codeins: string[]) => void; isAdmin?: boolean; } const EMPTY_DRAFT_CHANGES: Record = {}; const QLIK_NETWORK_COLUMN_IDS = new Set([ "caReseau", "qteReseau", "nbMagasinsReseau", "tendanceReseau", "caParMagasinReseau", "margePctReseau", ]); function getQlikNetworkSortValue(value: number | null | undefined, columnId: string, sorting: SortingState): number | undefined { if (value != null) return value; const activeSort = sorting.find((sort) => sort.id === columnId); if (!activeSort) return undefined; // TanStack inverse le résultat en tri descendant. On utilise donc une // sentinelle dépendante du sens de tri pour garder les valeurs absentes // toujours en bas, en ascendant comme en descendant. return activeSort.desc ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY; } // ========================================================================= // 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" || QLIK_NETWORK_COLUMN_IDS.has(cell.column.id) || 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; } /** Modal : quantités vendues réseau sur les 12 derniers mois, en une seule courbe. */ function NetworkMonthlyModal({ row, onClose }: { row: ProductRow; onClose: () => void }) { const trend = computeNetworkTrend(row.qteReseauByMonth); const { values, labels, direction, pct } = trend; const color = TREND_COLOR[direction]; // Deuxième courbe : le nombre de magasins vendeurs, pour distinguer une // hausse due à l'élargissement de la diffusion d'une vraie accélération. const magasins = computeStoresSeries(row.nbMagReseauByMonth); return ( {row.libelle1}

Ventes réseau · {labels.length > 0 ? `${labels.length} derniers mois` : "12 derniers mois"} {row.nbMagasinsReseau != null && <> · {row.nbMagasinsReseau} magasins} {pct != null && ( <> · {pct >= 0 ? "+" : ""}{Math.round(pct * 100)}% · {trendLabel(pct)} )}

{!trend.hasData ? (
Pas encore de détail mensuel pour ce produit.
Relancez un Sync Qlik pour le remplir.
) : ( )}
); } 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 [networkModal, setNetworkModal] = 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} ); }, }, { id: "caReseau", accessorFn: (row) => getQlikNetworkSortValue(row.caReseau, "caReseau", sorting), header: () =>
CA
Réseau
, size: 90, cell: ({ row }) => { const val = row.original.caReseau; return (
{val != null ? val.toLocaleString("fr-FR", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }) : "-"}
); }, }, { id: "qteReseau", accessorFn: (row) => getQlikNetworkSortValue(row.qteReseau, "qteReseau", sorting), header: () =>
Qté
Réseau
, size: 80, cell: ({ row }) => { const val = row.original.qteReseau; return (
{val != null ? Math.round(val).toLocaleString("fr-FR") : "-"}
); }, }, { id: "nbMagasinsReseau", accessorFn: (row) => getQlikNetworkSortValue(row.nbMagasinsReseau, "nbMagasinsReseau", sorting), header: () =>
Magasins
/ 270
, size: 80, cell: ({ row }) => { const val = row.original.nbMagasinsReseau; return (
{val != null ? val : "-"}
); }, }, { id: "tendanceReseau", accessorFn: (row) => { const t = computeNetworkTrend(row.qteReseauByMonth); return t.hasData && t.pct != null ? t.pct : Number.NEGATIVE_INFINITY; }, header: () =>
Tendance
Réseau · 12 m
, size: 78, cell: ({ row }) => { const trend = computeNetworkTrend(row.original.qteReseauByMonth); if (!trend.hasData) return
-
; // Cliquable → modal des ventes réseau mois par mois (12 derniers mois). return ( ); }, }, { id: "caParMagasinReseau", accessorFn: (row) => getQlikNetworkSortValue(row.caParMagasinReseau, "caParMagasinReseau", sorting), header: () =>
CA / Mag
Réseau
, size: 85, cell: ({ row }) => { const val = row.original.caParMagasinReseau; return (
{val != null ? val.toLocaleString("fr-FR", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }) : "-"}
); }, }, { id: "margePctReseau", accessorFn: (row) => getQlikNetworkSortValue(row.margePctReseau, "margePctReseau", sorting), header: () =>
Marge %
Réseau
, size: 75, cell: ({ row }) => { const val = row.original.margePctReseau; 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, sorting]); // 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" || QLIK_NETWORK_COLUMN_IDS.has(header.column.id) || 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)} />} { if (!open) setNetworkModal(null); }}> {networkModal !== null && setNetworkModal(null)} />} ); }