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 supply and demand card
Brad Barbinb1c705d98659
diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsxindex 360e951dbd..966ba3af99 100644--- a/apps/erp/app/components/Table/Table.tsx+++ b/apps/erp/app/components/Table/Table.tsx@@ -44,6 +44,7 @@ import type {EditableTableCellComponent,Position,} from "~/components/Editable";+import { useSavedViews } from "~/hooks/useSavedViews";import type { fieldMappings } from "~/modules/shared";import {IndeterminateCheckbox,@@ -57,7 +58,6 @@ import type { ColumnFilter } from "./components/Filter/types";import { useFilters } from "./components/Filter/useFilters";import type { ColumnSizeMap } from "./types";import { getAccessorKey, updateNestedProperty } from "./utils";-import { useSavedViews } from "~/hooks/useSavedViews";interface TableProps<T extends object> {columns: ColumnDef<T>[];@@ -134,6 +134,7 @@ const Table = <T extends object>({const [columnOrder, setColumnOrder] = useState<ColumnOrderState>(currentView?.columnOrder ?? defaultColumnOrder ?? []);+const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(() => {const left: string[] = [];const right: string[] = [];@@ -143,6 +144,7 @@ const Table = <T extends object>({if (renderContextMenu) {right.push("Actions");}+if (currentView?.columnPinning) {return currentView.columnPinning;}@@ -154,6 +156,17 @@ const Table = <T extends object>({left.push(...defaultColumnPinning.left);}+ if (+ defaultColumnPinning &&+ "right" in defaultColumnPinning &&+ Array.isArray(defaultColumnPinning.right)+ ) {+ console.log("adding right");+ right.push(...defaultColumnPinning.right);+ } else {+ console.log("no right");+ }+return {left,right,@@ -186,6 +199,14 @@ const Table = <T extends object>({left.push(...defaultColumnPinning.left);}+ if (+ defaultColumnPinning &&+ "right" in defaultColumnPinning &&+ Array.isArray(defaultColumnPinning.right)+ ) {+ right.push(...defaultColumnPinning.right);+ }+return {left,right,@@ -620,7 +641,11 @@ const Table = <T extends object>({left: isPinned === "left" ? startX : undefined,right: isPinned === "right" ? 0 : undefined,zIndex: 2,- maxWidth: isPinned === "right" ? 60 : undefined,+ maxWidth:+ isPinned === "right" &&+ column.columnDef.header?.toString() === "Actions"+ ? 60+ : undefined,};};diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex 9c3009b733..1a89fb115d 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -435,17 +435,15 @@ export const itemPlanningValidator = z.object({message: "Reordering policy is required",}),}),- critical: zfd.checkbox(),- safetyStockQuantity: zfd.numeric(z.number().min(0).optional()),- safetyStockLeadTime: zfd.numeric(z.number().min(0).optional()),demandAccumulationPeriod: 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(),- reorderMaximumInventory: zfd.numeric(z.number().min(0)).optional(),+ maximumInventoryQuantity: zfd.numeric(z.number().min(0)).optional(),minimumOrderQuantity: zfd.numeric(z.number().min(0)).optional(),maximumOrderQuantity: zfd.numeric(z.number().min(0)).optional(),orderMultiple: zfd.numeric(z.number().min(1)),+ // critical: zfd.checkbox(),});export const itemPurchasingValidator = z.object({diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex eee5cd5e1a..793c7048e8 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -1023,6 +1023,78 @@ function getMethodTreeArrayToTree(items: Method[]): MethodTreeItem[] {return rootItems.map((item) => traverseAndRenameIds(item));}+export async function getOpenJobMaterials(+ client: SupabaseClient<Database>,+ {+ itemId,+ companyId,+ locationId,+ }: { itemId: string; companyId: string; locationId: string }+) {+ return client+ .from("openJobMaterialLines")+ .select(+ "id, parentMaterialId, jobMakeMethodId, quantity:quantityToIssue, documentReadableId:jobReadableId, documentId:jobId, dueDate"+ )+ .eq("itemId", itemId)+ .eq("locationId", locationId)+ .eq("companyId", companyId);+}++export async function getOpenProductionOrders(+ client: SupabaseClient<Database>,+ {+ itemId,+ companyId,+ locationId,+ }: { itemId: string; companyId: string; locationId: string }+) {+ return client+ .from("openProductionOrders")+ .select(+ "id, quantity:quantityToReceive, documentReadableId:jobId, documentId:id, dueDate"+ )+ .eq("itemId", itemId)+ .eq("locationId", locationId)+ .eq("companyId", companyId);+}++export async function getOpenPurchaseOrderLines(+ client: SupabaseClient<Database>,+ {+ itemId,+ companyId,+ locationId,+ }: { itemId: string; companyId: string; locationId: string }+) {+ return client+ .from("openPurchaseOrderLines")+ .select(+ "id, quantity:quantityToReceive, dueDate:promisedDate, ...purchaseOrder(documentReadableId:purchaseOrderId, documentId:id)"+ )+ .eq("itemId", itemId)+ .eq("locationId", locationId)+ .eq("companyId", companyId);+}++export async function getOpenSalesOrderLines(+ client: SupabaseClient<Database>,+ {+ itemId,+ companyId,+ locationId,+ }: { itemId: string; companyId: string; locationId: string }+) {+ return client+ .from("openSalesOrderLines")+ .select(+ "id, quantity:quantityToSend, dueDate:promisedDate, ...salesOrder(documentReadableId:salesOrderId, documentId:id)"+ )+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .eq("locationId", locationId);+}+export async function getPart(client: SupabaseClient<Database>,itemId: string,diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsxindex b9592d3d32..a71adb1fd4 100644--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx@@ -1,10 +1,20 @@import {Card,+ CardAction,CardContent,+ CardDescription,CardHeader,CardTitle,+ cn,+ HStack,+ Input,Loading,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,useMount,+ VStack,} from "@carbon/react";import type { ChartConfig } from "@carbon/react/Chart";import {@@ -12,17 +22,27 @@ import {ChartTooltip,ChartTooltipContent,} from "@carbon/react/Chart";+import { formatDate } from "@carbon/utils";import { getLocalTimeZone, parseDate } from "@internationalized/date";-import { useDateFormatter } from "@react-aria/i18n";+import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";import { useFetcher } from "@remix-run/react";-import { useMemo } from "react";+import { useMemo, useState } from "react";import {+ LuClipboardList,+ LuCrown,+ LuFactory,+ LuMoveDown,+ LuMoveUp,+ LuSearch,+ LuShoppingCart,+} from "react-icons/lu";+import {+ Area,Bar,CartesianGrid,ComposedChart,Legend,- Line,ReferenceLine,XAxis,YAxis,@@ -32,7 +52,7 @@ import type { loader as forecastLoader } from "~/routes/api+/items.$id.$locationimport { path } from "~/utils/path";interface Data {- actualQuantity: number;+ quantity: number;companyId: string;createdAt: string;createdBy: string;@@ -42,7 +62,10 @@ interface Data {periodId: string;updatedAt: string;updatedBy: string;+ documentReadableId: string;+ dueDate: string;}+const supplySourceTypes = ["Purchase Order", "Production Order"] as const;const demandSourceTypes = ["Sales Order", "Job Material"] as const;@@ -64,6 +87,8 @@ interface ChartDataPoint {Projection: number;}+const chartConfig = {} satisfies ChartConfig;+export const ItemPlanningChart = ({itemId,locationId,@@ -73,12 +98,15 @@ export const ItemPlanningChart = ({}) => {const forecastFetcher = useFetcher<typeof forecastLoader>();const isFetching = forecastFetcher.state !== "idle" || !forecastFetcher.data;+ const [searchTerm, setSearchTerm] = useState("");const dateFormatter = useDateFormatter({month: "short",day: "numeric",});+ const numberFormatter = useNumberFormatter();+useMount(() => {forecastFetcher.load(path.to.api.itemForecast(itemId, locationId));});@@ -110,16 +138,33 @@ export const ItemPlanningChart = ({);// Add demand data- demand.forEach((curr: DemandData) => {- if (groupedData[curr.periodId]) {- groupedData[curr.periodId][curr.sourceType] -= curr.actualQuantity;+ demand.forEach((curr) => {+ if (+ groupedData[curr.periodId] &&+ curr.sourceType &&+ curr.actualQuantity+ ) {+ const sourceType = curr.sourceType as keyof ChartDataPoint;+ if (sourceType === "Sales Order" || sourceType === "Job Material") {+ groupedData[curr.periodId][sourceType] = -(curr.actualQuantity ?? 0);+ }}});// Add supply data- supply.forEach((curr: SupplyData) => {- if (groupedData[curr.periodId]) {- groupedData[curr.periodId][curr.sourceType] += curr.actualQuantity;+ supply.forEach((curr) => {+ if (+ groupedData[curr.periodId] &&+ curr.sourceType &&+ curr.actualQuantity+ ) {+ const sourceType = curr.sourceType as keyof ChartDataPoint;+ if (+ sourceType === "Purchase Order" ||+ sourceType === "Production Order"+ ) {+ groupedData[curr.periodId][sourceType] = curr.actualQuantity ?? 0;+ }}});@@ -142,7 +187,55 @@ export const ItemPlanningChart = ({});}, [forecastFetcher.data]);- const chartConfig = {} satisfies ChartConfig;+ const combinedSupplyAndDemand = useMemo(() => {+ let projectedQuantity = forecastFetcher.data?.quantityOnHand ?? 0;++ const combined = [+ ...(forecastFetcher.data?.openSalesOrderLines ?? []).map((line) => ({+ ...line,+ sourceType: "Sales Order",+ quantity: line.quantity ?? 0,+ })),+ ...(forecastFetcher.data?.openJobMaterials ?? []).map((line) => ({+ ...line,+ sourceType: "Job Material",+ quantity: line.quantity ?? 0,+ })),+ ...(forecastFetcher.data?.openPurchaseOrderLines ?? []).map((line) => ({+ ...line,+ sourceType: "Purchase Order",+ quantity: line.quantity ?? 0,+ })),+ ...(forecastFetcher.data?.openProductionOrders ?? []).map((line) => ({+ ...line,+ sourceType: "Production Order",+ quantity: line.quantity ?? 0,+ })),+ ]+ .sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""))+ .map((item) => {+ if (+ item.sourceType === "Sales Order" ||+ item.sourceType === "Job Material"+ ) {+ projectedQuantity -= item.quantity;+ } else {+ projectedQuantity += item.quantity;+ }+ return {+ ...item,+ projectedQuantity,+ };+ });++ if (!searchTerm) return combined;++ return combined.filter((item) =>+ (item.documentReadableId ?? "")+ .toLowerCase()+ .includes(searchTerm.toLowerCase())+ );+ }, [forecastFetcher.data, searchTerm]);if (forecastFetcher.data?.demand.length === 0 &&@@ -206,6 +299,15 @@ export const ItemPlanningChart = ({/>}/>+ <Area+ type="monotone"+ dataKey="Projection"+ strokeWidth={1}+ dot={false}+ stroke="#7c3aed"+ fill="#7c3aedcc"+ isAnimationActive={false}+ />{demandSourceTypes.map((sourceType: string, index: number) => (<Bar@@ -226,20 +328,178 @@ export const ItemPlanningChart = ({/>))}- <Line- type="monotone"- dataKey="Projection"- strokeWidth={2}- dot={false}- stroke="#7c3aed"- isAnimationActive={false}- /></ComposedChart></ChartContainer></Loading></div></CardContent></Card>+ <Tabs defaultValue="all" className="w-full">+ <Card>+ <HStack className="w-full justify-between">+ <CardHeader>+ <CardTitle>Supply & Demand</CardTitle>+ </CardHeader>+ <CardAction className="flex items-center gap-2">+ <TabsList>+ <TabsTrigger value="all">All</TabsTrigger>+ <TabsTrigger value="supply">Supply</TabsTrigger>+ <TabsTrigger value="demand">Demand</TabsTrigger>+ </TabsList>+ </CardAction>+ </HStack>+ <CardContent>+ <div className="w-full grid grid-cols-1 lg:grid-cols-3 gap-4 py-4">+ <Card>+ <CardHeader className="pb-8">+ <CardDescription>+ <VStack>Quantity on Hand</VStack>+ </CardDescription>+ <CardTitle className="text-4xl ">+ <div className="flex justify-start items-center gap-1">+ {`${numberFormatter.format(+ forecastFetcher.data?.quantityOnHand ?? 0+ )}`}+ </div>+ </CardTitle>+ </CardHeader>+ </Card>+ <Card>+ <CardHeader className="pb-8">+ <CardDescription>+ <VStack>Incoming</VStack>+ </CardDescription>+ <CardTitle className="text-4xl ">+ <div className="flex justify-start items-center gap-1">+ {`${numberFormatter.format(+ forecastFetcher.data?.supply.reduce(+ (acc, curr) => acc + (curr.actualQuantity ?? 0),+ 0+ ) ?? 0+ )}`}+ <LuMoveUp className="text-emerald-500 text-lg" />+ </div>+ </CardTitle>+ </CardHeader>+ </Card>+ <Card>+ <CardHeader className="pb-8">+ <CardDescription>+ <VStack>Outgoing</VStack>+ </CardDescription>+ <CardTitle className="text-4xl ">+ <div className="flex justify-start items-center gap-1">+ {`${numberFormatter.format(+ forecastFetcher.data?.demand.reduce(+ (acc, curr) => acc + (curr.actualQuantity ?? 0),+ 0+ ) ?? 0+ )}`}+ <LuMoveDown className="text-red-500 text-lg" />+ </div>+ </CardTitle>+ </CardHeader>+ </Card>+ </div>++ <div className="relative w-full mb-4">+ <Input+ placeholder="Search"+ value={searchTerm}+ onChange={(e) => setSearchTerm(e.target.value)}+ className="pl-10"+ />+ <LuSearch className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />+ </div>++ <TabsContent value="all" className="border rounded-lg">+ {combinedSupplyAndDemand.map((item, index) => (+ <SupplyDemandListItem key={index} item={item} />+ ))}+ </TabsContent>++ <TabsContent value="supply" className="border rounded-lg">+ {combinedSupplyAndDemand+ .filter((item) =>+ supplySourceTypes.includes(+ item.sourceType as (typeof supplySourceTypes)[number]+ )+ )+ .map((item, index) => (+ <SupplyDemandListItem key={index} item={item} />+ ))}+ </TabsContent>++ <TabsContent value="demand" className="border rounded-lg">+ {combinedSupplyAndDemand+ .filter((item) =>+ demandSourceTypes.includes(+ item.sourceType as (typeof demandSourceTypes)[number]+ )+ )+ .map((item, index) => (+ <SupplyDemandListItem key={index} item={item} />+ ))}+ </TabsContent>+ </CardContent>+ </Card>+ </Tabs></>);};++interface ListItem {+ sourceType: string;+ id: string | null;+ dueDate: string | null;+ documentReadableId: string | null;+ documentId: string | null;+ quantity: number;+ projectedQuantity: number;+}++const sourceTypeIcons = {+ "Sales Order": <LuCrown className="h-4 w-4 text-teal-500" />,+ "Job Material": <LuClipboardList className="h-4 w-4 text-teal-500" />,+ "Purchase Order": <LuShoppingCart className="h-4 w-4 text-blue-600" />,+ "Production Order": <LuFactory className="h-4 w-4 text-blue-600" />,+};++function SupplyDemandListItem({ item }: { item: ListItem }) {+ const numberFormatter = useNumberFormatter();++ return (+ <div className="flex flex-1 justify-between items-center w-full p-4 border-b last:border-b-0">+ <HStack spacing={4} className="w-1/2">+ <HStack spacing={4} className="flex-1">+ <div className="bg-muted border rounded-full flex items-center justify-center p-2">+ {sourceTypeIcons[item.sourceType as keyof typeof sourceTypeIcons]}+ </div>+ <VStack spacing={0}>+ <span className="text-sm font-medium">+ {item.documentReadableId}+ </span>+ <span className="text-xs text-muted-foreground">+ {item.dueDate ? formatDate(item.dueDate) : "No due date"}+ </span>+ </VStack>+ <div className="flex items-center gap-1 text-sm text-muted-foreground text-right">+ <span>{numberFormatter.format(item.quantity)}</span>+ {item.sourceType === "Sales Order" ||+ item.sourceType === "Job Material" ? (+ <LuMoveDown className="text-red-500" />+ ) : (+ <LuMoveUp className="text-emerald-500" />+ )}+ </div>+ </HStack>+ </HStack>++ <span+ className={cn("text-sm", item.projectedQuantity < 0 && "text-red-500")}+ >+ {numberFormatter.format(item.projectedQuantity)}+ </span>+ </div>+ );+}diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsxindex b56cfab01d..8308201052 100644--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx@@ -94,23 +94,10 @@ const ItemPlanningForm = ({{policy === "Maximum Quantity" && (<><Number- name="safetyStockQuantity"- label="Safety Stock Quantity"- />- <Number- name="safetyStockLeadTime"- label="Safety Stock Lead Time (Days)"- />- <Number- name="minimumOrderQuantity"- label="Minimum Order Quantity"- minValue={0}- />- <Number- name="maximumOrderQuantity"- label="Maximum Order Quantity"- minValue={0}+ name="maximumInventoryQuantity"+ label="Maximum Inventory Quantity"/>+ <div /></>)}@@ -121,6 +108,10 @@ const ItemPlanningForm = ({label="Demand Accumulation Period (Days)"minValue={0}/>+ <Boolean+ name="demandAccumulationIncludesInventory"+ label="Demand Includes Inventory"+ /></>)}{policy === "Fixed Reorder Quantity" && (@@ -131,24 +122,22 @@ const ItemPlanningForm = ({label="Reorder Quantity"minValue={0}/>- <Number- name="reorderMaximumInventory"- label="Reorder Maximum Inventory"- minValue={0}- /></>)}<Number name="orderMultiple" label="Order Multiple" minValue={0} />- <Boolean name="critical" label="Critical" />- {policy === "Demand-Based Reorder" && (- <>- <Boolean- name="demandAccumulationIncludesInventory"- label="Demand Includes Inventory"- />- </>- )}+ <Number+ name="minimumOrderQuantity"+ label="Minimum Order Quantity"+ minValue={0}+ />+ <Number+ name="maximumOrderQuantity"+ label="Maximum Order Quantity"+ minValue={0}+ />+ {/* <Boolean name="critical" label="Critical" /> */}+<CustomFormFields table="partPlanning" /></div></CardContent>diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsxnew file mode 100644index 0000000000..617665b5f2--- /dev/null+++ b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx@@ -0,0 +1,66 @@+import type { Database } from "@carbon/database";+import { Status } from "@carbon/react";+import type { ProductionPlanningItem } from "~/modules/production";++export function ItemReorderPolicy({+ reorderingPolicy,+ className,+}: {+ reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"];+ className?: string;+}) {+ switch (reorderingPolicy) {+ case "Manual Reorder":+ return (+ <Status color="gray" className={className}>+ Manual+ </Status>+ );+ case "Demand-Based Reorder":+ return (+ <Status color="blue" className={className}>+ Demand-Based{" "}+ </Status>+ );+ case "Fixed Reorder Quantity":+ return (+ <Status color="green" className={className}>+ Fixed Reorder+ </Status>+ );+ case "Maximum Quantity":+ return (+ <Status color="purple" className={className}>+ Max Quantity+ </Status>+ );+ }+}++export function getReorderPolicyDescription(+ itemPlanning: ProductionPlanningItem+) {+ switch (itemPlanning.reorderingPolicy) {+ case "Manual Reorder":+ return "Manually reorder the item";+ case "Demand-Based Reorder":+ return "Demand-Based";+ case "Fixed Reorder Quantity":+ const reorderPoint = itemPlanning.reorderPoint;+ const reorderQuantity = itemPlanning.reorderQuantity;++ const orderMultiple = itemPlanning.orderMultiple;+ const minimumOrderQuantity = Math.min(+ itemPlanning.minimumOrderQuantity ?? 0,+ reorderQuantity+ );+ const maximumOrderQuantity = Math.min(+ itemPlanning.maximumOrderQuantity ?? 0,+ reorderQuantity+ );++ return "Fixed Reorder Quantity";+ case "Maximum Quantity":+ return "Max Quantity";+ }+}diff --git a/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx b/apps/erp/app/modules/items/ui/useItemsSubmodules.tsxindex ba27e05c4a..01477b7eec 100644--- a/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx+++ b/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx@@ -14,7 +14,7 @@ import { path } from "~/utils/path";const itemsRoutes: AuthenticatedRouteGroup[] = [{- name: "Items",+ name: "Manage",routes: [{name: "Parts",diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsxindex 36a50749b2..3f976c64e8 100644--- a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx+++ b/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx@@ -1,6 +1,5 @@import {Button,- Checkbox,Combobox,HStack,Tooltip,@@ -16,7 +15,7 @@ import { memo, useMemo } from "react";import {LuBookMarked,LuBox,- LuCheck,+ LuCircleCheck,LuCirclePlay,LuPackage,} from "react-icons/lu";@@ -31,6 +30,10 @@ import { useLocations } from "~/components/Form/Location";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import { useUrlParams } from "~/hooks";import { itemTypes } from "~/modules/inventory/inventory.models";+import {+ getReorderPolicyDescription,+ ItemReorderPolicy,+} from "~/modules/items/ui/Item/ItemReorderPolicy";import type { action as mrpAction } from "~/routes/api+/mrp";import { path } from "~/utils/path";import type { ProductionPlanningItem } from "../../types";@@ -107,7 +110,9 @@ const PlanningTable = memo(/><Hyperlink- to={`${path.to.inventoryItem(row.original.id!)}/?${params}`}+ to={`${path.to.productionPlanningItem(+ row.original.id!+ )}?${params.toString()}`}><VStack spacing={0}>{row.original.readableIdWithRevision}@@ -129,6 +134,22 @@ const PlanningTable = memo(icon: <LuBookMarked />,},},+ {+ accessorKey: "reorderingPolicy",+ header: "Reorder Policy",+ cell: ({ row }) => (+ <Tooltip>+ <TooltipTrigger>+ <ItemReorderPolicy+ reorderingPolicy={row.original.reorderingPolicy}+ />+ </TooltipTrigger>+ <TooltipContent>+ {getReorderPolicyDescription(row.original)}+ </TooltipContent>+ </Tooltip>+ ),+ },{accessorKey: "quantityOnHand",header: "On Hand",@@ -152,34 +173,31 @@ const PlanningTable = memo(meta: {filter: {type: "static",- options: itemTypes.map((type) => ({- label: (- <HStack spacing={2}>- <MethodItemTypeIcon type={type} />- <span>{type}</span>- </HStack>- ),- value: type,- })),+ options: itemTypes+ .filter((t) => ["Part", "Tool"].includes(t))+ .map((type) => ({+ label: (+ <HStack spacing={2}>+ <MethodItemTypeIcon type={type} />+ <span>{type}</span>+ </HStack>+ ),+ value: type,+ })),},icon: <LuBox />,},},{- accessorKey: "active",- header: "Active",- cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,- meta: {- filter: {- type: "static",- options: [- { value: "true", label: "Active" },- { value: "false", label: "Inactive" },- ],- },- pluralHeader: "Active Statuses",- icon: <LuCheck />,- },+ id: "Order",+ header: "",+ cell: ({ row }) => (+ <HStack>+ <Button variant="secondary" leftIcon={<LuCircleCheck />}>+ Order+ </Button>+ </HStack>+ ),},];}, [periods, dateFormatter, numberFormatter, params, unitOfMeasures]);@@ -191,6 +209,7 @@ const PlanningTable = memo(const defaultColumnPinning = {left: ["readableIdWithRevision"],+ right: ["Order"],};const mrpFetcher = useFetcher<typeof mrpAction>();diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsxindex 3aea20a4f7..d2c072bc96 100644--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx@@ -20,6 +20,11 @@ const productionRoutes: AuthenticatedRouteGroup[] = [icon: <LuHardHat />,table: "job",},+ ],+ },+ {+ name: "Plan",+ routes: [{name: "Planning",to: path.to.productionPlanning,diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.tsindex 0c432fc49e..4bf4beeb64 100644--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts@@ -7,6 +7,10 @@ import {getItemDemand,getItemQuantities,getItemSupply,+ getOpenJobMaterials,+ getOpenProductionOrders,+ getOpenPurchaseOrderLines,+ getOpenSalesOrderLines,} from "~/modules/items/items.service";import { getPeriods } from "~/modules/shared/shared.service";@@ -15,6 +19,10 @@ const defaultResponse = {supply: [],periods: [],quantityOnHand: 0,+ openSalesOrderLines: [],+ openJobMaterials: [],+ openProductionOrders: [],+ openPurchaseOrderLines: [],};const WEEKS_TO_FORECAST = 12 * 4;@@ -42,7 +50,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const [demand, supply, quantities] = await Promise.all([+ const [+ demand,+ supply,+ quantities,+ openSalesOrderLines,+ openJobMaterials,+ openProductionOrders,+ openPurchaseOrderLines,+ ] = await Promise.all([getItemDemand(client, {itemId,locationId,@@ -56,6 +72,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {companyId,}),getItemQuantities(client, itemId, companyId, locationId),+ getOpenSalesOrderLines(client, { itemId, companyId, locationId }),+ getOpenJobMaterials(client, { itemId, companyId, locationId }),+ getOpenProductionOrders(client, { itemId, companyId, locationId }),+ getOpenPurchaseOrderLines(client, { itemId, companyId, locationId }),]);if (demand.error) {@@ -77,5 +97,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {supply: supply.data,periods: periods.data,quantityOnHand: quantities.data?.quantityOnHand ?? 0,+ openSalesOrderLines: openSalesOrderLines.data ?? [],+ openJobMaterials: openJobMaterials.data ?? [],+ openProductionOrders: openProductionOrders.data ?? [],+ openPurchaseOrderLines: openPurchaseOrderLines.data ?? [],});}diff --git a/apps/erp/app/routes/x+/production+/planning.$itemId.tsx b/apps/erp/app/routes/x+/production+/planning.$itemId.tsxnew file mode 100644index 0000000000..cc8394be99--- /dev/null+++ b/apps/erp/app/routes/x+/production+/planning.$itemId.tsx@@ -0,0 +1,97 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import {+ Button,+ ResizableHandle,+ ResizablePanel,+ ScrollArea,+ VStack,+} from "@carbon/react";+import { useRouteData, useUrlParams } from "@carbon/remix";+import { Link, useLoaderData, useNavigate, useParams } from "@remix-run/react";+import type { LoaderFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";+import { LuExternalLink, LuX } from "react-icons/lu";+import { useUser } from "~/hooks/useUser";+import { getItem } from "~/modules/items/items.service";+import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";+import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { itemId } = params;+ if (!itemId) {+ throw new Error("itemId not found");+ }++ const item = await getItem(client, itemId);++ return json({ item: item.data });+}++export default function ProductionPlanningDetailsRoute() {+ const { itemId } = useParams();+ if (!itemId) {+ throw new Error("itemId not found");+ }++ const { item } = useLoaderData<typeof loader>();++ const routeData = useRouteData<{ locationId: string }>(+ path.to.productionPlanning+ );++ const navigate = useNavigate();+ const [params] = useUrlParams();+ const { defaults } = useUser();++ return (+ <>+ <ResizableHandle withHandle />+ <ResizablePanel+ defaultSize={50}+ maxSize={70}+ minSize={25}+ className="bg-muted"+ >+ <ScrollArea className="h-[calc(100dvh-49px)]">+ <div className="w-full">+ <div className="flex justify-between items-center border-b border-border p-2 bg-card w-full">+ <Button+ isIcon+ variant="ghost"+ onClick={() =>+ navigate(`${path.to.productionPlanning}?${params.toString()}`)+ }+ >+ <LuX className="w-4 h-4" />+ </Button>+ {item && (+ <span className="flex items-center font-semibold text-center">+ {item.readableIdWithRevision ?? item.readableId}{" "}+ <Link+ to={getLinkToItemDetails(item.type as "Part", itemId)}+ className="ml-2"+ >+ <LuExternalLink />+ </Link>+ </span>+ )}+ <div />+ </div>+ </div>+ <VStack className="p-2" spacing={2}>+ <ItemPlanningChart+ key={itemId}+ itemId={itemId}+ locationId={routeData?.locationId ?? defaults.locationId ?? ""}+ />+ </VStack>+ </ScrollArea>+ </ResizablePanel>+ </>+ );+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 6d0d706414..8aab083252 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -972,6 +972,8 @@ export const path = {processes: `${x}/resources/processes`,production: `${x}/production`,productionPlanning: `${x}/production/planning`,+ productionPlanningItem: (itemId: string) =>+ generatePath(`${x}/production/planning/${itemId}`),productionSettings: `${x}/settings/production`,profile: `${x}/account/profile`,purchaseInvoice: (id: string) =>diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 623ff89329..20b3b429d9 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -8215,8 +8215,8 @@ export type Database = {createdBy: string;critical: boolean;customFields: Json | null;+ demandAccumulationIncludesInventory: boolean;demandAccumulationPeriod: number;- demandAccumulationSafetyStock: number;itemId: string;locationId: string;maximumInventoryQuantity: number;@@ -8236,8 +8236,8 @@ export type Database = {createdBy: string;critical?: boolean;customFields?: Json | null;+ demandAccumulationIncludesInventory?: boolean;demandAccumulationPeriod?: number;- demandAccumulationSafetyStock?: number;itemId: string;locationId: string;maximumInventoryQuantity?: number;@@ -8257,8 +8257,8 @@ export type Database = {createdBy?: string;critical?: boolean;customFields?: Json | null;+ demandAccumulationIncludesInventory?: boolean;demandAccumulationPeriod?: number;- demandAccumulationSafetyStock?: number;itemId?: string;locationId?: string;maximumInventoryQuantity?: number;@@ -37637,6 +37637,27 @@ export type Database = {referencedRelation: "companies";referencedColumns: ["id"];},+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey";+ columns: ["parentMaterialId"];+ isOneToOne: false;+ referencedRelation: "jobMaterialWithMakeMethodId";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey";+ columns: ["parentMaterialId"];+ isOneToOne: false;+ referencedRelation: "openJobMaterialLines";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "jobMaterial_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "companies";+ referencedColumns: ["id"];+ },{foreignKeyName: "jobMaterial_companyId_fkey";columns: ["companyId"];@@ -37694,12 +37715,26 @@ export type Database = {referencedColumns: ["id"];},{- foreignKeyName: "jobMaterial_jobId_fkey";- columns: ["jobId"];+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey";+ columns: ["jobMakeMethodId"];isOneToOne: false;- referencedRelation: "job";+ referencedRelation: "jobMakeMethod";referencedColumns: ["id"];},+ {+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey";+ columns: ["jobMakeMethodId"];+ isOneToOne: false;+ referencedRelation: "jobMaterialWithMakeMethodId";+ referencedColumns: ["jobMaterialMakeMethodId"];+ },+ {+ foreignKeyName: "jobMaterial_unitOfMeasureCode_fkey";+ columns: ["unitOfMeasureCode", "companyId"];+ isOneToOne: false;+ referencedRelation: "unitOfMeasure";+ referencedColumns: ["code", "companyId"];+ },{foreignKeyName: "jobMaterial_jobId_fkey";columns: ["jobId"];@@ -38097,14 +38132,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey";- columns: ["supplierLocationId"];+ columns: ["id"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];},{foreignKeyName: "partner_id_fkey";- columns: ["id"];+ columns: ["supplierLocationId"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];@@ -39444,14 +39479,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["supplierCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["supplierCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -41686,14 +41721,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["invoiceCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["invoiceCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -42229,14 +42264,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["paymentCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["paymentCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -45139,17 +45174,15 @@ export type Database = {manufacturingBlocked: boolean;lotSize: number;reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"];- safetyStockQuantity: number;- safetyStockLeadTime: number;demandAccumulationPeriod: number;demandAccumulationIncludesInventory: boolean;reorderPoint: number;reorderQuantity: number;- reorderMaximumInventory: number;minimumOrderQuantity: number;maximumOrderQuantity: number;orderMultiple: number;quantityOnHand: number;+ maximumInventoryQuantity: number;week1: number;week2: number;week3: number;diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 623ff89329..20b3b429d9 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -8215,8 +8215,8 @@ export type Database = {createdBy: string;critical: boolean;customFields: Json | null;+ demandAccumulationIncludesInventory: boolean;demandAccumulationPeriod: number;- demandAccumulationSafetyStock: number;itemId: string;locationId: string;maximumInventoryQuantity: number;@@ -8236,8 +8236,8 @@ export type Database = {createdBy: string;critical?: boolean;customFields?: Json | null;+ demandAccumulationIncludesInventory?: boolean;demandAccumulationPeriod?: number;- demandAccumulationSafetyStock?: number;itemId: string;locationId: string;maximumInventoryQuantity?: number;@@ -8257,8 +8257,8 @@ export type Database = {createdBy?: string;critical?: boolean;customFields?: Json | null;+ demandAccumulationIncludesInventory?: boolean;demandAccumulationPeriod?: number;- demandAccumulationSafetyStock?: number;itemId?: string;locationId?: string;maximumInventoryQuantity?: number;@@ -37637,6 +37637,27 @@ export type Database = {referencedRelation: "companies";referencedColumns: ["id"];},+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey";+ columns: ["parentMaterialId"];+ isOneToOne: false;+ referencedRelation: "jobMaterialWithMakeMethodId";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey";+ columns: ["parentMaterialId"];+ isOneToOne: false;+ referencedRelation: "openJobMaterialLines";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "jobMaterial_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "companies";+ referencedColumns: ["id"];+ },{foreignKeyName: "jobMaterial_companyId_fkey";columns: ["companyId"];@@ -37694,12 +37715,26 @@ export type Database = {referencedColumns: ["id"];},{- foreignKeyName: "jobMaterial_jobId_fkey";- columns: ["jobId"];+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey";+ columns: ["jobMakeMethodId"];isOneToOne: false;- referencedRelation: "job";+ referencedRelation: "jobMakeMethod";referencedColumns: ["id"];},+ {+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey";+ columns: ["jobMakeMethodId"];+ isOneToOne: false;+ referencedRelation: "jobMaterialWithMakeMethodId";+ referencedColumns: ["jobMaterialMakeMethodId"];+ },+ {+ foreignKeyName: "jobMaterial_unitOfMeasureCode_fkey";+ columns: ["unitOfMeasureCode", "companyId"];+ isOneToOne: false;+ referencedRelation: "unitOfMeasure";+ referencedColumns: ["code", "companyId"];+ },{foreignKeyName: "jobMaterial_jobId_fkey";columns: ["jobId"];@@ -38097,14 +38132,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey";- columns: ["supplierLocationId"];+ columns: ["id"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];},{foreignKeyName: "partner_id_fkey";- columns: ["id"];+ columns: ["supplierLocationId"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];@@ -39444,14 +39479,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["supplierCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["supplierCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -41686,14 +41721,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["invoiceCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["invoiceCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -42229,14 +42264,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["paymentCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["paymentCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -45139,17 +45174,15 @@ export type Database = {manufacturingBlocked: boolean;lotSize: number;reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"];- safetyStockQuantity: number;- safetyStockLeadTime: number;demandAccumulationPeriod: number;demandAccumulationIncludesInventory: boolean;reorderPoint: number;reorderQuantity: number;- reorderMaximumInventory: number;minimumOrderQuantity: number;maximumOrderQuantity: number;orderMultiple: number;quantityOnHand: number;+ maximumInventoryQuantity: number;week1: number;week2: number;week3: number;diff --git a/packages/database/supabase/migrations/20250616131548_production-planning.sql b/packages/database/supabase/migrations/20250616131548_production-planning.sqlindex 107bc3e52e..0154a279e0 100644--- a/packages/database/supabase/migrations/20250616131548_production-planning.sql+++ b/packages/database/supabase/migrations/20250616131548_production-planning.sql@@ -1,4 +1,9 @@-DROP FUNCTION IF EXISTS get_production_planning;+ALTER TABLE "itemPlanning" DROP COLUMN "demandReschedulingPeriod";+ALTER TABLE "itemPlanning" DROP COLUMN "safetyStockQuantity";+ALTER TABLE "itemPlanning" DROP COLUMN "safetyStockLeadTime";+ALTER TABLE "itemPlanning" DROP COLUMN "reorderMaximumInventory";+ALTER TABLE "itemPlanning" ADD COLUMN "maximumInventoryQuantity" NUMERIC NOT NULL DEFAULT 0;+-- Add indexes for supply and demand tablesCREATE INDEX IF NOT EXISTS "supplyActual_companyId_locationId_idx" ON "supplyActual" ("companyId", "locationId");@@ -6,6 +11,7 @@ CREATE INDEX IF NOT EXISTS "supplyForecast_companyId_locationId_idx" ON "supplyFCREATE INDEX IF NOT EXISTS "demandActual_companyId_locationId_idx" ON "demandActual" ("companyId", "locationId");CREATE INDEX IF NOT EXISTS "demandForecast_companyId_locationId_idx" ON "demandForecast" ("companyId", "locationId");+DROP FUNCTION IF EXISTS get_production_planning;CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id TEXT, periods TEXT[])RETURNS TABLE ("id" TEXT,@@ -21,17 +27,15 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id"manufacturingBlocked" BOOLEAN,"lotSize" INTEGER,"reorderingPolicy" "itemReorderingPolicy",- "safetyStockQuantity" INTEGER,- "safetyStockLeadTime" INTEGER,"demandAccumulationPeriod" INTEGER,"demandAccumulationIncludesInventory" BOOLEAN,"reorderPoint" INTEGER,"reorderQuantity" INTEGER,- "reorderMaximumInventory" INTEGER,"minimumOrderQuantity" INTEGER,"maximumOrderQuantity" INTEGER,"orderMultiple" INTEGER,"quantityOnHand" NUMERIC,+ "maximumInventoryQuantity" NUMERIC,"week1" NUMERIC,"week2" NUMERIC,"week3" NUMERIC,@@ -129,7 +133,7 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id),-- Base data for items with early filteringbase_items AS (- SELECT+ SELECT DISTINCT ON (i."id")i."id",i."readableIdWithRevision",i."name",@@ -146,16 +150,14 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_idir."manufacturingBlocked",ir."lotSize",ip."reorderingPolicy",- ip."safetyStockQuantity",- ip."safetyStockLeadTime",ip."demandAccumulationPeriod",ip."demandAccumulationIncludesInventory",ip."reorderPoint",ip."reorderQuantity",- ip."reorderMaximumInventory",ip."minimumOrderQuantity",ip."maximumOrderQuantity",ip."orderMultiple",+ ip."maximumInventoryQuantity",COALESCE((SELECT SUM("quantity")FROM "itemLedger"@@ -170,6 +172,17 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_idWHERE i."companyId" = company_idAND i."replenishmentSystem" = 'Make'AND i."active" = TRUE+ AND EXISTS (+ SELECT 1 FROM demand_data d+ WHERE d."itemId" = i."id"+ )+ AND COALESCE((+ SELECT SUM("quantity")+ FROM "itemLedger"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "itemId" = i."id"+ ), 0) >= 0),-- Recursive calculation of projections with optimized joinsprojections AS (@@ -200,16 +213,14 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_idp."manufacturingBlocked",p."lotSize",p."reorderingPolicy",- p."safetyStockQuantity",- p."safetyStockLeadTime",p."demandAccumulationPeriod",p."demandAccumulationIncludesInventory",p."reorderPoint",p."reorderQuantity",- p."reorderMaximumInventory",p."minimumOrderQuantity",p."maximumOrderQuantity",p."orderMultiple",+ p."maximumInventoryQuantity",p."quantityOnHand",periods[p.period_index + 1] as "periodId",p."projection" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",@@ -220,7 +231,7 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_idWHERE p.period_index < array_length(periods, 1))-- Final result with optimized pivot- SELECT+ SELECT DISTINCT ON (p."id")p."id",p."readableIdWithRevision",p."name",@@ -234,17 +245,15 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_idp."manufacturingBlocked",p."lotSize",p."reorderingPolicy",- p."safetyStockQuantity",- p."safetyStockLeadTime",p."demandAccumulationPeriod",p."demandAccumulationIncludesInventory",p."reorderPoint",p."reorderQuantity",- p."reorderMaximumInventory",p."minimumOrderQuantity",p."maximumOrderQuantity",p."orderMultiple",p."quantityOnHand",+ p."maximumInventoryQuantity",MAX(CASE WHEN p."periodId" = periods[1] THEN p."projection" END) AS "week1",MAX(CASE WHEN p."periodId" = periods[2] THEN p."projection" END) AS "week2",MAX(CASE WHEN p."periodId" = periods[3] THEN p."projection" END) AS "week3",@@ -312,26 +321,24 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_idp."manufacturingBlocked",p."lotSize",p."reorderingPolicy",- p."safetyStockQuantity",- p."safetyStockLeadTime",p."demandAccumulationPeriod",p."demandAccumulationIncludesInventory",p."reorderPoint",p."reorderQuantity",- p."reorderMaximumInventory",p."minimumOrderQuantity",p."maximumOrderQuantity",p."orderMultiple",- p."quantityOnHand";+ p."quantityOnHand",+ p."maximumInventoryQuantity";$$ LANGUAGE sql SECURITY DEFINER;---- add deadlineType to openProductionOrders+-- add deadlineType and jobId to openProductionOrdersDROP VIEW IF EXISTS "openProductionOrders";CREATE OR REPLACE VIEW "openProductionOrders" AS (SELECTj."id",j."itemId",+ j."jobId",j."productionQuantity" - j."quantityReceivedToInventory" AS "quantityToReceive",j."unitOfMeasureCode",j."companyId",@@ -353,8 +360,38 @@ CREATE OR REPLACE VIEW "openProductionOrders" AS (AND j."salesOrderId" IS NULL);--+-- add parentMaterialId, jobMakeMethodId, and jobReadableId to openJobMaterialLines+DROP VIEW IF EXISTS "openJobMaterialLines";+CREATE OR REPLACE VIEW "openJobMaterialLines" AS (+ SELECT+ jm."id",+ jm."jobId",+ jmm."parentMaterialId",+ jm."jobMakeMethodId",+ j."jobId" as "jobReadableId",+ jm."itemId",+ jm."quantityToIssue",+ jm."unitOfMeasureCode",+ jm."companyId",+ i1."replenishmentSystem",+ i1."itemTrackingType",+ ir."leadTime" AS "leadTime",+ j."locationId",+ j."dueDate"+ FROM "jobMaterial" jm+ INNER JOIN "job" j ON jm."jobId" = j."id"+ INNER JOIN "jobMakeMethod" jmm ON jm."jobMakeMethodId" = jmm."id"+ INNER JOIN "item" i1 ON jm."itemId" = i1."id"+ INNER JOIN "item" i2 ON j."itemId" = i2."id"+ INNER JOIN "itemReplenishment" ir ON i2."id" = ir."itemId"+ WHERE j."status" IN (+ 'Planned',+ 'Ready',+ 'In Progress',+ 'Paused'+ )+ AND jm."methodType" != 'Make'+);CREATE OR REPLACE FUNCTION public.create_item_related_records()diff --git a/packages/react/src/Badge.tsx b/packages/react/src/Badge.tsxindex 88dd32f529..1ab1fed002 100644--- a/packages/react/src/Badge.tsx+++ b/packages/react/src/Badge.tsx@@ -30,6 +30,8 @@ const badgeVariants = cva(red: "bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-400",blue: "bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-400",gray: "bg-[#e3e2e080] text-[#32302c] dark:bg-[#373737] dark:text-white hover:bg-[#e3e2e0] dark:hover:bg-[#5a5a5a]",+ purple:+ "bg-violet-100 text-violet-800 dark:bg-violet-900/50 dark:text-violet-400",},},defaultVariants: {diff --git a/packages/react/src/Status.tsx b/packages/react/src/Status.tsxindex 40592fc0e2..654c06b3d5 100644--- a/packages/react/src/Status.tsx+++ b/packages/react/src/Status.tsx@@ -3,7 +3,7 @@ import { Badge } from "./Badge";import { cn } from "./utils/cn";type StatusProps = ComponentProps<"div"> & {- color?: "green" | "orange" | "red" | "yellow" | "blue" | "gray";+ color?: "green" | "orange" | "red" | "yellow" | "blue" | "gray" | "purple";};const Status = ({