mirror of
https://github.com/R0m1k3/CollectFlow.git
synced 2026-10-11 17:26:32 +02:00
chore: retire la section Score des Paramètres et supprime la page Chat IA
- Section « Score Produit » retirée : elle ne faisait que décrire une formule, sans rien paramétrer. - Page /admin/ai-chat et sa route /api/admin/ai-chat supprimées, ainsi que l'entrée de menu et la section « Admin AI Chat — Fournisseur » des Paramètres, qui n'existait que pour la configurer. - Nettoyage de l'état devenu mort dans la page Paramètres : la liste des modèles Google et son chargement n'avaient plus d'interface. Effet de bord notable : tsc passe de 23 à 4 erreurs préexistantes — la page de chat en portait 19 à elle seule (flags de regex exigeant une cible es2018). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Y26nRZxTR57K7h8yqsF675
This commit is contained in:
6 files changed
+78
-1144
No files matched your search
@@ -178,6 +178,31 @@ async function main() {
|
||||
`);
|
||||
console.log("[DB Init] Table api_keys is verified/created.");
|
||||
|
||||
// Paramétrage et suivi de la synchronisation nocturne, par fournisseur.
|
||||
await tempPool.query(`
|
||||
CREATE TABLE IF NOT EXISTS "sync_fournisseurs" (
|
||||
"code_fournisseur" varchar(20) PRIMARY KEY NOT NULL,
|
||||
"nom_fournisseur" varchar(255),
|
||||
"actif_sql" boolean NOT NULL DEFAULT true,
|
||||
"actif_qlik" boolean NOT NULL DEFAULT true,
|
||||
"desactive_motif" text,
|
||||
"dernier_sql_at" timestamp,
|
||||
"dernier_sql_statut" varchar(20),
|
||||
"dernier_sql_lignes" integer,
|
||||
"dernier_sql_erreur" text,
|
||||
"dernier_sql_ms" integer,
|
||||
"dernier_qlik_at" timestamp,
|
||||
"dernier_qlik_statut" varchar(20),
|
||||
"dernier_qlik_codes" integer,
|
||||
"dernier_qlik_erreur" text,
|
||||
"dernier_qlik_ms" integer,
|
||||
"updated_at" timestamp DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS "idx_sync_fou_sql" ON "sync_fournisseurs" ("actif_sql", "dernier_sql_at");
|
||||
CREATE INDEX IF NOT EXISTS "idx_sync_fou_qlik" ON "sync_fournisseurs" ("actif_qlik", "dernier_qlik_at");
|
||||
`);
|
||||
console.log("[DB Init] Table sync_fournisseurs is verified/created.");
|
||||
|
||||
await tempPool.end();
|
||||
console.log("[DB Init] Initialization successful. Exiting.");
|
||||
process.exit(0);
|
||||
|
||||
@@ -1,528 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useEffect, useCallback } from "react";
|
||||
import { Send, Bot, User, Database, Loader2, AlertCircle, ChevronDown, Trash2, DollarSign } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
|
||||
// Strip HTML tags and convert common HTML constructs to Markdown equivalents
|
||||
function htmlToMarkdown(text: string): string {
|
||||
return text
|
||||
// Block-level → markdown
|
||||
.replace(/<h([1-6])[^>]*>(.*?)<\/h\1>/gis, (_, level, content) => `${"#".repeat(Number(level))} ${content.replace(/<[^>]+>/g, "")}\n`)
|
||||
.replace(/<strong[^>]*>(.*?)<\/strong>/gis, "**$1**")
|
||||
.replace(/<b[^>]*>(.*?)<\/b>/gis, "**$1**")
|
||||
.replace(/<em[^>]*>(.*?)<\/em>/gis, "*$1*")
|
||||
.replace(/<i[^>]*>(.*?)<\/i>/gis, "*$1*")
|
||||
.replace(/<code[^>]*>(.*?)<\/code>/gis, "`$1`")
|
||||
.replace(/<pre[^>]*>(.*?)<\/pre>/gis, (_, c) => "```\n" + c.replace(/<[^>]+>/g, "") + "\n```")
|
||||
.replace(/<li[^>]*>(.*?)<\/li>/gis, "- $1")
|
||||
.replace(/<ul[^>]*>|<\/ul>/gis, "")
|
||||
.replace(/<ol[^>]*>|<\/ol>/gis, "")
|
||||
.replace(/<tr[^>]*>/gis, "")
|
||||
.replace(/<\/tr>/gis, "\n")
|
||||
.replace(/<th[^>]*>(.*?)<\/th>/gis, "| **$1** ")
|
||||
.replace(/<td[^>]*>(.*?)<\/td>/gis, "| $1 ")
|
||||
.replace(/<table[^>]*>|<\/table>|<thead[^>]*>|<\/thead>|<tbody[^>]*>|<\/tbody>/gis, "")
|
||||
.replace(/<br\s*\/?>/gis, "\n")
|
||||
.replace(/<p[^>]*>(.*?)<\/p>/gis, "$1\n\n")
|
||||
.replace(/<div[^>]*>(.*?)<\/div>/gis, "$1\n")
|
||||
.replace(/<a[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>/gis, "[$2]($1)")
|
||||
// Strip any remaining tags
|
||||
.replace(/<[^>]+>/g, "")
|
||||
// Decode HTML entities
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/ /g, " ")
|
||||
// Clean up excessive blank lines
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
interface ModelInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
free: boolean;
|
||||
promptPrice: number; // $ per token
|
||||
completionPrice: number;
|
||||
}
|
||||
|
||||
interface ToolEvent {
|
||||
name: string;
|
||||
args: Record<string, unknown>;
|
||||
result?: string;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
toolEvents?: ToolEvent[];
|
||||
}
|
||||
|
||||
interface SessionUsage {
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
costUsd: number;
|
||||
}
|
||||
|
||||
const DEFAULT_MODEL = "google/gemini-2.0-flash-001";
|
||||
|
||||
// Compute cost from token counts and model pricing
|
||||
function computeCost(promptTokens: number, completionTokens: number, model: ModelInfo | null): number {
|
||||
if (!model) return 0;
|
||||
return promptTokens * model.promptPrice + completionTokens * model.completionPrice;
|
||||
}
|
||||
|
||||
function formatCost(usd: number): string {
|
||||
if (usd === 0) return "Gratuit";
|
||||
if (usd < 0.001) return `$${(usd * 1000).toFixed(4)}m`;
|
||||
return `$${usd.toFixed(6)}`;
|
||||
}
|
||||
|
||||
function ToolCallBlock({ event }: { event: ToolEvent }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const label = event.name === "execute_sql"
|
||||
? `SQL: ${String(event.args.query ?? "").substring(0, 60)}${String(event.args.query ?? "").length > 60 ? "…" : ""}`
|
||||
: event.name === "get_db_schema"
|
||||
? "Schéma DB"
|
||||
: event.name;
|
||||
|
||||
return (
|
||||
<div className="my-1 rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] overflow-hidden text-xs">
|
||||
<button
|
||||
onClick={() => setOpen(!open)}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-[var(--bg-base)] transition-colors"
|
||||
>
|
||||
<Database className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />
|
||||
<span className="flex-1 text-[var(--text-secondary)] font-mono truncate">{label}</span>
|
||||
<ChevronDown className={cn("w-3.5 h-3.5 text-[var(--text-muted)] transition-transform", open && "rotate-180")} />
|
||||
</button>
|
||||
{open && event.result && (
|
||||
<pre className="px-3 pb-3 pt-1 text-[10px] text-[var(--text-secondary)] overflow-x-auto whitespace-pre-wrap break-words max-h-48 overflow-y-auto">
|
||||
{event.result}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageBubble({ msg }: { msg: Message }) {
|
||||
const isUser = msg.role === "user";
|
||||
|
||||
return (
|
||||
<div className={cn("flex gap-3 mb-4", isUser && "flex-row-reverse")}>
|
||||
{/* Avatar */}
|
||||
<div className={cn(
|
||||
"w-8 h-8 rounded-full flex items-center justify-center shrink-0 mt-0.5",
|
||||
isUser ? "bg-[var(--accent)] text-white" : "bg-[var(--bg-elevated)] border border-[var(--border)]"
|
||||
)}>
|
||||
{isUser
|
||||
? <User className="w-4 h-4" />
|
||||
: <Bot className="w-4 h-4 text-[var(--accent)]" />
|
||||
}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className={cn("flex-1 max-w-[85%]", isUser && "flex flex-col items-end")}>
|
||||
{/* Tool events (assistant only) */}
|
||||
{msg.toolEvents && msg.toolEvents.length > 0 && (
|
||||
<div className="w-full mb-2">
|
||||
{msg.toolEvents.map((ev, i) => (
|
||||
<ToolCallBlock key={i} event={ev} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Text bubble */}
|
||||
{msg.content && (
|
||||
<div className={cn(
|
||||
"rounded-2xl px-4 py-3 text-sm leading-relaxed break-words",
|
||||
isUser
|
||||
? "bg-[var(--accent)] text-white rounded-tr-md"
|
||||
: "bg-[var(--bg-elevated)] border border-[var(--border)] text-[var(--text-primary)] rounded-tl-md"
|
||||
)}>
|
||||
{isUser ? msg.content : (
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={{
|
||||
p: ({ children }) => <p className="mb-2 last:mb-0">{children}</p>,
|
||||
h1: ({ children }) => <h1 className="text-base font-bold mb-2 mt-3 first:mt-0">{children}</h1>,
|
||||
h2: ({ children }) => <h2 className="text-sm font-bold mb-2 mt-3 first:mt-0">{children}</h2>,
|
||||
h3: ({ children }) => <h3 className="text-sm font-semibold mb-1 mt-2 first:mt-0">{children}</h3>,
|
||||
ul: ({ children }) => <ul className="list-disc list-inside mb-2 space-y-0.5">{children}</ul>,
|
||||
ol: ({ children }) => <ol className="list-decimal list-inside mb-2 space-y-0.5">{children}</ol>,
|
||||
li: ({ children }) => <li className="ml-2">{children}</li>,
|
||||
code: ({ inline, children }: { inline?: boolean; children?: React.ReactNode }) =>
|
||||
inline
|
||||
? <code className="px-1 py-0.5 rounded bg-[var(--bg-base)] border border-[var(--border)] font-mono text-xs text-[var(--accent)]">{children}</code>
|
||||
: <pre className="my-2 p-3 rounded-lg bg-[var(--bg-base)] border border-[var(--border)] overflow-x-auto"><code className="font-mono text-xs text-[var(--text-primary)] whitespace-pre">{children}</code></pre>,
|
||||
strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
|
||||
em: ({ children }) => <em className="italic">{children}</em>,
|
||||
blockquote: ({ children }) => <blockquote className="border-l-2 border-[var(--accent)] pl-3 my-2 text-[var(--text-secondary)] italic">{children}</blockquote>,
|
||||
table: ({ children }) => <div className="overflow-x-auto my-2"><table className="w-full text-xs border-collapse">{children}</table></div>,
|
||||
thead: ({ children }) => <thead className="bg-[var(--bg-base)]">{children}</thead>,
|
||||
th: ({ children }) => <th className="border border-[var(--border)] px-2 py-1 text-left font-semibold">{children}</th>,
|
||||
td: ({ children }) => <td className="border border-[var(--border)] px-2 py-1">{children}</td>,
|
||||
hr: () => <hr className="border-[var(--border)] my-3" />,
|
||||
a: ({ href, children }) => <a href={href} target="_blank" rel="noopener noreferrer" className="text-[var(--accent)] underline hover:opacity-80">{children}</a>,
|
||||
}}
|
||||
>
|
||||
{htmlToMarkdown(msg.content)}
|
||||
</ReactMarkdown>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
export default function AdminAiChatPage() {
|
||||
const [models, setModels] = useState<ModelInfo[]>([]);
|
||||
const [selectedModel, setSelectedModel] = useState<string>(DEFAULT_MODEL);
|
||||
const [aiProvider, setAiProviderState] = useState<"openrouter" | "google">("openrouter");
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [input, setInput] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loadingModels, setLoadingModels] = useState(true);
|
||||
const [sessionUsage, setSessionUsage] = useState<SessionUsage>({ promptTokens: 0, completionTokens: 0, costUsd: 0 });
|
||||
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const selectedModelInfo = models.find(m => m.id === selectedModel) ?? null;
|
||||
|
||||
// Fetch config + models
|
||||
useEffect(() => {
|
||||
setLoadingModels(true);
|
||||
fetch("/api/admin/ai-config")
|
||||
.then(r => r.json())
|
||||
.then(async d => {
|
||||
const provider: "openrouter" | "google" = d.provider ?? "openrouter";
|
||||
setAiProviderState(provider);
|
||||
if (provider === "google") {
|
||||
const gRes = await fetch("/api/google-ai/models").then(r => r.json()).catch(() => ({ models: [] }));
|
||||
setModels((gRes.models ?? []).map((m: { id: string; name: string }) => ({
|
||||
id: m.id, name: m.name, free: false, promptPrice: 0, completionPrice: 0,
|
||||
})));
|
||||
setSelectedModel(d.googleAiModel ?? "gemini-2.0-flash");
|
||||
} else {
|
||||
const od = await fetch("/api/openrouter/models").then(r => r.json()).catch(() => ({ models: [] }));
|
||||
if (od.models) setModels(od.models);
|
||||
if (d.openRouterModel) setSelectedModel(d.openRouterModel);
|
||||
}
|
||||
})
|
||||
.catch(async () => {
|
||||
const od = await fetch("/api/openrouter/models").then(r => r.json()).catch(() => ({ models: [] }));
|
||||
if (od.models) setModels(od.models);
|
||||
})
|
||||
.finally(() => setLoadingModels(false));
|
||||
}, []);
|
||||
|
||||
// Auto-scroll
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [messages, loading]);
|
||||
|
||||
const sendMessage = useCallback(async () => {
|
||||
if (!input.trim() || loading) return;
|
||||
|
||||
const userMsg: Message = { role: "user", content: input.trim() };
|
||||
setInput("");
|
||||
setError(null);
|
||||
setMessages(prev => [...prev, userMsg]);
|
||||
setLoading(true);
|
||||
|
||||
// Build messages to send (excluding tool events, which are local display only)
|
||||
const apiMessages = [...messages, userMsg].map(m => ({
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
}));
|
||||
|
||||
const assistantMsg: Message = { role: "assistant", content: "", toolEvents: [] };
|
||||
setMessages(prev => [...prev, assistantMsg]);
|
||||
|
||||
abortRef.current = new AbortController();
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/admin/ai-chat", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ messages: apiMessages, model: selectedModel }),
|
||||
signal: abortRef.current.signal,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new Error(err.error || "Erreur serveur");
|
||||
}
|
||||
|
||||
const reader = res.body!.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
const pendingToolEvents: ToolEvent[] = [];
|
||||
let lastToolStart: ToolEvent | null = null;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split("\n");
|
||||
buffer = lines.pop() ?? "";
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith("data: ")) continue;
|
||||
const raw = line.slice(6).trim();
|
||||
try {
|
||||
const event = JSON.parse(raw);
|
||||
|
||||
if (event.type === "text") {
|
||||
setMessages(prev => {
|
||||
const copy = [...prev];
|
||||
const last = { ...copy[copy.length - 1] };
|
||||
last.content += event.content;
|
||||
copy[copy.length - 1] = last;
|
||||
return copy;
|
||||
});
|
||||
} else if (event.type === "tool_start") {
|
||||
lastToolStart = { name: event.name, args: event.args };
|
||||
} else if (event.type === "tool_result") {
|
||||
if (lastToolStart) {
|
||||
const ev: ToolEvent = { ...lastToolStart, result: event.result };
|
||||
pendingToolEvents.push(ev);
|
||||
lastToolStart = null;
|
||||
setMessages(prev => {
|
||||
const copy = [...prev];
|
||||
const last = { ...copy[copy.length - 1] };
|
||||
last.toolEvents = [...pendingToolEvents];
|
||||
copy[copy.length - 1] = last;
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
} else if (event.type === "usage") {
|
||||
const pt = event.prompt_tokens ?? 0;
|
||||
const ct = event.completion_tokens ?? 0;
|
||||
const cost = computeCost(pt, ct, selectedModelInfo);
|
||||
setSessionUsage(prev => ({
|
||||
promptTokens: prev.promptTokens + pt,
|
||||
completionTokens: prev.completionTokens + ct,
|
||||
costUsd: prev.costUsd + cost,
|
||||
}));
|
||||
} else if (event.type === "error") {
|
||||
setError(event.message);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if ((err as Error).name !== "AbortError") {
|
||||
setError(err instanceof Error ? err.message : "Erreur inconnue");
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [input, loading, messages, selectedModel, selectedModelInfo]);
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
}
|
||||
};
|
||||
|
||||
const clearConversation = () => {
|
||||
setMessages([]);
|
||||
setSessionUsage({ promptTokens: 0, completionTokens: 0, costUsd: 0 });
|
||||
setError(null);
|
||||
if (loading && abortRef.current) {
|
||||
abortRef.current.abort();
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full max-h-full">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-4 shrink-0">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-[var(--text-primary)] flex items-center gap-2">
|
||||
<Bot className="w-5 h-5 text-[var(--accent)]" />
|
||||
Admin AI Chat
|
||||
</h1>
|
||||
<p className="text-xs text-[var(--text-muted)] mt-0.5">
|
||||
Accès direct à la base de données · Admin uniquement
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Usage / Cost */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[var(--bg-elevated)] border border-[var(--border)] text-xs text-[var(--text-secondary)]">
|
||||
<DollarSign className="w-3.5 h-3.5 text-[var(--accent)]" />
|
||||
<span className="font-mono font-semibold">{formatCost(sessionUsage.costUsd)}</span>
|
||||
<span className="text-[var(--text-muted)]">session</span>
|
||||
{sessionUsage.promptTokens > 0 && (
|
||||
<span className="text-[var(--text-muted)] ml-1">
|
||||
({sessionUsage.promptTokens + sessionUsage.completionTokens} tok)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={clearConversation}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-[var(--border)] text-xs text-[var(--text-secondary)] hover:bg-[var(--bg-elevated)] transition-colors"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
Effacer
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Model selector */}
|
||||
<div className="mb-4 shrink-0">
|
||||
<div className="flex items-center gap-3 p-3 rounded-xl bg-[var(--bg-elevated)] border border-[var(--border)]">
|
||||
<span className={cn(
|
||||
"text-[10px] font-semibold px-1.5 py-0.5 rounded shrink-0",
|
||||
aiProvider === "google"
|
||||
? "bg-blue-500/10 text-blue-500"
|
||||
: "bg-[var(--accent-bg)] text-[var(--accent)]"
|
||||
)}>
|
||||
{aiProvider === "google" ? "Google AI" : "OpenRouter"}
|
||||
</span>
|
||||
{loadingModels ? (
|
||||
<div className="flex items-center gap-2 text-xs text-[var(--text-muted)]">
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
Chargement des modèles…
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 flex-1 min-w-0">
|
||||
<select
|
||||
value={selectedModel}
|
||||
onChange={e => setSelectedModel(e.target.value)}
|
||||
className="flex-1 min-w-0 text-sm bg-transparent text-[var(--text-primary)] border-none outline-none cursor-pointer"
|
||||
>
|
||||
{models.map(m => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.name} {m.free ? "(Gratuit)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{selectedModelInfo && !selectedModelInfo.free && (
|
||||
<div className="flex items-center gap-2 text-[10px] text-[var(--text-muted)] shrink-0 font-mono">
|
||||
<span>in: ${(selectedModelInfo.promptPrice * 1_000_000).toFixed(2)}/M</span>
|
||||
<span>·</span>
|
||||
<span>out: ${(selectedModelInfo.completionPrice * 1_000_000).toFixed(2)}/M</span>
|
||||
</div>
|
||||
)}
|
||||
{selectedModelInfo?.free && (
|
||||
<span className="text-[10px] text-emerald-500 font-semibold shrink-0">GRATUIT</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Messages */}
|
||||
<div className="flex-1 overflow-y-auto min-h-0 rounded-xl bg-[var(--bg-base)] border border-[var(--border)] p-4">
|
||||
{messages.length === 0 && (
|
||||
<div className="h-full flex flex-col items-center justify-center text-center gap-4">
|
||||
<div className="w-16 h-16 rounded-2xl bg-[var(--accent-bg)] border border-[var(--accent-border)] flex items-center justify-center">
|
||||
<Bot className="w-8 h-8 text-[var(--accent)]" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[var(--text-primary)] font-medium mb-1">Assistant Admin CollectFlow</p>
|
||||
<p className="text-sm text-[var(--text-muted)] max-w-md">
|
||||
Posez des questions sur vos données, demandez des analyses, ou explorez la base de données.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2 max-w-lg mt-2">
|
||||
{[
|
||||
"Combien de produits par fournisseur ?",
|
||||
"Quels sont les 10 produits avec le plus de CA ?",
|
||||
"Montre-moi les snapshots récents",
|
||||
"Répartition des gammes A/B/C/D/Z",
|
||||
].map(suggestion => (
|
||||
<button
|
||||
key={suggestion}
|
||||
onClick={() => { setInput(suggestion); textareaRef.current?.focus(); }}
|
||||
className="text-xs text-left px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] hover:bg-[var(--bg-base)] text-[var(--text-secondary)] transition-colors"
|
||||
>
|
||||
{suggestion}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages.map((msg, i) => (
|
||||
<MessageBubble key={i} msg={msg} />
|
||||
))}
|
||||
|
||||
{loading && messages[messages.length - 1]?.role !== "assistant" && (
|
||||
<div className="flex gap-3 mb-4">
|
||||
<div className="w-8 h-8 rounded-full flex items-center justify-center bg-[var(--bg-elevated)] border border-[var(--border)]">
|
||||
<Bot className="w-4 h-4 text-[var(--accent)]" />
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 px-4 py-3 rounded-2xl rounded-tl-md bg-[var(--bg-elevated)] border border-[var(--border)]">
|
||||
<span className="w-1.5 h-1.5 bg-[var(--accent)] rounded-full animate-bounce [animation-delay:0ms]" />
|
||||
<span className="w-1.5 h-1.5 bg-[var(--accent)] rounded-full animate-bounce [animation-delay:150ms]" />
|
||||
<span className="w-1.5 h-1.5 bg-[var(--accent)] rounded-full animate-bounce [animation-delay:300ms]" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="flex items-start gap-2 p-3 rounded-xl bg-[var(--accent-error-bg)] border border-[var(--accent-error-border,var(--border))] text-sm text-[var(--accent-error)] mb-4">
|
||||
<AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
{/* Input */}
|
||||
<div className="mt-3 shrink-0">
|
||||
<div className="flex items-end gap-2 p-2 rounded-xl bg-[var(--bg-elevated)] border border-[var(--border)] focus-within:border-[var(--accent)] transition-colors">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={e => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Posez une question… (Entrée pour envoyer, Shift+Entrée pour nouvelle ligne)"
|
||||
rows={1}
|
||||
className="flex-1 resize-none bg-transparent text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)] outline-none py-2 px-2 max-h-32 overflow-y-auto"
|
||||
style={{ minHeight: "40px" }}
|
||||
onInput={(e) => {
|
||||
const el = e.currentTarget;
|
||||
el.style.height = "auto";
|
||||
el.style.height = Math.min(el.scrollHeight, 128) + "px";
|
||||
}}
|
||||
disabled={loading}
|
||||
/>
|
||||
<button
|
||||
onClick={sendMessage}
|
||||
disabled={!input.trim() || loading}
|
||||
className="w-9 h-9 rounded-lg bg-[var(--accent)] text-white flex items-center justify-center hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed transition-opacity shrink-0"
|
||||
>
|
||||
{loading
|
||||
? <Loader2 className="w-4 h-4 animate-spin" />
|
||||
: <Send className="w-4 h-4" />
|
||||
}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[10px] text-[var(--text-muted)] mt-1.5 text-center">
|
||||
L'IA peut exécuter des requêtes SELECT sur la base de données · Les modifications ne sont pas autorisées
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -263,10 +263,7 @@ export default function SettingsPage() {
|
||||
// AI Provider
|
||||
const [aiProvider, setAiProvider] = useState<"openrouter" | "google">("openrouter");
|
||||
const [googleAiKey, setGoogleAiKey] = useState("");
|
||||
const [showGoogleKey, setShowGoogleKey] = useState(false);
|
||||
const [googleAiModel, setGoogleAiModel] = useState("");
|
||||
const [googleModels, setGoogleModels] = useState<{ id: string; name: string }[]>([]);
|
||||
const [googleModelsStatus, setGoogleModelsStatus] = useState<"idle" | "loading" | "ok" | "error">("idle");
|
||||
|
||||
const [isMounted, setIsMounted] = useState(false);
|
||||
|
||||
@@ -280,20 +277,6 @@ export default function SettingsPage() {
|
||||
getDatabaseUrl
|
||||
} = useDbSettingsStore();
|
||||
|
||||
const fetchGoogleModels = useCallback(async (key: string) => {
|
||||
if (!key.trim()) return;
|
||||
setGoogleModelsStatus("loading");
|
||||
try {
|
||||
const res = await fetch("/api/google-ai/models", { headers: { "x-google-ai-key": key } });
|
||||
if (!res.ok) throw new Error();
|
||||
const data = await res.json();
|
||||
setGoogleModels(data.models ?? []);
|
||||
setGoogleModelsStatus("ok");
|
||||
} catch {
|
||||
setGoogleModelsStatus("error");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchModels = useCallback(async (key: string) => {
|
||||
if (!key.trim()) return;
|
||||
setModelsStatus("loading");
|
||||
@@ -333,13 +316,10 @@ export default function SettingsPage() {
|
||||
setSelectedModel(config.openRouterModel);
|
||||
}
|
||||
if (config.aiProvider) setAiProvider(config.aiProvider);
|
||||
if (config.googleAiKey) {
|
||||
setGoogleAiKey(config.googleAiKey);
|
||||
fetchGoogleModels(config.googleAiKey);
|
||||
}
|
||||
if (config.googleAiKey) setGoogleAiKey(config.googleAiKey);
|
||||
if (config.googleAiModel) setGoogleAiModel(config.googleAiModel);
|
||||
}
|
||||
}, [fetchModels, fetchGoogleModels, setApiKey, setDatabase, setHost, setPassword, setPort, setSelectedModel, setSsl, setUser]);
|
||||
}, [fetchModels, setApiKey, setDatabase, setHost, setPassword, setPort, setSelectedModel, setSsl, setUser]);
|
||||
|
||||
useEffect(() => {
|
||||
setIsMounted(true);
|
||||
@@ -477,86 +457,6 @@ export default function SettingsPage() {
|
||||
|
||||
<QlikSettingsSection />
|
||||
|
||||
{/* AI Provider selector */}
|
||||
<Section title="Admin AI Chat — Fournisseur" subtitle="Choisissez le fournisseur IA utilisé dans l'onglet Admin AI Chat">
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setAiProvider("openrouter")}
|
||||
className={`flex-1 py-2.5 px-4 rounded-lg border text-[13px] font-medium transition-colors ${aiProvider === "openrouter" ? "border-[var(--accent)] bg-[var(--accent-bg)] text-[var(--accent)]" : "border-[var(--border)] text-[var(--text-secondary)] hover:bg-[var(--bg-elevated)]"}`}
|
||||
>
|
||||
OpenRouter
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setAiProvider("google")}
|
||||
className={`flex-1 py-2.5 px-4 rounded-lg border text-[13px] font-medium transition-colors ${aiProvider === "google" ? "border-[var(--accent)] bg-[var(--accent-bg)] text-[var(--accent)]" : "border-[var(--border)] text-[var(--text-secondary)] hover:bg-[var(--bg-elevated)]"}`}
|
||||
>
|
||||
Google AI Studio
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{aiProvider === "google" && (
|
||||
<>
|
||||
<Field label="Clé API Google AI Studio" hint="Disponible sur aistudio.google.com/apikey — commence par AIza...">
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<input
|
||||
type={showGoogleKey ? "text" : "password"}
|
||||
placeholder="AIzaSy..."
|
||||
value={googleAiKey}
|
||||
onChange={(e) => setGoogleAiKey(e.target.value)}
|
||||
className="apple-input font-mono pr-10"
|
||||
/>
|
||||
<button
|
||||
onClick={() => setShowGoogleKey((v) => !v)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 opacity-50 hover:opacity-100 transition-opacity"
|
||||
>
|
||||
{showGoogleKey ? <EyeOff className="w-4 h-4" style={{ color: "var(--text-primary)" }} /> : <Eye className="w-4 h-4" style={{ color: "var(--text-primary)" }} />}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => fetchGoogleModels(googleAiKey)}
|
||||
disabled={!googleAiKey || googleModelsStatus === "loading"}
|
||||
className="apple-btn-secondary h-9 px-4 whitespace-nowrap"
|
||||
>
|
||||
{googleModelsStatus === "loading" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <RefreshCw className="w-3.5 h-3.5" />}
|
||||
Charger les modèles
|
||||
</button>
|
||||
</div>
|
||||
</Field>
|
||||
<Field
|
||||
label={`Modèle Google${googleModels.length > 0 ? ` (${googleModels.length} disponibles)` : ""}`}
|
||||
hint={googleModelsStatus === "error" ? "⚠ Erreur — vérifiez votre clé puis rechargez" : googleModelsStatus === "idle" ? "Entrez votre clé et cliquez « Charger les modèles »" : undefined}
|
||||
>
|
||||
{googleModels.length > 0 ? (
|
||||
<select
|
||||
value={googleAiModel}
|
||||
onChange={(e) => setGoogleAiModel(e.target.value)}
|
||||
className="apple-input"
|
||||
>
|
||||
{googleModels.map((m) => (
|
||||
<option key={m.id} value={m.id}>{m.name}</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
value={googleAiModel}
|
||||
onChange={(e) => setGoogleAiModel(e.target.value)}
|
||||
placeholder="ex: gemini-2.0-flash"
|
||||
className="apple-input"
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
|
||||
{aiProvider === "openrouter" && (
|
||||
<p className="text-[12px] text-[var(--text-muted)]">
|
||||
Utilise la clé OpenRouter configurée ci-dessous et le modèle sélectionné.
|
||||
</p>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{/* OpenRouter */}
|
||||
<Section title="IA Copilot — OpenRouter" subtitle="Clé API pour les analyses de gammes par intelligence artificielle">
|
||||
<Field label="Clé API" hint="Disponible sur openrouter.ai/keys — commence par sk-or-...">
|
||||
@@ -650,27 +550,6 @@ export default function SettingsPage() {
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
{/* Score Produit */}
|
||||
<Section title="Score Produit" subtitle="Formule hybride absolue + relative (v4)">
|
||||
<div className="bg-[var(--surface-tertiary)] rounded-lg p-3 space-y-2">
|
||||
<p className="text-[11px] text-[var(--text-secondary)]">
|
||||
<strong>Formule :</strong> Volume (50pts) + CA (30pts) + Marge (20pts) + Bonus relatif (±10pts)
|
||||
</p>
|
||||
<p className="text-[11px] text-[var(--text-muted)]">
|
||||
Le score est basé sur des paliers absolus sensibles au prix unitaire, avec un ajustement relatif selon la position dans le lot fournisseur.
|
||||
</p>
|
||||
<div className="border-t border-[var(--border-subtle)] pt-2 mt-2 space-y-1">
|
||||
<p className="text-[11px] text-[var(--text-secondary)]"><strong>Volume</strong> (0-50 pts) — unités / magasin / mois</p>
|
||||
<p className="text-[11px] text-[var(--text-secondary)]"><strong>CA</strong> (0-30 pts) — € / magasin / an</p>
|
||||
<p className="text-[11px] text-[var(--text-secondary)]"><strong>Marge</strong> (0-20 pts) — taux de marge %</p>
|
||||
<p className="text-[11px] text-[var(--text-secondary)]"><strong>Bonus relatif</strong> (±10 pts) — percentile composite dans le lot</p>
|
||||
</div>
|
||||
<p className="text-[11px] text-[var(--text-muted)] mt-2">
|
||||
Pénalité de régularité appliquée si inactivité prolongée. Score final borné 0-100.
|
||||
</p>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
{/* Journaux serveur — diagnostic des extractions Qlik */}
|
||||
<Section
|
||||
title="Journaux serveur"
|
||||
|
||||
@@ -1,491 +0,0 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
import { GoogleGenAI, Type } from "@google/genai";
|
||||
|
||||
interface AiConfig {
|
||||
provider: "openrouter" | "google";
|
||||
openRouterKey?: string;
|
||||
googleAiKey?: string;
|
||||
googleAiModel?: string;
|
||||
}
|
||||
|
||||
async function getAiConfig(): Promise<AiConfig> {
|
||||
try {
|
||||
const configFile = path.join(process.cwd(), "data", ".db-config.json");
|
||||
const data = await fs.readFile(configFile, "utf-8");
|
||||
const config = JSON.parse(data);
|
||||
return {
|
||||
provider: config.aiProvider ?? "openrouter",
|
||||
openRouterKey: config.openRouterKey ?? process.env.OPENROUTER_API_KEY,
|
||||
googleAiKey: config.googleAiKey ?? process.env.GOOGLE_AI_KEY,
|
||||
googleAiModel: config.googleAiModel ?? "gemini-2.0-flash",
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
provider: "openrouter",
|
||||
openRouterKey: process.env.OPENROUTER_API_KEY,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
|
||||
const FF_API_BASE = process.env.FF_API_BASE_URL ?? "https://api.ffnancy.fr";
|
||||
|
||||
// ─── Tool definitions ────────────────────────────────────────────────────────
|
||||
|
||||
const TOOLS_OPENROUTER = [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "call_api",
|
||||
description: "Appelle un endpoint de l'API FF Nancy pour récupérer des données (articles, stock, ventes, fournisseurs, commandes, etc.).",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
endpoint: {
|
||||
type: "string",
|
||||
description: "Chemin de l'endpoint, ex: /api/articles?codefou=FOU001&limit=50 ou /api/stock/article/12345",
|
||||
},
|
||||
},
|
||||
required: ["endpoint"],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const TOOLS_GOOGLE = [{
|
||||
functionDeclarations: [
|
||||
{
|
||||
name: "call_api",
|
||||
description: "Appelle un endpoint de l'API FF Nancy pour récupérer des données (articles, stock, ventes, fournisseurs, commandes, etc.).",
|
||||
parameters: {
|
||||
type: Type.OBJECT,
|
||||
properties: {
|
||||
endpoint: {
|
||||
type: Type.STRING,
|
||||
description: "Chemin de l'endpoint, ex: /api/articles?codefou=FOU001&limit=50 ou /api/stock/article/12345",
|
||||
},
|
||||
},
|
||||
required: ["endpoint"],
|
||||
},
|
||||
},
|
||||
],
|
||||
}];
|
||||
|
||||
// ─── API caller ───────────────────────────────────────────────────────────────
|
||||
|
||||
async function callFfApi(endpoint: string): Promise<string> {
|
||||
// Sécurité : uniquement GET, uniquement les endpoints documentés
|
||||
const allowedPrefixes = [
|
||||
"/api/health", "/api/sync", "/api/schema",
|
||||
"/api/articles", "/api/stock", "/api/fournisseurs",
|
||||
"/api/commandes", "/api/mouvements", "/api/performance",
|
||||
"/api/publicites", "/api/commandes-auto",
|
||||
];
|
||||
const isAllowed = allowedPrefixes.some(p => endpoint.startsWith(p));
|
||||
if (!isAllowed) {
|
||||
return `Erreur: endpoint non autorisé — "${endpoint}". Utilise uniquement les endpoints documentés.`;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${FF_API_BASE}${endpoint}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return `Erreur API ${res.status}: ${await res.text()}`;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const text = JSON.stringify(data);
|
||||
|
||||
// Tronquer si trop long (max 6000 chars)
|
||||
if (text.length > 6000) {
|
||||
return text.substring(0, 6000) + `\n...(tronqué, ${text.length} caractères total)`;
|
||||
}
|
||||
return text;
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Erreur inconnue";
|
||||
return `Erreur réseau: ${msg}`;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── System prompt ────────────────────────────────────────────────────────────
|
||||
|
||||
const SYSTEM_PROMPT = `Tu es un assistant IA administrateur expert pour l'application CollectFlow, un outil de gestion de gammes produits et d'analyse des ventes pour des magasins de distribution alimentaire (Foirfouille Nancy).
|
||||
|
||||
## Outil disponible
|
||||
- \`call_api\` : appelle un endpoint GET de l'API FF Nancy et retourne les données JSON
|
||||
|
||||
## API FF Nancy — Documentation complète
|
||||
Base URL : ${FF_API_BASE}
|
||||
Format des dates : YYYY-MM-DD
|
||||
Identifiants articles : toujours \`no_id\` (entier interne)
|
||||
Codes site : ex 000, 001, 002…
|
||||
|
||||
### Santé / Infra
|
||||
- GET /api/health — vérifie que l'API et PostgreSQL répondent
|
||||
- GET /api/sync/status — état de la synchronisation en cours
|
||||
- GET /api/schema/tables?search=nom — liste les tables PG
|
||||
- GET /api/schema/tables/:nom — colonnes d'une table
|
||||
- GET /api/schema/top?limit=10 — tables les plus peuplées
|
||||
|
||||
### Articles
|
||||
- GET /api/articles?search=&codein=&ean=&codefou=&actif=1&page=1&limit=50 — liste avec PA, GTIN, fournisseur principal (max 500/page)
|
||||
- GET /api/articles/:id — détail complet d'un article (no_id)
|
||||
- GET /api/articles/:id/referentiel — fournisseurs, tarifs, codes EAN
|
||||
- GET /api/articles/:id/mouvements — historique des mouvements
|
||||
- GET /api/articles/:id/mensuel — CA mensuel de l'article
|
||||
|
||||
Le champ **prix d'achat (PA)** est retourné directement dans GET /api/articles (champ \`pa\` ou \`prix_achat\`).
|
||||
Pour un article précis : GET /api/articles/:id/referentiel pour voir tous les tarifs fournisseurs.
|
||||
|
||||
### Stock
|
||||
- GET /api/stock?site=001&page=1&limit=100 — stock global tous articles (max 1000/page)
|
||||
- GET /api/stock/article/:id — stock par site pour un article (no_id) → contient aussi \`prmp\` (Prix de Revient Moyen Pondéré)
|
||||
- GET /api/stock/site/:site — tous les articles d'un site donné
|
||||
- GET /api/stock/article/:id/historique — historique stock de l'article
|
||||
- GET /api/stock/article/:id/periode?dateDebut=&dateFin= — stock sur période
|
||||
- GET /api/stock/valorisation — valeur totale du stock par site
|
||||
|
||||
Le **PRMP** (prix réel moyen pondéré) est dans GET /api/stock/article/:id, champ \`prmp\` par site.
|
||||
|
||||
### Fournisseurs
|
||||
- GET /api/fournisseurs?search=nom — liste des fournisseurs (champs : code, nom)
|
||||
- GET /api/fournisseurs/:code/articles — articles du fournisseur
|
||||
- GET /api/fournisseurs/:code/commandes — commandes du fournisseur
|
||||
|
||||
### Commandes
|
||||
- GET /api/commandes?dateDebut=&dateFin=&codefou= — liste des commandes fournisseurs
|
||||
- GET /api/commandes/:noCommande — détail d'une commande + ses lignes
|
||||
- GET /api/commandes/receptions/liste — liste des réceptions
|
||||
|
||||
### Commandes automatiques
|
||||
- GET /api/commandes-auto?site=&codefou= — résumé des propositions par fournisseur/site avec comparaison franco
|
||||
Champs : franco_ht, montant_propo_ht, franco_atteint (OUI/NON/N/A), ecart_franco
|
||||
- GET /api/commandes-auto/:codefou?site= — détail d'un fournisseur : résumé + liste des articles proposés avec stock et montant
|
||||
|
||||
### Mouvements
|
||||
- GET /api/mouvements/types — types de mouvements disponibles
|
||||
- GET /api/mouvements/articles?dateDebut=&dateFin=&site= — mouvements par article
|
||||
- GET /api/mouvements/entrees?dateDebut=&dateFin= — entrées marchandises
|
||||
- GET /api/mouvements/regularisations?dateDebut=&dateFin= — régularisations inventaire
|
||||
- GET /api/mouvements/reglements?dateDebut=&dateFin= — règlements
|
||||
- GET /api/mouvements/synthese?dateDebut=&dateFin=&site= — synthèse des mouvements
|
||||
|
||||
### Performance / CA
|
||||
- GET /api/performance/ca?dateDebut=&dateFin=&site=&groupBy=mois — CA global (groupBy: jour ou mois)
|
||||
- GET /api/performance/hitparade?dateDebut=&dateFin=&site=&limit=20&groupBy=ca — top articles (groupBy: qte, ca ou marge)
|
||||
- GET /api/performance/ca/nomenclature?dateDebut=&dateFin=&site=&niveau= — CA par nomenclature
|
||||
- GET /api/performance/ca/fournisseur?dateDebut=&dateFin=&site= — CA par fournisseur
|
||||
- GET /api/performance/ca/gamme?dateDebut=&dateFin=&site= — CA par gamme (A/B/C/D/Z)
|
||||
- GET /api/performance/dashboard — indicateurs résumés pour dashboard
|
||||
|
||||
### Publicités
|
||||
- GET /api/publicites?search=&site=&dateDebut=&dateFin=&page=1&limit=50 — liste des publicités
|
||||
- GET /api/publicites/:code?site= — détail d'une publicité
|
||||
|
||||
## Contexte métier CollectFlow
|
||||
- Application de gestion de gammes pour magasins Foirfouille Nancy
|
||||
- Gammes A/B/C/D/Z : A=pilier, B=bonne rotation, C=performance, D=saisonnier/niche, Z=sortie
|
||||
- Les ventes sont suivies par magasin (site) et par mois
|
||||
- Les utilisateurs arbitrent les classifications gamme par fournisseur
|
||||
|
||||
## Stratégie d'analyse
|
||||
1. Si tu ne connais pas un code fournisseur ou un no_id, commence par chercher avec /api/fournisseurs?search= ou /api/articles?search=
|
||||
2. Enchaîne plusieurs appels \`call_api\` si nécessaire pour compléter l'analyse
|
||||
3. Pour le prix d'achat : utilise /api/articles?codefou=CODE (champ pa) ou /api/articles/:id/referentiel
|
||||
4. Pour le PRMP (prix réel) : utilise /api/stock/article/:id (champ prmp par site)
|
||||
5. Ajoute toujours \`limit\` pour éviter des réponses trop volumineuses (limit=20 à 100 selon le contexte)
|
||||
|
||||
## Format de réponse — IMPORTANT
|
||||
- Réponds TOUJOURS en **Markdown** : titres ##, **gras**, tableaux \`| col | col |\`, listes \`-\`, blocs de code
|
||||
- N'utilise JAMAIS de HTML (<div>, <table>, <b>, <br>, etc.)
|
||||
- Réponds toujours en français
|
||||
- Sois précis, structuré et complet — ne tronque jamais ta réponse
|
||||
- Si les données sont nombreuses, résume et mets en avant les points clés`;
|
||||
|
||||
// ─── OpenRouter handler ───────────────────────────────────────────────────────
|
||||
|
||||
async function callOpenRouter(
|
||||
messages: object[],
|
||||
model: string,
|
||||
apiKey: string,
|
||||
useTools: boolean,
|
||||
stream: boolean
|
||||
): Promise<Response> {
|
||||
const body: Record<string, unknown> = {
|
||||
model,
|
||||
messages,
|
||||
temperature: 0.3,
|
||||
max_tokens: 8192,
|
||||
};
|
||||
if (useTools) {
|
||||
body.tools = TOOLS_OPENROUTER;
|
||||
body.tool_choice = "auto";
|
||||
}
|
||||
if (stream) {
|
||||
body.stream = true;
|
||||
body.stream_options = { include_usage: true };
|
||||
}
|
||||
return fetch(OPENROUTER_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
"HTTP-Referer": "https://collectflow.app",
|
||||
"X-Title": "CollectFlow Admin Chat",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Google AI handler ────────────────────────────────────────────────────────
|
||||
|
||||
async function handleGoogleAi(messages: Array<{ role: string; content: string }>, config: AiConfig): Promise<Response> {
|
||||
if (!config.googleAiKey) {
|
||||
return new Response(JSON.stringify({ error: "No Google AI key configured" }), { status: 500 });
|
||||
}
|
||||
|
||||
const model = config.googleAiModel ?? "gemini-2.0-flash";
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
function send(event: object) {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
}
|
||||
|
||||
try {
|
||||
const ai = new GoogleGenAI({ apiKey: config.googleAiKey! });
|
||||
|
||||
const contents: Array<{ role: string; parts: any[] }> = [
|
||||
...messages.map((m) => ({
|
||||
role: m.role === "assistant" ? "model" : "user",
|
||||
parts: [{ text: m.content }],
|
||||
})),
|
||||
];
|
||||
|
||||
for (let round = 0; round < 10; round++) {
|
||||
const streamResponse = await ai.models.generateContentStream({
|
||||
model,
|
||||
contents: contents as any,
|
||||
config: {
|
||||
systemInstruction: SYSTEM_PROMPT,
|
||||
tools: TOOLS_GOOGLE as any,
|
||||
maxOutputTokens: 8192,
|
||||
},
|
||||
});
|
||||
|
||||
let collectedText = "";
|
||||
const collectedParts: any[] = [];
|
||||
|
||||
for await (const chunk of streamResponse) {
|
||||
const text = chunk.text;
|
||||
if (text) {
|
||||
collectedText += text;
|
||||
send({ type: "text", content: text });
|
||||
}
|
||||
const parts = chunk.candidates?.[0]?.content?.parts;
|
||||
if (parts) collectedParts.push(...parts);
|
||||
}
|
||||
|
||||
const fnCallParts = collectedParts.filter((p: any) => p.functionCall);
|
||||
|
||||
if (fnCallParts.length === 0) break;
|
||||
|
||||
contents.push({ role: "model", parts: collectedText ? collectedParts : fnCallParts });
|
||||
|
||||
const toolResultParts: Array<{ functionResponse: { name: string; response: { output: string } } }> = [];
|
||||
for (const part of fnCallParts) {
|
||||
const fn = part.functionCall as { name: string; args: Record<string, unknown> };
|
||||
const args = fn.args ?? {};
|
||||
send({ type: "tool_start", name: fn.name, args });
|
||||
|
||||
let result = "";
|
||||
if (fn.name === "call_api") {
|
||||
result = await callFfApi(args.endpoint as string);
|
||||
} else {
|
||||
result = `Outil inconnu: ${fn.name}`;
|
||||
}
|
||||
|
||||
send({ type: "tool_result", name: fn.name, result: result.substring(0, 500) + (result.length > 500 ? "..." : "") });
|
||||
toolResultParts.push({ functionResponse: { name: fn.name, response: { output: result } } });
|
||||
}
|
||||
|
||||
contents.push({ role: "user", parts: toolResultParts as any });
|
||||
}
|
||||
|
||||
send({ type: "usage", prompt_tokens: 0, completion_tokens: 0 });
|
||||
send({ type: "done" });
|
||||
controller.close();
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Erreur inconnue";
|
||||
send({ type: "error", message: msg });
|
||||
controller.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── POST handler ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth();
|
||||
if (!session || (session.user as any)?.role !== "admin") {
|
||||
return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 403 });
|
||||
}
|
||||
|
||||
const { messages, model } = await req.json();
|
||||
const aiConfig = await getAiConfig();
|
||||
|
||||
if (aiConfig.provider === "google") {
|
||||
return handleGoogleAi(messages, aiConfig);
|
||||
}
|
||||
|
||||
const apiKey = aiConfig.openRouterKey;
|
||||
if (!apiKey) {
|
||||
return new Response(JSON.stringify({ error: "No OpenRouter API key configured" }), { status: 500 });
|
||||
}
|
||||
|
||||
const fullMessages: object[] = [
|
||||
{ role: "system", content: SYSTEM_PROMPT },
|
||||
...messages,
|
||||
];
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
function send(event: object) {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
}
|
||||
|
||||
try {
|
||||
let currentMessages = [...fullMessages];
|
||||
let totalPromptTokens = 0;
|
||||
let totalCompletionTokens = 0;
|
||||
let directAnswer: string | null = null;
|
||||
|
||||
for (let round = 0; round < 10; round++) {
|
||||
const res = await callOpenRouter(currentMessages, model, apiKey, true, false);
|
||||
if (!res.ok) {
|
||||
send({ type: "error", message: `OpenRouter error: ${await res.text()}` });
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
if (data.usage) {
|
||||
totalPromptTokens += data.usage.prompt_tokens ?? 0;
|
||||
totalCompletionTokens += data.usage.completion_tokens ?? 0;
|
||||
}
|
||||
|
||||
const assistantMessage = data.choices?.[0]?.message;
|
||||
if (!assistantMessage) break;
|
||||
currentMessages.push(assistantMessage);
|
||||
|
||||
const toolCalls = assistantMessage.tool_calls;
|
||||
if (!toolCalls || toolCalls.length === 0) {
|
||||
directAnswer = assistantMessage.content ?? "";
|
||||
break;
|
||||
}
|
||||
|
||||
const toolResults: object[] = [];
|
||||
for (const tc of toolCalls) {
|
||||
const fnName = tc.function?.name;
|
||||
let args: Record<string, unknown> = {};
|
||||
try { args = JSON.parse(tc.function?.arguments ?? "{}"); } catch { /* ignore */ }
|
||||
|
||||
send({ type: "tool_start", name: fnName, args });
|
||||
|
||||
let result = "";
|
||||
if (fnName === "call_api") {
|
||||
result = await callFfApi(args.endpoint as string);
|
||||
} else {
|
||||
result = `Outil inconnu: ${fnName}`;
|
||||
}
|
||||
|
||||
send({ type: "tool_result", name: fnName, result: result.substring(0, 500) + (result.length > 500 ? "..." : "") });
|
||||
toolResults.push({ role: "tool", tool_call_id: tc.id, content: result });
|
||||
}
|
||||
currentMessages.push(...toolResults);
|
||||
}
|
||||
|
||||
if (directAnswer !== null) {
|
||||
send({ type: "text", content: directAnswer });
|
||||
send({ type: "usage", prompt_tokens: totalPromptTokens, completion_tokens: totalCompletionTokens });
|
||||
send({ type: "done" });
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Final streaming call after tool use
|
||||
const finalRes = await callOpenRouter(currentMessages, model, apiKey, false, true);
|
||||
if (!finalRes.ok) {
|
||||
send({ type: "error", message: `OpenRouter error: ${await finalRes.text()}` });
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = finalRes.body?.getReader();
|
||||
if (!reader) { controller.close(); return; }
|
||||
|
||||
const textDecoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
let finalUsage: { prompt_tokens?: number; completion_tokens?: number } | null = null;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += textDecoder.decode(value, { stream: true });
|
||||
const lines = buffer.split("\n");
|
||||
buffer = lines.pop() ?? "";
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith("data: ")) continue;
|
||||
const raw = line.slice(6).trim();
|
||||
if (raw === "[DONE]") continue;
|
||||
try {
|
||||
const chunk = JSON.parse(raw);
|
||||
const delta = chunk.choices?.[0]?.delta?.content;
|
||||
if (delta) send({ type: "text", content: delta });
|
||||
if (chunk.usage) finalUsage = chunk.usage;
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
if (finalUsage) {
|
||||
totalPromptTokens += finalUsage.prompt_tokens ?? 0;
|
||||
totalCompletionTokens += finalUsage.completion_tokens ?? 0;
|
||||
}
|
||||
|
||||
send({ type: "usage", prompt_tokens: totalPromptTokens, completion_tokens: totalCompletionTokens });
|
||||
send({ type: "done" });
|
||||
controller.close();
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Erreur inconnue";
|
||||
send({ type: "error", message: msg });
|
||||
controller.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { LayoutGrid, Camera, FileDown, Settings, Package, PackageSearch, BarChart2, TrendingUp, Trophy, Megaphone, PackageMinus, ShoppingCart, LogOut, User as UserIcon, Loader2, ChevronRight, ChevronLeft, MessageSquareCode } from "lucide-react";
|
||||
import { LayoutGrid, Camera, FileDown, Settings, Package, PackageSearch, BarChart2, TrendingUp, Trophy, Megaphone, PackageMinus, ShoppingCart, LogOut, User as UserIcon, Loader2, ChevronRight, ChevronLeft } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -19,7 +19,6 @@ const NAV_ITEMS = [
|
||||
{ icon: ShoppingCart, label: "Commandes auto", href: "/commandes-auto" },
|
||||
{ icon: Camera, label: "Snapshots", href: "/snapshots" },
|
||||
{ icon: FileDown, label: "Exports", href: "/exports", adminOnly: true },
|
||||
{ icon: MessageSquareCode, label: "AI Chat Admin", href: "/admin/ai-chat", adminOnly: true },
|
||||
{ icon: Settings, label: "Paramètres", href: "/settings", adminOnly: true },
|
||||
];
|
||||
|
||||
|
||||
@@ -220,6 +220,56 @@ export const apiKeys = pgTable("api_keys", {
|
||||
revokedAt: timestamp("revoked_at"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Paramétrage et suivi de la synchronisation nocturne, un enregistrement par
|
||||
* fournisseur.
|
||||
*
|
||||
* Deux sources aux coûts très différents, donc deux cadences distinctes :
|
||||
* l'instantané SQL prend une minute au pire, l'extraction Qlik jusqu'à huit —
|
||||
* et le serveur Qlik abandonne quand on le sollicite trop. D'où `actifSql` et
|
||||
* `actifQlik` séparés, et deux dates de dernier passage.
|
||||
*
|
||||
* L'ordre de passage se déduit de `dernier*At` (le plus ancien d'abord) : la
|
||||
* nuit suivante reprend donc naturellement là où la précédente s'est arrêtée,
|
||||
* et repart d'elle-même pour un nouveau tour quand tout a été traité. Aucun
|
||||
* curseur ni compteur de tour à maintenir.
|
||||
*/
|
||||
export const syncFournisseurs = pgTable("sync_fournisseurs", {
|
||||
codeFournisseur: varchar("code_fournisseur", { length: 20 }).primaryKey(),
|
||||
nomFournisseur: varchar("nom_fournisseur", { length: 255 }),
|
||||
/** Inclus dans la rotation de l'instantané SQL. */
|
||||
actifSql: boolean("actif_sql").default(true).notNull(),
|
||||
/** Inclus dans la rotation Qlik (beaucoup plus coûteuse). */
|
||||
actifQlik: boolean("actif_qlik").default(true).notNull(),
|
||||
/**
|
||||
* Renseigné quand le planificateur a désactivé le fournisseur de lui-même —
|
||||
* typiquement « aucun article ». Évite de réessayer chaque nuit un
|
||||
* fournisseur vide, tout en gardant la raison visible pour le réactiver.
|
||||
*/
|
||||
desactiveMotif: text("desactive_motif"),
|
||||
|
||||
dernierSqlAt: timestamp("dernier_sql_at"),
|
||||
/** 'succes' | 'echec' | 'vide' */
|
||||
dernierSqlStatut: varchar("dernier_sql_statut", { length: 20 }),
|
||||
dernierSqlLignes: integer("dernier_sql_lignes"),
|
||||
dernierSqlErreur: text("dernier_sql_erreur"),
|
||||
dernierSqlMs: integer("dernier_sql_ms"),
|
||||
|
||||
dernierQlikAt: timestamp("dernier_qlik_at"),
|
||||
dernierQlikStatut: varchar("dernier_qlik_statut", { length: 20 }),
|
||||
dernierQlikCodes: integer("dernier_qlik_codes"),
|
||||
dernierQlikErreur: text("dernier_qlik_erreur"),
|
||||
dernierQlikMs: integer("dernier_qlik_ms"),
|
||||
|
||||
updatedAt: timestamp("updated_at").defaultNow(),
|
||||
}, (table) => {
|
||||
return [
|
||||
// Index de file d'attente : « le plus ancien d'abord », par source.
|
||||
index("idx_sync_fou_sql").on(table.actifSql, table.dernierSqlAt),
|
||||
index("idx_sync_fou_qlik").on(table.actifQlik, table.dernierQlikAt),
|
||||
];
|
||||
});
|
||||
|
||||
/** AI Context rules per supplier (Epic: AI Context) */
|
||||
export const aiSupplierContext = pgTable("ai_supplier_context", {
|
||||
/** Supplier code serving as the primary key */
|
||||
|
||||
Reference in new issue
Block a user