From 172400600e5ce00f2950128b1fff2a49b8cf5c63 Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Sun, 19 Apr 2026 17:15:27 +0000 Subject: [PATCH] Changes Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com> --- src/routes/settings.import.tsx | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/routes/settings.import.tsx b/src/routes/settings.import.tsx index 11dad04..2a40b3b 100644 --- a/src/routes/settings.import.tsx +++ b/src/routes/settings.import.tsx @@ -884,31 +884,49 @@ function ImportPage() { if (extId) ctx.caseByExt.set(String(extId), data.id); return data.id; }; - const ensurePreInvoicedInvoice = async (clientId: string, caseId: string): Promise => { - const cached = placeholderInvoiceByClient.get(clientId); + // Look up an existing invoice by number for this client, or create a + // new "sent" invoice with that exact number to bucket imported items. + const invoiceByClientAndNumber = new Map(); // `${clientId}::${number}` -> invoiceId + const ensureNamedInvoice = async ( + clientId: string, + caseId: string, + invoiceNumber: string, + ): Promise => { + const cacheKey = `${clientId}::${invoiceNumber}`; + const cached = invoiceByClientAndNumber.get(cacheKey); if (cached) return cached; - const invNumber = `IMPORT-PREBILLED-${Date.now()}-${Math.floor(Math.random() * 10000)}`; + // First try existing invoice with this number for this client + const { data: existing } = await supabase + .from("invoices") + .select("id") + .eq("client_id", clientId) + .eq("invoice_number", invoiceNumber) + .maybeSingle(); + if (existing?.id) { + invoiceByClientAndNumber.set(cacheKey, existing.id); + return existing.id; + } const { data, error } = await supabase .from("invoices") .insert({ client_id: clientId, case_id: caseId, - invoice_number: invNumber, - status: "void", + invoice_number: invoiceNumber, + status: "sent", issue_date: new Date().toISOString().slice(0, 10), subtotal: 0, tax: 0, total: 0, - notes: "Placeholder invoice for items imported as already invoiced.", + notes: "Auto-created from import to hold items linked to this invoice number.", created_by: user.id, } as any) .select("id") .single(); if (error || !data) { - errors.push(`Auto-create placeholder invoice: ${error?.message ?? "unknown"}`); + errors.push(`Auto-create invoice "${invoiceNumber}": ${error?.message ?? "unknown"}`); return null; } - placeholderInvoiceByClient.set(clientId, data.id); + invoiceByClientAndNumber.set(cacheKey, data.id); return data.id; };