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: crud for configuration rules

Brad Barbina8e22a2da60b
diff --git a/apps/carbon/app/components/Configurator/Configurator.tsx b/apps/carbon/app/components/Configurator/Configurator.tsx
index a660d4fa5e..abdb8b2f96 100644
--- a/apps/carbon/app/components/Configurator/Configurator.tsx
+++ b/apps/carbon/app/components/Configurator/Configurator.tsx
@@ -1,20 +1,34 @@
/* eslint-disable no-new-func */
-import { Button, Modal, ModalContent, ModalTitle } from "@carbon/react";
+import {
+ Badge,
+ Button,
+ HStack,
+ IconButton,
+ Modal,
+ ModalContent,
+ ModalTitle,
+ toast,
+ useDisclosure,
+} from "@carbon/react";
import type { OnMount } from "@monaco-editor/react";
import Editor from "@monaco-editor/react";
+import { useFetcher, useParams } from "@remix-run/react";
import type * as Monaco from "monaco-editor";
import { useCallback, useEffect, useMemo, useState } from "react";
-import { LuPlay, LuPower, LuSave } from "react-icons/lu";
+import { LuFunctionSquare, LuPlay, LuSave, LuTrash2 } from "react-icons/lu";
import { useMode } from "~/hooks/useMode";
+import type { action } from "~/routes/x+/part+/$itemId.rule";
+import { path } from "~/utils/path";
+import { ConfirmDelete } from "../Modals";
import ParameterPanel from "./ParameterPanel";
import type { Configuration, Parameter, ParameterInput } from "./types";
import { typeMap } from "./types";
import {
configureMonaco,
+ convertTypescriptToJavaScript,
generateDefaultCode,
generateTypeDefinitions,
getDefaultValue,
- stripTypeScript,
} from "./utils";
interface ConfiguratorProps {
@@ -22,7 +36,6 @@ interface ConfiguratorProps {
parameters: ParameterInput[];
open: boolean;
onClose: () => void;
- onSave: (code: string) => void;
}
export default function Configurator({
@@ -30,12 +43,14 @@ export default function Configurator({
open,
parameters: defaultParameters,
onClose,
- onSave,
}: ConfiguratorProps) {
const { code: defaultCode, defaultValue, label, returnType } = configuration;
+ const isActive = !!defaultCode;
const mode = useMode();
+
const [output, setOutput] = useState<string>("");
+ const [isScriptLoaded, setIsScriptLoaded] = useState(false);
const [parameters, setParameters] = useState<Parameter[]>(
defaultParameters.map((param) => ({
name: param.key,
@@ -143,6 +158,10 @@ export default function Configurator({
}
}, [parameters, monaco, editor, returnType]);
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+ const fetcher = useFetcher<typeof action>();
+
const getCodeToSave = () => {
const lines = code.split("\n");
const startLine = lockedLines;
@@ -165,15 +184,43 @@ export default function Configurator({
};
const handleSave = () => {
- const codeToSave = getCodeToSave();
- onSave(codeToSave);
+ const formData = new FormData();
+ formData.append("code", getCodeToSave());
+ formData.append("field", configuration.field);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.configurationRule(itemId),
+ });
};
+ useEffect(() => {
+ const head = document.querySelector("head")!;
+ const script = document.createElement("script");
+ script.setAttribute(
+ "src",
+ "https://unpkg.com/[email protected]/lib/typescript.js"
+ );
+ script.onload = () => setIsScriptLoaded(true);
+ head.appendChild(script);
+ return () => {
+ head.removeChild(script);
+ };
+ }, []);
+
+ useEffect(() => {
+ if (fetcher.data?.success === false) {
+ toast.error("Failed to save configuration rule");
+ }
+
+ if (fetcher.data?.success === true) {
+ onClose();
+ }
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.data]);
+
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] =
@@ -189,7 +236,7 @@ export default function Configurator({
const fn = new Function(
"parameters",
`
- ${codeStr}
+ ${convertTypescriptToJavaScript(code)}
return configure(parameters);
`
);
@@ -244,101 +291,111 @@ export default function Configurator({
}
}, [code, parameters, returnType]);
+ const deleteDialog = useDisclosure();
+
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 items-center justify-between p-6 pr-14">
- <ModalTitle>Configure {label}</ModalTitle>
- <ConfigurationToggle isActive={true} onChange={() => {}} />
- </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>
+ <>
+ <Modal
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <ModalContent size="xxxlarge" className="p-0 gap-0 h-[90dvh]">
+ <div className="flex items-center justify-between p-5 pr-14">
+ <ModalTitle>Configure {label}</ModalTitle>
+ <HStack>
+ <Badge variant={isActive ? "green" : "gray"}>
+ {isActive ? "Active" : "Inactive"}
+ <LuFunctionSquare className="ml-1" />
+ </Badge>
+ {isActive && (
+ <IconButton
+ icon={<LuTrash2 />}
+ variant="secondary"
+ size="sm"
+ onClick={deleteDialog.onOpen}
+ aria-label="Delete Rule"
+ />
+ )}
+ </HStack>
</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 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>
- </div>
- </ModalContent>
- </Modal>
- );
-}
-type ConfigurationToggleProps = {
- isActive: boolean;
- onChange: (active: boolean) => void;
-};
-
-function ConfigurationToggle({ isActive, onChange }: ConfigurationToggleProps) {
- return (
- <button
- onClick={() => onChange(!isActive)}
- className={`
- flex items-center gap-2 px-4 py-2 rounded-lg
- ${
- isActive
- ? "bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 hover:bg-green-200 dark:hover:bg-green-800"
- : "bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 hover:bg-red-200 dark:hover:bg-red-800"
- }
- `}
- >
- <LuPower className="w-4 h-4" />
- <span>{isActive ? "Active" : "Inactive"}</span>
- </button>
+ <div className="w-1/3 flex flex-col">
+ <ParameterPanel
+ parameters={parameters}
+ onChange={setParameters}
+ />
+ <div className="p-4 border-t space-y-2">
+ <Button
+ onClick={runCode}
+ className="w-full"
+ leftIcon={<LuPlay />}
+ variant="secondary"
+ isDisabled={!isScriptLoaded}
+ >
+ Run Test
+ </Button>
+ <Button
+ onClick={handleSave}
+ className="w-full"
+ leftIcon={<LuSave />}
+ variant="primary"
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Save & Close
+ </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>
+ {isActive && deleteDialog.isOpen && (
+ <ConfirmDelete
+ isOpen={deleteDialog.isOpen}
+ action={path.to.deleteConfigurationRule(itemId, configuration.field)}
+ name={label}
+ text={`Are you sure you want to deactivate the ${label} configuration rule?`}
+ onCancel={deleteDialog.onClose}
+ onSubmit={onClose}
+ />
+ )}
+ </>
);
}
diff --git a/apps/carbon/app/components/Configurator/Icons.tsx b/apps/carbon/app/components/Configurator/Icons.tsx
index de5a3599c5..aa2c78540a 100644
--- a/apps/carbon/app/components/Configurator/Icons.tsx
+++ b/apps/carbon/app/components/Configurator/Icons.tsx
@@ -1,11 +1,12 @@
import { cn } from "@carbon/react";
import { LuHash, LuList, LuToggleLeft, LuType } from "react-icons/lu";
+import type { ConfiguratorDataType } from "./types";
export function ConfiguratorDataTypeIcon({
type,
className,
}: {
- type: "numeric" | "text" | "boolean" | "list";
+ type: ConfiguratorDataType;
className?: string;
}) {
switch (type) {
@@ -17,6 +18,7 @@ export function ConfiguratorDataTypeIcon({
return (
<LuToggleLeft className={cn("w-4 h-4 text-purple-600", className)} />
);
+ case "enum":
case "list":
return <LuList className={cn("w-4 h-4 text-orange-600", className)} />;
default:
diff --git a/apps/carbon/app/components/Configurator/ParameterPanel.tsx b/apps/carbon/app/components/Configurator/ParameterPanel.tsx
index 2cf791544e..d7d003df0e 100644
--- a/apps/carbon/app/components/Configurator/ParameterPanel.tsx
+++ b/apps/carbon/app/components/Configurator/ParameterPanel.tsx
@@ -29,50 +29,52 @@ export default function ParameterPanel({
</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>
+ {parameters
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .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 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/types.ts b/apps/carbon/app/components/Configurator/types.ts
index 885b0b5ab4..5561700e11 100644
--- a/apps/carbon/app/components/Configurator/types.ts
+++ b/apps/carbon/app/components/Configurator/types.ts
@@ -1,6 +1,7 @@
export type Configuration = {
label: string;
code?: string;
+ field: string;
returnType: ReturnType;
defaultValue?: string | number | boolean | string[] | null;
};
diff --git a/apps/carbon/app/components/Configurator/utils.ts b/apps/carbon/app/components/Configurator/utils.ts
index b2fa8cb455..da1ea2b914 100644
--- a/apps/carbon/app/components/Configurator/utils.ts
+++ b/apps/carbon/app/components/Configurator/utils.ts
@@ -152,16 +152,16 @@ ${properties}
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();
+export function convertTypescriptToJavaScript(code: string): string {
+ // @ts-expect-error - TypeScript compiler is loaded globally
+ if (window?.ts) {
+ // @ts-expect-error - TypeScript compiler is loaded globally
+ return window.ts.transpileModule(code, {
+ compilerOptions: {
+ // @ts-expect-error - TypeScript compiler is loaded globally
+ target: window.ts.ScriptTarget.ES2020,
+ },
+ }).outputText;
+ }
+ return "";
}
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index d699a63937..76a652f672 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -125,6 +125,11 @@ export const configurationParameterValidator = z
{ message: "Key must be lowercase and underscore separated" }
);
+export const configurationRuleValidator = z.object({
+ field: z.string().min(1, { message: "Field is required" }),
+ code: z.string().min(1, { message: "Code is required" }),
+});
+
export const consumableValidator = itemValidator.merge(
z.object({
id: z.string().min(1, { message: "Consumable ID is required" }).max(255),
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index dac8e9bba6..eecbf56ba3 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -12,6 +12,7 @@ import type {
configurationParameterGroupValidator,
configurationParameterOrderValidator,
configurationParameterValidator,
+ configurationRuleValidator,
consumableValidator,
customerPartValidator,
getMethodValidator,
@@ -60,6 +61,18 @@ export async function deleteConfigurationParameter(
return client.from("configurationParameter").delete().eq("id", id);
}
+export async function deleteConfigurationRule(
+ client: SupabaseClient<Database>,
+ field: string,
+ itemId: string
+) {
+ return client
+ .from("configurationRule")
+ .delete()
+ .eq("field", field)
+ .eq("itemId", itemId);
+}
+
export async function deleteItemCustomerPart(
client: SupabaseClient<Database>,
id: string,
@@ -187,6 +200,23 @@ export async function getConfigurationParameters(
return { groups: groups.data ?? [], parameters: parameters.data ?? [] };
}
+export async function getConfigurationRules(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ const result = await client
+ .from("configurationRule")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId);
+ if (result.error) {
+ console.error(result.error);
+ return [];
+ }
+ return result.data ?? [];
+}
+
export async function getConsumable(
client: SupabaseClient<Database>,
itemId: string,
@@ -1232,6 +1262,19 @@ export async function upsertConfigurationParameterGroup(
});
}
+export async function upsertConfigurationRule(
+ client: SupabaseClient<Database>,
+ configurationRule: z.infer<typeof configurationRuleValidator> & {
+ itemId: string;
+ companyId: string;
+ updatedBy: string;
+ }
+) {
+ return client.from("configurationRule").upsert(configurationRule, {
+ onConflict: "itemId,field",
+ });
+}
+
export async function upsertConsumable(
client: SupabaseClient<Database>,
consumable:
diff --git a/apps/carbon/app/modules/items/types.ts b/apps/carbon/app/modules/items/types.ts
index 9fc4fcaa69..fc29446161 100644
--- a/apps/carbon/app/modules/items/types.ts
+++ b/apps/carbon/app/modules/items/types.ts
@@ -1,6 +1,7 @@
import type { Database } from "@carbon/database";
import type {
getConfigurationParameters,
+ getConfigurationRules,
getConsumable,
getConsumables,
getItemCost,
@@ -33,6 +34,10 @@ export type ConfigurationParameter = NonNullable<
Awaited<ReturnType<typeof getConfigurationParameters>>["parameters"]
>[number];
+export type ConfigurationRule = NonNullable<
+ Awaited<ReturnType<typeof getConfigurationRules>>
+>[number];
+
export type ConfigurationParameterGroup = NonNullable<
Awaited<ReturnType<typeof getConfigurationParameters>>["groups"]
>[number];
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
index 78bb411e1d..61113001d0 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -53,7 +53,7 @@ import {
import { path } from "~/utils/path";
import type { methodOperationValidator } from "../../items.models";
import { methodMaterialValidator } from "../../items.models";
-import type { ConfigurationParameter } from "../../types";
+import type { ConfigurationParameter, ConfigurationRule } from "../../types";
type Material = z.infer<typeof methodMaterialValidator> & {
description: string;
@@ -71,6 +71,7 @@ type BillOfMaterialProps = {
materials: Material[];
operations: Operation[];
parameters?: ConfigurationParameter[];
+ configurationRules?: ConfigurationRule[];
};
type OrderState = {
@@ -99,6 +100,7 @@ const initialMethodMaterial: Omit<Material, "makeMethodId" | "order"> & {
const BillOfMaterial = ({
configurable = false,
+ configurationRules,
makeMethodId,
materials: initialMaterials,
operations,
@@ -374,6 +376,7 @@ const BillOfMaterial = ({
item={item}
methodOperations={operations}
orderState={orderState}
+ rulesByField={rulesByField}
temporaryItems={temporaryItems}
onConfigure={onConfigure}
setOrderState={setOrderState}
@@ -405,6 +408,10 @@ const BillOfMaterial = ({
configuratorDisclosure.onOpen();
};
+ const rulesByField = new Map(
+ configurationRules?.map((rule) => [rule.field, rule]) ?? []
+ );
+
return (
<Card>
<HStack className="justify-between">
@@ -428,16 +435,26 @@ const BillOfMaterial = ({
icon={<LuFunctionSquare />}
aria-label="Configure"
variant="ghost"
- onClick={() => {
- onConfigure({
- label: "Bill of Material",
- code: undefined,
- returnType: {
- type: "list",
- listOptions: materials.map((m) => m.data.itemReadableId!),
- },
- });
- }}
+ className={cn(
+ rulesByField.has("billOfMaterial") &&
+ "text-emerald-500 hover:text-emerald-500"
+ )}
+ onClick={
+ configurable
+ ? () =>
+ onConfigure({
+ label: "Bill of Material",
+ field: "billOfMaterial",
+ code: rulesByField.get("billOfMaterial")?.code,
+ returnType: {
+ type: "list",
+ listOptions: materials.map(
+ (m) => m.data.itemReadableId!
+ ),
+ },
+ })
+ : undefined
+ }
/>
)}
</div>
@@ -458,7 +475,6 @@ const BillOfMaterial = ({
open={configuratorDisclosure.isOpen}
parameters={parameters ?? []}
onClose={configuratorDisclosure.onClose}
- onSave={() => {}}
/>
)}
</Card>
@@ -477,6 +493,7 @@ function MaterialForm({
methodOperations,
orderState,
temporaryItems,
+ rulesByField,
onConfigure,
setOrderState,
setSelectedItemId,
@@ -487,6 +504,7 @@ function MaterialForm({
methodOperations: Operation[];
orderState: OrderState;
temporaryItems: TemporaryItems;
+ rulesByField: Map<string, ConfigurationRule>;
setSelectedItemId: Dispatch<SetStateAction<string | null>>;
setTemporaryItems: Dispatch<SetStateAction<TemporaryItems>>;
setOrderState: Dispatch<SetStateAction<OrderState>>;
@@ -586,7 +604,7 @@ function MaterialForm({
}));
};
- console.log({ itemData });
+ const key = (field: string) => getFieldKey(field, item.id);
return (
<ValidatedForm
@@ -619,7 +637,7 @@ function MaterialForm({
includeInactive
type={itemType}
validItemTypes={["Consumable", "Material", "Part"]}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("itemId"))}
onChange={(value) => {
onItemChange(value?.value as string);
}}
@@ -628,7 +646,8 @@ function MaterialForm({
? () =>
onConfigure({
label: "Part",
- code: undefined,
+ field: key("itemId"),
+ code: rulesByField.get(key("itemId"))?.code,
defaultValue: itemData.itemId,
returnType: {
type: "text",
@@ -645,13 +664,14 @@ function MaterialForm({
label="Description"
isReadOnly
value={itemData.description}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("description"))}
onConfigure={
configurable
? () =>
onConfigure({
label: "Description",
- code: undefined,
+ field: key("description"),
+ code: rulesByField.get(key("description"))?.code,
defaultValue: itemData.description,
returnType: {
type: "text",
@@ -677,13 +697,14 @@ function MaterialForm({
name="methodType"
label="Method Type"
value={itemData.methodType}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("methodType"))}
onConfigure={
configurable
? () =>
onConfigure({
label: "Method Type",
- code: undefined,
+ field: key("methodType"),
+ code: rulesByField.get(key("methodType"))?.code,
defaultValue: itemData.methodType,
returnType: {
type: "enum",
@@ -697,13 +718,14 @@ function MaterialForm({
<Number
name="quantity"
label="Quantity"
- isConfigured={false}
+ isConfigured={rulesByField.has(key("quantity"))}
onConfigure={
configurable
? () =>
onConfigure({
label: "Quantity",
- code: undefined,
+ field: key("quantity"),
+ code: rulesByField.get(key("quantity"))?.code,
defaultValue: itemData.quantity,
returnType: { type: "numeric" },
})
@@ -719,13 +741,14 @@ function MaterialForm({
unitOfMeasureCode: newValue?.value ?? "EA",
}))
}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("unitOfMeasureCode"))}
onConfigure={
configurable
? () =>
onConfigure({
label: "Unit of Measure",
- code: undefined,
+ field: key("unitOfMeasureCode"),
+ code: rulesByField.get(key("unitOfMeasureCode"))?.code,
defaultValue: itemData.unitOfMeasureCode,
returnType: {
type: "enum",
@@ -809,6 +832,10 @@ function makeItem(
};
}
+function getFieldKey(field: string, materialId: string) {
+ return `${field}:${materialId}`;
+}
+
const usePendingMaterials = () => {
type PendingItem = ReturnType<typeof useFetchers>[number] & {
formData: FormData;
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 00331315f0..099ed17067 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -82,7 +82,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";
+import type { ConfigurationParameter, ConfigurationRule } from "../../types";
type Operation = z.infer<typeof methodOperationValidator> & {
workInstruction: JSONContent | null;
@@ -98,6 +98,7 @@ type ItemWithData = Item & {
type BillOfProcessProps = {
configurable?: boolean;
+ configurationRules?: ConfigurationRule[];
makeMethodId: string;
operations: OperationWithTools[];
parameters?: ConfigurationParameter[];
@@ -136,11 +137,11 @@ const initialOperation: Omit<Operation, "makeMethodId" | "order" | "tools"> = {
const BillOfProcess = ({
configurable = false,
+ configurationRules,
makeMethodId,
operations: initialOperations,
parameters,
}: BillOfProcessProps) => {
- console.log({ configurable });
const permissions = usePermissions();
const { carbon } = useCarbon();
const sortOrderFetcher = useFetcher<{}>();
@@ -388,6 +389,7 @@ const BillOfProcess = ({
<OperationForm
configurable={configurable}
item={item}
+ rulesByField={rulesByField}
workInstruction={workInstructions[item.id] ?? {}}
onConfigure={onConfigure}
setSelectedItemId={setSelectedItemId}
@@ -573,6 +575,10 @@ const BillOfProcess = ({
configuratorDisclosure.onOpen();
};
+ const rulesByField = new Map(
+ configurationRules?.map((rule) => [rule.field, rule]) ?? []
+ );
+
return (
<Card>
<HStack className="justify-between">
@@ -596,12 +602,17 @@ const BillOfProcess = ({
icon={<LuFunctionSquare />}
aria-label="Configure"
variant="ghost"
+ className={cn(
+ rulesByField.has("billOfProcess") &&
+ "text-emerald-500 hover:text-emerald-500"
+ )}
onClick={
configurable
? () =>
onConfigure({
label: "Bill of Process",
- code: undefined,
+ field: "billOfProcess",
+ code: rulesByField.get("billOfProcess")?.code,
returnType: {
type: "list",
listOptions: operations.map((op) => op.description),
@@ -629,7 +640,6 @@ const BillOfProcess = ({
open={configuratorDisclosure.isOpen}
parameters={parameters ?? []}
onClose={configuratorDisclosure.onClose}
- onSave={() => {}}
/>
)}
</Card>
@@ -645,6 +655,7 @@ function isTemporaryId(id: string) {
type OperationFormProps = {
configurable: boolean;
item: ItemWithData;
+ rulesByField: Map<string, ConfigurationRule>;
workInstruction: JSONContent;
onConfigure: (configuration: Configuration) => void;
setSelectedItemId: Dispatch<SetStateAction<string | null>>;
@@ -655,9 +666,10 @@ type OperationFormProps = {
function OperationForm({
configurable,
item,
- setSelectedItemId,
+ rulesByField,
workInstruction,
onConfigure,
+ setSelectedItemId,
setWorkInstructions,
setTemporaryItems,
}: OperationFormProps) {
@@ -783,6 +795,8 @@ function OperationForm({
}));
};
+ const key = (field: string) => getFieldKey(field, item.id);
+
return (
<ValidatedForm
action={
@@ -808,13 +822,14 @@ function OperationForm({
<Process
name="processId"
label="Process"
- isConfigured={false}
+ isConfigured={rulesByField.has(key("processId"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Process",
- code: undefined,
+ field: key("processId"),
+ code: rulesByField.get(key("processId"))?.code,
defaultValue: processData.processId,
returnType: {
type: "text",
@@ -874,13 +889,14 @@ function OperationForm({
operationType: value?.value as string,
}));
}}
- isConfigured
+ isConfigured={rulesByField.has(key("operationType"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Operation Type",
- code: undefined,
+ field: key("operationType"),
+ code: rulesByField.get(key("operationType"))?.code,
defaultValue: processData.operationType,
returnType: {
type: "enum",
@@ -900,13 +916,14 @@ function OperationForm({
setProcessData((d) => ({ ...d, description: newValue }));
}}
className="col-span-2"
- isConfigured={false}
+ isConfigured={rulesByField.has(key("description"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Description",
- code: undefined,
+ field: key("description"),
+ code: rulesByField.get(key("description"))?.code,
defaultValue: processData.description,
returnType: {
type: "text",
@@ -931,13 +948,14 @@ function OperationForm({
operationOrder: value?.value as string,
}));
}}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("operationOrder"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Operation Order",
- code: undefined,
+ field: key("operationOrder"),
+ code: rulesByField.get(key("operationOrder"))?.code,
defaultValue: processData.operationOrder,
returnType: {
type: "enum",
@@ -999,13 +1017,14 @@ function OperationForm({
hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
}));
}}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("setupUnitHint"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Setup Unit",
- code: undefined,
+ field: key("setupUnitHint"),
+ code: rulesByField.get(key("setupUnitHint"))?.code,
defaultValue: processData.setupUnitHint,
returnType: {
type: "enum",
@@ -1027,13 +1046,14 @@ function OperationForm({
setupTime: newValue,
}))
}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("setupTime"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Setup Time",
- code: undefined,
+ field: key("setupTime"),
+ code: rulesByField.get(key("setupTime"))?.code,
defaultValue: processData.setupTime,
returnType: {
type: "numeric",
@@ -1054,13 +1074,14 @@ function OperationForm({
setupUnit: newValue?.value ?? "Total Minutes",
}));
}}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("setupUnit"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Setup Unit",
- code: undefined,
+ field: key("setupUnit"),
+ code: rulesByField.get(key("setupUnit"))?.code,
defaultValue: processData.setupUnit,
returnType: {
type: "enum",
@@ -1122,13 +1143,14 @@ function OperationForm({
hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
}));
}}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("laborUnitHint"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Labor Unit",
- code: undefined,
+ field: key("laborUnitHint"),
+ code: rulesByField.get(key("laborUnitHint"))?.code,
defaultValue: processData.laborUnitHint,
returnType: {
type: "enum",
@@ -1150,13 +1172,14 @@ function OperationForm({
laborTime: newValue,
}))
}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("laborTime"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Labor Time",
- code: undefined,
+ field: key("laborTime"),
+ code: rulesByField.get(key("laborTime"))?.code,
defaultValue: processData.laborTime,
returnType: {
type: "numeric",
@@ -1177,13 +1200,14 @@ function OperationForm({
laborUnit: newValue?.value ?? "Total Minutes",
}));
}}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("laborUnit"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Labor Unit",
- code: undefined,
+ field: key("laborUnit"),
+ code: rulesByField.get(key("laborUnit"))?.code,
defaultValue: processData.laborUnit,
returnType: {
type: "enum",
@@ -1246,13 +1270,14 @@ function OperationForm({
hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
}));
}}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("machineUnitHint"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Machine Unit",
- code: undefined,
+ field: key("machineUnitHint"),
+ code: rulesByField.get(key("machineUnitHint"))?.code,
defaultValue: processData.machineUnitHint,
returnType: {
type: "enum",
@@ -1274,13 +1299,14 @@ function OperationForm({
machineTime: newValue,
}))
}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("machineTime"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Machine Time",
- code: undefined,
+ field: key("machineTime"),
+ code: rulesByField.get(key("machineTime"))?.code,
defaultValue: processData.machineTime,
returnType: {
type: "numeric",
@@ -1301,13 +1327,14 @@ function OperationForm({
machineUnit: newValue?.value ?? "Total Minutes",
}));
}}
- isConfigured={false}
+ isConfigured={rulesByField.has(key("machineUnit"))}
onConfigure={
configurable
? () => {
onConfigure({
label: "Machine Unit",
- code: undefined,
+ field: key("machineUnit"),
+ code: rulesByField.get(key("machineUnit"))?.code,
defaultValue: processData.machineUnit,
returnType: {
type: "enum",
@@ -1620,3 +1647,7 @@ function usePendingOperations() {
return acc;
}, []);
}
+
+function getFieldKey(field: string, operationId: string) {
+ return `${field}:${operationId}`;
+}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
index fa292339e9..9a8dea2f8e 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx
@@ -10,6 +10,7 @@ import { useRouteData } from "~/hooks";
import type { MakeMethod, Material, MethodOperation } from "~/modules/items";
import {
getConfigurationParameters,
+ getConfigurationRules,
getItemManufacturing,
partManufacturingValidator,
upsertItemManufacturing,
@@ -54,6 +55,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.requiresConfiguration
? await getConfigurationParameters(client, itemId, companyId)
: { groups: [], parameters: [] },
+ configurationRules: partManufacturing.data.requiresConfiguration
+ ? await getConfigurationRules(client, itemId, companyId)
+ : [],
});
}
@@ -101,8 +105,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function MakeMethodRoute() {
- const { partManufacturing, configurationParametersAndGroups } =
- useLoaderData<typeof loader>();
+ const {
+ partManufacturing,
+ configurationParametersAndGroups,
+ configurationRules,
+ } = useLoaderData<typeof loader>();
const { itemId } = useParams();
if (!itemId) throw new Error("Could not find itemId");
@@ -143,6 +150,7 @@ export default function MakeMethodRoute() {
// @ts-ignore
operations={manufacturingRouteData?.methodOperations ?? []}
parameters={configurationParametersAndGroups.parameters}
+ configurationRules={configurationRules}
/>
<BillOfMaterial
key={`bom:${itemId}`}
@@ -153,6 +161,7 @@ export default function MakeMethodRoute() {
// @ts-ignore
operations={manufacturingRouteData?.methodOperations}
parameters={configurationParametersAndGroups.parameters}
+ configurationRules={configurationRules}
/>
</VStack>
);
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.rule.delete.$field.tsx b/apps/carbon/app/routes/x+/part+/$itemId.rule.delete.$field.tsx
new file mode 100644
index 0000000000..1e82174ef8
--- /dev/null
+++ b/apps/carbon/app/routes/x+/part+/$itemId.rule.delete.$field.tsx
@@ -0,0 +1,28 @@
+import { assertIsPost, notFound } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { deleteConfigurationRule } from "~/modules/items";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "parts",
+ });
+
+ const { itemId, field } = params;
+ if (!itemId || !field) throw notFound("itemId or field not found");
+
+ const remove = await deleteConfigurationRule(client, field, itemId);
+
+ if (remove.error) {
+ return json({
+ success: false,
+ error: "Failed to delete configuration rule",
+ });
+ }
+
+ return json({
+ success: true,
+ });
+}
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.rule.tsx b/apps/carbon/app/routes/x+/part+/$itemId.rule.tsx
new file mode 100644
index 0000000000..61e225691f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/part+/$itemId.rule.tsx
@@ -0,0 +1,49 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import {
+ configurationRuleValidator,
+ upsertConfigurationRule,
+} from "~/modules/items";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(configurationRuleValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return json({
+ success: false,
+ error: "Invalid form data",
+ });
+ }
+
+ const upsert = await upsertConfigurationRule(client, {
+ ...validation.data,
+ itemId,
+ companyId,
+ updatedBy: userId,
+ });
+
+ if (upsert.error) {
+ console.error(upsert.error);
+ return json({
+ success: false,
+ error: upsert.error.message,
+ });
+ }
+
+ return json({
+ success: true,
+ });
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 511605605c..e883c39d39 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -148,6 +148,8 @@ export const path = {
generatePath(`${x}/part/${itemId}/parameter/group/order`),
configurationParameterOrder: (itemId: string) =>
generatePath(`${x}/part/${itemId}/parameter/order`),
+ configurationRule: (itemId: string) =>
+ generatePath(`${x}/part/${itemId}/rule`),
contractor: (id: string) =>
generatePath(`${x}/resources/contractors/${id}`),
contractors: `${x}/resources/contractors`,
@@ -234,6 +236,8 @@ export const path = {
generatePath(`${x}/part/${itemId}/parameter/delete/${id}`),
deleteConfigurationParameterGroup: (itemId: string, id: string) =>
generatePath(`${x}/part/${itemId}/parameter/group/delete/${id}`),
+ deleteConfigurationRule: (itemId: string, field: string) =>
+ generatePath(`${x}/part/${itemId}/rule/delete/${field}`),
deleteContractor: (id: string) =>
generatePath(`${x}/resources/contractors/delete/${id}`),
deleteCurrency: (id: string) =>
diff --git a/package-lock.json b/package-lock.json
index 360e90ff5d..007228f227 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -150,6 +150,7 @@
}
},
"apps/developers": {
+ "extraneous": true,
"dependencies": {
"@carbon/auth": "*",
"@carbon/database": "*",
@@ -265,7 +266,7 @@
"wait-on": "7.2.0"
}
},
- "apps/www": {
+ "apps/starter": {
"dependencies": {
"@carbon/auth": "*",
"@carbon/database": "*",
@@ -320,16 +321,60 @@
"wait-on": "7.2.0"
}
},
- "apps/www/node_modules/tailwind-scrollbar": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/tailwind-scrollbar/-/tailwind-scrollbar-3.1.0.tgz",
- "integrity": "sha512-pmrtDIZeHyu2idTejfV59SbaJyvp1VRjYxAjZBH0jnyrPRo6HL1kD5Glz8VPagasqr6oAx6M05+Tuw429Z8jxg==",
- "dev": true,
- "engines": {
- "node": ">=12.13.0"
+ "apps/www": {
+ "extraneous": true,
+ "dependencies": {
+ "@carbon/auth": "*",
+ "@carbon/database": "*",
+ "@carbon/documents": "*",
+ "@carbon/form": "*",
+ "@carbon/kv": "*",
+ "@carbon/logger": "*",
+ "@carbon/react": "*",
+ "@carbon/utils": "*",
+ "@react-aria/i18n": "^3.11.0",
+ "@remix-run/dev": "~2.11.2",
+ "@remix-run/eslint-config": "~2.11.2",
+ "@remix-run/react": "~2.11.2",
+ "@remix-run/serve": "~2.11.2",
+ "@supabase/functions-js": "2.1.5",
+ "@supabase/supabase-js": "^2.40.0",
+ "@tailwindcss/container-queries": "^0.1.1",
+ "@tailwindcss/forms": "^0.5.7",
+ "@tailwindcss/line-clamp": "^0.4.4",
+ "@tailwindcss/typography": "^0.5.10",
+ "@vercel/analytics": "^1.2.2",
+ "@vercel/remix": "2.11.2",
+ "framer-motion": "^11.1.7",
+ "isbot": "3.6.13",
+ "non.geist": "~1.0.3",
+ "react": "^18.3.1",
+ "react-dom": "^18.3.1",
+ "react-dropzone": "^14.2.3",
+ "react-hotkeys-hook": "~4.5.0",
+ "react-icons": "^5.3.0",
+ "tailwind-merge": "^2.2.1",
+ "tailwindcss-animate": "^1.0.7",
+ "zod": "^3.23.8",
+ "zod-form-data": "*"
},
- "peerDependencies": {
- "tailwindcss": "3.x"
+ "devDependencies": {
+ "@carbon/tailwind": "*",
+ "@carbon/tsconfig": "*",
+ "@types/react": "^18.2.74",
+ "@types/react-dom": "^18.2.24",
+ "autoprefixer": "10.4.14",
+ "cross-env": "7.0.3",
+ "nodemon": "^3.0.1",
+ "npm-run-all": "^4.1.5",
+ "postcss": "^8.4.33",
+ "tailwind-scrollbar": "^2.0.1",
+ "tailwind-scrollbar-hide": "^1.1.7",
+ "tailwindcss": "3.4.6",
+ "typescript": "^5.2.2",
+ "vite": "^5.3.3",
+ "vite-tsconfig-paths": "^4.3.2",
+ "wait-on": "7.2.0"
}
},
"ci": {
@@ -14635,10 +14680,6 @@
"resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz",
"integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="
},
- "node_modules/developers": {
- "resolved": "apps/developers",
- "link": true
- },
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
@@ -28877,6 +28918,10 @@
"resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz",
"integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A=="
},
+ "node_modules/starter": {
+ "resolved": "apps/starter",
+ "link": true
+ },
"node_modules/state-local": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/state-local/-/state-local-1.0.7.tgz",
@@ -32656,10 +32701,6 @@
}
}
},
- "node_modules/www": {
- "resolved": "apps/www",
- "link": true
- },
"node_modules/xdg-basedir": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-5.1.0.tgz",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 3687f6002c..883c023fef 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2175,6 +2175,104 @@ export type Database = {
},
]
}
+ configurationRule: {
+ Row: {
+ code: string
+ companyId: string
+ field: string
+ itemId: string
+ updatedAt: string
+ updatedBy: string | null
+ }
+ Insert: {
+ code: string
+ companyId: string
+ field: string
+ itemId: string
+ updatedAt?: string
+ updatedBy?: string | null
+ }
+ Update: {
+ code?: string
+ companyId?: string
+ field?: string
+ itemId?: string
+ updatedAt?: string
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "configurationRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "configurationRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "configurationRule_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
consumable: {
Row: {
approved: boolean
@@ -27004,14 +27102,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -28217,14 +28315,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 3687f6002c..883c023fef 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2175,6 +2175,104 @@ export type Database = {
},
]
}
+ configurationRule: {
+ Row: {
+ code: string
+ companyId: string
+ field: string
+ itemId: string
+ updatedAt: string
+ updatedBy: string | null
+ }
+ Insert: {
+ code: string
+ companyId: string
+ field: string
+ itemId: string
+ updatedAt?: string
+ updatedBy?: string | null
+ }
+ Update: {
+ code?: string
+ companyId?: string
+ field?: string
+ itemId?: string
+ updatedAt?: string
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "configurationRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "configurationRule_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "configurationRule_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "configurationRule_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
consumable: {
Row: {
approved: boolean
@@ -27004,14 +27102,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -28217,14 +28315,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/migrations/20241224174410_save-configuration.sql b/packages/database/supabase/migrations/20241224174410_save-configuration.sql
index 6af2149742..f1de18acef 100644
--- a/packages/database/supabase/migrations/20241224174410_save-configuration.sql
+++ b/packages/database/supabase/migrations/20241224174410_save-configuration.sql
@@ -32,20 +32,16 @@ FOR ALL USING (
);
CREATE TABLE "configurationRule" (
- "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
"itemId" TEXT NOT NULL,
"field" TEXT NOT NULL,
"code" TEXT NOT NULL,
"companyId" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
- "createdBy" TEXT NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updatedBy" TEXT,
- CONSTRAINT "configurationRule_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "configurationRule_pkey" PRIMARY KEY ("itemId", "field"),
CONSTRAINT "configurationRule_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
CONSTRAINT "configurationRule_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
- CONSTRAINT "configurationRule_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE,
CONSTRAINT "configurationRule_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE
);