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 outside operation to bill of process and purchase order line
Brad Barbin93077dfefab0
diff --git a/apps/erp/app/components/Agent/Agent.tsx b/apps/erp/app/components/Agent/Agent.tsxindex 4b74409055..83e5adfbf6 100644--- a/apps/erp/app/components/Agent/Agent.tsx+++ b/apps/erp/app/components/Agent/Agent.tsx@@ -197,7 +197,7 @@ export function Agent() {});if (!tools?.data?.result) {- toast.error("Failed to fetch tools");+ // toast.error("Failed to fetch tools");return;}diff --git a/apps/erp/app/components/Form/SupplierProcess.tsx b/apps/erp/app/components/Form/SupplierProcess.tsxindex 1b3a9967ae..446268af5f 100644--- a/apps/erp/app/components/Form/SupplierProcess.tsx+++ b/apps/erp/app/components/Form/SupplierProcess.tsx@@ -38,6 +38,7 @@ const SupplierProcess = ({ref={triggerRef}options={options}{...props}+ // @ts-ignorelabel={props?.label ?? "Work Center"}onCreateOption={(option) => {newSupplierProcessModal.onOpen();@@ -82,3 +83,16 @@ export const useSupplierProcesses = (args: { processId?: string }) => {return supplierProcesses;};++export const SupplierProcessPreview = ({ processId, supplierProcessId }: { processId: string, supplierProcessId?: string }) => {+ const [suppliers] = useSuppliers();+ const supplierProcess = useSupplierProcesses({ processId: processId });++ if (!supplierProcessId) return null;+ const supplierId = supplierProcess.find((supplierProcess) => supplierProcess.id === supplierProcessId)?.supplierId;+ if(!supplierId) return null;++ const supplier = suppliers.find((supplier) => supplier.id === supplierId);++ return <span className="text-xs text-muted-foreground">{supplier?.name}</span>;+};\ No newline at end of filediff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsxindex a02d3f3f8d..e4ffeea971 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx@@ -115,6 +115,7 @@ import type { ConfigurationParameter, ConfigurationRule } from "../../types";import { ProcedureAttributeTypeIcon } from "~/components/Icons";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import Procedure from "~/components/Form/Procedure";+import { SupplierProcessPreview } from "~/components/Form/SupplierProcess";type Operation = z.infer<typeof methodOperationValidator> & {workInstruction: JSONContent | null;@@ -785,6 +786,7 @@ const BillOfProcess = ({<ConfigurationEditorconfiguration={configuration}open={configuratorDisclosure.isOpen}+ // @ts-ignoreparameters={parameters ?? []}onClose={configuratorDisclosure.onClose}/>@@ -2598,9 +2600,14 @@ function makeItem(return {id: operation.id!,title: (- <h3 className="font-semibold truncate cursor-pointer">- {operation.description}- </h3>+ <VStack spacing={0}>+ <h3 className="font-semibold truncate cursor-pointer">+ {operation.description}+ </h3>+ {operation.operationType === "Outside" && (+ <SupplierProcessPreview processId={operation.processId} supplierProcessId={operation.operationSupplierProcessId} />+ )}+ </VStack>),checked: false,order: operation.operationOrder,diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex eefe8448ae..71081566e6 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -458,6 +458,19 @@ export async function getJobOperationsByMethodId(.order("order", { ascending: true });}+export async function getOutsideOperationsByJobId(+ client: SupabaseClient<Database>,+ jobId: string,+ companyId: string+) {+ return client+ .from("jobOperation")+ .select("id, description")+ .eq("jobId", jobId)+ .eq("companyId", companyId)+ .eq("operationType", "Outside");+}+export async function getProcedure(client: SupabaseClient<Database>,id: stringdiff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsxindex 1f7daeff98..3a4ac83395 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx@@ -144,6 +144,7 @@ import { JobOperationStatus } from "./JobOperationStatus";import { ProcedureAttributeTypeIcon } from "~/components/Icons";import Procedure from "~/components/Form/Procedure";import { useNumberFormatter } from "@react-aria/i18n";+import { SupplierProcessPreview } from "~/components/Form/SupplierProcess";export type Operation = z.infer<typeof jobOperationValidator> & {assignee: string | null;@@ -187,11 +188,14 @@ function makeItem(return {id: operation.id!,title: (- <HStack>+ <VStack spacing={0}><h3 className="font-semibold truncate cursor-pointer">{operation.description}</h3>- </HStack>+ {operation.operationType === "Outside" && (+ <SupplierProcessPreview processId={operation.processId} supplierProcessId={operation.operationSupplierProcessId} />+ )}+ </VStack>),checked: false,order: operation.operationOrder,@@ -1848,12 +1852,7 @@ function OperationForm({return (acc += sp.minimumCost ?? 0);}, 0) / supplierProcesses.data.length: p.operationMinimumCost,- operationUnitCost:- supplierProcesses.data && supplierProcesses.data.length > 0- ? supplierProcesses.data.reduce((acc, sp) => {- return (acc += sp.minimumCost ?? 0);- }, 0) / supplierProcesses.data.length- : p.operationUnitCost,+ operationUnitCost: item.data.operationUnitCost ?? 0,operationLeadTime:supplierProcesses.data && supplierProcesses.data.length > 0? supplierProcesses.data.reduce((acc, sp) => {@@ -1906,7 +1905,7 @@ function OperationForm({setProcessData((d) => ({...d,operationMinimumCost: data?.minimumCost ?? 0,- operationUnitCost: data?.minimumCost ?? 0,+ operationUnitCost: 0, // TODO: get the unit cost from the purchase order historyoperationLeadTime: data?.leadTime ?? 0,}));};diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.tsindex b7df670bac..a91922247e 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts@@ -42,7 +42,7 @@ export const purchaseOrderLineType = ["Comment",] as const;-export const purchaseOrderTypeType = ["Purchase", "Return"] as const;+export const purchaseOrderTypeType = ["Purchase", "Outside Processing"] as const;export const purchaseOrderStatusType = ["Draft",@@ -58,6 +58,11 @@ export const purchaseOrderStatusType = [export const purchaseOrderValidator = z.object({id: zfd.text(z.string().optional()),purchaseOrderId: zfd.text(z.string().optional()),+ purchaseOrderType: z.enum(purchaseOrderTypeType, {+ errorMap: (issue, ctx) => ({+ message: "Type is required",+ }),+ }),supplierId: z.string().min(36, { message: "Supplier is required" }),supplierLocationId: zfd.text(z.string().optional()),supplierContactId: zfd.text(z.string().optional()),@@ -131,6 +136,8 @@ export const purchaseOrderLineValidator = zsupplierTaxAmount: zfd.numeric(z.number().optional()),locationId: zfd.text(z.string().optional()),shelfId: zfd.text(z.string().optional()),+ jobId: zfd.text(z.string().optional()),+ jobOperationId: zfd.text(z.string().optional()),exchangeRate: zfd.numeric(z.number().optional()),}).refine(diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex e737ad3451..6433e94bde 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -429,6 +429,13 @@ export async function getSupplierPayment(.single();}+export async function getSupplierProcessById(+ client: SupabaseClient<Database>,+ supplierProcessId: string+) {+ return client.from("supplierProcesses").select("*").eq("id", supplierProcessId).single();+}+export async function getSupplierProcessesByProcess(client: SupabaseClient<Database>,processId: stringdiff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm.tsxindex 0a25a3cf54..efd8865ab1 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm.tsx@@ -1,5 +1,5 @@import { useCarbon } from "@carbon/auth";-import { ValidatedForm } from "@carbon/form";+import { Select, ValidatedForm } from "@carbon/form";import {Card,CardContent,@@ -25,7 +25,7 @@ import {SupplierLocation,} from "~/components/Form";import { usePermissions } from "~/hooks";-import { purchaseOrderValidator } from "~/modules/purchasing";+import { purchaseOrderTypeType, purchaseOrderValidator } from "~/modules/purchasing";type PurchaseOrderFormValues = z.infer<typeof purchaseOrderValidator>;@@ -147,7 +147,10 @@ const PurchaseOrderForm = ({ initialValues }: PurchaseOrderFormProps) => {}}}/>-+ <Select name="purchaseOrderType" label="Type" options={purchaseOrderTypeType.map(type => ({+ label: type,+ value: type,+ }))} /><CustomFormFields table="purchaseOrder" /></div></VStack>@@ -169,3 +172,4 @@ const PurchaseOrderForm = ({ initialValues }: PurchaseOrderFormProps) => {};export default PurchaseOrderForm;+diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsxindex 32cffe723a..a175a00007 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx@@ -1,4 +1,5 @@import {+ Badge,Button,DropdownMenu,DropdownMenuContent,@@ -81,6 +82,11 @@ const PurchaseOrderHeader = () => {</Heading></Link><PurchasingStatus status={routeData?.purchaseOrder?.status} />+ {routeData?.purchaseOrder?.purchaseOrderType === "Outside Processing" && (+ <Badge variant="default">+ {routeData?.purchaseOrder?.purchaseOrderType}+ </Badge>+ )}</HStack><HStack><DropdownMenu>diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsxindex 9a85248d4f..2a5d86ac98 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx@@ -1,4 +1,5 @@import {+ Badge,cn,FormControl,FormLabel,@@ -12,13 +13,14 @@ import {ModalCardProvider,ModalCardTitle,useDisclosure,+ useMount,VStack,} from "@carbon/react";import { useCarbon } from "@carbon/auth";-import { ValidatedForm } from "@carbon/form";+import { Combobox, ValidatedForm } from "@carbon/form";import { useFetcher, useParams } from "@remix-run/react";-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import type { z } from "zod";import {ConversionFactor,@@ -38,6 +40,7 @@ import type { MethodItemType } from "~/modules/shared";import type { action } from "~/routes/x+/purchase-order+/$orderId.$lineId.details";import { path } from "~/utils/path";import DeletePurchaseOrderLine from "./DeletePurchaseOrderLine";+import { PostgrestResponse } from "@supabase/supabase-js";type PurchaseOrderLineFormProps = {initialValues: z.infer<typeof purchaseOrderLineValidator>;@@ -63,6 +66,7 @@ const PurchaseOrderLineForm = ({purchaseOrder: PurchaseOrder;}>(path.to.purchaseOrder(orderId));+ const isOutsideProcessing = routeData?.purchaseOrder?.purchaseOrderType === "Outside Processing";const isEditable = ["Draft"].includes(routeData?.purchaseOrder?.status ?? "");const [itemType, setItemType] = useState<MethodItemType>(@@ -282,8 +286,10 @@ const PurchaseOrderLineForm = ({: "New Purchase Order Line"}</ModalCardTitle><ModalCardDescription>- {isEditing- ? itemData?.description || itemType+ {isOutsideProcessing ?+ <Badge variant="default">Outside Processing</Badge> :+ isEditing ?+ itemData?.description || itemType: "A purchase order line contains order details for a particular item"}</ModalCardDescription></ModalCardHeader>@@ -328,6 +334,10 @@ const PurchaseOrderLineForm = ({/></FormControl>+ {isOutsideProcessing && (+ <JobOperationSelect jobId={initialValues.jobId} />+ )}+<NumberControlledminValue={itemData.minimumOrderQuantity}name="purchaseQuantity"@@ -440,7 +450,7 @@ const PurchaseOrderLineForm = ({"Tool","Consumable","Fixed Asset",- ].includes(itemType) && (+ ].includes(itemType) && !isOutsideProcessing && (<Locationname="locationId"label="Location"@@ -456,7 +466,7 @@ const PurchaseOrderLineForm = ({"Tool","Consumable","Fixed Asset",- ].includes(itemType) && (+ ].includes(itemType) && !isOutsideProcessing && (<Shelfname="shelfId"label="Shelf"@@ -521,3 +531,53 @@ const PurchaseOrderLineForm = ({};export default PurchaseOrderLineForm;+++function JobOperationSelect(initialValues: {jobId?: string}) {+ const [jobId, setJobId] = useState<string | null>(initialValues.jobId ?? null);++ const jobsFetcher = useFetcher<PostgrestResponse<{id: string; jobId: string}>>();+ useMount(() => {+ jobsFetcher.load(path.to.api.jobs);+ });+++ const jobOptions = useMemo(+ () =>+ jobsFetcher.data?.data+ ? jobsFetcher.data?.data.map((c) => ({+ value: c.id,+ label: c.jobId,+ }))+ : [],+ [jobsFetcher.data]+ );+++ const jobOperationFetcher = useFetcher<PostgrestResponse<{id: string; description: string}>>();+ useEffect(() => {+ if(jobId) {+ jobOperationFetcher.load(path.to.api.outsideOperations(jobId));+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [jobId]);++ const jobOperationOptions = useMemo(() => {+ return jobOperationFetcher.data?.data?.map((c) => ({+ value: c.id,+ label: c.description,+ })) ?? [];+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [jobOperationFetcher.data]);++ return (+ <>+ <Combobox name="jobId" label="Job" options={jobOptions} onChange={(value) => {+ if(value) {+ setJobId(value.value as string);+ }+ }} />+ <Combobox name="jobOperationId" label="Operation" options={jobOperationOptions} />+ </>+ );+}\ No newline at end of filediff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsxindex 0c819f82ae..f9745e95b0 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx@@ -107,6 +107,7 @@ import UnitOfMeasure, {} from "~/components/Form/UnitOfMeasure";import { ProcedureAttributeTypeIcon } from "~/components/Icons";import Procedure from "~/components/Form/Procedure";+import { SupplierProcessPreview } from "~/components/Form/SupplierProcess";export type Operation = z.infer<typeof quoteOperationValidator> & {workInstruction: JSONContent | null;@@ -157,9 +158,14 @@ function makeItem(return {id: operation.id!,title: (- <h3 className="font-semibold truncate cursor-pointer">- {operation.description}- </h3>+ <VStack spacing={0}>+ <h3 className="font-semibold truncate cursor-pointer">+ {operation.description}+ </h3>+ {operation.operationType === "Outside" && (+ <SupplierProcessPreview processId={operation.processId} supplierProcessId={operation.operationSupplierProcessId} />+ )}+ </VStack>),checked: false,order: operation.operationOrder,@@ -1623,11 +1629,7 @@ function OperationForm({}, 0) / supplierProcesses.data.length: p.operationMinimumCost,operationUnitCost:- supplierProcesses.data && supplierProcesses.data.length > 0- ? supplierProcesses.data.reduce((acc, sp) => {- return (acc += sp.minimumCost ?? 0);- }, 0) / supplierProcesses.data.length- : p.operationUnitCost,+ item.data.operationUnitCost ?? 0,operationLeadTime:supplierProcesses.data && supplierProcesses.data.length > 0? supplierProcesses.data.reduce((acc, sp) => {@@ -1680,7 +1682,7 @@ function OperationForm({setProcessData((d) => ({...d,operationMinimumCost: data?.minimumCost ?? 0,- operationUnitCost: data?.minimumCost ?? 0,+ operationUnitCost: 0, // TODO: get the unit cost from the purchase order historyoperationLeadTime: data?.leadTime ?? 0,}));};diff --git a/apps/erp/app/routes/api+/production.jobs.ts b/apps/erp/app/routes/api+/production.jobs.tsnew file mode 100644index 0000000000..0bca369ba0--- /dev/null+++ b/apps/erp/app/routes/api+/production.jobs.ts@@ -0,0 +1,12 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";+import { getJobsList } from "~/modules/production";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "production",+ });++ return json(await getJobsList(client, companyId));+}diff --git a/apps/erp/app/routes/api+/production.outside-operations.$jobId.ts b/apps/erp/app/routes/api+/production.outside-operations.$jobId.tsnew file mode 100644index 0000000000..d1d3837979--- /dev/null+++ b/apps/erp/app/routes/api+/production.outside-operations.$jobId.ts@@ -0,0 +1,37 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";+import { getOutsideOperationsByJobId } from "~/modules/production";+++export async function loader({ request, params }: LoaderFunctionArgs) {+ const authorized = await requirePermissions(request, {+ view: "production",+ });++ const { jobId } = params;++ if (!jobId)+ return json({+ data: [],+ });++ const operations = await getOutsideOperationsByJobId(+ authorized.client,+ jobId,+ authorized.companyId+ );+ if (operations.error) {+ return json(+ operations,+ await flash(+ request,+ error(operations.error, "Failed to get outside operations")+ )+ );+ }++ return json(operations);+}diff --git a/apps/erp/app/routes/api+/production.scrap-reasons.ts b/apps/erp/app/routes/api+/production.scrap-reasons.tsindex 6d0bf214c2..5f39710aca 100644--- a/apps/erp/app/routes/api+/production.scrap-reasons.ts+++ b/apps/erp/app/routes/api+/production.scrap-reasons.ts@@ -4,9 +4,7 @@ import { json } from "@vercel/remix";import { getScrapReasonsList } from "~/modules/production";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "production",- });+ const { client, companyId } = await requirePermissions(request, {});return json(await getScrapReasonsList(client, companyId));}diff --git a/apps/erp/app/routes/api+/purchasing.supplier-processes.$processId.ts b/apps/erp/app/routes/api+/purchasing.supplier-processes.$processId.tsnew file mode 100644index 0000000000..9a831851c7--- /dev/null+++ b/apps/erp/app/routes/api+/purchasing.supplier-processes.$processId.ts@@ -0,0 +1,65 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { ClientLoaderFunctionArgs } from "@remix-run/react";+import type { LoaderFunctionArgs, SerializeFrom } from "@vercel/remix";+import { json } from "@vercel/remix";+import { getSupplierProcessesByProcess } from "~/modules/purchasing";+import { supplierProcessesQuery } from "~/utils/react-query";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const authorized = await requirePermissions(request, {+ view: "purchasing",+ });++ const { processId } = params;++ if (!processId)+ return json({+ data: [],+ });++ const processes = await getSupplierProcessesByProcess(+ authorized.client,+ processId+ );+ if (processes.error) {+ return json(+ processes,+ await flash(+ request,+ error(processes.error, "Failed to get supplier processes")+ )+ );+ }++ return json(processes);+}++export async function clientLoader({+ serverLoader,+ params,+}: ClientLoaderFunctionArgs) {+ const { processId } = params;++ if (!processId) {+ return await serverLoader<typeof loader>();+ }++ const queryKey = supplierProcessesQuery(processId).queryKey;+ const data =+ window?.clientCache?.getQueryData<SerializeFrom<typeof loader>>(queryKey);++ console.log('clientLoader', queryKey, data);+++ if (!data) {++ const serverData = await serverLoader<typeof loader>();+ window?.clientCache?.setQueryData(queryKey, serverData);+ return serverData;+ }++ return data;+}+clientLoader.hydrate = true;diff --git a/apps/erp/app/routes/api+/purchasing.supplier-processes.ts b/apps/erp/app/routes/api+/purchasing.supplier-processes.tsdeleted file mode 100644index bc22ee144a..0000000000--- a/apps/erp/app/routes/api+/purchasing.supplier-processes.ts+++ /dev/null@@ -1,37 +0,0 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import type { LoaderFunctionArgs } from "@vercel/remix";-import { json } from "@vercel/remix";-import { getSupplierProcessesByProcess } from "~/modules/purchasing";--export async function loader({ request }: LoaderFunctionArgs) {- const authorized = await requirePermissions(request, {- view: "purchasing",- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const processId = searchParams.get("processId") as string;-- if (!processId || processId === "undefined")- return json({- data: [],- });-- const processes = await getSupplierProcessesByProcess(- authorized.client,- processId- );- if (processes.error) {- return json(- processes,- await flash(- request,- error(processes.error, "Failed to get supplier processes")- )- );- }-- return json(processes);-}diff --git a/apps/erp/app/routes/x+/purchase-order+/new.tsx b/apps/erp/app/routes/x+/purchase-order+/new.tsxindex 24c62f8643..6e9bf96364 100644--- a/apps/erp/app/routes/x+/purchase-order+/new.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/new.tsx@@ -8,7 +8,6 @@ import { redirect } from "@vercel/remix";import { useUrlParams } from "~/hooks";import type {PurchaseOrderStatus,- PurchaseOrderType,} from "~/modules/purchasing";import {purchaseOrderValidator,@@ -87,7 +86,7 @@ export default function PurchaseOrderNewRoute() {supplierId: supplierId ?? "",orderDate: today(getLocalTimeZone()).toString(),status: "Draft" as PurchaseOrderStatus,- type: "Purchase" as PurchaseOrderType,+ purchaseOrderType: "Purchase" as const,};return (diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.$id.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.$id.tsxindex dc6320aa50..0da23df7fa 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.$id.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.$id.tsx@@ -2,7 +2,7 @@ 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 { useNavigate, useParams } from "@remix-run/react";+import { ClientActionFunctionArgs, useNavigate, useParams } from "@remix-run/react";import type { ActionFunctionArgs } from "@vercel/remix";import { redirect } from "@vercel/remix";import { useRouteData } from "~/hooks";@@ -14,6 +14,7 @@ import {import SupplierProcessForm from "~/modules/purchasing/ui/Supplier/SupplierProcessForm";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";+import { supplierProcessesQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -57,6 +58,27 @@ export async function action({ request, params }: ActionFunctionArgs) {return redirect(path.to.supplierProcesses(supplierId));}+export async function clientAction({+ request,+ serverAction,+ params,+}: ClientActionFunctionArgs) {+ const formData = await await request.clone().formData(); // if we. don't clone it we can't access it in the action+ const validation = await validator(supplierProcessValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ if (validation.data.processId) {+ window.clientCache?.setQueryData(+ supplierProcessesQuery(validation.data.processId).queryKey,+ null+ );+ }+ return await serverAction();+}+export default function SupplierProcessRoute() {const { supplierId, id } = useParams();if (!supplierId) throw new Error("Could not find supplier id");diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsxindex b7bce96aa2..45cf310351 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx@@ -1,16 +1,18 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { useNavigate, useParams } from "@remix-run/react";+import { ClientActionFunctionArgs, useNavigate, useParams } from "@remix-run/react";import type { ActionFunctionArgs } from "@vercel/remix";import { redirect } from "@vercel/remix";import { ConfirmDelete } from "~/components/Modals";import { useRouteData } from "~/hooks";import {deleteSupplierProcess,+ getSupplierProcessById,type SupplierProcess,} from "~/modules/purchasing";import { path } from "~/utils/path";+import { supplierProcessesQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -37,6 +39,24 @@ export async function action({ request, params }: ActionFunctionArgs) {return redirect(path.to.supplierProcesses(supplierId));}+export async function clientAction({+ serverAction,+ params,+}: ClientActionFunctionArgs) {+ const { id } = params;+ if(id) {+ const serviceRole = getCarbonServiceRole();+ const supplierProcessId = await getSupplierProcessById(serviceRole, id);+ if (supplierProcessId.data?.processId) {+ window.clientCache?.setQueryData(+ supplierProcessesQuery(supplierProcessId.data.processId).queryKey,+ null+ );+ }+ }+ return await serverAction();+}+export default function DeleteSupplierProcessRoute() {const navigate = useNavigate();const { supplierId, id } = useParams();diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsxindex 690166a418..2b753d6f41 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsx@@ -2,7 +2,7 @@ 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 { useNavigate, useParams } from "@remix-run/react";+import { ClientActionFunctionArgs, useNavigate, useParams } from "@remix-run/react";import type { ActionFunctionArgs } from "@vercel/remix";import { json, redirect } from "@vercel/remix";import {@@ -12,6 +12,7 @@ import {import SupplierProcessForm from "~/modules/purchasing/ui/Supplier/SupplierProcessForm";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";+import { supplierProcessesQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -57,6 +58,27 @@ export async function action({ request, params }: ActionFunctionArgs) {: redirect(path.to.supplierProcesses(supplierId));}+export async function clientAction({+ request,+ serverAction,+ params,+}: ClientActionFunctionArgs) {+ const formData = await await request.clone().formData(); // if we. don't clone it we can't access it in the action+ const validation = await validator(supplierProcessValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ if (validation.data.processId) {+ window.clientCache?.setQueryData(+ supplierProcessesQuery(validation.data.processId).queryKey,+ null+ );+ }+ return await serverAction();+}+export default function NewSupplierProcessRoute() {const { supplierId } = useParams();const navigate = useNavigate();diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex dac40a2e67..d2cc817010 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -40,12 +40,15 @@ export const path = {groupsByType: (type?: string) =>generatePath(`${api}/users/groups?type=${type}`),item: (type: string) => generatePath(`${api}/item/${type}`),+ jobs: `${api}/production/jobs`,locations: `${api}/resources/locations`,itemPostingGroups: `${api}/items/groups`,materialForms: `${api}/items/forms`,materialSubstances: `${api}/items/substances`,messagingNotify: `${api}/messaging/notify`,modelUpload: `${api}/model/upload`,+ outsideOperations: (jobId: string) =>+ generatePath(`${api}/production/outside-operations/${jobId}`),purchasingKpi: (key: string) =>generatePath(`${api}/purchasing/kpi/${key}`),procedures: `${api}/production/procedures`,@@ -77,7 +80,7 @@ export const path = {supplierLocations: (id: string) =>generatePath(`${api}/purchasing/supplier-locations/${id}`),supplierProcesses: (id?: string) =>- generatePath(`${api}/purchasing/supplier-processes?processId=${id}`),+ generatePath(`${api}/purchasing/supplier-processes/${id}`),supplierStatuses: `${api}/purchasing/supplier-statuses`,supplierTypes: `${api}/purchasing/supplier-types`,tags: (table?: string) =>diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.tsindex bbf78c3813..d908ddcce9 100644--- a/apps/erp/app/utils/react-query.ts+++ b/apps/erp/app/utils/react-query.ts@@ -94,6 +94,11 @@ export const supplierLocationsQuery = (supplierId: string) => ({staleTime: RefreshRate.Low,});+export const supplierProcessesQuery = (processId: string) => ({+ queryKey: ["supplierProcesses", processId],+ staleTime: RefreshRate.Low,+});+export const supplierTypesQuery = (companyId: string | null) => ({queryKey: ["supplierTypes", companyId ?? "null"],staleTime: RefreshRate.Low,diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex d32af70581..15e9afb6cb 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -16578,6 +16578,12 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrderLine.taxPercent",},+ {+ $ref: "#/parameters/rowFilter.purchaseOrderLine.jobId",+ },+ {+ $ref: "#/parameters/rowFilter.purchaseOrderLine.jobOperationId",+ },{$ref: "#/parameters/select",},@@ -16763,6 +16769,12 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrderLine.taxPercent",},+ {+ $ref: "#/parameters/rowFilter.purchaseOrderLine.jobId",+ },+ {+ $ref: "#/parameters/rowFilter.purchaseOrderLine.jobOperationId",+ },{$ref: "#/parameters/preferReturn",},@@ -16902,6 +16914,12 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrderLine.taxPercent",},+ {+ $ref: "#/parameters/rowFilter.purchaseOrderLine.jobId",+ },+ {+ $ref: "#/parameters/rowFilter.purchaseOrderLine.jobOperationId",+ },{$ref: "#/parameters/body.purchaseOrderLine",},@@ -27159,6 +27177,9 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrder.supplierInteractionId",},+ {+ $ref: "#/parameters/rowFilter.purchaseOrder.purchaseOrderType",+ },{$ref: "#/parameters/select",},@@ -27293,6 +27314,9 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrder.supplierInteractionId",},+ {+ $ref: "#/parameters/rowFilter.purchaseOrder.purchaseOrderType",+ },{$ref: "#/parameters/preferReturn",},@@ -27381,6 +27405,9 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrder.supplierInteractionId",},+ {+ $ref: "#/parameters/rowFilter.purchaseOrder.purchaseOrderType",+ },{$ref: "#/parameters/body.purchaseOrder",},@@ -38943,6 +38970,9 @@ export default {{$ref: "#/parameters/rowFilter.purchaseOrders.supplierInteractionId",},+ {+ $ref: "#/parameters/rowFilter.purchaseOrders.purchaseOrderType",+ },{$ref: "#/parameters/rowFilter.purchaseOrders.thumbnailPath",},@@ -55903,6 +55933,18 @@ export default {format: "numeric",type: "number",},+ jobId: {+ description:+ "Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",+ format: "text",+ type: "string",+ },+ jobOperationId: {+ description:+ "Note:\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",+ format: "text",+ type: "string",+ },},type: "object",},@@ -60394,6 +60436,7 @@ export default {"createdAt","createdBy","supplierInteractionId",+ "purchaseOrderType",],properties: {id: {@@ -60532,6 +60575,12 @@ export default {format: "text",type: "string",},+ purchaseOrderType: {+ default: "Purchase",+ enum: ["Purchase", "Return", "Outside Processing"],+ format: 'public."purchaseOrderType"',+ type: "string",+ },},type: "object",},@@ -66373,6 +66422,11 @@ export default {format: "text",type: "string",},+ purchaseOrderType: {+ enum: ["Purchase", "Return", "Outside Processing"],+ format: 'public."purchaseOrderType"',+ type: "string",+ },thumbnailPath: {format: "text",type: "string",@@ -77476,6 +77530,18 @@ export default {in: "query",type: "string",},+ "rowFilter.purchaseOrderLine.jobId": {+ name: "jobId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.purchaseOrderLine.jobOperationId": {+ name: "jobOperationId",+ required: false,+ in: "query",+ type: "string",+ },"body.accountDefault": {name: "accountDefault",description: "accountDefault",@@ -82639,6 +82705,12 @@ export default {in: "query",type: "string",},+ "rowFilter.purchaseOrder.purchaseOrderType": {+ name: "purchaseOrderType",+ required: false,+ in: "query",+ type: "string",+ },"body.salesOrderLines": {name: "salesOrderLines",description: "salesOrderLines",@@ -89347,6 +89419,12 @@ export default {in: "query",type: "string",},+ "rowFilter.purchaseOrders.purchaseOrderType": {+ name: "purchaseOrderType",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.purchaseOrders.thumbnailPath": {name: "thumbnailPath",required: false,diff --git a/packages/database/supabase/migrations/20250330231242_purchase-outside-service.sql b/packages/database/supabase/migrations/20250330231242_purchase-outside-service.sqlindex b9523c3d58..5702fb183f 100644--- a/packages/database/supabase/migrations/20250330231242_purchase-outside-service.sql+++ b/packages/database/supabase/migrations/20250330231242_purchase-outside-service.sql@@ -1,3 +1,45 @@ALTER TYPE "purchaseOrderType" ADD VALUE 'Outside Processing';-ALTER TABLE "purchaseOrder" ADD COLUMN "purchaseOrderType" "purchaseOrderType" NOT NULL DEFAULT 'Purchase';\ No newline at end of file+ALTER TABLE "purchaseOrder" ADD COLUMN "purchaseOrderType" "purchaseOrderType" NOT NULL DEFAULT 'Purchase';++ALTER TABLE "purchaseOrderLine" ADD COLUMN "jobId" TEXT;+ALTER TABLE "purchaseOrderLine" ADD CONSTRAINT "purchaseOrderLine_jobId_fkey" FOREIGN KEY ("jobId") REFERENCES "job" ("id") ON DELETE SET NULL ON UPDATE CASCADE;++ALTER TABLE "purchaseOrderLine" ADD COLUMN "jobOperationId" TEXT;+ALTER TABLE "purchaseOrderLine" ADD CONSTRAINT "purchaseOrderLine_jobOperationId_fkey" FOREIGN KEY ("jobOperationId") REFERENCES "jobOperation" ("id") ON DELETE SET NULL ON UPDATE CASCADE;++DROP VIEW IF EXISTS "purchaseOrders";+CREATE OR REPLACE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS+ SELECT+ p.*,+ pl."thumbnailPath",+ pl."itemType",+ pl."orderTotal" + pd."supplierShippingCost" * p."exchangeRate" AS "orderTotal",+ pd."shippingMethodId",+ pd."shippingTermId",+ pd."receiptRequestedDate",+ pd."receiptPromisedDate",+ pd."deliveryDate",+ pd."dropShipment",+ pp."paymentTermId",+ pd."locationId",+ pd."supplierShippingCost"+ FROM "purchaseOrder" p+ LEFT JOIN (+ SELECT+ pol."purchaseOrderId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(COALESCE(pol."purchaseQuantity", 0)*(COALESCE(pol."unitPrice", 0)) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)) AS "orderTotal",+ MIN(i."type") AS "itemType"+ FROM "purchaseOrderLine" pol+ LEFT JOIN "item" i+ ON i."id" = pol."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY pol."purchaseOrderId"+ ) pl ON pl."purchaseOrderId" = p."id"+ LEFT JOIN "purchaseOrderDelivery" pd ON pd."id" = p."id"+ LEFT JOIN "shippingTerm" st ON st."id" = pd."shippingTermId"+ LEFT JOIN "purchaseOrderPayment" pp ON pp."id" = p."id";\ No newline at end of filediff --git a/packages/form/src/components/CreatableCombobox.tsx b/packages/form/src/components/CreatableCombobox.tsxindex b031c8cc57..fbe35485ec 100644--- a/packages/form/src/components/CreatableCombobox.tsx+++ b/packages/form/src/components/CreatableCombobox.tsx@@ -17,7 +17,7 @@ export type CreatableComboboxProps = Omit<> & {autoSelectSingleOption?: boolean;name: string;- label?: string;+ label: string | JSX.Element;helperText?: string;isConfigured?: boolean;isOptional?: boolean;