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.

Run scheduled MRP without billing rows; keep hand-typed quote material costs (#1490)

Sidfecfa400d58c
diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.md
index 98e3348a04..e6f8c2bcbb 100644
--- a/.claude/rules/mrp-system.md
+++ b/.claude/rules/mrp-system.md
@@ -18,11 +18,31 @@ Deno edge function** — NOT Trigger.dev, and not inline in the app server.
1. **Scheduled job** — `packages/jobs/src/inngest/functions/scheduled/mrp.ts`.
`inngest.createFunction({ id: "mrp", retries: 2 }, { cron: "0 */3 * * *" }, …)`
- — every 3 hours. Fans out **per company**: selects all rows from `companyPlan`
+ — every 3 hours. Fans out **per company**: selects all rows from `company`
and, for each, calls `serviceRole.functions.invoke("mrp", { body: { type:
"company", id, companyId, userId: "system" } })`. There is no location-scoped
cron — only company-wide.
+ It enumerated `companyPlan` until 2026-08-26. MRP is not in `FEATURE_PLANS`,
+ so that was never a billing gate — just a convenient list of companies — but
+ the table is only written by Stripe checkout and is seeded nowhere, so every
+ self-hosted, community and local-dev install had an empty work list and
+ silently never ran MRP, reporting a green Inngest run. Do not reintroduce it:
+ the work list is `company`, and a company with no plan row must still run.
+ On **Cloud only**, companies whose `stripeSubscriptionStatus` is `'Canceled'`
+ are skipped, because `weekly.ts` deletes those. The selection rule is the pure
+ `selectCompaniesForMrp` (`scheduled/mrp-companies.ts`), unit-tested in its
+ sibling `.test.ts`; the scheduler logs a `warn` when the list comes back
+ empty, so "no work" can never again look like "worked fine".
+
+ Both reads go through `fetchAllFromTable` with a stable `.order("id")` — the
+ same reason the edge function pages (below): `max_rows = 1000` truncates a
+ bare select, and the dev stack does not enforce the cap, so a dropped tail is
+ invisible locally. A failed `company` read **throws**; returning would make
+ the step succeed having planned for nobody, which is this function's whole
+ bug class. A failed `companyPlan` read does not — it leaves `plans` null and
+ plans for everyone, which is the fail-safe direction.
+
2. **Manual trigger** — POST `apps/erp/app/routes/api+/mrp.ts` (permission
`update: "inventory"`). Reads `?location` query param; calls
`runMRP(getCarbonServiceRole(), { type: locationId ? "location" : "company",
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 38bee3cc13..e8cd00b86b 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -377,6 +377,9 @@ export const quoteMaterialValidator = z
quantity: zfd.numeric(z.number().min(0)),
storageUnitId: zfd.text(z.string().optional()),
unitCost: zfd.numeric(z.number().min(0)),
+ // Required, not optional-with-default: a form that omits it fails loudly
+ // instead of silently downgrading a typed cost to 'system'.
+ unitCostSource: z.enum(["system", "manual"]),
unitOfMeasureCode: z
.string()
.min(1, { message: "Unit of Measure is required" })
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 2925dd32c6..1cc0b040f2 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -28,6 +28,7 @@ import { normalizeOperationSourceIds } from "../shared";
import {
getModelByItemId,
lookupBuyPriceFromMap,
+ resolveBuyUnitCost,
upsertExternalLink
} from "../shared/shared.service";
import type {
@@ -4041,10 +4042,11 @@ async function buildCostEffects(
const operations = operationsResult.data ?? [];
- // Fix Buy material costs
+ // Refresh Buy material costs from supplier price breaks; resolveBuyUnitCost
+ // leaves a typed cost alone.
const buyMaterials = await client
.from("quoteMaterial")
- .select("id, itemId, unitCost")
+ .select("id, itemId, unitCost, unitCostSource")
.eq("quoteLineId", quoteLineId)
.eq("methodType", "Purchase to Order");
@@ -4054,7 +4056,8 @@ async function buildCostEffects(
const priceMap = await getSupplierPriceBreaksForItems(client, buyItemIds);
for (const mat of buyMaterials.data ?? []) {
- const price = lookupBuyPriceFromMap(mat.itemId, 1, priceMap, mat.unitCost);
+ if (mat.unitCostSource === "manual") continue;
+ const price = resolveBuyUnitCost(mat, 1, priceMap);
if (price !== mat.unitCost) {
await client
.from("quoteMaterial")
@@ -4170,13 +4173,17 @@ async function buildCostEffects(
itemId: string,
itemType: string,
quantity: number,
- unitCost: number
+ unitCost: number,
+ unitCostSource: string | null
) {
const costFn = (outerQty: number) => {
const requestedQty = quantity * outerQty;
return (
- lookupBuyPriceFromMap(itemId, requestedQty, priceMap, unitCost) *
- requestedQty
+ resolveBuyUnitCost(
+ { itemId, unitCost, unitCostSource },
+ requestedQty,
+ priceMap
+ ) * requestedQty
);
};
const key =
@@ -4199,7 +4206,13 @@ async function buildCostEffects(
const qty = d.quantity * parentQuantity;
if (d.methodType === "Purchase to Order") {
- pushBuyCostEffect(d.itemId, d.itemType, qty, d.unitCost);
+ pushBuyCostEffect(
+ d.itemId,
+ d.itemType,
+ qty,
+ d.unitCost,
+ d.unitCostSource
+ );
} else if (d.methodType === "Pull from Inventory") {
const costFn = (outerQty: number) => d.unitCost * qty * outerQty;
const key =
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index e63cd6fd64..93f339eed9 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -624,6 +624,7 @@ function MaterialForm({
methodType: MethodType;
description: string;
unitCost: number;
+ unitCostSource: "system" | "manual";
unitOfMeasureCode: string;
quantity: number;
kit: boolean;
@@ -637,6 +638,7 @@ function MaterialForm({
methodType: item.data.methodType ?? "Pull from Inventory",
description: item.data.description ?? "",
unitCost: item.data.unitCost ?? 0,
+ unitCostSource: item.data.unitCostSource === "manual" ? "manual" : "system",
unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",
quantity: item.data.quantity ?? 1,
kit: item.data.kit ?? false,
@@ -655,6 +657,7 @@ function MaterialForm({
methodType: "Pull from Inventory",
quantity: 1,
unitCost: 0,
+ unitCostSource: "system",
description: "",
unitOfMeasureCode: "EA",
kit: false,
@@ -712,6 +715,7 @@ function MaterialForm({
itemId,
description: item.data?.name ?? "",
unitCost,
+ unitCostSource: "system",
unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
methodType: item.data?.defaultMethodType ?? "Pull from Inventory",
requiresBatchTracking: item.data?.itemTrackingType === "Batch",
@@ -730,6 +734,8 @@ function MaterialForm({
if (itemData.methodType !== "Purchase to Order" || !itemData.itemId)
return;
+ // A typed cost survives a quantity change.
+ if (itemData.unitCostSource === "manual") return;
if (!carbon) return;
const itemCost = await carbon
@@ -745,9 +751,19 @@ function MaterialForm({
fallbackCost
);
- setItemData((d) => ({ ...d, unitCost }));
+ // Re-checked here because the guard above reads a captured value, and a
+ // cost can be typed while the awaits are in flight.
+ setItemData((d) =>
+ d.unitCostSource === "manual" ? d : { ...d, unitCost }
+ );
},
- [carbon, itemData.methodType, itemData.itemId, lookupBuyPriceFn]
+ [
+ carbon,
+ itemData.methodType,
+ itemData.itemId,
+ itemData.unitCostSource,
+ lookupBuyPriceFn
+ ]
);
const sourceDisclosure = useDisclosure();
@@ -776,6 +792,7 @@ function MaterialForm({
<Hidden name="quoteMakeMethodId" />
<Hidden name="kit" value={itemData.kit.toString()} />
<Hidden name="order" />
+ <Hidden name="unitCostSource" value={itemData.unitCostSource} />
{itemData.methodType === "Make to Order" && (
<Hidden name="unitCost" value={itemData.unitCost} />
@@ -829,6 +846,13 @@ function MaterialForm({
value={itemData.unitCost}
minValue={0}
formatOptions={INPUT_FORMAT.rate(baseCurrency, currencyDecimals)}
+ onChange={(newValue) =>
+ setItemData((d) => ({
+ ...d,
+ unitCost: newValue,
+ unitCostSource: "manual"
+ }))
+ }
/>
)}
</div>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index c42972f6af..31becadd94 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -67,6 +67,7 @@ const QuoteMaterialForm = ({
methodType: MethodType;
description: string;
unitCost: number;
+ unitCostSource: "system" | "manual";
unitOfMeasureCode: string;
quantity: number;
itemReplenishmentSystem: string;
@@ -75,6 +76,8 @@ const QuoteMaterialForm = ({
methodType: initialValues.methodType ?? "Pull from Inventory",
description: initialValues.description ?? "",
unitCost: initialValues.unitCost ?? 0,
+ unitCostSource:
+ initialValues.unitCostSource === "manual" ? "manual" : "system",
unitOfMeasureCode: initialValues.unitOfMeasureCode ?? "EA",
quantity: initialValues.quantity ?? 1,
itemReplenishmentSystem: initialValues.item?.replenishmentSystem ?? "Buy"
@@ -89,6 +92,7 @@ const QuoteMaterialForm = ({
quantity: 1,
description: "",
unitCost: 0,
+ unitCostSource: "system",
unitOfMeasureCode: "EA",
itemReplenishmentSystem: "Buy"
});
@@ -132,6 +136,7 @@ const QuoteMaterialForm = ({
itemId,
description: item.data?.name ?? "",
unitCost,
+ unitCostSource: "system",
unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
methodType: item.data?.defaultMethodType ?? "Purchase to Order",
itemReplenishmentSystem: item.data?.replenishmentSystem ?? "Buy"
@@ -144,6 +149,8 @@ const QuoteMaterialForm = ({
if (itemData.methodType !== "Purchase to Order" || !itemData.itemId)
return;
+ // A typed cost survives a quantity change.
+ if (itemData.unitCostSource === "manual") return;
if (!carbon) return;
const itemCost = await carbon
@@ -159,9 +166,19 @@ const QuoteMaterialForm = ({
fallbackCost
);
- setItemData((d) => ({ ...d, unitCost }));
+ // Re-checked here because the guard above reads a captured value, and a
+ // cost can be typed while the awaits are in flight.
+ setItemData((d) =>
+ d.unitCostSource === "manual" ? d : { ...d, unitCost }
+ );
},
- [carbon, itemData.methodType, itemData.itemId, lookupBuyPrice]
+ [
+ carbon,
+ itemData.methodType,
+ itemData.itemId,
+ itemData.unitCostSource,
+ lookupBuyPrice
+ ]
);
const [, setSearchParams] = useUrlParams();
@@ -213,6 +230,7 @@ const QuoteMaterialForm = ({
<Hidden name="unitCost" value={itemData.unitCost} />
)}
<Hidden name="order" />
+ <Hidden name="unitCostSource" value={itemData.unitCostSource} />
<VStack className="pt-4">
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
<Item
@@ -273,6 +291,13 @@ const QuoteMaterialForm = ({
label={t`Unit Cost`}
value={itemData.unitCost}
minValue={0}
+ onChange={(newValue) =>
+ setItemData((d) => ({
+ ...d,
+ unitCost: newValue,
+ unitCostSource: "manual"
+ }))
+ }
/>
)}
</div>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx b/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx
index e8485c7a92..1afac99c34 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/useLineCosts.tsx
@@ -1,7 +1,7 @@
import { useCallback, useMemo } from "react";
import { useParams } from "react-router";
import type { Tree } from "~/components/TreeView";
-import { lookupBuyPriceFromMap, type SupplierPriceMap } from "~/modules/shared";
+import { resolveBuyUnitCost, type SupplierPriceMap } from "~/modules/shared";
import type {
CostEffects,
Costs,
@@ -79,15 +79,15 @@ export function useLineCosts({
itemType: string,
quantity: number,
unitCost: number,
+ unitCostSource: string | null,
supplierPriceMap: SupplierPriceMap
) {
const costFn = (outerQty: number) => {
const requestedQty = quantity * outerQty;
- const resolved = lookupBuyPriceFromMap(
- itemId,
+ const resolved = resolveBuyUnitCost(
+ { itemId, unitCost, unitCostSource },
requestedQty,
- supplierPriceMap,
- unitCost
+ supplierPriceMap
);
return resolved * requestedQty;
};
@@ -121,6 +121,7 @@ export function useLineCosts({
data.itemType,
data.quantity,
data.unitCost,
+ data.unitCostSource,
supplierPriceMap
);
} else if (data.methodType === "Pull from Inventory") {
@@ -381,6 +382,10 @@ export function useLineCosts({
"Material",
1,
line.unitCost ?? 0,
+ // The quote LINE's own cost, not a BOM material's. Only quoteMaterial
+ // carries a typed/calculated flag, so this always resolves from the
+ // supplier's price breaks, exactly as it did before.
+ null,
supplierPriceMap
);
} else {
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index b38913ac9a..08ee7acef6 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -1401,6 +1401,32 @@ export function lookupBuyPriceFromMap(
);
}
+/**
+ * What a "Purchase to Order" quote material's unit cost IS: a typed cost wins,
+ * anything else re-resolves from supplier price breaks. Every reader of a
+ * bought-to-order cost must go through this — reaching for
+ * lookupBuyPriceFromMap directly silently ignores a typed cost.
+ *
+ * Mirrored in the Deno edge runtime (`functions/lib/methods.ts`).
+ */
+export function resolveBuyUnitCost(
+ material: {
+ itemId: string;
+ unitCost: number;
+ unitCostSource?: string | null;
+ },
+ requestedQty: number,
+ priceMap: SupplierPriceMap
+): number {
+ if (material.unitCostSource === "manual") return material.unitCost;
+ return lookupBuyPriceFromMap(
+ material.itemId,
+ requestedQty,
+ priceMap,
+ material.unitCost
+ );
+}
+
/**
* Resolve the best supplier unit price for a quantity, applying exchange
* rate conversion.
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 94a3654808..2ea0258e5a 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-08-26T13:44:13.092Z",
- "totalTools": 1447,
+ "generated": "2026-08-27T06:54:51.985Z",
+ "totalTools": 1448,
"modules": 15,
"tools": [
{
@@ -44766,6 +44766,56 @@
]
}
},
+ {
+ "name": "shared_resolveBuyUnitCost",
+ "module": "shared",
+ "classification": "WRITE",
+ "description": "resolve buy unit cost",
+ "paramCount": 3,
+ "serviceParams": [
+ "material",
+ "requestedQty",
+ "priceMap"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "material": {
+ "type": "object",
+ "properties": {
+ "itemId": {
+ "type": "string"
+ },
+ "unitCost": {
+ "type": "number"
+ },
+ "unitCostSource": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "itemId",
+ "unitCost"
+ ]
+ },
+ "requestedQty": {
+ "type": "number"
+ },
+ "priceMap": {}
+ },
+ "required": [
+ "material",
+ "requestedQty",
+ "priceMap"
+ ]
+ }
+ },
{
"name": "shared_resolveSupplierPrice",
"module": "shared",
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
index a9d3bdcca1..f0fc60570a 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
@@ -6,7 +6,7 @@ import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { getSupplierPriceBreaksForItems } from "~/modules/items";
import { upsertQuoteLineMethod } from "~/modules/sales/sales.service";
-import { lookupBuyPriceFromMap } from "~/modules/shared";
+import { resolveBuyUnitCost } from "~/modules/shared";
import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -64,10 +64,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- // Fix BOM material costs: replace average cost with price break values
+ // Replace average cost with price break values; resolveBuyUnitCost leaves
+ // a typed cost alone.
const buyMaterials = await serviceRole
.from("quoteMaterial")
- .select("id, itemId, unitCost")
+ .select("id, itemId, unitCost, unitCostSource")
.eq("quoteLineId", lineId)
.eq("methodType", "Purchase to Order");
@@ -80,12 +81,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
for (const mat of buyMaterials.data ?? []) {
- const price = lookupBuyPriceFromMap(
- mat.itemId,
- 1,
- priceMap,
- mat.unitCost
- );
+ if (mat.unitCostSource === "manual") continue;
+ const price = resolveBuyUnitCost(mat, 1, priceMap);
if (price !== mat.unitCost) {
await serviceRole
.from("quoteMaterial")
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 2be930702c..0bd9c9a192 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -16014,6 +16014,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMaterialWithMakeMethodId.storageUnitId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialWithMakeMethodId.unitCostSource"
+ },
{
$ref: "#/parameters/rowFilter.quoteMaterialWithMakeMethodId.quoteMaterialMakeMethodId"
},
@@ -43260,6 +43263,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMaterial.storageUnitId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterial.unitCostSource"
+ },
{
$ref: "#/parameters/select"
},
@@ -43391,6 +43397,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMaterial.storageUnitId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterial.unitCostSource"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -43476,6 +43485,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMaterial.storageUnitId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterial.unitCostSource"
+ },
{
$ref: "#/parameters/body.quoteMaterial"
},
@@ -106131,6 +106143,10 @@ export default {
format: "text",
type: "string"
},
+ unitCostSource: {
+ format: "text",
+ type: "string"
+ },
quoteMaterialMakeMethodId: {
description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
@@ -119179,7 +119195,8 @@ export default {
"createdBy",
"quoteMakeMethodId",
"scrapQuantity",
- "kit"
+ "kit",
+ "unitCostSource"
],
properties: {
id: {
@@ -119308,6 +119325,11 @@ export default {
"Note:\nThis is a Foreign Key to `storageUnit.id`.<fk table='storageUnit' column='id'/>",
format: "text",
type: "string"
+ },
+ unitCostSource: {
+ default: "system",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -148576,6 +148598,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.quoteMaterialWithMakeMethodId.unitCostSource": {
+ name: "unitCostSource",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.quoteMaterialWithMakeMethodId.quoteMaterialMakeMethodId": {
name: "quoteMaterialMakeMethodId",
required: false,
@@ -163130,6 +163158,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.quoteMaterial.unitCostSource": {
+ name: "unitCostSource",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.customerStatus": {
name: "customerStatus",
description: "customerStatus",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 1dccda60d7..47c7bb7ad1 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -42946,6 +42946,7 @@ export type Database = {
storageUnitId: string | null
tags: string[] | null
unitCost: number
+ unitCostSource: string
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
@@ -42972,6 +42973,7 @@ export type Database = {
storageUnitId?: string | null
tags?: string[] | null
unitCost?: number
+ unitCostSource?: string
unitOfMeasureCode?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -42998,6 +43000,7 @@ export type Database = {
storageUnitId?: string | null
tags?: string[] | null
unitCost?: number
+ unitCostSource?: string
unitOfMeasureCode?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -70176,6 +70179,7 @@ export type Database = {
storageUnitId: string | null
tags: string[] | null
unitCost: number | null
+ unitCostSource: string | null
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
@@ -77471,6 +77475,7 @@ export type Database = {
revision: string
storageUnitId: string
unitCost: number
+ unitCostSource: string
version: number
}[]
}
@@ -77497,6 +77502,7 @@ export type Database = {
revision: string
storageUnitId: string
unitCost: number
+ unitCostSource: string
unitOfMeasureCode: string
version: number
}[]
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 42f4f11726..a4f089ac69 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -5765,6 +5765,7 @@ serve(async (req: Request) => {
storageUnitId: child.data.storageUnitId,
unitOfMeasureCode: child.data.unitOfMeasureCode,
unitCost: child.data.unitCost ?? 0, // TODO: get real unit cost
+ unitCostSource: child.data.unitCostSource ?? "system",
companyId,
createdBy: userId,
customFields: {},
@@ -6282,6 +6283,7 @@ serve(async (req: Request) => {
quantity: child.data.quantity,
storageUnitId: child.data.storageUnitId,
unitCost: child.data.unitCost ?? 0, // TODO: get real unit cost
+ unitCostSource: child.data.unitCostSource ?? "system",
unitOfMeasureCode: child.data.unitOfMeasureCode,
companyId,
createdBy: userId,
diff --git a/packages/database/supabase/functions/lib/methods.ts b/packages/database/supabase/functions/lib/methods.ts
index fcc7686d05..66b61d4c86 100644
--- a/packages/database/supabase/functions/lib/methods.ts
+++ b/packages/database/supabase/functions/lib/methods.ts
@@ -405,6 +405,24 @@ function lookupBuyPriceFromMap(
);
}
+/**
+ * Mirror of `resolveBuyUnitCost` in
+ * `apps/erp/app/modules/shared/shared.service.ts` — keep both in sync.
+ */
+function resolveBuyUnitCost(
+ material: { itemId: string; unitCost: number; unitCostSource?: string | null },
+ requestedQty: number,
+ priceMap: SupplierPriceMap
+): number {
+ if (material.unitCostSource === "manual") return material.unitCost;
+ return lookupBuyPriceFromMap(
+ material.itemId,
+ requestedQty,
+ priceMap,
+ material.unitCost
+ );
+}
+
function normalizeTimeToHours(
time: number,
unit: string
@@ -524,10 +542,11 @@ export async function calculateQuoteLinePrices(
.map((row) => Number(row.quantity))
);
- // 2. Fix Buy material costs with supplier price breaks
+ // 2. Fix Buy material costs with supplier price breaks; resolveBuyUnitCost
+ // leaves a typed cost alone.
const buyMaterials = await client
.from("quoteMaterial")
- .select("id, itemId, unitCost")
+ .select("id, itemId, unitCost, unitCostSource")
.eq("quoteLineId", quoteLineId)
.eq("methodType", "Purchase to Order");
@@ -537,7 +556,8 @@ export async function calculateQuoteLinePrices(
const priceMap = await getSupplierPriceBreaksForItems(client, buyItemIds);
for (const mat of buyMaterials.data ?? []) {
- const price = lookupBuyPriceFromMap(mat.itemId, 1, priceMap, mat.unitCost);
+ if (mat.unitCostSource === "manual") continue;
+ const price = resolveBuyUnitCost(mat, 1, priceMap);
if (price !== mat.unitCost) {
await client
.from("quoteMaterial")
@@ -566,6 +586,7 @@ export async function calculateQuoteLinePrices(
methodType: string;
quantity: number;
unitCost: number;
+ unitCostSource: string | null;
quoteMaterialMakeMethodId: string;
operations: typeof operations;
children: EnhancedNode[];
@@ -585,6 +606,7 @@ export async function calculateQuoteLinePrices(
methodType: node.data.methodType,
quantity: qty,
unitCost: node.data.unitCost,
+ unitCostSource: node.data.unitCostSource,
quoteMaterialMakeMethodId: node.data.quoteMaterialMakeMethodId,
operations: nodeOps,
children: node.children.map((c) => buildEnhancedTree(c, qty)),
@@ -608,15 +630,15 @@ export async function calculateQuoteLinePrices(
itemId: string,
itemType: string,
quantity: number,
- unitCost: number
+ unitCost: number,
+ unitCostSource: string | null
) {
const costFn = (outerQty: number) => {
const requestedQty = quantity * outerQty;
- const resolved = lookupBuyPriceFromMap(
- itemId,
+ const resolved = resolveBuyUnitCost(
+ { itemId, unitCost, unitCostSource },
requestedQty,
- priceMap,
- unitCost
+ priceMap
);
return resolved * requestedQty;
};
@@ -641,7 +663,13 @@ export async function calculateQuoteLinePrices(
function walkTree(node: EnhancedNode) {
if (node.methodType === "Purchase to Order") {
- pushBuyCostEffect(node.itemId, node.itemType, node.quantity, node.unitCost);
+ pushBuyCostEffect(
+ node.itemId,
+ node.itemType,
+ node.quantity,
+ node.unitCost,
+ node.unitCostSource
+ );
} else if (node.methodType === "Pull from Inventory") {
const costFn = (quantity: number) =>
node.unitCost * node.quantity * quantity;
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 1dccda60d7..47c7bb7ad1 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -42946,6 +42946,7 @@ export type Database = {
storageUnitId: string | null
tags: string[] | null
unitCost: number
+ unitCostSource: string
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
@@ -42972,6 +42973,7 @@ export type Database = {
storageUnitId?: string | null
tags?: string[] | null
unitCost?: number
+ unitCostSource?: string
unitOfMeasureCode?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -42998,6 +43000,7 @@ export type Database = {
storageUnitId?: string | null
tags?: string[] | null
unitCost?: number
+ unitCostSource?: string
unitOfMeasureCode?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -70176,6 +70179,7 @@ export type Database = {
storageUnitId: string | null
tags: string[] | null
unitCost: number | null
+ unitCostSource: string | null
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
@@ -77471,6 +77475,7 @@ export type Database = {
revision: string
storageUnitId: string
unitCost: number
+ unitCostSource: string
version: number
}[]
}
@@ -77497,6 +77502,7 @@ export type Database = {
revision: string
storageUnitId: string
unitCost: number
+ unitCostSource: string
unitOfMeasureCode: string
version: number
}[]
diff --git a/packages/database/supabase/migrations/20260826143912_quote-material-cost-source.sql b/packages/database/supabase/migrations/20260826143912_quote-material-cost-source.sql
new file mode 100644
index 0000000000..19fa7e52a6
--- /dev/null
+++ b/packages/database/supabase/migrations/20260826143912_quote-material-cost-source.sql
@@ -0,0 +1,268 @@
+-- 'manual' = typed by a person and never recalculated; 'system' = derived, and
+-- re-derived on every quote method mutation.
+--
+-- Deliberately NOT backfilled, unlike the sibling quoteLinePrice."priceSource"
+-- (20260714180443). The overwrite this fixes has run on every save, so existing
+-- bought-to-order rows already hold the supplier price; marking them 'manual'
+-- would freeze a supplier-derived number forever.
+
+ALTER TABLE "quoteMaterial"
+ ADD COLUMN "unitCostSource" TEXT NOT NULL DEFAULT 'system';
+
+-- NOT VALID skips the full-table scan under the ACCESS EXCLUSIVE lock.
+ALTER TABLE "quoteMaterial"
+ ADD CONSTRAINT "quoteMaterial_unitCostSource_check"
+ CHECK ("unitCostSource" IN ('system', 'manual')) NOT VALID;
+
+ALTER TABLE "quoteMaterial"
+ VALIDATE CONSTRAINT "quoteMaterial_unitCostSource_check";
+
+-- The view is SELECT qm.*, but a view's column list is frozen at creation and
+-- CREATE OR REPLACE may only append, so it has to be dropped and recreated.
+
+DROP VIEW "quoteMaterialWithMakeMethodId";
+
+-- Source: 20260417000300_storage-unit-recreate-dependents.sql (latest body)
+CREATE VIEW "quoteMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ qm.*,
+ qmm."id" AS "quoteMaterialMakeMethodId",
+ qmm.version AS "version"
+ FROM "quoteMaterial" qm
+ LEFT JOIN "quoteMakeMethod" qmm
+ ON qmm."parentMaterialId" = qm."id";
+
+-- Both readers change their RETURNS TABLE, which CREATE OR REPLACE cannot do.
+
+DROP FUNCTION IF EXISTS get_quote_methods_by_method_id(TEXT);
+DROP FUNCTION IF EXISTS get_quote_methods(TEXT);
+
+-- Source: 20260417000300_storage-unit-recreate-dependents.sql (latest body)
+CREATE OR REPLACE FUNCTION get_quote_methods_by_method_id(mid TEXT)
+RETURNS TABLE (
+ "quoteId" TEXT,
+ "quoteLineId" TEXT,
+ "methodMaterialId" TEXT,
+ "quoteMakeMethodId" TEXT,
+ "quoteMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "itemType" TEXT,
+ "itemTrackingType" 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
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "quoteId",
+ "quoteLineId",
+ "id",
+ "id" AS "quoteMakeMethodId",
+ 'Make to Order'::"methodType" AS "methodType",
+ "id" AS "quoteMaterialMakeMethodId",
+ "version",
+ "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",
+ NULL::TEXT AS "storageUnitId"
+ FROM
+ "quoteMakeMethod"
+ WHERE
+ "id" = mid
+ UNION
+ SELECT
+ child."quoteId",
+ child."quoteLineId",
+ child."id",
+ child."quoteMakeMethodId",
+ child."methodType",
+ child."quoteMaterialMakeMethodId",
+ child."version",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ child."unitCostSource",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."storageUnitId"
+ FROM
+ "quoteMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."quoteMaterialMakeMethodId" = child."quoteMakeMethodId"
+ WHERE parent."methodType" = 'Make to Order'
+)
+SELECT
+ material."quoteId",
+ material."quoteLineId",
+ material.id as "methodMaterialId",
+ material."quoteMakeMethodId",
+ material."quoteMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ material."itemType",
+ item."itemTrackingType",
+ 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"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+
+-- Source: 20260417000300_storage-unit-recreate-dependents.sql (latest body)
+CREATE OR REPLACE 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
+) 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"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."quoteId" = qid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts
new file mode 100644
index 0000000000..61bb5d5422
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+import { selectCompaniesForMrp } from "./mrp-companies";
+
+const companies = [
+ { id: "c1", name: "Acme" },
+ { id: "c2", name: "Globex" },
+ { id: "c3", name: "Initech" }
+];
+
+describe("selectCompaniesForMrp", () => {
+ it("plans for a company with no companyPlan row", () => {
+ // The regression: an empty companyPlan table meant MRP ran for nobody.
+ expect(selectCompaniesForMrp(companies, [])).toEqual(companies);
+ });
+
+ it("plans for every company when there are no plans to consider", () => {
+ // null = not Cloud, or the plan lookup failed.
+ expect(selectCompaniesForMrp(companies, null)).toEqual(companies);
+ });
+
+ it("skips a cancelled company", () => {
+ const result = selectCompaniesForMrp(companies, [
+ { id: "c2", stripeSubscriptionStatus: "Canceled" }
+ ]);
+ expect(result.map((c) => c.id)).toEqual(["c1", "c3"]);
+ });
+
+ it("still plans for active, inactive and unknown-status companies", () => {
+ const result = selectCompaniesForMrp(companies, [
+ { id: "c1", stripeSubscriptionStatus: "Active" },
+ { id: "c2", stripeSubscriptionStatus: "Inactive" },
+ { id: "c3", stripeSubscriptionStatus: null }
+ ]);
+ expect(result).toEqual(companies);
+ });
+
+ it("ignores a plan row for a company that no longer exists", () => {
+ const result = selectCompaniesForMrp(companies, [
+ { id: "gone", stripeSubscriptionStatus: "Canceled" }
+ ]);
+ expect(result).toEqual(companies);
+ });
+
+ it("returns nothing when every company is cancelled", () => {
+ const result = selectCompaniesForMrp(
+ companies,
+ companies.map((c) => ({ id: c.id, stripeSubscriptionStatus: "Canceled" }))
+ );
+ expect(result).toEqual([]);
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts
new file mode 100644
index 0000000000..3539801339
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts
@@ -0,0 +1,24 @@
+/**
+ * Which companies a scheduled MRP run should plan for. A company with no
+ * `companyPlan` row still runs — MRP is not a paid feature.
+ *
+ * `plans` is null when there are none to consider (not Cloud, or the lookup
+ * failed), which means plan for everyone: planning for a cancelled company
+ * wastes a little work, planning for nobody is the bug this function exists for.
+ */
+export function selectCompaniesForMrp<T extends { id: string }>(
+ companies: T[],
+ plans: { id: string; stripeSubscriptionStatus: string | null }[] | null
+): T[] {
+ if (!plans) return companies;
+
+ // Only "Canceled" — the status the weekly job deletes on. "Inactive" (e.g.
+ // payment past due) still plans.
+ const cancelled = new Set(
+ plans
+ .filter((plan) => plan.stripeSubscriptionStatus === "Canceled")
+ .map((plan) => plan.id)
+ );
+
+ return companies.filter((company) => !cancelled.has(company.id));
+}
diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp.ts b/packages/jobs/src/inngest/functions/scheduled/mrp.ts
index 3673032537..9eccbeea6d 100644
--- a/packages/jobs/src/inngest/functions/scheduled/mrp.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/mrp.ts
@@ -1,5 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { fetchAllFromTable } from "@carbon/database";
+import { Edition } from "@carbon/utils";
import { inngest } from "../../client";
+import { selectCompaniesForMrp } from "./mrp-companies";
export const mrpFunction = inngest.createFunction(
{ id: "mrp", retries: 2 },
@@ -11,16 +14,60 @@ export const mrpFunction = inngest.createFunction(
`Scheduled MRP Calculation Started: ${new Date().toISOString()}`
);
- const companies = await serviceRole
- .from("companyPlan")
- .select("id, ...company(name)");
+ // Enumerate `company`, never `companyPlan` — that billing table is empty
+ // on every install where nobody completed Stripe checkout, and MRP
+ // silently never ran there. Paged, because max_rows would truncate the
+ // work list the same silent way.
+ const companies = await fetchAllFromTable<{ id: string; name: string }>(
+ serviceRole,
+ "company",
+ "id, name",
+ (query) => query.order("id")
+ );
if (companies.error) {
logger.error("Failed to get companies", { error: companies.error });
+ // Throwing, not returning: a return is a step that succeeds having
+ // planned for nobody, and never spends the configured retries.
+ throw companies.error;
+ }
+
+ // Cloud only: a cancelled subscription means the weekly job is about to
+ // delete the company. MRP is not a paid feature anywhere else.
+ let plans:
+ | { id: string; stripeSubscriptionStatus: string | null }[]
+ | null = null;
+ if (process.env.CARBON_EDITION === Edition.Cloud) {
+ const companyPlans = await fetchAllFromTable<{
+ id: string;
+ stripeSubscriptionStatus: string | null;
+ }>(
+ serviceRole,
+ "companyPlan",
+ "id, stripeSubscriptionStatus",
+ (query) => query.order("id")
+ );
+
+ if (companyPlans.error) {
+ // Deliberately not a return: leaving `plans` null plans for everyone.
+ logger.error("Failed to get company plans, planning for all", {
+ error: companyPlans.error
+ });
+ } else {
+ plans = companyPlans.data;
+ }
+ }
+
+ const scheduled = selectCompaniesForMrp(companies.data, plans);
+
+ if (scheduled.length === 0) {
+ logger.warn("No companies to run MRP for", {
+ companies: companies.data.length
+ });
return;
}
- for (const company of companies.data) {
+ for (const company of scheduled) {
try {
const result = await serviceRole.functions.invoke("mrp", {
body: {