diff --git a/src/features/grid/api/get-product-rows.ts b/src/features/grid/api/get-product-rows.ts index e1556de..23bcc68 100644 --- a/src/features/grid/api/get-product-rows.ts +++ b/src/features/grid/api/get-product-rows.ts @@ -17,16 +17,64 @@ interface GetProductRowsInput { } export async function getProductRows(input: GetProductRowsInput): Promise { - // MODEL DIAGNOSTIC (Clean version) + const { codeFournisseur, magasin = "TOTAL", filters } = input; + console.log(`\n>>> [getProductRows] RECEIVED CALL for supplier: ${codeFournisseur}, magasin: ${magasin}`); + + try { + // Self-healing: Ensure codeGammeInit column exists and is populated + if (!isSchemaInitialized) { + try { + await db.execute(sql` + ALTER TABLE ventes_produits + ADD COLUMN IF NOT EXISTS code_gamme_init VARCHAR(20) + `); + await db.execute(sql` + UPDATE ventes_produits + SET code_gamme_init = code_gamme + WHERE code_gamme_init IS NULL + `); + isSchemaInitialized = true; + console.log("[Schema] codeGammeInit initialized successfully."); + } catch (err) { + console.error("[Schema] Failed to initialize codeGammeInit:", err); + } + } + + const now = new Date(); + const allowedPeriods = new Set(); + for (let i = 12; i >= 0; i--) { + const d = new Date(now.getFullYear(), now.getMonth() - i, 1); + allowedPeriods.add(`${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}`); + } + + const conditions = [ + eq(ventesProduits.codeFournisseur, codeFournisseur), + ne(ventesProduits.periode, "TOTAL"), + magasin !== "TOTAL" ? eq(ventesProduits.magasin, magasin) : ne(ventesProduits.magasin, "TOTAL"), + ]; + + if (filters?.code3) { + conditions.push(eq(ventesProduits.code3, filters.code3)); + } else if (filters?.code2) { + conditions.push(like(ventesProduits.code3, `${filters.code2}%`)); + } else if (filters?.code1) { + conditions.push(like(ventesProduits.code3, `${filters.code1}%`)); + } + + const rows = await db + .select() + .from(ventesProduits) + .where(and(...conditions)); + console.log(`[getProductRows] Fetching for ${codeFournisseur} (${magasin}). Found ${rows.length} rows.`); + const productMap = new Map(); const storeParticipationMap = new Map>>(); // codein -> magasin -> Set of periods for (const row of rows) { const { codein, magasin, periode } = row; const isInPeriod = allowedPeriods.has(periode); - // Suivi de la participation par magasin (seulement si dans la période et pas TOTAL) if (isInPeriod && magasin !== "TOTAL") { if (!storeParticipationMap.has(codein)) storeParticipationMap.set(codein, new Map()); const productStores = storeParticipationMap.get(codein)!; @@ -36,20 +84,13 @@ export async function getProductRows(input: GetProductRowsInput): Promise = { - "20": "LIQUIDES", - "30": "ÉPICERIE", - "40": "DPH", - "50": "BAZAR", - "60": "TEXTILE", - "70": "FRAIS", - // Rayons + "20": "LIQUIDES", "30": "ÉPICERIE", "40": "DPH", "50": "BAZAR", "60": "TEXTILE", "70": "FRAIS", "2001": "EAUX", "2002": "JUS DE FRUITS", "2003": "SODAS / BOUILLONS", "2004": "BIERES", "2005": "VINS", "2006": "CIDRES", "2007": "APERITIFS", "2008": "ALCOOLS", "3001": "ÉPICERIE SALÉE", "3002": "ÉPICERIE SUCRÉE", "3003": "PETIT DÉJEUNER", "3004": "CONSERVES", "3005": "PLAT CUISINES", "4001": "HYGIÈNE", "4002": "ENTRETIEN", "4003": "PARFUMERIE", @@ -85,7 +126,6 @@ export async function getProductRows(input: GetProductRowsInput): Promise= 3 mois de vente) for (const [codein, product] of productMap.entries()) { const productStores = storeParticipationMap.get(codein); if (productStores) { @@ -114,9 +153,7 @@ export async function getProductRows(input: GetProductRowsInput): Promise 0) { - return query.where(and(...conditions)).orderBy(desc(sessionSnapshots.createdAt)); + if (!userId || isNaN(userId)) { + console.warn("[getSnapshots] Unauthenticated access attempt"); + return []; } - return query.orderBy(desc(sessionSnapshots.createdAt)); + const conditions = [eq(sessionSnapshots.userId, userId)]; + if (type) conditions.push(eq(sessionSnapshots.type, type)); + + return await db.select() + .from(sessionSnapshots) + .where(and(...conditions)) + .orderBy(desc(sessionSnapshots.createdAt)); } catch (err: any) { const msg = (err?.message || String(err)).split("\n")[0]; console.error(`[getSnapshots] ERROR (type=${type}):`, msg, err);