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: update id of material when properties change

Brad Barbin2084c7043166
diff --git a/apps/erp/app/components/Form/MaterialType.tsx b/apps/erp/app/components/Form/MaterialType.tsx
index 45f763e4f4..6e72e392ac 100644
--- a/apps/erp/app/components/Form/MaterialType.tsx
+++ b/apps/erp/app/components/Form/MaterialType.tsx
@@ -1,9 +1,6 @@
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo, useRef, useState } from "react";
-import type {
- MaterialType as MaterialTypeType,
- getMaterialTypeList,
-} from "~/modules/items";
+import type { getMaterialTypeList } from "~/modules/items";
import { path } from "~/utils/path";
import type { ComboboxProps } from "@carbon/form";
@@ -18,7 +15,13 @@ type MaterialTypeSelectProps = Omit<
substanceId?: string;
formId?: string;
inline?: boolean;
- onChange?: (materialType: MaterialTypeType | null) => void;
+ onChange?: (
+ materialType: {
+ label: string;
+ value: string;
+ code: string;
+ } | null
+ ) => void;
};
const MaterialTypePreview = (
@@ -31,45 +34,18 @@ const MaterialTypePreview = (
};
const MaterialType = (props: MaterialTypeSelectProps) => {
- const materialTypesLoader =
- useFetcher<Awaited<ReturnType<typeof getMaterialTypeList>>>();
-
const newTypeModal = useDisclosure();
const [created, setCreated] = useState<string>("");
const triggerRef = useRef<HTMLButtonElement>(null);
- useMount(() => {
- if (props.substanceId && props.formId) {
- materialTypesLoader.load(
- path.to.api.materialTypes(props.substanceId, props.formId)
- );
- }
- });
-
- useEffect(() => {
- if (props.substanceId && props.formId) {
- materialTypesLoader.load(
- path.to.api.materialTypes(props.substanceId, props.formId)
- );
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [props.substanceId, props.formId]);
-
- const options = useMemo(() => {
- return (materialTypesLoader.data?.data ?? []).map((c) => ({
- value: c.id,
- label: c.name,
- helper: c.companyId === null ? "Standard" : undefined,
- }));
- }, [materialTypesLoader.data?.data]);
+ const options = useMaterialTypes(props.substanceId!, props.formId!);
const onChange = (newValue: { label: string; value: string } | null) => {
const materialType =
- materialTypesLoader.data?.data?.find(
- (materialType) => materialType.id === newValue?.value
- ) ?? null;
+ options.find((materialType) => materialType.value === newValue?.value) ??
+ null;
- props.onChange?.(materialType as MaterialTypeType | null);
+ props.onChange?.(materialType);
};
return (
@@ -100,6 +76,7 @@ const MaterialType = (props: MaterialTypeSelectProps) => {
name: created,
materialSubstanceId: props.substanceId!,
materialFormId: props.formId!,
+ code: created,
}}
/>
)}
@@ -107,4 +84,33 @@ const MaterialType = (props: MaterialTypeSelectProps) => {
);
};
-export default MaterialType;
\ No newline at end of file
+export const useMaterialTypes = (substanceId?: string, formId?: string) => {
+ const materialTypes =
+ useFetcher<Awaited<ReturnType<typeof getMaterialTypeList>>>();
+
+ useMount(() => {
+ if (substanceId && formId) {
+ materialTypes.load(path.to.api.materialTypes(substanceId, formId));
+ }
+ });
+
+ useEffect(() => {
+ if (substanceId && formId) {
+ materialTypes.load(path.to.api.materialTypes(substanceId, formId));
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [substanceId, formId]);
+
+ const options = useMemo(() => {
+ return (materialTypes.data?.data ?? []).map((c) => ({
+ value: c.id,
+ label: c.name,
+ helper: c.companyId === null ? "Standard" : undefined,
+ code: c.code,
+ }));
+ }, [materialTypes.data?.data]);
+
+ return options;
+};
+
+export default MaterialType;
diff --git a/apps/erp/app/components/Form/Shape.tsx b/apps/erp/app/components/Form/Shape.tsx
index ec864bb98e..ea6215dfa2 100644
--- a/apps/erp/app/components/Form/Shape.tsx
+++ b/apps/erp/app/components/Form/Shape.tsx
@@ -53,6 +53,7 @@ const Shape = (props: ShapeSelectProps) => {
}}
initialValues={{
name: created,
+ code: created.slice(0, 3).toUpperCase(),
}}
/>
)}
@@ -84,6 +85,7 @@ export const useShape = () => {
value: c.id,
label: c.name,
helper: c.companyId === null ? "Standard" : undefined,
+ code: c.code,
}));
}, [materialFormsLoader.data?.data]);
diff --git a/apps/erp/app/components/Form/Substance.tsx b/apps/erp/app/components/Form/Substance.tsx
index 90a010c916..f6df2cd421 100644
--- a/apps/erp/app/components/Form/Substance.tsx
+++ b/apps/erp/app/components/Form/Substance.tsx
@@ -53,6 +53,7 @@ const Substance = (props: SubstanceSelectProps) => {
}}
initialValues={{
name: created,
+ code: created.slice(0, 3).toUpperCase(),
}}
/>
)}
@@ -84,6 +85,7 @@ export const useSubstance = () => {
value: c.id,
label: c.name,
helper: c.companyId === null ? "Standard" : undefined,
+ code: c.code,
}));
}, [materialSubstances.data?.data]);
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index 52b9de511d..413302ce28 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -438,6 +438,7 @@ export const materialFinishValidator = z.object({
export const materialFormValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }).max(255),
+ code: z.string().min(1, { message: "Code is required" }).max(10),
});
export const materialGradeValidator = z.object({
@@ -449,6 +450,7 @@ export const materialGradeValidator = z.object({
export const materialSubstanceValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }).max(255),
+ code: z.string().min(1, { message: "Code is required" }).max(10),
});
export const materialTypeValidator = z.object({
@@ -456,6 +458,7 @@ export const materialTypeValidator = z.object({
materialSubstanceId: z.string().min(1, { message: "Substance is required" }),
materialFormId: z.string().min(1, { message: "Shape is required" }),
name: z.string().min(1, { message: "Name is required" }).max(255),
+ code: z.string().min(1, { message: "Code is required" }).max(10),
});
export const partValidator = itemValidator.merge(
diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.ts
deleted file mode 100644
index 97c7e8ecb7..0000000000
--- a/apps/erp/app/modules/items/items.server.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import type { Database } from "@carbon/database";
-import { redis } from "@carbon/kv";
-import type { SupabaseClient } from "@supabase/supabase-js";
-import { sanitize } from "~/utils/supabase";
-
-export function getMetricSettingsKey(companyId: string) {
- return `metric:${companyId}`;
-}
-
-export async function getMetricSettings(
- client: SupabaseClient<Database>,
- companyId: string
-) {
- const key = getMetricSettingsKey(companyId);
-
- // Try to get from cache first
- try {
- const cached = await redis.get(key);
- if (cached !== null) {
- return cached === "true" || cached === true;
- }
- } catch (error) {
- // If cache fails, continue to database
- }
-
- // Fetch from database if not in cache
- const { data } = await client
- .from("companySettings")
- .select("useMetric")
- .eq("id", companyId)
- .single();
-
- const useMetric = data?.useMetric ?? false;
-
- // Store in cache for future use
- try {
- await redis.set(key, useMetric.toString());
- } catch (error) {
- // Log cache write error but don't fail the request
- }
-
- return useMetric;
-}
-
-export async function setMetricSettings(
- client: SupabaseClient<Database>,
- companyId: string,
- useMetric: boolean
-) {
- const result = await client
- .from("companySettings")
- .update(sanitize({ useMetric }))
- .eq("id", companyId);
-
- // Update cache if database update was successful
- if (!result.error) {
- const key = getMetricSettingsKey(companyId);
- try {
- await redis.set(key, useMetric.toString());
- } catch (error) {
- // Log cache write error but don't fail the request
- }
- }
-
- return result;
-}
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 7c46aacf21..fafbf9dd88 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -952,7 +952,7 @@ export async function getMaterialFormsList(
) {
return client
.from("materialForm")
- .select("id, name, companyId")
+ .select("id, name, code, companyId")
.or(`companyId.eq.${companyId},companyId.is.null`)
.order("name");
}
@@ -1040,7 +1040,7 @@ export async function getMaterialSubstancesList(
) {
return client
.from("materialSubstance")
- .select("id, name, companyId")
+ .select("id, name, code, companyId")
.or(`companyId.eq.${companyId},companyId.is.null`)
.order("name");
}
diff --git a/apps/erp/app/modules/items/ui/Item/RevisionForm.tsx b/apps/erp/app/modules/items/ui/Item/RevisionForm.tsx
index 2090ed1377..b04700d852 100644
--- a/apps/erp/app/modules/items/ui/Item/RevisionForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/RevisionForm.tsx
@@ -22,12 +22,14 @@ import { revisionValidator } from "../../items.models";
type RevisionFormProps = {
initialValues: z.infer<typeof revisionValidator>;
+ hasSizesInsteadOfRevisions?: boolean;
open?: boolean;
onClose: (data?: { id: string; name: string }) => void;
};
const RevisionForm = ({
initialValues,
+ hasSizesInsteadOfRevisions = false,
open = true,
onClose,
}: RevisionFormProps) => {
@@ -76,12 +78,14 @@ const RevisionForm = ({
>
<ModalDrawerHeader>
<ModalDrawerTitle>
- {isEditing ? "Edit" : "New"} Revision
+ {isEditing ? "Edit" : "New"}{" "}
+ {hasSizesInsteadOfRevisions ? "Size" : "Revision"}
</ModalDrawerTitle>
{!isEditing && (
<ModalDrawerDescription>
- A new revision will be created using a copy of the current
- revision
+ A new {hasSizesInsteadOfRevisions ? "size" : "revision"} will
+ be created using a copy of the current
+ {hasSizesInsteadOfRevisions ? "size" : "revision"}
</ModalDrawerDescription>
)}
</ModalDrawerHeader>
@@ -93,8 +97,12 @@ const RevisionForm = ({
<VStack spacing={4}>
<Input
name="revision"
- label="Revision"
- helperText="The revision number of the part"
+ label={hasSizesInsteadOfRevisions ? "Size" : "Revision"}
+ helperText={
+ hasSizesInsteadOfRevisions
+ ? "The size of the part"
+ : "The revision number of the part"
+ }
/>
</VStack>
</ModalDrawerBody>
diff --git a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
index 3485e5c663..49ed8958cb 100644
--- a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
+++ b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
@@ -93,11 +93,13 @@ export function UsedInTree({
revisions: revisionsJson,
itemReadableId,
itemReadableIdWithRevision,
+ hasSizesInsteadOfRevisions = false,
}: {
tree: UsedInNode[];
revisions?: Json;
itemReadableId: string;
itemReadableIdWithRevision: string;
+ hasSizesInsteadOfRevisions?: boolean;
}) {
const [filterText, setFilterText] = useState("");
@@ -137,11 +139,12 @@ export function UsedInTree({
filterText={filterText}
node={{
key: (revisions?.[0]?.type as UsedInKey) ?? "Part",
- name: "Revisions",
+ name: hasSizesInsteadOfRevisions ? "Sizes" : "Revisions",
module: "parts",
children: revisions,
}}
maxRevision={revisions?.[0]?.revision ?? ""}
+ hasSizesInsteadOfRevisions={hasSizesInsteadOfRevisions}
/>
{tree.map((node) => (
<UsedInItem
@@ -160,10 +163,12 @@ export function RevisionsItem({
node,
filterText,
maxRevision,
+ hasSizesInsteadOfRevisions = false,
}: {
node: UsedInNode;
filterText: string;
maxRevision: string;
+ hasSizesInsteadOfRevisions?: boolean;
}) {
const { itemId } = useParams();
const permissions = usePermissions();
@@ -219,7 +224,9 @@ export function RevisionsItem({
setSelectedRevision({
copyFromId: itemId,
type: node.key as "Part",
- revision: getNextRevision(maxRevision),
+ revision: hasSizesInsteadOfRevisions
+ ? ""
+ : getNextRevision(maxRevision),
});
revisionDisclosure.onOpen();
});
@@ -295,7 +302,8 @@ export function RevisionsItem({
}}
>
<DropdownMenuIcon icon={<LuStar />} />
- Set as Default Revision
+ Set as Default{" "}
+ {hasSizesInsteadOfRevisions ? "Size" : "Revision"}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -311,14 +319,19 @@ export function RevisionsItem({
<RevisionForm
initialValues={selectedRevision!}
onClose={revisionDisclosure.onClose}
+ hasSizesInsteadOfRevisions={hasSizesInsteadOfRevisions}
/>
)}
{defaultDisclosure.isOpen && selectedRevision && (
<Confirm
action={path.to.defaultRevision(selectedRevision.id!)}
- confirmText="Make Default"
- title={`Make revision ${selectedRevision.revision} default?`}
- text="This will replace all method materials of other revisions with this revision."
+ confirmText={`Make Default`}
+ title={`Make ${hasSizesInsteadOfRevisions ? "size" : "revision"} ${
+ selectedRevision.revision
+ } default?`}
+ text={`This will replace all method materials of other ${
+ hasSizesInsteadOfRevisions ? "sizes" : "revisions"
+ } with this ${hasSizesInsteadOfRevisions ? "size" : "revision"}.`}
isOpen
onSubmit={() => {
defaultDisclosure.onClose();
diff --git a/apps/erp/app/modules/items/ui/MaterialForms/MaterialShapeForm.tsx b/apps/erp/app/modules/items/ui/MaterialForms/MaterialShapeForm.tsx
index 9cae1b7375..27bd899e20 100644
--- a/apps/erp/app/modules/items/ui/MaterialForms/MaterialShapeForm.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialForms/MaterialShapeForm.tsx
@@ -14,9 +14,9 @@ import {
} from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import type { z } from "zod";
-import { CustomFormFields, Hidden, Input, Submit } from "~/components/Form";
+import { CustomFormFields, Hidden, Input, InputControlled, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
import { materialFormValidator } from "../../items.models";
@@ -36,6 +36,7 @@ const MaterialShapeForm = ({
}: MaterialShapeFormProps) => {
const permissions = usePermissions();
const fetcher = useFetcher<PostgrestResponse<{ id: string; name: string }>>();
+ const [code, setCode] = useState<string>(initialValues.code);
const isEditing = initialValues.id !== undefined;
const isDisabled = isEditing
@@ -86,6 +87,15 @@ const MaterialShapeForm = ({
<Hidden name="type" value={type} />
<VStack spacing={4}>
<Input name="name" label="Name" />
+ <InputControlled
+ name="code"
+ label="Code"
+ value={code}
+ onChange={(value) =>
+ setCode(value.toUpperCase().replace(/\s/g, ""))
+ }
+ helperText="Unique, uppercase, without spaces"
+ />
<CustomFormFields table="materialForm" />
</VStack>
</ModalDrawerBody>
diff --git a/apps/erp/app/modules/items/ui/MaterialForms/MaterialShapesTable.tsx b/apps/erp/app/modules/items/ui/MaterialForms/MaterialShapesTable.tsx
index cf6d40c90e..cd6e1ee981 100644
--- a/apps/erp/app/modules/items/ui/MaterialForms/MaterialShapesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialForms/MaterialShapesTable.tsx
@@ -2,7 +2,13 @@ import { Badge, MenuIcon, MenuItem } from "@carbon/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
-import { LuBookMarked, LuCircleCheck, LuPencil, LuTrash } from "react-icons/lu";
+import {
+ LuBookMarked,
+ LuCircleCheck,
+ LuCode,
+ LuPencil,
+ LuTrash,
+} from "react-icons/lu";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions, useUrlParams } from "~/hooks";
@@ -45,6 +51,14 @@ const MaterialShapesTable = memo(
icon: <LuBookMarked />,
},
},
+ {
+ accessorKey: "code",
+ header: "Code",
+ cell: ({ row }) => row.original.code,
+ meta: {
+ icon: <LuCode />,
+ },
+ },
{
accessorKey: "companyId",
header: "Standard",
diff --git a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceForm.tsx b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceForm.tsx
index 650201af22..58c95fd39e 100644
--- a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceForm.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceForm.tsx
@@ -14,9 +14,9 @@ import {
} from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import type { z } from "zod";
-import { CustomFormFields, Hidden, Input, Submit } from "~/components/Form";
+import { CustomFormFields, Hidden, Input, InputControlled, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
import { materialSubstanceValidator } from "../../items.models";
@@ -36,6 +36,7 @@ const MaterialSubstanceForm = ({
}: MaterialSubstanceFormProps) => {
const permissions = usePermissions();
const fetcher = useFetcher<PostgrestResponse<{ id: string; name: string }>>();
+ const [code, setCode] = useState<string>(initialValues.code);
const isEditing = initialValues.id !== undefined;
const isDisabled = isEditing
@@ -86,6 +87,15 @@ const MaterialSubstanceForm = ({
<Hidden name="type" value={type} />
<VStack spacing={4}>
<Input name="name" label="Name" />
+ <InputControlled
+ name="code"
+ label="Code"
+ value={code}
+ onChange={(value) =>
+ setCode(value.toUpperCase().replace(/\s/g, ""))
+ }
+ helperText="Unique, uppercase, without spaces"
+ />
<CustomFormFields table="materialSubstance" />
</VStack>
</ModalDrawerBody>
diff --git a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
index 068ca6050d..1d5463e63e 100644
--- a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
@@ -2,7 +2,13 @@ import { Badge, MenuIcon, MenuItem } from "@carbon/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
-import { LuBookMarked, LuCircleCheck, LuPencil, LuTrash } from "react-icons/lu";
+import {
+ LuBookMarked,
+ LuCircleCheck,
+ LuCode,
+ LuPencil,
+ LuTrash,
+} from "react-icons/lu";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions, useUrlParams } from "~/hooks";
@@ -45,6 +51,14 @@ const MaterialSubstancesTable = memo(
icon: <LuBookMarked />,
},
},
+ {
+ accessorKey: "code",
+ header: "Code",
+ cell: ({ row }) => row.original.code,
+ meta: {
+ icon: <LuCode />,
+ },
+ },
{
accessorKey: "companyId",
header: "Standard",
diff --git a/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypeForm.tsx b/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypeForm.tsx
index ba85df55f7..b9db180baf 100644
--- a/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypeForm.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypeForm.tsx
@@ -14,9 +14,9 @@ import {
} from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import type { z } from "zod";
-import { Hidden, Input, Submit } from "~/components/Form";
+import { Hidden, Input, InputControlled, Submit } from "~/components/Form";
import Shape from "~/components/Form/Shape";
import Substance from "~/components/Form/Substance";
import { usePermissions } from "~/hooks";
@@ -38,6 +38,7 @@ const MaterialTypeForm = ({
}: MaterialTypeFormProps) => {
const permissions = usePermissions();
const fetcher = useFetcher<PostgrestResponse<{ id: string; name: string }>>();
+ const [code, setCode] = useState<string>(initialValues.code);
const isEditing = initialValues.id !== undefined;
const isDisabled = isEditing
@@ -90,6 +91,15 @@ const MaterialTypeForm = ({
<Substance name="materialSubstanceId" label="Substance" />
<Shape name="materialFormId" label="Shape" />
<Input name="name" label="Name" />
+ <InputControlled
+ name="code"
+ label="Code"
+ value={code}
+ onChange={(value) =>
+ setCode(value.toUpperCase().replace(/\s/g, ""))
+ }
+ helperText="Unique, uppercase, without spaces"
+ />
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
index 244bafba5b..c46dd62314 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
@@ -13,7 +13,7 @@ import {
} from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useCallback, useEffect, useState } from "react";
+import { useEffect, useState } from "react";
import type { z } from "zod";
import { TrackingTypeIcon } from "~/components";
import {
@@ -28,11 +28,12 @@ import {
import MaterialDimension from "~/components/Form/MaterialDimension";
import MaterialFinish from "~/components/Form/MaterialFinish";
import MaterialGrade from "~/components/Form/MaterialGrade";
-import MaterialType from "~/components/Form/MaterialType";
-import Shape from "~/components/Form/Shape";
-import Substance from "~/components/Form/Substance";
+import MaterialType, { useMaterialTypes } from "~/components/Form/MaterialType";
+import Shape, { useShape } from "~/components/Form/Shape";
+import Substance, { useSubstance } from "~/components/Form/Substance";
import { useNextItemId, usePermissions, useUser } from "~/hooks";
import { useSettings } from "~/hooks/useSettings";
+import { getMaterialDescription, getMaterialId } from "~/utils/items";
import { path } from "~/utils/path";
import {
itemTrackingTypes,
@@ -58,8 +59,6 @@ const MaterialForm = ({
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode;
- const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
-
const [materialId, setMaterialId] = useState(initialValues.id ?? "");
const [description, setDescription] = useState(
initialValues.description ?? ""
@@ -67,49 +66,27 @@ const MaterialForm = ({
const [properties, setProperties] = useState<{
substance?: string;
+ substanceCode?: string;
shape?: string;
+ shapeCode?: string;
grade?: string;
dimensions?: string;
finish?: string;
materialType?: string;
+ materialTypeCode?: string;
}>({});
const [substanceId, setSubstanceId] = useState<string | undefined>();
const [formId, setFormId] = useState<string | undefined>();
- // const getMaterialFamily = useCallback(() => {
- // const base = [
- // properties.substance,
- // properties.grade,
- // properties.shape,
- // properties.finish,
- // ]
- // .filter((p) => !!p)
- // .join(" ");
-
- // return base.toUpperCase();
- // }, [properties]);
-
- const getDescription = useCallback(() => {
- const base = [
- properties.materialType,
- properties.substance,
- properties.grade,
- properties.shape,
- properties.dimensions,
- properties.finish,
- ]
- .filter((p) => !!p)
- .join(" ");
-
- return base;
- }, [properties]);
+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
+ const materialTypes = useMaterialTypes(substanceId, formId);
+ const substance = useSubstance();
+ const shape = useShape();
useEffect(() => {
- // const materialFamily = getMaterialFamily();
- const d = getDescription();
- setDescription(d);
- setMaterialId(d.toUpperCase());
- }, [getDescription]);
+ setMaterialId(getMaterialId(properties));
+ setDescription(getMaterialDescription(properties));
+ }, [properties]);
useEffect(() => {
if (type !== "modal") return;
@@ -215,6 +192,9 @@ const MaterialForm = ({
setProperties((prev) => ({
...prev,
substance: (value?.label as string) ?? "",
+ substanceCode:
+ substance.find((s) => s.value === value?.value)?.code ??
+ "",
}));
}}
/>
@@ -237,6 +217,8 @@ const MaterialForm = ({
setProperties((prev) => ({
...prev,
shape: (value?.label as string) ?? "",
+ shapeCode:
+ shape.find((s) => s.value === value?.value)?.code ?? "",
}));
}}
/>
@@ -246,9 +228,13 @@ const MaterialForm = ({
substanceId={substanceId}
formId={formId}
onChange={(value) => {
+ const code = materialTypes.find(
+ (m) => m.value === value?.value
+ )?.code;
setProperties((prev) => ({
...prev,
- materialType: value?.name ?? "",
+ materialType: value?.label ?? "",
+ materialTypeCode: code,
}));
}}
/>
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx
index 71fbdebcd7..f2d98b4a86 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx
@@ -1,6 +1,8 @@
import type { Json } from "@carbon/database";
import { InputControlled, ValidatedForm } from "@carbon/form";
import {
+ Alert,
+ AlertTitle,
Badge,
Button,
DropdownMenu,
@@ -9,16 +11,23 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
HStack,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
Tooltip,
TooltipContent,
TooltipTrigger,
VStack,
cn,
toast,
+ useDisclosure,
} from "@carbon/react";
import { Await, useFetcher, useParams } from "@remix-run/react";
import { Suspense, useCallback, useEffect, useState } from "react";
-import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";
+import { LuCopy, LuKeySquare, LuLink, LuTriangleAlert } from "react-icons/lu";
import { z } from "zod";
import { zfd } from "zod-form-data";
import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/components";
@@ -32,6 +41,7 @@ import Shape from "~/components/Form/Shape";
import Substance from "~/components/Form/Substance";
import { ItemThumbnailUpload } from "~/components/ItemThumnailUpload";
import { useRouteData } from "~/hooks";
+import { useSettings } from "~/hooks/useSettings";
import { methodType } from "~/modules/shared";
import type { action } from "~/routes/x+/items+/update";
import { useSuppliers } from "~/stores";
@@ -85,6 +95,20 @@ const MaterialProperties = () => {
}
}, [fetcher.data]);
+ const confirmDisclosure = useDisclosure();
+ const [materialPropertyUpdate, setMaterialPropertyUpdate] = useState<{
+ field:
+ | "materialFormId"
+ | "materialSubstanceId"
+ | "gradeId"
+ | "dimensionId"
+ | "finishId"
+ | "materialTypeId";
+ value: string | null;
+ } | null>(null);
+
+ const settings = useSettings();
+
const onUpdate = useCallback(
(
field:
@@ -116,6 +140,51 @@ const MaterialProperties = () => {
[itemId]
);
+ const handleUpdate = useCallback(
+ (
+ field:
+ | "name"
+ | "replenishmentSystem"
+ | "defaultMethodType"
+ | "itemTrackingType"
+ | "active"
+ | "unitOfMeasureCode"
+ | "materialFormId"
+ | "materialSubstanceId"
+ | "gradeId"
+ | "dimensionId"
+ | "finishId"
+ | "materialTypeId",
+ value: string | null
+ ) => {
+ console.log(settings.materialGeneratedIds);
+ console.log(field);
+ if (
+ settings.materialGeneratedIds &&
+ [
+ "materialSubstanceId",
+ "materialFormId",
+ "dimensionId",
+ "finishId",
+ "materialTypeId",
+ "gradeId",
+ ].includes(field)
+ ) {
+ console.log("ok");
+ setMaterialPropertyUpdate({
+ // @ts-ignore
+ field,
+ value,
+ });
+ confirmDisclosure.onOpen();
+ return;
+ }
+
+ onUpdate(field, value);
+ },
+ [confirmDisclosure, onUpdate, settings.materialGeneratedIds]
+ );
+
const onUpdateTags = useCallback(
(value: string[]) => {
const formData = new FormData();
@@ -165,106 +234,107 @@ const MaterialProperties = () => {
}, [routeData?.materialSummary]);
return (
- <VStack
- spacing={4}
- className="w-96 bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border px-4 py-2 text-sm"
- >
- <VStack spacing={2}>
- <HStack className="w-full justify-between">
- <h3 className="text-xs text-muted-foreground">Properties</h3>
- <HStack spacing={1}>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- aria-label="Link"
- size="sm"
- className="p-1"
- onClick={() =>
- copyToClipboard(
- window.location.origin + path.to.material(itemId)
- )
- }
- >
- <LuLink className="w-3 h-3" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <span>Copy link to material</span>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- aria-label="Copy"
- size="sm"
- className="p-1"
- onClick={() =>
- copyToClipboard(routeData?.materialSummary?.id ?? "")
- }
- >
- <LuKeySquare className="w-3 h-3" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <span>Copy material unique identifier</span>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- aria-label="Copy"
- size="sm"
- className="p-1"
- onClick={() =>
- copyToClipboard(routeData?.materialSummary?.id ?? "")
- }
- >
- <LuCopy className="w-3 h-3" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <span>Copy material number</span>
- </TooltipContent>
- </Tooltip>
+ <>
+ <VStack
+ spacing={4}
+ className="w-96 bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border px-4 py-2 text-sm"
+ >
+ <VStack spacing={2}>
+ <HStack className="w-full justify-between">
+ <h3 className="text-xs text-muted-foreground">Properties</h3>
+ <HStack spacing={1}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label="Link"
+ size="sm"
+ className="p-1"
+ onClick={() =>
+ copyToClipboard(
+ window.location.origin + path.to.material(itemId)
+ )
+ }
+ >
+ <LuLink className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>Copy link to material</span>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label="Copy"
+ size="sm"
+ className="p-1"
+ onClick={() =>
+ copyToClipboard(routeData?.materialSummary?.id ?? "")
+ }
+ >
+ <LuKeySquare className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>Copy material unique identifier</span>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label="Copy"
+ size="sm"
+ className="p-1"
+ onClick={() =>
+ copyToClipboard(routeData?.materialSummary?.id ?? "")
+ }
+ >
+ <LuCopy className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>Copy material number</span>
+ </TooltipContent>
+ </Tooltip>
+ </HStack>
</HStack>
- </HStack>
- <VStack spacing={0}>
- <span className="text-sm tracking-tight">
- {routeData?.materialSummary?.readableIdWithRevision}
- </span>
- <ValidatedForm
- defaultValues={{
- name: routeData?.materialSummary?.name ?? undefined,
- }}
- validator={z.object({
- name: z.string(),
- })}
- className="w-full -mt-2"
- >
- <span className="text-xs text-muted-foreground">
- <InputControlled
- label=""
- name="name"
- inline
- size="sm"
- value={routeData?.materialSummary?.name ?? ""}
- onBlur={(e) => {
- onUpdate("name", e.target.value ?? null);
- }}
- className="text-muted-foreground"
- />
+ <VStack spacing={0}>
+ <span className="text-sm tracking-tight">
+ {routeData?.materialSummary?.readableIdWithRevision}
</span>
- </ValidatedForm>
+ <ValidatedForm
+ defaultValues={{
+ name: routeData?.materialSummary?.name ?? undefined,
+ }}
+ validator={z.object({
+ name: z.string(),
+ })}
+ className="w-full -mt-2"
+ >
+ <span className="text-xs text-muted-foreground">
+ <InputControlled
+ label=""
+ name="name"
+ inline
+ size="sm"
+ value={routeData?.materialSummary?.name ?? ""}
+ onBlur={(e) => {
+ onUpdate("name", e.target.value ?? null);
+ }}
+ className="text-muted-foreground"
+ />
+ </span>
+ </ValidatedForm>
+ </VStack>
+ <ItemThumbnailUpload
+ path={routeData?.materialSummary?.thumbnailPath}
+ itemId={itemId}
+ />
</VStack>
- <ItemThumbnailUpload
- path={routeData?.materialSummary?.thumbnailPath}
- itemId={itemId}
- />
- </VStack>
- {/* <VStack spacing={2}>
+ {/* <VStack spacing={2}>
<h3 className="text-xs text-muted-foreground">Assignee</h3>
<Assignee
id={itemId}
@@ -274,310 +344,405 @@ const MaterialProperties = () => {
/>
</VStack> */}
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">Tracking Type</h3>
- <DropdownMenu>
- <DropdownMenuTrigger>
- <Badge variant="secondary">
- <TrackingTypeIcon
- type={routeData?.materialSummary?.itemTrackingType!}
- className={cn(
- "mr-2",
- routeData?.materialSummary?.active === false && "opacity-50"
- )}
- />
- <span>{routeData?.materialSummary?.itemTrackingType!}</span>
- </Badge>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- {itemTrackingTypes.map((type) => (
- <DropdownMenuItem
- key={type}
- onClick={() => onUpdate("itemTrackingType", type)}
- >
- <DropdownMenuIcon icon={<TrackingTypeIcon type={type} />} />
- <span>{type}</span>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- </VStack>
-
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">Default Method Type</h3>
- <DropdownMenu>
- <DropdownMenuTrigger>
- <Badge variant="secondary">
- <MethodIcon
- type={routeData?.materialSummary?.defaultMethodType!}
- className={cn(
- "mr-2",
- routeData?.materialSummary?.active === false && "opacity-50"
- )}
- />
- <span>{routeData?.materialSummary?.defaultMethodType!}</span>
- </Badge>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- {methodType
- .filter((type) => type !== "Make")
- .map((type) => (
+ <VStack spacing={2}>
+ <h3 className="text-xs text-muted-foreground">Tracking Type</h3>
+ <DropdownMenu>
+ <DropdownMenuTrigger>
+ <Badge variant="secondary">
+ <TrackingTypeIcon
+ type={routeData?.materialSummary?.itemTrackingType!}
+ className={cn(
+ "mr-2",
+ routeData?.materialSummary?.active === false && "opacity-50"
+ )}
+ />
+ <span>{routeData?.materialSummary?.itemTrackingType!}</span>
+ </Badge>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {itemTrackingTypes.map((type) => (
<DropdownMenuItem
key={type}
- onClick={() => onUpdate("defaultMethodType", type)}
+ onClick={() => onUpdate("itemTrackingType", type)}
>
- <DropdownMenuIcon icon={<MethodIcon type={type} />} />
+ <DropdownMenuIcon icon={<TrackingTypeIcon type={type} />} />
<span>{type}</span>
</DropdownMenuItem>
))}
- </DropdownMenuContent>
- </DropdownMenu>
- </VStack>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </VStack>
- <ValidatedForm
- defaultValues={{
- materialFormId:
- routeData?.materialSummary?.materialFormId ?? undefined,
- }}
- validator={z.object({
- materialFormId: z.string().nullable(),
- })}
- className="w-full"
- >
- <Shape
- label="Shape"
- name="materialFormId"
- inline
- onChange={(value) => {
- setFormId(value?.value as string | undefined);
- onUpdate("materialFormId", value?.value ?? null);
- }}
- />
- </ValidatedForm>
-
- <ValidatedForm
- defaultValues={{
- materialSubstanceId:
- routeData?.materialSummary?.materialSubstanceId ?? undefined,
- }}
- validator={z.object({
- materialSubstanceId: z.string().nullable(),
- })}
- className="w-full"
- >
- <Substance
- label="Substance"
- name="materialSubstanceId"
- inline
- onChange={(value) => {
- setSubstanceId(value?.value as string | undefined);
- onUpdate("materialSubstanceId", value?.value ?? null);
+ <VStack spacing={2}>
+ <h3 className="text-xs text-muted-foreground">Default Method Type</h3>
+ <DropdownMenu>
+ <DropdownMenuTrigger>
+ <Badge variant="secondary">
+ <MethodIcon
+ type={routeData?.materialSummary?.defaultMethodType!}
+ className={cn(
+ "mr-2",
+ routeData?.materialSummary?.active === false && "opacity-50"
+ )}
+ />
+ <span>{routeData?.materialSummary?.defaultMethodType!}</span>
+ </Badge>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {methodType
+ .filter((type) => type !== "Make")
+ .map((type) => (
+ <DropdownMenuItem
+ key={type}
+ onClick={() => onUpdate("defaultMethodType", type)}
+ >
+ <DropdownMenuIcon icon={<MethodIcon type={type} />} />
+ <span>{type}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </VStack>
+
+ <ValidatedForm
+ defaultValues={{
+ materialFormId:
+ routeData?.materialSummary?.materialFormId ?? undefined,
}}
- />
- </ValidatedForm>
-
- <ValidatedForm
- defaultValues={{
- gradeId: routeData?.materialSummary?.gradeId ?? undefined,
- }}
- validator={z.object({
- gradeId: zfd.text(z.string().optional()),
- })}
- className="w-full"
- >
- <MaterialGrade
- label="Grade"
- name="gradeId"
- substanceId={substanceId}
- inline
- onChange={(value) => {
- onUpdate("gradeId", value?.id ?? null);
+ validator={z.object({
+ materialFormId: z.string().nullable(),
+ })}
+ className="w-full"
+ >
+ <Shape
+ label="Shape"
+ name="materialFormId"
+ inline
+ onChange={(value) => {
+ handleUpdate("materialFormId", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ materialSubstanceId:
+ routeData?.materialSummary?.materialSubstanceId ?? undefined,
}}
- />
- </ValidatedForm>
-
- <ValidatedForm
- defaultValues={{
- dimensionId: routeData?.materialSummary?.dimensionId ?? undefined,
- }}
- validator={z.object({
- dimensionId: zfd.text(z.string().optional()),
- })}
- className="w-full"
- >
- <MaterialDimension
- label="Dimensions"
- name="dimensionId"
- formId={formId}
- inline
- onChange={(value) => {
- onUpdate("dimensionId", value?.id ?? null);
+ validator={z.object({
+ materialSubstanceId: z.string().nullable(),
+ })}
+ className="w-full"
+ >
+ <Substance
+ label="Substance"
+ name="materialSubstanceId"
+ inline
+ onChange={(value) => {
+ handleUpdate("materialSubstanceId", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ gradeId: routeData?.materialSummary?.gradeId ?? undefined,
}}
- />
- </ValidatedForm>
-
- <ValidatedForm
- defaultValues={{
- finishId: routeData?.materialSummary?.finishId ?? undefined,
- }}
- validator={z.object({
- finishId: zfd.text(z.string().optional()),
- })}
- className="w-full"
- >
- <MaterialFinish
- label="Finish"
- name="finishId"
- substanceId={substanceId}
- inline
- onChange={(value) => {
- onUpdate("finishId", value?.id ?? null);
+ validator={z.object({
+ gradeId: zfd.text(z.string().optional()),
+ })}
+ className="w-full"
+ >
+ <MaterialGrade
+ label="Grade"
+ name="gradeId"
+ substanceId={substanceId}
+ inline
+ onChange={(value) => {
+ handleUpdate("gradeId", value?.id ?? null);
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ dimensionId: routeData?.materialSummary?.dimensionId ?? undefined,
}}
- />
- </ValidatedForm>
+ validator={z.object({
+ dimensionId: zfd.text(z.string().optional()),
+ })}
+ className="w-full"
+ >
+ <MaterialDimension
+ label="Dimensions"
+ name="dimensionId"
+ formId={formId}
+ inline
+ onChange={(value) => {
+ handleUpdate("dimensionId", value?.id ?? null);
+ }}
+ />
+ </ValidatedForm>
- {substanceId && formId && (
<ValidatedForm
defaultValues={{
- materialTypeId:
- routeData?.materialSummary?.materialTypeId ?? undefined,
+ finishId: routeData?.materialSummary?.finishId ?? undefined,
}}
validator={z.object({
- materialTypeId: zfd.text(z.string().optional()),
+ finishId: zfd.text(z.string().optional()),
})}
className="w-full"
>
- <MaterialType
- label="Type"
- name="materialTypeId"
+ <MaterialFinish
+ label="Finish"
+ name="finishId"
substanceId={substanceId}
- formId={formId}
inline
onChange={(value) => {
- onUpdate("materialTypeId", value?.id ?? null);
+ handleUpdate("finishId", value?.id ?? null);
}}
/>
</ValidatedForm>
- )}
- <ValidatedForm
- defaultValues={{
- unitOfMeasureCode:
- routeData?.materialSummary?.unitOfMeasureCode ?? undefined,
- }}
- validator={z.object({
- unitOfMeasureCode: z
- .string()
- .min(1, { message: "Unit of Measure is required" }),
- })}
- className="w-full"
- >
- <UnitOfMeasure
- label="Unit of Measure"
- name="unitOfMeasureCode"
- inline
- onChange={(value) => {
- onUpdate("unitOfMeasureCode", value?.value ?? null);
+ {substanceId && formId && (
+ <ValidatedForm
+ defaultValues={{
+ materialTypeId:
+ routeData?.materialSummary?.materialTypeId ?? undefined,
+ }}
+ validator={z.object({
+ materialTypeId: zfd.text(z.string().optional()),
+ })}
+ className="w-full"
+ >
+ <MaterialType
+ label="Type"
+ name="materialTypeId"
+ substanceId={substanceId}
+ formId={formId}
+ inline
+ onChange={(value) => {
+ handleUpdate("materialTypeId", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+ )}
+
+ <ValidatedForm
+ defaultValues={{
+ unitOfMeasureCode:
+ routeData?.materialSummary?.unitOfMeasureCode ?? undefined,
}}
- />
- </ValidatedForm>
+ validator={z.object({
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of Measure is required" }),
+ })}
+ className="w-full"
+ >
+ <UnitOfMeasure
+ label="Unit of Measure"
+ name="unitOfMeasureCode"
+ inline
+ onChange={(value) => {
+ onUpdate("unitOfMeasureCode", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
- <VStack spacing={2}>
- <HStack className="w-full justify-between">
- <h3 className="text-xs text-muted-foreground">Methods</h3>
- </HStack>
+ <VStack spacing={2}>
+ <HStack className="w-full justify-between">
+ <h3 className="text-xs text-muted-foreground">Methods</h3>
+ </HStack>
- {routeData?.materialSummary?.replenishmentSystem?.includes("Buy") &&
- supplierParts.map((method) => (
+ {routeData?.materialSummary?.replenishmentSystem?.includes("Buy") &&
+ supplierParts.map((method) => (
+ <MethodBadge
+ key={method.id}
+ type="Buy"
+ text={
+ suppliers.find((s) => s.id === method.supplierId)?.name ?? ""
+ }
+ to={path.to.partPurchasing(itemId)}
+ />
+ ))}
+ {pickMethods.map((method) => (
<MethodBadge
- key={method.id}
- type="Buy"
+ key={method.locationId}
+ type="Pick"
text={
- suppliers.find((s) => s.id === method.supplierId)?.name ?? ""
+ locations.find((l) => l.id === method.locationId)?.name ?? ""
}
- to={path.to.partPurchasing(itemId)}
+ to={path.to.partInventoryLocation(itemId, method.locationId)}
/>
))}
- {pickMethods.map((method) => (
- <MethodBadge
- key={method.locationId}
- type="Pick"
- text={locations.find((l) => l.id === method.locationId)?.name ?? ""}
- to={path.to.partInventoryLocation(itemId, method.locationId)}
+ </VStack>
+ <ValidatedForm
+ defaultValues={{
+ active: routeData?.materialSummary?.active ?? undefined,
+ }}
+ validator={z.object({
+ active: zfd.checkbox(),
+ })}
+ className="w-full"
+ >
+ <Boolean
+ label="Active"
+ name="active"
+ variant="small"
+ onChange={(value) => {
+ onUpdate("active", value ? "on" : "off");
+ }}
/>
- ))}
- </VStack>
- <ValidatedForm
- defaultValues={{
- active: routeData?.materialSummary?.active ?? undefined,
- }}
- validator={z.object({
- active: zfd.checkbox(),
- })}
- className="w-full"
- >
- <Boolean
- label="Active"
- name="active"
- variant="small"
- onChange={(value) => {
- onUpdate("active", value ? "on" : "off");
+ </ValidatedForm>
+ <ValidatedForm
+ defaultValues={{
+ tags: routeData?.materialSummary?.tags ?? [],
}}
- />
- </ValidatedForm>
- <ValidatedForm
- defaultValues={{
- tags: routeData?.materialSummary?.tags ?? [],
- }}
- validator={z.object({
- tags: z.array(z.string()).optional(),
- })}
- className="w-full"
- >
- <Tags
- label="Tags"
- name="tags"
- availableTags={routeData?.tags ?? []}
+ validator={z.object({
+ tags: z.array(z.string()).optional(),
+ })}
+ className="w-full"
+ >
+ <Tags
+ label="Tags"
+ name="tags"
+ availableTags={routeData?.tags ?? []}
+ table="material"
+ inline
+ onChange={onUpdateTags}
+ />
+ </ValidatedForm>
+
+ <CustomFormInlineFields
+ customFields={
+ (routeData?.materialSummary?.customFields ?? {}) as Record<
+ string,
+ Json
+ >
+ }
table="material"
- inline
- onChange={onUpdateTags}
+ tags={routeData?.materialSummary?.tags ?? []}
+ onUpdate={onUpdateCustomFields}
/>
- </ValidatedForm>
- <CustomFormInlineFields
- customFields={
- (routeData?.materialSummary?.customFields ?? {}) as Record<
- string,
- Json
- >
- }
- table="material"
- tags={routeData?.materialSummary?.tags ?? []}
- onUpdate={onUpdateCustomFields}
- />
-
- <VStack spacing={2}>
- <HStack className="w-full justify-between">
- <h3 className="text-xs text-muted-foreground">Files</h3>
- </HStack>
-
- <Suspense fallback={null}>
- <Await resolve={routeData?.files}>
- {(files) =>
- files?.map((file) => (
- <FileBadge
- key={file.id}
- file={file}
- itemId={itemId}
- itemType="Material"
- />
- ))
- }
- </Await>
- </Suspense>
+ <VStack spacing={2}>
+ <HStack className="w-full justify-between">
+ <h3 className="text-xs text-muted-foreground">Files</h3>
+ </HStack>
+
+ <Suspense fallback={null}>
+ <Await resolve={routeData?.files}>
+ {(files) =>
+ files?.map((file) => (
+ <FileBadge
+ key={file.id}
+ file={file}
+ itemId={itemId}
+ itemType="Material"
+ />
+ ))
+ }
+ </Await>
+ </Suspense>
+ </VStack>
</VStack>
- </VStack>
+ {confirmDisclosure.isOpen && (
+ <ConfirmMaterialIdChange
+ materialPropertyUpdate={materialPropertyUpdate}
+ onClose={() => {
+ // this is hacky but the value is already changed in the UI
+ window.location.reload();
+ }}
+ onConfirm={() => {
+ onUpdate(
+ // @ts-ignore
+ materialPropertyUpdate?.field,
+ materialPropertyUpdate?.value
+ );
+ confirmDisclosure.onClose();
+ setMaterialPropertyUpdate(null);
+ }}
+ />
+ )}
+ </>
);
};
export default MaterialProperties;
+
+function ConfirmMaterialIdChange({
+ materialPropertyUpdate,
+ onClose,
+ onConfirm,
+}: {
+ materialPropertyUpdate: {
+ field:
+ | "materialFormId"
+ | "materialSubstanceId"
+ | "gradeId"
+ | "dimensionId"
+ | "finishId"
+ | "materialTypeId";
+ value: string | null;
+ } | null;
+ onClose: () => void;
+ onConfirm: () => void;
+}) {
+ const propertyName = getPropertyName(materialPropertyUpdate?.field ?? "");
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Confirm ID Change</ModalTitle>
+ </ModalHeader>
+ <ModalBody className="space-y-4">
+ <Alert variant="destructive">
+ <LuTriangleAlert className="h-4 w-4" />
+ <AlertTitle>Changing this will update the part ID</AlertTitle>
+ </Alert>
+ <p className="text-sm text-muted-foreground">
+ Are you sure you want to change the {propertyName} property? Since
+ you use generated material IDs this will change the part ID of this
+ part, and all related revisions.
+ </p>
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button variant="destructive" onClick={onConfirm}>
+ Yes, Update IDs
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+}
+
+function getPropertyName(field?: string) {
+ switch (field) {
+ case "materialFormId":
+ return "shape";
+ case "materialSubstanceId":
+ return "substance";
+ case "gradeId":
+ return "grade";
+ case "dimensionId":
+ return "dimensions";
+ case "finishId":
+ return "finish";
+ case "materialTypeId":
+ return "type";
+ default:
+ return field;
+ }
+}
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 85a110ccb4..8d36ff57d6 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -431,6 +431,17 @@ export async function updateCompany(
return client.from("company").update(sanitize(company)).eq("id", companyId);
}
+export async function updateMetricSettings(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ useMetric: boolean
+) {
+ return client
+ .from("companySettings")
+ .update(sanitize({ useMetric }))
+ .eq("id", companyId);
+}
+
export async function upsertApiKey(
client: SupabaseClient<Database>,
apiKey:
diff --git a/apps/erp/app/routes/api+/items.dimensions.$formId.ts b/apps/erp/app/routes/api+/items.dimensions.$formId.ts
index b830afc406..28097f081e 100644
--- a/apps/erp/app/routes/api+/items.dimensions.$formId.ts
+++ b/apps/erp/app/routes/api+/items.dimensions.$formId.ts
@@ -2,7 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
import { getMaterialDimensionList } from "~/modules/items";
-import { getMetricSettings } from "~/modules/items/items.server";
+import { getCompanySettings } from "~/modules/settings";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
@@ -14,7 +14,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return json({ error: "Form ID is required" }, { status: 400 });
}
- const isMetric = await getMetricSettings(client, companyId);
+ const settings = await getCompanySettings(client, companyId);
- return json(await getMaterialDimensionList(client, params.formId, isMetric, companyId));
+ return json(
+ await getMaterialDimensionList(
+ client,
+ params.formId,
+ settings?.data?.useMetric ?? false,
+ companyId
+ )
+ );
}
diff --git a/apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts b/apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts
index 9df500bea4..0bd52e98fc 100644
--- a/apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts
+++ b/apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts
@@ -1,7 +1,9 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import type { LoaderFunctionArgs } from "@vercel/remix";
+import type { ClientLoaderFunctionArgs } from "@remix-run/react";
+import type { LoaderFunctionArgs, SerializeFrom } from "@vercel/remix";
import { json } from "@vercel/remix";
import { getMaterialTypeList } from "~/modules/items";
+import { getCompanyId, materialTypesQuery } from "~/utils/react-query";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
@@ -25,3 +27,33 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
)
);
}
+
+export async function clientLoader({
+ params,
+ serverLoader,
+}: ClientLoaderFunctionArgs) {
+ const companyId = getCompanyId();
+
+ if (!companyId || !params.substanceId || !params.formId) {
+ return await serverLoader<typeof loader>();
+ }
+
+ const query = materialTypesQuery(
+ params.substanceId,
+ params.formId,
+ companyId
+ );
+ const data = window?.clientCache?.getQueryData<SerializeFrom<typeof loader>>(
+ query.queryKey
+ );
+
+ if (!data) {
+ const serverData = await serverLoader<typeof loader>();
+ window?.clientCache?.setQueryData(query.queryKey, serverData);
+ return serverData;
+ }
+
+ return data;
+}
+
+clientLoader.hydrate = true;
diff --git a/apps/erp/app/routes/onboarding+/theme.tsx b/apps/erp/app/routes/onboarding+/theme.tsx
index 004f7e7269..3f3b75057f 100644
--- a/apps/erp/app/routes/onboarding+/theme.tsx
+++ b/apps/erp/app/routes/onboarding+/theme.tsx
@@ -184,6 +184,9 @@ export default function OnboardingTheme() {
"--theme-primary": `hsl(${
t?.activeColor[mode === "dark" ? "dark" : "light"]
})`,
+ borderColor: `hsl(${
+ t?.activeColor[mode === "dark" ? "dark" : "light"]
+ })`,
} as React.CSSProperties
}
>
diff --git a/apps/erp/app/routes/x+/items+/dimensions.new.tsx b/apps/erp/app/routes/x+/items+/dimensions.new.tsx
index 1719a9825a..eec23be32f 100644
--- a/apps/erp/app/routes/x+/items+/dimensions.new.tsx
+++ b/apps/erp/app/routes/x+/items+/dimensions.new.tsx
@@ -9,8 +9,8 @@ import {
materialDimensionValidator,
upsertMaterialDimension,
} from "~/modules/items";
-import { getMetricSettings } from "~/modules/items/items.server";
import MaterialDimensionForm from "~/modules/items/ui/MaterialDimensions/MaterialDimensionForm";
+import { getCompanySettings } from "~/modules/settings";
import { getParams, path } from "~/utils/path";
@@ -41,12 +41,12 @@ export async function action({ request }: ActionFunctionArgs) {
const { id, ...data } = validation.data;
- const isMetric = await getMetricSettings(client, companyId);
+ const settings = await getCompanySettings(client, companyId);
const insertMaterialDimension = await upsertMaterialDimension(client, {
...data,
companyId,
- isMetric,
+ isMetric: settings?.data?.useMetric ?? false,
});
if (insertMaterialDimension.error) {
diff --git a/apps/erp/app/routes/x+/items+/dimensions.tsx b/apps/erp/app/routes/x+/items+/dimensions.tsx
index 262a82c38f..7264003546 100644
--- a/apps/erp/app/routes/x+/items+/dimensions.tsx
+++ b/apps/erp/app/routes/x+/items+/dimensions.tsx
@@ -6,8 +6,8 @@ import { Outlet, useLoaderData } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { getMaterialDimensions } from "~/modules/items";
-import { getMetricSettings } from "~/modules/items/items.server";
import MaterialDimensionsTable from "~/modules/items/ui/MaterialDimensions/MaterialDimensionsTable";
+import { getCompanySettings } from "~/modules/settings/settings.service";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -30,7 +30,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const isMetric = await getMetricSettings(client, companyId);
+ const settings = await getCompanySettings(client, companyId);
const [materialDimensions] = await Promise.all([
getMaterialDimensions(client, companyId, {
@@ -39,7 +39,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
sorts,
search,
filters,
- isMetric,
+ isMetric: settings?.data?.useMetric ?? false,
}),
]);
diff --git a/apps/erp/app/routes/x+/items+/forms.$formId.tsx b/apps/erp/app/routes/x+/items+/forms.$formId.tsx
index 00f95f5d7a..9c378fd569 100644
--- a/apps/erp/app/routes/x+/items+/forms.$formId.tsx
+++ b/apps/erp/app/routes/x+/items+/forms.$formId.tsx
@@ -86,6 +86,7 @@ export default function EditMaterialFormsRoute() {
const initialValues = {
id: materialForm?.id ?? undefined,
name: materialForm?.name ?? "",
+ code: materialForm?.code ?? "",
...getCustomFields(materialForm?.customFields),
};
diff --git a/apps/erp/app/routes/x+/items+/forms.new.tsx b/apps/erp/app/routes/x+/items+/forms.new.tsx
index 651864e1ae..cd0e8c944b 100644
--- a/apps/erp/app/routes/x+/items+/forms.new.tsx
+++ b/apps/erp/app/routes/x+/items+/forms.new.tsx
@@ -74,6 +74,7 @@ export default function NewMaterialFormsRoute() {
const navigate = useNavigate();
const initialValues = {
name: "",
+ code: "",
description: "",
};
diff --git a/apps/erp/app/routes/x+/items+/substances.$substanceId.tsx b/apps/erp/app/routes/x+/items+/substances.$substanceId.tsx
index 20440280de..46e51d5231 100644
--- a/apps/erp/app/routes/x+/items+/substances.$substanceId.tsx
+++ b/apps/erp/app/routes/x+/items+/substances.$substanceId.tsx
@@ -94,6 +94,7 @@ export default function EditMaterialSubstancesRoute() {
const initialValues = {
id: materialSubstance?.id ?? undefined,
name: materialSubstance?.name ?? "",
+ code: materialSubstance?.code ?? "",
...getCustomFields(materialSubstance?.customFields),
};
diff --git a/apps/erp/app/routes/x+/items+/substances.new.tsx b/apps/erp/app/routes/x+/items+/substances.new.tsx
index 3e9531eca9..8cf83b0ff1 100644
--- a/apps/erp/app/routes/x+/items+/substances.new.tsx
+++ b/apps/erp/app/routes/x+/items+/substances.new.tsx
@@ -82,6 +82,7 @@ export default function NewMaterialSubstancesRoute() {
const navigate = useNavigate();
const initialValues = {
name: "",
+ code: "",
description: "",
};
diff --git a/apps/erp/app/routes/x+/items+/types.$id.tsx b/apps/erp/app/routes/x+/items+/types.$id.tsx
index 0434846cac..4e0bf66270 100644
--- a/apps/erp/app/routes/x+/items+/types.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/types.$id.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, notFound, 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 type { ClientActionFunctionArgs } from "@remix-run/react";
import { useLoaderData, useNavigate } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
@@ -13,6 +14,8 @@ import {
import MaterialTypeForm from "~/modules/items/ui/MaterialTypes/MaterialTypeForm";
import { getParams, path } from "~/utils/path";
+import { getCompanyId, materialTypesQuery } from "~/utils/react-query";
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client } = await requirePermissions(request, {
view: "parts",
@@ -76,6 +79,30 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+export async function clientAction({
+ request,
+ serverAction,
+}: ClientActionFunctionArgs) {
+ const formData = await request.clone().formData();
+ const validation = await validator(materialTypeValidator).validate(formData);
+
+ if (!validation.error) {
+ const companyId = getCompanyId();
+ const { materialSubstanceId, materialFormId } = validation.data;
+
+ if (companyId && materialSubstanceId && materialFormId) {
+ // Invalidate the cache for this specific combination
+ window.clientCache?.setQueryData(
+ materialTypesQuery(materialSubstanceId, materialFormId, companyId)
+ .queryKey,
+ null
+ );
+ }
+ }
+
+ return await serverAction();
+}
+
export default function EditMaterialTypesRoute() {
const { materialType } = useLoaderData<typeof loader>();
const navigate = useNavigate();
@@ -83,6 +110,7 @@ export default function EditMaterialTypesRoute() {
const initialValues = {
id: materialType?.id ?? undefined,
name: materialType?.name ?? "",
+ code: materialType?.code ?? "",
materialSubstanceId: materialType?.materialSubstanceId ?? "",
materialFormId: materialType?.materialFormId ?? "",
};
@@ -94,4 +122,4 @@ export default function EditMaterialTypesRoute() {
onClose={() => navigate(-1)}
/>
);
-}
\ No newline at end of file
+}
diff --git a/apps/erp/app/routes/x+/items+/types.delete.$id.tsx b/apps/erp/app/routes/x+/items+/types.delete.$id.tsx
index 2ce53f04d9..68104ec900 100644
--- a/apps/erp/app/routes/x+/items+/types.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/types.delete.$id.tsx
@@ -78,4 +78,4 @@ export default function DeleteMaterialTypeRoute() {
onCancel={onCancel}
/>
);
-}
\ No newline at end of file
+}
diff --git a/apps/erp/app/routes/x+/items+/types.new.tsx b/apps/erp/app/routes/x+/items+/types.new.tsx
index a878f8e635..06d334bb8c 100644
--- a/apps/erp/app/routes/x+/items+/types.new.tsx
+++ b/apps/erp/app/routes/x+/items+/types.new.tsx
@@ -2,6 +2,7 @@ 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 type { ClientActionFunctionArgs } from "@remix-run/react";
import { useNavigate } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
@@ -9,6 +10,7 @@ import { materialTypeValidator, upsertMaterialType } from "~/modules/items";
import MaterialTypeForm from "~/modules/items/ui/MaterialTypes/MaterialTypeForm";
import { getParams, path } from "~/utils/path";
+import { getCompanyId, materialTypesQuery } from "~/utils/react-query";
export async function loader({ request }: LoaderFunctionArgs) {
await requirePermissions(request, {
@@ -68,10 +70,35 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+export async function clientAction({
+ request,
+ serverAction,
+}: ClientActionFunctionArgs) {
+ const formData = await request.clone().formData();
+ const validation = await validator(materialTypeValidator).validate(formData);
+
+ if (!validation.error) {
+ const companyId = getCompanyId();
+ const { materialSubstanceId, materialFormId } = validation.data;
+
+ if (companyId && materialSubstanceId && materialFormId) {
+ // Invalidate the cache for this specific combination
+ window.clientCache?.setQueryData(
+ materialTypesQuery(materialSubstanceId, materialFormId, companyId)
+ .queryKey,
+ null
+ );
+ }
+ }
+
+ return await serverAction();
+}
+
export default function NewMaterialTypesRoute() {
const navigate = useNavigate();
const initialValues = {
name: "",
+ code: "",
materialSubstanceId: "",
materialFormId: "",
};
@@ -82,4 +109,4 @@ export default function NewMaterialTypesRoute() {
initialValues={initialValues}
/>
);
-}
\ No newline at end of file
+}
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index 18ba15efe9..9d80eed726 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -1,9 +1,11 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import type { Database } from "@carbon/database";
import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { getCompanySettings } from "~/modules/settings";
+import { getMaterialDescription, getMaterialId } from "~/utils/items";
export async function action({ request }: ActionFunctionArgs) {
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "parts",
});
@@ -36,6 +38,7 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString(),
})
.in("id", items as string[])
+ .eq("companyId", companyId)
);
}
if (field === "defaultMethodType" && value !== "Pick") {
@@ -51,6 +54,7 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString(),
})
.in("id", items as string[])
+ .eq("companyId", companyId)
);
}
return json(
@@ -62,6 +66,7 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString(),
})
.in("id", items as string[])
+ .eq("companyId", companyId)
);
case "gradeId":
case "dimensionId":
@@ -69,42 +74,208 @@ export async function action({ request }: ActionFunctionArgs) {
case "materialFormId":
case "materialSubstanceId":
case "materialTypeId":
- const materialItems = await client
- .from("item")
- .select("readableId")
- .in("id", items as string[]);
- const materialIds = [
- ...new Set(materialItems.data?.map((item) => item.readableId) ?? []),
- ];
- if (materialIds.length === 0) {
- return json({ error: { message: "No materials found" }, data: null });
- }
+ const settings = await getCompanySettings(client, companyId);
- let updateData: Database["public"]["Tables"]["material"]["Update"] = {
- [field]: value || null,
- updatedBy: userId,
- updatedAt: new Date().toISOString(),
- };
-
- // If substance changes, reset finishId, gradeId, and materialTypeId
- if (field === "materialSubstanceId") {
- updateData.finishId = null;
- updateData.gradeId = null;
- updateData.materialTypeId = null;
- }
+ if (settings.data?.materialGeneratedIds) {
+ let name = "";
+ let code = "";
+ if (field === "materialSubstanceId") {
+ const materialSubstance = await client
+ .from("materialSubstance")
+ .select("name, code")
+ .eq("code", value)
+ .single();
+ name = materialSubstance.data?.name ?? "";
+ code = materialSubstance.data?.code ?? "";
+ }
+ if (field === "materialFormId") {
+ const materialForm = await client
+ .from("materialForm")
+ .select("name, code")
+ .eq("code", value)
+ .single();
+ name = materialForm.data?.name ?? "";
+ code = materialForm.data?.code ?? "";
+ }
+ if (field === "materialTypeId") {
+ const materialType = await client
+ .from("materialType")
+ .select("name, code")
+ .eq("code", value)
+ .single();
+ name = materialType.data?.name ?? "";
+ code = materialType.data?.code ?? "";
+ }
+ if (field === "finishId") {
+ const finish = await client
+ .from("materialFinish")
+ .select("name")
+ .eq("id", value)
+ .single();
+ name = finish.data?.name ?? "";
+ }
+ if (field === "gradeId") {
+ const grade = await client
+ .from("materialGrade")
+ .select("name")
+ .eq("id", value)
+ .single();
- // If form changes, reset dimensionId and materialTypeId
- if (field === "materialFormId") {
- updateData.dimensionId = null;
- updateData.materialTypeId = null;
- }
+ name = grade.data?.name ?? "";
+ }
+ if (field === "dimensionId") {
+ const dimension = await client
+ .from("materialDimension")
+ .select("name")
+ .eq("id", value)
+ .single();
+ name = dimension.data?.name ?? "";
+ }
- return json(
- await client
- .from("material")
- .update(updateData)
- .in("id", materialIds as string[])
- );
+ for await (const id of items as string[]) {
+ const item = await client
+ .from("item")
+ .select("readableId")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+
+ const readableId = item.data?.readableId;
+
+ if (readableId) {
+ const [materialDetails, relatedItems] = await Promise.all([
+ client
+ .rpc("get_material_naming_details", { readable_id: readableId })
+ .single(),
+ client
+ .from("item")
+ .select("id")
+ .eq("readableId", readableId)
+ .eq("companyId", companyId),
+ ]);
+
+ if (materialDetails.data) {
+ const namingDetails = materialDetails.data;
+ if (field === "materialSubstanceId") {
+ namingDetails.substance = name;
+ namingDetails.substanceCode = code;
+ }
+ if (field === "materialFormId") {
+ namingDetails.shape = name;
+ namingDetails.shapeCode = code;
+ }
+ if (field === "materialTypeId") {
+ namingDetails.materialType = name;
+ namingDetails.materialTypeCode = code;
+ }
+ if (field === "finishId") {
+ namingDetails.finish = name;
+ }
+ if (field === "gradeId") {
+ namingDetails.grade = name;
+ }
+ if (field === "dimensionId") {
+ namingDetails.dimensions = name;
+ }
+
+ const newMaterialId = getMaterialId(namingDetails);
+ const newDescription = getMaterialDescription(namingDetails);
+
+ const relatedItemIds = relatedItems.data?.map((item) => item.id);
+
+ if (relatedItemIds) {
+ const itemUpdateResult = await client
+ .from("item")
+ .update({ readableId: newMaterialId, name: newDescription })
+ .in("id", relatedItemIds as string[])
+ .eq("companyId", companyId);
+
+ if (itemUpdateResult.error) {
+ return json(itemUpdateResult);
+ }
+ }
+
+ let updateData: Database["public"]["Tables"]["material"]["Update"] =
+ {
+ [field]: value || null,
+ id: newMaterialId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ };
+
+ // If substance changes, reset finishId, gradeId, and materialTypeId
+ if (field === "materialSubstanceId") {
+ updateData.finishId = null;
+ updateData.gradeId = null;
+ updateData.materialTypeId = null;
+ }
+
+ // If form changes, reset dimensionId and materialTypeId
+ if (field === "materialFormId") {
+ updateData.dimensionId = null;
+ updateData.materialTypeId = null;
+ }
+
+ const update = await client
+ .from("material")
+ .update(updateData)
+ .eq("id", readableId)
+ .eq("companyId", companyId);
+
+ if (update.error) {
+ return json({
+ error: { message: update.error.message },
+ data: null,
+ });
+ }
+ }
+ }
+ }
+
+ return json({
+ data: null,
+ error: null,
+ });
+ } else {
+ const materialItems = await client
+ .from("item")
+ .select("readableId")
+ .in("id", items as string[])
+ .eq("companyId", companyId);
+ const materialIds = [
+ ...new Set(materialItems.data?.map((item) => item.readableId) ?? []),
+ ];
+ if (materialIds.length === 0) {
+ return json({ error: { message: "No materials found" }, data: null });
+ }
+
+ let updateData: Database["public"]["Tables"]["material"]["Update"] = {
+ [field]: value || null,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ };
+
+ // If substance changes, reset finishId, gradeId, and materialTypeId
+ if (field === "materialSubstanceId") {
+ updateData.finishId = null;
+ updateData.gradeId = null;
+ updateData.materialTypeId = null;
+ }
+
+ // If form changes, reset dimensionId and materialTypeId
+ if (field === "materialFormId") {
+ updateData.dimensionId = null;
+ updateData.materialTypeId = null;
+ }
+
+ return json(
+ await client
+ .from("material")
+ .update(updateData)
+ .in("id", materialIds as string[])
+ .eq("companyId", companyId)
+ );
+ }
case "active":
return json(
await client
@@ -115,6 +286,7 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString(),
})
.in("id", items as string[])
+ .eq("companyId", companyId)
);
default:
return json({ error: { message: "Invalid field" }, data: null });
diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsx
index c88ae176eb..90f59e3b64 100644
--- a/apps/erp/app/routes/x+/job+/update.tsx
+++ b/apps/erp/app/routes/x+/job+/update.tsx
@@ -34,6 +34,7 @@ export async function action({ request }: ActionFunctionArgs) {
.from("job")
.delete()
.in("id", ids as string[])
+ .eq("companyId", companyId)
);
}
if (typeof value !== "string" && value !== null) {
@@ -80,7 +81,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: userId,
updatedAt: new Date().toISOString(),
})
- .in("id", ids as string[]),
+ .in("id", ids as string[])
+ .eq("companyId", companyId),
client
.from("jobMakeMethod")
@@ -90,7 +92,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString(),
})
.in("jobId", ids as string[])
- .is("parentMaterialId", null),
+ .is("parentMaterialId", null)
+ .eq("companyId", companyId),
]);
if (itemUpdate.error) {
@@ -138,6 +141,7 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString(),
})
.in("id", ids as string[])
+ .eq("companyId", companyId)
);
case "quantity":
case "scrapQuantity":
@@ -148,7 +152,8 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: userId,
updatedAt: new Date().toISOString(),
})
- .in("id", ids as string[]);
+ .in("id", ids as string[])
+ .eq("companyId", companyId);
if (quantityUpdate.error) {
return json(quantityUpdate);
@@ -175,6 +180,7 @@ export async function action({ request }: ActionFunctionArgs) {
.from("job")
.update({ salesOrderId: null, salesOrderLineId: null })
.in("id", ids as string[])
+ .eq("companyId", companyId)
);
} else {
return json({
diff --git a/apps/erp/app/routes/x+/material+/$itemId.view.tsx b/apps/erp/app/routes/x+/material+/$itemId.view.tsx
index ae8c6d349f..94cb429f86 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.view.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.view.tsx
@@ -127,6 +127,7 @@ export default function MaterialViewRoute() {
return (
<UsedInTree
tree={tree}
+ hasSizesInsteadOfRevisions={true}
revisions={materialData.materialSummary?.revisions}
itemReadableId={
materialData.materialSummary?.readableId ?? ""
diff --git a/apps/erp/app/routes/x+/settings+/items.tsx b/apps/erp/app/routes/x+/settings+/items.tsx
index 8ba988bcb4..6045d0a72a 100644
--- a/apps/erp/app/routes/x+/settings+/items.tsx
+++ b/apps/erp/app/routes/x+/settings+/items.tsx
@@ -19,13 +19,14 @@ import { flash } from "@carbon/auth/session.server";
import { Boolean, Submit, ValidatedForm, validator } from "@carbon/form";
import { useFetcher, useLoaderData } from "@remix-run/react";
import { useEffect } from "react";
-import { setMetricSettings } from "~/modules/items/items.server";
import {
getCompanySettings,
materialIdsValidator,
materialUnitsValidator,
updateMaterialGeneratedIdsSetting,
+ updateMetricSettings,
} from "~/modules/settings";
+
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -93,7 +94,7 @@ export async function action({ request }: ActionFunctionArgs) {
return json({ success: false, message: "Invalid form data" });
}
- const materialUnitsResult = await setMetricSettings(
+ const materialUnitsResult = await updateMetricSettings(
client,
companyId,
unitsValidation.data.useMetric
diff --git a/apps/erp/app/utils/items.ts b/apps/erp/app/utils/items.ts
index 0fea996e59..ce883c4ad0 100644
--- a/apps/erp/app/utils/items.ts
+++ b/apps/erp/app/utils/items.ts
@@ -24,3 +24,43 @@ export function getItemReadableId(
export function getItemById(items: Item[], itemId: string): Item | undefined {
return items.find((item) => item.id === itemId);
}
+
+export function getMaterialDescription(material: {
+ materialType?: string;
+ substance?: string;
+ grade?: string;
+ shape?: string;
+ dimensions?: string;
+ finish?: string;
+}) {
+ return [
+ material.grade,
+ material.substance,
+ material.materialType,
+ material.shape,
+ material.dimensions,
+ material.finish,
+ ]
+ .filter((p) => !!p)
+ .join(" ");
+}
+
+export function getMaterialId(material: {
+ materialTypeCode?: string;
+ substanceCode?: string;
+ grade?: string;
+ shapeCode?: string;
+ dimensions?: string;
+ finish?: string;
+}) {
+ return [
+ material.grade,
+ material.substanceCode,
+ material.materialTypeCode,
+ material.shapeCode,
+ material.dimensions,
+ material.finish,
+ ]
+ .filter((p) => !!p)
+ .join("-");
+}
diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.ts
index d908ddcce9..5a79c1d542 100644
--- a/apps/erp/app/utils/react-query.ts
+++ b/apps/erp/app/utils/react-query.ts
@@ -118,3 +118,12 @@ export const workCentersQuery = (companyId: string | null) => ({
queryKey: ["workCenters", companyId ?? "null"],
staleTime: RefreshRate.Low,
});
+
+export const materialTypesQuery = (
+ substanceId: string,
+ formId: string,
+ companyId: string | null
+) => ({
+ queryKey: ["materialTypes", substanceId, formId, companyId ?? "null"],
+ staleTime: RefreshRate.Low,
+});
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 07dcd3e39c..84667febf4 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -18189,6 +18189,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialType.name",
},
+ {
+ $ref: "#/parameters/rowFilter.materialType.code",
+ },
{
$ref: "#/parameters/rowFilter.materialType.materialSubstanceId",
},
@@ -18263,6 +18266,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialType.name",
},
+ {
+ $ref: "#/parameters/rowFilter.materialType.code",
+ },
{
$ref: "#/parameters/rowFilter.materialType.materialSubstanceId",
},
@@ -18291,6 +18297,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialType.name",
},
+ {
+ $ref: "#/parameters/rowFilter.materialType.code",
+ },
{
$ref: "#/parameters/rowFilter.materialType.materialSubstanceId",
},
@@ -27846,6 +27855,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialForm.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.materialForm.code",
+ },
{
$ref: "#/parameters/select",
},
@@ -27932,6 +27944,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialForm.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.materialForm.code",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -27972,6 +27987,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialForm.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.materialForm.code",
+ },
{
$ref: "#/parameters/body.materialForm",
},
@@ -46938,6 +46956,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialSubstance.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.materialSubstance.code",
+ },
{
$ref: "#/parameters/select",
},
@@ -47024,6 +47045,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialSubstance.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.materialSubstance.code",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -47064,6 +47088,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materialSubstance.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.materialSubstance.code",
+ },
{
$ref: "#/parameters/body.materialSubstance",
},
@@ -66837,7 +66864,7 @@ export default {
type: "object",
},
materialType: {
- required: ["id", "name", "materialSubstanceId", "materialFormId"],
+ required: ["id", "name", "code", "materialSubstanceId", "materialFormId"],
properties: {
id: {
default: "public.xid()",
@@ -66849,6 +66876,10 @@ export default {
format: "text",
type: "string",
},
+ code: {
+ format: "text",
+ type: "string",
+ },
materialSubstanceId: {
description:
"Note:\nThis is a Foreign Key to `materialSubstance.id`.<fk table='materialSubstance' column='id'/>",
@@ -71079,7 +71110,7 @@ export default {
type: "object",
},
materialForm: {
- required: ["id", "name", "createdBy", "createdAt"],
+ required: ["id", "name", "createdBy", "createdAt", "code"],
properties: {
id: {
default: "public.xid()",
@@ -71128,6 +71159,10 @@ export default {
},
type: "array",
},
+ code: {
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -80207,7 +80242,7 @@ export default {
type: "object",
},
materialSubstance: {
- required: ["id", "name", "createdBy", "createdAt"],
+ required: ["id", "name", "createdBy", "createdAt", "code"],
properties: {
id: {
default: "public.xid()",
@@ -80256,6 +80291,10 @@ export default {
},
type: "array",
},
+ code: {
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -93062,6 +93101,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.materialType.code": {
+ name: "code",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.materialType.materialSubstanceId": {
name: "materialSubstanceId",
required: false,
@@ -97868,6 +97913,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.materialForm.code": {
+ name: "code",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.supplierQuotes": {
name: "supplierQuotes",
description: "supplierQuotes",
@@ -108275,6 +108326,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.materialSubstance.code": {
+ name: "code",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.quoteMakeMethod": {
name: "quoteMakeMethod",
description: "quoteMakeMethod",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 311c706354..be519f8905 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -12294,6 +12294,7 @@ export type Database = {
}
materialForm: {
Row: {
+ code: string
companyId: string | null
createdAt: string
createdBy: string
@@ -12305,6 +12306,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ code: string
companyId?: string | null
createdAt?: string
createdBy: string
@@ -12316,6 +12318,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ code?: string
companyId?: string | null
createdAt?: string
createdBy?: string
@@ -12486,6 +12489,7 @@ export type Database = {
}
materialSubstance: {
Row: {
+ code: string
companyId: string | null
createdAt: string
createdBy: string
@@ -12497,6 +12501,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ code: string
companyId?: string | null
createdAt?: string
createdBy: string
@@ -12508,6 +12513,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ code?: string
companyId?: string | null
createdAt?: string
createdBy?: string
@@ -12621,6 +12627,7 @@ export type Database = {
}
materialType: {
Row: {
+ code: string
companyId: string | null
id: string
materialFormId: string
@@ -12628,6 +12635,7 @@ export type Database = {
name: string
}
Insert: {
+ code: string
companyId?: string | null
id?: string
materialFormId: string
@@ -12635,6 +12643,7 @@ export type Database = {
name: string
}
Update: {
+ code?: string
companyId?: string | null
id?: string
materialFormId?: string
@@ -40247,14 +40256,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -45827,6 +45836,14 @@ export type Database = {
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
materialSubstanceId: string
materialFormId: string
+ dimensionId: string
+ dimension: string
+ finishId: string
+ finish: string
+ gradeId: string
+ grade: string
+ materialType: string
+ materialTypeId: string
thumbnailPath: string
unitOfMeasureCode: string
quantityOnHand: number
@@ -46041,6 +46058,23 @@ export type Database = {
updatedAt: string
}[]
}
+ get_material_naming_details: {
+ Args: {
+ readable_id: string
+ }
+ Returns: {
+ id: string
+ shape: string
+ substanceCode: string
+ substance: string
+ shapeCode: string
+ finish: string
+ grade: string
+ dimensions: string
+ materialType: string
+ materialTypeCode: string
+ }[]
+ }
get_method_tree: {
Args: {
uid: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 311c706354..be519f8905 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -12294,6 +12294,7 @@ export type Database = {
}
materialForm: {
Row: {
+ code: string
companyId: string | null
createdAt: string
createdBy: string
@@ -12305,6 +12306,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ code: string
companyId?: string | null
createdAt?: string
createdBy: string
@@ -12316,6 +12318,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ code?: string
companyId?: string | null
createdAt?: string
createdBy?: string
@@ -12486,6 +12489,7 @@ export type Database = {
}
materialSubstance: {
Row: {
+ code: string
companyId: string | null
createdAt: string
createdBy: string
@@ -12497,6 +12501,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ code: string
companyId?: string | null
createdAt?: string
createdBy: string
@@ -12508,6 +12513,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ code?: string
companyId?: string | null
createdAt?: string
createdBy?: string
@@ -12621,6 +12627,7 @@ export type Database = {
}
materialType: {
Row: {
+ code: string
companyId: string | null
id: string
materialFormId: string
@@ -12628,6 +12635,7 @@ export type Database = {
name: string
}
Insert: {
+ code: string
companyId?: string | null
id?: string
materialFormId: string
@@ -12635,6 +12643,7 @@ export type Database = {
name: string
}
Update: {
+ code?: string
companyId?: string | null
id?: string
materialFormId?: string
@@ -40247,14 +40256,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -45827,6 +45836,14 @@ export type Database = {
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
materialSubstanceId: string
materialFormId: string
+ dimensionId: string
+ dimension: string
+ finishId: string
+ finish: string
+ gradeId: string
+ grade: string
+ materialType: string
+ materialTypeId: string
thumbnailPath: string
unitOfMeasureCode: string
quantityOnHand: number
@@ -46041,6 +46058,23 @@ export type Database = {
updatedAt: string
}[]
}
+ get_material_naming_details: {
+ Args: {
+ readable_id: string
+ }
+ Returns: {
+ id: string
+ shape: string
+ substanceCode: string
+ substance: string
+ shapeCode: string
+ finish: string
+ grade: string
+ dimensions: string
+ materialType: string
+ materialTypeCode: string
+ }[]
+ }
get_method_tree: {
Args: {
uid: string
diff --git a/packages/database/supabase/migrations/20250719100358_material-seed.sql b/packages/database/supabase/migrations/20250719100358_material-seed.sql
index 8af80a2837..29bceb1902 100644
--- a/packages/database/supabase/migrations/20250719100358_material-seed.sql
+++ b/packages/database/supabase/migrations/20250719100358_material-seed.sql
@@ -1,52 +1,55 @@
ALTER TABLE "companySettings" ADD COLUMN "materialGeneratedIds" BOOLEAN NOT NULL DEFAULT true;
ALTER TABLE "companySettings" ADD COLUMN "useMetric" BOOLEAN NOT NULL DEFAULT FALSE;
+ALTER TABLE "materialSubstance" ADD COLUMN "code" TEXT;
+ALTER TABLE "materialForm" ADD COLUMN "code" TEXT;
+
COMMIT;
-- Set materialGeneratedIds to false for all existing companies
UPDATE "companySettings" SET "materialGeneratedIds" = false;
-INSERT INTO "materialForm" ("id", "name", "createdBy") VALUES
- ('angle', 'Angle', 'system'),
- ('billet', 'Billet', 'system'),
- ('channel', 'Channel', 'system'),
- ('flatbar', 'Flat Bar', 'system'),
- ('filament', 'Filament', 'system'),
- ('hexbar', 'Hex Bar', 'system'),
- ('pellet', 'Pellet', 'system'),
- ('plate', 'Plate', 'system'),
- ('rectbar', 'Rectangular Bar', 'system'),
- ('recttube', 'Rectangular Tube', 'system'),
- ('roundbar', 'Round Bar', 'system'),
- ('roundtube', 'Round Tube', 'system'),
- ('squaretube', 'Square Tube', 'system'),
- ('sbeam', 'S-Beam', 'system'),
- ('sheet', 'Sheet', 'system'),
- ('squarebar', 'Square Bar', 'system'),
- ('tbar', 'T-Bar', 'system'),
- ('treadplate', 'Tread Plate', 'system'),
- ('wbeam', 'W-Beam', 'system'),
- ('widebar', 'Wide Bar', 'system');
+INSERT INTO "materialForm" ("id", "name", "code", "createdBy") VALUES
+ ('angle', 'Angle', 'ANGLE', 'system'),
+ ('billet', 'Billet', 'BIL', 'system'),
+ ('channel', 'Channel', 'CHAN', 'system'),
+ ('flatbar', 'Flat Bar', 'FLAT', 'system'),
+ ('filament', 'Filament', 'FIL', 'system'),
+ ('hexbar', 'Hex Bar', 'HEX', 'system'),
+ ('pellet', 'Pellet', 'PEL', 'system'),
+ ('plate', 'Plate', 'PLT', 'system'),
+ ('rectbar', 'Rectangular Bar', 'RECTBAR', 'system'),
+ ('recttube', 'Rectangular Tube', 'RECTTUBE', 'system'),
+ ('roundbar', 'Round Bar', 'ROUNDBAR', 'system'),
+ ('roundtube', 'Round Tube', 'ROUNDTUBE', 'system'),
+ ('squaretube', 'Square Tube', 'SQUARETUBE', 'system'),
+ ('sbeam', 'S-Beam', 'SBEAM', 'system'),
+ ('sheet', 'Sheet', 'SHEET', 'system'),
+ ('squarebar', 'Square Bar', 'SQBAR', 'system'),
+ ('tbar', 'T-Bar', 'TBAR', 'system'),
+ ('treadplate', 'Tread Plate', 'TREADPLATE', 'system'),
+ ('wbeam', 'W-Beam', 'WBEAM', 'system'),
+ ('widebar', 'Wide Bar', 'WIDEBAR', 'system');
-INSERT INTO "materialSubstance" ("id", "name", "createdBy") VALUES
- ('steel', 'Steel', 'system'),
- ('aluminum', 'Aluminum', 'system'),
- ('brass', 'Brass', 'system'),
- ('bronze', 'Bronze', 'system'),
- ('copper', 'Copper', 'system'),
- ('inconel', 'Inconel', 'system'),
- ('magnesium', 'Magnesium', 'system'),
- ('monel', 'Monel', 'system'),
- ('nylon', 'Nylon', 'system'),
- ('plastic', 'Plastic', 'system'),
- ('pvc', 'PVC', 'system'),
- ('rubber', 'Rubber', 'system'),
- ('stainless', 'Stainless Steel', 'system'),
- ('titanium', 'Titanium', 'system'),
- ('tungsten', 'Tungsten', 'system'),
- ('zinc', 'Zinc', 'system'),
- ('zirconium', 'Zirconium', 'system');
+INSERT INTO "materialSubstance" ("id", "name", "code", "createdBy") VALUES
+ ('steel', 'Steel', 'STEEL', 'system'),
+ ('aluminum', 'Aluminum', 'AL', 'system'),
+ ('brass', 'Brass', 'BR', 'system'),
+ ('bronze', 'Bronze', 'BZ', 'system'),
+ ('copper', 'Copper', 'CU', 'system'),
+ ('inconel', 'Inconel', 'INC', 'system'),
+ ('magnesium', 'Magnesium', 'MAG', 'system'),
+ ('monel', 'Monel', 'MON', 'system'),
+ ('nylon', 'Nylon', 'NYL', 'system'),
+ ('plastic', 'Plastic', 'PLA', 'system'),
+ ('pvc', 'PVC', 'PVC', 'system'),
+ ('rubber', 'Rubber', 'RU', 'system'),
+ ('stainless', 'Stainless Steel', 'SS', 'system'),
+ ('titanium', 'Titanium', 'TI', 'system'),
+ ('tungsten', 'Tungsten', 'TU', 'system'),
+ ('zinc', 'Zinc', 'ZN', 'system'),
+ ('zirconium', 'Zirconium', 'ZR', 'system');
CREATE TABLE "materialFinish" (
@@ -145,91 +148,92 @@ CREATE OR REPLACE VIEW "materialGrades" WITH(SECURITY_INVOKER=true) AS
INSERT INTO "materialGrade" ("id", "materialSubstanceId", "name", "companyId") VALUES
-- Steel grades
- ('1018', 'steel', '1018', null),
- ('1045', 'steel', '1045', null),
- ('4140', 'steel', '4140', null),
- ('4340', 'steel', '4340', null),
- ('a36', 'steel', 'A36', null),
- ('1020', 'steel', '1020', null),
- ('1095', 'steel', '1095', null),
- ('4130', 'steel', '4130', null),
- ('8620', 'steel', '8620', null),
- ('d2', 'steel', 'D2', null),
+ ('steel-1018', 'steel', '1018', null),
+ ('steel-1045', 'steel', '1045', null),
+ ('steel-4140', 'steel', '4140', null),
+ ('steel-4340', 'steel', '4340', null),
+ ('steel-a36', 'steel', 'A36', null),
+ ('steel-1020', 'steel', '1020', null),
+ ('steel-1095', 'steel', '1095', null),
+ ('steel-4130', 'steel', '4130', null),
+ ('steel-8620', 'steel', '8620', null),
+ ('steel-d2', 'steel', 'D2', null),
-- Aluminum grades
- ('6061', 'aluminum', '6061', null),
- ('2024', 'aluminum', '2024', null),
- ('5052', 'aluminum', '5052', null),
- ('7075', 'aluminum', '7075', null),
- ('3003', 'aluminum', '3003', null),
- ('5083', 'aluminum', '5083', null),
- ('6063', 'aluminum', '6063', null),
- ('7050', 'aluminum', '7050', null),
- ('2017', 'aluminum', '2017', null),
- ('5086', 'aluminum', '5086', null),
+ ('aluminum-6061', 'aluminum', '6061', null),
+ ('aluminum-2024', 'aluminum', '2024', null),
+ ('aluminum-5052', 'aluminum', '5052', null),
+ ('aluminum-7075', 'aluminum', '7075', null),
+ ('aluminum-3003', 'aluminum', '3003', null),
+ ('aluminum-5083', 'aluminum', '5083', null),
+ ('aluminum-6063', 'aluminum', '6063', null),
+ ('aluminum-7050', 'aluminum', '7050', null),
+ ('aluminum-2017', 'aluminum', '2017', null),
+ ('aluminum-5086', 'aluminum', '5086', null),
-- Stainless grades
- ('304', 'stainless', '304', null),
- ('316', 'stainless', '316', null),
- ('410', 'stainless', '410', null),
- ('17-4', 'stainless', '17-4', null),
- ('303', 'stainless', '303', null),
- ('316l', 'stainless', '316L', null),
- ('321', 'stainless', '321', null),
- ('347', 'stainless', '347', null),
- ('420', 'stainless', '420', null),
- ('440c', 'stainless', '440C', null),
+ ('stainless-304', 'stainless', '304', null),
+ ('stainless-316', 'stainless', '316', null),
+ ('stainless-410', 'stainless', '410', null),
+ ('stainless-17-4', 'stainless', '17-4', null),
+ ('stainless-303', 'stainless', '303', null),
+ ('stainless-316l', 'stainless', '316L', null),
+ ('stainless-321', 'stainless', '321', null),
+ ('stainless-347', 'stainless', '347', null),
+ ('stainless-420', 'stainless', '420', null),
+ ('stainless-440c', 'stainless', '440C', null),
-- Brass grades
- ('360', 'brass', '360', null),
- ('385', 'brass', '385', null),
- ('230', 'brass', '230', null),
- ('260', 'brass', '260', null),
- ('353', 'brass', '353', null),
- ('365', 'brass', '365', null),
+ ('brass-360', 'brass', '360', null),
+ ('brass-385', 'brass', '385', null),
+ ('brass-230', 'brass', '230', null),
+ ('brass-260', 'brass', '260', null),
+ ('brass-353', 'brass', '353', null),
+ ('brass-365', 'brass', '365', null),
-- Bronze grades
- ('544', 'bronze', '544', null),
- ('932', 'bronze', '932', null),
- ('954', 'bronze', '954', null),
- ('903', 'bronze', '903', null),
- ('905', 'bronze', '905', null),
- ('863', 'bronze', '863', null),
+ ('bronze-544', 'bronze', '544', null),
+ ('bronze-932', 'bronze', '932', null),
+ ('bronze-954', 'bronze', '954', null),
+ ('bronze-903', 'bronze', '903', null),
+ ('bronze-905', 'bronze', '905', null),
+ ('bronze-863', 'bronze', '863', null),
-- Titanium grades
- ('gr1', 'titanium', 'Grade 1', null),
- ('gr2', 'titanium', 'Grade 2', null),
- ('gr3', 'titanium', 'Grade 3', null),
- ('gr4', 'titanium', 'Grade 4', null),
- ('gr5', 'titanium', 'Grade 5', null),
- ('gr7', 'titanium', 'Grade 7', null),
- ('gr9', 'titanium', 'Grade 9', null),
+ ('titanium-gr1', 'titanium', 'Grade 1', null),
+ ('titanium-gr2', 'titanium', 'Grade 2', null),
+ ('titanium-gr3', 'titanium', 'Grade 3', null),
+ ('titanium-gr4', 'titanium', 'Grade 4', null),
+ ('titanium-gr5', 'titanium', 'Grade 5', null),
+ ('titanium-gr7', 'titanium', 'Grade 7', null),
+ ('titanium-gr9', 'titanium', 'Grade 9', null),
-- Inconel grades
- ('600', 'inconel', '600', null),
- ('625', 'inconel', '625', null),
- ('718', 'inconel', '718', null),
- ('601', 'inconel', '601', null),
- ('617', 'inconel', '617', null),
- ('722', 'inconel', '722', null),
- ('725', 'inconel', '725', null),
+ ('inconel-600', 'inconel', '600', null),
+ ('inconel-625', 'inconel', '625', null),
+ ('inconel-718', 'inconel', '718', null),
+ ('inconel-601', 'inconel', '601', null),
+ ('inconel-617', 'inconel', '617', null),
+ ('inconel-722', 'inconel', '722', null),
+ ('inconel-725', 'inconel', '725', null),
-- Copper grades
- ('110', 'copper', 'C110', null),
- ('101', 'copper', 'C101', null),
- ('102', 'copper', 'C102', null),
- ('145', 'copper', 'C145', null),
+ ('copper-110', 'copper', 'C110', null),
+ ('copper-101', 'copper', 'C101', null),
+ ('copper-102', 'copper', 'C102', null),
+ ('copper-145', 'copper', 'C145', null),
-- Monel grades
- ('400', 'monel', '400', null),
- ('401', 'monel', '401', null),
- ('404', 'monel', '404', null),
- ('500', 'monel', '500', null);
+ ('monel-400', 'monel', '400', null),
+ ('monel-401', 'monel', '401', null),
+ ('monel-404', 'monel', '404', null),
+ ('monel-500', 'monel', '500', null);
CREATE TABLE "materialType" (
"id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),
"name" TEXT NOT NULL,
+ "code" TEXT NOT NULL,
"materialSubstanceId" TEXT NOT NULL,
"materialFormId" TEXT NOT NULL,
"companyId" TEXT,
@@ -237,6 +241,7 @@ CREATE TABLE "materialType" (
CONSTRAINT "materialType_materialSubstanceId_fkey" FOREIGN KEY ("materialSubstanceId") REFERENCES "materialSubstance"("id"),
CONSTRAINT "materialType_materialFormId_fkey" FOREIGN KEY ("materialFormId") REFERENCES "materialForm"("id"),
CONSTRAINT "materialType_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id"),
+ CONSTRAINT "materialType_code_companyId_unique" UNIQUE ("materialSubstanceId", "materialFormId","code", "companyId"),
CONSTRAINT "materialType_name_companyId_unique" UNIQUE ("materialSubstanceId", "materialFormId", "name", "companyId")
);
@@ -253,46 +258,46 @@ CREATE OR REPLACE VIEW "materialTypes" WITH(SECURITY_INVOKER=true) AS
LEFT JOIN "materialSubstance" ON "materialType"."materialSubstanceId" = "materialSubstance"."id"
LEFT JOIN "materialForm" ON "materialType"."materialFormId" = "materialForm"."id";
-INSERT INTO "materialType" ("id", "name", "materialSubstanceId", "materialFormId", "companyId") VALUES
+INSERT INTO "materialType" ("id", "name", "code", "materialSubstanceId", "materialFormId", "companyId") VALUES
-- Steel Plate types
- ('hot-rolled-steel-plate', 'Hot Rolled', 'steel', 'plate', null),
- ('cold-rolled-steel-plate', 'Cold Rolled', 'steel', 'plate', null),
- ('pickled-oiled-steel-plate', 'Pickled & Oiled', 'steel', 'plate', null),
- ('normalized-steel-plate', 'Normalized', 'steel', 'plate', null),
+ ('hot-rolled-steel-plate', 'Hot Rolled', 'HR', 'steel', 'plate', null),
+ ('cold-rolled-steel-plate', 'Cold Rolled', 'CR', 'steel', 'plate', null),
+ ('pickled-oiled-steel-plate', 'Pickled & Oiled', 'PO', 'steel', 'plate', null),
+ ('normalized-steel-plate', 'Normalized', 'NO', 'steel', 'plate', null),
-- Aluminum Round Tube types
- ('seamless-aluminum-roundtube', 'Seamless', 'aluminum', 'roundtube', null),
- ('structural-aluminum-roundtube', 'Structural', 'aluminum', 'roundtube', null),
- ('drawn-aluminum-roundtube', 'Drawn', 'aluminum', 'roundtube', null),
+ ('seamless-aluminum-roundtube', 'Seamless', 'SE', 'aluminum', 'roundtube', null),
+ ('structural-aluminum-roundtube', 'Structural', 'ST', 'aluminum', 'roundtube', null),
+ ('drawn-aluminum-roundtube', 'Drawn', 'DR', 'aluminum', 'roundtube', null),
-- Steel Round Tube types
- ('seamless-steel-roundtube', 'Seamless', 'steel', 'roundtube', null),
- ('welded-steel-roundtube', 'Welded', 'steel', 'roundtube', null),
- ('dom-steel-roundtube', 'DOM (Drawn Over Mandrel)', 'steel', 'roundtube', null),
+ ('seamless-steel-roundtube', 'Seamless', 'SE', 'steel', 'roundtube', null),
+ ('welded-steel-roundtube', 'Welded', 'WE', 'steel', 'roundtube', null),
+ ('dom-steel-roundtube', 'DOM (Drawn Over Mandrel)', 'DOM', 'steel', 'roundtube', null),
-- Stainless Steel types
- ('annealed-stainless-plate', 'Annealed', 'stainless', 'plate', null),
- ('pickled-stainless-plate', 'Pickled', 'stainless', 'plate', null),
- ('solution-annealed-stainless-plate', 'Solution Annealed', 'stainless', 'plate', null),
+ ('annealed-stainless-plate', 'Annealed', 'AN', 'stainless', 'plate', null),
+ ('pickled-stainless-plate', 'Pickled', 'PI', 'stainless', 'plate', null),
+ ('solution-annealed-stainless-plate', 'Solution Annealed', 'SA', 'stainless', 'plate', null),
-- Aluminum Bar types
- ('extruded-aluminum-roundbar', 'Extruded', 'aluminum', 'roundbar', null),
- ('cold-finished-aluminum-roundbar', 'Cold Finished', 'aluminum', 'roundbar', null),
- ('heat-treated-aluminum-roundbar', 'Heat Treated', 'aluminum', 'roundbar', null),
+ ('extruded-aluminum-roundbar', 'Extruded', 'EX', 'aluminum', 'roundbar', null),
+ ('cold-finished-aluminum-roundbar', 'Cold Finished', 'CF', 'aluminum', 'roundbar', null),
+ ('heat-treated-aluminum-roundbar', 'Heat Treated', 'HT', 'aluminum', 'roundbar', null),
-- Steel Bar types
- ('hot-rolled-steel-roundbar', 'Hot Rolled', 'steel', 'roundbar', null),
- ('cold-finished-steel-roundbar', 'Cold Finished', 'steel', 'roundbar', null),
- ('ground-steel-roundbar', 'Ground', 'steel', 'roundbar', null),
+ ('hot-rolled-steel-roundbar', 'Hot Rolled', 'HR', 'steel', 'roundbar', null),
+ ('cold-finished-steel-roundbar', 'Cold Finished', 'CF', 'steel', 'roundbar', null),
+ ('ground-steel-roundbar', 'Ground', 'GR', 'steel', 'roundbar', null),
-- Sheet types
- ('hot-rolled-steel-sheet', 'Hot Rolled', 'steel', 'sheet', null),
- ('cold-rolled-steel-sheet', 'Cold Rolled', 'steel', 'sheet', null),
- ('galvanized-steel-sheet', 'Galvanized', 'steel', 'sheet', null),
+ ('hot-rolled-steel-sheet', 'Hot Rolled', 'HR', 'steel', 'sheet', null),
+ ('cold-rolled-steel-sheet', 'Cold Rolled', 'CR', 'steel', 'sheet', null),
+ ('galvanized-steel-sheet', 'Galvanized', 'GA', 'steel', 'sheet', null),
-- Aluminum Sheet types
- ('rolled-aluminum-sheet', 'Rolled', 'aluminum', 'sheet', null),
- ('treadplate-aluminum-sheet', 'Tread Plate', 'aluminum', 'sheet', null);
+ ('rolled-aluminum-sheet', 'Rolled', 'RL', 'aluminum', 'sheet', null),
+ ('treadplate-aluminum-sheet', 'Tread Plate', 'TR', 'aluminum', 'sheet', null);
diff --git a/packages/database/supabase/migrations/20250724214243_add-material-codes-nullable.sql b/packages/database/supabase/migrations/20250724214243_add-material-codes-nullable.sql
new file mode 100644
index 0000000000..cbf790c11b
--- /dev/null
+++ b/packages/database/supabase/migrations/20250724214243_add-material-codes-nullable.sql
@@ -0,0 +1,4 @@
+
+-- Add unique constraints for code within company scope
+ALTER TABLE "materialSubstance" ADD CONSTRAINT "materialSubstance_code_companyId_unique" UNIQUE ("code", "companyId");
+ALTER TABLE "materialForm" ADD CONSTRAINT "materialForm_code_companyId_unique" UNIQUE ("code", "companyId");
diff --git a/packages/database/supabase/migrations/20250724214244_populate-material-codes.sql b/packages/database/supabase/migrations/20250724214244_populate-material-codes.sql
new file mode 100644
index 0000000000..534fd5345a
--- /dev/null
+++ b/packages/database/supabase/migrations/20250724214244_populate-material-codes.sql
@@ -0,0 +1,63 @@
+-- Populate code values for existing materialSubstance records
+-- Take first two characters of name and capitalize them
+UPDATE "materialSubstance"
+SET "code" = UPPER(LEFT("name", 2))
+WHERE "code" IS NULL;
+
+-- Populate code values for existing materialForm records
+-- Take first two characters of name and capitalize them
+UPDATE "materialForm"
+SET "code" = UPPER(LEFT("name", 2))
+WHERE "code" IS NULL;
+
+-- Populate code values for existing materialType records
+-- Take first two characters of name and capitalize them
+UPDATE "materialType"
+SET "code" = UPPER(LEFT("name", 2))
+WHERE "code" IS NULL;
+
+-- Handle any duplicates that might occur by appending numbers
+-- For materialSubstance
+WITH duplicates AS (
+ SELECT
+ id,
+ code,
+ "companyId",
+ ROW_NUMBER() OVER (PARTITION BY code, "companyId" ORDER BY id) as rn
+ FROM "materialSubstance"
+ WHERE code IS NOT NULL
+)
+UPDATE "materialSubstance" ms
+SET code = CONCAT(d.code, d.rn - 1)
+FROM duplicates d
+WHERE ms.id = d.id AND d.rn > 1;
+
+-- For materialForm
+WITH duplicates AS (
+ SELECT
+ id,
+ code,
+ "companyId",
+ ROW_NUMBER() OVER (PARTITION BY code, "companyId" ORDER BY id) as rn
+ FROM "materialForm"
+ WHERE code IS NOT NULL
+)
+UPDATE "materialForm" mf
+SET code = CONCAT(d.code, d.rn - 1)
+FROM duplicates d
+WHERE mf.id = d.id AND d.rn > 1;
+
+-- For materialType
+WITH duplicates AS (
+ SELECT
+ id,
+ code,
+ "companyId",
+ ROW_NUMBER() OVER (PARTITION BY code, "companyId" ORDER BY id) as rn
+ FROM "materialType"
+ WHERE code IS NOT NULL
+)
+UPDATE "materialType" mt
+SET code = CONCAT(d.code, d.rn - 1)
+FROM duplicates d
+WHERE mt.id = d.id AND d.rn > 1;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20250724214245_make-material-codes-non-nullable.sql b/packages/database/supabase/migrations/20250724214245_make-material-codes-non-nullable.sql
new file mode 100644
index 0000000000..a6dfa3e666
--- /dev/null
+++ b/packages/database/supabase/migrations/20250724214245_make-material-codes-non-nullable.sql
@@ -0,0 +1,4 @@
+-- Make code columns non-nullable now that all records have codes
+ALTER TABLE "materialSubstance" ALTER COLUMN "code" SET NOT NULL;
+ALTER TABLE "materialForm" ALTER COLUMN "code" SET NOT NULL;
+ALTER TABLE "materialType" ALTER COLUMN "code" SET NOT NULL;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20250725140205_material-details.sql b/packages/database/supabase/migrations/20250725140205_material-details.sql
new file mode 100644
index 0000000000..fc5bfc452a
--- /dev/null
+++ b/packages/database/supabase/migrations/20250725140205_material-details.sql
@@ -0,0 +1,39 @@
+
+-- Update get_material_naming_details function to use new ID-based relationships
+DROP FUNCTION IF EXISTS get_material_naming_details;
+CREATE OR REPLACE FUNCTION get_material_naming_details(readable_id TEXT)
+RETURNS TABLE (
+ "id" TEXT,
+ "shape" TEXT,
+ "shapeCode" TEXT,
+ "substance" TEXT,
+ "substanceCode" TEXT,
+ "finish" TEXT,
+ "grade" TEXT,
+ "dimensions" TEXT,
+ "materialType" TEXT,
+ "materialTypeCode" TEXT
+
+) AS $$
+BEGIN
+ RETURN QUERY SELECT
+ "material"."id",
+ "materialForm"."name" AS "shape",
+ "materialForm"."code" AS "shapeCode",
+ "materialSubstance"."name" AS "substance",
+ "materialSubstance"."code" AS "substanceCode",
+ "materialFinish"."name" AS "finish",
+ "materialGrade"."name" AS "grade",
+ "materialDimension"."name" AS "dimensions",
+ "materialType"."name" AS "materialType",
+ "materialType"."code" AS "materialTypeCode"
+ FROM "material" LEFT JOIN "materialForm" ON "material"."materialFormId" = "materialForm"."id"
+ LEFT JOIN "materialSubstance" ON "material"."materialSubstanceId" = "materialSubstance"."id"
+ LEFT JOIN "materialFinish" ON "material"."finishId" = "materialFinish"."id"
+ LEFT JOIN "materialGrade" ON "material"."gradeId" = "materialGrade"."id"
+ LEFT JOIN "materialType" ON "material"."materialTypeId" = "materialType"."id"
+ LEFT JOIN "materialDimension" ON "material"."dimensionId" = "materialDimension"."id"
+ WHERE "material"."id" = readable_id;
+END;
+$$ LANGUAGE plpgsql STABLE;
+
diff --git a/packages/documents/src/pdf/PackingSlipPDF.tsx b/packages/documents/src/pdf/PackingSlipPDF.tsx
index 9bbe0349fa..93dd4cb05c 100644
--- a/packages/documents/src/pdf/PackingSlipPDF.tsx
+++ b/packages/documents/src/pdf/PackingSlipPDF.tsx
@@ -265,9 +265,6 @@ const PackingSlipPDF = ({
function getLineQuantity(
line: Database["public"]["Views"]["shipmentLines"]["Row"]
) {
- if (line.shippedQuantity === line.orderQuantity) {
- return `${line.shippedQuantity} ${line.unitOfMeasure}`;
- }
return `${line.shippedQuantity} / ${line.orderQuantity} ${line.unitOfMeasure}`;
}