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 configurator
Brad Barbind1ea4b554286
diff --git a/apps/carbon/app/components/Configurator/Configurator.tsx b/apps/carbon/app/components/Configurator/Configurator.tsxnew file mode 100644index 0000000000..69caa5add1--- /dev/null+++ b/apps/carbon/app/components/Configurator/Configurator.tsx@@ -0,0 +1,303 @@+/* eslint-disable no-new-func */+import { Button, Modal, ModalContent, ModalTitle } from "@carbon/react";+import type { OnMount } from "@monaco-editor/react";+import Editor from "@monaco-editor/react";+import type * as Monaco from "monaco-editor";+import { useCallback, useEffect, useMemo, useState } from "react";+import { LuPlay, LuSave } from "react-icons/lu";+import { useMode } from "~/hooks/useMode";+import ParameterPanel from "./ParameterPanel";+import type { Configuration, Parameter, ParameterInput } from "./types";+import { typeMap } from "./types";+import {+ configureMonaco,+ generateDefaultCode,+ generateTypeDefinitions,+ getDefaultValue,+ stripTypeScript,+} from "./utils";++interface ConfiguratorProps {+ configuration: Configuration;+ parameters: ParameterInput[];+ open: boolean;+ onClose: () => void;+ onSave: (code: string) => void;+}++export default function Configurator({+ configuration,+ open,+ parameters: defaultParameters,+ onClose,+ onSave,+}: ConfiguratorProps) {+ const { code: defaultCode, label, returnType } = configuration;++ const mode = useMode();+ const [output, setOutput] = useState<string>("");+ const [parameters, setParameters] = useState<Parameter[]>(+ defaultParameters.map((param) => ({+ name: param.key,+ type: param.dataType,+ value: getDefaultValue(param.dataType, param.listOptions),+ config:+ param.dataType === "list"+ ? { options: param.listOptions ?? [] }+ : undefined,+ }))+ );++ useEffect(() => {+ setParameters((prev) =>+ defaultParameters.map((param) => ({+ name: param.key,+ type: param.dataType,+ value:+ prev.find((p) => p.name === param.key)?.value ||+ getDefaultValue(param.dataType, param.listOptions),+ config:+ param.dataType === "list"+ ? { options: param.listOptions ?? [] }+ : undefined,+ }))+ );+ }, [defaultParameters]);++ const [code, setCode] = useState(+ generateDefaultCode(parameters, returnType, defaultCode)+ );+ const [editor, setEditor] =+ useState<Monaco.editor.IStandaloneCodeEditor | null>(null);+ const [monaco, setMonaco] = useState<typeof Monaco | null>(null);++ const lockedLines = useMemo(() => {+ const baseLockedLines = 8; // For the function declaration and closing lines+ const totalLockedLines = baseLockedLines + parameters.length;++ return totalLockedLines;+ }, [parameters]);++ useEffect(() => {+ if (editor && monaco) {+ editor.onDidChangeCursorSelection(() => {+ const selectionInLockedRange = editor+ .getSelections()+ ?.some((selection) => {+ return selection.intersectRanges(+ new monaco.Range(1, 0, lockedLines + 1, 0)+ );+ });+ editor.updateOptions({+ readOnly: selectionInLockedRange,+ readOnlyMessage: { value: "Cannot edit locked lines." },+ });+ });+ }+ }, [editor, monaco, lockedLines]);++ const handleEditorDidMount: OnMount = (editor, monaco) => {+ setEditor(editor);+ setMonaco(monaco);++ // Configure Monaco+ configureMonaco(monaco);++ // Add initial type definitions+ const typeDefinitions = generateTypeDefinitions(parameters, returnType);+ monaco.languages.typescript.javascriptDefaults.addExtraLib(+ typeDefinitions,+ "parameters.d.ts"+ );++ editor.onDidChangeCursorSelection(() => {+ const selectionInLockedRange = editor+ .getSelections()+ ?.some((selection) => {+ return selection.intersectRanges(+ new monaco.Range(1, 0, lockedLines + 1, 0)+ );+ });++ editor.updateOptions({+ readOnly: selectionInLockedRange,+ readOnlyMessage: { value: "Cannot edit locked lines." },+ });+ });+ };++ // Update type definitions when parameters change+ useEffect(() => {+ if (monaco && editor) {+ const typeDefinitions = generateTypeDefinitions(parameters, returnType);+ monaco.languages.typescript.javascriptDefaults.addExtraLib(+ typeDefinitions,+ "parameters.d.ts"+ );++ // Trigger a re-validation of the model+ const model = editor.getModel();+ if (model) {+ monaco.editor.setModelMarkers(model, "typescript", []);+ }+ }+ }, [parameters, monaco, editor, returnType]);++ const getCodeToSave = () => {+ const lines = code.split("\n");+ const startLine = lockedLines;+ let endLine = lines.length - 1;++ // Find the closing brace of the configure function+ let braceCount = 0;+ for (let i = startLine; i < lines.length; i++) {+ const line = lines[i];+ braceCount += (line.match(/{/g) || []).length;+ braceCount -= (line.match(/}/g) || []).length;+ if (braceCount === -1) {+ endLine = i;+ break;+ }+ }++ const storedCode = lines.slice(startLine, endLine).join("\n").trim();+ return storedCode;+ };++ const handleSave = () => {+ const codeToSave = getCodeToSave();+ onSave(codeToSave);+ };++ const runCode = useCallback(() => {+ try {+ // Check for potentially problematic code+ const codeStr = stripTypeScript(code);++ // Create parameters object from the panel+ const parametersObj = parameters.reduce((acc, v) => {+ acc[v.name] =+ v.type === "numeric"+ ? Number(v.value)+ : v.type === "boolean"+ ? v.value === "true"+ : v.value;+ return acc;+ }, {} as Record<string, string | number | boolean>);++ // Execute the code+ const fn = new Function(+ "parameters",+ `+ ${codeStr}+ return configure(parameters);+ `+ );++ const result = fn(parametersObj);++ // Verify return type+ if (returnType.type === "list") {+ if (!Array.isArray(result)) {+ throw new Error("Expected return type to be an array");+ }+ if (returnType.listOptions) {+ const invalidValue = result.find(+ (value) => !returnType.listOptions?.includes(value)+ );+ if (invalidValue) {+ throw new Error(+ `Invalid value "${invalidValue}" in array. Must be one of: ${returnType.listOptions.join(+ ", "+ )}`+ );+ }+ }+ } else {+ const actualType = typeof result;+ if (actualType !== typeMap[returnType.type]) {+ throw new Error(+ `Expected return type ${returnType.type}, but got ${actualType}`+ );+ }+ }++ setOutput(`Result: ${JSON.stringify(result)}`);+ } catch (error) {+ setOutput(`Error: ${(error as Error).message}`);+ }+ }, [code, parameters, returnType]);++ if (!open) return null;++ return (+ <Modal+ open={open}+ onOpenChange={(open) => {+ if (!open) {+ onClose();+ }+ }}+ >+ <ModalContent size="xxxlarge" className="p-0 gap-0 h-[90dvh]">+ <div className="flex p-6">+ <ModalTitle>Configure {label}</ModalTitle>+ </div>++ <div className="flex-1 flex h-full border-t">+ <div className="flex-1 w-2/3 border-r">+ <div className="h-full">+ <Editor+ height="100%"+ defaultLanguage="javascript"+ value={code}+ onChange={(value) => setCode(value || "")}+ theme={mode === "light" ? "vs-light" : "vs-dark"}+ onMount={handleEditorDidMount}+ options={{+ minimap: { enabled: false },+ fontSize: 14,+ suggest: {+ showProperties: true,+ showValues: true,+ preview: true,+ },+ quickSuggestions: true,+ snippetSuggestions: "inline",+ formatOnType: true,+ formatOnPaste: true,+ }}+ />+ </div>+ </div>++ <div className="w-1/3 flex flex-col">+ <ParameterPanel parameters={parameters} onChange={setParameters} />+ <div className="p-4 border-t space-y-2">+ <Button+ onClick={handleSave}+ className="w-full"+ leftIcon={<LuSave />}+ variant="secondary"+ >+ Save & Close+ </Button>+ <Button+ onClick={runCode}+ className="w-full"+ leftIcon={<LuPlay />}+ variant="primary"+ >+ Run Test+ </Button>++ <div className="font-mono mt-4 p-2 bg-accent rounded min-h-[100px] whitespace-pre-wrap">+ {output}+ </div>+ </div>+ </div>+ </div>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/carbon/app/components/Configurator/Icons.tsx b/apps/carbon/app/components/Configurator/Icons.tsxnew file mode 100644index 0000000000..de5a3599c5--- /dev/null+++ b/apps/carbon/app/components/Configurator/Icons.tsx@@ -0,0 +1,25 @@+import { cn } from "@carbon/react";+import { LuHash, LuList, LuToggleLeft, LuType } from "react-icons/lu";++export function ConfiguratorDataTypeIcon({+ type,+ className,+}: {+ type: "numeric" | "text" | "boolean" | "list";+ className?: string;+}) {+ switch (type) {+ case "numeric":+ return <LuHash className={cn("w-4 h-4 text-blue-600", className)} />;+ case "text":+ return <LuType className={cn("w-4 h-4 text-green-600", className)} />;+ case "boolean":+ return (+ <LuToggleLeft className={cn("w-4 h-4 text-purple-600", className)} />+ );+ case "list":+ return <LuList className={cn("w-4 h-4 text-orange-600", className)} />;+ default:+ return null;+ }+}diff --git a/apps/carbon/app/components/Configurator/ParameterPanel.tsx b/apps/carbon/app/components/Configurator/ParameterPanel.tsxnew file mode 100644index 0000000000..2cf791544e--- /dev/null+++ b/apps/carbon/app/components/Configurator/ParameterPanel.tsx@@ -0,0 +1,79 @@+import { ConfiguratorDataTypeIcon } from "./Icons";+import type { Parameter } from "./types";++interface ParameterPanelProps {+ parameters: Parameter[];+ onChange: (parameters: Parameter[]) => void;+}++export default function ParameterPanel({+ parameters,+ onChange,+}: ParameterPanelProps) {+ const updateValue = (index: number, value: string) => {+ const newParameters = [...parameters];+ newParameters[index] = { ...newParameters[index], value };+ onChange(newParameters);+ };++ return (+ <div className="flex-1 p-4 overflow-y-auto text-sm">+ <h3 className="text-lg font-semibold mb-4">Parameters</h3>+ <div className="border rounded-lg overflow-hidden">+ <div className="grid grid-cols-2 bg-accent border-b">+ <div className="px-4 py-2 font-medium text-muted-foreground border-r">+ Name+ </div>+ <div className="px-4 py-2 font-medium text-muted-foreground">+ Test Value+ </div>+ </div>++ {parameters.map((parameter, index) => (+ <div+ key={parameter.name}+ className="grid grid-cols-2 border-b last:border-b-0 hover:bg-accent"+ >+ <div className="px-4 py-2 border-r flex items-center gap-2 min-w-[140px]">+ <ConfiguratorDataTypeIcon type={parameter.type} />+ <span className="text-sm font-medium text-foreground">+ {parameter.name}+ </span>+ </div>+ <div className="px-2 py-1">+ {parameter.type === "boolean" ? (+ <select+ value={parameter.value}+ onChange={(e) => updateValue(index, e.target.value)}+ className="w-full h-full px-2 bg-transparent border-0 focus:ring-0"+ >+ <option value="true">true</option>+ <option value="false">false</option>+ </select>+ ) : parameter.type === "list" && parameter.config?.options ? (+ <select+ value={parameter.value}+ onChange={(e) => updateValue(index, e.target.value)}+ className="w-full h-full px-2 bg-transparent border-0 focus:ring-0"+ >+ {parameter.config.options.map((option) => (+ <option key={option} value={option}>+ {option}+ </option>+ ))}+ </select>+ ) : (+ <input+ type={parameter.type === "numeric" ? "number" : "text"}+ value={parameter.value}+ onChange={(e) => updateValue(index, e.target.value)}+ className="w-full h-full px-2 bg-transparent border-0 focus:ring-0"+ />+ )}+ </div>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/apps/carbon/app/components/Configurator/index.ts b/apps/carbon/app/components/Configurator/index.tsnew file mode 100644index 0000000000..08c8236134--- /dev/null+++ b/apps/carbon/app/components/Configurator/index.ts@@ -0,0 +1,3 @@+import Configurator from "./Configurator";++export { Configurator };diff --git a/apps/carbon/app/components/Configurator/types.ts b/apps/carbon/app/components/Configurator/types.tsnew file mode 100644index 0000000000..6342e47091--- /dev/null+++ b/apps/carbon/app/components/Configurator/types.ts@@ -0,0 +1,40 @@+export type Configuration = {+ label: string;+ code?: string;+ returnType: ReturnType;+};++export type ConfiguratorDataType = "boolean" | "list" | "numeric" | "text";++export interface ListTypeConfig {+ options: string[];+}++export interface Parameter {+ config?: ListTypeConfig;+ name: string;+ type: ConfiguratorDataType;+ value: string;+}++export type ParameterInput = {+ dataType: ConfiguratorDataType;+ key: string;+ listOptions: string[] | null;+};++export type ReturnType = {+ listOptions?: string[];+ type: ConfiguratorDataType;+};++export type TypeMap = {+ [key in ConfiguratorDataType]: string;+};++export const typeMap: TypeMap = {+ boolean: "boolean",+ list: "string[]",+ numeric: "number",+ text: "string",+};diff --git a/apps/carbon/app/components/Configurator/utils.ts b/apps/carbon/app/components/Configurator/utils.tsnew file mode 100644index 0000000000..cfcadc5eca--- /dev/null+++ b/apps/carbon/app/components/Configurator/utils.ts@@ -0,0 +1,146 @@+import type * as Monaco from "monaco-editor";+import {+ typeMap,+ type ConfiguratorDataType,+ type Parameter,+ type ReturnType,+} from "./types";++export function configureMonaco(monaco: typeof Monaco) {+ // Configure JavaScript defaults+ monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({+ noSemanticValidation: false,+ noSyntaxValidation: false,+ });++ monaco.languages.typescript.javascriptDefaults.setCompilerOptions({+ target: monaco.languages.typescript.ScriptTarget.ES2020,+ allowNonTsExtensions: true,+ moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,+ module: monaco.languages.typescript.ModuleKind.CommonJS,+ noEmit: true,+ typeRoots: ["node_modules/@types"],+ strict: true,+ });+}++export function generateDefaultCode(+ params: Parameter[],+ returnType: ReturnType,+ defaultCode?: string+): string {+ const parameterTypes = params+ .map((parameter) => {+ if (parameter.type === "list" && parameter.config?.options) {+ const unionType = parameter.config.options+ .map((opt) => `"${opt}"`)+ .join(" | ");+ return ` * @param params.${parameter.name}: ${unionType}`;+ }+ return ` * @param params.${parameter.name}: ${typeMap[parameter.type]}`;+ })+ .join("\n ");++ const returnTypeStr =+ returnType.type === "list" && returnType.listOptions+ ? `Array<${returnType.listOptions.map((opt) => `"${opt}"`).join(" | ")}>`+ : typeMap[returnType.type];++ return `+/**+ * Configure function that processes the provided params+ * @returns ${+ returnType.type === "list"+ ? "an array of predefined values"+ : `a ${returnType.type} value`+ }+ ${parameterTypes}+**/++function configure(params: Params): ${returnTypeStr} {+ // return ${+ returnType.type === "list"+ ? "an array of predefined values"+ : `a ${returnType.type} value`+ }+ ${+ defaultCode+ ? `${defaultCode}`+ : `return ${+ returnType.type === "text"+ ? '"test"'+ : returnType.type === "numeric"+ ? "1"+ : returnType.type === "boolean"+ ? "true"+ : returnType.listOptions+ ? `["${returnType.listOptions[0]}"]`+ : "[]"+ };`+ }+}`;+}++export function getDefaultValue(+ type: ConfiguratorDataType,+ listOptions: string[] | null+): string {+ switch (type) {+ case "numeric":+ return "1";+ case "text":+ return "test";+ case "boolean":+ return "true";+ case "list":+ return listOptions ? listOptions[0] : "";+ }+}++export function generateTypeDefinitions(+ params: Parameter[],+ returnType: ReturnType+): string {+ const properties = params+ .map((parameter) => {+ let typeStr = parameter.type;+ if (parameter.type === "list" && parameter.config?.options) {+ // @ts-expect-error - we know this is a list+ typeStr = parameter.config.options.map((opt) => `"${opt}"`).join(" | ");+ }+ const comment = `/** ${parameter.name} - ${parameter.type} parameter */`;+ return ` ${comment}\n ${parameter.name}: ${typeStr};`;+ })+ .join("\n\n");++ const returnTypeStr =+ returnType.type === "list" && returnType.listOptions+ ? `(${returnType.listOptions.map((opt) => `"${opt}"`).join(" | ")})[]`+ : returnType.type;++ return `+declare type Params = {+${properties}+}++/**+ * Configure function that processes the provided params+ * @param params The params object containing all available params+ * @returns A value matching the selected return type+ */+declare function configure(params: Params): ${returnTypeStr};+`;+}++export function stripTypeScript(code: string): string {+ return code+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/interface\s+\w+\s*{[^}]*}/g, "")+ .replace(/type\s+\w+\s*=\s*[^;]+;/g, "")+ .replace(/(\w+)\s*:\s*[^,)]+([,)])/g, "$1$2")+ .replace(/\)\s*:\s*[^{]+({)/g, ") $1")+ .replace(/as\s+[^;,)]+([;,)])/g, "$1")+ .replace(/<[^>]+>/g, "")+ .replace(/\n\s*\n\s*\n/g, "\n\n")+ .trim();+}diff --git a/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsxdeleted file mode 100644index 30c05a0ba6..0000000000--- a/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx+++ /dev/null@@ -1,258 +0,0 @@-/* eslint-disable react/display-name */-import type { Database } from "@carbon/database";-import { Combobox } from "@carbon/react";-import type {- PostgrestSingleResponse,- SupabaseClient,-} from "@supabase/supabase-js";-import type { EditableTableCellComponentProps } from "~/components/Editable";-import type { PurchaseInvoiceLine } from "~/modules/invoicing";-import type { Item } from "~/stores";--const EditablePurchaseInvoiceLineNumber =- (- mutation: (- accessorKey: string,- newValue: string,- row: PurchaseInvoiceLine- ) => Promise<PostgrestSingleResponse<unknown>>,- options: {- client?: SupabaseClient<Database>;- items: Item[];- accounts: { label: string; value: string }[];- defaultLocationId: string | null;- supplierId: string;- userId: string;- }- ) =>- ({- value,- row,- accessorKey,- onError,- onUpdate,- }: EditableTableCellComponentProps<PurchaseInvoiceLine>) => {- const { client, items, accounts, supplierId, userId } = options;- const selectOptions =- row.invoiceLineType === "G/L Account"- ? accounts- : items- .filter((item) => item.type === row.invoiceLineType)- .map((item) => ({- label: item.name,- value: item.id,- }));-- const onAccountChange = async (accountNumber: string) => {- if (!client) throw new Error("Carbon client not found");-- const account = await client- .from("account")- .select("name")- .eq("number", accountNumber)- .eq("companyId", row.companyId)- .single();-- onUpdate({- itemId: null,- itemReadableId: null,- description: account.data?.name ?? "",- accountNumber: accountNumber,- });-- try {- const { error } = await client- .from("purchaseInvoiceLine")- .update({- itemId: null,- itemReadableId: null,- accountNumber: accountNumber,- description: account.data?.name ?? "",- updatedBy: userId,- })- .eq("id", row.id);-- if (error) onError();- } catch (error) {- console.error(error);- onError();- }- };-- const onItemChange = async (itemId: string) => {- if (!client) throw new Error("Carbon client not found");- switch (row.invoiceLineType) {- case "Material":- case "Part":- case "Tool":- case "Consumable":- const [item, supplierPart, inventory] = await Promise.all([- client- .from("item")- .select(- "name, readableId, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"- )- .eq("id", itemId)- .eq("companyId", row.companyId!)- .single(),- client- .from("supplierPart")- .select("*")- .eq("itemId", itemId)- .eq("companyId", row.companyId!)- .eq("supplierId", supplierId)- .maybeSingle(),- client- .from("pickMethod")- .select("defaultShelfId")- .eq("itemId", itemId)- .eq("companyId", row.companyId!)- .eq("locationId", row.locationId!)- .maybeSingle(),- ]);-- const itemCost = item?.data?.itemCost?.[0];- const itemReplenishment = item?.data?.itemReplenishment;-- if (item.error || supplierPart.error || inventory.error) {- onError();- return;- }-- onUpdate({- itemId: itemId,- itemReadableId: item.data?.readableId,- locationId: options.defaultLocationId,- description: item.data?.name ?? "",- quantity: supplierPart?.data?.minimumOrderQuantity ?? 1,- unitPrice: supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0,- purchaseUnitOfMeasureCode:- itemReplenishment?.purchasingUnitOfMeasureCode ??- item.data?.unitOfMeasureCode ??- "EA",-- conversionFactor: itemReplenishment?.conversionFactor ?? 1,- shelfId: inventory.data?.defaultShelfId ?? null,- });-- try {- const { error } = await client- .from("purchaseInvoiceLine")- .update({- itemId: itemId,- itemReadableId: item.data?.readableId,- locationId: options.defaultLocationId,- description: item.data?.name ?? "",- quantity: supplierPart?.data?.minimumOrderQuantity ?? 1,- unitPrice:- supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0,- purchaseUnitOfMeasureCode:- itemReplenishment?.purchasingUnitOfMeasureCode ??- item.data?.unitOfMeasureCode ??- "EA",-- conversionFactor: itemReplenishment?.conversionFactor ?? 1,- shelfId: inventory.data?.defaultShelfId ?? null,- updatedBy: userId,- })- .eq("id", row.id);-- if (error) onError();- } catch (error) {- console.error(error);- onError();- }- break;- case "Service":- const service = await client- .from("item")- .select("readableId, name")- .eq("id", itemId)- .eq("companyId", row.companyId)- .single();-- if (service.error) {- onError();- return;- }-- onUpdate({- itemId: itemId,- itemReadableId: service.data?.readableId,- description: service.data?.name,- });-- try {- const { error } = await client- .from("purchaseInvoiceLine")- .update({- itemId: itemId,- itemReadableId: service.data?.readableId,- description: service.data?.name,- updatedBy: userId,- })- .eq("id", row.id);-- if (error) onError();- } catch (error) {- console.error(error);- onError();- }- break;- default:- throw new Error(- `Invalid invoice line type: ${row.invoiceLineType} is not implemented`- );- }- };-- const onChange = (newValue: string | null) => {- if (!newValue) return;-- if (- ["Part", "Service", "Material", "Tool", "Consumable"].includes(- row.invoiceLineType- )- ) {- onItemChange(newValue);- } else if (row.invoiceLineType === "G/L Account") {- onAccountChange(newValue);- }- };-- const selectedValue = getValue(row);-- return (- <Combobox- autoFocus- value={selectedValue ?? ""}- options={selectOptions}- onChange={onChange}- size="sm"- className="border-0 rounded-none w-full"- />- );- };--EditablePurchaseInvoiceLineNumber.displayName =- "EditablePurchaseInvoiceLineNumber";-export default EditablePurchaseInvoiceLineNumber;--function getValue(row: PurchaseInvoiceLine) {- switch (row.invoiceLineType) {- case "Part":- case "Service":- case "Material":- case "Tool":- case "Fixture":- case "Consumable":- return row.itemId;-- case "G/L Account":- return row.accountNumber;- case "Fixed Asset":- return row.assetId;- default:- return null;- }-}diff --git a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsxdeleted file mode 100644index cec4c53be2..0000000000--- a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx+++ /dev/null@@ -1,263 +0,0 @@-/* eslint-disable react/display-name */-import type { Database } from "@carbon/database";-import { Combobox } from "@carbon/react";-import type {- PostgrestSingleResponse,- SupabaseClient,-} from "@supabase/supabase-js";-import type { EditableTableCellComponentProps } from "~/components/Editable";-import type { PurchaseOrderLine } from "~/modules/purchasing";-import type { Item } from "~/stores";--const EditablePurchaseOrderLineNumber =- (- mutation: (- accessorKey: string,- newValue: string,- row: PurchaseOrderLine- ) => Promise<PostgrestSingleResponse<unknown>>,- options: {- client?: SupabaseClient<Database>;- items: Item[];- accounts: { label: string; value: string }[];- defaultLocationId: string | null;- supplierId: string;- userId: string;- }- ) =>- ({- value,- row,- accessorKey,- onError,- onUpdate,- }: EditableTableCellComponentProps<PurchaseOrderLine>) => {- const { client, items, accounts, supplierId, userId } = options;- const selectOptions =- row.purchaseOrderLineType === "G/L Account"- ? accounts- : items- .filter((item) => item.type === row.purchaseOrderLineType)- .map((item) => ({- label: item.name,- value: item.id,- }));-- const onAccountChange = async (accountNumber: string) => {- if (!client) throw new Error("Carbon client not found");- if (!row.companyId) throw new Error("Company ID not found");- if (!row.id) throw new Error("Purchase order line ID not found");-- const account = await client- .from("account")- .select("name")- .eq("number", accountNumber)- .eq("companyId", row.companyId)- .single();-- onUpdate({- itemId: null,- itemReadableId: null,- description: account.data?.name ?? "",- accountNumber: accountNumber,- });-- try {- const { error } = await client- .from("purchaseOrderLine")- .update({- itemId: null,- itemReadableId: null,- accountNumber: accountNumber,- description: account.data?.name ?? "",- updatedBy: userId,- })- .eq("id", row.id);-- if (error) onError();- } catch (error) {- console.error(error);- onError();- }- };-- const onItemChange = async (itemId: string) => {- if (!client) throw new Error("Carbon client not found");- if (!row.companyId) throw new Error("Company ID not found");- if (!row.id) throw new Error("Purchase order line ID not found");-- switch (row.purchaseOrderLineType) {- case "Material":- case "Part":- case "Tool":- case "Consumable":- const [item, supplierPart, inventory] = await Promise.all([- client- .from("item")- .select(- "name, readableId, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"- )- .eq("id", itemId)- .eq("companyId", row.companyId!)- .single(),-- client- .from("supplierPart")- .select("*")- .eq("itemId", itemId)- .eq("companyId", row.companyId!)- .eq("supplierId", supplierId)- .maybeSingle(),- client- .from("pickMethod")- .select("defaultShelfId")- .eq("itemId", itemId)- .eq("companyId", row.companyId!)- .eq("locationId", row.locationId!)- .maybeSingle(),- ]);-- const itemCost = item?.data?.itemCost?.[0];- const itemReplenishment = item?.data?.itemReplenishment;-- if (item.error || supplierPart.error || inventory.error) {- onError();- return;- }-- onUpdate({- itemId: itemId,- itemReadableId: item.data?.readableId,- locationId: options.defaultLocationId,- description: item.data?.name ?? "",- purchaseQuantity: supplierPart?.data?.minimumOrderQuantity ?? 1,- unitPrice: supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0,- purchaseUnitOfMeasureCode:- itemReplenishment?.purchasingUnitOfMeasureCode ??- item.data?.unitOfMeasureCode ??- "EA",-- conversionFactor: itemReplenishment?.conversionFactor ?? 1,- shelfId: inventory.data?.defaultShelfId ?? null,- });-- try {- const { error } = await client- .from("purchaseOrderLine")- .update({- itemId: itemId,- itemReadableId: item.data?.readableId,- locationId: options.defaultLocationId,- description: item.data?.name ?? "",- purchaseQuantity: supplierPart?.data?.minimumOrderQuantity ?? 1,- unitPrice:- supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0,- purchaseUnitOfMeasureCode:- itemReplenishment?.purchasingUnitOfMeasureCode ??- item.data?.unitOfMeasureCode ??- "EA",-- conversionFactor: itemReplenishment?.conversionFactor ?? 1,- shelfId: inventory.data?.defaultShelfId ?? null,- updatedBy: userId,- })- .eq("id", row.id);-- if (error) onError();- } catch (error) {- console.error(error);- onError();- }- break;- case "Service":- const service = await client- .from("item")- .select("name, readableId")- .eq("id", itemId)- .eq("companyId", row.companyId)- .single();-- if (service.error) {- onError();- return;- }-- onUpdate({- itemId: itemId,- itemReadableId: service.data?.readableId,- description: service.data?.name,- });-- try {- const { error } = await client- .from("purchaseOrderLine")- .update({- itemId: itemId,- itemReadableId: service.data?.readableId,- description: service.data?.name,- updatedBy: userId,- })- .eq("id", row.id);-- if (error) onError();- } catch (error) {- console.error(error);- onError();- }- break;- default:- throw new Error(- `Invalid invoice line type: ${row.purchaseOrderLineType} is not implemented`- );- }- };-- const onChange = (newValue: string | null) => {- if (!newValue) return;- if (!row.purchaseOrderLineType) return;-- if (- ["Part", "Service", "Material", "Tool", "Consumable"].includes(- row.purchaseOrderLineType- )- ) {- onItemChange(newValue);- } else if (row.purchaseOrderLineType === "G/L Account") {- onAccountChange(newValue);- }- };-- const selectedValue = getValue(row);-- return (- <Combobox- autoFocus- value={selectedValue ?? ""}- options={selectOptions}- onChange={onChange}- size="sm"- className="border-0 rounded-none w-full"- />- );- };--EditablePurchaseOrderLineNumber.displayName = "EditablePurchaseOrderLineNumber";-export default EditablePurchaseOrderLineNumber;--function getValue(row: PurchaseOrderLine) {- switch (row.purchaseOrderLineType) {- case "Part":- // case "Service":- case "Material":- case "Tool":- case "Consumable":- return row.itemId;-- case "G/L Account":- return row.accountNumber;- case "Fixed Asset":- return row.assetId;- default:- return null;- }-}diff --git a/apps/carbon/app/components/Editable/index.ts b/apps/carbon/app/components/Editable/index.tsindex 3af30890b1..daaaa5515b 100644--- a/apps/carbon/app/components/Editable/index.ts+++ b/apps/carbon/app/components/Editable/index.ts@@ -1,14 +1,6 @@import EditableList from "./EditableList";import EditableNumber from "./EditableNumber";-import EditablePurchaseInvoiceLineNumber from "./EditablePurchaseInvoiceLineNumber";-import EditablePurchaseOrderLineNumber from "./EditablePurchaseOrderLineNumber";import EditableText from "./EditableText";export * from "./types";-export {- EditableList,- EditableNumber,- EditablePurchaseInvoiceLineNumber,- EditablePurchaseOrderLineNumber,- EditableText,-};+export { EditableList, EditableNumber, EditableText };diff --git a/apps/carbon/app/modules/items/types.ts b/apps/carbon/app/modules/items/types.tsindex f17078cd9b..9fc4fcaa69 100644--- a/apps/carbon/app/modules/items/types.ts+++ b/apps/carbon/app/modules/items/types.ts@@ -30,7 +30,11 @@ import type {} from "./items.service";export type ConfigurationParameter = NonNullable<- Awaited<ReturnType<typeof getConfigurationParameters>>["data"]+ Awaited<ReturnType<typeof getConfigurationParameters>>["parameters"]+>[number];++export type ConfigurationParameterGroup = NonNullable<+ Awaited<ReturnType<typeof getConfigurationParameters>>["groups"]>[number];export type Consumable = NonNullable<diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsxindex 9909127ad1..3a91207fed 100644--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -11,7 +11,9 @@ import {CardTitle,cn,HStack,+ IconButton,toast,+ useDisclosure,useThrottle,VStack,} from "@carbon/react";@@ -19,9 +21,11 @@ import { useFetcher, useFetchers, useParams } from "@remix-run/react";import { AnimatePresence, LayoutGroup, motion } from "framer-motion";import type { Dispatch, SetStateAction } from "react";import { useCallback, useEffect, useState } from "react";-import { LuSettings2, LuX } from "react-icons/lu";+import { flushSync } from "react-dom";+import { LuFunctionSquare, LuSettings2, LuX } from "react-icons/lu";import type { z } from "zod";import { MethodIcon, MethodItemTypeIcon } from "~/components";+import type { Configuration } from "~/components/Configurator/types";import {DefaultMethodType,Hidden,@@ -39,10 +43,12 @@ import type {import { SortableList, SortableListItem } from "~/components/SortableList";import { usePermissions, useUser } from "~/hooks";+import { Configurator } from "~/components/Configurator";import type { MethodItemType, MethodType } from "~/modules/shared";import { path } from "~/utils/path";import type { methodOperationValidator } from "../../items.models";import { methodMaterialValidator } from "../../items.models";+import type { ConfigurationParameter } from "../../types";type Material = z.infer<typeof methodMaterialValidator> & {description: string;@@ -55,9 +61,11 @@ type ItemWithData = SortableItem & {};type BillOfMaterialProps = {+ configurable?: boolean;makeMethodId: string;materials: Material[];operations: Operation[];+ parameters?: ConfigurationParameter[];};type OrderState = {@@ -72,57 +80,6 @@ type TemporaryItems = {[key: string]: Material;};-function makeItems(- materials: Material[],- orderState: OrderState,- checkedState: CheckedState-): ItemWithData[] {- return materials.map((material) => {- const order = material.id- ? orderState[material.id] ?? material.order- : material.order;- const checked = material.id ? checkedState[material.id] ?? false : false;- return makeItem(material, order, checked);- });-}--function makeItem(- material: Material,- order: number,- checked: boolean-): ItemWithData {- return {- id: material.id!,- title: (- <VStack spacing={0} className="py-2.5">- <h3 className="font-semibold truncate">{material.itemReadableId}</h3>- {material?.description && (- <span className="text-xs text-muted-foreground">- {material.description}{" "}- </span>- )}- </VStack>- ),- checked,- details: (- <HStack spacing={2}>- <Badge variant="secondary">- <MethodIcon type={material.methodType} />- </Badge>-- <Badge variant="secondary">{material.quantity}</Badge>- <Badge variant="secondary">- <MethodItemTypeIcon type={material.itemType} />- </Badge>- </HStack>- ),- data: {- ...material,- order,- },- };-}-const initialMethodMaterial: Omit<Material, "makeMethodId" | "order"> & {description: string;} = {@@ -135,36 +92,12 @@ const initialMethodMaterial: Omit<Material, "makeMethodId" | "order"> & {unitOfMeasureCode: "EA",};-const usePendingMaterials = () => {- type PendingItem = ReturnType<typeof useFetchers>[number] & {- formData: FormData;- };-- return useFetchers()- .filter((fetcher): fetcher is PendingItem => {- return (- (fetcher.formAction === path.to.newMethodMaterial ||- fetcher.formAction?.includes("/items/methods/material/")) ??- false- );- })- .reduce<z.infer<typeof methodMaterialValidator>[]>((acc, fetcher) => {- const formData = fetcher.formData;- const material = methodMaterialValidator.safeParse(- Object.fromEntries(formData)- );-- if (material.success) {- return [...acc, material.data];- }- return acc;- }, []);-};-const BillOfMaterial = ({+ configurable = false,makeMethodId,materials: initialMaterials,operations,+ parameters,}: BillOfMaterialProps) => {const fetcher = useFetcher<{}>();const permissions = usePermissions();@@ -209,7 +142,7 @@ const BillOfMaterial = ({materialsById.set(id, material);});- const items = makeItems(+ const materials = makeItems(Array.from(materialsById.values()),orderState,checkedState@@ -229,8 +162,8 @@ const BillOfMaterial = ({setSelectedItemId(temporaryId);let newOrder = 1;- if (items.length) {- newOrder = Math.max(...items.map((item) => item.data.order)) + 1;+ if (materials.length) {+ newOrder = Math.max(...materials.map((item) => item.data.order)) + 1;}setTemporaryItems((prev) => ({@@ -313,16 +246,16 @@ const BillOfMaterial = ({const newState = { ...prev };let changed = false;- items.forEach((item) => {- if (item.checked) {- newState[item.id] = false;+ materials.forEach((material) => {+ if (material.checked) {+ newState[material.id] = false;changed = true;}});return changed ? newState : prev;});- }, [items]);+ }, [materials]);const renderListItem = ({item,@@ -453,6 +386,11 @@ const BillOfMaterial = ({);};+ const configuratorDisclosure = useDisclosure();+ const [configuration, setConfiguration] = useState<Configuration | null>(+ null+ );+return (<Card><HStack className="justify-between">@@ -461,26 +399,59 @@ const BillOfMaterial = ({</CardHeader><CardAction>- <Button- variant="secondary"- isDisabled={- !permissions.can("update", "parts") || selectedItemId !== null- }- onClick={onAddItem}- >- Add Material- </Button>+ <div className="flex items-center gap-2">+ <Button+ variant="secondary"+ isDisabled={+ !permissions.can("update", "parts") || selectedItemId !== null+ }+ onClick={onAddItem}+ >+ Add Material+ </Button>+ {configurable && (+ <IconButton+ icon={<LuFunctionSquare />}+ aria-label="Configure"+ variant="ghost"+ onClick={() => {+ flushSync(() => {+ setConfiguration({+ label: "Bill of Material",+ code: undefined,+ returnType: {+ type: "list",+ listOptions: materials.map(+ (m) => m.data.itemReadableId!+ ),+ },+ });+ });+ configuratorDisclosure.onOpen();+ }}+ />+ )}+ </div></CardAction></HStack><CardContent><SortableList- items={items}+ items={materials}onReorder={onReorder}onToggleItem={onToggleItem}onRemoveItem={onRemoveItem}renderItem={renderListItem}/></CardContent>+ {configuratorDisclosure.isOpen && configuration && (+ <Configurator+ configuration={configuration}+ open={configuratorDisclosure.isOpen}+ parameters={parameters ?? []}+ onClose={configuratorDisclosure.onClose}+ onSave={() => {}}+ />+ )}</Card>);};@@ -695,3 +666,80 @@ function MaterialForm({</ValidatedForm>);}++function makeItems(+ materials: Material[],+ orderState: OrderState,+ checkedState: CheckedState+): ItemWithData[] {+ return materials.map((material) => {+ const order = material.id+ ? orderState[material.id] ?? material.order+ : material.order;+ const checked = material.id ? checkedState[material.id] ?? false : false;+ return makeItem(material, order, checked);+ });+}++function makeItem(+ material: Material,+ order: number,+ checked: boolean+): ItemWithData {+ return {+ id: material.id!,+ title: (+ <VStack spacing={0} className="py-2.5">+ <h3 className="font-semibold truncate">{material.itemReadableId}</h3>+ {material?.description && (+ <span className="text-xs text-muted-foreground">+ {material.description}{" "}+ </span>+ )}+ </VStack>+ ),+ checked,+ details: (+ <HStack spacing={2}>+ <Badge variant="secondary">+ <MethodIcon type={material.methodType} />+ </Badge>++ <Badge variant="secondary">{material.quantity}</Badge>+ <Badge variant="secondary">+ <MethodItemTypeIcon type={material.itemType} />+ </Badge>+ </HStack>+ ),+ data: {+ ...material,+ order,+ },+ };+}++const usePendingMaterials = () => {+ type PendingItem = ReturnType<typeof useFetchers>[number] & {+ formData: FormData;+ };++ return useFetchers()+ .filter((fetcher): fetcher is PendingItem => {+ return (+ (fetcher.formAction === path.to.newMethodMaterial ||+ fetcher.formAction?.includes("/items/methods/material/")) ??+ false+ );+ })+ .reduce<z.infer<typeof methodMaterialValidator>[]>((acc, fetcher) => {+ const formData = fetcher.formData;+ const material = methodMaterialValidator.safeParse(+ Object.fromEntries(formData)+ );++ if (material.success) {+ return [...acc, material.data];+ }+ return acc;+ }, []);+};diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsxindex 65b486cd71..cd4591e2bc 100644--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx@@ -37,6 +37,7 @@ import { useEffect, useRef, useState } from "react";import {LuAlertTriangle,LuChevronDown,+ LuFunctionSquare,LuHammer,LuMoreVertical,LuPlusCircle,@@ -61,6 +62,9 @@ import {WorkCenter,} from "~/components/Form";+import { flushSync } from "react-dom";+import { Configurator } from "~/components/Configurator";+import type { Configuration } from "~/components/Configurator/types";import { getUnitHint } from "~/components/Form/UnitHint";import { ConfirmDelete } from "~/components/Modals";import type { Item, SortableItemRenderProps } from "~/components/SortableList";@@ -77,6 +81,7 @@ import type { action as newMethodOperationToolAction } from "~/routes/x+/items+/import { useTools } from "~/stores";import { getPrivateUrl, path } from "~/utils/path";import { methodOperationValidator } from "../../items.models";+import type { ConfigurationParameter } from "../../types";type Operation = z.infer<typeof methodOperationValidator> & {workInstruction: JSONContent | null;@@ -91,8 +96,10 @@ type ItemWithData = Item & {};type BillOfProcessProps = {+ configurable?: boolean;makeMethodId: string;operations: OperationWithTools[];+ parameters?: ConfigurationParameter[];};type PendingWorkInstructions = {@@ -111,48 +118,6 @@ type TemporaryItems = {[key: string]: Operation;};-function makeItems(operations: Operation[]): ItemWithData[] {- return operations.map(makeItem);-}--function makeItem(operation: Operation): ItemWithData {- return {- id: operation.id!,- title: <h3 className="font-semibold truncate">{operation.description}</h3>,- checked: false,- order: operation.operationOrder,- details: (- <HStack spacing={1}>- {operation.operationType === "Outside" ? (- <Badge>Outside</Badge>- ) : (- <>- {(operation?.setupTime ?? 0) > 0 && (- <Badge variant="secondary">- <TimeTypeIcon type="Setup" className="h-3 w-3 mr-1" />- {operation.setupTime} {operation.setupUnit}- </Badge>- )}- {(operation?.laborTime ?? 0) > 0 && (- <Badge variant="secondary">- <TimeTypeIcon type="Labor" className="h-3 w-3 mr-1" />- {operation.laborTime} {operation.laborUnit}- </Badge>- )}- {(operation?.machineTime ?? 0) > 0 && (- <Badge variant="secondary">- <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />- {operation.machineTime} {operation.machineUnit}- </Badge>- )}- </>- )}- </HStack>- ),- data: operation,- };-}-const initialOperation: Omit<Operation, "makeMethodId" | "order" | "tools"> = {description: "",laborTime: 0,@@ -168,35 +133,11 @@ const initialOperation: Omit<Operation, "makeMethodId" | "order" | "tools"> = {workInstruction: {},};-const usePendingOperations = () => {- type PendingItem = ReturnType<typeof useFetchers>[number] & {- formData: FormData;- };-- return useFetchers()- .filter((fetcher): fetcher is PendingItem => {- return (- (fetcher.formAction === path.to.newMethodOperation ||- fetcher.formAction?.includes("/items/methods/operation/")) ??- false- );- })- .reduce<z.infer<typeof methodOperationValidator>[]>((acc, fetcher) => {- const formData = fetcher.formData;- const operation = methodOperationValidator.safeParse(- Object.fromEntries(formData)- );-- if (operation.success) {- return [...acc, operation.data];- }- return acc;- }, []);-};-const BillOfProcess = ({+ configurable = false,makeMethodId,operations: initialOperations,+ parameters,}: BillOfProcessProps) => {const permissions = usePermissions();const { carbon } = useCarbon();@@ -616,6 +557,11 @@ const BillOfProcess = ({);};+ const configuratorDisclosure = useDisclosure();+ const [configuration, setConfiguration] = useState<Configuration | null>(+ null+ );+return (<Card><HStack className="justify-between">@@ -624,15 +570,37 @@ const BillOfProcess = ({</CardHeader><CardAction>- <Button- variant="secondary"- isDisabled={- !permissions.can("update", "parts") || selectedItemId !== null- }- onClick={onAddItem}- >- Add Operation- </Button>+ <div className="flex items-center gap-2">+ <Button+ variant="secondary"+ isDisabled={+ !permissions.can("update", "parts") || selectedItemId !== null+ }+ onClick={onAddItem}+ >+ Add Operation+ </Button>+ {configurable && (+ <IconButton+ icon={<LuFunctionSquare />}+ aria-label="Configure"+ variant="ghost"+ onClick={() => {+ flushSync(() => {+ setConfiguration({+ label: "Bill of Process",+ code: undefined,+ returnType: {+ type: "list",+ listOptions: operations.map((op) => op.description),+ },+ });+ });+ configuratorDisclosure.onOpen();+ }}+ />+ )}+ </div></CardAction></HStack><CardContent>@@ -644,6 +612,15 @@ const BillOfProcess = ({renderItem={renderListItem}/></CardContent>+ {configuratorDisclosure.isOpen && configuration && (+ <Configurator+ configuration={configuration}+ open={configuratorDisclosure.isOpen}+ parameters={parameters ?? []}+ onClose={configuratorDisclosure.onClose}+ onSave={() => {}}+ />+ )}</Card>);};@@ -1353,3 +1330,71 @@ function ToolsForm({</div>);}++function makeItems(operations: Operation[]): ItemWithData[] {+ return operations.map(makeItem);+}++function makeItem(operation: Operation): ItemWithData {+ return {+ id: operation.id!,+ title: <h3 className="font-semibold truncate">{operation.description}</h3>,+ checked: false,+ order: operation.operationOrder,+ details: (+ <HStack spacing={1}>+ {operation.operationType === "Outside" ? (+ <Badge>Outside</Badge>+ ) : (+ <>+ {(operation?.setupTime ?? 0) > 0 && (+ <Badge variant="secondary">+ <TimeTypeIcon type="Setup" className="h-3 w-3 mr-1" />+ {operation.setupTime} {operation.setupUnit}+ </Badge>+ )}+ {(operation?.laborTime ?? 0) > 0 && (+ <Badge variant="secondary">+ <TimeTypeIcon type="Labor" className="h-3 w-3 mr-1" />+ {operation.laborTime} {operation.laborUnit}+ </Badge>+ )}+ {(operation?.machineTime ?? 0) > 0 && (+ <Badge variant="secondary">+ <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />+ {operation.machineTime} {operation.machineUnit}+ </Badge>+ )}+ </>+ )}+ </HStack>+ ),+ data: operation,+ };+}++function usePendingOperations() {+ type PendingItem = ReturnType<typeof useFetchers>[number] & {+ formData: FormData;+ };++ return useFetchers()+ .filter((fetcher): fetcher is PendingItem => {+ return (+ (fetcher.formAction === path.to.newMethodOperation ||+ fetcher.formAction?.includes("/items/methods/operation/")) ??+ false+ );+ })+ .reduce<z.infer<typeof methodOperationValidator>[]>((acc, fetcher) => {+ const formData = fetcher.formData;+ const operation = methodOperationValidator.safeParse(+ Object.fromEntries(formData)+ );++ if (operation.success) {+ return [...acc, operation.data];+ }+ return acc;+ }, []);+}diff --git a/apps/carbon/app/modules/items/ui/Parts/ConfigurationParameters.tsx b/apps/carbon/app/modules/items/ui/Parts/ConfigurationParameters.tsxindex d8afa5a963..592f6772af 100644--- a/apps/carbon/app/modules/items/ui/Parts/ConfigurationParameters.tsx+++ b/apps/carbon/app/modules/items/ui/Parts/ConfigurationParameters.tsx@@ -41,13 +41,9 @@ import { useEffect, useRef, useState } from "react";import {LuFolderOpen,LuGripVertical,- LuHash,LuKeySquare,- LuList,LuMoreVertical,LuPlusCircle,- LuToggleLeft,- LuType,} from "react-icons/lu";import { EmployeeAvatar } from "~/components";import type { ConfigurationParameter } from "~/modules/items";@@ -86,6 +82,7 @@ import {import { SortableContext, useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { createPortal, flushSync } from "react-dom";+import { ConfiguratorDataTypeIcon } from "~/components/Configurator/Icons";import { ConfirmDelete } from "~/components/Modals";type ConfigurationParameterGroup = {@@ -231,7 +228,7 @@ export default function ConfigurationParametersForm({options={configurationParameterDataTypes.map((type) => ({label: (<HStack className="w-full">- <ConfigurationParameterDataTypeIcon+ <ConfiguratorDataTypeIcontype={type}className="mr-2"/>@@ -884,10 +881,7 @@ function ConfigurableParameter({options={configurationParameterDataTypes.map((type) => ({label: (<HStack className="w-full">- <ConfigurationParameterDataTypeIcon- type={type}- className="mr-2"- />+ <ConfiguratorDataTypeIcon type={type} className="mr-2" />{capitalize(type)}</HStack>),@@ -929,7 +923,7 @@ function ConfigurableParameter({/><HStack spacing={4} className="flex-1"><div className="bg-muted border rounded-full flex items-center justify-center p-2">- <ConfigurationParameterDataTypeIcon+ <ConfiguratorDataTypeIcontype={parameter.dataType}className="w-4 h-4"/>@@ -993,29 +987,6 @@ function ConfigurableParameter({);}-function ConfigurationParameterDataTypeIcon({- type,- className,-}: {- type: (typeof configurationParameterDataTypes)[number];- className?: string;-}) {- switch (type) {- case "numeric":- return <LuHash className={cn("w-4 h-4 text-blue-600", className)} />;- case "text":- return <LuType className={cn("w-4 h-4 text-green-600", className)} />;- case "boolean":- return (- <LuToggleLeft className={cn("w-4 h-4 text-purple-600", className)} />- );- case "list":- return <LuList className={cn("w-4 h-4 text-orange-600", className)} />;- default:- return null;- }-}-function useConfigurationParameters(parameter?: ConfigurationParameter) {const { itemId } = useParams();if (!itemId) throw new Error("Could not find itemId");diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsxindex 61449ec2a0..fa292339e9 100644--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx@@ -2,17 +2,10 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import {- Card,- CardContent,- CardHeader,- CardTitle,- VStack,-} from "@carbon/react";-import { Await, useLoaderData, useParams } from "@remix-run/react";+import { VStack } from "@carbon/react";+import { useLoaderData, useParams } from "@remix-run/react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";-import { defer, redirect } from "@vercel/remix";-import { Suspense } from "react";+import { json, redirect } from "@vercel/remix";import { useRouteData } from "~/hooks";import type { MakeMethod, Material, MethodOperation } from "~/modules/items";import {@@ -55,12 +48,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- return defer({+ return json({partManufacturing: partManufacturing.data,configurationParametersAndGroups: partManufacturing.data.requiresConfiguration- ? getConfigurationParameters(client, itemId, companyId)- : Promise.resolve({ groups: [], parameters: [] }),+ ? await getConfigurationParameters(client, itemId, companyId)+ : { groups: [], parameters: [] },});}@@ -136,41 +129,30 @@ export default function MakeMethodRoute() {initialValues={manufacturingInitialValues}/>{partManufacturing.requiresConfiguration && (- <Suspense- fallback={- <Card>- <CardHeader>- <CardTitle>Parameters</CardTitle>- </CardHeader>- <CardContent className="min-h-[200px]"></CardContent>- </Card>- }- >- <Await resolve={configurationParametersAndGroups}>- {(resolvedParametersAndGroups) => (- <ConfigurationParametersForm- key={`options:${itemId}`}- parameters={resolvedParametersAndGroups.parameters}- groups={resolvedParametersAndGroups.groups}- />- )}- </Await>- </Suspense>+ <ConfigurationParametersForm+ key={`options:${itemId}`}+ parameters={configurationParametersAndGroups.parameters}+ groups={configurationParametersAndGroups.groups}+ />)}<BillOfProcesskey={`bop:${itemId}`}+ configurable={partManufacturing.requiresConfiguration}makeMethodId={makeMethodId}// @ts-ignoreoperations={manufacturingRouteData?.methodOperations ?? []}+ parameters={configurationParametersAndGroups.parameters}/><BillOfMaterialkey={`bom:${itemId}`}+ configurable={partManufacturing.requiresConfiguration}makeMethodId={makeMethodId}// @ts-ignorematerials={manufacturingRouteData?.methodMaterials ?? []}// @ts-ignoreoperations={manufacturingRouteData?.methodOperations}+ parameters={configurationParametersAndGroups.parameters}/></VStack>);diff --git a/apps/carbon/package.json b/apps/carbon/package.jsonindex dde290c7cf..64b9af17f7 100644--- a/apps/carbon/package.json+++ b/apps/carbon/package.json@@ -16,6 +16,7 @@"@dnd-kit/sortable": "^8.0.0","@epic-web/remember": "^1.1.0","@internationalized/date": "^3.5.2",+ "@monaco-editor/react": "^4.6.0","@nanostores/react": "^0.7.1","@novu/headless": "^2.0.0","@novu/framework": "^2.3.0",diff --git a/package-lock.json b/package-lock.jsonindex 8bb1d207b5..360e90ff5d 100644--- a/package-lock.json+++ b/package-lock.json@@ -44,6 +44,7 @@"@dnd-kit/sortable": "^8.0.0","@epic-web/remember": "^1.1.0","@internationalized/date": "^3.5.2",+ "@monaco-editor/react": "^4.6.0","@nanostores/react": "^0.7.1","@novu/framework": "^2.3.0","@novu/headless": "^2.0.0",@@ -3306,6 +3307,30 @@"resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.15.0.tgz","integrity": "sha512-HZpPoABogPvjeJOdzCOSJsXeL/SMCBgBZMVC3X3d7YYp2gf31MfxhUoYUNwf1ERPJOnQc0wkFn9trqI6ZEdZuA=="},+ "node_modules/@monaco-editor/loader": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.4.0.tgz",+ "integrity": "sha512-00ioBig0x642hytVspPl7DbQyaSWRaolYie/UFNjoTdvoKPzo6xrXLhTk9ixgIKcLH5b5vDOjVNiGyY+uDCUlg==",+ "dependencies": {+ "state-local": "^1.0.6"+ },+ "peerDependencies": {+ "monaco-editor": ">= 0.21.0 < 1"+ }+ },+ "node_modules/@monaco-editor/react": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/@monaco-editor/react/-/react-4.6.0.tgz",+ "integrity": "sha512-RFkU9/i7cN2bsq/iTkurMWOEErmYcY6JiQI3Jn+WeR/FGISH8JbHERjpS9oRuSOPvDMJI0Z8nJeKkbOs9sBYQw==",+ "dependencies": {+ "@monaco-editor/loader": "^1.4.0"+ },+ "peerDependencies": {+ "monaco-editor": ">= 0.25.0 < 1",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0",+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"+ }+ },"node_modules/@nanostores/react": {"version": "0.7.3","resolved": "https://registry.npmjs.org/@nanostores/react/-/react-0.7.3.tgz",@@ -22809,6 +22834,12 @@"resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.3.tgz","integrity": "sha512-ySViT69/76t8VhE1xXHK6Ch4NcDd26gx0MzKXLO+F7NOtnqH68d9zF94nT8ZWSxXh8ELOERsnJO/sWt1xZYw5A=="},+ "node_modules/monaco-editor": {+ "version": "0.52.2",+ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.52.2.tgz",+ "integrity": "sha512-GEQWEZmfkOGLdd3XK8ryrfWz3AIP8YymVXiPHEdewrUq7mh0qrKrfHLNCXcbB6sTnMLnOZ3ztSiKcciFUkIJwQ==",+ "peer": true+ },"node_modules/morgan": {"version": "1.10.0","resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",@@ -28846,6 +28877,11 @@"resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz","integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A=="},+ "node_modules/state-local": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/state-local/-/state-local-1.0.7.tgz",+ "integrity": "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w=="+ },"node_modules/static-extend": {"version": "0.1.2","resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz",