Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add attributes to job bop and get-method
Brad Barbin65e484662252
diff --git a/apps/erp/app/components/Icons.tsx b/apps/erp/app/components/Icons.tsxindex b38f5f2ab4..f89510bc32 100644--- a/apps/erp/app/components/Icons.tsx+++ b/apps/erp/app/components/Icons.tsx@@ -12,11 +12,11 @@ import {LuClock,LuClock3,LuExternalLink,- LuFile,LuGroup,LuHammer,LuHardHat,LuHeadphones,+ LuImage,LuList,LuPizza,LuQrCode,@@ -186,7 +186,7 @@ export const ProcedureAttributeTypeIcon = ({}) => {switch (type) {case "Value":- return <LuQrCode className={cn("text-emerald-600", className)} />;+ return <LuQrCode className={cn("text-foreground", className)} />;case "Measurement":return <LuRuler className={cn("text-blue-600", className)} />;case "Checkbox":@@ -198,7 +198,7 @@ export const ProcedureAttributeTypeIcon = ({case "List":return <LuList className={cn("text-orange-600", className)} />;case "File":- return <LuFile className={cn("text-foreground", className)} />;+ return <LuImage className={cn("text-emerald-600", className)} />;}};diff --git a/apps/erp/app/components/SortableList.tsx b/apps/erp/app/components/SortableList.tsxindex 7c0e71a6f1..f23bc2d097 100644--- a/apps/erp/app/components/SortableList.tsx+++ b/apps/erp/app/components/SortableList.tsx@@ -7,6 +7,7 @@ import { useState } from "react";import { Checkbox, HStack, cn } from "@carbon/react";import { flushSync } from "react-dom";import { LuTrash } from "react-icons/lu";+import Empty from "./Empty";export interface Item {checked: boolean;@@ -48,10 +49,11 @@ function SortableListItem<T>({className,}: SortableListItemProps<T>) {const [isDragging, setIsDragging] = useState(false);- const [isDraggable] = useState(true);+ const [isDraggable] = useState(!isExpanded);const dragControls = useDragControls();const handleDragStart = (event: any) => {+ if (isExpanded) return;flushSync(() => setIsDragging(true));dragControls.start(event, { snapToCursor: true });handleDrag();@@ -69,12 +71,12 @@ function SortableListItem<T>({className={cn("relative z-auto grow","h-full rounded-md bg-muted/30",- "border border-border rounded-lg",- item.checked ? "cursor-not-allowed" : "cursor-grab",+ "border border-border rounded-lg ",+ !isExpanded && "cursor-grab",item.checked && !isDragging ? "w-7/10" : "w-full")}key={item.id}- dragListener={!item.checked}+ dragListener={!item.checked && !isExpanded}dragControls={dragControls}onDragEnd={handleDragEnd}style={@@ -215,7 +217,7 @@ function SortableList<T extends Item>({onReorder,renderItem,}: SortableListProps<T>) {- if (items) {+ if (items && Array.isArray(items) && items.length > 0) {return (<LayoutGroup><Reorder.Group@@ -236,8 +238,9 @@ function SortableList<T extends Item>({</Reorder.Group></LayoutGroup>);+ } else {+ return <Empty />;}- return null;}SortableList.displayName = "SortableList";diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 7d09a0cfd1..8877ce05eb 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -1911,8 +1911,13 @@ export async function upsertMethodOperationAttribute(companyId: string;createdBy: string;})- | (Omit<z.infer<typeof operationAttributeValidator>, "id"> & {+ | (Omit<+ z.infer<typeof operationAttributeValidator>,+ "id" | "minValue" | "maxValue"+ > & {id: string;+ minValue: number | null;+ maxValue: number | null;updatedBy: string;updatedAt: string;})diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsxindex 72b281cbe9..bd9669d37a 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -492,8 +492,6 @@ function MaterialForm({configurable,item,methodOperations,- orderState,- temporaryItems,rulesByField,onConfigure,setOrderState,diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsxindex f37b657705..12a9bcbaab 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx@@ -48,6 +48,8 @@ import {LuHammer,LuInfo,LuList,+ LuMinimize2,+ LuMaximize2,LuSettings2,LuSquareFunction,LuTriangleAlert,@@ -110,7 +112,6 @@ import { getPrivateUrl, path } from "~/utils/path";import { methodOperationValidator } from "../../items.models";import type { ConfigurationParameter, ConfigurationRule } from "../../types";import { ProcedureAttributeTypeIcon } from "~/components/Icons";-import type { ProcedureAttribute } from "~/modules/production";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";type Operation = z.infer<typeof methodOperationValidator> & {@@ -1512,9 +1513,10 @@ function AttributesForm({name="type"label="Type"options={typeOptions}+ value={type}onChange={(option) => {if (option) {- setType(option.value as ProcedureAttribute["type"]);+ setType(option.value as OperationAttribute["type"]);}}}/>@@ -1534,8 +1536,14 @@ function AttributesForm({onValueChange={setNumericControls}className="justify-start items-start mt-6">- <ToggleGroupItem value="min">Minimum</ToggleGroupItem>- <ToggleGroupItem value="max">Maximum</ToggleGroupItem>+ <ToggleGroupItem size="sm" value="min">+ <LuMinimize2 className="mr-2" />+ Minimum+ </ToggleGroupItem>+ <ToggleGroupItem size="sm" value="max">+ <LuMaximize2 className="mr-2" />+ Maximum+ </ToggleGroupItem></ToggleGroup>{numericControls.includes("min") && (@@ -1694,7 +1702,7 @@ function AttributesListItem({options={typeOptions}onChange={(option) => {if (option) {- setType(option.value as ProcedureAttribute["type"]);+ setType(option.value as OperationAttribute["type"]);}}}/>@@ -1714,8 +1722,14 @@ function AttributesListItem({onValueChange={setNumericControls}className="justify-start items-start mt-6">- <ToggleGroupItem value="min">Minimum</ToggleGroupItem>- <ToggleGroupItem value="max">Maximum</ToggleGroupItem>+ <ToggleGroupItem size="sm" value="min">+ <LuMinimize2 className="mr-2" />+ Minimum+ </ToggleGroupItem>+ <ToggleGroupItem size="sm" value="max">+ <LuMaximize2 className="mr-2" />+ Maximum+ </ToggleGroupItem></ToggleGroup>{numericControls.includes("min") && (@@ -1726,6 +1740,32 @@ function AttributesListItem({minimumFractionDigits: 0,maximumFractionDigits: 10,}}+ isConfigured={rulesByField.has(+ getFieldKey(`attribute:${id}:minValue`, operationId)+ )}+ onConfigure={+ configurable && typeof onConfigure === "function"+ ? () => {+ onConfigure({+ label: "Minimum",+ field: getFieldKey(+ `attribute:${id}:minValue`,+ operationId+ ),+ code: rulesByField.get(+ getFieldKey(+ `attribute:${id}:minValue`,+ operationId+ )+ )?.code,+ defaultValue: minValue ?? 0,+ returnType: {+ type: "numeric",+ },+ });+ }+ : undefined+ }/>)}{numericControls.includes("max") && (@@ -1736,6 +1776,32 @@ function AttributesListItem({minimumFractionDigits: 0,maximumFractionDigits: 10,}}+ isConfigured={rulesByField.has(+ getFieldKey(`attribute:${id}:maxValue`, operationId)+ )}+ onConfigure={+ configurable && typeof onConfigure === "function"+ ? () => {+ onConfigure({+ label: "Maximum",+ field: getFieldKey(+ `attribute:${id}:maxValue`,+ operationId+ ),+ code: rulesByField.get(+ getFieldKey(+ `attribute:${id}:maxValue`,+ operationId+ )+ )?.code,+ defaultValue: maxValue ?? 0,+ returnType: {+ type: "numeric",+ },+ });+ }+ : undefined+ }/>)}</div>@@ -1808,14 +1874,19 @@ function AttributesListItem({{isConfigured && (<Tooltip><TooltipTrigger>- <LuSquareFunction- aria-label="Configured"- className="size-4 text-emerald-500"- />+ <div className="flex flex-col items-center justify-center gap-1 text-emerald-500">+ <LuSquareFunction+ aria-label="Configured"+ className="size-4 "+ />+ <span className="text-xxs font-mono uppercase">+ Configured+ </span>+ </div></TooltipTrigger><TooltipContent><p className="text-foreground text-sm">- This attribute is configured for this operation.+ This attribute is configured</p></TooltipContent></Tooltip>@@ -2091,14 +2162,19 @@ function ParametersListItem({{isConfigured ? (<Tooltip><TooltipTrigger>- <LuSquareFunction- aria-label="Configured"- className="size-4 text-emerald-500"- />+ <div className="flex flex-col items-center justify-center gap-1 text-emerald-500">+ <LuSquareFunction+ aria-label="Configured"+ className="size-4 "+ />+ <span className="text-xxs font-mono uppercase">+ Configured+ </span>+ </div></TooltipTrigger><TooltipContent><p className="text-foreground text-sm">- This value is configured for this operation.+ This value is configured</p></TooltipContent></Tooltip>diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 5a22a385fb..eda1f2f3da 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -426,7 +426,9 @@ export async function getJobOperationsByMethodId() {return client.from("jobOperation")- .select("*, jobOperationTool(*), jobOperationParameter(*)")+ .select(+ "*, jobOperationTool(*), jobOperationParameter(*), jobOperationAttribute(*)"+ ).eq("jobMakeMethodId", jobMakeMethodId).order("order", { ascending: true });}@@ -962,8 +964,13 @@ export async function upsertJobOperationAttribute(companyId: string;createdBy: string;})- | (Omit<z.infer<typeof operationAttributeValidator>, "id"> & {+ | (Omit<+ z.infer<typeof operationAttributeValidator>,+ "id" | "minValue" | "maxValue"+ > & {id: string;+ minValue: number | null;+ maxValue: number | null;updatedBy: string;updatedAt: string;})diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsxindex 1ec9cabe8c..a9b6f56fe8 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx@@ -1,7 +1,7 @@"use client";import { useCarbon } from "@carbon/auth";import type { Database } from "@carbon/database";-import { Input, ValidatedForm } from "@carbon/form";+import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";import type { JSONContent } from "@carbon/react";import {Alert,@@ -26,6 +26,11 @@ import {Label,Loading,ScrollArea,+ ToggleGroup,+ ToggleGroupItem,+ Tooltip,+ TooltipContent,+ TooltipTrigger,VStack,cn,useDebounce,@@ -44,7 +49,7 @@ import type { RealtimeChannel } from "@supabase/supabase-js";import { AnimatePresence, LayoutGroup, motion } from "framer-motion";import { nanoid } from "nanoid";import type { Dispatch, SetStateAction } from "react";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { flushSync } from "react-dom";import {LuActivity,@@ -53,6 +58,10 @@ import {LuDollarSign,LuEllipsisVertical,LuHammer,+ LuInfo,+ LuList,+ LuMaximize2,+ LuMinimize2,LuSend,LuSettings2,LuTriangleAlert,@@ -90,23 +99,36 @@ import type { Item, SortableItemRenderProps } from "~/components/SortableList";import { SortableList, SortableListItem } from "~/components/SortableList";import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";import { useTags } from "~/hooks/useTags";-import type { OperationParameter, OperationTool } from "~/modules/shared";+import type {+ OperationAttribute,+ OperationParameter,+ OperationTool,+} from "~/modules/shared";import {methodOperationOrders,+ operationAttributeValidator,operationParameterValidator,operationToolValidator,operationTypes,+ procedureAttributeType,} from "~/modules/shared";++import type { action as editJobOperationAttributeAction } from "~/routes/x+/job+/methods+/operation.attribute.$id";import type { action as editJobOperationParameterAction } from "~/routes/x+/job+/methods+/operation.parameter.$id";import type { action as editJobOperationToolAction } from "~/routes/x+/job+/methods+/operation.tool.$id";import type { action as newJobOperationParameterAction } from "~/routes/x+/job+/methods+/operation.parameter.new";import type { action as newJobOperationToolAction } from "~/routes/x+/job+/methods+/operation.tool.new";+import { usePeople, useTools } from "~/stores";import { getPrivateUrl, path } from "~/utils/path";import { jobOperationValidator } from "../../production.models";import { getProductionEventsPage } from "../../production.service";import type { Job, JobOperation } from "../../types";+import UnitOfMeasure, {+ useUnitOfMeasure,+} from "~/components/Form/UnitOfMeasure";import { JobOperationStatus } from "./JobOperationStatus";+import { ProcedureAttributeTypeIcon } from "~/components/Icons";export type Operation = z.infer<typeof jobOperationValidator> & {assignee: string | null;@@ -125,6 +147,7 @@ type JobBillOfProcessProps = {operations: (Operation & {jobOperationTool: OperationTool[];jobOperationParameter: OperationParameter[];+ jobOperationAttribute: OperationAttribute[];})[];tags: { name: string }[];};@@ -611,6 +634,9 @@ const JobBillOfProcess = ({const parameters =initialOperations.find((o) => o.id === item.id)?.jobOperationParameter ??[];+ const attributes =+ initialOperations.find((o) => o.id === item.id)?.jobOperationAttribute ??+ [];const tabs = [{@@ -697,6 +723,26 @@ const JobBillOfProcess = ({</div>),},+ {+ id: 3,+ label: (+ <span className="flex items-center gap-2">+ <span>Attributes</span>+ {attributes.length > 0 && <Count count={attributes.length} />}+ </span>+ ),+ content: (+ <div className="flex w-full flex-col py-4">+ <AttributesForm+ attributes={attributes}+ operationId={item.id!}+ isDisabled={+ selectedItemId === null || isTemporaryId(selectedItemId!)+ }+ />+ </div>+ ),+ },{id: 4,label: (@@ -896,6 +942,439 @@ function isTemporaryId(id: string) {return id.length < 20;}+function AttributesForm({+ operationId,+ isDisabled,+ attributes,+}: {+ operationId: string;+ isDisabled: boolean;+ attributes: OperationAttribute[];+}) {+ const fetcher = useFetcher<typeof newJobOperationParameterAction>();+ const [type, setType] = useState<OperationAttribute["type"]>("Value");+ const [numericControls, setNumericControls] = useState<string[]>([]);+ const typeOptions = useMemo(+ () =>+ procedureAttributeType.map((type) => ({+ label: (+ <HStack>+ <ProcedureAttributeTypeIcon type={type} className="mr-2" />+ {type}+ </HStack>+ ),+ value: type,+ })),+ []+ );++ if (isDisabled && isTemporaryId(operationId)) {+ return (+ <Alert className="max-w-[420px] mx-auto my-8">+ <LuTriangleAlert />+ <AlertTitle>Cannot add attributes to unsaved operation</AlertTitle>+ <AlertDescription>+ Please save the operation before adding attributes.+ </AlertDescription>+ </Alert>+ );+ }++ return (+ <div className="flex flex-col gap-6">+ <div className="p-6 border rounded-lg">+ <ValidatedForm+ action={path.to.newJobOperationAttribute}+ method="post"+ validator={operationAttributeValidator}+ fetcher={fetcher}+ resetAfterSubmit+ defaultValues={{+ id: undefined,+ name: "",+ description: "",+ type: "Value",+ unitOfMeasureCode: "",+ minValue: 0,+ maxValue: 0,+ listValues: [],+ sortOrder:+ attributes.reduce(+ (acc, a) => Math.max(acc, a.sortOrder ?? 0),+ 0+ ) + 1,+ operationId,+ }}+ onSubmit={() => {+ setType("Value");+ }}+ className="w-full"+ >+ <Hidden name="operationId" />+ <Hidden name="sortOrder" />+ <VStack spacing={4}>+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <SelectControlled+ name="type"+ label="Type"+ options={typeOptions}+ value={type}+ onChange={(option) => {+ if (option) {+ setType(option.value as OperationAttribute["type"]);+ }+ }}+ />+ <Input name="name" label="Name" />+ </div>++ {type === "Measurement" && (+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <UnitOfMeasure+ name="unitOfMeasureCode"+ label="Unit of Measure"+ />++ <ToggleGroup+ type="multiple"+ value={numericControls}+ onValueChange={setNumericControls}+ className="justify-start items-start mt-6"+ >+ <ToggleGroupItem size="sm" value="min">+ <LuMinimize2 className="mr-2" />+ Minimum+ </ToggleGroupItem>+ <ToggleGroupItem size="sm" value="max">+ <LuMaximize2 className="mr-2" />+ Maximum+ </ToggleGroupItem>+ </ToggleGroup>++ {numericControls.includes("min") && (+ <Number+ name="minValue"+ label="Minimum"+ formatOptions={{+ minimumFractionDigits: 0,+ maximumFractionDigits: 10,+ }}+ />+ )}+ {numericControls.includes("max") && (+ <Number+ name="maxValue"+ label="Maximum"+ formatOptions={{+ minimumFractionDigits: 0,+ maximumFractionDigits: 10,+ }}+ />+ )}+ </div>+ )}+ {type === "List" && (+ <ArrayInput name="listValues" label="List Options" />+ )}++ <Submit+ leftIcon={<LuCirclePlus />}+ isDisabled={isDisabled || fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ Add Attribute+ </Submit>+ </VStack>+ </ValidatedForm>+ </div>++ {attributes.length > 0 && (+ <div className="border rounded-lg">+ {[...attributes]+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))+ .map((a, index) => (+ <AttributesListItem+ key={a.id}+ attribute={a}+ operationId={operationId}+ typeOptions={typeOptions}+ className={index === attributes.length - 1 ? "border-none" : ""}+ />+ ))}+ </div>+ )}+ </div>+ );+}++function AttributesListItem({+ attribute,+ operationId,+ typeOptions,+ className,+}: {+ attribute: OperationAttribute;+ operationId: string;+ typeOptions: { label: JSX.Element; value: string }[];+ className?: string;+}) {+ const {+ name,+ unitOfMeasureCode,+ minValue,+ maxValue,+ id,+ updatedBy,+ updatedAt,+ createdBy,+ createdAt,+ } = attribute;++ const disclosure = useDisclosure();+ const deleteModalDisclosure = useDisclosure();+ const submitted = useRef(false);+ const fetcher = useFetcher<typeof editJobOperationAttributeAction>();++ useEffect(() => {+ if (submitted.current && fetcher.state === "idle") {+ disclosure.onClose();+ submitted.current = false;+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [fetcher.state]);++ const [type, setType] = useState<OperationAttribute["type"]>(attribute.type);+ const [numericControls, setNumericControls] = useState<string[]>(() => {+ const controls = [];+ if (type === "Measurement") {+ if (minValue !== null) {+ controls.push("min");+ }+ if (maxValue !== null) {+ controls.push("max");+ }+ }+ return controls;+ });++ const isUpdated = updatedBy !== null;+ const person = isUpdated ? updatedBy : createdBy;+ const date = updatedAt ?? createdAt;++ const unitOfMeasures = useUnitOfMeasure();++ if (!id) return null;++ return (+ <div className={cn("border-b p-6", className)}>+ {disclosure.isOpen ? (+ <ValidatedForm+ action={path.to.jobOperationAttribute(id)}+ method="post"+ validator={operationAttributeValidator}+ fetcher={fetcher}+ resetAfterSubmit+ onSubmit={() => {+ disclosure.onClose();+ }}+ defaultValues={{+ ...attribute,+ operationId,+ }}+ className="w-full"+ >+ <Hidden name="operationId" />+ <VStack spacing={4}>+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <SelectControlled+ name="type"+ label="Type"+ options={typeOptions}+ onChange={(option) => {+ if (option) {+ setType(option.value as OperationAttribute["type"]);+ }+ }}+ />+ <Input name="name" label="Name" />+ </div>+ <Input name="description" label="Description" />+ {type === "Measurement" && (+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <UnitOfMeasure+ name="unitOfMeasureCode"+ label="Unit of Measure"+ />++ <ToggleGroup+ type="multiple"+ value={numericControls}+ onValueChange={setNumericControls}+ className="justify-start items-start mt-6"+ >+ <ToggleGroupItem size="sm" value="min">+ <LuMinimize2 className="mr-2" />+ Minimum+ </ToggleGroupItem>+ <ToggleGroupItem size="sm" value="max">+ <LuMaximize2 className="mr-2" />+ Maximum+ </ToggleGroupItem>+ </ToggleGroup>++ {numericControls.includes("min") && (+ <Number+ name="minValue"+ label="Minimum"+ formatOptions={{+ minimumFractionDigits: 0,+ maximumFractionDigits: 10,+ }}+ />+ )}+ {numericControls.includes("max") && (+ <Number+ name="maxValue"+ label="Maximum"+ formatOptions={{+ minimumFractionDigits: 0,+ maximumFractionDigits: 10,+ }}+ />+ )}+ </div>+ )}+ {type === "List" && (+ <ArrayInput name="listValues" label="List Options" />+ )}+ <HStack className="w-full justify-end" spacing={2}>+ <Button variant="secondary" onClick={disclosure.onClose}>+ Cancel+ </Button>+ <Submit+ isDisabled={fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ Save+ </Submit>+ </HStack>+ </VStack>+ </ValidatedForm>+ ) : (+ <div className="flex flex-1 justify-between items-center w-full">+ <HStack spacing={4} className="w-1/2">+ <HStack spacing={4} className="flex-1">+ <div className="bg-muted border rounded-full flex items-center justify-center p-2">+ <ProcedureAttributeTypeIcon type={type} />+ </div>+ <VStack spacing={0}>+ <HStack>+ <p className="text-foreground text-sm font-medium">+ {attribute.name}+ </p>+ {attribute.description && (+ <Tooltip>+ <TooltipTrigger>+ <LuInfo className="text-muted-foreground size-3" />+ </TooltipTrigger>+ <TooltipContent side="right">+ <p className="text-foreground text-sm">+ {attribute.description}+ </p>+ </TooltipContent>+ </Tooltip>+ )}+ </HStack>+ {attribute.type === "Measurement" && (+ <span className="text-xs text-muted-foreground text-right">+ {attribute.minValue !== null && attribute.maxValue !== null+ ? `Must be between ${attribute.minValue} and ${+ attribute.maxValue+ } ${+ unitOfMeasures.find(+ (u) => u.value === unitOfMeasureCode+ )?.label+ }`+ : attribute.minValue !== null+ ? `Must be > ${attribute.minValue} ${+ unitOfMeasures.find(+ (u) => u.value === unitOfMeasureCode+ )?.label+ }`+ : `Must be < ${attribute.maxValue} ${+ unitOfMeasures.find(+ (u) => u.value === unitOfMeasureCode+ )?.label+ }`}+ </span>+ )}+ </VStack>++ {attribute.type === "List" &&+ Array.isArray(attribute.listValues) && (+ <Tooltip>+ <TooltipTrigger>+ <LuList className="size-4 text-muted-foreground" />+ </TooltipTrigger>+ <TooltipContent>+ {attribute.listValues.map((value) => (+ <p key={value} className="text-foreground text-sm">+ {value}+ </p>+ ))}+ </TooltipContent>+ </Tooltip>+ )}+ </HStack>+ </HStack>+ <div className="flex items-center justify-end gap-2">+ <HStack spacing={2}>+ <span className="text-xs text-muted-foreground">+ {isUpdated ? "Updated" : "Created"} {formatRelativeTime(date)}+ </span>+ <EmployeeAvatar employeeId={person} withName={false} />+ </HStack>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Open menu"+ icon={<LuEllipsisVertical />}+ variant="ghost"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={disclosure.onOpen}>+ Edit+ </DropdownMenuItem>+ <DropdownMenuItem+ destructive+ onClick={deleteModalDisclosure.onOpen}+ >+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ )}+ {deleteModalDisclosure.isOpen && (+ <ConfirmDelete+ action={path.to.deleteJobOperationAttribute(id)}+ isOpen={deleteModalDisclosure.isOpen}+ name={name}+ text={`Are you sure you want to delete the ${name} attribute from this operation? This cannot be undone.`}+ onCancel={() => {+ deleteModalDisclosure.onClose();+ }}+ onSubmit={() => {+ deleteModalDisclosure.onClose();+ }}+ />+ )}+ </div>+ );+}+function ParametersForm({operationId,isDisabled,diff --git a/apps/erp/app/modules/production/ui/Procedures/ProcedureAttributesExplorer.tsx b/apps/erp/app/modules/production/ui/Procedures/ProcedureExplorer.tsxsimilarity index 99%rename from apps/erp/app/modules/production/ui/Procedures/ProcedureAttributesExplorer.tsxrename to apps/erp/app/modules/production/ui/Procedures/ProcedureExplorer.tsxindex efbaa8c322..bad96d6fc1 100644--- a/apps/erp/app/modules/production/ui/Procedures/ProcedureAttributesExplorer.tsx+++ b/apps/erp/app/modules/production/ui/Procedures/ProcedureExplorer.tsx@@ -59,7 +59,7 @@ import { Reorder } from "framer-motion";import { flushSync } from "react-dom";import { procedureAttributeType } from "~/modules/shared";-export default function ProcedureAttributesExplorer() {+export default function ProcedureExplorer() {const { id } = useParams();if (!id) throw new Error("Could not find id");const procedureData = useRouteData<{@@ -499,6 +499,7 @@ function ProcedureAttributeForm({name="type"label="Type"options={typeOptions}+ value={type}onChange={(option) => {if (option) {setType(option.value as ProcedureAttribute["type"]);diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 4d5aabed6c..7a2488f2dd 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -2193,8 +2193,13 @@ export async function upsertQuoteOperationAttribute(companyId: string;createdBy: string;})- | (Omit<z.infer<typeof operationAttributeValidator>, "id"> & {+ | (Omit<+ z.infer<typeof operationAttributeValidator>,+ "id" | "minValue" | "maxValue"+ > & {id: string;+ minValue: number | null;+ maxValue: number | null;updatedBy: string;updatedAt: string;})diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsxindex bc22c081e2..83f1be55ae 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx@@ -1,6 +1,6 @@"use client";import { useCarbon } from "@carbon/auth";-import { Input, ValidatedForm } from "@carbon/form";+import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";import type { JSONContent } from "@carbon/react";import {Alert,@@ -21,6 +21,11 @@ import {HStack,IconButton,Label,+ ToggleGroup,+ ToggleGroupItem,+ Tooltip,+ TooltipContent,+ TooltipTrigger,VStack,cn,useDebounce,@@ -33,7 +38,7 @@ import { useFetcher, useFetchers, useParams } from "@remix-run/react";import { AnimatePresence, LayoutGroup, motion } from "framer-motion";import { nanoid } from "nanoid";import type { Dispatch, SetStateAction } from "react";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import {LuActivity,LuChevronDown,@@ -41,6 +46,10 @@ import {LuDollarSign,LuEllipsisVertical,LuHammer,+ LuInfo,+ LuList,+ LuMaximize2,+ LuMinimize2,LuSettings2,LuTriangleAlert,LuX,@@ -68,21 +77,34 @@ import { ConfirmDelete } from "~/components/Modals";import type { Item, SortableItemRenderProps } from "~/components/SortableList";import { SortableList, SortableListItem } from "~/components/SortableList";import { usePermissions, useRouteData, useUser } from "~/hooks";-import type { OperationParameter, OperationTool } from "~/modules/shared";+import type {+ OperationAttribute,+ OperationParameter,+ OperationTool,+} from "~/modules/shared";import {methodOperationOrders,operationParameterValidator,operationToolValidator,operationTypes,+ operationAttributeValidator,+ procedureAttributeType,} from "~/modules/shared";++import type { action as editQuoteOperationAttributeAction } from "~/routes/x+/quote+/methods+/operation.attribute.$id";import type { action as editQuoteOperationToolAction } from "~/routes/x+/quote+/methods+/operation.tool.$id";import type { action as editQuoteOperationParameterAction } from "~/routes/x+/quote+/methods+/operation.parameter.$id";import type { action as newQuoteOperationToolAction } from "~/routes/x+/quote+/methods+/operation.tool.new";import type { action as newQuoteOperationParameterAction } from "~/routes/x+/quote+/methods+/operation.parameter.new";+import { useTools } from "~/stores";import { getPrivateUrl, path } from "~/utils/path";import { quoteOperationValidator } from "../../sales.models";import type { Quotation } from "../../types";+import UnitOfMeasure, {+ useUnitOfMeasure,+} from "~/components/Form/UnitOfMeasure";+import { ProcedureAttributeTypeIcon } from "~/components/Icons";export type Operation = z.infer<typeof quoteOperationValidator> & {workInstruction: JSONContent | null;@@ -98,6 +120,7 @@ type QuoteBillOfProcessProps = {operations: (Operation & {quoteOperationTool: OperationTool[];quoteOperationParameter: OperationParameter[];+ quoteOperationAttribute: OperationAttribute[];})[];tags: { name: string }[];};@@ -458,6 +481,9 @@ const QuoteBillOfProcess = ({const parameters =initialOperations.find((o) => o.id === item.id)?.quoteOperationParameter ?? [];+ const attributes =+ initialOperations.find((o) => o.id === item.id)+ ?.quoteOperationAttribute ?? [];const tabs = [{@@ -543,6 +569,26 @@ const QuoteBillOfProcess = ({</div>),},+ {+ id: 3,+ label: (+ <span className="flex items-center gap-2">+ <span>Attributes</span>+ {attributes.length > 0 && <Count count={attributes.length} />}+ </span>+ ),+ content: (+ <div className="flex w-full flex-col py-4">+ <AttributesForm+ attributes={attributes}+ operationId={item.id!}+ isDisabled={+ selectedItemId === null || isTemporaryId(selectedItemId!)+ }+ />+ </div>+ ),+ },{id: 4,label: (@@ -712,6 +758,439 @@ export function isTemporaryId(id: string) {return id.length < 20;}+function AttributesForm({+ operationId,+ isDisabled,+ attributes,+}: {+ operationId: string;+ isDisabled: boolean;+ attributes: OperationAttribute[];+}) {+ const fetcher = useFetcher<typeof newQuoteOperationParameterAction>();+ const [type, setType] = useState<OperationAttribute["type"]>("Value");+ const [numericControls, setNumericControls] = useState<string[]>([]);+ const typeOptions = useMemo(+ () =>+ procedureAttributeType.map((type) => ({+ label: (+ <HStack>+ <ProcedureAttributeTypeIcon type={type} className="mr-2" />+ {type}+ </HStack>+ ),+ value: type,+ })),+ []+ );++ if (isDisabled && isTemporaryId(operationId)) {+ return (+ <Alert className="max-w-[420px] mx-auto my-8">+ <LuTriangleAlert />+ <AlertTitle>Cannot add attributes to unsaved operation</AlertTitle>+ <AlertDescription>+ Please save the operation before adding attributes.+ </AlertDescription>+ </Alert>+ );+ }++ return (+ <div className="flex flex-col gap-6">+ <div className="p-6 border rounded-lg">+ <ValidatedForm+ action={path.to.newQuoteOperationAttribute}+ method="post"+ validator={operationAttributeValidator}+ fetcher={fetcher}+ resetAfterSubmit+ defaultValues={{+ id: undefined,+ name: "",+ description: "",+ type: "Value",+ unitOfMeasureCode: "",+ minValue: 0,+ maxValue: 0,+ listValues: [],+ sortOrder:+ attributes.reduce(+ (acc, a) => Math.max(acc, a.sortOrder ?? 0),+ 0+ ) + 1,+ operationId,+ }}+ onSubmit={() => {+ setType("Value");+ }}+ className="w-full"+ >+ <Hidden name="operationId" />+ <Hidden name="sortOrder" />+ <VStack spacing={4}>+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <SelectControlled+ name="type"+ label="Type"+ options={typeOptions}+ value={type}+ onChange={(option) => {+ if (option) {+ setType(option.value as OperationAttribute["type"]);+ }+ }}+ />+ <Input name="name" label="Name" />+ </div>++ {type === "Measurement" && (+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <UnitOfMeasure+ name="unitOfMeasureCode"+ label="Unit of Measure"+ />++ <ToggleGroup+ type="multiple"+ value={numericControls}+ onValueChange={setNumericControls}+ className="justify-start items-start mt-6"+ >+ <ToggleGroupItem size="sm" value="min">+ <LuMinimize2 className="mr-2" />+ Minimum+ </ToggleGroupItem>+ <ToggleGroupItem size="sm" value="max">+ <LuMaximize2 className="mr-2" />+ Maximum+ </ToggleGroupItem>+ </ToggleGroup>++ {numericControls.includes("min") && (+ <Number+ name="minValue"+ label="Minimum"+ formatOptions={{+ minimumFractionDigits: 0,+ maximumFractionDigits: 10,+ }}+ />+ )}+ {numericControls.includes("max") && (+ <Number+ name="maxValue"+ label="Maximum"+ formatOptions={{+ minimumFractionDigits: 0,+ maximumFractionDigits: 10,+ }}+ />+ )}+ </div>+ )}+ {type === "List" && (+ <ArrayInput name="listValues" label="List Options" />+ )}++ <Submit+ leftIcon={<LuCirclePlus />}+ isDisabled={isDisabled || fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ Add Attribute+ </Submit>+ </VStack>+ </ValidatedForm>+ </div>++ {attributes.length > 0 && (+ <div className="border rounded-lg">+ {[...attributes]+ .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))+ .map((a, index) => (+ <AttributesListItem+ key={a.id}+ attribute={a}+ operationId={operationId}+ typeOptions={typeOptions}+ className={index === attributes.length - 1 ? "border-none" : ""}+ />+ ))}+ </div>+ )}+ </div>+ );+}++function AttributesListItem({+ attribute,+ operationId,+ typeOptions,+ className,+}: {+ attribute: OperationAttribute;+ operationId: string;+ typeOptions: { label: JSX.Element; value: string }[];+ className?: string;+}) {+ const {+ name,+ unitOfMeasureCode,+ minValue,+ maxValue,+ id,+ updatedBy,+ updatedAt,+ createdBy,+ createdAt,+ } = attribute;++ const disclosure = useDisclosure();+ const deleteModalDisclosure = useDisclosure();+ const submitted = useRef(false);+ const fetcher = useFetcher<typeof editQuoteOperationAttributeAction>();++ useEffect(() => {+ if (submitted.current && fetcher.state === "idle") {+ disclosure.onClose();+ submitted.current = false;+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [fetcher.state]);++ const [type, setType] = useState<OperationAttribute["type"]>(attribute.type);+ const [numericControls, setNumericControls] = useState<string[]>(() => {+ const controls = [];+ if (type === "Measurement") {+ if (minValue !== null) {+ controls.push("min");+ }+ if (maxValue !== null) {+ controls.push("max");+ }+ }+ return controls;+ });++ const isUpdated = updatedBy !== null;+ const person = isUpdated ? updatedBy : createdBy;+ const date = updatedAt ?? createdAt;++ const unitOfMeasures = useUnitOfMeasure();++ if (!id) return null;++ return (+ <div className={cn("border-b p-6", className)}>+ {disclosure.isOpen ? (+ <ValidatedForm+ action={path.to.quoteOperationAttribute(id)}+ method="post"+ validator={operationAttributeValidator}+ fetcher={fetcher}+ resetAfterSubmit+ onSubmit={() => {+ disclosure.onClose();+ }}+ defaultValues={{+ ...attribute,+ operationId,+ }}+ className="w-full"+ >+ <Hidden name="operationId" />+ <VStack spacing={4}>+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <SelectControlled+ name="type"+ label="Type"+ options={typeOptions}+ onChange={(option) => {+ if (option) {+ setType(option.value as OperationAttribute["type"]);+ }+ }}+ />+ <Input name="name" label="Name" />+ </div>+ <Input name="description" label="Description" />+ {type === "Measurement" && (+ <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-4 items-start">+ <UnitOfMeasure+ name="unitOfMeasureCode"+ label="Unit of Measure"+ />++ <ToggleGroup+ type="multiple"+ value={numericControls}+ onValueChange={setNumericControls}+ className="justify-start items-start mt-6"+ >+ <ToggleGroupItem size="sm" value="min">+ <LuMinimize2 className="mr-2" />+ Minimum+ </ToggleGroupItem>+ <ToggleGroupItem size="sm" value="max">+ <LuMaximize2 className="mr-2" />+ Maximum+ </ToggleGroupItem>+ </ToggleGroup>++ {numericControls.includes("min") && (+ <Number+ name="minValue"+ label="Minimum"+ formatOptions={{+ minimumFractionDigits: 0,+ maximumFractionDigits: 10,+ }}+ />+ )}+ {numericControls.includes("max") && (+ <Number+ name="maxValue"+ label="Maximum"+ formatOptions={{+ minimumFractionDigits: 0,+ maximumFractionDigits: 10,+ }}+ />+ )}+ </div>+ )}+ {type === "List" && (+ <ArrayInput name="listValues" label="List Options" />+ )}+ <HStack className="w-full justify-end" spacing={2}>+ <Button variant="secondary" onClick={disclosure.onClose}>+ Cancel+ </Button>+ <Submit+ isDisabled={fetcher.state !== "idle"}+ isLoading={fetcher.state !== "idle"}+ >+ Save+ </Submit>+ </HStack>+ </VStack>+ </ValidatedForm>+ ) : (+ <div className="flex flex-1 justify-between items-center w-full">+ <HStack spacing={4} className="w-1/2">+ <HStack spacing={4} className="flex-1">+ <div className="bg-muted border rounded-full flex items-center justify-center p-2">+ <ProcedureAttributeTypeIcon type={type} />+ </div>+ <VStack spacing={0}>+ <HStack>+ <p className="text-foreground text-sm font-medium">+ {attribute.name}+ </p>+ {attribute.description && (+ <Tooltip>+ <TooltipTrigger>+ <LuInfo className="text-muted-foreground size-3" />+ </TooltipTrigger>+ <TooltipContent side="right">+ <p className="text-foreground text-sm">+ {attribute.description}+ </p>+ </TooltipContent>+ </Tooltip>+ )}+ </HStack>+ {attribute.type === "Measurement" && (+ <span className="text-xs text-muted-foreground text-right">+ {attribute.minValue !== null && attribute.maxValue !== null+ ? `Must be between ${attribute.minValue} and ${+ attribute.maxValue+ } ${+ unitOfMeasures.find(+ (u) => u.value === unitOfMeasureCode+ )?.label+ }`+ : attribute.minValue !== null+ ? `Must be > ${attribute.minValue} ${+ unitOfMeasures.find(+ (u) => u.value === unitOfMeasureCode+ )?.label+ }`+ : `Must be < ${attribute.maxValue} ${+ unitOfMeasures.find(+ (u) => u.value === unitOfMeasureCode+ )?.label+ }`}+ </span>+ )}+ </VStack>++ {attribute.type === "List" &&+ Array.isArray(attribute.listValues) && (+ <Tooltip>+ <TooltipTrigger>+ <LuList className="size-4 text-muted-foreground" />+ </TooltipTrigger>+ <TooltipContent>+ {attribute.listValues.map((value) => (+ <p key={value} className="text-foreground text-sm">+ {value}+ </p>+ ))}+ </TooltipContent>+ </Tooltip>+ )}+ </HStack>+ </HStack>+ <div className="flex items-center justify-end gap-2">+ <HStack spacing={2}>+ <span className="text-xs text-muted-foreground">+ {isUpdated ? "Updated" : "Created"} {formatRelativeTime(date)}+ </span>+ <EmployeeAvatar employeeId={person} withName={false} />+ </HStack>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Open menu"+ icon={<LuEllipsisVertical />}+ variant="ghost"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={disclosure.onOpen}>+ Edit+ </DropdownMenuItem>+ <DropdownMenuItem+ destructive+ onClick={deleteModalDisclosure.onOpen}+ >+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ )}+ {deleteModalDisclosure.isOpen && (+ <ConfirmDelete+ action={path.to.deleteQuoteOperationAttribute(id)}+ isOpen={deleteModalDisclosure.isOpen}+ name={name}+ text={`Are you sure you want to delete the ${name} attribute from this operation? This cannot be undone.`}+ onCancel={() => {+ deleteModalDisclosure.onClose();+ }}+ onSubmit={() => {+ deleteModalDisclosure.onClose();+ }}+ />+ )}+ </div>+ );+}+function ParametersForm({operationId,isDisabled,diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.attribute.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.attribute.$id.tsxindex aed8a1179e..b88a7d064f 100644--- a/apps/erp/app/routes/x+/items+/methods+/operation.attribute.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operation.attribute.$id.tsx@@ -31,6 +31,8 @@ export async function action({ request, params }: ActionFunctionArgs) {const update = await upsertMethodOperationAttribute(client, {id,...data,+ minValue: data.minValue ?? null,+ maxValue: data.maxValue ?? null,updatedBy: userId,updatedAt: new Date().toISOString(),});diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.attribute.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.attribute.$id.tsxnew file mode 100644index 0000000000..cc845bb9a1--- /dev/null+++ b/apps/erp/app/routes/x+/job+/methods+/operation.attribute.$id.tsx@@ -0,0 +1,69 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validator } from "@carbon/form";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { upsertJobOperationAttribute } from "~/modules/production";+import { operationAttributeValidator } from "~/modules/shared";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "production",+ });++ const { id } = params;+ if (!id) {+ return json({ success: false, message: "Invalid operation attribute id" });+ }++ const formData = await request.formData();+ const validation = await validator(operationAttributeValidator).validate(+ formData+ );++ if (validation.error) {+ return json({ success: false, message: "Invalid form data" });+ }++ const { id: _id, ...data } = validation.data;++ const update = await upsertJobOperationAttribute(client, {+ id,+ ...data,+ minValue: data.minValue ?? null,+ maxValue: data.maxValue ?? null,+ companyId,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ });+ if (update.error) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(update.error, "Failed to update job operation attribute")+ )+ );+ }++ const operationAttributeId = update.data?.id;+ if (!operationAttributeId) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(update.error, "Failed to update job operation attribute")+ )+ );+ }++ return json(+ { id: operationAttributeId },+ await flash(request, success("Job operation attribute updated"))+ );+}diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.attribute.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.attribute.delete.$id.tsxnew file mode 100644index 0000000000..57931ed965--- /dev/null+++ b/apps/erp/app/routes/x+/job+/methods+/operation.attribute.delete.$id.tsx@@ -0,0 +1,38 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { deleteJobOperationAttribute } from "~/modules/production";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ delete: "production",+ });++ const { id } = params;+ if (!id) {+ throw new Error("id not found");+ }++ const deleteOperationAttribute = await deleteJobOperationAttribute(+ client,+ id+ );+ if (deleteOperationAttribute.error) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(+ deleteOperationAttribute.error,+ "Failed to delete job operation attribute"+ )+ )+ );+ }++ return json({});+}diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.attribute.new.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.attribute.new.tsxnew file mode 100644index 0000000000..f811e96cb5--- /dev/null+++ b/apps/erp/app/routes/x+/job+/methods+/operation.attribute.new.tsx@@ -0,0 +1,60 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { upsertJobOperationAttribute } from "~/modules/production";+import { operationAttributeValidator } from "~/modules/shared";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "production",+ });++ const formData = await request.formData();+ const validation = await validator(operationAttributeValidator).validate(+ formData+ );++ console.log({ validation });++ if (validation.error) {+ return validationError(validation.error);+ }++ const insert = await upsertJobOperationAttribute(client, {+ ...validation.data,+ companyId,+ createdBy: userId,+ });++ console.log({ insert });++ if (insert.error) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(insert.error, "Failed to insert job operation attribute")+ )+ );+ }++ const jobOperationAttributeId = insert.data?.id;+ if (!jobOperationAttributeId) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(insert.error, "Failed to insert job operation attribute")+ )+ );+ }++ return json({ id: jobOperationAttributeId });+}diff --git a/apps/erp/app/routes/x+/procedure+/$id.tsx b/apps/erp/app/routes/x+/procedure+/$id.tsxindex 84eb561e61..77613913fe 100644--- a/apps/erp/app/routes/x+/procedure+/$id.tsx+++ b/apps/erp/app/routes/x+/procedure+/$id.tsx@@ -10,14 +10,14 @@ import type { LoaderFunctionArgs } from "@vercel/remix";import { defer, redirect } from "@vercel/remix";import { nanoid } from "nanoid";import { useState } from "react";-import { ResizablePanels , PanelProvider } from "~/components/Layout/Panels";+import { ResizablePanels, PanelProvider } from "~/components/Layout/Panels";import { usePermissions, useUser } from "~/hooks";import {getProcedure,getProcedureAttributes,getProcedureVersions,} from "~/modules/production";-import ProcedureAttributesExplorer from "~/modules/production/ui/Procedures/ProcedureAttributesExplorer";+import ProcedureExplorer from "~/modules/production/ui/Procedures/ProcedureExplorer";import ProcedureHeader from "~/modules/production/ui/Procedures/ProcedureHeader";import ProcedureProperties from "~/modules/production/ui/Procedures/ProcedureProperties";import type { action } from "~/routes/x+/procedure+/update";@@ -67,7 +67,7 @@ export default function ProcedureRoute() {<div className="flex h-[calc(100dvh-99px)] overflow-hidden w-full"><div className="flex flex-grow overflow-hidden"><ResizablePanels- explorer={<ProcedureAttributesExplorer />}+ explorer={<ProcedureExplorer />}content={<div className="bg-background h-[calc(100dvh-99px)] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full"><ProcedureEditor />diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.$id.tsxnew file mode 100644index 0000000000..b3728207ef--- /dev/null+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.$id.tsx@@ -0,0 +1,69 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validator } from "@carbon/form";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { upsertQuoteOperationAttribute } from "~/modules/sales";+import { operationAttributeValidator } from "~/modules/shared";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { id } = params;+ if (!id) {+ return json({ success: false, message: "Invalid operation attribute id" });+ }++ const formData = await request.formData();+ const validation = await validator(operationAttributeValidator).validate(+ formData+ );++ if (validation.error) {+ return json({ success: false, message: "Invalid form data" });+ }++ const { id: _id, ...data } = validation.data;++ const update = await upsertQuoteOperationAttribute(client, {+ id,+ ...data,+ minValue: data.minValue ?? null,+ maxValue: data.maxValue ?? null,+ companyId,+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+ });+ if (update.error) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(update.error, "Failed to update operation attribute")+ )+ );+ }++ const operationAttributeId = update.data?.id;+ if (!operationAttributeId) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(update.error, "Failed to update operation attribute")+ )+ );+ }++ return json(+ { id: operationAttributeId },+ await flash(request, success("Quote operation attribute updated"))+ );+}diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.delete.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.delete.$id.tsxnew file mode 100644index 0000000000..50c0ebbcf8--- /dev/null+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.delete.$id.tsx@@ -0,0 +1,38 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { deleteQuoteOperationAttribute } from "~/modules/sales";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ delete: "parts",+ });++ const { id } = params;+ if (!id) {+ throw new Error("id not found");+ }++ const deleteOperationAttribute = await deleteQuoteOperationAttribute(+ client,+ id+ );+ if (deleteOperationAttribute.error) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(+ deleteOperationAttribute.error,+ "Failed to delete quote operation parameter"+ )+ )+ );+ }++ return json({});+}diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.new.tsxnew file mode 100644index 0000000000..25d6fbdb14--- /dev/null+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.attribute.new.tsx@@ -0,0 +1,55 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { upsertQuoteOperationAttribute } from "~/modules/sales";+import { operationAttributeValidator } from "~/modules/shared";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "parts",+ });++ const formData = await request.formData();+ const validation = await validator(operationAttributeValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const insert = await upsertQuoteOperationAttribute(client, {+ ...validation.data,+ companyId,+ createdBy: userId,+ });+ if (insert.error) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(insert.error, "Failed to insert quote operation attribute")+ )+ );+ }++ const quoteOperationAttributeId = insert.data?.id;+ if (!quoteOperationAttributeId) {+ return json(+ {+ id: null,+ },+ await flash(+ request,+ error(insert.error, "Failed to insert quote operation attribute")+ )+ );+ }++ return json({ id: quoteOperationAttributeId });+}diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 90c7131827..e0bc2f1215 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -91,7 +91,9 @@ serve(async (req: Request) => {.eq("makeMethodId", sourceMakeMethod.data.id),client.from("methodOperation")- .select("*, methodOperationTool(*), methodOperationParameter(*)")+ .select(+ "*, methodOperationTool(*), methodOperationParameter(*), methodOperationAttribute(*)"+ ).eq("makeMethodId", sourceMakeMethod.data.id),]);@@ -149,8 +151,11 @@ serve(async (req: Request) => {index,operation,] of sourceOperations.data.entries()) {- const { methodOperationTool, methodOperationParameter } =- operation;+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationAttribute,+ } = operation;const operationId = operationIds[index].id;if (@@ -189,6 +194,23 @@ serve(async (req: Request) => {).execute();}++ if (+ Array.isArray(methodOperationAttribute) &&+ methodOperationAttribute.length > 0+ ) {+ await trx+ .insertInto("methodOperationAttribute")+ .values(+ methodOperationAttribute.map((attribute) => ({+ ...attribute,+ operationId: operationId!,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }}}});@@ -322,7 +344,9 @@ serve(async (req: Request) => {const relatedOperations = await client.from("methodOperation")- .select("*, methodOperationTool(*), methodOperationParameter(*)")+ .select(+ "*, methodOperationTool(*), methodOperationParameter(*), methodOperationAttribute(*)"+ ).eq("makeMethodId", node.data.materialMakeMethodId);let jobOperationsInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =@@ -467,8 +491,11 @@ serve(async (req: Request) => {const operationId = operationIds[index].id;if (operationId) {- const { methodOperationTool, methodOperationParameter } =- operation;+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationAttribute,+ } = operation;if (Array.isArray(methodOperationTool) &&@@ -511,6 +538,35 @@ serve(async (req: Request) => {.values(parameters).execute();}++ if (+ Array.isArray(methodOperationAttribute) &&+ methodOperationAttribute.length > 0+ ) {+ const attributes = await Promise.all(+ methodOperationAttribute.map(async (attribute) => ({+ ...attribute,+ operationId,+ minValue: await getConfiguredValue({+ id: operation.id,+ field: `attribute:${attribute.id}:minValue`,+ defaultValue: attribute.minValue,+ }),+ maxValue: await getConfiguredValue({+ id: operation.id,+ field: `attribute:${attribute.id}:maxValue`,+ defaultValue: attribute.maxValue,+ }),+ companyId,+ createdBy: userId,+ }))+ );++ await trx+ .insertInto("jobOperationAttribute")+ .values(attributes)+ .execute();+ }}}@@ -764,7 +820,9 @@ serve(async (req: Request) => {) {const relatedOperations = await client.from("methodOperation")- .select("*, methodOperationTool(*), methodOperationParameter(*)")+ .select(+ "*, methodOperationTool(*), methodOperationParameter(*), methodOperationAttribute(*)"+ ).eq("makeMethodId", node.data.materialMakeMethodId);const jobOperationsInserts =@@ -810,8 +868,11 @@ serve(async (req: Request) => {const operationId = operationIds[index].id;if (operationId) {- const { methodOperationTool, methodOperationParameter } =- operation;+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationAttribute,+ } = operation;if (Array.isArray(methodOperationTool) &&methodOperationTool.length > 0@@ -847,6 +908,23 @@ serve(async (req: Request) => {).execute();}++ if (+ Array.isArray(methodOperationAttribute) &&+ methodOperationAttribute.length > 0+ ) {+ await trx+ .insertInto("jobOperationAttribute")+ .values(+ methodOperationAttribute.map((attribute) => ({+ ...attribute,+ operationId,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }}}@@ -1064,7 +1142,9 @@ serve(async (req: Request) => {) {const relatedOperations = await client.from("methodOperation")- .select("*, methodOperationTool(*), methodOperationParameter(*)")+ .select(+ "*, methodOperationTool(*), methodOperationParameter(*), methodOperationAttribute(*)"+ ).eq("makeMethodId", node.data.materialMakeMethodId);let quoteOperationsInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =@@ -1215,8 +1295,11 @@ serve(async (req: Request) => {const operationId = operationIds[index].id;if (operationId) {- const { methodOperationTool, methodOperationParameter } =- operation;+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationAttribute,+ } = operation;if (Array.isArray(methodOperationTool) &&@@ -1259,6 +1342,35 @@ serve(async (req: Request) => {.values(parameters).execute();}++ if (+ Array.isArray(methodOperationAttribute) &&+ methodOperationAttribute.length > 0+ ) {+ const attributes = await Promise.all(+ methodOperationAttribute.map(async (attribute) => ({+ ...attribute,+ operationId,+ minValue: await getConfiguredValue({+ id: operation.id,+ field: `attribute:${attribute.id}:minValue`,+ defaultValue: attribute.minValue,+ }),+ maxValue: await getConfiguredValue({+ id: operation.id,+ field: `attribute:${attribute.id}:maxValue`,+ defaultValue: attribute.maxValue,+ }),+ companyId,+ createdBy: userId,+ }))+ );++ await trx+ .insertInto("quoteOperationAttribute")+ .values(attributes)+ .execute();+ }}}@@ -1515,7 +1627,9 @@ serve(async (req: Request) => {) {const relatedOperations = await client.from("methodOperation")- .select("*, methodOperationTool(*), methodOperationParameter(*)")+ .select(+ "*, methodOperationTool(*), methodOperationParameter(*), methodOperationAttribute(*)"+ ).eq("makeMethodId", node.data.materialMakeMethodId);const quoteOperationInserts =@@ -1562,8 +1676,11 @@ serve(async (req: Request) => {const operationId = operationIds[index].id;if (operationId) {- const { methodOperationTool, methodOperationParameter } =- operation;+ const {+ methodOperationTool,+ methodOperationParameter,+ methodOperationAttribute,+ } = operation;if (Array.isArray(methodOperationTool) &&methodOperationTool.length > 0@@ -1599,6 +1716,23 @@ serve(async (req: Request) => {).execute();}++ if (+ Array.isArray(methodOperationAttribute) &&+ methodOperationAttribute.length > 0+ ) {+ await trx+ .insertInto("quoteOperationAttribute")+ .values(+ methodOperationAttribute.map((attribute) => ({+ ...attribute,+ operationId,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }}}@@ -1711,7 +1845,9 @@ serve(async (req: Request) => {const [jobOperations] = await Promise.all([client.from("jobOperationsWithMakeMethods")- .select("*, jobOperationTool(*), jobOperationParameter(*)")+ .select(+ "*, jobOperationTool(*), jobOperationParameter(*), jobOperationAttribute(*)"+ ).eq("jobId", jobMakeMethod.data.jobId),]);@@ -1872,7 +2008,11 @@ serve(async (req: Request) => {).entries()) {const operationId = operationIds[index].id;if (operationId) {- const { jobOperationTool, jobOperationParameter } = operation;+ const {+ jobOperationTool,+ jobOperationParameter,+ jobOperationAttribute,+ } = operation;if (Array.isArray(jobOperationTool) &&@@ -1909,6 +2049,23 @@ serve(async (req: Request) => {).execute();}++ if (+ Array.isArray(jobOperationAttribute) &&+ jobOperationAttribute.length > 0+ ) {+ await trx+ .insertInto("jobOperationAttribute")+ .values(+ jobOperationAttribute.map((attribute) => ({+ ...attribute,+ operationId,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }}}}@@ -1933,7 +2090,9 @@ serve(async (req: Request) => {.single(),client.from("jobOperationsWithMakeMethods")- .select("*, jobOperationTool(*), jobOperationParameter(*)")+ .select(+ "*, jobOperationTool(*), jobOperationParameter(*), jobOperationAttribute(*)"+ ).eq("jobId", jobId),]);@@ -2095,7 +2254,11 @@ serve(async (req: Request) => {).entries()) {const operationId = operationIds[index].id;if (operationId) {- const { jobOperationTool, jobOperationParameter } = operation;+ const {+ jobOperationTool,+ jobOperationParameter,+ jobOperationAttribute,+ } = operation;if (Array.isArray(jobOperationTool) &&@@ -2132,6 +2295,23 @@ serve(async (req: Request) => {).execute();}++ if (+ Array.isArray(jobOperationAttribute) &&+ jobOperationAttribute.length > 0+ ) {+ await trx+ .insertInto("jobOperationAttribute")+ .values(+ jobOperationAttribute.map((attribute) => ({+ ...attribute,+ operationId,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }}}}@@ -2157,7 +2337,9 @@ serve(async (req: Request) => {.single(),client.from("quoteOperationsWithMakeMethods")- .select("*, quoteOperationTool(*), quoteOperationParameter(*)")+ .select(+ "*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"+ ).eq("quoteLineId", quoteLineId),]);@@ -2326,8 +2508,11 @@ serve(async (req: Request) => {).entries()) {const operationId = operationIds[index].id;if (operationId) {- const { quoteOperationTool, quoteOperationParameter } =- operation;+ const {+ quoteOperationTool,+ quoteOperationParameter,+ quoteOperationAttribute,+ } = operation;if (Array.isArray(quoteOperationTool) &&@@ -2364,6 +2549,23 @@ serve(async (req: Request) => {).execute();}++ if (+ Array.isArray(quoteOperationAttribute) &&+ quoteOperationAttribute.length > 0+ ) {+ await trx+ .insertInto("quoteOperationAttribute")+ .values(+ quoteOperationAttribute.map((attribute) => ({+ ...attribute,+ operationId,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }}}}@@ -2406,7 +2608,9 @@ serve(async (req: Request) => {.eq("quoteLineId", quoteLineId),client.from("quoteOperation")- .select("*, quoteOperationTool(*), quoteOperationParameter(*)")+ .select(+ "*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"+ ).eq("quoteLineId", quoteLineId),]);@@ -2566,8 +2770,11 @@ serve(async (req: Request) => {).entries()) {const operationId = operationIds[index].id;if (operationId) {- const { quoteOperationTool, quoteOperationParameter } =- operation;+ const {+ quoteOperationTool,+ quoteOperationParameter,+ quoteOperationAttribute,+ } = operation;if (Array.isArray(quoteOperationTool) &&@@ -2604,6 +2811,23 @@ serve(async (req: Request) => {).execute();}++ if (+ Array.isArray(quoteOperationAttribute) &&+ quoteOperationAttribute.length > 0+ ) {+ await trx+ .insertInto("quoteOperationAttribute")+ .values(+ quoteOperationAttribute.map((attribute) => ({+ ...attribute,+ operationId,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }}}}@@ -2635,7 +2859,9 @@ serve(async (req: Request) => {const [quoteOperations] = await Promise.all([client.from("quoteOperationsWithMakeMethods")- .select("*, quoteOperationTool(*), quoteOperationParameter(*)")+ .select(+ "*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"+ ).eq("quoteLineId", quoteMakeMethod.data.quoteLineId),]);@@ -2800,8 +3026,11 @@ serve(async (req: Request) => {).entries()) {const operationId = operationIds[index].id;if (operationId) {- const { quoteOperationTool, quoteOperationParameter } =- operation;+ const {+ quoteOperationTool,+ quoteOperationParameter,+ quoteOperationAttribute,+ } = operation;if (Array.isArray(quoteOperationTool) &&@@ -2838,6 +3067,23 @@ serve(async (req: Request) => {).execute();}++ if (+ Array.isArray(quoteOperationAttribute) &&+ quoteOperationAttribute.length > 0+ ) {+ await trx+ .insertInto("methodOperationAttribute")+ .values(+ quoteOperationAttribute.map((attribute) => ({+ ...attribute,+ operationId,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }}}}diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.tsindex 5af0770c5f..74be8568db 100644--- a/packages/utils/src/themes.ts+++ b/packages/utils/src/themes.ts@@ -43,16 +43,16 @@ export const themes = ["primary-foreground": "220 5.9% 10%",active: "220 5.2% 13.9%","active-foreground": "0 0% 98%",- secondary: "220 3.7% 15.9%",+ secondary: "220 10% 15.9%","secondary-foreground": "0 0% 98%",- muted: "220 3.7% 15.9%",+ muted: "220 10% 15.9%","muted-foreground": "220 5% 64.9%",- accent: "220 3.7% 15.9%",+ accent: "220 10% 15.9%","accent-foreground": "0 0% 98%",destructive: "0 62.8% 30.6%","destructive-foreground": "0 0% 98%",- border: "220 3.7% 15.9%",- input: "220 3.7% 15.9%",+ border: "220 10% 15.9%",+ input: "220 10% 15.9%",ring: "220 4.9% 83.9%",},},@@ -381,16 +381,16 @@ export const themes = ["primary-foreground": "216 80.4% 100%",active: "216 50% 15%","active-foreground": "216 98% 58%",- secondary: "220 3.7% 15.9%",+ secondary: "220 10% 15.9%","secondary-foreground": "220 0% 98%",- muted: "220 3.7% 15.9%",+ muted: "220 10% 15.9%","muted-foreground": "220 5% 64.9%",- accent: "220 3.7% 15.9%",+ accent: "220 10% 15.9%","accent-foreground": "0 0% 98%",destructive: "0 62.8% 30.6%","destructive-foreground": "0 85.7% 97.3%",- border: "220 3.7% 15.9%",- input: "220 3.7% 15.9%",+ border: "220 10% 15.9%",+ input: "220 10% 15.9%",ring: "216 71.8% 29.2%",},},