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.

refactor: streamline job order status logic

naveenkashf65731e7dc67
diff --git a/apps/erp/app/modules/production/jobOrderStatus.ts b/apps/erp/app/modules/production/jobOrderStatus.ts
index 81361b6313..b0c6866a39 100644
--- a/apps/erp/app/modules/production/jobOrderStatus.ts
+++ b/apps/erp/app/modules/production/jobOrderStatus.ts
@@ -71,19 +71,6 @@ export const PO_STATUS_PRIORITY: PurchaseOrderStatus[] = [
"Completed"
];
-// PO statuses whose quantity is NOT yet counted in `quantityOnPurchaseOrder`
-// (the get_job_quantity_on_hand RPC only counts 'To Receive' /
-// 'To Receive and Invoice'), but which still represent incoming supply the badge
-// treats as coverage. The shortfall allocator adds these so a planned PO is
-// handed out to the highest-priority job first — matching how planned *jobs*
-// already count (the RPC's production CTE includes 'Planned'). 'To Invoice' /
-// 'Completed' are excluded — those goods are received and already in on-hand.
-export const PENDING_PO_SUPPLY_STATUSES: PurchaseOrderStatus[] = [
- "Planned",
- "Needs Approval",
- "To Review"
-];
-
type OrderStatusMaterial = {
itemTrackingType: string | null;
methodType: string | null;
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 3d962564f8..70aeae7d7e 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -21,8 +21,7 @@ import {
getJobOrderStatusByMaterial,
type ItemOrderStatus,
type ItemShortfall,
- isJobOrderStatusHidden,
- PENDING_PO_SUPPLY_STATUSES
+ isJobOrderStatusHidden
} from "./jobOrderStatus";
import type {
deadlineTypes,
@@ -1006,13 +1005,15 @@ export async function getJobMaterialShortfallByItem(
jobId: string,
companyId: string,
locationId: string,
- materials: JobItemAvailability[],
- purchaseOrderLines: JobMaterialPurchaseOrderLine[]
+ materials: JobItemAvailability[]
): Promise<Record<string, ItemShortfall>> {
// Two pools per item, kept separate so allocation can hand out already-received
// on-hand stock BEFORE incoming supply — that's what lets a fulfilled
// high-priority job read "in stock" while a lower-priority job sharing the same
// partially-received PO reads "receiving". (The RPC repeats item-level values.)
+ // quantityOnPurchaseOrder / quantityOnProductionOrder already include
+ // planned/pending POs and planned jobs (conversion-factor applied), so incoming
+ // supply is taken straight from the RPC here.
const onHandByItem = new Map<string, number>();
const incomingByItem = new Map<string, number>();
for (const material of materials) {
@@ -1030,24 +1031,6 @@ export async function getJobMaterialShortfallByItem(
);
}
- // quantityOnPurchaseOrder (from the RPC) only counts 'To Receive' /
- // 'To Receive and Invoice'. Add planned/pending PO quantity to the incoming
- // pool so it's allocated by priority too — otherwise a planned PO covers no job
- // and every consumer shows a needs-order dot. Guarded to items the job uses.
- for (const line of purchaseOrderLines) {
- if (!line.itemId || !line.status) continue;
- if (!PENDING_PO_SUPPLY_STATUSES.includes(line.status)) continue;
- if (!incomingByItem.has(line.itemId)) continue;
- const incoming = Math.max(
- (line.purchaseQuantity ?? 0) - (line.quantityReceived ?? 0),
- 0
- );
- incomingByItem.set(
- line.itemId,
- (incomingByItem.get(line.itemId) ?? 0) + incoming
- );
- }
-
const itemIds = Array.from(onHandByItem.keys());
if (itemIds.length === 0) return {};
@@ -1131,21 +1114,20 @@ export async function getJobOrderStatusMap(
// Completed/Draft/Cancelled/Closed jobs show no procurement indicators.
if (isJobOrderStatusHidden(jobStatus)) return {};
- const [purchaseOrderLines, supplyJobLines] = await Promise.all([
- getJobMaterialPurchaseOrderLines(client, materials, locationId),
- getJobMaterialSupplyJobLines(client, materials, companyId, locationId)
- ]);
-
- // Shortfall depends on the PO lines (planned/pending PO quantity feeds the
- // allocation pool), so it runs after they're fetched.
- const shortfallByItemId = await getJobMaterialShortfallByItem(
- client,
- jobId,
- companyId,
- locationId,
- materials,
- purchaseOrderLines
- );
+ // PO lines + supply jobs drive the badge's status/supply indicators; the
+ // shortfall reads incoming supply from the RPC totals, so all three run together.
+ const [purchaseOrderLines, supplyJobLines, shortfallByItemId] =
+ await Promise.all([
+ getJobMaterialPurchaseOrderLines(client, materials, locationId),
+ getJobMaterialSupplyJobLines(client, materials, companyId, locationId),
+ getJobMaterialShortfallByItem(
+ client,
+ jobId,
+ companyId,
+ locationId,
+ materials
+ )
+ ]);
return getJobOrderStatusByMaterial(
materials,
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 36bf835238..8b853065c5 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-06-23T22:34:05.399Z",
+ "generated": "2026-06-24T06:20:49.542Z",
"totalTools": 1214,
"modules": 15,
"tools": [
@@ -15029,14 +15029,13 @@
"module": "production",
"classification": "READ",
"description": "get job material shortfall by item",
- "paramCount": 4,
+ "paramCount": 3,
"serviceParams": [
"client",
"jobId",
"companyId",
"locationId",
- "materials",
- "purchaseOrderLines"
+ "materials"
],
"injectAuth": [
"companyId"
@@ -15053,17 +15052,12 @@
"materials": {
"type": "array",
"items": {}
- },
- "purchaseOrderLines": {
- "type": "array",
- "items": {}
}
},
"required": [
"jobId",
"locationId",
- "materials",
- "purchaseOrderLines"
+ "materials"
]
}
},
diff --git a/packages/database/supabase/migrations/20260612134529_job-quantity-on-hand-null-storage-unit.sql b/packages/database/supabase/migrations/20260612134529_job-quantity-on-hand-null-storage-unit.sql
index 50e2ffaa94..e020e445d4 100644
--- a/packages/database/supabase/migrations/20260612134529_job-quantity-on-hand-null-storage-unit.sql
+++ b/packages/database/supabase/migrations/20260612134529_job-quantity-on-hand-null-storage-unit.sql
@@ -1,19 +1,19 @@
--- Fix get_job_quantity_on_hand dropping stock / demand that has no storage unit.
+-- get_job_quantity_on_hand: per-material on-hand, demand, and incoming supply for
+-- one job's materials, scoped to the job's company + location. Feeds the Materials
+-- page (on-hand/incoming/required columns) and the order-status badge/shortfall.
--
--- On-hand and production demand are split into two buckets: "in the material's
--- storage unit" and "not in it". The "not in" join used
--- (jm.storageUnitId IS NULL OR jm.storageUnitId != x.storageUnitId)
--- which, when the material IS pinned to a storage unit but the ledger/demand row
--- has a NULL storageUnitId, evaluates `'unit' != NULL` -> NULL (not true). So the
--- row matched neither bucket and silently disappeared, reporting on-hand (and
--- required) as 0. That produced false "needs ordering" flags (and false
--- "create order for N items" counts on the Materials page) for any item whose
--- stock isn't assigned to a shelf.
---
--- Fix: treat a NULL storageUnitId on the ledger/demand row as "not in the unit",
--- by adding `x.storageUnitId IS NULL OR` to both "not in storage unit" joins.
--- The "in storage unit" joins are unchanged, so storage-unit-specific columns
--- (e.g. the Materials page "On Storage Unit" indicator) keep the same behavior.
+-- This revision:
+-- 1. NULL storage unit: a ledger/demand row with NULL storageUnitId now counts in
+-- the "not in storage unit" bucket (was dropped, reporting 0 -> false
+-- "needs ordering"). Added `x.storageUnitId IS NULL OR` to both "not in" joins.
+-- 2. open_jobs (production supply): include 'Planned' jobs and scope to
+-- company + location. Was Ready/In Progress/Paused and unscoped, so planned
+-- (MRP) supply was ignored while planned demand counted, and other locations'
+-- production leaked in.
+-- 3. open_purchase_orders: include planned/pending POs ('Planned',
+-- 'Needs Approval', 'To Review') with COALESCE(conversionFactor, 1). Replaces
+-- app-side PENDING_PO_SUPPLY_STATUSES so the Incoming column and shortfall
+-- agree and the purchase-unit conversion is applied.
CREATE OR REPLACE FUNCTION get_job_quantity_on_hand(job_id TEXT, company_id TEXT, location_id TEXT)
RETURNS TABLE (
@@ -65,7 +65,7 @@ WITH
open_purchase_orders AS (
SELECT
pol."itemId" AS "purchaseOrderItemId",
- SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"
+ SUM(pol."quantityToReceive" * COALESCE(pol."conversionFactor", 1)) AS "quantityOnPurchaseOrder"
FROM
"purchaseOrder" po
INNER JOIN "purchaseOrderLine" pol
@@ -74,6 +74,9 @@ WITH
ON jm."itemId" = pol."itemId"
WHERE
po."status" IN (
+ 'Planned',
+ 'Needs Approval',
+ 'To Review',
'To Receive',
'To Receive and Invoice'
)
@@ -143,10 +146,13 @@ WITH
SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
FROM job j
WHERE j."status" IN (
+ 'Planned',
'Ready',
'In Progress',
'Paused'
)
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
GROUP BY j."itemId"
),
open_job_requirements AS (