Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add quote BoM and BoP components
Brad Barbin34307b57fb68
diff --git a/apps/carbon/app/modules/documents/documents.models.ts b/apps/carbon/app/modules/documents/documents.models.tsindex 70d7618a62..3747171004 100644--- a/apps/carbon/app/modules/documents/documents.models.ts+++ b/apps/carbon/app/modules/documents/documents.models.ts@@ -1,5 +1,5 @@import { z } from "zod";-import { methodItemType } from "../items";+import { methodItemType } from "~/modules/shared";export const documentTypes = ["Archive",diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.tsindex 09a3666a4f..3d0797f8c5 100644--- a/apps/carbon/app/modules/items/items.models.ts+++ b/apps/carbon/app/modules/items/items.models.ts@@ -1,18 +1,11 @@import { z } from "zod";import { zfd } from "zod-form-data";-import { standardFactorType } from "../shared";--export const defaultWorkInstruction = {- type: "doc",- content: [- {- type: "heading",- attrs: { level: 2 },- content: [{ type: "text", text: "Work Instructions" }],- },- { type: "paragraph" },- ],-};+import {+ methodItemType,+ methodOperationOrders,+ methodType,+ standardFactorType,+} from "../shared";export const itemTrackingTypes = ["Inventory", "Non-Inventory"] as const;@@ -30,22 +23,6 @@ export const itemReorderingPolicies = ["Maximum Quantity",] as const;-export const methodItemType = [- "Part",- "Material",- "Tool",- "Fixture",- "Consumable",- "Service",-] as const;--export const methodType = ["Buy", "Make", "Pick"] as const;--export const methodOperationOrders = [- "After Previous",- "With Previous",-] as const;-export const itemReplenishmentSystems = ["Buy","Make",diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.tsindex 5b88e7f72f..5fdf8e6de2 100644--- a/apps/carbon/app/modules/items/items.service.ts+++ b/apps/carbon/app/modules/items/items.service.ts@@ -549,6 +549,7 @@ export async function getMethodTree() {const items = await getMethodTreeArray(client, makeMethodId);if (items.error) return items;+ console.log({ items: items.data });const tree = getMethodTreeArrayToTree(items.data);return {diff --git a/apps/carbon/app/modules/items/types.ts b/apps/carbon/app/modules/items/types.tsindex 52fa5b0e8b..595106d8c3 100644--- a/apps/carbon/app/modules/items/types.ts+++ b/apps/carbon/app/modules/items/types.ts@@ -1,5 +1,4 @@import type { Database } from "@carbon/database";-import type { methodItemType, methodType } from "./items.models";import type {getBuyMethods,getConsumables,@@ -85,8 +84,6 @@ export type Method = NonNullable<Awaited<ReturnType<typeof getMethodTreeArray>>["data"]>[number];-export type MethodItemType = (typeof methodItemType)[number];-export type MethodMaterial = NonNullable<Awaited<ReturnType<typeof getMethodMaterials>>["data"]>[number];@@ -95,8 +92,6 @@ export type MethodOperation = NonNullable<Awaited<ReturnType<typeof getMethodOperations>>["data"]>[number];-export type MethodType = (typeof methodType)[number];-export type ModelUpload = {modelId: string | null;modelName: string | null;diff --git a/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx b/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsxindex 3b6f5f03f3..67f5863492 100644--- a/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx+++ b/apps/carbon/app/modules/items/ui/Consumables/ConsumableProperties.tsx@@ -13,11 +13,11 @@ import { useParams } from "@remix-run/react";import { LuCopy, LuLink } from "react-icons/lu";import { Assignee, useOptimisticAssignment } from "~/components";import { useRouteData } from "~/hooks";+import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/modules/shared";import type { ListItem } from "~/types";import { path } from "~/utils/path";import type { BuyMethod, Consumable, ItemFile, PickMethod } from "../../types";-import { FileBadge, MethodIcon, TrackingTypeIcon } from "../Item";-import { MethodBadge } from "../Item/MethodBadge";+import { FileBadge } from "../Item";const ConsumableProperties = () => {const { itemId } = useParams();diff --git a/apps/carbon/app/modules/items/ui/Consumables/ConsumablesTable.tsx b/apps/carbon/app/modules/items/ui/Consumables/ConsumablesTable.tsxindex fad863b498..980dddef27 100644--- a/apps/carbon/app/modules/items/ui/Consumables/ConsumablesTable.tsx+++ b/apps/carbon/app/modules/items/ui/Consumables/ConsumablesTable.tsx@@ -15,12 +15,8 @@ import { ConfirmDelete } from "~/components/Modals";import { usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { Consumable } from "~/modules/items";-import {- MethodIcon,- TrackingTypeIcon,- itemTrackingTypes,- methodType,-} from "~/modules/items";+import { itemTrackingTypes } from "~/modules/items";+import { MethodIcon, TrackingTypeIcon, methodType } from "~/modules/shared";import { usePeople } from "~/stores";import type { ListItem } from "~/types";import { path } from "~/utils/path";diff --git a/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx b/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsxindex 0884bf7f2e..c518291144 100644--- a/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx+++ b/apps/carbon/app/modules/items/ui/Fixtures/FixtureProperties.tsx@@ -17,11 +17,11 @@ import {useOptimisticAssignment,} from "~/components";import { useRouteData } from "~/hooks";+import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/modules/shared";import type { ListItem } from "~/types";import { path } from "~/utils/path";import type { BuyMethod, Fixture, ItemFile, PickMethod } from "../../types";-import { FileBadge, MethodIcon, TrackingTypeIcon } from "../Item";-import { MethodBadge } from "../Item/MethodBadge";+import { FileBadge } from "../Item";const FixtureProperties = () => {const { itemId } = useParams();diff --git a/apps/carbon/app/modules/items/ui/Fixtures/FixturesTable.tsx b/apps/carbon/app/modules/items/ui/Fixtures/FixturesTable.tsxindex 72ac8ee61f..549d90000e 100644--- a/apps/carbon/app/modules/items/ui/Fixtures/FixturesTable.tsx+++ b/apps/carbon/app/modules/items/ui/Fixtures/FixturesTable.tsx@@ -22,13 +22,8 @@ import { ConfirmDelete } from "~/components/Modals";import { usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { Fixture } from "~/modules/items";-import {- MethodIcon,- TrackingTypeIcon,- itemReplenishmentSystems,- itemTrackingTypes,- methodType,-} from "~/modules/items";+import { itemReplenishmentSystems, itemTrackingTypes } from "~/modules/items";+import { MethodIcon, TrackingTypeIcon, methodType } from "~/modules/shared";import { useCustomers, usePeople } from "~/stores";import type { ListItem } from "~/types";import { path } from "~/utils/path";diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsxindex 701494bbf9..c85156a7c5 100644--- a/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/carbon/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -7,11 +7,11 @@ import {CardContent,CardHeader,CardTitle,- HStack,- VStack,cn,+ HStack,toast,useDebounce,+ VStack,} from "@carbon/react";import { ValidatedForm } from "@carbon/remix-validated-form";import { useFetcher, useParams } from "@remix-run/react";@@ -38,11 +38,15 @@ import type {import { SortableList, SortableListItem } from "~/components/SortableList";import { useUser } from "~/hooks";import { useSupabase } from "~/lib/supabase";+import type { MethodItemType, MethodType } from "~/modules/shared";+import {+ MethodIcon,+ methodItemType,+ MethodItemTypeIcon,+} from "~/modules/shared";import { path } from "~/utils/path";import type { methodOperationValidator } from "../../items.models";-import { methodItemType, methodMaterialValidator } from "../../items.models";-import type { MethodItemType, MethodType } from "../../types";-import { MethodIcon, MethodItemTypeIcon } from "./MethodIcon";+import { methodMaterialValidator } from "../../items.models";type Material = z.infer<typeof methodMaterialValidator> & {description: string;diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsxindex fe6ce9c3da..4d0d5ef42d 100644--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx@@ -38,12 +38,9 @@ import type { Item, SortableItemRenderProps } from "~/components/SortableList";import { SortableList, SortableListItem } from "~/components/SortableList";import { useUser } from "~/hooks";import { useSupabase } from "~/lib/supabase";+import { methodOperationOrders } from "~/modules/shared";import { path } from "~/utils/path";-import {- defaultWorkInstruction,- methodOperationOrders,- methodOperationValidator,-} from "../../items.models";+import { methodOperationValidator } from "../../items.models";type Operation = z.infer<typeof methodOperationValidator> & {methodOperationWorkInstruction: {@@ -91,7 +88,7 @@ const initialMethodOperation: Omit<Operation, "makeMethodId" | "order"> = {standardFactor: "Hours/Piece",operationOrder: "After Previous",methodOperationWorkInstruction: {- content: defaultWorkInstruction,+ content: {},},};diff --git a/apps/carbon/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/carbon/app/modules/items/ui/Item/BoMExplorer.tsxindex a3bd7dcb4d..152794bff7 100644--- a/apps/carbon/app/modules/items/ui/Item/BoMExplorer.tsx+++ b/apps/carbon/app/modules/items/ui/Item/BoMExplorer.tsx@@ -13,9 +13,10 @@ import { useRef, useState } from "react";import { LuChevronDown, LuChevronUp, LuSearch } from "react-icons/lu";import type { FlatTreeItem } from "~/components/TreeView/TreeView";import { TreeView, useTree } from "~/components/TreeView/TreeView";+import type { Method } from "~/modules/items";+import type { MethodItemType } from "~/modules/shared";+import { MethodIcon, MethodItemTypeIcon } from "~/modules/shared";import { path } from "~/utils/path";-import type { Method, MethodItemType } from "../../types";-import { MethodIcon, MethodItemTypeIcon } from "./MethodIcon";type BoMExplorerProps = {itemType: MethodItemType;diff --git a/apps/carbon/app/modules/items/ui/Item/index.ts b/apps/carbon/app/modules/items/ui/Item/index.tsindex cfd999234d..afdc87c2d4 100644--- a/apps/carbon/app/modules/items/ui/Item/index.ts+++ b/apps/carbon/app/modules/items/ui/Item/index.ts@@ -11,7 +11,7 @@ import ItemForm from "./ItemForm";import ItemPlanningForm from "./ItemPlanningForm";import ItemPurchasingForm from "./ItemPurchasingForm";import ItemSalePriceForm from "./ItemSalePriceForm";-import { MethodIcon, MethodItemTypeIcon, TrackingTypeIcon } from "./MethodIcon";+import PickMethodForm from "./PickMethodForm";export {@@ -28,8 +28,5 @@ export {ItemPlanningForm,ItemPurchasingForm,ItemSalePriceForm,- MethodIcon,- MethodItemTypeIcon,PickMethodForm,- TrackingTypeIcon,};diff --git a/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx b/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsxindex aa5715814e..8e1b159f8b 100644--- a/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx+++ b/apps/carbon/app/modules/items/ui/Materials/MaterialProperties.tsx@@ -13,11 +13,11 @@ import { useParams } from "@remix-run/react";import { LuCopy, LuLink } from "react-icons/lu";import { Assignee, useOptimisticAssignment } from "~/components";import { useRouteData } from "~/hooks";+import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/modules/shared";import type { ListItem } from "~/types";import { path } from "~/utils/path";import type { BuyMethod, ItemFile, Material, PickMethod } from "../../types";-import { FileBadge, MethodIcon, TrackingTypeIcon } from "../Item";-import { MethodBadge } from "../Item/MethodBadge";+import { FileBadge } from "../Item";const MaterialProperties = () => {const { itemId } = useParams();diff --git a/apps/carbon/app/modules/items/ui/Materials/MaterialsTable.tsx b/apps/carbon/app/modules/items/ui/Materials/MaterialsTable.tsxindex 86d1324ede..91fa36e6ab 100644--- a/apps/carbon/app/modules/items/ui/Materials/MaterialsTable.tsx+++ b/apps/carbon/app/modules/items/ui/Materials/MaterialsTable.tsx@@ -16,12 +16,8 @@ import { ConfirmDelete } from "~/components/Modals";import { usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { Material } from "~/modules/items";-import {- MethodIcon,- TrackingTypeIcon,- itemTrackingTypes,- methodType,-} from "~/modules/items";+import { itemTrackingTypes } from "~/modules/items";+import { MethodIcon, TrackingTypeIcon, methodType } from "~/modules/shared";import { usePeople } from "~/stores";import type { ListItem } from "~/types";import { path } from "~/utils/path";diff --git a/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx b/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsxindex c47508ae74..b806732e71 100644--- a/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx+++ b/apps/carbon/app/modules/items/ui/Parts/PartProperties.tsx@@ -14,12 +14,11 @@ import { LuCopy, LuExternalLink, LuLink, LuMove3D } from "react-icons/lu";import { useOptimisticAssignment } from "~/components";import Assignee from "~/components/Assignee";import { useRouteData } from "~/hooks";+import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/modules/shared";import type { ListItem } from "~/types";import { path } from "~/utils/path";import type { BuyMethod, ItemFile, PartSummary, PickMethod } from "../../types";import { FileBadge } from "../Item";-import { MethodBadge } from "../Item/MethodBadge";-import { MethodIcon, TrackingTypeIcon } from "../Item/MethodIcon";const PartProperties = () => {const { itemId } = useParams();diff --git a/apps/carbon/app/modules/items/ui/Parts/PartsTable.tsx b/apps/carbon/app/modules/items/ui/Parts/PartsTable.tsxindex 1c0b193fa7..db8cff5d70 100644--- a/apps/carbon/app/modules/items/ui/Parts/PartsTable.tsx+++ b/apps/carbon/app/modules/items/ui/Parts/PartsTable.tsx@@ -16,13 +16,8 @@ import { ConfirmDelete } from "~/components/Modals";import { usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { Part } from "~/modules/items";-import {- MethodIcon,- TrackingTypeIcon,- itemReplenishmentSystems,- itemTrackingTypes,- methodType,-} from "~/modules/items";+import { itemReplenishmentSystems, itemTrackingTypes } from "~/modules/items";+import { MethodIcon, TrackingTypeIcon, methodType } from "~/modules/shared";import { usePeople } from "~/stores";import type { ListItem } from "~/types";import { path } from "~/utils/path";diff --git a/apps/carbon/app/modules/items/ui/Services/ServiceProperties.tsx b/apps/carbon/app/modules/items/ui/Services/ServiceProperties.tsxindex dc658554f4..8ad054052f 100644--- a/apps/carbon/app/modules/items/ui/Services/ServiceProperties.tsx+++ b/apps/carbon/app/modules/items/ui/Services/ServiceProperties.tsx@@ -13,10 +13,10 @@ import { useParams } from "@remix-run/react";import { LuCopy, LuLink } from "react-icons/lu";import { Assignee, useOptimisticAssignment } from "~/components";import { useRouteData } from "~/hooks";+import { MethodBadge, MethodIcon } from "~/modules/shared";import { path } from "~/utils/path";import type { BuyMethod, ItemFile, PickMethod, Service } from "../../types";-import { FileBadge, MethodIcon } from "../Item";-import { MethodBadge } from "../Item/MethodBadge";+import { FileBadge } from "../Item";const ServiceProperties = () => {const { itemId } = useParams();diff --git a/apps/carbon/app/modules/items/ui/Services/ServicesTable.tsx b/apps/carbon/app/modules/items/ui/Services/ServicesTable.tsxindex 2410afaf9b..b2b007aad5 100644--- a/apps/carbon/app/modules/items/ui/Services/ServicesTable.tsx+++ b/apps/carbon/app/modules/items/ui/Services/ServicesTable.tsx@@ -16,7 +16,8 @@ import { ConfirmDelete } from "~/components/Modals";import { usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { Service } from "~/modules/items";-import { MethodIcon, methodType, serviceType } from "~/modules/items";+import { serviceType } from "~/modules/items";+import { MethodIcon, methodType } from "~/modules/shared";import { usePeople } from "~/stores";import { path } from "~/utils/path";diff --git a/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx b/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsxindex 6d7733f5aa..f9117d55b7 100644--- a/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx+++ b/apps/carbon/app/modules/items/ui/Tools/ToolProperties.tsx@@ -13,11 +13,11 @@ import { useParams } from "@remix-run/react";import { LuCopy, LuLink } from "react-icons/lu";import { Assignee, useOptimisticAssignment } from "~/components";import { useRouteData } from "~/hooks";+import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/modules/shared";import type { ListItem } from "~/types";import { path } from "~/utils/path";import type { BuyMethod, ItemFile, PickMethod, Tool } from "../../types";-import { FileBadge, MethodIcon, TrackingTypeIcon } from "../Item";-import { MethodBadge } from "../Item/MethodBadge";+import { FileBadge } from "../Item";const ToolProperties = () => {const { itemId } = useParams();diff --git a/apps/carbon/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/carbon/app/modules/items/ui/Tools/ToolsTable.tsxindex d51ca6b915..e813684e52 100644--- a/apps/carbon/app/modules/items/ui/Tools/ToolsTable.tsx+++ b/apps/carbon/app/modules/items/ui/Tools/ToolsTable.tsx@@ -15,12 +15,8 @@ import { ConfirmDelete } from "~/components/Modals";import { usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { Tool } from "~/modules/items";-import {- MethodIcon,- TrackingTypeIcon,- itemTrackingTypes,- methodType,-} from "~/modules/items";+import { itemTrackingTypes } from "~/modules/items";+import { MethodIcon, TrackingTypeIcon, methodType } from "~/modules/shared";import { usePeople } from "~/stores";import type { ListItem } from "~/types";import { path } from "~/utils/path";diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsxindex 4f25064ac1..e112295efe 100644--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx@@ -31,7 +31,7 @@ import {} from "~/components/Form";import { usePermissions, useRouteData, useUser } from "~/hooks";import { useSupabase } from "~/lib/supabase";-import { methodItemType, type getShelvesList } from "~/modules/items";+import type { getShelvesList } from "~/modules/items";import type {PurchaseOrder,PurchaseOrderLineType,@@ -40,6 +40,7 @@ import {purchaseOrderLineType,purchaseOrderLineValidator,} from "~/modules/purchasing";+import { methodItemType } from "~/modules/shared";import type { ListItem } from "~/types";import { path } from "~/utils/path";diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.tsindex 877ceace92..19e811fb1f 100644--- a/apps/carbon/app/modules/sales/sales.models.ts+++ b/apps/carbon/app/modules/sales/sales.models.ts@@ -2,7 +2,7 @@ import { z } from "zod";import { zfd } from "zod-form-data";import { address, contact } from "~/types/validators";import { currencyCodes } from "../accounting";-import { methodType } from "../items";+import { methodItemType, methodOperationOrders, methodType } from "../shared";import { standardFactorType } from "../shared/types";export const salesRFQStatusType = [@@ -150,6 +150,104 @@ export const quotationMaterialValidator = z.object({unitOfMeasureCode: zfd.text(z.string().optional()),});+export const quoteMaterialValidator = z+ .object({+ id: zfd.text(z.string().optional()),+ makeMethodId: z.string().min(20, { message: "Make method is required" }),+ order: zfd.numeric(z.number().min(0)),+ itemType: z.enum(methodItemType, {+ errorMap: (issue, ctx) => ({+ message: "Item type is required",+ }),+ }),+ methodType: z.enum(methodType, {+ errorMap: (issue, ctx) => ({+ message: "Method type is required",+ }),+ }),+ itemId: z.string().optional(),+ itemReadableId: z.string().optional(),+ description: zfd.text(z.string().optional()),+ methodOperationId: zfd.text(z.string().optional()),+ // description: z.string().min(1, { message: "Description is required" }),+ quantity: zfd.numeric(z.number().min(0)),+ unitOfMeasureCode: z+ .string()+ .min(1, { message: "Unit of Measure is required" }),+ })+ .refine(+ (data) => {+ if (data.itemType === "Part") {+ return !!data.itemReadableId;+ }+ return true;+ },+ {+ message: "Part ID is required",+ path: ["itemId"],+ }+ )+ .refine(+ (data) => {+ if (data.itemType === "Material") {+ return !!data.itemReadableId;+ }+ return true;+ },+ {+ message: "Material ID is required",+ path: ["itemId"],+ }+ )+ .refine(+ (data) => {+ if (data.itemType === "Fixture") {+ return !!data.itemReadableId;+ }+ return true;+ },+ {+ message: "Fixture ID is required",+ path: ["itemId"],+ }+ )+ .refine(+ (data) => {+ if (data.itemType === "Tool") {+ return !!data.itemReadableId;+ }+ return true;+ },+ {+ message: "Tool ID is required",+ path: ["itemId"],+ }+ )+ .refine(+ (data) => {+ if (data.itemType === "Consumable") {+ return !!data.itemReadableId;+ }+ return true;+ },+ {+ message: "Consumable ID is required",+ path: ["itemId"],+ }+ )+ .refine(+ (data) => {+ if (data.itemType === "Service") {+ return !!data.itemReadableId;+ }+ return true;+ },+ {+ message: "Service ID is required",+ path: ["itemId"],+ }+ );+export const quotationOperationValidator = z.object({id: zfd.text(z.string().optional()),quoteAssemblyId: zfd.text(z.string().optional()),@@ -168,6 +266,30 @@ export const quotationOperationValidator = z.object({overheadRate: zfd.numeric(z.number().min(0)),});+export const quoteOperationValidator = z.object({+ id: zfd.text(z.string().optional()),+ quoteMakeMethodId: z+ .string()+ .min(1, { message: "Quote Make Method is required" }),+ operationOrder: z.enum(methodOperationOrders, {+ errorMap: () => ({ message: "Operation Order is required" }),+ }),+ order: zfd.numeric(z.number().min(0)),+ workCellTypeId: z.string().min(20, { message: "Work cell is required" }),+ equipmentTypeId: zfd.text(z.string().optional()),+ description: zfd.text(+ z.string().min(0, { message: "Description is required" })+ ),+ setupHours: zfd.numeric(z.number().min(0)),+ standardFactor: z.enum(standardFactorType, {+ errorMap: () => ({ message: "Standard factor is required" }),+ }),+ productionStandard: zfd.numeric(z.number().min(0)),+ quotingRate: zfd.numeric(z.number().min(0)),+ laborRate: zfd.numeric(z.number().min(0)),+ overheadRate: zfd.numeric(z.number().min(0)),+});+export const quotationPricingValidator = z.object({quantity: zfd.numeric(z.number()),unitCost: zfd.numeric(z.number()),diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsxnew file mode 100644index 0000000000..f483091b51--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx@@ -0,0 +1,580 @@+"use client";+import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ cn,+ HStack,+ toast,+ useDebounce,+ VStack,+} from "@carbon/react";+import { ValidatedForm } from "@carbon/remix-validated-form";+import { useFetcher, useParams } from "@remix-run/react";+import { AnimatePresence, LayoutGroup, motion } from "framer-motion";+import type { Dispatch, SetStateAction } from "react";+import { useCallback, useEffect, useState } from "react";+import { flushSync } from "react-dom";+import { LuSettings2, LuX } from "react-icons/lu";+import type { z } from "zod";+import {+ DefaultMethodType,+ Hidden,+ InputControlled,+ Item,+ Number,+ Select,+ Submit,+ UnitOfMeasure,+} from "~/components/Form";+import type {+ Item as SortableItem,+ SortableItemRenderProps,+} from "~/components/SortableList";+import { SortableList, SortableListItem } from "~/components/SortableList";+import { useUser } from "~/hooks";+import { useSupabase } from "~/lib/supabase";+import type { MethodItemType, MethodType } from "~/modules/shared";+import {+ MethodIcon,+ methodItemType,+ MethodItemTypeIcon,+} from "~/modules/shared";+import { path } from "~/utils/path";+import type { quoteOperationValidator } from "../../sales.models";+import { quoteMaterialValidator } from "../../sales.models";++type Material = z.infer<typeof quoteMaterialValidator>;++type Operation = z.infer<typeof quoteOperationValidator>;++type ItemWithData = SortableItem & {+ data: Material;+};++type BillOfMaterialProps = {+ makeMethodId: string;+ materials: Material[];+ operations: Operation[];+};++function makeItems(materials: Material[]): ItemWithData[] {+ return materials.map(makeItem);+}++function makeItem(material: Material): ItemWithData {+ return {+ id: material.id!,+ title: (+ <VStack spacing={0}>+ <h4 className="font-mono">{material.itemReadableId}</h4>+ {material?.description && (+ <span className="text-xs text-muted-foreground">+ {material.description}{" "}+ </span>+ )}+ </VStack>+ ),+ checked: false,+ details: (+ <HStack spacing={2}>+ <Badge variant="secondary">+ <MethodIcon type={material.methodType} />+ </Badge>++ <Badge variant="secondary">{material.quantity}</Badge>+ <Badge variant="secondary">+ <MethodItemTypeIcon type={material.itemType} />+ </Badge>+ </HStack>+ ),+ data: material,+ };+}++const initialMethodMaterial: Omit<Material, "makeMethodId" | "order"> & {+ description: string;+} = {+ itemId: "",+ itemReadableId: "",+ itemType: "Part" as const,+ methodType: "Buy" as const,+ description: "",+ quantity: 1,+ unitOfMeasureCode: "EA",+};++const BillOfMaterial = ({+ makeMethodId,+ materials,+ operations,+}: BillOfMaterialProps) => {+ const fetcher = useFetcher<{}>();++ const [items, setItems] = useState<ItemWithData[]>(+ makeItems(materials ?? [])+ );+ const [selectedItemId, setSelectedItemId] = useState<string | null>(null);++ const onToggleItem = (id: string) => {+ setItems((prevItems) =>+ prevItems.map((item) =>+ item.id === id ? { ...item, checked: !item.checked } : item+ )+ );+ };++ // we create a temporary item and append it to the list+ const onAddItem = () => {+ const temporaryId = Math.random().toString(16).slice(2);+ setSelectedItemId(temporaryId);+ setItems((prevItems) => {+ let newOrder = 1;+ if (prevItems.length) {+ newOrder = prevItems[prevItems.length - 1].data.order + 1;+ }++ return [+ ...prevItems,+ {+ title: "",+ checked: false,+ id: temporaryId,+ data: {+ ...initialMethodMaterial,+ order: newOrder,+ makeMethodId,+ },+ },+ ];+ });+ };++ const onRemoveItem = async (id: string) => {+ // get the item and it's order in the list+ const itemIndex = items.findIndex((i) => i.id === id);+ const item = items[itemIndex];++ setItems((prevItems) => prevItems.filter((item) => item.id !== id));++ fetcher.submit(new FormData(), {+ method: "post",+ action: path.to.deleteMethodMaterial(makeMethodId, item.id),+ });+ };++ const onReorder = (reorderedItems: ItemWithData[]) => {+ const newItems = reorderedItems.map((item, index) => ({+ ...item,+ data: {+ ...item.data,+ order: index + 1,+ },+ }));+ const updates = newItems.reduce<Record<string, number>>((acc, item) => {+ if (!isTemporaryId(item.id)) {+ acc[item.id] = item.data.order;+ }+ return acc;+ }, {});++ setItems(reorderedItems);+ updateSortOrder(updates);+ };++ const updateSortOrder = useDebounce((updates: Record<string, number>) => {+ let formData = new FormData();+ formData.append("updates", JSON.stringify(updates));+ fetcher.submit(formData, {+ method: "post",+ action: path.to.methodMaterialsOrder(makeMethodId),+ });+ }, 1000);++ const onCloseOnDrag = useCallback(() => {+ setItems((prevItems) => {+ const updatedItems = prevItems.map((item) =>+ item.checked ? { ...item, checked: false } : item+ );+ return updatedItems.some(+ (item, index) => item.checked !== prevItems[index].checked+ )+ ? updatedItems+ : prevItems;+ });+ }, []);++ const renderListItem = ({+ item,+ items,+ order,+ onToggleItem,+ onRemoveItem,+ }: SortableItemRenderProps<ItemWithData>) => {+ const isOpen = item.id === selectedItemId;++ return (+ <SortableListItem<Material>+ item={item}+ items={items}+ order={order}+ key={item.id}+ isExpanded={isOpen}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ handleDrag={onCloseOnDrag}+ className="my-2 "+ renderExtra={(item) => (+ <div+ key={`${isOpen}`}+ className={cn(+ "flex h-full flex-col items-center justify-center pl-2",+ isOpen ? "py-1" : "py-3 "+ )}+ >+ <motion.button+ layout+ onClick={+ isOpen+ ? () => {+ if (isTemporaryId(item.id)) {+ setItems((prevItems) =>+ prevItems.filter((i) => i.id !== item.id)+ );+ }+ setSelectedItemId(null);+ }+ : () => {+ setSelectedItemId(item.id);+ }+ }+ key="collapse"+ className={cn(+ isOpen+ ? "absolute right-3 top-3 z-10 "+ : "relative z-10 ml-auto mr-3 "+ )}+ >+ {isOpen ? (+ <motion.span+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ exit={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ duration: 1.95,+ }}+ >+ <LuX className="h-5 w-5 text-foreground" />+ </motion.span>+ ) : (+ <motion.span+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ exit={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ duration: 0.95,+ }}+ >+ <LuSettings2 className="stroke-1 h-5 w-5 text-foreground/80 hover:stroke-primary/70 " />+ </motion.span>+ )}+ </motion.button>++ <LayoutGroup id={`${item.id}`}>+ <AnimatePresence mode="popLayout">+ {isOpen ? (+ <motion.div className="flex w-full flex-col ">+ <div className=" w-full p-2">+ <motion.div+ initial={{+ y: 0,+ opacity: 0,+ filter: "blur(4px)",+ }}+ animate={{+ y: 0,+ opacity: 1,+ filter: "blur(0px)",+ }}+ transition={{+ type: "spring",+ duration: 0.15,+ }}+ layout+ className="w-full "+ >+ <motion.div+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ bounce: 0.2,+ duration: 0.75,+ delay: 0.15,+ }}+ >+ <MaterialForm+ item={item}+ setItems={setItems}+ setSelectedItemId={setSelectedItemId}+ methodOperations={operations}+ />+ </motion.div>+ </motion.div>+ </div>+ </motion.div>+ ) : null}+ </AnimatePresence>+ </LayoutGroup>+ </div>+ )}+ />+ );+ };++ return (+ <Card>+ <HStack className="justify-between">+ <CardHeader>+ <CardTitle>Bill of Material</CardTitle>+ </CardHeader>++ <CardAction>+ <Button+ variant="secondary"+ isDisabled={selectedItemId !== null}+ onClick={onAddItem}+ >+ Add Material+ </Button>+ </CardAction>+ </HStack>+ <CardContent>+ <SortableList+ items={items}+ onReorder={onReorder}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ renderItem={renderListItem}+ />+ </CardContent>+ </Card>+ );+};++export default BillOfMaterial;++function isTemporaryId(id: string) {+ return id.length < 20;+}++function MaterialForm({+ item,+ setItems,+ setSelectedItemId,+ methodOperations,+}: {+ item: ItemWithData;+ setItems: Dispatch<SetStateAction<ItemWithData[]>>;+ setSelectedItemId: Dispatch<SetStateAction<string | null>>;+ methodOperations: Operation[];+}) {+ const { supabase } = useSupabase();+ const methodMaterialFetcher = useFetcher<{ id: string }>();+ const params = useParams();+ const { company } = useUser();++ useEffect(() => {+ // replace the temporary id with the actual id+ if (methodMaterialFetcher.data && methodMaterialFetcher.data.id) {+ flushSync(() => {+ setItems((prevItems) =>+ prevItems.map((i) =>+ i.id === item.id+ ? {+ ...i,+ id: methodMaterialFetcher.data!.id!,+ data: {+ ...i.data,+ ...methodMaterialFetcher.data,+ },+ }+ : i+ )+ );+ });+ setSelectedItemId(null);+ }+ }, [item.id, methodMaterialFetcher.data, setItems, setSelectedItemId]);++ const [itemType, setItemType] = useState<MethodItemType>(item.data.itemType);+ const [itemData, setItemData] = useState<{+ itemId: string;+ itemReadableId: string;+ methodType: MethodType;+ description: string;+ unitOfMeasureCode: string;+ quantity: number;+ }>({+ itemId: item.data.itemId ?? "",+ itemReadableId: item.data.itemReadableId ?? "",+ methodType: item.data.methodType ?? "Buy",+ description: item.data.description ?? "",+ unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",+ quantity: item.data.quantity ?? 1,+ });++ const onTypeChange = (value: MethodItemType) => {+ setItemType(value);+ setItemData({+ itemId: "",+ itemReadableId: "",+ methodType: "" as "Buy",+ quantity: 1,+ description: "",+ unitOfMeasureCode: "EA",+ });+ };++ const onItemChange = async (itemId: string) => {+ if (!supabase) return;+ if (itemId === params.itemId) {+ toast.error("An item cannot be added to itself.");+ return;+ }++ const item = await supabase+ .from("item")+ .select("name, readableId, unitOfMeasureCode, defaultMethodType")+ .eq("id", itemId)+ .eq("companyId", company.id)+ .single();++ if (item.error) {+ toast.error("Failed to load item details");+ return;+ }++ setItemData((d) => ({+ ...d,+ itemId,+ itemReadableId: item.data?.readableId ?? "",+ description: item.data?.name ?? "",+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",+ methodType: item.data?.defaultMethodType ?? "Buy",+ }));+ };++ return (+ <ValidatedForm+ action={+ isTemporaryId(item.id)+ ? path.to.newMethodMaterial(item.data.makeMethodId!)+ : path.to.methodMaterial(item.data.makeMethodId, item.id!)+ }+ method="post"+ defaultValues={item.data}+ validator={quoteMaterialValidator}+ className="w-full"+ fetcher={methodMaterialFetcher}+ onSubmit={(values) => {+ setItems((prevItems) =>+ prevItems.map((i) =>+ i.id === item.id+ ? {+ ...makeItem({ ...values, description: itemData.description }),+ id: item.id,+ }+ : i+ )+ );+ }}+ >+ <Hidden name="makeMethodId" />+ <Hidden name="itemReadableId" value={itemData.itemReadableId} />+ <Hidden name="order" />+ <VStack className="pt-4">+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">+ <Select+ name="itemType"+ label="Type"+ options={methodItemType.map((value) => ({+ value,+ label: value,+ }))}+ onChange={(value) => {+ onTypeChange(value?.value as MethodItemType);+ }}+ />+ <Item+ disabledItems={[params.itemId!]}+ name="itemId"+ label={itemType}+ // @ts-ignore+ type={itemType}+ onChange={(value) => {+ onItemChange(value?.value as string);+ }}+ />+ <Select+ name="methodOperationId"+ label="Operation"+ isClearable+ options={methodOperations.map((o) => ({+ value: o.id!,+ label: o.description,+ }))}+ />+ </div>+ <InputControlled+ name="description"+ label="Description"+ value={itemData.description}+ onChange={(newValue) => {+ setItemData((d) => ({ ...d, description: newValue }));+ }}+ />+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">+ <DefaultMethodType+ name="methodType"+ label="Method Type"+ value={itemData.methodType}+ replenishmentSystem="Buy and Make"+ />+ <Number name="quantity" label="Quantity" />+ <UnitOfMeasure+ name="unitOfMeasureCode"+ value={itemData.unitOfMeasureCode}+ onChange={(newValue) =>+ setItemData((d) => ({+ ...d,+ unitOfMeasureCode: newValue?.value ?? "EA",+ }))+ }+ />+ </div>++ <motion.div+ className="flex w-full items-center justify-end p-2"+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ bounce: 0,+ duration: 0.55,+ }}+ >+ <motion.div layout className="ml-auto mr-1 pt-2">+ <Submit>Save</Submit>+ </motion.div>+ </motion.div>+ </VStack>+ </ValidatedForm>+ );+}diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsxnew file mode 100644index 0000000000..d44f773f31--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx@@ -0,0 +1,593 @@+"use client";+import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ HStack,+ cn,+ useDebounce,+} from "@carbon/react";+import { ValidatedForm } from "@carbon/remix-validated-form";+import { useFetcher } from "@remix-run/react";+import { AnimatePresence, LayoutGroup, motion } from "framer-motion";+import type { Dispatch, SetStateAction } from "react";+import { useCallback, useEffect, useState } from "react";+import { flushSync } from "react-dom";+import { LuSettings2, LuX } from "react-icons/lu";+import type { z } from "zod";+import {+ EquipmentType,+ Hidden,+ InputControlled,+ Number,+ NumberControlled,+ Select,+ StandardFactor,+ Submit,+ WorkCellType,+} from "~/components/Form";+import type { Item, SortableItemRenderProps } from "~/components/SortableList";+import { SortableList, SortableListItem } from "~/components/SortableList";+import { useSupabase } from "~/lib/supabase";+import { methodOperationOrders } from "~/modules/shared";+import { path } from "~/utils/path";+import { quoteOperationValidator } from "../../sales.models";++type Operation = z.infer<typeof quoteOperationValidator>;++type ItemWithData = Item & {+ data: Operation;+};++type BillOfProcessProps = {+ quoteMakeMethodId: string;+ operations: Operation[];+};++function makeItems(operations: Operation[]): ItemWithData[] {+ return operations.map(makeItem);+}++function makeItem(operation: Operation): ItemWithData {+ return {+ id: operation.id!,+ title: operation.description ?? "",+ checked: false,+ order: operation.operationOrder,+ details: (+ <HStack spacing={1}>+ <Badge variant="secondary">+ {operation.productionStandard} {operation.standardFactor}+ </Badge>+ <Badge variant="secondary">{operation.operationOrder}</Badge>+ </HStack>+ ),+ data: operation,+ };+}++const initialMethodOperation: Omit<Operation, "quoteMakeMethodId" | "order"> = {+ description: "",+ workCellTypeId: "",+ equipmentTypeId: "",+ setupHours: 0,+ productionStandard: 0,+ standardFactor: "Hours/Piece",+ operationOrder: "After Previous",+ quotingRate: 0,+ laborRate: 0,+ overheadRate: 0,+};++const BillOfProcess = ({+ quoteMakeMethodId,+ operations,+}: BillOfProcessProps) => {+ const { supabase } = useSupabase();+ const sortOrderFetcher = useFetcher<{}>();++ const [items, setItems] = useState<ItemWithData[]>(+ makeItems(operations ?? [])+ );+ const [selectedItemId, setSelectedItemId] = useState<string | null>(null);++ const onToggleItem = (id: string) => {+ setItems((prevItems) =>+ prevItems.map((item) =>+ item.id === id ? { ...item, checked: !item.checked } : item+ )+ );+ };++ // we create a temporary item and append it to the list+ const onAddItem = () => {+ const temporaryId = Math.random().toString(16).slice(2);+ setSelectedItemId(temporaryId);+ setItems((prevItems) => {+ let newOrder = 1;+ if (prevItems.length) {+ newOrder = prevItems[prevItems.length - 1].data.order + 1;+ }++ return [+ ...prevItems,+ {+ title: "",+ checked: false,+ id: temporaryId,+ data: {+ ...initialMethodOperation,+ order: newOrder,+ quoteMakeMethodId,+ },+ },+ ];+ });+ };++ const onRemoveItem = async (id: string) => {+ // get the item and it's order in the list+ const itemIndex = items.findIndex((i) => i.id === id);+ const item = items[itemIndex];++ setItems((prevItems) => prevItems.filter((item) => item.id !== id));++ const response = await supabase+ ?.from("methodOperation")+ .delete()+ .eq("id", id);+ if (response?.error) {+ // add the item back to the list if there was an error+ setItems((prevItems) => {+ const updatedItems = [...prevItems];+ updatedItems.splice(itemIndex, 0, item);+ return updatedItems;+ });+ }+ };++ const onReorder = (items: ItemWithData[]) => {+ const newItems = items.map((item, index) => ({+ ...item,+ data: {+ ...item.data,+ order: index + 1,+ },+ }));+ const updates = newItems.reduce<Record<string, number>>((acc, item) => {+ if (!isTemporaryId(item.id)) {+ acc[item.id] = item.data.order;+ }+ return acc;+ }, {});++ setItems(newItems);+ updateSortOrder(updates);+ };++ const updateSortOrder = useDebounce((updates: Record<string, number>) => {+ let formData = new FormData();+ formData.append("updates", JSON.stringify(updates));+ sortOrderFetcher.submit(formData, {+ method: "post",+ action: path.to.methodOperationsOrder(quoteMakeMethodId),+ });+ }, 1000);++ const onCloseOnDrag = useCallback(() => {+ setItems((prevItems) => {+ const updatedItems = prevItems.map((item) =>+ item.checked ? { ...item, checked: false } : item+ );+ return updatedItems.some(+ (item, index) => item.checked !== prevItems[index].checked+ )+ ? updatedItems+ : prevItems;+ });+ }, []);++ const renderListItem = ({+ item,+ items,+ order,+ onToggleItem,+ onRemoveItem,+ }: SortableItemRenderProps<ItemWithData>) => {+ const isOpen = item.id === selectedItemId;++ return (+ <SortableListItem<Operation>+ item={item}+ items={items}+ order={order}+ key={item.id}+ isExpanded={isOpen}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ handleDrag={onCloseOnDrag}+ className="my-2 "+ renderExtra={(item) => (+ <div+ key={`${isOpen}`}+ className={cn(+ "flex h-full flex-col items-center justify-center gap-2 pl-2",+ isOpen ? "py-1" : "py-3 "+ )}+ >+ <motion.button+ layout+ onClick={+ isOpen+ ? () => {+ if (isTemporaryId(item.id)) {+ setItems((prevItems) =>+ prevItems.filter((i) => i.id !== item.id)+ );+ }+ setSelectedItemId(null);+ }+ : () => {+ setSelectedItemId(item.id);+ }+ }+ key="collapse"+ className={cn(+ isOpen+ ? "absolute right-3 top-3 z-10 "+ : "relative z-10 ml-auto mr-3 "+ )}+ >+ {isOpen ? (+ <motion.span+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ exit={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ duration: 1.95,+ }}+ >+ <LuX className="h-5 w-5 text-foreground" />+ </motion.span>+ ) : (+ <motion.span+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ exit={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ duration: 0.95,+ }}+ >+ <LuSettings2 className="stroke-1 h-5 w-5 text-foreground/80 hover:stroke-primary/70 " />+ </motion.span>+ )}+ </motion.button>++ <LayoutGroup id={`${item.id}`}>+ <AnimatePresence mode="popLayout">+ {isOpen ? (+ <motion.div className="flex w-full flex-col ">+ <div className=" w-full p-2">+ <motion.div+ initial={{+ y: 0,+ opacity: 0,+ filter: "blur(4px)",+ }}+ animate={{+ y: 0,+ opacity: 1,+ filter: "blur(0px)",+ }}+ transition={{+ type: "spring",+ duration: 0.15,+ }}+ layout+ className="w-full "+ >+ <div className="flex w-full flex-col pr-2 py-2">+ <motion.div+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ bounce: 0.2,+ duration: 0.75,+ delay: 0.15,+ }}+ >+ <OperationForm+ item={item}+ setItems={setItems}+ setSelectedItemId={setSelectedItemId}+ />+ </motion.div>+ </div>+ </motion.div>+ </div>+ </motion.div>+ ) : null}+ </AnimatePresence>+ </LayoutGroup>+ </div>+ )}+ />+ );+ };++ return (+ <Card>+ <HStack className="justify-between">+ <CardHeader>+ <CardTitle>Bill of Process</CardTitle>+ </CardHeader>++ <CardAction>+ <Button+ variant="secondary"+ isDisabled={selectedItemId !== null}+ onClick={onAddItem}+ >+ Add Operation+ </Button>+ </CardAction>+ </HStack>+ <CardContent>+ <SortableList+ items={items}+ onReorder={onReorder}+ onToggleItem={onToggleItem}+ onRemoveItem={onRemoveItem}+ renderItem={renderListItem}+ />+ </CardContent>+ </Card>+ );+};++export default BillOfProcess;++function isTemporaryId(id: string) {+ return id.length < 20;+}++function OperationForm({+ item,+ setItems,+ setSelectedItemId,+}: {+ item: ItemWithData;+ setItems: Dispatch<SetStateAction<ItemWithData[]>>;+ setSelectedItemId: Dispatch<SetStateAction<string | null>>;+}) {+ const methodOperationFetcher = useFetcher<{ id: string }>();+ const { supabase } = useSupabase();++ useEffect(() => {+ // replace the temporary id with the actual id+ if (methodOperationFetcher.data && methodOperationFetcher.data.id) {+ flushSync(() => {+ setItems((prevItems) =>+ prevItems.map((i) =>+ i.id === item.id+ ? {+ ...i,+ id: methodOperationFetcher.data!.id!,+ data: {+ ...i.data,+ ...methodOperationFetcher.data,+ },+ }+ : i+ )+ );+ });+ setSelectedItemId(null);+ }+ }, [item.id, methodOperationFetcher.data, setItems, setSelectedItemId]);++ const [workCellData, setWorkCellData] = useState<{+ workCellTypeId: string;+ description: string;+ standardFactor: string;+ quotingRate: number;+ laborRate: number;+ overheadRate: number;+ }>({+ workCellTypeId: item.data.workCellTypeId ?? "",+ description: item.data.description ?? "",+ standardFactor: item.data.standardFactor ?? "Hours/Piece",+ quotingRate: item.data.quotingRate ?? 0,+ laborRate: item.data.laborRate ?? 0,+ overheadRate: item.data.overheadRate ?? 0,+ });++ const onWorkCellChange = async (workCellTypeId: string) => {+ if (!supabase || !workCellTypeId) return;+ const { data, error } = await supabase+ .from("workCellType")+ .select("*")+ .eq("id", workCellTypeId)+ .single();++ if (error) throw new Error(error.message);++ setWorkCellData({+ workCellTypeId,+ description: data?.name ?? "",+ standardFactor: data?.defaultStandardFactor ?? "Hours/Piece",+ quotingRate: data?.quotingRate ?? 0,+ laborRate: data?.laborRate ?? 0,+ overheadRate: data?.overheadRate ?? 0,+ });+ };++ const [equipmentData, setEquipmentData] = useState<{+ equipmentTypeId: string;+ setupHours: number;+ }>({+ equipmentTypeId: item.data.equipmentTypeId ?? "",+ setupHours: item.data.setupHours ?? 0,+ });++ const onEquipmentChange = async (equipmentTypeId: string) => {+ if (!supabase || !equipmentTypeId) return;+ const { data, error } = await supabase+ .from("equipmentType")+ .select("*")+ .eq("id", equipmentTypeId)+ .single();++ if (error) throw new Error(error.message);++ setEquipmentData({+ equipmentTypeId,+ setupHours: data?.setupHours ?? 0,+ });+ };++ return (+ <ValidatedForm+ action={+ isTemporaryId(item.id)+ ? path.to.newMethodOperation(item.data.quoteMakeMethodId!)+ : path.to.methodOperation(item.data.quoteMakeMethodId, item.id!)+ }+ method="post"+ defaultValues={item.data}+ validator={quoteOperationValidator}+ className="w-full flex flex-col gap-y-4"+ fetcher={methodOperationFetcher}+ onSubmit={(values) => {+ setItems((prevItems) =>+ prevItems.map((i) =>+ i.id === item.id+ ? {+ ...makeItem(values),+ id: item.id,+ }+ : i+ )+ );+ }}+ >+ <Hidden name="quoteMakeMethodId" />+ <Hidden name="order" />+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">+ <WorkCellType+ name="workCellTypeId"+ label="Work Cell"+ onChange={(value) => {+ onWorkCellChange(value?.value as string);+ }}+ />+ <EquipmentType+ name="equipmentTypeId"+ label="Equipment"+ onChange={(value) => onEquipmentChange(value?.value as string)}+ />+ <Select+ name="operationOrder"+ label="Operation Order"+ placeholder="Operation Order"+ options={methodOperationOrders.map((o) => ({+ value: o,+ label: o,+ }))}+ />+ </div>+ <InputControlled+ name="description"+ label="Description"+ value={workCellData.description}+ onChange={(newValue) => {+ setWorkCellData((d) => ({ ...d, description: newValue }));+ }}+ />+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">+ <NumberControlled+ name="setupHours"+ label="Setup Time (hours)"+ minValue={0}+ value={equipmentData.setupHours}+ onChange={(newValue) => {+ setEquipmentData((d) => ({ ...d, setupHours: newValue }));+ }}+ />+ <Number+ name="productionStandard"+ label="Production Standard"+ minValue={0}+ />+ <StandardFactor+ name="standardFactor"+ label="Standard Factor"+ value={workCellData.standardFactor}+ onChange={(newValue) => {+ setWorkCellData((d) => ({+ ...d,+ standardFactor: newValue?.value ?? "Hours/Piece",+ }));+ }}+ />+ <NumberControlled+ name="quotingRate"+ label="Quoting Rate"+ minValue={0}+ value={workCellData.quotingRate}+ onChange={(newValue) =>+ setWorkCellData((d) => ({+ ...d,+ quotingRate: newValue,+ }))+ }+ />+ <NumberControlled+ name="laborRate"+ label="Labor Rate"+ minValue={0}+ value={workCellData.laborRate}+ onChange={(newValue) =>+ setWorkCellData((d) => ({+ ...d,+ laborRate: newValue,+ }))+ }+ />+ <NumberControlled+ name="overheadRate"+ label="Overhead Rate"+ minValue={0}+ value={workCellData.overheadRate}+ onChange={(newValue) =>+ setWorkCellData((d) => ({+ ...d,+ overheadRate: newValue,+ }))+ }+ />+ </div>+ <motion.div+ className="flex w-full items-center justify-end p-2"+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ bounce: 0,+ duration: 0.55,+ }}+ >+ <motion.div layout className="ml-auto mr-1 pt-2">+ <Submit>Save</Submit>+ </motion.div>+ </motion.div>+ </ValidatedForm>+ );+}diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsxindex 27dd6afbf6..b1c3ba8069 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx@@ -4,10 +4,7 @@ import { LuChevronDown, LuChevronUp } from "react-icons/lu";import type { FlatTreeItem } from "~/components/TreeView/TreeView";import { TreeView, useTree } from "~/components/TreeView/TreeView";import type { Method } from "~/modules/items/types";-import {- MethodIcon,- MethodItemTypeIcon,-} from "~/modules/items/ui/Item/MethodIcon";+import { MethodIcon, MethodItemTypeIcon } from "~/modules/shared";type QuoteBoMExplorerProps = {methods: FlatTreeItem<Method>[];diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsxindex 87d2a81c5e..790394c830 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx@@ -37,13 +37,13 @@ import {} from "~/components/Form";import { usePermissions, useRouteData, useUser } from "~/hooks";import { useSupabase } from "~/lib/supabase";-import { methodType } from "~/modules/items";import type { Quotation, QuotationLine } from "~/modules/sales";import {DeleteQuoteLine,quoteLineStatusType,quoteLineValidator,} from "~/modules/sales";+import { methodType } from "~/modules/shared";import { path } from "~/utils/path";type QuoteLineFormProps = {diff --git a/apps/carbon/app/modules/shared/shared.models.ts b/apps/carbon/app/modules/shared/shared.models.tsindex 11cf4bd1ae..7889a9c2da 100644--- a/apps/carbon/app/modules/shared/shared.models.ts+++ b/apps/carbon/app/modules/shared/shared.models.ts@@ -1,6 +1,22 @@import { z } from "zod";import { zfd } from "zod-form-data";+export const methodItemType = [+ "Part",+ "Material",+ "Tool",+ "Fixture",+ "Consumable",+ "Service",+] as const;++export const methodOperationOrders = [+ "After Previous",+ "With Previous",+] as const;++export const methodType = ["Buy", "Make", "Pick"] as const;+export const noteValidator = z.object({id: zfd.text(z.string().optional()),documentId: z.string().min(1),diff --git a/apps/carbon/app/modules/shared/types.ts b/apps/carbon/app/modules/shared/types.tsindex d71ea77bea..1f15d4837b 100644--- a/apps/carbon/app/modules/shared/types.ts+++ b/apps/carbon/app/modules/shared/types.ts@@ -1,3 +1,4 @@+import type { methodItemType, methodType } from "./shared.models";import type { getNotes } from "./shared.service";export type BillOfMaterialNodeType =@@ -28,6 +29,9 @@ export enum DataType {User = 6,}+export type MethodItemType = (typeof methodItemType)[number];+export type MethodType = (typeof methodType)[number];+export type Note = NonNullable<Awaited<ReturnType<typeof getNotes>>["data"]>[number];diff --git a/apps/carbon/app/modules/items/ui/Item/MethodBadge.tsx b/apps/carbon/app/modules/shared/ui/MethodBadge.tsxsimilarity index 95%rename from apps/carbon/app/modules/items/ui/Item/MethodBadge.tsxrename to apps/carbon/app/modules/shared/ui/MethodBadge.tsxindex b355660043..e2c0fcb147 100644--- a/apps/carbon/app/modules/items/ui/Item/MethodBadge.tsx+++ b/apps/carbon/app/modules/shared/ui/MethodBadge.tsx@@ -1,7 +1,7 @@import { Badge, HStack, cn } from "@carbon/react";import { Link } from "@remix-run/react";import { LuExternalLink } from "react-icons/lu";-import type { MethodType } from "../../types";+import type { MethodType } from "../types";import { MethodIcon } from "./MethodIcon";type MethodBadgeProps = {diff --git a/apps/carbon/app/modules/items/ui/Item/MethodIcon.tsx b/apps/carbon/app/modules/shared/ui/MethodIcon.tsxsimilarity index 100%rename from apps/carbon/app/modules/items/ui/Item/MethodIcon.tsxrename to apps/carbon/app/modules/shared/ui/MethodIcon.tsxdiff --git a/apps/carbon/app/modules/shared/ui/index.ts b/apps/carbon/app/modules/shared/ui/index.tsindex 54614d1c6c..e5ace07958 100644--- a/apps/carbon/app/modules/shared/ui/index.ts+++ b/apps/carbon/app/modules/shared/ui/index.ts@@ -1,5 +1,15 @@import CadModelUpload from "./CadModelUpload";+import { MethodBadge } from "./MethodBadge";+import { MethodIcon, MethodItemTypeIcon, TrackingTypeIcon } from "./MethodIcon";import Notes from "./Notes";import RealtimeDataProvider from "./RealtimeDataProvider";-export { CadModelUpload, Notes, RealtimeDataProvider };+export {+ CadModelUpload,+ MethodBadge,+ MethodIcon,+ MethodItemTypeIcon,+ Notes,+ RealtimeDataProvider,+ TrackingTypeIcon,+};diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsxindex 3ef1d13e77..718d6099f2 100644--- a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx@@ -3,7 +3,6 @@ import { VStack } from "@carbon/react";import type { LoaderFunctionArgs } from "@remix-run/node";import { json, redirect, useLoaderData, useParams } from "@remix-run/react";-import type { MethodItemType, MethodType } from "~/modules/items";import {BillOfMaterial,BillOfProcess,@@ -13,6 +12,7 @@ import {getMethodMaterials,getMethodOperations,} from "~/modules/items";+import type { MethodItemType, MethodType } from "~/modules/shared";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { path } from "~/utils/path";diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.tsxindex 183ebe8e69..6f6e874f05 100644--- a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.tsx+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.tsx@@ -17,13 +17,7 @@ import {import type { FlatTreeItem } from "~/components/TreeView/TreeView";import { flattenTree } from "~/components/TreeView/TreeView";-import { useRouteData } from "~/hooks";-import type {- Fixture,- Method,- MethodItemType,- MethodType,-} from "~/modules/items";+import type { Method } from "~/modules/items";import {BoMExplorer,getMakeMethod,@@ -31,6 +25,7 @@ import {getMethodOperations,getMethodTree,} from "~/modules/items";+import type { MethodItemType, MethodType } from "~/modules/shared";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { path } from "~/utils/path";@@ -121,10 +116,6 @@ export default function FixtureManufacturing() {const { itemId } = params;if (!itemId) throw new Error("Could not find itemId");- const routeData = useRouteData<{- fixtureSummary: Fixture;- }>(path.to.fixture(itemId));-return (<div className="flex flex-grow overflow-hidden"><ClientOnly fallback={null}>diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsxindex fc64a46cce..ac9f720432 100644--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx@@ -3,7 +3,6 @@ import { VStack } from "@carbon/react";import type { LoaderFunctionArgs } from "@remix-run/node";import { json, redirect, useLoaderData, useParams } from "@remix-run/react";-import type { MethodItemType, MethodType } from "~/modules/items";import {BillOfMaterial,BillOfProcess,@@ -13,6 +12,7 @@ import {getMethodMaterials,getMethodOperations,} from "~/modules/items";+import type { MethodItemType, MethodType } from "~/modules/shared";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { path } from "~/utils/path";diff --git a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsxindex 30b80a2791..cc6e3e8fd8 100644--- a/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx+++ b/apps/carbon/app/routes/x+/part+/$itemId.manufacturing.tsx@@ -17,7 +17,7 @@ import {import type { FlatTreeItem } from "~/components/TreeView/TreeView";import { flattenTree } from "~/components/TreeView/TreeView";-import type { Method, MethodItemType, MethodType } from "~/modules/items";+import type { Method } from "~/modules/items";import {BoMExplorer,getMakeMethod,@@ -25,6 +25,7 @@ import {getMethodOperations,getMethodTree,} from "~/modules/items";+import type { MethodItemType, MethodType } from "~/modules/shared";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";import { path } from "~/utils/path";diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex bd9178b0f7..2360304e21 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -13424,6 +13424,7 @@ export type Database = {itemId: stringitemType: stringmethodType: Database["public"]["Enums"]["methodType"]+ order: numberquantity: numberquoteId: stringquoteLineId: string@@ -13444,6 +13445,7 @@ export type Database = {itemId: stringitemType?: stringmethodType?: Database["public"]["Enums"]["methodType"]+ order?: numberquantity?: numberquoteId: stringquoteLineId: string@@ -13464,6 +13466,7 @@ export type Database = {itemId?: stringitemType?: stringmethodType?: Database["public"]["Enums"]["methodType"]+ order?: numberquantity?: numberquoteId?: stringquoteLineId?: string@@ -13655,6 +13658,8 @@ export type Database = {equipmentTypeId: string | nullid: stringlaborRate: number+ operationOrder: Database["public"]["Enums"]["methodOperationOrder"]+ order: numberoverheadRate: numberproductionStandard: numberquoteId: string@@ -13676,6 +13681,8 @@ export type Database = {equipmentTypeId?: string | nullid?: stringlaborRate?: number+ operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]+ order?: numberoverheadRate?: numberproductionStandard?: numberquoteId: string@@ -13697,6 +13704,8 @@ export type Database = {equipmentTypeId?: string | nullid?: stringlaborRate?: number+ operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]+ order?: numberoverheadRate?: numberproductionStandard?: numberquoteId?: string@@ -25404,6 +25413,26 @@ export type Database = {}Returns: string[]}+ get_quote_methods: {+ Args: {+ qid: string+ }+ Returns: {+ quoteId: string+ quoteLineId: string+ parentMaterialId: string+ parentItemId: string+ quantityPerParent: number+ quoteMaterialId: string+ itemId: string+ itemType: string+ methodType: string+ order: number+ quantity: number+ unitOfMeasureCode: string+ unitCost: number+ }[]+ }groups_for_user: {Args: {uid: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex bd9178b0f7..2360304e21 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -13424,6 +13424,7 @@ export type Database = {itemId: stringitemType: stringmethodType: Database["public"]["Enums"]["methodType"]+ order: numberquantity: numberquoteId: stringquoteLineId: string@@ -13444,6 +13445,7 @@ export type Database = {itemId: stringitemType?: stringmethodType?: Database["public"]["Enums"]["methodType"]+ order?: numberquantity?: numberquoteId: stringquoteLineId: string@@ -13464,6 +13466,7 @@ export type Database = {itemId?: stringitemType?: stringmethodType?: Database["public"]["Enums"]["methodType"]+ order?: numberquantity?: numberquoteId?: stringquoteLineId?: string@@ -13655,6 +13658,8 @@ export type Database = {equipmentTypeId: string | nullid: stringlaborRate: number+ operationOrder: Database["public"]["Enums"]["methodOperationOrder"]+ order: numberoverheadRate: numberproductionStandard: numberquoteId: string@@ -13676,6 +13681,8 @@ export type Database = {equipmentTypeId?: string | nullid?: stringlaborRate?: number+ operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]+ order?: numberoverheadRate?: numberproductionStandard?: numberquoteId: string@@ -13697,6 +13704,8 @@ export type Database = {equipmentTypeId?: string | nullid?: stringlaborRate?: number+ operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]+ order?: numberoverheadRate?: numberproductionStandard?: numberquoteId?: string@@ -25404,6 +25413,26 @@ export type Database = {}Returns: string[]}+ get_quote_methods: {+ Args: {+ qid: string+ }+ Returns: {+ quoteId: string+ quoteLineId: string+ parentMaterialId: string+ parentItemId: string+ quantityPerParent: number+ quoteMaterialId: string+ itemId: string+ itemType: string+ methodType: string+ order: number+ quantity: number+ unitOfMeasureCode: string+ unitCost: number+ }[]+ }groups_for_user: {Args: {uid: stringdiff --git a/packages/database/supabase/migrations/20240715024405_quotes.sql b/packages/database/supabase/migrations/20240715024405_quotes.sqlindex 38ce2af9f1..2655eceed7 100644--- a/packages/database/supabase/migrations/20240715024405_quotes.sql+++ b/packages/database/supabase/migrations/20240715024405_quotes.sql@@ -100,10 +100,11 @@ CREATE TABLE "quoteMaterial" ("itemId" TEXT NOT NULL,"itemType" TEXT NOT NULL DEFAULT 'Part',"methodType" "methodType" NOT NULL DEFAULT 'Make',+ "order" DOUBLE PRECISION NOT NULL DEFAULT 1,"description" TEXT NOT NULL,- "quantity" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "quantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,"unitOfMeasureCode" TEXT,- "unitCost" NUMERIC(10, 2) NOT NULL DEFAULT 0,+ "unitCost" NUMERIC(10, 4) NOT NULL DEFAULT 0,"companyId" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"createdBy" TEXT NOT NULL,@@ -131,7 +132,7 @@ CREATE TABLE "quoteMakeMethod" ("quoteLineId" TEXT NOT NULL,"parentMaterialId" TEXT,"itemId" TEXT NOT NULL,- "quantityPerParent" NUMERIC(10, 2) NOT NULL DEFAULT 1,+ "quantityPerParent" NUMERIC(10, 4) NOT NULL DEFAULT 1,"companyId" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"createdBy" TEXT NOT NULL,@@ -249,12 +250,14 @@ CREATE TABLE "quoteOperation" ("quoteId" TEXT NOT NULL,"quoteLineId" TEXT NOT NULL,"quoteMakeMethodId" TEXT,+ "order" DOUBLE PRECISION NOT NULL DEFAULT 1,"workCellTypeId" TEXT NOT NULL,"equipmentTypeId" TEXT,"description" TEXT,"setupHours" NUMERIC(10,2) NOT NULL DEFAULT 0,"standardFactor" factor NOT NULL DEFAULT 'Hours/Piece',"productionStandard" NUMERIC(10,4) NOT NULL DEFAULT 0,+ "operationOrder" "methodOperationOrder" NOT NULL DEFAULT 'After Previous',"quotingRate" NUMERIC(10,4) NOT NULL DEFAULT 0,"laborRate" NUMERIC(10,4) NOT NULL DEFAULT 0,"overheadRate" NUMERIC(10,4) NOT NULL DEFAULT 0,@@ -333,4 +336,43 @@ CREATE OR REPLACE VIEW "quotes" WITH(SECURITY_INVOKER=true) ASGROUP BY "quoteId") ql ON ql."quoteId" = q.idLEFT JOIN "location" l- ON l.id = q."locationId";\ No newline at end of file+ ON l.id = q."locationId";++CREATE OR REPLACE FUNCTION get_quote_methods(qid TEXT)+RETURNS TABLE (+ "quoteId" TEXT,+ "quoteLineId" TEXT,+ "parentMaterialId" TEXT,+ "parentItemId" TEXT,+ "quantityPerParent" NUMERIC(10, 4),+ "quoteMaterialId" TEXT,+ "itemId" TEXT,+ "itemType" TEXT,+ "methodType" TEXT,+ "order" DOUBLE PRECISION,+ "quantity" NUMERIC(10, 4),+ "unitOfMeasureCode" TEXT,+ "unitCost" NUMERIC(10,4)+) AS $$+BEGIN+ RETURN QUERY+ SELECT+ make."quoteId",+ make."quoteLineId",+ make."parentMaterialId",+ make."itemId" AS "parentItemId",+ make."quantityPerParent",+ mat."id" AS "quoteMaterialId",+ mat."itemId",+ mat."itemType",+ mat."methodType",+ mat."order",+ mat."quantity",+ mat."unitOfMeasureCode",+ mat."unitCost"+ FROM "quoteMakeMethod" make+ LEFT OUTER JOIN "quoteMaterial" mat+ ON make."id" = mat."quoteMakeMethodId"+ WHERE make."quoteId" = qid;+END;+$$ LANGUAGE plpgsql;diff --git a/packages/database/supabase/migrations/20240721201537_method-tree-order-fix.sql b/packages/database/supabase/migrations/20240721201537_method-tree-order-fix.sqlnew file mode 100644index 0000000000..3d79c7045e--- /dev/null+++ b/packages/database/supabase/migrations/20240721201537_method-tree-order-fix.sql@@ -0,0 +1,76 @@+DROP FUNCTION get_method_tree;+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",+ "parentMaterialId" TEXT,+ "order" DOUBLE PRECISION,+ "isRoot" BOOLEAN+) AS $$+WITH RECURSIVE material AS (+ SELECT+ "id",+ "makeMethodId",+ "methodType",+ "materialMakeMethodId",+ "itemId",+ "itemType",+ "quantity",+ "makeMethodId" AS "parentMaterialId",+ CAST(1 AS DOUBLE PRECISION) AS "order"+ FROM+ "methodMaterial"+ WHERE+ "makeMethodId" = uid+ UNION+ SELECT+ child."id",+ child."makeMethodId",+ child."methodType",+ child."materialMakeMethodId",+ child."itemId",+ child."itemType",+ child."quantity",+ parent."id" AS "parentMaterialId",+ child."order"+ FROM+ "methodMaterial" child+ INNER JOIN material parent ON parent."materialMakeMethodId" = child."makeMethodId"+)+SELECT+ material.id as "methodMaterialId",+ material."makeMethodId",+ material."materialMakeMethodId",+ material."itemId",+ item."readableId" AS "itemReadableId",+ material."itemType",+ material."quantity",+ material."methodType",+ material."parentMaterialId",+ material."order",+ 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",+ NULL AS "parentMaterialId",+ CAST(1 AS DOUBLE PRECISION) AS "order",+ true AS "isRoot"++FROM "makeMethod" mm INNER JOIN item i ON mm."itemId" = i.id+WHERE mm.id = uid+ORDER BY "order"+$$ LANGUAGE sql STABLE;\ No newline at end of file