Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: tree view for part manufacturing
Brad Barbin72f2933fa95f
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.tsindex ad4fd40e7d..65a04e08c5 100644--- a/apps/carbon/app/modules/items/items.models.ts+++ b/apps/carbon/app/modules/items/items.models.ts@@ -252,10 +252,8 @@ export const partValidator = itemValidator.merge(export const partManufacturingValidator = z.object({itemId: z.string().min(1, { message: "Item ID is required" }),- manufacturingLeadTime: zfd.numeric(z.number().min(0)),manufacturingBlocked: zfd.checkbox(),- requiresConfiguration: zfd.checkbox(),- scrapPercentage: zfd.numeric(z.number().min(0).max(100)),+ // requiresConfiguration: zfd.checkbox(),lotSize: zfd.numeric(z.number().min(0)),});diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.tsindex 77933375dc..06084ee4d8 100644--- a/apps/carbon/app/modules/items/items.service.ts+++ b/apps/carbon/app/modules/items/items.service.ts@@ -496,6 +496,69 @@ export async function getMethodOperations(.order("order", { ascending: true });}+type Method = NonNullable<+ Awaited<ReturnType<typeof getMethodTreeArray>>["data"]+>[number];+type MethodTreeItem = {+ id: string;+ data: Method;+ children: MethodTreeItem[];+};++export async function getMethodTree(+ client: SupabaseClient<Database>,+ makeMethodId: string+) {+ const items = await getMethodTreeArray(client, makeMethodId);+ if (items.error) return items;+ const tree = getMethodTreeArrayToTree(items.data);+ return {+ data: tree,+ error: null,+ };+}++export async function getMethodTreeArray(+ client: SupabaseClient<Database>,+ makeMethodId: string+) {+ return client.rpc("get_method_tree", {+ uid: makeMethodId,+ });+}++function getMethodTreeArrayToTree(items: Method[]): MethodTreeItem[] {+ const rootItems: MethodTreeItem[] = [];+ const lookup: { [id: string]: MethodTreeItem } = {};++ for (const item of items) {+ const itemId = item.materialMakeMethodId ?? item.methodMaterialId;+ const parentId = item.makeMethodId;++ if (!Object.prototype.hasOwnProperty.call(lookup, itemId)) {+ // @ts-ignore+ lookup[itemId] = { id: itemId, children: [] };+ }++ lookup[itemId]["data"] = item;++ const treeItem = lookup[itemId];++ if (parentId === null || parentId === undefined) {+ rootItems.push(treeItem);+ } else {+ if (!Object.prototype.hasOwnProperty.call(lookup, parentId)) {+ // @ts-ignore+ lookup[parentId] = { id: parentId, children: [] };+ }++ lookup[parentId]["children"].push(treeItem);+ }+ }++ return rootItems;+}+export async function getPart(client: SupabaseClient<Database>,itemId: string,@@ -1263,16 +1326,33 @@ export async function upsertMethodMaterial(customFields?: Json;})) {+ let materialMakeMethodId: string | null = null;+ if (methodMaterial.methodType === "Make") {+ const makeMethod = await client+ .from("makeMethod")+ .select("id")+ .eq("itemId", methodMaterial.itemId)+ .single();++ if (makeMethod.error) return makeMethod;+ materialMakeMethodId = makeMethod.data?.id;+ }+if ("createdBy" in methodMaterial) {return client.from("methodMaterial")- .insert([methodMaterial])+ .insert([+ {+ ...methodMaterial,+ materialMakeMethodId,+ },+ ]).select("id").single();}return client.from("methodMaterial")- .update(sanitize(methodMaterial))+ .update(sanitize({ ...methodMaterial, materialMakeMethodId })).eq("id", methodMaterial.id).select("id").single();diff --git a/apps/carbon/app/modules/items/types.ts b/apps/carbon/app/modules/items/types.tsindex 75b5bc408b..ddaea17932 100644--- a/apps/carbon/app/modules/items/types.ts+++ b/apps/carbon/app/modules/items/types.ts@@ -8,11 +8,13 @@ import type {getItemPostingGroups,getItemPostingGroupsList,getItemQuantities,+ getMakeMethod,getMaterialForms,getMaterialSubstances,getMaterials,getMethodMaterials,getMethodOperations,+ getMethodTreeArray,getPart,getParts,getPickMethods,@@ -66,10 +68,18 @@ export type BuyMethod = NonNullable<export type InventoryItemType = Database["public"]["Enums"]["itemTrackingType"];+export type MakeMethod = NonNullable<+ Awaited<ReturnType<typeof getMakeMethod>>["data"]+>;+export type Material = NonNullable<Awaited<ReturnType<typeof getMaterials>>["data"]>[number];+export type Method = NonNullable<+ Awaited<ReturnType<typeof getMethodTreeArray>>["data"]+>[number];+export type MethodItemType = (typeof methodItemType)[number];export type MethodMaterial = NonNullable<diff --git a/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx b/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsxindex e3520c1b6f..4206bfd1c7 100644--- a/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx+++ b/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx@@ -118,16 +118,6 @@ const FixtureProperties = () => {</Badge></VStack>- <VStack spacing={2}>- <h3 className="text-xs text-muted-foreground">Replenishment</h3>- <Enumerable- className={cn(- routeData?.fixtureSummary?.active === false && "opacity-50"- )}- value={routeData?.fixtureSummary?.replenishmentSystem ?? null}- />- </VStack>-<VStack spacing={2}><h3 className="text-xs text-muted-foreground">Default Method Type</h3><Badge variant="secondary">@@ -142,6 +132,16 @@ const FixtureProperties = () => {</Badge></VStack>+ <VStack spacing={2}>+ <h3 className="text-xs text-muted-foreground">Replenishment</h3>+ <Enumerable+ className={cn(+ routeData?.fixtureSummary?.active === false && "opacity-50"+ )}+ value={routeData?.fixtureSummary?.replenishmentSystem ?? null}+ />+ </VStack>+<VStack spacing={2}><h3 className="text-xs text-muted-foreground">Customer</h3>{routeData?.fixtureSummary?.customerId ? (diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsxindex b19b8c4ce0..bb746b9e30 100644--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -505,12 +505,6 @@ function MaterialForm({onItemChange(value?.value as string);}}/>- <DefaultMethodType- name="methodType"- label="Method Type"- value={itemData.methodType}- replenishmentSystem="Buy and Make"- /><InputControlledname="description"label="Description"@@ -519,6 +513,12 @@ function MaterialForm({setItemData((d) => ({ ...d, description: newValue }));}}/>+ <DefaultMethodType+ name="methodType"+ label="Method Type"+ value={itemData.methodType}+ replenishmentSystem="Buy and Make"+ /><Number name="quantity" label="Quantity" /><UnitOfMeasurename="unitOfMeasureCode"diff --git a/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx b/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsxindex 5bcae5b445..548220df9a 100644--- a/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx+++ b/apps/carbon/app/modules/items/ui/Parts/PartManufacturingForm.tsx@@ -39,22 +39,16 @@ const PartManufacturingForm = ({<CardContent><Hidden name="itemId" /><div className="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4 w-full">- <Number name="manufacturingLeadTime" label="Lead Time (Days)" />- <Number- name="scrapPercentage"- label="Scrap Percentage"- formatOptions={{ style: "percent" }}- /><Number name="lotSize" label="Lot Size" /><Booleanname="manufacturingBlocked"label="Manufacturing Blocked"/>- <Boolean+ {/* <Booleanname="requiresConfiguration"label="Requires Configuration"- />+ /> */}<CustomFormFields table="partReplenishment" /></div></CardContent>diff --git a/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx b/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsxindex 34b397db14..23c2820fdc 100644--- a/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx+++ b/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx@@ -118,16 +118,6 @@ const PartProperties = () => {</Badge></VStack>- <VStack spacing={2}>- <h3 className="text-xs text-muted-foreground">Replenishment</h3>- <Enumerable- className={cn(- routeData?.partSummary?.active === false && "opacity-50"- )}- value={routeData?.partSummary?.replenishmentSystem ?? null}- />- </VStack>-<VStack spacing={2}><h3 className="text-xs text-muted-foreground">Default Method Type</h3><Badge variant="secondary">@@ -142,6 +132,16 @@ const PartProperties = () => {</Badge></VStack>+ <VStack spacing={2}>+ <h3 className="text-xs text-muted-foreground">Replenishment</h3>+ <Enumerable+ className={cn(+ routeData?.partSummary?.active === false && "opacity-50"+ )}+ value={routeData?.partSummary?.replenishmentSystem ?? null}+ />+ </VStack>+<VStack spacing={2}><h3 className="text-xs text-muted-foreground">Unit of Measure</h3><Enumerable value={routeData?.partSummary?.unitOfMeasure ?? null} />diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsxindex c8e246a7d6..98181bb929 100644--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.method.tsx@@ -1,4 +1,3 @@-import type { JSONContent } from "@carbon/react";import {Button,HStack,@@ -17,15 +16,17 @@ import { LuCopy, LuLink } from "react-icons/lu";import { redirect } from "remix-typedjson";import { useRouteData } from "~/hooks";-import type { MethodItemType, MethodType, PartSummary } from "~/modules/items";+import type {+ MakeMethod,+ Material,+ MethodOperation,+ PartSummary,+} from "~/modules/items";import {BillOfMaterial,BillOfProcess,PartManufacturingForm,getItemManufacturing,- getMakeMethod,- getMethodMaterials,- getMethodOperations,partManufacturingValidator,upsertItemManufacturing,} from "~/modules/items";@@ -44,9 +45,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { itemId } = params;if (!itemId) throw new Error("Could not find itemId");- const [partManufacturing, makeMethod] = await Promise.all([+ const [partManufacturing] = await Promise.all([getItemManufacturing(client, itemId, companyId),- getMakeMethod(client, itemId, companyId),]);if (partManufacturing.error) {@@ -59,57 +59,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- if (makeMethod.error) {- throw redirect(- path.to.partDetails(itemId),- await flash(- request,- error(makeMethod.error, "Failed to load make method")- )- );- }-- const [methodMaterials, methodOperations] = await Promise.all([- getMethodMaterials(client, makeMethod.data.id),- getMethodOperations(client, makeMethod.data.id),- ]);- if (methodOperations.error) {- throw redirect(- path.to.partDetails(itemId),- await flash(- request,- error(methodOperations.error, "Failed to load method operations")- )- );- }- if (methodMaterials.error) {- throw redirect(- path.to.partDetails(itemId),- await flash(- request,- error(methodMaterials.error, "Failed to load method materials")- )- );- }-return json({partManufacturing: partManufacturing.data,- makeMethod: makeMethod.data,- methodMaterials:- methodMaterials.data?.map((m) => ({- ...m,- methodType: m.methodType as MethodType,- itemType: m.itemType as MethodItemType,- })) ?? [],- methodOperations:- methodOperations.data?.map((operation) => ({- ...operation,- equipmentTypeId: operation.equipmentTypeId ?? undefined,- methodOperationWorkInstruction:- operation.methodOperationWorkInstruction as {- content: JSONContent | null;- },- })) ?? [],});}@@ -157,11 +108,17 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function MakeMethodRoute() {- const { makeMethod, methodMaterials, methodOperations, partManufacturing } =- useLoaderData<typeof loader>();+ const { partManufacturing } = useLoaderData<typeof loader>();const { itemId } = useParams();if (!itemId) throw new Error("Could not find itemId");- const makeMethodId = makeMethod?.id;++ const manufacturingRouteData = useRouteData<{+ makeMethod: MakeMethod;+ methodMaterials: Material[];+ methodOperations: MethodOperation[];+ }>(path.to.partManufacturing(itemId));++ const makeMethodId = manufacturingRouteData?.makeMethod?.id;if (!makeMethodId) throw new Error("Could not find makeMethodId");const manufacturingInitialValues = {@@ -191,12 +148,14 @@ export default function MakeMethodRoute() {<BillOfMaterialkey={itemId}makeMethodId={makeMethodId}- materials={methodMaterials}+ // @ts-ignore+ materials={manufacturingRouteData?.methodMaterials ?? []}/><BillOfProcesskey={itemId}makeMethodId={makeMethodId}- operations={methodOperations}+ // @ts-ignore+ operations={manufacturingRouteData?.methodOperations ?? []}/></VStack></ScrollArea>diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsxindex b6f0cedb52..2b4758eb2a 100644--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx@@ -1,3 +1,4 @@+import type { JSONContent } from "@carbon/react";import {Badge,ClientOnly,@@ -13,115 +14,106 @@ import {VStack,cn,} from "@carbon/react";-import { TreeView, useTree } from "~/components/TreeView/TreeView";+import type { FlatTreeItem } from "~/components/TreeView/TreeView";+import { TreeView, flattenTree, useTree } from "~/components/TreeView/TreeView";import type { LoaderFunctionArgs } from "@remix-run/node";-import { Outlet, useParams } from "@remix-run/react";+import { Outlet, json, useLoaderData, useParams } from "@remix-run/react";import { useRef, useState } from "react";import { LuChevronDown, LuChevronUp, LuPlus, LuSearch } from "react-icons/lu";-import { typedjson, useTypedLoaderData } from "remix-typedjson";-import type { MethodType } from "~/modules/items";-import { MethodIcon } from "~/modules/items";+import { redirect } from "remix-typedjson";+import type { Method, MethodItemType, MethodType } from "~/modules/items";+import {+ MethodIcon,+ getMakeMethod,+ getMethodMaterials,+ getMethodOperations,+ getMethodTree,+} from "~/modules/items";import { requirePermissions } from "~/services/auth/auth.server";--type Method = {- id: string;- parentId: string | undefined;- children: string[];- hasChildren: boolean;- level: number;- data: {- itemId: string;- readableId: string;- description: string;- quantity: number;- fulfillmentMethod: MethodType;- isInherited: boolean;- isRoot: boolean;- };-};+import { flash } from "~/services/session.server";+import { path } from "~/utils/path";+import { error } from "~/utils/result";export async function loader({ request, params }: LoaderFunctionArgs) {- await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "parts",});const { itemId } = params;if (!itemId) throw new Error("Could not find itemId");- return typedjson({- methods: [- {- id: "1",- parentId: undefined,- hasChildren: true,- children: ["2", "3"],- level: 0,- data: {- itemId: "1",- readableId: "F02134",- description: '1/2" x 3" x 4" Bracket',- quantity: 1,- fulfillmentMethod: "Make",- isInherited: false,- isRoot: true,- },- },- {- id: "2",- parentId: "1",- hasChildren: true,- children: ["4"],- level: 1,- data: {- itemId: "2",- readableId: "F501932",- description: '1/2" x 3" x 4" Cutout',- quantity: 1,- fulfillmentMethod: "Make",- isInherited: false,- isRoot: false,- },- },+ const makeMethod = await getMakeMethod(client, itemId, companyId);- {- id: "4",- parentId: "2",- hasChildren: false,- children: [],- level: 2,- data: {- itemId: "4",- readableId: "F41858",- description: "1/8 X 5/8 6061-T6511 Aluminum Flat",- quantity: 2.8,- fulfillmentMethod: "Pick",- isInherited: true,- isRoot: false,- },- },- {- id: "3",- parentId: "1",- hasChildren: false,- children: [],- level: 1,- data: {- itemId: "3",- readableId: "91772A061",- description: '5/16" Threaded Machine Screw',- quantity: 4,- fulfillmentMethod: "Buy",- isInherited: false,- isRoot: false,- },- },- ] satisfies Method[],+ if (makeMethod.error) {+ throw redirect(+ path.to.partDetails(itemId),+ await flash(+ request,+ error(makeMethod.error, "Failed to load make method")+ )+ );+ }++ const [methodTree, methodMaterials, methodOperations] = await Promise.all([+ getMethodTree(client, makeMethod.data.id),+ getMethodMaterials(client, makeMethod.data.id),+ getMethodOperations(client, makeMethod.data.id),+ ]);+ if (methodTree?.error) {+ throw redirect(+ path.to.partDetails(itemId),+ await flash(+ request,+ error(methodTree.error, "Failed to load method tree")+ )+ );+ }++ if (methodOperations.error) {+ throw redirect(+ path.to.partDetails(itemId),+ await flash(+ request,+ error(methodOperations.error, "Failed to load method operations")+ )+ );+ }+ if (methodMaterials.error) {+ throw redirect(+ path.to.partDetails(itemId),+ await flash(+ request,+ error(methodMaterials.error, "Failed to load method materials")+ )+ );+ }++ return json({+ makeMethod: makeMethod.data,+ methodMaterials:+ methodMaterials.data?.map((m) => ({+ ...m,+ methodType: m.methodType as MethodType,+ itemType: m.itemType as MethodItemType,+ })) ?? [],+ methodOperations:+ methodOperations.data?.map((operation) => ({+ ...operation,+ equipmentTypeId: operation.equipmentTypeId ?? undefined,+ methodOperationWorkInstruction:+ operation.methodOperationWorkInstruction as {+ content: JSONContent | null;+ },+ })) ?? [],+ methods: (methodTree.data.length > 0+ ? flattenTree(methodTree.data[0])+ : []) satisfies FlatTreeItem<Method>[],});}export default function PartManufacturing() {- const { methods } = useTypedLoaderData<typeof loader>();+ const { methods } = useLoaderData<typeof loader>();const { itemId } = useParams();if (!itemId) throw new Error("Could not find itemId");@@ -139,6 +131,7 @@ export default function PartManufacturing() {<ScrollArea className="h-[calc(100vh-99px)]"><div className="grid h-full overflow-hidden p-2"><BoMExplorer+ // @ts-ignoremethods={methods}onSelectedIdChanged={(selectedId) => {console.log(selectedId);@@ -158,7 +151,7 @@ export default function PartManufacturing() {}type BoMExplorerProps = {- methods: Method[];+ methods: FlatTreeItem<Method>[];selectedId?: string;onSelectedIdChanged: (selectedId: string | undefined) => void;};@@ -195,7 +188,9 @@ function BoMExplorer({fn: (value, node) => {if (value.text === "") return true;if (- node.data.readableId.toLowerCase().includes(value.text.toLowerCase())+ node.data.itemReadableId+ .toLowerCase()+ .includes(value.text.toLowerCase())) {return true;}@@ -283,13 +278,13 @@ function BoMExplorer({<divclassName={cn("flex items-center gap-2 overflow-x-hidden",- node.data.isInherited && "opacity-50"+ node.level > 1 && "opacity-50")}><MethodIcontype={// node.data.isRoot ? "Method" :- node.data.fulfillmentMethod+ node.data.methodType}className="h-4 min-h-4 w-4 min-w-4"/>@@ -313,15 +308,15 @@ function BoMExplorer({);}-function NodeText({ node }: { node: Method }) {+function NodeText({ node }: { node: FlatTreeItem<Method> }) {return (<div className="flex items-center gap-1">- <span className="text-sm font-mono">{node.data.readableId}</span>+ <span className="text-sm font-mono">{node.data.itemReadableId}</span></div>);}-function NodeQuantity({ node }: { node: Method }) {+function NodeQuantity({ node }: { node: FlatTreeItem<Method> }) {return (<Badge className="text-xs" variant="outline">{node.data.quantity}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 9675da3e50..cf97c6e6da 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -6029,6 +6029,7 @@ export type Database = {name: stringreadableId: stringreplenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]+ thumbnailUrl: string | nulltype: Database["public"]["Enums"]["itemType"]unitOfMeasureCode: string | nullupdatedAt: string | null@@ -6047,6 +6048,7 @@ export type Database = {name: stringreadableId: stringreplenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]+ thumbnailUrl?: string | nulltype: Database["public"]["Enums"]["itemType"]unitOfMeasureCode?: string | nullupdatedAt?: string | null@@ -6065,6 +6067,7 @@ export type Database = {name?: stringreadableId?: stringreplenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]+ thumbnailUrl?: string | nulltype?: Database["public"]["Enums"]["itemType"]unitOfMeasureCode?: string | nullupdatedAt?: string | null@@ -6874,13 +6877,11 @@ export type Database = {itemId: stringlotSize: number | nullmanufacturingBlocked: boolean- manufacturingLeadTime: numberpreferredSupplierId: string | nullpurchasingBlocked: booleanpurchasingLeadTime: numberpurchasingUnitOfMeasureCode: string | nullrequiresConfiguration: boolean- scrapPercentage: numberupdatedAt: string | nullupdatedBy: string | null}@@ -6893,13 +6894,11 @@ export type Database = {itemId: stringlotSize?: number | nullmanufacturingBlocked?: boolean- manufacturingLeadTime?: numberpreferredSupplierId?: string | nullpurchasingBlocked?: booleanpurchasingLeadTime?: numberpurchasingUnitOfMeasureCode?: string | nullrequiresConfiguration?: boolean- scrapPercentage?: numberupdatedAt?: string | nullupdatedBy?: string | null}@@ -6912,13 +6911,11 @@ export type Database = {itemId?: stringlotSize?: number | nullmanufacturingBlocked?: boolean- manufacturingLeadTime?: numberpreferredSupplierId?: string | nullpurchasingBlocked?: booleanpurchasingLeadTime?: numberpurchasingUnitOfMeasureCode?: string | nullrequiresConfiguration?: boolean- scrapPercentage?: numberupdatedAt?: string | nullupdatedBy?: string | null}@@ -8186,6 +8183,7 @@ export type Database = {itemReadableId: stringitemType: stringmakeMethodId: string+ materialMakeMethodId: string | nullmethodType: Database["public"]["Enums"]["methodType"]order: numberquantity: number@@ -8204,6 +8202,7 @@ export type Database = {itemReadableId: stringitemType?: stringmakeMethodId: string+ materialMakeMethodId?: string | nullmethodType?: Database["public"]["Enums"]["methodType"]order?: numberquantity: number@@ -8222,6 +8221,7 @@ export type Database = {itemReadableId?: stringitemType?: stringmakeMethodId?: string+ materialMakeMethodId?: string | nullmethodType?: Database["public"]["Enums"]["methodType"]order?: numberquantity?: number@@ -8293,6 +8293,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "methodMaterial_materialMakeMethodId_fkey"+ columns: ["materialMakeMethodId"]+ isOneToOne: false+ referencedRelation: "makeMethod"+ referencedColumns: ["id"]+ },{foreignKeyName: "methodMaterial_methodId_fkey"columns: ["makeMethodId"]@@ -23974,6 +23981,22 @@ export type Database = {}Returns: string}+ get_method_tree: {+ Args: {+ uid: string+ }+ Returns: {+ methodMaterialId: string+ makeMethodId: string+ materialMakeMethodId: string+ itemId: string+ itemReadableId: string+ itemType: string+ quantity: number+ methodType: Database["public"]["Enums"]["methodType"]+ isRoot: boolean+ }[]+ }get_my_claim: {Args: {claim: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 9675da3e50..cf97c6e6da 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -6029,6 +6029,7 @@ export type Database = {name: stringreadableId: stringreplenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]+ thumbnailUrl: string | nulltype: Database["public"]["Enums"]["itemType"]unitOfMeasureCode: string | nullupdatedAt: string | null@@ -6047,6 +6048,7 @@ export type Database = {name: stringreadableId: stringreplenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]+ thumbnailUrl?: string | nulltype: Database["public"]["Enums"]["itemType"]unitOfMeasureCode?: string | nullupdatedAt?: string | null@@ -6065,6 +6067,7 @@ export type Database = {name?: stringreadableId?: stringreplenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]+ thumbnailUrl?: string | nulltype?: Database["public"]["Enums"]["itemType"]unitOfMeasureCode?: string | nullupdatedAt?: string | null@@ -6874,13 +6877,11 @@ export type Database = {itemId: stringlotSize: number | nullmanufacturingBlocked: boolean- manufacturingLeadTime: numberpreferredSupplierId: string | nullpurchasingBlocked: booleanpurchasingLeadTime: numberpurchasingUnitOfMeasureCode: string | nullrequiresConfiguration: boolean- scrapPercentage: numberupdatedAt: string | nullupdatedBy: string | null}@@ -6893,13 +6894,11 @@ export type Database = {itemId: stringlotSize?: number | nullmanufacturingBlocked?: boolean- manufacturingLeadTime?: numberpreferredSupplierId?: string | nullpurchasingBlocked?: booleanpurchasingLeadTime?: numberpurchasingUnitOfMeasureCode?: string | nullrequiresConfiguration?: boolean- scrapPercentage?: numberupdatedAt?: string | nullupdatedBy?: string | null}@@ -6912,13 +6911,11 @@ export type Database = {itemId?: stringlotSize?: number | nullmanufacturingBlocked?: boolean- manufacturingLeadTime?: numberpreferredSupplierId?: string | nullpurchasingBlocked?: booleanpurchasingLeadTime?: numberpurchasingUnitOfMeasureCode?: string | nullrequiresConfiguration?: boolean- scrapPercentage?: numberupdatedAt?: string | nullupdatedBy?: string | null}@@ -8186,6 +8183,7 @@ export type Database = {itemReadableId: stringitemType: stringmakeMethodId: string+ materialMakeMethodId: string | nullmethodType: Database["public"]["Enums"]["methodType"]order: numberquantity: number@@ -8204,6 +8202,7 @@ export type Database = {itemReadableId: stringitemType?: stringmakeMethodId: string+ materialMakeMethodId?: string | nullmethodType?: Database["public"]["Enums"]["methodType"]order?: numberquantity: number@@ -8222,6 +8221,7 @@ export type Database = {itemReadableId?: stringitemType?: stringmakeMethodId?: string+ materialMakeMethodId?: string | nullmethodType?: Database["public"]["Enums"]["methodType"]order?: numberquantity?: number@@ -8293,6 +8293,13 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},+ {+ foreignKeyName: "methodMaterial_materialMakeMethodId_fkey"+ columns: ["materialMakeMethodId"]+ isOneToOne: false+ referencedRelation: "makeMethod"+ referencedColumns: ["id"]+ },{foreignKeyName: "methodMaterial_methodId_fkey"columns: ["makeMethodId"]@@ -23974,6 +23981,22 @@ export type Database = {}Returns: string}+ get_method_tree: {+ Args: {+ uid: string+ }+ Returns: {+ methodMaterialId: string+ makeMethodId: string+ materialMakeMethodId: string+ itemId: string+ itemReadableId: string+ itemType: string+ quantity: number+ methodType: Database["public"]["Enums"]["methodType"]+ isRoot: boolean+ }[]+ }get_my_claim: {Args: {claim: stringdiff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sqlindex 4e9403acca..662ff99dde 100644--- a/packages/database/supabase/migrations/20230330024716_parts.sql+++ b/packages/database/supabase/migrations/20230330024716_parts.sql@@ -136,14 +136,15 @@ CREATE TYPE "methodType" AS ENUM (CREATE TABLE "item" ("id" TEXT NOT NULL DEFAULT xid(),"readableId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,"type" "itemType" NOT NULL,"replenishmentSystem" "itemReplenishmentSystem" NOT NULL DEFAULT 'Buy',"defaultMethodType" "methodType" DEFAULT 'Buy',- "name" TEXT NOT NULL,- "description" TEXT,"itemTrackingType" "itemTrackingType" NOT NULL,"unitOfMeasureCode" TEXT,"active" BOOLEAN NOT NULL DEFAULT true,+ "thumbnailUrl" TEXT,"blocked" BOOLEAN NOT NULL DEFAULT false,"companyId" TEXT NOT NULL,"createdBy" TEXT NOT NULL,@@ -249,9 +250,9 @@ CREATE INDEX "part_companyId_idx" ON "part" ("companyId");ALTER publication supabase_realtime ADD TABLE "part";-ALTER TABLE "item" ENABLE ROW LEVEL SECURITY;+ALTER TABLE "part" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees can view parts" ON "item"+CREATE POLICY "Employees can view parts" ON "part"FOR SELECTUSING (has_role('employee', "companyId")@@ -260,21 +261,21 @@ CREATE POLICY "Employees can view parts" ON "item"));-CREATE POLICY "Employees with parts_create can insert parts" ON "item"+CREATE POLICY "Employees with parts_create can insert parts" ON "part"FOR INSERTWITH CHECK (has_role('employee', "companyId") ANDhas_company_permission('parts_create', "companyId"));-CREATE POLICY "Employees with parts_update can update parts" ON "item"+CREATE POLICY "Employees with parts_update can update parts" ON "part"FOR UPDATEUSING (has_role('employee', "companyId") ANDhas_company_permission('parts_update', "companyId"));-CREATE POLICY "Employees with parts_delete can delete parts" ON "item"+CREATE POLICY "Employees with parts_delete can delete parts" ON "part"FOR DELETEUSING (has_role('employee', "companyId") AND@@ -516,10 +517,8 @@ CREATE TABLE "itemReplenishment" ("conversionFactor" NUMERIC(15,5) NOT NULL DEFAULT 1,"purchasingBlocked" BOOLEAN NOT NULL DEFAULT false,"manufacturingPolicy" "partManufacturingPolicy" NOT NULL DEFAULT 'Make to Stock',- "manufacturingLeadTime" INTEGER NOT NULL DEFAULT 0,"manufacturingBlocked" BOOLEAN NOT NULL DEFAULT false,"requiresConfiguration" BOOLEAN NOT NULL DEFAULT false,- "scrapPercentage" NUMERIC(15,5) NOT NULL DEFAULT 0,"lotSize" INTEGER,"companyId" TEXT NOT NULL,"createdBy" TEXT NOT NULL,@@ -557,7 +556,7 @@ CREATE POLICY "Employees with parts_update can update part costs" ON "itemReplen);-CREATE POLICY "Suppliers with parts can view parts they created or supply" ON "item"+CREATE POLICY "Suppliers with parts_view can view items they created or supply" ON "item"FOR SELECTUSING (has_role('supplier', "companyId") AND@@ -574,7 +573,7 @@ CREATE POLICY "Suppliers with parts can view parts they created or supply" ON "i));-CREATE POLICY "Supliers with parts_create can insert parts" ON "item"+CREATE POLICY "Supliers with parts_create can insert items" ON "item"FOR INSERTWITH CHECK (has_role('supplier', "companyId") AND@@ -598,7 +597,7 @@ CREATE POLICY "Suppliers with parts_update can update parts that they created or));-CREATE POLICY "Suppliers with parts_delete can delete parts that they created or supply" ON "item"+CREATE POLICY "Suppliers with parts_delete can delete items that they created or supply" ON "item"FOR DELETEUSING (has_role('supplier', "companyId") AND@@ -615,7 +614,65 @@ CREATE POLICY "Suppliers with parts_delete can delete parts that they created or));-CREATE POLICY "Suppliers with parts_view can view part costs they supply" ON "itemCost"+CREATE POLICY "Suppliers with parts_view can view parts they created or supply" ON "part"+ FOR SELECT+ USING (+ has_role('supplier', "companyId") AND+ has_company_permission('parts_view', "companyId")+ AND (+ "createdBy" = auth.uid()::text+ OR (+ "itemId" IN (+ SELECT "itemId" FROM "buyMethod" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Supliers with parts_create can insert parts" ON "part"+ FOR INSERT+ WITH CHECK (+ has_role('supplier', "companyId") AND+ has_company_permission('parts_create', "companyId")+ );++CREATE POLICY "Suppliers with parts_update can update parts that they created or supply" ON "part"+ FOR UPDATE+ USING (+ has_role('supplier', "companyId") AND+ has_company_permission('parts_create', "companyId")+ AND (+ "createdBy" = auth.uid()::text+ OR (+ "itemId" IN (+ SELECT "itemId" FROM "buyMethod" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_delete can delete parts that they created or supply" ON "part"+ FOR DELETE+ USING (+ has_role('supplier', "companyId") AND+ has_company_permission('parts_create', "companyId")+ AND (+ "createdBy" = auth.uid()::text+ OR (+ "itemId" IN (+ SELECT "itemId" FROM "buyMethod" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_view can view item costs they supply" ON "itemCost"FOR SELECTUSING (has_role('supplier', "companyId") AND@@ -643,11 +700,11 @@ CREATE POLICY "Suppliers with parts_update can update parts costs that they supp));-CREATE POLICY "Suppliers with parts_view can view part replenishments they supply" ON "itemReplenishment"+CREATE POLICY "Suppliers with parts_view can view part replenishment they supply" ON "itemReplenishment"FOR SELECTUSING (has_role('supplier', "companyId") AND- has_company_permission('parts_create', "companyId")+ has_company_permission('parts_view', "companyId")AND ("itemId" IN (SELECT "itemId" FROM "buyMethod" WHERE "supplierId" IN (diff --git a/packages/database/supabase/migrations/20240608114413_materials.sql b/packages/database/supabase/migrations/20240608114413_materials.sqlindex 571f847432..b6feec9dbf 100644--- a/packages/database/supabase/migrations/20240608114413_materials.sql+++ b/packages/database/supabase/migrations/20240608114413_materials.sql@@ -30,6 +30,14 @@ CREATE TABLE "materialForm" (CREATE INDEX "materialForm_companyId_idx" ON "materialForm"("companyId");ALTER TABLE "materialForm" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view global material forms" ON "materialForm"+ FOR SELECT+ USING (+ auth.role() = 'authenticated' AND+ "companyId" IS NULL+ );+CREATE POLICY "Employees can view material forms" ON "materialForm"FOR SELECTUSING (@@ -98,6 +106,13 @@ CREATE POLICY "Employees can view material substances" ON "materialSubstance"));+CREATE POLICY "Authenticated users can view global material substances" ON "materialSubstance"+ FOR SELECT+ USING (+ auth.role() = 'authenticated' AND+ "companyId" IS NULL+ );+CREATE POLICY "Employees with parts_create can insert material substances" ON "materialSubstance"FOR INSERTWITH CHECK (diff --git a/packages/database/supabase/migrations/20240619095417_methods.sql b/packages/database/supabase/migrations/20240619095417_methods.sqlindex 3971d65951..770c2db106 100644--- a/packages/database/supabase/migrations/20240619095417_methods.sql+++ b/packages/database/supabase/migrations/20240619095417_methods.sql@@ -55,6 +55,7 @@ CREATE TABLE "methodMaterial" ("id" TEXT NOT NULL DEFAULT xid(),"makeMethodId" TEXT NOT NULL,"methodType" "methodType" NOT NULL DEFAULT 'Buy',+ "materialMakeMethodId" TEXT,"itemType" TEXT NOT NULL DEFAULT 'Material',"itemId" TEXT NOT NULL,"quantity" NUMERIC NOT NULL,@@ -67,6 +68,7 @@ CREATE TABLE "methodMaterial" (CONSTRAINT "methodMaterial_pkey" PRIMARY KEY ("id"),CONSTRAINT "methodMaterial_methodId_fkey" FOREIGN KEY ("makeMethodId") REFERENCES "makeMethod" ("id") ON UPDATE CASCADE ON DELETE CASCADE,+ CONSTRAINT "methodMaterial_materialMakeMethodId_fkey" FOREIGN KEY ("materialMakeMethodId") REFERENCES "makeMethod" ("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "methodMaterial_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure" ("code", "companyId") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "methodMaterial_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON UPDATE CASCADE ON DELETE CASCADE,CONSTRAINT "methodMaterial_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,diff --git a/packages/database/supabase/migrations/20240625154513_method-tree.sql b/packages/database/supabase/migrations/20240625154513_method-tree.sqlnew file mode 100644index 0000000000..aa50ac353a--- /dev/null+++ b/packages/database/supabase/migrations/20240625154513_method-tree.sql@@ -0,0 +1,64 @@+CREATE OR REPLACE FUNCTION get_method_tree(uid TEXT)+RETURNS TABLE (+ "methodMaterialId" TEXT,+ "makeMethodId" TEXT,+ "materialMakeMethodId" TEXT,+ "itemId" TEXT,+ "itemReadableId" TEXT,+ "itemType" TEXT,+ "quantity" NUMERIC,+ "methodType" "methodType",+ "isRoot" BOOLEAN+) AS $$+WITH RECURSIVE material AS (+ SELECT+ "id",+ "makeMethodId",+ "methodType",+ "materialMakeMethodId",+ "itemId",+ "itemType",+ "quantity"+ FROM+ "methodMaterial"+ WHERE+ "makeMethodId" = uid+ UNION+ SELECT+ children."id",+ children."makeMethodId",+ children."methodType",+ children."materialMakeMethodId",+ children."itemId",+ children."itemType",+ children."quantity"+ FROM+ "methodMaterial" children+ INNER JOIN material b ON b."materialMakeMethodId" = children."makeMethodId"+)+SELECT+ material.id as "methodMaterialId",+ material."makeMethodId",+ material."materialMakeMethodId",+ material."itemId",+ item."readableId" AS "itemReadableId",+ material."itemType",+ material."quantity",+ material."methodType",+ false AS "isRoot"+FROM material INNER JOIN item ON material."itemId" = item.id+UNION+SELECT+ mm."id" AS "methodMaterialId",+ NULL AS "makeMethodId",+ mm.id AS "materialMakeMethodId",+ mm."itemId",+ i."readableId" AS "itemReadableId",+ i."type"::text,+ 1 AS "quantity",+ 'Make' AS "methodType",+ true AS "isRoot"++FROM "makeMethod" mm INNER JOIN item i ON mm."itemId" = i.id+WHERE mm.id = uid+$$ LANGUAGE sql STABLE;\ No newline at end of filediff --git a/packages/react/src/Switch.tsx b/packages/react/src/Switch.tsxindex 4c58807dad..a7eb817084 100644--- a/packages/react/src/Switch.tsx+++ b/packages/react/src/Switch.tsx@@ -8,8 +8,7 @@ import { cn } from "./utils/cn";const variations = {large: {- container:- "flex items-center gap-x-2 rounded-md hover:bg-muted p-2 transition",+ container: "flex items-center gap-x-2 rounded-md hover:bg-muted transition",root: "h-6 w-11",thumb:"h-5 w-5 data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0",