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: allow unconfigured parts to be configured with get method

Brad Barbin2e3006578aed
diff --git a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.ee.tsx b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.ee.tsx
index dcee863950..d1b4a75cb9 100644
--- a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.ee.tsx
+++ b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.ee.tsx
@@ -517,7 +517,7 @@ type ConfiguratorStepProps = {
function ConfiguratorStep({ group, parameters }: ConfiguratorStepProps) {
return (
- <div className="flex flex-col gap-6">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2 w-full">
{parameters.map((parameter) => (
<ParameterField key={parameter.id} parameter={parameter} />
))}
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 811922fd0e..06c4ffaadc 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1347,14 +1347,31 @@ export async function upsertJobMethod(
targetId: string;
companyId: string;
userId: string;
- configuration?: any;
+ configuration?: Record<string, unknown>;
}
) {
+ const body: {
+ type: "itemToJob" | "quoteLineToJob";
+ sourceId: string;
+ targetId: string;
+ companyId: string;
+ userId: string;
+ configuration?: Record<string, unknown>;
+ } = {
+ type,
+ sourceId: jobMethod.sourceId,
+ targetId: jobMethod.targetId,
+ companyId: jobMethod.companyId,
+ userId: jobMethod.userId,
+ };
+
+ // Only add configuration if it exists
+ if (jobMethod.configuration !== undefined) {
+ body.configuration = jobMethod.configuration;
+ }
+
const getMethodResult = await client.functions.invoke("get-method", {
- body: {
- type,
- ...jobMethod,
- },
+ body,
region: FunctionRegion.UsEast1,
});
if (getMethodResult.error) {
@@ -1374,16 +1391,31 @@ export async function upsertJobMaterialMakeMethod(
targetId: string;
companyId: string;
userId: string;
+ configuration?: Record<string, unknown>;
}
) {
+ const body: {
+ type: "itemToJobMakeMethod";
+ sourceId: string;
+ targetId: string;
+ companyId: string;
+ userId: string;
+ configuration?: Record<string, unknown>;
+ } = {
+ type: "itemToJobMakeMethod",
+ sourceId: jobMaterial.sourceId,
+ targetId: jobMaterial.targetId,
+ companyId: jobMaterial.companyId,
+ userId: jobMaterial.userId,
+ };
+
+ // Only add configuration if it exists
+ if (jobMaterial.configuration !== undefined) {
+ body.configuration = jobMaterial.configuration;
+ }
+
const { error } = await client.functions.invoke("get-method", {
- body: {
- type: "itemToJobMakeMethod",
- sourceId: jobMaterial.sourceId,
- targetId: jobMaterial.targetId,
- companyId: jobMaterial.companyId,
- userId: jobMaterial.userId,
- },
+ body,
region: FunctionRegion.UsEast1,
});
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index 899863b185..7811facf8d 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -53,6 +53,7 @@ import type {
ConfigurationParameter,
ConfigurationParameterGroup,
} from "~/modules/items";
+import { getConfigurationParameters } from "~/modules/items";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import MakeMethodVersionStatus from "~/modules/items/ui/Item/MakeMethodVersionStatus";
import { QuoteLineMethodForm } from "~/modules/sales/ui/Quotes/QuoteLineMethodForm";
@@ -193,6 +194,16 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
const [selectedMakeMethod, setSelectedMakeMethod] = useState<string | null>(
null
);
+ const [sourceItemRequiresConfiguration, setSourceItemRequiresConfiguration] =
+ useState(false);
+ const [
+ sourceItemConfigurationParameters,
+ setSourceItemConfigurationParameters,
+ ] = useState<{
+ groups: ConfigurationParameterGroup[];
+ parameters: ConfigurationParameter[];
+ }>({ groups: [], parameters: [] });
+ const [pendingGetMethodData, setPendingGetMethodData] = useState<any>(null);
const getMakeMethods = async (itemId: string) => {
setMakeMethods([]);
@@ -332,7 +343,66 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
fetcher={fetcher}
action={path.to.jobMethodGet}
validator={getJobMethodValidator}
- onSubmit={getMethodModal.onClose}
+ onSubmit={async (data, e) => {
+ if (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+
+ const sourceId = data.sourceId as string;
+ // Get type from the form element since it's not in validated data
+ const formElement = e?.target as HTMLFormElement;
+ const formData = new FormData(formElement);
+ const type = formData.get("type") as string;
+
+ // Only check configuration for "item" and "method" types, not "quoteLine"
+ if (sourceId && carbon && (type === "item" || type === "method")) {
+ // Store the form data for later use (include type which isn't in validated data)
+ setPendingGetMethodData({ ...data, type });
+
+ // Check if the source item requires configuration
+ const { data: replenishmentData } = await carbon
+ .from("itemReplenishment")
+ .select("requiresConfiguration, companyId")
+ .eq("itemId", sourceId)
+ .single();
+
+ if (replenishmentData?.requiresConfiguration) {
+ // Get configuration parameters for the source item
+ const companyId = replenishmentData?.companyId;
+ if (!companyId) {
+ toast.error("Unable to get company ID");
+ return;
+ }
+ const configParams = await getConfigurationParameters(
+ carbon,
+ sourceId,
+ companyId
+ );
+
+ setSourceItemRequiresConfiguration(true);
+ setSourceItemConfigurationParameters(configParams);
+ getMethodModal.onClose();
+ configuratorModal.onOpen();
+ } else {
+ // No configuration needed, proceed with normal submission
+ fetcher.submit({ ...data, type }, {
+ method: "post",
+ action: path.to.jobMethodGet,
+ });
+ getMethodModal.onClose();
+ }
+ } else {
+ // No sourceId, no carbon, or type is "quoteLine" - proceed with normal submission
+ // Need to include type for jobs since it's not in validated data
+ const dataWithType = type ? { ...data, type } : data;
+ fetcher.submit(dataWithType, {
+ method: "post",
+ action: path.to.jobMethodGet,
+ });
+ getMethodModal.onClose();
+ }
+ }}
>
<ModalHeader>
<ModalTitle>Get Method</ModalTitle>
@@ -538,23 +608,66 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
{configuratorModal.isOpen && (
<Suspense fallback={null}>
- <Await resolve={routeData?.configurationParameters}>
- {(configurationParameters) => (
- <ConfiguratorModal
- open
- destructive
- initialValues={
- (routeData?.job.configuration || {}) as Record<string, any>
+ {sourceItemRequiresConfiguration ? (
+ // Configurator for source item when getting method
+ <ConfiguratorModal
+ open
+ destructive
+ initialValues={{} as Record<string, any>}
+ groups={sourceItemConfigurationParameters.groups}
+ parameters={sourceItemConfigurationParameters.parameters}
+ onClose={() => {
+ configuratorModal.onClose();
+ setSourceItemRequiresConfiguration(false);
+ setSourceItemConfigurationParameters({
+ groups: [],
+ parameters: [],
+ });
+ }}
+ onSubmit={(config: Record<string, any>) => {
+ // Submit the get method with configuration
+ if (pendingGetMethodData) {
+ const dataWithConfig = {
+ ...pendingGetMethodData,
+ configuration: JSON.stringify(config),
+ };
+
+ fetcher.submit(dataWithConfig, {
+ method: "post",
+ action: path.to.jobMethodGet,
+ });
+
+ setPendingGetMethodData(null);
}
- groups={configurationParameters?.groups ?? []}
- parameters={configurationParameters?.parameters ?? []}
- onClose={configuratorModal.onClose}
- onSubmit={(config: Record<string, any>) => {
- saveConfiguration(config);
- }}
- />
- )}
- </Await>
+
+ configuratorModal.onClose();
+ setSourceItemRequiresConfiguration(false);
+ setSourceItemConfigurationParameters({
+ groups: [],
+ parameters: [],
+ });
+ }}
+ />
+ ) : (
+ // Regular configurator for job configuration
+ <Await resolve={routeData?.configurationParameters}>
+ {(configurationParameters) => (
+ <ConfiguratorModal
+ open
+ destructive
+ initialValues={
+ (routeData?.job.configuration || {}) as Record<string, any>
+ }
+ groups={configurationParameters?.groups ?? []}
+ parameters={configurationParameters?.parameters ?? []}
+ onClose={configuratorModal.onClose}
+ onSubmit={(config: Record<string, any>) => {
+ saveConfiguration(config);
+ }}
+ />
+ )}
+ </Await>
+ )}
</Suspense>
)}
</>
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 5767f1b03a..a797b33db9 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -2278,15 +2278,28 @@ export async function upsertQuoteLineMethod(
configuration?: Record<string, unknown>;
}
) {
+ const body: {
+ type: "itemToQuoteLine";
+ sourceId: string;
+ targetId: string;
+ companyId: string;
+ userId: string;
+ configuration?: Record<string, unknown>;
+ } = {
+ type: "itemToQuoteLine",
+ sourceId: lineMethod.itemId,
+ targetId: `${lineMethod.quoteId}:${lineMethod.quoteLineId}`,
+ companyId: lineMethod.companyId,
+ userId: lineMethod.userId,
+ };
+
+ // Only add configuration if it exists
+ if (lineMethod.configuration !== undefined) {
+ body.configuration = lineMethod.configuration;
+ }
+
return client.functions.invoke("get-method", {
- body: {
- type: "itemToQuoteLine",
- sourceId: lineMethod.itemId,
- targetId: `${lineMethod.quoteId}:${lineMethod.quoteLineId}`,
- companyId: lineMethod.companyId,
- configuration: lineMethod.configuration,
- userId: lineMethod.userId,
- },
+ body,
region: FunctionRegion.UsEast1,
});
}
@@ -2333,16 +2346,31 @@ export async function upsertQuoteMaterialMakeMethod(
targetId: string;
companyId: string;
userId: string;
+ configuration?: Record<string, unknown>;
}
) {
+ const body: {
+ type: "itemToQuoteMakeMethod";
+ sourceId: string;
+ targetId: string;
+ companyId: string;
+ userId: string;
+ configuration?: Record<string, unknown>;
+ } = {
+ type: "itemToQuoteMakeMethod",
+ sourceId: quoteMethod.sourceId,
+ targetId: quoteMethod.targetId,
+ companyId: quoteMethod.companyId,
+ userId: quoteMethod.userId,
+ };
+
+ // Only add configuration if it exists
+ if (quoteMethod.configuration !== undefined) {
+ body.configuration = quoteMethod.configuration;
+ }
+
const { error } = await client.functions.invoke("get-method", {
- body: {
- type: "itemToQuoteMakeMethod",
- sourceId: quoteMethod.sourceId,
- targetId: quoteMethod.targetId,
- companyId: quoteMethod.companyId,
- userId: quoteMethod.userId,
- },
+ body,
region: FunctionRegion.UsEast1,
});
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
index f7ffd7e567..f4acada2d4 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
@@ -50,6 +50,7 @@ import type {
ConfigurationParameter,
ConfigurationParameterGroup,
} from "~/modules/items";
+import { getConfigurationParameters } from "~/modules/items";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import MakeMethodVersionStatus from "~/modules/items/ui/Item/MakeMethodVersionStatus";
import type { MethodItemType } from "~/modules/shared/types";
@@ -167,6 +168,16 @@ const QuoteMakeMethodTools = () => {
const [selectedMakeMethod, setSelectedMakeMethod] = useState<string | null>(
null
);
+ const [sourceItemRequiresConfiguration, setSourceItemRequiresConfiguration] =
+ useState(false);
+ const [
+ sourceItemConfigurationParameters,
+ setSourceItemConfigurationParameters,
+ ] = useState<{
+ groups: ConfigurationParameterGroup[];
+ parameters: ConfigurationParameter[];
+ }>({ groups: [], parameters: [] });
+ const [pendingGetMethodData, setPendingGetMethodData] = useState<any>(null);
const getMakeMethods = async (itemId: string) => {
setMakeMethods([]);
@@ -274,7 +285,61 @@ const QuoteMakeMethodTools = () => {
fetcher={fetcher}
action={path.to.quoteMethodGet}
validator={getMethodValidator}
- onSubmit={getMethodModal.onClose}
+ onSubmit={async (data, e) => {
+ if (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+
+ const sourceId = data.sourceId as string;
+ const type = data.type as string;
+
+ // Only check configuration for "item" and "method" types, not "quoteLine"
+ if (sourceId && carbon && (type === "item" || type === "method")) {
+ // Store the form data for later use
+ setPendingGetMethodData(data);
+
+ // Check if the source item requires configuration
+ const { data: replenishmentData } = await carbon
+ .from("itemReplenishment")
+ .select("requiresConfiguration, companyId")
+ .eq("itemId", sourceId)
+ .single();
+
+ if (replenishmentData?.requiresConfiguration) {
+ // Get configuration parameters for the source item
+ const companyId = replenishmentData?.companyId;
+ if (!companyId) {
+ toast.error("Unable to get company ID");
+ return;
+ }
+ const configParams = await getConfigurationParameters(
+ carbon,
+ sourceId,
+ companyId
+ );
+
+ setSourceItemRequiresConfiguration(true);
+ setSourceItemConfigurationParameters(configParams);
+ getMethodModal.onClose();
+ configuratorModal.onOpen();
+ } else {
+ // No configuration needed, proceed with normal submission
+ fetcher.submit(data, {
+ method: "post",
+ action: path.to.quoteMethodGet,
+ });
+ getMethodModal.onClose();
+ }
+ } else {
+ // No sourceId, no carbon, or type is "quoteLine" - proceed with normal submission
+ fetcher.submit(data, {
+ method: "post",
+ action: path.to.quoteMethodGet,
+ });
+ getMethodModal.onClose();
+ }
+ }}
>
<ModalHeader>
<ModalTitle>Get Method</ModalTitle>
@@ -499,23 +564,66 @@ const QuoteMakeMethodTools = () => {
{configuratorModal.isOpen && (
<Suspense fallback={null}>
- <Await resolve={lineData?.configurationParameters}>
- {(configurationParameters) => (
- <ConfiguratorModal
- open
- destructive
- initialValues={
- (line?.configuration || {}) as Record<string, any>
+ {sourceItemRequiresConfiguration ? (
+ // Configurator for source item when getting method
+ <ConfiguratorModal
+ open
+ destructive
+ initialValues={{} as Record<string, any>}
+ groups={sourceItemConfigurationParameters.groups}
+ parameters={sourceItemConfigurationParameters.parameters}
+ onClose={() => {
+ configuratorModal.onClose();
+ setSourceItemRequiresConfiguration(false);
+ setSourceItemConfigurationParameters({
+ groups: [],
+ parameters: [],
+ });
+ }}
+ onSubmit={(config: Record<string, any>) => {
+ // Submit the get method with configuration
+ if (pendingGetMethodData) {
+ const dataWithConfig = {
+ ...pendingGetMethodData,
+ configuration: JSON.stringify(config),
+ };
+
+ fetcher.submit(dataWithConfig, {
+ method: "post",
+ action: path.to.quoteMethodGet,
+ });
+
+ setPendingGetMethodData(null);
}
- groups={configurationParameters?.groups ?? []}
- parameters={configurationParameters?.parameters ?? []}
- onClose={configuratorModal.onClose}
- onSubmit={(config: Record<string, any>) => {
- saveConfiguration(config);
- }}
- />
- )}
- </Await>
+
+ configuratorModal.onClose();
+ setSourceItemRequiresConfiguration(false);
+ setSourceItemConfigurationParameters({
+ groups: [],
+ parameters: [],
+ });
+ }}
+ />
+ ) : (
+ // Regular configurator for line configuration
+ <Await resolve={lineData?.configurationParameters}>
+ {(configurationParameters) => (
+ <ConfiguratorModal
+ open
+ destructive
+ initialValues={
+ (line?.configuration || {}) as Record<string, any>
+ }
+ groups={configurationParameters?.groups ?? []}
+ parameters={configurationParameters?.parameters ?? []}
+ onClose={configuratorModal.onClose}
+ onSubmit={(config: Record<string, any>) => {
+ saveConfiguration(config);
+ }}
+ />
+ )}
+ </Await>
+ )}
</Suspense>
)}
</>
diff --git a/apps/erp/app/routes/x+/job+/methods+/get.tsx b/apps/erp/app/routes/x+/job+/methods+/get.tsx
index 735ebb288b..0aa65108f5 100644
--- a/apps/erp/app/routes/x+/job+/methods+/get.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/get.tsx
@@ -18,6 +18,10 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const type = formData.get("type") as string;
+ const configurationStr = formData.get("configuration") as string | null;
+ const configuration = configurationStr
+ ? JSON.parse(configurationStr)
+ : undefined;
const serviceRole = getCarbonServiceRole();
@@ -27,14 +31,21 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (["item", "quoteLine"].includes(type)) {
+ const jobMethodPayload: any = {
+ ...validation.data,
+ companyId,
+ userId,
+ };
+
+ // Only add configuration if it exists
+ if (configuration !== undefined && type === "item") {
+ jobMethodPayload.configuration = configuration;
+ }
+
const jobMethod = await upsertJobMethod(
serviceRole,
type === "item" ? "itemToJob" : "quoteLineToJob",
- {
- ...validation.data,
- companyId,
- userId,
- }
+ jobMethodPayload
);
const [calculateQuantities, calculateDependencies] = await Promise.all([
@@ -68,11 +79,21 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (type === "method") {
- const makeMethod = await upsertJobMaterialMakeMethod(serviceRole, {
+ const makeMethodPayload: any = {
...validation.data,
companyId,
userId,
- });
+ };
+
+ // Only add configuration if it exists
+ if (configuration !== undefined) {
+ makeMethodPayload.configuration = configuration;
+ }
+
+ const makeMethod = await upsertJobMaterialMakeMethod(
+ serviceRole,
+ makeMethodPayload
+ );
if (makeMethod.error) {
return json({
diff --git a/apps/erp/app/routes/x+/quote+/methods+/get.tsx b/apps/erp/app/routes/x+/quote+/methods+/get.tsx
index 15b1177082..01f064b986 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/get.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/get.tsx
@@ -17,6 +17,8 @@ export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const type = formData.get("type") as string;
+ const configurationStr = formData.get("configuration") as string | null;
+ const configuration = configurationStr ? JSON.parse(configurationStr) : undefined;
const serviceRole = getCarbonServiceRole();
if (type === "item") {
@@ -28,13 +30,20 @@ export async function action({ request }: ActionFunctionArgs) {
const [quoteId, quoteLineId] = validation.data.targetId.split(":");
const itemId = validation.data.sourceId;
- const lineMethod = await upsertQuoteLineMethod(serviceRole, {
+ const lineMethodPayload: any = {
itemId,
quoteId,
quoteLineId,
companyId,
userId,
- });
+ };
+
+ // Only add configuration if it exists
+ if (configuration !== undefined) {
+ lineMethodPayload.configuration = configuration;
+ }
+
+ const lineMethod = await upsertQuoteLineMethod(serviceRole, lineMethodPayload);
return json({
error: lineMethod.error ? "Failed to get quote line method" : null,
@@ -64,11 +73,18 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const makeMethod = await upsertQuoteMaterialMakeMethod(serviceRole, {
+ const makeMethodPayload: any = {
...validation.data,
companyId,
userId,
- });
+ };
+
+ // Only add configuration if it exists
+ if (configuration !== undefined) {
+ makeMethodPayload.configuration = configuration;
+ }
+
+ const makeMethod = await upsertQuoteMaterialMakeMethod(serviceRole, makeMethodPayload);
if (makeMethod.error) {
return json({
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 46a7ec8c59..125d3b191a 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -873,6 +873,7 @@ serve(async (req: Request) => {
throw new Error("Invalid targetId");
}
const itemId = sourceId;
+ const isConfigured = !!configuration;
const [makeMethod, jobMakeMethod, workCenters, supplierProcesses] =
await Promise.all([
@@ -903,8 +904,22 @@ serve(async (req: Request) => {
throw new Error("Failed to get job make method");
}
- const [methodTrees] = await Promise.all([
+ const hydratedConfiguration = await hydrateConfiguration(
+ client,
+ configuration,
+ itemId,
+ companyId
+ );
+
+ 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) {
@@ -921,6 +936,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 jobMakeMethodOperation, jobMakeMethodMaterial
await Promise.all([
@@ -939,6 +962,38 @@ serve(async (req: Request) => {
.execute(),
]);
+ function getFieldKey(field: string, id: string) {
+ return `${field}:${id}`;
+ }
+
+ async function getConfiguredValue<T>({
+ 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 mod = await importTypeScript(
+ configurationCodeByField[fieldKey]
+ );
+ const result = await mod.configure(hydratedConfiguration);
+ return (result ?? defaultValue) as T;
+ } catch (err) {
+ console.error(err);
+ return defaultValue;
+ }
+ }
+
+ return defaultValue;
+ }
+
// traverse method tree and create:
// - jobMakeMethod
// - jobMakeMethodOperation
@@ -1776,6 +1831,7 @@ serve(async (req: Request) => {
throw new Error("Invalid targetId");
}
const itemId = sourceId;
+ const isConfigured = !!configuration;
const [makeMethod, quoteMakeMethod, workCenters, supplierProcesses] =
await Promise.all([
@@ -1806,8 +1862,22 @@ serve(async (req: Request) => {
throw new Error("Failed to get quote make method");
}
- const [methodTrees] = await Promise.all([
+ const hydratedConfiguration = await hydrateConfiguration(
+ client,
+ configuration,
+ itemId,
+ companyId
+ );
+
+ 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) {
@@ -1824,6 +1894,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 quoteMakeMethodOperation, quoteMakeMethodMaterial
await Promise.all([
@@ -1842,6 +1920,38 @@ serve(async (req: Request) => {
.execute(),
]);
+ function getFieldKey(field: string, id: string) {
+ return `${field}:${id}`;
+ }
+
+ async function getConfiguredValue<T>({
+ 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 mod = await importTypeScript(
+ configurationCodeByField[fieldKey]
+ );
+ const result = await mod.configure(hydratedConfiguration);
+ return (result ?? defaultValue) as T;
+ } catch (err) {
+ console.error(err);
+ return defaultValue;
+ }
+ }
+
+ return defaultValue;
+ }
+
// traverse method tree and create:
// - quoteMakeMethod
// - quoteMakeMethodOperation