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: BoM replenishment system, purchasing UoM, and MES issue/kanban fixes (#1565)

Brad Barbina4a8b1212cfe
diff --git a/.ai/research/inventory-count-variance-account.md b/.ai/research/inventory-count-variance-account.md
new file mode 100644
index 0000000000..3b32c2e118
--- /dev/null
+++ b/.ai/research/inventory-count-variance-account.md
@@ -0,0 +1,196 @@
+# Inventory Count Adjustment GL Posting Research: Best Practices Survey
+
+## Summary
+
+Question: when posting the accounting journal for a physical/cycle inventory
+count adjustment, should the offsetting entry go to a **dedicated inventory
+variance / adjustment / shrinkage account**, or straight against the raw
+material / finished goods (inventory asset) account?
+
+Across every ERP surveyed — SAP S/4HANA, NetSuite, Dynamics 365 Business
+Central, QuickBooks Online, and Fishbowl — the common pattern is the same: the
+inventory asset account is **one** leg of the journal, and the recommended
+**offset is a dedicated P&L (COGS-type) variance/adjustment account**, not a
+second inventory-asset line. This is each product's default or recommended
+configuration, not a hard-coded universal rule — the offset is typically a
+configurable account (NetSuite exposes a transaction-level Adjustment Account;
+Business Central resolves an Inventory Adjmt. Account through configurable
+posting setups), and specific defaults/capabilities vary by product and version.
+Routing the offset back into the inventory account would net the journal to zero
+and destroy the ability to analyse shrinkage. **Carbon's own policy already
+follows this pattern** — it posts DR/CR against the inventory asset
+(`rawMaterialsAccount`/`finishedGoodsAccount`) and a dedicated
+`inventoryAdjustmentVarianceAccount`. No change is required; this note documents
+that Carbon's behaviour matches the common industry pattern and captures the one
+genuine design choice (whether to split gains vs. losses).
+
+## Competitors Surveyed
+
+- **SAP S/4HANA (MM Inventory Management)** — reference enterprise pattern for
+ automatic account determination.
+- **NetSuite** — mid-market cloud ERP; closest analogue to Carbon's model.
+- **Dynamics 365 Business Central** — posting-group-matrix account determination.
+- **QuickBooks Online** — SMB baseline; adjustment posts to a selected
+ (auto-created "Inventory Shrinkage") account. Desktop is not covered by the
+ cited source.
+- **Fishbowl Inventory** — inventory sub-ledger that syncs journals to QB/Xero;
+ part-type + per-part account mapping, plus a distinct Scrap account.
+
+## Key Consensus Patterns
+
+### 1. Offset is a dedicated P&L variance account, NOT the inventory asset
+
+Every system posts a **two-line balanced journal**: inventory asset on one side,
+a dedicated variance/adjustment/shrinkage account (P&L, COGS-type) on the other.
+
+- **SAP**: stock account (event key **BSX**, the raw-material / finished-goods
+ GL account) vs. offset **GBB + general modification INV** —
+ "expenditure/income from inventory differences," an explicit P&L account. Not
+ PRD (price differences), not AUM (stock transfer).
+- **NetSuite**: item's **Inventory Asset** account vs. a transaction-selected
+ **Adjustment Account** — guidance says a dedicated expense account (Inventory
+ Adjustment Expense / Shrinkage / Scrap), explicitly *not* the asset account.
+- **Business Central**: **Inventory Account** (Inventory Posting Setup) vs.
+ **Inventory Adjmt. Account** (General Posting Setup), set up as a COGS-type
+ account.
+- **QuickBooks**: **Inventory Asset** vs. **Inventory Shrinkage** (auto-created,
+ COGS-adjacent).
+- **Fishbowl**: **Inventory (asset)** vs. a mapped **Inventory Adjustment**
+ account (and a separate **Scrap** account for scrapped goods).
+- **Rationale**: the whole point of a count adjustment is to recognise a **loss
+ or gain in the P&L**. If the offset were the inventory asset, the journal would
+ self-cancel and no expense/income would ever be recognised. A dedicated account
+ also makes shrinkage a first-class, analysable line — reportable, dimensioned,
+ and separable by reason.
+
+### 2. Gains vs. losses use ONE account by default; direction is the debit/credit sign
+
+Every system uses a **single** variance account for both directions out of the
+box and flips the debit/credit side based on the sign of the quantity delta.
+
+- Gain / found stock (positive): **DR Inventory asset, CR Variance** (income/contra).
+- Loss / short (negative): **CR Inventory asset, DR Variance** (expense).
+
+Splitting gains and losses into separate GL accounts is available but opt-in:
+
+- **SAP**: GBB/INV has separate Debit and Credit account slots in OBYC — same
+ account by default, separable by configuration.
+- **NetSuite**: commonly routed via reason codes to a "Gain / Other Income"
+ account vs. an "Expense / Shrinkage" account, but not by default.
+- **BC / QuickBooks / Fishbowl**: single account, direction by sign; no default
+ gain/loss split.
+
+### 3. Account determination is data-driven, keyed on the item — not hardcoded
+
+None hardcode the accounts; each resolves them from configuration keyed (at
+least partly) on the item.
+
+- **SAP**: material's **valuation class** → OBYC → GBB/INV → GL account, scoped by
+ valuation grouping code (plant/company).
+- **NetSuite**: per-transaction Adjustment Account, optionally defaulted by
+ **location** or a **reason code → account** map. Inventory asset comes from the
+ item master.
+- **Business Central**: **General Posting Setup** keyed on
+ **Gen. Bus. Posting Group × Gen. Prod. Posting Group** (item carries the prod.
+ group).
+- **QuickBooks**: single per-transaction account with a default (auto-created
+ Inventory Shrinkage).
+- **Fishbowl**: **part-type default mapping** + optional **per-part overrides**,
+ plus a distinct Scrap account.
+
+## Answers to Research Questions
+
+1. **Offset = dedicated variance account or the inventory asset?** — Dedicated
+ variance/adjustment (P&L, COGS-type) account. Unanimous across SAP, NetSuite,
+ BC, QuickBooks, Fishbowl. Never a second inventory-asset line.
+
+2. **Is the offset ever the inventory asset itself?** — No. That would net to
+ zero and recognise no gain/loss. Explicitly warned against in NetSuite guidance.
+
+3. **How is the variance account configured?** — Data-driven, keyed on the item
+ (valuation class / posting group / part type) and/or per-transaction
+ selection, sometimes with reason-code or location defaults. Never hardcoded.
+
+4. **Gains vs. losses — separate accounts?** — One account by default, direction
+ by debit/credit sign. Separate gain/loss accounts are an opt-in configuration
+ in every system (SAP's dual OBYC slots; NetSuite reason codes).
+
+5. **Standard terminology?** — SAP: "inventory differences,"
+ "expenditure/income from inventory differences." NetSuite: "Adjustment
+ Account," "variance," "shrinkage." BC: "Inventory Adjmt. Account." QuickBooks:
+ "Inventory Shrinkage." Common thread: **variance / adjustment / shrinkage**.
+
+## Carbon — Current State (grounded in code)
+
+**Carbon already implements the industry-standard model.** The shared write path
+`shared/post-adjustment.ts` → `bookAdjustment()` posts a balanced two-line
+journal for every valued count/adjustment movement (when `accountingEnabled` and
+the movement has non-zero value):
+
+- **Inventory asset leg**: `resolveInventoryAccount()`
+ (`shared/get-posting-group.ts`) picks by the item's `replenishmentSystem` —
+ `Make` / `Buy and Make` → `finishedGoodsAccount` (1220), else
+ `rawMaterialsAccount` (1210).
+- **Offset leg**: `inventoryAdjustmentVarianceAccount` (a dedicated variance
+ expense account). Scrap/NCR/inspection write-offs override the offset to
+ `scrapAccount` (falling back to the variance account).
+- **Direction** (`isGain = quantity > 0`): positive → DR asset / CR variance;
+ negative → CR asset / DR variance. Amount = carrying/COGS value of the delta.
+- **Account source**: flat per-company `accountDefault` row (posting-group
+ matrix was deliberately dropped in `20260229000000_drop-posting-groups.sql`,
+ consistent with Carbon's "no matrix config" principle).
+- Both `post-inventory-count` (one shared journal per count, snapshot-delta) and
+ `post-inventory-adjustment` route through the same core, and each line is
+ tagged with Item / ItemPostingGroup / Location dimensions.
+
+Relevant files:
+- `packages/database/supabase/functions/shared/post-adjustment.ts:348-388`
+- `packages/database/supabase/functions/shared/get-posting-group.ts:18-34`
+- `packages/database/supabase/functions/post-inventory-count/index.ts`
+- `packages/database/supabase/functions/post-inventory-adjustment/index.ts:345-360`
+- Schema: `20260713190909_raw-materials-finished-goods-accounts.sql`,
+ `20260726012013_add_scrap_account.sql`
+
+## Recommended Approach for Carbon
+
+1. **Keep the current model — it is correct.** The offset already goes to a
+ dedicated `inventoryAdjustmentVarianceAccount`, matching SAP's GBB/INV,
+ NetSuite's Adjustment Account, BC's Inventory Adjmt. Account, and QuickBooks'
+ Inventory Shrinkage. Do **not** change it to post the offset against
+ raw material / finished goods — that would net to zero and recognise no
+ gain/loss, and no surveyed ERP does that.
+
+2. **The one genuine design choice: gain vs. loss split.** Carbon uses a single
+ variance account for both directions, which is the default everywhere. If
+ accountants ask to see inventory *gains* separately from *losses/shrinkage*,
+ the standard move is an optional second account (e.g. keep
+ `inventoryAdjustmentVarianceAccount` for losses, add an
+ `inventoryAdjustmentGainAccount` selected when `isGain`). This is opt-in in
+ every ERP — only add it if a customer requests it; the current single-account
+ behaviour is fully standard-conformant. Follows SAP's dual-slot GBB/INV and
+ NetSuite's gain/loss reason-code pattern.
+
+3. **Scrap already has its own account** (`scrapAccount`), mirroring Fishbowl's
+ distinct Scrap vs. Adjustment split and NetSuite's Scrap Inventory account —
+ good, keep it.
+
+4. **No posting-group matrix.** Carbon's flat `accountDefault` (item drives the
+ asset-account split via `replenishmentSystem`) is the deliberate design and
+ aligns with the project's "no matrix config" principle; BC's posting-group
+ matrix is the more complex alternative and is not recommended here.
+
+## Sources
+
+- SAP — Accounting entries for movement types 701 & 702: https://community.sap.com/t5/enterprise-resource-planning-q-a/accounting-entries-for-movement-types-701-702/qaq-p/3408376
+- SAP — Accounting entries during physical inventory count: https://community.sap.com/t5/enterprise-resource-planning-q-a/accounting-entries-during-physical-inventory-count/qaq-p/8204057
+- SAP — Account determination (GBB/INV) in S/4HANA MM: https://blog.sap-press.com/cross-functional-customizing-in-sap-s4hana-mm-account-determination-configuration
+- SAP — OBYC GBB general modification: https://community.sap.com/t5/enterprise-resource-planning-q-a/obyc-transaction-gbb-general-modification-how-to-create/qaq-p/3125701
+- NetSuite — Inventory Adjustment: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_0817101055.html
+- NetSuite — Inventory Count: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2296970.html
+- NetSuite — Adjustment reason codes (RSM): https://technologyblog.rsmus.com/technologies/netsuite/how-to-set-up-inventory-adjustment-reason-codes-in-netsuite/
+- NetSuite — Shrinkage: https://www.netsuite.com/portal/resource/articles/inventory-management/shrinkage.shtml
+- Business Central — General Posting Setup inventory fields: https://usedynamics.com/business-central/finance/fields-for-inventory-in-the-general-posting-setup/
+- Business Central — Count, adjust, reclassify inventory: https://learn.microsoft.com/en-us/dynamics365/business-central/inventory-how-count-adjust-reclassify
+- QuickBooks — Adjust inventory quantity on hand: https://quickbooks.intuit.com/learn-support/en-us/help-article/inventory-quantity/adjust-inventory-quantity-hand-quickbooks-online/L6O3QhOEZ_US_en_US
+- Fishbowl — inventory adjustments guide (TaraByte): https://blog.tarabyte.com/blog/oops-vs-ugh-a-guide-to-inventory-adjustments-for-fishbowl-inventory
+- Fishbowl & QuickBooks Online integration: https://www.fishbowlinventory.com/integrations/quickbooks-online
diff --git a/apps/erp/app/components/BoMExplorer/BoMExplorer.tsx b/apps/erp/app/components/BoMExplorer/BoMExplorer.tsx
index 46c31d831b..6d2ed7e0a7 100644
--- a/apps/erp/app/components/BoMExplorer/BoMExplorer.tsx
+++ b/apps/erp/app/components/BoMExplorer/BoMExplorer.tsx
@@ -34,7 +34,12 @@ import { useOptimisticLocation, useQuantityFormatter } from "~/hooks";
import { useIntegrations } from "~/hooks/useIntegrations";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import { generateBomIds } from "~/utils/bom";
-import { MethodIcon, MethodItemTypeIcon, OnshapeStatus } from "../Icons";
+import {
+ MethodIcon,
+ MethodItemTypeIcon,
+ OnshapeStatus,
+ ReplenishmentSystemIcon
+} from "../Icons";
import type { FlatTree, FlatTreeItem, NodeState } from "../TreeView";
import { LevelLine, TreeView, useTree } from "../TreeView";
@@ -57,6 +62,7 @@ export type BoMExplorerNodeData = {
unitOfMeasureCode?: string | null;
externalId?: unknown;
isPickDescendant?: boolean | null;
+ replenishmentSystem?: string | null;
};
type BoMNode = FlatTreeItem<BoMExplorerNodeData>;
@@ -625,6 +631,17 @@ function BoMNodePreview({ node }: { node: BoMNode }) {
<span>{node.data.itemType}</span>
</HStack>
</VStack>
+ {node.data.replenishmentSystem && (
+ <VStack spacing={1}>
+ <span className="text-xs text-muted-foreground font-medium">
+ <Trans>Replenishment System</Trans>
+ </span>
+ <HStack className="w-full">
+ <ReplenishmentSystemIcon type={node.data.replenishmentSystem} />
+ <span>{node.data.replenishmentSystem}</span>
+ </HStack>
+ </VStack>
+ )}
{node.data.methodType === "Make to Order" &&
node.data.version != null && (
<VStack spacing={1}>
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index d08321a4b3..7020cdf42e 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -3682,13 +3682,41 @@ export async function upsertItemPlanning(
export async function upsertItemPurchasing(
client: SupabaseClient<Database>,
itemPurchasing: z.infer<typeof itemPurchasingValidator> & {
+ companyId: string;
updatedBy: string;
}
) {
+ const { companyId, ...update } = itemPurchasing;
+
+ // `purchasingUnitOfMeasureCode` and `conversionFactor` are a property of the
+ // preferred supplier's supplierPart, not free-form input — the form submits
+ // them only as (client-derived) hidden fields. Re-derive them server-side so
+ // a forged submission can't persist a conversion factor that disagrees with
+ // the supplier part (which drives PO quantities and costs). The
+ // ("itemId","supplierId","companyId") unique constraint makes the lookup
+ // single; `.single()` rejects a preferred supplier with no matching part.
+ if (update.preferredSupplierId) {
+ const supplierPart = await client
+ .from("supplierPart")
+ .select("supplierUnitOfMeasureCode, conversionFactor")
+ .eq("companyId", companyId)
+ .eq("itemId", update.itemId)
+ .eq("supplierId", update.preferredSupplierId)
+ .single();
+ if (supplierPart.error) return supplierPart;
+ update.purchasingUnitOfMeasureCode =
+ supplierPart.data.supplierUnitOfMeasureCode ?? undefined;
+ update.conversionFactor = supplierPart.data.conversionFactor ?? 1;
+ } else {
+ // No preferred supplier → identity conversion, no purchasing UoM override.
+ update.purchasingUnitOfMeasureCode = undefined;
+ update.conversionFactor = 1;
+ }
+
return client
.from("itemReplenishment")
- .update(sanitize(itemPurchasing))
- .eq("itemId", itemPurchasing.itemId);
+ .update(sanitize(update))
+ .eq("itemId", update.itemId);
}
export async function upsertItemSupersession(
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPurchasingForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemPurchasingForm.tsx
index bfab0dbc7c..4f816a5ae1 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPurchasingForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPurchasingForm.tsx
@@ -15,27 +15,22 @@ import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { Link, useParams } from "react-router";
import type { z } from "zod";
-import {
- ConversionFactor,
- Hidden,
- Number,
- Submit,
- UnitOfMeasure
-} from "~/components/Form";
-import { usePermissions, useRouteData } from "~/hooks";
+import { Hidden, Number, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
import { useSuppliers } from "~/stores/suppliers";
-import { path } from "~/utils/path";
import { itemPurchasingValidator } from "../../items.models";
-import type { PartSummary } from "../../types";
+import type { SupplierPart } from "../../types";
type ItemPurchasingFormProps = {
initialValues: z.infer<typeof itemPurchasingValidator>;
allowedSuppliers?: string[];
+ supplierParts?: SupplierPart[];
};
const ItemPurchasingForm = ({
initialValues,
- allowedSuppliers
+ allowedSuppliers,
+ supplierParts
}: ItemPurchasingFormProps) => {
const permissions = usePermissions();
const { t } = useLingui();
@@ -56,14 +51,18 @@ const ItemPurchasingForm = ({
[] as { label: string; value: string }[]
);
- const routeData = useRouteData<{ partSummary: PartSummary }>(
- path.to.part(itemId)
- );
+ // Purchasing unit of measure and conversion factor are not editable here —
+ // they are pulled from the preferred supplier's supplier part record.
+ const [preferredSupplierId, setPreferredSupplierId] = useState<
+ string | undefined
+ >(initialValues.preferredSupplierId ?? undefined);
- const inventoryCode = routeData?.partSummary?.unitOfMeasureCode;
- const [purchasingCode, setPurchasingCode] = useState<string | null>(
- initialValues.purchasingUnitOfMeasureCode ?? null
+ const preferredSupplierPart = supplierParts?.find(
+ (sp) => sp.supplierId === preferredSupplierId
);
+ const purchasingUnitOfMeasureCode =
+ preferredSupplierPart?.supplierUnitOfMeasureCode ?? "";
+ const conversionFactor = preferredSupplierPart?.conversionFactor ?? 1;
return (
<Card>
@@ -79,12 +78,20 @@ const ItemPurchasingForm = ({
</CardHeader>
<CardContent>
<Hidden name="itemId" />
+ <Hidden
+ name="purchasingUnitOfMeasureCode"
+ value={purchasingUnitOfMeasureCode}
+ />
+ <Hidden name="conversionFactor" value={conversionFactor} />
<div className="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4 w-full">
<Select
name="preferredSupplierId"
label={t`Preferred Supplier`}
termId="item-preferred-supplier"
options={allowedSuppliersOptions}
+ onChange={(newValue) =>
+ setPreferredSupplierId(newValue?.value ?? undefined)
+ }
emptyMessage={
<FieldEmptyState
title={<Trans>No suppliers yet</Trans>}
@@ -104,21 +111,6 @@ const ItemPurchasingForm = ({
label={t`Lead Time (Days)`}
termId="item-purchasing-lead-time"
/>
- <UnitOfMeasure
- name="purchasingUnitOfMeasureCode"
- label={t`Purchasing Unit of Measure`}
- termId="item-purchasing-uom"
- onChange={(newValue) => {
- if (newValue) setPurchasingCode(newValue.value);
- }}
- />
- <ConversionFactor
- name="conversionFactor"
- isReadOnly={!purchasingCode || !inventoryCode}
- purchasingCode={purchasingCode ?? undefined}
- inventoryCode={inventoryCode ?? undefined}
- termId="conversion-factor"
- />
{/* <Boolean name="purchasingBlocked" label={t`Purchasing Blocked`} /> */}
</div>
</CardContent>
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 3f69603932..b0db755c74 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-09-03T15:31:57.926Z",
+ "generated": "2026-09-03T20:26:47.954Z",
"totalTools": 1495,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.tsx
index 2619ea5ddc..b134a37986 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.tsx
@@ -53,7 +53,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -72,6 +72,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateConsumablePurchasing = await upsertItemPurchasing(client, {
...validation.data,
itemId,
+ companyId,
updatedBy: userId
});
if (updateConsumablePurchasing.error) {
@@ -126,6 +127,7 @@ export default function ConsumablePurchasingRoute() {
allowedSuppliers={
supplierParts.map((s) => s.supplierId).filter(Boolean) as string[]
}
+ supplierParts={supplierParts}
/>
<SupplierParts
supplierParts={supplierParts}
diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.tsx
index 767c1cf774..0bad13f8cf 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.tsx
@@ -55,7 +55,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -74,6 +74,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateMaterialPurchasing = await upsertItemPurchasing(client, {
...validation.data,
itemId,
+ companyId,
updatedBy: userId
});
if (updateMaterialPurchasing.error) {
@@ -131,6 +132,7 @@ export default function MaterialPurchasingRoute() {
allowedSuppliers={
supplierParts.map((s) => s.supplierId).filter(Boolean) as string[]
}
+ supplierParts={supplierParts}
/>
<SupplierParts
supplierParts={supplierParts}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.tsx
index 7c4b7b3860..61b0769c6f 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.tsx
@@ -52,7 +52,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -71,6 +71,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatePartPurchasing = await upsertItemPurchasing(client, {
...validation.data,
itemId,
+ companyId,
updatedBy: userId
});
if (updatePartPurchasing.error) {
@@ -122,6 +123,7 @@ export default function PartPurchasingRoute() {
allowedSuppliers={
supplierParts.map((s) => s.supplierId).filter(Boolean) as string[]
}
+ supplierParts={supplierParts}
/>
<SupplierParts
supplierParts={supplierParts}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.tsx
index 2b9ba506cd..46348b5477 100644
--- a/apps/erp/app/routes/x+/service+/$itemId.purchasing.tsx
+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.tsx
@@ -51,7 +51,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -69,6 +69,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateServicePurchasing = await upsertItemPurchasing(client, {
...validation.data,
itemId,
+ companyId,
updatedBy: userId
});
if (updateServicePurchasing.error) {
@@ -122,6 +123,7 @@ export default function ServicePurchasingRoute() {
allowedSuppliers={
supplierParts.map((s) => s.supplierId).filter(Boolean) as string[]
}
+ supplierParts={supplierParts}
/>
<SupplierParts supplierParts={supplierParts} />
<ItemCostHistoryChart
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.tsx
index 00e3fe8b54..b87214e848 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.tsx
@@ -52,7 +52,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
});
@@ -71,6 +71,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateToolPurchasing = await upsertItemPurchasing(client, {
...validation.data,
itemId,
+ companyId,
updatedBy: userId
});
if (updateToolPurchasing.error) {
@@ -122,6 +123,7 @@ export default function ToolPurchasingRoute() {
allowedSuppliers={
supplierParts.map((s) => s.supplierId).filter(Boolean) as string[]
}
+ supplierParts={supplierParts}
/>
<SupplierParts
supplierParts={supplierParts}
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 430c41f3a8..4078f7ba2d 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -1156,7 +1156,7 @@ export const JobOperation = ({
"opacity-50 hover:opacity-100"
)}
>
- <Td>
+ <Td className="max-w-[20vw]">
<HStack
spacing={2}
className="justify-between min-w-0"
@@ -1357,7 +1357,7 @@ export const JobOperation = ({
"opacity-50 hover:opacity-100"
)}
>
- <Td className="pl-10">
+ <Td className="pl-10 max-w-[20vw]">
<HStack
spacing={2}
className="justify-between min-w-0"
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index 1439e52451..44b6ba2347 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -1174,6 +1174,27 @@ export function IssueMaterialModal({
const hasTrackedInputs = trackedInputs.length > 0;
+ // Scrapping a tracked entity is attributed to a job material: the scrap
+ // action requires a materialId, and it relieves that material's WIP /
+ // reopens its requirement. The generic "Issue Material" button opens this
+ // modal with no material, so there is nothing to scrap against — and building
+ // the scrap URL with an empty materialId 404s (generatePath collapses the
+ // empty segment to `/x/entity/:id/scrap`, which matches no route). Only offer
+ // the Scrap tab when a material is in context.
+ const canScrap = !!material?.id;
+
+ // The tracked (Serial/Batch) tabs are: Scan + Select, plus Scrap when there's
+ // a material, plus Unconsume when there are consumed inputs. Compute the grid
+ // column count from what's actually rendered so the triggers stay evenly
+ // spaced (Tailwind needs the literal class name).
+ const trackedTabCount = 2 + (canScrap ? 1 : 0) + (hasTrackedInputs ? 1 : 0);
+ const trackedTabsListClass = cn(
+ "grid w-full mb-4",
+ trackedTabCount === 2 && "grid-cols-2",
+ trackedTabCount === 3 && "grid-cols-3",
+ trackedTabCount === 4 && "grid-cols-4"
+ );
+
return (
<>
<Modal open onOpenChange={onClose}>
@@ -1359,12 +1380,7 @@ export function IssueMaterialModal({
{showContent && trackingType === "Serial" && (
<Tabs value={activeTab} onValueChange={setActiveTab}>
- <TabsList
- className={cn(
- "grid w-full grid-cols-3 mb-4",
- hasTrackedInputs && "grid-cols-4"
- )}
- >
+ <TabsList className={trackedTabsListClass}>
<TabsTrigger value="scan">
<LuQrCode className="mr-2" />
Scan
@@ -1373,10 +1389,12 @@ export function IssueMaterialModal({
<LuList className="mr-2" />
Select
</TabsTrigger>
- <TabsTrigger value="scrap">
- <LuTrash2 className="mr-2" />
- Scrap
- </TabsTrigger>
+ {canScrap && (
+ <TabsTrigger value="scrap">
+ <LuTrash2 className="mr-2" />
+ Scrap
+ </TabsTrigger>
+ )}
{hasTrackedInputs && (
<TabsTrigger value="unconsume">
<LuUndo2 className="mr-2" />
@@ -1385,17 +1403,19 @@ export function IssueMaterialModal({
)}
</TabsList>
- <TabsContent value="scrap">
- <ScrapTab
- entities={scrappableEntities}
- onScrap={(entity) =>
- setScrapEntityTarget({
- id: entity.id,
- readableId: entity.readableId
- })
- }
- />
- </TabsContent>
+ {canScrap && (
+ <TabsContent value="scrap">
+ <ScrapTab
+ entities={scrappableEntities}
+ onScrap={(entity) =>
+ setScrapEntityTarget({
+ id: entity.id,
+ readableId: entity.readableId
+ })
+ }
+ />
+ </TabsContent>
+ )}
<TabsContent value="scan">
<div className="flex flex-col gap-4">
@@ -1628,12 +1648,7 @@ export function IssueMaterialModal({
{showContent && trackingType === "Batch" && (
<Tabs value={activeTab} onValueChange={setActiveTab}>
- <TabsList
- className={cn(
- "grid w-full grid-cols-3 mb-4",
- hasTrackedInputs && "grid-cols-4"
- )}
- >
+ <TabsList className={trackedTabsListClass}>
<TabsTrigger value="scan">
<LuQrCode className="mr-2" />
Scan
@@ -1642,10 +1657,12 @@ export function IssueMaterialModal({
<LuList className="mr-2" />
Select
</TabsTrigger>
- <TabsTrigger value="scrap">
- <LuTrash2 className="mr-2" />
- Scrap
- </TabsTrigger>
+ {canScrap && (
+ <TabsTrigger value="scrap">
+ <LuTrash2 className="mr-2" />
+ Scrap
+ </TabsTrigger>
+ )}
{hasTrackedInputs && (
<TabsTrigger value="unconsume">
<LuUndo2 className="mr-2" />
@@ -1654,17 +1671,19 @@ export function IssueMaterialModal({
)}
</TabsList>
- <TabsContent value="scrap">
- <ScrapTab
- entities={scrappableEntities}
- onScrap={(entity) =>
- setScrapEntityTarget({
- id: entity.id,
- readableId: entity.readableId
- })
- }
- />
- </TabsContent>
+ {canScrap && (
+ <TabsContent value="scrap">
+ <ScrapTab
+ entities={scrappableEntities}
+ onScrap={(entity) =>
+ setScrapEntityTarget({
+ id: entity.id,
+ readableId: entity.readableId
+ })
+ }
+ />
+ </TabsContent>
+ )}
<TabsContent value="scan">
<div className="flex flex-col gap-4">
diff --git a/apps/mes/app/routes/x+/assigned.tsx b/apps/mes/app/routes/x+/assigned.tsx
index b79ee11ed2..5e3578b2a8 100644
--- a/apps/mes/app/routes/x+/assigned.tsx
+++ b/apps/mes/app/routes/x+/assigned.tsx
@@ -10,6 +10,7 @@ import {
Popover,
PopoverContent,
PopoverTrigger,
+ Separator,
SidebarTrigger,
Switch,
ToggleGroup,
@@ -71,10 +72,10 @@ export async function loader({ context, request }: LoaderFunctionArgs) {
type AssignedView = "board" | "list";
const ASSIGNED_VIEW_KEY = "assigned-view";
-const EMPTY_WORK_CENTERS_KEY = "assigned-show-empty-work-centers";
+const DISPLAY_SETTINGS_KEY = "kanban-assigned-display-settings";
const UNASSIGNED_COLUMN_ID = "unassigned";
-const displaySettings: DisplaySettings = {
+const defaultDisplaySettings: DisplaySettings = {
emptyWorkCenters: false,
showCustomer: false,
showDescription: true,
@@ -96,9 +97,13 @@ export default function AssignedRoute() {
ASSIGNED_VIEW_KEY,
"board"
);
- const [showEmptyWorkCenters, setShowEmptyWorkCenters] = useLocalStorage(
- EMPTY_WORK_CENTERS_KEY,
- false
+ const [displaySettings, setDisplaySettings] = useLocalStorage(
+ DISPLAY_SETTINGS_KEY,
+ defaultDisplaySettings
+ );
+ const mergedDisplaySettings = useMemo(
+ () => ({ ...defaultDisplaySettings, ...displaySettings }),
+ [displaySettings]
);
const filteredOperations = useMemo(() => {
@@ -136,7 +141,7 @@ export default function AssignedRoute() {
// By default only work centers with assigned operations become columns;
// the display setting adds the rest of the current location's work centers.
- if (showEmptyWorkCenters) {
+ if (mergedDisplaySettings.emptyWorkCenters) {
for (const workCenter of workCenters) {
if (workCenter.id && workCenter.locationId === locationId) {
columnWorkCenterIds.add(workCenter.id);
@@ -205,13 +210,19 @@ export default function AssignedRoute() {
})) satisfies Item[];
return { columns, items };
- }, [filteredOperations, workCenters, showEmptyWorkCenters, locationId, t]);
+ }, [
+ filteredOperations,
+ workCenters,
+ mergedDisplaySettings.emptyWorkCenters,
+ locationId,
+ t
+ ]);
// With "Empty work centers" on, an empty board of location columns is
// still worth showing — but a search with no matches keeps its empty state.
const showEmptyBoard =
view === "board" &&
- showEmptyWorkCenters &&
+ mergedDisplaySettings.emptyWorkCenters &&
!searchTerm &&
columns.length > 0;
@@ -256,12 +267,62 @@ export default function AssignedRoute() {
<span className="text-xs font-medium text-muted-foreground">
<Trans>Columns</Trans>
</span>
- <Switch
- variant="small"
- label={t`Empty work centers`}
- checked={showEmptyWorkCenters}
- onCheckedChange={setShowEmptyWorkCenters}
- />
+ {[
+ {
+ key: "emptyWorkCenters",
+ label: t`Empty work centers`
+ }
+ ].map(({ key, label }) => (
+ <Switch
+ key={key}
+ variant="small"
+ label={label}
+ checked={
+ mergedDisplaySettings[
+ key as keyof DisplaySettings
+ ]
+ }
+ onCheckedChange={(checked) =>
+ setDisplaySettings((prev) => ({
+ ...defaultDisplaySettings,
+ ...prev,
+ [key]: checked
+ }))
+ }
+ />
+ ))}
+ <Separator />
+ <span className="text-xs font-medium text-muted-foreground">
+ <Trans>Cards</Trans>
+ </span>
+ {[
+ { key: "showCustomer", label: t`Customer` },
+ { key: "showDescription", label: t`Description` },
+ { key: "showDueDate", label: t`Due Date` },
+ { key: "showDuration", label: t`Duration` },
+ { key: "showProgress", label: t`Progress` },
+ { key: "showStatus", label: t`Status` },
+ { key: "showSalesOrder", label: t`Sales Order` },
+ { key: "showThumbnail", label: t`Thumbnail` }
+ ].map(({ key, label }) => (
+ <Switch
+ key={key}
+ variant="small"
+ label={label}
+ checked={
+ mergedDisplaySettings[
+ key as keyof DisplaySettings
+ ]
+ }
+ onCheckedChange={(checked) =>
+ setDisplaySettings((prev) => ({
+ ...defaultDisplaySettings,
+ ...prev,
+ [key]: checked
+ }))
+ }
+ />
+ ))}
</VStack>
</PopoverContent>
</Popover>
@@ -295,15 +356,12 @@ export default function AssignedRoute() {
}
>
{() => (
- <div className="flex flex-grow items-stretch justify-center overflow-hidden relative">
- <div
- className="flex flex-1 min-h-full w-full relative"
- style={{ maxWidth: `${columns.length * 350}px` }}
- >
+ <div className="flex flex-grow items-stretch overflow-hidden relative">
+ <div className="flex flex-1 min-h-full w-full relative">
<Kanban
columns={columns}
items={items}
- {...displaySettings}
+ {...mergedDisplaySettings}
/>
</div>
</div>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 903be69fdc..d24430a038 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -68428,14 +68428,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -73517,21 +73517,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -74078,14 +74078,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -78324,6 +78324,7 @@ export type Database = {
order: number
parentMaterialId: string
quantity: number
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
revision: string
storageUnitId: string
unitCost: number
@@ -79081,6 +79082,7 @@ export type Database = {
quoteLineId: string
quoteMakeMethodId: string
quoteMaterialMakeMethodId: string
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
revision: string
storageUnitId: string
unitCost: number
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index cc0ace157f..07914f2baa 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -140,6 +140,18 @@ function remapStepLinks(
});
}
+// A BOM line whose quantity is explicitly 0 contributes nothing, so it is
+// dropped whenever a method is instantiated or copied. `null`/`undefined` is
+// NOT treated as zero — those fall back to a quantity of 1 elsewhere in this
+// file, so only a real numeric 0 removes the line.
+function isZeroQuantity(quantity: unknown): boolean {
+ // Only a real numeric 0 removes the line. `getConfiguredValue` returns a
+ // dynamically-configured value behind a type assertion, so `""`/`false`/`[]`
+ // can reach here — `Number("")`/`Number(false)` are 0 and would wrongly drop
+ // the line. A strict typeof check keeps those falling back to a quantity of 1.
+ return typeof quantity === "number" && quantity === 0;
+}
+
const partsValidator = z.object({
billOfMaterial: z.boolean().default(true),
billOfProcess: z.boolean().default(true),
@@ -291,12 +303,17 @@ serve(async (req: Request) => {
: Promise.resolve(),
]);
- // Copy materials from source to target
- if (parts.billOfMaterial && sourceMaterials.data && sourceMaterials.data.length > 0) {
+ // Copy materials from source to target, dropping any zero-quantity
+ // BOM lines.
+ const materialsToCopy = (
+ (sourceMaterials.data ??
+ []) as Database["public"]["Tables"]["methodMaterial"]["Row"][]
+ ).filter((material) => !isZeroQuantity(material.quantity));
+ if (parts.billOfMaterial && materialsToCopy.length > 0) {
await trx
.insertInto("methodMaterial")
.values(
- sourceMaterials.data.map((material) => ({
+ materialsToCopy.map((material) => ({
...material,
productionQuantity: undefined,
id: undefined, // Let the database generate a new ID
@@ -1321,6 +1338,10 @@ serve(async (req: Request) => {
]);
if (itemId === "") return null;
+ // A configured (or authored) quantity of 0 removes the line from
+ // the BOM. Made sub-assemblies drop out of `configuredChildren`
+ // below with the row, so their sub-tree is never exploded either.
+ if (isZeroQuantity(quantity)) return null;
let itemType = child.data.itemType;
let unitCost = child.data.unitCost;
@@ -2234,6 +2255,10 @@ serve(async (req: Request) => {
[];
for await (const child of node.children) {
+ // A zero-quantity BOM line is removed from the method. `madeChildren`
+ // below filters the same way, so a skipped made row stays index-aligned
+ // and its sub-tree is never exploded.
+ if (isZeroQuantity(child.data.quantity)) continue;
const material = await mapMethodMaterialToJobMaterial(child);
if (child.data.methodType === "Make to Order") {
madeMaterials.push(material);
@@ -2287,7 +2312,9 @@ serve(async (req: Request) => {
}
const madeChildren = node.children.filter(
- (child) => child.data.methodType === "Make to Order"
+ (child) =>
+ child.data.methodType === "Make to Order" &&
+ !isZeroQuantity(child.data.quantity)
);
for (const [index, child] of madeChildren.entries()) {
@@ -2941,6 +2968,9 @@ serve(async (req: Request) => {
]);
if (itemId === "") return null;
+ // A configured (or authored) quantity of 0 removes the line from
+ // the BOM (and its sub-tree, via configuredChildren below).
+ if (isZeroQuantity(quantity)) return null;
let itemType = child.data.itemType;
let unitCost = child.data.unitCost;
@@ -3446,11 +3476,18 @@ serve(async (req: Request) => {
customFields: {},
});
+ // A zero-quantity BOM line is removed from the method. Filtering the
+ // children (not the mapped rows) keeps `madeChildren`/`madeMaterials`
+ // index-aligned and stops a made line's sub-tree from being exploded.
const madeChildren = node.children.filter(
- (child) => child.data.methodType === "Make to Order"
+ (child) =>
+ child.data.methodType === "Make to Order" &&
+ !isZeroQuantity(child.data.quantity)
);
const unmadeChildren = node.children.filter(
- (child) => child.data.methodType !== "Make to Order"
+ (child) =>
+ child.data.methodType !== "Make to Order" &&
+ !isZeroQuantity(child.data.quantity)
);
const madeMaterials = madeChildren.map(
@@ -3616,6 +3653,8 @@ serve(async (req: Request) => {
}
node.children.forEach((child) => {
+ // A zero-quantity BOM line is dropped from the saved method.
+ if (isZeroQuantity(child.data.quantity)) return;
materialInserts.push({
makeMethodId: makeMethodByItemId[node.data.itemId],
materialMakeMethodId: makeMethodByItemId[child.data.itemId],
@@ -3936,6 +3975,8 @@ serve(async (req: Request) => {
}
node.children.forEach((child) => {
+ // A zero-quantity BOM line is dropped from the saved method.
+ if (isZeroQuantity(child.data.quantity)) return;
materialInserts.push({
makeMethodId: makeMethodByItemId[node.data.itemId],
materialMakeMethodId: makeMethodByItemId[child.data.itemId],
@@ -4441,6 +4482,16 @@ serve(async (req: Request) => {
}
for await (const child of node.children) {
+ // A zero-quantity Buy/Pick line is dropped from the copied job.
+ // A made sub-assembly is left intact even at quantity 0: its
+ // operations are copied by make method below and would reference
+ // a make method that never got created if the row were removed.
+ if (
+ isZeroQuantity(child.data.quantity) &&
+ child.data.methodType !== "Make to Order"
+ ) {
+ continue;
+ }
const sourceMaterial = sourceMaterialById.get(child.id);
const newMaterialId = nanoid();
sourceMaterialIdToJobMaterialId[child.id] = newMaterialId;
@@ -4961,12 +5012,17 @@ serve(async (req: Request) => {
: Promise.resolve(),
]);
- // Copy materials from source to target
- if (parts.billOfMaterial && sourceMaterials.data && sourceMaterials.data.length > 0) {
+ // Copy materials from source to target, dropping any zero-quantity
+ // BOM lines.
+ const materialsToCopy = (
+ (sourceMaterials.data ??
+ []) as Database["public"]["Tables"]["methodMaterial"]["Row"][]
+ ).filter((material) => !isZeroQuantity(material.quantity));
+ if (parts.billOfMaterial && materialsToCopy.length > 0) {
await trx
.insertInto("methodMaterial")
.values(
- sourceMaterials.data.map((material) => ({
+ materialsToCopy.map((material) => ({
...material,
productionQuantity: undefined,
id: undefined, // Let the database generate a new ID
@@ -5344,6 +5400,8 @@ serve(async (req: Request) => {
}
node.children.forEach((child) => {
+ // A zero-quantity BOM line is dropped from the saved method.
+ if (isZeroQuantity(child.data.quantity)) return;
materialInserts.push({
makeMethodId: makeMethodByItemId[node.data.itemId],
materialMakeMethodId: makeMethodByItemId[child.data.itemId],
@@ -5665,6 +5723,8 @@ serve(async (req: Request) => {
}
node.children.forEach((child) => {
+ // A zero-quantity BOM line is dropped from the saved method.
+ if (isZeroQuantity(child.data.quantity)) return;
materialInserts.push({
makeMethodId: makeMethodByItemId[node.data.itemId],
materialMakeMethodId: makeMethodByItemId[child.data.itemId],
@@ -6067,6 +6127,16 @@ serve(async (req: Request) => {
}
for await (const child of node.children) {
+ // A zero-quantity Buy/Pick line is dropped from the created job.
+ // A made sub-assembly is left intact even at quantity 0: its
+ // operations are copied by make method below and would reference
+ // a make method that never got created if the row were removed.
+ if (
+ isZeroQuantity(child.data.quantity) &&
+ child.data.methodType !== "Make to Order"
+ ) {
+ continue;
+ }
const newMaterialId = nanoid();
quoteMaterialIdToJobMaterialId[child.id] = newMaterialId;
@@ -6529,6 +6599,16 @@ serve(async (req: Request) => {
[];
for await (const child of node.children) {
+ // A zero-quantity Buy/Pick line is dropped from the copied quote.
+ // A made sub-assembly is left intact even at quantity 0: its
+ // operations are copied by make method below and would reference
+ // a make method that never got created if the row were removed.
+ if (
+ isZeroQuantity(child.data.quantity) &&
+ child.data.methodType !== "Make to Order"
+ ) {
+ continue;
+ }
const newMaterialId = nanoid();
quoteMaterialIdToQuoteMaterialId[child.id] = newMaterialId;
@@ -7055,6 +7135,16 @@ serve(async (req: Request) => {
[];
for await (const child of node.children) {
+ // A zero-quantity Buy/Pick line is dropped from the new quote.
+ // A made sub-assembly is left intact even at quantity 0: its
+ // operations are copied by make method below and would reference
+ // a make method that never got created if the row were removed.
+ if (
+ isZeroQuantity(child.data.quantity) &&
+ child.data.methodType !== "Make to Order"
+ ) {
+ continue;
+ }
const newMaterialId = nanoid();
quoteMaterialIdToQuoteMaterialId[child.id] = newMaterialId;
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 903be69fdc..d24430a038 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -68428,14 +68428,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -73517,21 +73517,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -74078,14 +74078,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -78324,6 +78324,7 @@ export type Database = {
order: number
parentMaterialId: string
quantity: number
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
revision: string
storageUnitId: string
unitCost: number
@@ -79081,6 +79082,7 @@ export type Database = {
quoteLineId: string
quoteMakeMethodId: string
quoteMaterialMakeMethodId: string
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
revision: string
storageUnitId: string
unitCost: number
diff --git a/packages/database/supabase/migrations/20260903164003_bom-explorer-replenishment-system.sql b/packages/database/supabase/migrations/20260903164003_bom-explorer-replenishment-system.sql
new file mode 100644
index 0000000000..f7f761903a
--- /dev/null
+++ b/packages/database/supabase/migrations/20260903164003_bom-explorer-replenishment-system.sql
@@ -0,0 +1,214 @@
+-- Surface each material's item replenishment system (Buy / Make / Buy and Make)
+-- in the job and quote BoM explorers, mirroring get_method_tree which already
+-- returns it. Both functions already INNER JOIN item, so no new join is needed —
+-- only a new RETURNS TABLE column and a corresponding SELECT column.
+-- Adding a column changes the return type, so the functions must be dropped and
+-- recreated rather than CREATE OR REPLACE'd.
+
+DROP FUNCTION IF EXISTS get_job_method(TEXT);
+CREATE FUNCTION get_job_method(jid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "version" NUMERIC,
+ "storageUnitId" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem"
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make to Order'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit",
+ "version",
+ NULL::TEXT AS "storageUnitId"
+ FROM
+ "jobMakeMethod"
+ WHERE
+ "jobId" = jid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."jobId",
+ child."id",
+ child."jobMakeMethodId",
+ child."methodType",
+ child."jobMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."version",
+ child."storageUnitId"
+ FROM
+ "jobMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."jobMaterialMakeMethodId" = child."jobMakeMethodId"
+ WHERE parent."methodType" = 'Make to Order'
+)
+SELECT
+ material."jobId",
+ material.id as "methodMaterialId",
+ material."jobMakeMethodId",
+ material."jobMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ material."version",
+ material."storageUnitId",
+ item."replenishmentSystem"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."jobId" = jid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+DROP FUNCTION IF EXISTS get_quote_methods(TEXT);
+CREATE FUNCTION get_quote_methods(qid TEXT)
+RETURNS TABLE (
+ "quoteId" TEXT,
+ "quoteLineId" TEXT,
+ "methodMaterialId" TEXT,
+ "quoteMakeMethodId" TEXT,
+ "quoteMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "unitCostSource" TEXT,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC,
+ "storageUnitId" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem"
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "quoteId",
+ "quoteLineId",
+ "id",
+ "id" AS "quoteMakeMethodId",
+ 'Make to Order'::"methodType" AS "methodType",
+ "id" AS "quoteMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ 'system'::TEXT AS "unitCostSource",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit",
+ "version",
+ NULL::TEXT AS "storageUnitId"
+ FROM
+ "quoteMakeMethod"
+ WHERE
+ "quoteId" = qid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."quoteId",
+ child."quoteLineId",
+ child."id",
+ child."quoteMakeMethodId",
+ child."methodType",
+ child."quoteMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ child."unitCostSource",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."version",
+ child."storageUnitId"
+ FROM
+ "quoteMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."quoteMaterialMakeMethodId" = child."quoteMakeMethodId"
+)
+SELECT
+ material."quoteId",
+ material."quoteLineId",
+ material.id as "methodMaterialId",
+ material."quoteMakeMethodId",
+ material."quoteMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."unitCostSource",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ material."version",
+ material."storageUnitId",
+ item."replenishmentSystem"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."quoteId" = qid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;