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): populate invoice due date from payment term when posting

sidgaikwaddaec3e4f0023
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index da5eb4717c..55fd8160df 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -52,6 +52,10 @@ import type {
* - "End of Month": daysDue days after the end of the issue month.
* - "Day of Month": due on day daysDue of the month — the first occurrence on
* or after the issue date, clamped to the month's length (31 → Feb 28).
+ *
+ * Mirrors calculateDueDate in
+ * packages/database/supabase/functions/shared/calculate-due-date.ts (used when
+ * posting invoices) — keep the two in sync.
*/
export async function computeInvoiceDateDue(
client: SupabaseClient<Database>,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 7d179182d5..3f7a9a07fa 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-08-04T13:23:06.779Z",
+ "generated": "2026-08-04T14:09:22.886Z",
"totalTools": 1411,
"modules": 15,
"tools": [
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 607669d226..4f61351235 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -7,6 +7,7 @@ import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
import { credit, debit, journalReference } from "../lib/utils.ts";
+import { calculateDueDate } from "../shared/calculate-due-date.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import {
allocateVarianceAcrossLayers,
@@ -2015,10 +2016,26 @@ serve(async (req: Request) => {
.execute();
}
+ // Posting keeps the supplier's dateIssued, so only fill dateDue when it
+ // is empty — a manually entered due date from the supplier's invoice wins.
+ const paymentTerm =
+ !purchaseInvoice.data?.dateDue && purchaseInvoice.data?.paymentTermId
+ ? await trx
+ .selectFrom("paymentTerm")
+ .select(["daysDue", "calculationMethod"])
+ .where("id", "=", purchaseInvoice.data.paymentTermId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : undefined;
+ const dateDue = paymentTerm
+ ? calculateDueDate(purchaseInvoice.data?.dateIssued ?? today, paymentTerm)
+ : null;
+
await trx
.updateTable("purchaseInvoice")
.set({
datePaid: today, // TODO: remove this once we have payments working
+ ...(dateDue ? { dateDue } : {}),
postingDate: today,
status: "Open",
})
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index 2dc662152a..f81aa0038a 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -8,6 +8,7 @@ import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
import { credit, debit, journalReference } from "../lib/utils.ts";
+import { calculateDueDate } from "../shared/calculate-due-date.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
import {
@@ -1265,10 +1266,25 @@ serve(async (req: Request) => {
.execute();
}
+ // Posting stamps dateIssued with today, so recompute dateDue from
+ // the payment term to keep it consistent with the new issue date.
+ const paymentTerm = salesInvoice.data?.paymentTermId
+ ? await trx
+ .selectFrom("paymentTerm")
+ .select(["daysDue", "calculationMethod"])
+ .where("id", "=", salesInvoice.data.paymentTermId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ : undefined;
+ const dateDue = paymentTerm
+ ? calculateDueDate(today, paymentTerm)
+ : null;
+
await trx
.updateTable("salesInvoice")
.set({
dateIssued: today,
+ ...(dateDue ? { dateDue } : {}),
postingDate: today,
status: "Submitted",
})
diff --git a/packages/database/supabase/functions/shared/calculate-due-date.ts b/packages/database/supabase/functions/shared/calculate-due-date.ts
new file mode 100644
index 0000000000..ec6d324703
--- /dev/null
+++ b/packages/database/supabase/functions/shared/calculate-due-date.ts
@@ -0,0 +1,60 @@
+import type { Database } from "../lib/types.ts";
+
+type PaymentTermCalculationMethod =
+ Database["public"]["Enums"]["paymentTermCalculationMethod"];
+
+/**
+ * Compute an invoice due date from its issue date and payment term. Mirrors
+ * computeInvoiceDateDue in apps/erp/app/modules/invoicing/invoicing.service.ts
+ * — keep the two in sync.
+ *
+ * The term's calculationMethod decides the anchor for daysDue:
+ * - "Net": daysDue days after the issue date.
+ * - "End of Month": daysDue days after the end of the issue month.
+ * - "Day of Month": due on day daysDue of the month — the first occurrence on
+ * or after the issue date, clamped to the month's length (31 → Feb 28).
+ *
+ * Dates are yyyy-MM-dd strings; returns null when dateIssued can't be parsed.
+ */
+export function calculateDueDate(
+ dateIssued: string,
+ paymentTerm: {
+ daysDue: number;
+ calculationMethod: PaymentTermCalculationMethod;
+ }
+): string | null {
+ const issued = new Date(`${dateIssued}T00:00:00Z`);
+ if (Number.isNaN(issued.getTime())) return null;
+
+ const { daysDue, calculationMethod } = paymentTerm;
+ const year = issued.getUTCFullYear();
+ const month = issued.getUTCMonth();
+
+ let due: Date;
+ switch (calculationMethod) {
+ case "End of Month":
+ // day 0 of month + 1 is the last day of the issue month
+ due = new Date(Date.UTC(year, month + 1, daysDue));
+ break;
+ case "Day of Month": {
+ due = new Date(Date.UTC(year, month, clampDay(daysDue, year, month)));
+ if (due < issued) {
+ due = new Date(
+ Date.UTC(year, month + 1, clampDay(daysDue, year, month + 1))
+ );
+ }
+ break;
+ }
+ default:
+ due = new Date(Date.UTC(year, month, issued.getUTCDate() + daysDue));
+ }
+
+ return due.toISOString().slice(0, 10);
+}
+
+// Clamp a configured day-of-month into the target month's real range so day 31
+// resolves to Feb 28 rather than rolling into March.
+function clampDay(day: number, year: number, month: number): number {
+ const daysInMonth = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
+ return Math.min(Math.max(day, 1), daysInMonth);
+}