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(purchasing): PO goes Completed with quantity still to invoice (#1976)

Brad Barbine45a8e2004c1
diff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.md
index d53b4f0f43..be5ff4e486 100644
--- a/apps/erp/app/modules/purchasing/AGENTS.md
+++ b/apps/erp/app/modules/purchasing/AGENTS.md
@@ -63,6 +63,7 @@ cd apps/erp && pnpm exec vitest run app/modules/purchasing
- `getPurchaseOrder` / `getPurchaseOrders` / `getPurchaseOrderLines` — read POs
- `submitPurchaseOrderForApproval(db, …)` — Needs Approval, the order date when it has none, and the approval request unless one is pending, inside the caller's transaction (the status update locks the order first)
- `setPurchaseOrderStatus(db, …)` / `cancelPendingApprovals(db, …)` — the Kysely status write and approval-request cancel that `reopenPurchaseOrder`, `closePurchaseOrderAndApprovals` and `deletePurchaseOrders` run in ONE transaction, so a status change or delete that fails leaves the requests Pending
+- A line's `receivedComplete` / `invoicedComplete` are only ever SET by receipt and invoice posting (`stored || …`), and the header status is derived from them. So every write that changes an existing line's `purchaseQuantity` — `upsertPurchaseOrderLine`, `updatePurchaseOrderLineSchedule`, the planning Increase / Decrease in `applyPurchasingPlanningActions` — restates both through `getCompletionAfterQuantityChange` (`@carbon/utils` `short-close.ts`; a line still short-closed stays closed), computed against the current row: the two Kysely paths lock it `FOR UPDATE` in the write's transaction, and `upsertPurchaseOrderLine` (Supabase client) is a compare-and-swap on the columns the flags came from, retried when a receipt or invoice lands in between. Without it a PO invoiced for 10, reopened and raised to 20 went straight to Completed on receipt with 10 never invoiced
- `shortClosePurchaseOrderLine` — Kysely transaction; sets a line's `receivedComplete` ("Stop/Resume Receiving") and recomputes the header status. Open-PO supply queries (`get_inventory_quantities`, `openPurchaseOrderLines`, `get_job_quantity_on_hand`) exclude `receivedComplete` lines, so short-closed remainders stop counting as incoming stock
- `convertSupplierQuoteToOrder` — calls `convertDocument` (`shared.service.ts`, ported from the `convert` server function)
- `duplicatePurchaseOrder` — copies a PO with new sequence
diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.ts
index 98d0e0f4eb..976c098020 100644
--- a/apps/erp/app/modules/purchasing/purchasing.server.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts
@@ -5394,10 +5394,10 @@ export const updatePurchaseOrderLine = defineServiceFn({
async run(ctx, input) {
return unwrap(
ctx,
- await service.upsertPurchaseOrderLine(
- ctx.asCaller.supabase,
- payload(ctx, input).forUpdate() as never
- )
+ await service.upsertPurchaseOrderLine(ctx.asCaller.supabase, {
+ ...payload(ctx, input).forUpdate(),
+ companyId: ctx.company.id
+ } as never)
);
}
});
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index c745c5f970..15adba42f7 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -67,6 +67,7 @@ import {
datetime,
EPSILON,
escalatedLeasePayment,
+ getCompletionAfterQuantityChange,
getPurchaseOrderStatus,
getPurchaseReturnOrderStatus,
groupBy,
@@ -2058,6 +2059,85 @@ function normalizePurchaseOrderLineReferences<
return { ...line, itemId: null, accountId: null, assetId: null };
}
+/** The columns a quantity edit's completion flags are derived from. */
+const COMPLETION_SOURCE_COLUMNS = [
+ "purchaseQuantity",
+ "quantityReceived",
+ "quantityInvoiced",
+ "receivedComplete"
+] as const;
+
+/** A quantity edit retries this many times when a receipt or invoice lands. */
+const COMPLETION_CAS_ATTEMPTS = 3;
+
+/**
+ * Update an existing line, restating its completion flags when the edit
+ * changes `purchaseQuantity` (`getCompletionAfterQuantityChange`). The flags
+ * are derived from a read, so the UPDATE is a compare-and-swap on the columns
+ * they came from: a receipt or invoice posted in between matches no row, and
+ * the edit re-reads and tries again rather than overwriting what it posted.
+ */
+async function updatePurchaseOrderLineRestatingCompletion(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ line: { id: string; purchaseQuantity?: number }
+) {
+ for (let attempt = 0; attempt < COMPLETION_CAS_ATTEMPTS; attempt++) {
+ const current = await client
+ .from("purchaseOrderLine")
+ .select(COMPLETION_SOURCE_COLUMNS.join(", "))
+ .eq("id", line.id)
+ .eq("companyId", companyId)
+ .single<
+ Pick<
+ Database["public"]["Tables"]["purchaseOrderLine"]["Row"],
+ (typeof COMPLETION_SOURCE_COLUMNS)[number]
+ >
+ >();
+ if (current.error) return { data: null, error: current.error };
+
+ const quantityChanged =
+ line.purchaseQuantity !== undefined &&
+ !equals(
+ Number(current.data.purchaseQuantity ?? 0),
+ line.purchaseQuantity
+ );
+
+ let update = client
+ .from("purchaseOrderLine")
+ .update(
+ sanitize({
+ ...line,
+ ...(quantityChanged
+ ? getCompletionAfterQuantityChange(
+ current.data,
+ line.purchaseQuantity!
+ )
+ : {})
+ })
+ )
+ .eq("id", line.id)
+ .eq("companyId", companyId);
+ if (quantityChanged) {
+ for (const column of COMPLETION_SOURCE_COLUMNS) {
+ const value = current.data[column];
+ update =
+ value === null ? update.is(column, null) : update.eq(column, value);
+ }
+ }
+
+ const updated = await update.select("id").maybeSingle();
+ if (updated.error) return { data: null, error: updated.error };
+ if (updated.data) return { data: updated.data, error: null };
+ }
+ return {
+ data: null,
+ error: new Error(
+ "The line was received or invoiced while saving. Try again."
+ )
+ };
+}
+
export async function upsertPurchaseOrderLine(
client: SupabaseClient<Database>,
purchaseOrderLine:
@@ -2068,6 +2148,7 @@ export async function upsertPurchaseOrderLine(
})
| (Omit<z.infer<typeof purchaseOrderLineValidator>, "id"> & {
id: string;
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -2081,12 +2162,8 @@ export async function upsertPurchaseOrderLine(
if (cleared.error) return { data: null, error: cleared.error };
if ("id" in normalized) {
- return client
- .from("purchaseOrderLine")
- .update(sanitize(normalized))
- .eq("id", normalized.id)
- .select("id")
- .single();
+ const { companyId, ...line } = normalized;
+ return updatePurchaseOrderLineRestatingCompletion(client, companyId, line);
}
const existing = await client
@@ -2362,6 +2439,8 @@ export async function applyPurchasingPlanningActions(
"pol.supplierShippingCost",
"pol.purchaseQuantity",
"pol.quantityReceived",
+ "pol.quantityInvoiced",
+ "pol.receivedComplete",
"pol.taxPercent",
"pol.supplierTaxAmount",
"pol.conversionFactor",
@@ -2370,6 +2449,8 @@ export async function applyPurchasingPlanningActions(
])
.where("pol.id", "in", lineIds)
.where("pol.companyId", "=", companyId)
+ // the completion flags below are derived from these rows
+ .forUpdate("pol")
.execute()
).map(({ baseCurrencyCode, ...line }) => ({
...line,
@@ -2401,6 +2482,8 @@ export async function applyPurchasingPlanningActions(
quantity: number;
percent: number;
amount: number;
+ receivedComplete: boolean;
+ invoicedComplete: boolean;
}[] = [];
const unheld: string[] = [];
for (const action of quantities) {
@@ -2439,7 +2522,8 @@ export async function applyPurchasingPlanningActions(
lineId: action.lineId,
quantity,
percent: pair.percent,
- amount: pair.amount
+ amount: pair.amount,
+ ...getCompletionAfterQuantityChange(line, quantity)
});
}
// a failed computation never holds its claim
@@ -2451,14 +2535,16 @@ export async function applyPurchasingPlanningActions(
SET "purchaseQuantity" = v."purchaseQuantity"::numeric,
"taxPercent" = v."taxPercent"::numeric,
"supplierTaxAmount" = v."supplierTaxAmount"::numeric,
+ "receivedComplete" = v."receivedComplete"::boolean,
+ "invoicedComplete" = v."invoicedComplete"::boolean,
"updatedBy" = ${userId},
"updatedAt" = ${now}
FROM (VALUES ${sql.join(
values.map(
(v) =>
- sql`(${v.lineId}, ${v.quantity}, ${v.percent}, ${v.amount})`
+ sql`(${v.lineId}, ${v.quantity}, ${v.percent}, ${v.amount}, ${v.receivedComplete}, ${v.invoicedComplete})`
)
- )}) AS v("id", "purchaseQuantity", "taxPercent", "supplierTaxAmount")
+ )}) AS v("id", "purchaseQuantity", "taxPercent", "supplierTaxAmount", "receivedComplete", "invoicedComplete")
WHERE l."id" = v."id"
AND l."companyId" = ${companyId}
AND l."purchaseOrderId" IN (${editablePurchaseOrders})
@@ -3526,30 +3612,54 @@ export async function updatePurchaseOrderLineSchedule(
}
try {
- const updated = await db
- .updateTable("purchaseOrderLine")
- .set({
- ...(args.requiredDate !== undefined
- ? { requiredDate: args.requiredDate }
- : {}),
- ...(args.purchaseQuantity !== undefined
- ? { purchaseQuantity: args.purchaseQuantity }
- : {}),
- ...(tax ?? {}),
- updatedBy: args.userId,
- updatedAt: datetime.timestamp()
- })
- .where("id", "=", args.lineId)
- .where("companyId", "=", args.companyId)
- .where("purchaseOrderId", "in", (eb) =>
- eb
- .selectFrom("purchaseOrder")
- .select("id")
- .where("companyId", "=", args.companyId)
- .where("status", "in", [...PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES])
- )
- .returning("id")
- .execute();
+ const updated = await db.transaction().execute(async (trx) => {
+ // The completion flags are derived from the row locked here, so a
+ // receipt or invoice posted meanwhile is not overwritten.
+ const current =
+ args.purchaseQuantity !== undefined
+ ? await trx
+ .selectFrom("purchaseOrderLine")
+ .select([...COMPLETION_SOURCE_COLUMNS])
+ .where("id", "=", args.lineId)
+ .where("companyId", "=", args.companyId)
+ .forUpdate()
+ .executeTakeFirst()
+ : undefined;
+ const completion =
+ current &&
+ args.purchaseQuantity !== undefined &&
+ !equals(Number(current.purchaseQuantity ?? 0), args.purchaseQuantity)
+ ? getCompletionAfterQuantityChange(current, args.purchaseQuantity)
+ : {};
+
+ return trx
+ .updateTable("purchaseOrderLine")
+ .set({
+ ...(args.requiredDate !== undefined
+ ? { requiredDate: args.requiredDate }
+ : {}),
+ ...(args.purchaseQuantity !== undefined
+ ? { purchaseQuantity: args.purchaseQuantity }
+ : {}),
+ ...(tax ?? {}),
+ ...completion,
+ updatedBy: args.userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", args.lineId)
+ .where("companyId", "=", args.companyId)
+ .where("purchaseOrderId", "in", (eb) =>
+ eb
+ .selectFrom("purchaseOrder")
+ .select("id")
+ .where("companyId", "=", args.companyId)
+ .where("status", "in", [
+ ...PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES
+ ])
+ )
+ .returning("id")
+ .execute();
+ });
return { updated: updated.length > 0, error: null };
} catch (err) {
return {
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
index 6dc7b7966f..65bd7dfe9a 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
@@ -120,7 +120,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
message: "Cannot modify a confirmed purchase order."
});
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "purchasing"
});
@@ -139,6 +139,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatePurchaseOrderLine = await upsertPurchaseOrderLine(client, {
id: lineId,
...d,
+ companyId,
updatedBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/packages/utils/src/short-close.test.ts b/packages/utils/src/short-close.test.ts
index 35afd0652c..0fb9e3c5bc 100644
--- a/packages/utils/src/short-close.test.ts
+++ b/packages/utils/src/short-close.test.ts
@@ -5,6 +5,7 @@
import { expect, it } from "vitest";
import {
getBillableQuantity,
+ getCompletionAfterQuantityChange,
getRemainingQuantityToInvoice,
type ShortCloseInvoicingLine
} from "./short-close";
@@ -84,3 +85,61 @@ it("null quantities behave as zero", () => {
expect(getBillableQuantity(l)).toEqual(0);
expect(getRemainingQuantityToInvoice(l)).toEqual(0);
});
+
+it("raising an invoiced line's quantity reopens invoicing", () => {
+ // Ordered 10 and invoiced 10, then reopened and raised to 20.
+ const l = line({ purchaseQuantity: 10, quantityInvoiced: 10 });
+ expect(getCompletionAfterQuantityChange(l, 20)).toEqual({
+ receivedComplete: false,
+ invoicedComplete: false
+ });
+});
+
+it("raising a received line's quantity reopens receiving", () => {
+ const l = line({
+ purchaseQuantity: 10,
+ quantityReceived: 10,
+ receivedComplete: true
+ });
+ expect(getCompletionAfterQuantityChange(l, 20)).toEqual({
+ receivedComplete: false,
+ invoicedComplete: false
+ });
+});
+
+it("lowering a line to what was received and invoiced completes it", () => {
+ const l = line({
+ purchaseQuantity: 20,
+ quantityReceived: 10,
+ quantityInvoiced: 10
+ });
+ expect(getCompletionAfterQuantityChange(l, 10)).toEqual({
+ receivedComplete: true,
+ invoicedComplete: true
+ });
+});
+
+it("a short-closed line stays closed when its quantity changes", () => {
+ // Ordered 9, received 2, Stop Receiving, then raised to 12.
+ const l = line({ quantityReceived: 2, receivedComplete: true });
+ expect(getCompletionAfterQuantityChange(l, 12)).toEqual({
+ receivedComplete: true,
+ invoicedComplete: false
+ });
+ expect(
+ getCompletionAfterQuantityChange({ ...l, quantityInvoiced: 2 }, 12)
+ ).toEqual({ receivedComplete: true, invoicedComplete: true });
+});
+
+it("a short-close settled by matching the quantity reopens on a later raise", () => {
+ // Ordered 9, received 2, Stop Receiving, set to 2, then raised to 12.
+ const settled = line({
+ purchaseQuantity: 2,
+ quantityReceived: 2,
+ receivedComplete: true
+ });
+ expect(getCompletionAfterQuantityChange(settled, 12)).toEqual({
+ receivedComplete: false,
+ invoicedComplete: false
+ });
+});
diff --git a/packages/utils/src/short-close.ts b/packages/utils/src/short-close.ts
index 38342fd668..6cd90a229e 100644
--- a/packages/utils/src/short-close.ts
+++ b/packages/utils/src/short-close.ts
@@ -42,3 +42,27 @@ export function getRemainingQuantityToInvoice(
): number {
return Math.max(getBillableQuantity(line) - (line.quantityInvoiced ?? 0), 0);
}
+
+/**
+ * The line's completion flags once its ordered quantity becomes
+ * `purchaseQuantity`. Receipt and invoice posting only ever set the flags,
+ * so a quantity edit (a reopened order, a planning Increase) must restate
+ * them: a line invoiced for 10 and raised to 20 still has 10 to invoice. A
+ * line still short-closed (received below the ordered quantity) stays closed
+ * — Stop Receiving is the buyer's decision, not a quantity fact. Once the
+ * ordered quantity is set to what was received nothing is short any more, so
+ * a later increase is a new request and reopens receiving.
+ */
+export function getCompletionAfterQuantityChange(
+ line: ShortCloseInvoicingLine,
+ purchaseQuantity: number
+): { receivedComplete: boolean; invoicedComplete: boolean } {
+ const received = line.quantityReceived ?? 0;
+ const isShortClosed =
+ !!line.receivedComplete && received < (line.purchaseQuantity ?? 0);
+ const receivedComplete = isShortClosed || received >= purchaseQuantity;
+ const invoicedComplete =
+ (line.quantityInvoiced ?? 0) >=
+ getBillableQuantity({ ...line, purchaseQuantity, receivedComplete });
+ return { receivedComplete, invoicedComplete };
+}