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.

feat: enhance job order status handling and material shortfall calculations

naveenkashe4f0a2926450
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 92cd02072e..ce89d86261 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1073,10 +1073,17 @@ export const JOB_SUPPLY_STATUS_PRIORITY: JobStatus[] = [
export function getJobOrderStatusCategory(
status: ItemOrderStatus | undefined
): JobOrderStatusCategory | null {
+ // Already pulled into the job — procurement is moot, so this outranks all
+ // other indicators (and hides any stale PO still attached to the item).
+ if (status?.isIssued) return "issued";
+
// A still-unmet, priority-adjusted shortfall outranks the supply indicators —
// see JobOrderStatusBadge for why.
if (status?.needsOrder) return "needsOrder";
+ // Made-to-order with no job producing it yet — the make-side of needsOrder.
+ if (status?.needsJob) return "needsJob";
+
if (status?.coveredByOnHand) return "inStock";
switch (status?.status) {
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 6003ba080e..ad349874fe 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -997,10 +997,21 @@ type JobItemAvailability = {
quantityOnProductionOrder: number | null;
};
-// Per-item shortfall for one job: its remaining need (quantityToIssue) minus its
-// share of the available pool (on hand + incoming), handed out to jobs by
-// priority (job.priority ascending). Stock is shared with no per-job
-// reservation, so allocation order matters.
+// Pull-from-Inventory lines consume on-hand before other (e.g. Purchase to Order)
+// lines, matching their sourcing intent.
+function methodAllocationRank(methodType: string | null): number {
+ return methodType === "Pull from Inventory" ? 0 : 1;
+}
+
+// Per-LINE shortfall for one job. Two-level allocation of each item's available
+// pool (on hand + incoming):
+// 1. Across all active jobs by priority (job.priority ascending) — higher
+// priority jobs take their full need first.
+// 2. Within THIS job, split its share across its own BoM lines for the item
+// (Pull-from-Inventory first), so an item on multiple lines can read
+// "in stock" on one line and "needs order" on another.
+// Stock is shared with no per-job reservation, so order matters. Result is keyed
+// by jobMaterial id (the line), not item id.
export async function getJobMaterialShortfallByItem(
client: SupabaseClient<Database>,
jobId: string,
@@ -1009,12 +1020,9 @@ export async function getJobMaterialShortfallByItem(
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.
+ // on-hand stock BEFORE incoming supply. quantityOnPurchaseOrder /
+ // quantityOnProductionOrder already include planned/pending POs and planned
+ // jobs (conversion-factor applied), so incoming is taken straight from the RPC.
const onHandByItem = new Map<string, number>();
const incomingByItem = new Map<string, number>();
for (const material of materials) {
@@ -1039,7 +1047,7 @@ export async function getJobMaterialShortfallByItem(
const { data } = await client
.from("jobMaterial")
.select(
- "itemId, jobId, quantityToIssue, job!inner(priority, status, locationId)"
+ "id, itemId, jobId, methodType, quantityToIssue, job!inner(priority, status, locationId)"
)
.in("itemId", itemIds)
.eq("companyId", companyId)
@@ -1047,8 +1055,17 @@ export async function getJobMaterialShortfallByItem(
.in("job.status", ACTIVE_JOB_STATUSES)
.eq("job.locationId", locationId);
+ // Other jobs' demand is lumped per (item, job); THIS job's demand is also kept
+ // per-line so its allocation can be split across its own BoM lines.
type Demand = { jobId: string; priority: number; remaining: number };
+ type Line = {
+ materialId: string;
+ remaining: number;
+ methodType: string | null;
+ };
const demandByItem = new Map<string, Map<string, Demand>>();
+ const thisJobLinesByItem = new Map<string, Line[]>();
+
for (const row of data ?? []) {
const itemId = row.itemId;
const rowJobId = row.jobId;
@@ -1067,12 +1084,15 @@ export async function getJobMaterialShortfallByItem(
const existing = jobs.get(rowJobId);
if (existing) existing.remaining += remaining;
else jobs.set(rowJobId, { jobId: rowJobId, priority, remaining });
+
+ if (rowJobId === jobId && row.id) {
+ const lines = thisJobLinesByItem.get(itemId) ?? [];
+ lines.push({ materialId: row.id, remaining, methodType: row.methodType });
+ thisJobLinesByItem.set(itemId, lines);
+ }
}
- // Allocate each item's pools by priority (lower first): on-hand first, then
- // incoming. Record this job's shortfall and whether its whole need came from
- // on-hand (no incoming was needed → "in stock").
- const shortfallByItem: Record<string, ItemShortfall> = {};
+ const shortfallByMaterial: Record<string, ItemShortfall> = {};
for (const [itemId, jobsMap] of demandByItem) {
let onHand = onHandByItem.get(itemId) ?? 0;
let incoming = incomingByItem.get(itemId) ?? 0;
@@ -1082,14 +1102,36 @@ export async function getJobMaterialShortfallByItem(
(a.jobId < b.jobId ? -1 : a.jobId > b.jobId ? 1 : 0)
);
for (const job of jobs) {
- const fromOnHand = Math.min(job.remaining, Math.max(onHand, 0));
- onHand -= fromOnHand;
- let need = job.remaining - fromOnHand;
- const fromIncoming = Math.min(need, Math.max(incoming, 0));
- incoming -= fromIncoming;
- need -= fromIncoming;
- if (job.jobId === jobId) {
- shortfallByItem[itemId] = {
+ if (job.jobId !== jobId) {
+ // Other jobs consume their lump share off the top of the pools.
+ const fromOnHand = Math.min(job.remaining, Math.max(onHand, 0));
+ onHand -= fromOnHand;
+ const need = job.remaining - fromOnHand;
+ incoming -= Math.min(need, Math.max(incoming, 0));
+ continue;
+ }
+ // THIS job: split the remaining pool across its lines (Pull-from-Inventory
+ // first, then a stable order by material id).
+ const lines = (thisJobLinesByItem.get(itemId) ?? [])
+ .slice()
+ .sort(
+ (a, b) =>
+ methodAllocationRank(a.methodType) -
+ methodAllocationRank(b.methodType) ||
+ (a.materialId < b.materialId
+ ? -1
+ : a.materialId > b.materialId
+ ? 1
+ : 0)
+ );
+ for (const line of lines) {
+ const fromOnHand = Math.min(line.remaining, Math.max(onHand, 0));
+ onHand -= fromOnHand;
+ let need = line.remaining - fromOnHand;
+ const fromIncoming = Math.min(need, Math.max(incoming, 0));
+ incoming -= fromIncoming;
+ need -= fromIncoming;
+ shortfallByMaterial[line.materialId] = {
shortfall: need > 0 ? need : 0,
// Fully met without leaning on incoming supply.
coveredByOnHand: need <= 0 && fromIncoming === 0
@@ -1097,12 +1139,14 @@ export async function getJobMaterialShortfallByItem(
}
}
}
- return shortfallByItem;
+ return shortfallByMaterial;
}
type OrderStatusMaterial = {
itemTrackingType: string | null;
methodType: string | null;
+ estimatedQuantity: number | null;
+ quantityIssued: number | null;
};
type OrderStatusBuildMaterial = OrderStatusMaterial & {
@@ -1119,6 +1163,10 @@ function getJobMaterialOrderStatus(
shortfall: number,
coveredByOnHand: boolean
): ItemOrderStatus {
+ // Fully pulled into the job (its whole requirement has been issued/consumed).
+ const estimated = material.estimatedQuantity ?? 0;
+ const isIssued = estimated > 0 && (material.quantityIssued ?? 0) >= estimated;
+
const needsOrder =
material.itemTrackingType !== "Non-Inventory" &&
material.methodType !== "Make to Order" &&
@@ -1134,6 +1182,13 @@ function getJobMaterialOrderStatus(
supplyJobLines.some((line) => line.status === candidate)
) ?? null;
+ // A made-to-order material with no job producing it yet still needs to be made
+ // — the make-side counterpart to needsOrder.
+ const needsJob =
+ material.methodType === "Make to Order" &&
+ !isIssued &&
+ supplyJobStatus === null;
+
let ordered = 0;
let received = 0;
if (status) {
@@ -1146,10 +1201,12 @@ function getJobMaterialOrderStatus(
return {
needsOrder,
+ needsJob,
shortfall,
status,
supplyJobStatus,
coveredByOnHand,
+ isIssued,
ordered,
received
};
@@ -1161,7 +1218,7 @@ function getJobOrderStatusByMaterial(
materials: OrderStatusBuildMaterial[],
purchaseOrderLines: JobMaterialPurchaseOrderLine[],
supplyJobLines: JobMaterialSupplyJobLine[],
- shortfallByItemId: Record<string, ItemShortfall>
+ shortfallByMaterialId: Record<string, ItemShortfall>
): Record<string, ItemOrderStatus> {
const linesByItemId = new Map<string, JobMaterialPurchaseOrderLine[]>();
for (const line of purchaseOrderLines) {
@@ -1188,15 +1245,13 @@ function getJobOrderStatusByMaterial(
const jobLines = material.jobMaterialItemId
? (jobLinesByItemId.get(material.jobMaterialItemId) ?? [])
: [];
- const itemShortfall = material.jobMaterialItemId
- ? shortfallByItemId[material.jobMaterialItemId]
- : undefined;
+ const lineShortfall = shortfallByMaterialId[material.id];
byMaterialId[material.id] = getJobMaterialOrderStatus(
material,
poLines,
jobLines,
- itemShortfall?.shortfall ?? 0,
- itemShortfall?.coveredByOnHand ?? false
+ lineShortfall?.shortfall ?? 0,
+ lineShortfall?.coveredByOnHand ?? false
);
}
return byMaterialId;
@@ -1219,7 +1274,7 @@ export async function getJobOrderStatusMap(
// 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] =
+ const [purchaseOrderLines, supplyJobLines, shortfallByMaterialId] =
await Promise.all([
getJobMaterialPurchaseOrderLines(client, materials, locationId),
getJobMaterialSupplyJobLines(client, materials, companyId, locationId),
@@ -1236,7 +1291,7 @@ export async function getJobOrderStatusMap(
materials,
purchaseOrderLines,
supplyJobLines,
- shortfallByItemId
+ shortfallByMaterialId
);
}
diff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.ts
index f522c932db..2ae98251a9 100644
--- a/apps/erp/app/modules/production/types.ts
+++ b/apps/erp/app/modules/production/types.ts
@@ -124,16 +124,20 @@ export type JobStatus = Database["public"]["Enums"]["jobStatus"];
export type ItemOrderStatus = {
needsOrder: boolean;
+ needsJob: boolean;
shortfall: number;
status: PurchaseOrderStatus | null;
supplyJobStatus: JobStatus | null;
coveredByOnHand: boolean;
+ isIssued: boolean;
ordered: number;
received: number;
};
export type JobOrderStatusCategory =
+ | "issued"
| "needsOrder"
+ | "needsJob"
| "planned"
| "plannedJob"
| "awaitingApproval"
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
index c007292148..9b5d911aa0 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
@@ -201,12 +201,14 @@ const JobMaterialsTable = memo(
isArray: true,
options: [
{ value: "needsOrder", label: t`Needs ordering` },
+ { value: "needsJob", label: t`Needs job` },
{ value: "planned", label: t`Planned` },
{ value: "plannedJob", label: t`Planned job` },
{ value: "awaitingApproval", label: t`Awaiting approval` },
{ value: "onOrder", label: t`On order` },
{ value: "received", label: t`Pending` },
- { value: "inStock", label: t`In stock` }
+ { value: "inStock", label: t`In stock` },
+ { value: "issued", label: t`Issued` }
]
}
}
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobOrderStatus.tsx b/apps/erp/app/modules/production/ui/Jobs/JobOrderStatus.tsx
index 2898dce8f4..a379453c21 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobOrderStatus.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobOrderStatus.tsx
@@ -1,7 +1,13 @@
import { Tooltip, TooltipContent, TooltipTrigger } from "@carbon/react";
import { Trans } from "@lingui/react/macro";
import type { ReactNode } from "react";
-import { LuCircleAlert, LuCircleCheck, LuClock, LuStamp } from "react-icons/lu";
+import {
+ LuCircleAlert,
+ LuCircleCheck,
+ LuClock,
+ LuPackageCheck,
+ LuStamp
+} from "react-icons/lu";
import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
@@ -27,6 +33,11 @@ export function JobOrderStatusBadge({
const category = getJobOrderStatusCategory(status);
switch (category) {
+ case "issued":
+ return badge(
+ <LuPackageCheck className="text-muted-foreground" />,
+ <Trans>Issued</Trans>
+ );
case "inStock":
return badge(
<LuCircleCheck className="text-emerald-600" />,
@@ -37,6 +48,11 @@ export function JobOrderStatusBadge({
<LuCircleAlert className="text-red-500" />,
<Trans>Order {status?.shortfall} for this job</Trans>
);
+ case "needsJob":
+ return badge(
+ <LuClock className="text-red-500" />,
+ <Trans>Needs job</Trans>
+ );
case "planned":
return badge(
<TodoStatusIcon className="text-blue-600" />,
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 975efcb2bf..32d1de857e 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-25T05:27:31.359Z",
+ "generated": "2026-06-25T10:12:48.779Z",
"totalTools": 1215,
"modules": 15,
"tools": [
diff --git a/packages/database/supabase/migrations/20260625090248_job-quantity-on-hand-fanout-fix.sql b/packages/database/supabase/migrations/20260625090248_job-quantity-on-hand-fanout-fix.sql
new file mode 100644
index 0000000000..cec7569061
--- /dev/null
+++ b/packages/database/supabase/migrations/20260625090248_job-quantity-on-hand-fanout-fix.sql
@@ -0,0 +1,279 @@
+-- Fix over-counting (join fan-out) in get_job_quantity_on_hand.
+--
+-- The aggregate CTEs filtered to the job's items by joining the raw job_materials
+-- rows. When an item is on more than one BoM line those joins multiplied the
+-- aggregates: on-hand is joined twice (the total, then the in/not-storage-unit
+-- split) so it inflated ~N^2, while PO / sales-order / production supply / demand
+-- are joined once so ~N. e.g. an item on 2 lines reported 4x its real on-hand
+-- (3 -> 12). The CTEs now join deduped sets (job_material_items /
+-- job_material_item_units), so each item is counted once.
+
+DROP FUNCTION IF EXISTS get_job_quantity_on_hand;
+CREATE OR REPLACE FUNCTION get_job_quantity_on_hand(job_id TEXT, company_id TEXT, location_id TEXT)
+ RETURNS TABLE (
+ "id" TEXT,
+ "jobMaterialItemId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "itemReadableId" TEXT,
+ "name" TEXT,
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "methodType" "methodType",
+ "type" "itemType",
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "quantityPerParent" NUMERIC,
+ "estimatedQuantity" NUMERIC,
+ "quantityIssued" NUMERIC,
+ "quantityOnHandInStorageUnit" NUMERIC,
+ "quantityOnHandNotInStorageUnit" NUMERIC,
+ "quantityOnSalesOrder" NUMERIC,
+ "quantityOnPurchaseOrder" NUMERIC,
+ "quantityOnProductionOrder" NUMERIC,
+ "quantityFromProductionOrderInStorageUnit" NUMERIC,
+ "quantityFromProductionOrderNotInStorageUnit" NUMERIC,
+ "quantityInTransitToStorageUnit" NUMERIC,
+ "storageUnitId" TEXT,
+ "storageUnitName" TEXT
+ ) AS $$
+ BEGIN
+ RETURN QUERY
+
+WITH
+ job_materials AS (
+ SELECT
+ jm."id",
+ jm."itemId",
+ jm."jobMakeMethodId",
+ jm."description",
+ jm."methodType",
+ jm."quantity",
+ jm."estimatedQuantity",
+ jm."quantityIssued",
+ jm."storageUnitId"
+ FROM
+ "jobMaterial" jm
+ WHERE
+ jm."jobId" = job_id
+ ),
+ -- Distinct item / item+unit sets used to FILTER the aggregate CTEs below.
+ -- Joining the raw job_materials rows fans out (multiplies) the aggregates when
+ -- an item is on more than one BoM line — these dedupe so each item is counted
+ -- once.
+ job_material_items AS (
+ SELECT DISTINCT jm."itemId" FROM job_materials jm
+ ),
+ job_material_item_units AS (
+ SELECT DISTINCT jm."itemId", jm."storageUnitId" FROM job_materials jm
+ ),
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId" AS "purchaseOrderItemId",
+ SUM(pol."quantityToReceive" * COALESCE(pol."conversionFactor", 1)) AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = pol."itemId"
+ WHERE
+ po."status" IN (
+ 'Planned',
+ 'Needs Approval',
+ 'To Review',
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ GROUP BY pol."itemId"
+ ),
+ open_stock_transfers_to AS (
+ SELECT
+ stl."itemId",
+ stl."toStorageUnitId" AS "storageUnitId",
+ SUM(stl."outstandingQuantity") AS "quantityOnStockTransferTo"
+ FROM "stockTransferLine" stl
+ INNER JOIN "stockTransfer" st ON stl."stockTransferId" = st."id"
+ INNER JOIN job_material_items jm ON jm."itemId" = stl."itemId"
+ WHERE st."status" IN ('Released', 'In Progress')
+ AND st."companyId" = company_id
+ AND st."locationId" = location_id
+ GROUP BY stl."itemId", stl."toStorageUnitId"
+ ),
+ open_stock_transfers_from AS (
+ SELECT
+ stl."itemId",
+ stl."fromStorageUnitId" AS "storageUnitId",
+ SUM(stl."outstandingQuantity") AS "quantityOnStockTransferFrom"
+ FROM "stockTransferLine" stl
+ INNER JOIN "stockTransfer" st ON stl."stockTransferId" = st."id"
+ INNER JOIN job_material_items jm ON jm."itemId" = stl."itemId"
+ WHERE st."status" IN ('Released', 'In Progress')
+ AND st."companyId" = company_id
+ AND st."locationId" = location_id
+ GROUP BY stl."itemId", stl."fromStorageUnitId"
+ ),
+ stock_transfers_in_transit AS (
+ SELECT
+ COALESCE(stt."itemId", stf."itemId") AS "itemId",
+ COALESCE(stt."storageUnitId", stf."storageUnitId") AS "storageUnitId",
+ COALESCE(stt."quantityOnStockTransferTo", 0) - COALESCE(stf."quantityOnStockTransferFrom", 0) AS "quantityInTransit"
+ FROM open_stock_transfers_to stt
+ FULL OUTER JOIN open_stock_transfers_from stf ON stt."itemId" = stf."itemId" AND stt."storageUnitId" = stf."storageUnitId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId" AS "salesOrderItemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = sol."itemId"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ GROUP BY sol."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId" AS "jobItemId",
+ 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 (
+ SELECT
+ jm."itemId",
+ jm."storageUnitId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ INNER JOIN job_material_items jmat
+ ON jmat."itemId" = jm."itemId"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ GROUP BY jm."itemId", jm."storageUnitId"
+ ),
+ open_job_requirements_in_storage_unit AS (
+ SELECT
+ ojr."itemId",
+ SUM(ojr."quantityOnProductionDemand") AS "quantityOnProductionDemandInStorageUnit"
+ FROM open_job_requirements ojr
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = ojr."itemId" AND jm."storageUnitId" = ojr."storageUnitId"
+ GROUP BY ojr."itemId"
+ ),
+ open_job_requirements_not_in_storage_unit AS (
+ SELECT
+ ojr."itemId",
+ SUM(ojr."quantityOnProductionDemand") AS "quantityOnProductionDemandNotInStorageUnit"
+ FROM open_job_requirements ojr
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = ojr."itemId" AND (jm."storageUnitId" IS NULL OR ojr."storageUnitId" IS NULL OR jm."storageUnitId" != ojr."storageUnitId")
+ GROUP BY ojr."itemId"
+ ),
+ item_ledgers AS (
+ SELECT
+ il."itemId" AS "ledgerItemId",
+ il."storageUnitId",
+ -- quantityOnHand excludes only Rejected tracked entities. On Hold
+ -- units are still physically in the warehouse and count toward
+ -- on-hand. Rows with no tracked entity always count.
+ SUM(il."quantity") FILTER (
+ WHERE il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ ) AS "quantityOnHand"
+ FROM "itemLedger" il
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = il."itemId"
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ GROUP BY il."itemId", il."storageUnitId"
+ ),
+ item_ledgers_in_storage_unit AS (
+ SELECT
+ il."ledgerItemId",
+ SUM(il."quantityOnHand") AS "quantityOnHandInStorageUnit"
+ FROM item_ledgers il
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = il."ledgerItemId" AND jm."storageUnitId" = il."storageUnitId"
+ GROUP BY il."ledgerItemId"
+ ),
+ item_ledgers_not_in_storage_unit AS (
+ SELECT
+ il."ledgerItemId",
+ SUM(il."quantityOnHand") AS "quantityOnHandNotInStorageUnit"
+ FROM item_ledgers il
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = il."ledgerItemId" AND (jm."storageUnitId" IS NULL OR il."storageUnitId" IS NULL OR jm."storageUnitId" != il."storageUnitId")
+ GROUP BY il."ledgerItemId"
+ )
+
+SELECT
+ jm."id",
+ jm."itemId" AS "jobMaterialItemId",
+ jm."jobMakeMethodId",
+ i."readableId" AS "itemReadableId",
+ i."name",
+ jm."description",
+ i."itemTrackingType",
+ jm."methodType",
+ i."type",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ jm."quantity" as "quantityPerParent",
+ jm."estimatedQuantity",
+ jm."quantityIssued",
+ COALESCE(ils."quantityOnHandInStorageUnit", 0) AS "quantityOnHandInStorageUnit",
+ COALESCE(ilns."quantityOnHandNotInStorageUnit", 0) AS "quantityOnHandNotInStorageUnit",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(oj."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(ojis."quantityOnProductionDemandInStorageUnit", 0) AS "quantityFromProductionOrderInStorageUnit",
+ COALESCE(ojns."quantityOnProductionDemandNotInStorageUnit", 0) AS "quantityFromProductionOrderNotInStorageUnit",
+ COALESCE(stit."quantityInTransit", 0) AS "quantityInTransitToStorageUnit",
+ jm."storageUnitId",
+ s."name" AS "storageUnitName"
+FROM
+ job_materials jm
+ INNER JOIN "item" i ON i."id" = jm."itemId"
+ LEFT JOIN "storageUnit" s ON s."id" = jm."storageUnitId"
+ LEFT JOIN item_ledgers_in_storage_unit ils ON i."id" = ils."ledgerItemId"
+ LEFT JOIN item_ledgers_not_in_storage_unit ilns ON i."id" = ilns."ledgerItemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."salesOrderItemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."purchaseOrderItemId"
+ LEFT JOIN open_jobs oj ON i."id" = oj."jobItemId"
+ LEFT JOIN open_job_requirements_in_storage_unit ojis ON i."id" = ojis."itemId"
+ LEFT JOIN open_job_requirements_not_in_storage_unit ojns ON i."id" = ojns."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN stock_transfers_in_transit stit ON jm."itemId" = stit."itemId" AND jm."storageUnitId" = stit."storageUnitId";
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 9da2e29c8c..7ac7ee3f81 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -5273,6 +5273,9 @@ msgstr "Problemablauf-Workflows"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "Problemarbeitsabläufe definierten die voreingestellten Werte für ein Problem. Beispielsweise können Sie einen 8D-Arbeitsablauf oder einen Eindämmungsarbeitsablauf haben."
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "Ausstellungsdatum"
@@ -6126,6 +6129,9 @@ msgstr "Benötigen Sie die richtigen Spalten?"
msgid "Needs fixing"
msgstr "Muss behoben werden"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "Bestellung erforderlich"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 7f80acd971..c11b756679 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -5273,6 +5273,9 @@ msgstr "Issue Workflows"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
+msgid "Issued"
+msgstr "Issued"
+
msgid "Issued Date"
msgstr "Issued Date"
@@ -6126,6 +6129,9 @@ msgstr "Need the right columns?"
msgid "Needs fixing"
msgstr "Needs fixing"
+msgid "Needs job"
+msgstr "Needs job"
+
msgid "Needs ordering"
msgstr "Needs ordering"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 3bce6e3794..9221beff5b 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -5273,6 +5273,9 @@ msgstr "Flujos de trabajo de problemas"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "Los flujos de trabajo de problemas definieron los valores predeterminados para un problema. Por ejemplo, puede tener un flujo de trabajo de 8D o un flujo de trabajo de contención."
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "Fecha de Emisión"
@@ -6126,6 +6129,9 @@ msgstr "¿Necesitas las columnas correctas?"
msgid "Needs fixing"
msgstr "Necesita reparación"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "Requiere pedido"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 80baa6147d..b0a0c434be 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -5273,6 +5273,9 @@ msgstr "Flux de travail des problèmes"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "Les flux de travail de problèmes ont défini les valeurs par défaut pour un problème. Par exemple, vous pouvez avoir un flux de travail 8D ou un flux de travail de confinement."
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "Date d'émission"
@@ -6126,6 +6129,9 @@ msgstr "Besoin des bonnes colonnes ?"
msgid "Needs fixing"
msgstr "Doit être réparé"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "À commander"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 562010ba81..241cb5f9e0 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -5273,6 +5273,9 @@ msgstr "समस्या वर्कफ़्लो"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "समस्या वर्कफ़्लो ने किसी समस्या के लिए पूर्वनिर्धारित मान परिभाषित किए। उदाहरण के लिए, आपके पास 8D वर्कफ़्लो या निरोध वर्कफ़्लो हो सकता है।"
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "जारी तारीख"
@@ -6126,6 +6129,9 @@ msgstr "क्या आपको सही कॉलम चाहिए?"
msgid "Needs fixing"
msgstr "मरम्मत की आवश्यकता है"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "ऑर्डर करने की आवश्यकता"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 46cbbaca9e..8f406a2375 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -5273,6 +5273,9 @@ msgstr "Flussi di lavoro dei problemi"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "I flussi di lavoro dei problemi hanno definito i valori predefiniti per un problema. Ad esempio, puoi avere un flusso di lavoro 8D o un flusso di lavoro di contenimento."
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "Data di Emissione"
@@ -6126,6 +6129,9 @@ msgstr "Hai bisogno delle colonne giuste?"
msgid "Needs fixing"
msgstr "Necessita correzione"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "Da ordinare"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 2104829179..c123c4b87c 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -5273,6 +5273,9 @@ msgstr "問題ワークフロー"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "問題ワークフローは、問題の事前設定値を定義しました。例えば、8Dワークフローまたは封じ込めワークフローを使用できます。"
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "発行日"
@@ -6126,6 +6129,9 @@ msgstr "正しい列が必要ですか?"
msgid "Needs fixing"
msgstr "修理が必要です"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "発注が必要"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 5335ff1032..43f70e62c9 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -5273,6 +5273,9 @@ msgstr "Przepływy pracy problemów"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "Przepływy pracy problemów zdefiniowały wstępnie ustawione wartości problemu. Na przykład możesz mieć przepływ pracy 8D lub przepływ pracy zawierania."
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "Data wystawienia"
@@ -6126,6 +6129,9 @@ msgstr "Potrzebujesz odpowiednich kolumn?"
msgid "Needs fixing"
msgstr "Wymaga naprawy"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "Wymaga zamówienia"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 776a9cb558..db5e0bef23 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -5273,6 +5273,9 @@ msgstr "Fluxos de Trabalho de Problemas"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "Os fluxos de trabalho de problemas definiram os valores predefinidos para um problema. Por exemplo, você pode ter um fluxo de trabalho 8D ou um fluxo de trabalho de contenção."
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "Data de Emissão"
@@ -6126,6 +6129,9 @@ msgstr "Precisa das colunas certas?"
msgid "Needs fixing"
msgstr "Precisa de reparo"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "Requer pedido"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 3284ff1596..46bcb553ec 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -5273,6 +5273,9 @@ msgstr "Рабочие процессы проблем"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "Рабочие процессы проблем определили предустановленные значения для проблемы. Например, у вас может быть рабочий процесс 8D или рабочий процесс сдерживания."
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "Дата выпуска"
@@ -6126,6 +6129,9 @@ msgstr "Нужны правильные столбцы?"
msgid "Needs fixing"
msgstr "Требуется исправление"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "Требуется заказ"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index bdc4ef9d00..553caaa968 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -5273,6 +5273,9 @@ msgstr "İş Akışları"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "Sorun iş akışları bir sorun için önceden ayarlanmış değerleri tanımladı. Örneğin, 8D iş akışına veya kapsama iş akışına sahip olabilirsiniz."
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "Düzenlenme Tarihi"
@@ -6126,6 +6129,9 @@ msgstr "Doğru sütunlara ihtiyacınız var mı?"
msgid "Needs fixing"
msgstr "Onarılması gerekir"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "Sipariş gerekli"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 96a019b66d..d225539dd2 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -5273,6 +5273,9 @@ msgstr "问题工作流"
msgid "Issue workflows defined the preset values for an issue. For example, you can have an 8D workflow or a containment workflow."
msgstr "问题工作流定义了问题的预设值。例如,您可以有8D工作流或遏制工作流。"
+msgid "Issued"
+msgstr ""
+
msgid "Issued Date"
msgstr "签发日期"
@@ -6126,6 +6129,9 @@ msgstr "需要正确的列吗?"
msgid "Needs fixing"
msgstr "需要修复"
+msgid "Needs job"
+msgstr ""
+
msgid "Needs ordering"
msgstr "需要订购"