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
feat(purchasing): implement short-close functionality for purchase order lines
naveenkashd49ee6a98ee2
diff --git a/.ai/rules/inventory-system.md b/.ai/rules/inventory-system.mdindex be00025904..21a9085943 100644--- a/.ai/rules/inventory-system.md+++ b/.ai/rules/inventory-system.md@@ -63,7 +63,7 @@ Validators in `inventory.models.ts`: `inventoryAdjustmentValidator`, `receiptVal- **`storageRule`** + assignment tables — renamed from `customRule`/`itemRule` (`20260603130000`).`get_inventory_quantities(company_id TEXT, location_id TEXT)` — the central read. Newest definition is-`20260512130000_inventory-storage-unit-filter.sql` (NOT the old-doc's 2025 migration). Returns ~52 cols:+`20260708204214_partial-gr-visibility-and-short-close.sql` (NOT the old-doc's 2025 migration). Returns ~52 cols:item identity + material props, planning fields, and quantities `quantityOnHand`, `quantityOnHold`,`quantityRejected` (status-aware: excludes `Rejected`, surfaces `On Hold`), `quantityOnSalesOrder`,`quantityOnPurchaseOrder`, `quantityOnProductionOrder`, `quantityOnProductionDemand`, `demandForecast`,@@ -81,8 +81,13 @@ Relevant enums: `itemLedgerType`, `itemLedgerDocumentType`, `trackedEntityStatus`customRule`→`storageRule`. Grep the NEWEST migration for the real name; never trust an older one or theold cache. The `shelf`→`storageUnit` rename was split across paired migrations`20260417000100` (rename, M2) + `..000300` (recreate dependents, M4) — they must apply together.-- **`get_inventory_quantities` has many revisions.** Always read the newest (`20260512130000`), not the+- **`get_inventory_quantities` has many revisions.** Always read the newest (`20260708204214`), not thefirst match. `quantityOnHand` is status-aware: `Rejected` tracked entities are excluded.+- **Short-closed PO lines don't count as incoming supply.** `get_inventory_quantities`,+ `get_job_quantity_on_hand`, and the `openPurchaseOrderLines` view (MRP) all filter open-PO supply with+ `pol."receivedComplete" = false` (`20260708204214`). A line short-closed via+ `shortClosePurchaseOrderLine` ("Stop Receiving") keeps `quantityToReceive > 0` but is excluded from+ `quantityOnPurchaseOrder`.- **The auto-generated MCP reference (`.ai/rules/mcp-tools-reference.md`) is stale** for storage units —it still lists `getShelf`/`getDefaultShelfForJob`. The real service exports `getStorageUnit*` /`getDefaultStorageUnitForJob`. Trust the service file.diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsxindex de637006e5..c2309e11a5 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx@@ -446,6 +446,12 @@ function ReceiptLineItem({const splitDisclosure = useDisclosure();const deleteDisclosure = useDisclosure();+ // Negative remaining means more was received than ordered — shown as a+ // positive "Surplus" instead of a negative "Outstanding".+ const remainingQuantity =+ (line.outstandingQuantity ?? 0) - (line.receivedQuantity ?? 0);+ const isSurplus = remainingQuantity < 0;+return (<div className={cn("flex flex-col border-b p-6 gap-6 relative", className)}><div className="absolute top-4 right-6">@@ -548,16 +554,16 @@ function ReceiptLineItem({<VStack spacing={1} className="text-center items-center"><label className="text-xs text-muted-foreground">- Outstanding+ {isSurplus ? "Surplus" : "Outstanding"}</label><HStack className="justify-center">- <span className="text-sm py-1.5">- {(line.outstandingQuantity ?? 0) -- (line.receivedQuantity ?? 0)}+ <span+ className={cn("text-sm py-1.5", isSurplus && "text-red-500")}+ >+ {Math.abs(remainingQuantity)}</span>- {(line.receivedQuantity ?? 0) >- (line.outstandingQuantity ?? 0) && (+ {isSurplus && (<Tooltip><TooltipTrigger><LuCircleAlert className="text-red-500" />diff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.mdindex 0535310e03..4bb06b5b56 100644--- a/apps/erp/app/modules/purchasing/AGENTS.md+++ b/apps/erp/app/modules/purchasing/AGENTS.md@@ -39,7 +39,7 @@ pnpm --filter @carbon/erp test| Table / View | Purpose ||---|---|-| `purchaseOrder` / `purchaseOrders` (view) | PO header: supplier, status, dates, location |+| `purchaseOrder` / `purchaseOrders` (view) | PO header: supplier, status, dates, location; view adds `receivableQuantity`/`receivedQuantity` aggregates (drives the list's Received progress bar and the derived "Partially Received" header chip — display-only, not a status enum value) || `purchaseOrderLine` | Line items: item, quantity, price, conversionFactor, jobId || `purchaseOrderDelivery` / `purchaseOrderPayment` | PO delivery and payment terms || `supplier` / `suppliers` (view) | Vendor master: name, type, status, tax info |@@ -54,6 +54,7 @@ pnpm --filter @carbon/erp test- `getPurchaseOrder` / `getPurchaseOrders` / `getPurchaseOrderLines` — read POs- `closePurchaseOrder` — marks a PO closed+- `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 `convert` edge function- `duplicatePurchaseOrder` — copies a PO with new sequence- `finalizePurchaseOrder` / `finalizeSupplierQuote` — lock documents for processingdiff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 464e2ac494..51967c2d4a 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -1793,6 +1793,65 @@ export async function updatePurchaseOrderLineOrder(});}+/**+ * Short-close ("stop receiving") or reopen a purchase order line whose+ * remaining quantity will never arrive. Sets `receivedComplete` without+ * touching quantities or pricing, then recomputes the header status from the+ * line completeness flags. Open-PO supply queries (get_inventory_quantities,+ * openPurchaseOrderLines) exclude `receivedComplete` lines, so the undelivered+ * remainder stops counting as incoming stock.+ */+export async function shortClosePurchaseOrderLine(+ db: Kysely<KyselyDatabase>,+ {+ lineId,+ purchaseOrderId,+ companyId,+ userId,+ intent+ }: {+ lineId: string;+ purchaseOrderId: string;+ companyId: string;+ userId: string;+ intent: "close" | "reopen";+ }+) {+ return db.transaction().execute(async (trx) => {+ await trx+ .updateTable("purchaseOrderLine")+ .set({+ receivedComplete: intent === "close",+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", lineId)+ .where("purchaseOrderId", "=", purchaseOrderId)+ .where("companyId", "=", companyId)+ .execute();++ const lines = await trx+ .selectFrom("purchaseOrderLine")+ .select(["purchaseOrderLineType", "invoicedComplete", "receivedComplete"])+ .where("purchaseOrderId", "=", purchaseOrderId)+ .where("companyId", "=", companyId)+ .execute();++ const { status } = getPurchaseOrderStatus(lines);++ await trx+ .updateTable("purchaseOrder")+ .set({+ status,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", purchaseOrderId)+ .where("companyId", "=", companyId)+ .execute();+ });+}+export async function upsertPurchaseOrderPayment(client: SupabaseClient<Database>,purchaseOrderPayment:diff --git a/apps/erp/app/modules/purchasing/types.ts b/apps/erp/app/modules/purchasing/types.tsindex 8f007eebc6..2d20124c27 100644--- a/apps/erp/app/modules/purchasing/types.ts+++ b/apps/erp/app/modules/purchasing/types.ts@@ -24,7 +24,14 @@ export type PurchaseOrderAttachment = FileObject; // TODO: removeexport type PurchaseOrder = NonNullable<Awaited<ReturnType<typeof getPurchaseOrders>>["data"]->[number];+>[number] & // migration 20260708204214 but the generated DB types could not be // TEMPORARY: these columns were added to the "purchaseOrders" view by+// regenerated (local dev DB was restored from a backup older than the+// checked-in types, so `pnpm db:types` would clobber unrelated types).+// Remove this intersection after rebuilding the DB and regenerating types.+{+ receivableQuantity?: number | null;+ receivedQuantity?: number | null;+};export type PurchaseOrderDelivery = NonNullable<Awaited<ReturnType<typeof getPurchaseOrderDelivery>>["data"]diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsxindex 2f75fa3cdd..636321a9f5 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx@@ -24,6 +24,8 @@ import { useMemo, useRef, useState } from "react";import {LuCirclePlus,LuEllipsisVertical,+ LuPackageCheck,+ LuPackageX,LuSettings2,LuTrash} from "react-icons/lu";@@ -36,6 +38,7 @@ import {ReorderEditBar,useLineOrderEditMode} from "~/components/LineReorder";+import { Confirm } from "~/components/Modals";import {useOptimisticLocation,usePermissions,@@ -277,7 +280,11 @@ function PurchaseOrderLineItem({if (!orderId) throw new Error("Could not find orderId");const permissions = usePermissions();const disclosure = useDisclosure();+ const receivingDisclosure = useDisclosure();const location = useOptimisticLocation();+ const orderData = useRouteData<{ purchaseOrder: PurchaseOrder }>(+ path.to.purchaseOrder(orderId)+ );useMount(() => {if (lineId === line.id) {@@ -288,6 +295,33 @@ function PurchaseOrderLineItem({const isSelected =location.pathname === path.to.purchaseOrderLine(orderId, line.id!);+ // Short close ("Stop Receiving"): settle a line whose remainder will never+ // arrive. Only receivable line types, only on a released order, and only+ // while the line still has an outstanding quantity.+ const isReceivableLineType =+ line.purchaseOrderLineType !== "Comment" &&+ line.purchaseOrderLineType !== "G/L Account";+ const hasOutstandingQuantity = (line.quantityToReceive ?? 0) > 0;+ const orderStatus = orderData?.purchaseOrder?.status ?? "";+ const canUpdate = permissions.can("update", "purchasing");+ const canStopReceiving =+ canUpdate &&+ isReceivableLineType &&+ hasOutstandingQuantity &&+ !line.receivedComplete &&+ ["To Receive", "To Receive and Invoice"].includes(orderStatus);+ const canResumeReceiving =+ canUpdate &&+ isReceivableLineType &&+ hasOutstandingQuantity &&+ !!line.receivedComplete &&+ [+ "To Receive",+ "To Receive and Invoice",+ "To Invoice",+ "Completed"+ ].includes(orderStatus);+return (<VStack spacing={0} className="border-b"><Link@@ -349,6 +383,26 @@ function PurchaseOrderLineItem({<DropdownMenuIcon icon={<LuTrash />} /><Trans>Delete Line</Trans></DropdownMenuItem>+ {(canStopReceiving || canResumeReceiving) && (+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ receivingDisclosure.onOpen();+ }}+ >+ <DropdownMenuIcon+ icon={+ canStopReceiving ? <LuPackageX /> : <LuPackageCheck />+ }+ />+ {canStopReceiving ? (+ <Trans>Stop Receiving</Trans>+ ) : (+ <Trans>Resume Receiving</Trans>+ )}+ </DropdownMenuItem>+ )}{/* @ts-expect-error */}{methodItemType.includes(line?.purchaseOrderLineType ?? "") && (<DropdownMenuItem asChild>@@ -370,6 +424,32 @@ function PurchaseOrderLineItem({</div></HStack></Link>+ {receivingDisclosure.isOpen && (+ <Confirm+ action={path.to.purchaseOrderLineReceiving(orderId, line.id!)}+ title={canStopReceiving ? t`Stop Receiving` : t`Resume Receiving`}+ text={+ canStopReceiving+ ? t`The remaining ${line.quantityToReceive} ${+ line.purchaseUnitOfMeasureCode ?? ""+ } will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged.`+ : t`The remaining ${line.quantityToReceive} ${+ line.purchaseUnitOfMeasureCode ?? ""+ } will be expected again and counted as incoming supply.`+ }+ confirmText={+ canStopReceiving ? t`Stop Receiving` : t`Resume Receiving`+ }+ onCancel={receivingDisclosure.onClose}+ onSubmit={receivingDisclosure.onClose}+ >+ <input+ type="hidden"+ name="intent"+ value={canStopReceiving ? "close" : "reopen"}+ />+ </Confirm>+ )}</VStack>);}diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsxindex 2d8adc6f76..8f2ee06ae1 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx@@ -79,6 +79,9 @@ const LineItems = ({const isGlAccount = line.purchaseOrderLineType === "G/L Account";const isFixedAsset = line.purchaseOrderLineType === "Fixed Asset";const isIndirect = isGlAccount || isFixedAsset;+ const isReceivable = !isGlAccount && (line.purchaseQuantity ?? 0) > 0;+ const quantityReceived = line.quantityReceived ?? 0;+ const quantityInvoiced = line.quantityInvoiced ?? 0;const itemReadableId = isGlAccount? line.description || "Indirect Expense": isFixedAsset@@ -228,7 +231,7 @@ const LineItems = ({<Tr><Td>Quantity</Td><Td className="text-right">- <VStack spacing={0}>+ <VStack spacing={0} className="items-end"><span>{line.purchaseQuantity}{" "}{@@ -254,10 +257,58 @@ const LineItems = ({</VStack></Td></Tr>+ {isReceivable && (+ <Tr>+ <Td>Received</Td>+ <Td className="text-right">+ <VStack spacing={0} className="items-end">+ <span>+ {quantityReceived} of {line.purchaseQuantity}{" "}+ {+ unitOfMeasures.find(+ (uom) =>+ uom.value === line.purchaseUnitOfMeasureCode+ )?.label+ }+ </span>+ {!line.receivedComplete &&+ (line.quantityToReceive ?? 0) > 0 && (+ <span className="text-muted-foreground text-xs">+ {line.quantityToReceive} remaining+ </span>+ )}+ </VStack>+ </Td>+ </Tr>+ )}+ {(line.purchaseQuantity ?? 0) > 0 && (+ <Tr>+ <Td>Invoiced</Td>+ <Td className="text-right">+ <VStack spacing={0} className="items-end">+ <span>+ {quantityInvoiced} of {line.purchaseQuantity}{" "}+ {+ unitOfMeasures.find(+ (uom) =>+ uom.value === line.purchaseUnitOfMeasureCode+ )?.label+ }+ </span>+ {!line.invoicedComplete &&+ (line.quantityToInvoice ?? 0) > 0 && (+ <span className="text-muted-foreground text-xs">+ {line.quantityToInvoice} remaining+ </span>+ )}+ </VStack>+ </Td>+ </Tr>+ )}<Tr><Td>Unit Price</Td><Td className="text-right">- <VStack spacing={0}>+ <VStack spacing={0} className="items-end"><span>{formatter.format(line.unitPrice ?? 0)}</span>{shouldConvertCurrency && (<span className="text-muted-foreground text-xs">@@ -272,7 +323,7 @@ const LineItems = ({<Tr className="border-b border-border"><Td>Extended Price</Td><Td className="text-right">- <VStack spacing={0}>+ <VStack spacing={0} className="items-end"><span>{formatter.format(lineTotal)}</span>{shouldConvertCurrency && (<span className="text-muted-foreground text-xs">@@ -290,7 +341,7 @@ const LineItems = ({Tax ({percentFormatter.format(line.taxPercent ?? 0)})</Td><Td className="text-right">- <VStack spacing={0}>+ <VStack spacing={0} className="items-end"><span>{formatter.format(line.taxAmount ?? 0)}</span>{shouldConvertCurrency && (<span className="text-muted-foreground text-xs">@@ -306,7 +357,7 @@ const LineItems = ({<Tr key="shipping" className="border-b border-border"><Td>Shipping</Td><Td className="text-right">- <VStack spacing={0}>+ <VStack spacing={0} className="items-end"><span>{formatter.format(line.shippingCost ?? 0)}</span>@@ -324,7 +375,7 @@ const LineItems = ({<Tr key="total" className="font-bold"><Td>Total</Td><Td className="text-right">- <VStack spacing={0}>+ <VStack spacing={0} className="items-end"><span>{formatter.format(total)}</span>{shouldConvertCurrency && (<span className="text-muted-foreground text-xs">diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsxindex b5362b2a86..f141c484d8 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx@@ -1,4 +1,5 @@import {+ BarProgress,Checkbox,DropdownMenuContent,DropdownMenuGroup,@@ -23,6 +24,7 @@ import {LuCreditCard,LuDollarSign,LuHandCoins,+ LuPackageCheck,LuPencil,LuQrCode,LuStar,@@ -145,6 +147,29 @@ const PurchaseOrdersTable = memo(icon: <LuStar />}},+ {+ id: "received",+ header: t`Received`,+ cell: ({ row }) => {+ const receivable = row.original.receivableQuantity ?? 0;+ const received = row.original.receivedQuantity ?? 0;+ if (receivable <= 0) return null;+ return (+ <BarProgress+ progress={(received / receivable) * 100}+ value={`${received}/${receivable}`}+ />+ );+ },+ meta: {+ filterHeader: t`Received`,+ icon: <LuPackageCheck />,+ exportValue: (row: PurchaseOrder) =>+ (row.receivableQuantity ?? 0) > 0+ ? `${row.receivedQuantity ?? 0}/${row.receivableQuantity}`+ : null+ }+ },{accessorKey: "supplierReference",header: t`Supplier Ref.`,diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 196397b3ef..9365d152d7 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-07-09T01:32:43.903Z",- "totalTools": 1263,+ "generated": "2026-07-10T08:58:33.053Z",+ "totalTools": 1264,"modules": 15,"tools": [{@@ -22049,6 +22049,43 @@]}},+ {+ "name": "purchasing_shortClosePurchaseOrderLine",+ "module": "purchasing",+ "classification": "WRITE",+ "description": "short close purchase order line",+ "paramCount": 3,+ "serviceParams": [+ "db",+ "{\n lineId,\n purchaseOrderId,\n companyId,\n userId,\n intent\n }"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "lineId": {+ "type": "string"+ },+ "purchaseOrderId": {+ "type": "string"+ },+ "intent": {+ "type": "string",+ "enum": [+ "close",+ "reopen"+ ]+ }+ },+ "required": [+ "lineId",+ "purchaseOrderId",+ "intent"+ ]+ }+ },{"name": "purchasing_upsertPurchaseOrderPayment","module": "purchasing",diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.receiving.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.receiving.tsxnew file mode 100644index 0000000000..edc90fc525--- /dev/null+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.receiving.tsx@@ -0,0 +1,118 @@+import { assertIsPost, error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { data, redirect } from "react-router";+import {+ getPurchaseOrder,+ getPurchaseOrderLine,+ shortClosePurchaseOrderLine+} from "~/modules/purchasing";+import { getDatabaseClient } from "~/services/database.server";+import { path } from "~/utils/path";++// Short-close ("Stop Receiving") or reopen a purchase order line whose+// remaining quantity will never arrive. Intentionally does NOT use+// requireUnlocked — short close only makes sense on released (locked) orders.+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "purchasing"+ });++ const { lineId, orderId } = params;+ if (!lineId) throw notFound("Could not find lineId");+ if (!orderId) throw notFound("Could not find orderId");++ const formData = await request.formData();+ const intent = formData.get("intent");+ if (intent !== "close" && intent !== "reopen") {+ return data(+ {},+ await flash(request, error(null, "Invalid receiving intent"))+ );+ }++ const [purchaseOrder, purchaseOrderLine] = await Promise.all([+ getPurchaseOrder(client, orderId),+ getPurchaseOrderLine(client, lineId)+ ]);++ if (purchaseOrder.error || purchaseOrderLine.error) {+ throw redirect(+ path.to.purchaseOrderDetails(orderId),+ await flash(+ request,+ error(+ purchaseOrder.error ?? purchaseOrderLine.error,+ "Failed to load purchase order line"+ )+ )+ );+ }++ const line = purchaseOrderLine.data;+ const status = purchaseOrder.data?.status;++ const failWith = async (message: string) =>+ redirect(+ path.to.purchaseOrderDetails(orderId),+ await flash(request, error(null, message))+ );++ if (+ ![+ "To Receive",+ "To Receive and Invoice",+ "To Invoice",+ "Completed"+ ].includes(status ?? "")+ ) {+ throw await failWith(+ "Receiving can only be closed or reopened on a released purchase order"+ );+ }+ if (+ line?.purchaseOrderId !== orderId ||+ line?.purchaseOrderLineType === "Comment" ||+ line?.purchaseOrderLineType === "G/L Account"+ ) {+ throw await failWith("This line cannot be received");+ }+ if ((line?.quantityToReceive ?? 0) <= 0) {+ throw await failWith("This line has no outstanding quantity to receive");+ }+ if (intent === "close" && line?.receivedComplete) {+ throw await failWith("Receiving is already closed for this line");+ }+ if (intent === "reopen" && !line?.receivedComplete) {+ throw await failWith("Receiving is not closed for this line");+ }++ try {+ await shortClosePurchaseOrderLine(getDatabaseClient(), {+ lineId,+ purchaseOrderId: orderId,+ companyId,+ userId,+ intent+ });+ } catch (err) {+ throw redirect(+ path.to.purchaseOrderDetails(orderId),+ await flash(request, error(err, "Failed to update line receiving"))+ );+ }++ throw redirect(+ path.to.purchaseOrderDetails(orderId),+ await flash(+ request,+ success(+ intent === "close"+ ? "Stopped receiving for line"+ : "Resumed receiving for line"+ )+ )+ );+}diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsxindex 372d01e3b0..50569a647a 100644--- a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx@@ -10,6 +10,7 @@ import {import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { getCachedPrinterConfig } from "@carbon/printing/printing.server";+import { getOverReceiptViolations } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { reconcileReceiptSerialEntities } from "~/modules/inventory";@@ -35,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const { data: lines } = await serviceRole.from("receiptLine").select(- "id, itemId, storageUnitId, receivedQuantity, locationId, receiptId, requiresSerialTracking"+ "id, itemId, storageUnitId, receivedQuantity, locationId, receiptId, requiresSerialTracking, lineId, conversionFactor").eq("receiptId", receiptId).eq("companyId", companyId);@@ -97,6 +98,41 @@ export async function action({ request, params }: ActionFunctionArgs) {Object.assign(allRuleNames, ruleNames);}+ // Over-receipt check: warn (and require acknowledgment) when posting would+ // push a PO line's received quantity past its ordered quantity. Uses the+ // live PO lines rather than the receipt's outstanding-quantity snapshot so+ // concurrent receipts are counted.+ if (receiptForSurface?.sourceDocument === "Purchase Order") {+ const purchaseOrderLineIds = [+ ...new Set(+ (lines ?? [])+ .map((l) => l.lineId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ if (purchaseOrderLineIds.length > 0) {+ const { data: purchaseOrderLines } = await serviceRole+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, quantityReceived, item(readableIdWithRevision)"+ )+ .in("id", purchaseOrderLineIds)+ .eq("companyId", companyId);++ const overReceipt = getOverReceiptViolations(+ lines ?? [],+ (purchaseOrderLines ?? []).map((line) => ({+ id: line.id,+ purchaseQuantity: line.purchaseQuantity,+ quantityReceived: line.quantityReceived,+ itemReadableId: line.item?.readableIdWithRevision+ }))+ );+ allViolations.push(...overReceipt.violations);+ Object.assign(allRuleNames, overReceipt.ruleNames);+ }+ }+const deduped = dedupeViolations(allViolations);if (deduped.length > 0 && isBlocked(deduped, acknowledged)) {return {diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex df7bd0e519..281d2ba1c8 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1494,6 +1494,8 @@ export const path = {purchaseOrderFavorite: `${x}/purchasing/orders/favorite`,purchaseOrderLine: (orderId: string, id: string) =>generatePath(`${x}/purchase-order/${orderId}/${id}/details`),+ purchaseOrderLineReceiving: (orderId: string, id: string) =>+ generatePath(`${x}/purchase-order/${orderId}/${id}/receiving`),purchaseOrderLineOrder: (orderId: string) =>generatePath(`${x}/purchase-order/${orderId}/line-order`),purchaseOrderPayment: (id: string) =>diff --git a/packages/database/supabase/migrations/20260708204214_partial-gr-visibility-and-short-close.sql b/packages/database/supabase/migrations/20260708204214_partial-gr-visibility-and-short-close.sqlnew file mode 100644index 0000000000..eae0f2e7e8--- /dev/null+++ b/packages/database/supabase/migrations/20260708204214_partial-gr-visibility-and-short-close.sql@@ -0,0 +1,668 @@+-- ============================================================+-- Partial GR visibility + per-line short close+--+-- 1. "purchaseOrders" view: add received-progress aggregates+-- (receivableQuantity / receivedQuantity over non-Comment,+-- non-G/L lines) so the PO list and header can show ordered+-- vs received without loading lines.+-- Forked verbatim from 20260702061504_fix-supplier-shipping-+-- cost-exchange-rate.sql (the newest definition) — only the+-- two aggregates and their outer-select exposure are new.+--+-- 2. Short close: a purchaseOrderLine whose remainder will never+-- arrive gets "receivedComplete" = true while quantityToReceive+-- (GENERATED purchaseQuantity - quantityReceived) stays > 0.+-- Every open-PO supply computation must stop counting such+-- lines, so add `AND pol."receivedComplete" = false` to:+-- * get_inventory_quantities (forked from 20260512130000)+-- * get_job_quantity_on_hand (forked from 20260625090248)+-- * "openPurchaseOrderLines" (forked from 20260529074512;+-- feeds MRP + purchasing planning)+-- Fully-received lines have quantityToReceive = 0, so the+-- filter only changes behavior for short-closed lines.+-- ============================================================++-- ------------------------------------------------------------+-- 1. purchaseOrders view: received-progress aggregates+-- ------------------------------------------------------------++DROP VIEW IF EXISTS "purchaseOrders";+CREATE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS+ SELECT+ p.*,+ pl."thumbnailPath",+ pl."itemType",+ pl."orderTotal" + pd."supplierShippingCost" / CASE WHEN p."exchangeRate" = 0 THEN 1 ELSE p."exchangeRate" END AS "orderTotal",+ COALESCE(pl."receivableQuantity", 0) AS "receivableQuantity",+ COALESCE(pl."receivedQuantity", 0) AS "receivedQuantity",+ pd."shippingMethodId",+ pd."shippingTermId",+ pd."receiptRequestedDate",+ pd."receiptPromisedDate",+ pd."deliveryDate",+ pd."dropShipment",+ pp."paymentTermId",+ pd."locationId",+ pd."supplierShippingCost",+ pd."incoterm",+ pd."incotermLocation",+ u."fullName" AS "createdByFullName",+ u."email" AS "createdByEmail",+ u."phone" AS "createdByPhone",+ ua."fullName" AS "assigneeFullName",+ ua."email" AS "assigneeEmail",+ ua."phone" AS "assigneePhone",+ uam."fullName" AS "accountManagerFullName",+ uam."email" AS "accountManagerEmail",+ uam."phone" AS "accountManagerPhone"+ FROM "purchaseOrder" p+ LEFT JOIN (+ SELECT+ pol."purchaseOrderId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(COALESCE(pol."purchaseQuantity", 0)*(COALESCE(pol."unitPrice", 0)) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)) AS "orderTotal",+ SUM(CASE WHEN pol."purchaseOrderLineType" NOT IN ('Comment', 'G/L Account') THEN COALESCE(pol."purchaseQuantity", 0) ELSE 0 END) AS "receivableQuantity",+ SUM(CASE WHEN pol."purchaseOrderLineType" NOT IN ('Comment', 'G/L Account') THEN COALESCE(pol."quantityReceived", 0) ELSE 0 END) AS "receivedQuantity",+ MIN(i."type") AS "itemType"+ FROM "purchaseOrderLine" pol+ LEFT JOIN "item" i+ ON i."id" = pol."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY pol."purchaseOrderId"+ ) pl ON pl."purchaseOrderId" = p."id"+ LEFT JOIN "purchaseOrderDelivery" pd ON pd."id" = p."id"+ LEFT JOIN "shippingTerm" st ON st."id" = pd."shippingTermId"+ LEFT JOIN "purchaseOrderPayment" pp ON pp."id" = p."id"+ LEFT JOIN "user" u ON u."id" = p."createdBy"+ LEFT JOIN "user" ua ON ua."id" = p."assignee"+ LEFT JOIN "supplier" s ON s."id" = p."supplierId"+ LEFT JOIN "user" uam ON uam."id" = s."accountManagerId";++-- ------------------------------------------------------------+-- 2a. openPurchaseOrderLines: exclude short-closed lines+-- ------------------------------------------------------------++CREATE OR REPLACE VIEW "openPurchaseOrderLines" WITH (security_invoker=true) AS (+ SELECT+ pol."id",+ pol."purchaseOrderId",+ po."purchaseOrderId" as "purchaseOrderReadableId",+ po."supplierId",+ pol."itemId",+ pol."quantityToReceive" * pol."conversionFactor" AS "quantityToReceive",+ i."unitOfMeasureCode",+ pol."purchaseOrderLineType",+ pol."requiredDate" AS "dueDate",+ pol."companyId",+ pol."locationId",+ po."orderDate",+ po."status",+ COALESCE(pol."promisedDate", pod."receiptPromisedDate") AS "promisedDate",+ i."replenishmentSystem",+ i."itemTrackingType",+ ir."leadTime" AS "leadTime"+ FROM "purchaseOrderLine" pol+ INNER JOIN "purchaseOrder" po ON pol."purchaseOrderId" = po."id"+ INNER JOIN "purchaseOrderDelivery" pod ON pod."id" = po."id"+ INNER JOIN "item" i ON pol."itemId" = i."id"+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"+ WHERE+ pol."purchaseOrderLineType" != 'Service'+ AND po."status" IN ('To Receive', 'To Receive and Invoice', 'Planned')+ AND pol."receivedComplete" = false+);++-- ------------------------------------------------------------+-- 2b. get_inventory_quantities: exclude short-closed lines+-- (forked verbatim from 20260512130000; only the+-- receivedComplete filter in open_purchase_orders is new)+-- ------------------------------------------------------------++DROP FUNCTION IF EXISTS get_inventory_quantities(TEXT, TEXT);++CREATE OR REPLACE FUNCTION get_inventory_quantities(company_id TEXT, location_id TEXT)+ RETURNS TABLE (+ "id" TEXT,+ "readableId" TEXT,+ "readableIdWithRevision" TEXT,+ "name" TEXT,+ "active" BOOLEAN,+ "type" "itemType",+ "itemTrackingType" "itemTrackingType",+ "replenishmentSystem" "itemReplenishmentSystem",+ "materialSubstanceId" TEXT,+ "materialFormId" TEXT,+ "dimensionId" TEXT,+ "dimension" TEXT,+ "finishId" TEXT,+ "finish" TEXT,+ "gradeId" TEXT,+ "grade" TEXT,+ "materialType" TEXT,+ "materialTypeId" TEXT,+ "thumbnailPath" TEXT,+ "unitOfMeasureCode" TEXT,+ "leadTime" INTEGER,+ "lotSize" INTEGER,+ "reorderingPolicy" "itemReorderingPolicy",+ "demandAccumulationPeriod" INTEGER,+ "demandAccumulationSafetyStock" NUMERIC,+ "reorderPoint" INTEGER,+ "reorderQuantity" INTEGER,+ "minimumOrderQuantity" INTEGER,+ "maximumOrderQuantity" INTEGER,+ "maximumInventoryQuantity" NUMERIC,+ "orderMultiple" INTEGER,+ "quantityOnHand" NUMERIC,+ "quantityOnHold" NUMERIC,+ "quantityRejected" NUMERIC,+ "quantityOnSalesOrder" NUMERIC,+ "quantityOnPurchaseOrder" NUMERIC,+ "quantityOnProductionOrder" NUMERIC,+ "quantityOnProductionDemand" NUMERIC,+ "demandForecast" NUMERIC,+ "usageLast30Days" NUMERIC,+ "usageLast90Days" NUMERIC,+ "daysRemaining" NUMERIC,+ "storageTypeIds" TEXT[],+ "storageUnitIds" TEXT[]+ ) AS $$+ BEGIN+ RETURN QUERY++WITH+ open_purchase_orders AS (+ SELECT+ pol."itemId",+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"+ FROM+ "purchaseOrder" po+ INNER JOIN "purchaseOrderLine" pol+ ON pol."purchaseOrderId" = po."id"+ WHERE+ po."status" IN (+ 'Planned',+ 'To Receive',+ 'To Receive and Invoice'+ )+ AND po."companyId" = company_id+ AND pol."locationId" = location_id+ AND pol."receivedComplete" = false+ GROUP BY pol."itemId"+ ),+ open_sales_orders AS (+ SELECT+ sol."itemId",+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"+ FROM+ "salesOrder" so+ INNER JOIN "salesOrderLine" sol+ ON sol."salesOrderId" = so."id"+ 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_job_requirements AS (+ SELECT+ jm."itemId",+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"+ FROM "jobMaterial" jm+ INNER JOIN "job" j ON jm."jobId" = j."id"+ 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"+ ),+ open_jobs AS (+ SELECT+ j."itemId",+ 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"+ ),+ item_ledgers AS (+ SELECT+ "itemId",+ SUM("quantity") FILTER (+ WHERE "trackedEntityStatus" IS NULL+ OR "trackedEntityStatus" != 'Rejected'+ ) AS "quantityOnHand",+ SUM("quantity") FILTER (WHERE "trackedEntityStatus" = 'On Hold')+ AS "quantityOnHold",+ SUM("quantity") FILTER (WHERE "trackedEntityStatus" = 'Rejected')+ AS "quantityRejected",+ SUM(CASE+ WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')+ AND "createdAt" >= CURRENT_DATE - INTERVAL '30 days'+ THEN -"quantity"+ ELSE 0+ END) / 30 AS "usageLast30Days",+ SUM(CASE+ WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')+ AND "createdAt" >= CURRENT_DATE - INTERVAL '90 days'+ THEN -"quantity"+ ELSE 0+ END) / 90 AS "usageLast90Days"+ FROM "itemLedger"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ GROUP BY "itemId"+ ),+ -- Distinct storage types the item is stocked in, joined via the storage+ -- units referenced by its ledger rows. NULL storageUnitId rows are+ -- excluded — they don't belong to any unit so they can't carry types.+ item_storage_types AS (+ SELECT+ il."itemId",+ ARRAY_AGG(DISTINCT t) AS "storageTypeIds"+ FROM "itemLedger" il+ INNER JOIN "storageUnit" su+ ON su."id" = il."storageUnitId"+ AND su."companyId" = company_id+ CROSS JOIN LATERAL unnest(su."storageTypeIds") AS t+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ GROUP BY il."itemId"+ ),+ -- Distinct storage units the item is stocked in. NULL storageUnitId rows+ -- are excluded so the array only contains real units.+ item_storage_units AS (+ SELECT+ il."itemId",+ ARRAY_AGG(DISTINCT il."storageUnitId") AS "storageUnitIds"+ FROM "itemLedger" il+ WHERE il."companyId" = company_id+ AND il."locationId" = location_id+ AND il."storageUnitId" IS NOT NULL+ GROUP BY il."itemId"+ ),+ demand_forecast AS (+ SELECT "itemId", SUM(qty) AS "demandForecast"+ FROM (+ SELECT "itemId", "actualQuantity" AS qty+ FROM "demandActual"+ WHERE "companyId" = company_id AND "locationId" = location_id+ UNION ALL+ SELECT "itemId", "forecastQuantity" AS qty+ FROM "demandForecast"+ WHERE "companyId" = company_id AND "locationId" = location_id+ ) combined+ GROUP BY "itemId"+ )++SELECT+ i."id",+ i."readableId",+ i."readableIdWithRevision",+ i."name",+ i."active",+ i."type",+ i."itemTrackingType",+ i."replenishmentSystem",+ m."materialSubstanceId",+ m."materialFormId",+ m."dimensionId",+ md."name" AS "dimension",+ m."finishId",+ mf."name" AS "finish",+ m."gradeId",+ mg."name" AS "grade",+ mt."name" AS "materialType",+ m."materialTypeId",+ CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END AS "thumbnailPath",+ i."unitOfMeasureCode",+ ir."leadTime",+ ir."lotSize",+ ip."reorderingPolicy",+ ip."demandAccumulationPeriod",+ ip."demandAccumulationSafetyStock",+ ip."reorderPoint",+ ip."reorderQuantity",+ ip."minimumOrderQuantity",+ ip."maximumOrderQuantity",+ ip."maximumInventoryQuantity",+ ip."orderMultiple",+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",+ COALESCE(il."quantityOnHold", 0) AS "quantityOnHold",+ COALESCE(il."quantityRejected", 0) AS "quantityRejected",+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand",+ COALESCE(df."demandForecast", 0) AS "demandForecast",+ COALESCE(il."usageLast30Days", 0) AS "usageLast30Days",+ COALESCE(il."usageLast90Days", 0) AS "usageLast90Days",+ CASE+ WHEN COALESCE(il."usageLast30Days", 0) > 0+ THEN ROUND(COALESCE(il."quantityOnHand", 0) / il."usageLast30Days", 2)+ ELSE NULL+ END AS "daysRemaining",+ COALESCE(ist."storageTypeIds", ARRAY[]::TEXT[]) AS "storageTypeIds",+ COALESCE(isu."storageUnitIds", ARRAY[]::TEXT[]) AS "storageUnitIds"+FROM+ "item" i+ LEFT JOIN item_ledgers il ON i."id" = il."itemId"+ LEFT JOIN item_storage_types ist ON i."id" = ist."itemId"+ LEFT JOIN item_storage_units isu ON i."id" = isu."itemId"+ LEFT JOIN open_sales_orders so ON i."id" = so."itemId"+ LEFT JOIN open_purchase_orders po ON i."id" = po."itemId"+ LEFT JOIN open_jobs jo ON i."id" = jo."itemId"+ LEFT JOIN open_job_requirements jr ON i."id" = jr."itemId"+ LEFT JOIN demand_forecast df ON i."id" = df."itemId"+ LEFT JOIN material m ON i."readableId" = m."id" AND m."companyId" = company_id+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"+ LEFT JOIN "materialFinish" mf ON m."finishId" = mf."id"+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id"+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt."id"+ LEFT JOIN "itemReplenishment" ir ON i."id" = ir."itemId" AND ir."companyId" = company_id+ LEFT JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id+WHERE+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id;+ END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++-- ------------------------------------------------------------+-- 2c. get_job_quantity_on_hand: exclude short-closed lines+-- (forked verbatim from 20260625090248; only the+-- receivedComplete filter in open_purchase_orders is new)+-- ------------------------------------------------------------++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+ AND pol."receivedComplete" = false+ 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.poindex 3628c9e210..4a6173cdcc 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -9360,6 +9360,9 @@ msgstr "Zahlung erhalten · {0} Rechnungen"msgid "Receive to Inventory"msgstr "In Bestand empfangen"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Ergebnisse"msgid "Results per page"msgstr "Ergebnisse pro Seite"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "Thesaurierte Gewinne"@@ -10975,6 +10981,9 @@ msgstr "Ausverkauft"msgid "Stop raising purchase orders after this date"msgstr "Bestellungen nach diesem Datum nicht mehr aufgeben"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "Speicherclient nicht verfügbar"@@ -11910,6 +11919,16 @@ msgstr "Die aufgezeichnete Genealogie der verfolgten Einheiten – welche Eingabmsgid "The reference data everything else hangs off. Loads first."msgstr "Die Referenzdaten, auf denen alles andere aufbaut. Wird zuerst geladen."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "Das Residualwip, das ein Auftrag bei Schließung verlassen hat, gefegt auf ein Produktionsvarianzverkehr – die einzige Varianz Carbon Bücher für einen Auftrag."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 479b6701c5..58cb349992 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -9360,6 +9360,9 @@ msgstr "Receive Payment · {0} invoices"msgid "Receive to Inventory"msgstr "Receive to Inventory"+msgid "Received"+msgstr "Received"+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Results"msgid "Results per page"msgstr "Results per page"+msgid "Resume Receiving"+msgstr "Resume Receiving"+msgid "Retained Earnings"msgstr "Retained Earnings"@@ -10975,6 +10981,9 @@ msgstr "Stockout"msgid "Stop raising purchase orders after this date"msgstr "Stop raising purchase orders after this date"+msgid "Stop Receiving"+msgstr "Stop Receiving"+msgid "Storage client not available"msgstr "Storage client not available"@@ -11910,6 +11919,16 @@ msgstr "The recorded genealogy of tracked entities — which inputs were consumemsgid "The reference data everything else hangs off. Loads first."msgstr "The reference data everything else hangs off. Loads first."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr "The remaining {0} {1} will be expected again and counted as incoming supply."++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 792c86aa0d..497f88cd50 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -9360,6 +9360,9 @@ msgstr "Recibir Pago · {0} facturas"msgid "Receive to Inventory"msgstr "Recibir al Inventario"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Resultados"msgid "Results per page"msgstr "Resultados por página"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "Ganancias retenidas"@@ -10975,6 +10981,9 @@ msgstr "Agotado"msgid "Stop raising purchase orders after this date"msgstr "Dejar de crear órdenes de compra después de esta fecha"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "Cliente de almacenamiento no disponible"@@ -11910,6 +11919,16 @@ msgstr "La genealogía registrada de entidades rastreadas - qué entradas se conmsgid "The reference data everything else hangs off. Loads first."msgstr "Los datos de referencia de los que todo lo demás depende. Se carga primero."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "El WIP residual que un trabajo ha dejado al cerrar, barrido a una cuenta de varianza de producción - la única varianza que Carbon registra para un trabajo."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 3e2aad98e0..933b748dc2 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -9360,6 +9360,9 @@ msgstr "Recevoir le paiement · {0} factures"msgid "Receive to Inventory"msgstr "Recevoir en inventaire"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Résultats"msgid "Results per page"msgstr "Résultats par page"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "Bénéfices non distribués"@@ -10975,6 +10981,9 @@ msgstr "Rupture de stock"msgid "Stop raising purchase orders after this date"msgstr "Arrêter de créer des commandes d'achat après cette date"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "Client de stockage non disponible"@@ -11910,6 +11919,16 @@ msgstr "La généalogie enregistrée des entités suivies - quelles entrées ontmsgid "The reference data everything else hangs off. Loads first."msgstr "Les données de référence sur lesquelles tout le reste repose. Se charge en premier."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "Le WIP résiduel qu'un travail a laissé à la fermeture, balayé sur un compte de variance de production - la seule variance que Carbon enregistre pour une tâche."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 92f305c537..b78049bcb9 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -9360,6 +9360,9 @@ msgstr "भुगतान प्राप्त करें · {0} चालmsgid "Receive to Inventory"msgstr "इन्वेंटरी में प्राप्त करें"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "परिणाम"msgid "Results per page"msgstr "प्रति पृष्ठ परिणाम"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "संचित मुनाफा"@@ -10975,6 +10981,9 @@ msgstr "स्टॉक समाप्त"msgid "Stop raising purchase orders after this date"msgstr "इस तारीख के बाद क्रय आदेश जारी करना बंद करें"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "स्टोरेज क्लाइंट उपलब्ध नहीं है"@@ -11910,6 +11919,16 @@ msgstr "ट्रैक किए गए इकाइयों का रिकmsgid "The reference data everything else hangs off. Loads first."msgstr "संदर्भ डेटा जिस पर सब कुछ निर्भर करता है। पहले लोड होता है।"+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "अवशिष्ट WIP जो एक काम को बंद करने पर छोड़ गया है, उत्पादन विचरण खाते में स्वेप किया गया - एक काम के लिए कार्बन पुस्तकें का एकमात्र विचरण।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex a4e1a3a772..c483f41c3f 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -9360,6 +9360,9 @@ msgstr "Ricevi Pagamento · {0} fatture"msgid "Receive to Inventory"msgstr "Ricevi in Inventario"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Risultati"msgid "Results per page"msgstr "Risultati per pagina"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "Utili non distribuiti"@@ -10975,6 +10981,9 @@ msgstr "Esaurimento scorte"msgid "Stop raising purchase orders after this date"msgstr "Smetti di creare ordini di acquisto dopo questa data"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "Client di archiviazione non disponibile"@@ -11910,6 +11919,16 @@ msgstr "La genealogia registrata delle entità monitorate - quali input sono stamsgid "The reference data everything else hangs off. Loads first."msgstr "I dati di riferimento su cui tutto il resto si basa. Caricati per primi."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "Il WIP residuo che un lavoro ha lasciato alla chiusura, spazzato via in un conto di varianza di produzione - l'unica varianza che Carbon registra per un lavoro."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex df0b1c2deb..d724ce0c3f 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -9360,6 +9360,9 @@ msgstr "支払いを受け取る · {0} 件の請求書"msgid "Receive to Inventory"msgstr "在庫に受け取る"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "結果"msgid "Results per page"msgstr "ページあたりの結果数"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "利益剰余金"@@ -10975,6 +10981,9 @@ msgstr "在庫切れ"msgid "Stop raising purchase orders after this date"msgstr "この日付以降、発注を停止します"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "ストレージクライアントが利用できません"@@ -11910,6 +11919,16 @@ msgstr "追跡されたエンティティの記録された系統 - どの入力msgid "The reference data everything else hangs off. Loads first."msgstr "参照データはすべての基盤となります。最初に読み込まれます。"+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "ジョブがクローズ時に残した残留WIP。生産差異勘定に削除されます—Carbonがジョブのために記録する唯一の差異。"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex cf56061cc5..a09fcfec16 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -9360,6 +9360,9 @@ msgstr "Otrzymaj płatność · {0} faktury"msgid "Receive to Inventory"msgstr "Odbierz do Magazynu"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Wyniki"msgid "Results per page"msgstr "Wyniki na stronę"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "Zyski zatrzymane"@@ -10975,6 +10981,9 @@ msgstr "Brak zapasów"msgid "Stop raising purchase orders after this date"msgstr "Przestań wystawiać zamówienia zakupu po tej dacie"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "Klient magazynu niedostępny"@@ -11910,6 +11919,16 @@ msgstr "Zanotowana genealogia śledzonych jednostek - które wejścia zostały zmsgid "The reference data everything else hangs off. Loads first."msgstr "Dane referencyjne, na których opiera się wszystko inne. Ładuje się jako pierwsze."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "Pozostałe WIP, które zadanie pozostawiło przy zamknięciu, zamiecione na konto wariancji produkcji - jedyna wariancja, którą Carbon rejestruje dla zadania."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex e0f3ac0344..fb81447891 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -9360,6 +9360,9 @@ msgstr "Receber Pagamento · {0} faturas"msgid "Receive to Inventory"msgstr "Receber para Inventário"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Resultados"msgid "Results per page"msgstr "Resultados por página"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "Lucros acumulados"@@ -10975,6 +10981,9 @@ msgstr "Fora de estoque"msgid "Stop raising purchase orders after this date"msgstr "Parar de criar ordens de compra após esta data"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "Cliente de armazenamento não disponível"@@ -11910,6 +11919,16 @@ msgstr "A genealogia registrada de entidades rastreadas - quais entradas foram cmsgid "The reference data everything else hangs off. Loads first."msgstr "Os dados de referência dos quais tudo o mais depende. Carrega primeiro."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "O WIP residual que um trabalho deixou no fechamento, varrido para uma conta de variância de produção - a única variância que o Carbon registra para um trabalho."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex aeb64a1bcd..f8c049966a 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -9360,6 +9360,9 @@ msgstr "Получить платеж · {0} счетов"msgid "Receive to Inventory"msgstr "Получить в инвентарь"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Результаты"msgid "Results per page"msgstr "Результатов на странице"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "Нераспределенная прибыль"@@ -10975,6 +10981,9 @@ msgstr "Отсутствие запасов"msgid "Stop raising purchase orders after this date"msgstr "Прекратить создание заказов на покупку после этой даты"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "Клиент хранилища недоступен"@@ -11910,6 +11919,16 @@ msgstr "Записанная генеалогия отслеживаемых оmsgid "The reference data everything else hangs off. Loads first."msgstr "Справочные данные, на которые опирается всё остальное. Загружаются первыми."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "Остаточное незавершенное производство, оставленное заданием при закрытии, перемещено на счет производственного отклонения — единственное отклонение, которое Carbon регистрирует для задания."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 82b93df756..feab72e134 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -9360,6 +9360,9 @@ msgstr "Ödeme Al · {0} fatura"msgid "Receive to Inventory"msgstr "Envantere Al"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "Sonuçlar"msgid "Results per page"msgstr "Sayfa başına sonuçlar"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "Biriktirilmiş kârlar"@@ -10975,6 +10981,9 @@ msgstr "Stok tükenmesi"msgid "Stop raising purchase orders after this date"msgstr "Bu tarihten sonra satın alma siparişleri vermeyi durdur"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "Depolama istemcisi kullanılamıyor"@@ -11910,6 +11919,16 @@ msgstr "İzlenen varlıkların kaydedilmiş soykütüğü - hangi girdiler hangimsgid "The reference data everything else hangs off. Loads first."msgstr "Diğer her şeyin bağlı olduğu referans veriler. Önce yüklenir."+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "Bir işin kapatmada bıraktığı artık WIP, bir üretim varyans hesabına süpürülen - Carbon'un bir iş için kaydettiği tek varyans."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 449a26e6a9..3880c18e1b 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -9360,6 +9360,9 @@ msgstr "收款 · {0} 张发票"msgid "Receive to Inventory"msgstr "接收到库存"+msgid "Received"+msgstr ""+#. placeholder {0}: status?.received#. placeholder {1}: status?.orderedmsgid "Received {0} of {1}"@@ -9710,6 +9713,9 @@ msgstr "结果"msgid "Results per page"msgstr "每页结果数"+msgid "Resume Receiving"+msgstr ""+msgid "Retained Earnings"msgstr "留存收益"@@ -10975,6 +10981,9 @@ msgstr "缺货"msgid "Stop raising purchase orders after this date"msgstr "在此日期后停止提出采购订单"+msgid "Stop Receiving"+msgstr ""+msgid "Storage client not available"msgstr "存储客户端不可用"@@ -11910,6 +11919,16 @@ msgstr "跟踪实体的记录系统 - 消费了哪些输入来生成哪些输出msgid "The reference data everything else hangs off. Loads first."msgstr "参考数据是其他一切的基础。首先加载。"+#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will be expected again and counted as incoming supply."+msgstr ""++#. placeholder {0}: line.quantityToReceive+#. placeholder {1}: line.purchaseUnitOfMeasureCode ?? ""+msgid "The remaining {0} {1} will no longer be expected. On-order supply and MRP will stop counting it. The ordered quantity and pricing are unchanged."+msgstr ""+msgid "The residual WIP a job has left at close, swept to a Production Variance account — the only variance Carbon books for a job."msgstr "工作在关闭时留下的残余在制品,扫至生产差异帐户 - Carbon为工作记录的唯一差异。"diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex 79dbb96db4..0b3ace5139 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -18,6 +18,7 @@ export * from "./labels";export * from "./llm";export * from "./math";export * from "./object";+export * from "./receiving";export * from "./ssr";export * from "./status";export * from "./status-colors";diff --git a/packages/utils/src/receiving.test.ts b/packages/utils/src/receiving.test.tsnew file mode 100644index 0000000000..10f7f7052d--- /dev/null+++ b/packages/utils/src/receiving.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from "vitest";+import { getOverReceiptViolations } from "./receiving";++describe("getOverReceiptViolations", () => {+ const poLine = (overrides = {}) => ({+ id: "pol1",+ purchaseQuantity: 20,+ quantityReceived: 0,+ itemReadableId: "CAM-01",+ ...overrides+ });++ it("returns no violations for an under-receipt", () => {+ const { violations } = getOverReceiptViolations(+ [{ lineId: "pol1", receivedQuantity: 12, conversionFactor: 1 }],+ [poLine()]+ );+ expect(violations).toHaveLength(0);+ });++ it("returns no violations for an exact receipt", () => {+ const { violations } = getOverReceiptViolations(+ [{ lineId: "pol1", receivedQuantity: 20, conversionFactor: 1 }],+ [poLine()]+ );+ expect(violations).toHaveLength(0);+ });++ it("warns when the receipt exceeds the ordered quantity", () => {+ const { violations, ruleNames } = getOverReceiptViolations(+ [{ lineId: "pol1", receivedQuantity: 25, conversionFactor: 1 }],+ [poLine()]+ );+ expect(violations).toHaveLength(1);+ expect(violations[0]?.severity).toBe("warn");+ expect(violations[0]?.ruleId).toBe("over-receipt:pol1");+ expect(violations[0]?.message).toContain("CAM-01");+ expect(violations[0]?.message).toContain("25");+ expect(violations[0]?.message).toContain("20");+ expect(ruleNames["over-receipt:pol1"]).toBe("Over Receipt");+ });++ it("counts previously received quantity toward the total", () => {+ const { violations } = getOverReceiptViolations(+ [{ lineId: "pol1", receivedQuantity: 10, conversionFactor: 1 }],+ [poLine({ quantityReceived: 12 })]+ );+ expect(violations).toHaveLength(1);+ expect(violations[0]?.message).toContain("22");+ });++ it("converts inventory units to purchase units via conversionFactor", () => {+ // 20 ordered in purchase units × factor 12 = 240 inventory units allowed.+ const exact = getOverReceiptViolations(+ [{ lineId: "pol1", receivedQuantity: 240, conversionFactor: 12 }],+ [poLine()]+ );+ expect(exact.violations).toHaveLength(0);++ const over = getOverReceiptViolations(+ [{ lineId: "pol1", receivedQuantity: 241, conversionFactor: 12 }],+ [poLine()]+ );+ expect(over.violations).toHaveLength(1);+ });++ it("does not flag float artifacts from unit conversion", () => {+ const { violations } = getOverReceiptViolations(+ [{ lineId: "pol1", receivedQuantity: 6, conversionFactor: 3 }],+ [poLine({ purchaseQuantity: 2 })]+ );+ expect(violations).toHaveLength(0);+ });++ it("sums multiple receipt lines pointing at the same purchase order line", () => {+ const { violations } = getOverReceiptViolations(+ [+ { lineId: "pol1", receivedQuantity: 12, conversionFactor: 1 },+ { lineId: "pol1", receivedQuantity: 10, conversionFactor: 1 }+ ],+ [poLine()]+ );+ expect(violations).toHaveLength(1);+ });++ it("ignores receipt lines without a purchase order line reference", () => {+ const { violations } = getOverReceiptViolations(+ [{ lineId: null, receivedQuantity: 100, conversionFactor: 1 }],+ [poLine()]+ );+ expect(violations).toHaveLength(0);+ });++ it("treats a missing or zero conversion factor as 1", () => {+ const { violations } = getOverReceiptViolations(+ [{ lineId: "pol1", receivedQuantity: 25, conversionFactor: 0 }],+ [poLine()]+ );+ expect(violations).toHaveLength(1);+ });+});diff --git a/packages/utils/src/receiving.ts b/packages/utils/src/receiving.tsnew file mode 100644index 0000000000..f15672ad8a--- /dev/null+++ b/packages/utils/src/receiving.ts@@ -0,0 +1,68 @@+import type { Violation } from "./storage-rules";++export type OverReceiptReceiptLine = {+ lineId: string | null;+ receivedQuantity: number | null;+ conversionFactor: number | null;+};++export type OverReceiptPurchaseOrderLine = {+ id: string;+ purchaseQuantity: number | null;+ quantityReceived: number | null;+ itemReadableId?: string | null;+};++/**+ * Receipt lines are in inventory units; purchase order lines are in purchase+ * units. Incoming quantity is converted with `receivedQuantity /+ * conversionFactor` (the same math post-receipt uses when advancing+ * `quantityReceived`) before comparing against the ordered quantity. Returns+ * `severity: "warn"` violations so the post action's acknowledge flow lets the+ * user confirm and proceed.+ */+export function getOverReceiptViolations(+ receiptLines: OverReceiptReceiptLine[],+ purchaseOrderLines: OverReceiptPurchaseOrderLine[]+): { violations: Violation[]; ruleNames: Record<string, string> } {+ const incomingByLine = new Map<string, number>();+ for (const line of receiptLines) {+ if (!line.lineId) continue;+ const quantityInPurchaseUnits =+ (line.receivedQuantity ?? 0) / (line.conversionFactor || 1);+ incomingByLine.set(+ line.lineId,+ (incomingByLine.get(line.lineId) ?? 0) + quantityInPurchaseUnits+ );+ }++ const round = (value: number) => Math.round(value * 100000) / 100000;++ const violations: Violation[] = [];+ const ruleNames: Record<string, string> = {};+ for (const poLine of purchaseOrderLines) {+ const incoming = incomingByLine.get(poLine.id);+ if (!incoming || incoming <= 0) continue;++ const ordered = poLine.purchaseQuantity ?? 0;+ const alreadyReceived = poLine.quantityReceived ?? 0;+ const total = alreadyReceived + incoming;+ // Small tolerance so float artifacts from unit conversion don't flag an+ // exact receipt as over.+ if (total > ordered + 1e-6) {+ const ruleId = `over-receipt:${poLine.id}`;+ violations.push({+ ruleId,+ severity: "warn",+ message: `${poLine.itemReadableId ?? "Line"}: receiving ${round(+ incoming+ )} would bring the total received to ${round(total)} of ${round(+ ordered+ )} ordered`+ });+ ruleNames[ruleId] = "Over Receipt";+ }+ }++ return { violations, ruleNames };+}