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.

merge main

naveenkash31aacd722dd7
diff --cc .ai/rules/inventory-system.md
index 21a9085943,e64ae6025a..3113723e06
--- a/.ai/rules/inventory-system.md
+++ b/.ai/rules/inventory-system.md
@@@ -81,13 -97,9 +97,14 @@@ Relevant enums: `itemLedgerType`, `item
`customRule`→`storageRule`. Grep the NEWEST migration for the real name; never trust an older one or the
old 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 (`20260708204214`), not the
- first 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`.
+ - **`get_inventory_quantities` has many revisions.** Always read the newest (`20260713235406`), not the
+ first match. `quantityOnHand` is status-aware: `Rejected` tracked entities are excluded, and tracked
+ rows are always computed live (never from `itemLedgerSnapshot`) so status flips are never stale.
- **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 --cc apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
index 94f6a51f56,153cb4a010..c08eb363ff
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
@@@ -380,28 -349,9 +380,29 @@@ 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 ?? "") && (
+ {(itemType as readonly string[]).includes(
+ line?.purchaseOrderLineType ?? ""
+ ) && (
<DropdownMenuItem asChild>
<Link
to={getLinkToItemDetails(
diff --cc apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 0c6bec1136,1460d003e5..980ba5faad
--- 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 +1,6 @@@
{
- "generated": "2026-07-14T08:43:06.820Z",
- "totalTools": 1326,
- "generated": "2026-07-15T06:27:13.763Z",
- "totalTools": 1334,
++ "generated": "2026-07-15T13:07:53.800Z",
++ "totalTools": 1335,
"modules": 15,
"tools": [
{
diff --cc packages/database/supabase/functions/post-purchase-invoice/index.ts
index 50440a4d92,51450f46df..2c00d94af2
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@@ -13,11 -13,10 +13,14 @@@ import
type VarianceAllocation,
} from "../shared/purchase-cost-adjustment.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
- import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
+import {
+ getBillableQuantity,
+ getRemainingQuantityToInvoice,
+} from "../shared/short-close.ts";
+ import {
+ getDefaultPostingGroup,
+ resolveInventoryAccount,
+ } from "../shared/get-posting-group.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@@ -155,9 -154,9 +158,9 @@@ serve(async (req: Request) =>
const purchaseOrderLinesVoid =
affectedPurchaseOrderIdsVoid.length > 0
? await client
-- .from("purchaseOrderLine")
-- .select("*")
-- .in("purchaseOrderId", affectedPurchaseOrderIdsVoid)
++ .from("purchaseOrderLine")
++ .select("*")
++ .in("purchaseOrderId", affectedPurchaseOrderIdsVoid)
: { data: [] as Database["public"]["Tables"]["purchaseOrderLine"]["Row"][], error: null };
if (purchaseOrderLinesVoid.error)
@@@ -193,13 -192,11 +196,13 @@@
const newQuantityInvoiced = Math.max(
0,
(purchaseOrderLine.quantityInvoiced ?? 0) -
-- invoicedQuantityInPurchaseUnit
++ invoicedQuantityInPurchaseUnit
);
+ // Short-close aware: compare against the billable (received)
+ // quantity for short-closed lines, not the ordered quantity.
const invoicedComplete =
- newQuantityInvoiced >= purchaseOrderLine.purchaseQuantity;
+ newQuantityInvoiced >= getBillableQuantity(purchaseOrderLine);
acc[invoiceLine.purchaseOrderLineId] = {
quantityInvoiced: newQuantityInvoiced,
@@@ -256,7 -253,7 +259,7 @@@
Database["public"]["Tables"]["journalLine"]["Insert"],
"journalId"
>[] = accountingEnabled
-- ? originalJournalLines.data.map((entry) => ({
++ ? originalJournalLines.data.map((entry) => ({
accountId: entry.accountId,
accrual: entry.accrual,
description: `VOID: ${entry.description}`,
@@@ -269,7 -266,7 +272,7 @@@
journalLineReference: entry.journalLineReference,
companyId,
}))
-- : [];
++ : [];
const reversingItemLedger: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
originalItemLedger.data.map((entry) => ({
@@@ -283,8 -280,8 +286,8 @@@
entry.entryType === "Positive Adjmt."
? "Negative Adjmt."
: entry.entryType === "Negative Adjmt."
-- ? "Positive Adjmt."
-- : entry.entryType,
++ ? "Positive Adjmt."
++ : entry.entryType,
documentType: entry.documentType,
documentId: entry.documentId,
externalDocumentId: entry.externalDocumentId,
@@@ -722,7 -717,8 +725,7 @@@
const invoicedComplete =
purchaseOrderLine.invoicedComplete ||
invoiceLine.quantity >=
- getRemainingQuantityToInvoice(purchaseOrderLine);
- (purchaseOrderLine.quantityToInvoice ??
- purchaseOrderLine.purchaseQuantity);
++ getRemainingQuantityToInvoice(purchaseOrderLine);
return {
...acc,
@@@ -807,10 -803,10 +810,10 @@@
invoiceLine.invoiceLineType === "Comment"
? 0
: totalLinesCost === 0
-- ? postableLineCount === 0
-- ? 0
-- : 1 / postableLineCount
-- : totalLineCost / totalLinesCost;
++ ? postableLineCount === 0
++ ? 0
++ : 1 / postableLineCount
++ : totalLineCost / totalLinesCost;
const lineWeightedShippingCost =
shippingCost * lineCostPercentageOfTotalCost;
// Line cost and weighted shipping are both base currency here; the
@@@ -969,8 -977,8 +984,8 @@@
// determine the journal lines that should be reversed
const existingJournalLines = invoiceLine.purchaseOrderLineId
? journalLinesByPurchaseOrderLine[
-- invoiceLine.purchaseOrderLineId
-- ] ?? []
++ invoiceLine.purchaseOrderLineId
++ ] ?? []
: [];
let previousJournalId: number | null = null;
@@@ -1038,8 -1046,8 +1053,8 @@@
const quantityAvailableToReverseForEntry =
quantityAlreadyReversed > quantityCounted
? entry[0].quantity +
-- quantityCounted -
-- quantityAlreadyReversed
++ quantityCounted -
++ quantityAlreadyReversed
: entry[0].quantity;
const quantityRequiredToReverse =
@@@ -1134,15 -1143,15 +1150,15 @@@
const receiptLayers =
receiptIds.length > 0
? await client
-- .from("costLedger")
-- .select("id, quantity, remainingQuantity")
-- .eq("documentType", "Purchase Receipt")
-- .in("documentId", receiptIds)
-- .eq("itemId", invoiceLine.itemId!)
-- .eq("adjustment", false)
-- .eq("companyId", companyId)
-- .order("postingDate", { ascending: true })
-- .order("createdAt", { ascending: true })
++ .from("costLedger")
++ .select("id, quantity, remainingQuantity")
++ .eq("documentType", "Purchase Receipt")
++ .in("documentId", receiptIds)
++ .eq("itemId", invoiceLine.itemId!)
++ .eq("adjustment", false)
++ .eq("companyId", companyId)
++ .order("postingDate", { ascending: true })
++ .order("createdAt", { ascending: true })
: { data: [], error: null };
if (receiptLayers.error) {
throw new Error("Failed to fetch receipt cost layers");
@@@ -1340,25 -1353,49 +1360,49 @@@
journalLineReference = nanoid();
- // DR GR/IR Clearing — debit balance represents goods invoiced but not received
- journalLineInserts.push({
- accountId:
- accountDefaults.data.goodsReceivedNotInvoicedAccount,
- description: "GR/IR Clearing",
- accrual: true,
- amount: debit("liability", accrualCost),
- quantity: quantityToAccrue,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice.data?.supplierReference,
- documentLineReference: invoiceLine.purchaseOrderLineId
- ? journalReference.to.purchaseInvoice(
+ // Services are never received, so there is no GR/IR accrual to
+ // clear — expense the cost directly to indirect cost instead.
+ const isService = invoiceLine.invoiceLineType === "Service";
+
+ if (isService) {
+ // DR Indirect Cost Account
+ journalLineInserts.push({
+ accountId: accountDefaults.data.indirectCostAccount,
+ description: "Indirect Cost Account",
+ amount: debit("asset", accrualCost),
+ quantity: quantityToAccrue,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ documentLineReference: invoiceLine.purchaseOrderLineId
+ ? journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId
- )
+ invoiceLine.purchaseOrderLineId
+ )
- : null,
- journalLineReference,
- companyId,
- });
+ : null,
+ journalLineReference,
+ companyId,
+ });
+ } else {
+ // DR GR/IR Clearing — debit balance represents goods invoiced but not received
+ journalLineInserts.push({
+ accountId:
+ accountDefaults.data.goodsReceivedNotInvoicedAccount,
+ description: "GR/IR Clearing",
+ accrual: true,
+ amount: debit("liability", accrualCost),
+ quantity: quantityToAccrue,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ documentLineReference: invoiceLine.purchaseOrderLineId
+ ? journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId
- )
++ invoiceLine.purchaseOrderLineId
++ )
+ : null,
+ journalLineReference,
+ companyId,
+ });
+ }
// CR Accounts Payable
journalLineInserts.push({
@@@ -1372,8 -1409,8 +1416,8 @@@
externalDocumentId: purchaseInvoice.data?.supplierReference,
documentLineReference: invoiceLine.purchaseOrderLineId
? journalReference.to.purchaseInvoice(
-- invoiceLine.purchaseOrderLineId
-- )
++ invoiceLine.purchaseOrderLineId
++ )
: null,
journalLineReference,
companyId,
@@@ -1433,7 -1470,7 +1477,7 @@@
// Receipt was already posted — reverse the GR/IR accrual
const existingJournalLines =
journalLinesByPurchaseOrderLine[
-- invoiceLine.purchaseOrderLineId
++ invoiceLine.purchaseOrderLineId
] ?? [];
let receiptCost = 0;
@@@ -1558,8 -1595,8 +1602,8 @@@
externalDocumentId: purchaseInvoice.data?.supplierReference,
documentLineReference: invoiceLine.purchaseOrderLineId
? journalReference.to.purchaseInvoice(
-- invoiceLine.purchaseOrderLineId
-- )
++ invoiceLine.purchaseOrderLineId
++ )
: null,
journalLineReference,
companyId,
@@@ -1575,8 -1612,8 +1619,8 @@@
externalDocumentId: purchaseInvoice.data?.supplierReference,
documentLineReference: invoiceLine.purchaseOrderLineId
? journalReference.to.purchaseInvoice(
-- invoiceLine.purchaseOrderLineId
-- )
++ invoiceLine.purchaseOrderLineId
++ )
: null,
journalLineReference,
companyId,
@@@ -1651,8 -1688,8 +1695,8 @@@
externalDocumentId: purchaseInvoice.data?.supplierReference,
documentLineReference: invoiceLine.purchaseOrderLineId
? journalReference.to.purchaseInvoice(
-- invoiceLine.purchaseOrderLineId
-- )
++ invoiceLine.purchaseOrderLineId
++ )
: null,
journalLineReference,
companyId,
@@@ -1668,8 -1705,8 +1712,8 @@@
externalDocumentId: purchaseInvoice.data?.supplierReference,
documentLineReference: invoiceLine.purchaseOrderLineId
? journalReference.to.purchaseInvoice(
-- invoiceLine.purchaseOrderLineId
-- )
++ invoiceLine.purchaseOrderLineId
++ )
: null,
journalLineReference,
companyId,