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(planning,purchasing): stop FK/check violations from bad locationId and stale PO line refs (#1580)

Brad Barbinf43f46092d3a
diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.md
index 833be9cdb5..d1872674a9 100644
--- a/.claude/rules/mrp-system.md
+++ b/.claude/rules/mrp-system.md
@@ -119,9 +119,16 @@ Base tables defined in `20250610000433_demand-planning.sql`; lineage table in
| `supplyActual` | `(itemId, locationId, periodId, sourceType)` | `actualQuantity`, `sourceType` | `sourceType` enum `supplySourceType` = `'Purchase Order'\|'Production Order'` |
| `demandForecastSource` | surrogate `id` | `sourceType`, `jobId`/`salesOrderLineId`/`demandProjectionId`, `parentItemId`, `quantity` | MRP lineage; enum `demandForecastSourceType` = `'Job Material'\|'Sales Order'\|'Demand Projection'`; CHECK exactly one source id set |
-`locationId` is nullable on all five planning tables. Audit cols
-(`createdBy/At`, `updatedBy/At`) present except on `period` and
-`demandForecastSource` (created-only).
+`locationId` is declared `TEXT` (no `NOT NULL`) on all five planning tables, but
+it is part of the PRIMARY KEY of every one of them (see the PK column above), so
+Postgres makes it **implicitly NOT NULL** — a null `locationId` raises 23502, and
+it is also an FK to `location(id)`, so a bogus value (e.g. the empty string
+`runMrp` used to write via a `?? ""` key fallback for a source line with no
+location) raises 23503 `*_locationId_fkey` and rolls the whole run back. `runMrp`
+therefore SKIPS any source line (sales/job-material/production/PO/projection) with
+no `locationId` rather than fabricating one. Audit cols (`createdBy/At`,
+`updatedBy/At`) present except on `period` and `demandForecastSource`
+(created-only).
## Planning split functions
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 58cb1b9a6b..2290636277 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -1805,6 +1805,47 @@ export async function upsertPurchaseOrderDelivery(
.single();
}
+const PURCHASE_ORDER_LINE_ITEM_TYPES = [
+ "Part",
+ "Material",
+ "Tool",
+ "Service",
+ "Consumable",
+ "Fixture"
+];
+
+/**
+ * Force the mutually-exclusive reference columns (`itemId`, `accountId`,
+ * `assetId`) to match the line's `purchaseOrderLineType`, nulling the ones that
+ * don't apply. `purchaseOrderLineType_check` requires exactly one of these set
+ * per type, but the form only submits the active tab's field and `sanitize()`
+ * turns *absent* keys into nothing (not null), so switching a G/L Account or
+ * Fixed Asset line to an item type would otherwise leave a stale `accountId`/
+ * `assetId` on the row and violate the check (23514). Setting the inapplicable
+ * ids to explicit `null` clears them on update and hardens every caller (form,
+ * public API, MCP) at once.
+ */
+function normalizePurchaseOrderLineReferences<
+ T extends {
+ purchaseOrderLineType: string;
+ itemId?: string | null;
+ accountId?: string | null;
+ assetId?: string | null;
+ }
+>(line: T): T {
+ if (PURCHASE_ORDER_LINE_ITEM_TYPES.includes(line.purchaseOrderLineType)) {
+ return { ...line, accountId: null, assetId: null };
+ }
+ if (line.purchaseOrderLineType === "G/L Account") {
+ return { ...line, itemId: null, assetId: null };
+ }
+ if (line.purchaseOrderLineType === "Fixed Asset") {
+ return { ...line, itemId: null, accountId: null };
+ }
+ // Comment (and any other non-reference type) carries no reference id.
+ return { ...line, itemId: null, accountId: null, assetId: null };
+}
+
export async function upsertPurchaseOrderLine(
client: SupabaseClient<Database>,
purchaseOrderLine:
@@ -1819,11 +1860,13 @@ export async function upsertPurchaseOrderLine(
customFields?: Json;
})
) {
- if ("id" in purchaseOrderLine) {
+ const normalized = normalizePurchaseOrderLineReferences(purchaseOrderLine);
+
+ if ("id" in normalized) {
return client
.from("purchaseOrderLine")
- .update(sanitize(purchaseOrderLine))
- .eq("id", purchaseOrderLine.id)
+ .update(sanitize(normalized))
+ .eq("id", normalized.id)
.select("id")
.single();
}
@@ -1831,7 +1874,7 @@ export async function upsertPurchaseOrderLine(
const existing = await client
.from("purchaseOrderLine")
.select("sortOrder")
- .eq("purchaseOrderId", purchaseOrderLine.purchaseOrderId);
+ .eq("purchaseOrderId", normalized.purchaseOrderId);
const maxSortOrder = (existing.data ?? []).reduce(
(max, row) => Math.max(max, row.sortOrder ?? 0),
@@ -1840,7 +1883,7 @@ export async function upsertPurchaseOrderLine(
return client
.from("purchaseOrderLine")
- .insert([{ ...purchaseOrderLine, sortOrder: maxSortOrder + 1 }])
+ .insert([{ ...normalized, sortOrder: maxSortOrder + 1 }])
.select("id")
.single();
}
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 f9ed111eeb..b83eb36678 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-09-05T12:37:38.879Z",
+ "generated": "2026-09-05T14:29:16.500Z",
"totalTools": 1495,
"modules": 15,
"tools": [
diff --git a/packages/ee/src/planning/mrp/mrp.ts b/packages/ee/src/planning/mrp/mrp.ts
index 79926956b5..407cd85372 100644
--- a/packages/ee/src/planning/mrp/mrp.ts
+++ b/packages/ee/src/planning/mrp/mrp.ts
@@ -360,7 +360,11 @@ export async function runMrp(
const jobSupplyByLocationPeriodItem = new Map<string, number>();
for (const line of productionLines.data ?? []) {
- if (!line.itemId || !line.quantityToReceive) continue;
+ // locationId is part of the supplyActual primary key (hence NOT NULL) and
+ // an FK to location. A line with no location has nowhere to be planned and
+ // would write locationId="" (via the ?? "" key fallback), violating
+ // supplyActual_locationId_fkey and aborting the whole run. Skip it.
+ if (!line.itemId || !line.quantityToReceive || !line.locationId) continue;
const dueDate = line.dueDate
? parseDate(line.dueDate)
@@ -386,7 +390,9 @@ export async function runMrp(
const poSupplyByLocationPeriodItem = new Map<string, number>();
for (const line of purchaseOrderLines.data ?? []) {
- if (!line.itemId || !line.quantityToReceive) continue;
+ // See the productionLines guard above: a null locationId would write
+ // supplyActual with locationId="" and violate its FK.
+ if (!line.itemId || !line.quantityToReceive || !line.locationId) continue;
const dueDate = line.promisedDate
? parseDate(line.promisedDate)
@@ -433,7 +439,15 @@ export async function runMrp(
// jobAndPoSupplyByLocationPeriodItem below). Netting here as well would
// double-count supply and under-drive child demand.
for (const projection of demandProjections.data ?? []) {
- if (!projection.itemId || !projection.forecastQuantity) continue;
+ // locationId is part of the demandForecast primary key (hence NOT NULL)
+ // and an FK to location; a null one would write locationId="" and violate
+ // demandForecast_locationId_fkey, aborting the run.
+ if (
+ !projection.itemId ||
+ !projection.forecastQuantity ||
+ !projection.locationId
+ )
+ continue;
const netDemand = projection.forecastQuantity;
@@ -463,7 +477,9 @@ export async function runMrp(
// Sales order lines
for (const line of salesOrderLines.data ?? []) {
- if (!line.itemId || !line.quantityToSend) continue;
+ // A null locationId would write demandForecast/demandActual with
+ // locationId="" and violate their locationId FK — skip (see above).
+ if (!line.itemId || !line.quantityToSend || !line.locationId) continue;
const promiseDate = line.promisedDate
? parseDate(line.promisedDate)
@@ -499,7 +515,9 @@ export async function runMrp(
// Job material lines
for (const line of jobMaterialLines.data ?? []) {
- if (!line.itemId || !line.quantityToIssue) continue;
+ // A null locationId would write demandForecast/demandActual with
+ // locationId="" and violate their locationId FK — skip (see above).
+ if (!line.itemId || !line.quantityToIssue || !line.locationId) continue;
const dueDate = line.dueDate ? parseDate(line.dueDate) : today;
const requiredDate = dueDate.add({ days: -(line.leadTime ?? 7) });