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.

fix: quantities and estimated quantities

Brad Barbin07e8e157990e
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 4831a37034..89cbc32adc 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -626,8 +626,7 @@ export const JobOperation = ({
</div>
<div className="p-6 pt-0">
<Heading size="h1">
- {operation.quantityComplete} of{" "}
- {operation.operationQuantity}
+ {operation.quantityComplete} of {operation.targetQuantity}
</Heading>
</div>
</div>
diff --git a/apps/mes/app/components/Kanban/components/ItemCard.tsx b/apps/mes/app/components/Kanban/components/ItemCard.tsx
index b32ba5483d..23b48e0cef 100644
--- a/apps/mes/app/components/Kanban/components/ItemCard.tsx
+++ b/apps/mes/app/components/Kanban/components/ItemCard.tsx
@@ -129,7 +129,7 @@ export function ItemCard({
</span>
</div>
<Heading size="h4" className="text-muted-foreground/70">
- {item.operationQuantity}
+ {item.targetQuantity}
</Heading>
</div>
diff --git a/apps/mes/app/components/Kanban/types.ts b/apps/mes/app/components/Kanban/types.ts
index 51438ecbcb..b541743140 100644
--- a/apps/mes/app/components/Kanban/types.ts
+++ b/apps/mes/app/components/Kanban/types.ts
@@ -51,6 +51,7 @@ const itemValidator = z.object({
itemReadableId: z.string().optional(),
jobReadableId: z.string().optional(),
operationQuantity: z.number().optional(),
+ targetQuantity: z.number().optional(),
progress: z.number().optional(), // miliseconds
quantity: z.number().optional(),
quantityCompleted: z.number().optional(),
diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsx
index f4b9c776ba..3322318ff1 100644
--- a/apps/mes/app/routes/x+/operations.tsx
+++ b/apps/mes/app/routes/x+/operations.tsx
@@ -143,6 +143,10 @@ export async function loader({ context, request }: LoaderFunctionArgs) {
)
]);
+ if (operations.error) {
+ console.error(operations.error);
+ }
+
const activeWorkCenters = new Set();
operations.data?.forEach((op) => {
if (op.operationStatus === "In Progress") {
@@ -246,6 +250,7 @@ export async function loader({ context, request }: LoaderFunctionArgs) {
deadlineType: op.jobDeadlineType,
customerId: op.jobCustomerId,
operationQuantity: op.operationQuantity,
+ targetQuantity: op.targetQuantity ?? op.operationQuantity,
jobReadableId: op.jobReadableId,
itemReadableId: op.itemReadableId,
itemDescription: op.itemDescription,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 1efff9abc0..91921c61b4 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -10049,6 +10049,7 @@ export type Database = {
customFields: Json | null
id: string
itemId: string
+ itemScrapPercentage: number
jobId: string
parentMaterialId: string | null
quantityPerParent: number
@@ -10066,6 +10067,7 @@ export type Database = {
customFields?: Json | null
id?: string
itemId: string
+ itemScrapPercentage?: number
jobId: string
parentMaterialId?: string | null
quantityPerParent?: number
@@ -10083,6 +10085,7 @@ export type Database = {
customFields?: Json | null
id?: string
itemId?: string
+ itemScrapPercentage?: number
jobId?: string
parentMaterialId?: string | null
quantityPerParent?: number
@@ -10289,6 +10292,7 @@ export type Database = {
estimatedQuantity: number | null
id: string
itemId: string
+ itemScrapPercentage: number
itemType: string
jobId: string
jobMakeMethodId: string
@@ -10318,6 +10322,7 @@ export type Database = {
estimatedQuantity?: number | null
id?: string
itemId: string
+ itemScrapPercentage?: number
itemType?: string
jobId: string
jobMakeMethodId: string
@@ -10347,6 +10352,7 @@ export type Database = {
estimatedQuantity?: number | null
id?: string
itemId?: string
+ itemScrapPercentage?: number
itemType?: string
jobId?: string
jobMakeMethodId?: string
@@ -10619,6 +10625,7 @@ export type Database = {
startDate: string | null
status: Database["public"]["Enums"]["jobOperationStatus"]
tags: string[] | null
+ targetQuantity: number | null
updatedAt: string | null
updatedBy: string | null
workCenterId: string | null
@@ -10663,6 +10670,7 @@ export type Database = {
startDate?: string | null
status?: Database["public"]["Enums"]["jobOperationStatus"]
tags?: string[] | null
+ targetQuantity?: number | null
updatedAt?: string | null
updatedBy?: string | null
workCenterId?: string | null
@@ -10707,6 +10715,7 @@ export type Database = {
startDate?: string | null
status?: Database["public"]["Enums"]["jobOperationStatus"]
tags?: string[] | null
+ targetQuantity?: number | null
updatedAt?: string | null
updatedBy?: string | null
workCenterId?: string | null
@@ -31325,6 +31334,48 @@ export type Database = {
},
]
}
+ searchIndex_7XFgHYBbyiscTuvDxncdhj: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -46751,14 +46802,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49442,14 +49493,14 @@ 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: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -52935,6 +52986,7 @@ export type Database = {
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
tags: string[]
+ targetQuantity: number
thumbnailPath: string
workCenterId: string
}[]
@@ -53272,6 +53324,7 @@ export type Database = {
quantityScrapped: number
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
+ targetQuantity: number
workCenterId: string
workInstruction: Json
}[]
@@ -53327,6 +53380,7 @@ export type Database = {
quantityScrapped: number
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
+ targetQuantity: number
workCenterId: string
}[]
}
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 95db438bc9..07af96c970 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -34,7 +34,7 @@ import {
getNextRevisionSequence,
getNextSequence,
} from "../shared/get-next-sequence.ts";
-import { KyselyDatabase } from "../lib/postgres/index.js";
+import { KyselyDatabase } from "../lib/postgres/index.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -304,7 +304,7 @@ serve(async (req: Request) => {
.eq("companyId", companyId),
client
.from("job")
- .select("locationId")
+ .select("locationId, quantity")
.eq("id", jobId)
.eq("companyId", companyId)
.single(),
@@ -421,8 +421,42 @@ serve(async (req: Request) => {
// - jobMakeMethodMaterial
async function traverseMethod(
node: MethodTreeItem,
- parentJobMakeMethodId: string | null
+ parentJobMakeMethodId: string | null,
+ parentEstimatedQuantity: number
) {
+ // For root node, targetQuantity equals the job quantity (parentEstimatedQuantity passed in)
+ // For children, targetQuantity = parentEstimatedQuantity * quantityPerParent
+ const targetQuantity = node.data.isRoot
+ ? parentEstimatedQuantity
+ : parentEstimatedQuantity * (node.data.quantity ?? 1);
+
+ // Get scrap percentage for this node's item
+ const nodeItemReplenishment = await trx
+ .selectFrom("itemReplenishment")
+ .select("scrapPercentage")
+ .where("itemId", "=", node.data.itemId)
+ .executeTakeFirst();
+ const nodeScrapPercentage = Number(
+ nodeItemReplenishment?.scrapPercentage ?? 0
+ );
+
+ // Calculate quantities:
+ // - For Make parts: estimatedQuantity = targetQuantity (good quantity, NOT including scrap)
+ // - For Buy/Pick parts: estimatedQuantity = target + scrap (what we need to procure)
+ // - scrapQuantity = targetQuantity * scrapRate (the extra needed for scrap)
+ // - totalForChildren = target + scrap (passed to children for cascade)
+ const nodeScrapQuantity = targetQuantity * nodeScrapPercentage;
+ const totalWithScrap = Math.ceil(targetQuantity + nodeScrapQuantity);
+
+ // For Make: estimatedQuantity is the good quantity (without scrap)
+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure
+ const estimatedQuantity =
+ node.data.methodType === "Make" ? targetQuantity : totalWithScrap;
+ // operationQuantity should be the total (including scrap) since that's what we need to make
+ const operationQuantity = totalWithScrap;
+ // Pass total (including scrap) to children so cascade works correctly
+ const totalQuantityForChildren = totalWithScrap;
+
const nodeLevelConfigurationKey = `${
node.data.materialMakeMethodId
}:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;
@@ -536,6 +570,8 @@ serve(async (req: Request) => {
op.operationSupplierProcessId
),
workInstruction: op.workInstruction,
+ targetQuantity,
+ operationQuantity,
companyId,
createdBy: userId,
customFields: {},
@@ -767,6 +803,19 @@ serve(async (req: Request) => {
itemReplenishment?.scrapPercentage ?? 0
);
+ // Calculate scrap quantities for this material
+ // targetQuantity for this child = parent's total (including scrap) * quantity per parent
+ const childTargetQuantity = totalQuantityForChildren * quantity;
+ // scrapQuantity = portion attributable to scrap
+ const childScrapQuantity = childTargetQuantity * itemScrapPercentage;
+ const childTotalWithScrap = Math.ceil(
+ childTargetQuantity + childScrapQuantity
+ );
+ // For Make: estimatedQuantity is the good quantity (without scrap)
+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure
+ const childEstimatedQuantity =
+ methodType === "Make" ? childTargetQuantity : childTotalWithScrap;
+
return {
jobId,
jobMakeMethodId: parentJobMakeMethodId!,
@@ -779,6 +828,8 @@ serve(async (req: Request) => {
order: child.data.order,
description,
quantity,
+ scrapQuantity: childScrapQuantity,
+ estimatedQuantity: childEstimatedQuantity,
shelfId: locationId
? await getShelfId(
trx,
@@ -877,10 +928,20 @@ serve(async (req: Request) => {
const jobMakeMethodId = materialId
? materialIdToJobMakeMethodId[materialId]
: null;
+ // Get the total quantity (estimated + scrap) for this child material
+ // This is what we pass to children for the cascade
+ const material = madeMaterials[index];
+ const childTotalForCascade =
+ (material?.estimatedQuantity ?? 0) +
+ (material?.scrapQuantity ?? 0);
// prevent an infinite loop
if (child.data.itemId !== itemId && jobMakeMethodId) {
- await traverseMethod(child, jobMakeMethodId);
+ await traverseMethod(
+ child,
+ jobMakeMethodId,
+ childTotalForCascade || 1
+ );
}
}
}
@@ -893,7 +954,12 @@ serve(async (req: Request) => {
}
}
- await traverseMethod(methodTree, jobMakeMethod.data.id);
+ // Start traversal with job quantity as the root's target/parent estimated quantity
+ await traverseMethod(
+ methodTree,
+ jobMakeMethod.data.id,
+ job.data?.quantity ?? 1
+ );
});
break;
@@ -943,6 +1009,27 @@ serve(async (req: Request) => {
companyId
);
+ // Get parent estimated quantity context
+ let parentEstimatedQuantity = 1;
+ if (jobMakeMethod.data.parentMaterialId) {
+ // This is a sub-item - get the parent material's estimated quantity
+ const parentMaterial = await client
+ .from("jobMaterial")
+ .select("estimatedQuantity")
+ .eq("id", jobMakeMethod.data.parentMaterialId)
+ .single();
+ parentEstimatedQuantity =
+ parentMaterial.data?.estimatedQuantity ?? 1;
+ } else {
+ // This is the root - get job's quantity
+ const rootJob = await client
+ .from("job")
+ .select("quantity")
+ .eq("id", jobMakeMethod.data.jobId)
+ .single();
+ parentEstimatedQuantity = rootJob.data?.quantity ?? 1;
+ }
+
const [job, methodTrees, configurationRules] = await Promise.all([
client
.from("job")
@@ -1006,8 +1093,34 @@ serve(async (req: Request) => {
// - jobMakeMethodMaterial
async function traverseMethod(
node: MethodTreeItem,
- parentJobMakeMethodId: string | null
+ parentJobMakeMethodId: string | null,
+ nodeParentEstimatedQuantity: number
) {
+ // Calculate target and estimated quantities for this node
+ const targetQuantity = node.data.isRoot
+ ? nodeParentEstimatedQuantity
+ : nodeParentEstimatedQuantity * (node.data.quantity ?? 1);
+
+ // Get scrap percentage for this node's item
+ const nodeItemReplenishment = await trx
+ .selectFrom("itemReplenishment")
+ .select("scrapPercentage")
+ .where("itemId", "=", node.data.itemId)
+ .executeTakeFirst();
+ const nodeScrapPercentage = Number(
+ nodeItemReplenishment?.scrapPercentage ?? 0
+ );
+
+ // Calculate quantities:
+ // - For Make parts: estimatedQuantity = targetQuantity (good quantity, NOT including scrap)
+ // - For Buy/Pick parts: estimatedQuantity = target + scrap (what we need to procure)
+ const nodeScrapQuantity = targetQuantity * nodeScrapPercentage;
+ const totalWithScrap = Math.ceil(targetQuantity + nodeScrapQuantity);
+ const estimatedQuantity =
+ node.data.methodType === "Make" ? targetQuantity : totalWithScrap;
+ const operationQuantity = totalWithScrap;
+ const totalQuantityForChildren = totalWithScrap;
+
const relatedOperations = await client
.from("methodOperation")
.select(
@@ -1041,6 +1154,8 @@ serve(async (req: Request) => {
),
tags: op.tags ?? [],
workInstruction: op.workInstruction,
+ targetQuantity,
+ operationQuantity,
companyId,
createdBy: userId,
customFields: {},
@@ -1158,6 +1273,22 @@ serve(async (req: Request) => {
itemReplenishment?.scrapPercentage ?? 0
);
+ // Calculate scrap quantities for this material
+ // Use totalQuantityForChildren (parent's total including scrap) for child calculations
+ const childTargetQuantity =
+ totalQuantityForChildren * (child.data.quantity ?? 1);
+ const childScrapQuantity =
+ childTargetQuantity * itemScrapPercentage;
+ const childTotalWithScrap = Math.ceil(
+ childTargetQuantity + childScrapQuantity
+ );
+ // For Make: estimatedQuantity is the good quantity (without scrap)
+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure
+ const childEstimatedQuantity =
+ child.data.methodType === "Make"
+ ? childTargetQuantity
+ : childTotalWithScrap;
+
return {
jobId: jobMakeMethod.data?.jobId!,
jobMakeMethodId: parentJobMakeMethodId!,
@@ -1170,6 +1301,8 @@ serve(async (req: Request) => {
order: child.data.order,
description: child.data.description,
quantity: child.data.quantity,
+ scrapQuantity: childScrapQuantity,
+ estimatedQuantity: childEstimatedQuantity,
requiresBatchTracking: child.data.itemTrackingType === "Batch",
requiresSerialTracking:
child.data.itemTrackingType === "Serial",
@@ -1236,10 +1369,20 @@ serve(async (req: Request) => {
const jobMakeMethodId = materialId
? materialIdToJobMakeMethodId[materialId]
: null;
+ // Get the total quantity (estimated + scrap) for this child material
+ // This is what we pass to children for the cascade
+ const material = madeMaterials[index];
+ const childTotalForCascade =
+ (material?.estimatedQuantity ?? 0) +
+ (material?.scrapQuantity ?? 0);
// prevent an infinite loop
if (child.data.itemId !== itemId && jobMakeMethodId) {
- await traverseMethod(child, jobMakeMethodId);
+ await traverseMethod(
+ child,
+ jobMakeMethodId,
+ childTotalForCascade || 1
+ );
}
}
}
@@ -1252,7 +1395,12 @@ serve(async (req: Request) => {
}
}
- await traverseMethod(methodTree, jobMakeMethod.data.id);
+ // Start traversal with the parent's estimated quantity
+ await traverseMethod(
+ methodTree,
+ jobMakeMethod.data.id,
+ parentEstimatedQuantity
+ );
});
break;
}
@@ -3713,7 +3861,7 @@ serve(async (req: Request) => {
] = await Promise.all([
client
.from("job")
- .select("locationId")
+ .select("locationId, quantity")
.eq("id", jobId)
.eq("companyId", companyId)
.single(),
@@ -3785,6 +3933,11 @@ serve(async (req: Request) => {
const quoteMaterialIdToJobMaterialId: Record<string, string> = {};
const quoteMakeMethodIdToJobMakeMethodId: Record<string, string> = {};
+ // Track estimated quantities for each make method to set on operations
+ const quoteMakeMethodIdToQuantities: Record<
+ string,
+ { targetQuantity: number; estimatedQuantity: number }
+ > = {};
await db.transaction().execute(async (trx) => {
// Delete existing jobMakeMethods, jobMaterials, and jobOperations for this job
@@ -3810,6 +3963,51 @@ serve(async (req: Request) => {
const jobMakeMethodInserts: Database["public"]["Tables"]["jobMakeMethod"]["Insert"][] =
[];
+ // Get the total quantity for this node (parent level) to pass to children
+ // This is estimated + scrap for Make parts (what children use for their target calculation)
+ let nodeTotalForChildren: number;
+ if (node.data.isRoot) {
+ // Root: target = job quantity, calculate scrap and total
+ const rootItemReplenishment = await trx
+ .selectFrom("itemReplenishment")
+ .select("scrapPercentage")
+ .where("itemId", "=", node.data.itemId)
+ .executeTakeFirst();
+ const rootScrapPercentage = Number(
+ rootItemReplenishment?.scrapPercentage ?? 0
+ );
+ const rootTarget = job.data?.quantity ?? 1;
+ const rootScrapQuantity =
+ node.data.methodType === "Make"
+ ? rootTarget * rootScrapPercentage
+ : 0;
+ const rootTotalWithScrap = Math.ceil(
+ rootTarget + rootScrapQuantity
+ );
+ // For Make: estimatedQuantity is good quantity (without scrap)
+ // For Buy/Pick: estimatedQuantity = total (but scrap is 0, so same as target)
+ const rootEstimatedQuantity =
+ node.data.methodType === "Make"
+ ? rootTarget
+ : rootTotalWithScrap;
+
+ nodeTotalForChildren = rootTotalWithScrap;
+
+ // Store root quantities
+ quoteMakeMethodIdToQuantities[quoteMakeMethod.data.id] = {
+ targetQuantity: rootTarget,
+ estimatedQuantity: rootEstimatedQuantity,
+ totalWithScrap: rootTotalWithScrap,
+ };
+ } else {
+ // Non-root: get from stored quantities using parent's quoteMakeMethodId
+ const parentQuoteMakeMethodId = node.data.quoteMaterialMakeMethodId;
+ const parentQuantities =
+ quoteMakeMethodIdToQuantities[parentQuoteMakeMethodId ?? ""];
+ // Children receive parent's total (estimated + scrap) for cascade
+ nodeTotalForChildren = parentQuantities?.totalWithScrap ?? 1;
+ }
+
for await (const child of node.children) {
const newMaterialId = nanoid();
quoteMaterialIdToJobMaterialId[child.id] = newMaterialId;
@@ -3824,6 +4022,35 @@ serve(async (req: Request) => {
itemReplenishment?.scrapPercentage ?? 0
);
+ // Calculate scrap quantities for this child material
+ // Target = parent's total (including scrap) * quantity per parent
+ const childTargetQuantity =
+ nodeTotalForChildren * (child.data.quantity ?? 1);
+ const childScrapQuantity =
+ child.data.methodType === "Make"
+ ? childTargetQuantity * itemScrapPercentage
+ : 0;
+ const childTotalWithScrap = Math.ceil(
+ childTargetQuantity + childScrapQuantity
+ );
+ // For Make: estimatedQuantity is good quantity (without scrap)
+ // For Buy/Pick: estimatedQuantity = total (but scrap is 0, so same as target)
+ const childEstimatedQuantity =
+ child.data.methodType === "Make"
+ ? childTargetQuantity
+ : childTotalWithScrap;
+
+ // Store quantities for this child's make method (if it has one)
+ if (child.data.quoteMaterialMakeMethodId) {
+ quoteMakeMethodIdToQuantities[
+ child.data.quoteMaterialMakeMethodId
+ ] = {
+ targetQuantity: childTargetQuantity,
+ estimatedQuantity: childEstimatedQuantity,
+ totalWithScrap: childTotalWithScrap,
+ };
+ }
+
jobMaterialInserts.push({
id: newMaterialId,
jobId,
@@ -3840,6 +4067,8 @@ serve(async (req: Request) => {
child.data.quoteMakeMethodId
],
quantity: child.data.quantity,
+ scrapQuantity: childScrapQuantity,
+ estimatedQuantity: childEstimatedQuantity,
itemScrapPercentage,
shelfId: await getShelfId(
trx,
@@ -3898,35 +4127,42 @@ serve(async (req: Request) => {
);
const jobOperationInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =
- quoteOperations.data.map((op) => ({
- jobId,
- jobMakeMethodId:
- op.quoteMakeMethodId === quoteMakeMethod.data.id
- ? jobMakeMethod.data.id
- : quoteMakeMethodIdToJobMakeMethodId[op.quoteMakeMethodId!],
- processId: op.processId,
- procedureId: op.procedureId,
- workCenterId: op.workCenterId,
- description: op.description,
- setupTime: op.setupTime,
- setupUnit: op.setupUnit,
- laborTime: op.laborTime,
- laborUnit: op.laborUnit,
- machineTime: op.machineTime,
- machineUnit: op.machineUnit,
- order: op.order,
- operationOrder: op.operationOrder,
- operationType: op.operationType,
- operationSupplierProcessId: op.operationSupplierProcessId,
- operationMinimumCost: op.operationMinimumCost ?? 0,
- operationLeadTime: op.operationLeadTime ?? 0,
- operationUnitCost: op.operationUnitCost ?? 0,
- tags: op.tags ?? [],
- workInstruction: op.workInstruction,
- companyId,
- createdBy: userId,
- customFields: {},
- }));
+ quoteOperations.data.map((op) => {
+ // Get quantities for this operation's make method
+ const opQuantities =
+ quoteMakeMethodIdToQuantities[op.quoteMakeMethodId ?? ""];
+ return {
+ jobId,
+ jobMakeMethodId:
+ op.quoteMakeMethodId === quoteMakeMethod.data.id
+ ? jobMakeMethod.data.id
+ : quoteMakeMethodIdToJobMakeMethodId[op.quoteMakeMethodId!],
+ processId: op.processId,
+ procedureId: op.procedureId,
+ workCenterId: op.workCenterId,
+ description: op.description,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit,
+ order: op.order,
+ operationOrder: op.operationOrder,
+ operationType: op.operationType,
+ operationSupplierProcessId: op.operationSupplierProcessId,
+ operationMinimumCost: op.operationMinimumCost ?? 0,
+ operationLeadTime: op.operationLeadTime ?? 0,
+ operationUnitCost: op.operationUnitCost ?? 0,
+ tags: op.tags ?? [],
+ workInstruction: op.workInstruction,
+ targetQuantity: opQuantities?.targetQuantity ?? 0,
+ operationQuantity: opQuantities?.totalWithScrap ?? 0,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ };
+ });
if (jobOperationInserts.length > 0) {
const operationIds = await trx
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index d663b736e8..91921c61b4 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -10049,6 +10049,7 @@ export type Database = {
customFields: Json | null
id: string
itemId: string
+ itemScrapPercentage: number
jobId: string
parentMaterialId: string | null
quantityPerParent: number
@@ -10066,6 +10067,7 @@ export type Database = {
customFields?: Json | null
id?: string
itemId: string
+ itemScrapPercentage?: number
jobId: string
parentMaterialId?: string | null
quantityPerParent?: number
@@ -10083,6 +10085,7 @@ export type Database = {
customFields?: Json | null
id?: string
itemId?: string
+ itemScrapPercentage?: number
jobId?: string
parentMaterialId?: string | null
quantityPerParent?: number
@@ -10289,6 +10292,7 @@ export type Database = {
estimatedQuantity: number | null
id: string
itemId: string
+ itemScrapPercentage: number
itemType: string
jobId: string
jobMakeMethodId: string
@@ -10318,6 +10322,7 @@ export type Database = {
estimatedQuantity?: number | null
id?: string
itemId: string
+ itemScrapPercentage?: number
itemType?: string
jobId: string
jobMakeMethodId: string
@@ -10347,6 +10352,7 @@ export type Database = {
estimatedQuantity?: number | null
id?: string
itemId?: string
+ itemScrapPercentage?: number
itemType?: string
jobId?: string
jobMakeMethodId?: string
@@ -10619,6 +10625,7 @@ export type Database = {
startDate: string | null
status: Database["public"]["Enums"]["jobOperationStatus"]
tags: string[] | null
+ targetQuantity: number | null
updatedAt: string | null
updatedBy: string | null
workCenterId: string | null
@@ -10663,6 +10670,7 @@ export type Database = {
startDate?: string | null
status?: Database["public"]["Enums"]["jobOperationStatus"]
tags?: string[] | null
+ targetQuantity?: number | null
updatedAt?: string | null
updatedBy?: string | null
workCenterId?: string | null
@@ -10707,6 +10715,7 @@ export type Database = {
startDate?: string | null
status?: Database["public"]["Enums"]["jobOperationStatus"]
tags?: string[] | null
+ targetQuantity?: number | null
updatedAt?: string | null
updatedBy?: string | null
workCenterId?: string | null
@@ -31325,6 +31334,48 @@ export type Database = {
},
]
}
+ searchIndex_7XFgHYBbyiscTuvDxncdhj: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -46751,14 +46802,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49442,14 +49493,14 @@ 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: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -52935,6 +52986,7 @@ export type Database = {
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
tags: string[]
+ targetQuantity: number
thumbnailPath: string
workCenterId: string
}[]
@@ -53136,6 +53188,7 @@ export type Database = {
reorderPoint: number
reorderQuantity: number
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
+ tags: string[]
thumbnailPath: string
type: Database["public"]["Enums"]["itemType"]
unitOfMeasureCode: string
@@ -53271,6 +53324,7 @@ export type Database = {
quantityScrapped: number
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
+ targetQuantity: number
workCenterId: string
workInstruction: Json
}[]
@@ -53326,6 +53380,7 @@ export type Database = {
quantityScrapped: number
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
+ targetQuantity: number
workCenterId: string
}[]
}
diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.ts
index e3eb9573ee..3360a23644 100644
--- a/packages/database/supabase/functions/recalculate/index.ts
+++ b/packages/database/supabase/functions/recalculate/index.ts
@@ -166,11 +166,12 @@ serve(async (req: Request) => {
}
await db.transaction().execute(async (trx) => {
- // Use productionQuantity (quantity + scrapQuantity) to include job-level scrap
+ // Use job.quantity as the root's target quantity (not productionQuantity)
+ // The item's scrap percentage will be applied within updateJobQuantities
await updateJobQuantities(
trx,
jobMethodTree,
- job.data?.productionQuantity ?? job.data?.quantity
+ job.data?.quantity ?? 1
);
});
@@ -202,29 +203,60 @@ serve(async (req: Request) => {
const updateJobQuantities = async (
trx: Transaction<DB>,
tree: JobMethodTreeItem,
- parentQuantity: number = 1
+ parentEstimatedQuantity: number = 1
) => {
- const baseQuantity = tree.data.quantity * parentQuantity;
-
- // For Make-type items, inflate quantity to account for scrap rate
- let currentQuantity = baseQuantity;
- if (tree.data.methodType === "Make" && !tree.data.isRoot) {
- const itemReplenishment = await trx
- .selectFrom("itemReplenishment")
- .select("scrapPercentage")
- .where("itemId", "=", tree.data.itemId)
+ // Target quantity for this node:
+ // - For root: targetQuantity = parentEstimatedQuantity (which is productionQuantity from job)
+ // - For children: targetQuantity = parentEstimatedQuantity * quantity (quantity per parent)
+ const targetQuantity = tree.data.isRoot
+ ? parentEstimatedQuantity
+ : tree.data.quantity * parentEstimatedQuantity;
+
+ // Get scrap percentage from jobMaterial (stored at job creation time)
+ // Fall back to itemReplenishment if not stored
+ let scrapPercentage = 0;
+ if (tree.data.methodType === "Make") {
+ const jobMaterial = await trx
+ .selectFrom("jobMaterial")
+ .select("itemScrapPercentage")
+ .where("id", "=", tree.id)
.executeTakeFirst();
- const scrapPercentage = Number(itemReplenishment?.scrapPercentage ?? 0);
- if (scrapPercentage > 0 && scrapPercentage < 100) {
- currentQuantity = Math.ceil(baseQuantity / (1 - scrapPercentage / 100));
+ if (
+ jobMaterial?.itemScrapPercentage != null &&
+ jobMaterial.itemScrapPercentage > 0
+ ) {
+ scrapPercentage = Number(jobMaterial.itemScrapPercentage);
+ } else {
+ // Fall back to itemReplenishment
+ const itemReplenishment = await trx
+ .selectFrom("itemReplenishment")
+ .select("scrapPercentage")
+ .where("itemId", "=", tree.data.itemId)
+ .executeTakeFirst();
+ scrapPercentage = Number(itemReplenishment?.scrapPercentage ?? 0);
}
}
- // Update jobMaterial
+ // Calculate scrap and estimated quantities
+ // scrapQuantity = portion attributable to scrap (only for Make parts)
+ // totalWithScrap = target + scrap allowance (what we need to make/procure)
+ // estimatedQuantity: For Make = good quantity (without scrap), For Buy/Pick = total
+ const scrapQuantity =
+ tree.data.methodType === "Make" ? targetQuantity * scrapPercentage : 0;
+ const totalWithScrap = Math.ceil(targetQuantity + scrapQuantity);
+ // For Make: estimatedQuantity is good quantity (without scrap)
+ // For Buy/Pick: estimatedQuantity = total (but scrap is 0, so same as target)
+ const estimatedQuantity =
+ tree.data.methodType === "Make" ? targetQuantity : totalWithScrap;
+
+ // Update jobMaterial with scrap and estimated quantities
await trx
.updateTable("jobMaterial")
- .set({ estimatedQuantity: currentQuantity })
+ .set({
+ scrapQuantity: scrapQuantity,
+ estimatedQuantity: estimatedQuantity,
+ })
.where("id", "=", tree.id)
.execute();
@@ -242,7 +274,10 @@ const updateJobQuantities = async (
.execute(),
trx
.updateTable("jobOperation")
- .set({ operationQuantity: currentQuantity })
+ .set({
+ targetQuantity: targetQuantity,
+ operationQuantity: totalWithScrap,
+ })
.where("jobMakeMethodId", "=", tree.data.jobMaterialMakeMethodId)
.execute(),
]);
@@ -251,17 +286,18 @@ const updateJobQuantities = async (
await trx
.updateTable("trackedEntity")
.set({
- quantity: jobMakeMethod.requiresSerialTracking ? 1 : currentQuantity,
+ quantity: jobMakeMethod.requiresSerialTracking ? 1 : totalWithScrap,
})
.where("id", "=", jobMakeMethod.trackedEntityId)
.execute();
}
}
- // Recursively update children
+ // Recursively update children with this node's total (estimated + scrap)
+ // Children use the total for their target calculation to properly cascade scrap
if (tree.children) {
for (const child of tree.children) {
- await updateJobQuantities(trx, child, currentQuantity);
+ await updateJobQuantities(trx, child, totalWithScrap);
}
}
};
diff --git a/packages/database/supabase/migrations/20260119120000_add-target-quantity-to-job-operation.sql b/packages/database/supabase/migrations/20260119120000_add-target-quantity-to-job-operation.sql
new file mode 100644
index 0000000000..85db6d9c26
--- /dev/null
+++ b/packages/database/supabase/migrations/20260119120000_add-target-quantity-to-job-operation.sql
@@ -0,0 +1,8 @@
+-- Add targetQuantity column to jobOperation table
+-- This stores the quantity to produce before accounting for scrap
+-- (parent.estimatedQuantity * quantityPerParent for children, or productionQuantity for root)
+ALTER TABLE "jobOperation"
+ ADD COLUMN IF NOT EXISTS "targetQuantity" NUMERIC DEFAULT 0;
+
+-- Add comment for documentation
+COMMENT ON COLUMN "jobOperation"."targetQuantity" IS 'The target quantity to produce before accounting for scrap (parent.estimatedQuantity * quantityPerParent)';
diff --git a/packages/database/supabase/migrations/20260119130000_add-target-quantity-to-operation-functions.sql b/packages/database/supabase/migrations/20260119130000_add-target-quantity-to-operation-functions.sql
new file mode 100644
index 0000000000..2fdda1dc0d
--- /dev/null
+++ b/packages/database/supabase/migrations/20260119130000_add-target-quantity-to-operation-functions.sql
@@ -0,0 +1,196 @@
+-- Add targetQuantity to get_active_job_operations_by_location function
+DROP FUNCTION IF EXISTS get_active_job_operations_by_location;
+CREATE OR REPLACE FUNCTION get_active_job_operations_by_location(
+ location_id TEXT,
+ work_center_ids TEXT[]
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "jobId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "priority" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ "description" TEXT,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "jobCustomerId" TEXT,
+ "customerName" TEXT,
+ "parentMaterialId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "operationStatus" "jobOperationStatus",
+ "targetQuantity" NUMERIC,
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityScrapped" NUMERIC,
+ "salesOrderId" TEXT,
+ "salesOrderLineId" TEXT,
+ "salesOrderReadableId" TEXT,
+ "assignee" TEXT,
+ "tags" TEXT[],
+ "thumbnailPath" TEXT
+)
+SECURITY INVOKER
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH relevant_jobs AS (
+ SELECT *
+ FROM "job"
+ WHERE "locationId" = location_id
+ AND ("status" = 'Ready' OR "status" = 'In Progress' OR "status" = 'Paused')
+ )
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."jobMakeMethodId",
+ jo."order" AS "operationOrder",
+ jo."priority",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ rj."jobId" AS "jobReadableId",
+ rj."status" AS "jobStatus",
+ rj."dueDate" AS "jobDueDate",
+ rj."deadlineType" AS "jobDeadlineType",
+ rj."customerId" AS "jobCustomerId",
+ c."name" AS "customerName",
+ jmm."parentMaterialId",
+ i."readableId" as "itemReadableId",
+ i."name" as "itemDescription",
+ CASE
+ WHEN rj."status" = 'Paused' THEN 'Paused'
+ ELSE jo."status"
+ END AS "operationStatus",
+ jo."targetQuantity"::NUMERIC,
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityScrapped",
+ rj."salesOrderId",
+ rj."salesOrderLineId",
+ so."salesOrderId" as "salesOrderReadableId",
+ jo."assignee",
+ jo."tags",
+ COALESCE(mu."thumbnailPath", i."thumbnailPath") as "thumbnailPath"
+ FROM "jobOperation" jo
+ JOIN relevant_jobs rj ON rj.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ LEFT JOIN "customer" c ON rj."customerId" = c.id
+ LEFT JOIN "salesOrder" so ON rj."salesOrderId" = so.id
+ LEFT JOIN "modelUpload" mu ON i."modelUploadId" = mu.id
+ WHERE CASE
+ WHEN array_length(work_center_ids, 1) > 0 THEN
+ jo."workCenterId" = ANY(work_center_ids) AND jo."status" != 'Done' AND jo."status" != 'Canceled'
+ ELSE jo."status" != 'Done' AND jo."status" != 'Canceled'
+ END
+ ORDER BY jo."startDate", jo."priority";
+
+END;
+$$ LANGUAGE plpgsql;
+
+
+-- Add targetQuantity to get_job_operation_by_id function
+DROP FUNCTION IF EXISTS get_job_operation_by_id(TEXT);
+CREATE OR REPLACE FUNCTION get_job_operation_by_id(operation_id TEXT)
+RETURNS TABLE (
+ id TEXT,
+ "jobId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ description TEXT,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "parentMaterialId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "itemUnitOfMeasure" TEXT,
+ "itemModelPath" TEXT,
+ "itemModelId" TEXT,
+ "itemModelName" TEXT,
+ "itemModelSize" BIGINT,
+ "operationStatus" "jobOperationStatus",
+ "targetQuantity" NUMERIC,
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityReworked" NUMERIC,
+ "quantityScrapped" NUMERIC,
+ "workInstruction" JSON
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."jobMakeMethodId",
+ jo."order" AS "operationOrder",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ j."jobId" AS "jobReadableId",
+ j."status" AS "jobStatus",
+ j."dueDate"::DATE AS "jobDueDate",
+ j."deadlineType" AS "jobDeadlineType",
+ jmm."parentMaterialId",
+ i."id" as "itemId",
+ i."readableIdWithRevision" as "itemReadableId",
+ i."name" as "itemDescription",
+ uom."name" as "itemUnitOfMeasure",
+ m."modelPath" as "itemModelPath",
+ m."id" as "itemModelId",
+ m."name" as "itemModelName",
+ m."size" as "itemModelSize",
+ jo."status" AS "operationStatus",
+ jo."targetQuantity"::NUMERIC,
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityReworked",
+ jo."quantityScrapped",
+ jo."workInstruction"
+ FROM "jobOperation" jo
+ JOIN "job" j ON j.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ LEFT JOIN "unitOfMeasure" uom ON i."unitOfMeasureCode" = uom."code" AND i."companyId" = uom."companyId"
+ LEFT JOIN "modelUpload" m ON i."modelUploadId" = m.id
+ WHERE jo.id = operation_id
+ LIMIT 1;
+END;
+$$ LANGUAGE plpgsql;