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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add ordering from job materials table
Brad Barbin8f585935cc55
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsxindex 2458eb8da8..a97c4c6c01 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx@@ -76,7 +76,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {const [session, setStockTransferSession] = useStockTransferSession();useMount(() => {- // Prepopulate stock transfer session with all parts that need transferred or ordered+ // Pre-populate stock transfer session with all parts that need transferred or orderedconst itemsToAdd: Array<{id: string; // Job material IDitemId: string; // Actual item IDdiff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsxindex ba4496d263..776941de8c 100644--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx@@ -197,71 +197,16 @@ const OrderDrawer = memo(};});- if (selectedSupplier) {- const { data: existingPurchaseOrders } = await carbon- ?.from("purchaseOrder")- .select(- "id, purchaseOrderId, orderDate, status, purchaseOrderDelivery(receiptRequestedDate, receiptPromisedDate)"- )- .eq("supplierId", selectedSupplier)- .in("status", ["Draft", "Planned"]);-- const existingPOs =- existingPurchaseOrders?.map((order) => {- const dueDate =- order?.purchaseOrderDelivery?.receiptPromisedDate ??- order?.purchaseOrderDelivery?.receiptRequestedDate;- return {- id: order.id,- readableId: order.purchaseOrderId,- status: order.status,- dueDate,- };- }) ?? [];-- const ordersMappedToExistingPOs = orders.map((order) => {- const period = periods.find((p) => p.id === order.periodId);-- if (period) {- const firstPOInPeriod = existingPOs.find((po) => {- const dueDate = po?.dueDate ? parseDate(po.dueDate) : null;- return (- dueDate !== null &&- parseDate(period.startDate) <= dueDate &&- parseDate(period.endDate) >= dueDate- );- });-- if (firstPOInPeriod) {- return {- ...order,- existingId: firstPOInPeriod.id,- existingLineId: undefined,- existingReadableId: firstPOInPeriod.readableId,- existingStatus: firstPOInPeriod.status,- };- }- }-- return order;- });-- setOrders(- selectedItem,- [...ordersMappedToExistingPOs, ...existingOrders].sort((a, b) => {- return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;- })- );- } else {- setOrders(- selectedItem,- [...orders, ...existingOrders].sort((a, b) => {- return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;- })- );- }+ // Backend now handles grouping items by supplier into single POs+ // So we just need to merge the existing orders with current orders+ setOrders(+ selectedItem,+ [...orders, ...existingOrders].sort((a, b) => {+ return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;+ })+ );}- }, [carbon, selectedItem, selectedSupplier, orders, periods, setOrders]);+ }, [carbon, selectedItem, orders, periods, setOrders]);useMount(async () => {if (selectedItem.id) {diff --git a/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.pick.tsx b/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.pick.tsxindex e5dc3456a2..81bb81967a 100644--- a/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.pick.tsx+++ b/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.pick.tsx@@ -74,7 +74,8 @@ export async function loader({ request, params }: ActionFunctionArgs) {const result = await fetch(updateQuantityUrl.toString(), {method: "POST",headers: {- ...Object.fromEntries(request.headers.entries()),+ Authorization: request.headers.get("Authorization") || "",+ Cookie: request.headers.get("Cookie") || "",},body: formData,});diff --git a/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.unpick.tsx b/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.unpick.tsxindex 8702a7a052..6e7fb64b75 100644--- a/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.unpick.tsx+++ b/apps/erp/app/routes/api+/stock-transfer.$id.$lineId.unpick.tsx@@ -11,7 +11,6 @@ export async function loader({ request, params }: ActionFunctionArgs) {});const url = new URL(request.url);- const type = url.searchParams.get("type");const { id, lineId } = params;if (!id) throw notFound("id not found");@@ -76,7 +75,8 @@ export async function loader({ request, params }: ActionFunctionArgs) {const result = await fetch(updateQuantityUrl.toString(), {method: "POST",headers: {- ...Object.fromEntries(request.headers.entries()),+ Authorization: request.headers.get("Authorization") || "",+ Cookie: request.headers.get("Cookie") || "",},body: formData,});diff --git a/apps/erp/app/routes/x+/job+/$jobId.materials.session.new.tsx b/apps/erp/app/routes/x+/job+/$jobId.materials.session.new.tsxindex acb26b2aee..799798205a 100644--- a/apps/erp/app/routes/x+/job+/$jobId.materials.session.new.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.materials.session.new.tsx@@ -2,19 +2,24 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validator } from "@carbon/form";+import {+ getLocalTimeZone,+ parseDate,+ startOfWeek,+ today,+} from "@internationalized/date";import type { ActionFunctionArgs } from "@vercel/remix";import { json } from "@vercel/remix";import { z } from "zod";import {deleteStockTransfer,- getDefaultShelfForJob,upsertStockTransfer,upsertStockTransferLines,} from "~/modules/inventory";-import { getItem } from "~/modules/items";-import { getJob, upsertJob, upsertJobMethod } from "~/modules/production";-import { upsertPurchaseOrder } from "~/modules/purchasing";+import { getJob } from "~/modules/production";import { getNextSequence } from "~/modules/settings";+import { getPeriods } from "~/modules/shared/shared.service";+import { path } from "~/utils/path";const jobMaterialsSessionValidator = z.object({jobId: z.string(),@@ -31,7 +36,7 @@ const jobMaterialsSessionValidator = z.object({quantity: z.number().optional(),requiresSerialTracking: z.boolean(),requiresBatchTracking: z.boolean(),- shelfId: z.string().optional(),+ shelfId: z.string().nullable().optional(),}));return itemsSchema.parse(parsed);@@ -67,9 +72,22 @@ export async function action({ request, params }: ActionFunctionArgs) {}const { items: sessionItems } = validation.data;+ const startDate = startOfWeek(today(getLocalTimeZone()), "en-US");// Get job information to determine location- const jobResult = await getJob(client, jobId);+ const [jobResult, itemReplenishments] = await Promise.all([+ getJob(client, jobId),+ client+ .from("itemReplenishment")+ .select(+ "itemId, leadTime, lotSize, manufacturingBlocked, purchasingBlocked, preferredSupplierId, requiresConfiguration, scrapPercentage, ...item(replenishmentSystem)"+ )+ .in(+ "itemId",+ sessionItems.map((item) => item.itemId)+ )+ .eq("companyId", companyId),+ ]);if (jobResult.error || !jobResult.data) {return json({ success: false, message: "Failed to get job information" },@@ -80,8 +98,13 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ const itemReplenishmentsMap = new Map(+ itemReplenishments.data?.map((item) => [item.itemId, item]) ?? []+ );+const job = jobResult.data;const locationId = job.locationId;+ const jobStartDate = job.startDate;if (!locationId) {return json(@@ -93,6 +116,18 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ const periods = await getPeriods(client, {+ startDate: startDate.toString(),+ endDate: (jobStartDate ?? startDate.add({ weeks: 8 })).toString(),+ });++ if (periods.error || !periods.data) {+ return json(+ { success: false, message: "Failed to get periods" },+ await flash(request, error(periods.error, "Failed to get periods"))+ );+ }+const transferItems = sessionItems.filter((item) => item.action === "transfer");@@ -196,266 +231,389 @@ export async function action({ request, params }: ActionFunctionArgs) {return acc;}, []);- if (linesWithExpandedSerialTracking.length === 0) {- // No valid transfer lines, skip creating the stock transfer- return json(- { success: false, message: "No valid transfer lines could be created" },- await flash(- request,- error(- "No valid transfer lines could be created",- "No transfers created"- )- )+ if (linesWithExpandedSerialTracking.length > 0) {+ // Now that we have valid transfer lines, create the stock transfer+ // Get next sequence for stock transfer+ const nextSequence = await getNextSequence(+ client,+ "stockTransfer",+ companyId);- }+ if (nextSequence.error) {+ return json(+ { success: false, message: "Failed to get next sequence" },+ await flash(+ request,+ error(nextSequence.error, "Failed to get next sequence")+ )+ );+ }- // Now that we have valid transfer lines, create the stock transfer- // Get next sequence for stock transfer- const nextSequence = await getNextSequence(- client,- "stockTransfer",- companyId- );- if (nextSequence.error) {- return json(- { success: false, message: "Failed to get next sequence" },- await flash(- request,- error(nextSequence.error, "Failed to get next sequence")- )- );- }+ // Create stock transfer+ const createStockTransfer = await upsertStockTransfer(client, {+ stockTransferId: nextSequence.data,+ locationId,+ companyId,+ createdBy: userId,+ });- // Create stock transfer- const createStockTransfer = await upsertStockTransfer(client, {- stockTransferId: nextSequence.data,- locationId,- companyId,- createdBy: userId,- });-- if (createStockTransfer.error) {- return json(- { success: false, message: "Failed to create stock transfer" },- await flash(- request,- error(createStockTransfer.error, "Failed to create stock transfer")- )- );- }+ if (createStockTransfer.error) {+ return json(+ { success: false, message: "Failed to create stock transfer" },+ await flash(+ request,+ error(createStockTransfer.error, "Failed to create stock transfer")+ )+ );+ }- // Create stock transfer lines- const createStockTransferLines = await upsertStockTransferLines(client, {- lines: linesWithExpandedSerialTracking,- stockTransferId: createStockTransfer.data.id,- companyId,- createdBy: userId,- });-- if (createStockTransferLines.error) {- await deleteStockTransfer(client, createStockTransfer.data.id);- return json(- { success: false, message: "Failed to create stock transfer lines" },- await flash(- request,- error(- createStockTransferLines.error,- "Failed to create stock transfer lines"+ // Create stock transfer lines+ const createStockTransferLines = await upsertStockTransferLines(client, {+ lines: linesWithExpandedSerialTracking,+ stockTransferId: createStockTransfer.data.id,+ companyId,+ createdBy: userId,+ });++ if (createStockTransferLines.error) {+ await deleteStockTransfer(client, createStockTransfer.data.id);+ return json(+ { success: false, message: "Failed to create stock transfer lines" },+ await flash(+ request,+ error(+ createStockTransferLines.error,+ "Failed to create stock transfer lines"+ ))- )- );- }+ );+ }- hasTransfer = true;+ hasTransfer = true;+ }}- // Handle "order" items (purchase orders and jobs)if (orderItems.length > 0) {- // Get item details for all order items to determine make/buy- const itemDetails = await Promise.all(- orderItems.map(async (item) => {- const itemResult = await getItem(client, item.itemId);- return {- ...item,- itemDetails: itemResult.data,- itemError: itemResult.error,- };- })- );-// Separate items into make vs buy based on replenishment system// If replenishment system is "Buy and Make", treat as "Buy" (purchase order)- const buyItems = itemDetails.filter(+ const buyItems = orderItems.filter((item) =>- !item.itemError &&- item.itemDetails &&- (item.itemDetails.replenishmentSystem === "Buy" ||- item.itemDetails.replenishmentSystem === "Buy and Make")+ itemReplenishmentsMap.get(item.itemId)?.replenishmentSystem === "Buy" ||+ itemReplenishmentsMap.get(item.itemId)?.replenishmentSystem ===+ "Buy and Make");- const makeItems = itemDetails.filter(+ const makeItems = orderItems.filter((item) =>- !item.itemError &&- item.itemDetails &&- item.itemDetails.replenishmentSystem === "Make"+ itemReplenishmentsMap.get(item.itemId)?.replenishmentSystem === "Make");// Create purchase orders for buy itemsif (buyItems.length > 0) {// Get supplier information for buy items- const buyItemIds = buyItems.map((item) => item.itemId);- const { data: supplierParts, error: supplierPartsError } = await client+ const supplierParts = await client.from("supplierPart")- .select("itemId, supplierId, unitPrice, supplierUnitOfMeasureCode")- .in("itemId", buyItemIds)+ .select("*")+ .in(+ "itemId",+ buyItems.map((item) => item.itemId)+ ).eq("companyId", companyId);- if (supplierPartsError) {- // Continue without supplier parts- }+ if (supplierParts.error) {+ console.error(supplierParts.error);+ } else {+ // Group items by supplier to create one purchase order per supplier+ const itemsBySupplier = new Map<+ string,+ Array<{+ item: (typeof buyItems)[0];+ supplier: any;+ replenishment: any;+ }>+ >();++ // First pass: assign suppliers to each item+ for (const item of buyItems) {+ const replenishment = itemReplenishmentsMap.get(item.itemId);++ // Find preferred supplier or first available supplier+ const itemSupplierParts =+ supplierParts.data?.filter((sp) => sp.itemId === item.itemId) || [];++ let selectedSupplier = null;++ // First try to find preferred supplier+ if (replenishment?.preferredSupplierId) {+ selectedSupplier = itemSupplierParts.find(+ (sp) => sp.supplierId === replenishment.preferredSupplierId+ );+ }- // Group items by supplier- const itemsBySupplier = new Map<string, typeof buyItems>();+ // If no preferred supplier found, take the first one+ if (!selectedSupplier && itemSupplierParts.length > 0) {+ selectedSupplier = itemSupplierParts[0];+ }- for (const item of buyItems) {- const supplierPart = supplierParts?.find(- (sp) => sp.itemId === item.itemId- );- const supplierId = supplierPart?.supplierId || "NO_SUPPLIER";+ if (!selectedSupplier) {+ console.error(+ `[Purchase Orders] No supplier found for item ${item.itemId}`+ );+ continue;+ }- if (!itemsBySupplier.has(supplierId)) {- itemsBySupplier.set(supplierId, []);+ // Group by supplier+ if (!itemsBySupplier.has(selectedSupplier.supplierId)) {+ itemsBySupplier.set(selectedSupplier.supplierId, []);+ }+ itemsBySupplier.get(selectedSupplier.supplierId)!.push({+ item,+ supplier: selectedSupplier,+ replenishment,+ });}- itemsBySupplier.get(supplierId)!.push(item);- }- // Create purchase orders for each supplier group- for (const [supplierId, items] of itemsBySupplier.entries()) {- if (supplierId === "NO_SUPPLIER") {- continue;- }+ // Build purchase planning payload - one planning item per actual item+ const purchasePlanningItems = [];- // Validate that we have valid items with quantities before creating purchase order- // This prevents creating empty purchase orders and wasting sequence numbers- const validItems = items.filter(- (item) => item.quantity && item.quantity > 0- );+ // Helper function to find period ID+ const findPeriodId = (dueDate: string) => {+ const dueDateParsed = parseDate(dueDate);+ const period = periods.data?.find((p) => {+ const startDate = parseDate(p.startDate);+ const endDate = parseDate(p.endDate);+ return dueDateParsed >= startDate && dueDateParsed <= endDate;+ });- if (validItems.length === 0) {- continue;- }+ if (!period) {+ if (periods.data && periods.data.length > 0) {+ const firstPeriod = periods.data[0];+ const lastPeriod = periods.data[periods.data.length - 1];+ const firstStartDate = parseDate(firstPeriod.startDate);+ const lastEndDate = parseDate(lastPeriod.endDate);++ if (dueDateParsed < firstStartDate) {+ return firstPeriod.id;+ } else if (dueDateParsed > lastEndDate) {+ return lastPeriod.id;+ }+ }+ return periods.data?.[0]?.id || "";+ }- try {- // Get next sequence for purchase order- const nextSequence = await getNextSequence(- client,- "purchaseOrder",- companyId- );+ return period.id;+ };- if (nextSequence.error) {- continue;+ for (const [supplierId, supplierItems] of itemsBySupplier.entries()) {+ // Create one planning item per actual item+ for (const { item, supplier, replenishment } of supplierItems) {+ // Calculate dates: due date = job start date, start date = due date - lead time+ const jobStartDateParsed = jobStartDate+ ? parseDate(jobStartDate)+ : today(getLocalTimeZone());+ const leadTime = replenishment?.leadTime || 0;+ const purchaseOrderDueDate = jobStartDateParsed.toString();+ const purchaseOrderStartDate = jobStartDateParsed+ .subtract({ days: leadTime })+ .toString();++ const periodId = findPeriodId(purchaseOrderDueDate);++ const orders = [+ {+ quantity: Math.max(item.quantity || 0, 1),+ dueDate: purchaseOrderDueDate,+ startDate: purchaseOrderStartDate,+ periodId: periodId,+ supplierId: supplierId,+ unitPrice: supplier.unitPrice || 0,+ unitOfMeasureCode: supplier.supplierUnitOfMeasureCode || "EA",+ description: item.description,+ },+ ];++ purchasePlanningItems.push({+ id: item.itemId,+ orders,+ });}+ }- // Create purchase order- const createPurchaseOrder = await upsertPurchaseOrder(client, {- purchaseOrderId: nextSequence.data,- purchaseOrderType: "Purchase",- supplierId: supplierId,- companyId,- createdBy: userId,- });+ if (purchasePlanningItems.length > 0) {+ const purchasePlanningPayload = {+ action: "order" as const,+ items: purchasePlanningItems,+ locationId,+ };- if (createPurchaseOrder.error) {- continue;- }+ const purchasePlanningUrl = `${new URL(request.url).origin}${+ path.to.bulkUpdatePurchasingPlanning+ }`;- // TODO: Add purchase order lines for each valid item- // This would require implementing purchase order line creation+ const result = await fetch(purchasePlanningUrl, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: request.headers.get("Authorization") || "",+ Cookie: request.headers.get("Cookie") || "",+ },+ body: JSON.stringify(purchasePlanningPayload),+ });- hasPurchaseOrder = true;- } catch (error) {- // Continue to next supplier+ if (result.ok) {+ const responseData = await result.json();++ if (responseData?.success) {+ hasPurchaseOrder = true;+ } else {+ console.error(+ `[Purchase Orders] API returned success: false`,+ responseData+ );+ }+ } else {+ const errorText = await result.text();+ console.error(`[Purchase Orders] API call failed:`, {+ status: result.status,+ statusText: result.statusText,+ error: errorText,+ });+ }}}}// Create jobs for make itemsif (makeItems.length > 0) {- for (const item of makeItems) {- try {- if (!item.quantity || item.quantity <= 0) {- continue;- }-- // Get next sequence for job- const nextSequence = await getNextSequence(client, "job", companyId);-- if (nextSequence.error) {- continue;- }-- const shelfId = await getDefaultShelfForJob(- client,- item.itemId,- locationId,- companyId- );-- const createJob = await upsertJob(- client,- {- jobId: nextSequence.data,- itemId: item.itemId,- quantity: item.quantity,- scrapQuantity: 0, // Default to 0 for now- locationId: locationId,- unitOfMeasureCode: item.itemDetails?.unitOfMeasureCode || "EA", // Default to "EA" if not specified- deadlineType: "ASAP", // Default to ASAP for job materials- shelfId: shelfId ?? undefined,- companyId,- createdBy: userId,- },- "Planned"- );+ const productionPlanningUrl = `${new URL(request.url).origin}${+ path.to.bulkUpdateProductionPlanning+ }`;++ // Build production planning payload with lot size chunking+ const productionPlanningItems = makeItems.map((item) => {+ const replenishment = itemReplenishmentsMap.get(item.itemId);+ const lotSize = replenishment?.lotSize ?? 0;+ const requiredQuantity = item.quantity || 0;++ // Calculate orders based on lot size chunking+ const orders = [];++ // Calculate dates: due date = job start date, start date = due date - lead time+ const jobStartDateParsed = jobStartDate+ ? parseDate(jobStartDate)+ : today(getLocalTimeZone());+ const leadTime = replenishment?.leadTime || 0;+ const productionOrderDueDate = jobStartDateParsed.toString();+ const productionOrderStartDate = jobStartDateParsed+ .subtract({ days: leadTime })+ .toString();++ // Find the correct period based on the production order due date+ const findPeriodId = (dueDate: string) => {+ const dueDateParsed = parseDate(dueDate);+ const period = periods.data?.find((p) => {+ const startDate = parseDate(p.startDate);+ const endDate = parseDate(p.endDate);+ return dueDateParsed >= startDate && dueDateParsed <= endDate;+ });- if (createJob.error) {- continue;+ // If no matching period found, use the first period if due date is before it,+ // or the last period if due date is after all periods+ if (!period) {+ if (periods.data && periods.data.length > 0) {+ const firstPeriod = periods.data[0];+ const lastPeriod = periods.data[periods.data.length - 1];+ const firstStartDate = parseDate(firstPeriod.startDate);+ const lastEndDate = parseDate(lastPeriod.endDate);++ if (dueDateParsed < firstStartDate) {+ return firstPeriod.id;+ } else if (dueDateParsed > lastEndDate) {+ return lastPeriod.id;+ }+ }+ return periods.data?.[0]?.id || "";}- const jobId = createJob.data?.id;- if (!jobId) {- continue;- }+ return period.id;+ };- // Create job method to link the item to the job- const upsertMethod = await upsertJobMethod(client, "itemToJob", {- sourceId: item.itemId,- targetId: jobId,- companyId,- userId,+ const periodId = findPeriodId(productionOrderDueDate);++ if (lotSize === 0) {+ // If lot size is 0, order the exact required quantity+ const orderQuantity = Math.max(requiredQuantity, 1); // At least 1 if no quantity specified+ orders.push({+ quantity: orderQuantity,+ dueDate: productionOrderDueDate,+ startDate: productionOrderStartDate,+ isASAP: startDate.compare(today(getLocalTimeZone())) < 0,+ periodId: periodId,});-- if (upsertMethod.error) {- // Continue anyway as the job was created successfully+ } else {+ // If lot size > 0, use lot size chunking+ if (requiredQuantity <= 0) {+ // If no quantity required, create one order with lot size+ orders.push({+ quantity: lotSize,+ dueDate: productionOrderDueDate,+ startDate: productionOrderStartDate,+ isASAP: false,+ periodId: periodId,+ });+ } else if (requiredQuantity <= lotSize) {+ // If required quantity is less than or equal to lot size, order the lot size+ orders.push({+ quantity: lotSize,+ dueDate: productionOrderDueDate,+ startDate: productionOrderStartDate,+ isASAP: false,+ periodId: periodId,+ });+ } else {+ // If required quantity is greater than lot size, create multiple orders+ const numberOfOrders = Math.ceil(requiredQuantity / lotSize);+ for (let i = 0; i < numberOfOrders; i++) {+ orders.push({+ quantity: lotSize,+ dueDate: productionOrderDueDate,+ startDate: productionOrderStartDate,+ isASAP: false,+ periodId: periodId,+ });+ }}+ }- // TODO: Trigger job requirements recalculation- // This would typically be done with a background job+ return {+ id: item.itemId,+ orders,+ };+ });- hasJobs = true;- } catch (error) {- // Continue to next item- }+ const productionPlanningPayload = {+ action: "order" as const,+ items: productionPlanningItems,+ locationId,+ };++ const result = await fetch(productionPlanningUrl, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: request.headers.get("Authorization") || "",+ Cookie: request.headers.get("Cookie") || "",+ },+ body: JSON.stringify(productionPlanningPayload),+ });++ const data = await result.json();+ if (data?.success) {+ hasJobs = true;}}}- // TODO: Update job material statuses- // TODO: Send notifications-- // Determine what was created for the success messageconst createdItems = [];if (hasTransfer) createdItems.push("stock transfer");if (hasPurchaseOrder) createdItems.push("purchase order(s)");diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsxindex 820bb6802f..1c7ef95172 100644--- a/apps/erp/app/routes/x+/production+/planning.update.tsx+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx@@ -297,11 +297,31 @@ export async function action({ request }: ActionFunctionArgs) {}}- // Insert all supply forecasts+ // Insert all supply forecasts using upsert to handle duplicatesif (allSupplyForecasts.length > 0) {+ // Group supply forecasts by unique key to avoid duplicate conflicts+ const forecastMap = new Map<string, (typeof allSupplyForecasts)[0]>();++ for (const forecast of allSupplyForecasts) {+ const key = `${forecast.itemId}-${forecast.locationId}-${forecast.periodId}`;+ const existing = forecastMap.get(key);++ if (existing) {+ // Combine quantities for the same key+ existing.forecastQuantity += forecast.forecastQuantity;+ } else {+ forecastMap.set(key, { ...forecast });+ }+ }++ const uniqueSupplyForecasts = Array.from(forecastMap.values());+const insertForecasts = await client.from("supplyForecast")- .insert(allSupplyForecasts);+ .upsert(uniqueSupplyForecasts, {+ onConflict: "itemId,locationId,periodId",+ ignoreDuplicates: false,+ });if (insertForecasts.error) {const errorMsg = `Failed to insert supply forecasts: ${insertForecasts.error.message}`;diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsxindex 83ce2f9944..37c97bb60f 100644--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx@@ -83,7 +83,6 @@ export async function action({ request }: ActionFunctionArgs) {return error.message;});- console.error("Validation errors:", parsedItems.error.errors);return json({success: false,@@ -120,11 +119,27 @@ export async function action({ request }: ActionFunctionArgs) {updatedBy: string;}> = [];+ // Group items and orders by supplier+ const ordersBySupplier: Map<+ string,+ Array<{+ itemId: string;+ order: (typeof itemsToOrder)[0]["orders"][0];+ }>+ > = new Map();+for (const item of itemsToOrder) {itemIds.add(item.id);for (const order of item.orders) {if (order.supplierId) {supplierIds.add(order.supplierId);+ if (!ordersBySupplier.has(order.supplierId)) {+ ordersBySupplier.set(order.supplierId, []);+ }+ ordersBySupplier.get(order.supplierId)!.push({+ itemId: item.id,+ order,+ });}if (order.periodId) {periodIds.add(order.periodId);@@ -203,327 +218,284 @@ export async function action({ request }: ActionFunctionArgs) {let processedItems = 0;let errors: string[] = [];- for (const item of itemsToOrder) {- const orders = item.orders;- const supplier = suppliersById.get(orders[0]?.supplierId ?? "");- const supplierPart =- supplierParts?.data?.find(- (sp) => sp.itemId === item.id && sp.supplierId === supplier?.id- ) ?? undefined;-- const supplyForecastByPeriod: Record<string, number> = {};-- const purchasing = await client- .from("itemReplenishment")- .select("purchasingBlocked")- .eq("itemId", item.id)- .single();-- if (purchasing.error) {- const errorMsg = `Failed to retrieve purchasing data for item ${item.id}: ${purchasing.error.message}`;+ // Process orders grouped by supplier+ for (const [supplierId, ordersForSupplier] of ordersBySupplier) {+ const supplier = suppliersById.get(supplierId);+ if (!supplier) {+ const errorMsg = `Supplier ${supplierId} not found`;console.error(errorMsg);errors.push(errorMsg);continue;}- if (purchasing.data?.purchasingBlocked) {- const errorMsg = `Purchasing is blocked for item ${item.id}`;- console.warn(errorMsg);- errors.push(errorMsg);- continue;- }-// Get existing purchase orders for this supplierconst { data: existingPurchaseOrders, error: poError } = await client.from("purchaseOrder")- .select(- "id, purchaseOrderId, orderDate, status, purchaseOrderDelivery(receiptRequestedDate, receiptPromisedDate)"- )- .eq("supplierId", supplier?.id ?? "")+ .select("id, purchaseOrderId, status")+ .eq("supplierId", supplierId).in("status", ["Draft", "Planned"]);if (poError) {- const errorMsg = `Failed to retrieve existing purchase orders for supplier ${supplier?.id}: ${poError.message}`;+ const errorMsg = `Failed to retrieve existing purchase orders for supplier ${supplierId}: ${poError.message}`;console.error(errorMsg);errors.push(errorMsg);continue;}- const existingPOs =- existingPurchaseOrders?.map((order) => {- const dueDate =- order?.purchaseOrderDelivery?.receiptPromisedDate ??- order?.purchaseOrderDelivery?.receiptRequestedDate;- return {- id: order.id,- readableId: order.purchaseOrderId,- status: order.status,- dueDate,- };- }) ?? [];-- // Map orders to existing POs in the same period- const ordersMappedToExistingPOs = orders.map((order) => {- const period = periods?.data?.find((p) => p.id === order.periodId);- if (period) {- const firstPOInPeriod = existingPOs.find((po) => {- const dueDate = po?.dueDate ? new Date(po.dueDate) : null;- return (- dueDate !== null &&- new Date(period.startDate) <= dueDate &&- new Date(period.endDate) >= dueDate- );- });+ // Use the first existing Draft/Planned PO, or create a new one+ let purchaseOrderId = existingPurchaseOrders?.[0]?.id;+ let createdNewPO = false;- if (firstPOInPeriod) {- return {- ...order,- existingId: firstPOInPeriod.id,- existingLineId: undefined,- existingReadableId: firstPOInPeriod.readableId,- existingStatus: firstPOInPeriod.status,- };- }+ if (!purchaseOrderId) {+ const nextSequence = await getNextSequence(+ client,+ "purchaseOrder",+ companyId+ );+ if (nextSequence.error) {+ const errorMsg = `Failed to generate purchase order sequence for supplier ${supplierId}: ${nextSequence.error.message}`;+ console.error(errorMsg);+ errors.push(errorMsg);+ continue;}- return order;- });-- let itemProcessed = false;-- for (const order of ordersMappedToExistingPOs) {- if (!order.supplierId) {- const errorMsg = `Supplier ID is missing for item ${item.id}`;+ const purchaseOrderIdValue = nextSequence.data;+ if (!purchaseOrderIdValue) {+ const errorMsg = `Failed to generate purchase order ID for supplier ${supplierId}`;console.error(errorMsg);errors.push(errorMsg);continue;}- if (!order.existingId) {- const nextSequence = await getNextSequence(+ let exchangeRate = 1;+ if (supplier.currencyCode !== baseCurrencyCode) {+ const currency = await getCurrencyByCode(client,- "purchaseOrder",- companyId+ companyId,+ supplier.currencyCode ?? baseCurrencyCode);- if (nextSequence.error) {- const errorMsg = `Failed to generate purchase order sequence for item ${item.id}: ${nextSequence.error.message}`;- console.error(errorMsg);- errors.push(errorMsg);- continue;- }- const purchaseOrderId = nextSequence.data;- if (!purchaseOrderId) {- const errorMsg = `Failed to generate purchase order ID for item ${item.id}`;+ if (currency.error) {+ const errorMsg = `Failed to retrieve exchange rate for currency ${supplier.currencyCode}: ${currency.error.message}`;console.error(errorMsg);errors.push(errorMsg);continue;}- let exchangeRate = 1;- if (supplier?.currencyCode !== baseCurrencyCode) {- const currency = await getCurrencyByCode(- client,- companyId,- supplier?.currencyCode ?? baseCurrencyCode- );-- if (currency.error) {- const errorMsg = `Failed to retrieve exchange rate for currency ${supplier?.currencyCode}: ${currency.error.message}`;- console.error(errorMsg);- errors.push(errorMsg);- continue;- }-- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- }+ if (currency.data) {+ exchangeRate = currency.data.exchangeRate ?? 1;}+ }- const createPurchaseOrder = await upsertPurchaseOrder(- client,- {- purchaseOrderId,- status: "Planned" as const,- supplierId: order.supplierId,- purchaseOrderType: "Purchase",- currencyCode: supplier?.currencyCode ?? baseCurrencyCode,- exchangeRate: exchangeRate,- companyId,- createdBy: userId,- },- order.dueDate ?? undefined- );+ const createPurchaseOrder = await upsertPurchaseOrder(+ client,+ {+ purchaseOrderId: purchaseOrderIdValue,+ status: "Planned" as const,+ supplierId,+ purchaseOrderType: "Purchase",+ currencyCode: supplier.currencyCode ?? baseCurrencyCode,+ exchangeRate: exchangeRate,+ companyId,+ createdBy: userId,+ },+ undefined+ );- if (createPurchaseOrder.error) {- const errorMsg = `Failed to create purchase order for item ${item.id}: ${createPurchaseOrder.error.message}`;- console.error(errorMsg);- errors.push(errorMsg);- continue;- }+ if (createPurchaseOrder.error) {+ const errorMsg = `Failed to create purchase order for supplier ${supplierId}: ${createPurchaseOrder.error.message}`;+ console.error(errorMsg);+ errors.push(errorMsg);+ continue;+ }- const purchaseOrder = createPurchaseOrder.data?.[0];- if (!purchaseOrder) {- const errorMsg = `Purchase order was not returned after creation for item ${item.id}`;- console.error(errorMsg);- errors.push(errorMsg);- continue;- }+ const purchaseOrder = createPurchaseOrder.data?.[0];+ if (!purchaseOrder) {+ const errorMsg = `Purchase order was not returned after creation for supplier ${supplierId}`;+ console.error(errorMsg);+ errors.push(errorMsg);+ continue;+ }- const createPurchaseOrderLine = await upsertPurchaseOrderLine(- client,- {- purchaseOrderId: purchaseOrder.id,- itemId: item.id,- description: order.description,- purchaseOrderLineType: "Part",- purchaseQuantity: order.quantity,- purchaseUnitOfMeasureCode:- supplierPart?.supplierUnitOfMeasureCode ??- order.unitOfMeasureCode,- inventoryUnitOfMeasureCode: order.unitOfMeasureCode,- conversionFactor: supplierPart?.conversionFactor ?? 1,- supplierUnitPrice: supplierPart?.unitPrice ?? 0,- supplierTaxAmount:- ((order.unitPrice ?? 0) * (supplier?.taxPercent ?? 0)) /- 100,- supplierShippingCost: 0,- promisedDate: order.dueDate ?? undefined,- locationId,- companyId,- createdBy: userId,- }- );+ purchaseOrderId = purchaseOrder.id;+ createdNewPO = true;+ }- if (createPurchaseOrderLine.error) {- const errorMsg = `Failed to create purchase order line for item ${item.id}: ${createPurchaseOrderLine.error.message}`;- console.error(errorMsg);- errors.push(errorMsg);- continue;- }+ // Group orders by itemId to consolidate into single lines+ const ordersByItem = new Map<+ string,+ Array<{+ order: (typeof ordersForSupplier)[0]["order"];+ periodId: string;+ }>+ >();++ for (const { itemId, order } of ordersForSupplier) {+ if (!ordersByItem.has(itemId)) {+ ordersByItem.set(itemId, []);+ }+ ordersByItem.get(itemId)!.push({+ order,+ periodId: order.periodId,+ });+ }- itemProcessed = true;- } else {- if (order.existingLineId) {- const updatePurchaseOrderLine = await upsertPurchaseOrderLine(- client,- {- id: order.existingLineId,- purchaseOrderId: order.existingId,- itemId: item.id,- description: order.description,- purchaseOrderLineType: "Part",- purchaseQuantity: order.quantity,- purchaseUnitOfMeasureCode:- supplierPart?.supplierUnitOfMeasureCode ??- order.unitOfMeasureCode,- inventoryUnitOfMeasureCode: order.unitOfMeasureCode,- conversionFactor: supplierPart?.conversionFactor ?? 1,- supplierUnitPrice: supplierPart?.unitPrice ?? 0,- supplierTaxAmount:- ((order.unitPrice ?? 0) * (supplier?.taxPercent ?? 0)) /- 100,- supplierShippingCost: 0,- promisedDate: order.dueDate ?? undefined,- locationId,- companyId,- createdBy: userId,- }- );-- if (updatePurchaseOrderLine.error) {- const errorMsg = `Failed to update purchase order line ${order.existingLineId} for item ${item.id}: ${updatePurchaseOrderLine.error.message}`;- console.error(errorMsg);- errors.push(errorMsg);- continue;- }- } else {- const insertPurchaseOrderLine = await upsertPurchaseOrderLine(- client,- {- purchaseOrderId: order.existingId,- itemId: item.id,- description: order.description,- purchaseOrderLineType: "Part",- purchaseQuantity: order.quantity,- purchaseUnitOfMeasureCode:- supplierPart?.supplierUnitOfMeasureCode ??- order.unitOfMeasureCode,- inventoryUnitOfMeasureCode: order.unitOfMeasureCode,- conversionFactor: supplierPart?.conversionFactor ?? 1,- supplierUnitPrice: supplierPart?.unitPrice ?? 0,- supplierTaxAmount:- ((order.unitPrice ?? 0) * (supplier?.taxPercent ?? 0)) /- 100,- supplierShippingCost: 0,- promisedDate: order.dueDate ?? undefined,- locationId,- companyId,- createdBy: userId,- }- );-- if (insertPurchaseOrderLine.error) {- const errorMsg = `Failed to add purchase order line for item ${item.id}: ${insertPurchaseOrderLine.error.message}`;- console.error(errorMsg);- errors.push(errorMsg);- continue;- }- }+ // Now create one line per item (consolidating all orders for that item)+ for (const [itemId, itemOrders] of ordersByItem) {+ const supplierPart = supplierParts?.data?.find(+ (sp) => sp.itemId === itemId && sp.supplierId === supplierId+ );- const updateResult = await updatePurchaseOrder(client, {- id: order.existingId,- status: "Planned" as const,- updatedBy: userId,- });+ const purchasing = await client+ .from("itemReplenishment")+ .select("purchasingBlocked")+ .eq("itemId", itemId)+ .single();- if (updateResult.error) {- const errorMsg = `Failed to update purchase order status for item ${item.id}: ${updateResult.error.message}`;- console.error(errorMsg);- errors.push(errorMsg);- continue;+ if (purchasing.error) {+ const errorMsg = `Failed to retrieve purchasing data for item ${itemId}: ${purchasing.error.message}`;+ console.error(errorMsg);+ errors.push(errorMsg);+ continue;+ }++ if (purchasing.data?.purchasingBlocked) {+ const errorMsg = `Purchasing is blocked for item ${itemId}`;+ console.error(errorMsg);+ errors.push(errorMsg);+ continue;+ }++ // Sum up all quantities for this item+ const totalQuantity = itemOrders.reduce(+ (sum, { order }) => sum + order.quantity,+ 0+ );++ // Apply minimum order quantity+ const minimumOrderQuantity =+ supplierPart?.minimumOrderQuantity ?? 0;++ let adjustedQuantity = totalQuantity;++ // Apply minimum order quantity+ if (+ minimumOrderQuantity > 0 &&+ adjustedQuantity < minimumOrderQuantity+ ) {+ adjustedQuantity = minimumOrderQuantity;+ }++ // Use the earliest due date from all orders for this item+ const earliestDueDate = itemOrders.reduce((earliest, { order }) => {+ if (!earliest) return order.dueDate;+ if (!order.dueDate) return earliest;+ return order.dueDate < earliest ? order.dueDate : earliest;+ }, itemOrders[0].order.dueDate);++ // Use the first order's description+ const description = itemOrders[0].order.description;+ const unitOfMeasureCode = itemOrders[0].order.unitOfMeasureCode;++ const createPurchaseOrderLine = await upsertPurchaseOrderLine(+ client,+ {+ purchaseOrderId: purchaseOrderId!,+ itemId: itemId,+ description: description,+ purchaseOrderLineType: "Part",+ purchaseQuantity: adjustedQuantity,+ purchaseUnitOfMeasureCode:+ supplierPart?.supplierUnitOfMeasureCode ?? unitOfMeasureCode,+ inventoryUnitOfMeasureCode: unitOfMeasureCode,+ conversionFactor: supplierPart?.conversionFactor ?? 1,+ supplierUnitPrice: supplierPart?.unitPrice ?? 0,+ supplierTaxAmount:+ ((supplierPart?.unitPrice ?? 0) *+ (supplier.taxPercent ?? 0)) /+ 100,+ supplierShippingCost: 0,+ promisedDate: earliestDueDate ?? undefined,+ locationId,+ companyId,+ createdBy: userId,}+ );- itemProcessed = true;+ if (createPurchaseOrderLine.error) {+ const errorMsg = `Failed to create purchase order line for item ${itemId}: ${createPurchaseOrderLine.error.message}`;+ console.error(errorMsg);+ errors.push(errorMsg);+ continue;}- const periodId = order.periodId;+ processedItems++;- // Convert purchase quantity back to inventory quantity for supply forecast- // Inventory Quantity = Purchase Quantity × Conversion Factor+ // Add supply forecasts for each period this item appears inconst conversionFactor = supplierPart?.conversionFactor ?? 1;- const purchaseQuantityDelta =- order.quantity - (order.existingQuantity ?? 0);- const inventoryQuantityDelta =- purchaseQuantityDelta * conversionFactor;+ const periodQuantities = new Map<string, number>();++ for (const { order, periodId } of itemOrders) {+ const currentPeriodQty = periodQuantities.get(periodId) || 0;+ periodQuantities.set(periodId, currentPeriodQty + order.quantity);+ }- supplyForecastByPeriod[periodId] =- (supplyForecastByPeriod[periodId] || 0) + inventoryQuantityDelta;+ for (const [periodId, quantity] of periodQuantities) {+ const inventoryQuantityDelta = quantity * conversionFactor;++ allSupplyForecasts.push({+ itemId: itemId,+ locationId,+ sourceType: "Purchase Order" as const,+ forecastQuantity: inventoryQuantityDelta,+ periodId,+ companyId,+ createdBy: userId,+ updatedBy: userId,+ });+ }}- if (itemProcessed) {- processedItems++;- Object.entries(supplyForecastByPeriod).forEach(- ([periodId, quantity]) => {- allSupplyForecasts.push({- itemId: item.id,- locationId,- sourceType: "Purchase Order" as const,- forecastQuantity: quantity,- periodId,- companyId,- createdBy: userId,- updatedBy: userId,- });- }- );+ // Update PO status if we added to an existing PO+ if (!createdNewPO && purchaseOrderId) {+ const updateResult = await updatePurchaseOrder(client, {+ id: purchaseOrderId,+ status: "Planned" as const,+ updatedBy: userId,+ });++ if (updateResult.error) {+ const errorMsg = `Failed to update purchase order status for supplier ${supplierId}: ${updateResult.error.message}`;+ console.error(errorMsg);+ errors.push(errorMsg);+ }}}if (allSupplyForecasts.length > 0) {+ // Group supply forecasts by unique key to avoid duplicate conflicts+ const forecastMap = new Map<string, (typeof allSupplyForecasts)[0]>();++ for (const forecast of allSupplyForecasts) {+ const key = `${forecast.itemId}-${forecast.locationId}-${forecast.periodId}`;+ const existing = forecastMap.get(key);++ if (existing) {+ // Combine quantities for the same key+ existing.forecastQuantity += forecast.forecastQuantity;+ } else {+ forecastMap.set(key, { ...forecast });+ }+ }++ const uniqueSupplyForecasts = Array.from(forecastMap.values());+const insertForecasts = await client.from("supplyForecast")- .insert(allSupplyForecasts);+ .upsert(uniqueSupplyForecasts, {+ onConflict: "itemId,locationId,periodId",+ ignoreDuplicates: false,+ });if (insertForecasts.error) {const errorMsg = `Failed to insert supply forecasts: ${insertForecasts.error.message}`;diff --git a/packages/database/supabase/migrations/20251013212930_stock-transfer-wizard-view.sql b/packages/database/supabase/migrations/20251013212930_stock-transfer-wizard-view.sqlindex da4b58a4a9..185e535ec1 100644--- a/packages/database/supabase/migrations/20251013212930_stock-transfer-wizard-view.sql+++ b/packages/database/supabase/migrations/20251013212930_stock-transfer-wizard-view.sql@@ -99,6 +99,7 @@ WITHON pol."purchaseOrderId" = po."id"WHEREpo."status" IN (+ 'Planned','To Receive','To Receive and Invoice')@@ -296,6 +297,7 @@ WITHON pol."purchaseOrderId" = po."id"WHEREpo."status" IN (+ 'Planned','To Receive','To Receive and Invoice')@@ -448,6 +450,7 @@ WITHON jm."itemId" = pol."itemId"WHEREpo."status" IN (+ 'Planned','To Receive','To Receive and Invoice')