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(invoicing): read legacy settlements that have no document principal (#1632)

Naveen Kashyap71eaa6f2e682
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 7ab35bd9c5..dd0add5f48 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1531,3 +1531,13 @@ full-screen ERP route.
**Rule:** Include a UI-only field's initial value in ValidatedForm defaults, and key stateful composers by the document/party/currency/direction identity whose data they hold. Verify the initial label and actual submitted fields in the browser.
**Applies to:** PaymentForm, PaymentApplyTable, and other forms using derived presentation choices.
+
+## A nullable column added by migration needs a reader that tolerates NULL
+
+**Context:** The accounting corrections release added `invoiceSettlement.sourceAmount` (document-currency principal) without backfilling rows written before it, and the migration comment explicitly declared legacy NULLs valid.
+
+**Problem:** The shared TypeScript reducer that computes an invoice's remaining balance and a payment's remaining funding threw "Settlement is missing its document principal" on any NULL. Every invoice with a pre-release partial payment or credit became unpayable: the New Payment loader seeded from such an invoice returned a 500, and posting a payment for that party would have failed the same way. The schema and the code disagreed about what a valid row is.
+
+**Rule:** When a migration adds a nullable column and leaves existing rows NULL, every reader added in the same change must define what NULL means and handle it, or the migration must backfill. Keep the throw only where a DB constraint already guarantees the value (source-linked rows). Derive legacy values from the columns that did exist (`appliedAmount` at the applicable exchange rate) and cover the NULL case in the pure-function tests.
+
+**Applies to:** `payment-funding.ts` reducers, any future column added to `invoiceSettlement`, `journalLine`, or other high-volume tables where a backfill is skipped.
diff --git a/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts b/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts
index f2e940af51..556796e1d4 100644
--- a/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.settlements.test.ts
@@ -1171,8 +1171,38 @@ it.each([
});
});
+it("reads a legacy settlement with no document principal from its applied base", async () => {
+ const { client } = clientFor({
+ ...config,
+ salesInvoices: [{ ...invoice, totalAmount: 90, exchangeRate: 1 }],
+ invoiceSettlement: [
+ {
+ paymentId: "posted",
+ memoId: null,
+ targetSalesInvoiceId: "invoice",
+ sourceAmount: null,
+ appliedAmount: 1,
+ discountAmount: 0,
+ writeOffAmount: 0,
+ payment: { status: "Posted" },
+ memo: null,
+ appliedViaPayment: null
+ }
+ ]
+ });
+ const result = await service.getOpenSalesInvoicesForCustomer(
+ client,
+ "co",
+ "cust",
+ "EUR"
+ );
+ expect(result.error).toBeNull();
+ expect(result.data?.[0]).toMatchObject({
+ balance: 89,
+ remainingDocument: 89
+ });
+});
it.each([
- null,
-1,
Number.NaN
])("refuses invalid effective invoice principal %s", async (sourceAmount) => {
diff --git a/packages/database/supabase/functions/shared/payment-funding.test.ts b/packages/database/supabase/functions/shared/payment-funding.test.ts
index 6837ff4244..0cff61a92c 100644
--- a/packages/database/supabase/functions/shared/payment-funding.test.ts
+++ b/packages/database/supabase/functions/shared/payment-funding.test.ts
@@ -398,3 +398,24 @@ Deno.test("source reduction preserves principal, final carry and AP FX direction
}
assertThrows(() => remainingFundingSources([payment], [{ ...use, sourceAmount: 161 }], decimals, true), Error, "Invalid remaining");
});
+Deno.test("legacy settlements without a document principal derive it from applied base", () => {
+ const legacy = { sourceAmount: null, appliedAmount: 110, discountAmount: 0, writeOffAmount: 0 };
+ assertEquals(reduceInvoiceSettlements([legacy], 1.1, 2), { document: 121, base: 110 });
+ assertEquals(reduceInvoiceSettlements([legacy, { ...legacy, sourceAmount: 121 }], 1.1, 2), { document: 242, base: 220 });
+ for (const isAR of [true, false]) {
+ const invoice = { id: "invoice", totalAmount: 200, exchangeRate: 1.1 };
+ const row = { ...legacy, targetSalesInvoiceId: "invoice", targetPurchaseInvoiceId: "invoice" };
+ assertEquals(invoiceRemainingAmounts(invoice, [row], new Map([["invoice", 200]]), 2, isAR),
+ { remainingDocument: 99, remainingBase: 90 });
+ }
+ const payment = { id: "p", totalAmount: 220, exchangeRate: 1.1, postingDate: "2026-01-01", paymentDate: "2026-01-01", currencyCode: "EUR" };
+ const decimals = new Map([["EUR", 2]]);
+ const direct = { paymentId: "p", sourcePaymentId: null, sourceAmount: null, appliedAmount: 110, fxGainLossAmount: null };
+ assertEquals(remainingFundingSources([payment], [direct], decimals, true),
+ [{ paymentId: "p", postingDate: "2026-01-01", exchangeRate: 1.1, remainingDocument: 99, remainingBase: 90 }]);
+ assertThrows(() => remainingFundingSources([payment], [{ ...direct, paymentId: "q", sourcePaymentId: "p" }], decimals, true),
+ Error, "missing its document principal");
+ const tiny = { ...direct, appliedAmount: 0.004 };
+ assertEquals(reduceInvoiceSettlements([tiny, tiny].map((row) => ({ ...row, discountAmount: 0, writeOffAmount: 0 })), 1.1, 2).document, 0);
+ assertEquals(remainingFundingSources([payment], [tiny, tiny], decimals, true)[0].remainingDocument, 220);
+});
diff --git a/packages/database/supabase/functions/shared/payment-funding.ts b/packages/database/supabase/functions/shared/payment-funding.ts
index 304830bcfe..be90cac2af 100644
--- a/packages/database/supabase/functions/shared/payment-funding.ts
+++ b/packages/database/supabase/functions/shared/payment-funding.ts
@@ -246,6 +246,19 @@ function sourcePrincipal(value: number | null): number {
return nonnegativeAmount(Number(value), "Settlement document principal");
}
+function settlementPrincipal(
+ row: { sourceAmount: number | null; appliedAmount: number },
+ exchangeRate: number,
+ decimals: number
+): number {
+ if (row.sourceAmount !== null) return sourcePrincipal(row.sourceAmount);
+ return toDocumentAmount(
+ nonnegativeAmount(Number(row.appliedAmount), "Settlement applied amount"),
+ exchangeRate,
+ decimals
+ );
+}
+
/** Accumulate first; each adjustment is rounded at its document boundary. */
export function reduceInvoiceSettlements(
rows: readonly Pick<SettlementBalanceRow, "sourceAmount" | "appliedAmount" | "discountAmount" | "writeOffAmount">[],
@@ -257,7 +270,7 @@ export function reduceInvoiceSettlements(
for (const row of rows) {
const adjustments = nonnegativeAmount(Number(row.discountAmount), "Settlement discount") +
nonnegativeAmount(Number(row.writeOffAmount), "Settlement write-off");
- document += sourcePrincipal(row.sourceAmount) + toDocumentAmount(adjustments, exchangeRate, decimals);
+ document += settlementPrincipal(row, exchangeRate, decimals) + toDocumentAmount(adjustments, exchangeRate, decimals);
base += nonnegativeAmount(Number(row.appliedAmount), "Settlement applied amount") + adjustments;
}
return { document: toDocumentAmount(document, 1, decimals), base: round(base) };
@@ -311,20 +324,31 @@ export function remainingFundingSources(
decimals: ReadonlyMap<string, number>,
isAR: boolean
): FundingSource[] {
+ const precisionFor = (payment: FundingPaymentRow): number => {
+ const precision = decimals.get(payment.currencyCode);
+ if (precision == null) throw new Error(`Currency ${payment.currencyCode} requires configured decimal places`);
+ return precision;
+ };
+ const paymentsById = new Map(payments.map((payment) => [payment.id, payment]));
const consumed = new Map<string, { document: number; base: number }>();
for (const row of consumption) {
const sourceId = row.sourcePaymentId ?? row.paymentId;
if (!sourceId) continue;
const current = consumed.get(sourceId) ?? { document: 0, base: 0 };
- current.document += sourcePrincipal(row.sourceAmount);
+ if (row.sourceAmount === null && row.sourcePaymentId === null) {
+ const payment = paymentsById.get(sourceId);
+ if (!payment) continue;
+ current.document += settlementPrincipal(row, Number(payment.exchangeRate), precisionFor(payment));
+ } else {
+ current.document += sourcePrincipal(row.sourceAmount);
+ }
const fx = Number(row.fxGainLossAmount ?? 0);
if (!Number.isFinite(fx)) throw new Error("Settlement FX must be finite");
current.base += nonnegativeAmount(Number(row.appliedAmount), "Settlement applied amount") + (isAR ? 1 : -1) * fx;
consumed.set(sourceId, current);
}
return payments.map((payment) => {
- const precision = decimals.get(payment.currencyCode);
- if (precision == null) throw new Error(`Currency ${payment.currencyCode} requires configured decimal places`);
+ const precision = precisionFor(payment);
const use = consumed.get(payment.id);
const total = nonnegativeAmount(Number(payment.totalAmount), "Funding document total");
const remainingDocument = toDocumentAmount(total - (use?.document ?? 0), 1, precision);