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): base sales-order paid amount on applied settlement principal (#1619)

Brad Barbin4bbb4ac1a164
diff --git a/.ai/lessons.md b/.ai/lessons.md
index f6084f6fb8..7ab35bd9c5 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -6,6 +6,16 @@ Format: `Context → Problem → Rule → Applies to`
---
+## Sales-order Paid Amount uses invoice-target principal
+
+**Context:** Summarizing linked sales-invoice payments on a sales order.
+
+**Problem:** `invoiceSettlement.sourceAmount` is principal in the payment funding source's currency, so it does not represent the amount applied to the invoice. Using it for the order's Paid Amount disagrees with the invoice Payments panel and can mix currency semantics.
+
+**Rule:** Sales-order Paid Amount sums posted payment `appliedAmount` (company base) per invoice, then converts it with that invoice's exchange rate into the matching order currency. Do not use `sourceAmount` for this summary. There is no legacy `baseStatus === "Paid"` fallback that counts the full invoice total — every payment flows through `invoiceSettlement`, so a fully-paid invoice's settlements already sum to its total.
+
+**Applies to:** `getSalesOrderInvoicePaymentsByIds`, the sales-order loader's `invoiceSummary`, and any UI summarizing cash applied to invoice targets.
+
## ioredis retryStrategy returning null kills auto-recovery
**Context:** Making the Redis client (`@carbon/kv`) resilient to outages (issue #1076).
diff --git a/.ai/runs/2026-09-11-sales-order-paid-amount.md b/.ai/runs/2026-09-11-sales-order-paid-amount.md
new file mode 100644
index 0000000000..a29e5308c0
--- /dev/null
+++ b/.ai/runs/2026-09-11-sales-order-paid-amount.md
@@ -0,0 +1,25 @@
+# Bugfix run: Sales order paid amount
+
+- Date: 2026-09-11
+- Mode: fully-autonomous
+- Request: "we made another try recently to fix the paid amount on the sales invoice summary but it's still showing 0 and it should show the full amount"
+- Phase plan: root-cause [run] · instrument [skip — cause proven statically] · fix [run] · test [run — user-facing summary] · commit [skip — not requested]
+
+## Decisions
+
+- instrument: skip — the screenshots and invoice Payments panel prove that the summary should use settlement `appliedAmount`.
+- browser test: run if the local ERP stack is available after scoped automated gates.
+- commit: skip — the user did not request a commit.
+
+## Phase log
+
+- root-cause: HIGH — the recent sales-order summary reads payment-source `sourceAmount`, while the invoice Payments panel and requested summary semantics use invoice-target `appliedAmount`.
+- fix: replaced the payment-source amount with `appliedAmount` and converts that base principal into the invoice/order currency.
+- regression: RED proved the summary used `sourceAmount` (80) instead of `appliedAmount` (75); GREEN passed 3/3 focused invoice-summary tests.
+- gates: biome PASS with two pre-existing warnings in untouched lines · ERP typecheck PASS after local React Router type generation · sales module tests PASS (23/23).
+- browser test: SKIP — this workspace has no `.env.local`/`ERP_URL` and no local ERP process; the only running ERP processes belong to other workspaces.
+- commit: SKIP — not requested.
+
+## Outcome
+
+- READY
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 1240bd441e..5d88df62e3 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1776,9 +1776,7 @@ export async function getSalesOrderInvoicesByIds(
) {
return client
.from("salesInvoices")
- .select(
- "id, invoiceTotal, balance, status, baseStatus, currencyCode, exchangeRate"
- )
+ .select("id, invoiceTotal, balance, status, currencyCode, exchangeRate")
.in("id", invoiceIds);
}
@@ -1789,12 +1787,12 @@ export async function getSalesOrderInvoicePaymentsByIds(
) {
return fetchAllFromTable<{
targetSalesInvoiceId: string | null;
- sourceAmount: number | null;
+ appliedAmount: number;
payment: { status: string } | null;
}>(
client,
"invoiceSettlement",
- "targetSalesInvoiceId, sourceAmount, payment:payment!invoiceSettlement_paymentId_fkey!inner(status)",
+ "targetSalesInvoiceId, appliedAmount, payment:payment!invoiceSettlement_paymentId_fkey!inner(status)",
(query) =>
query
.eq("companyId", companyId)
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index c366b2df78..fb3ac94bca 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1283,8 +1283,8 @@
{"name":"sales_getSalesOrderCustomerDetails","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"141326b70f84","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderCustomers","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fc7a0345fc53","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderInvoiceLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"1ff852ae9154","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderInvoicePaymentsByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"8d4d69c4c240","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"59ff21b17d0d","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderInvoicePaymentsByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"397cd2bf218b","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"cd5bcdc964de","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"680c6abfc2c8","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"12480eaf2ca4","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLinesByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"12480eaf2ca4","injectAuth":"companyId","permission":"sales:view","paginates":false},
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts b/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts
index 5d8a31a2d3..972efed840 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts
@@ -102,7 +102,6 @@ beforeEach(() => {
invoiceTotal: 100,
balance: 0,
status: "Paid",
- baseStatus: "Submitted",
currencyCode: "USD",
exchangeRate: 1
}
@@ -113,7 +112,7 @@ beforeEach(() => {
data: [
{
targetSalesInvoiceId: "invoice-1",
- sourceAmount: 80,
+ appliedAmount: 75,
payment: { status: "Posted" }
}
],
@@ -131,7 +130,7 @@ beforeEach(() => {
});
describe("sales order invoice summary", () => {
- it("counts posted cash principal instead of discounts and write-offs", async () => {
+ it("counts applied payment principal instead of discounts and write-offs", async () => {
const result = await loader({
request: new Request("http://localhost/x/sales-order/order-1"),
params: { orderId: "order-1" },
@@ -140,41 +139,11 @@ describe("sales order invoice summary", () => {
expect(result.invoiceSummary).toEqual({
invoicedAmount: 100,
- paidAmount: 80,
+ paidAmount: 75,
currencyMismatchCount: 0
});
});
- it("preserves legacy invoices explicitly marked paid", async () => {
- vi.mocked(sales.getSalesOrderInvoicesByIds).mockResolvedValue({
- data: [
- {
- id: "invoice-1",
- invoiceTotal: 100,
- balance: 0,
- status: "Paid",
- baseStatus: "Paid",
- currencyCode: "USD",
- exchangeRate: 1
- }
- ],
- error: null
- } as never);
- getSalesOrderInvoicePaymentsByIds.mockResolvedValue({
- data: [],
- count: 0,
- error: null
- });
-
- const result = await loader({
- request: new Request("http://localhost/x/sales-order/order-1"),
- params: { orderId: "order-1" },
- context: {}
- } as unknown as Parameters<typeof loader>[0]);
-
- expect(result.invoiceSummary.paidAmount).toBe(100);
- });
-
it("returns invoice and payment totals in the order currency", async () => {
vi.mocked(sales.getSalesOrder).mockResolvedValue({
data: {
@@ -193,7 +162,6 @@ describe("sales order invoice summary", () => {
invoiceTotal: 100,
balance: 50,
status: "Partially Paid",
- baseStatus: "Submitted",
currencyCode: "EUR",
exchangeRate: 0.8
}
@@ -204,7 +172,7 @@ describe("sales order invoice summary", () => {
data: [
{
targetSalesInvoiceId: "invoice-1",
- sourceAmount: 40,
+ appliedAmount: 50,
payment: { status: "Posted" }
}
],
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
index 2b2ef393c8..f4881a376e 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
@@ -144,13 +144,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- const paidByInvoiceId = new Map<string, number>();
+ const paidBaseByInvoiceId = new Map<string, number>();
for (const payment of payments.data ?? []) {
if (!payment.targetSalesInvoiceId) continue;
- paidByInvoiceId.set(
+ paidBaseByInvoiceId.set(
payment.targetSalesInvoiceId,
- (paidByInvoiceId.get(payment.targetSalesInvoiceId) ?? 0) +
- (payment.sourceAmount ?? 0)
+ (paidBaseByInvoiceId.get(payment.targetSalesInvoiceId) ?? 0) +
+ payment.appliedAmount
);
}
@@ -176,13 +176,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
continue;
}
- const invoiceTotalInOrderCurrency =
- invoiceTotal * (invoice.exchangeRate ?? 1);
- invoicedAmount += invoiceTotalInOrderCurrency;
- if (invoice.baseStatus === "Paid") {
- paidAmount += invoiceTotalInOrderCurrency;
- } else if (invoice.id) {
- paidAmount += paidByInvoiceId.get(invoice.id) ?? 0;
+ invoicedAmount += invoiceTotal * (invoice.exchangeRate ?? 1);
+ if (invoice.id) {
+ paidAmount +=
+ (paidBaseByInvoiceId.get(invoice.id) ?? 0) *
+ (invoice.exchangeRate ?? 1);
}
}
}