Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add calculations for order dates and quantities using reorder policies

Brad Barbin5193f0c34bc3
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index b26ae5d4e1..e25301f7c2 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -427,24 +427,41 @@ export const itemPostingGroupValidator = z.object({
description: z.string().optional(),
});
-export const itemPlanningValidator = z.object({
- itemId: z.string().min(1, { message: "Item ID is required" }),
- locationId: z.string().min(20, { message: "Location is required" }),
- reorderingPolicy: z.enum(itemReorderingPolicies, {
- errorMap: (issue, ctx) => ({
- message: "Reordering policy is required",
+export const itemPlanningValidator = z
+ .object({
+ itemId: z.string().min(1, { message: "Item ID is required" }),
+ locationId: z.string().min(20, { message: "Location is required" }),
+ reorderingPolicy: z.enum(itemReorderingPolicies, {
+ errorMap: (issue, ctx) => ({
+ message: "Reordering policy is required",
+ }),
}),
- }),
- 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(),
- 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)).optional(),
- // critical: zfd.checkbox(),
-});
+ demandAccumulationPeriod: zfd.numeric(z.number().min(0).optional()),
+ demandAccumulationSafetyStock: zfd.numeric(z.number().min(0).optional()),
+ reorderPoint: zfd.numeric(z.number().min(0).optional()).optional(),
+ reorderQuantity: 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)).optional(),
+ // critical: zfd.checkbox(),
+ })
+ .refine(
+ (data) => {
+ if (data.reorderingPolicy === "Maximum Quantity") {
+ return (
+ data.maximumInventoryQuantity &&
+ data.reorderPoint &&
+ data.maximumInventoryQuantity > data.reorderPoint
+ );
+ }
+ return true;
+ },
+ {
+ message: "Maximum inventory quantity must be greater than reorder point",
+ path: ["maximumInventoryQuantity"],
+ }
+ );
export const itemPurchasingValidator = z.object({
itemId: z.string().min(1, { message: "Item ID is required" }),
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 793c7048e8..90360674ef 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -1034,7 +1034,7 @@ export async function getOpenJobMaterials(
return client
.from("openJobMaterialLines")
.select(
- "id, parentMaterialId, jobMakeMethodId, quantity:quantityToIssue, documentReadableId:jobReadableId, documentId:jobId, dueDate"
+ "id, parentMaterialId, jobMakeMethodId, jobId, quantity:quantityToIssue, documentReadableId:jobReadableId, documentId:jobId, dueDate"
)
.eq("itemId", itemId)
.eq("locationId", locationId)
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
index a71adb1fd4..447d54705d 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
@@ -47,36 +47,13 @@ import {
XAxis,
YAxis,
} from "recharts";
-import { Empty } from "~/components";
+import { Empty, Hyperlink } from "~/components";
import type { loader as forecastLoader } from "~/routes/api+/items.$id.$locationId.forecast";
import { path } from "~/utils/path";
-interface Data {
- quantity: number;
- companyId: string;
- createdAt: string;
- createdBy: string;
- itemId: string;
- locationId: string;
- notes: string | null;
- 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;
-interface DemandData extends Data {
- sourceType: (typeof demandSourceTypes)[number];
-}
-
-interface SupplyData extends Data {
- sourceType: (typeof supplySourceTypes)[number];
-}
-
interface ChartDataPoint {
startDate: string;
period: string;
@@ -92,9 +69,11 @@ const chartConfig = {} satisfies ChartConfig;
export const ItemPlanningChart = ({
itemId,
locationId,
+ safetyStock,
}: {
itemId: string;
locationId: string;
+ safetyStock?: number;
}) => {
const forecastFetcher = useFetcher<typeof forecastLoader>();
const isFetching = forecastFetcher.state !== "idle" || !forecastFetcher.data;
@@ -277,6 +256,13 @@ export const ItemPlanningChart = ({
/>
<YAxis tickLine={false} axisLine={false} />
<ReferenceLine y={0} stroke="#94a3b8" strokeDasharray="3 3" />
+ {safetyStock && safetyStock > 0 && (
+ <ReferenceLine
+ y={safetyStock}
+ stroke="#f43f5e"
+ strokeDasharray="3 3"
+ />
+ )}
<Legend
payload={[
{ value: "Demand", type: "rect", color: "#14b8a6" },
@@ -286,6 +272,15 @@ export const ItemPlanningChart = ({
type: "line",
color: "#7c3aed",
},
+ ...(safetyStock && safetyStock > 0
+ ? [
+ {
+ value: "Safety Stock",
+ type: "line" as const,
+ color: "#f43f5e",
+ },
+ ]
+ : []),
]}
/>
<ChartTooltip
@@ -414,7 +409,7 @@ export const ItemPlanningChart = ({
<TabsContent value="all" className="border rounded-lg">
{combinedSupplyAndDemand.map((item, index) => (
- <SupplyDemandListItem key={index} item={item} />
+ <SupplyDemandPlanningItem key={index} item={item} />
))}
</TabsContent>
@@ -426,7 +421,7 @@ export const ItemPlanningChart = ({
)
)
.map((item, index) => (
- <SupplyDemandListItem key={index} item={item} />
+ <SupplyDemandPlanningItem key={index} item={item} />
))}
</TabsContent>
@@ -438,7 +433,7 @@ export const ItemPlanningChart = ({
)
)
.map((item, index) => (
- <SupplyDemandListItem key={index} item={item} />
+ <SupplyDemandPlanningItem key={index} item={item} />
))}
</TabsContent>
</CardContent>
@@ -448,7 +443,7 @@ export const ItemPlanningChart = ({
);
};
-interface ListItem {
+interface PlanningItem {
sourceType: string;
id: string | null;
dueDate: string | null;
@@ -456,6 +451,9 @@ interface ListItem {
documentId: string | null;
quantity: number;
projectedQuantity: number;
+ parentMaterialId?: string | null;
+ jobId?: string | null;
+ jobMakeMethodId?: string | null;
}
const sourceTypeIcons = {
@@ -465,7 +463,7 @@ const sourceTypeIcons = {
"Production Order": <LuFactory className="h-4 w-4 text-blue-600" />,
};
-function SupplyDemandListItem({ item }: { item: ListItem }) {
+function SupplyDemandPlanningItem({ item }: { item: PlanningItem }) {
const numberFormatter = useNumberFormatter();
return (
@@ -476,9 +474,12 @@ function SupplyDemandListItem({ item }: { item: ListItem }) {
{sourceTypeIcons[item.sourceType as keyof typeof sourceTypeIcons]}
</div>
<VStack spacing={0}>
- <span className="text-sm font-medium">
+ <Hyperlink
+ to={getPathToDocument(item)}
+ className="text-sm font-medium"
+ >
{item.documentReadableId}
- </span>
+ </Hyperlink>
<span className="text-xs text-muted-foreground">
{item.dueDate ? formatDate(item.dueDate) : "No due date"}
</span>
@@ -503,3 +504,22 @@ function SupplyDemandListItem({ item }: { item: ListItem }) {
</div>
);
}
+
+function getPathToDocument(item: PlanningItem) {
+ switch (item.sourceType) {
+ case "Sales Order":
+ return path.to.salesOrder(item.documentId ?? "");
+ case "Job Material":
+ if (!item.jobId) return "#";
+ if (!item.jobMakeMethodId) return "#";
+ return item.parentMaterialId
+ ? path.to.jobMakeMethod(item.jobId, item.jobMakeMethodId)
+ : path.to.jobMethod(item.jobId, item.jobMakeMethodId);
+ case "Purchase Order":
+ return path.to.purchaseOrder(item.documentId ?? "");
+ case "Production Order":
+ return path.to.job(item.documentId ?? "");
+ default:
+ return "";
+ }
+}
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx
index 2f18e0487c..c301f3a4ee 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningForm.tsx
@@ -13,7 +13,6 @@ import { useState } from "react";
import type { z } from "zod";
import {
- Boolean,
CustomFormFields,
Hidden,
Number,
@@ -110,12 +109,13 @@ const ItemPlanningForm = ({
<>
<Number
name="demandAccumulationPeriod"
- label="Demand Accumulation Period (Days)"
+ label="Accumulation Period (Weeks)"
minValue={0}
/>
- <Boolean
- name="demandAccumulationIncludesInventory"
- label="Demand Includes Inventory"
+ <Number
+ name="demandAccumulationSafetyStock"
+ label="Safety Stock"
+ minValue={0}
/>
</>
)}
diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
index 972e5707f3..5c3fa5bddb 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
@@ -56,6 +56,7 @@ export function getReorderPolicyDescription(
return `When stock is below ${reorderPoint}, order up to ${maximumInventoryQuantity} units`;
}
}
+
export function getOrdersFromProductionPlanning(
itemPlanning: ProductionPlanningItem,
periods: { startDate: string; id: string }[]
@@ -75,16 +76,83 @@ export function getOrdersFromProductionPlanning(
quantity: number;
isASAP: boolean;
}[] = [];
- const leadTime = itemPlanning.leadTime;
+
+ const {
+ demandAccumulationPeriod,
+ demandAccumulationSafetyStock,
+ leadTime,
+ lotSize,
+ maximumInventoryQuantity,
+ maximumOrderQuantity,
+ minimumOrderQuantity,
+ orderMultiple,
+ reorderPoint,
+ reorderQuantity,
+ } = itemPlanning;
+
const todaysDate = today(getLocalTimeZone());
+ let orderedQuantity = 0;
switch (itemPlanning.reorderingPolicy) {
case "Demand-Based Reorder":
+ // Process periods in chunks of demandAccumulationPeriod
+ for (let i = 0; i < periods.length; i += demandAccumulationPeriod) {
+ const currentPeriod = periods[i];
+
+ // Get the projection for this period
+ const periodKey = `week${i + 1}` as keyof ProductionPlanningItem;
+ const projection = (itemPlanning[periodKey] as number) || 0;
+
+ // If projection plus ordered quantity is below safety stock, create order
+ if (projection + orderedQuantity < demandAccumulationSafetyStock) {
+ let remainingQuantityNeeded =
+ demandAccumulationSafetyStock - (projection + orderedQuantity);
+ let dayOffset = 0;
+
+ while (remainingQuantityNeeded > 0) {
+ // Apply lot sizing rules
+ let orderQuantity = Math.max(
+ Math.min(
+ remainingQuantityNeeded,
+ lotSize > 0
+ ? lotSize // If lotSize exists, use it as maximum
+ : maximumOrderQuantity > 0
+ ? maximumOrderQuantity
+ : Infinity
+ ),
+ minimumOrderQuantity
+ );
+
+ if (orderMultiple > 0) {
+ orderQuantity =
+ Math.ceil(orderQuantity / orderMultiple) * orderMultiple;
+ }
+
+ if (lotSize > 0) {
+ orderQuantity = Math.min(lotSize, orderQuantity);
+ }
+
+ const dueDate = parseDate(currentPeriod.startDate).add({
+ days: dayOffset,
+ });
+ const startDate = dueDate.subtract({ days: leadTime });
+
+ orders.push({
+ startDate: startDate.toString(),
+ dueDate: dueDate.toString(),
+ quantity: orderQuantity,
+ isASAP: startDate.compare(todaysDate) < 0,
+ });
+
+ orderedQuantity += orderQuantity;
+ remainingQuantityNeeded -= orderQuantity;
+ dayOffset++;
+ }
+ }
+ }
+
return orders;
case "Fixed Reorder Quantity":
- const reorderPoint = itemPlanning.reorderPoint;
- const reorderQuantity = itemPlanning.reorderQuantity;
- let orderedQuantity = 0;
for (let i = 0; i < periods.length; i++) {
const period = periods[i];
const periodKey = `week${i + 1}` as keyof ProductionPlanningItem;
@@ -97,7 +165,7 @@ export function getOrdersFromProductionPlanning(
let day = 0;
while (remainingQuantityNeeded > 0 && day < 5) {
const dueDate = parseDate(period.startDate).add({ days: day });
- const startDate = parseDate(period.startDate).subtract({
+ const startDate = dueDate.subtract({
days: leadTime,
});
@@ -116,6 +184,59 @@ export function getOrdersFromProductionPlanning(
return orders;
case "Maximum Quantity":
+ for (let i = 0; i < periods.length; i++) {
+ const period = periods[i];
+ const periodKey = `week${i + 1}` as keyof ProductionPlanningItem;
+ const projectedQuantity = (itemPlanning[periodKey] as number) || 0;
+
+ // Check if we need to order based on reorder point
+ let remainingQuantityNeeded =
+ reorderPoint - (projectedQuantity + orderedQuantity);
+
+ let day = 0;
+ while (remainingQuantityNeeded > 0 && day < 5) {
+ const dueDate = parseDate(period.startDate).add({ days: day });
+ const startDate = dueDate.subtract({
+ days: leadTime,
+ });
+
+ // Calculate required quantity up to maximum inventory
+ const requiredQuantity =
+ maximumInventoryQuantity - (projectedQuantity + orderedQuantity);
+
+ // Adjust quantity based on order constraints
+ let orderQuantity = Math.max(minimumOrderQuantity, requiredQuantity);
+
+ // Round to nearest multiple if specified
+ if (orderMultiple && orderMultiple > 1) {
+ orderQuantity =
+ Math.ceil(orderQuantity / orderMultiple) * orderMultiple;
+ }
+
+ // Only apply lot size if it's greater than 0
+ if (lotSize > 0) {
+ orderQuantity = Math.ceil(orderQuantity / lotSize) * lotSize;
+ }
+
+ // Apply maximum order quantity only if it's greater than 0
+ if (maximumOrderQuantity > 0) {
+ orderQuantity = Math.min(orderQuantity, maximumOrderQuantity);
+ }
+
+ orders.push({
+ startDate: startDate.toString(),
+ dueDate: dueDate.toString(),
+ quantity: orderQuantity,
+ isASAP:
+ startDate.compare(todaysDate) < 0 &&
+ projectedQuantity + orderedQuantity < 0,
+ });
+ day++;
+ orderedQuantity += orderQuantity;
+ remainingQuantityNeeded =
+ reorderPoint - (projectedQuantity + orderedQuantity);
+ }
+ }
return orders;
default:
return orders;
diff --git a/apps/erp/app/modules/production/ui/Jobs/Deadline.tsx b/apps/erp/app/modules/production/ui/Jobs/Deadline.tsx
index a86c9eedb0..fd359282bb 100644
--- a/apps/erp/app/modules/production/ui/Jobs/Deadline.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/Deadline.tsx
@@ -1,23 +1,17 @@
-import { cn } from "@carbon/react";
import { BsExclamationSquareFill } from "react-icons/bs";
import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
import { LowPriorityIcon } from "~/assets/icons/LowPriorityIcon";
import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
import type { deadlineTypes } from "../../production.models";
-export function getDeadlineIcon(
- deadlineType: (typeof deadlineTypes)[number],
- overdue: boolean
-) {
+export function getDeadlineIcon(deadlineType: (typeof deadlineTypes)[number]) {
switch (deadlineType) {
case "ASAP":
return <BsExclamationSquareFill className="text-red-500" />;
case "Hard Deadline":
- return <HighPriorityIcon className={cn(overdue ? "text-red-500" : "")} />;
+ return <HighPriorityIcon />;
case "Soft Deadline":
- return (
- <MediumPriorityIcon className={cn(overdue ? "text-red-500" : "")} />
- );
+ return <MediumPriorityIcon />;
case "No Deadline":
return <LowPriorityIcon />;
}
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx b/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
index 8e569661d8..ee6efea6fd 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
@@ -355,7 +355,7 @@ const JobForm = ({ initialValues }: JobFormProps) => {
value: d,
label: (
<div className="flex gap-1 items-center">
- {getDeadlineIcon(d, false)}
+ {getDeadlineIcon(d)}
<span>{getDeadlineText(d)}</span>
</div>
),
@@ -520,7 +520,7 @@ const JobForm = ({ initialValues }: JobFormProps) => {
value: d,
label: (
<div className="flex gap-1 items-center">
- {getDeadlineIcon(d, false)}
+ {getDeadlineIcon(d)}
<span>{getDeadlineText(d)}</span>
</div>
),
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx b/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx
index e1948af305..5d83196624 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx
@@ -387,7 +387,7 @@ const JobProperties = () => {
const deadlineType = value as (typeof deadlineTypes)[number];
return (
<div className="flex gap-1 items-center">
- {getDeadlineIcon(deadlineType, false)}
+ {getDeadlineIcon(deadlineType)}
<span>{getDeadlineText(deadlineType)}</span>
</div>
);
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
index 4b586298fa..a0fe3d7a32 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
@@ -226,19 +226,18 @@ const JobsTable = memo(({ data, count, tags }: JobsTableProps) => {
cell: ({ row }) => {
const dueDate = row.original.dueDate!;
const deadlineType = row.original.deadlineType!;
- const isOverdue = new Date(dueDate) < new Date();
if (!dueDate)
return (
<div className="flex gap-1 items-center">
- {getDeadlineIcon(deadlineType, false)}
+ {getDeadlineIcon(deadlineType)}
<span>{getDeadlineText(deadlineType)}</span>
</div>
);
return (
<div className="flex items-center gap-1">
- {getDeadlineIcon(deadlineType, isOverdue)}
+ {getDeadlineIcon(deadlineType)}
<span>{getDeadlineText(deadlineType)}</span>
</div>
);
@@ -250,7 +249,7 @@ const JobsTable = memo(({ data, count, tags }: JobsTableProps) => {
value: type,
label: (
<div className="flex gap-1 items-center">
- {getDeadlineIcon(type, false)}
+ {getDeadlineIcon(type)}
<span>{getDeadlineText(type)}</span>
</div>
),
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
index 10ab7ae5f1..62af000fb9 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
@@ -335,7 +335,7 @@ export function ItemCard({ item, isOverlay, progressByItemId }: ItemCardProps) {
)}
{displaySettings.showDueDate && item.deadlineType && (
<HStack className="justify-start space-x-2">
- {getDeadlineIcon(item.deadlineType, isOverdue)}
+ {getDeadlineIcon(item.deadlineType)}
<Tooltip>
<TooltipTrigger>
<span
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.view.planning.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.view.planning.tsx
index 2c8b6a5c0f..33dff7cf39 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.view.planning.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.view.planning.tsx
@@ -149,6 +149,11 @@ export default function ConsumablePlanningRoute() {
<ItemPlanningChart
itemId={consumablePlanning.itemId}
locationId={locationId}
+ safetyStock={
+ consumablePlanning.reorderingPolicy === "Demand-Based Reorder"
+ ? consumablePlanning.demandAccumulationSafetyStock ?? 0
+ : undefined
+ }
/>
</VStack>
);
diff --git a/apps/erp/app/routes/x+/material+/$itemId.view.planning.tsx b/apps/erp/app/routes/x+/material+/$itemId.view.planning.tsx
index 8728f654cf..853ae63118 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.view.planning.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.view.planning.tsx
@@ -146,6 +146,11 @@ export default function MateriallanningRoute() {
<ItemPlanningChart
itemId={materialPlanning.itemId}
locationId={locationId}
+ safetyStock={
+ materialPlanning.reorderingPolicy === "Demand-Based Reorder"
+ ? materialPlanning.demandAccumulationSafetyStock ?? 0
+ : undefined
+ }
/>
</VStack>
);
diff --git a/apps/erp/app/routes/x+/part+/$itemId.view.planning.tsx b/apps/erp/app/routes/x+/part+/$itemId.view.planning.tsx
index 4cd5e4e34c..d49a500faa 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.view.planning.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.view.planning.tsx
@@ -142,7 +142,15 @@ export default function PartPlanningRoute() {
locations={sharedPartsData.locations ?? []}
type="Part"
/>
- <ItemPlanningChart itemId={partPlanning.itemId} locationId={locationId} />
+ <ItemPlanningChart
+ itemId={partPlanning.itemId}
+ locationId={locationId}
+ safetyStock={
+ partPlanning.reorderingPolicy === "Demand-Based Reorder"
+ ? partPlanning.demandAccumulationSafetyStock ?? 0
+ : undefined
+ }
+ />
</VStack>
);
}
diff --git a/apps/erp/app/routes/x+/production+/_index.tsx b/apps/erp/app/routes/x+/production+/_index.tsx
index 6670f546bc..3fbb628bd1 100644
--- a/apps/erp/app/routes/x+/production+/_index.tsx
+++ b/apps/erp/app/routes/x+/production+/_index.tsx
@@ -923,7 +923,7 @@ function WorkCenterCards({
{deadlineType && (
<HStack className="justify-start space-x-2">
- {getDeadlineIcon(deadlineType, isOverdue)}
+ {getDeadlineIcon(deadlineType)}
<Tooltip>
<TooltipTrigger>
<span
diff --git a/apps/erp/app/routes/x+/production+/planning.$itemId.tsx b/apps/erp/app/routes/x+/production+/planning.$itemId.tsx
index cc8394be99..4c2c9403cc 100644
--- a/apps/erp/app/routes/x+/production+/planning.$itemId.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.$itemId.tsx
@@ -1,4 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
import {
Button,
ResizableHandle,
@@ -9,16 +10,20 @@ import {
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 { json, redirect } from "@vercel/remix";
import { LuExternalLink, LuX } from "react-icons/lu";
import { useUser } from "~/hooks/useUser";
-import { getItem } from "~/modules/items/items.service";
+import { getItem, getItemPlanning } from "~/modules/items/items.service";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";
+import type { ProductionPlanningItem } from "~/modules/production/types";
+import { getLocationsList } from "~/modules/resources/resources.service";
+import { getUserDefaults } from "~/modules/users/users.server";
import { path } from "~/utils/path";
+import { error } from "../../../../../../packages/auth/src/utils/result";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, userId, companyId } = await requirePermissions(request, {
view: "parts",
});
@@ -27,9 +32,45 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("itemId not found");
}
- const item = await getItem(client, itemId);
+ const searchParams = new URL(request.url).searchParams;
- return json({ item: item.data });
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.productionPlanning,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ const [item, itemPlanning] = await Promise.all([
+ getItem(client, itemId),
+ getItemPlanning(client, itemId, companyId, locationId),
+ ]);
+
+ return json({ item: item.data, itemPlanning: itemPlanning.data });
}
export default function ProductionPlanningDetailsRoute() {
@@ -38,11 +79,12 @@ export default function ProductionPlanningDetailsRoute() {
throw new Error("itemId not found");
}
- const { item } = useLoaderData<typeof loader>();
+ const { item, itemPlanning } = useLoaderData<typeof loader>();
- const routeData = useRouteData<{ locationId: string }>(
- path.to.productionPlanning
- );
+ const routeData = useRouteData<{
+ locationId: string;
+ itemPlanning: ProductionPlanningItem;
+ }>(path.to.productionPlanning);
const navigate = useNavigate();
const [params] = useUrlParams();
@@ -88,6 +130,11 @@ export default function ProductionPlanningDetailsRoute() {
key={itemId}
itemId={itemId}
locationId={routeData?.locationId ?? defaults.locationId ?? ""}
+ safetyStock={
+ itemPlanning?.reorderingPolicy === "Demand-Based Reorder"
+ ? itemPlanning.demandAccumulationSafetyStock
+ : undefined
+ }
/>
</VStack>
</ScrollArea>
diff --git a/package-lock.json b/package-lock.json
index 4fd03d9301..4686ae3c05 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -15,6 +15,7 @@
"react-intersection-observer": "^9.13.1"
},
"devDependencies": {
+ "csv-parse": "^5.5.0",
"eslint": "^8.23.1",
"eslint-config-carbon": "*",
"husky": "^8.0.3",
@@ -15942,6 +15943,12 @@
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="
},
+ "node_modules/csv-parse": {
+ "version": "5.6.0",
+ "resolved": "https://registry.npmjs.org/csv-parse/-/csv-parse-5.6.0.tgz",
+ "integrity": "sha512-l3nz3euub2QMg5ouu5U09Ew9Wf6/wQ8I++ch1loQ0ljmzhmfZYrH9fflS22i/PQEvsPvxCwxgz5q7UB8K1JO4Q==",
+ "dev": true
+ },
"node_modules/d3": {
"version": "7.9.0",
"resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",
diff --git a/package.json b/package.json
index 6c12fad853..55b2216556 100755
--- a/package.json
+++ b/package.json
@@ -1,5 +1,6 @@
{
"devDependencies": {
+ "csv-parse": "^5.5.0",
"eslint": "^8.23.1",
"eslint-config-carbon": "*",
"husky": "^8.0.3",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 20b3b429d9..a7ccd9060e 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;
@@ -45175,7 +45175,7 @@ export type Database = {
lotSize: number;
reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"];
demandAccumulationPeriod: number;
- demandAccumulationIncludesInventory: boolean;
+ demandAccumulationSafetyStock: number;
reorderPoint: number;
reorderQuantity: number;
minimumOrderQuantity: number;
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 20b3b429d9..a7ccd9060e 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;
@@ -45175,7 +45175,7 @@ export type Database = {
lotSize: number;
reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"];
demandAccumulationPeriod: number;
- demandAccumulationIncludesInventory: boolean;
+ demandAccumulationSafetyStock: number;
reorderPoint: number;
reorderQuantity: number;
minimumOrderQuantity: number;
diff --git a/packages/database/supabase/migrations/20250616131548_production-planning.sql b/packages/database/supabase/migrations/20250616131548_production-planning.sql
index 0154a279e0..a0043d7d6e 100644
--- a/packages/database/supabase/migrations/20250616131548_production-planning.sql
+++ b/packages/database/supabase/migrations/20250616131548_production-planning.sql
@@ -1,8 +1,14 @@
ALTER TABLE "itemPlanning" DROP COLUMN "demandReschedulingPeriod";
+ALTER TABLE "itemPlanning" DROP COLUMN "demandAccumulationSafetyStock";
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;
+ALTER TABLE "itemPlanning" ADD COLUMN "demandAccumulationSafetyStock" NUMERIC NOT NULL DEFAULT 0;
+
+
+ALTER TABLE "itemPlanning" ALTER COLUMN "demandAccumulationPeriod" SET DEFAULT 4;
+UPDATE "itemPlanning" SET "demandAccumulationPeriod" = 4;
-- Add indexes for supply and demand tables
@@ -28,7 +34,7 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id
"lotSize" INTEGER,
"reorderingPolicy" "itemReorderingPolicy",
"demandAccumulationPeriod" INTEGER,
- "demandAccumulationIncludesInventory" BOOLEAN,
+ "demandAccumulationSafetyStock" NUMERIC,
"reorderPoint" INTEGER,
"reorderQuantity" INTEGER,
"minimumOrderQuantity" INTEGER,
@@ -151,7 +157,7 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id
ir."lotSize",
ip."reorderingPolicy",
ip."demandAccumulationPeriod",
- ip."demandAccumulationIncludesInventory",
+ ip."demandAccumulationSafetyStock",
ip."reorderPoint",
ip."reorderQuantity",
ip."minimumOrderQuantity",
@@ -214,7 +220,7 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id
p."lotSize",
p."reorderingPolicy",
p."demandAccumulationPeriod",
- p."demandAccumulationIncludesInventory",
+ p."demandAccumulationSafetyStock",
p."reorderPoint",
p."reorderQuantity",
p."minimumOrderQuantity",
@@ -246,7 +252,7 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id
p."lotSize",
p."reorderingPolicy",
p."demandAccumulationPeriod",
- p."demandAccumulationIncludesInventory",
+ p."demandAccumulationSafetyStock",
p."reorderPoint",
p."reorderQuantity",
p."minimumOrderQuantity",
@@ -322,7 +328,7 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id
p."lotSize",
p."reorderingPolicy",
p."demandAccumulationPeriod",
- p."demandAccumulationIncludesInventory",
+ p."demandAccumulationSafetyStock",
p."reorderPoint",
p."reorderQuantity",
p."minimumOrderQuantity",
diff --git a/scripts/migrations/part-revision-merges.ts b/scripts/migrations/part-revision-merges.ts
new file mode 100644
index 0000000000..a8364838d4
--- /dev/null
+++ b/scripts/migrations/part-revision-merges.ts
@@ -0,0 +1,147 @@
+import { createClient } from "@supabase/supabase-js";
+import { parse } from "csv-parse";
+import * as dotenv from "dotenv";
+import { createReadStream } from "fs";
+import { homedir } from "os";
+import { resolve } from "path";
+dotenv.config();
+
+const COMPANY_ID = "cs868u84gfk07v78v9e0";
+const PROD: boolean = true;
+const READ_ONLY: boolean = false;
+
+const sourceFile = resolve(homedir(), "Desktop/black-cat-renames.csv");
+const columns = ["ID", "OLD", "NEW", "REVISION"];
+
+const parser = parse({
+ delimiter: ",",
+ columns,
+ fromLine: 2, // Skip header row
+});
+
+const supabaseUrl = PROD
+ ? process.env.PROD_SUPABASE_URL!
+ : process.env.SUPABASE_URL!;
+const supabaseServiceRoleKey = PROD
+ ? process.env.PROD_SUPABASE_SERVICE_ROLE_KEY!
+ : process.env.SUPABASE_SERVICE_ROLE_KEY!;
+
+const readStream = createReadStream(sourceFile);
+const client = createClient(supabaseUrl, supabaseServiceRoleKey);
+
+(async () => {
+ const company = await client
+ .from("company")
+ .select("name")
+ .eq("id", COMPANY_ID)
+ .single();
+
+ if (company?.error) {
+ console.error("Error fetching company:", company.error);
+ }
+
+ const rows: {
+ ID: string;
+ OLD: string;
+ NEW: string;
+ REVISION: string;
+ }[] = [];
+
+ readStream
+ .pipe(parser)
+ .on("data", (row) => {
+ rows.push(row);
+ })
+ .on("end", async () => {
+ const fetchErrors: string[] = [];
+ const updateErrors: string[] = [];
+
+ for (const row of rows) {
+ console.log(`Fetching ${row.OLD.trim()}`);
+ const [item, oldPart, newPart] = await Promise.all([
+ client
+ .from("item")
+ .select("*")
+ .eq("readableId", row.OLD.trim())
+ .eq("companyId", COMPANY_ID)
+ .single(),
+ client
+ .from("part")
+ .select("*")
+ .eq("id", row.OLD.trim())
+ .eq("companyId", COMPANY_ID)
+ .single(),
+ client
+ .from("part")
+ .select("*")
+ .eq("id", row.NEW.trim())
+ .eq("companyId", COMPANY_ID)
+ .maybeSingle(),
+ ]);
+
+ if (item.error || oldPart.error) {
+ console.log(`Failed to fetch ${row.OLD.trim()}`);
+ fetchErrors.push(row.OLD.trim());
+ continue;
+ }
+
+ // @ts-ignore
+ if (READ_ONLY === false) {
+ console.log(`Updating ${row.OLD.trim()}`);
+
+ const itemUpdate = await client
+ .from("item")
+ .update({
+ readableId: row.NEW.trim(),
+ revision: row.REVISION.trim(),
+ })
+ .eq("id", item.data.id)
+ .eq("companyId", COMPANY_ID);
+
+ if (itemUpdate.error) {
+ console.log(`Failed to update item ${row.OLD.trim()}`);
+ console.log(itemUpdate);
+ updateErrors.push(row.OLD.trim());
+ }
+
+ if (newPart.data) {
+ const oldPartDelete = await client
+ .from("part")
+ .delete()
+ .eq("id", oldPart.data.id)
+ .eq("companyId", COMPANY_ID);
+
+ if (itemUpdate.error || oldPartDelete.error) {
+ console.log(`Failed to update ${row.OLD.trim()}`);
+ console.log(itemUpdate, oldPartDelete);
+ updateErrors.push(row.OLD.trim());
+ }
+ } else {
+ const oldPartUpdate = await client
+ .from("part")
+ .update({ id: row.NEW.trim() })
+ .eq("id", oldPart.data.id)
+ .eq("companyId", COMPANY_ID);
+ if (itemUpdate.error || oldPartUpdate.error) {
+ console.log(`Failed to update ${row.OLD.trim()}`);
+ console.log(itemUpdate, oldPartUpdate);
+ updateErrors.push(row.OLD.trim());
+ }
+ }
+ }
+ }
+
+ if (fetchErrors.length > 0) {
+ console.error("Failed to fetch the following items:");
+ console.log(fetchErrors);
+ }
+
+ if (updateErrors.length > 0) {
+ console.error("Failed to update the following items:");
+ console.log(updateErrors);
+ }
+ })
+ .on("error", (error) => {
+ console.error("Error processing CSV:", error);
+ });
+})();