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.

Onshape Integration (#178)

Brad Barbin6bbc9c03a4b4
diff --git a/apps/erp/app/components/SortableList.tsx b/apps/erp/app/components/SortableList.tsx
index f23bc2d097..6ce3b6b4fa 100644
--- a/apps/erp/app/components/SortableList.tsx
+++ b/apps/erp/app/components/SortableList.tsx
@@ -2,7 +2,7 @@
import { LayoutGroup, Reorder, motion, useDragControls } from "framer-motion";
import type { ReactNode } from "react";
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { Checkbox, HStack, cn } from "@carbon/react";
import { flushSync } from "react-dom";
@@ -32,6 +32,7 @@ interface SortableListItemProps<T> {
onRemoveItem: (id: string) => void;
renderExtra?: (item: SortableItem<T>) => React.ReactNode;
isExpanded?: boolean;
+ isHighlighted?: boolean;
className?: string;
handleDrag: () => void;
}
@@ -46,11 +47,13 @@ function SortableListItem<T>({
renderExtra,
handleDrag,
isExpanded,
+ isHighlighted,
className,
}: SortableListItemProps<T>) {
const [isDragging, setIsDragging] = useState(false);
const [isDraggable] = useState(!isExpanded);
const dragControls = useDragControls();
+ const itemRef = useRef<HTMLDivElement>(null);
const handleDragStart = (event: any) => {
if (isExpanded) return;
@@ -63,8 +66,18 @@ function SortableListItem<T>({
setIsDragging(false);
};
+ // Scroll into view when highlighted
+ useEffect(() => {
+ if (isHighlighted && itemRef.current) {
+ itemRef.current.scrollIntoView({
+ behavior: "smooth",
+ block: "nearest",
+ });
+ }
+ }, [isHighlighted]);
+
return (
- <div className={cn("", className)} key={item.id}>
+ <div className={cn("", className)} key={item.id} ref={itemRef}>
<div className="flex w-full items-center">
<Reorder.Item
value={item}
@@ -73,6 +86,7 @@ function SortableListItem<T>({
"h-full rounded-md bg-muted/30",
"border border-border rounded-lg ",
!isExpanded && "cursor-grab",
+ isHighlighted && "border-2 border-primary",
item.checked && !isDragging ? "w-7/10" : "w-full"
)}
key={item.id}
diff --git a/apps/erp/app/components/TreeView/reducer.ts b/apps/erp/app/components/TreeView/reducer.ts
index 30041850c4..a9b4ea0ab8 100644
--- a/apps/erp/app/components/TreeView/reducer.ts
+++ b/apps/erp/app/components/TreeView/reducer.ts
@@ -561,6 +561,7 @@ export function reducer(state: TreeState, action: Action): TreeState {
case "UPDATE_TREE": {
//update the tree but try and keep the selected and expanded states
const selectedId = selectedIdFromState(state.nodes);
+
const collapsedIds = collapsedIdsFromState(state.nodes);
const newState = concreteStateFromInput({
...state,
diff --git a/apps/erp/app/integrations/index.ts b/apps/erp/app/integrations/index.ts
index 156037f90b..2a4b4e0397 100644
--- a/apps/erp/app/integrations/index.ts
+++ b/apps/erp/app/integrations/index.ts
@@ -1,4 +1,5 @@
import { ExchangeRates } from "./exchange-rates/config";
+import { Onshape } from "./onshape/config";
import { PaperlessParts } from "./paperless-parts/config";
import { QuickBooks } from "./quickbooks/config";
import { Resend } from "./resend/config";
@@ -8,8 +9,9 @@ import { Zapier } from "./zapier/config";
export const integrations = [
ExchangeRates,
- PaperlessParts,
Resend,
+ PaperlessParts,
+ Onshape,
Slack,
QuickBooks,
Xero,
diff --git a/apps/erp/app/integrations/onshape/config.tsx b/apps/erp/app/integrations/onshape/config.tsx
new file mode 100644
index 0000000000..3adfb9a02c
--- /dev/null
+++ b/apps/erp/app/integrations/onshape/config.tsx
@@ -0,0 +1,159 @@
+import { Badge } from "@carbon/react";
+import type { SVGProps } from "react";
+import { z } from "zod";
+import type { IntegrationConfig } from "../types";
+
+export const Onshape: IntegrationConfig = {
+ name: "Onshape",
+ id: "onshape",
+ active: true,
+ category: "CAD",
+ logo: Logo,
+ description:
+ "Onshape is a CAD software that allows you to create 2D and 3D designs. This integration will sync data from Onshape to Carbon.",
+ shortDescription: "Sync data from Onshape to Carbon.",
+ setupInstructions: SetupInstructions,
+ images: [],
+
+ settings: [
+ {
+ name: "baseUrl",
+ label: "Base URL",
+ type: "text",
+ required: true,
+ value: "https://cad.onshape.com",
+ },
+ {
+ name: "accessKey",
+ label: "Access Key/Username",
+ type: "text",
+ required: true,
+ value: "",
+ },
+ {
+ name: "secretKey",
+ label: "Secret Key/Password",
+ type: "text",
+ required: true,
+ value: "",
+ },
+ {
+ name: "companyId",
+ label: "Company ID",
+ type: "text",
+ required: true,
+ value: "",
+ },
+ ],
+ schema: z.object({
+ baseUrl: z
+ .string()
+ .min(1, { message: "Base URL is required" })
+ .regex(/^https:\/\/.*onshape\.com$/, {
+ message: "URL must start with https:// and end with onshape.com",
+ }),
+
+ accessKey: z.string().min(1, { message: "Access Key is required" }),
+ secretKey: z.string().min(1, { message: "Secret Key is required" }),
+ companyId: z.string().min(1, { message: "Company ID is required" }),
+ }),
+ onInitialize: () => {},
+ onUninstall: () => {},
+};
+
+function SetupInstructions({ companyId }: { companyId: string }) {
+ return (
+ <>
+ <p className="text-sm text-muted-foreground">
+ First, get the base URL of your Onshape account. This is either{" "}
+ <Badge className="font-mono lowercase" variant="gray">
+ https://cad.onshape.com
+ </Badge>{" "}
+ or something like{" "}
+ <Badge className="font-mono lowercase" variant="gray">
+ https://your-company.onshape.com/
+ </Badge>
+ .
+ </p>
+ <p className="text-sm text-muted-foreground">
+ Next, copy the API Key and Secret Key from your Onshape account and
+ paste them into the API Key and Secret Key fields below. Finally, enter
+ the Company ID of your Onshape account.
+ </p>
+ </>
+ );
+}
+
+export function Logo(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ width="216"
+ height="49"
+ viewBox="0 0 216 49"
+ fill="currentColor"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <path
+ d="M11.2302 24.3207L14.7526 26.3435V21.7777L24.3381 16.1716L20.8735 14.0332L11.2302 19.6971V24.3207Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M20.8735 0.97168L28.8421 5.59527L7.8811 18.0212V28.7132L0.258911 24.263V12.993L20.8735 0.97168Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M26.4168 17.3855L22.8945 19.4083L26.9365 21.7779L26.8788 32.5855L30.4012 30.5627V19.6973L26.4168 17.3855Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M41.6612 36.8622L33.6925 41.6014V17.8477L24.0493 12.1838L32.1335 7.50244L41.6612 13.0507V36.8622Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M24.8578 33.857V29.9269L20.8157 32.2965L11.2302 26.6904V30.6205L20.8734 36.2266L24.8578 33.857Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M0.258911 37.0355V28.2507L20.8735 40.0409L30.3435 34.377L30.4012 43.5086L21.1045 48.9991L0.258911 37.0355Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M68.4544 15.3625C71.3416 15.3625 73.6514 16.3451 75.4414 18.2523C77.116 20.1017 77.9822 22.4713 77.9822 25.3033C77.9822 28.1352 77.116 30.5048 75.4414 32.3542C73.6514 34.2614 71.3416 35.244 68.4544 35.244C65.5672 35.244 63.2575 34.2614 61.4674 32.3542C59.7929 30.5048 58.9267 28.1352 58.9267 25.3033C58.9267 22.4713 59.7929 20.1017 61.4674 18.2523C63.2575 16.3451 65.5672 15.3625 68.4544 15.3625ZM68.4544 32.5854C70.5332 32.5854 72.15 31.8919 73.3627 30.447C74.5175 29.0599 75.095 27.3839 75.095 25.3033C75.095 23.2226 74.5175 21.4888 73.3627 20.1595C72.15 18.7146 70.5332 18.0211 68.4544 18.0211C66.3757 18.0211 64.7588 18.7146 63.5462 20.1595C62.3913 21.5466 61.8139 23.2226 61.8139 25.3033C61.8139 27.3839 62.3913 29.1177 63.5462 30.447C64.7011 31.8919 66.3757 32.5854 68.4544 32.5854Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M84.6805 15.7093V18.7146C85.3734 17.7899 86.2396 17.0386 87.2212 16.3451C88.2028 15.7093 89.3577 15.3625 90.6281 15.3625C91.8984 15.3625 92.9956 15.5359 93.9195 15.8827C94.8434 16.2295 95.6518 16.8074 96.3447 17.501C97.9038 19.0614 98.7122 21.142 98.7122 23.685V34.8972H95.825V23.8006C95.825 22.009 95.3053 20.6219 94.3237 19.5816C93.342 18.5413 92.0139 18.0211 90.4549 18.0211C88.838 18.0211 87.4522 18.5413 86.355 19.6394C85.2002 20.7375 84.6805 22.1245 84.6805 23.8584V34.955H81.7933V15.7093H84.6805Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M114.823 20.853C114.592 18.8302 112.975 17.8477 110.03 17.8477C107.085 17.8477 105.584 18.7724 105.584 20.6218C105.584 21.3731 105.872 21.9511 106.508 22.3557C107.143 22.7602 107.951 23.107 108.875 23.3382C109.799 23.5693 110.838 23.8583 111.993 24.0317C113.09 24.2629 114.13 24.5519 115.111 24.9564C116.035 25.361 116.844 25.8811 117.479 26.5747C118.114 27.2682 118.403 28.1929 118.403 29.4066C118.403 31.2561 117.71 32.7009 116.266 33.6834C114.881 34.666 112.975 35.1861 110.55 35.1861C108.009 35.1861 105.93 34.5504 104.429 33.2789C103.043 32.123 102.292 30.6781 102.177 28.8287H105.18C105.353 30.6203 106.334 31.7762 108.182 32.412C108.875 32.6431 109.51 32.7009 110.146 32.7009C110.781 32.7009 111.416 32.6431 111.993 32.5853C112.571 32.5275 113.09 32.3542 113.668 32.1808C114.881 31.7184 115.516 30.8515 115.516 29.6956C115.516 28.8865 115.227 28.3085 114.592 27.8462C113.957 27.4416 113.148 27.0948 112.224 26.8059C111.3 26.5169 110.261 26.2857 109.106 26.0545C108.009 25.8233 106.97 25.5344 105.988 25.1298C105.064 24.7252 104.256 24.2051 103.62 23.5693C102.985 22.8758 102.697 22.0089 102.697 20.7952C102.697 19.0614 103.332 17.6743 104.602 16.7496C105.872 15.767 107.72 15.3047 110.203 15.3047C112.571 15.3047 114.419 15.8826 115.747 16.9807C116.902 17.9055 117.537 19.1769 117.71 20.7374H114.823V20.853Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M124.928 7.96484V18.6569C125.621 17.7322 126.487 16.9808 127.469 16.2873C128.45 15.6516 129.605 15.3048 130.876 15.3048C132.146 15.3048 133.243 15.4782 134.167 15.8249C135.091 16.1717 135.899 16.7497 136.592 17.4432C138.151 19.0037 138.96 21.0843 138.96 23.6272V34.8394H136.073V23.8006C136.073 22.009 135.553 20.6219 134.571 19.5816C133.59 18.5413 132.261 18.0211 130.702 18.0211C129.086 18.0211 127.7 18.5413 126.603 19.6394C125.448 20.7375 124.928 22.1246 124.928 23.8584V34.955H122.041V7.96484H124.928Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M158.766 31.8341C157.207 34.0881 154.955 35.244 151.894 35.244C149.123 35.244 146.871 34.2614 145.138 32.3542C143.464 30.447 142.598 28.1352 142.598 25.3033C142.598 22.5291 143.464 20.1595 145.138 18.2523C146.871 16.3451 149.18 15.3625 152.068 15.3625C154.955 15.3625 157.207 16.5184 158.766 18.7724V15.6515H161.653V34.8972H158.766V31.8341ZM152.299 32.5854C154.377 32.5854 155.994 31.8919 157.207 30.447C158.362 29.0599 158.939 27.3839 158.939 25.3033C158.939 23.2226 158.362 21.4888 157.207 20.1595C155.994 18.7146 154.377 18.0211 152.299 18.0211C150.278 18.0211 148.603 18.7146 147.333 20.1595C146.12 21.5466 145.543 23.2226 145.543 25.3033C145.543 27.3839 146.12 29.1177 147.333 30.447C148.545 31.8919 150.22 32.5854 152.299 32.5854Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M169.506 18.7724C171.065 16.5184 173.317 15.3625 176.378 15.3625C179.149 15.3625 181.401 16.3451 183.076 18.2523C184.808 20.1595 185.675 22.4713 185.675 25.3033C185.675 28.0774 184.808 30.447 183.076 32.3542C181.344 34.2614 179.034 35.244 176.147 35.244C173.26 35.244 171.008 34.0881 169.448 31.8341V42.5839H166.561V15.7093H169.448V18.7724H169.506ZM176.031 17.9633C173.952 17.9633 172.336 18.6569 171.123 20.1017C169.968 21.4888 169.391 23.1648 169.391 25.2455C169.391 27.3261 169.968 29.0599 171.123 30.3892C172.336 31.8341 173.952 32.5276 176.031 32.5276C178.052 32.5276 179.727 31.8341 180.997 30.3892C182.21 29.0021 182.787 27.3261 182.787 25.2455C182.787 23.1648 182.21 21.431 180.997 20.1017C179.727 18.7146 178.052 17.9633 176.031 17.9633Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M198.032 32.5853C200.63 32.5853 202.478 31.4872 203.575 29.3488H206.751C206.058 31.0827 205.019 32.5275 203.575 33.5679C202.132 34.666 200.284 35.1861 197.974 35.1861C195.087 35.1861 192.719 34.2036 190.929 32.2964C189.139 30.4469 188.273 28.0773 188.273 25.2454C188.273 22.4135 189.139 20.0439 190.814 18.1944C192.604 16.2872 194.914 15.3047 197.801 15.3047C200.688 15.3047 202.998 16.2872 204.788 18.1944C206.462 20.0439 207.329 22.4135 207.329 25.2454V26.4013H191.218C191.449 28.1929 192.142 29.6378 193.354 30.7937C194.567 32.0074 196.126 32.5853 198.032 32.5853ZM197.801 17.9633C196.011 17.9633 194.567 18.5412 193.354 19.6393C192.2 20.6796 191.564 22.0667 191.276 23.7427H204.326C204.095 22.0667 203.402 20.6796 202.247 19.6393C201.034 18.5412 199.591 17.9633 197.801 17.9633Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M212.756 21.4889C211.082 21.4889 209.754 20.1019 209.754 18.4836C209.754 16.8075 211.14 15.4783 212.756 15.4783C214.431 15.4783 215.759 16.8653 215.759 18.4836C215.759 20.1019 214.431 21.4889 212.756 21.4889ZM212.756 15.7094C211.255 15.7094 210.042 16.9231 210.042 18.4258C210.042 19.9285 211.255 21.1422 212.756 21.1422C214.258 21.1422 215.47 19.9285 215.47 18.4258C215.47 16.9231 214.2 15.7094 212.756 15.7094Z"
+ fill="currentColor"
+ ></path>
+ <path
+ d="M213.045 16.9231C213.334 16.9231 213.565 16.9809 213.738 17.1543C213.911 17.3277 213.969 17.501 213.969 17.79C213.969 17.9634 213.911 18.1368 213.854 18.3102C213.738 18.4836 213.623 18.5414 213.449 18.5991C213.565 18.5991 213.623 18.6569 213.68 18.7147C213.738 18.7725 213.796 18.8303 213.796 18.8881C213.854 18.9459 213.854 19.0037 213.854 19.0615C213.854 19.1193 213.854 19.2349 213.911 19.2927C213.911 19.3505 213.911 19.4661 213.911 19.5239C213.911 19.5817 213.911 19.6972 213.911 19.755C213.911 19.8128 213.969 19.9284 213.969 19.9862C213.969 20.044 214.027 20.1018 214.084 20.1596H213.623C213.565 20.1018 213.565 20.1018 213.565 20.044C213.565 19.9862 213.565 19.9284 213.565 19.8706C213.565 19.8128 213.565 19.6972 213.565 19.6394C213.565 19.5817 213.565 19.4661 213.565 19.4083C213.565 19.3505 213.565 19.2349 213.507 19.1771C213.507 19.1193 213.449 19.0615 213.449 19.0037C213.392 18.9459 213.334 18.8881 213.276 18.8881C213.218 18.8303 213.103 18.8303 213.045 18.8303H212.006V20.2174H211.602V17.0387H213.045V16.9231ZM213.161 18.368C213.276 18.368 213.334 18.3102 213.392 18.2524C213.449 18.1946 213.507 18.1368 213.565 18.079C213.623 18.0212 213.623 17.9056 213.623 17.79C213.623 17.6166 213.565 17.501 213.507 17.3855C213.392 17.2699 213.276 17.2121 213.045 17.2121H212.006V18.3102H212.872C212.987 18.368 213.045 18.368 213.161 18.368Z"
+ fill="currentColor"
+ ></path>
+ </svg>
+ );
+}
diff --git a/apps/erp/app/integrations/onshape/lib/OnshapeSync.tsx b/apps/erp/app/integrations/onshape/lib/OnshapeSync.tsx
new file mode 100644
index 0000000000..80e7f671f0
--- /dev/null
+++ b/apps/erp/app/integrations/onshape/lib/OnshapeSync.tsx
@@ -0,0 +1,429 @@
+import { useCarbon } from "@carbon/auth";
+import {
+ Badge,
+ Button,
+ Combobox,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ PulsingDot,
+ Spinner,
+ cn,
+ toast,
+ useDisclosure,
+ useMount,
+} from "@carbon/react";
+import { formatDateTime } from "@carbon/utils";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { LuChevronRight } from "react-icons/lu";
+import { MethodIcon } from "~/components";
+import { Logo } from "~/integrations/onshape/config";
+import { methodType } from "~/modules/shared";
+import type { action as onShapeSyncAction } from "~/routes/api+/integrations.onshape.sync";
+import { path } from "~/utils/path";
+
+interface TreeNode {
+ data: TreeData;
+ children: TreeNode[];
+ level: number;
+}
+
+interface TreeData {
+ id?: string;
+ index: string;
+ readableId: string;
+ name?: string;
+ quantity: number;
+ unitOfMeasure: string;
+ replenishmentSystem: string;
+ defaultMethodType: string;
+ mass: number;
+ level: number;
+}
+
+export const OnshapeSync = ({
+ itemId,
+ makeMethodId,
+}: {
+ itemId: string;
+ makeMethodId: string;
+}) => {
+ const [documentId, setDocumentId] = useState<string | null>(null);
+ const [versionId, setVersionId] = useState<string | null>(null);
+ const [elementId, setElementId] = useState<string | null>(null);
+ const [lastSyncedAt, setLastSyncedAt] = useState<string | null>(null);
+
+ const { carbon } = useCarbon();
+ useMount(() => {
+ if (!carbon) {
+ toast.error("Failed to load item data");
+ return;
+ }
+ carbon
+ ?.from("item")
+ .select("externalId")
+ .eq("id", itemId)
+ .single()
+ .then(({ data }) => {
+ const externalId = data?.externalId as Record<string, any>;
+ setDocumentId(externalId.onshape?.documentId);
+ setVersionId(externalId.onshape?.versionId);
+ setElementId(externalId.onshape?.elementId);
+ setLastSyncedAt(externalId.onshape?.lastSyncedAt);
+ });
+ });
+
+ const [bomRows, setBomRows] = useState<TreeData[]>([]);
+ const disclosure = useDisclosure();
+
+ const documentsFetcher = useFetcher<
+ | { data: { items: { id: string; name: string }[] }; error: null }
+ | { data: null; error: string }
+ >({});
+
+ useMount(() => {
+ documentsFetcher.load(path.to.api.onShapeDocuments);
+ });
+
+ useEffect(() => {
+ if (documentsFetcher.data?.error) {
+ toast.error(documentsFetcher.data.error);
+ }
+ }, [documentsFetcher.data]);
+
+ const documentOptions =
+ useMemo(() => {
+ return (
+ documentsFetcher.data?.data?.items
+ ?.map((c) => ({
+ value: c.id,
+ label: c.name,
+ }))
+ .sort((a, b) => a.label.localeCompare(b.label)) ?? []
+ );
+ }, [documentsFetcher.data]) ?? [];
+
+ const versionsFetcher = useFetcher<
+ | { data: { id: string; name: string }[]; error: null }
+ | { data: null; error: string }
+ >({});
+
+ useEffect(() => {
+ if (documentId) {
+ versionsFetcher.load(path.to.api.onShapeVersions(documentId));
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [documentId]);
+
+ const versionOptions =
+ useMemo(() => {
+ return (
+ versionsFetcher.data?.data
+ ?.map((c) => ({
+ value: c.id,
+ label: c.name,
+ }))
+ .sort((a, b) => a.label.localeCompare(b.label)) ?? []
+ );
+ }, [versionsFetcher.data]) ?? [];
+
+ const elementsFetcher = useFetcher<
+ | { data: { id: string; name: string }[]; error: null }
+ | { data: null; error: string }
+ >({});
+
+ useEffect(() => {
+ if (documentId && versionId) {
+ elementsFetcher.load(path.to.api.onShapeElements(documentId, versionId));
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [documentId, versionId]);
+
+ const elementOptions =
+ useMemo(() => {
+ return (
+ elementsFetcher.data?.data?.map((c) => ({
+ value: c.id,
+ label: c.name,
+ })) ?? []
+ );
+ }, [elementsFetcher.data]) ?? [];
+
+ const isDataLoading =
+ documentsFetcher.state === "loading" ||
+ versionsFetcher.state === "loading" ||
+ elementsFetcher.state === "loading";
+
+ const isReadyForSync =
+ documentId &&
+ versionId &&
+ elementId &&
+ documentOptions.some((c) => c.value === documentId) &&
+ versionOptions.some((c) => c.value === versionId) &&
+ elementOptions.some((c) => c.value === elementId);
+
+ const bomFetcher = useFetcher<
+ | { data: null; error: string }
+ | {
+ data: {
+ tree: TreeNode[];
+ rows: TreeData[];
+ };
+ error: null;
+ }
+ >();
+
+ useEffect(() => {
+ if (bomFetcher.data?.data?.rows) {
+ setBomRows(bomFetcher.data.data.rows);
+ }
+ }, [bomFetcher.data]);
+
+ const loadBom = () => {
+ if (isReadyForSync) {
+ bomFetcher.load(path.to.api.onShapeBom(documentId, versionId, elementId));
+ }
+ };
+
+ const upsertBomFetcher = useFetcher<typeof onShapeSyncAction>();
+ const syncSubmitted = useRef(false);
+ const saveBom = () => {
+ syncSubmitted.current = true;
+ const formData = new FormData();
+ formData.append("documentId", documentId ?? "");
+ formData.append("versionId", versionId ?? "");
+ formData.append("elementId", elementId ?? "");
+ formData.append("makeMethodId", makeMethodId);
+ formData.append("rows", JSON.stringify(bomRows));
+ upsertBomFetcher.submit(formData, {
+ method: "post",
+ action: path.to.api.onShapeSync,
+ });
+ };
+
+ useEffect(() => {
+ if (
+ syncSubmitted.current &&
+ upsertBomFetcher.data?.success &&
+ bomRows.length > 0
+ ) {
+ setBomRows([]);
+ setLastSyncedAt(new Date().toISOString());
+ syncSubmitted.current = false;
+ toast.success("BOM synced successfully");
+ }
+
+ if (upsertBomFetcher.data?.success === false) {
+ toast.error(upsertBomFetcher.data.message);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [bomRows.length, upsertBomFetcher.data]);
+
+ return (
+ <div className="flex flex-col gap-2 w-full">
+ <div className="flex flex-col gap-2 border bg-muted/30 rounded p-2 w-full">
+ <div className="flex items-center w-full justify-between">
+ <Logo className="h-5 w-auto" />
+ <IconButton
+ aria-label="Show sync options"
+ variant="ghost"
+ size="sm"
+ icon={<LuChevronRight />}
+ className={cn(disclosure.isOpen && "rotate-90")}
+ onClick={disclosure.onToggle}
+ />
+ </div>
+
+ {disclosure.isOpen && (
+ <>
+ <div className="flex w-full items-center justify-between gap-2">
+ <span className="text-xs text-muted-foreground">Document:</span>
+ <div className="w-[180px]">
+ <Combobox
+ isLoading={documentsFetcher.state === "loading"}
+ options={documentOptions}
+ onChange={(value) => {
+ setVersionId(null);
+ setElementId(null);
+ setDocumentId(value);
+ }}
+ size="sm"
+ className="text-xs"
+ value={documentId ?? undefined}
+ />
+ </div>
+ </div>
+
+ <div className="flex w-full items-center justify-between gap-2">
+ <span className="text-xs text-muted-foreground">Version:</span>
+ <div className="w-[180px]">
+ <Combobox
+ isLoading={versionsFetcher.state === "loading"}
+ options={versionOptions}
+ onChange={(value) => {
+ setVersionId(value);
+ setElementId(null);
+ }}
+ size="sm"
+ className="text-xs"
+ value={versionId ?? undefined}
+ />
+ </div>
+ </div>
+
+ <div className="flex w-full items-center justify-between gap-2">
+ <span className="text-xs text-muted-foreground">Element:</span>
+ <div className="w-[180px]">
+ <Combobox
+ isLoading={elementsFetcher.state === "loading"}
+ options={elementOptions}
+ onChange={(value) => {
+ setElementId(value);
+ }}
+ size="sm"
+ className="text-xs"
+ value={elementId ?? undefined}
+ />
+ </div>
+ </div>
+
+ {/* <div className="flex w-full items-center justify-between gap-2">
+ <span className="text-xs text-muted-foreground">Sync mode:</span>
+ <div className="flex items-center space-x-4">
+ <div className="flex items-center space-x-2">
+ <input
+ type="radio"
+ id="manual"
+ name="syncMode"
+ value="manual"
+ className="h-4 w-4 text-primary border-muted-foreground focus:ring-primary"
+ defaultChecked={mode === "manual"}
+ />
+ <label htmlFor="manual" className="text-xs cursor-pointer">
+ Manual
+ </label>
+ </div>
+ <div className="flex items-center space-x-2">
+ <input
+ type="radio"
+ id="automatic"
+ name="syncMode"
+ value="automatic"
+ className="h-4 w-4 text-primary border-muted-foreground focus:ring-primary"
+ defaultChecked={mode === "automatic"}
+ />
+ <label htmlFor="automatic" className="text-xs cursor-pointer">
+ Automatic
+ </label>
+ </div>
+ </div>
+ </div> */}
+ </>
+ )}
+ {lastSyncedAt && (
+ <div className="flex items-center gap-1 w-full justify-between">
+ <span className="text-xs text-muted-foreground">
+ Last synced: {formatDateTime(lastSyncedAt)}
+ </span>
+ {isDataLoading ? (
+ <Spinner className="size-3" />
+ ) : (
+ <Button
+ variant={bomRows.length > 0 ? "secondary" : "primary"}
+ isLoading={bomFetcher.state !== "idle"}
+ isDisabled={!isReadyForSync || bomFetcher.state !== "idle"}
+ size="sm"
+ onClick={loadBom}
+ >
+ {bomRows.length > 0 ? "Refresh" : "Sync"}
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ {bomRows.length > 0 && (
+ <div className="flex flex-col gap-2 border bg-muted/30 rounded p-2 w-full">
+ <HStack className="w-full justify-between">
+ <span className="text-xs text-muted-foreground font-light mb-1">
+ Bill of Materials
+ </span>
+ <Button
+ size="sm"
+ onClick={saveBom}
+ isLoading={upsertBomFetcher.state !== "idle"}
+ isDisabled={upsertBomFetcher.state !== "idle"}
+ >
+ Save
+ </Button>
+ </HStack>
+
+ <div className="max-h-60 overflow-y-auto flex flex-col">
+ {bomRows.map((row) => (
+ <div
+ key={row.index}
+ className={cn(
+ "flex min-h-8 cursor-pointer items-center overflow-hidden rounded-sm pr-2 w-full gap-1 hover:bg-muted/90"
+ )}
+ style={{
+ paddingLeft: `${row.level * 12}px`,
+ }}
+ >
+ <div
+ className={cn(
+ "flex items-center gap-2 font-medium text-sm w-full",
+ row.level > 1 && "opacity-50"
+ )}
+ >
+ <DropdownMenu>
+ <DropdownMenuTrigger>
+ <MethodIcon type={row.defaultMethodType} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuRadioGroup
+ value={row.defaultMethodType}
+ onValueChange={(value) => {
+ setBomRows((prevRows) =>
+ prevRows.map((r) =>
+ r.index === row.index
+ ? { ...r, defaultMethodType: value }
+ : r
+ )
+ );
+ }}
+ >
+ {methodType.map((type) => (
+ <DropdownMenuRadioItem key={type} value={type}>
+ <DropdownMenuIcon
+ icon={<MethodIcon type={type} />}
+ />
+ {type}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <span className="line-clamp-1">
+ {row.readableId || row.name}
+ </span>
+ {!row.id && <PulsingDot className="mt-0.5" />}
+ </div>
+ <HStack spacing={1}>
+ <Badge className="text-xs" variant="outline">
+ {row.quantity}
+ </Badge>
+ </HStack>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/apps/erp/app/integrations/onshape/lib/client.ts b/apps/erp/app/integrations/onshape/lib/client.ts
new file mode 100644
index 0000000000..a2ed841042
--- /dev/null
+++ b/apps/erp/app/integrations/onshape/lib/client.ts
@@ -0,0 +1,101 @@
+interface OnshapeClientConfig {
+ baseUrl: string;
+ accessKey: string;
+ secretKey: string;
+}
+
+export interface OnshapePart {
+ id: string;
+ name: string;
+ partNumber: string;
+ revision: string;
+ description: string;
+ metadata: Record<string, string>;
+}
+
+export class OnshapeClient {
+ private baseUrl: string;
+ private accessKey: string;
+ private secretKey: string;
+
+ constructor(config: OnshapeClientConfig) {
+ this.baseUrl = config.baseUrl;
+ this.accessKey = config.accessKey;
+ this.secretKey = config.secretKey;
+ }
+
+ /**
+ * Generate the authorization headers for Onshape API requests
+ */
+ private getAuthHeaders(): Record<string, string> {
+ return {
+ "Content-Type": "application/json",
+ Accept: "application/json;charset=UTF-8; qs=0.09",
+ Authorization: `Basic ${btoa(`${this.accessKey}:${this.secretKey}`)}`,
+ };
+ }
+
+ /**
+ * Make an authenticated request to the Onshape API
+ */
+ private async request<T>(
+ method: string,
+ path: string,
+ body?: Record<string, unknown>
+ ): Promise<T> {
+ const headers = this.getAuthHeaders();
+ const url = `${this.baseUrl}${path}`;
+
+ const response = await fetch(url, {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(`Onshape API error (${response.status}): ${errorText}`);
+ }
+
+ return response.json();
+ }
+
+ /**
+ * Get a list of documents
+ */
+ async getDocuments(limit: number = 20, offset: number = 0): Promise<any> {
+ return this.request(
+ "GET",
+ `/api/v10/documents?limit=${limit}&offset=${offset}`
+ );
+ }
+
+ async getVersions(
+ documentId: string,
+ limit: number = 20,
+ offset: number = 0
+ ): Promise<any> {
+ return this.request(
+ "GET",
+ `/api/v10/documents/d/${documentId}/versions?limit=${limit}&offset=${offset}`
+ );
+ }
+
+ async getElements(documentId: string, versionId: string): Promise<any> {
+ return this.request(
+ "GET",
+ `/api/v10/documents/d/${documentId}/v/${versionId}/elements`
+ );
+ }
+
+ async getBillOfMaterials(
+ documentId: string,
+ versionId: string,
+ elementId: string
+ ): Promise<any> {
+ return this.request(
+ "GET",
+ `/api/v10/assemblies/d/${documentId}/v/${versionId}/e/${elementId}/bom?indented=true&multiLevel=true&generateIfAbsent=true&onlyVisibleColumns=true&includeItemMicroversions=false&includeTopLevelAssemblyRow=true&thumbnail=false`
+ );
+ }
+}
diff --git a/apps/erp/app/integrations/onshape/lib/data.ts b/apps/erp/app/integrations/onshape/lib/data.ts
new file mode 100644
index 0000000000..edf52fedd1
--- /dev/null
+++ b/apps/erp/app/integrations/onshape/lib/data.ts
@@ -0,0 +1,15 @@
+import { z } from "zod";
+import { itemReplenishmentSystems } from "~/modules/items/items.models";
+import { methodType } from "~/modules/shared/shared.models";
+
+export const onShapeDataValidator = z
+ .object({
+ id: z.string().optional(),
+ index: z.string(),
+ readableId: z.string().optional(),
+ name: z.string(),
+ quantity: z.number(),
+ replenishmentSystem: z.enum(itemReplenishmentSystems),
+ defaultMethodType: z.enum(methodType),
+ })
+ .array();
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 410ad96bb7..c93a7c8b05 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -657,6 +657,19 @@ export async function getMakeMethod(
.single();
}
+export async function getMakeMethodById(
+ client: SupabaseClient<Database>,
+ makeMethodId: string,
+ companyId: string
+) {
+ return client
+ .from("makeMethod")
+ .select("*")
+ .eq("id", makeMethodId)
+ .eq("companyId", companyId)
+ .single();
+}
+
export async function getMaterial(
client: SupabaseClient<Database>,
itemId: string,
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index f75a529be9..2380ad0b56 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -25,7 +25,12 @@ import {
useThrottle,
VStack,
} from "@carbon/react";
-import { useFetcher, useFetchers, useParams } from "@remix-run/react";
+import {
+ useFetcher,
+ useFetchers,
+ useParams,
+ useSearchParams,
+} from "@remix-run/react";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import type { Dispatch, SetStateAction } from "react";
import { useCallback, useEffect, useState } from "react";
@@ -64,6 +69,7 @@ import {
type MethodItemType,
type MethodType,
} from "~/modules/shared";
+import { useBom } from "~/stores";
import { path } from "~/utils/path";
import type { methodOperationValidator } from "../../items.models";
import { methodMaterialValidator } from "../../items.models";
@@ -127,7 +133,8 @@ const BillOfMaterial = ({
}: BillOfMaterialProps) => {
const fetcher = useFetcher<{}>();
const permissions = usePermissions();
-
+ const [searchParams] = useSearchParams();
+ const materialId = searchParams.get("materialId");
const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
const [temporaryItems, setTemporaryItems] = useState<TemporaryItems>({});
const [checkedState, setCheckedState] = useState<CheckedState>({});
@@ -287,6 +294,8 @@ const BillOfMaterial = ({
});
}, [materials]);
+ const [selectedMaterialId, setSelectedMaterialId] = useBom();
+
const renderListItem = ({
item,
items,
@@ -295,6 +304,10 @@ const BillOfMaterial = ({
onRemoveItem,
}: SortableItemRenderProps<ItemWithData>) => {
const isOpen = item.id === selectedItemId;
+ const onSelectItem = (id: string | null) => {
+ setSelectedMaterialId(id);
+ setSelectedItemId(id);
+ };
return (
<SortableListItem<Material>
@@ -303,7 +316,8 @@ const BillOfMaterial = ({
order={order}
key={item.id}
isExpanded={isOpen}
- onSelectItem={setSelectedItemId}
+ isHighlighted={item.id === selectedMaterialId}
+ onSelectItem={onSelectItem}
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={onCloseOnDrag}
@@ -321,10 +335,10 @@ const BillOfMaterial = ({
onClick={
isOpen
? () => {
- setSelectedItemId(null);
+ onSelectItem(null);
}
: () => {
- setSelectedItemId(item.id);
+ onSelectItem(item.id);
}
}
key="collapse"
@@ -435,8 +449,6 @@ const BillOfMaterial = ({
configurationRules?.map((rule) => [rule.field, rule]) ?? []
);
- const { materialId } = useParams();
-
return (
<Card>
<HStack className="justify-between">
@@ -928,8 +940,8 @@ function makeItem(
};
}
-function getFieldKey(field: string, materialId: string) {
- return `${field}:${materialId}`;
+function getFieldKey(field: string, itemId: string) {
+ return `${field}:${itemId}`;
}
const usePendingMaterials = () => {
diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
index 336c3a15fe..ac9155fe77 100644
--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
@@ -18,20 +18,30 @@ import { LuChevronDown, LuChevronRight, LuSearch } from "react-icons/lu";
import { MethodIcon, MethodItemTypeIcon } from "~/components";
import type { FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
-import type { MethodItemType } from "~/modules/shared";
+import { useIntegrations } from "~/hooks/useIntegrations";
+import { OnshapeSync } from "~/integrations/onshape/lib/OnshapeSync";
+import { type MethodItemType } from "~/modules/shared";
+import { useBom } from "~/stores";
import { path } from "~/utils/path";
import type { Method } from "../../types";
type BoMExplorerProps = {
itemType: MethodItemType;
+ makeMethodId: string;
methods: FlatTreeItem<Method>[];
selectedId?: string;
};
-const BoMExplorer = ({ itemType, methods, selectedId }: BoMExplorerProps) => {
+const BoMExplorer = ({
+ itemType,
+ makeMethodId,
+ methods,
+ selectedId,
+}: BoMExplorerProps) => {
const [filterText, setFilterText] = useState("");
const parentRef = useRef<HTMLDivElement>(null);
-
+ const integrations = useIntegrations();
+ const params = useParams();
const {
nodes,
getTreeProps,
@@ -69,13 +79,22 @@ const BoMExplorer = ({ itemType, methods, selectedId }: BoMExplorerProps) => {
});
const navigate = useNavigate();
- const params = useParams();
+
const { itemId } = params;
if (!itemId) throw new Error("itemId not found");
+ const [selectedMaterialId, setSelectedMaterialId] = useBom();
useMount(() => {
- if (params.materialId) {
- selectNode(params.materialId);
+ if (selectedMaterialId) {
+ const node = methods.find(
+ (m) => m.data.methodMaterialId === selectedMaterialId
+ );
+ selectNode(node?.id ?? methods[0].id);
+ } else if (params.makeMethodId) {
+ const node = methods.find(
+ (m) => m.data.materialMakeMethodId === params.makeMethodId
+ );
+ selectNode(node?.id ?? methods[0].id);
} else if (methods?.length > 0) {
selectNode(methods[0].id);
}
@@ -95,6 +114,9 @@ const BoMExplorer = ({ itemType, methods, selectedId }: BoMExplorerProps) => {
/>
</InputGroup>
</HStack>
+ {integrations.has("onshape") && (
+ <OnshapeSync makeMethodId={makeMethodId} itemId={itemId} />
+ )}
<TreeView
parentRef={parentRef}
virtualizer={virtualizer}
@@ -103,98 +125,99 @@ const BoMExplorer = ({ itemType, methods, selectedId }: BoMExplorerProps) => {
nodes={nodes}
getNodeProps={getNodeProps}
getTreeProps={getTreeProps}
- renderNode={({ node, state }) => (
- <HoverCard>
- <HoverCardTrigger asChild>
- <div
- key={node.id}
- className={cn(
- "flex h-8 cursor-pointer items-center overflow-hidden rounded-sm pr-2 gap-1",
- state.selected
- ? "bg-muted hover:bg-muted/90"
- : "bg-transparent hover:bg-muted/90"
- )}
- onClick={() => {
- selectNode(node.id);
- if (node.data.isRoot) {
- navigate(getRootLink(itemType, itemId));
- } else {
- navigate(
- getMaterialLink(
- itemType,
- itemId,
- node.data.materialMakeMethodId ??
- node.data.methodType.toLowerCase(),
- node.data.methodMaterialId
- )
- );
- }
- }}
- >
- <div className="flex h-8 items-center">
- {Array.from({ length: node.level }).map((_, index) => (
- <LevelLine key={index} isSelected={state.selected} />
- ))}
- <div
- className={cn(
- "flex h-8 w-4 items-center",
- node.hasChildren && "hover:bg-accent"
- )}
- onClick={(e) => {
- e.stopPropagation();
- if (e.altKey) {
- if (state.expanded) {
- collapseAllBelowDepth(node.level);
+ renderNode={({ node, state }) => {
+ return (
+ <HoverCard>
+ <HoverCardTrigger asChild>
+ <div
+ key={node.id}
+ className={cn(
+ "flex h-8 cursor-pointer items-center overflow-hidden rounded-sm pr-2 gap-1",
+ state.selected
+ ? "bg-muted hover:bg-muted/90"
+ : "bg-transparent hover:bg-muted/90"
+ )}
+ onClick={() => {
+ selectNode(node.id);
+ setSelectedMaterialId(node.data.methodMaterialId);
+ if (node.data.isRoot) {
+ navigate(getRootLink(itemType, itemId));
+ } else {
+ navigate(
+ getMaterialLink(
+ itemType,
+ itemId,
+ node.data.makeMethodId
+ )
+ );
+ }
+ }}
+ >
+ <div className="flex h-8 items-center">
+ {Array.from({ length: node.level }).map((_, index) => (
+ <LevelLine key={index} isSelected={state.selected} />
+ ))}
+ <div
+ className={cn(
+ "flex h-8 w-4 items-center",
+ node.hasChildren && "hover:bg-accent"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (e.altKey) {
+ if (state.expanded) {
+ collapseAllBelowDepth(node.level);
+ } else {
+ expandAllBelowDepth(node.level);
+ }
} else {
- expandAllBelowDepth(node.level);
+ toggleExpandNode(node.id);
}
- } else {
- toggleExpandNode(node.id);
- }
- scrollToNode(node.id);
- }}
- >
- {node.hasChildren ? (
- state.expanded ? (
- <LuChevronDown className="h-4 w-4 text-gray-400 flex-shrink-0 ml-1" />
+ scrollToNode(node.id);
+ }}
+ >
+ {node.hasChildren ? (
+ state.expanded ? (
+ <LuChevronDown className="h-4 w-4 text-gray-400 flex-shrink-0 ml-1" />
+ ) : (
+ <LuChevronRight className="h-4 w-4 text-gray-400 flex-shrink-0 ml-1" />
+ )
) : (
- <LuChevronRight className="h-4 w-4 text-gray-400 flex-shrink-0 ml-1" />
- )
- ) : (
- <div className="h-8 w-4" />
- )}
+ <div className="h-8 w-4" />
+ )}
+ </div>
</div>
- </div>
- <div className="flex w-full items-center justify-between gap-2">
- <div className="flex items-center gap-2 overflow-x-hidden">
- <MethodIcon
- type={
- // node.data.isRoot ? "Method" :
- node.data.methodType
- }
- isKit={node.data.kit}
- className="h-4 min-h-4 w-4 min-w-4 flex-shrink-0"
- />
- <NodeText node={node} />
- </div>
- <div className="flex items-center gap-1">
- {node.data.isRoot ? (
- <Badge variant="outline" className="text-xs">
- Method
- </Badge>
- ) : (
- <NodeData node={node} />
- )}
+ <div className="flex w-full items-center justify-between gap-2">
+ <div className="flex items-center gap-2 overflow-x-hidden">
+ <MethodIcon
+ type={
+ // node.data.isRoot ? "Method" :
+ node.data.methodType
+ }
+ isKit={node.data.kit}
+ className="h-4 min-h-4 w-4 min-w-4 flex-shrink-0"
+ />
+ <NodeText node={node} />
+ </div>
+ <div className="flex items-center gap-1">
+ {node.data.isRoot ? (
+ <Badge variant="outline" className="text-xs">
+ Method
+ </Badge>
+ ) : (
+ <NodeData node={node} />
+ )}
+ </div>
</div>
</div>
- </div>
- </HoverCardTrigger>
- <HoverCardContent side="right">
- <NodePreview node={node} />
- </HoverCardContent>
- </HoverCard>
- )}
+ </HoverCardTrigger>
+ <HoverCardContent side="right">
+ <NodePreview node={node} />
+ </HoverCardContent>
+ </HoverCard>
+ );
+ }}
/>
</VStack>
);
@@ -206,7 +229,7 @@ function NodeText({ node }: { node: FlatTreeItem<Method> }) {
return (
<div className="flex flex-col items-start gap-0">
<span className="text-sm truncate font-medium">
- {node.data.description || node.data.itemReadableId}
+ {node.data.itemReadableId || node.data.description}
</span>
</div>
);
@@ -293,28 +316,13 @@ function getRootLink(itemType: MethodItemType, itemId: string) {
function getMaterialLink(
itemType: MethodItemType,
itemId: string,
- makeMethodId: string,
- materialId: string
+ makeMethodId: string
) {
switch (itemType) {
case "Part":
- return path.to.partManufacturingMaterial(
- itemId,
- makeMethodId,
- materialId
- );
- // case "Fixture":
- // return path.to.fixtureManufacturingMaterial(
- // itemId,
- // makeMethodId,
- // materialId
- // );
+ return path.to.partManufacturingMaterial(itemId, makeMethodId);
case "Tool":
- return path.to.toolManufacturingMaterial(
- itemId,
- makeMethodId,
- materialId
- );
+ return path.to.toolManufacturingMaterial(itemId, makeMethodId);
default:
throw new Error(`Unimplemented BoMExplorer itemType: ${itemType}`);
}
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index e780f09945..0b6f3bc589 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1,4 +1,5 @@
import type { Database, Json } from "@carbon/database";
+import type { JSONContent } from "@carbon/react";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
import type { StorageItem } from "~/types";
@@ -24,7 +25,6 @@ import type {
scrapReasonValidator,
} from "./production.models";
import type { Job } from "./types";
-import { JSONContent } from "@carbon/react";
export async function deleteJob(
client: SupabaseClient<Database>,
@@ -247,7 +247,7 @@ export async function getJobMakeMethodById(
) {
return client
.from("jobMakeMethod")
- .select("*")
+ .select("*, ...item(itemType:type)")
.eq("id", jobMakeMethodId)
.single();
}
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index 353c478a8a..63ed62f3b6 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -48,6 +48,7 @@ import type {
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import type { MethodItemType, MethodType } from "~/modules/shared";
+import { useBom } from "~/stores";
import { path } from "~/utils/path";
import type { jobOperationValidator } from "../../production.models";
import {
@@ -379,6 +380,12 @@ const JobBillOfMaterial = ({
});
}, [items]);
+ const [selectedMaterialId, setSelectedMaterialId] = useBom();
+ const onSelectItem = (id: string | null) => {
+ setSelectedMaterialId(id);
+ setSelectedItemId(id);
+ };
+
const renderListItem = ({
item,
items,
@@ -395,7 +402,8 @@ const JobBillOfMaterial = ({
order={order}
key={item.id}
isExpanded={isOpen}
- onSelectItem={setSelectedItemId}
+ isHighlighted={item.id === selectedMaterialId}
+ onSelectItem={onSelectItem}
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={onCloseOnDrag}
@@ -428,10 +436,10 @@ const JobBillOfMaterial = ({
};
});
}
- setSelectedItemId(null);
+ onSelectItem(null);
}
: () => {
- setSelectedItemId(item.id);
+ onSelectItem(item.id);
}
}
key="collapse"
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
index 471f9bf354..1051c805f1 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
@@ -15,13 +15,14 @@ import {
VStack,
cn,
} from "@carbon/react";
-import { useFetchers, useNavigate } from "@remix-run/react";
-import { useRef, useState } from "react";
+import { useFetchers, useNavigate, useParams } from "@remix-run/react";
+import { useEffect, useRef, useState } from "react";
import { LuChevronDown, LuChevronRight, LuSearch } from "react-icons/lu";
import { MethodIcon, MethodItemTypeIcon } from "~/components";
import type { FlatTree, FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useOptimisticLocation } from "~/hooks";
+import { useBom } from "~/stores";
import { path } from "~/utils/path";
import type { JobMethod } from "../../production.service";
@@ -34,6 +35,7 @@ const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {
const navigate = useNavigate();
const location = useOptimisticLocation();
const [filterText, setFilterText] = useState("");
+ const { methodId } = useParams();
const fetchers = useFetchers();
const getMethodFetcher = fetchers.find(
@@ -78,6 +80,24 @@ const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {
isEager: true,
});
+ const [selectedMaterialId, setSelectedMaterialId] = useBom();
+ useEffect(() => {
+ if (selectedMaterialId) {
+ const node = method.find(
+ (m) => m.data.methodMaterialId === selectedMaterialId
+ );
+ selectNode(node?.id ?? method[0].id);
+ } else if (methodId) {
+ const node = method.find(
+ (m) => m.data.jobMaterialMakeMethodId === methodId
+ );
+ selectNode(node?.id ?? method[0].id);
+ } else if (method?.length > 0) {
+ selectNode(method[0].id);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedMaterialId, methodId]);
+
return (
<VStack>
{isLoading ? (
@@ -113,12 +133,13 @@ const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {
key={node.id}
className={cn(
"flex h-8 cursor-pointer items-center overflow-hidden rounded-sm pr-2 gap-1",
- getNodePath(node) === location.pathname
+ state.selected
? "bg-muted hover:bg-muted/90"
: "bg-transparent hover:bg-muted/90"
)}
onClick={(e) => {
selectNode(node.id);
+ setSelectedMaterialId(node.data.methodMaterialId);
navigate(getNodePath(node));
}}
>
@@ -202,7 +223,7 @@ function NodeText({ node }: { node: FlatTreeItem<JobMethod> }) {
return (
<div className="flex items-center gap-1">
<span className="font-medium text-sm truncate">
- {node.data.description || node.data.itemReadableId}
+ {node.data.itemReadableId || node.data.description}
</span>
</div>
);
@@ -282,15 +303,8 @@ function NodePreview({ node }: { node: FlatTreeItem<JobMethod> }) {
function getNodePath(node: FlatTreeItem<JobMethod>) {
return node.data.isRoot
? path.to.jobMethod(node.data.jobId, node.data.jobMaterialMakeMethodId)
- : node.data.methodType === "Make"
- ? path.to.jobMakeMethod(
- node.data.jobId,
- node.data.jobMaterialMakeMethodId,
- node.data.methodMaterialId
- )
- : path.to.jobMethodMaterial(
+ : path.to.jobMakeMethod(
node.data.jobId,
- node.data.methodType.toLowerCase(),
node.data.jobMakeMethodId,
node.data.methodMaterialId
);
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index fad8554add..b268e2cb53 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -25,14 +25,15 @@ import {
useMount,
VStack,
} from "@carbon/react";
+import { labelSizes } from "@carbon/utils";
import {
Await,
Link,
useFetcher,
useLocation,
useParams,
+ useSearchParams,
} from "@remix-run/react";
-import type { PostgrestSingleResponse } from "@supabase/supabase-js";
import { Suspense, useEffect, useState } from "react";
import {
LuGitBranch,
@@ -52,21 +53,18 @@ import type {
ConfigurationParameterGroup,
} from "~/modules/items";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
+import { QuoteLineMethodForm } from "~/modules/sales/ui/Quotes/QuoteLineMethodForm";
import type { MethodItemType } from "~/modules/shared/types";
import { path } from "~/utils/path";
import { getJobMethodValidator } from "../../production.models";
-import type { Job, JobMakeMethod, JobMaterial, JobMethod } from "../../types";
-import { labelSizes } from "@carbon/utils";
-import { QuoteLineMethodForm } from "~/modules/sales/ui/Quotes/QuoteLineMethodForm";
+import type { Job, JobMakeMethod, JobMethod } from "../../types";
-const JobMakeMethodTools = ({
- makeMethod,
-}: {
- makeMethod?: Promise<PostgrestSingleResponse<JobMakeMethod>>;
-}) => {
+const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
const permissions = usePermissions();
- const { jobId, methodId, materialId } = useParams();
+ const { jobId, methodId } = useParams();
if (!jobId) throw new Error("jobId not found");
+ const [searchParams] = useSearchParams();
+ const materialId = searchParams.get("materialId");
const fetcher = useFetcher<{ error: string | null }>();
const routeData = useRouteData<{
@@ -79,13 +77,13 @@ const JobMakeMethodTools = ({
}>(path.to.job(jobId));
const materialRouteData = useRouteData<{
- material: JobMaterial;
+ makeMethod: JobMakeMethod;
}>(path.to.jobMakeMethod(jobId, methodId!, materialId!));
const itemId =
- materialRouteData?.material?.jobMaterialItemId ?? routeData?.job?.itemId;
+ materialRouteData?.makeMethod?.itemId ?? routeData?.job?.itemId;
const itemType =
- materialRouteData?.material?.type ?? routeData?.job?.itemType;
+ materialRouteData?.makeMethod?.itemType ?? routeData?.job?.itemType;
const itemLink =
itemType && itemId
@@ -123,7 +121,7 @@ const JobMakeMethodTools = ({
const isJobMakeMethod =
methodId &&
materialId &&
- pathname === path.to.jobMakeMethod(jobId, methodId, materialId);
+ pathname === path.to.jobMakeMethod(jobId, methodId);
const { carbon } = useCarbon();
@@ -237,40 +235,26 @@ const JobMakeMethodTools = ({
</Link>
</MenubarItem>
)}
- {makeMethod && (
- <Suspense fallback={null}>
- <Await resolve={makeMethod}>
- {(resolvedMakeMethod) =>
- resolvedMakeMethod.data?.requiresSerialTracking ||
- resolvedMakeMethod.data?.requiresBatchTracking ? (
- <SplitButton
- dropdownItems={labelSizes.map((size) => ({
- label: size.name,
- onClick: () =>
- navigateToTrackingLabels(
- resolvedMakeMethod.data?.id,
- !!size.zpl,
- {
- labelSize: size.id,
- }
- ),
- }))}
- leftIcon={<LuQrCode />}
- variant="ghost"
- onClick={() =>
- navigateToTrackingLabels(
- resolvedMakeMethod.data?.id,
- false
- )
- }
- >
- Tracking Labels
- </SplitButton>
- ) : null
+ {makeMethod &&
+ (makeMethod.requiresSerialTracking ||
+ makeMethod.requiresBatchTracking) && (
+ <SplitButton
+ dropdownItems={labelSizes.map((size) => ({
+ label: size.name,
+ onClick: () =>
+ navigateToTrackingLabels(makeMethod.id, !!size.zpl, {
+ labelSize: size.id,
+ }),
+ }))}
+ leftIcon={<LuQrCode />}
+ variant="ghost"
+ onClick={() =>
+ navigateToTrackingLabels(makeMethod.id, false)
}
- </Await>
- </Suspense>
- )}
+ >
+ Tracking Labels
+ </SplitButton>
+ )}
</HStack>
</HStack>
</Menubar>
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
index 461386ceb1..8ca1f7ab8a 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialForm.tsx
@@ -33,6 +33,7 @@ import {
} from "~/components/Form";
import { usePermissions, useRouteData } from "~/hooks";
import type { MethodItemType, MethodType } from "~/modules/shared";
+import { useBom } from "~/stores";
import { path } from "~/utils/path";
import type { jobOperationValidator } from "../../production.models";
import { jobMaterialValidator } from "../../production.models";
@@ -128,40 +129,17 @@ const JobMaterialForm = ({
}
};
- useEffect(() => {
- const newPath =
- initialValues.methodType === "Make"
- ? path.to.jobMakeMethod(
- jobId,
- initialValues.jobMaterialMakeMethodId!,
- initialValues.id!
- )
- : path.to.jobMethodMaterial(
- jobId,
- initialValues.methodType.toLowerCase(),
- initialValues.jobMakeMethodId,
- initialValues.id!
- );
- if (
- fetcher.data?.methodType === "Make" &&
- !location.pathname.includes("make")
- ) {
- navigate(newPath);
- }
-
- if (
- fetcher.data?.methodType === "Buy" &&
- !location.pathname.includes("buy")
- ) {
- navigate(newPath);
- }
+ const [, setSelectedMaterialId] = useBom();
- if (
- fetcher.data?.methodType === "Pick" &&
- !location.pathname.includes("pick")
- ) {
- navigate(newPath);
- }
+ useEffect(() => {
+ const newPath = path.to.jobMakeMethod(
+ jobId,
+ initialValues.jobMakeMethodId!,
+ initialValues.id!
+ );
+
+ setSelectedMaterialId(initialValues.id ?? null);
+ navigate(newPath);
}, [
fetcher.data,
initialValues,
@@ -171,6 +149,7 @@ const JobMaterialForm = ({
jobId,
location.pathname,
navigate,
+ setSelectedMaterialId,
]);
const isDisabled = ["Completed", "Cancelled"].includes(
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
index 820b11fd23..cb4b06b30d 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMaterialsTable.tsx
@@ -21,13 +21,12 @@ import {
} from "~/components";
import { EditableNumber, EditableText } from "~/components/Editable";
import { Enumerable } from "~/components/Enumerable";
-import { useLocations } from "~/components/Form/Location";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
-import { usePermissions, useRouteData, useUser } from "~/hooks";
+import { usePermissions, useUser } from "~/hooks";
import { methodType } from "~/modules/shared";
+import { useBom, useItems } from "~/stores";
import { path } from "~/utils/path";
-import type { Job, JobMaterial } from "../../types";
-import { useItems } from "~/stores";
+import type { JobMaterial } from "../../types";
type JobMaterialsTableProps = {
data: JobMaterial[];
@@ -37,14 +36,12 @@ type JobMaterialsTableProps = {
const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
const { jobId } = useParams();
if (!jobId) throw new Error("Job ID is required");
- const routeData = useRouteData<{
- job: Job;
- }>(path.to.job(jobId));
const fetcher = useFetcher<{}>();
const unitsOfMeasure = useUnitOfMeasure();
- const locations = useLocations();
+
const [items] = useItems();
+ const [, setSelectedMaterialId] = useBom();
const columns = useMemo<ColumnDef<JobMaterial>[]>(() => {
return [
@@ -61,12 +58,14 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
<VStack spacing={0}>
<Hyperlink
- to={path.to.jobMethodMaterial(
+ to={path.to.jobMakeMethod(
jobId,
- row.original.methodType.toLowerCase(),
row.original.jobMakeMethodId,
row.original.id
)}
+ onClick={() => {
+ setSelectedMaterialId(row.original.id ?? null);
+ }}
className="max-w-[260px] truncate"
>
{row.original.itemReadableId}
@@ -206,7 +205,7 @@ const JobMaterialsTable = memo(({ data, count }: JobMaterialsTableProps) => {
},
},
];
- }, [jobId, locations, items, routeData?.job.locationId, unitsOfMeasure]);
+ }, [items, jobId, setSelectedMaterialId, unitsOfMeasure]);
const permissions = usePermissions();
const { carbon } = useCarbon();
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index db0ac13112..7ae33aeef4 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -803,7 +803,7 @@ export async function getQuoteMakeMethod(
) {
return client
.from("quoteMakeMethod")
- .select("*")
+ .select("*, ...item(itemType:type)")
.eq("id", quoteMakeMethodId)
.single();
}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index 8d2d53873f..0cafa8f110 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -24,7 +24,12 @@ import {
useDebounce,
VStack,
} from "@carbon/react";
-import { useFetcher, useFetchers, useParams } from "@remix-run/react";
+import {
+ useFetcher,
+ useFetchers,
+ useParams,
+ useSearchParams,
+} from "@remix-run/react";
import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
import type { Dispatch, SetStateAction } from "react";
import { useCallback, useEffect, useState } from "react";
@@ -49,6 +54,7 @@ import type {
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
import type { MethodItemType, MethodType } from "~/modules/shared";
+import { useBom } from "~/stores";
import { path } from "~/utils/path";
import type { quoteOperationValidator } from "../../sales.models";
import { quoteMaterialValidator } from "../../sales.models";
@@ -218,6 +224,8 @@ const QuoteBillOfMaterial = ({
const { quoteId, lineId } = useParams();
if (!quoteId) throw new Error("quoteId not found");
if (!lineId) throw new Error("lineId not found");
+ const [searchParams] = useSearchParams();
+ const materialId = searchParams.get("materialId");
const fetcher = useFetcher<{}>();
const permissions = usePermissions();
@@ -388,6 +396,12 @@ const QuoteBillOfMaterial = ({
});
}, [items]);
+ const [selectedMaterialId, setSelectedMaterialId] = useBom();
+ const onSelectItem = (id: string | null) => {
+ setSelectedMaterialId(id);
+ setSelectedItemId(id);
+ };
+
const renderListItem = ({
item,
items,
@@ -404,7 +418,8 @@ const QuoteBillOfMaterial = ({
order={order}
key={item.id}
isExpanded={isOpen}
- onSelectItem={setSelectedItemId}
+ isHighlighted={item.id === selectedMaterialId}
+ onSelectItem={onSelectItem}
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={onCloseOnDrag}
@@ -422,10 +437,10 @@ const QuoteBillOfMaterial = ({
onClick={
isOpen
? () => {
- setSelectedItemId(null);
+ onSelectItem(null);
}
: () => {
- setSelectedItemId(item.id);
+ onSelectItem(item.id);
}
}
key="collapse"
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
index 0d88492573..b538ab2f7d 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
@@ -15,13 +15,14 @@ import {
VStack,
cn,
} from "@carbon/react";
-import { useFetchers, useNavigate } from "@remix-run/react";
-import { useRef, useState } from "react";
+import { useFetchers, useNavigate, useParams } from "@remix-run/react";
+import { useEffect, useRef, useState } from "react";
import { LuChevronDown, LuChevronRight, LuSearch } from "react-icons/lu";
import { MethodIcon, MethodItemTypeIcon } from "~/components";
import type { FlatTree, FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useOptimisticLocation } from "~/hooks";
+import { useBom } from "~/stores";
import { path } from "~/utils/path";
import type { QuoteMethod } from "../../types";
@@ -86,6 +87,23 @@ const QuoteBoMExplorer = ({
isEager: true,
});
+ const params = useParams();
+ const [selectedMaterialId, setSelectedMaterialId] = useBom();
+ useEffect(() => {
+ if (selectedMaterialId) {
+ const node = methods.find(
+ (m) => m.data.methodMaterialId === selectedMaterialId
+ );
+ if (node?.id) selectNode(node?.id);
+ } else if (params.methodId) {
+ const node = methods.find(
+ (m) => m.data.quoteMaterialMakeMethodId === params.methodId
+ );
+ if (node?.id) selectNode(node?.id);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedMaterialId, params.methodId]);
+
return (
<VStack>
{isLoading ? (
@@ -123,12 +141,13 @@ const QuoteBoMExplorer = ({
key={node.id}
className={cn(
"flex h-8 cursor-pointer items-center overflow-hidden rounded-sm pr-2 gap-1",
- getNodePath(node) === location.pathname
+ state.selected
? "bg-muted hover:bg-muted/90"
: "bg-transparent hover:bg-muted/90"
)}
onClick={(e) => {
selectNode(node.id);
+ setSelectedMaterialId(node.data.methodMaterialId);
navigate(getNodePath(node), { replace: true });
}}
>
@@ -212,7 +231,7 @@ function NodeText({ node }: { node: FlatTreeItem<QuoteMethod> }) {
return (
<div className="flex items-center gap-1">
<span className="font-medium text-sm truncate">
- {node.data.description || node.data.itemReadableId}
+ {node.data.itemReadableId || node.data.description}
</span>
</div>
);
@@ -296,17 +315,9 @@ function getNodePath(node: FlatTreeItem<QuoteMethod>) {
node.data.quoteLineId,
node.data.quoteMaterialMakeMethodId
)
- : node.data.methodType === "Make"
- ? path.to.quoteLineMakeMethod(
- node.data.quoteId,
- node.data.quoteLineId,
- node.data.quoteMaterialMakeMethodId,
- node.data.methodMaterialId
- )
- : path.to.quoteLineMethodMaterial(
+ : path.to.quoteLineMakeMethod(
node.data.quoteId,
node.data.quoteLineId,
- node.data.methodType.toLowerCase(),
node.data.quoteMakeMethodId,
node.data.methodMaterialId
);
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
index fe4eaa6935..89b587fa0d 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
@@ -30,6 +30,7 @@ import {
useFetcher,
useLocation,
useParams,
+ useSearchParams,
} from "@remix-run/react";
import { Suspense, useEffect, useState } from "react";
import {
@@ -40,6 +41,7 @@ import {
LuSquareStack,
LuTriangleAlert,
} from "react-icons/lu";
+import { RiProgress4Line } from "react-icons/ri";
import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";
import { Hidden, Item, Submit } from "~/components/Form";
import type { Tree } from "~/components/TreeView";
@@ -53,14 +55,16 @@ import type { MethodItemType } from "~/modules/shared/types";
import { path } from "~/utils/path";
import { getMethodValidator } from "../../sales.models";
import type { Quotation, QuotationLine, QuoteMethod } from "../../types";
-import { RiProgress4Line } from "react-icons/ri";
import { QuoteLineMethodForm } from "./QuoteLineMethodForm";
const QuoteMakeMethodTools = () => {
const permissions = usePermissions();
- const { quoteId, lineId, methodId, materialId } = useParams();
+ const { quoteId, lineId, methodId } = useParams();
if (!quoteId) throw new Error("quoteId not found");
+ const [searchParams] = useSearchParams();
+ const materialId = searchParams.get("materialId");
+
const fetcher = useFetcher<{ error: string | null }>();
const routeData = useRouteData<{
quote: Quotation;
@@ -69,14 +73,21 @@ const QuoteMakeMethodTools = () => {
}>(path.to.quote(quoteId));
const materialRouteData = useRouteData<{
- material: { itemId: string; itemType: MethodItemType | null };
- }>(path.to.quoteLineMakeMethod(quoteId, lineId!, methodId!, materialId!));
+ makeMethod: { itemId: string; itemType: MethodItemType | null };
+ }>(
+ path.to.quoteLineMakeMethod(
+ quoteId,
+ lineId!,
+ methodId!,
+ materialId ?? undefined
+ )
+ );
const itemId =
- materialRouteData?.material?.itemId ??
+ materialRouteData?.makeMethod?.itemId ??
routeData?.lines.find((line) => line.id === lineId)?.itemId;
const itemType =
- materialRouteData?.material?.itemType ??
+ materialRouteData?.makeMethod?.itemType ??
routeData?.lines.find((line) => line.id === lineId)?.itemType;
const itemLink =
@@ -121,9 +132,7 @@ const QuoteMakeMethodTools = () => {
pathname === path.to.quoteLineMethod(quoteId, lineId!, methodId!);
const isQuoteMakeMethod =
methodId &&
- materialId &&
- pathname ===
- path.to.quoteLineMakeMethod(quoteId, lineId!, methodId, materialId);
+ pathname === path.to.quoteLineMakeMethod(quoteId, lineId!, methodId);
const { carbon } = useCarbon();
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index 672a9b0ce4..fb36676f36 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -33,6 +33,7 @@ import {
} from "~/components/Form";
import { usePermissions } from "~/hooks";
import type { MethodItemType, MethodType } from "~/modules/shared";
+import { useBom } from "~/stores";
import { path } from "~/utils/path";
import type { quoteOperationValidator } from "../../sales.models";
import { quoteMaterialValidator } from "../../sales.models";
@@ -122,42 +123,17 @@ const QuoteMaterialForm = ({
}));
};
- useEffect(() => {
- const newPath =
- initialValues.methodType === "Make"
- ? path.to.quoteLineMakeMethod(
- quoteId,
- lineId,
- initialValues.quoteMaterialMakeMethodId!,
- initialValues.id!
- )
- : path.to.quoteLineMethodMaterial(
- quoteId,
- lineId,
- initialValues.methodType.toLowerCase(),
- initialValues.quoteMakeMethodId,
- initialValues.id!
- );
- if (
- fetcher.data?.methodType === "Make" &&
- !location.pathname.includes("make")
- ) {
- navigate(newPath);
- }
-
- if (
- fetcher.data?.methodType === "Buy" &&
- !location.pathname.includes("buy")
- ) {
- navigate(newPath);
- }
+ const [, setSelectedMaterialId] = useBom();
- if (
- fetcher.data?.methodType === "Pick" &&
- !location.pathname.includes("pick")
- ) {
- navigate(newPath);
- }
+ useEffect(() => {
+ const newPath = path.to.quoteLineMakeMethod(
+ quoteId,
+ lineId,
+ initialValues.quoteMaterialMakeMethodId!
+ );
+
+ setSelectedMaterialId(initialValues.id ?? null);
+ navigate(newPath);
}, [
fetcher.data,
initialValues,
@@ -168,6 +144,7 @@ const QuoteMaterialForm = ({
location.pathname,
navigate,
quoteId,
+ setSelectedMaterialId,
]);
return (
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
index 20753542cb..ff674bdd3e 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
@@ -64,7 +64,7 @@ function IntegrationCard({
return (
<Card>
- <div className="pt-6 px-6 h-16 flex items-center justify-between">
+ <div className="pt-6 px-6 h-16 flex items-center justify-between gap-6">
<integration.logo className="h-10 w-auto" />
{integration.active ? (
installed ? (
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts
new file mode 100644
index 0000000000..13645f360d
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts
@@ -0,0 +1,178 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ShouldRevalidateFunction } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { Onshape as OnshapeConfig } from "~/integrations/onshape/config";
+import { OnshapeClient } from "~/integrations/onshape/lib/client";
+import { getIntegration } from "~/modules/settings/settings.service";
+
+export const shouldRevalidate: ShouldRevalidateFunction = () => {
+ return false;
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const { did } = params;
+ if (!did) {
+ return json({
+ data: [],
+ error: "Document ID is required",
+ });
+ }
+
+ const { vid } = params;
+ if (!vid) {
+ return json({
+ data: [],
+ error: "Version ID is required",
+ });
+ }
+
+ const { eid } = params;
+ if (!eid) {
+ return json({
+ data: [],
+ error: "Element ID is required",
+ });
+ }
+
+ const integration = await getIntegration(client, "onshape", companyId);
+
+ if (integration.error || !integration.data) {
+ return json({
+ data: [],
+ error: integration.error,
+ });
+ }
+
+ const integrationMetadata = OnshapeConfig.schema.safeParse(
+ integration?.data?.metadata
+ );
+
+ if (!integrationMetadata.success) {
+ return json({
+ data: [],
+ error: integrationMetadata.error,
+ });
+ }
+
+ const onshapeClient = new OnshapeClient({
+ baseUrl: integrationMetadata.data.baseUrl,
+ accessKey: integrationMetadata.data.accessKey,
+ secretKey: integrationMetadata.data.secretKey,
+ });
+
+ try {
+ const response = await onshapeClient.getBillOfMaterials(did, vid, eid);
+ if (
+ "headers" in response &&
+ Array.isArray(response.headers) &&
+ "rows" in response &&
+ Array.isArray(response.rows)
+ ) {
+ // Transform the BOM data into a structured array of objects
+ const headers = response.headers;
+ const rows = response.rows;
+
+ // Create an array of objects where each object represents a row with properties named after headers
+ const flattenedData = rows.map((row) => {
+ const rowData: Record<string, any> = {};
+
+ // Map each header to its corresponding value in the row
+ headers.forEach((header) => {
+ if (header.name === "Material") {
+ // Handle special case for Material field which might have a displayName
+ rowData[header.name] =
+ row.headerIdToValue[header.id]?.displayName || "";
+ } else {
+ // For other fields, just use the value directly
+ rowData[header.name] = row.headerIdToValue[header.id] || "";
+ }
+ });
+
+ return rowData;
+ });
+
+ const uniquePartNumbers = new Set(
+ flattenedData.map((row) => row["Part number"] || row["Name"])
+ );
+
+ let itemsMap: Map<
+ string,
+ {
+ itemId: string;
+ defaultMethodType: string;
+ replenishmentSystem: string;
+ }
+ > | null = null;
+
+ if (uniquePartNumbers.size) {
+ const items = await client
+ .from("item")
+ .select("id, readableId, defaultMethodType, replenishmentSystem")
+ .in("readableId", Array.from(uniquePartNumbers));
+
+ itemsMap = new Map(
+ items.data?.map((item) => [
+ item.readableId,
+ {
+ itemId: item.id,
+ defaultMethodType: item.defaultMethodType,
+ replenishmentSystem: item.replenishmentSystem,
+ },
+ ])
+ );
+ }
+
+ const flattenedDataWithMetadata = flattenedData.map((row) => {
+ const item = itemsMap?.get(row["Part number"] || row["Name"]);
+ let replenishmentSystem = item?.replenishmentSystem;
+ let defaultMethodType = item?.defaultMethodType;
+
+ if (!replenishmentSystem) {
+ if (row["Purchasing Level"] === "Purchased") {
+ replenishmentSystem = "Buy";
+ } else {
+ replenishmentSystem = "Make";
+ }
+ }
+
+ if (!defaultMethodType) {
+ defaultMethodType =
+ row["Purchasing Level"] === "Purchased" ? "Pick" : "Make";
+ }
+
+ return {
+ mass: row["Mass"],
+ index: row["Item"],
+ readableId: row["Part number"],
+ name: row["Name"],
+ id: item?.itemId ?? undefined,
+ replenishmentSystem,
+ defaultMethodType,
+ quantity: row["Quantity"],
+ level: row["Item"].toString().split(".").length,
+ };
+ });
+
+ // Return the transformed data instead of the raw response
+ return json({
+ data: {
+ rows: flattenedDataWithMetadata,
+ },
+ error: null,
+ });
+ }
+ return json({
+ data: [],
+ error: "No BOM data found",
+ });
+ } catch (error) {
+ console.error(error);
+ return json({
+ data: [],
+ error: error,
+ });
+ }
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts
new file mode 100644
index 0000000000..dce72831ae
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts
@@ -0,0 +1,93 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ShouldRevalidateFunction } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { Onshape as OnshapeConfig } from "~/integrations/onshape/config";
+import { OnshapeClient } from "~/integrations/onshape/lib/client";
+import { getIntegration } from "~/modules/settings/settings.service";
+
+export const shouldRevalidate: ShouldRevalidateFunction = () => {
+ return false;
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const { did } = params;
+ if (!did) {
+ return json({
+ data: [],
+ error: "Document ID is required",
+ });
+ }
+
+ const { vid } = params;
+ if (!vid) {
+ return json({
+ data: [],
+ error: "Version ID is required",
+ });
+ }
+
+ const integration = await getIntegration(client, "onshape", companyId);
+
+ if (integration.error || !integration.data) {
+ return json({
+ data: [],
+ error: integration.error,
+ });
+ }
+
+ const integrationMetadata = OnshapeConfig.schema.safeParse(
+ integration?.data?.metadata
+ );
+
+ if (!integrationMetadata.success) {
+ return json({
+ data: [],
+ error: integrationMetadata.error,
+ });
+ }
+
+ const onshapeClient = new OnshapeClient({
+ baseUrl: integrationMetadata.data.baseUrl,
+ accessKey: integrationMetadata.data.accessKey,
+ secretKey: integrationMetadata.data.secretKey,
+ });
+
+ try {
+ let limit = 20;
+ let offset = 0;
+ let allDocuments: Array<{ id: string; name: string }> = [];
+
+ while (true) {
+ const response = await onshapeClient.getElements(did, vid, limit, offset);
+
+ if (!response || response.length === 0) {
+ break;
+ }
+
+ allDocuments.push(...response);
+
+ if (response.length < limit) {
+ break;
+ }
+
+ offset += limit;
+ }
+
+ return json({
+ data: allDocuments,
+ error: null,
+ });
+ } catch (error) {
+ console.error(error);
+ return json({
+ data: null,
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to get versions from Onshape",
+ });
+ }
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts
new file mode 100644
index 0000000000..10c505f60e
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts
@@ -0,0 +1,85 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ShouldRevalidateFunction } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { Onshape as OnshapeConfig } from "~/integrations/onshape/config";
+import { OnshapeClient } from "~/integrations/onshape/lib/client";
+import { getIntegration } from "~/modules/settings/settings.service";
+
+export const shouldRevalidate: ShouldRevalidateFunction = () => {
+ return false;
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const { did } = params;
+ if (!did) {
+ return json({
+ data: [],
+ error: "Document ID is required",
+ });
+ }
+
+ const integration = await getIntegration(client, "onshape", companyId);
+
+ if (integration.error || !integration.data) {
+ return json({
+ data: [],
+ error: integration.error,
+ });
+ }
+
+ const integrationMetadata = OnshapeConfig.schema.safeParse(
+ integration?.data?.metadata
+ );
+
+ if (!integrationMetadata.success) {
+ return json({
+ data: [],
+ error: integrationMetadata.error,
+ });
+ }
+
+ const onshapeClient = new OnshapeClient({
+ baseUrl: integrationMetadata.data.baseUrl,
+ accessKey: integrationMetadata.data.accessKey,
+ secretKey: integrationMetadata.data.secretKey,
+ });
+
+ try {
+ let limit = 20;
+ let offset = 0;
+ let allDocuments: Array<{ id: string; name: string }> = [];
+
+ while (true) {
+ const response = await onshapeClient.getVersions(did, limit, offset);
+
+ if (!response || response.length === 0) {
+ break;
+ }
+
+ allDocuments.push(...response);
+
+ if (response.length < limit) {
+ break;
+ }
+
+ offset += limit;
+ }
+
+ return json({
+ data: allDocuments,
+ error: null,
+ });
+ } catch (error) {
+ console.error(error);
+ return json({
+ data: null,
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to get versions from Onshape",
+ });
+ }
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.documents.ts b/apps/erp/app/routes/api+/integrations.onshape.documents.ts
new file mode 100644
index 0000000000..69532f84d2
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.documents.ts
@@ -0,0 +1,77 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ShouldRevalidateFunction } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { Onshape as OnshapeConfig } from "~/integrations/onshape/config";
+import { OnshapeClient } from "~/integrations/onshape/lib/client";
+import { getIntegration } from "~/modules/settings/settings.service";
+
+export const shouldRevalidate: ShouldRevalidateFunction = () => {
+ return false;
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const integration = await getIntegration(client, "onshape", companyId);
+
+ if (integration.error || !integration.data) {
+ return json({
+ data: [],
+ error: integration.error,
+ });
+ }
+
+ const integrationMetadata = OnshapeConfig.schema.safeParse(
+ integration?.data?.metadata
+ );
+
+ if (!integrationMetadata.success) {
+ return json({
+ data: [],
+ error: integrationMetadata.error,
+ });
+ }
+
+ const onshapeClient = new OnshapeClient({
+ baseUrl: integrationMetadata.data.baseUrl,
+ accessKey: integrationMetadata.data.accessKey,
+ secretKey: integrationMetadata.data.secretKey,
+ });
+
+ try {
+ let limit = 20;
+ let offset = 0;
+ let allDocuments: Array<{ id: string; name: string }> = [];
+
+ while (true) {
+ const response = await onshapeClient.getDocuments(limit, offset);
+
+ if (!response.items || response.items.length === 0) {
+ break;
+ }
+
+ allDocuments.push(...response.items);
+
+ if (response.items.length < limit) {
+ break;
+ }
+
+ offset += limit;
+ }
+
+ return json({
+ data: { items: allDocuments },
+ error: null,
+ });
+ } catch (error) {
+ console.error(error);
+ return json({
+ data: null,
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to get documents from Onshape",
+ });
+ }
+}
diff --git a/apps/erp/app/routes/api+/integrations.onshape.sync.ts b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
new file mode 100644
index 0000000000..0b5fd9bc6e
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
@@ -0,0 +1,99 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { onShapeDataValidator } from "~/integrations/onshape/lib/data";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "parts",
+ });
+
+ const formData = await request.formData();
+ const documentId = formData.get("documentId");
+ const versionId = formData.get("versionId");
+ const elementId = formData.get("elementId");
+
+ const makeMethodId = formData.get("makeMethodId");
+ const rows = formData.get("rows");
+
+ if (!makeMethodId || !rows) {
+ return json(
+ { success: false, message: "Missing required fields" },
+ { status: 400 }
+ );
+ }
+
+ const record = await client
+ .from("makeMethod")
+ .select("itemId, companyId")
+ .eq("id", makeMethodId as string)
+ .single();
+
+ if (record.data?.companyId !== companyId) {
+ return json(
+ { success: false, message: "Invalid make method id" },
+ { status: 400 }
+ );
+ }
+
+ try {
+ const data = onShapeDataValidator.parse(JSON.parse(rows as string));
+ const serviceRole = await getCarbonServiceRole();
+
+ const [sync, item] = await Promise.all([
+ serviceRole.functions.invoke("sync", {
+ body: {
+ type: "onshape",
+ makeMethodId,
+ data,
+ companyId,
+ userId,
+ },
+ }),
+ serviceRole
+ .from("item")
+ .select("externalId")
+ .eq("id", record.data?.itemId as string)
+ .single(),
+ ]);
+
+ if (sync.error) {
+ return json(
+ { success: false, message: "Failed to sync onshape data" },
+ { status: 400 }
+ );
+ }
+
+ if (item.error) {
+ return json(
+ { success: false, message: "Failed to get item" },
+ { status: 400 }
+ );
+ }
+
+ const currentExternalId =
+ (item.data?.externalId as Record<string, any>) ?? {};
+
+ currentExternalId["onshape"] = {
+ documentId,
+ versionId,
+ elementId,
+ lastSyncedAt: new Date().toISOString(),
+ };
+
+ await client
+ .from("item")
+ .update({
+ externalId: currentExternalId,
+ })
+ .eq("id", record.data?.itemId as string);
+ } catch (error) {
+ console.error("Failed to sync onshape data");
+ return json(
+ { success: false, message: "Invalid rows data" },
+ { status: 400 }
+ );
+ }
+
+ return json({ success: true, message: "Synced successfully" });
+}
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index 81738eb340..23aa4c2e73 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -21,6 +21,37 @@ export async function action({ request }: ActionFunctionArgs) {
case "name":
case "replenishmentSystem":
case "unitOfMeasureCode":
+ // For other fields, just update the specified field
+ if (field === "replenishmentSystem") {
+ return json(
+ await client
+ .from("item")
+ .update({
+ // @ts-expect-error
+ [field]: value,
+ // @ts-expect-error
+ defaultMethodType: value,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", items as string[])
+ );
+ }
+ if (field === "defaultMethodType" && value !== "Pick") {
+ return json(
+ await client
+ .from("item")
+ .update({
+ // @ts-expect-error
+ defaultMethodType: value,
+ // @ts-expect-error
+ replenishmentSystem: value,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .in("id", items as string[])
+ );
+ }
return json(
await client
.from("item")
diff --git a/apps/erp/app/routes/x+/job+/$jobId.buy.$methodId.$materialId.tsx b/apps/erp/app/routes/x+/job+/$jobId.buy.$methodId.$materialId.tsx
deleted file mode 100644
index c046cc0606..0000000000
--- a/apps/erp/app/routes/x+/job+/$jobId.buy.$methodId.$materialId.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useMount, VStack } from "@carbon/react";
-import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
-import type { LoaderFunctionArgs } from "@vercel/remix";
-
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import {
- getJobMaterial,
- getJobOperationsByMethodId,
-} from "~/modules/production";
-import { JobMaterialForm } from "~/modules/production/ui/Jobs";
-import JobMakeMethodTools from "~/modules/production/ui/Jobs/JobMakeMethodTools";
-import { path } from "~/utils/path";
-import { usePanels } from "~/components/Layout";
-
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "production",
- });
-
- const { jobId, methodId, materialId } = params;
- if (!jobId) throw new Error("Could not find jobId");
- if (!methodId) throw new Error("Could not find methodId");
- if (!materialId) throw new Error("Could not find materialId");
-
- const [material, operations] = await Promise.all([
- getJobMaterial(client, materialId),
- getJobOperationsByMethodId(client, methodId),
- ]);
-
- if (material.error) {
- throw redirect(
- path.to.job(jobId),
- await flash(request, error(material.error, "Failed to load job material"))
- );
- }
-
- return json({
- material: {
- ...material.data,
- id: material.data.id ?? "",
- description: material.data.description ?? "",
- itemId: material.data.itemId ?? "",
- itemReadableId: material.data.itemReadableId ?? "",
- itemType: material.data.itemType as "Part",
- methodType: material.data.methodType ?? "Make",
- order: material.data.order ?? 1,
- quantity: material.data.quantity ?? 0,
- jobMakeMethodId: material.data.jobMakeMethodId ?? "",
- jobMaterialMakeMethodId: material.data.jobMaterialMakeMethodId,
- jobOperationId: material.data.jobOperationId ?? undefined,
- unitCost: material.data.unitCost ?? 0,
- unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
- },
- operations:
- operations.data?.map((o) => ({
- ...o,
- description: o.description ?? "",
- laborRate: o.laborRate ?? 0,
- machineRate: o.machineRate ?? 0,
- operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,
- jobMakeMethodId: o.jobMakeMethodId ?? methodId,
- workCenterId: o.workCenterId ?? undefined,
- })) ?? [],
- });
-}
-
-export default function JobMaterialBuyPage() {
- const { material, operations } = useLoaderData<typeof loader>();
-
- const { materialId } = useParams();
- if (!materialId) throw new Error("Could not find materialId");
-
- const { setIsExplorerCollapsed, isExplorerCollapsed } = usePanels();
-
- useMount(() => {
- if (isExplorerCollapsed) {
- setIsExplorerCollapsed(false);
- }
- });
-
- return (
- <VStack spacing={2} className="p-2">
- <JobMakeMethodTools />
- <JobMaterialForm
- key={materialId}
- initialValues={material}
- operations={operations}
- />
- </VStack>
- );
-}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
similarity index 78%
rename from apps/erp/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
rename to apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
index af43b87795..55e6d0452b 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
@@ -14,11 +14,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { Suspense } from "react";
import { CadModel } from "~/components";
+import { usePanels } from "~/components/Layout";
import { usePermissions, useRouteData } from "~/hooks";
import type { Job } from "~/modules/production";
import {
getJobMakeMethodById,
- getJobMaterial,
getJobMaterialsByMethodId,
getJobOperationsByMethodId,
getProductionDataByOperations,
@@ -27,12 +27,10 @@ import {
JobBillOfMaterial,
JobBillOfProcess,
JobEstimatesVsActuals,
- JobMaterialForm,
} from "~/modules/production/ui/Jobs";
import JobMakeMethodTools from "~/modules/production/ui/Jobs/JobMakeMethodTools";
import { getModelByItemId, getTagsList } from "~/modules/shared";
import { path } from "~/utils/path";
-import { usePanels } from "~/components/Layout";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
@@ -40,21 +38,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
bypassRls: true,
});
- const { jobId, methodId, materialId } = params;
+ const { jobId, methodId } = params;
if (!jobId) throw new Error("Could not find jobId");
if (!methodId) throw new Error("Could not find methodId");
- if (!materialId) throw new Error("Could not find materialId");
- const [material, materials, operations, tags] = await Promise.all([
- getJobMaterial(client, materialId),
+ const [makeMethod, materials, operations, tags] = await Promise.all([
+ getJobMakeMethodById(client, methodId),
getJobMaterialsByMethodId(client, methodId),
getJobOperationsByMethodId(client, methodId),
getTagsList(client, companyId, "operation"),
]);
- if (material.error) {
+ if (makeMethod.error) {
throw redirect(
path.to.job(jobId),
- await flash(request, error(material.error, "Failed to load job material"))
+ await flash(
+ request,
+ error(makeMethod.error, "Failed to load job make method")
+ )
);
}
@@ -79,22 +79,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
return defer({
- material: {
- ...material.data,
- id: material.data.id ?? "",
- description: material.data.description ?? "",
- itemId: material.data.itemId ?? "",
- itemReadableId: material.data.itemReadableId ?? "",
- itemType: material.data.itemType as "Part",
- methodType: material.data.methodType ?? "Make",
- order: material.data.order ?? 1,
- quantity: material.data.quantity ?? 0,
- jobMakeMethodId: material.data.jobMakeMethodId ?? "",
- jobMaterialMakeMethodId: material.data.jobMaterialMakeMethodId,
- jobOperationId: material.data.jobOperationId ?? undefined,
- unitCost: material.data.unitCost ?? 0,
- unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
- },
materials:
materials?.data.map((m) => ({
...m,
@@ -113,25 +97,25 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
jobMakeMethodId: o.jobMakeMethodId ?? methodId,
workInstruction: o.workInstruction as JSONContent | null,
})) ?? [],
- makeMethod: getJobMakeMethodById(client, methodId),
+ makeMethod: makeMethod.data,
productionData: getProductionDataByOperations(
client,
operations?.data?.map((o) => o.id)
),
- model: getModelByItemId(client, material.data.itemId!),
+ model: getModelByItemId(client, makeMethod.data.itemId!),
tags: tags.data ?? [],
});
}
export default function JobMakeMethodRoute() {
- const { makeMethod } = useLoaderData<typeof loader>();
const permissions = usePermissions();
const { methodId, jobId } = useParams();
if (!methodId) throw new Error("Could not find methodId");
if (!jobId) throw new Error("Could not find jobId");
const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));
const loaderData = useLoaderData<typeof loader>();
- const { material, materials, operations, productionData, tags } = loaderData;
+ const { makeMethod, materials, operations, productionData, tags } =
+ loaderData;
const { setIsExplorerCollapsed, isExplorerCollapsed } = usePanels();
@@ -144,14 +128,11 @@ export default function JobMakeMethodRoute() {
return (
<VStack spacing={2} className="p-2">
<JobMakeMethodTools makeMethod={makeMethod} />
- <JobMaterialForm
- key={material.id}
- initialValues={material}
- operations={operations}
- />
+
<JobBillOfProcess
key={`bop:${methodId}`}
jobMakeMethodId={methodId}
+ // @ts-expect-error
operations={operations}
locationId={routeData?.job?.locationId ?? ""}
tags={tags}
@@ -160,6 +141,7 @@ export default function JobMakeMethodRoute() {
key={`bom:${methodId}`}
jobMakeMethodId={methodId}
materials={materials}
+ // @ts-expect-error
operations={operations}
/>
<Suspense
@@ -172,7 +154,9 @@ export default function JobMakeMethodRoute() {
<Await resolve={productionData}>
{(resolvedProductionData) => (
<JobEstimatesVsActuals
+ // @ts-expect-error
materials={materials ?? []}
+ // @ts-expect-error
operations={operations}
productionEvents={resolvedProductionData.events}
productionQuantities={resolvedProductionData.quantities}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.pick.$methodId.$materialId.tsx b/apps/erp/app/routes/x+/job+/$jobId.pick.$methodId.$materialId.tsx
deleted file mode 100644
index 14eeab44b9..0000000000
--- a/apps/erp/app/routes/x+/job+/$jobId.pick.$methodId.$materialId.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useMount, VStack } from "@carbon/react";
-import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
-import type { LoaderFunctionArgs } from "@vercel/remix";
-
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import {
- getJobMaterial,
- getJobOperationsByMethodId,
-} from "~/modules/production";
-import { JobMaterialForm } from "~/modules/production/ui/Jobs";
-import JobMakeMethodTools from "~/modules/production/ui/Jobs/JobMakeMethodTools";
-import { path } from "~/utils/path";
-import { usePanels } from "~/components/Layout";
-
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "production",
- });
-
- const { jobId, methodId, materialId } = params;
- if (!jobId) throw new Error("Could not find jobId");
- if (!methodId) throw new Error("Could not find methodId");
- if (!materialId) throw new Error("Could not find materialId");
-
- const [material, operations] = await Promise.all([
- getJobMaterial(client, materialId),
- getJobOperationsByMethodId(client, methodId),
- ]);
-
- if (material.error) {
- throw redirect(
- path.to.job(jobId),
- await flash(request, error(material.error, "Failed to load job material"))
- );
- }
-
- return json({
- material: {
- ...material.data,
- id: material.data.id ?? "",
- description: material.data.description ?? "",
- itemId: material.data.itemId ?? "",
- itemReadableId: material.data.itemReadableId ?? "",
- itemType: material.data.itemType as "Part",
- methodType: material.data.methodType ?? "Make",
- order: material.data.order ?? 1,
- quantity: material.data.quantity ?? 0,
- jobMakeMethodId: material.data.jobMakeMethodId ?? "",
- jobMaterialMakeMethodId: material.data.jobMaterialMakeMethodId,
- jobOperationId: material.data.jobOperationId ?? undefined,
- unitCost: material.data.unitCost ?? 0,
- unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
- },
- operations:
- operations.data?.map((o) => ({
- ...o,
- description: o.description ?? "",
- laborRate: o.laborRate ?? 0,
- machineRate: o.machineRate ?? 0,
- operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,
- jobMakeMethodId: o.jobMakeMethodId ?? methodId,
- workCenterId: o.workCenterId ?? undefined,
- })) ?? [],
- });
-}
-
-export default function JobMaterialPickPage() {
- const { material, operations } = useLoaderData<typeof loader>();
-
- const { setIsExplorerCollapsed, isExplorerCollapsed } = usePanels();
-
- useMount(() => {
- if (isExplorerCollapsed) {
- setIsExplorerCollapsed(false);
- }
- });
-
- const { materialId } = useParams();
- if (!materialId) throw new Error("Could not find materialId");
-
- return (
- <VStack spacing={2} className="p-2">
- <JobMakeMethodTools />
- <JobMaterialForm
- key={materialId}
- initialValues={material}
- operations={operations}
- />
- </VStack>
- );
-}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.tsx
similarity index 79%
rename from apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
rename to apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.tsx
index fd2920b7d2..da3fc0642d 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$makeMethodId.tsx
@@ -24,15 +24,13 @@ import type {
partManufacturingValidator,
} from "~/modules/items";
import {
- getItem,
- getMethodMaterial,
+ getMakeMethodById,
getMethodMaterialsByMakeMethod,
getMethodOperationsByMakeMethodId,
} from "~/modules/items";
import {
BillOfMaterial,
BillOfProcess,
- ItemForm,
MakeMethodTools,
} from "~/modules/items/ui/Item";
import {
@@ -42,29 +40,31 @@ import {
type MethodType,
} from "~/modules/shared";
import { path } from "~/utils/path";
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "parts",
});
- const { itemId, materialId, makeMethodId } = params;
+ const { itemId, makeMethodId } = params;
if (!itemId) throw new Error("Could not find itemId");
- if (!materialId) throw new Error("Could not find materialId");
if (!makeMethodId) throw new Error("Could not find makeMethodId");
- const [material, methodMaterials, methodOperations, tags] = await Promise.all(
- [
- getMethodMaterial(client, materialId),
+ const [makeMethod, methodMaterials, methodOperations, tags] =
+ await Promise.all([
+ getMakeMethodById(client, makeMethodId, companyId),
getMethodMaterialsByMakeMethod(client, makeMethodId),
getMethodOperationsByMakeMethodId(client, makeMethodId),
getTagsList(client, companyId, "operation"),
- ]
- );
+ ]);
- if (material.error) {
+ if (makeMethod.error) {
throw redirect(
path.to.partDetails(itemId),
- await flash(request, error(material.error, "Failed to load material"))
+ await flash(
+ request,
+ error(makeMethod.error, "Failed to load make method")
+ )
);
}
@@ -87,22 +87,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- const item = await getItem(client, material.data.itemId);
- if (item.error) {
- throw redirect(
- path.to.partDetails(itemId),
- await flash(request, error(item.error, "Failed to load item"))
- );
- }
-
return defer({
- item: {
- ...item.data,
- defaultMethodType: item.data.defaultMethodType ?? "Buy",
- unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",
- description: item.data.description ?? "",
- },
- material: material.data,
+ makeMethod: makeMethod.data,
+
methodMaterials:
methodMaterials.data?.map((m) => ({
...m,
@@ -125,7 +112,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
workCenterId: operation.workCenterId ?? undefined,
workInstruction: operation.workInstruction as JSONContent | null,
})) ?? [],
- model: getModelByItemId(client, material.data.itemId),
+ model: getModelByItemId(client, makeMethod.data.itemId),
tags: tags.data ?? [],
});
}
@@ -133,12 +120,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export default function MethodMaterialMakePage() {
const loaderData = useLoaderData<typeof loader>();
const permissions = usePermissions();
- const { item, methodMaterials, methodOperations, tags } = loaderData;
+ const { makeMethod, methodMaterials, methodOperations, tags } = loaderData;
- const { itemId, makeMethodId, materialId } = useParams();
+ const { itemId, makeMethodId } = useParams();
if (!itemId) throw new Error("Could not find itemId");
if (!makeMethodId) throw new Error("Could not find makeMethodId");
- if (!materialId) throw new Error("Could not find materialId");
const routeData = useRouteData<{
partManufacturing: z.infer<typeof partManufacturingValidator> & {
@@ -153,15 +139,12 @@ export default function MethodMaterialMakePage() {
return (
<VStack spacing={2} className="p-2">
- <MakeMethodTools itemId={item.id} type="Part" />
- <ItemForm
- key={`item:${itemId}:${makeMethodId}:${materialId}`}
- type={item.type}
- initialValues={item}
- />
+ <MakeMethodTools itemId={makeMethod.itemId} type="Part" />
+
<BillOfProcess
key={`bop:${itemId}`}
makeMethodId={makeMethodId}
+ // @ts-ignore
operations={methodOperations}
configurable={routeData?.partManufacturing.requiresConfiguration}
configurationRules={routeData?.configurationRules}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.buy.$materialId.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.buy.$materialId.tsx
deleted file mode 100644
index 0368f5bcd9..0000000000
--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.buy.$materialId.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { VStack } from "@carbon/react";
-import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
-import type { LoaderFunctionArgs } from "@vercel/remix";
-
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { getItem, getMethodMaterial } from "~/modules/items";
-import { ItemForm } from "~/modules/items/ui/Item";
-import { path } from "~/utils/path";
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "parts",
- });
-
- const { itemId, materialId } = params;
- if (!itemId) throw new Error("Could not find itemId");
- if (!materialId) throw new Error("Could not find materialId");
-
- const [material] = await Promise.all([getMethodMaterial(client, materialId)]);
-
- if (material.error) {
- throw redirect(
- path.to.partDetails(itemId),
- await flash(request, error(material.error, "Failed to load material"))
- );
- }
-
- const item = await getItem(client, material.data.itemId);
- if (item.error) {
- throw redirect(
- path.to.partDetails(itemId),
- await flash(request, error(item.error, "Failed to load item"))
- );
- }
-
- return json({
- item: {
- ...item.data,
- defaultMethodType: item.data.defaultMethodType ?? "Buy",
- unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",
- description: item.data.description ?? "",
- },
- material: material.data,
- });
-}
-
-export default function MethodMaterialBuyPage() {
- const { item } = useLoaderData<typeof loader>();
- const { itemId, materialId } = useParams();
- if (!itemId) throw new Error("Could not find itemId");
- if (!materialId) throw new Error("Could not find materialId");
-
- return (
- <VStack spacing={2} className="p-2">
- <ItemForm
- key={`item:${itemId}:${materialId}`}
- type={item.type}
- initialValues={item}
- />
- </VStack>
- );
-}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.pick.$materialId.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.pick.$materialId.tsx
deleted file mode 100644
index 0ccd611150..0000000000
--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.pick.$materialId.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { VStack } from "@carbon/react";
-import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
-import type { LoaderFunctionArgs } from "@vercel/remix";
-
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { getItem, getMethodMaterial } from "~/modules/items";
-import { ItemForm } from "~/modules/items/ui/Item";
-import { path } from "~/utils/path";
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "parts",
- });
-
- const { itemId, materialId } = params;
- if (!itemId) throw new Error("Could not find itemId");
- if (!materialId) throw new Error("Could not find materialId");
-
- const [material] = await Promise.all([getMethodMaterial(client, materialId)]);
-
- if (material.error) {
- throw redirect(
- path.to.partDetails(itemId),
- await flash(request, error(material.error, "Failed to load material"))
- );
- }
-
- const item = await getItem(client, material.data.itemId);
- if (item.error) {
- throw redirect(
- path.to.partDetails(itemId),
- await flash(request, error(item.error, "Failed to load item"))
- );
- }
-
- return json({
- item: {
- ...item.data,
- defaultMethodType: item.data.defaultMethodType ?? "Buy",
- unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",
- description: item.data.description ?? "",
- },
- material: material.data,
- });
-}
-
-export default function MethodMaterialPickPage() {
- const { item } = useLoaderData<typeof loader>();
- const { itemId, materialId } = useParams();
- if (!itemId) throw new Error("Could not find itemId");
- if (!materialId) throw new Error("Could not find materialId");
-
- return (
- <VStack spacing={2} className="p-2">
- <ItemForm
- key={`item:${itemId}:${materialId}`}
- type={item.type}
- initialValues={item}
- />
- </VStack>
- );
-}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
index 9bfc65757f..b52c7f5a2f 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
@@ -130,7 +130,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function PartManufacturing() {
- const { methods } = useLoaderData<typeof loader>();
+ const { makeMethod, methods } = useLoaderData<typeof loader>();
const params = useParams();
const { itemId } = params;
@@ -149,6 +149,7 @@ export default function PartManufacturing() {
<div className="grid h-full overflow-hidden p-2">
<BoMExplorer
itemType="Part"
+ makeMethodId={makeMethod.id}
// @ts-ignore
methods={methods}
/>
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.buy.$methodId.$materialId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.buy.$methodId.$materialId.tsx
deleted file mode 100644
index 73cac70ac7..0000000000
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.buy.$methodId.$materialId.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { VStack } from "@carbon/react";
-import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
-import type { LoaderFunctionArgs } from "@vercel/remix";
-
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import {
- getQuoteMaterial,
- getQuoteOperationsByMethodId,
-} from "~/modules/sales";
-import { QuoteMaterialForm } from "~/modules/sales/ui/Quotes";
-import { path } from "~/utils/path";
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "parts",
- });
-
- const { quoteId, lineId, methodId, materialId } = params;
- if (!quoteId) throw new Error("Could not find quoteId");
- if (!lineId) throw new Error("Could not find lineId");
- if (!methodId) throw new Error("Could not find methodId");
- if (!materialId) throw new Error("Could not find materialId");
-
- const [material, operations] = await Promise.all([
- getQuoteMaterial(client, materialId),
- getQuoteOperationsByMethodId(client, methodId),
- ]);
-
- if (material.error) {
- throw redirect(
- path.to.quoteLine(quoteId, lineId),
- await flash(
- request,
- error(material.error, "Failed to load quote material")
- )
- );
- }
-
- return json({
- material: {
- ...material.data,
- id: material.data.id ?? "",
- description: material.data.description ?? "",
- itemId: material.data.itemId ?? "",
- itemReadableId: material.data.itemReadableId ?? "",
- itemType: material.data.itemType as "Part",
- methodType: material.data.methodType ?? "Make",
- order: material.data.order ?? 1,
- quantity: material.data.quantity ?? 0,
- quoteMakeMethodId: material.data.quoteMakeMethodId ?? "",
- quoteMaterialMakeMethodId: material.data.quoteMaterialMakeMethodId,
- quoteOperationId: material.data.quoteOperationId ?? undefined,
- unitCost: material.data.unitCost ?? 0,
- unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
- },
- operations:
- operations.data?.map((o) => ({
- ...o,
- description: o.description ?? "",
- laborRate: o.laborRate ?? 0,
- machineRate: o.machineRate ?? 0,
- operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,
- quoteMakeMethodId: o.quoteMakeMethodId ?? methodId,
- workCenterId: o.workCenterId ?? undefined,
- })) ?? [],
- });
-}
-
-export default function QuoteMaterialBuyPage() {
- const { material, operations } = useLoaderData<typeof loader>();
-
- const { materialId } = useParams();
- if (!materialId) throw new Error("Could not find materialId");
-
- return (
- <VStack spacing={2}>
- <QuoteMaterialForm
- key={materialId}
- initialValues={material}
- operations={operations}
- />
- </VStack>
- );
-}
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx
similarity index 74%
rename from apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx
rename to apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx
index 50017d26ce..13bf35ae87 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.tsx
@@ -16,7 +16,7 @@ import { Suspense } from "react";
import { CadModel } from "~/components";
import { usePermissions } from "~/hooks";
import {
- getQuoteMaterial,
+ getQuoteMakeMethod,
getQuoteMaterialsByMethodId,
getQuoteOperationsByMethodId,
} from "~/modules/sales";
@@ -24,7 +24,6 @@ import {
QuoteBillOfMaterial,
QuoteBillOfProcess,
QuoteMakeMethodTools,
- QuoteMaterialForm,
} from "~/modules/sales/ui/Quotes";
import { getModelByItemId, getTagsList } from "~/modules/shared";
import { path } from "~/utils/path";
@@ -34,29 +33,27 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
view: "sales",
});
- const { quoteId, lineId, methodId, materialId } = params;
+ const { quoteId, lineId, methodId } = params;
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
if (!methodId) throw new Error("Could not find methodId");
- if (!materialId) throw new Error("Could not find materialId");
- const [material, materials, operations, tags] = await Promise.all([
- getQuoteMaterial(client, materialId),
+ const [makeMethod, materials, operations, tags] = await Promise.all([
+ getQuoteMakeMethod(client, methodId),
getQuoteMaterialsByMethodId(client, methodId),
getQuoteOperationsByMethodId(client, methodId),
getTagsList(client, companyId, "operation"),
]);
- if (material.error) {
+ if (makeMethod.error) {
throw redirect(
path.to.quoteLine(quoteId, lineId),
await flash(
request,
- error(material.error, "Failed to load quote material")
+ error(makeMethod.error, "Failed to load quote make method")
)
);
}
-
if (materials.error) {
throw redirect(
path.to.quoteLine(quoteId, lineId),
@@ -78,22 +75,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
return defer({
- material: {
- ...material.data,
- id: material.data.id ?? "",
- description: material.data.description ?? "",
- itemId: material.data.itemId ?? "",
- itemReadableId: material.data.itemReadableId ?? "",
- itemType: material.data.itemType as "Part",
- methodType: material.data.methodType ?? "Make",
- order: material.data.order ?? 1,
- quantity: material.data.quantity ?? 0,
- quoteMakeMethodId: material.data.quoteMakeMethodId ?? "",
- quoteMaterialMakeMethodId: material.data.quoteMaterialMakeMethodId,
- quoteOperationId: material.data.quoteOperationId ?? undefined,
- unitCost: material.data.unitCost ?? 0,
- unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
- },
materials:
materials?.data.map((m) => ({
...m,
@@ -116,7 +97,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
tags: o.tags ?? [],
})) ?? [],
tags: tags.data ?? [],
- model: getModelByItemId(client, material.data.itemId!),
+ model: getModelByItemId(client, makeMethod.data.itemId!),
});
}
@@ -126,19 +107,16 @@ export default function QuoteMakeMethodRoute() {
if (!methodId) throw new Error("Could not find methodId");
const loaderData = useLoaderData<typeof loader>();
- const { material, materials, operations, tags } = loaderData;
+ const { materials, operations, tags } = loaderData;
return (
<VStack spacing={2}>
<QuoteMakeMethodTools />
- <QuoteMaterialForm
- key={material.id}
- initialValues={material}
- operations={operations}
- />
+
<QuoteBillOfProcess
key={`bop:${methodId}`}
quoteMakeMethodId={methodId}
+ // @ts-ignore
operations={operations}
tags={tags}
/>
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.pick.$methodId.$materialId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.pick.$methodId.$materialId.tsx
deleted file mode 100644
index 8fd4dc74c2..0000000000
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.pick.$methodId.$materialId.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { VStack } from "@carbon/react";
-import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
-import type { LoaderFunctionArgs } from "@vercel/remix";
-
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import {
- getQuoteMaterial,
- getQuoteOperationsByMethodId,
-} from "~/modules/sales";
-import { QuoteMaterialForm } from "~/modules/sales/ui/Quotes";
-import { path } from "~/utils/path";
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "parts",
- });
-
- const { quoteId, lineId, methodId, materialId } = params;
- if (!quoteId) throw new Error("Could not find quoteId");
- if (!lineId) throw new Error("Could not find lineId");
- if (!methodId) throw new Error("Could not find methodId");
- if (!materialId) throw new Error("Could not find materialId");
-
- const [material, operations] = await Promise.all([
- getQuoteMaterial(client, materialId),
- getQuoteOperationsByMethodId(client, methodId),
- ]);
-
- if (material.error) {
- throw redirect(
- path.to.quoteLine(quoteId, lineId),
- await flash(
- request,
- error(material.error, "Failed to load quote material")
- )
- );
- }
-
- return json({
- material: {
- ...material.data,
- id: material.data.id ?? "",
- description: material.data.description ?? "",
- itemId: material.data.itemId ?? "",
- itemReadableId: material.data.itemReadableId ?? "",
- itemType: material.data.itemType as "Part",
- methodType: material.data.methodType ?? "Make",
- order: material.data.order ?? 1,
- quantity: material.data.quantity ?? 0,
- quoteMakeMethodId: material.data.quoteMakeMethodId ?? "",
- quoteMaterialMakeMethodId: material.data.quoteMaterialMakeMethodId,
- quoteOperationId: material.data.quoteOperationId ?? undefined,
- unitCost: material.data.unitCost ?? 0,
- unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
- },
- operations:
- operations.data?.map((o) => ({
- ...o,
- description: o.description ?? "",
- laborRate: o.laborRate ?? 0,
- machineRate: o.machineRate ?? 0,
- operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,
- quoteMakeMethodId: o.quoteMakeMethodId ?? methodId,
- workCenterId: o.workCenterId ?? undefined,
- })) ?? [],
- });
-}
-
-export default function QuoteMaterialPickPage() {
- const { material, operations } = useLoaderData<typeof loader>();
-
- const { materialId } = useParams();
- if (!materialId) throw new Error("Could not find materialId");
-
- return (
- <VStack spacing={2}>
- <QuoteMaterialForm
- key={materialId}
- initialValues={material}
- operations={operations}
- />
- </VStack>
- );
-}
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.tsx b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.tsx
index 2f4fad8bb6..75752bb0dc 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.tsx
@@ -106,7 +106,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function ToolManufacturing() {
- const { methods } = useLoaderData<typeof loader>();
+ const { makeMethod, methods } = useLoaderData<typeof loader>();
const params = useParams();
const { itemId } = params;
@@ -125,6 +125,7 @@ export default function ToolManufacturing() {
<div className="grid h-full overflow-hidden p-2">
<BoMExplorer
itemType="Tool"
+ makeMethodId={makeMethod.id}
// @ts-ignore
methods={methods}
/>
diff --git a/apps/erp/app/stores/bom.ts b/apps/erp/app/stores/bom.ts
new file mode 100644
index 0000000000..e2453f722f
--- /dev/null
+++ b/apps/erp/app/stores/bom.ts
@@ -0,0 +1,5 @@
+import { atom } from "nanostores";
+import { useNanoStore } from "~/hooks";
+
+const $bomStore = atom<string | null>(null);
+export const useBom = () => useNanoStore($bomStore, "bom");
diff --git a/apps/erp/app/stores/index.ts b/apps/erp/app/stores/index.ts
index 99aeb06bee..632604e84e 100644
--- a/apps/erp/app/stores/index.ts
+++ b/apps/erp/app/stores/index.ts
@@ -1,3 +1,4 @@
+export * from "./bom";
export * from "./customers";
export * from "./items";
export * from "./people";
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index d2cc817010..0c358a7d83 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -47,6 +47,18 @@ export const path = {
materialSubstances: `${api}/items/substances`,
messagingNotify: `${api}/messaging/notify`,
modelUpload: `${api}/model/upload`,
+ onShapeBom: (documentId: string, versionId: string, elementId: string) =>
+ generatePath(
+ `${api}/integrations/onshape/d/${documentId}/v/${versionId}/e/${elementId}/bom`
+ ),
+ onShapeDocuments: `${api}/integrations/onshape/documents`,
+ onShapeVersions: (documentId: string) =>
+ generatePath(`${api}/integrations/onshape/d/${documentId}/versions`),
+ onShapeElements: (documentId: string, versionId: string) =>
+ generatePath(
+ `${api}/integrations/onshape/d/${documentId}/v/${versionId}/elements`
+ ),
+ onShapeSync: `${api}/integrations/onshape/sync`,
outsideOperations: (jobId: string) =>
generatePath(`${api}/production/outside-operations/${jobId}`),
purchasingKpi: (key: string) =>
@@ -565,17 +577,13 @@ export const path = {
jobMaterials: (id: string) => generatePath(`${x}/job/${id}/materials`),
jobMethod: (jobId: string, methodId: string) =>
generatePath(`${x}/job/${jobId}/method/${methodId}`),
- jobMakeMethod: (jobId: string, makeMethodId: string, materialId: string) =>
- generatePath(`${x}/job/${jobId}/make/${makeMethodId}/${materialId}`),
- jobMethodMaterial: (
- jobId: string,
- methodType: string,
- makeMethodId: string,
- materialId: string
- ) =>
+ jobMakeMethod: (jobId: string, makeMethodId: string, materialId?: string) =>
generatePath(
- `${x}/job/${jobId}/${methodType}/${makeMethodId}/${materialId}`
+ `${x}/job/${jobId}/make/${makeMethodId}${
+ materialId ? `?materialId=${materialId}` : ""
+ }`
),
+
jobMaterialsOrder: `${x}/job/methods/material/order`,
jobMethodGet: `${x}/job/methods/get`,
jobMethodSave: `${x}/job/methods/save`,
@@ -793,14 +801,8 @@ export const path = {
generatePath(`${x}/part/${id}/manufacturing/method`),
partManufacturing: (id: string) =>
generatePath(`${x}/part/${id}/manufacturing`),
- partManufacturingMaterial: (
- itemId: string,
- makeMethodId: string,
- methodMaterialId: string
- ) =>
- generatePath(
- `${x}/part/${itemId}/manufacturing/${makeMethodId}/${methodMaterialId}`
- ),
+ partManufacturingMaterial: (itemId: string, makeMethodId: string) =>
+ generatePath(`${x}/part/${itemId}/manufacturing/${makeMethodId}`),
partPlanning: (id: string) => generatePath(`${x}/part/${id}/planning`),
partPlanningLocation: (id: string, locationId: string) =>
generatePath(`${x}/part/${id}/planning?location=${locationId}`),
@@ -890,24 +892,17 @@ export const path = {
generatePath(`${x}/quote/${quoteId}/${lineId}/configure`),
quoteLineCost: (quoteId: string, lineId: string) =>
generatePath(`${x}/quote/${quoteId}/${lineId}/cost/update`),
- quoteLineMethodMaterial: (
- quoteId: string,
- lineId: string,
- methodType: string,
- methodId: string,
- id: string
- ) =>
- generatePath(
- `${x}/quote/${quoteId}/${lineId}/${methodType}/${methodId}/${id}`
- ),
+
quoteLineMakeMethod: (
quoteId: string,
lineId: string,
makeMethodId: string,
- materialId: string
+ materialId?: string
) =>
generatePath(
- `${x}/quote/${quoteId}/${lineId}/make/${makeMethodId}/${materialId}`
+ `${x}/quote/${quoteId}/${lineId}/make/${makeMethodId}${
+ materialId ? `?materialId=${materialId}` : ""
+ }`
),
quoteLineMethod: (quoteId: string, quoteLineId: string, methodId: string) =>
generatePath(`${x}/quote/${quoteId}/${quoteLineId}/method/${methodId}`),
@@ -1088,15 +1083,8 @@ export const path = {
generatePath(`${x}/tool/${id}/manufacturing/method`),
toolManufacturing: (id: string) =>
generatePath(`${x}/tool/${id}/manufacturing`),
- toolManufacturingMaterial: (
- itemId: string,
- makeMethodId: string,
- methodMaterialId: string
- ) =>
- generatePath(
- `${x}/tool/${itemId}/manufacturing/${makeMethodId}/${methodMaterialId}`
- ),
-
+ toolManufacturingMaterial: (itemId: string, makeMethodId: string) =>
+ generatePath(`${x}/tool/${itemId}/manufacturing/${makeMethodId}`),
toolPlanning: (id: string) => generatePath(`${x}/tool/${id}/planning`),
toolPlanningLocation: (id: string, locationId: string) =>
generatePath(`${x}/tool/${id}/planning?location=${locationId}`),
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index 8e204cd265..3ff9986165 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -126,3 +126,14 @@ backend = "postgres"
[functions.image-resizer]
enabled = true
verify_jwt = false
+
+[functions.sync]
+enabled = true
+verify_jwt = true
+import_map = "./functions/sync/deno.json"
+# Uncomment to specify a custom file path to the entrypoint.
+# Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx
+entrypoint = "./functions/sync/index.ts"
+# Specifies static files to be bundled with the function. Supports glob patterns.
+# For example, if you want to serve static HTML pages in your function:
+# static_files = [ "./functions/sync/*.html" ]
diff --git a/packages/database/supabase/functions/create-inventory-document/index.ts b/packages/database/supabase/functions/create-inventory-document/index.ts
index a5e39810e2..d58f31c18e 100644
--- a/packages/database/supabase/functions/create-inventory-document/index.ts
+++ b/packages/database/supabase/functions/create-inventory-document/index.ts
@@ -85,7 +85,7 @@ serve(async (req: Request) => {
return new Response("ok", { headers: corsHeaders });
}
const payload = await req.json();
- console.log(payloadValidator.safeParse(payload));
+
const { type, companyId, userId } = payloadValidator.parse(payload);
switch (type) {
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 0be6e2407e..b5ebc4d12b 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -35,9 +35,6 @@ serve(async (req: Request) => {
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
- console.log(payload);
- console.log(payloadValidator.safeParse(payload));
-
try {
const { receiptId, userId, companyId } = payloadValidator.parse(payload);
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index 20867dc7f4..14ed95f3d6 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -24,9 +24,6 @@ serve(async (req: Request) => {
const payload = await req.json();
const today = format(new Date(), "yyyy-MM-dd");
- console.log(payload);
- console.log(payloadValidator.safeParse(payload));
-
try {
const { shipmentId, userId, companyId } = payloadValidator.parse(payload);
diff --git a/packages/database/supabase/functions/sync/.npmrc b/packages/database/supabase/functions/sync/.npmrc
new file mode 100644
index 0000000000..48c6388638
--- /dev/null
+++ b/packages/database/supabase/functions/sync/.npmrc
@@ -0,0 +1,3 @@
+# Configuration for private npm package dependencies
+# For more information on using private registries with Edge Functions, see:
+# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
diff --git a/packages/database/supabase/functions/sync/deno.json b/packages/database/supabase/functions/sync/deno.json
new file mode 100644
index 0000000000..f6ca8454c5
--- /dev/null
+++ b/packages/database/supabase/functions/sync/deno.json
@@ -0,0 +1,3 @@
+{
+ "imports": {}
+}
diff --git a/packages/database/supabase/functions/sync/index.ts b/packages/database/supabase/functions/sync/index.ts
new file mode 100644
index 0000000000..e9d7926761
--- /dev/null
+++ b/packages/database/supabase/functions/sync/index.ts
@@ -0,0 +1,277 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+
+import z from "npm:zod@^3.24.1";
+import { corsHeaders } from "../lib/headers.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+const onShapeDataValidator = z.object({
+ index: z.string(),
+ id: z.string().optional(),
+ readableId: z.string().optional(),
+ name: z.string(),
+ quantity: z.number(),
+ replenishmentSystem: z.enum(["Make", "Buy", "Buy and Make"]),
+ defaultMethodType: z.enum(["Make", "Buy", "Pick"]),
+});
+
+const payloadValidator = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("onshape"),
+ makeMethodId: z.string(),
+ data: onShapeDataValidator.array(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
+]);
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+ const payload = await req.json();
+
+ const { type, companyId, userId } = payloadValidator.parse(payload);
+
+ switch (type) {
+ case "onshape": {
+ const { makeMethodId, data } = payload;
+
+ console.log({
+ function: "sync",
+ type,
+ makeMethodId,
+ data,
+ companyId,
+ userId,
+ });
+
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key") ?? ""
+ );
+
+ const existingItemIds = new Set(
+ data.map((item: { id?: string }) => item.id).filter(Boolean)
+ );
+
+ const [existingMakeMethods, existingItems] = await Promise.all([
+ client
+ .from("makeMethod")
+ .select("id, itemId")
+ .eq("companyId", companyId)
+ .in("itemId", Array.from(existingItemIds)),
+ client
+ .from("item")
+ .select("id, readableId, unitOfMeasureCode, type")
+ .eq("companyId", companyId)
+ .in("id", Array.from(existingItemIds)),
+ ]);
+
+ const existingMakeMethodIdsByItemId = new Map(
+ existingMakeMethods.data?.map((makeMethod) => [
+ makeMethod.itemId,
+ makeMethod.id,
+ ]) ?? []
+ );
+
+ const existingItemsByItemId = new Map(
+ existingItems.data?.map((item) => [item.id, item]) ?? []
+ );
+
+ try {
+ interface TreeNode {
+ data: z.infer<typeof onShapeDataValidator>;
+ children: TreeNode[];
+ level: number;
+ }
+
+ // Sort the data by index to ensure parent nodes come before children
+ const sortedData = [...data].sort((a, b) => {
+ const aIndices = a.index.toString().split(".");
+ const bIndices = b.index.toString().split(".");
+
+ // Compare each level of the index
+ for (let i = 0; i < Math.min(aIndices.length, bIndices.length); i++) {
+ const aVal = parseInt(aIndices[i]);
+ const bVal = parseInt(bIndices[i]);
+ if (aVal !== bVal) {
+ return aVal - bVal;
+ }
+ }
+
+ // If one index is a prefix of the other, the shorter one comes first
+ return aIndices.length - bIndices.length;
+ });
+
+ // Build the tree
+ const buildTree = (
+ d: z.infer<typeof onShapeDataValidator>[]
+ ): TreeNode[] => {
+ const result: TreeNode[] = [];
+ const nodeMap = new Map<string, TreeNode>();
+
+ d.forEach((item) => {
+ const indexStr = item.index.toString();
+ const node: TreeNode = {
+ data: item,
+ children: [],
+ level: indexStr.split(".").length,
+ };
+
+ nodeMap.set(indexStr, node);
+
+ // Find parent node
+ const lastDotIndex = indexStr.lastIndexOf(".");
+ if (lastDotIndex === -1) {
+ // This is a root node
+ result.push(node);
+ } else {
+ // This is a child node
+ const parentIndex = indexStr.substring(0, lastDotIndex);
+ const parentNode = nodeMap.get(parentIndex);
+ if (parentNode) {
+ parentNode.children.push(node);
+ }
+ }
+ });
+
+ return result;
+ };
+
+ const tree = buildTree(sortedData);
+
+ await db.transaction().execute(async (trx) => {
+ await trx
+ .deleteFrom("methodMaterial")
+ .where("makeMethodId", "=", makeMethodId)
+ .execute();
+
+ async function traverseTree(
+ node: TreeNode,
+ parentMakeMethodId: string,
+ index: number
+ ) {
+ const { data, children } = node;
+ const {
+ id,
+ readableId,
+ name,
+ quantity,
+ replenishmentSystem,
+ defaultMethodType,
+ } = data;
+
+ const partId = readableId || name;
+ if (!partId) return;
+
+ const isMade = children.length > 0;
+ let itemId = id;
+
+ if (!itemId) {
+ const item = await trx
+ .insertInto("item")
+ .values({
+ readableId: partId,
+ name,
+ type: "Part",
+ unitOfMeasureCode: "EA",
+ itemTrackingType: "Inventory",
+ replenishmentSystem,
+ defaultMethodType,
+ companyId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .executeTakeFirst();
+
+ itemId = item?.id;
+
+ await trx
+ .insertInto("part")
+ .values({
+ id: partId,
+ itemId: itemId!,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+ }
+
+ if (!itemId) throw new Error("Failed to create item");
+
+ let materialMakeMethodId =
+ existingMakeMethodIdsByItemId.get(itemId);
+ if (defaultMethodType === "Make" || isMade) {
+ if (!materialMakeMethodId) {
+ const makeMethod = await trx
+ .selectFrom("makeMethod")
+ .select(["id"])
+ .where("itemId", "=", itemId)
+ .executeTakeFirst();
+
+ materialMakeMethodId = makeMethod?.id;
+ }
+ }
+
+ await trx
+ .insertInto("methodMaterial")
+ .values({
+ itemId,
+ quantity: quantity ?? 1,
+ makeMethodId: parentMakeMethodId,
+ materialMakeMethodId,
+ methodType: defaultMethodType,
+ order: index,
+ itemReadableId:
+ existingItemsByItemId.get(itemId)?.readableId ?? partId,
+ itemType: existingItemsByItemId.get(itemId)?.type ?? "Part",
+ unitOfMeasureCode:
+ existingItemsByItemId.get(itemId)?.unitOfMeasureCode ?? "EA",
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ if (materialMakeMethodId) {
+ await trx
+ .deleteFrom("methodMaterial")
+ .where("makeMethodId", "=", materialMakeMethodId)
+ .execute();
+
+ for await (const child of children) {
+ const childIndex = children.indexOf(child);
+ await traverseTree(child, materialMakeMethodId, childIndex);
+ }
+ }
+ }
+
+ let index = 0;
+ for await (const node of tree) {
+ await traverseTree(node, makeMethodId, index);
+ index++;
+ }
+ });
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ }
+ );
+ }
+ }
+});
diff --git a/packages/database/supabase/migrations/20250410120243_onshape-integration.sql b/packages/database/supabase/migrations/20250410120243_onshape-integration.sql
new file mode 100644
index 0000000000..a52bb24db5
--- /dev/null
+++ b/packages/database/supabase/migrations/20250410120243_onshape-integration.sql
@@ -0,0 +1,3 @@
+INSERT INTO "integration" ("id", "jsonschema")
+VALUES
+ ('onshape', '{"type": "object", "properties": {"baseUrl": {"type": "string"}, "accessKey": {"type": "string"}, "secretKey": {"type": "string"}, "companyId": {"type": "string"}}, "required": ["baseUrl", "accessKey", "secretKey", "companyId"]}'::json);
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20250415163128_kit-part-fix.sql b/packages/database/supabase/migrations/20250415163128_kit-part-fix.sql
new file mode 100644
index 0000000000..b26ddaa3ac
--- /dev/null
+++ b/packages/database/supabase/migrations/20250415163128_kit-part-fix.sql
@@ -0,0 +1,164 @@
+DROP FUNCTION IF EXISTS get_quote_methods;
+CREATE OR REPLACE FUNCTION get_quote_methods(qid TEXT)
+RETURNS TABLE (
+ "quoteId" TEXT,
+ "quoteLineId" TEXT,
+ "methodMaterialId" TEXT,
+ "quoteMakeMethodId" TEXT,
+ "quoteMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "quoteId",
+ "quoteLineId",
+ "id",
+ "id" AS "quoteMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "quoteMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit"
+ FROM
+ "quoteMakeMethod"
+ WHERE
+ "quoteId" = qid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."quoteId",
+ child."quoteLineId",
+ child."id",
+ child."quoteMakeMethodId",
+ child."methodType",
+ child."quoteMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit"
+ FROM
+ "quoteMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."quoteMaterialMakeMethodId" = child."quoteMakeMethodId"
+)
+SELECT
+ material."quoteId",
+ material."quoteLineId",
+ material.id as "methodMaterialId",
+ material."quoteMakeMethodId",
+ material."quoteMaterialMakeMethodId",
+ material."itemId",
+ item."readableId" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."quoteId" = qid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+DROP FUNCTION IF EXISTS get_job_method;
+CREATE OR REPLACE FUNCTION get_job_method(jid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit"
+ FROM
+ "jobMakeMethod"
+ WHERE
+ "jobId" = jid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."jobId",
+ child."id",
+ child."jobMakeMethodId",
+ child."methodType",
+ child."jobMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit"
+ FROM
+ "jobMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."jobMaterialMakeMethodId" = child."jobMakeMethodId"
+ WHERE parent."methodType" = 'Make'
+)
+SELECT
+ material."jobId",
+ material.id as "methodMaterialId",
+ material."jobMakeMethodId",
+ material."jobMaterialMakeMethodId",
+ material."itemId",
+ item."readableId" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."jobId" = jid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
\ No newline at end of file
diff --git a/packages/react/src/Loading.tsx b/packages/react/src/Loading.tsx
index 68e7d14f81..feecbc05b3 100644
--- a/packages/react/src/Loading.tsx
+++ b/packages/react/src/Loading.tsx
@@ -6,8 +6,11 @@ export function Loading({
children,
isLoading,
className,
+ spinnerClassName,
...props
-}: PropsWithChildren<ComponentProps<"div"> & { isLoading: boolean }>) {
+}: PropsWithChildren<
+ ComponentProps<"div"> & { isLoading: boolean; spinnerClassName?: string }
+>) {
return isLoading ? (
<div
className={cn(
@@ -16,7 +19,7 @@ export function Loading({
)}
{...props}
>
- <Spinner className="size-8" />
+ <Spinner className={spinnerClassName ?? "size-8"} />
</div>
) : (
<>{children}</>
diff --git a/packages/utils/src/const.ts b/packages/utils/src/const.ts
index 56f06c7d54..7124aeea13 100644
--- a/packages/utils/src/const.ts
+++ b/packages/utils/src/const.ts
@@ -1 +1 @@
-export const SUPPORT_EMAIL = "[email protected]";
+export const SUPPORT_EMAIL = "[email protected]";