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 projections to planning chart

Brad Barbina6c48c5f44bb
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index e25301f7c2..4784640f2e 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -560,3 +560,14 @@ export const unitOfMeasureValidator = z.object({
code: z.string().min(1, { message: "Code is required" }).max(10),
name: z.string().min(1, { message: "Name is required" }).max(50),
});
+
+export type Order = {
+ startDate: string | null;
+ dueDate: string | null;
+ quantity: number;
+ existingId?: string;
+ existingQuantity?: number;
+ existingReadableId?: string;
+ existingStatus?: string;
+ isASAP: boolean;
+};
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
index 447d54705d..2cac009bbb 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
@@ -50,10 +50,16 @@ import {
import { Empty, Hyperlink } from "~/components";
import type { loader as forecastLoader } from "~/routes/api+/items.$id.$locationId.forecast";
import { path } from "~/utils/path";
+import type { Order } from "../../items.models";
const supplySourceTypes = ["Purchase Order", "Production Order"] as const;
const demandSourceTypes = ["Sales Order", "Job Material"] as const;
+type SourceType =
+ | (typeof supplySourceTypes)[number]
+ | (typeof demandSourceTypes)[number]
+ | "Planned";
+
interface ChartDataPoint {
startDate: string;
period: string;
@@ -61,18 +67,23 @@ interface ChartDataPoint {
"Job Material": number;
"Purchase Order": number;
"Production Order": number;
+ Planned: number;
Projection: number;
}
const chartConfig = {} satisfies ChartConfig;
export const ItemPlanningChart = ({
+ compact = false,
itemId,
locationId,
+ plannedOrders = [],
safetyStock,
}: {
+ compact?: boolean;
itemId: string;
locationId: string;
+ plannedOrders?: Order[];
safetyStock?: number;
}) => {
const forecastFetcher = useFetcher<typeof forecastLoader>();
@@ -109,6 +120,7 @@ export const ItemPlanningChart = ({
"Job Material": 0,
"Purchase Order": 0,
"Production Order": 0,
+ Planned: 0,
Projection: currentQuantity, // Initialize with current quantity
};
return acc;
@@ -116,6 +128,25 @@ export const ItemPlanningChart = ({
{}
);
+ // Add projected orders
+ plannedOrders.forEach((order) => {
+ let periodId = periods.find(
+ (p) =>
+ new Date(p.startDate) <= new Date(order.dueDate ?? "") &&
+ new Date(p.endDate) >= new Date(order.dueDate ?? "")
+ )?.id;
+
+ // If no period found or order date is before first period, use first period
+ if (!periodId || !order.dueDate) {
+ periodId = periods[0].id;
+ }
+
+ if (groupedData[periodId]) {
+ groupedData[periodId]["Planned"] +=
+ (order.quantity ?? 0) - (order.existingQuantity ?? 0);
+ }
+ });
+
// Add demand data
demand.forEach((curr) => {
if (
@@ -157,14 +188,16 @@ export const ItemPlanningChart = ({
return sortedData.map((period) => {
// Add supply
runningProjection +=
- period["Purchase Order"] + period["Production Order"];
+ period["Purchase Order"] +
+ period["Production Order"] +
+ period["Planned"];
// Subtract demand
runningProjection += period["Sales Order"] + period["Job Material"];
// Update projection
period.Projection = runningProjection;
return period;
});
- }, [forecastFetcher.data]);
+ }, [forecastFetcher.data, plannedOrders]);
const combinedSupplyAndDemand = useMemo(() => {
let projectedQuantity = forecastFetcher.data?.quantityOnHand ?? 0;
@@ -172,24 +205,32 @@ export const ItemPlanningChart = ({
const combined = [
...(forecastFetcher.data?.openSalesOrderLines ?? []).map((line) => ({
...line,
- sourceType: "Sales Order",
+ sourceType: "Sales Order" as SourceType,
quantity: line.quantity ?? 0,
})),
...(forecastFetcher.data?.openJobMaterials ?? []).map((line) => ({
...line,
- sourceType: "Job Material",
+ sourceType: "Job Material" as SourceType,
quantity: line.quantity ?? 0,
})),
...(forecastFetcher.data?.openPurchaseOrderLines ?? []).map((line) => ({
...line,
- sourceType: "Purchase Order",
+ sourceType: "Purchase Order" as SourceType,
quantity: line.quantity ?? 0,
})),
...(forecastFetcher.data?.openProductionOrders ?? []).map((line) => ({
...line,
- sourceType: "Production Order",
+ sourceType: "Production Order" as SourceType,
quantity: line.quantity ?? 0,
})),
+ ...plannedOrders.map((order) => ({
+ ...order,
+ sourceType: "Planned" as SourceType,
+ quantity: order.quantity ?? 0,
+ documentReadableId: order?.existingReadableId ?? "Planned",
+ documentId: order?.existingId ?? null,
+ id: order?.existingId ?? null,
+ })),
]
.sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""))
.map((item) => {
@@ -214,7 +255,7 @@ export const ItemPlanningChart = ({
.toLowerCase()
.includes(searchTerm.toLowerCase())
);
- }, [forecastFetcher.data, searchTerm]);
+ }, [forecastFetcher.data, searchTerm, plannedOrders]);
if (
forecastFetcher.data?.demand.length === 0 &&
@@ -234,11 +275,11 @@ export const ItemPlanningChart = ({
return (
<>
- <Card>
- <CardHeader>
+ <Card className={cn(compact && "border-none p-0")}>
+ <CardHeader className={cn(compact && "px-0")}>
<CardTitle>Projections</CardTitle>
</CardHeader>
- <CardContent>
+ <CardContent className={cn(compact && "px-0")}>
<div className="w-full h-[360px]">
<Loading isLoading={isFetching}>
<ChartContainer config={chartConfig} className="w-full h-full">
@@ -267,6 +308,7 @@ export const ItemPlanningChart = ({
payload={[
{ value: "Demand", type: "rect", color: "#14b8a6" },
{ value: "Supply", type: "rect", color: "#2563eb" },
+ { value: "Planned", type: "rect", color: "#4f46e5" },
{
value: "Projection",
type: "line",
@@ -303,26 +345,27 @@ export const ItemPlanningChart = ({
fill="#7c3aedcc"
isAnimationActive={false}
/>
- {demandSourceTypes.map(
- (sourceType: string, index: number) => (
- <Bar
- key={sourceType}
- dataKey={sourceType}
- stackId="stack"
- className="fill-teal-500"
- />
- )
- )}
- {supplySourceTypes.map(
- (sourceType: string, index: number) => (
- <Bar
- key={sourceType}
- dataKey={sourceType}
- stackId="stack"
- className="fill-blue-600"
- />
- )
- )}
+ {demandSourceTypes.map((sourceType) => (
+ <Bar
+ key={sourceType}
+ dataKey={sourceType}
+ stackId="stack"
+ className="fill-teal-500"
+ />
+ ))}
+ {supplySourceTypes.map((sourceType) => (
+ <Bar
+ key={sourceType}
+ dataKey={sourceType}
+ stackId="stack"
+ className="fill-blue-600"
+ />
+ ))}
+ <Bar
+ dataKey="Planned"
+ stackId="stack"
+ className="fill-indigo-600"
+ />
</ComposedChart>
</ChartContainer>
</Loading>
@@ -330,9 +373,9 @@ export const ItemPlanningChart = ({
</CardContent>
</Card>
<Tabs defaultValue="all" className="w-full">
- <Card>
+ <Card className={cn(compact && "border-none p-0")}>
<HStack className="w-full justify-between">
- <CardHeader>
+ <CardHeader className={cn(compact && "px-0")}>
<CardTitle>Supply & Demand</CardTitle>
</CardHeader>
<CardAction className="flex items-center gap-2">
@@ -343,7 +386,7 @@ export const ItemPlanningChart = ({
</TabsList>
</CardAction>
</HStack>
- <CardContent>
+ <CardContent className={cn(compact && "px-0")}>
<div className="w-full grid grid-cols-1 lg:grid-cols-3 gap-4 py-4">
<Card>
<CardHeader className="pb-8">
@@ -444,7 +487,7 @@ export const ItemPlanningChart = ({
};
interface PlanningItem {
- sourceType: string;
+ sourceType: SourceType;
id: string | null;
dueDate: string | null;
documentReadableId: string | null;
@@ -454,13 +497,15 @@ interface PlanningItem {
parentMaterialId?: string | null;
jobId?: string | null;
jobMakeMethodId?: string | null;
+ existingOrderReadableId?: string | null;
}
-const sourceTypeIcons = {
+const sourceTypeIcons: Record<SourceType, JSX.Element> = {
"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" />,
+ Planned: <LuMoveUp className="h-4 w-4 text-teal-500" />,
};
function SupplyDemandPlanningItem({ item }: { item: PlanningItem }) {
@@ -471,7 +516,7 @@ function SupplyDemandPlanningItem({ item }: { item: PlanningItem }) {
<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]}
+ {sourceTypeIcons[item.sourceType]}
</div>
<VStack spacing={0}>
<Hyperlink
@@ -519,6 +564,8 @@ function getPathToDocument(item: PlanningItem) {
return path.to.purchaseOrder(item.documentId ?? "");
case "Production Order":
return path.to.job(item.documentId ?? "");
+ case "Planned":
+ return "#";
default:
return "";
}
diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
index df220f17eb..9fb253be01 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
@@ -2,6 +2,7 @@ import type { Database } from "@carbon/database";
import { Status } from "@carbon/react";
import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
import type { ProductionPlanningItem } from "~/modules/production";
+import type { Order } from "../../items.models";
export function ItemReorderPolicy({
reorderingPolicy,
@@ -57,13 +58,6 @@ export function getReorderPolicyDescription(
}
}
-export type Order = {
- startDate: string;
- dueDate: string;
- quantity: number;
- isASAP: boolean;
-};
-
export function getOrdersFromProductionPlanning(
itemPlanning: ProductionPlanningItem,
periods: { startDate: string; id: string }[]
@@ -72,12 +66,7 @@ export function getOrdersFromProductionPlanning(
return [];
}
- const orders: {
- startDate: string;
- dueDate: string;
- quantity: number;
- isASAP: boolean;
- }[] = [];
+ const orders: Order[] = [];
const {
demandAccumulationPeriod,
@@ -143,6 +132,7 @@ export function getOrdersFromProductionPlanning(
startDate: startDate.toString(),
dueDate: dueDate.toString(),
quantity: orderQuantity,
+
isASAP: startDate.compare(todaysDate) < 0,
});
@@ -175,6 +165,7 @@ export function getOrdersFromProductionPlanning(
startDate: startDate.toString(),
dueDate: dueDate.toString(),
quantity: reorderQuantity,
+
isASAP: startDate.compare(todaysDate) < 0,
});
day++;
@@ -229,6 +220,7 @@ export function getOrdersFromProductionPlanning(
startDate: startDate.toString(),
dueDate: dueDate.toString(),
quantity: orderQuantity,
+
isASAP:
startDate.compare(todaysDate) < 0 &&
projectedQuantity + orderedQuantity < 0,
diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
index 51915c3adb..f352b59ca9 100644
--- a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
@@ -1,7 +1,15 @@
+import { useCarbon } from "@carbon/auth";
import {
Button,
Combobox,
DatePicker,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerDescription,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
@@ -9,13 +17,6 @@ import {
DropdownMenuSeparator,
HStack,
IconButton,
- Modal,
- ModalBody,
- ModalContent,
- ModalDescription,
- ModalFooter,
- ModalHeader,
- ModalTitle,
NumberDecrementStepper,
NumberField,
NumberIncrementStepper,
@@ -23,22 +24,26 @@ import {
NumberInputGroup,
NumberInputStepper,
PulsingDot,
+ Separator,
Table as TableBase,
Tbody,
Td,
Th,
Thead,
+ toast,
Tooltip,
TooltipContent,
TooltipTrigger,
Tr,
+ useMount,
VStack,
} from "@carbon/react";
import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";
-import { useFetcher } from "@remix-run/react";
+import type { FetcherWithComponents } from "@remix-run/react";
+import { Link, useFetcher } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useCallback, useMemo, useState } from "react";
+import { memo, useCallback, useEffect, useMemo, useState } from "react";
import {
LuBookMarked,
LuBox,
@@ -47,24 +52,23 @@ import {
LuChevronUp,
LuCircleCheck,
LuCirclePlay,
+ LuExternalLink,
+ LuHardHat,
LuPackage,
LuPlus,
LuSquareChartGantt,
LuTrash2,
} from "react-icons/lu";
-import {
- Hyperlink,
- ItemThumbnail,
- MethodItemTypeIcon,
- Table,
-} from "~/components";
+import { ItemThumbnail, MethodItemTypeIcon, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
-import { usePermissions, useUrlParams } from "~/hooks";
+import { usePermissions } from "~/hooks";
import { itemTypes } from "~/modules/inventory/inventory.models";
+import type { Order } from "~/modules/items/items.models";
import { itemReorderingPolicies } from "~/modules/items/items.models";
-import type { Order } from "~/modules/items/ui/Item/ItemReorderPolicy";
+import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
+import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";
import {
getOrdersFromProductionPlanning,
getReorderPolicyDescription,
@@ -74,6 +78,7 @@ import type { action as mrpAction } from "~/routes/api+/mrp";
import type { action as bulkUpdateAction } from "~/routes/x+/production+/planning.update";
import { path } from "~/utils/path";
import type { ProductionPlanningItem } from "../../types";
+import { getDeadlineIcon, JobStatus } from "../Jobs";
type PlanningTableProps = {
data: ProductionPlanningItem[];
@@ -82,155 +87,375 @@ type PlanningTableProps = {
periods: { id: string; startDate: string; endDate: string }[];
};
-const OrderModal = memo(
+const OrderDrawer = memo(
({
+ fetcher,
row,
orders,
setOrders,
+ locationId,
isOpen,
onClose,
}: {
+ fetcher: FetcherWithComponents<typeof bulkUpdateAction>;
row: ProductionPlanningItem;
orders: Order[];
setOrders: (item: ProductionPlanningItem, orders: Order[]) => void;
+ locationId: string;
isOpen: boolean;
onClose: () => void;
}) => {
- const handleAddOrder = () => {
+ const { carbon } = useCarbon();
+ const getExistingOrders = useCallback(async () => {
+ if (!carbon || !row.id) return;
+
+ const { data: existingOrderData } = await carbon
+ ?.from("job")
+ .select("*")
+ .eq("itemId", row.id)
+ .in("status", ["Draft", "Planned"]);
+
+ if (existingOrderData) {
+ const existingOrders: Order[] = existingOrderData
+ .filter(
+ (order) =>
+ !orders.some((existing) => existing.existingId === order.id)
+ )
+ .map((order) => ({
+ existingId: order.id,
+ existingReadableId: order.jobId,
+ existingQuantity: order.quantity,
+ existingStatus: order.status,
+ startDate: order.startDate ?? null,
+ dueDate: order.dueDate ?? null,
+ quantity: order.quantity,
+ isASAP: order.deadlineType === "ASAP",
+ }));
+
+ setOrders(
+ row,
+ [...orders, ...existingOrders].sort((a, b) => {
+ return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;
+ })
+ );
+ }
+ }, [carbon, orders, row, setOrders]);
+
+ useMount(() => {
+ if (row.id) {
+ getExistingOrders();
+ }
+ });
+ console.log({ orders });
+
+ const onAddOrder = () => {
if (row.id) {
const newOrder: Order = {
- quantity: 0,
- dueDate: today(getLocalTimeZone()).toString(),
+ quantity: row.lotSize ?? row.minimumOrderQuantity ?? 0,
+ dueDate: today(getLocalTimeZone())
+ .add({ days: row.leadTime ?? 0 })
+ .toString(),
+ startDate: today(getLocalTimeZone()).toString(),
+ isASAP: false,
};
setOrders(row, [...orders, newOrder]);
}
};
- const handleRemoveOrder = (index: number) => {
+ const onRemoveOrder = (index: number) => {
if (row.id) {
const newOrders = orders.filter((_, i) => i !== index);
setOrders(row, newOrders);
}
};
+ const onSubmit = useCallback(
+ (id: string, orders: Order[]) => {
+ const payload = {
+ locationId,
+ items: [
+ {
+ id: id,
+ orders: orders,
+ },
+ ],
+ action: "order" as const,
+ };
+ fetcher.submit(payload, {
+ method: "post",
+ action: path.to.bulkUpdateProductionPlanning,
+ encType: "application/json",
+ });
+ },
+ [fetcher, locationId]
+ );
+
+ useEffect(() => {
+ if (fetcher.data?.success === false && fetcher?.data?.message) {
+ toast.error(fetcher.data.message);
+ }
+
+ if (fetcher.data?.success === true) {
+ toast.success("Orders submitted");
+ onClose();
+ }
+ }, [fetcher.data, fetcher.state]);
+
return (
- <Modal open={isOpen} onOpenChange={(open) => !open && onClose()}>
- <ModalContent>
- <ModalHeader>
- <ModalTitle>{row.readableIdWithRevision}</ModalTitle>
- <ModalDescription>{row.name}</ModalDescription>
- </ModalHeader>
- <ModalBody>
- <TableBase full>
- <Thead>
- <Th className="pl-0">
- <div className="flex items-center gap-2">
- <LuPackage />
- <span>Quantity</span>
- </div>
- </Th>
- <Th>
- <div className="justify-end flex items-center gap-2">
- <LuCalendar />
- <span>Due Date</span>
- </div>
- </Th>
- <Th className="w-[50px]"></Th>
- </Thead>
- <Tbody>
- {orders.map((order, index) => (
- <Tr key={index}>
- <Td className="pl-0 pr-1 group-hover:bg-inherit">
- <NumberField
- value={order.quantity}
- onChange={(value) => {
- if (row.id && value) {
- const newOrders = [...orders];
- newOrders[index] = {
- ...order,
- quantity: value,
- };
- setOrders(row, newOrders);
- }
- }}
- >
- <NumberInputGroup className="relative group-hover:bg-inherit">
- <NumberInput />
- <NumberInputStepper>
- <NumberIncrementStepper>
- <LuChevronUp size="1em" strokeWidth="3" />
- </NumberIncrementStepper>
- <NumberDecrementStepper>
- <LuChevronDown size="1em" strokeWidth="3" />
- </NumberDecrementStepper>
- </NumberInputStepper>
- </NumberInputGroup>
- </NumberField>
- </Td>
- <Td className="text-right px-1 group-hover:bg-inherit">
- <HStack className="justify-end">
- <DatePicker
- value={parseDate(order.dueDate)}
- onChange={(date) => {
- if (row.id) {
+ <Drawer open={isOpen} onOpenChange={(open) => !open && onClose()}>
+ <DrawerContent size="lg">
+ <DrawerHeader>
+ <DrawerTitle className="flex items-center gap-2">
+ <span>{row.readableIdWithRevision}</span>
+ <Link
+ // @ts-ignore
+ to={getLinkToItemDetails(row.type, row.id)}
+ >
+ <LuExternalLink />
+ </Link>
+ </DrawerTitle>
+ <DrawerDescription>{row.name}</DrawerDescription>
+ </DrawerHeader>
+ <DrawerBody>
+ <div className="flex flex-col gap-4 w-full">
+ {(row.lotSize ||
+ row.minimumOrderQuantity ||
+ row.maximumOrderQuantity) && (
+ <VStack spacing={2} className="text-sm border rounded-lg p-4">
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Reorder Policy:
+ </span>
+ <ItemReorderPolicy
+ reorderingPolicy={row.reorderingPolicy}
+ />
+ </HStack>
+ <Separator />
+ {row.reorderingPolicy === "Maximum Quantity" && (
+ <>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Reorder Point:
+ </span>
+ <span>{row.reorderPoint}</span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Maximum Inventory:
+ </span>
+ <span>{row.maximumInventoryQuantity}</span>
+ </HStack>
+ </>
+ )}
+
+ {row.reorderingPolicy === "Demand-Based Reorder" && (
+ <>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Accumulation Period:
+ </span>
+ <span>{row.demandAccumulationPeriod} weeks</span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Safety Stock:
+ </span>
+ <span>{row.demandAccumulationSafetyStock}</span>
+ </HStack>
+ </>
+ )}
+
+ {row.reorderingPolicy === "Fixed Reorder Quantity" && (
+ <>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Reorder Point:
+ </span>
+ <span>{row.reorderPoint}</span>
+ </HStack>
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Reorder Quantity:
+ </span>
+ <span>{row.reorderQuantity}</span>
+ </HStack>
+ </>
+ )}
+ {(row.lotSize > 0 ||
+ row.minimumOrderQuantity > 0 ||
+ row.maximumOrderQuantity > 0) && <Separator />}
+ {row.lotSize > 0 && (
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">Lot Size:</span>
+ <span>{row.lotSize}</span>
+ </HStack>
+ )}
+ {row.minimumOrderQuantity > 0 && (
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Minimum Order:
+ </span>
+ <span>{row.minimumOrderQuantity}</span>
+ </HStack>
+ )}
+ {row.maximumOrderQuantity > 0 && (
+ <HStack className="justify-between w-full">
+ <span className="text-muted-foreground">
+ Maximum Order:
+ </span>
+ <span>{row.maximumOrderQuantity}</span>
+ </HStack>
+ )}
+ </VStack>
+ )}
+
+ <TableBase full>
+ <Thead>
+ <Th className="pl-0">
+ <div className="flex items-center gap-2">
+ <LuHardHat />
+ <span>Job</span>
+ </div>
+ </Th>
+ <Th>
+ <div className="px-1 flex items-center gap-2 text-right">
+ <LuPackage />
+ <span>Quantity</span>
+ </div>
+ </Th>
+ <Th>
+ <div className="justify-end flex items-center gap-2">
+ <LuCalendar />
+ <span>Due Date</span>
+ </div>
+ </Th>
+ <Th className="w-[50px]"></Th>
+ </Thead>
+ <Tbody>
+ {orders.map((order, index) => (
+ <Tr key={index}>
+ <Td className="flex flex-row items-center gap-1 pl-0 pr-1 group-hover:bg-inherit justify-between">
+ {order.existingReadableId && order.existingId ? (
+ <VStack spacing={0}>
+ <Link to={path.to.job(order.existingId)}>
+ {order.existingReadableId}
+ </Link>
+ {/* @ts-expect-error - status is a string because we have a general type for purchase orders and jobs */}
+ <JobStatus status={order.existingStatus} />
+ </VStack>
+ ) : (
+ "New Job"
+ )}
+ {order.isASAP && getDeadlineIcon("ASAP")}
+ </Td>
+ <Td className="text-right px-1 group-hover:bg-inherit">
+ <NumberField
+ value={order.quantity}
+ onChange={(value) => {
+ if (row.id && value) {
const newOrders = [...orders];
newOrders[index] = {
...order,
- dueDate: date ? date.toString() : order.dueDate,
+ quantity: value,
};
setOrders(row, newOrders);
}
}}
+ >
+ <NumberInputGroup className="relative group-hover:bg-inherit">
+ <NumberInput />
+ <NumberInputStepper>
+ <NumberIncrementStepper>
+ <LuChevronUp size="1em" strokeWidth="3" />
+ </NumberIncrementStepper>
+ <NumberDecrementStepper>
+ <LuChevronDown size="1em" strokeWidth="3" />
+ </NumberDecrementStepper>
+ </NumberInputStepper>
+ </NumberInputGroup>
+ </NumberField>
+ </Td>
+ <Td className="text-right px-1 group-hover:bg-inherit">
+ <HStack className="justify-end">
+ <DatePicker
+ value={
+ order.dueDate ? parseDate(order.dueDate) : null
+ }
+ onChange={(date) => {
+ if (row.id) {
+ const newOrders = [...orders];
+ newOrders[index] = {
+ ...order,
+ dueDate: date ? date.toString() : null,
+ };
+ setOrders(row, newOrders);
+ }
+ }}
+ />
+ </HStack>
+ </Td>
+ <Td className="pl-1 pr-0 group-hover:bg-inherit">
+ <IconButton
+ aria-label="Remove order"
+ variant="ghost"
+ size="sm"
+ isDisabled={!!order.existingId}
+ onClick={() => onRemoveOrder(index)}
+ icon={<LuTrash2 className="text-destructive" />}
/>
- </HStack>
- </Td>
- <Td className="pl-1 pr-0 group-hover:bg-inherit">
- <IconButton
- aria-label="Remove order"
- variant="ghost"
- size="sm"
- onClick={() => handleRemoveOrder(index)}
- icon={<LuTrash2 className="text-destructive" />}
- />
- </Td>
- </Tr>
- ))}
- </Tbody>
- </TableBase>
- <Button
- variant="secondary"
- size="sm"
- className="mt-4"
- leftIcon={<LuPlus />}
- onClick={handleAddOrder}
- >
- Add Order
- </Button>
- </ModalBody>
- <ModalFooter>
+ </Td>
+ </Tr>
+ ))}
+ </Tbody>
+ </TableBase>
+
+ <div>
+ <Button
+ variant="secondary"
+ size="sm"
+ className="mt-4"
+ leftIcon={<LuPlus />}
+ onClick={onAddOrder}
+ >
+ Add Order
+ </Button>
+ </div>
+
+ <ItemPlanningChart
+ compact
+ itemId={row.id}
+ locationId={locationId}
+ safetyStock={row.demandAccumulationSafetyStock}
+ plannedOrders={orders}
+ />
+ </div>
+ </DrawerBody>
+ <DrawerFooter>
<Button variant="secondary" onClick={onClose}>
Close
</Button>
<Button
variant="primary"
- onClick={() => console.log(row.id, orders)}
+ onClick={() => onSubmit(row.id, orders)}
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
>
Order
</Button>
- </ModalFooter>
- </ModalContent>
- </Modal>
+ </DrawerFooter>
+ </DrawerContent>
+ </Drawer>
);
}
);
-OrderModal.displayName = "OrderModal";
+OrderDrawer.displayName = "OrderDrawer";
const PlanningTable = memo(
({ data, count, locationId, periods }: PlanningTableProps) => {
const permissions = usePermissions();
const isDisabled = !permissions.can("create", "production");
- const [params] = useUrlParams();
+
const dateFormatter = useDateFormatter({
month: "short",
day: "numeric",
@@ -243,7 +468,7 @@ const PlanningTable = memo(
const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();
// Store orders in a map keyed by item id
- const [ordersMap, setOrderssMap] = useState<Record<string, Order[]>>(() => {
+ const [ordersMap, setOrdersMap] = useState<Record<string, Order[]>>(() => {
const initialMap: Record<string, Order[]> = {};
data.forEach((item) => {
if (item.id) {
@@ -282,7 +507,7 @@ const PlanningTable = memo(
const setOrders = useCallback(
(item: ProductionPlanningItem, orders: Order[]) => {
if (item.id) {
- setOrderssMap((prev) => ({
+ setOrdersMap((prev) => ({
...prev,
[item.id!]: orders,
}));
@@ -335,7 +560,12 @@ const PlanningTable = memo(
accessorKey: "readableIdWithRevision",
header: "Part ID",
cell: ({ row }) => (
- <HStack className="py-1">
+ <HStack
+ className="py-1 cursor-pointer"
+ onClick={() => {
+ setSelectedItem(row.original);
+ }}
+ >
<ItemThumbnail
size="sm"
thumbnailPath={row.original.thumbnailPath}
@@ -343,31 +573,31 @@ const PlanningTable = memo(
type={row.original.type}
/>
- <Hyperlink
- to={`${path.to.productionPlanningItem(
- row.original.id!
- )}?${params.toString()}`}
- >
- <VStack spacing={0}>
- {row.original.readableIdWithRevision}
- <div className="w-full truncate text-muted-foreground text-xs">
- {row.original.name}
- </div>
- </VStack>
- </Hyperlink>
- <Enumerable
- value={
- unitOfMeasures.find(
- (uom) => uom.value === row.original.unitOfMeasureCode
- )?.label ?? null
- }
- />
+ <VStack spacing={0} className="font-medium">
+ {row.original.readableIdWithRevision}
+ <div className="w-full truncate text-muted-foreground text-xs">
+ {row.original.name}
+ </div>
+ </VStack>
</HStack>
),
meta: {
icon: <LuBookMarked />,
},
},
+ {
+ accessorKey: "unitOfMeasureCode",
+ header: "",
+ cell: ({ row }) => (
+ <Enumerable
+ value={
+ unitOfMeasures.find(
+ (uom) => uom.value === row.original.unitOfMeasureCode
+ )?.label ?? null
+ }
+ />
+ ),
+ },
{
accessorKey: "reorderingPolicy",
header: "Reorder Policy",
@@ -445,7 +675,8 @@ const PlanningTable = memo(
: [];
const hasOrders = orders.length > 0;
const orderQuantity = orders.reduce(
- (acc, order) => acc + order.quantity,
+ (acc, order) =>
+ acc + (order.quantity - (order.existingQuantity ?? 0)),
0
);
return (
@@ -476,7 +707,6 @@ const PlanningTable = memo(
periods,
dateFormatter,
numberFormatter,
- params,
unitOfMeasures,
isDisabled,
ordersMap,
@@ -566,7 +796,10 @@ const PlanningTable = memo(
/>
{selectedItem && (
- <OrderModal
+ <OrderDrawer
+ // @ts-ignore
+ fetcher={bulkUpdateFetcher}
+ locationId={locationId}
row={selectedItem}
orders={selectedItem.id ? ordersMap[selectedItem.id] || [] : []}
setOrders={setOrders}
diff --git a/apps/erp/app/routes/x+/production+/planning.$itemId.tsx b/apps/erp/app/routes/x+/production+/planning.$itemId.tsx
deleted file mode 100644
index 4c2c9403cc..0000000000
--- a/apps/erp/app/routes/x+/production+/planning.$itemId.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.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, redirect } from "@vercel/remix";
-import { LuExternalLink, LuX } from "react-icons/lu";
-import { useUser } from "~/hooks/useUser";
-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, userId, companyId } = await requirePermissions(request, {
- view: "parts",
- });
-
- const { itemId } = params;
- if (!itemId) {
- throw new Error("itemId not found");
- }
-
- const searchParams = new URL(request.url).searchParams;
-
- 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() {
- const { itemId } = useParams();
- if (!itemId) {
- throw new Error("itemId not found");
- }
-
- const { item, itemPlanning } = useLoaderData<typeof loader>();
-
- const routeData = useRouteData<{
- locationId: string;
- itemPlanning: ProductionPlanningItem;
- }>(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 ?? ""}
- safetyStock={
- itemPlanning?.reorderingPolicy === "Demand-Based Reorder"
- ? itemPlanning.demandAccumulationSafetyStock
- : undefined
- }
- />
- </VStack>
- </ScrollArea>
- </ResizablePanel>
- </>
- );
-}
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsx
index 24d043baf9..2570f4bac3 100644
--- a/apps/erp/app/routes/x+/production+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx
@@ -9,13 +9,15 @@ export async function action({ request }: ActionFunctionArgs) {
const { items, action, locationId } = await request.json();
if (typeof action !== "string") {
- return json({ error: { message: "Invalid form data" }, data: null });
+ return json({ success: false, message: "Invalid form data" });
}
switch (action) {
case "order":
console.log({ items, action, locationId });
+
+ return json({ success: true, message: "Orders submitted" });
default:
- return json({ error: { message: "Invalid field" }, data: null });
+ return json({ success: false, message: "Invalid field" });
}
}
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.tsx
index 316a1e011e..0e130b15fb 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,7 +1,7 @@
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 { validationError, validator } from "@carbon/form";
import { Menubar, VStack } from "@carbon/react";
import { Await, useLoaderData, useParams } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
@@ -28,7 +28,6 @@ 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, {
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 18104b0107..6bb8502381 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -9030,6 +9030,7 @@ export type Database = {
salesOrderLineId: string | null
scrapQuantity: number
secondsToComplete: number | null
+ startDate: string | null
status: Database["public"]["Enums"]["jobStatus"]
tags: string[] | null
unitOfMeasureCode: string
@@ -9067,6 +9068,7 @@ export type Database = {
salesOrderLineId?: string | null
scrapQuantity?: number
secondsToComplete?: number | null
+ startDate?: string | null
status?: Database["public"]["Enums"]["jobStatus"]
tags?: string[] | null
unitOfMeasureCode: string
@@ -9104,6 +9106,7 @@ export type Database = {
salesOrderLineId?: string | null
scrapQuantity?: number
secondsToComplete?: number | null
+ startDate?: string | null
status?: Database["public"]["Enums"]["jobStatus"]
tags?: string[] | null
unitOfMeasureCode?: string
@@ -38093,14 +38096,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 18104b0107..6bb8502381 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -9030,6 +9030,7 @@ export type Database = {
salesOrderLineId: string | null
scrapQuantity: number
secondsToComplete: number | null
+ startDate: string | null
status: Database["public"]["Enums"]["jobStatus"]
tags: string[] | null
unitOfMeasureCode: string
@@ -9067,6 +9068,7 @@ export type Database = {
salesOrderLineId?: string | null
scrapQuantity?: number
secondsToComplete?: number | null
+ startDate?: string | null
status?: Database["public"]["Enums"]["jobStatus"]
tags?: string[] | null
unitOfMeasureCode: string
@@ -9104,6 +9106,7 @@ export type Database = {
salesOrderLineId?: string | null
scrapQuantity?: number
secondsToComplete?: number | null
+ startDate?: string | null
status?: Database["public"]["Enums"]["jobStatus"]
tags?: string[] | null
unitOfMeasureCode?: string
@@ -38093,14 +38096,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
diff --git a/packages/database/supabase/migrations/20250616131548_production-planning.sql b/packages/database/supabase/migrations/20250616131548_production-planning.sql
index 9794c7abda..fcb051f064 100644
--- a/packages/database/supabase/migrations/20250616131548_production-planning.sql
+++ b/packages/database/supabase/migrations/20250616131548_production-planning.sql
@@ -9,6 +9,7 @@ ALTER TABLE "itemPlanning" ADD COLUMN "demandAccumulationSafetyStock" NUMERIC NO
ALTER TABLE "itemPlanning" ALTER COLUMN "demandAccumulationPeriod" SET DEFAULT 4;
UPDATE "itemPlanning" SET "demandAccumulationPeriod" = 4;
+ALTER TABLE "job" ADD COLUMN "startDate" DATE;
-- Add indexes for supply and demand tables
CREATE INDEX IF NOT EXISTS "supplyActual_companyId_locationId_idx" ON "supplyActual" ("companyId", "locationId");
diff --git a/scripts/migrations/part-revision-merges.ts b/scripts/migrations/part-revision-merges.ts
index a8364838d4..19ad5c0343 100644
--- a/scripts/migrations/part-revision-merges.ts
+++ b/scripts/migrations/part-revision-merges.ts
@@ -10,7 +10,7 @@ const COMPANY_ID = "cs868u84gfk07v78v9e0";
const PROD: boolean = true;
const READ_ONLY: boolean = false;
-const sourceFile = resolve(homedir(), "Desktop/black-cat-renames.csv");
+const sourceFile = resolve(homedir(), "Desktop/black-cat-renames-2.csv");
const columns = ["ID", "OLD", "NEW", "REVISION"];
const parser = parse({