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 chart for demand
Brad Barbin84e7e82ba022
diff --git a/.env.example b/.env.exampleindex 3fed80c80e..48c01a5ce5 100644--- a/.env.example+++ b/.env.example@@ -1,3 +1,5 @@+DEFAULT_EMAIL_ADDRESS="[email protected]"+NOVU_APPLICATION_ID="********************"NOVU_SECRET_KEY="********************"diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryDetails.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryDetails.tsxindex ace7ec9835..355bcaf648 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryDetails.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryDetails.tsx@@ -6,6 +6,7 @@ import {VStack,} from "@carbon/react";import { useLocale } from "@react-aria/i18n";+import { LuMoveDown, LuMoveUp } from "react-icons/lu";import type { z } from "zod";import type {ItemQuantities,@@ -78,10 +79,20 @@ const InventoryDetails = ({<CardDescription><VStack>Quantity on Production Order</VStack></CardDescription>- <CardTitle className="text-4xl">- {`${formatter.format(- quantities?.quantityOnProductionOrder ?? 0- )}`}+ <CardTitle className="text-4xl flex items-start justify-start gap-2">+ <div className="flex justify-start items-center gap-1">+ <span>{`${formatter.format(+ quantities?.quantityOnProductionOrder ?? 0+ )}`}</span>+ <LuMoveUp className="text-emerald-500 text-lg" />+ </div>++ <div className="flex justify-start items-center gap-1">+ <span>{`${formatter.format(+ quantities?.quantityOnProductionDemand ?? 0+ )}`}</span>+ <LuMoveDown className="text-red-500 text-lg" />+ </div></CardTitle></CardHeader></Card>diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsxindex 6f1ca74f10..34ced4ee7f 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx@@ -268,7 +268,7 @@ const InventoryTable = memo(isDisabled={mrpFetcher.state !== "idle"}isLoading={mrpFetcher.state !== "idle"}>- MRP+ Recalculate</Button></TooltipTrigger><TooltipContent>diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsxindex 5b46980979..8dd770f7e0 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx@@ -157,7 +157,7 @@ const PurchaseInvoiceLineForm = ({carbon.from("item").select(- "name, readableIdWithRevision, type, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"+ "name, readableIdWithRevision, type, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, leadTime)").eq("id", itemId).eq("companyId", company.id)diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex acc9c5a91c..9c3009b733 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -412,6 +412,15 @@ export const itemCostValidator = z.object({// costIsAdjusted: zfd.checkbox(),});+export const itemManufacturingValidator = z.object({+ itemId: z.string().min(1, { message: "Item ID is required" }),+ // manufacturingBlocked: zfd.checkbox(),+ requiresConfiguration: zfd.checkbox().optional(),+ lotSize: zfd.numeric(z.number().min(0)),+ scrapPercentage: zfd.numeric(z.number().min(0)),+ leadTime: zfd.numeric(z.number().min(0)),+});+export const itemPostingGroupValidator = z.object({id: zfd.text(z.string().optional()),name: z.string().min(1, { message: "Name is required" }).max(255),@@ -430,7 +439,6 @@ export const itemPlanningValidator = z.object({safetyStockQuantity: zfd.numeric(z.number().min(0).optional()),safetyStockLeadTime: zfd.numeric(z.number().min(0).optional()),demandAccumulationPeriod: zfd.numeric(z.number().min(0).optional()),- demandReschedulingPeriod: zfd.numeric(z.number().min(0).optional()),demandAccumulationIncludesInventory: zfd.checkbox().optional(),reorderPoint: zfd.numeric(z.number().min(0).optional()).optional(),reorderQuantity: zfd.numeric(z.number().min(0)).optional(),@@ -446,7 +454,7 @@ export const itemPurchasingValidator = z.object({conversionFactor: zfd.numeric(z.number().min(0)),leadTime: zfd.numeric(z.number().min(0)),purchasingUnitOfMeasureCode: zfd.text(z.string().optional()),- purchasingBlocked: zfd.checkbox(),+ // purchasingBlocked: zfd.checkbox(),});export const itemUnitSalePriceValidator = z.object({@@ -479,14 +487,6 @@ export const partValidator = itemValidator.merge(}));-export const partManufacturingValidator = z.object({- itemId: z.string().min(1, { message: "Item ID is required" }),- // manufacturingBlocked: zfd.checkbox(),- requiresConfiguration: zfd.checkbox(),- lotSize: zfd.numeric(z.number().min(0)),- scrapPercentage: zfd.numeric(z.number().min(0)),-});-export const pickMethodValidator = z.object({itemId: z.string().min(1, { message: "Item ID is required" }),locationId: z.string().min(20, { message: "Location is required" }),diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 31a2eb2901..a5661e3ca0 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -21,6 +21,7 @@ import type {customerPartValidator,getMethodValidator,itemCostValidator,+ itemManufacturingValidator,itemPlanningValidator,itemPostingGroupValidator,itemPurchasingValidator,@@ -32,7 +33,6 @@ import type {materialValidator,methodMaterialValidator,methodOperationValidator,- partManufacturingValidator,partValidator,pickMethodValidator,serviceValidator,@@ -433,6 +433,29 @@ export async function getItemCustomerParts(.eq("companyId", companyId);}+export async function getItemDemand(+ client: SupabaseClient<Database>,+ {+ itemId,+ locationId,+ periods,+ companyId,+ }: {+ itemId: string;+ locationId: string;+ periods: string[];+ companyId: string;+ }+) {+ return client+ .from("demandActual")+ .select("*")+ .eq("itemId", itemId)+ .eq("locationId", locationId)+ .eq("companyId", companyId)+ .in("periodId", periods);+}+export async function getItemFiles(client: SupabaseClient<Database>,itemId: string,@@ -648,101 +671,6 @@ export async function getMaterialUsedIn(};}-export async function getPartUsedIn(- client: SupabaseClient<Database>,- itemId: string,- companyId: string-) {- const [- jobMaterials,- jobs,- methodMaterials,- purchaseOrderLines,- receiptLines,- quoteLines,- quoteMaterials,- salesOrderLines,- shipmentLines,- supplierQuotes,- ] = await Promise.all([- client- .from("jobMaterial")- .select("id, methodType, ...job(documentReadableId:jobId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("job")- .select("id, documentReadableId:jobId")- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("methodMaterial")- .select(- "id, methodType, ...makeMethod!makeMethodId(documentId:id, version, ...item(documentReadableId:readableIdWithRevision, documentParentId:id, itemType:type))"- )- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("purchaseOrderLine")- .select(- "id, ...purchaseOrder(documentReadableId:purchaseOrderId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("receiptLine")- .select("id, ...receipt(documentReadableId:receiptId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("quoteLine")- .select(- "id, methodType, ...quote(documentReadableId:quoteId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("quoteMaterial")- .select(- "id, methodType, documentParentId:quoteId, documentId:quoteLineId, ...quoteLine(documentReadableId:itemReadableId)"- )- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("salesOrderLine")- .select(- "id, methodType, ...salesOrder(documentReadableId:salesOrderId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("shipmentLine")- .select("id, ...shipment(documentReadableId:shipmentId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("supplierQuoteLine")- .select(- "id, ...supplierQuote(documentReadableId:supplierQuoteId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId),- ]);-- return {- jobMaterials: jobMaterials.data ?? [],- jobs: jobs.data ?? [],- methodMaterials: methodMaterials.data ?? [],- purchaseOrderLines: purchaseOrderLines.data ?? [],- receiptLines: receiptLines.data ?? [],- quoteLines: quoteLines.data ?? [],- quoteMaterials: quoteMaterials.data ?? [],- salesOrderLines: salesOrderLines.data ?? [],- shipmentLines: shipmentLines.data ?? [],- supplierQuotes: supplierQuotes.data ?? [],- };-}-export async function getMakeMethods(client: SupabaseClient<Database>,itemId: string,@@ -1129,6 +1057,113 @@ export async function getPartsList(return query.order("name");}+export async function getPartUsedIn(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+) {+ const [+ jobMaterials,+ jobs,+ methodMaterials,+ purchaseOrderLines,+ receiptLines,+ quoteLines,+ quoteMaterials,+ salesOrderLines,+ shipmentLines,+ supplierQuotes,+ ] = await Promise.all([+ client+ .from("jobMaterial")+ .select("id, methodType, ...job(documentReadableId:jobId, documentId:id)")+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("job")+ .select("id, documentReadableId:jobId")+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("methodMaterial")+ .select(+ "id, methodType, ...makeMethod!makeMethodId(documentId:id, version, ...item(documentReadableId:readableIdWithRevision, documentParentId:id, itemType:type))"+ )+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("purchaseOrderLine")+ .select(+ "id, ...purchaseOrder(documentReadableId:purchaseOrderId, documentId:id)"+ )+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("receiptLine")+ .select("id, ...receipt(documentReadableId:receiptId, documentId:id)")+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("quoteLine")+ .select(+ "id, methodType, ...quote(documentReadableId:quoteId, documentId:id)"+ )+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("quoteMaterial")+ .select(+ "id, methodType, documentParentId:quoteId, documentId:quoteLineId, ...quoteLine(documentReadableId:itemReadableId)"+ )+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("salesOrderLine")+ .select(+ "id, methodType, ...salesOrder(documentReadableId:salesOrderId, documentId:id)"+ )+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("shipmentLine")+ .select("id, ...shipment(documentReadableId:shipmentId, documentId:id)")+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ client+ .from("supplierQuoteLine")+ .select(+ "id, ...supplierQuote(documentReadableId:supplierQuoteId, documentId:id)"+ )+ .eq("itemId", itemId)+ .eq("companyId", companyId),+ ]);++ return {+ jobMaterials: jobMaterials.data ?? [],+ jobs: jobs.data ?? [],+ methodMaterials: methodMaterials.data ?? [],+ purchaseOrderLines: purchaseOrderLines.data ?? [],+ receiptLines: receiptLines.data ?? [],+ quoteLines: quoteLines.data ?? [],+ quoteMaterials: quoteMaterials.data ?? [],+ salesOrderLines: salesOrderLines.data ?? [],+ shipmentLines: shipmentLines.data ?? [],+ supplierQuotes: supplierQuotes.data ?? [],+ };+}++export async function getPeriods(+ client: SupabaseClient<Database>,+ { startDate, endDate }: { startDate: string; endDate: string }+) {+ const endWithTime = endDate.includes("T") ? endDate : `${endDate}T23:59:59`;+ return client+ .from("period")+ .select("*")+ .gte("startDate", startDate)+ .lte("endDate", endWithTime);+}+export async function getPickMethod(client: SupabaseClient<Database>,itemId: string,@@ -1851,7 +1886,7 @@ export async function upsertPickMethod(export async function upsertItemManufacturing(client: SupabaseClient<Database>,- partManufacturing: z.infer<typeof partManufacturingValidator> & {+ partManufacturing: z.infer<typeof itemManufacturingValidator> & {updatedBy: string;customFields?: Json;}diff --git a/apps/erp/app/modules/items/ui/Consumables/useConsumableNavigation.tsx b/apps/erp/app/modules/items/ui/Consumables/useConsumableNavigation.tsxindex 078de2a94a..11f31cac84 100644--- a/apps/erp/app/modules/items/ui/Consumables/useConsumableNavigation.tsx+++ b/apps/erp/app/modules/items/ui/Consumables/useConsumableNavigation.tsx@@ -1,6 +1,12 @@import { useParams } from "@remix-run/react";-import { LuBox, LuFileText, LuShoppingCart, LuTags } from "react-icons/lu";+import {+ LuBox,+ LuChartLine,+ LuFileText,+ LuShoppingCart,+ LuTags,+} from "react-icons/lu";import { usePermissions, useRouteData } from "~/hooks";import type { Role } from "~/types";import { path } from "~/utils/path";@@ -42,13 +48,13 @@ export function useConsumableNavigation() {icon: LuTags,shortcut: "Command+Shift+c",},- // {- // name: "Planning",- // to: path.to.consumablePlanning(itemId),- // role: ["employee"],- // icon: LuFileBarChart,- // shortcut: "Command+Shift+p",- // },+ {+ name: "Planning",+ to: path.to.consumablePlanning(itemId),+ role: ["employee"],+ icon: LuChartLine,+ shortcut: "Command+Shift+p",+ },{name: "Inventory",to: path.to.consumableInventory(itemId),diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsxindex e539f29afd..dceb6da81c 100644--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx@@ -112,14 +112,16 @@ const BoMExplorer = ({const node = methods.find((m) => m.data.methodMaterialId === selectedMaterialId);- selectNode(node?.id ?? methods[0].id);+ if (node) {+ selectNode(node.id);+ }} else if (params.makeMethodId) {const node = methods.find((m) => m.data.materialMakeMethodId === params.makeMethodId);- selectNode(node?.id ?? methods[0].id);- } else if (methods?.length > 0) {- selectNode(methods[0].id);+ if (node) {+ selectNode(node.id);+ }}});diff --git a/apps/erp/app/modules/items/ui/Item/ItemDemandChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemDemandChart.tsxnew file mode 100644index 0000000000..384fd38ade--- /dev/null+++ b/apps/erp/app/modules/items/ui/Item/ItemDemandChart.tsx@@ -0,0 +1,174 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Loading,+ useMount,+} from "@carbon/react";+import type { ChartConfig } from "@carbon/react/Chart";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@carbon/react/Chart";+import { getLocalTimeZone, parseDate } from "@internationalized/date";+import { useDateFormatter } from "@react-aria/i18n";+import { useFetcher } from "@remix-run/react";++import { useMemo } from "react";+import { Bar, BarChart, CartesianGrid, Line, XAxis, YAxis } from "recharts";+import type { loader as forecastLoader } from "~/routes/api+/items.$id.$locationId.forecast";+import { path } from "~/utils/path";++interface DemandData {+ actualQuantity: number;+ companyId: string;+ createdAt: string;+ createdBy: string;+ itemId: string;+ locationId: string;+ notes: string | null;+ periodId: string;+ sourceType: "Sales Order" | "Job Material";+ updatedAt: string;+ updatedBy: string;+}++interface ChartDataPoint {+ startDate: string;+ period: string;+ "Sales Order": number;+ "Job Material": number;+ forecast: number;+}++export const ItemDemandChart = ({+ itemId,+ locationId,+}: {+ itemId: string;+ locationId: string;+}) => {+ const forecastFetcher = useFetcher<typeof forecastLoader>();+ const isFetching = forecastFetcher.state !== "idle" || !forecastFetcher.data;++ const dateFormatter = useDateFormatter({+ month: "short",+ day: "numeric",+ });++ useMount(() => {+ forecastFetcher.load(path.to.api.itemForecast(itemId, locationId));+ });++ const chartData = useMemo(() => {+ if (!forecastFetcher.data?.demand || !forecastFetcher.data?.periods)+ return [];++ const periods = forecastFetcher.data.periods;+ const demand = forecastFetcher.data.demand;+ const forecast = forecastFetcher.data?.forecast ?? 5;++ // Initialize all periods with zero values+ const groupedData = periods.reduce(+ (acc: Record<string, ChartDataPoint>, period) => {+ acc[period.id] = {+ period: period.id,+ startDate: period.startDate,+ "Sales Order": 0,+ "Job Material": 0,+ forecast,+ };+ return acc;+ },+ {}+ );++ // Add demand data+ demand.forEach((curr: DemandData) => {+ if (groupedData[curr.periodId]) {+ groupedData[curr.periodId][curr.sourceType] += curr.actualQuantity;+ }+ });++ return Object.values(groupedData).sort(+ (a, b) =>+ new Date(a.startDate).getTime() - new Date(b.startDate).getTime()+ );+ }, [+ forecastFetcher.data?.demand,+ forecastFetcher.data?.periods,+ forecastFetcher.data?.forecast,+ ]);++ const sourceTypes = useMemo(() => {+ if (!forecastFetcher.data?.demand) return [];+ return [+ ...new Set(+ forecastFetcher.data.demand.map((item: DemandData) => item.sourceType)+ ),+ ];+ }, [forecastFetcher.data?.demand]);++ const chartConfig = {} satisfies ChartConfig;++ return (+ <Card>+ <CardHeader>+ <CardTitle>Demand</CardTitle>+ </CardHeader>+ <CardContent>+ <div className="min-h-[200px] max-h-[360px]">+ <Loading isLoading={isFetching}>+ <ChartContainer config={chartConfig} className="w-full h-full">+ <BarChart data={chartData}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="startDate"+ tickLine={false}+ axisLine={false}+ tickFormatter={(value) =>+ dateFormatter.format(+ parseDate(value).toDate(getLocalTimeZone())+ )+ }+ />+ <YAxis tickLine={false} axisLine={false} />+ <ChartTooltip+ content={+ <ChartTooltipContent+ labelFormatter={(value) =>+ `Week of ${dateFormatter.format(+ parseDate(value).toDate(getLocalTimeZone())+ )}`+ }+ />+ }+ />+ {sourceTypes.map((sourceType: string, index: number) => (+ <Bar+ key={sourceType}+ dataKey={sourceType}+ stackId="demand"+ className={+ sourceType === "Sales Order"+ ? "fill-violet-600"+ : "fill-teal-500"+ }+ />+ ))}+ <Line+ type="monotone"+ dataKey="forecast"+ stroke="#ff7300"+ strokeWidth={2}+ />+ </BarChart>+ </ChartContainer>+ </Loading>+ </div>+ </CardContent>+ </Card>+ );+};diff --git a/apps/erp/app/modules/items/ui/Parts/PartManufacturingForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsxsimilarity index 68%rename from apps/erp/app/modules/items/ui/Parts/PartManufacturingForm.tsxrename to apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsxindex 88191c9855..7bb09336be 100644--- a/apps/erp/app/modules/items/ui/Parts/PartManufacturingForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx@@ -18,15 +18,17 @@ import {import { usePermissions } from "~/hooks";import type { action } from "~/routes/x+/part+/$itemId.manufacturing.$methodId.method";-import { partManufacturingValidator } from "../../items.models";+import { itemManufacturingValidator } from "../../items.models";-type PartManufacturingFormProps = {- initialValues: z.infer<typeof partManufacturingValidator>;+type ItemManufacturingFormProps = {+ initialValues: z.infer<typeof itemManufacturingValidator>;+ withConfiguration?: boolean;};-const PartManufacturingForm = ({+const ItemManufacturingForm = ({initialValues,-}: PartManufacturingFormProps) => {+ withConfiguration = true,+}: ItemManufacturingFormProps) => {const fetcher = useFetcher<typeof action>();const permissions = usePermissions();const { itemId } = useParams();@@ -37,7 +39,7 @@ const PartManufacturingForm = ({<Card><ValidatedFormmethod="post"- validator={partManufacturingValidator}+ validator={itemManufacturingValidator}defaultValues={initialValues}fetcher={fetcher}>@@ -55,19 +57,24 @@ const PartManufacturingForm = ({style: "percent",}}/>+ <Number name="leadTime" label="Lead Time (Days)" />{/* <Booleanname="manufacturingBlocked"label="Manufacturing Blocked"/> */}+ <div className="col-span-2" />- <Boolean- name="requiresConfiguration"- label="Requires Configuration"- />+ {withConfiguration && (+ <Boolean+ name="requiresConfiguration"+ label=""+ description="Use parameters to generate the Bill of Materials and Bill of Process"+ />+ )}<CustomFormFields table="partReplenishment" /></div></CardContent>- <CardFooter>+ <CardFooter className="flex justify-between"><SubmitwithBlocker={false}isDisabled={!permissions.can("update", "parts")}@@ -80,4 +87,4 @@ const PartManufacturingForm = ({);};-export default PartManufacturingForm;+export default ItemManufacturingForm;diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsxindex 2eaf9f421f..b56cfab01d 100644--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx@@ -121,15 +121,6 @@ const ItemPlanningForm = ({label="Demand Accumulation Period (Days)"minValue={0}/>- <Number- name="demandReschedulingPeriod"- label="Rescheduling Period (Days)"- minValue={0}- />- <Boolean- name="demandAccumulationIncludesInventory"- label="Demand Includes Inventory"- /></>)}{policy === "Fixed Reorder Quantity" && (@@ -150,6 +141,14 @@ const ItemPlanningForm = ({<Number name="orderMultiple" label="Order Multiple" minValue={0} /><Boolean name="critical" label="Critical" />+ {policy === "Demand-Based Reorder" && (+ <>+ <Boolean+ name="demandAccumulationIncludesInventory"+ label="Demand Includes Inventory"+ />+ </>+ )}<CustomFormFields table="partPlanning" /></div></CardContent>diff --git a/apps/erp/app/modules/items/ui/Item/ItemPurchasingForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemPurchasingForm.tsxindex 742dfd72f4..8a5098f01f 100644--- a/apps/erp/app/modules/items/ui/Item/ItemPurchasingForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemPurchasingForm.tsx@@ -10,7 +10,6 @@ import { useParams } from "@remix-run/react";import { useState } from "react";import type { z } from "zod";import {- Boolean,ConversionFactor,Hidden,Number,@@ -74,7 +73,7 @@ const ItemPurchasingForm = ({label="Preferred Supplier"options={allowedSuppliersOptions}/>- <Number name="purchasingLeadTime" label="Lead Time (Days)" />+ <Number name="leadTime" label="Lead Time (Days)" /><UnitOfMeasurename="purchasingUnitOfMeasureCode"label="Purchasing Unit of Measure"@@ -88,7 +87,7 @@ const ItemPurchasingForm = ({purchasingCode={purchasingCode ?? undefined}inventoryCode={inventoryCode ?? undefined}/>- <Boolean name="purchasingBlocked" label="Purchasing Blocked" />+ {/* <Boolean name="purchasingBlocked" label="Purchasing Blocked" /> */}</div></CardContent><CardFooter>diff --git a/apps/erp/app/modules/items/ui/Materials/useMaterialNavigation.tsx b/apps/erp/app/modules/items/ui/Materials/useMaterialNavigation.tsxindex 652def69f0..aa6ea24e26 100644--- a/apps/erp/app/modules/items/ui/Materials/useMaterialNavigation.tsx+++ b/apps/erp/app/modules/items/ui/Materials/useMaterialNavigation.tsx@@ -1,6 +1,12 @@import { useParams } from "@remix-run/react";-import { LuBox, LuFileText, LuShoppingCart, LuTags } from "react-icons/lu";+import {+ LuBox,+ LuChartLine,+ LuFileText,+ LuShoppingCart,+ LuTags,+} from "react-icons/lu";import { usePermissions, useRouteData } from "~/hooks";import type { Role } from "~/types";import { path } from "~/utils/path";@@ -42,13 +48,13 @@ export function useMaterialNavigation() {icon: LuTags,shortcut: "Command+Shift+c",},- // {- // name: "Planning",- // to: path.to.materialPlanning(itemId),- // role: ["employee"],- // icon: LuFileBarChart,- // shortcut: "Command+Shift+p",- // },+ {+ name: "Planning",+ to: path.to.materialPlanning(itemId),+ role: ["employee"],+ icon: LuChartLine,+ shortcut: "Command+Shift+p",+ },{name: "Inventory",to: path.to.materialInventory(itemId),diff --git a/apps/erp/app/modules/items/ui/Parts/index.ts b/apps/erp/app/modules/items/ui/Parts/index.tsindex d6aeb6e9f0..af1e30a74b 100644--- a/apps/erp/app/modules/items/ui/Parts/index.ts+++ b/apps/erp/app/modules/items/ui/Parts/index.ts@@ -1,7 +1,6 @@import ConfigurationParametersForm from "./ConfigurationParameters";import PartForm from "./PartForm";import PartHeader from "./PartHeader";-import PartManufacturingForm from "./PartManufacturingForm";import PartProperties from "./PartProperties";import PartsTable from "./PartsTable";@@ -9,7 +8,6 @@ export {ConfigurationParametersForm,PartForm,PartHeader,- PartManufacturingForm,PartProperties,PartsTable,};diff --git a/apps/erp/app/modules/items/ui/Parts/usePartNavigation.tsx b/apps/erp/app/modules/items/ui/Parts/usePartNavigation.tsxindex 8919be8135..fb2049aac5 100644--- a/apps/erp/app/modules/items/ui/Parts/usePartNavigation.tsx+++ b/apps/erp/app/modules/items/ui/Parts/usePartNavigation.tsx@@ -2,6 +2,7 @@ import { useParams } from "@remix-run/react";import {LuBox,+ LuChartLine,LuFactory,LuFileText,LuReceipt,@@ -69,13 +70,13 @@ export function usePartNavigation() {icon: LuTags,shortcut: "Command+Shift+a",},- // {- // name: "Planning",- // to: path.to.partPlanning(itemId),- // role: ["employee"],- // icon: LuFileBarChart,- // shortcut: "Command+Shift+p",- // },+ {+ name: "Planning",+ to: path.to.partPlanning(itemId),+ role: ["employee"],+ icon: LuChartLine,+ shortcut: "Command+Shift+p",+ },{name: "Sales",to: path.to.partSales(itemId),diff --git a/apps/erp/app/modules/items/ui/Tools/useToolNavigation.tsx b/apps/erp/app/modules/items/ui/Tools/useToolNavigation.tsxindex d8f889db45..f424083e29 100644--- a/apps/erp/app/modules/items/ui/Tools/useToolNavigation.tsx+++ b/apps/erp/app/modules/items/ui/Tools/useToolNavigation.tsx@@ -2,6 +2,7 @@ import { useParams } from "@remix-run/react";import {LuBox,+ LuChartLine,LuFactory,LuFileText,LuShoppingCart,@@ -60,13 +61,13 @@ export function useToolNavigation() {icon: LuTags,shortcut: "Command+Shift+c",},- // {- // name: "Planning",- // to: path.to.toolPlanning(itemId),- // role: ["employee"],- // icon: LuFileBarChart,- // shortcut: "Command+Shift+p",- // },+ {+ name: "Planning",+ to: path.to.toolPlanning(itemId),+ role: ["employee"],+ icon: LuChartLine,+ shortcut: "Command+Shift+p",+ },{name: "Inventory",to: path.to.toolInventory(itemId),diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex e17854498d..b1712d2689 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -853,7 +853,7 @@ export async function recalculateJobMakeMethodRequirements(export async function runMRP(client: SupabaseClient<Database>,params: {- type: "company" | "job" | "salesOrder";+ type: "company" | "job" | "salesOrder" | "item" | "purchaseOrder";id: string;companyId: string;userId: string;diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsxindex 060e7979d7..81fa076a6f 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx@@ -98,14 +98,16 @@ const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {const node = method.find((m) => m.data.methodMaterialId === selectedMaterialId);- selectNode(node?.id ?? method[0].id);+ if (node) {+ selectNode(node.id);+ }} else if (methodId) {const node = method.find((m) => m.data.jobMaterialMakeMethodId === methodId);- selectNode(node?.id ?? method[0].id);- } else if (method?.length > 0) {- selectNode(method[0].id);+ if (node) {+ selectNode(node.id);+ }}// eslint-disable-next-line react-hooks/exhaustive-deps}, [selectedMaterialId, methodId]);diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsxindex a9833d3ca1..9e09e2281c 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx@@ -173,7 +173,7 @@ const PurchaseOrderLineForm = ({carbon.from("item").select(- "name, readableIdWithRevision, type, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"+ "name, readableIdWithRevision, type, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, leadTime)").eq("id", itemId).eq("companyId", company.id)diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.tsnew file mode 100644index 0000000000..5cd12ff4f1--- /dev/null+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts@@ -0,0 +1,53 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { getLocalTimeZone, startOfWeek, today } from "@internationalized/date";+import { json, type LoaderFunctionArgs } from "@vercel/remix";+import { getItemDemand, getPeriods } from "~/modules/items/items.service";++const defaultResponse = {+ demand: [],+ periods: [],+};++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "parts",+ });++ const { id: itemId, locationId } = params;+ if (!itemId) throw new Error("Could not find itemId");+ if (!locationId) throw new Error("Could not find locationId");++ const startDate = startOfWeek(today(getLocalTimeZone()), "en-US");+ const endDate = startDate.add({ weeks: 18 * 4 });+ const periods = await getPeriods(client, {+ startDate: startDate.toString(),+ endDate: endDate.toString(),+ });++ if (periods.error) {+ return json(+ defaultResponse,+ await flash(request, error(periods.error, "Failed to load periods"))+ );+ }++ const [demand] = await Promise.all([+ getItemDemand(client, {+ itemId,+ locationId,+ periods: periods.data.map((p) => p.id ?? ""),+ companyId,+ }),+ ]);++ if (demand.error) {+ return json(+ defaultResponse,+ await flash(request, error(demand.error, "Failed to load demand"))+ );+ }++ return json({ demand: demand.data, periods: periods.data });+}diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.tsxindex 5a8556d51c..154460c29f 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.tsx@@ -110,7 +110,7 @@ export default function ConsumablePurchasingRoute() {const initialValues = {...consumablePurchasing,preferredSupplierId: consumablePurchasing?.preferredSupplierId ?? undefined,- purchasingLeadTime: consumablePurchasing?.purchasingLeadTime ?? "",+ leadTime: consumablePurchasing?.leadTime ?? "",purchasingBlocked: consumablePurchasing?.purchasingBlocked ?? false,purchasingUnitOfMeasureCode:consumablePurchasing?.purchasingUnitOfMeasureCode ?? "",diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.tsxindex 73bafb043b..036edf8caf 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.tsx@@ -110,7 +110,7 @@ export default function MaterialPurchasingRoute() {const initialValues = {...materialPurchasing,preferredSupplierId: materialPurchasing?.preferredSupplierId ?? undefined,- purchasingLeadTime: materialPurchasing?.purchasingLeadTime ?? "",+ leadTime: materialPurchasing?.leadTime ?? "",purchasingBlocked: materialPurchasing?.purchasingBlocked ?? false,purchasingUnitOfMeasureCode:materialPurchasing?.purchasingUnitOfMeasureCode ?? "",diff --git a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsxindex f8f69637c0..e97c34c627 100644--- a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx@@ -17,6 +17,7 @@ import {upsertPickMethod,} from "~/modules/items";import { PickMethodForm } from "~/modules/items/ui/Item";+import { ItemDemandChart } from "~/modules/items/ui/Item/ItemDemandChart";import { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";import { useItems } from "~/stores";@@ -134,6 +135,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemShelfQuantities: itemShelfQuantities.data,quantities: quantities.data,itemId,+ locationId,});}@@ -185,7 +187,7 @@ export default function PartInventoryRoute() {unitOfMeasures: UnitOfMeasureListItem[];}>(path.to.partRoot);- const { partInventory, itemShelfQuantities, quantities, itemId } =+ const { partInventory, itemShelfQuantities, quantities, itemId, locationId } =useLoaderData<typeof loader>();const partData = useRouteData<{@@ -220,6 +222,7 @@ export default function PartInventoryRoute() {quantities={quantities}shelves={sharedPartsData?.shelves ?? []}/>+ <ItemDemandChart itemId={itemId} locationId={locationId} /></VStack>);}diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.make.$makeMethodId.tsxindex 273c1b303b..3a48ed02af 100644--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.make.$makeMethodId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.make.$makeMethodId.tsx@@ -21,7 +21,7 @@ import type {ConfigurationParameter,ConfigurationParameterGroup,ConfigurationRule,- partManufacturingValidator,+ itemManufacturingValidator,} from "~/modules/items";import {getMakeMethodById,@@ -130,7 +130,7 @@ export default function MethodMaterialMakePage() {if (!makeMethodId) throw new Error("Could not find makeMethodId");const routeData = useRouteData<{- partManufacturing: z.infer<typeof partManufacturingValidator> & {+ partManufacturing: z.infer<typeof itemManufacturingValidator> & {customFields: Record<string, string>;};configurationParametersAndGroups: {diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.method.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.method.tsxindex 93795ff7e7..5e7a349e13 100644--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.method.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.$methodId.method.tsx@@ -21,7 +21,7 @@ import type {PartSummary,} from "~/modules/items";import {- partManufacturingValidator,+ itemManufacturingValidator,upsertItemManufacturing,} from "~/modules/items";import {@@ -29,10 +29,8 @@ import {BillOfProcess,MakeMethodTools,} from "~/modules/items/ui/Item";-import {- ConfigurationParametersForm,- PartManufacturingForm,-} from "~/modules/items/ui/Parts";+import ItemManufacturingForm from "~/modules/items/ui/Item/ItemManufacturingForm";+import { ConfigurationParametersForm } from "~/modules/items/ui/Parts";import { getTagsList } from "~/modules/shared";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";@@ -49,7 +47,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "parts",});@@ -58,7 +56,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!methodId) throw new Error("Could not find methodId");const formData = await request.formData();- const validation = await validator(partManufacturingValidator).validate(+ const validation = await validator(itemManufacturingValidator).validate(formData);@@ -105,7 +103,7 @@ export default function MakeMethodRoute() {}>(path.to.part(itemId));const manufacturingRouteData = useRouteData<{- partManufacturing: z.infer<typeof partManufacturingValidator> & {+ partManufacturing: z.infer<typeof itemManufacturingValidator> & {customFields: Record<string, string>;};configurationParametersAndGroups: {@@ -142,7 +140,7 @@ export default function MakeMethodRoute() {)}</Await></Suspense>- <PartManufacturingForm+ <ItemManufacturingFormkey={itemId}// @ts-ignoreinitialValues={manufacturingInitialValues}diff --git a/apps/erp/app/routes/x+/part+/$itemId.planning.tsx b/apps/erp/app/routes/x+/part+/$itemId.planning.tsxindex a8ed1fae06..4e7367ec0d 100644--- a/apps/erp/app/routes/x+/part+/$itemId.planning.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.planning.tsx@@ -13,6 +13,7 @@ import {upsertItemPlanning,} from "~/modules/items";import { ItemPlanningForm } from "~/modules/items/ui/Item";+import { ItemDemandChart } from "~/modules/items/ui/Item/ItemDemandChart";import { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";import type { ListItem } from "~/types";@@ -99,6 +100,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return json({partPlanning: partPlanning.data,+ locationId,});}@@ -145,7 +147,7 @@ export default function PartPlanningRoute() {locations: ListItem[];}>(path.to.partRoot);- const { partPlanning } = useLoaderData<typeof loader>();+ const { partPlanning, locationId } = useLoaderData<typeof loader>();if (!sharedPartsData) throw new Error("Could not load shared parts data");@@ -160,6 +162,7 @@ export default function PartPlanningRoute() {locations={sharedPartsData.locations ?? []}type="Part"/>+ <ItemDemandChart itemId={partPlanning.itemId} locationId={locationId} /></VStack>);}diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.tsxindex 2b27f598b3..a6a6c92290 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.tsx@@ -103,7 +103,7 @@ export default function PartPurchasingRoute() {const initialValues = {...partPurchasing,preferredSupplierId: partPurchasing?.preferredSupplierId ?? undefined,- purchasingLeadTime: partPurchasing?.purchasingLeadTime ?? "",+ leadTime: partPurchasing?.leadTime ?? "",purchasingBlocked: partPurchasing?.purchasingBlocked ?? false,purchasingUnitOfMeasureCode:partPurchasing?.purchasingUnitOfMeasureCode ?? "",diff --git a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.method.tsx b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.method.tsxindex b482f906f5..316a1e011e 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.method.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.method.tsx@@ -1,25 +1,34 @@+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError } from "@carbon/form";import { Menubar, VStack } from "@carbon/react";import { Await, useLoaderData, useParams } from "@remix-run/react";import type { PostgrestResponse } from "@supabase/supabase-js";-import type { LoaderFunctionArgs } from "@vercel/remix";-import { json } from "@vercel/remix";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";import { Suspense } from "react";+import type { z } from "zod";import CadModel from "~/components/CadModel";import { usePermissions, useRouteData } from "~/hooks";-import type {- MakeMethod,- Material,- MethodOperation,- ToolSummary,+import {+ itemManufacturingValidator,+ upsertItemManufacturing,+ type MakeMethod,+ type Material,+ type MethodOperation,+ type ToolSummary,} from "~/modules/items";import {BillOfMaterial,BillOfProcess,MakeMethodTools,} from "~/modules/items/ui/Item";+import ItemManufacturingForm from "~/modules/items/ui/Item/ItemManufacturingForm";import { getTagsList } from "~/modules/shared";+import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";+import { validator } from "../../../../../../packages/form/src/zod";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -31,6 +40,50 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return json({ tags: tags.data ?? [] });}+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { itemId, methodId } = params;+ if (!itemId) throw new Error("Could not find itemId");+ if (!methodId) throw new Error("Could not find methodId");++ const formData = await request.formData();+ const validation = await validator(itemManufacturingValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updateToolManufacturing = await upsertItemManufacturing(client, {+ ...validation.data,+ itemId,+ updatedBy: userId,+ customFields: setCustomFields(formData),+ });+ if (updateToolManufacturing.error) {+ throw redirect(+ path.to.tool(itemId),+ await flash(+ request,+ error(+ updateToolManufacturing.error,+ "Failed to update tool manufacturing"+ )+ )+ );+ }++ throw redirect(+ path.to.toolMakeMethod(itemId, methodId),+ await flash(request, success("Updated part manufacturing"))+ );+}+export default function MakeMethodRoute() {const permissions = usePermissions();const { itemId, methodId } = useParams();@@ -45,6 +98,9 @@ export default function MakeMethodRoute() {}>(path.to.tool(itemId));const manufacturingRouteData = useRouteData<{+ toolManufacturing: z.infer<typeof itemManufacturingValidator> & {+ customFields: Record<string, string>;+ };makeMethod: MakeMethod;methodMaterials: Material[];methodOperations: MethodOperation[];@@ -55,6 +111,12 @@ export default function MakeMethodRoute() {const makeMethodId = manufacturingRouteData?.makeMethod?.id;if (!makeMethodId) throw new Error("Could not find makeMethodId");+ const manufacturingInitialValues = {+ ...manufacturingRouteData?.toolManufacturing,+ lotSize: manufacturingRouteData?.toolManufacturing.lotSize ?? 0,+ ...getCustomFields(manufacturingRouteData?.toolManufacturing.customFields),+ };+return (<VStack spacing={2} className="p-2"><Suspense fallback={<Menubar />}>@@ -68,7 +130,12 @@ export default function MakeMethodRoute() {)}</Await></Suspense>-+ <ItemManufacturingForm+ key={itemId}+ // @ts-ignore+ initialValues={manufacturingInitialValues}+ withConfiguration={false}+ /><BillOfProcesskey={`bop:${itemId}`}makeMethod={manufacturingRouteData?.makeMethod}diff --git a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.tsxindex 0a49cf3198..6153dc2942 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.manufacturing.$methodId.tsx@@ -22,6 +22,7 @@ import type { FlatTreeItem } from "~/components/TreeView";import { flattenTree } from "~/components/TreeView";import type { Method } from "~/modules/items";import {+ getItemManufacturing,getMakeMethodById,getMethodMaterialsByMakeMethod,getMethodOperationsByMakeMethodId,@@ -60,12 +61,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const [methodTree, methodMaterials, methodOperations] = await Promise.all([- getMethodTree(client, makeMethod.data.id),- getMethodMaterialsByMakeMethod(client, makeMethod.data.id),- getMethodOperationsByMakeMethodId(client, makeMethod.data.id),- // getItemManufacturing(client, itemId, companyId),- ]);+ const [methodTree, methodMaterials, methodOperations, toolManufacturing] =+ await Promise.all([+ getMethodTree(client, makeMethod.data.id),+ getMethodMaterialsByMakeMethod(client, makeMethod.data.id),+ getMethodOperationsByMakeMethodId(client, makeMethod.data.id),+ getItemManufacturing(client, itemId, companyId),+ ]);if (methodTree?.error) {throw redirect(path.to.partDetails(itemId),@@ -115,7 +117,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {methods: (methodTree.data.length > 0? flattenTree(methodTree.data[0]): []) satisfies FlatTreeItem<Method>[],- // toolManufacturing: toolManufacturing.data,+ toolManufacturing: toolManufacturing.data,// configurationParametersAndGroups: toolManufacturing.data// ?.requiresConfiguration// ? await getConfigurationParameters(client, itemId, companyId)diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.tsxindex f42ff88aca..87f8008714 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.tsx@@ -103,7 +103,7 @@ export default function ToolPurchasingRoute() {const initialValues = {...toolPurchasing,preferredSupplierId: toolPurchasing?.preferredSupplierId ?? undefined,- purchasingLeadTime: toolPurchasing?.purchasingLeadTime ?? "",+ leadTime: toolPurchasing?.leadTime ?? "",purchasingBlocked: toolPurchasing?.purchasingBlocked ?? false,purchasingUnitOfMeasureCode:toolPurchasing?.purchasingUnitOfMeasureCode ?? "",diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 2aadf2221e..1295e8ecd3 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -49,6 +49,9 @@ export const path = {groupsByType: (type?: string) =>generatePath(`${api}/users/groups?type=${type}`),item: (type: string) => generatePath(`${api}/item/${type}`),+ itemForecast: (itemId: string, locationId: string) =>+ generatePath(`${api}/items/${itemId}/${locationId}/forecast`),+ itemPostingGroups: `${api}/items/groups`,jobBillOfMaterials: (id: string, withOperations: boolean = false) =>generatePath(`${api}/production/methods/${id}/bom?withOperations=${withOperations}`@@ -59,7 +62,6 @@ export const path = {),jobs: `${api}/production/jobs`,locations: `${api}/resources/locations`,- itemPostingGroups: `${api}/items/groups`,materialForms: `${api}/items/forms`,materialSubstances: `${api}/items/substances`,messagingNotify: `${api}/messaging/notify`,diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 77208022d5..ef119ab495 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -9532,7 +9532,7 @@ export default {$ref: "#/parameters/rowFilter.demandForecast.locationId",},{- $ref: "#/parameters/rowFilter.demandForecast.demandPeriodId",+ $ref: "#/parameters/rowFilter.demandForecast.periodId",},{$ref: "#/parameters/rowFilter.demandForecast.forecastQuantity",@@ -9546,6 +9546,9 @@ export default {{$ref: "#/parameters/rowFilter.demandForecast.notes",},+ {+ $ref: "#/parameters/rowFilter.demandForecast.companyId",+ },{$ref: "#/parameters/rowFilter.demandForecast.createdBy",},@@ -9624,7 +9627,7 @@ export default {$ref: "#/parameters/rowFilter.demandForecast.locationId",},{- $ref: "#/parameters/rowFilter.demandForecast.demandPeriodId",+ $ref: "#/parameters/rowFilter.demandForecast.periodId",},{$ref: "#/parameters/rowFilter.demandForecast.forecastQuantity",@@ -9638,6 +9641,9 @@ export default {{$ref: "#/parameters/rowFilter.demandForecast.notes",},+ {+ $ref: "#/parameters/rowFilter.demandForecast.companyId",+ },{$ref: "#/parameters/rowFilter.demandForecast.createdBy",},@@ -9670,7 +9676,7 @@ export default {$ref: "#/parameters/rowFilter.demandForecast.locationId",},{- $ref: "#/parameters/rowFilter.demandForecast.demandPeriodId",+ $ref: "#/parameters/rowFilter.demandForecast.periodId",},{$ref: "#/parameters/rowFilter.demandForecast.forecastQuantity",@@ -9684,6 +9690,9 @@ export default {{$ref: "#/parameters/rowFilter.demandForecast.notes",},+ {+ $ref: "#/parameters/rowFilter.demandForecast.companyId",+ },{$ref: "#/parameters/rowFilter.demandForecast.createdBy",},@@ -14461,7 +14470,7 @@ export default {$ref: "#/parameters/rowFilter.demandActual.locationId",},{- $ref: "#/parameters/rowFilter.demandActual.demandPeriodId",+ $ref: "#/parameters/rowFilter.demandActual.periodId",},{$ref: "#/parameters/rowFilter.demandActual.actualQuantity",@@ -14472,6 +14481,9 @@ export default {{$ref: "#/parameters/rowFilter.demandActual.notes",},+ {+ $ref: "#/parameters/rowFilter.demandActual.companyId",+ },{$ref: "#/parameters/rowFilter.demandActual.createdBy",},@@ -14550,7 +14562,7 @@ export default {$ref: "#/parameters/rowFilter.demandActual.locationId",},{- $ref: "#/parameters/rowFilter.demandActual.demandPeriodId",+ $ref: "#/parameters/rowFilter.demandActual.periodId",},{$ref: "#/parameters/rowFilter.demandActual.actualQuantity",@@ -14561,6 +14573,9 @@ export default {{$ref: "#/parameters/rowFilter.demandActual.notes",},+ {+ $ref: "#/parameters/rowFilter.demandActual.companyId",+ },{$ref: "#/parameters/rowFilter.demandActual.createdBy",},@@ -14593,7 +14608,7 @@ export default {$ref: "#/parameters/rowFilter.demandActual.locationId",},{- $ref: "#/parameters/rowFilter.demandActual.demandPeriodId",+ $ref: "#/parameters/rowFilter.demandActual.periodId",},{$ref: "#/parameters/rowFilter.demandActual.actualQuantity",@@ -14604,6 +14619,9 @@ export default {{$ref: "#/parameters/rowFilter.demandActual.notes",},+ {+ $ref: "#/parameters/rowFilter.demandActual.companyId",+ },{$ref: "#/parameters/rowFilter.demandActual.createdBy",},@@ -18900,6 +18918,141 @@ export default {tags: ["shifts"],},},+ "/period": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.period.id",+ },+ {+ $ref: "#/parameters/rowFilter.period.startDate",+ },+ {+ $ref: "#/parameters/rowFilter.period.endDate",+ },+ {+ $ref: "#/parameters/rowFilter.period.periodType",+ },+ {+ $ref: "#/parameters/rowFilter.period.createdAt",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/period",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["period"],+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.period",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/preferPost",+ },+ ],+ responses: {+ "201": {+ description: "Created",+ },+ },+ tags: ["period"],+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.period.id",+ },+ {+ $ref: "#/parameters/rowFilter.period.startDate",+ },+ {+ $ref: "#/parameters/rowFilter.period.endDate",+ },+ {+ $ref: "#/parameters/rowFilter.period.periodType",+ },+ {+ $ref: "#/parameters/rowFilter.period.createdAt",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["period"],+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.period.id",+ },+ {+ $ref: "#/parameters/rowFilter.period.startDate",+ },+ {+ $ref: "#/parameters/rowFilter.period.endDate",+ },+ {+ $ref: "#/parameters/rowFilter.period.periodType",+ },+ {+ $ref: "#/parameters/rowFilter.period.createdAt",+ },+ {+ $ref: "#/parameters/body.period",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["period"],+ },+ },"/jobOperationDependency": {get: {parameters: [@@ -19890,141 +20043,6 @@ export default {tags: ["salesOrderFavorite"],},},- "/demandPeriod": {- get: {- parameters: [- {- $ref: "#/parameters/rowFilter.demandPeriod.id",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.startDate",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.endDate",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.periodType",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.createdAt",- },- {- $ref: "#/parameters/select",- },- {- $ref: "#/parameters/order",- },- {- $ref: "#/parameters/range",- },- {- $ref: "#/parameters/rangeUnit",- },- {- $ref: "#/parameters/offset",- },- {- $ref: "#/parameters/limit",- },- {- $ref: "#/parameters/preferCount",- },- ],- responses: {- "200": {- description: "OK",- schema: {- items: {- $ref: "#/definitions/demandPeriod",- },- type: "array",- },- },- "206": {- description: "Partial Content",- },- },- tags: ["demandPeriod"],- },- post: {- parameters: [- {- $ref: "#/parameters/body.demandPeriod",- },- {- $ref: "#/parameters/select",- },- {- $ref: "#/parameters/preferPost",- },- ],- responses: {- "201": {- description: "Created",- },- },- tags: ["demandPeriod"],- },- delete: {- parameters: [- {- $ref: "#/parameters/rowFilter.demandPeriod.id",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.startDate",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.endDate",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.periodType",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.createdAt",- },- {- $ref: "#/parameters/preferReturn",- },- ],- responses: {- "204": {- description: "No Content",- },- },- tags: ["demandPeriod"],- },- patch: {- parameters: [- {- $ref: "#/parameters/rowFilter.demandPeriod.id",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.startDate",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.endDate",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.periodType",- },- {- $ref: "#/parameters/rowFilter.demandPeriod.createdAt",- },- {- $ref: "#/parameters/body.demandPeriod",- },- {- $ref: "#/parameters/preferReturn",- },- ],- responses: {- "204": {- description: "No Content",- },- },- tags: ["demandPeriod"],- },- },"/purchaseOrderLine": {get: {parameters: [@@ -60147,8 +60165,9 @@ export default {required: ["itemId","locationId",- "demandPeriodId",+ "periodId","forecastQuantity",+ "companyId","createdBy","createdAt","updatedAt",@@ -60167,9 +60186,9 @@ export default {format: "text",type: "string",},- demandPeriodId: {+ periodId: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `demandPeriod.id`.<fk table='demandPeriod' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `period.id`.<fk table='period' column='id'/>",format: "text",type: "string",},@@ -60190,6 +60209,12 @@ export default {format: "text",type: "string",},+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },createdBy: {description:"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",@@ -62560,9 +62585,10 @@ export default {required: ["itemId","locationId",- "demandPeriodId",+ "periodId","actualQuantity","sourceType",+ "companyId","createdBy","createdAt","updatedAt",@@ -62581,9 +62607,9 @@ export default {format: "text",type: "string",},- demandPeriodId: {+ periodId: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `demandPeriod.id`.<fk table='demandPeriod' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `period.id`.<fk table='period' column='id'/>",format: "text",type: "string",},@@ -62602,6 +62628,12 @@ export default {format: "text",type: "string",},+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },createdBy: {description:"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",@@ -64562,6 +64594,36 @@ export default {},type: "object",},+ period: {+ required: ["id", "startDate", "endDate", "periodType", "createdAt"],+ properties: {+ id: {+ default: "public.xid()",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string",+ },+ startDate: {+ format: "date",+ type: "string",+ },+ endDate: {+ format: "date",+ type: "string",+ },+ periodType: {+ enum: ["Week", "Day", "Month"],+ format: 'public."periodType"',+ type: "string",+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string",+ },+ },+ type: "object",+ },jobOperationDependency: {required: ["operationId",@@ -64895,36 +64957,6 @@ export default {},type: "object",},- demandPeriod: {- required: ["id", "startDate", "endDate", "periodType", "createdAt"],- properties: {- id: {- default: "public.xid()",- description: "Note:\nThis is a Primary Key.<pk/>",- format: "text",- type: "string",- },- startDate: {- format: "date",- type: "string",- },- endDate: {- format: "date",- type: "string",- },- periodType: {- enum: ["Week", "Day", "Month"],- format: 'public."demandPeriodType"',- type: "string",- },- createdAt: {- default: "now()",- format: "timestamp with time zone",- type: "string",- },- },- type: "object",- },purchaseOrderLine: {required: ["id",@@ -75192,7 +75224,7 @@ export default {type: "integer",},demandAccumulationPeriod: {- default: 0,+ default: 30,format: "integer",type: "integer",},@@ -84869,8 +84901,8 @@ export default {in: "query",type: "string",},- "rowFilter.demandForecast.demandPeriodId": {- name: "demandPeriodId",+ "rowFilter.demandForecast.periodId": {+ name: "periodId",required: false,in: "query",type: "string",@@ -84899,6 +84931,12 @@ export default {in: "query",type: "string",},+ "rowFilter.demandForecast.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.demandForecast.createdBy": {name: "createdBy",required: false,@@ -87521,8 +87559,8 @@ export default {in: "query",type: "string",},- "rowFilter.demandActual.demandPeriodId": {- name: "demandPeriodId",+ "rowFilter.demandActual.periodId": {+ name: "periodId",required: false,in: "query",type: "string",@@ -87545,6 +87583,12 @@ export default {in: "query",type: "string",},+ "rowFilter.demandActual.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.demandActual.createdBy": {name: "createdBy",required: false,@@ -89816,6 +89860,45 @@ export default {in: "query",type: "string",},+ "body.period": {+ name: "period",+ description: "period",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/period",+ },+ },+ "rowFilter.period.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.period.startDate": {+ name: "startDate",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.period.endDate": {+ name: "endDate",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.period.periodType": {+ name: "periodType",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.period.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string",+ },"body.jobOperationDependency": {name: "jobOperationDependency",description: "jobOperationDependency",@@ -90170,45 +90253,6 @@ export default {in: "query",type: "string",},- "body.demandPeriod": {- name: "demandPeriod",- description: "demandPeriod",- required: false,- in: "body",- schema: {- $ref: "#/definitions/demandPeriod",- },- },- "rowFilter.demandPeriod.id": {- name: "id",- required: false,- in: "query",- type: "string",- },- "rowFilter.demandPeriod.startDate": {- name: "startDate",- required: false,- in: "query",- type: "string",- },- "rowFilter.demandPeriod.endDate": {- name: "endDate",- required: false,- in: "query",- type: "string",- },- "rowFilter.demandPeriod.periodType": {- name: "periodType",- required: false,- in: "query",- type: "string",- },- "rowFilter.demandPeriod.createdAt": {- name: "createdAt",- required: false,- in: "query",- type: "string",- },"body.purchaseOrderLine": {name: "purchaseOrderLine",description: "purchaseOrderLine",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex d657aa498d..416f9909c3 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -4756,41 +4756,72 @@ export type Database = {demandActual: {Row: {actualQuantity: number+ companyId: stringcreatedAt: stringcreatedBy: string- demandPeriodId: stringitemId: stringlocationId: stringnotes: string | null+ periodId: stringsourceType: Database["public"]["Enums"]["demandSourceType"]updatedAt: stringupdatedBy: string}Insert: {actualQuantity?: number+ companyId: stringcreatedAt?: stringcreatedBy: string- demandPeriodId: stringitemId: stringlocationId: stringnotes?: string | null+ periodId: stringsourceType: Database["public"]["Enums"]["demandSourceType"]updatedAt?: stringupdatedBy: string}Update: {actualQuantity?: number+ companyId?: stringcreatedAt?: stringcreatedBy?: string- demandPeriodId?: stringitemId?: stringlocationId?: stringnotes?: string | null+ periodId?: stringsourceType?: Database["public"]["Enums"]["demandSourceType"]updatedAt?: stringupdatedBy?: string}Relationships: [+ {+ foreignKeyName: "demandActual_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "demandActual_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "demandActual_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "demandActual_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },{foreignKeyName: "demandActual_createdBy_fkey"columns: ["createdBy"]@@ -4826,13 +4857,6 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},- {- foreignKeyName: "demandActual_demandPeriodId_fkey"- columns: ["demandPeriodId"]- isOneToOne: false- referencedRelation: "demandPeriod"- referencedColumns: ["id"]- },{foreignKeyName: "demandActual_itemId_fkey"columns: ["itemId"]@@ -4875,6 +4899,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "demandActual_periodId_fkey"+ columns: ["periodId"]+ isOneToOne: false+ referencedRelation: "period"+ referencedColumns: ["id"]+ },{foreignKeyName: "demandActual_updatedBy_fkey"columns: ["updatedBy"]@@ -4914,45 +4945,76 @@ export type Database = {}demandForecast: {Row: {+ companyId: stringconfidence: number | nullcreatedAt: stringcreatedBy: string- demandPeriodId: stringforecastMethod: string | nullforecastQuantity: numberitemId: stringlocationId: stringnotes: string | null+ periodId: stringupdatedAt: stringupdatedBy: string}Insert: {+ companyId: stringconfidence?: number | nullcreatedAt?: stringcreatedBy: string- demandPeriodId: stringforecastMethod?: string | nullforecastQuantity?: numberitemId: stringlocationId: stringnotes?: string | null+ periodId: stringupdatedAt?: stringupdatedBy: string}Update: {+ companyId?: stringconfidence?: number | nullcreatedAt?: stringcreatedBy?: string- demandPeriodId?: stringforecastMethod?: string | nullforecastQuantity?: numberitemId?: stringlocationId?: stringnotes?: string | null+ periodId?: stringupdatedAt?: stringupdatedBy?: string}Relationships: [+ {+ foreignKeyName: "demandForecast_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "demandForecast_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "demandForecast_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "demandForecast_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },{foreignKeyName: "demandForecast_createdBy_fkey"columns: ["createdBy"]@@ -4988,13 +5050,6 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},- {- foreignKeyName: "demandForecast_demandPeriodId_fkey"- columns: ["demandPeriodId"]- isOneToOne: false- referencedRelation: "demandPeriod"- referencedColumns: ["id"]- },{foreignKeyName: "demandForecast_itemId_fkey"columns: ["itemId"]@@ -5037,6 +5092,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "demandForecast_periodId_fkey"+ columns: ["periodId"]+ isOneToOne: false+ referencedRelation: "period"+ referencedColumns: ["id"]+ },{foreignKeyName: "demandForecast_updatedBy_fkey"columns: ["updatedBy"]@@ -5074,30 +5136,6 @@ export type Database = {},]}- demandPeriod: {- Row: {- createdAt: string- endDate: string- id: string- periodType: Database["public"]["Enums"]["demandPeriodType"]- startDate: string- }- Insert: {- createdAt?: string- endDate: string- id?: string- periodType: Database["public"]["Enums"]["demandPeriodType"]- startDate: string- }- Update: {- createdAt?: string- endDate?: string- id?: string- periodType?: Database["public"]["Enums"]["demandPeriodType"]- startDate?: string- }- Relationships: []- }department: {Row: {companyId: string@@ -16988,6 +17026,30 @@ export type Database = {},]}+ period: {+ Row: {+ createdAt: string+ endDate: string+ id: string+ periodType: Database["public"]["Enums"]["periodType"]+ startDate: string+ }+ Insert: {+ createdAt?: string+ endDate: string+ id?: string+ periodType: Database["public"]["Enums"]["periodType"]+ startDate: string+ }+ Update: {+ createdAt?: string+ endDate?: string+ id?: string+ periodType?: Database["public"]["Enums"]["periodType"]+ startDate?: string+ }+ Relationships: []+ }pickMethod: {Row: {companyId: string@@ -44671,7 +44733,6 @@ export type Database = {| "Variance"| "Total"deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"- demandPeriodType: "Week" | "Day" | "Month"demandSourceType: "Sales Order" | "Job Material"documentSourceType:| "Job"@@ -44895,6 +44956,7 @@ export type Database = {| "Consumable"| "Fixture"paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"+ periodType: "Week" | "Day" | "Month"procedureAttributeType:| "Value"| "Measurement"diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex d657aa498d..416f9909c3 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -4756,41 +4756,72 @@ export type Database = {demandActual: {Row: {actualQuantity: number+ companyId: stringcreatedAt: stringcreatedBy: string- demandPeriodId: stringitemId: stringlocationId: stringnotes: string | null+ periodId: stringsourceType: Database["public"]["Enums"]["demandSourceType"]updatedAt: stringupdatedBy: string}Insert: {actualQuantity?: number+ companyId: stringcreatedAt?: stringcreatedBy: string- demandPeriodId: stringitemId: stringlocationId: stringnotes?: string | null+ periodId: stringsourceType: Database["public"]["Enums"]["demandSourceType"]updatedAt?: stringupdatedBy: string}Update: {actualQuantity?: number+ companyId?: stringcreatedAt?: stringcreatedBy?: string- demandPeriodId?: stringitemId?: stringlocationId?: stringnotes?: string | null+ periodId?: stringsourceType?: Database["public"]["Enums"]["demandSourceType"]updatedAt?: stringupdatedBy?: string}Relationships: [+ {+ foreignKeyName: "demandActual_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "demandActual_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "demandActual_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "demandActual_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },{foreignKeyName: "demandActual_createdBy_fkey"columns: ["createdBy"]@@ -4826,13 +4857,6 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},- {- foreignKeyName: "demandActual_demandPeriodId_fkey"- columns: ["demandPeriodId"]- isOneToOne: false- referencedRelation: "demandPeriod"- referencedColumns: ["id"]- },{foreignKeyName: "demandActual_itemId_fkey"columns: ["itemId"]@@ -4875,6 +4899,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "demandActual_periodId_fkey"+ columns: ["periodId"]+ isOneToOne: false+ referencedRelation: "period"+ referencedColumns: ["id"]+ },{foreignKeyName: "demandActual_updatedBy_fkey"columns: ["updatedBy"]@@ -4914,45 +4945,76 @@ export type Database = {}demandForecast: {Row: {+ companyId: stringconfidence: number | nullcreatedAt: stringcreatedBy: string- demandPeriodId: stringforecastMethod: string | nullforecastQuantity: numberitemId: stringlocationId: stringnotes: string | null+ periodId: stringupdatedAt: stringupdatedBy: string}Insert: {+ companyId: stringconfidence?: number | nullcreatedAt?: stringcreatedBy: string- demandPeriodId: stringforecastMethod?: string | nullforecastQuantity?: numberitemId: stringlocationId: stringnotes?: string | null+ periodId: stringupdatedAt?: stringupdatedBy: string}Update: {+ companyId?: stringconfidence?: number | nullcreatedAt?: stringcreatedBy?: string- demandPeriodId?: stringforecastMethod?: string | nullforecastQuantity?: numberitemId?: stringlocationId?: stringnotes?: string | null+ periodId?: stringupdatedAt?: stringupdatedBy?: string}Relationships: [+ {+ foreignKeyName: "demandForecast_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "demandForecast_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "demandForecast_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "demandForecast_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },{foreignKeyName: "demandForecast_createdBy_fkey"columns: ["createdBy"]@@ -4988,13 +5050,6 @@ export type Database = {referencedRelation: "userDefaults"referencedColumns: ["userId"]},- {- foreignKeyName: "demandForecast_demandPeriodId_fkey"- columns: ["demandPeriodId"]- isOneToOne: false- referencedRelation: "demandPeriod"- referencedColumns: ["id"]- },{foreignKeyName: "demandForecast_itemId_fkey"columns: ["itemId"]@@ -5037,6 +5092,13 @@ export type Database = {referencedRelation: "location"referencedColumns: ["id"]},+ {+ foreignKeyName: "demandForecast_periodId_fkey"+ columns: ["periodId"]+ isOneToOne: false+ referencedRelation: "period"+ referencedColumns: ["id"]+ },{foreignKeyName: "demandForecast_updatedBy_fkey"columns: ["updatedBy"]@@ -5074,30 +5136,6 @@ export type Database = {},]}- demandPeriod: {- Row: {- createdAt: string- endDate: string- id: string- periodType: Database["public"]["Enums"]["demandPeriodType"]- startDate: string- }- Insert: {- createdAt?: string- endDate: string- id?: string- periodType: Database["public"]["Enums"]["demandPeriodType"]- startDate: string- }- Update: {- createdAt?: string- endDate?: string- id?: string- periodType?: Database["public"]["Enums"]["demandPeriodType"]- startDate?: string- }- Relationships: []- }department: {Row: {companyId: string@@ -16988,6 +17026,30 @@ export type Database = {},]}+ period: {+ Row: {+ createdAt: string+ endDate: string+ id: string+ periodType: Database["public"]["Enums"]["periodType"]+ startDate: string+ }+ Insert: {+ createdAt?: string+ endDate: string+ id?: string+ periodType: Database["public"]["Enums"]["periodType"]+ startDate: string+ }+ Update: {+ createdAt?: string+ endDate?: string+ id?: string+ periodType?: Database["public"]["Enums"]["periodType"]+ startDate?: string+ }+ Relationships: []+ }pickMethod: {Row: {companyId: string@@ -44671,7 +44733,6 @@ export type Database = {| "Variance"| "Total"deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"- demandPeriodType: "Week" | "Day" | "Month"demandSourceType: "Sales Order" | "Job Material"documentSourceType:| "Job"@@ -44895,6 +44956,7 @@ export type Database = {| "Consumable"| "Fixture"paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"+ periodType: "Week" | "Day" | "Month"procedureAttributeType:| "Value"| "Measurement"diff --git a/packages/database/supabase/functions/mcp/tools.ts b/packages/database/supabase/functions/mcp/tools.tsindex e582a98331..bd0a797fc0 100644--- a/packages/database/supabase/functions/mcp/tools.ts+++ b/packages/database/supabase/functions/mcp/tools.ts@@ -192,7 +192,7 @@ const createPurchaseOrder = tool({.select(["purchasingUnitOfMeasureCode","conversionFactor",- "purchasingLeadTime",+ "leadTime",]).where("itemId", "=", part.partId).executeTakeFirst(),diff --git a/packages/database/supabase/functions/mrp/index.ts b/packages/database/supabase/functions/mrp/index.tsindex 9a4766fffe..ae735dc54b 100644--- a/packages/database/supabase/functions/mrp/index.ts+++ b/packages/database/supabase/functions/mrp/index.ts@@ -20,7 +20,7 @@ const db = getDatabaseClient<DB>(pool);const WEEKS_TO_FORECAST = 18 * 4;type DemandPeriod = Omit<- Database["public"]["Tables"]["demandPeriod"]["Row"],+ Database["public"]["Tables"]["period"]["Row"],"createdAt">;@@ -30,6 +30,12 @@ const payloadValidator = z.discriminatedUnion("type", [companyId: z.string(),userId: z.string(),}),+ z.object({+ type: z.literal("item"),+ id: z.string(),+ companyId: z.string(),+ userId: z.string(),+ }),z.object({type: z.literal("job"),id: z.string(),@@ -50,6 +56,8 @@ const payloadValidator = z.discriminatedUnion("type", [}),]);+// TODO: we can do a reduced version based on the type of the payload, but for now, we're just running full MRP+serve(async (req: Request) => {if (req.method === "OPTIONS") {return new Response("ok", { headers: corsHeaders });@@ -67,8 +75,8 @@ serve(async (req: Request) => {});const today = getToday(getLocalTimeZone());- const periods = getStartAndEndDates(today, "Week");- const demandPeriods = await getOrCreateDemandPeriods(db, periods, "Week");+ const ranges = getStartAndEndDates(today, "Week");+ const periods = await getOrCreateDemandPeriods(db, ranges, "Week");const client = await getSupabaseServiceRole(req.headers.get("Authorization"),@@ -110,7 +118,7 @@ serve(async (req: Request) => {location.id);if (salesLocationPeriods) {- for (const period of demandPeriods) {+ for (const period of periods) {salesLocationPeriods.set(period.id ?? "", new Map<string, number>());}}@@ -119,7 +127,7 @@ serve(async (req: Request) => {location.id);if (jobMaterialLocationPeriods) {- for (const period of demandPeriods) {+ for (const period of periods) {jobMaterialLocationPeriods.set(period.id ?? "",new Map<string, number>()@@ -129,549 +137,210 @@ serve(async (req: Request) => {}try {- switch (type) {- case "company": {- const [salesOrderLines, jobMaterialLines] = await Promise.all([- client- .from("openSalesOrderLines")- .select("*")- .eq("companyId", companyId),- client- .from("openJobMaterialLines")- .select("*")- .eq("companyId", companyId),- ]);-- if (salesOrderLines.error) {- throw new Error("No sales order lines found");- }+ const [salesOrderLines, jobMaterialLines] = await Promise.all([+ client.from("openSalesOrderLines").select("*").eq("companyId", companyId),+ client+ .from("openJobMaterialLines")+ .select("*")+ .eq("companyId", companyId),+ ]);++ if (salesOrderLines.error) {+ throw new Error("No sales order lines found");+ }- if (jobMaterialLines.error) {- throw new Error("No job material lines found");- }+ if (jobMaterialLines.error) {+ throw new Error("No job material lines found");+ }- // Group sales order lines into demand periods- for (const line of salesOrderLines.data) {- if (!line.itemId || !line.quantityToSend) continue;-- const promiseDate = line.promisedDate- ? parseDate(line.promisedDate)- : today;- const requiredDate = promiseDate.add({- days: -(line?.leadTime ?? 7),- });-- // If promised date is before today, use first period- let period;- if (requiredDate.compare(today) < 0) {- period = demandPeriods[0];- } else {- // Find matching period for promised date- period = demandPeriods.find((p) => {- return (- p.startDate?.compare(requiredDate) <= 0 &&- p.endDate?.compare(requiredDate) >= 0- );- });- }+ // Group sales order lines into demand periods+ for (const line of salesOrderLines.data) {+ if (!line.itemId || !line.quantityToSend) continue;++ const promiseDate = line.promisedDate+ ? parseDate(line.promisedDate)+ : today;+ const requiredDate = promiseDate;++ // If promised date is before today, use first period+ let period;+ if (requiredDate.compare(today) < 0) {+ period = periods[0];+ } else {+ // Find matching period for promised date+ period = periods.find((p) => {+ return (+ p.startDate?.compare(requiredDate) <= 0 &&+ p.endDate?.compare(requiredDate) >= 0+ );+ });+ }- if (period) {- const locationDemand = salesDemandByLocationAndPeriod.get(- line.locationId ?? ""- );- if (locationDemand) {- const periodDemand = locationDemand.get(period.id ?? "");- if (periodDemand) {- const currentDemand = periodDemand.get(line.itemId) ?? 0;- periodDemand.set(- line.itemId,- currentDemand + line.quantityToSend- );- }- }+ if (period) {+ const locationDemand = salesDemandByLocationAndPeriod.get(+ line.locationId ?? ""+ );+ if (locationDemand) {+ const periodDemand = locationDemand.get(period.id ?? "");+ if (periodDemand) {+ const currentDemand = periodDemand.get(line.itemId) ?? 0;+ periodDemand.set(line.itemId, currentDemand + line.quantityToSend);}}+ }+ }- // Group job material lines into demand periods- for (const line of jobMaterialLines.data) {- if (!line.itemId || !line.quantityToIssue) continue;-- const dueDate = line.dueDate ? parseDate(line.dueDate) : today;- const requiredDate = dueDate.add({ days: -(line.leadTime ?? 7) });-- // If required date is before today, use first period- let period;- if (requiredDate.compare(today) < 0) {- period = demandPeriods[0];- } else {- // Find matching period for required date- period = demandPeriods.find((p) => {- return (- p.startDate?.compare(requiredDate) <= 0 &&- p.endDate?.compare(requiredDate) >= 0- );- });- }+ // Group job material lines into demand periods+ for (const line of jobMaterialLines.data) {+ if (!line.itemId || !line.quantityToIssue) continue;++ const dueDate = line.dueDate ? parseDate(line.dueDate) : today;+ const requiredDate = dueDate.add({ days: -(line.leadTime ?? 7) });++ // If required date is before today, use first period+ let period;+ if (requiredDate.compare(today) < 0) {+ period = periods[0];+ } else {+ // Find matching period for required date+ period = periods.find((p) => {+ return (+ p.startDate?.compare(requiredDate) <= 0 &&+ p.endDate?.compare(requiredDate) >= 0+ );+ });+ }- if (period) {- const locationDemand = jobMaterialDemandByLocationAndPeriod.get(- line.locationId ?? ""- );- if (locationDemand) {- const periodDemand = locationDemand.get(period.id ?? "");- if (periodDemand) {- const currentDemand = periodDemand.get(line.itemId) ?? 0;- periodDemand.set(- line.itemId,- currentDemand + line.quantityToIssue- );- }- }+ if (period) {+ const locationDemand = jobMaterialDemandByLocationAndPeriod.get(+ line.locationId ?? ""+ );+ if (locationDemand) {+ const periodDemand = locationDemand.get(period.id ?? "");+ if (periodDemand) {+ const currentDemand = periodDemand.get(line.itemId) ?? 0;+ periodDemand.set(line.itemId, currentDemand + line.quantityToIssue);}}+ }+ }- const demandActualUpserts: Database["public"]["Tables"]["demandActual"]["Insert"][] =- [];-- // Create a Map to store unique demand actuals by composite key- const demandActualsMap = new Map<- string,- Database["public"]["Tables"]["demandActual"]["Insert"]- >();-- // Get existing demand actuals- const { data: existingDemandActuals, error: demandActualsError } =- await client- .from("demandActual")- .select("*")+ const demandActualUpserts: Database["public"]["Tables"]["demandActual"]["Insert"][] =+ [];- .in(- "demandPeriodId",- demandPeriods.map((p) => p.id ?? "")- );+ // Create a Map to store unique demand actuals by composite key+ const demandActualsMap = new Map<+ string,+ Database["public"]["Tables"]["demandActual"]["Insert"]+ >();- if (demandActualsError) throw demandActualsError;+ // Get existing demand actuals+ const { data: existingDemandActuals, error: demandActualsError } =+ await client+ .from("demandActual")+ .select("*")- // First add all existing records with quantity 0- if (existingDemandActuals) {- for (const existing of existingDemandActuals) {- const key = `${existing.itemId}-${existing.locationId}-${existing.demandPeriodId}-${existing.sourceType}`;- demandActualsMap.set(key, {- itemId: existing.itemId,- locationId: existing.locationId,- demandPeriodId: existing.demandPeriodId,- actualQuantity: 0,- sourceType: existing.sourceType,- createdBy: userId,- updatedBy: userId,- });- }- }-- // Then add/update current demand for sales order lines- for (const [locationId, periodMap] of salesDemandByLocationAndPeriod) {- for (const [periodId, itemMap] of periodMap) {- for (const [itemId, quantity] of itemMap) {- if (quantity > 0) {- const key = `${itemId}-${locationId}-${periodId}-Sales Order`;- demandActualsMap.set(key, {- itemId,- locationId,- demandPeriodId: periodId,- actualQuantity: quantity,- sourceType: "Sales Order",- createdBy: userId,- updatedBy: userId,- });- }- }- }- }-- // Then add/update current demand for job material lines- for (const [- locationId,- periodMap,- ] of jobMaterialDemandByLocationAndPeriod) {- for (const [periodId, itemMap] of periodMap) {- for (const [itemId, quantity] of itemMap) {- if (quantity > 0) {- const key = `${itemId}-${locationId}-${periodId}-Job Material`;- demandActualsMap.set(key, {- itemId,- locationId,- demandPeriodId: periodId,- actualQuantity: quantity,- sourceType: "Job Material",- createdBy: userId,- updatedBy: userId,- });- }- }- }- }+ .in(+ "periodId",+ periods.map((p) => p.id ?? "")+ );- // Convert Map values to array for upsert- demandActualUpserts.push(...demandActualsMap.values());-- try {- await db.transaction().execute(async (trx) => {- if (demandActualUpserts.length > 0) {- await trx- .insertInto("demandActual")- .values(demandActualUpserts)- .onConflict((oc) =>- oc- .columns([- "itemId",- "locationId",- "demandPeriodId",- "sourceType",- ])- .doUpdateSet({- actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),- updatedAt: new Date().toISOString(),- updatedBy: userId,- })- )- .execute();- }- });-- return new Response(JSON.stringify({ success: true }), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 201,- });- } catch (err) {- console.error(err);- return new Response(JSON.stringify(err), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 500,- });- }+ if (demandActualsError) throw demandActualsError;++ // First add all existing records with quantity 0+ if (existingDemandActuals) {+ for (const existing of existingDemandActuals) {+ const key = `${existing.itemId}-${existing.locationId}-${existing.periodId}-${existing.sourceType}`;+ demandActualsMap.set(key, {+ itemId: existing.itemId,+ locationId: existing.locationId,+ periodId: existing.periodId,+ actualQuantity: 0,+ sourceType: existing.sourceType,+ companyId,+ createdBy: userId,+ updatedBy: userId,+ });}- case "salesOrder": {- const { id } = parsedPayload;-- const [salesOrderLines] = await Promise.all([- client- .from("openSalesOrderLines")- .select("*")- .eq("salesOrderId", id)- .eq("companyId", companyId),- ]);-- if (salesOrderLines.error) {- throw new Error("No sales order lines found");- }-- // Group sales order lines into demand periods- for (const line of salesOrderLines.data) {- if (!line.itemId || !line.quantityToSend) continue;-- const promiseDate = line.promisedDate- ? parseDate(line.promisedDate)- : today;- const requiredDate = promiseDate.add({- days: -(line?.leadTime ?? 7),- });-- // If promised date is before today, use first period- let period;- if (requiredDate.compare(today) < 0) {- period = demandPeriods[0];- } else {- // Find matching period for promised date- period = demandPeriods.find((p) => {- return (- p.startDate?.compare(requiredDate) <= 0 &&- p.endDate?.compare(requiredDate) >= 0- );- });- }-- if (period) {- const locationDemand = salesDemandByLocationAndPeriod.get(- line.locationId ?? ""- );- if (locationDemand) {- const periodDemand = locationDemand.get(period.id ?? "");- if (periodDemand) {- const currentDemand = periodDemand.get(line.itemId) ?? 0;- periodDemand.set(- line.itemId,- currentDemand + line.quantityToSend- );- }- }- }- }-- const demandActualUpserts: Database["public"]["Tables"]["demandActual"]["Insert"][] =- [];-- // Create a Map to store unique demand actuals by composite key- const demandActualsMap = new Map<- string,- Database["public"]["Tables"]["demandActual"]["Insert"]- >();-- // Get existing demand actuals- const { data: existingDemandActuals, error: demandActualsError } =- await client- .from("demandActual")- .select("*")- .in(- "itemId",- salesOrderLines.data.map((line) => line.itemId)- )- .in(- "demandPeriodId",- demandPeriods.map((p) => p.id ?? "")- );-- if (demandActualsError) throw demandActualsError;+ }- // First add all existing records with quantity 0- if (existingDemandActuals) {- for (const existing of existingDemandActuals) {- const key = `${existing.itemId}-${existing.locationId}-${existing.demandPeriodId}-${existing.sourceType}`;+ // Then add/update current demand for sales order lines+ for (const [locationId, periodMap] of salesDemandByLocationAndPeriod) {+ for (const [periodId, itemMap] of periodMap) {+ for (const [itemId, quantity] of itemMap) {+ if (quantity > 0) {+ const key = `${itemId}-${locationId}-${periodId}-Sales Order`;demandActualsMap.set(key, {- itemId: existing.itemId,- locationId: existing.locationId,- demandPeriodId: existing.demandPeriodId,- actualQuantity: 0,- sourceType: existing.sourceType,+ itemId,+ locationId,+ periodId: periodId,+ actualQuantity: quantity,+ sourceType: "Sales Order",+ companyId,createdBy: userId,updatedBy: userId,});}}-- // Then add/update current demand for sales order lines- for (const [locationId, periodMap] of salesDemandByLocationAndPeriod) {- for (const [periodId, itemMap] of periodMap) {- for (const [itemId, quantity] of itemMap) {- if (quantity > 0) {- const key = `${itemId}-${locationId}-${periodId}-Sales Order`;- demandActualsMap.set(key, {- itemId,- locationId,- demandPeriodId: periodId,- actualQuantity: quantity,- sourceType: "Sales Order",- createdBy: userId,- updatedBy: userId,- });- }- }- }- }-- // Convert Map values to array for upsert- demandActualUpserts.push(...demandActualsMap.values());-- try {- await db.transaction().execute(async (trx) => {- if (demandActualUpserts.length > 0) {- await trx- .insertInto("demandActual")- .values(demandActualUpserts)- .onConflict((oc) =>- oc- .columns([- "itemId",- "locationId",- "demandPeriodId",- "sourceType",- ])- .doUpdateSet({- actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),- updatedAt: new Date().toISOString(),- updatedBy: userId,- })- )- .execute();- }- });- return new Response(JSON.stringify({ success: true }), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 201,- });- } catch (err) {- console.error(err);- return new Response(JSON.stringify(err), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 500,- });- }}- case "job": {- const { id } = parsedPayload;-- const [job, jobMaterialLines] = await Promise.all([- client- .from("job")- .select("itemId")- .eq("id", id)- .eq("companyId", companyId)- .single(),- client- .from("openJobMaterialLines")- .select("*")- .eq("jobId", id)- .eq("companyId", companyId),- ]);-- if (job.error) {- throw new Error("No job found");- }-- if (jobMaterialLines.error) {- throw new Error("No job material lines found");- }-- // Group job material lines into demand periods- for (const line of jobMaterialLines.data) {- if (!line.itemId || !line.quantityToIssue) continue;-- const dueDate = line.dueDate ? parseDate(line.dueDate) : today;- const requiredDate = dueDate.add({ days: -(line.leadTime ?? 7) });-- // If required date is before today, use first period- let period;- if (requiredDate.compare(today) < 0) {- period = demandPeriods[0];- } else {- // Find matching period for required date- period = demandPeriods.find((p) => {- return (- p.startDate?.compare(requiredDate) <= 0 &&- p.endDate?.compare(requiredDate) >= 0- );- });- }-- if (period) {- const locationDemand = jobMaterialDemandByLocationAndPeriod.get(- line.locationId ?? ""- );- if (locationDemand) {- const periodDemand = locationDemand.get(period.id ?? "");- if (periodDemand) {- const currentDemand = periodDemand.get(line.itemId) ?? 0;- periodDemand.set(- line.itemId,- currentDemand + line.quantityToIssue- );- }- }- }- }+ }- const demandActualUpserts: Database["public"]["Tables"]["demandActual"]["Insert"][] =- [];-- // Create a Map to store unique demand actuals by composite key- const demandActualsMap = new Map<- string,- Database["public"]["Tables"]["demandActual"]["Insert"]- >();-- // Get existing demand actuals- const { data: existingDemandActuals, error: demandActualsError } =- await client- .from("demandActual")- .select("*")- .eq("itemId", job.data.itemId)- .in(- "demandPeriodId",- demandPeriods.map((p) => p.id ?? "")- );-- if (demandActualsError) throw demandActualsError;-- // First add all existing records with quantity 0- if (existingDemandActuals) {- for (const existing of existingDemandActuals) {- const key = `${existing.itemId}-${existing.locationId}-${existing.demandPeriodId}-${existing.sourceType}`;+ // Then add/update current demand for job material lines+ for (const [+ locationId,+ periodMap,+ ] of jobMaterialDemandByLocationAndPeriod) {+ for (const [periodId, itemMap] of periodMap) {+ for (const [itemId, quantity] of itemMap) {+ if (quantity > 0) {+ const key = `${itemId}-${locationId}-${periodId}-Job Material`;demandActualsMap.set(key, {- itemId: existing.itemId,- locationId: existing.locationId,- demandPeriodId: existing.demandPeriodId,- actualQuantity: 0,- sourceType: existing.sourceType,+ itemId,+ locationId,+ periodId: periodId,+ actualQuantity: quantity,+ sourceType: "Job Material",+ companyId,createdBy: userId,updatedBy: userId,});}}+ }+ }- // Then add/update current demand for job material lines- for (const [- locationId,- periodMap,- ] of jobMaterialDemandByLocationAndPeriod) {- for (const [periodId, itemMap] of periodMap) {- for (const [itemId, quantity] of itemMap) {- if (quantity > 0) {- const key = `${itemId}-${locationId}-${periodId}-Job Material`;- demandActualsMap.set(key, {- itemId,- locationId,- demandPeriodId: periodId,- actualQuantity: quantity,- sourceType: "Job Material",- createdBy: userId,+ // Convert Map values to array for upsert+ demandActualUpserts.push(...demandActualsMap.values());++ try {+ await db.transaction().execute(async (trx) => {+ if (demandActualUpserts.length > 0) {+ await trx+ .insertInto("demandActual")+ .values(demandActualUpserts)+ .onConflict((oc) =>+ oc+ .columns(["itemId", "locationId", "periodId", "sourceType"])+ .doUpdateSet({+ actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),+ updatedAt: new Date().toISOString(),updatedBy: userId,- });- }- }- }- }-- // Convert Map values to array for upsert- demandActualUpserts.push(...demandActualsMap.values());-- try {- await db.transaction().execute(async (trx) => {- if (demandActualUpserts.length > 0) {- await trx- .insertInto("demandActual")- .values(demandActualUpserts)- .onConflict((oc) =>- oc- .columns([- "itemId",- "locationId",- "demandPeriodId",- "sourceType",- ])- .doUpdateSet({- actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),- updatedAt: new Date().toISOString(),- updatedBy: userId,- })- )- .execute();- }- });-- return new Response(JSON.stringify({ success: true }), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 201,- });- } catch (err) {- console.error(err);- return new Response(JSON.stringify(err), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 500,- });+ })+ )+ .execute();}- }- default: {- throw new Error("Invalid type");- }+ });++ return new Response(JSON.stringify({ success: true }), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 201,+ });+ } catch (err) {+ console.error(err);+ return new Response(JSON.stringify(err), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });}} catch (err) {console.error(err);@@ -723,7 +392,7 @@ async function getOrCreateDemandPeriods() {// Get all existing periods for these datesconst existingPeriods = await db- .selectFrom("demandPeriod")+ .selectFrom("period").selectAll().where("startDate",@@ -762,7 +431,7 @@ async function getOrCreateDemandPeriods(// Create missing periods in a transactionconst created = await db.transaction().execute(async (trx) => {return await trx- .insertInto("demandPeriod")+ .insertInto("period").values(periodsToCreate.map((period) => ({startDate: period.startDate,diff --git a/packages/database/supabase/migrations/20250610000433_demand-planning.sql b/packages/database/supabase/migrations/20250610000433_demand-planning.sqlindex 56f7211453..12e68dc255 100644--- a/packages/database/supabase/migrations/20250610000433_demand-planning.sql+++ b/packages/database/supabase/migrations/20250610000433_demand-planning.sql@@ -1,6 +1,11 @@+ALTER TABLE "jobOperation" ADD COLUMN "startDate" DATE;ALTER TABLE "jobOperation" ADD COLUMN "dueDate" DATE;+ALTER TABLE "itemPlanning" ALTER COLUMN "demandAccumulationPeriod" SET DEFAULT 30;+UPDATE "itemPlanning" SET "demandAccumulationPeriod" = 30;++ALTER TABLE "itemReplenishment" ADD COLUMN "leadTime" INTEGER NOT NULL DEFAULT 7;UPDATE "itemReplenishment"SET "leadTime" = "purchasingLeadTime"@@ -13,38 +18,40 @@ ALTER TABLE "itemReplenishment" DROP COLUMN "purchasingLeadTime";-- Demand Planning Tables-- Enum types-CREATE TYPE "demandPeriodType" AS ENUM ('Week', 'Day', 'Month');+CREATE TYPE "periodType" AS ENUM ('Week', 'Day', 'Month');CREATE TYPE "demandSourceType" AS ENUM ('Sales Order', 'Job Material');-- Time periods table for flexible bucketing (weeks initially, days in future)-CREATE TABLE "demandPeriod" (+CREATE TABLE "period" ("id" TEXT NOT NULL DEFAULT xid(),"startDate" DATE NOT NULL,"endDate" DATE NOT NULL,- "periodType" "demandPeriodType" NOT NULL,+ "periodType" "periodType" NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),- CONSTRAINT "demandPeriod_pkey" PRIMARY KEY ("id")+ CONSTRAINT "period_pkey" PRIMARY KEY ("id"));-- Demand forecasts table for estimatesCREATE TABLE "demandForecast" ("itemId" TEXT NOT NULL,"locationId" TEXT,- "demandPeriodId" TEXT NOT NULL,+ "periodId" TEXT NOT NULL,"forecastQuantity" NUMERIC(15,5) NOT NULL DEFAULT 0,"forecastMethod" TEXT, -- 'manual', 'statistical', 'ml', etc."confidence" NUMERIC(3,2), -- 0.00 to 1.00"notes" TEXT,+ "companyId" TEXT NOT NULL,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedBy" TEXT NOT NULL,- CONSTRAINT "demandForecast_pkey" PRIMARY KEY ("itemId", "locationId", "demandPeriodId"),+ CONSTRAINT "demandForecast_pkey" PRIMARY KEY ("itemId", "locationId", "periodId"),CONSTRAINT "demandForecast_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,CONSTRAINT "demandForecast_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,- CONSTRAINT "demandForecast_demandPeriodId_fkey" FOREIGN KEY ("demandPeriodId") REFERENCES "demandPeriod"("id") ON DELETE CASCADE,+ CONSTRAINT "demandForecast_periodId_fkey" FOREIGN KEY ("periodId") REFERENCES "period"("id") ON DELETE CASCADE,+ CONSTRAINT "demandForecast_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,CONSTRAINT "demandForecast_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT,CONSTRAINT "demandForecast_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT);@@ -53,37 +60,39 @@ CREATE TABLE "demandForecast" (CREATE TABLE "demandActual" ("itemId" TEXT NOT NULL,"locationId" TEXT,- "demandPeriodId" TEXT NOT NULL,+ "periodId" TEXT NOT NULL,"actualQuantity" NUMERIC(15,5) NOT NULL DEFAULT 0,"sourceType" "demandSourceType" NOT NULL,"notes" TEXT,+ "companyId" TEXT NOT NULL,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedBy" TEXT NOT NULL,- CONSTRAINT "demandActual_pkey" PRIMARY KEY ("itemId", "locationId", "demandPeriodId", "sourceType"),+ CONSTRAINT "demandActual_pkey" PRIMARY KEY ("itemId", "locationId", "periodId", "sourceType"),CONSTRAINT "demandActual_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,CONSTRAINT "demandActual_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,- CONSTRAINT "demandActual_demandPeriodId_fkey" FOREIGN KEY ("demandPeriodId") REFERENCES "demandPeriod"("id") ON DELETE CASCADE,+ CONSTRAINT "demandActual_periodId_fkey" FOREIGN KEY ("periodId") REFERENCES "period"("id") ON DELETE CASCADE,+ CONSTRAINT "demandActual_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,CONSTRAINT "demandActual_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT,CONSTRAINT "demandActual_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT);-- Indexes for performance-CREATE INDEX "demandPeriod_startDate_endDate_idx" ON "demandPeriod" ("periodType", "startDate", "endDate");+CREATE INDEX "period_startDate_endDate_idx" ON "period" ("periodType", "startDate", "endDate");-CREATE INDEX "demandPeriod_startDate_idx" ON "demandPeriod" ("periodType","startDate");-CREATE INDEX "demandPeriod_endDate_idx" ON "demandPeriod" ("periodType", "endDate");+CREATE INDEX "period_startDate_idx" ON "period" ("periodType","startDate");+CREATE INDEX "period_endDate_idx" ON "period" ("periodType", "endDate");-CREATE INDEX "demandForecast_itemId_locationId_demandPeriodId_idx" ON "demandForecast" ("itemId", "locationId", "demandPeriodId");+CREATE INDEX "demandForecast_itemId_locationId_periodId_idx" ON "demandForecast" ("itemId", "locationId", "periodId");CREATE INDEX "demandForecast_createdAt_idx" ON "demandForecast" ("createdAt");-CREATE INDEX "demandActual_itemId_locationId_demandPeriodId_idx" ON "demandActual" ("itemId", "locationId", "demandPeriodId");+CREATE INDEX "demandActual_itemId_locationId_periodId_idx" ON "demandActual" ("itemId", "locationId", "periodId");CREATE INDEX "demandActual_createdAt_idx" ON "demandActual" ("createdAt");-- Unique constraints to prevent duplicate forecasts/actuals for same item/location/period-CREATE UNIQUE INDEX "demandForecast_unique_item_location_period_idx" ON "demandForecast" ("itemId", COALESCE("locationId", ''), "demandPeriodId");+CREATE UNIQUE INDEX "demandForecast_unique_item_location_period_idx" ON "demandForecast" ("itemId", COALESCE("locationId", ''), "periodId");CREATE OR REPLACE VIEW "openSalesOrderLines" AS (SELECT@@ -120,15 +129,14 @@ CREATE OR REPLACE VIEW "openJobMaterialLines" AS (jm."companyId",i1."replenishmentSystem",i1."itemTrackingType",- ir1."leadTime" + ir2."leadTime" AS "leadTime",+ ir."leadTime" AS "leadTime",j."locationId",j."dueDate"FROM "jobMaterial" jmINNER JOIN "job" j ON jm."jobId" = j."id"INNER JOIN "item" i1 ON jm."itemId" = i1."id"- INNER JOIN "itemReplenishment" ir1 ON i1."id" = ir1."itemId"INNER JOIN "item" i2 ON j."itemId" = i2."id"- INNER JOIN "itemReplenishment" ir2 ON i2."id" = ir2."itemId"+ INNER JOIN "itemReplenishment" ir ON i2."id" = ir."itemId"WHERE j."status" IN ('Draft','Ready',