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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(invoicing): default due date to Net 30 when no payment term is set (#1422)
Siddharth Gaikwad1b23c010886c
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 3d98f87757..4019c339a0 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -40,15 +40,32 @@ const PURCHASE_INVOICES_LIST_COLUMNS =const SALES_INVOICES_LIST_COLUMNS ="id,invoiceId,status,customerId,customerReference,invoiceCustomerId,postingDate,dateIssued,dateDue,datePaid,balance,assignee,companyId,customFields,createdAt,createdBy,updatedAt,updatedBy,thumbnailPath,itemType,invoiceTotal,paymentTermName" as const;+/**+ * The payment term an invoice falls back to when none is specified — Net 30,+ * matching Stripe's default of 30 days until an invoice is due. Without it an+ * invoice with no payment term carried no due date at all, so it could never+ * read as overdue and never surfaced in AR/AP aging.+ *+ * Mirrors DEFAULT_PAYMENT_TERM in+ * packages/database/supabase/functions/shared/calculate-due-date.ts — keep the+ * two in sync.+ */+export const DEFAULT_PAYMENT_TERM: {+ daysDue: number;+ calculationMethod: Database["public"]["Enums"]["paymentTermCalculationMethod"];+} = { daysDue: 30, calculationMethod: "Net" };+/*** Compute an invoice's Due Date from its Issue Date and Payment Term.- * Returns null when either input is missing, the payment term genuinely doesn't- * exist for the company, or the stored date can't be parsed — callers fall back- * to a plain field update in that case. A payment-term *query failure* is- * different: it throws, so callers abort instead of writing the invoice with a- * stale dateDue. The read is scoped by companyId for tenant isolation (defense- * in depth alongside RLS) and uses maybeSingle so an absent row is data: null- * (not an error) — keeping "missing" distinguishable from "failed".+ * Returns null only when the issue date is missing or can't be parsed — callers+ * fall back to a plain field update in that case. A missing payment term is NOT+ * a missing due date: an unset paymentTermId, or one whose row genuinely+ * doesn't exist for the company, falls back to DEFAULT_PAYMENT_TERM (Net 30).+ * A payment-term *query failure* is different: it throws, so callers abort+ * instead of writing the invoice with a stale dateDue. The read is scoped by+ * companyId for tenant isolation (defense in depth alongside RLS) and uses+ * maybeSingle so an absent row is data: null (not an error) — keeping "missing"+ * distinguishable from "failed".** The term's calculationMethod decides the anchor for daysDue:* - "Net": daysDue days after the issue date.@@ -69,23 +86,25 @@ export async function computeInvoiceDateDue(}): Promise<string | null> {const { dateIssued, paymentTermId, companyId } = args;- if (!dateIssued || !paymentTermId) return null;-- const paymentTerm = await client- .from("paymentTerm")- .select("daysDue, calculationMethod")- .eq("id", paymentTermId)- .eq("companyId", companyId)- .maybeSingle();-- if (paymentTerm.error) {+ if (!dateIssued) return null;++ const paymentTerm = paymentTermId+ ? await client+ .from("paymentTerm")+ .select("daysDue, calculationMethod")+ .eq("id", paymentTermId)+ .eq("companyId", companyId)+ .maybeSingle()+ : null;++ if (paymentTerm?.error) {throw new Error(`Failed to load payment term ${paymentTermId} while recomputing invoice due date: ${paymentTerm.error.message}`);}- if (!paymentTerm.data) return null;- const { daysDue, calculationMethod } = paymentTerm.data;+ const { daysDue, calculationMethod } =+ paymentTerm?.data ?? DEFAULT_PAYMENT_TERM;try {const issued = parseDate(dateIssued);diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsindex 509ae13fe5..f90ddd4190 100644--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts@@ -2241,6 +2241,7 @@ serve(async (req: Request) => {// 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.+ // With no payment term the invoice still gets one, via Net 30.const paymentTerm =!purchaseInvoice.data?.dateDue && purchaseInvoice.data?.paymentTermId? await trx@@ -2250,9 +2251,12 @@ serve(async (req: Request) => {.where("companyId", "=", companyId).executeTakeFirst(): undefined;- const dateDue = paymentTerm- ? calculateDueDate(purchaseInvoice.data?.dateIssued ?? today, paymentTerm)- : null;+ const dateDue = purchaseInvoice.data?.dateDue+ ? null+ : calculateDueDate(+ purchaseInvoice.data?.dateIssued ?? today,+ paymentTerm+ );await trx.updateTable("purchaseInvoice")diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.tsindex c30084d498..7dd18423b7 100644--- a/packages/database/supabase/functions/post-sales-invoice/index.ts+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts@@ -1385,6 +1385,7 @@ serve(async (req: Request) => {// Posting stamps dateIssued with today, so recompute dateDue from// the payment term to keep it consistent with the new issue date.+ // With no payment term the invoice still gets one, via Net 30.const paymentTerm = salesInvoice.data?.paymentTermId? await trx.selectFrom("paymentTerm")@@ -1393,9 +1394,7 @@ serve(async (req: Request) => {.where("companyId", "=", companyId).executeTakeFirst(): undefined;- const dateDue = paymentTerm- ? calculateDueDate(today, paymentTerm)- : null;+ const dateDue = calculateDueDate(today, paymentTerm);await trx.updateTable("salesInvoice")diff --git a/packages/database/supabase/functions/shared/calculate-due-date.ts b/packages/database/supabase/functions/shared/calculate-due-date.tsindex ec6d324703..f2b4d81ef4 100644--- a/packages/database/supabase/functions/shared/calculate-due-date.ts+++ b/packages/database/supabase/functions/shared/calculate-due-date.ts@@ -3,6 +3,20 @@ import type { Database } from "../lib/types.ts";type PaymentTermCalculationMethod =Database["public"]["Enums"]["paymentTermCalculationMethod"];+/**+ * The payment term an invoice falls back to when none is specified — Net 30,+ * matching Stripe's default of 30 days until an invoice is due. Without it an+ * invoice with no payment term carried no due date at all, so it could never+ * read as overdue and never surfaced in AR/AP aging.+ *+ * Mirrors DEFAULT_PAYMENT_TERM in+ * apps/erp/app/modules/invoicing/invoicing.service.ts — keep the two in sync.+ */+export const DEFAULT_PAYMENT_TERM: {+ daysDue: number;+ calculationMethod: PaymentTermCalculationMethod;+} = { daysDue: 30, calculationMethod: "Net" };+/*** Compute an invoice due date from its issue date and payment term. Mirrors* computeInvoiceDateDue in apps/erp/app/modules/invoicing/invoicing.service.ts@@ -14,19 +28,22 @@ type PaymentTermCalculationMethod =* - "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).*+ * A missing payment term is not a missing due date: it falls back to+ * DEFAULT_PAYMENT_TERM (Net 30) rather than returning null.+ ** Dates are yyyy-MM-dd strings; returns null when dateIssued can't be parsed.*/export function calculateDueDate(dateIssued: string,- paymentTerm: {+ paymentTerm?: {daysDue: number;calculationMethod: PaymentTermCalculationMethod;- }+ } | null): string | null {const issued = new Date(`${dateIssued}T00:00:00Z`);if (Number.isNaN(issued.getTime())) return null;- const { daysDue, calculationMethod } = paymentTerm;+ const { daysDue, calculationMethod } = paymentTerm ?? DEFAULT_PAYMENT_TERM;const year = issued.getUTCFullYear();const month = issued.getUTCMonth();