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.

fix(sales): stop salesOrders orderTotal collapsing equal line amounts (#1380)

Naveen Kashyap890984d8d91a
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 607ed6a8d2..cc346f8f9a 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -953,3 +953,13 @@ canvas hosting Radix popovers/selects.
**Rule:** Any PostgREST read that can exceed 1000 rows must paginate — `fetchAllFromTable`/`fetchAllRecords` from `@carbon/database` in app code, `fetchAll` from `supabase/functions/lib/fetch-all.ts` in edge functions — and must carry a stable `.order()` so pages don't shift between requests. Do not conclude "it returns everything" from a local run; check the row count against `max_rows` in `config.toml` instead.
**Applies to:** `packages/database/supabase/functions/mrp/index.ts`, `packages/database/supabase/functions/lib/fetch-all.ts`, `packages/database/supabase/config.toml`, any `.select()` in `packages/database/supabase/functions/**` or `apps/erp/app/modules/**`.
+
+## `sum(DISTINCT expr)` is not a fan-out dedup — it collapses equal values from different rows
+
+**Context:** The `salesOrders` view aggregated line totals in a lateral that also LEFT JOINs `job` (one line → many jobs), and used `sum(DISTINCT <line total>)` to cancel the join fan-out. An order with two different lines that compute to the same amount (e.g. two items at 10 × $50 each) counted that amount once, understating the total on the list page, the dashboard KPI chart, and the sales funnel — while the detail page and PDF (app-side plain sums) were correct. Dozens of real orders were affected.
+
+**Problem:** `DISTINCT` inside an aggregate dedupes by VALUE, not by source row. It cancels duplication from a join fan-out only as long as no two *distinct* rows produce the same value — for money amounts (repeated items, same qty × price) that collision is routine. The failure is silent and data-dependent: the view verifies "byte-identical" against its predecessor because the predecessor had the same bug.
+
+**Rule:** Never use `sum(DISTINCT ...)`/`count(DISTINCT ...)`-style aggregates to undo join fan-out. Compute the aggregate in its own lateral/subquery over just the table being summed (no fan-out ⇒ plain `sum()`), and keep the fanned join in a separate lateral for the aggregates that need it. When reviewing a view, treat any `agg(DISTINCT ...)` over a joined row set as a probable value-collapse bug. Fixed in `20260812211507_fix-sales-order-total-duplicate-line-amounts.sql`.
+
+**Applies to:** `packages/database/supabase/migrations/` views aggregating over joins (`salesOrders`, `purchaseOrders`, quotes/invoices list views); any SQL review touching `sum(DISTINCT`.
diff --git a/packages/database/supabase/migrations/20260812211507_fix-sales-order-total-duplicate-line-amounts.sql b/packages/database/supabase/migrations/20260812211507_fix-sales-order-total-duplicate-line-amounts.sql
new file mode 100644
index 0000000000..0ed180b8ea
--- /dev/null
+++ b/packages/database/supabase/migrations/20260812211507_fix-sales-order-total-duplicate-line-amounts.sql
@@ -0,0 +1,106 @@
+-- Fix "salesOrders"."orderTotal" dropping lines whose computed totals are equal.
+--
+-- The lateral that aggregates line data also LEFT JOINs "job" (a line can have
+-- several jobs), so every line-level aggregate in it has to survive that
+-- fan-out. "orderTotal" did so with sum(DISTINCT <line total>) — but DISTINCT
+-- dedupes by VALUE, not by line: an order with two different lines that happen
+-- to compute to the same amount (e.g. two items at 10 × $50 each) counts
+-- that amount ONCE. The list page, dashboard KPI chart, and sales funnel all
+-- read this column, so they understated such orders while the order detail
+-- page and PDF (which sum the lines in the app) showed the correct total.
+--
+-- Fix: compute the total in its own lateral over "salesOrderLine" alone — no
+-- job fan-out, so a plain sum() is correct. Everything else is forked verbatim
+-- from 20260807011742_lateralize-order-list-views.sql (the newest definition).
+-- The extra lateral is one index scan on "salesOrderLine"("salesOrderId") per
+-- output row, evaluated per page row like the existing one (see the
+-- parameterization notes in 20260807011742).
+--
+-- Semantics preserved for orders with no lines: sum() over an empty set is
+-- NULL, so "orderTotal" stays NULL there, exactly as before.
+
+CREATE OR REPLACE VIEW "salesOrders" WITH (security_invoker = true) AS
+ SELECT s.id,
+ s."salesOrderId",
+ s."revisionId",
+ s.status,
+ s."orderDate",
+ s."currencyCode",
+ s."customerId",
+ s."customerLocationId",
+ s."customerContactId",
+ s."customerReference",
+ s.assignee,
+ s."companyId",
+ s."closedAt",
+ s."closedBy",
+ s."customFields",
+ s."createdAt",
+ s."createdBy",
+ s."updatedAt",
+ s."updatedBy",
+ s."locationId",
+ s."exchangeRate",
+ s."exchangeRateUpdatedAt",
+ s."externalNotes",
+ s."internalNotes",
+ s."salesPersonId",
+ s."sentCompleteDate",
+ s."opportunityId",
+ s."completedDate",
+ s."customerEngineeringContactId",
+ CASE
+ WHEN (s.status <> ALL (ARRAY['Closed'::"salesOrderStatus", 'Cancelled'::"salesOrderStatus"])) AND (EXISTS ( SELECT 1
+ FROM "salesOrderLine" sol
+ WHERE sol."salesOrderId" = s.id AND sol."methodType" = 'Make to Order'::"methodType" AND COALESCE(( SELECT sum(j."quantityComplete") AS sum
+ FROM job j
+ WHERE j."salesOrderLineId" = sol.id AND j."salesOrderId" = sol."salesOrderId"), 0::numeric) < sol."saleQuantity")) THEN 'In Progress'::"salesOrderStatus"
+ ELSE s.status
+ END AS "displayStatus",
+ sl."thumbnailPath",
+ sl."itemType",
+ tot."orderTotal" + COALESCE(ss."shippingCost", 0::numeric) AS "orderTotal",
+ sl.jobs,
+ sl.lines,
+ st.name AS "shippingTermName",
+ sp."paymentTermId",
+ ss."shippingMethodId",
+ ss."receiptRequestedDate",
+ ss."receiptPromisedDate",
+ ss."dropShipment",
+ ss."shippingCost",
+ ss.incoterm,
+ ss."incotermLocation",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'salesOrder'::text AND eim."entityId" = s.id) AS "externalId"
+ FROM "salesOrder" s
+ LEFT JOIN LATERAL ( SELECT
+ min(
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ min(i.type) AS "itemType",
+ array_agg(
+ CASE
+ WHEN j.id IS NOT NULL THEN json_build_object('id', j.id, 'jobId', j."jobId", 'status', j.status, 'dueDate', j."dueDate", 'productionQuantity', j."productionQuantity", 'quantityComplete', j."quantityComplete", 'quantityShipped', j."quantityShipped", 'quantity', j.quantity, 'scrapQuantity', j."scrapQuantity", 'salesOrderLineId', sol.id, 'assignee', j.assignee)
+ ELSE NULL::json
+ END ORDER BY sol.id, j.id) FILTER (WHERE j.id IS NOT NULL) AS jobs,
+ array_agg(json_build_object('id', sol.id, 'methodType', sol."methodType", 'saleQuantity', sol."saleQuantity") ORDER BY sol.id) AS lines
+ FROM "salesOrderLine" sol
+ LEFT JOIN item i ON i.id = sol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN job j ON j."salesOrderId" = sol."salesOrderId" AND j."salesOrderLineId" = sol.id
+ WHERE sol."salesOrderId" = s.id) sl ON true
+ LEFT JOIN LATERAL ( SELECT
+ sum((1::numeric + COALESCE(sol."taxPercent", 0::numeric)) * (COALESCE(sol."saleQuantity", 0::numeric) * COALESCE(sol."unitPrice", 0::numeric) + COALESCE(sol."shippingCost", 0::numeric) + COALESCE(sol."addOnCost", 0::numeric)) + COALESCE(sol."nonTaxableAddOnCost", 0::numeric)) AS "orderTotal"
+ FROM "salesOrderLine" sol
+ WHERE sol."salesOrderId" = s.id) tot ON true
+ LEFT JOIN "salesOrderShipment" ss ON ss.id = s.id
+ LEFT JOIN "shippingTerm" st ON st.id = ss."shippingTermId"
+ LEFT JOIN "salesOrderPayment" sp ON sp.id = s.id;