Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add mutation for ordering multiple items through production palnning

Brad Barbin1da951184110
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
index 66c0b60fec..2fd96b8f20 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
@@ -4,6 +4,7 @@ import {
MenuIcon,
MenuItem,
useDisclosure,
+ VStack,
} from "@carbon/react";
import { formatDate } from "@carbon/utils";
import { useNavigate } from "@remix-run/react";
@@ -112,7 +113,16 @@ const JobsTable = memo(({ data, count, tags }: JobsTableProps) => {
{
accessorKey: "itemReadableIdWithRevision",
header: "Item",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => {
+ return (
+ <VStack spacing={0}>
+ {row.original.itemReadableIdWithRevision}
+ <div className="w-full truncate text-muted-foreground text-xs">
+ {row.original.name}
+ </div>
+ </VStack>
+ );
+ },
meta: {
filter: {
type: "static",
@@ -132,6 +142,7 @@ const JobsTable = memo(({ data, count, tags }: JobsTableProps) => {
icon: <LuHash />,
},
},
+
{
id: "customerId",
header: "Customer",
diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
index d4a14cd7c2..53f6630694 100644
--- a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
@@ -559,7 +559,6 @@ OrderDrawer.displayName = "OrderDrawer";
const PlanningTable = memo(
({ data, count, locationId, periods }: PlanningTableProps) => {
const permissions = usePermissions();
- const isDisabled = !permissions.can("create", "production");
const dateFormatter = useDateFormatter({
month: "short",
@@ -570,8 +569,27 @@ const PlanningTable = memo(
const locations = useLocations();
const unitOfMeasures = useUnitOfMeasure();
+ const mrpFetcher = useFetcher<typeof mrpAction>();
const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();
+ useEffect(() => {
+ if (
+ bulkUpdateFetcher.data?.success === false &&
+ bulkUpdateFetcher?.data?.message
+ ) {
+ toast.error(bulkUpdateFetcher.data.message);
+ }
+
+ if (bulkUpdateFetcher.data?.success === true) {
+ toast.success("Orders submitted");
+ }
+ }, [bulkUpdateFetcher.data]);
+
+ const isDisabled =
+ !permissions.can("create", "production") ||
+ bulkUpdateFetcher.state !== "idle" ||
+ mrpFetcher.state !== "idle";
+
const getOrders = useCallback(() => {
const initialMap: Record<string, Order[]> = {};
data.forEach((item) => {
@@ -883,8 +901,6 @@ const PlanningTable = memo(
right: ["Order"],
};
- const mrpFetcher = useFetcher<typeof mrpAction>();
-
return (
<>
<Table<ProductionPlanningItem>
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsx
index 7387ac161c..2cdb184a8a 100644
--- a/apps/erp/app/routes/x+/production+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx
@@ -1,12 +1,20 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { z } from "zod";
import { orderValidator } from "~/modules/items/items.models";
-import { upsertJob, upsertJobMethod } from "~/modules/production";
+import {
+ recalculateJobRequirements,
+ runMRP,
+ upsertJob,
+ upsertJobMethod,
+} from "~/modules/production";
import { getNextSequence } from "~/modules/settings/settings.service";
-const itemValidator = z
+export const config = {
+ maxDuration: 300,
+};
+
+const itemsValidator = z
.object({
id: z.string(),
orders: z.array(orderValidator),
@@ -31,7 +39,7 @@ export async function action({ request }: ActionFunctionArgs) {
switch (action) {
case "order":
- const parsedItems = itemValidator.safeParse(items);
+ const parsedItems = itemsValidator.safeParse(items);
if (!parsedItems.success) {
return json({ success: false, message: "Invalid form data" });
@@ -42,162 +50,170 @@ export async function action({ request }: ActionFunctionArgs) {
return json({ success: false, message: "No items to order" });
}
- if (itemsToOrder.length === 1) {
- let jobIds: string[] = [];
- let supplyForecastByPeriod: Record<string, number> = {};
- const item = itemsToOrder[0];
- const orders = item.orders;
-
- const manufacturing = await client
- .from("itemReplenishment")
- .select(
- "manufacturingBlocked, scrapPercentage, requiresConfiguration"
- )
- .eq("itemId", item.id)
- .single();
-
- if (manufacturing.error) {
- return json({
- success: false,
- message: "Failed to get manufacturing data",
- });
- }
+ try {
+ const allJobIds: string[] = [];
+ const allSupplyForecasts: Array<{
+ itemId: string;
+ locationId: string;
+ sourceType: "Production Order";
+ forecastQuantity: number;
+ periodId: string;
+ companyId: string;
+ createdBy: string;
+ updatedBy: string;
+ }> = [];
- if (manufacturing.data?.manufacturingBlocked) {
- return json({
- success: false,
- message: "Manufacturing is blocked for this item",
- });
- }
+ for (const item of itemsToOrder) {
+ const orders = item.orders;
+ const jobIds: string[] = [];
+ const supplyForecastByPeriod: Record<string, number> = {};
- if (manufacturing.data?.requiresConfiguration) {
- return json({
- success: false,
- message: "Manufacturing requires configuration",
- });
- }
+ // Get manufacturing data for this item
+ const manufacturing = await client
+ .from("itemReplenishment")
+ .select(
+ "manufacturingBlocked, scrapPercentage, requiresConfiguration"
+ )
+ .eq("itemId", item.id)
+ .single();
- for await (const order of orders) {
- if (!order.existingId) {
- const nextSequence = await getNextSequence(
- client,
- "job",
- companyId
+ if (manufacturing.error) {
+ console.error(
+ `Failed to get manufacturing data for item ${item.id}:`,
+ manufacturing.error
);
- if (nextSequence.error) {
- return json({
- success: false,
- message: "Failed to get next sequence",
- });
- }
+ continue;
+ }
- const jobId = nextSequence.data;
- if (!jobId) {
- return json({
- success: false,
- message: "Failed to get job ID",
- });
- }
+ if (manufacturing.data?.manufacturingBlocked) {
+ console.warn(`Manufacturing is blocked for item ${item.id}`);
+ continue;
+ }
- const createJob = await upsertJob(
- client,
- {
- itemId: item.id,
- jobId,
- quantity: order.quantity,
- scrapQuantity: Math.ceil(
- order.quantity * (manufacturing.data?.scrapPercentage ?? 0)
- ),
- startDate: order.startDate ?? undefined,
- dueDate: order.dueDate ?? undefined,
- deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",
- locationId,
- companyId,
- createdBy: userId,
- unitOfMeasureCode: "EA",
- },
- "Planned"
+ if (manufacturing.data?.requiresConfiguration) {
+ console.warn(
+ `Manufacturing requires configuration for item ${item.id}`
);
+ continue;
+ }
- if (createJob.error) {
- return json({
- success: false,
- message: "Failed to create job",
- });
- }
+ // Process each order for this item
+ for (const order of orders) {
+ if (!order.existingId) {
+ // Create new job
+ const nextSequence = await getNextSequence(
+ client,
+ "job",
+ companyId
+ );
+ if (nextSequence.error) {
+ console.error(
+ `Failed to get next sequence for item ${item.id}:`,
+ nextSequence.error
+ );
+ continue;
+ }
- const id = createJob.data?.id;
- if (!id) {
- return json({
- success: false,
- message: "Failed to get created job ID",
- });
- }
+ const jobId = nextSequence.data;
+ if (!jobId) {
+ console.error(`Failed to get job ID for item ${item.id}`);
+ continue;
+ }
- const upsertMethod = await upsertJobMethod(client, "itemToJob", {
- sourceId: item.id,
- targetId: id,
- companyId,
- userId,
- });
+ const createJob = await upsertJob(
+ client,
+ {
+ itemId: item.id,
+ jobId,
+ quantity: order.quantity,
+ scrapQuantity: Math.ceil(
+ order.quantity * (manufacturing.data?.scrapPercentage ?? 0)
+ ),
+ startDate: order.startDate ?? undefined,
+ dueDate: order.dueDate ?? undefined,
+ deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",
+ locationId,
+ companyId,
+ createdBy: userId,
+ unitOfMeasureCode: "EA",
+ },
+ "Planned"
+ );
- if (upsertMethod.error) {
- return json({
- success: false,
- message: "Failed to create job method",
- });
- }
+ if (createJob.error) {
+ console.error(
+ `Failed to create job for item ${item.id}:`,
+ createJob.error
+ );
+ continue;
+ }
- jobIds.push(id);
- } else {
- jobIds.push(order.existingId);
- 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)
- ),
- startDate: order.startDate ?? undefined,
- status: "Planned",
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
- })
- .eq("id", order.existingId);
-
- if (updateJob.error) {
- console.error("Failed to update job", updateJob.error);
- return json({
- success: false,
- message: "Failed to update job",
+ const id = createJob.data?.id;
+ if (!id) {
+ console.error(
+ `Failed to get created job ID for item ${item.id}`
+ );
+ continue;
+ }
+
+ const upsertMethod = await upsertJobMethod(client, "itemToJob", {
+ sourceId: item.id,
+ targetId: id,
+ companyId,
+ userId,
});
+
+ if (upsertMethod.error) {
+ console.error(
+ `Failed to create job method for item ${item.id}:`,
+ upsertMethod.error
+ );
+ continue;
+ }
+
+ jobIds.push(id);
+ } else {
+ // Update existing job
+ jobIds.push(order.existingId);
+ 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)
+ ),
+ startDate: order.startDate ?? undefined,
+ status: "Planned",
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ .eq("id", order.existingId);
+
+ if (updateJob.error) {
+ console.error(
+ `Failed to update job ${order.existingId}:`,
+ updateJob.error
+ );
+ continue;
+ }
}
+
+ // Track supply forecast by period
+ const periodId = order.periodId;
+ supplyForecastByPeriod[periodId] =
+ (supplyForecastByPeriod[periodId] || 0) +
+ (order.quantity - (order.existingQuantity ?? 0));
}
- // Track supply forecast by period
- const periodId = order.periodId;
- supplyForecastByPeriod[periodId] =
- (supplyForecastByPeriod[periodId] || 0) +
- (order.quantity - (order.existingQuantity ?? 0));
- }
+ // Add job IDs to the overall list
+ allJobIds.push(...jobIds);
- await Promise.all([
- tasks.batchTrigger(
- "recalculate",
- jobIds.map((id) => ({
- payload: {
- type: "jobRequirements",
- id,
- companyId,
- userId,
- },
- }))
- ),
- client.from("supplyForecast").insert(
- Object.entries(supplyForecastByPeriod).map(
- ([periodId, quantity]) => ({
+ // Add supply forecasts for this item
+ Object.entries(supplyForecastByPeriod).forEach(
+ ([periodId, quantity]) => {
+ allSupplyForecasts.push({
itemId: item.id,
locationId,
sourceType: "Production Order" as const,
@@ -206,15 +222,57 @@ export async function action({ request }: ActionFunctionArgs) {
companyId,
createdBy: userId,
updatedBy: userId,
- })
- )
- ),
- ]);
- } else {
- // TODO: Implement multiple item order
+ });
+ }
+ );
+ }
+
+ // Insert all supply forecasts
+ if (allSupplyForecasts.length > 0) {
+ const insertForecasts = await client
+ .from("supplyForecast")
+ .insert(allSupplyForecasts);
+
+ if (insertForecasts.error) {
+ console.error(
+ "Failed to insert supply forecasts:",
+ insertForecasts.error
+ );
+ }
+ }
+
+ // Trigger recalculation for all jobs
+ if (allJobIds.length > 0) {
+ for (const jobId of allJobIds) {
+ await recalculateJobRequirements(client, {
+ id: jobId,
+ companyId,
+ userId,
+ });
+ }
+
+ await runMRP(client, {
+ type: "company",
+ id: companyId,
+ companyId,
+ userId,
+ });
+ }
+
+ return json({
+ success: true,
+ message: `Successfully processed ${itemsToOrder.length} items with ${allJobIds.length} jobs`,
+ });
+ } catch (error) {
+ console.error("Error processing production orders:", error);
+ return json({
+ success: false,
+ message: `Error processing production orders: ${
+ error instanceof Error ? error.message : "Unknown error"
+ }`,
+ });
}
- return json({ success: true, message: "Orders submitted" });
default:
return json({ success: false, message: "Invalid field" });
}
diff --git a/packages/database/supabase/migrations/20250616131548_production-planning.sql b/packages/database/supabase/migrations/20250616131548_production-planning.sql
index fdd6a1b891..a44db5142a 100644
--- a/packages/database/supabase/migrations/20250616131548_production-planning.sql
+++ b/packages/database/supabase/migrations/20250616131548_production-planning.sql
@@ -606,4 +606,5 @@ INNER JOIN "item" i ON j."itemId" = i."id" AND j."companyId" = i."companyId"
LEFT JOIN job_model jm ON j.id = jm.job_id AND j."companyId" = jm."companyId"
LEFT JOIN "modelUpload" mu ON mu.id = jm.model_upload_id
LEFT JOIN "salesOrder" so on j."salesOrderId" = so.id AND j."companyId" = so."companyId"
-LEFT JOIN "quote" qo ON j."quoteId" = qo.id AND j."companyId" = qo."companyId";
\ No newline at end of file
+LEFT JOIN "quote" qo ON j."quoteId" = qo.id AND j."companyId" = qo."companyId";
+