Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

comment fixes

Gaurav Bhatt6f223ab60477
diff --git a/packages/database/supabase/migrations/20260604120000_invoice-total-tax-interceptors.sql b/packages/database/supabase/migrations/20260604120000_invoice-total-tax-interceptors.sql
deleted file mode 100644
index 4254a04b8f..0000000000
--- a/packages/database/supabase/migrations/20260604120000_invoice-total-tax-interceptors.sql
+++ /dev/null
@@ -1,192 +0,0 @@
--- =============================================================================
--- Keep invoice "totalTax" header columns in sync with their line items.
---
--- Root cause of the "totalTax: 0" bug: salesInvoice."totalTax" and
--- purchaseInvoice."totalTax" are stored denormalized columns written to 0 at
--- invoice creation (convert edge function: convert/index.ts:726/:1315 sales,
--- :320 purchase) and never recomputed. The per-line tax is the real source of
--- truth, so the API (salesInvoices/purchaseInvoices views -> *.totalTax) and the
--- Xero sync (invoice.ts TaxTotal / bill.ts TotalTax) both report 0.
---
--- Fix: AFTER interceptors on each *InvoiceLine table that recompute the parent
--- invoice's "totalTax" on insert/update/delete, plus one-time backfills.
--- Idempotent: safe to re-run.
--- =============================================================================
-
-
--- #############################################################################
--- SALES INVOICE
--- #############################################################################
-
--- Taxable base per line matches the salesInvoices view's "invoiceTotal":
--- taxPercent * (quantity*unitPrice + shippingCost + addOnCost)
--- (raw / document currency, to match the stored "subtotal"; nonTaxableAddOnCost
--- is excluded, and shipment-level shipping is untaxed -> tax depends only on
--- salesInvoiceLine rows). salesInvoiceLine."invoiceId" is the FK to
--- salesInvoice."id". On DELETE the dispatcher passes the OLD row as p_new, so
--- p_new->>'invoiceId' is populated for INSERT, UPDATE, and DELETE.
-
-CREATE OR REPLACE FUNCTION sync_recompute_sales_invoice_tax(
- p_table TEXT,
- p_operation TEXT,
- p_new JSONB,
- p_old JSONB
-)
-RETURNS VOID
-LANGUAGE plpgsql
-SECURITY DEFINER
-SET search_path = public
-AS $$
-DECLARE
- v_invoice_id TEXT := p_new->>'invoiceId';
- v_old_invoice_id TEXT;
-BEGIN
- IF v_invoice_id IS NOT NULL THEN
- UPDATE "salesInvoice" si
- SET "totalTax" = COALESCE((
- SELECT SUM(
- COALESCE(sil."taxPercent", 0) * (
- COALESCE(sil."quantity", 0) * COALESCE(sil."unitPrice", 0)
- + COALESCE(sil."shippingCost", 0)
- + COALESCE(sil."addOnCost", 0)
- )
- )
- FROM "salesInvoiceLine" sil
- WHERE sil."invoiceId" = v_invoice_id
- ), 0)
- WHERE si."id" = v_invoice_id;
- END IF;
-
- -- Defensive: if a line is re-pointed to a different invoice on UPDATE,
- -- refresh the previous invoice's total too.
- IF p_operation = 'UPDATE' THEN
- v_old_invoice_id := p_old->>'invoiceId';
- IF v_old_invoice_id IS NOT NULL AND v_old_invoice_id IS DISTINCT FROM v_invoice_id THEN
- UPDATE "salesInvoice" si
- SET "totalTax" = COALESCE((
- SELECT SUM(
- COALESCE(sil."taxPercent", 0) * (
- COALESCE(sil."quantity", 0) * COALESCE(sil."unitPrice", 0)
- + COALESCE(sil."shippingCost", 0)
- + COALESCE(sil."addOnCost", 0)
- )
- )
- FROM "salesInvoiceLine" sil
- WHERE sil."invoiceId" = v_old_invoice_id
- ), 0)
- WHERE si."id" = v_old_invoice_id;
- END IF;
- END IF;
-END;
-$$;
-
--- Register the AFTER interceptor on salesInvoiceLine. The existing registration
--- (20260218) passes only an empty BEFORE list; the async statement-level audit
--- triggers are re-attached unconditionally by attach_event_trigger.
-SELECT attach_event_trigger(
- 'salesInvoiceLine',
- ARRAY[]::TEXT[],
- ARRAY['sync_recompute_sales_invoice_tax']::TEXT[]
-);
-
--- Backfill existing invoices. The IS DISTINCT FROM guard skips already-correct
--- rows, avoiding no-op writes.
-UPDATE "salesInvoice" si
-SET "totalTax" = t."computedTax"
-FROM (
- SELECT
- inv."id" AS "invoiceId",
- COALESCE(SUM(
- COALESCE(sil."taxPercent", 0) * (
- COALESCE(sil."quantity", 0) * COALESCE(sil."unitPrice", 0)
- + COALESCE(sil."shippingCost", 0)
- + COALESCE(sil."addOnCost", 0)
- )
- ), 0) AS "computedTax"
- FROM "salesInvoice" inv
- LEFT JOIN "salesInvoiceLine" sil ON sil."invoiceId" = inv."id"
- GROUP BY inv."id"
-) t
-WHERE si."id" = t."invoiceId"
- AND si."totalTax" IS DISTINCT FROM t."computedTax";
-
-
--- #############################################################################
--- PURCHASE INVOICE
--- #############################################################################
-
--- purchaseInvoiceLine."taxAmount" is a GENERATED column (= supplierTaxAmount *
--- exchangeRate, base currency) that the purchaseInvoices view already sums into
--- "orderTotal", so the header total is simply SUM("taxAmount") -- consistent
--- with the stored "subtotal" (also base currency).
-
-CREATE OR REPLACE FUNCTION sync_recompute_purchase_invoice_tax(
- p_table TEXT,
- p_operation TEXT,
- p_new JSONB,
- p_old JSONB
-)
-RETURNS VOID
-LANGUAGE plpgsql
-SECURITY DEFINER
-SET search_path = public
-AS $$
-DECLARE
- v_invoice_id TEXT := p_new->>'invoiceId';
- v_old_invoice_id TEXT;
-BEGIN
- IF v_invoice_id IS NOT NULL THEN
- UPDATE "purchaseInvoice" pi
- SET "totalTax" = COALESCE((
- SELECT SUM(COALESCE(pil."taxAmount", 0))
- FROM "purchaseInvoiceLine" pil
- WHERE pil."invoiceId" = v_invoice_id
- ), 0)
- WHERE pi."id" = v_invoice_id;
- END IF;
-
- -- Defensive: if a line is re-pointed to a different invoice on UPDATE,
- -- refresh the previous invoice's total too.
- IF p_operation = 'UPDATE' THEN
- v_old_invoice_id := p_old->>'invoiceId';
- IF v_old_invoice_id IS NOT NULL AND v_old_invoice_id IS DISTINCT FROM v_invoice_id THEN
- UPDATE "purchaseInvoice" pi
- SET "totalTax" = COALESCE((
- SELECT SUM(COALESCE(pil."taxAmount", 0))
- FROM "purchaseInvoiceLine" pil
- WHERE pil."invoiceId" = v_old_invoice_id
- ), 0)
- WHERE pi."id" = v_old_invoice_id;
- END IF;
- END IF;
-END;
-$$;
-
--- Register the AFTER interceptor on purchaseInvoiceLine.
--- IMPORTANT: purchaseInvoiceLine already has an AFTER interceptor
--- (sync_purchase_invoice_line_price_change). 20260416 deliberately moved it
--- BEFORE -> AFTER because the generated STORED column "unitPrice" is NULL in
--- BEFORE triggers (which crashed it on the NOT NULL price-change insert). It
--- must STAY in the AFTER list -- moving it back to BEFORE would reintroduce that
--- crash. Our tax interceptor is also AFTER (it reads the finalized generated
--- "taxAmount" column), so both go in the AFTER array.
-SELECT attach_event_trigger(
- 'purchaseInvoiceLine',
- ARRAY[]::TEXT[],
- ARRAY['sync_purchase_invoice_line_price_change', 'sync_recompute_purchase_invoice_tax']::TEXT[]
-);
-
--- Backfill. ROUND to 2dp: purchaseInvoice."totalTax" is NUMERIC(10,2) while
--- "taxAmount" is NUMERIC(10,5), so rounding keeps the guard idempotent on re-run.
-UPDATE "purchaseInvoice" pi
-SET "totalTax" = ROUND(t."computedTax", 2)
-FROM (
- SELECT
- inv."id" AS "invoiceId",
- COALESCE(SUM(COALESCE(pil."taxAmount", 0)), 0) AS "computedTax"
- FROM "purchaseInvoice" inv
- LEFT JOIN "purchaseInvoiceLine" pil ON pil."invoiceId" = inv."id"
- GROUP BY inv."id"
-) t
-WHERE pi."id" = t."invoiceId"
- AND pi."totalTax" IS DISTINCT FROM ROUND(t."computedTax", 2);
diff --git a/packages/database/supabase/migrations/20260604120000_invoice-totals-computed-in-views.sql b/packages/database/supabase/migrations/20260604120000_invoice-totals-computed-in-views.sql
new file mode 100644
index 0000000000..a50eee4139
--- /dev/null
+++ b/packages/database/supabase/migrations/20260604120000_invoice-totals-computed-in-views.sql
@@ -0,0 +1,193 @@
+-- =============================================================================
+-- Compute invoice totals (subtotal, totalTax, totalAmount) in the invoice views
+-- instead of relying on the stored header columns, which are set once at
+-- creation and never updated -- so the API/MCP (which read these views) return
+-- the correct, live values derived from the line items.
+--
+-- Replaces the earlier trigger/interceptor approach: the totals are now computed
+-- on read in `salesInvoices` / `purchaseInvoices`. The backend getSalesInvoice/
+-- getSalesInvoices (and purchase equivalents) already select from these views.
+--
+-- The stored salesInvoice/purchaseInvoice.{subtotal,totalTax,totalAmount} columns
+-- are left in place (still read by the Xero sync) but are no longer the source
+-- of truth for the API. Definitions (document currency, matching the existing
+-- invoiceTotal/orderTotal): nonTaxableAddOnCost is untaxed; shipment-level
+-- shipping is untaxed and added on top.
+-- subtotal = Σ (qty*unitPrice + addOnCost + nonTaxableAddOnCost + lineShipping)
+-- totalTax = Σ taxPercent * (qty*unitPrice + addOnCost + lineShipping)
+-- totalAmount= subtotal + totalTax + shipmentShipping (== invoiceTotal)
+-- =============================================================================
+
+
+-- -----------------------------------------------------------------------------
+-- Unwind the interceptor approach (replaced by view computation).
+-- -----------------------------------------------------------------------------
+
+-- salesInvoiceLine: clear our after-interceptor (no before/after interceptors).
+SELECT attach_event_trigger('salesInvoiceLine', ARRAY[]::TEXT[], ARRAY[]::TEXT[]);
+DROP FUNCTION IF EXISTS sync_recompute_sales_invoice_tax(TEXT, TEXT, JSONB, JSONB);
+
+-- purchaseInvoiceLine: restore just the price-change AFTER interceptor (drop ours).
+SELECT attach_event_trigger(
+ 'purchaseInvoiceLine',
+ ARRAY[]::TEXT[],
+ ARRAY['sync_purchase_invoice_line_price_change']::TEXT[]
+);
+DROP FUNCTION IF EXISTS sync_recompute_purchase_invoice_tax(TEXT, TEXT, JSONB, JSONB);
+
+
+-- -----------------------------------------------------------------------------
+-- salesInvoices: compute subtotal / totalTax / totalAmount from the lines.
+-- (si.* expanded to an explicit list so the computed columns replace the stored
+-- ones. plain SUM, not SUM(DISTINCT) -- DISTINCT dropped identical line amounts.)
+-- -----------------------------------------------------------------------------
+
+CREATE OR REPLACE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ si."id",
+ si."invoiceId",
+ si."status",
+ si."customerId",
+ si."customerReference",
+ si."invoiceCustomerId",
+ si."invoiceCustomerLocationId",
+ si."invoiceCustomerContactId",
+ si."paymentTermId",
+ si."postingDate",
+ si."dateIssued",
+ si."dateDue",
+ si."datePaid",
+ si."locationId",
+ si."currencyCode",
+ COALESCE(sil."subtotal", 0) AS "subtotal",
+ si."totalDiscount",
+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "totalAmount",
+ COALESCE(sil."totalTax", 0) AS "totalTax",
+ si."balance",
+ si."exchangeRate",
+ si."exchangeRateUpdatedAt",
+ si."opportunityId",
+ si."shipmentId",
+ si."assignee",
+ si."companyId",
+ si."customFields",
+ si."internalNotes",
+ si."externalNotes",
+ si."tags",
+ si."createdAt",
+ si."createdBy",
+ si."updatedAt",
+ si."updatedBy",
+ sil."thumbnailPath",
+ sil."itemType",
+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "invoiceTotal",
+ sil."lines"
+ FROM "salesInvoice" si
+ LEFT JOIN (
+ SELECT
+ sil."invoiceId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(
+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)
+ + COALESCE(sil."addOnCost", 0)
+ + COALESCE(sil."nonTaxableAddOnCost", 0)
+ + COALESCE(sil."shippingCost", 0)
+ ) AS "subtotal",
+ SUM(
+ COALESCE(sil."taxPercent", 0) * (
+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)
+ + COALESCE(sil."addOnCost", 0)
+ + COALESCE(sil."shippingCost", 0)
+ )
+ ) AS "totalTax",
+ MIN(i."type") AS "itemType",
+ ARRAY_AGG(
+ json_build_object(
+ 'id', sil.id,
+ 'invoiceLineType', sil."invoiceLineType",
+ 'quantity', sil."quantity",
+ 'unitPrice', sil."unitPrice",
+ 'itemId', sil."itemId"
+ )
+ ) AS "lines"
+ FROM "salesInvoiceLine" sil
+ LEFT JOIN "item" i
+ ON i."id" = sil."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY sil."invoiceId"
+ ) sil ON sil."invoiceId" = si."id"
+ JOIN "salesInvoiceShipment" ss ON ss."id" = si."id";
+
+
+-- -----------------------------------------------------------------------------
+-- purchaseInvoices: compute subtotal / totalTax / totalAmount from the lines.
+-- purchaseInvoiceLine."taxAmount" is the generated per-line tax (base currency).
+-- -----------------------------------------------------------------------------
+
+CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ pi."id",
+ pi."invoiceId",
+ pi."supplierId",
+ pi."invoiceSupplierId",
+ pi."supplierInteractionId",
+ pi."supplierReference",
+ pi."invoiceSupplierContactId",
+ pi."invoiceSupplierLocationId",
+ pi."locationId",
+ pi."postingDate",
+ pi."dateIssued",
+ pi."dateDue",
+ pi."datePaid",
+ pi."paymentTermId",
+ pi."currencyCode",
+ pi."exchangeRate",
+ pi."exchangeRateUpdatedAt",
+ COALESCE(pl."subtotal", 0) AS "subtotal",
+ pi."totalDiscount",
+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "totalAmount",
+ COALESCE(pl."totalTax", 0) AS "totalTax",
+ pi."balance",
+ pi."assignee",
+ pi."createdBy",
+ pi."createdAt",
+ pi."updatedBy",
+ pi."updatedAt",
+ pi."internalNotes",
+ pi."customFields",
+ pi."companyId",
+ pl."thumbnailPath",
+ pl."itemType",
+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",
+ CASE
+ WHEN pi."dateDue" < CURRENT_DATE AND pi."datePaid" IS NULL THEN 'Overdue'
+ ELSE pi."status"
+ END AS status,
+ pt."name" AS "paymentTermName"
+ FROM "purchaseInvoice" pi
+ LEFT JOIN (
+ SELECT
+ pol."invoiceId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(
+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)
+ ) AS "subtotal",
+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",
+ SUM(
+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)
+ ) AS "orderTotal",
+ MIN(i."type") AS "itemType"
+ FROM "purchaseInvoiceLine" pol
+ LEFT JOIN "item" i
+ ON i."id" = pol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY pol."invoiceId"
+ ) pl ON pl."invoiceId" = pi."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"
+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id";