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: material forms and substances

Brad Barbin17014efdb43a
diff --git a/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx b/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
index 5a6647f4a8..1176111815 100644
--- a/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
+++ b/apps/carbon/app/components/Search/DebouncedInput/DebouncedInput.tsx
@@ -1,6 +1,6 @@
import type { InputProps } from "@carbon/react";
import { Input, useDebounce } from "@carbon/react";
-import { useRef, useState } from "react";
+import { useState } from "react";
import { useUrlParams } from "~/hooks";
type DebounceInputProps = InputProps & {
@@ -8,15 +8,10 @@ type DebounceInputProps = InputProps & {
};
const DebouncedInput = ({ param, ...props }: DebounceInputProps) => {
- const initialLoad = useRef(true);
const [params, setParams] = useUrlParams();
const [query, setQuery] = useState(params.get(param) || "");
const debounceQuery = useDebounce((q: string) => {
- if (initialLoad.current) {
- initialLoad.current = false;
- } else {
- setParams({ [param]: q });
- }
+ setParams({ [param]: q });
}, 500);
return (
diff --git a/apps/carbon/app/components/Search/Search/Search.tsx b/apps/carbon/app/components/Search/Search/Search.tsx
index 8fb6c0a0be..17e78e8486 100644
--- a/apps/carbon/app/components/Search/Search/Search.tsx
+++ b/apps/carbon/app/components/Search/Search/Search.tsx
@@ -38,7 +38,7 @@ import { useAccountingSubmodules } from "~/modules/accounting";
import { useDocumentsSubmodules } from "~/modules/documents";
import { useInventorySubmodules } from "~/modules/inventory";
import { useInvoicingSubmodules } from "~/modules/invoicing";
-import { usePartsSubmodules } from "~/modules/items";
+import { useItemsSubmodules } from "~/modules/items";
import { usePurchasingSubmodules } from "~/modules/purchasing";
import { useResourcesSubmodules } from "~/modules/resources";
import { useSalesSubmodules } from "~/modules/sales";
@@ -296,7 +296,7 @@ const SearchButton = () => {
function useGroupedSubmodules() {
const modules = useModules();
- const parts = usePartsSubmodules();
+ const parts = useItemsSubmodules();
// const jobs = useJobsSidebar();
const inventory = useInventorySubmodules();
// const scheduling = useSchedulingSidebar();
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index 868da0ecd7..d1ab17b167 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -115,6 +115,16 @@ export const itemInventoryValidator = z.object({
defaultShelfId: zfd.text(z.string().optional()),
});
+export const materialFormValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }).max(255),
+});
+
+export const materialSubstanceValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }).max(255),
+});
+
export const partManufacturingValidator = z.object({
itemId: z.string().min(1, { message: "Item ID is required" }),
manufacturingPolicy: z.enum(partManufacturingPolicies, {
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index 38db4fd231..90914f84e5 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -14,6 +14,8 @@ import type {
itemSupplierValidator,
itemUnitSalePriceValidator,
itemValidator,
+ materialFormValidator,
+ materialSubstanceValidator,
partManufacturingValidator,
partValidator,
serviceValidator,
@@ -28,6 +30,20 @@ export async function deleteItemGroup(
return client.from("itemGroup").delete().eq("id", id);
}
+export async function deleteMaterialForm(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("materialForm").delete().eq("id", id);
+}
+
+export async function deleteMaterialSubstance(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("materialSubstance").delete().eq("id", id);
+}
+
export async function deleteUnitOfMeasure(
client: SupabaseClient<Database>,
id: string
@@ -147,6 +163,92 @@ export async function getItemReplenishment(
.single();
}
+export async function getMaterialForm(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("materialForm").select("*").eq("id", id).single();
+}
+
+export async function getMaterialForms(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { search: string | null }
+) {
+ let query = client
+ .from("materialForm")
+ .select("*", {
+ count: "exact",
+ })
+ .or(`companyId.eq.${companyId},companyId.is.null`);
+
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "name", ascending: true },
+ ]);
+ }
+
+ return query;
+}
+
+export async function getMaterialFormsList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("materialForm")
+ .select("id, name")
+ .or(`companyId.eq.${companyId},companyId.is.null`)
+ .order("name");
+}
+
+export async function getMaterialSubstance(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("materialSubstance").select("*").eq("id", id).single();
+}
+
+export async function getMaterialSubstances(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { search: string | null }
+) {
+ let query = client
+ .from("materialSubstance")
+ .select("*", {
+ count: "exact",
+ })
+ .or(`companyId.eq.${companyId},companyId.is.null`);
+
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "name", ascending: true },
+ ]);
+ }
+
+ return query;
+}
+
+export async function getMaterialSubstancesList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("materialSubstance")
+ .select("id, name")
+ .or(`companyId.eq.${companyId},companyId.is.null`)
+ .order("name");
+}
+
export async function getParts(
client: SupabaseClient<Database>,
companyId: string,
@@ -680,6 +782,70 @@ export async function upsertItemUnitSalePrice(
.eq("itemId", itemUnitSalePrice.itemId);
}
+export async function upsertMaterialForm(
+ client: SupabaseClient<Database>,
+ materialForm:
+ | (Omit<z.infer<typeof materialFormValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof materialFormValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in materialForm) {
+ return client
+ .from("materialForm")
+ .insert([materialForm])
+ .select("*")
+ .single();
+ }
+ return (
+ client
+ .from("materialForm")
+ .update(sanitize(materialForm))
+ // @ts-ignore
+ .eq("id", materialForm.id)
+ .select("id")
+ .single()
+ );
+}
+
+export async function upsertMaterialSubstance(
+ client: SupabaseClient<Database>,
+ materialSubstance:
+ | (Omit<z.infer<typeof materialSubstanceValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof materialSubstanceValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in materialSubstance) {
+ return client
+ .from("materialSubstance")
+ .insert([materialSubstance])
+ .select("*")
+ .single();
+ }
+ return (
+ client
+ .from("materialSubstance")
+ .update(sanitize(materialSubstance))
+ // @ts-ignore
+ .eq("id", materialSubstance.id)
+ .select("id")
+ .single()
+ );
+}
+
export async function upsertService(
client: SupabaseClient<Database>,
service:
diff --git a/apps/carbon/app/modules/items/types.ts b/apps/carbon/app/modules/items/types.ts
index 221770096a..921b550887 100644
--- a/apps/carbon/app/modules/items/types.ts
+++ b/apps/carbon/app/modules/items/types.ts
@@ -5,6 +5,8 @@ import type {
getItemGroupsList,
getItemQuantities,
getItemSuppliers,
+ getMaterialForms,
+ getMaterialSubstances,
getPart,
getParts,
getServices,
@@ -16,7 +18,7 @@ export type ItemCost = NonNullable<
Awaited<ReturnType<typeof getItemCost>>
>["data"];
-export type PartCostingMethod =
+export type ItemCostingMethod =
Database["public"]["Enums"]["itemCostingMethod"];
export type ItemGroup = NonNullable<
@@ -45,6 +47,17 @@ export type ItemSupplier = NonNullable<
Awaited<ReturnType<typeof getItemSuppliers>>["data"]
>[number];
+export type InventoryItemType =
+ Database["public"]["Enums"]["itemInventoryType"];
+
+export type MaterialForm = NonNullable<
+ Awaited<ReturnType<typeof getMaterialForms>>["data"]
+>[number];
+
+export type MaterialSubstance = NonNullable<
+ Awaited<ReturnType<typeof getMaterialSubstances>>["data"]
+>[number];
+
export type PartManufacturingPolicy =
Database["public"]["Enums"]["partManufacturingPolicy"];
@@ -52,8 +65,6 @@ export type Part = NonNullable<
Awaited<ReturnType<typeof getParts>>["data"]
>[number];
-export type PartType = Database["public"]["Enums"]["itemInventoryType"];
-
export type Service = NonNullable<
Awaited<ReturnType<typeof getServices>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemCostingForm.tsx b/apps/carbon/app/modules/items/ui/Item/ItemCostingForm.tsx
index 2173c43164..eeb06aee83 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemCostingForm.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemCostingForm.tsx
@@ -27,7 +27,7 @@ const currency = "USD"; // TODO: get from settings
const ItemCostingForm = ({ initialValues }: ItemCostingFormProps) => {
const permissions = usePermissions();
- const [partCostingMethod, setPartCostingMethod] = useState<string>(
+ const [partCostingMethod, setItemCostingMethod] = useState<string>(
initialValues.costingMethod
);
@@ -56,7 +56,7 @@ const ItemCostingForm = ({ initialValues }: ItemCostingFormProps) => {
label="Part Costing Method"
options={partCostingMethodOptions}
onChange={(newValue) => {
- if (newValue) setPartCostingMethod(newValue.value);
+ if (newValue) setItemCostingMethod(newValue.value);
}}
/>
<Number
diff --git a/apps/carbon/app/modules/items/ui/MaterialForms/MaterialFormForm.tsx b/apps/carbon/app/modules/items/ui/MaterialForms/MaterialFormForm.tsx
new file mode 100644
index 0000000000..e2c7166f20
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/MaterialForms/MaterialFormForm.tsx
@@ -0,0 +1,107 @@
+import {
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ VStack,
+ toast,
+} from "@carbon/react";
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useFetcher } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect } from "react";
+import type { z } from "zod";
+import { CustomFormFields, Hidden, Input, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { materialFormValidator } from "~/modules/items";
+import { path } from "~/utils/path";
+
+type MaterialFormFormProps = {
+ initialValues: z.infer<typeof materialFormValidator>;
+ type?: "modal" | "drawer";
+ open?: boolean;
+ onClose: (data?: { id: string; name: string }) => void;
+};
+
+const MaterialFormForm = ({
+ initialValues,
+ open = true,
+ type = "drawer",
+ onClose,
+}: MaterialFormFormProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<PostgrestResponse<{ id: string; name: string }>>();
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "parts")
+ : !permissions.can("create", "parts");
+
+ useEffect(() => {
+ if (type !== "modal") return;
+
+ if (fetcher.state === "loading" && fetcher.data?.data) {
+ onClose?.();
+ toast.success(`Created material form`);
+ } else if (fetcher.state === "idle" && fetcher.data?.error) {
+ toast.error(
+ `Failed to create material form: ${fetcher.data.error.message}`
+ );
+ }
+ }, [fetcher.data, fetcher.state, onClose, type]);
+
+ return (
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={materialFormValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.materialForm(initialValues.id!)
+ : path.to.newMaterialForm
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Material Form
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <CustomFormFields table="materialForm" />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={() => onClose()}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default MaterialFormForm;
diff --git a/apps/carbon/app/modules/items/ui/MaterialForms/MaterialFormsTable.tsx b/apps/carbon/app/modules/items/ui/MaterialForms/MaterialFormsTable.tsx
new file mode 100644
index 0000000000..8552e828cf
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/MaterialForms/MaterialFormsTable.tsx
@@ -0,0 +1,106 @@
+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 { LuPencil, LuTrash } from "react-icons/lu";
+import { Hyperlink, New, Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import { useCustomColumns } from "~/hooks/useCustomColumns";
+import type { MaterialForm } from "~/modules/items";
+import { path } from "~/utils/path";
+
+type MaterialFormsTableProps = {
+ data: MaterialForm[];
+ count: number;
+};
+
+const MaterialFormsTable = memo(({ data, count }: MaterialFormsTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const rows = useMemo(() => data, [data]);
+ const customColumns = useCustomColumns<MaterialForm>("materialForm");
+
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
+ const defaultColumns: ColumnDef<(typeof rows)[number]>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <Hyperlink
+ to={`${path.to.materialForm(row.original.id)}?${params.toString()}`}
+ >
+ {row.original.name}
+ </Hyperlink>
+ ),
+ },
+ {
+ header: "Type",
+ cell: ({ row }) =>
+ row.original.companyId === null ? (
+ <Badge className="border-dashed" variant="outline">
+ Global
+ </Badge>
+ ) : (
+ <Badge>Company</Badge>
+ ),
+ },
+ ];
+ return [...defaultColumns, ...customColumns];
+ }, [params, customColumns]);
+
+ const renderContextMenu = useCallback(
+ (row: (typeof rows)[number]) => {
+ return (
+ <>
+ <MenuItem
+ disabled={
+ !permissions.can("update", "parts") || row.companyId === null
+ }
+ onClick={() => {
+ navigate(`${path.to.materialForm(row.id)}?${params.toString()}`);
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Material Form
+ </MenuItem>
+ <MenuItem
+ disabled={
+ !permissions.can("delete", "parts") || row.companyId === null
+ }
+ onClick={() => {
+ navigate(
+ `${path.to.deleteMaterialForm(row.id)}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Material Form
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<(typeof rows)[number]>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={
+ permissions.can("create", "parts") && (
+ <New
+ label="Material Form"
+ to={`${path.to.newMaterialForm}?${params.toString()}`}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ />
+ );
+});
+
+MaterialFormsTable.displayName = "MaterialFormsTable";
+export default MaterialFormsTable;
diff --git a/apps/carbon/app/modules/items/ui/MaterialForms/index.ts b/apps/carbon/app/modules/items/ui/MaterialForms/index.ts
new file mode 100644
index 0000000000..bb058c52d1
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/MaterialForms/index.ts
@@ -0,0 +1,4 @@
+import MaterialFormForm from "./MaterialFormForm";
+import MaterialFormsTable from "./MaterialFormsTable";
+
+export { MaterialFormForm, MaterialFormsTable };
diff --git a/apps/carbon/app/modules/items/ui/MaterialSubstances/MaterialSubstanceForm.tsx b/apps/carbon/app/modules/items/ui/MaterialSubstances/MaterialSubstanceForm.tsx
new file mode 100644
index 0000000000..94f295a22a
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/MaterialSubstances/MaterialSubstanceForm.tsx
@@ -0,0 +1,109 @@
+import {
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ VStack,
+ toast,
+} from "@carbon/react";
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useFetcher } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect } from "react";
+import type { z } from "zod";
+import { CustomFormFields, Hidden, Input, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { materialSubstanceValidator } from "~/modules/items";
+import { path } from "~/utils/path";
+
+type MaterialSubstanceFormProps = {
+ initialValues: z.infer<typeof materialSubstanceValidator>;
+ type?: "modal" | "drawer";
+ open?: boolean;
+ onClose: (data?: { id: string; name: string }) => void;
+};
+
+const MaterialSubstanceForm = ({
+ initialValues,
+ open = true,
+ type = "drawer",
+ onClose,
+}: MaterialSubstanceFormProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<PostgrestResponse<{ id: string; name: string }>>();
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "parts")
+ : !permissions.can("create", "parts");
+
+ useEffect(() => {
+ if (type !== "modal") return;
+
+ if (fetcher.state === "loading" && fetcher.data?.data) {
+ onClose?.();
+ toast.success(`Created material form`);
+ } else if (fetcher.state === "idle" && fetcher.data?.error) {
+ toast.error(
+ `Failed to create material form: ${fetcher.data.error.message}`
+ );
+ }
+ }, [fetcher.data, fetcher.state, onClose, type]);
+
+ console.log(isEditing);
+
+ return (
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={materialSubstanceValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.materialSubstance(initialValues.id!)
+ : path.to.newMaterialSubstance
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Material Substance
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <VStack spacing={4}>
+ <Input name="name" label="Name" />
+ <CustomFormFields table="materialSubstance" />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={() => onClose()}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default MaterialSubstanceForm;
diff --git a/apps/carbon/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx b/apps/carbon/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
new file mode 100644
index 0000000000..d01549acf6
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
@@ -0,0 +1,115 @@
+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 { LuPencil, LuTrash } from "react-icons/lu";
+import { Hyperlink, New, Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import { useCustomColumns } from "~/hooks/useCustomColumns";
+import type { MaterialSubstance } from "~/modules/items";
+import { path } from "~/utils/path";
+
+type MaterialSubstancesTableProps = {
+ data: MaterialSubstance[];
+ count: number;
+};
+
+const MaterialSubstancesTable = memo(
+ ({ data, count }: MaterialSubstancesTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const rows = useMemo(() => data, [data]);
+ const customColumns =
+ useCustomColumns<MaterialSubstance>("materialSubstance");
+
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
+ const defaultColumns: ColumnDef<(typeof rows)[number]>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <Hyperlink
+ to={`${path.to.materialSubstance(
+ row.original.id
+ )}?${params.toString()}`}
+ >
+ {row.original.name}
+ </Hyperlink>
+ ),
+ },
+ {
+ header: "Type",
+ cell: ({ row }) =>
+ row.original.companyId === null ? (
+ <Badge className="border-dashed" variant="outline">
+ Global
+ </Badge>
+ ) : (
+ <Badge>Company</Badge>
+ ),
+ },
+ ];
+ return [...defaultColumns, ...customColumns];
+ }, [params, customColumns]);
+
+ const renderContextMenu = useCallback(
+ (row: (typeof rows)[number]) => {
+ return (
+ <>
+ <MenuItem
+ disabled={
+ !permissions.can("update", "parts") || row.companyId === null
+ }
+ onClick={() => {
+ navigate(
+ `${path.to.materialSubstance(row.id)}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Substance
+ </MenuItem>
+ <MenuItem
+ disabled={
+ !permissions.can("delete", "parts") || row.companyId === null
+ }
+ onClick={() => {
+ navigate(
+ `${path.to.deleteMaterialSubstance(
+ row.id
+ )}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Substance
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<(typeof rows)[number]>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={
+ permissions.can("create", "parts") && (
+ <New
+ label="Material Substance"
+ to={`${path.to.newMaterialSubstance}?${params.toString()}`}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ />
+ );
+ }
+);
+
+MaterialSubstancesTable.displayName = "MaterialSubstancesTable";
+export default MaterialSubstancesTable;
diff --git a/apps/carbon/app/modules/items/ui/MaterialSubstances/index.ts b/apps/carbon/app/modules/items/ui/MaterialSubstances/index.ts
new file mode 100644
index 0000000000..de0079db82
--- /dev/null
+++ b/apps/carbon/app/modules/items/ui/MaterialSubstances/index.ts
@@ -0,0 +1,4 @@
+import MaterialSubstanceForm from "./MaterialSubstanceForm";
+import MaterialSubstancesTable from "./MaterialSubstanceTable";
+
+export { MaterialSubstanceForm, MaterialSubstancesTable };
diff --git a/apps/carbon/app/modules/items/ui/index.ts b/apps/carbon/app/modules/items/ui/index.ts
index 5494d77158..d72bebd7a0 100644
--- a/apps/carbon/app/modules/items/ui/index.ts
+++ b/apps/carbon/app/modules/items/ui/index.ts
@@ -1,11 +1,13 @@
-import usePartsSubmodules from "./usePartsSubmodules";
+import useItemsSubmodules from "./useItemsSubmodules";
export * from "./Item";
export * from "./ItemGroups";
+export * from "./MaterialForms";
+export * from "./MaterialSubstances";
export * from "./Part";
export * from "./Parts";
export * from "./Routing";
export * from "./Service";
export * from "./Services";
export * from "./UnitOfMeasure";
-export { usePartsSubmodules };
+export { useItemsSubmodules };
diff --git a/apps/carbon/app/modules/items/ui/usePartsSubmodules.tsx b/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
similarity index 69%
rename from apps/carbon/app/modules/items/ui/usePartsSubmodules.tsx
rename to apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
index a50febae5c..3fa76c2e84 100644
--- a/apps/carbon/app/modules/items/ui/usePartsSubmodules.tsx
+++ b/apps/carbon/app/modules/items/ui/useItemsSubmodules.tsx
@@ -2,7 +2,7 @@ import { usePermissions } from "~/hooks";
import type { AuthenticatedRouteGroup } from "~/types";
import { path } from "~/utils/path";
-const partsRoutes: AuthenticatedRouteGroup[] = [
+const itemsRoutes: AuthenticatedRouteGroup[] = [
{
name: "Manage",
routes: [
@@ -10,6 +10,22 @@ const partsRoutes: AuthenticatedRouteGroup[] = [
name: "Parts",
to: path.to.parts,
},
+ {
+ name: "Materials",
+ to: path.to.materials,
+ },
+ {
+ name: "Tools",
+ to: path.to.tools,
+ },
+ {
+ name: "Fixtures",
+ to: path.to.fixtures,
+ },
+ {
+ name: "Consumables",
+ to: path.to.consumables,
+ },
{
name: "Services",
to: path.to.services,
@@ -24,6 +40,14 @@ const partsRoutes: AuthenticatedRouteGroup[] = [
{
name: "Configure",
routes: [
+ {
+ name: "Forms",
+ to: path.to.materialForms,
+ },
+ {
+ name: "Substances",
+ to: path.to.materialSubstances,
+ },
{
name: "Posting Groups",
to: path.to.itemGroups,
@@ -38,10 +62,10 @@ const partsRoutes: AuthenticatedRouteGroup[] = [
},
];
-export default function usePartsSubmodules() {
+export default function useItemsSubmodules() {
const permissions = usePermissions();
return {
- groups: partsRoutes
+ groups: itemsRoutes
.filter((group) => {
const filteredRoutes = group.routes.filter((route) => {
if (route.role) {
diff --git a/apps/carbon/app/modules/settings/settings.models.ts b/apps/carbon/app/modules/settings/settings.models.ts
index d37fc61248..21279685f6 100644
--- a/apps/carbon/app/modules/settings/settings.models.ts
+++ b/apps/carbon/app/modules/settings/settings.models.ts
@@ -7,9 +7,9 @@ export const modulesType = [
// "Documents",
"Invoicing",
"Inventory",
+ "Items",
"Jobs",
// "Messaging",
- "Parts",
"Purchasing",
"Resources",
"Sales",
diff --git a/apps/carbon/app/routes/x+/items+/_layout.tsx b/apps/carbon/app/routes/x+/items+/_layout.tsx
index 3f7c986010..24bcfefa24 100644
--- a/apps/carbon/app/routes/x+/items+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/items+/_layout.tsx
@@ -2,7 +2,7 @@ import { VStack } from "@carbon/react";
import type { MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout";
-import { usePartsSubmodules } from "~/modules/items";
+import { useItemsSubmodules } from "~/modules/items";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -17,7 +17,7 @@ export const handle: Handle = {
};
export default function PartsRoute() {
- const { groups } = usePartsSubmodules();
+ const { groups } = useItemsSubmodules();
return (
<div className="grid grid-cols-[auto_1fr] w-full h-full">
diff --git a/apps/carbon/app/routes/x+/items+/forms.$formId.tsx b/apps/carbon/app/routes/x+/items+/forms.$formId.tsx
new file mode 100644
index 0000000000..a7c5d192f6
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/forms.$formId.tsx
@@ -0,0 +1,90 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate } from "@remix-run/react";
+import {
+ MaterialFormForm,
+ getMaterialForm,
+ materialFormValidator,
+ upsertMaterialForm,
+} from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { assertIsPost, notFound } from "~/utils/http";
+import { getParams, path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "parts",
+ role: "employee",
+ });
+
+ const { formId } = params;
+ if (!formId) throw notFound("formId not found");
+
+ const materialForm = await getMaterialForm(client, formId);
+
+ return json({
+ materialForm: materialForm?.data ?? null,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { formId } = params;
+ if (!formId) throw new Error("Could not find formId");
+
+ const formData = await request.formData();
+ const validation = await validator(materialFormValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateMaterialForm = await upsertMaterialForm(client, {
+ id: formId,
+ ...validation.data,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (updateMaterialForm.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateMaterialForm.error, "Failed to update material form")
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.materialForms}?${getParams(request)}`,
+ await flash(request, success("Updated material form"))
+ );
+}
+
+export default function EditMaterialFormsRoute() {
+ const { materialForm } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const initialValues = {
+ id: materialForm?.id ?? undefined,
+ name: materialForm?.name ?? "",
+ ...getCustomFields(materialForm?.customFields),
+ };
+
+ return (
+ <MaterialFormForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/forms.delete.$formId.tsx b/apps/carbon/app/routes/x+/items+/forms.delete.$formId.tsx
new file mode 100644
index 0000000000..a97109a8aa
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/forms.delete.$formId.tsx
@@ -0,0 +1,82 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteMaterialForm, getMaterialForm } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { notFound } from "~/utils/http";
+import { getParams, path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "parts",
+ });
+ const { formId } = params;
+ if (!formId) throw notFound("formId not found");
+
+ const materialForm = await getMaterialForm(client, formId);
+ if (materialForm.error) {
+ throw redirect(
+ path.to.materialForms,
+ await flash(
+ request,
+ error(materialForm.error, "Failed to get material form")
+ )
+ );
+ }
+
+ return json({ materialForm: materialForm.data });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "parts",
+ });
+
+ const { formId } = params;
+ if (!formId) {
+ throw redirect(
+ path.to.materialForms,
+ await flash(request, error(params, "Failed to get an material form id"))
+ );
+ }
+
+ const { error: deleteTypeError } = await deleteMaterialForm(client, formId);
+ if (deleteTypeError) {
+ throw redirect(
+ `${path.to.materialForms}?${getParams(request)}`,
+ await flash(
+ request,
+ error(deleteTypeError, "Failed to delete material form")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.materialForms,
+ await flash(request, success("Successfully deleted material form"))
+ );
+}
+
+export default function DeleteMaterialFormRoute() {
+ const { formId } = useParams();
+ if (!formId) throw new Error("formId not found");
+
+ const { materialForm } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!materialForm) return null;
+
+ const onCancel = () => navigate(-1);
+
+ return (
+ <ConfirmDelete
+ action={path.to.deleteMaterialForm(formId)}
+ name={materialForm.name}
+ text={`Are you sure you want to delete the material form: ${materialForm.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/forms.new.tsx b/apps/carbon/app/routes/x+/items+/forms.new.tsx
new file mode 100644
index 0000000000..3b25736ee1
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/forms.new.tsx
@@ -0,0 +1,90 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useNavigate } from "@remix-run/react";
+import {
+ MaterialFormForm,
+ materialFormValidator,
+ upsertMaterialForm,
+} from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { getParams, path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ create: "parts",
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "parts",
+ });
+
+ const formData = await request.formData();
+ const modal = formData.get("type") == "modal";
+
+ const validation = await validator(materialFormValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const insertMaterialForm = await upsertMaterialForm(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (insertMaterialForm.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertMaterialForm.error, "Failed to insert material form")
+ )
+ );
+ }
+
+ const materialFormId = insertMaterialForm.data?.id;
+ if (!materialFormId) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertMaterialForm, "Failed to insert material form")
+ )
+ );
+ }
+
+ return modal
+ ? json(insertMaterialForm, { status: 201 })
+ : redirect(
+ `${path.to.materialForms}?${getParams(request)}`,
+ await flash(request, success("Material form created"))
+ );
+}
+
+export default function NewMaterialFormsRoute() {
+ const navigate = useNavigate();
+ const initialValues = {
+ name: "",
+ description: "",
+ };
+
+ return (
+ <MaterialFormForm
+ onClose={() => navigate(-1)}
+ initialValues={initialValues}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/forms.tsx b/apps/carbon/app/routes/x+/items+/forms.tsx
new file mode 100644
index 0000000000..2f2a829671
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/forms.tsx
@@ -0,0 +1,62 @@
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import { MaterialFormsTable, getMaterialForms } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export const handle: Handle = {
+ breadcrumb: "Forms",
+ to: path.to.materialForms,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [materialForms] = await Promise.all([
+ getMaterialForms(client, companyId, {
+ limit,
+ offset,
+ sorts,
+ search,
+ filters,
+ }),
+ ]);
+
+ if (materialForms.error) {
+ throw redirect(
+ path.to.items,
+ await flash(request, error(null, "Error loading material forms"))
+ );
+ }
+
+ return json({
+ materialForms: materialForms.data ?? [],
+ count: materialForms.count ?? 0,
+ });
+}
+
+export default function MaterialFormsRoute() {
+ const { materialForms, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <MaterialFormsTable data={materialForms} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/groups.new.tsx b/apps/carbon/app/routes/x+/items+/groups.new.tsx
index a2da270e04..80227ac751 100644
--- a/apps/carbon/app/routes/x+/items+/groups.new.tsx
+++ b/apps/carbon/app/routes/x+/items+/groups.new.tsx
@@ -70,7 +70,7 @@ export async function action({ request }: ActionFunctionArgs) {
? json(insertItemGroup, { status: 201 })
: redirect(
`${path.to.itemGroups}?${getParams(request)}`,
- await flash(request, success("Part group created"))
+ await flash(request, success("Item posting group created"))
);
}
diff --git a/apps/carbon/app/routes/x+/items+/substances.$substanceId.tsx b/apps/carbon/app/routes/x+/items+/substances.$substanceId.tsx
new file mode 100644
index 0000000000..3621672957
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/substances.$substanceId.tsx
@@ -0,0 +1,95 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate } from "@remix-run/react";
+import {
+ MaterialSubstanceForm,
+ getMaterialSubstance,
+ materialSubstanceValidator,
+ upsertMaterialSubstance,
+} from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { assertIsPost, notFound } from "~/utils/http";
+import { getParams, path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "parts",
+ role: "employee",
+ });
+
+ const { substanceId } = params;
+ if (!substanceId) throw notFound("substanceId not found");
+
+ const materialSubstance = await getMaterialSubstance(client, substanceId);
+
+ return json({
+ materialSubstance: materialSubstance?.data ?? null,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const { substanceId } = params;
+ if (!substanceId) throw new Error("Could not find substanceId");
+
+ const formData = await request.formData();
+ const validation = await validator(materialSubstanceValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateMaterialSubstance = await upsertMaterialSubstance(client, {
+ id: substanceId,
+ ...validation.data,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (updateMaterialSubstance.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(
+ updateMaterialSubstance.error,
+ "Failed to update material substance"
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.materialSubstances}?${getParams(request)}`,
+ await flash(request, success("Updated material substance"))
+ );
+}
+
+export default function EditMaterialSubstancesRoute() {
+ const { materialSubstance } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const initialValues = {
+ id: materialSubstance?.id ?? undefined,
+ name: materialSubstance?.name ?? "",
+ ...getCustomFields(materialSubstance?.customFields),
+ };
+
+ return (
+ <MaterialSubstanceForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/substances.delete.$substanceId.tsx b/apps/carbon/app/routes/x+/items+/substances.delete.$substanceId.tsx
new file mode 100644
index 0000000000..a97109a8aa
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/substances.delete.$substanceId.tsx
@@ -0,0 +1,82 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteMaterialForm, getMaterialForm } from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { notFound } from "~/utils/http";
+import { getParams, path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "parts",
+ });
+ const { formId } = params;
+ if (!formId) throw notFound("formId not found");
+
+ const materialForm = await getMaterialForm(client, formId);
+ if (materialForm.error) {
+ throw redirect(
+ path.to.materialForms,
+ await flash(
+ request,
+ error(materialForm.error, "Failed to get material form")
+ )
+ );
+ }
+
+ return json({ materialForm: materialForm.data });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "parts",
+ });
+
+ const { formId } = params;
+ if (!formId) {
+ throw redirect(
+ path.to.materialForms,
+ await flash(request, error(params, "Failed to get an material form id"))
+ );
+ }
+
+ const { error: deleteTypeError } = await deleteMaterialForm(client, formId);
+ if (deleteTypeError) {
+ throw redirect(
+ `${path.to.materialForms}?${getParams(request)}`,
+ await flash(
+ request,
+ error(deleteTypeError, "Failed to delete material form")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.materialForms,
+ await flash(request, success("Successfully deleted material form"))
+ );
+}
+
+export default function DeleteMaterialFormRoute() {
+ const { formId } = useParams();
+ if (!formId) throw new Error("formId not found");
+
+ const { materialForm } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!materialForm) return null;
+
+ const onCancel = () => navigate(-1);
+
+ return (
+ <ConfirmDelete
+ action={path.to.deleteMaterialForm(formId)}
+ name={materialForm.name}
+ text={`Are you sure you want to delete the material form: ${materialForm.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/substances.new.tsx b/apps/carbon/app/routes/x+/items+/substances.new.tsx
new file mode 100644
index 0000000000..9f780068a3
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/substances.new.tsx
@@ -0,0 +1,95 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useNavigate } from "@remix-run/react";
+import {
+ MaterialSubstanceForm,
+ materialSubstanceValidator,
+ upsertMaterialSubstance,
+} from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { getParams, path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ create: "parts",
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "parts",
+ });
+
+ const formData = await request.formData();
+ const modal = formData.get("type") == "modal";
+
+ const validation = await validator(materialSubstanceValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const insertMaterialSubstance = await upsertMaterialSubstance(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (insertMaterialSubstance.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(
+ insertMaterialSubstance.error,
+ "Failed to insert material substance"
+ )
+ )
+ );
+ }
+
+ const materialSubstanceId = insertMaterialSubstance.data?.id;
+ if (!materialSubstanceId) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertMaterialSubstance, "Failed to insert material substance")
+ )
+ );
+ }
+
+ return modal
+ ? json(insertMaterialSubstance, { status: 201 })
+ : redirect(
+ `${path.to.materialSubstances}?${getParams(request)}`,
+ await flash(request, success("Part group created"))
+ );
+}
+
+export default function NewMaterialSubstancesRoute() {
+ const navigate = useNavigate();
+ const initialValues = {
+ name: "",
+ description: "",
+ };
+
+ return (
+ <MaterialSubstanceForm
+ onClose={() => navigate(-1)}
+ initialValues={initialValues}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/substances.tsx b/apps/carbon/app/routes/x+/items+/substances.tsx
new file mode 100644
index 0000000000..31995e1969
--- /dev/null
+++ b/apps/carbon/app/routes/x+/items+/substances.tsx
@@ -0,0 +1,65 @@
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ MaterialSubstancesTable,
+ getMaterialSubstances,
+} from "~/modules/items";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export const handle: Handle = {
+ breadcrumb: "Substances",
+ to: path.to.materialSubstances,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [materialSubstances] = await Promise.all([
+ getMaterialSubstances(client, companyId, {
+ limit,
+ offset,
+ sorts,
+ search,
+ filters,
+ }),
+ ]);
+
+ if (materialSubstances.error) {
+ throw redirect(
+ path.to.items,
+ await flash(request, error(null, "Error loading material substances"))
+ );
+ }
+
+ return json({
+ materialSubstances: materialSubstances.data ?? [],
+ count: materialSubstances.count ?? 0,
+ });
+}
+
+export default function MaterialSubstancesRoute() {
+ const { materialSubstances, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <MaterialSubstancesTable data={materialSubstances} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index ce81fdb37b..10470bc990 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -106,6 +106,7 @@ export const path = {
contractor: (id: string) =>
generatePath(`${x}/resources/contractors/${id}`),
contractors: `${x}/resources/contractors`,
+ consumables: `${x}/items/consumables`,
convertQuoteToOrder: (id: string) =>
generatePath(`${x}/quote/${id}/convert-to-order`),
currency: (id: string) => generatePath(`${x}/accounting/currencies/${id}`),
@@ -185,6 +186,10 @@ export const path = {
deleteNote: (id: string) => generatePath(`${x}/shared/notes/${id}/delete`),
deleteItemGroup: (id: string) =>
generatePath(`${x}/items/groups/delete/${id}`),
+ deleteMaterialForm: (id: string) =>
+ generatePath(`${x}/items/forms/delete/${id}`),
+ deleteMaterialSubstance: (id: string) =>
+ generatePath(`${x}/items/substances/delete/${id}`),
deletePartner: (id: string) =>
generatePath(`${x}/resources/partners/delete/${id}`),
deletePaymentTerm: (id: string) =>
@@ -260,6 +265,7 @@ export const path = {
equipmentUnit: (id: string) =>
generatePath(`${x}/resources/equipment/unit/${id}`),
fiscalYears: `${x}/accounting/years`,
+ fixtures: `${x}/items/fixtures`,
forgotPassword: "/forgot-password",
group: (id: string) => generatePath(`${x}/users/groups/${id}`),
groups: `${x}/users/groups`,
@@ -276,6 +282,12 @@ export const path = {
locations: `${x}/resources/locations`,
login: "/login",
logout: "/logout",
+ materials: `${x}/items/materials`,
+ materialForm: (id: string) => generatePath(`${x}/items/forms/${id}`),
+ materialForms: `${x}/items/forms`,
+ materialSubstance: (id: string) =>
+ generatePath(`${x}/items/substances/${id}`),
+ materialSubstances: `${x}/items/substances`,
messaging: `${x}/messaging`,
newAbility: `${x}/resources/abilities/new`,
newAccountingCategory: `${x}/accounting/categories/new`,
@@ -315,6 +327,8 @@ export const path = {
newNote: `${x}/shared/notes/new`,
newPart: `${x}/part/new`,
newItemGroup: `${x}/items/groups/new`,
+ newMaterialForm: `${x}/items/forms/new`,
+ newMaterialSubstance: `${x}/items/substances/new`,
newPartSupplier: (id: string) =>
generatePath(`${x}/part/${id}/suppliers/new`),
newPartner: `${x}/resources/partners/new`,
@@ -388,7 +402,6 @@ export const path = {
partSupplier: (itemId: string, id: string) =>
generatePath(`${x}/part/${itemId}/suppliers/${id}`),
partSuppliers: (id: string) => generatePath(`${x}/part/${id}/suppliers`),
-
parts: `${x}/items/parts`,
partner: (id: string, abilityId: string) =>
generatePath(`${x}/resources/partners/${id}/${abilityId}`),
@@ -543,6 +556,7 @@ export const path = {
generatePath(`${x}/settings/sequences/${id}`),
theme: `${x}/account/theme`,
timecards: `${x}/timecards`,
+ tools: `${x}/items/tools`,
uom: (id: string) => generatePath(`${x}/items/uom/${id}`),
uoms: `${x}/items/uom`,
userAttribute: (id: string) => generatePath(`${x}/account/${id}/attribute`),
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index a0d01adeba..b5c1b2e690 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -7709,8 +7709,8 @@ export type Database = {
grade: string | null
id: string
itemId: string | null
- materialFormId: number
- materialSubstanceId: number
+ materialFormId: string
+ materialSubstanceId: string
unitOfMeasureCode: string
updatedAt: string | null
updatedBy: string | null
@@ -7727,8 +7727,8 @@ export type Database = {
grade?: string | null
id: string
itemId?: string | null
- materialFormId: number
- materialSubstanceId: number
+ materialFormId: string
+ materialSubstanceId: string
unitOfMeasureCode: string
updatedAt?: string | null
updatedBy?: string | null
@@ -7745,8 +7745,8 @@ export type Database = {
grade?: string | null
id?: string
itemId?: string | null
- materialFormId?: number
- materialSubstanceId?: number
+ materialFormId?: string
+ materialSubstanceId?: string
unitOfMeasureCode?: string
updatedAt?: string | null
updatedBy?: string | null
@@ -7927,7 +7927,8 @@ export type Database = {
companyId: string | null
createdAt: string
createdBy: string
- id: number
+ customFields: Json | null
+ id: string
name: string
updatedAt: string | null
updatedBy: string | null
@@ -7936,7 +7937,8 @@ export type Database = {
companyId?: string | null
createdAt?: string
createdBy: string
- id?: number
+ customFields?: Json | null
+ id?: string
name: string
updatedAt?: string | null
updatedBy?: string | null
@@ -7945,7 +7947,8 @@ export type Database = {
companyId?: string | null
createdAt?: string
createdBy?: string
- id?: number
+ customFields?: Json | null
+ id?: string
name?: string
updatedAt?: string | null
updatedBy?: string | null
@@ -8056,7 +8059,8 @@ export type Database = {
companyId: string | null
createdAt: string
createdBy: string
- id: number
+ customFields: Json | null
+ id: string
name: string
updatedAt: string | null
updatedBy: string | null
@@ -8065,7 +8069,8 @@ export type Database = {
companyId?: string | null
createdAt?: string
createdBy: string
- id?: number
+ customFields?: Json | null
+ id?: string
name: string
updatedAt?: string | null
updatedBy?: string | null
@@ -8074,7 +8079,8 @@ export type Database = {
companyId?: string | null
createdAt?: string
createdBy?: string
- id?: number
+ customFields?: Json | null
+ id?: string
name?: string
updatedAt?: string | null
updatedBy?: string | null
@@ -20912,9 +20918,9 @@ export type Database = {
| Database["public"]["Enums"]["itemInventoryType"]
| null
materialForm: string | null
- materialFormId: number | null
+ materialFormId: string | null
materialSubstance: string | null
- materialSubstanceId: number | null
+ materialSubstanceId: string | null
name: string | null
supplierIds: string[] | null
unitOfMeasure: string | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index a0d01adeba..b5c1b2e690 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -7709,8 +7709,8 @@ export type Database = {
grade: string | null
id: string
itemId: string | null
- materialFormId: number
- materialSubstanceId: number
+ materialFormId: string
+ materialSubstanceId: string
unitOfMeasureCode: string
updatedAt: string | null
updatedBy: string | null
@@ -7727,8 +7727,8 @@ export type Database = {
grade?: string | null
id: string
itemId?: string | null
- materialFormId: number
- materialSubstanceId: number
+ materialFormId: string
+ materialSubstanceId: string
unitOfMeasureCode: string
updatedAt?: string | null
updatedBy?: string | null
@@ -7745,8 +7745,8 @@ export type Database = {
grade?: string | null
id?: string
itemId?: string | null
- materialFormId?: number
- materialSubstanceId?: number
+ materialFormId?: string
+ materialSubstanceId?: string
unitOfMeasureCode?: string
updatedAt?: string | null
updatedBy?: string | null
@@ -7927,7 +7927,8 @@ export type Database = {
companyId: string | null
createdAt: string
createdBy: string
- id: number
+ customFields: Json | null
+ id: string
name: string
updatedAt: string | null
updatedBy: string | null
@@ -7936,7 +7937,8 @@ export type Database = {
companyId?: string | null
createdAt?: string
createdBy: string
- id?: number
+ customFields?: Json | null
+ id?: string
name: string
updatedAt?: string | null
updatedBy?: string | null
@@ -7945,7 +7947,8 @@ export type Database = {
companyId?: string | null
createdAt?: string
createdBy?: string
- id?: number
+ customFields?: Json | null
+ id?: string
name?: string
updatedAt?: string | null
updatedBy?: string | null
@@ -8056,7 +8059,8 @@ export type Database = {
companyId: string | null
createdAt: string
createdBy: string
- id: number
+ customFields: Json | null
+ id: string
name: string
updatedAt: string | null
updatedBy: string | null
@@ -8065,7 +8069,8 @@ export type Database = {
companyId?: string | null
createdAt?: string
createdBy: string
- id?: number
+ customFields?: Json | null
+ id?: string
name: string
updatedAt?: string | null
updatedBy?: string | null
@@ -8074,7 +8079,8 @@ export type Database = {
companyId?: string | null
createdAt?: string
createdBy?: string
- id?: number
+ customFields?: Json | null
+ id?: string
name?: string
updatedAt?: string | null
updatedBy?: string | null
@@ -20912,9 +20918,9 @@ export type Database = {
| Database["public"]["Enums"]["itemInventoryType"]
| null
materialForm: string | null
- materialFormId: number | null
+ materialFormId: string | null
materialSubstance: string | null
- materialSubstanceId: number | null
+ materialSubstanceId: string | null
name: string | null
supplierIds: string[] | null
unitOfMeasure: string | null
diff --git a/packages/database/supabase/migrations/20240608114413_materials.sql b/packages/database/supabase/migrations/20240608114413_materials.sql
index 5035177dac..234aaf79ab 100644
--- a/packages/database/supabase/migrations/20240608114413_materials.sql
+++ b/packages/database/supabase/migrations/20240608114413_materials.sql
@@ -12,14 +12,16 @@ ALTER POLICY "Employees can view items" ON "item"
);
CREATE TABLE "materialForm" (
- "id" SERIAL PRIMARY KEY,
+ "id" TEXT NOT NULL DEFAULT xid(),
"name" TEXT NOT NULL,
"companyId" TEXT,
+ "customFields" JSONB,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
"updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "materialForm_pkey" PRIMARY KEY ("id"),
CONSTRAINT "materialForm_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "materialForm_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "materialForm_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
@@ -27,6 +29,7 @@ CREATE TABLE "materialForm" (
CREATE INDEX "materialForm_companyId_idx" ON "materialForm"("companyId");
+ALTER TABLE "materialForm" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view material forms" ON "materialForm"
FOR SELECT
USING (
@@ -64,22 +67,25 @@ INSERT INTO "customFieldTable" ("table", "name", "module")
VALUES ('materialForm', 'Material Form', 'Items');
CREATE TABLE "materialSubstance" (
- "id" SERIAL PRIMARY KEY,
+ "id" TEXT NOT NULL DEFAULT xid(),
"name" TEXT NOT NULL,
"companyId" TEXT,
+ "customFields" JSONB,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
"updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "materialSubstance_pkey" PRIMARY KEY ("id"),
CONSTRAINT "materialSubstance_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "materialSubstance_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "materialSubstance_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-CREATE INDEX "materialSubstance_companyId_idx" ON "materialSubstance"("companyId");
+CREATE INDEX "materialSubstance_companyId_idx" ON "materialSubstance"("companyId");
+ALTER TABLE "materialSubstance" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view material substances" ON "materialSubstance"
FOR SELECT
USING (
@@ -119,8 +125,8 @@ VALUES ('materialSubstance', 'Material Substance', 'Items');
CREATE TABLE "material" (
"id" TEXT NOT NULL,
"itemId" TEXT,
- "materialFormId" INTEGER NOT NULL,
- "materialSubstanceId" INTEGER NOT NULL,
+ "materialFormId" TEXT NOT NULL,
+ "materialSubstanceId" TEXT NOT NULL,
"grade" TEXT,
"dimensions" TEXT,
"finish" TEXT,
@@ -128,7 +134,7 @@ CREATE TABLE "material" (
"approved" BOOLEAN NOT NULL DEFAULT false,
"approvedBy" TEXT,
"customFields" JSONB,
- "companyId" TEXT, -- we share certain materials across companies
+ "companyId" TEXT, -- nullable because we share certain materials across companies
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
@@ -140,7 +146,7 @@ CREATE TABLE "material" (
CONSTRAINT "material_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "material_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL ON UPDATE CASCADE,
-- unique index on itemId, materialFormId, materialSubstanceId, grade, dimensions, finish
- CONSTRAINT "material_unique" UNIQUE ("itemId", "materialFormId", "materialSubstanceId", "grade", "dimensions", "finish"),
+ CONSTRAINT "material_unique" UNIQUE ("itemId", "materialFormId", "materialSubstanceId", "grade", "dimensions", "finish", "companyId"),
CONSTRAINT "material_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id"),
CONSTRAINT "material_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id"),
CONSTRAINT "material_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
@@ -150,6 +156,7 @@ CREATE TABLE "material" (
CREATE INDEX "material_companyId_idx" ON "material"("companyId");
CREATE INDEX "material_itemId_idx" ON "material"("itemId");
+ALTER TABLE "material" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees can view materials" ON "material"
FOR SELECT
USING (
@@ -214,3 +221,28 @@ CREATE OR REPLACE VIEW "materials" WITH(SECURITY_INVOKER=true) AS
LEFT JOIN "materialForm" mf ON mf.id = m."materialFormId"
LEFT JOIN "materialSubstance" ms ON ms.id = m."materialSubstanceId"
LEFT JOIN "unitOfMeasure" uom ON uom.code = m."unitOfMeasureCode" AND uom."companyId" = m."companyId";
+
+
+INSERT INTO "materialSubstance" ("name", "createdBy")
+VALUES
+ ('Aluminum', 'system'),
+ ('Steel', 'system'),
+ ('Stainless Steel', 'system'),
+ ('Titanium', 'system'),
+ ('Brass', 'system'),
+ ('Copper', 'system');
+
+INSERT INTO "materialForm" ("name", "createdBy")
+VALUES
+ ('Angle', 'system'),
+ ('Channel', 'system'),
+ ('Beam', 'system'),
+ ('Flat Bar', 'system'),
+ ('Round Bar', 'system'),
+ ('Square Bar', 'system'),
+ ('Pipe', 'system'),
+ ('Square Tube', 'system'),
+ ('Rectangle Tube', 'system'),
+ ('Diamond Plate', 'system'),
+ ('Plate', 'system'),
+ ('Sheet', 'system');