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.

llm: implement scrap workflow

Brad Barbin0dc2f5ceb1a3
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index d32891afb0..29bb271fd4 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -188,12 +188,19 @@ export const jobValidator = baseJobValidator.refine(
}
);
+export const leftoverAction = ["ship", "receive", "split", "discard"] as const;
+export type LeftoverAction = (typeof leftoverAction)[number];
+
export const jobCompleteValidator = z.object({
quantityComplete: zfd.numeric(z.number().min(0)),
salesOrderId: zfd.text(z.string().optional()),
salesOrderLineId: zfd.text(z.string().optional()),
locationId: zfd.text(z.string().optional()),
- shelfId: zfd.text(z.string().optional())
+ shelfId: zfd.text(z.string().optional()),
+ // Leftover handling fields - for when quantityComplete > job.quantity
+ leftoverAction: zfd.text(z.enum(leftoverAction).optional()),
+ leftoverShipQuantity: zfd.numeric(z.number().min(0).optional()),
+ leftoverReceiveQuantity: zfd.numeric(z.number().min(0).optional())
});
export const salesOrderToJobValidator = baseJobValidator
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index c1d38a3c06..7e9930c201 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -163,6 +163,13 @@ export async function convertSalesOrderLinesToJobs(
companyId
);
+ // Calculate scrap quantity based on item's scrap percentage
+ const scrapPercentage = manufacturing.data?.scrapPercentage ?? 0;
+ const scrapQuantity =
+ scrapPercentage > 0
+ ? Math.ceil(jobQuantity * (scrapPercentage / 100))
+ : 0;
+
const data = {
customerId: salesOrder.data?.customerId ?? undefined,
deadlineType: "Hard Deadline" as const,
@@ -180,7 +187,7 @@ export async function convertSalesOrderLinesToJobs(
quoteLineId: quoteId ? line.id : undefined,
salesOrderId: salesOrderId ?? undefined,
salesOrderLineId: line.id,
- scrapQuantity: 0,
+ scrapQuantity,
shelfId: shelfId ?? undefined,
unitOfMeasureCode: line.unitOfMeasureCode ?? "EA"
};
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
index f6e167ae70..caa25a1d75 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -869,7 +869,17 @@ function JobCompleteModal({
);
const [hasTrackedQuantity, setHasTrackedQuantity] = useState<boolean>(false);
+ // Leftover handling state
+ const [leftoverAction, setLeftoverAction] = useState<
+ "ship" | "receive" | "split" | "discard" | undefined
+ >(undefined);
+ const [leftoverShipQuantity, setLeftoverShipQuantity] = useState<number>(0);
+ const [leftoverReceiveQuantity, setLeftoverReceiveQuantity] =
+ useState<number>(0);
+
const makeToOrder = !!job?.salesOrderId && !!job?.salesOrderLineId;
+ const leftoverQuantity = Math.max(0, quantityComplete - (job?.quantity ?? 0));
+ const hasLeftover = leftoverQuantity > 0;
const getJobData = async () => {
if (!carbon) return;
@@ -924,11 +934,33 @@ function JobCompleteModal({
getJobData();
});
+ // Update leftover quantities when action changes
+ const handleLeftoverActionChange = (
+ action: "ship" | "receive" | "split" | "discard"
+ ) => {
+ setLeftoverAction(action);
+ if (action === "ship") {
+ setLeftoverShipQuantity(leftoverQuantity);
+ setLeftoverReceiveQuantity(0);
+ } else if (action === "receive") {
+ setLeftoverShipQuantity(0);
+ setLeftoverReceiveQuantity(leftoverQuantity);
+ } else if (action === "split") {
+ // Default to half and half, user can adjust
+ const halfQty = Math.floor(leftoverQuantity / 2);
+ setLeftoverShipQuantity(halfQty);
+ setLeftoverReceiveQuantity(leftoverQuantity - halfQty);
+ } else {
+ setLeftoverShipQuantity(0);
+ setLeftoverReceiveQuantity(0);
+ }
+ };
+
if (!job) return null;
return (
<Modal open onOpenChange={onClose}>
- <ModalContent>
+ <ModalContent size={hasLeftover ? "large" : "medium"}>
{loading ? (
<ModalBody>
<div className="flex flex-col h-[118px] w-full items-center justify-center gap-2">
@@ -964,6 +996,15 @@ function JobCompleteModal({
</ModalHeader>
<Hidden name="salesOrderId" />
<Hidden name="salesOrderLineId" />
+ <Hidden name="leftoverAction" value={leftoverAction} />
+ <Hidden
+ name="leftoverShipQuantity"
+ value={leftoverShipQuantity.toString()}
+ />
+ <Hidden
+ name="leftoverReceiveQuantity"
+ value={leftoverReceiveQuantity.toString()}
+ />
{makeToOrder && (
<>
<Hidden name="locationId" />
@@ -989,6 +1030,137 @@ function JobCompleteModal({
onChange={(value) => setQuantityComplete(value)}
isReadOnly={hasTrackedQuantity}
/>
+
+ {hasLeftover && (
+ <>
+ <Alert>
+ <LuPackage />
+ <AlertTitle>Leftover Parts Detected</AlertTitle>
+ <AlertDescription>
+ You completed {leftoverQuantity} more{" "}
+ {leftoverQuantity === 1 ? "part" : "parts"} than the
+ ordered quantity of {job.quantity}. What would you like
+ to do with the extra parts?
+ </AlertDescription>
+ </Alert>
+
+ <div className="grid grid-cols-2 gap-2 w-full">
+ {makeToOrder && (
+ <Button
+ variant={
+ leftoverAction === "ship" ? "primary" : "secondary"
+ }
+ onClick={() => handleLeftoverActionChange("ship")}
+ type="button"
+ className="h-auto py-3"
+ >
+ <VStack spacing={1}>
+ <span>Ship to Customer</span>
+ <span className="text-xs opacity-70">
+ Include extra parts in shipment
+ </span>
+ </VStack>
+ </Button>
+ )}
+ <Button
+ variant={
+ leftoverAction === "receive" ? "primary" : "secondary"
+ }
+ onClick={() => handleLeftoverActionChange("receive")}
+ type="button"
+ className="h-auto py-3"
+ >
+ <VStack spacing={1}>
+ <span>Receive to Inventory</span>
+ <span className="text-xs opacity-70">
+ Add to stock for future use
+ </span>
+ </VStack>
+ </Button>
+ {makeToOrder && (
+ <Button
+ variant={
+ leftoverAction === "split" ? "primary" : "secondary"
+ }
+ onClick={() => handleLeftoverActionChange("split")}
+ type="button"
+ className="h-auto py-3"
+ >
+ <VStack spacing={1}>
+ <span>Split</span>
+ <span className="text-xs opacity-70">
+ Ship some, stock some
+ </span>
+ </VStack>
+ </Button>
+ )}
+ <Button
+ variant={
+ leftoverAction === "discard" ? "primary" : "secondary"
+ }
+ onClick={() => handleLeftoverActionChange("discard")}
+ type="button"
+ className="h-auto py-3"
+ >
+ <VStack spacing={1}>
+ <span>Discard</span>
+ <span className="text-xs opacity-70">
+ No action needed
+ </span>
+ </VStack>
+ </Button>
+ </div>
+
+ {leftoverAction === "split" && (
+ <HStack className="w-full">
+ <div className="flex-1">
+ <label className="text-sm font-medium">
+ Ship to Customer
+ </label>
+ <input
+ type="number"
+ className="w-full mt-1 px-3 py-2 border rounded-md"
+ value={leftoverShipQuantity}
+ onChange={(e) => {
+ const shipQty = Math.min(
+ Number(e.target.value),
+ leftoverQuantity
+ );
+ setLeftoverShipQuantity(shipQty);
+ setLeftoverReceiveQuantity(
+ leftoverQuantity - shipQty
+ );
+ }}
+ min={0}
+ max={leftoverQuantity}
+ />
+ </div>
+ <div className="flex-1">
+ <label className="text-sm font-medium">
+ Receive to Inventory
+ </label>
+ <input
+ type="number"
+ className="w-full mt-1 px-3 py-2 border rounded-md"
+ value={leftoverReceiveQuantity}
+ onChange={(e) => {
+ const receiveQty = Math.min(
+ Number(e.target.value),
+ leftoverQuantity
+ );
+ setLeftoverReceiveQuantity(receiveQty);
+ setLeftoverShipQuantity(
+ leftoverQuantity - receiveQty
+ );
+ }}
+ min={0}
+ max={leftoverQuantity}
+ />
+ </div>
+ </HStack>
+ )}
+ </>
+ )}
</VStack>
</ModalBody>
<ModalFooter>
@@ -996,7 +1168,9 @@ function JobCompleteModal({
Cancel
</Button>
- <Button type="submit">Complete Job</Button>
+ <Button type="submit" isDisabled={hasLeftover && !leftoverAction}>
+ Complete Job
+ </Button>
</ModalFooter>
</ValidatedForm>
)}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx b/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
index dc69ced70e..4f313e6211 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
@@ -41,11 +41,58 @@ export async function action({ request, params }: ActionFunctionArgs) {
salesOrderId,
salesOrderLineId,
locationId,
- shelfId
+ shelfId,
+ leftoverAction,
+ leftoverShipQuantity,
+ leftoverReceiveQuantity
} = validation.data;
const makeToOrder = !!salesOrderId || !!salesOrderLineId;
+ // Get job data to calculate leftovers
+ const job = await client
+ .from("job")
+ .select("quantity")
+ .eq("id", jobId)
+ .single();
+ if (job.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(request, error(job.error, "Failed to get job data"))
+ );
+ }
+
+ const originalQuantity = job.data?.quantity ?? 0;
+ const leftoverQuantity = Math.max(0, quantityComplete - originalQuantity);
+ const hasLeftover = leftoverQuantity > 0;
+
+ // Calculate what to ship vs receive based on leftover action
+ let quantityToShip = originalQuantity; // Default: ship original quantity
+ let quantityToReceiveToInventory = 0;
+
+ if (hasLeftover && leftoverAction) {
+ switch (leftoverAction) {
+ case "ship":
+ // Ship all completed (including leftovers) to customer
+ quantityToShip = quantityComplete;
+ break;
+ case "receive":
+ // Ship original quantity, receive leftovers to inventory
+ quantityToShip = originalQuantity;
+ quantityToReceiveToInventory = leftoverQuantity;
+ break;
+ case "split":
+ // Ship original + specified amount, receive rest to inventory
+ quantityToShip = originalQuantity + (leftoverShipQuantity ?? 0);
+ quantityToReceiveToInventory = leftoverReceiveQuantity ?? 0;
+ break;
+ case "discard":
+ // Ship original quantity, discard leftovers (no action)
+ quantityToShip = originalQuantity;
+ break;
+ }
+ }
+
if (makeToOrder) {
const makeToOrderUpdate = await client
.from("job")
@@ -53,6 +100,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
status: "Completed" as const,
completedDate: new Date().toISOString(),
quantityComplete,
+ quantityShipped: quantityToShip,
updatedAt: new Date().toISOString(),
updatedBy: userId
})
@@ -67,7 +115,35 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
);
}
+
+ // If we need to receive leftovers to inventory
+ if (quantityToReceiveToInventory > 0) {
+ const serviceRole = await getCarbonServiceRole();
+ const issue = await serviceRole.functions.invoke("issue", {
+ body: {
+ jobId,
+ type: "jobCompleteInventory",
+ companyId,
+ userId,
+ quantityComplete: quantityToReceiveToInventory,
+ shelfId,
+ locationId
+ },
+ region: FunctionRegion.UsEast1
+ });
+
+ if (issue.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(
+ request,
+ error(issue.error, "Failed to receive leftovers to inventory")
+ )
+ );
+ }
+ }
} else {
+ // Make-to-stock: receive all completed to inventory
const serviceRole = await getCarbonServiceRole();
const issue = await serviceRole.functions.invoke("issue", {
body: {
diff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsx
index ec8bdddb07..a2f5259897 100644
--- a/apps/erp/app/routes/x+/job+/new.tsx
+++ b/apps/erp/app/routes/x+/job+/new.tsx
@@ -45,36 +45,45 @@ export async function action({ request }: ActionFunctionArgs) {
let jobId = validation.data.jobId;
const useNextSequence = !jobId;
- let leadTime = 7;
+
+ // Fetch manufacturing data for lead time and scrap percentage
+ const [nextSequenceResult, manufacturing] = await Promise.all([
+ useNextSequence
+ ? getNextSequence(client, "job", companyId)
+ : Promise.resolve({ data: null, error: null }),
+ getItemReplenishment(client, validation.data.itemId, companyId)
+ ]);
if (useNextSequence) {
- const [nextSequence, manufacturing] = await Promise.all([
- getNextSequence(client, "job", companyId),
- getItemReplenishment(client, validation.data.itemId, companyId)
- ]);
- if (nextSequence.error) {
+ if (nextSequenceResult.error) {
throw redirect(
path.to.newJob,
await flash(
request,
- error(nextSequence.error, "Failed to get next sequence")
+ error(nextSequenceResult.error, "Failed to get next sequence")
)
);
}
- jobId = nextSequence.data;
- leadTime = manufacturing.data?.leadTime ?? 7;
- } else {
- const manufacturing = await getItemReplenishment(
- client,
- validation.data.itemId,
- companyId
- );
- leadTime = manufacturing.data?.leadTime ?? 7;
+ jobId = nextSequenceResult.data;
}
+ const leadTime = manufacturing.data?.leadTime ?? 7;
+
if (!jobId) throw new Error("jobId is not defined");
const { id: _id, ...d } = validation.data;
+ // Calculate scrap quantity from the item's scrap percentage if not set
+ const scrapPercentage = manufacturing.data?.scrapPercentage ?? 0;
+ const calculatedScrapQuantity =
+ scrapPercentage > 0
+ ? Math.ceil(validation.data.quantity * (scrapPercentage / 100))
+ : 0;
+ // Use the form value if set, otherwise use calculated value
+ const scrapQuantity =
+ d.scrapQuantity && d.scrapQuantity > 0
+ ? d.scrapQuantity
+ : calculatedScrapQuantity;
+
let configuration = undefined;
if (d.configuration) {
try {
@@ -104,6 +113,7 @@ export async function action({ request }: ActionFunctionArgs) {
jobId,
configuration,
priority,
+ scrapQuantity,
shelfId: shelfId ?? undefined,
startDate: d.dueDate
? parseDate(d.dueDate).subtract({ days: leadTime }).toString()
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsx
index e3858a4ad6..a705382d71 100644
--- a/apps/erp/app/routes/x+/production+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx
@@ -182,15 +182,20 @@ export async function action({ request }: ActionFunctionArgs) {
companyId
);
+ // Calculate scrap quantity based on scrap percentage
+ const scrapPercentage = manufacturing.data?.scrapPercentage ?? 0;
+ const scrapQuantity =
+ scrapPercentage > 0
+ ? Math.ceil(order.quantity * (scrapPercentage / 100))
+ : 0;
+
const createJob = await upsertJob(
client,
{
itemId: item.id,
jobId,
quantity: order.quantity,
- scrapQuantity: Math.ceil(
- order.quantity * (manufacturing.data?.scrapPercentage ?? 0)
- ),
+ scrapQuantity,
startDate: order.startDate ?? undefined,
dueDate: order.dueDate ?? undefined,
deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",
@@ -237,15 +242,22 @@ export async function action({ request }: ActionFunctionArgs) {
} else {
// Update existing job
jobIds.push(order.existingId);
+
+ // Calculate scrap quantity based on scrap percentage
+ const updateScrapPercentage =
+ manufacturing.data?.scrapPercentage ?? 0;
+ const updateScrapQuantity =
+ updateScrapPercentage > 0
+ ? Math.ceil(order.quantity * (updateScrapPercentage / 100))
+ : 0;
+
const updateJob = await client
.from("job")
.update({
dueDate: order.dueDate ?? undefined,
deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",
quantity: order.quantity,
- scrapQuantity: Math.ceil(
- order.quantity * (manufacturing.data?.scrapPercentage ?? 0)
- ),
+ scrapQuantity: updateScrapQuantity,
startDate: order.startDate ?? undefined,
status: "Planned",
updatedAt: new Date().toISOString(),
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 3d354feff4..95db438bc9 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -34,6 +34,7 @@ import {
getNextRevisionSequence,
getNextSequence,
} from "../shared/get-next-sequence.ts";
+import { KyselyDatabase } from "../lib/postgres/index.js";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -756,6 +757,16 @@ serve(async (req: Request) => {
}
}
+ // Get scrap percentage for this item
+ const itemReplenishment = await trx
+ .selectFrom("itemReplenishment")
+ .select("scrapPercentage")
+ .where("itemId", "=", itemId)
+ .executeTakeFirst();
+ const itemScrapPercentage = Number(
+ itemReplenishment?.scrapPercentage ?? 0
+ );
+
return {
jobId,
jobMakeMethodId: parentJobMakeMethodId!,
@@ -781,6 +792,7 @@ serve(async (req: Request) => {
requiresBatchTracking,
unitOfMeasureCode,
unitCost,
+ itemScrapPercentage,
companyId,
createdBy: userId,
customFields: {},
@@ -970,7 +982,7 @@ serve(async (req: Request) => {
return acc;
}, {});
- await db.transaction().execute(async (trx) => {
+ await db.transaction().execute(async (trx: Transaction) => {
// Delete existing jobMakeMethodOperation, jobMakeMethodMaterial
await Promise.all([
trx
@@ -1135,33 +1147,47 @@ serve(async (req: Request) => {
const mapMethodMaterialToJobMaterial = async (
child: MethodTreeItem
- ) => ({
- jobId: jobMakeMethod.data?.jobId!,
- jobMakeMethodId: parentJobMakeMethodId!,
- jobOperationId:
- methodOperationsToJobOperations[child.data.operationId],
- itemId: child.data.itemId,
- kit: child.data.kit,
- itemType: child.data.itemType,
- methodType: child.data.methodType,
- order: child.data.order,
- description: child.data.description,
- quantity: child.data.quantity,
- requiresBatchTracking: child.data.itemTrackingType === "Batch",
- requiresSerialTracking: child.data.itemTrackingType === "Serial",
- unitOfMeasureCode: child.data.unitOfMeasureCode,
- unitCost: child.data.unitCost,
- shelfId: await getShelfId(
- trx,
- child.data.itemId,
- job.data?.locationId ?? "",
- // @ts-ignore
- child.data.shelfIds?.[job.data.locationId] ?? undefined
- ),
- companyId,
- createdBy: userId,
- customFields: {},
- });
+ ) => {
+ // Get scrap percentage for this item
+ const itemReplenishment = await trx
+ .selectFrom("itemReplenishment")
+ .select("scrapPercentage")
+ .where("itemId", "=", child.data.itemId)
+ .executeTakeFirst();
+ const itemScrapPercentage = Number(
+ itemReplenishment?.scrapPercentage ?? 0
+ );
+
+ return {
+ jobId: jobMakeMethod.data?.jobId!,
+ jobMakeMethodId: parentJobMakeMethodId!,
+ jobOperationId:
+ methodOperationsToJobOperations[child.data.operationId],
+ itemId: child.data.itemId,
+ kit: child.data.kit,
+ itemType: child.data.itemType,
+ methodType: child.data.methodType,
+ order: child.data.order,
+ description: child.data.description,
+ quantity: child.data.quantity,
+ requiresBatchTracking: child.data.itemTrackingType === "Batch",
+ requiresSerialTracking:
+ child.data.itemTrackingType === "Serial",
+ unitOfMeasureCode: child.data.unitOfMeasureCode,
+ unitCost: child.data.unitCost,
+ itemScrapPercentage,
+ shelfId: await getShelfId(
+ trx,
+ child.data.itemId,
+ job.data?.locationId ?? "",
+ // @ts-ignore: shelfIds is a dynamic field
+ child.data.shelfIds?.[job.data.locationId] ?? undefined
+ ),
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ };
+ };
const madeMaterials: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =
[];
@@ -1322,7 +1348,7 @@ serve(async (req: Request) => {
supplierProcesses?.data
);
- await db.transaction().execute(async (trx) => {
+ await db.transaction().execute(async (trx: Transaction<KyselyDatabase>) => {
// Delete existing quoteMakeMethod, quoteMakeMethodOperation, quoteMakeMethodMaterial
await Promise.all([
trx
@@ -3788,6 +3814,16 @@ serve(async (req: Request) => {
const newMaterialId = nanoid();
quoteMaterialIdToJobMaterialId[child.id] = newMaterialId;
+ // Get scrap percentage for this item
+ const itemReplenishment = await trx
+ .selectFrom("itemReplenishment")
+ .select("scrapPercentage")
+ .where("itemId", "=", child.data.itemId)
+ .executeTakeFirst();
+ const itemScrapPercentage = Number(
+ itemReplenishment?.scrapPercentage ?? 0
+ );
+
jobMaterialInserts.push({
id: newMaterialId,
jobId,
@@ -3804,6 +3840,7 @@ serve(async (req: Request) => {
child.data.quoteMakeMethodId
],
quantity: child.data.quantity,
+ itemScrapPercentage,
shelfId: await getShelfId(
trx,
child.data.itemId,
diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.ts
index 47b2d35162..e3eb9573ee 100644
--- a/packages/database/supabase/functions/recalculate/index.ts
+++ b/packages/database/supabase/functions/recalculate/index.ts
@@ -166,7 +166,12 @@ serve(async (req: Request) => {
}
await db.transaction().execute(async (trx) => {
- await updateJobQuantities(trx, jobMethodTree, job.data?.quantity);
+ // Use productionQuantity (quantity + scrapQuantity) to include job-level scrap
+ await updateJobQuantities(
+ trx,
+ jobMethodTree,
+ job.data?.productionQuantity ?? job.data?.quantity
+ );
});
break;
@@ -199,7 +204,22 @@ const updateJobQuantities = async (
tree: JobMethodTreeItem,
parentQuantity: number = 1
) => {
- const currentQuantity = tree.data.quantity * parentQuantity;
+ 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)
+ .executeTakeFirst();
+
+ const scrapPercentage = Number(itemReplenishment?.scrapPercentage ?? 0);
+ if (scrapPercentage > 0 && scrapPercentage < 100) {
+ currentQuantity = Math.ceil(baseQuantity / (1 - scrapPercentage / 100));
+ }
+ }
// Update jobMaterial
await trx
diff --git a/packages/database/supabase/migrations/20260116120000_item-scrap-percentage-on-job.sql b/packages/database/supabase/migrations/20260116120000_item-scrap-percentage-on-job.sql
new file mode 100644
index 0000000000..fc10ddb4fe
--- /dev/null
+++ b/packages/database/supabase/migrations/20260116120000_item-scrap-percentage-on-job.sql
@@ -0,0 +1,12 @@
+-- Add itemScrapPercentage column to jobMaterial table
+-- This stores the scrap percentage at the time the job was created for historical accuracy
+ALTER TABLE "jobMaterial"
+ ADD COLUMN IF NOT EXISTS "itemScrapPercentage" NUMERIC(5, 2) DEFAULT 0 NOT NULL;
+
+-- Add itemScrapPercentage column to jobMakeMethod table
+ALTER TABLE "jobMakeMethod"
+ ADD COLUMN IF NOT EXISTS "itemScrapPercentage" NUMERIC(5, 2) DEFAULT 0 NOT NULL;
+
+-- Add comment for documentation
+COMMENT ON COLUMN "jobMaterial"."itemScrapPercentage" IS 'Scrap percentage from itemReplenishment at time of job creation';
+COMMENT ON COLUMN "jobMakeMethod"."itemScrapPercentage" IS 'Scrap percentage from itemReplenishment at time of job creation';