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 bop in edge function

Brad Barbined2c4fb160ca
diff --git a/apps/erp/app/components/Configurator/ConfigurationEditor/ConfigurationEditor.tsx b/apps/erp/app/components/Configurator/ConfigurationEditor/ConfigurationEditor.tsx
index 242e812058..85f90c7af3 100644
--- a/apps/erp/app/components/Configurator/ConfigurationEditor/ConfigurationEditor.tsx
+++ b/apps/erp/app/components/Configurator/ConfigurationEditor/ConfigurationEditor.tsx
@@ -230,7 +230,8 @@ export default function Configurator({
}, [fetcher.data]);
const runCode = useCallback(() => {
- if (isUnsafeCode(code)) {
+ const jsCode = convertTypescriptToJavaScript(code);
+ if (isUnsafeCode(jsCode)) {
setOutput(
"Error: Unsupported code detected. The code you're trying to run contains disallowed patterns."
);
@@ -253,7 +254,7 @@ export default function Configurator({
const fn = new Function(
"parameters",
`
- ${convertTypescriptToJavaScript(code)}
+ ${jsCode}
return configure(parameters);
`
);
@@ -432,12 +433,10 @@ export default function Configurator({
function isUnsafeCode(code: string) {
// Check for disallowed code patterns
const disallowedPatterns = [
- /\b(for|while|do)\b/, // loops
/\bfetch\b/, // fetch calls
/setTimeout|setInterval/, // timeouts
/\bimport\b/, // dynamic imports
/new Promise/, // promise construction
- /\beval\b/, // eval
/Function\(/, // Function constructor
];
diff --git a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
index e4e22b1ee7..48929e2e25 100644
--- a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
+++ b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
@@ -271,6 +271,8 @@ function ConfiguratorFormContent({
return groupedParameters[currentStep].parameters.every((parameter) => {
if (parameter.dataType === "boolean") return true;
+ if (parameter.dataType === "numeric")
+ return formData[parameter.key] !== undefined;
return (
formData[parameter.key] !== undefined && formData[parameter.key] !== ""
);
@@ -339,6 +341,8 @@ function ConfiguratorForm(props: ConfiguratorFormProps) {
props.parameters.forEach((param) => {
if (param.dataType === "boolean") {
values[param.key] = props.initialValues?.[param.key] ?? false;
+ } else if (param.dataType === "numeric") {
+ values[param.key] = props.initialValues?.[param.key] ?? 0;
} else {
values[param.key] = props.initialValues?.[param.key] ?? "";
}
diff --git a/apps/erp/app/components/Form/WorkCenter.tsx b/apps/erp/app/components/Form/WorkCenter.tsx
index 532c9d85bd..5056b38f1f 100644
--- a/apps/erp/app/components/Form/WorkCenter.tsx
+++ b/apps/erp/app/components/Form/WorkCenter.tsx
@@ -11,6 +11,8 @@ import { path } from "~/utils/path";
type WorkCenterSelectProps = Omit<ComboboxProps, "options"> & {
processId?: string;
locationId?: string;
+ isConfigured?: boolean;
+ onConfigure?: () => void;
};
const WorkCenter = (props: WorkCenterSelectProps) => {
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
index f163ae7230..09a55a6e98 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -1014,23 +1014,6 @@ function OperationForm({
hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
}));
}}
- isConfigured={rulesByField.has(key("setupUnitHint"))}
- onConfigure={
- configurable && !isTemporaryId(item.id)
- ? () => {
- onConfigure({
- label: "Setup Unit",
- field: key("setupUnitHint"),
- code: rulesByField.get(key("setupUnitHint"))?.code,
- defaultValue: processData.setupUnitHint,
- returnType: {
- type: "enum",
- listOptions: ["Fixed", "Per Unit"],
- },
- });
- }
- : undefined
- }
/>
<NumberControlled
name="setupTime"
@@ -1140,23 +1123,6 @@ function OperationForm({
hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
}));
}}
- isConfigured={rulesByField.has(key("laborUnitHint"))}
- onConfigure={
- configurable && !isTemporaryId(item.id)
- ? () => {
- onConfigure({
- label: "Labor Unit",
- field: key("laborUnitHint"),
- code: rulesByField.get(key("laborUnitHint"))?.code,
- defaultValue: processData.laborUnitHint,
- returnType: {
- type: "enum",
- listOptions: ["Fixed", "Per Unit"],
- },
- });
- }
- : undefined
- }
/>
<NumberControlled
name="laborTime"
@@ -1267,23 +1233,6 @@ function OperationForm({
hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
}));
}}
- isConfigured={rulesByField.has(key("machineUnitHint"))}
- onConfigure={
- configurable && !isTemporaryId(item.id)
- ? () => {
- onConfigure({
- label: "Machine Unit",
- field: key("machineUnitHint"),
- code: rulesByField.get(key("machineUnitHint"))?.code,
- defaultValue: processData.machineUnitHint,
- returnType: {
- type: "enum",
- listOptions: ["Fixed", "Per Unit"],
- },
- });
- }
- : undefined
- }
/>
<NumberControlled
name="machineTime"
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
index 34fea21526..71469bc6e3 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
@@ -77,7 +77,7 @@ const PurchaseOrderHeader = () => {
/>
<Link to={path.to.purchaseOrderDetails(orderId)}>
<Heading size="h4" className="flex items-center gap-2">
- <span>{routeData?.purchaseOrder?.purchaseOrderId}</span>
+ {routeData?.purchaseOrder?.purchaseOrderId}
</Heading>
</Link>
<PurchasingStatus status={routeData?.purchaseOrder?.status} />
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index f233b2cd8d..0c267cc612 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1876,6 +1876,7 @@ export async function upsertQuoteLineMethod(
quoteLineId: string;
companyId: string;
userId: string;
+ configuration?: Record<string, unknown>;
}
) {
return client.functions.invoke("get-method", {
@@ -1884,6 +1885,7 @@ export async function upsertQuoteLineMethod(
sourceId: lineMethod.itemId,
targetId: `${lineMethod.quoteId}:${lineMethod.quoteLineId}`,
companyId: lineMethod.companyId,
+ configuration: lineMethod.configuration,
userId: lineMethod.userId,
},
});
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx
index 54e40c46ae..16b8c263a5 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.new.tsx
@@ -63,6 +63,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
quoteId,
quoteLineId,
itemId: data.itemId,
+ configuration,
companyId,
userId,
});
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 17a8cb28fc..d85c326383 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -21,6 +21,7 @@ import {
traverseJobMethod,
traverseQuoteMethod,
} from "../lib/methods.ts";
+import { importTypeScript } from "../lib/sandbox.ts";
import { getSupabaseServiceRoleFromAuthorizationHeader } from "../lib/supabase.ts";
const pool = getConnectionPool(1);
@@ -43,6 +44,7 @@ const payloadValidator = z.object({
targetId: z.string(),
companyId: z.string(),
userId: z.string(),
+ configuration: z.record(z.unknown()).optional(),
});
serve(async (req: Request) => {
@@ -52,7 +54,7 @@ serve(async (req: Request) => {
const payload = await req.json();
try {
- const { type, sourceId, targetId, companyId, userId } =
+ const { type, sourceId, targetId, companyId, userId, configuration } =
payloadValidator.parse(payload);
console.log({
@@ -62,6 +64,7 @@ serve(async (req: Request) => {
targetId,
companyId,
userId,
+ configuration,
});
const client = getSupabaseServiceRoleFromAuthorizationHeader(
@@ -631,22 +634,38 @@ serve(async (req: Request) => {
throw new Error("Invalid targetId");
}
const itemId = sourceId;
+ const isConfigured = !!configuration;
- const [makeMethod, quoteMakeMethod, workCenters, supplierProcesses] =
- await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
- client
- .from("quoteMakeMethod")
- .select("*")
- .eq("quoteLineId", quoteLineId)
- .is("parentMaterialId", null)
- .single(),
- client.from("workCenters").select("*").eq("companyId", companyId),
- client
- .from("supplierProcess")
- .select("*")
- .eq("companyId", companyId),
- ]);
+ const [
+ makeMethod,
+ quoteMakeMethod,
+ workCenters,
+ supplierProcesses,
+ configurationRules,
+ ] = await Promise.all([
+ client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("quoteMakeMethod")
+ .select("*")
+ .eq("quoteLineId", quoteLineId)
+ .is("parentMaterialId", null)
+ .single(),
+ client.from("workCenters").select("*").eq("companyId", companyId),
+ client.from("supplierProcess").select("*").eq("companyId", companyId),
+ isConfigured
+ ? client
+ .from("configurationRule")
+ .select("field, code")
+ .eq("itemId", itemId)
+ : Promise.resolve({ data: null, error: null }),
+ ]);
+
+ const configurationCodeByField = configurationRules?.data?.reduce<
+ Record<string, string>
+ >((acc, rule) => {
+ acc[rule.field] = rule.code;
+ return acc;
+ }, {});
if (makeMethod.error) {
throw new Error("Failed to get make method");
@@ -700,6 +719,36 @@ serve(async (req: Request) => {
.execute(),
]);
+ async function getConfiguredValue<
+ T extends number | string | boolean | null
+ >({
+ id,
+ field,
+ defaultValue,
+ }: {
+ id: string;
+ field: string;
+ defaultValue: T;
+ }): Promise<T> {
+ if (!configurationCodeByField) return defaultValue;
+
+ const fieldKey = getFieldKey(field, id);
+ if (configurationCodeByField[fieldKey]) {
+ try {
+ const code = configurationCodeByField[fieldKey];
+ const mod = await importTypeScript(code);
+ 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:
// - quoteMakeMethod
// - quoteMakeMethodOperation
@@ -715,34 +764,101 @@ serve(async (req: Request) => {
)
.eq("makeMethodId", node.data.materialMakeMethodId);
- const quoteOperations =
- relatedOperations?.data?.map((op) => ({
+ const quoteOperations: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =
+ [];
+ for await (const op of relatedOperations?.data ?? []) {
+ const [
+ processId,
+ 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: "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,
+ }),
+ ]);
+
+ quoteOperations.push({
quoteId,
quoteLineId,
quoteMakeMethodId: parentQuoteMakeMethodId!,
- processId: op.processId,
+ 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),
+ 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: {},
- })) ?? [];
+ });
+ }
let methodOperationsToQuoteOperations: Record<string, string> = {};
if (quoteOperations?.length > 0) {
@@ -2249,3 +2365,7 @@ function getMethodTreeArrayToTree(items: Method[]): MethodTreeItem[] {
return rootItems.map((item) => traverseAndRenameIds(item));
}
+
+function getFieldKey(field: string, id: string) {
+ return `${field}:${id}`;
+}
diff --git a/packages/database/supabase/functions/lib/sandbox.ts b/packages/database/supabase/functions/lib/sandbox.ts
index 2b141d4ac4..bd37fdbf6e 100644
--- a/packages/database/supabase/functions/lib/sandbox.ts
+++ b/packages/database/supabase/functions/lib/sandbox.ts
@@ -2,12 +2,10 @@ import { transpile } from "https://deno.land/x/[email protected]/mod.ts";
// Check for disallowed code patterns
const disallowedPatterns = [
- /\b(for|while|do)\b/, // loops
/\bfetch\b/, // fetch calls
/setTimeout|setInterval/, // timeouts
/\bimport\b/, // dynamic imports
/new Promise/, // promise construction
- /\beval\b/, // eval
/Function\(/, // Function constructor
];