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: configure and re-configure job

Brad Barbin1352ee4ea6af
diff --git a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
index f6fc6d8802..d12e0075cb 100644
--- a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
+++ b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
@@ -345,7 +345,7 @@ function ConfiguratorFormContent({
disabled={!isStepValid}
variant={isLastStep && destructive ? "destructive" : "primary"}
>
- {isLastStep ? "Save" : "Next"}
+ {isLastStep ? (destructive ? "Save and Overwrite" : "Save") : "Next"}
</Button>
</div>
</form>
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 72712b355f..73eed86d1c 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -832,6 +832,7 @@ export async function upsertJobMethod(
targetId: string;
companyId: string;
userId: string;
+ configuration?: any;
}
) {
return client.functions.invoke("get-method", {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index 16e6f816c0..717a8187b4 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -371,6 +371,7 @@ const JobBreadcrumbs = () => {
{(configurationParameters) => (
<ConfiguratorModal
open
+ destructive
initialValues={
(routeData?.job.configuration || {}) as Record<string, any>
}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.configure.tsx b/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
index 5c09f3980c..277a8e621d 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
@@ -1,11 +1,12 @@
-import { error, success } from "@carbon/auth";
+import { error, getCarbonServiceRole, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
+import { upsertJobMethod } from "~/modules/production";
import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "production",
role: "employee",
});
@@ -15,14 +16,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
const configuration = await request.json();
if (configuration) {
- const result = await client
- .from("job")
- .update({
- configuration,
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
- })
- .eq("id", jobId);
+ const [result, job] = await Promise.all([
+ client
+ .from("job")
+ .update({
+ configuration,
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ .eq("id", jobId),
+ client.from("job").select("itemId").eq("id", jobId).single(),
+ ]);
if (result.error) {
throw redirect(
@@ -30,6 +34,29 @@ export async function action({ request, params }: ActionFunctionArgs) {
await flash(request, error("Failed to update job"))
);
}
+
+ if (job.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(request, error("Failed to get job"))
+ );
+ }
+
+ const serviceRole = await getCarbonServiceRole();
+ const upsertMethod = await upsertJobMethod(serviceRole, "itemToJob", {
+ sourceId: job.data.itemId,
+ targetId: jobId,
+ companyId,
+ userId,
+ configuration,
+ });
+
+ if (upsertMethod.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(request, error("Failed to update job method"))
+ );
+ }
} else {
throw new Error("No configuration provided");
}
diff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsx
index d74e5ec47e..4ecf74dd91 100644
--- a/apps/erp/app/routes/x+/job+/new.tsx
+++ b/apps/erp/app/routes/x+/job+/new.tsx
@@ -87,6 +87,7 @@ export async function action({ request }: ActionFunctionArgs) {
targetId: id,
companyId,
userId,
+ configuration,
});
if (upsertMethod.error) {
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index e929bf524a..1610ffb8df 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -182,6 +182,7 @@ serve(async (req: Request) => {
throw new Error("Invalid targetId");
}
const itemId = sourceId;
+ const isConfigured = !!configuration;
const [makeMethod, jobMakeMethod, workCenters, supplierProcesses] =
await Promise.all([
@@ -211,8 +212,15 @@ serve(async (req: Request) => {
throw new Error("Failed to get related work centers");
}
- const [methodTrees] = await Promise.all([
+ const [methodTrees, configurationRules] = await Promise.all([
getMethodTree(client, makeMethod.data.id),
+ isConfigured
+ ? client
+ .from("configurationRule")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ : Promise.resolve({ data: [] }),
]);
if (methodTrees.error) {
@@ -229,6 +237,14 @@ serve(async (req: Request) => {
supplierProcesses?.data
);
+ // Get configuration code by field
+ const configurationCodeByField = configurationRules.data?.reduce<
+ Record<string, string>
+ >((acc, rule) => {
+ acc[rule.field] = rule.code;
+ return acc;
+ }, {});
+
await db.transaction().execute(async (trx) => {
// Delete existing jobMakeMethod, jobMakeMethodOperation, jobMakeMethodMaterial
await Promise.all([
@@ -245,6 +261,33 @@ serve(async (req: Request) => {
trx.deleteFrom("jobOperation").where("jobId", "=", jobId).execute(),
]);
+ async function getConfiguredValue<T>({
+ id,
+ field,
+ defaultValue,
+ }: {
+ id: string;
+ field: string;
+ defaultValue: T;
+ }): Promise<T> {
+ const configurationKey = `${id}:${field}`;
+
+ if (configurationCodeByField?.[configurationKey]) {
+ try {
+ const mod = await importTypeScript(
+ configurationCodeByField[configurationKey]
+ );
+ const result = await mod.configure(configuration);
+ return (result ?? defaultValue) as T;
+ } catch (err) {
+ console.error(err);
+ return defaultValue;
+ }
+ }
+
+ return defaultValue;
+ }
+
// traverse method tree and create:
// - jobMakeMethod
// - jobMakeMethodOperation
@@ -253,6 +296,10 @@ serve(async (req: Request) => {
node: MethodTreeItem,
parentJobMakeMethodId: string | null
) {
+ const nodeLevelConfigurationKey = `${
+ node.data.materialMakeMethodId
+ }:${node.data.isRoot ? "undefined" : node.data.methodMaterialId}`;
+
const relatedOperations = await client
.from("methodOperation")
.select(
@@ -260,33 +307,133 @@ serve(async (req: Request) => {
)
.eq("makeMethodId", node.data.materialMakeMethodId);
- const jobOperations =
- relatedOperations?.data?.map((op) => ({
+ let jobOperations: Database["public"]["Tables"]["jobOperation"]["Insert"][] =
+ [];
+ for await (const op of relatedOperations?.data ?? []) {
+ const [
+ processId,
+ workCenterId,
+ description,
+ setupTime,
+ setupUnit,
+ laborTime,
+ laborUnit,
+ machineTime,
+ machineUnit,
+ operationOrder,
+ operationType,
+ ] = await Promise.all([
+ getConfiguredValue({
+ id: op.id,
+ field: "processId",
+ defaultValue: op.processId,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "workCenterId",
+ defaultValue: op.workCenterId,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "description",
+ defaultValue: op.description,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "setupTime",
+ defaultValue: op.setupTime,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "setupUnit",
+ defaultValue: op.setupUnit,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "laborTime",
+ defaultValue: op.laborTime,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "laborUnit",
+ defaultValue: op.laborUnit,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "machineTime",
+ defaultValue: op.machineTime,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "machineUnit",
+ defaultValue: op.machineUnit,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "operationOrder",
+ defaultValue: op.operationOrder,
+ }),
+ getConfiguredValue({
+ id: op.id,
+ field: "operationType",
+ defaultValue: op.operationType,
+ }),
+ ]);
+
+ jobOperations.push({
jobId,
jobMakeMethodId: parentJobMakeMethodId!,
- processId: op.processId,
- workCenterId: op.workCenterId,
- description: op.description,
- setupTime: op.setupTime,
- setupUnit: op.setupUnit,
- laborTime: op.laborTime,
- laborUnit: op.laborUnit,
- machineTime: op.machineTime,
- machineUnit: op.machineUnit,
- ...getLaborAndOverheadRates(op.processId, op.workCenterId),
+ processId,
+ workCenterId,
+ description,
+ setupTime,
+ setupUnit,
+ laborTime,
+ laborUnit,
+ machineTime,
+ machineUnit,
+ ...getLaborAndOverheadRates(processId, op.workCenterId),
order: op.order,
- operationOrder: op.operationOrder,
- operationType: op.operationType,
+ operationOrder,
+ operationType,
operationSupplierProcessId: op.operationSupplierProcessId,
...getOutsideOperationRates(
- op.processId,
+ processId,
op.operationSupplierProcessId
),
workInstruction: op.workInstruction,
companyId,
createdBy: userId,
customFields: {},
- })) ?? [];
+ });
+ }
+
+ const bopConfigurationKey = `billOfProcess:${nodeLevelConfigurationKey}`;
+ let bopConfiguration: string[] | null = null;
+
+ if (configurationCodeByField?.[bopConfigurationKey]) {
+ const mod = await importTypeScript(
+ configurationCodeByField[bopConfigurationKey]
+ );
+ bopConfiguration = await mod.configure(configuration);
+ }
+
+ if (bopConfiguration) {
+ // @ts-expect-error - we can't assign undefined to materialsWithConfiguredFields but we filter them in the next step
+ jobOperations = bopConfiguration
+ .map((description, index) => {
+ const operation = jobOperations.find(
+ (operation) => operation.description === description
+ );
+ if (operation) {
+ return {
+ ...operation,
+ order: index + 1,
+ };
+ }
+ })
+ .filter(Boolean);
+ }
let methodOperationsToJobOperations: Record<string, string> = {};
if (jobOperations?.length > 0) {
@@ -335,38 +482,133 @@ serve(async (req: Request) => {
) ?? {};
}
- const mapMethodMaterialToJobMaterial = (child: MethodTreeItem) => ({
- jobId,
- jobMakeMethodId: parentJobMakeMethodId!,
- jobOperationId:
- methodOperationsToJobOperations[child.data.operationId],
- itemId: child.data.itemId,
- itemReadableId: child.data.itemReadableId,
- itemType: child.data.itemType,
- methodType: child.data.methodType,
- order: child.data.order,
- description: child.data.description,
- quantity: child.data.quantity,
- unitOfMeasureCode: child.data.unitOfMeasureCode,
- unitCost: child.data.unitCost,
- companyId,
- createdBy: userId,
- customFields: {},
- });
+ const mapMethodMaterialToJobMaterial = async (
+ child: MethodTreeItem
+ ) => {
+ let [
+ itemId,
+ description,
+ quantity,
+ methodType,
+ unitOfMeasureCode,
+ ] = await Promise.all([
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "itemId",
+ defaultValue: child.data.itemId,
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "description",
+ defaultValue: child.data.description,
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "quantity",
+ defaultValue: child.data.quantity,
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "methodType",
+ defaultValue: child.data.methodType,
+ }),
+ getConfiguredValue({
+ id: child.data.methodMaterialId,
+ field: "unitOfMeasureCode",
+ defaultValue: child.data.unitOfMeasureCode,
+ }),
+ ]);
- const madeChildren = node.children.filter(
- (child) => child.data.methodType === "Make"
- );
- const unmadeChildren = node.children.filter(
- (child) => child.data.methodType !== "Make"
- );
+ let itemReadableId = child.data.itemReadableId;
+ let itemType = child.data.itemType;
+ let unitCost = child.data.unitCost;
- const madeMaterials = madeChildren.map(
- mapMethodMaterialToJobMaterial
+ if (itemId !== child.data.itemId) {
+ const item = await client
+ .from("item")
+ .select("readableId, type, name, itemCost(unitCost)")
+ .eq("id", itemId)
+ .single();
+ if (item.data) {
+ itemReadableId = item.data.readableId;
+ itemType = item.data.type;
+ unitCost =
+ item.data.itemCost[0]?.unitCost ?? child.data.unitCost;
+ if (description === child.data.description) {
+ description = item.data.name;
+ }
+ } else {
+ itemId = child.data.itemId;
+ }
+ }
+
+ return {
+ jobId,
+ jobMakeMethodId: parentJobMakeMethodId!,
+ jobOperationId:
+ methodOperationsToJobOperations[child.data.operationId],
+ itemId,
+ itemReadableId,
+ itemType,
+ methodType,
+ order: child.data.order,
+ description,
+ quantity,
+ unitOfMeasureCode,
+ unitCost,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ };
+ };
+
+ let materialsWithConfiguredFields = await Promise.all(
+ node.children.map(mapMethodMaterialToJobMaterial)
);
- const pickedOrBoughtMaterials = unmadeChildren.map(
- mapMethodMaterialToJobMaterial
+
+ const bomConfigurationKey = `billOfMaterial:${nodeLevelConfigurationKey}`;
+ let bomConfiguration: string[] | null = null;
+
+ if (configurationCodeByField?.[bomConfigurationKey]) {
+ const mod = await importTypeScript(
+ configurationCodeByField[bomConfigurationKey]
+ );
+ bomConfiguration = await mod.configure(configuration);
+ }
+
+ if (bomConfiguration) {
+ // @ts-expect-error - we can't assign undefined to materialsWithConfiguredFields but we filter them in the next step
+ materialsWithConfiguredFields = bomConfiguration
+ .map((readableId, index) => {
+ const material = materialsWithConfiguredFields.find(
+ (material) => material.itemReadableId === readableId
+ );
+ if (material) {
+ return {
+ ...material,
+ order: index + 1,
+ };
+ }
+ })
+ .filter(Boolean);
+ }
+
+ const madeMaterials = materialsWithConfiguredFields.filter(
+ (material) => material.methodType === "Make"
);
+
+ const pickedOrBoughtMaterials =
+ materialsWithConfiguredFields.filter(
+ (material) => material.methodType !== "Make"
+ );
+
+ const madeChildren = madeMaterials.map((material, index) => {
+ const childIndex = materialsWithConfiguredFields.findIndex(
+ (m) => m.itemReadableId === material.itemReadableId
+ );
+ return node.children[childIndex];
+ });
+
if (madeMaterials.length > 0) {
const madeMaterialIds = await trx
.insertInto("jobMaterial")
diff --git a/packages/react/src/Alert.tsx b/packages/react/src/Alert.tsx
index dc029cf118..2b98ecdc69 100644
--- a/packages/react/src/Alert.tsx
+++ b/packages/react/src/Alert.tsx
@@ -5,7 +5,7 @@ import { forwardRef } from "react";
import { cn } from "./utils/cn";
const alertVariants = cva(
- "relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-5 [&>svg]:text-foreground",
+ "relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-[19px] [&>svg]:text-foreground",
{
variants: {
variant: {
@@ -14,7 +14,7 @@ const alertVariants = cva(
"bg-gradient-to-tr via-card to-card hover:to-muted/30 hover:via-muted/30 border-emerald-600/30 from-emerald-600/10 text-emerald-600 [&>svg]:text-emerald-600 dark:text-foreground dark:[&>svg]:text-foreground",
warning: "",
destructive:
- "bg-gradient-to-tr via-card to-card hover:to-muted/30 hover:via-muted/30 border-red-500/30 from-red-500/10 text-destructive [&>svg]:text-destructive dark:text-foreground dark:[&>svg]:text-foreground",
+ "bg-gradient-to-tr via-card to-card hover:to-muted/30 hover:via-muted/30 border-red-500/30 from-red-500/10 text-destructive [&>svg]:text-destructive dark:text-foreground dark:[&>svg]:text-red-500",
},
},
defaultVariants: {