Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add materials to bill of material in paperless parts sync

Brad Barbind00e17277482
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
index 4a3fffc668..9d8d19fd4d 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
@@ -18,12 +18,12 @@ import {
} from "@carbon/react";
import { useRouteData } from "@carbon/remix";
import type { TrackedEntityAttributes } from "@carbon/utils";
+import { getItemReadableId } from "@carbon/utils";
import { useFetcher, useNavigation, useParams } from "@remix-run/react";
import { useEffect, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import { useUser } from "~/hooks";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import { getReceiptTracking } from "../../inventory.service";
import type { ReceiptLine } from "../../types";
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
index 28d3abd0d9..df797f4829 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
@@ -36,7 +36,7 @@ import {
VStack,
} from "@carbon/react";
import type { TrackedEntityAttributes } from "@carbon/utils";
-import { labelSizes } from "@carbon/utils";
+import { getItemReadableId, labelSizes } from "@carbon/utils";
import {
Outlet,
useFetcher,
@@ -71,7 +71,6 @@ import type {
import { splitValidator } from "~/modules/inventory";
import type { action as shipmentLinesUpdateAction } from "~/routes/x+/shipment+/lines.update";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
const ShipmentLines = () => {
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
index 6d12a41d6b..05718587e7 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
@@ -18,12 +18,12 @@ import {
} from "@carbon/react";
import { useRouteData } from "@carbon/remix";
import type { TrackedEntityAttributes } from "@carbon/utils";
+import { getItemReadableId } from "@carbon/utils";
import { useFetcher, useNavigation, useParams } from "@remix-run/react";
import { useEffect, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import { useUser } from "~/hooks";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { ShipmentLine } from "../..";
import { getShipmentTracking } from "../..";
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
index d3364ce122..17a350c084 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx
@@ -24,13 +24,16 @@ import {
cn,
useDisclosure,
} from "@carbon/react";
-import { formatRelativeTime } from "@carbon/utils";
+import {
+ formatRelativeTime,
+ getItemById,
+ getItemReadableId,
+} from "@carbon/utils";
import { Link, Outlet, useFetcher, useNavigate } from "@remix-run/react";
import { useEffect, useRef } from "react";
import { LuArrowRight, LuCirclePlus, LuEllipsisVertical } from "react-icons/lu";
import { EmployeeAvatar, Empty, ItemThumbnail } from "~/components";
import { useItems } from "~/stores";
-import { getItemById, getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { WarehouseTransfer, WarehouseTransferLine } from "../../types";
import useWarehouseTransferLines from "./useWarehouseTransferLines";
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
index e2ef748fba..d7a7e570ab 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
@@ -16,7 +16,7 @@ import {
useKeyboardShortcuts,
VStack,
} from "@carbon/react";
-import { prettifyKeyboardShortcut } from "@carbon/utils";
+import { getItemReadableId, prettifyKeyboardShortcut } from "@carbon/utils";
import { Link, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
@@ -32,7 +32,6 @@ import type { Supplier } from "~/modules/purchasing/types";
import type { MethodItemType } from "~/modules/shared";
import { methodItemType } from "~/modules/shared";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { PurchaseInvoice, PurchaseInvoiceLine } from "../../types";
import DeletePurchaseInvoiceLine from "./DeletePurchaseInvoiceLine";
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
index 6affb42708..43eaf0dd32 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
@@ -12,6 +12,7 @@ import {
IconButton,
useDisclosure,
} from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
import { Link, useFetcher, useParams } from "@remix-run/react";
import { useEffect, useState } from "react";
import { flushSync } from "react-dom";
@@ -29,7 +30,6 @@ import type { PurchaseInvoice, PurchaseInvoiceLine } from "~/modules/invoicing";
import { PurchaseInvoicingStatus } from "~/modules/invoicing";
import type { action as statusAction } from "~/routes/x+/purchase-invoice+/$invoiceId.status";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import PurchaseInvoicePostModal from "./PurchaseInvoicePostModal";
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
index bcaf9a0d2e..431625d8f2 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
@@ -16,6 +16,7 @@ import {
import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
+import { getItemReadableId } from "@carbon/utils";
import { useParams } from "@remix-run/react";
import { useEffect, useState } from "react";
import type { z } from "zod";
@@ -35,7 +36,6 @@ import type { PurchaseInvoice } from "~/modules/invoicing";
import { purchaseInvoiceLineValidator } from "~/modules/invoicing";
import type { MethodItemType } from "~/modules/shared";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
type PurchaseInvoiceLineFormProps = {
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
index a309c9eb99..cb2b4829b9 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
@@ -17,11 +17,11 @@ import {
VStack,
} from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
import { useFetcher } from "@remix-run/react";
import { useEffect } from "react";
import type { action } from "~/routes/x+/purchase-invoice+/$invoiceId.post";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
type PurchaseInvoicePostModalProps = {
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
index 98a2454749..23fbe0ad92 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
@@ -13,7 +13,7 @@ import {
Tr,
VStack,
} from "@carbon/react";
-import { formatDate } from "@carbon/utils";
+import { formatDate, getItemReadableId } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
@@ -28,7 +28,6 @@ import {
useUser,
} from "~/hooks";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { getPrivateUrl, path } from "~/utils/path";
import type {
PurchaseInvoice,
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/DeleteSalesInvoiceLine.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/DeleteSalesInvoiceLine.tsx
index b5053cf1e6..6f41ed3aff 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/DeleteSalesInvoiceLine.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/DeleteSalesInvoiceLine.tsx
@@ -1,7 +1,7 @@
+import { getItemReadableId } from "@carbon/utils";
import { useParams } from "@remix-run/react";
import { ConfirmDelete } from "~/components/Modals";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { SalesInvoiceLine } from "../../types";
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
index af62503402..3f0b75074d 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
@@ -16,7 +16,7 @@ import {
useKeyboardShortcuts,
VStack,
} from "@carbon/react";
-import { prettifyKeyboardShortcut } from "@carbon/utils";
+import { getItemReadableId, prettifyKeyboardShortcut } from "@carbon/utils";
import { Link, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
@@ -32,7 +32,6 @@ import type { Supplier } from "~/modules/purchasing/types";
import type { MethodItemType } from "~/modules/shared";
import { methodItemType } from "~/modules/shared";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { SalesInvoice, SalesInvoiceLine } from "../../types";
import DeleteSalesInvoiceLine from "./DeleteSalesInvoiceLine";
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
index d8966d3247..b3257c1058 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
@@ -13,6 +13,7 @@ import {
IconButton,
useDisclosure,
} from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
import { Link, useFetcher, useParams } from "@remix-run/react";
import { useEffect, useState } from "react";
import { flushSync } from "react-dom";
@@ -33,7 +34,6 @@ import { salesInvoiceStatusType } from "~/modules/invoicing";
import type { action } from "~/routes/x+/sales-invoice+/$invoiceId.post";
import type { action as statusAction } from "~/routes/x+/sales-invoice+/$invoiceId.status";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import SalesInvoicePostModal from "./SalesInvoicePostModal";
import SalesInvoiceStatus from "./SalesInvoiceStatus";
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
index 68abc1b349..ac403bd503 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
@@ -17,6 +17,7 @@ import {
import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
+import { getItemReadableId } from "@carbon/utils";
import { useParams } from "@remix-run/react";
import { useEffect, useState } from "react";
import type { z } from "zod";
@@ -38,7 +39,6 @@ import { salesInvoiceLineValidator } from "~/modules/invoicing";
import type { MethodItemType } from "~/modules/shared";
import { methodType } from "~/modules/shared";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
type SalesInvoiceLineFormProps = {
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary.tsx
index 6117bec8f2..362f0cb3b8 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary.tsx
@@ -13,7 +13,7 @@ import {
Tr,
VStack,
} from "@carbon/react";
-import { formatDate } from "@carbon/utils";
+import { formatDate, getItemReadableId } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
@@ -28,7 +28,6 @@ import {
useUser,
} from "~/hooks";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { getPrivateUrl, path } from "~/utils/path";
import type {
SalesInvoice,
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index 6f0ccb71d8..629e9fa90d 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -65,6 +65,7 @@ import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useUser } from "~/hooks";
import type { Database } from "@carbon/database";
+import { getItemReadableId } from "@carbon/utils";
import { ConfigurationEditor } from "~/components/Configurator/ConfigurationEditor";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import {
@@ -73,7 +74,6 @@ import {
type MethodType,
} from "~/modules/shared";
import { useBom, useItems, type Item as ItemType } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { methodOperationValidator } from "../../items.models";
import { methodMaterialValidator } from "../../items.models";
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
index 3869d1f76b..8bb58791b2 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
@@ -11,6 +11,7 @@ import {
cn,
toast,
} from "@carbon/react";
+import { getMaterialDescription, getMaterialId } from "@carbon/utils";
import { useFetcher } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect, useState } from "react";
@@ -34,7 +35,6 @@ import Shape, { useShape } from "~/components/Form/Shape";
import Substance, { useSubstance } from "~/components/Form/Substance";
import { useNextItemId, usePermissions, useUser } from "~/hooks";
import { useSettings } from "~/hooks/useSettings";
-import { getMaterialDescription, getMaterialId } from "~/utils/items";
import { path } from "~/utils/path";
import {
itemTrackingTypes,
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index 4d7341ec5d..68e335e1e2 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -23,6 +23,7 @@ import {
useDebounce,
VStack,
} from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
import { Link, useFetcher, useFetchers, useParams } from "@remix-run/react";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import type { Dispatch, SetStateAction } from "react";
@@ -55,7 +56,6 @@ import { usePermissions, useRouteData, useUser } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { useBom, useItems, type Item as ItemType } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { jobOperationValidator } from "../../production.models";
import {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
index e81035ed8b..84221a83ca 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
@@ -36,7 +36,7 @@ import type { z } from "zod";
import { MethodIcon, TimeTypeIcon } from "~/components/Icons";
import { useCarbon } from "@carbon/auth";
-import { formatDurationMilliseconds } from "@carbon/utils";
+import { formatDurationMilliseconds, getItemReadableId } from "@carbon/utils";
import {
getLocalTimeZone,
now,
@@ -49,7 +49,6 @@ import { EmployeeAvatar, EmployeeAvatarGroup } from "~/components";
import { useCurrencyFormatter, usePercentFormatter, useUser } from "~/hooks";
import { useItems } from "~/stores";
import { makeDurations } from "~/utils/duration";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { jobOperationValidator } from "../../production.models";
import type { getJobMaterialsByMethodId } from "../../production.service";
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
index ca011b3376..bb8e26e9ef 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
@@ -18,6 +18,7 @@ import {
import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
+import { getItemReadableId } from "@carbon/utils";
import { useEffect, useState } from "react";
import type { z } from "zod";
import {
@@ -34,7 +35,6 @@ import {
import { usePermissions, useRouteData } from "~/hooks";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { useBom, useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { jobOperationValidator } from "../../production.models";
import { jobMaterialValidator } from "../../production.models";
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/DeletePurchaseOrderLine.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/DeletePurchaseOrderLine.tsx
index 00f1729508..75aefb51cb 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/DeletePurchaseOrderLine.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/DeletePurchaseOrderLine.tsx
@@ -1,7 +1,7 @@
+import { getItemReadableId } from "@carbon/utils";
import { useParams } from "@remix-run/react";
import { ConfirmDelete } from "~/components/Modals";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { PurchaseOrderLine } from "../../types";
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
index 7f6d6e0197..735f074ccd 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
@@ -17,7 +17,7 @@ import {
useMount,
VStack,
} from "@carbon/react";
-import { prettifyKeyboardShortcut } from "@carbon/utils";
+import { getItemReadableId, prettifyKeyboardShortcut } from "@carbon/utils";
import { Link, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
@@ -32,7 +32,6 @@ import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType } from "~/modules/shared";
import { methodItemType } from "~/modules/shared";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { PurchaseOrder, PurchaseOrderLine, Supplier } from "../../types";
import DeletePurchaseOrderLine from "./DeletePurchaseOrderLine";
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
index dcb0c98104..84ea1ba45c 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
@@ -19,6 +19,7 @@ import {
import { useCarbon } from "@carbon/auth";
import { Combobox, ValidatedForm } from "@carbon/form";
+import { getItemReadableId } from "@carbon/utils";
import { useFetcher, useParams } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect, useMemo, useState } from "react";
@@ -40,7 +41,6 @@ import { purchaseOrderLineValidator } from "~/modules/purchasing";
import type { MethodItemType } from "~/modules/shared";
import type { action } from "~/routes/x+/purchase-order+/$orderId.$lineId.details";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import DeletePurchaseOrderLine from "./DeletePurchaseOrderLine";
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
index 12c51793ad..c9cc2cc7f2 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
@@ -13,7 +13,7 @@ import {
Tr,
VStack,
} from "@carbon/react";
-import { formatDate } from "@carbon/utils";
+import { formatDate, getItemReadableId } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
@@ -28,7 +28,6 @@ import {
useUser,
} from "~/hooks";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { getPrivateUrl, path } from "~/utils/path";
import type {
PurchaseOrder,
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/DeleteSupplierQuoteLine.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/DeleteSupplierQuoteLine.tsx
index 15c2575915..8110955f64 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/DeleteSupplierQuoteLine.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/DeleteSupplierQuoteLine.tsx
@@ -1,7 +1,7 @@
+import { getItemReadableId } from "@carbon/utils";
import { useParams } from "@remix-run/react";
import { ConfirmDelete } from "~/components/Modals";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
export default function DeleteSupplierQuoteLine({
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
index 72f8b910c5..3054d84134 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
@@ -17,7 +17,7 @@ import {
useMount,
VStack,
} from "@carbon/react";
-import { prettifyKeyboardShortcut } from "@carbon/utils";
+import { getItemReadableId, prettifyKeyboardShortcut } from "@carbon/utils";
import { Link, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
@@ -26,7 +26,6 @@ import { useOptimisticLocation, usePermissions, useRouteData } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType } from "~/modules/shared";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { Supplier, SupplierQuote, SupplierQuoteLine } from "../../types";
import DeleteSupplierQuoteLine from "./DeleteSupplierQuoteLine";
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
index 840c602d53..90106eacec 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
@@ -15,7 +15,7 @@ import {
Tr,
VStack,
} from "@carbon/react";
-import { formatDate } from "@carbon/utils";
+import { formatDate, getItemReadableId } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
@@ -25,7 +25,6 @@ import { SupplierAvatar } from "~/components";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { useCurrencyFormatter, useRouteData, useUser } from "~/hooks";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { getPrivateUrl, path } from "~/utils/path";
import type {
PurchaseOrderLine,
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
index b1c20d5062..5ac1c247d0 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
@@ -26,6 +26,7 @@ import {
useMount,
VStack,
} from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
import { Link, useFetcher, useParams } from "@remix-run/react";
import { useEffect, useState } from "react";
import { flushSync } from "react-dom";
@@ -51,7 +52,6 @@ import { LevelLine } from "~/components/TreeView";
import { usePermissions } from "~/hooks";
import type { action as associationAction } from "~/routes/x+/issue+/$id.association.new";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import { issueAssociationValidator } from "../../quality.models";
import type { IssueAssociationKey, IssueAssociationNode } from "../../types";
diff --git a/apps/erp/app/modules/sales/ui/Quotes/DeleteQuoteLine.tsx b/apps/erp/app/modules/sales/ui/Quotes/DeleteQuoteLine.tsx
index 30bffc7db3..050ca2dd10 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/DeleteQuoteLine.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/DeleteQuoteLine.tsx
@@ -1,7 +1,7 @@
+import { getItemReadableId } from "@carbon/utils";
import { useParams } from "@remix-run/react";
import { ConfirmDelete } from "~/components/Modals";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { QuotationLine } from "../../types";
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index e4c559a3a0..337ae539b0 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -24,6 +24,7 @@ import {
useDebounce,
VStack,
} from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
import { Link, useFetcher, useFetchers, useParams } from "@remix-run/react";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import type { Dispatch, SetStateAction } from "react";
@@ -56,7 +57,6 @@ import { usePermissions, useRouteData, useUser } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { useBom, useItems, type Item as ItemType } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { quoteOperationValidator } from "../../sales.models";
import { quoteMaterialValidator } from "../../sales.models";
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
index 9210c63d77..69acc73d59 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -42,6 +42,7 @@ import {
import { usePermissions, useRouteData, useUser } from "~/hooks";
import type { Quotation, QuotationLine } from "../../types";
+import { getItemReadableId } from "@carbon/utils";
import { MethodIcon, MethodItemTypeIcon } from "~/components";
import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";
import { QuoteLineStatusIcon } from "~/components/Icons";
@@ -53,7 +54,6 @@ import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import { methodType } from "~/modules/shared";
import type { action } from "~/routes/x+/quote+/$quoteId.new";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import { quoteLineStatusType, quoteLineValidator } from "../../sales.models";
import DeleteQuoteLine from "./DeleteQuoteLine";
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index 093ed07be1..f6fa7dfead 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -18,6 +18,7 @@ import {
import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
+import { getItemReadableId } from "@carbon/utils";
import { useEffect, useState } from "react";
import type { z } from "zod";
import {
@@ -34,7 +35,6 @@ import {
import { usePermissions } from "~/hooks";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { useBom, useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import type { quoteOperationValidator } from "../../sales.models";
import { quoteMaterialValidator } from "../../sales.models";
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
index d3ea1e45d5..1a55a366de 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
@@ -21,7 +21,7 @@ import {
useMount,
VStack,
} from "@carbon/react";
-import { prettifyKeyboardShortcut } from "@carbon/utils";
+import { getItemReadableId, prettifyKeyboardShortcut } from "@carbon/utils";
import { Await, Link, useNavigate, useParams } from "@remix-run/react";
import { Suspense, useRef, useState } from "react";
import {
@@ -53,7 +53,6 @@ import type { MethodItemType } from "~/modules/shared";
import { methodItemType } from "~/modules/shared";
import { useItems } from "~/stores/items";
import { path } from "~/utils/path";
-import { getItemReadableId } from "~/utils/items";
import type {
Customer,
SalesOrder,
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index 8968cd574f..8a93a51d78 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -44,9 +44,9 @@ import {
import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useCarbon } from "@carbon/auth";
+import { getItemReadableId } from "@carbon/utils";
import { methodType } from "~/modules/shared";
import { useItems } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
import { salesOrderLineValidator } from "../../sales.models";
import type {
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index 3121fc4de1..9550622b8b 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -1,8 +1,8 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import type { Database } from "@carbon/database";
+import { getMaterialDescription, getMaterialId } from "@carbon/utils";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { getCompanySettings } from "~/modules/settings";
-import { getMaterialDescription, getMaterialId } from "~/utils/items";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx
index 9cc069e947..8d16b6831d 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx
@@ -4,6 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import { Spinner } from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
import { Await, Outlet, useLoaderData, useParams } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { defer, redirect } from "@vercel/remix";
@@ -22,7 +23,6 @@ import {
} from "~/modules/purchasing/ui/SupplierInteraction";
import { useItems } from "~/stores";
import { getCustomFields, setCustomFields } from "~/utils/form";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
index 9e1af2bb8f..9ed682409c 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
@@ -4,6 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import { Spinner } from "@carbon/react";
+import { getItemReadableId } from "@carbon/utils";
import { Await, Outlet, useLoaderData, useParams } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { defer, redirect } from "@vercel/remix";
@@ -22,7 +23,6 @@ import {
} from "~/modules/sales/ui/Opportunity";
import { useItems } from "~/stores";
import { getCustomFields, setCustomFields } from "~/utils/form";
-import { getItemReadableId } from "~/utils/items";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 5473c3ed26..328f7b9dd1 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -136,6 +136,7 @@ import {
formatDateTime,
formatDurationMilliseconds,
formatRelativeTime,
+ getItemReadableId,
labelSizes,
} from "@carbon/utils";
import {
@@ -194,7 +195,6 @@ import type {
} from "~/services/inventory.service";
import { getFileType } from "~/services/operations.service";
import { useItems, usePeople } from "~/stores";
-import { getItemReadableId } from "~/utils/items";
import FileDropzone from "./FileDropzone";
import ItemThumbnail from "./ItemThumbnail";
import ScrapReason from "./ScrapReason";
diff --git a/package-lock.json b/package-lock.json
index 7685a457a6..da1e40c5ef 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -36379,14 +36379,17 @@
}
},
"packages/ee": {
+ "name": "@carbon/ee",
"version": "*",
"dependencies": {
+ "@ai-sdk/openai": "^0.0.66",
"@carbon/auth": "*",
"@carbon/react": "*",
"@carbon/utils": "*",
"@slack/bolt": "~4.4.0",
"@slack/oauth": "~3.0.3",
"@slack/web-api": "~7.6.0",
+ "ai": "3.4.9",
"zod": "^3.24.1"
},
"devDependencies": {
@@ -36394,6 +36397,71 @@
"typescript": "^5.2.2"
}
},
+ "packages/ee/node_modules/@ai-sdk/openai": {
+ "version": "0.0.66",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/openai/-/openai-0.0.66.tgz",
+ "integrity": "sha512-V4XeDnlNl5/AY3GB3ozJUjqnBLU5pK3DacKTbCNH3zH8/MggJoH6B8wRGdLUPVFMcsMz60mtvh4DC9JsIVFrKw==",
+ "dependencies": {
+ "@ai-sdk/provider": "0.0.24",
+ "@ai-sdk/provider-utils": "1.0.20"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.0.0"
+ }
+ },
+ "packages/ee/node_modules/@ai-sdk/provider": {
+ "version": "0.0.24",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-0.0.24.tgz",
+ "integrity": "sha512-XMsNGJdGO+L0cxhhegtqZ8+T6nn4EoShS819OvCgI2kLbYTIvk0GWFGD0AXJmxkxs3DrpsJxKAFukFR7bvTkgQ==",
+ "dependencies": {
+ "json-schema": "0.4.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "packages/ee/node_modules/@ai-sdk/provider-utils": {
+ "version": "1.0.20",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-1.0.20.tgz",
+ "integrity": "sha512-ngg/RGpnA00eNOWEtXHenpX1MsM2QshQh4QJFjUfwcqHpM5kTfG7je7Rc3HcEDP+OkRVv2GF+X4fC1Vfcnl8Ow==",
+ "dependencies": {
+ "@ai-sdk/provider": "0.0.24",
+ "eventsource-parser": "1.1.2",
+ "nanoid": "3.3.6",
+ "secure-json-parse": "2.7.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "zod": {
+ "optional": true
+ }
+ }
+ },
+ "packages/ee/node_modules/nanoid": {
+ "version": "3.3.6",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz",
+ "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
"packages/eslint-config-carbon": {
"version": "*",
"dependencies": {
diff --git a/packages/database/supabase/migrations/20250826220816_hrpo.sql b/packages/database/supabase/migrations/20250826220816_hrpo.sql
new file mode 100644
index 0000000000..bf8ef88f4d
--- /dev/null
+++ b/packages/database/supabase/migrations/20250826220816_hrpo.sql
@@ -0,0 +1,18 @@
+INSERT INTO "materialType" ("id", "name", "code", "materialSubstanceId", "materialFormId", "companyId") VALUES
+ ('hrpo-steel-sheet', 'HRPO', 'HRPO', 'steel', 'sheet', null),
+ ('hrpo-steel-plate', 'HRPO', 'HRPO', 'steel', 'plate', null),
+ ('hrpo-stainless-sheet', 'HRPO', 'HRPO', 'stainless', 'sheet', null),
+ ('hrpo-stainless-plate', 'HRPO', 'HRPO', 'stainless', 'plate', null),
+ ('galvanized-steel-plate', 'Galvanized', 'GA', 'steel', 'plate', null),
+ ('galvannealed-steel-sheet', 'Galvannealed', 'GN', 'steel', 'sheet', null),
+ ('galvannealed-steel-plate', 'Galvannealed', 'GN', 'steel', 'plate', null);
+
+
+UPDATE "material" SET "materialTypeId" = 'hrpo-steel-plate' WHERE "id" = 'pickled-oiled-steel-plate';
+UPDATE "material" SET "materialTypeId" = 'hrpo-stainless-sheet' WHERE "id" = 'pickled-stainless-plate';
+
+DELETE FROM "materialType" WHERE "id" = 'pickled-oiled-steel-plate';
+DELETE FROM "materialType" WHERE "id" = 'pickled-stainless-plate';
+
+INSERT INTO "materialGrade" ("id", "materialSubstanceId", "name", "companyId") VALUES
+('steel-a653', 'steel', 'A653', null);
\ No newline at end of file
diff --git a/packages/ee/package.json b/packages/ee/package.json
index f202c81648..6e24aff868 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -25,9 +25,11 @@
"@carbon/auth": "*",
"@carbon/react": "*",
"@carbon/utils": "*",
+ "@ai-sdk/openai": "^0.0.66",
"@slack/bolt": "~4.4.0",
"@slack/oauth": "~3.0.3",
"@slack/web-api": "~7.6.0",
+ "ai": "3.4.9",
"zod": "^3.24.1"
},
"devDependencies": {
diff --git a/packages/ee/src/paperless-parts/lib/utils.ts b/packages/ee/src/paperless-parts/lib/utils.ts
index 874c26aeac..371f7cd652 100644
--- a/packages/ee/src/paperless-parts/lib/utils.ts
+++ b/packages/ee/src/paperless-parts/lib/utils.ts
@@ -1,9 +1,17 @@
+import { openai } from "@ai-sdk/openai";
import type { Database } from "@carbon/database";
-import { supportedModelTypes, textToTiptap } from "@carbon/utils";
+import {
+ getMaterialDescription,
+ getMaterialId,
+ openAiCategorizationModel,
+ supportedModelTypes,
+ textToTiptap,
+} from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { generateObject } from "ai";
import { nanoid } from "nanoid";
-import type z from "zod";
-import type { PaperlessPartsClient } from "./client";
+import { z } from "zod";
+import type { PaperlessPartsClient, QuoteCostingVariable } from "./client";
import type {
AddressSchema,
ContactSchema,
@@ -56,6 +64,660 @@ function isModelFile(filename: string): boolean {
const extension = filename.toLowerCase().split(".").pop() || "";
return supportedModelTypes.includes(extension);
}
+const substanceSchema = z.object({
+ substanceId: z
+ .string()
+ .describe("The ID of the best matching material substance"),
+ confidence: z
+ .number()
+ .min(0)
+ .max(1)
+ .describe("Confidence level of the match (0-1)"),
+ reasoning: z
+ .string()
+ .describe("Brief explanation of why this substance was chosen"),
+});
+
+async function determineMaterialSubstance(
+ carbon: SupabaseClient<Database>,
+ materialInfo: {
+ description: string;
+ materialName: string;
+ materialDisplayName: string;
+ materialFamily: string;
+ materialClass: string;
+ processName: string;
+ }
+): Promise<z.infer<typeof substanceSchema> | null> {
+ const substances = await carbon
+ .from("materialSubstance")
+ .select("id, name")
+ .is("companyId", null);
+
+ if (substances.error || !substances.data?.length) {
+ console.error("Failed to fetch material substances:", substances.error);
+ return null;
+ }
+
+ try {
+ const availableSubstances = substances.data
+ .map((s) => `${s.id}: ${s.name}`)
+ .join("\n");
+
+ const { object } = await generateObject({
+ model: openai(openAiCategorizationModel),
+ schema: substanceSchema,
+ prompt: `
+ Based on the following material information, determine the best matching material substance from the available options.
+
+ Material Information:
+ - Description: ${materialInfo.description}
+ - Material Name: ${materialInfo.materialName}
+ - Material Display Name: ${materialInfo.materialDisplayName}
+ - Material Family: ${materialInfo.materialFamily}
+ - Material Class: ${materialInfo.materialClass}
+ - Process Name: ${materialInfo.processName}
+
+ Available Material Substances:
+ ${availableSubstances}
+
+ Select the substance that best matches the material information provided. Consider material type, grade, and common industry terminology.
+ `,
+ temperature: 0.2,
+ });
+
+ return object;
+ } catch (error) {
+ console.error("Failed to determine material substance using AI:", error);
+ return null;
+ }
+}
+
+const materialPropertiesSchema = z.object({
+ gradeId: z
+ .string()
+ .describe("The ID of the best matching material grade")
+ .nullable(),
+ dimensionId: z
+ .string()
+ .describe("The ID of the best matching material dimension")
+ .nullable(),
+ finishId: z
+ .string()
+ .describe("The ID of the best matching material finish")
+ .nullable(),
+ typeId: z
+ .string()
+ .describe("The ID of the best matching material type")
+ .nullable(),
+ quantity: z.number().describe("The quantity of the material properties"),
+ confidence: z.number().describe("Confidence level of the match (0-1)"),
+ reasoning: z
+ .string()
+ .describe("Brief explanation of why this material properties were chosen"),
+});
+
+// Cache for material properties by substance ID
+type MaterialPropertiesCache = {
+ grades: Array<{ id: string; name: string }>;
+ dimensions: Array<{ id: string; name: string; materialFormId: string }>;
+ finishes: Array<{ id: string; name: string }>;
+ types: Array<{ id: string; name: string; code: string }>;
+ forms: Array<{ id: string; name: string; code: string }>;
+ substance: { id: string; name: string; code: string };
+ timestamp: number;
+};
+
+const materialPropertiesCache = new Map<string, MaterialPropertiesCache>();
+
+// Cache TTL in milliseconds (30 minutes)
+const CACHE_TTL = 30 * 60 * 1000;
+
+/**
+ * Clean expired cache entries
+ */
+function cleanExpiredCache(): void {
+ const now = Date.now();
+ for (const [key, value] of materialPropertiesCache.entries()) {
+ if (now - value.timestamp > CACHE_TTL) {
+ materialPropertiesCache.delete(key);
+ }
+ }
+}
+
+/**
+ * Get cached material properties or fetch from database if not cached
+ */
+async function getCachedMaterialProperties(
+ carbon: SupabaseClient<Database>,
+ substanceId: string
+): Promise<MaterialPropertiesCache | null> {
+ // Clean expired entries periodically
+ if (materialPropertiesCache.size > 0) {
+ cleanExpiredCache();
+ }
+
+ // Check if we have cached data for this substance
+ const cached = materialPropertiesCache.get(substanceId);
+ if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
+ return cached;
+ }
+
+ // Fetch from database
+ const [grades, dimensions, finishes, types, forms, substance] =
+ await Promise.all([
+ carbon
+ .from("materialGrade")
+ .select("id, name")
+ .is("companyId", null)
+ .eq("materialSubstanceId", substanceId),
+ carbon
+ .from("materialDimension")
+ .select("id, name, materialFormId")
+ .is("companyId", null)
+ .or("materialFormId.eq.plate,materialFormId.eq.sheet"),
+ carbon
+ .from("materialFinish")
+ .select("id, name")
+ .is("companyId", null)
+ .eq("materialSubstanceId", substanceId),
+ carbon
+ .from("materialType")
+ .select("id, name, code")
+ .is("companyId", null)
+ .eq("materialSubstanceId", substanceId),
+ carbon
+ .from("materialForm")
+ .select("id, name, code")
+ .or("code.eq.plate,code.eq.sheet")
+ .is("companyId", null),
+ carbon
+ .from("materialSubstance")
+ .select("id, name, code")
+ .eq("id", substanceId)
+ .single(),
+ ]);
+
+ // Check for any errors
+ if (
+ grades.error ||
+ dimensions.error ||
+ finishes.error ||
+ types.error ||
+ forms.error ||
+ substance.error
+ ) {
+ console.error("Error fetching material properties:", {
+ grades: grades.error,
+ dimensions: dimensions.error,
+ finishes: finishes.error,
+ types: types.error,
+ forms: forms.error,
+ substance: substance.error,
+ });
+ return null;
+ }
+
+ if (!substance.data) {
+ console.error(`Substance not found for ID: ${substanceId}`);
+ return null;
+ }
+
+ // Create cache entry
+ const cacheEntry: MaterialPropertiesCache = {
+ grades: grades.data || [],
+ dimensions: dimensions.data || [],
+ finishes: finishes.data || [],
+ types: types.data || [],
+ forms: forms.data || [],
+ substance: substance.data,
+ timestamp: Date.now(),
+ };
+
+ // Cache the result
+ materialPropertiesCache.set(substanceId, cacheEntry);
+
+ return cacheEntry;
+}
+
+/**
+ * Clear all cached material properties
+ */
+export function clearMaterialPropertiesCache(): void {
+ materialPropertiesCache.clear();
+ console.log("Material properties cache cleared");
+}
+
+/**
+ * Get current cache statistics
+ */
+export function getMaterialPropertiesCacheStats(): {
+ size: number;
+ substances: string[];
+ oldestEntry?: number;
+ newestEntry?: number;
+} {
+ const substances = Array.from(materialPropertiesCache.keys());
+ const timestamps = Array.from(materialPropertiesCache.values()).map(
+ (v) => v.timestamp
+ );
+
+ return {
+ size: materialPropertiesCache.size,
+ substances,
+ oldestEntry: timestamps.length > 0 ? Math.min(...timestamps) : undefined,
+ newestEntry: timestamps.length > 0 ? Math.max(...timestamps) : undefined,
+ };
+}
+
+export type MaterialNamingDetails = {
+ // IDs for database operations
+ gradeId?: string | null;
+ dimensionId?: string | null;
+ finishId?: string | null;
+ formId?: string;
+ typeId?: string | null;
+
+ // Names for getMaterialDescription
+ materialType?: string;
+ substance?: string;
+ grade?: string;
+ shape?: string;
+ dimensions?: string;
+ finish?: string;
+
+ // Codes for getMaterialId
+ materialTypeCode?: string;
+ substanceCode?: string;
+ shapeCode?: string;
+
+ // Other properties
+ quantity?: number;
+ confidence?: number;
+ reasoning?: string;
+};
+
+type PaperlessPartsMaterialInput = {
+ description?: string;
+ material?: {
+ display_name?: string;
+ family?: string;
+ material_class?: string;
+ name?: string;
+ };
+ material_operations?: {
+ costing_variables?: QuoteCostingVariable[];
+ }[];
+ process?: {
+ name?: string;
+ };
+ quantities?: {
+ quantity?: number;
+ }[];
+};
+
+async function determineMaterialProperties(
+ carbon: SupabaseClient<Database>,
+ substanceId: string,
+ materialInfo: PaperlessPartsMaterialInput
+): Promise<MaterialNamingDetails | null> {
+ // Get cached or fresh material properties
+ const materialProperties = await getCachedMaterialProperties(
+ carbon,
+ substanceId
+ );
+
+ if (!materialProperties) {
+ return null;
+ }
+
+ const { grades, dimensions, finishes, types, forms, substance } =
+ materialProperties;
+
+ const { object } = await generateObject({
+ model: openai(openAiCategorizationModel),
+ schema: materialPropertiesSchema,
+ prompt: `
+ Based on the following material information, determine the best matching material properties from the available options.
+
+ If the material is sheet metal, the quantity returned should be the parts per sheet. Use the materialFormId from the dimension to determine the formId to return.
+
+ Material Information:
+ - Description: ${materialInfo.description}
+ - Material Name: ${materialInfo.material?.name}
+ - Material Display Name: ${materialInfo.material?.display_name}
+ - Material Family: ${materialInfo.material?.family}
+ - Material Class: ${materialInfo.material?.material_class}
+ - Process Name: ${materialInfo.process?.name}
+
+ - Material Metadata:
+ ${materialInfo.material_operations
+ ?.map((op) =>
+ op.costing_variables
+ ?.map((cv) => `- ${cv.label}: ${cv.value}`)
+ .join("\n")
+ )
+ .filter(Boolean)
+ .join("\n")}
+
+ Available Material Properties:
+ - Grades: ${grades.map((g) => `${g.id}: ${g.name}`).join("\n")}
+ - Dimensions: ${dimensions
+ .map((d) => `${d.id}: ${d.name}, ${d.materialFormId}`)
+ .join("\n")}
+ - Finishes: ${finishes.map((f) => `${f.id}: ${f.name}`).join("\n")}
+ - Types: ${types.map((t) => `${t.id}: ${t.name}`).join("\n")}
+
+ Select the properties that best match the material information provided. Consider material type, grade, and common industry terminology.
+ `,
+ temperature: 0.2,
+ });
+
+ if (object.confidence < 0.5) {
+ return null;
+ }
+
+ const dimension = dimensions.find((d) => d.id === object.dimensionId);
+ const form = forms.find((f) => f.id === dimension?.materialFormId);
+ const grade = grades.find((g) => g.id === object.gradeId);
+ const finish = finishes.find((f) => f.id === object.finishId);
+ const type = types.find((t) => t.id === object.typeId);
+
+ // Return enhanced structure with both IDs, names, and codes
+ return {
+ // IDs for database operations
+ gradeId: object.gradeId,
+ dimensionId: object.dimensionId,
+ finishId: object.finishId,
+ formId: dimension?.materialFormId,
+ typeId: object.typeId,
+
+ // Names for getMaterialDescription
+ materialType: type?.name,
+ substance: substance.name,
+ grade: grade?.name,
+ shape: form?.name,
+ dimensions: dimension?.name,
+ finish: finish?.name,
+
+ // Codes for getMaterialId
+ materialTypeCode: type?.code,
+ substanceCode: substance.code,
+ shapeCode: form?.code,
+
+ // Other properties
+ quantity: object.quantity,
+ confidence: object.confidence,
+ reasoning: object.reasoning,
+ };
+}
+
+/**
+ * Get material properties with names and codes needed for getMaterialId and getMaterialDescription
+ *
+ * @example
+ * ```typescript
+ * const materialProps = await getMaterialProperties(client, materialId, companyId);
+ * if (materialProps) {
+ * const newMaterialId = getMaterialId(materialProps);
+ * const newDescription = getMaterialDescription(materialProps);
+ * }
+ * ```
+ *
+ * @param carbon - Supabase client
+ * @param materialId - The material ID (readableId)
+ * @param companyId - The company ID
+ * @returns Material naming details with both names and codes
+ */
+export async function getMaterialProperties(
+ carbon: SupabaseClient<Database>,
+ materialId: string,
+ companyId: string
+): Promise<MaterialNamingDetails | null> {
+ try {
+ const materialNamingDetails = await carbon
+ .rpc("get_material_naming_details", { readable_id: materialId })
+ .single();
+
+ if (materialNamingDetails.error || !materialNamingDetails.data) {
+ console.error(
+ "Failed to get material naming details:",
+ materialNamingDetails.error
+ );
+ return null;
+ }
+
+ const details = materialNamingDetails.data;
+
+ return {
+ // IDs for database operations (not available from this function)
+ gradeId: null,
+ dimensionId: null,
+ finishId: null,
+ formId: undefined,
+ typeId: null,
+
+ // Names for getMaterialDescription
+ materialType: details.materialType,
+ substance: details.substance,
+ grade: details.grade,
+ shape: details.shape,
+ dimensions: details.dimensions,
+ finish: details.finish,
+
+ // Codes for getMaterialId
+ materialTypeCode: details.materialTypeCode,
+ substanceCode: details.substanceCode,
+ shapeCode: details.shapeCode,
+
+ // Other properties
+ quantity: undefined,
+ confidence: undefined,
+ reasoning: undefined,
+ };
+ } catch (error) {
+ console.error("Error getting material properties:", error);
+ return null;
+ }
+}
+
+export async function getOrCreateMaterial(
+ carbon: SupabaseClient<Database>,
+ args: {
+ input: PaperlessPartsMaterialInput;
+ createdBy: string;
+ companyId: string;
+ }
+): Promise<{
+ itemId: string;
+ unitOfMeasureCode: string;
+ quantity: number;
+}> | null {
+ if (
+ args.input.process?.name?.toLowerCase().includes("laser") ||
+ args.input.process?.name?.toLowerCase().includes("plasma") ||
+ args.input.process?.name?.toLowerCase().includes("jet")
+ ) {
+ const materialInfo = {
+ description: args.input.description || "",
+ materialName: args.input.material?.name || "",
+ materialDisplayName: args.input.material?.display_name || "",
+ materialFamily: args.input.material?.family || "",
+ materialClass: args.input.material?.material_class || "",
+ processName: args.input.process?.name || "",
+ };
+
+ const substanceResult = await determineMaterialSubstance(
+ carbon,
+ materialInfo
+ );
+
+ if (!substanceResult) {
+ return null;
+ }
+
+ const materialPropertiesResult = await determineMaterialProperties(
+ carbon,
+ substanceResult.substanceId,
+ args.input
+ );
+
+ if (!materialPropertiesResult) {
+ return null;
+ }
+
+ console.log({
+ quantity: materialPropertiesResult.quantity,
+ quantities: args.input.quantities,
+ });
+
+ // Use quantity from material properties AI determination, fallback to input quantity
+ const quantity = materialPropertiesResult.quantity
+ ? 1 / materialPropertiesResult.quantity
+ : args.input.quantities?.[0]?.quantity || 1;
+
+ let materialQuery = carbon
+ .from("material")
+ .select("id")
+ .eq("companyId", args.companyId);
+
+ if (substanceResult.substanceId) {
+ materialQuery = materialQuery.eq(
+ "materialSubstanceId",
+ substanceResult.substanceId
+ );
+ } else {
+ materialQuery = materialQuery.is("materialSubstanceId", null);
+ }
+
+ if (materialPropertiesResult?.gradeId) {
+ materialQuery = materialQuery.eq(
+ "gradeId",
+ materialPropertiesResult.gradeId
+ );
+ } else {
+ materialQuery = materialQuery.is("gradeId", null);
+ }
+
+ if (materialPropertiesResult?.dimensionId) {
+ materialQuery = materialQuery.eq(
+ "dimensionId",
+ materialPropertiesResult.dimensionId
+ );
+ } else {
+ materialQuery = materialQuery.is("dimensionId", null);
+ }
+
+ if (materialPropertiesResult?.finishId) {
+ materialQuery = materialQuery.eq(
+ "finishId",
+ materialPropertiesResult.finishId
+ );
+ } else {
+ materialQuery = materialQuery.is("finishId", null);
+ }
+
+ if (materialPropertiesResult?.typeId) {
+ materialQuery = materialQuery.eq(
+ "materialTypeId",
+ materialPropertiesResult.typeId
+ );
+ } else {
+ materialQuery = materialQuery.is("materialTypeId", null);
+ }
+
+ const materialResult = await materialQuery.single();
+
+ if (materialResult.data) {
+ const item = await carbon
+ .from("item")
+ .select("id, revision, unitOfMeasureCode")
+ .eq("companyId", args.companyId)
+ .eq("readableId", materialResult.data.id);
+
+ if (item.error || !item.data?.length) {
+ console.error(`Failed to find item:`, item.error);
+ return null;
+ }
+
+ return {
+ itemId: item.data[0].id,
+ unitOfMeasureCode: item.data[0].unitOfMeasureCode ?? "EA",
+ quantity,
+ };
+ } else {
+ const readableId = getMaterialId({
+ materialTypeCode: materialPropertiesResult?.materialTypeCode,
+ substanceCode: materialPropertiesResult?.substanceCode,
+ grade: materialPropertiesResult?.grade,
+ shapeCode: materialPropertiesResult?.shapeCode,
+ dimensions: materialPropertiesResult?.dimensions,
+ finish: materialPropertiesResult?.finish,
+ });
+ const description = getMaterialDescription({
+ materialType: materialPropertiesResult?.materialType,
+ substance: materialPropertiesResult?.substance,
+ grade: materialPropertiesResult?.grade,
+ shape: materialPropertiesResult?.shape,
+ dimensions: materialPropertiesResult?.dimensions,
+ finish: materialPropertiesResult?.finish,
+ });
+
+ const itemInsert = await carbon
+ .from("item")
+ .insert({
+ readableId,
+ name: description,
+ type: "Material",
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Buy",
+ itemTrackingType: "Inventory",
+ unitOfMeasureCode: "EA",
+ active: true,
+ companyId: args.companyId,
+ createdBy: args.createdBy,
+ })
+ .select("id, unitOfMeasureCode")
+ .single();
+
+ if (itemInsert.error) {
+ console.error(`Failed to insert item:`, itemInsert.error);
+ return null;
+ }
+
+ const materialData = {
+ id: readableId,
+ companyId: args.companyId,
+ materialSubstanceId: substanceResult.substanceId,
+ materialFormId: materialPropertiesResult?.formId,
+ gradeId: materialPropertiesResult?.gradeId,
+ dimensionId: materialPropertiesResult?.dimensionId,
+ finishId: materialPropertiesResult?.finishId,
+ materialTypeId: materialPropertiesResult?.typeId,
+ createdBy: args.createdBy,
+ };
+
+ const materialInsert = await carbon
+ .from("material")
+ .upsert(materialData)
+ .select("id")
+ .single();
+
+ if (materialInsert.error) {
+ console.error(`Failed to insert material:`, materialInsert.error);
+ return null;
+ }
+
+ return {
+ itemId: itemInsert.data.id,
+ unitOfMeasureCode: itemInsert.data.unitOfMeasureCode ?? "EA",
+ quantity,
+ };
+ }
+ }
+
+ return null;
+}
/**
* Upload CAD model file and create model record
@@ -452,42 +1114,119 @@ export async function getCustomerIdAndContactId(
}
}
} else {
- // If the quote contact does not have an account, we need to create a new customer in Carbon
- // and also create a corresponding account in Paperless Parts
+ // If the quote contact does not have an account, first search for existing accounts
+ // in Paperless Parts by name before creating a new one
const customerName = `${contact.first_name} ${contact.last_name}`;
- // // Create a new account in Paperless Parts
- // const newPaperlessPartsAccount = await paperless.accounts.createAccount({
- // name: customerName,
- // });
+ // Search for existing accounts in Paperless Parts by name
+ const existingAccountsResponse = await paperless.accounts.listAccounts({
+ search: customerName,
+ });
- // if (newPaperlessPartsAccount.error || !newPaperlessPartsAccount.data) {
- // throw new Error("Failed to create account in Paperless Parts");
- // }
+ let paperlessPartsAccountId: number;
+ let existingPaperlessAccount = null;
- // const newPaperlessPartsAccountId = newPaperlessPartsAccount.data.id;
+ if (
+ existingAccountsResponse.data &&
+ existingAccountsResponse.data.length > 0
+ ) {
+ // Look for an exact name match
+ existingPaperlessAccount = existingAccountsResponse.data.find(
+ (account) => account.name === customerName
+ );
+ }
- const newCustomer = await carbon
- .from("customer")
- .insert({
- companyId: company.id,
+ if (existingPaperlessAccount) {
+ // Use the existing account ID
+ paperlessPartsAccountId = existingPaperlessAccount.id!;
+ console.info(
+ `🔗 Found existing Paperless Parts account: ${customerName}`
+ );
+ } else {
+ // Create a new account in Paperless Parts
+ const newPaperlessPartsAccount = await paperless.accounts.createAccount({
name: customerName,
- externalId: {
- paperlessPartsId: "newPaperlessPartsAccountId",
- },
- currencyCode: company.baseCurrencyCode,
- createdBy: "system",
- })
- .select()
- .single();
+ });
+
+ if (newPaperlessPartsAccount.error || !newPaperlessPartsAccount.data) {
+ throw new Error("Failed to create account in Paperless Parts");
+ }
- if (newCustomer.error || !newCustomer.data) {
- throw new Error("Failed to create customer in Carbon");
+ paperlessPartsAccountId = newPaperlessPartsAccount.data.id;
+ console.info("🔰 New Paperless Parts account created");
}
- console.info("🔰 New Carbon customer created");
+ // Check if customer already exists in Carbon with this paperless account ID
+ const existingCustomerByPaperlessId = await carbon
+ .from("customer")
+ .select("id")
+ .eq("companyId", company.id)
+ .eq("externalId->>paperlessPartsId", String(paperlessPartsAccountId))
+ .maybeSingle();
+
+ if (existingCustomerByPaperlessId.data) {
+ customerId = existingCustomerByPaperlessId.data.id;
+ } else {
+ // Try to find existing customer by name in Carbon
+ const existingCustomerByName = await carbon
+ .from("customer")
+ .select("id")
+ .eq("companyId", company.id)
+ .eq("name", customerName)
+ .maybeSingle();
+
+ if (existingCustomerByName.data) {
+ // Update the existing customer with the external ID
+ const updatedCustomer = await carbon
+ .from("customer")
+ .update({
+ externalId: {
+ paperlessPartsId: paperlessPartsAccountId,
+ },
+ })
+ .eq("id", existingCustomerByName.data.id)
+ .select()
+ .single();
+
+ if (updatedCustomer.error || !updatedCustomer.data) {
+ console.error(updatedCustomer.error);
+ throw new Error("Failed to update customer externalId in Carbon");
+ }
+
+ customerId = updatedCustomer.data.id;
+ console.info(
+ "🔗 Updated existing Carbon customer with Paperless Parts ID"
+ );
+ } else {
+ // Create a new customer in Carbon
+ const newCustomer = await carbon
+ .from("customer")
+ .upsert(
+ {
+ companyId: company.id,
+ name: customerName,
+ externalId: {
+ paperlessPartsId: paperlessPartsAccountId,
+ },
+ currencyCode: company.baseCurrencyCode,
+ createdBy,
+ },
+ {
+ onConflict: "name, companyId",
+ }
+ )
+ .select()
+ .single();
+
+ if (newCustomer.error || !newCustomer.data) {
+ console.error(newCustomer.error);
+ throw new Error("Failed to create customer in Carbon");
+ }
- customerId = newCustomer.data.id;
+ console.info("🔰 New Carbon customer created");
+ customerId = newCustomer.data.id;
+ }
+ }
}
// Get the contact ID from Carbon based on the Paperless Parts ID
@@ -1029,23 +1768,29 @@ export async function createPartFromComponent(
Database["public"]["Tables"]["methodOperation"]["Insert"],
"makeMethodId"
>[] = [];
+ const materials: Omit<
+ Database["public"]["Tables"]["methodMaterial"]["Insert"],
+ "makeMethodId"
+ >[] = [];
+
+ if (component.material_operations || component.material) {
+ const material = await getOrCreateMaterial(carbon, {
+ companyId,
+ createdBy,
+ input: component,
+ });
- // // Log costing variables and quantities if they exist
- // if (component.material_operations) {
- // component.material_operations.forEach((operation: any) => {
- // console.log("material operation", operation);
- // if (operation.costing_variables) {
- // operation.costing_variables.forEach((cv: any) => {
- // console.log("material costing_variable", cv.costing_variable);
- // });
- // }
- // if (operation.quantities) {
- // operation.quantities.forEach((q: any) => {
- // console.log("material quantity", q.quantity);
- // });
- // }
- // });
- // }
+ if (material) {
+ materials.push({
+ itemId: material.itemId,
+ itemType: "Material",
+ quantity: material.quantity,
+ companyId,
+ createdBy,
+ unitOfMeasureCode: "EA",
+ });
+ }
+ }
if (component.shop_operations) {
for await (const [
@@ -1060,7 +1805,7 @@ export async function createPartFromComponent(
createdBy
);
if (process) {
- console.log({ operation });
+ // console.log({ operation });
operations.push({
order: operation.position ?? index + 1,
operationOrder: "After Previous",
@@ -1184,17 +1929,34 @@ export async function createPartFromComponent(
const makeMethodId = makeMethod.data?.id;
if (makeMethodId) {
- const operationInsert = await carbon.from("methodOperation").insert(
- operations.map((operation) => ({
- ...operation,
- makeMethodId,
- }))
- );
- if (operationInsert.error) {
- console.error(
- "Failed to create method operations:",
- operationInsert.error
+ if (operations.length) {
+ const operationInsert = await carbon.from("methodOperation").insert(
+ operations.map((operation) => ({
+ ...operation,
+ makeMethodId,
+ }))
+ );
+ if (operationInsert.error) {
+ console.error(
+ "Failed to create method operations:",
+ operationInsert.error
+ );
+ }
+ }
+
+ if (materials.length) {
+ const materialInsert = await carbon.from("methodMaterial").insert(
+ materials.map((material) => ({
+ ...material,
+ makeMethodId,
+ }))
);
+ if (materialInsert.error) {
+ console.error(
+ "Failed to create method materials:",
+ materialInsert.error
+ );
+ }
}
}
@@ -1342,6 +2104,8 @@ export async function insertOrderLines(
component,
});
+ // console.log("component", component);
+
// Calculate quantities
const saleQuantity =
component.deliver_quantity || orderItem.quantity || 1;
diff --git a/packages/jobs/trigger/paperless-parts.ts b/packages/jobs/trigger/paperless-parts.ts
index cfcc1431b5..90b3748df7 100644
--- a/packages/jobs/trigger/paperless-parts.ts
+++ b/packages/jobs/trigger/paperless-parts.ts
@@ -108,6 +108,7 @@ export const paperlessPartsTask = task({
retry: {
maxAttempts: 1,
},
+ maxDuration: 5 * 60,
run: async (payload: z.infer<typeof paperlessPartsSchema>) => {
let result: { success: boolean; message: string };
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index ff0b059510..4a07b4d76c 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -7,8 +7,10 @@ export * from "./date";
export * from "./duration";
export * from "./file";
export * from "./geo";
+export * from "./items";
export * from "./keyboard";
export * from "./labels";
+export * from "./llm";
export * from "./math";
export * from "./ssr";
export * from "./themes";
diff --git a/apps/erp/app/utils/items.ts b/packages/utils/src/items.ts
similarity index 95%
rename from apps/erp/app/utils/items.ts
rename to packages/utils/src/items.ts
index ce883c4ad0..6c176e2e49 100644
--- a/apps/erp/app/utils/items.ts
+++ b/packages/utils/src/items.ts
@@ -1,4 +1,7 @@
-import type { Item } from "~/stores/items";
+type Item = {
+ id: string;
+ readableIdWithRevision: string;
+};
/**
* Get the readable ID for an item given its ID
diff --git a/packages/utils/src/llm.ts b/packages/utils/src/llm.ts
new file mode 100644
index 0000000000..551bdb49ad
--- /dev/null
+++ b/packages/utils/src/llm.ts
@@ -0,0 +1,2 @@
+export const openAiCategorizationModel = "gpt-4o" as const;
+export const anthropicAgentModel = "claude-3-7-sonnet-20250219" as const;