feat(grid): replace ranking/AI/score with Qlik network data

Remove ranking, AI analysis (routes + ai-copilot module), and score-engine
from the grid. Add Qlik Sense network metrics (CA, Qte, nb magasins per
product) joined by code centrale (articles.artcentrale).

- qlik-client.ts: NTLM + ticket SSO auth, QIX hypercube extraction (master items)
- qlik-network-cache.ts + qlik_network_metrics table (db-init): cache layer
- POST /api/qlik/sync?fournisseur=: per-supplier sync into cache
- SyncQlikButton: per-supplier sync, grid reload, last-update date display
- get-product-rows Phase 8: enrich rows with cached network metrics
- heatmap-grid: CA reseau / Qte reseau / Magasins (/270) / % presence columns
- discovery: app 9872ee6e, master items CA N / Quantite N / Magasin Ventes Nb N
- deps: httpntlm, ws

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MichaelandClaude Opus 4.8 committed 2026-06-20 22:52:39 +02:00
1 parent 02a10caa4b
commit aee968d30f
34 files changed
+1043 -2925

No files matched your search

@@ -1,402 +0,0 @@
"use client";
import React, { useState, useRef, useEffect } from "react";
import { useGridStore } from "@/features/grid/store/use-grid-store";
import { useAiCopilotStore } from "@/features/ai-copilot/store/use-ai-copilot-store";
import { ContextProfiler } from "@/features/ai-copilot/business/context-profiler";
import { Sparkles, Loader2, CheckCircle2, XCircle } from "lucide-react";
import { GammeCode } from "@/types/grid";
import { ProductAnalysisInput } from "@/features/ai-copilot/models/ai-analysis.types";
import { SupplierAiContextModal } from "./supplier-ai-context-modal";
export function BulkAiAnalyzer() {
const rows = useGridStore((s) => s.rows);
const supplierCode = rows.length > 0 ? rows[0].codeFournisseur : null;
const supplierName = rows.length > 0 ? rows[0].nomFournisseur : null;
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [progress, setProgress] = useState({ current: 0, total: 0, message: "", errors: 0 });
const isCancelledRef = useRef(false);
const batchSetDraftGamme = useGridStore((s) => s.batchSetDraftGamme);
const setDraftGamme = useGridStore((s) => s.setDraftGamme);
const { setInsight, batchSetInsights, batchSetLoading, setError } = useAiCopilotStore();
const prevSupplierRef = useRef(supplierCode);
useEffect(() => {
if (supplierCode !== prevSupplierRef.current) {
if (!isAnalyzing) {
setProgress({ current: 0, total: 0, message: "", errors: 0 });
}
prevSupplierRef.current = supplierCode;
}
}, [supplierCode, isAnalyzing]);
const handleStop = () => {
isCancelledRef.current = true;
setProgress((prev) => ({ ...prev, message: "Arrêt en cours..." }));
};
const handleAnalyze = async () => {
const { rows } = useGridStore.getState();
isCancelledRef.current = false;
// Show immediate visual feedback before any async work
setIsAnalyzing(true);
setProgress({ current: 0, total: 0, message: "Chargement du contexte...", errors: 0 });
// 1. Fetch AI Context for the Supplier
let supplierContext = "";
if (supplierCode) {
try {
const ctxRes = await fetch(`/api/ai/context?fournisseur=${supplierCode}`);
if (ctxRes.ok) {
const data = await ctxRes.json();
supplierContext = data.context || "";
}
} catch (err) {
console.error("Failed to load supplier context for AI", err);
}
}
// 2a. Produits sans aucune vente → Z direct, sans appel IA (avant de construire les payloads)
const zeroSalesRows = rows.filter((r) => (r.totalQuantite || 0) === 0);
if (zeroSalesRows.length > 0) {
const zChanges: Record<string, GammeCode> = {};
zeroSalesRows.forEach(r => { zChanges[r.codein] = "Z"; });
batchSetDraftGamme(zChanges);
batchSetInsights(zeroSalesRows.map(r => ({
codein: r.codein,
insight: "Aucune vente sur 12 mois — produit classé Z automatiquement.",
})));
}
// Construire les payloads uniquement pour les produits avec ventes
const rowsWithSales = rows.filter((r) => (r.totalQuantite || 0) > 0);
const initialPayloads: ProductAnalysisInput[] = rowsWithSales.map((r) => {
const sc = r.workingStores?.length || 1;
const weight = sc === 1 ? 2 : 1;
const allMonths = Object.keys(r.sales12m || {});
const referenceMonth = allMonths.length > 0 ? Math.max(...allMonths.map((m) => parseInt(m))).toString() : "";
const salesMonths = Object.entries(r.sales12m || {})
.filter(([_, qty]) => qty > 0)
.map(([m]) => parseInt(m))
.sort((a, b) => b - a);
const lastMonth = salesMonths.length > 0 ? salesMonths[0].toString() : "";
let inactivity = 0;
if (referenceMonth && lastMonth) {
const refY = parseInt(referenceMonth.substring(0, 4));
const refM = parseInt(referenceMonth.substring(4, 6));
const lastY = parseInt(lastMonth.substring(0, 4));
const lastM = parseInt(lastMonth.substring(4, 6));
inactivity = (refY - lastY) * 12 + (refM - lastM);
}
const regScore = Object.values(r.sales12m || {}).filter((v) => v > 0).length;
return {
codein: r.codein,
noid: r.noid,
libelle1: r.libelle1 || "",
libelleNiveau2: r.libelleNiveau2 || "Général",
codeNomenclatureN2: r.code2 || undefined,
totalCa: r.totalCa || 0,
tauxMarge: r.tauxMarge || 0,
totalQuantite: r.totalQuantite || 0,
weightedTotalQuantite: (r.totalQuantite || 0) * weight,
weightedTotalCa: (r.totalCa || 0) * weight,
storeCount: sc,
sales12m: Object.fromEntries(Object.entries(r.sales12m || {}).map(([month, val]) => [month, (val as number) * weight])),
codeGamme: r.codeGamme || null,
score: r.score || 0,
regularityScore: regScore,
lastMonthWithSale: lastMonth,
inactivityMonths: inactivity,
codeFournisseur: r.codeFournisseur || undefined,
avgQtyFournisseur: r.avgQtyFournisseur,
avgQtyRayon: r.avgQtyRayon,
shareCa: r.shareCa,
shareMarge: r.shareMarge,
shareQty: r.shareQty,
totalFournisseurCa: r.totalFournisseurCa,
supplierContext: supplierContext,
};
});
// 2b. Stock mort absolu : CA < 100€ ET quantité < 30 → Z direct, sans appel IA
const deadStockRows = rows.filter(r =>
(r.totalQuantite || 0) > 0 &&
(r.totalCa ?? 0) < 100 && (r.totalQuantite ?? 0) < 30
);
if (deadStockRows.length > 0) {
const zChanges: Record<string, GammeCode> = {};
deadStockRows.forEach(r => { zChanges[r.codein] = "Z"; });
batchSetDraftGamme(zChanges);
batchSetInsights(deadStockRows.map(r => ({
codein: r.codein,
insight: `CA < 100€ (${(r.totalCa ?? 0).toFixed(0)}€) et quantité < 30 (${r.totalQuantite} uté) — stock mort absolu, classé Z automatiquement.`,
})));
}
const deadStockCodes = new Set(deadStockRows.map(r => r.codein));
// 2c. Top 20 réseau → A direct, sans appel IA
const top20Rows = rows.filter(r =>
(r.totalQuantite || 0) > 0 &&
!deadStockCodes.has(r.codein) &&
((r.rankingCa != null && r.rankingCa <= 20) || (r.rankingQte != null && r.rankingQte <= 20))
);
if (top20Rows.length > 0) {
const aChanges: Record<string, GammeCode> = {};
top20Rows.forEach(r => { aChanges[r.codein] = "A"; });
batchSetDraftGamme(aChanges);
batchSetInsights(top20Rows.map(r => {
const rkCa = r.rankingCa != null ? `${r.rankingCa}e CA` : "";
const rkQte = r.rankingQte != null ? `${r.rankingQte}e Qté` : "";
const total = r.totalRankedProducts ? ` / ${r.totalRankedProducts.toLocaleString("fr-FR")} produits` : "";
return {
codein: r.codein,
insight: `Top 20 réseau (${[rkCa, rkQte].filter(Boolean).join(", ")}${total}) — classé A automatiquement.`,
};
}));
}
const top20Codes = new Set(top20Rows.map(r => r.codein));
// Filtrer : ne soumettre à l'IA que les produits avec au moins 1 vente et CA/quantité suffisants
const payloadsWithSales = initialPayloads.filter(p =>
(p.totalQuantite || 0) > 0 && !deadStockCodes.has(p.codein) && !top20Codes.has(p.codein)
);
// 2c. Context profiling en micro-batches asynchrones
// Le score est déjà calculé par score-engine.ts (champ row.score sur chaque ProductRow).
setProgress({ current: 0, total: payloadsWithSales.length, message: "Calcul du contexte...", errors: 0 });
const SCORING_BATCH_SIZE = 25;
const productPayloads: ProductAnalysisInput[] = [];
// Pre-compute context thresholds to prevent O(N^2) and O(N^2 log N) performance freezes
const contextCache = ContextProfiler.prepareCache(payloadsWithSales);
// Map codein → row pour récupérer le score et les flags depuis score-engine
const rowByCodein = new Map(rows.map(r => [r.codein, r]));
for (let i = 0; i < payloadsWithSales.length; i += SCORING_BATCH_SIZE) {
if (isCancelledRef.current) break;
const batch = payloadsWithSales.slice(i, i + SCORING_BATCH_SIZE);
for (const p of batch) {
const row = rowByCodein.get(p.codein);
const score = row?.score ?? p.score ?? 0;
const verdict: "A" | "Z" = score >= 45 ? "A" : "Z";
let contextProfile: ProductAnalysisInput["contextProfile"];
try {
contextProfile = ContextProfiler.buildProfile(p, payloadsWithSales, score, contextCache);
} catch (err) {
console.warn(`[BulkAnalyzer] ContextProfiler failed for ${p.codein}:`, err);
contextProfile = undefined;
}
productPayloads.push({
...p,
prixVente: row?.prixVente,
unitsPerStorePerMonth: row?.unitsPerStorePerMonth,
caPerStorePerYear: row?.caPerStorePerYear,
stockActuel: row?.stockActuel,
stockTotal: row?.stockTotal,
pcb: row?.pcb,
commandesEnCours: row?.commandesEnCours,
nbJoursDerniereVente: row?.nbJoursDerniereVente,
derniereVente: row?.derniereVente,
rankingCa: row?.rankingCa,
rankingQte: row?.rankingQte,
rankingMagCa: row?.rankingMagCa,
rankingMagQte: row?.rankingMagQte,
totalRankedProducts: row?.totalRankedProducts,
contextProfile,
scoring: {
score,
verdict,
quadrant: contextProfile?.quadrant,
isRecent: row?.isRecent ?? false,
isLastProduct: row?.isLastProduct ?? false,
isTop30Supplier: row?.isTop30Supplier ?? false,
},
});
}
// Yield au navigateur entre chaque batch pour éviter le freeze
setProgress(prev => ({
...prev,
current: Math.min(i + SCORING_BATCH_SIZE, payloadsWithSales.length),
message: `Contexte : ${Math.min(i + SCORING_BATCH_SIZE, payloadsWithSales.length)}/${payloadsWithSales.length}`,
}));
await new Promise(r => setTimeout(r, 0));
}
if (isCancelledRef.current) {
setIsAnalyzing(false);
return;
}
let completed = 0;
let errorsCount = 0;
const totalItems = productPayloads.length;
setProgress({ current: 0, total: totalItems, message: "Envoi aux modèles IA...", errors: 0 });
// Reset global ATOMIQUE et IMMÉDIAT
const codeins = productPayloads.map(p => p.codein);
batchSetLoading(codeins);
const gammeChanges: Record<string, GammeCode> = {};
codeins.forEach(c => gammeChanges[c] = "Aucune");
batchSetDraftGamme(gammeChanges);
const CONCURRENCY = 2;
const remaining = [...productPayloads];
const processBatch = async () => {
const workers = Array.from({ length: Math.min(CONCURRENCY, remaining.length) }, async () => {
while (remaining.length > 0 && !isCancelledRef.current) {
const payload = remaining.shift();
if (!payload) break;
try {
let res: Response | null = null;
// Jusqu'à 3 tentatives par produit
for (let attempt = 0; attempt < 3; attempt++) {
if (isCancelledRef.current) break;
try {
res = await fetch("/api/ai/analyze", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (res.ok) break; // Succès → sortie de boucle
if (res.status === 429) {
// Rate-limit : on attend avant de réessayer
const retryData = await res.json().catch(() => ({}));
const wait = (retryData.retryAfter ?? 30) * 1000;
console.warn(`[BulkAI] Rate limited, retry in ${wait / 1000}s`);
await new Promise((r) => setTimeout(r, Math.min(wait, 15_000)));
} else if (res.status === 504 || res.status === 502 || res.status === 503 || res.status === 529) {
// Timeout ou réseau surchargé : on tente de réessayer de suite
console.warn(`[BulkAI] Network issue (${res.status}) for ${payload.codein}, retry #${attempt + 1}`);
await new Promise((r) => setTimeout(r, 2_000 * (attempt + 1))); // Exponential backoff (2s, 4s, 6s)
} else {
// Autre erreur (500 local, auth, etc.) : ne pas réessayer inutilement
break;
}
} catch (fetchErr) {
console.error(`[BulkAI] Fetch error (attempt ${attempt + 1}) for ${payload.codein}`, fetchErr);
await new Promise((r) => setTimeout(r, 1_000)); // Petite pause avant retry réseau
}
}
if (!res || !res.ok) {
let errorMsg = res?.status === 504 ? "Timeout IA" : (res?.status === 502 ? "API Surchargée" : `Erreur HTTP ${res?.status}`);
// On tente d'extraire le message original s'il y en a un
if (res && res.headers.get("content-type")?.includes("application/json")) {
try {
const errData = await res.json();
if (errData.error) errorMsg += ` - ${errData.error}`;
if (errData.detail) errorMsg += ` (${errData.detail})`;
} catch (e) { /* ignore JSON parse error on error */ }
}
setError(payload.codein, errorMsg);
errorsCount++;
} else {
const data = await res.json();
setInsight(payload.codein, data.insight, data.isDuplicate);
if (data.recommandation) {
setDraftGamme(payload.codein, data.recommandation as GammeCode);
}
}
} catch (err) {
console.error(`[BulkAI] Error processing ${payload.codein}`, err);
setError(payload.codein, "Erreur");
errorsCount++;
} finally {
completed++;
setProgress((prev) => ({
...prev,
current: completed,
message: `Analyse: ${completed}/${totalItems}`,
errors: errorsCount,
}));
}
}
});
await Promise.all(workers);
};
await processBatch();
// Nettoyer les drafts "Aucune" restants (produits en erreur dont l'IA n'a pas retourné A/Z)
// Pour éviter que "Valider" ne sauvegarde "Aucune" comme gamme réelle
const currentDrafts = useGridStore.getState().draftChanges;
const aucuneCodeins = codeins.filter(c => currentDrafts[c] === "Aucune");
if (aucuneCodeins.length > 0) {
const { clearDrafts } = useGridStore.getState();
clearDrafts(aucuneCodeins);
}
setProgress((prev) => ({
...prev,
message: isCancelledRef.current ? `Analyse interrompue (${completed}/${totalItems})` : `Analyse terminée ! (${errorsCount > 0 ? errorsCount + " erreurs" : "succès"})`,
}));
setTimeout(() => setIsAnalyzing(false), 3000);
};
return (
<div className="flex items-center gap-3">
<SupplierAiContextModal codeFournisseur={supplierCode} nomFournisseur={supplierName} />
{isAnalyzing ? (
<div className="flex items-center gap-4 h-10 px-4 rounded-xl bg-[var(--accent-bg)] border border-[var(--accent-border)] shadow-sm">
<Loader2 className="w-4 h-4 text-[var(--accent)] animate-spin" />
<div className="flex flex-col min-w-[150px]">
<span className="text-[10px] font-bold text-[var(--accent)] leading-none">
{progress.message}
</span>
<div className="w-full bg-[var(--bg-elevated)] rounded-full h-1 mt-1 overflow-hidden">
<div
className="bg-[var(--accent)] h-1 rounded-full transition-all duration-300"
style={{ width: `${Math.max(5, (progress.current / progress.total) * 100)}%` }}
></div>
</div>
</div>
<button
onClick={handleStop}
className="p-1 hover:bg-[var(--bg-elevated)] rounded-lg transition-colors text-[var(--text-muted)] hover:text-[var(--accent-error)]"
title="Arrêter l'analyse"
>
<XCircle className="w-4 h-4" />
</button>
</div>
) : progress.current > 0 ? (
<div className="apple-btn-primary opacity-80 cursor-default">
<CheckCircle2 className="w-4 h-4" />
<span>
{progress.errors > 0 ? `Terminé (${progress.current - progress.errors}/${progress.total})` : `Analyse Terminée`}
</span>
</div>
) : (
<button
onClick={handleAnalyze}
className="apple-btn-secondary"
>
<Sparkles className="w-4 h-4" style={{ color: "var(--accent)" }} />
Analyse IA
</button>
)}
</div>
);
}
@@ -118,7 +118,7 @@ export function ExportDropdown({ nomFournisseur }: { nomFournisseur?: string })
doc.text(`Export généré le : ${new Date().toLocaleDateString("fr-FR")}`, 14, 30);
const head = [
["Gencode", "Code In", "Réf.", "Libellé", "Score", "Vol.", "CA", "Marge", "Gamme"]
["Gencode", "Code In", "Réf.", "Libellé", "Mag. Rés.", "Vol.", "CA", "Marge", "Gamme"]
];
const body = rows.map(r => {
@@ -128,7 +128,7 @@ export function ExportDropdown({ nomFournisseur }: { nomFournisseur?: string })
r.codein,
r.reference || "-",
r.libelle1 ? r.libelle1.substring(0, 60) + (r.libelle1.length > 60 ? "..." : "") : "",
r.score.toString(),
r.nbMagasinsReseau != null ? r.nbMagasinsReseau.toString() : "-",
Math.round(r.totalQuantite).toLocaleString("fr-FR"),
`${Math.round(r.totalCa).toLocaleString("fr-FR")} €`,
`${Math.round(r.totalMarge).toLocaleString("fr-FR")} €\n(${r.tauxMarge.toFixed(1)}%)`,
@@ -1,8 +1,7 @@
import { useGridStore } from "@/features/grid/store/use-grid-store";
import { useAiCopilotStore } from "@/features/ai-copilot/store/use-ai-copilot-store";
import { useSession } from "next-auth/react";
import { BulkAiAnalyzer } from "./bulk-ai-analyzer";
import { SyncQlikButton } from "./sync-qlik-button";
import { useSaveDrafts } from "@/features/grid/hooks/use-save-drafts";
import { Loader2, CheckCircle, AlertCircle, RotateCcw, Camera, ChevronDown } from "lucide-react";
import { useMemo, useState, useTransition } from "react";
@@ -35,7 +34,6 @@ export function FloatingSummaryBar() {
const rows = useGridStore((s) => s.rows);
const filters = useGridStore((s) => s.filters);
const draftChanges = useGridStore((s) => s.draftChanges);
const { resetInsights } = useAiCopilotStore();
const [isPending, startTransition] = useTransition();
const [isSavingSnapshot, setIsSavingSnapshot] = useState(false);
const [saveStatus, setSaveStatus] = useState<"idle" | "success" | "error">("idle");
@@ -48,6 +46,15 @@ export function FloatingSummaryBar() {
const visibleCodeins = useMemo(() => rows.map(r => r.codein), [rows]);
const { save, hasDrafts, count } = useSaveDrafts(filters.magasin || "TOTAL", visibleCodeins);
const supplierCode = filters.codeFournisseur || rows[0]?.codeFournisseur;
const lastQlikUpdate = useMemo(() => {
let max: string | null = null;
for (const r of rows) {
if (r.networkFetchedAt && (!max || r.networkFetchedAt > max)) max = r.networkFetchedAt;
}
return max;
}, [rows]);
const handleSave = () => {
startTransition(async () => {
const result = await save();
@@ -57,9 +64,8 @@ export function FloatingSummaryBar() {
};
const handleReset = () => {
if (window.confirm("Es-tu sûr de vouloir annuler tous les changements non enregistrés (gammes et analyses IA) ?")) {
if (window.confirm("Es-tu sûr de vouloir annuler tous les changements non enregistrés (gammes) ?")) {
resetDrafts();
resetInsights();
}
};
@@ -182,7 +188,7 @@ export function FloatingSummaryBar() {
</div>
<div className="flex space-x-3 items-center">
{isAdmin && <BulkAiAnalyzer />}
{isAdmin && <SyncQlikButton codeFournisseur={supplierCode} lastUpdate={lastQlikUpdate} />}
<DropdownMenu>
<DropdownMenuTrigger asChild>
+51 -74
View File
@@ -26,7 +26,6 @@ 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 { AiInsightBlock } from "@/features/ai-copilot/components/ai-insight-block";
function getLast12Months(): string[] {
const months: string[] = [];
@@ -178,8 +177,8 @@ const GridRow = React.memo(({ virtualRow, row, rowHeight, isSelected, columnVisi
}}
>
{row.getVisibleCells().map((cell: Cell<ProductRow, unknown>) => {
const isFlexible = cell.column.id === "libelle1" || cell.column.id === "ai" || 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 === "score" || cell.column.id === "gamme";
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 === "tauxPresenceReseau" || cell.column.id === "gamme";
const size = cell.column.getSize();
return (
<td
@@ -507,67 +506,56 @@ export function HeatmapGrid({ onSelectionChange, isAdmin }: HeatmapGridProps) {
},
},
{
accessorKey: "score",
header: "Score",
size: 60,
accessorKey: "caReseau",
header: () => <div className="text-center w-full">CA<br/><span className="text-[9px] opacity-60">Réseau</span></div>,
size: 90,
cell: ({ getValue }) => {
const val = getValue<number>();
const color = val >= 80 ? "text-emerald-500" : val >= 50 ? "text-amber-500" : "text-rose-500";
const val = getValue<number | undefined>();
return (
<div className="text-center tabular-nums text-[12px] font-bold text-emerald-600 dark:text-emerald-400">
{val != null ? val.toLocaleString("fr-FR", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }) : "-"}
</div>
);
},
},
{
accessorKey: "qteReseau",
header: () => <div className="text-center w-full">Qté<br/><span className="text-[9px] opacity-60">Réseau</span></div>,
size: 80,
cell: ({ getValue }) => {
const val = getValue<number | undefined>();
return (
<div className="text-center tabular-nums text-[12px] font-bold" style={{ color: "var(--text-secondary)" }}>
{val != null ? Math.round(val).toLocaleString("fr-FR") : "-"}
</div>
);
},
},
{
accessorKey: "nbMagasinsReseau",
header: () => <div className="text-center w-full">Magasins<br/><span className="text-[9px] opacity-60">/ 270</span></div>,
size: 80,
cell: ({ getValue }) => {
const val = getValue<number | undefined>();
return (
<div className="text-center tabular-nums text-[12px] font-bold" style={{ color: "var(--text-secondary)" }}>
{val != null ? val : "-"}
</div>
);
},
},
{
accessorKey: "tauxPresenceReseau",
header: () => <div className="text-center w-full">% Prés.<br/><span className="text-[9px] opacity-60">Réseau</span></div>,
size: 70,
cell: ({ getValue }) => {
const val = getValue<number | undefined>();
if (val == null) return <div className="text-center text-[12px]" style={{ color: "var(--text-secondary)" }}>-</div>;
const pct = Math.round(val * 100);
const color = pct >= 66 ? "text-emerald-500" : pct >= 33 ? "text-amber-500" : "text-rose-500";
return (
<div className={cn("text-center font-black text-[13px] tabular-nums", color)}>
{val}
</div>
);
},
},
{
accessorKey: "rankingCa",
header: () => <div className="text-center w-full">Rk CA<br/><span className="text-[9px] opacity-60">Réseau</span></div>,
size: 70,
cell: ({ getValue }) => {
const val = getValue<number | undefined>();
return (
<div className="text-center tabular-nums text-[12px] font-bold" style={{ color: "var(--text-secondary)" }}>
{val != null ? val : "-"}
</div>
);
},
},
{
accessorKey: "rankingQte",
header: () => <div className="text-center w-full">Rk Qté<br/><span className="text-[9px] opacity-60">Réseau</span></div>,
size: 70,
cell: ({ getValue }) => {
const val = getValue<number | undefined>();
return (
<div className="text-center tabular-nums text-[12px] font-bold" style={{ color: "var(--text-secondary)" }}>
{val != null ? val : "-"}
</div>
);
},
},
{
accessorKey: "rankingMagCa",
header: () => <div className="text-center w-full">Rk CA<br/><span className="text-[9px] opacity-60">Mag.</span></div>,
size: 70,
cell: ({ getValue }) => {
const val = getValue<number | undefined>();
return (
<div className="text-center tabular-nums text-[12px] font-bold" style={{ color: "var(--text-secondary)" }}>
{val != null ? val : "-"}
</div>
);
},
},
{
accessorKey: "rankingMagQte",
header: () => <div className="text-center w-full">Rk Qté<br/><span className="text-[9px] opacity-60">Mag.</span></div>,
size: 70,
cell: ({ getValue }) => {
const val = getValue<number | undefined>();
return (
<div className="text-center tabular-nums text-[12px] font-bold" style={{ color: "var(--text-secondary)" }}>
{val != null ? val : "-"}
{pct}%
</div>
);
},
@@ -679,17 +667,6 @@ export function HeatmapGrid({ onSelectionChange, isAdmin }: HeatmapGridProps) {
size: 110,
cell: ({ row }) => <GammeCell row={row.original} isAdmin={isAdmin} />,
},
{
id: "ai",
header: () => <div className="print:hidden">Recommandation IA</div>,
size: 230,
enableSorting: false,
cell: ({ row }) => (
<div className="print:hidden w-full h-full">
<AiInsightBlock row={row.original} />
</div>
),
},
], [MONTHS_12, activeMagasin, isAdmin]); // activeMagasin déclenche re-render des cellules mensuelles et totaux
const table = useReactTable({
@@ -800,8 +777,8 @@ export function HeatmapGrid({ onSelectionChange, isAdmin }: HeatmapGridProps) {
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id} className="flex w-full">
{headerGroup.headers.map((header) => {
const isFlexible = header.column.id === "libelle1" || header.column.id === "ai" || 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 === "score" || header.column.id === "gamme";
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 === "tauxPresenceReseau" || header.column.id === "gamme";
const size = header.getSize();
return (
<th
@@ -110,7 +110,7 @@ export function NoSalesTab() {
<div className="sticky top-0 z-10 grid grid-cols-[90px_minmax(220px,1fr)_120px_76px_130px_70px_90px_110px_70px]"
style={{ background: "var(--bg-elevated)", borderBottom: "1px solid var(--border)" }}
>
{["Code", "Libellé", "Réf.", "Gamme", "Dernière vente", "Jours", "Stock", "CA 12m", "Score"].map(col => (
{["Code", "Libellé", "Réf.", "Gamme", "Dernière vente", "Jours", "Stock", "CA 12m", "Mag."].map(col => (
<div key={col}
className="px-3 py-2 text-left font-semibold whitespace-nowrap"
style={{ color: "var(--text-muted)" }}
@@ -159,8 +159,8 @@ export function NoSalesTab() {
{row.totalCa > 0 ? formatCa(row.totalCa) : "—"}
</div>
<div className="px-3 py-1.5 text-right tabular-nums font-semibold"
style={{ color: row.score >= 50 ? "var(--color-amber, #f59e0b)" : "var(--text-muted)" }}>
{row.score > 0 ? row.score : "—"}
style={{ color: "var(--text-secondary)" }}>
{row.nbMagasinsReseau != null ? row.nbMagasinsReseau : "—"}
</div>
</div>
);
@@ -1,104 +0,0 @@
"use client";
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogTrigger } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Brain } from "lucide-react";
interface SupplierAiContextModalProps {
codeFournisseur: string | null;
nomFournisseur: string | null;
}
export function SupplierAiContextModal({ codeFournisseur, nomFournisseur }: SupplierAiContextModalProps) {
const [open, setOpen] = useState(false);
const [context, setContext] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [isSaving, setIsSaving] = useState(false);
useEffect(() => {
if (open && codeFournisseur) {
fetchContext();
}
}, [open, codeFournisseur]);
const fetchContext = async () => {
setIsLoading(true);
try {
const res = await fetch(`/api/ai/context?fournisseur=${codeFournisseur}`);
if (res.ok) {
const data = await res.json();
setContext(data.context || "");
}
} catch (error) {
console.error("Failed to load AI context", error);
} finally {
setIsLoading(false);
}
};
const handleSave = async () => {
if (!codeFournisseur) return;
setIsSaving(true);
try {
const res = await fetch("/api/ai/context", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ codeFournisseur, context }),
});
if (res.ok) {
setOpen(false);
} else {
console.error("Failed to save AI context");
}
} catch (error) {
console.error("Failed to save AI context", error);
} finally {
setIsSaving(false);
}
};
if (!codeFournisseur) return null;
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<button className="apple-btn-rules">
<Brain className="w-4 h-4" />
Règles IA
</button>
</DialogTrigger>
<DialogContent className="sm:max-w-[500px] bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-xl">
<DialogHeader>
<DialogTitle>Contexte IA - {nomFournisseur || codeFournisseur}</DialogTitle>
<DialogDescription>
Définissez ici les règles métier absolues pour ce fournisseur.
Mary (l'IA) respectera ces consignes en priorité lors de ses recommandations (ex: "Les calendriers vont en gamme C").
</DialogDescription>
</DialogHeader>
<div className="py-4">
<Textarea
placeholder="Ex: Les produits dont le nom contient 'Agenda' doivent toujours être classés en [A]..."
value={context}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setContext(e.target.value)}
disabled={isLoading}
className="min-h-[150px]"
/>
</div>
<DialogFooter>
<button className="apple-btn-secondary" onClick={() => setOpen(false)} disabled={isSaving}>
Annuler
</button>
<button onClick={handleSave} disabled={isSaving || isLoading} className="apple-btn-primary">
{isSaving ? "Enregistrement..." : "Enregistrer les règles"}
</button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,82 @@
"use client";
import { useState } from "react";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { Loader2, RefreshCw, CheckCircle, AlertCircle } from "lucide-react";
interface SyncQlikButtonProps {
/** Code fournisseur affiché (pour sync ciblée) */
codeFournisseur?: string;
/** Date ISO de dernière maj Qlik pour ce fournisseur (max des lignes) */
lastUpdate?: string | null;
}
function formatDate(iso?: string | null): string {
if (!iso) return "jamais";
const d = new Date(iso);
if (isNaN(d.getTime())) return "jamais";
return d.toLocaleString("fr-FR", { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" });
}
/**
* Bouton admin : synchronise depuis Qlik les métriques réseau du fournisseur affiché
* (POST /api/qlik/sync?fournisseur=…) puis recharge la grille. Affiche la dernière maj.
*/
export function SyncQlikButton({ codeFournisseur, lastUpdate }: SyncQlikButtonProps) {
const [status, setStatus] = useState<"idle" | "loading" | "success" | "error">("idle");
const [message, setMessage] = useState<string>("");
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const handleSync = async () => {
if (!codeFournisseur) {
setStatus("error");
setMessage("Aucun fournisseur sélectionné");
return;
}
setStatus("loading");
setMessage("");
try {
const res = await fetch(`/api/qlik/sync?fournisseur=${encodeURIComponent(codeFournisseur)}`, { method: "POST" });
const data = await res.json();
if (!res.ok || !data.success) throw new Error(data.error || `HTTP ${res.status}`);
setStatus("success");
setMessage(`${data.upserted} produits réseau synchronisés`);
// Recharge la grille pour afficher les nouvelles données réseau
const params = new URLSearchParams(searchParams.toString());
params.set("_refresh", String(Date.now()));
router.replace(`${pathname}?${params.toString()}`);
setTimeout(() => setStatus("idle"), 4000);
} catch (e) {
setStatus("error");
setMessage(e instanceof Error ? e.message : String(e));
setTimeout(() => setStatus("idle"), 6000);
}
};
return (
<div className="flex flex-col items-end">
<button
onClick={handleSync}
disabled={status === "loading"}
className="btn-action btn-action-secondary flex items-center gap-1.5 disabled:opacity-60"
title={message || "Synchroniser les données réseau Qlik pour ce fournisseur"}
>
{status === "loading" ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : status === "success" ? (
<CheckCircle className="w-3.5 h-3.5 text-emerald-500" />
) : status === "error" ? (
<AlertCircle className="w-3.5 h-3.5 text-rose-500" />
) : (
<RefreshCw className="w-3.5 h-3.5" />
)}
Sync Qlik
</button>
<span className="text-[10px] text-slate-500 mt-0.5">
{status === "error" ? message : `MAJ Qlik : ${formatDate(lastUpdate)}`}
</span>
</div>
);
}