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(purchasing): short-close aware invoicing quantities
naveenkashb6167efe968c
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 3d3e33aae7..4e84d8a769 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -1801,6 +1801,12 @@ export async function updatePurchaseOrderLineOrder(* line completeness flags. Open-PO supply queries (get_inventory_quantities,* openPurchaseOrderLines) exclude `receivedComplete` lines, so the undelivered* remainder stops counting as incoming stock.+ *+ * Closing also caps the billable quantity at what was received (the convert+ * and post-purchase-invoice functions apply the same rule), so a line whose+ * received quantity is already fully invoiced gets `invoicedComplete` too —+ * otherwise the order could never reach Completed. Reopening restores the+ * natural rule (fully invoiced = ordered quantity).*/export async function shortClosePurchaseOrderLine(db: Kysely<KyselyDatabase>,@@ -1819,10 +1825,29 @@ export async function shortClosePurchaseOrderLine(}) {return db.transaction().execute(async (trx) => {+ const line = await trx+ .selectFrom("purchaseOrderLine")+ .select(["purchaseQuantity", "quantityReceived", "quantityInvoiced"])+ .where("id", "=", lineId)+ .where("purchaseOrderId", "=", purchaseOrderId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ if (!line) throw new Error("Purchase order line not found");++ // NUMERIC columns come back from the pg driver as strings+ const ordered = Number(line.purchaseQuantity ?? 0);+ const received = Number(line.quantityReceived ?? 0);+ const invoiced = Number(line.quantityInvoiced ?? 0);++ const invoicedComplete =+ intent === "close" ? invoiced >= received : invoiced >= ordered;+await trx.updateTable("purchaseOrderLine").set({receivedComplete: intent === "close",+ invoicedComplete,updatedBy: userId,updatedAt: new Date().toISOString()})diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex d25a162974..0c6bec1136 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-07-13T10:01:21.326Z",+ "generated": "2026-07-14T08:43:06.820Z","totalTools": 1326,"modules": 15,"tools": [diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.tsindex 51bfe44204..ea8b88974e 100644--- a/packages/database/supabase/functions/convert/index.ts+++ b/packages/database/supabase/functions/convert/index.ts@@ -13,6 +13,7 @@ import { corsHeaders } from "../lib/headers.ts";import { requirePermissions } from "../lib/supabase.ts";import { Database } from "../lib/types.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";+import { getRemainingQuantityToInvoice } from "../shared/short-close.ts";const pool = getConnectionPool(2);const db = getDatabaseClient<DB>(pool);@@ -292,13 +293,16 @@ serve(async (req: Request) => {if (!purchaseOrderDelivery.data)throw new Error("Purchase order delivery not found");+ // Short-closed lines ("Stop Receiving") only bill what was received,+ // so quantities go through getRemainingQuantityToInvoice rather than+ // the generated quantityToInvoice column (ordered - invoiced).const uninvoicedLines = purchaseOrderLines?.data?.reduce<(typeof purchaseOrderLines)["data"]>((acc, line) => {if (- line?.quantityToInvoice &&- line.quantityToInvoice > 0 &&- !line.invoicedComplete+ line &&+ !line.invoicedComplete &&+ getRemainingQuantityToInvoice(line) > 0) {acc.push(line);}@@ -313,12 +317,8 @@ serve(async (req: Request) => {}const uninvoicedSubtotal = uninvoicedLines.reduce((acc, line) => {- if (- line?.quantityToInvoice &&- line.unitPrice &&- line.quantityToInvoice > 0- ) {- acc += line.quantityToInvoice * line.unitPrice;+ if (line?.unitPrice) {+ acc += getRemainingQuantityToInvoice(line) * line.unitPrice;}return acc;@@ -339,11 +339,13 @@ serve(async (req: Request) => {const uninvoicedFraction = (line: {purchaseQuantity: number | null;- quantityToInvoice: number | null;+ quantityReceived: number | null;+ quantityInvoiced: number | null;+ receivedComplete: boolean | null;}) => {const ordered = line.purchaseQuantity ?? 0;if (ordered <= 0) return 1;- return Math.min((line.quantityToInvoice ?? 0) / ordered, 1);+ return Math.min(getRemainingQuantityToInvoice(line) / ordered, 1);};let purchaseInvoiceId = "";@@ -417,7 +419,7 @@ serve(async (req: Request) => {costCenterId: line.costCenterId,assetId: line.assetId,description: line.description,- quantity: line.quantityToInvoice,+ quantity: getRemainingQuantityToInvoice(line),supplierUnitPrice: line.supplierUnitPrice ?? 0,supplierShippingCost:(line.supplierShippingCost ?? 0) * uninvoicedFraction(line),diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsindex 4ebd24b50d..50440a4d92 100644--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts@@ -14,6 +14,10 @@ import {} from "../shared/purchase-cost-adjustment.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";+import {+ getBillableQuantity,+ getRemainingQuantityToInvoice,+} from "../shared/short-close.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);@@ -192,8 +196,10 @@ serve(async (req: Request) => {invoicedQuantityInPurchaseUnit);+ // Short-close aware: compare against the billable (received)+ // quantity for short-closed lines, not the ordered quantity.const invoicedComplete =- newQuantityInvoiced >= purchaseOrderLine.purchaseQuantity;+ newQuantityInvoiced >= getBillableQuantity(purchaseOrderLine);acc[invoiceLine.purchaseOrderLineId] = {quantityInvoiced: newQuantityInvoiced,@@ -711,11 +717,12 @@ serve(async (req: Request) => {const newQuantityInvoiced =(purchaseOrderLine.quantityInvoiced ?? 0) + invoiceLine.quantity;+ // Short-close aware: a line whose receiving was stopped is fully+ // invoiced once the received (not ordered) quantity is billed.const invoicedComplete =purchaseOrderLine.invoicedComplete ||invoiceLine.quantity >=- (purchaseOrderLine.quantityToInvoice ??- purchaseOrderLine.purchaseQuantity);+ getRemainingQuantityToInvoice(purchaseOrderLine);return {...acc,diff --git a/packages/database/supabase/functions/shared/short-close.test.ts b/packages/database/supabase/functions/shared/short-close.test.tsnew file mode 100644index 0000000000..98b3099de9--- /dev/null+++ b/packages/database/supabase/functions/shared/short-close.test.ts@@ -0,0 +1,84 @@+import {+ assertEquals,+} from "https://deno.land/[email protected]/testing/asserts.ts";+import {+ getBillableQuantity,+ getRemainingQuantityToInvoice,+ type ShortCloseInvoicingLine,+} from "./short-close.ts";++const line = (+ overrides: Partial<ShortCloseInvoicingLine>+): ShortCloseInvoicingLine => ({+ purchaseQuantity: 9,+ quantityReceived: 0,+ quantityInvoiced: 0,+ receivedComplete: false,+ ...overrides,+});++Deno.test("open line bills the ordered quantity", () => {+ const l = line({ quantityReceived: 2 });+ assertEquals(getBillableQuantity(l), 9);+ assertEquals(getRemainingQuantityToInvoice(l), 9);+});++Deno.test("fully received line bills the ordered quantity", () => {+ const l = line({ quantityReceived: 9, receivedComplete: true });+ assertEquals(getBillableQuantity(l), 9);+ assertEquals(getRemainingQuantityToInvoice(l), 9);+});++Deno.test("short-closed line bills only the received quantity", () => {+ // Ordered 9, received 2, then Stop Receiving.+ const l = line({ quantityReceived: 2, receivedComplete: true });+ assertEquals(getBillableQuantity(l), 2);+ assertEquals(getRemainingQuantityToInvoice(l), 2);+});++Deno.test("short-closed line already invoiced for receipts has nothing left", () => {+ const l = line({+ quantityReceived: 2,+ quantityInvoiced: 2,+ receivedComplete: true,+ });+ assertEquals(getRemainingQuantityToInvoice(l), 0);+});++Deno.test("short-closed with nothing received has nothing to invoice", () => {+ const l = line({ receivedComplete: true });+ assertEquals(getBillableQuantity(l), 0);+ assertEquals(getRemainingQuantityToInvoice(l), 0);+});++Deno.test("partial invoice against an open line leaves the remainder", () => {+ const l = line({ quantityReceived: 2, quantityInvoiced: 4 });+ assertEquals(getRemainingQuantityToInvoice(l), 5);+});++Deno.test("over-invoiced short-closed line clamps to zero", () => {+ const l = line({+ quantityReceived: 2,+ quantityInvoiced: 5,+ receivedComplete: true,+ });+ assertEquals(getRemainingQuantityToInvoice(l), 0);+});++Deno.test("over-received line is not short-closed", () => {+ // Received more than ordered (over-receipt) then flagged complete: the+ // received < ordered guard keeps the billable quantity at the order.+ const l = line({ quantityReceived: 11, receivedComplete: true });+ assertEquals(getBillableQuantity(l), 9);+});++Deno.test("null quantities behave as zero", () => {+ const l = line({+ purchaseQuantity: null,+ quantityReceived: null,+ quantityInvoiced: null,+ receivedComplete: true,+ });+ assertEquals(getBillableQuantity(l), 0);+ assertEquals(getRemainingQuantityToInvoice(l), 0);+});diff --git a/packages/database/supabase/functions/shared/short-close.ts b/packages/database/supabase/functions/shared/short-close.tsnew file mode 100644index 0000000000..acbbf3f1e9--- /dev/null+++ b/packages/database/supabase/functions/shared/short-close.ts@@ -0,0 +1,40 @@+/**+ * Short-close-aware invoicing quantities for purchase order lines.+ *+ * A short-closed line has `receivedComplete = true` while+ * `quantityReceived < purchaseQuantity`: the buyer declared the undelivered+ * remainder will never arrive ("Stop Receiving"). Only what was actually+ * received is billable. The generated `quantityToInvoice` column+ * (purchaseQuantity - quantityInvoiced) knows nothing about receiving, so+ * invoicing paths must go through these helpers instead of the column.+ */++export type ShortCloseInvoicingLine = {+ purchaseQuantity: number | null;+ quantityReceived: number | null;+ quantityInvoiced: number | null;+ receivedComplete: boolean | null;+};++/**+ * Quantity the supplier can ultimately bill for the line: the ordered+ * quantity normally, or only the received quantity when the line is+ * short-closed.+ */+export function getBillableQuantity(line: ShortCloseInvoicingLine): number {+ const ordered = line.purchaseQuantity ?? 0;+ const received = line.quantityReceived ?? 0;+ const isShortClosed = !!line.receivedComplete && received < ordered;+ return isShortClosed ? received : ordered;+}++/**+ * Billable quantity not yet invoiced. Equals the generated+ * `quantityToInvoice` column for normal lines; capped at the received+ * quantity for short-closed lines.+ */+export function getRemainingQuantityToInvoice(+ line: ShortCloseInvoicingLine+): number {+ return Math.max(getBillableQuantity(line) - (line.quantityInvoiced ?? 0), 0);+}