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 ui for purchase planning

Brad Barbin1ec76d295984
diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
index b7a6f4c811..2ad0ac249a 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 { PurchasingPlanningItem } from "~/modules/purchasing";
import type { Order } from "../../items.models";
export function ItemReorderPolicy({
@@ -40,7 +41,7 @@ export function ItemReorderPolicy({
}
export function getReorderPolicyDescription(
- itemPlanning: ProductionPlanningItem
+ itemPlanning: ProductionPlanningItem | PurchasingPlanningItem
) {
const reorderPoint = itemPlanning.reorderPoint;
switch (itemPlanning.reorderingPolicy) {
@@ -58,8 +59,8 @@ export function getReorderPolicyDescription(
}
}
-export function getOrdersFromProductionPlanning(
- itemPlanning: ProductionPlanningItem,
+export function getOrdersFromPlanning(
+ itemPlanning: ProductionPlanningItem | PurchasingPlanningItem,
periods: { startDate: string; id: string }[]
): Order[] {
if (itemPlanning.reorderingPolicy === "Manual Reorder") {
@@ -140,7 +141,7 @@ export function getOrdersFromProductionPlanning(
case "Fixed Reorder Quantity":
for (let i = 0; i < periods.length; i++) {
const period = periods[i];
- const periodKey = `week${i + 1}` as keyof ProductionPlanningItem;
+ const periodKey = `week${i + 1}` as "week1";
const projectedQuantity = (itemPlanning[periodKey] as number) || 0;
// Check if we need to order based on reorder point
@@ -172,7 +173,7 @@ export function getOrdersFromProductionPlanning(
case "Maximum Quantity":
for (let i = 0; i < periods.length; i++) {
const period = periods[i];
- const periodKey = `week${i + 1}` as keyof ProductionPlanningItem;
+ const periodKey = `week${i + 1}` as "week1";
const projectedQuantity = (itemPlanning[periodKey] as number) || 0;
// Check if we need to order based on reorder point
diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
similarity index 98%
rename from apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
rename to apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
index fdacf3d4d1..3d3c671f32 100644
--- a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
@@ -70,7 +70,7 @@ import { itemReorderingPolicies } from "~/modules/items/items.models";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";
import {
- getOrdersFromProductionPlanning,
+ getOrdersFromPlanning,
getReorderPolicyDescription,
ItemReorderPolicy,
} from "~/modules/items/ui/Item/ItemReorderPolicy";
@@ -80,7 +80,7 @@ import { path } from "~/utils/path";
import type { ProductionPlanningItem } from "../../types";
import { JobStatus } from "../Jobs";
-type PlanningTableProps = {
+type ProductionPlanningTableProps = {
data: ProductionPlanningItem[];
count: number;
locationId: string;
@@ -286,7 +286,7 @@ const OrderDrawer = memo(
// Memoize drawer content
const drawerContent = useMemo(
() => (
- <DrawerContent size="md">
+ <DrawerContent size="lg">
<DrawerHeader>
<DrawerTitle className="flex items-center gap-2">
<span>{row.readableIdWithRevision}</span>
@@ -548,8 +548,8 @@ const OrderDrawer = memo(
OrderDrawer.displayName = "OrderDrawer";
-const PlanningTable = memo(
- ({ data, count, locationId, periods }: PlanningTableProps) => {
+const ProductionPlanningTable = memo(
+ ({ data, count, locationId, periods }: ProductionPlanningTableProps) => {
const permissions = usePermissions();
const dateFormatter = useDateFormatter({
@@ -586,7 +586,7 @@ const PlanningTable = memo(
const initialMap: Record<string, Order[]> = {};
data.forEach((item) => {
if (item.id) {
- initialMap[item.id] = getOrdersFromProductionPlanning(item, periods);
+ initialMap[item.id] = getOrdersFromPlanning(item, periods);
}
});
return initialMap;
@@ -939,7 +939,7 @@ const PlanningTable = memo(
}
renderActions={renderActions}
title="Planning"
- table="planning"
+ table="production-planning"
withSavedView
withSelectableRows
/>
@@ -960,9 +960,9 @@ const PlanningTable = memo(
}
);
-PlanningTable.displayName = "PlanningTable";
+ProductionPlanningTable.displayName = "ProductionPlanningTable";
-export default PlanningTable;
+export default ProductionPlanningTable;
function getLocationPath(locationId: string) {
return `${path.to.productionPlanning}?location=${locationId}`;
diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
index a788843c04..d606b58450 100644
--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
@@ -29,7 +29,7 @@ const productionRoutes: AuthenticatedRouteGroup[] = [
name: "Planning",
to: path.to.productionPlanning,
icon: <LuSquareChartGantt />,
- table: "planning",
+ table: "production-planning",
},
{
name: "Schedule",
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 772506edc1..f485f1d126 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -314,6 +314,40 @@ export async function getPurchasingDocumentsAssignedToMe(
return merged;
}
+export async function getPurchasingPlanning(
+ client: SupabaseClient<Database>,
+ locationId: string,
+ companyId: string,
+ periods: string[],
+ args: GenericQueryFilters & {
+ search: string | null;
+ }
+) {
+ let query = client.rpc(
+ "get_purchasing_planning",
+ {
+ location_id: locationId,
+ company_id: companyId,
+ periods,
+ },
+ {
+ count: "exact",
+ }
+ );
+
+ if (args?.search) {
+ query = query.or(
+ `name.ilike.%${args.search}%,readableIdWithRevision.ilike.%${args.search}%`
+ );
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "readableIdWithRevision", ascending: true },
+ ]);
+
+ return query;
+}
+
export async function getPurchasingTerms(
client: SupabaseClient<Database>,
companyId: string
diff --git a/apps/erp/app/modules/purchasing/types.ts b/apps/erp/app/modules/purchasing/types.ts
index 5c823d3523..e0d3c1522d 100644
--- a/apps/erp/app/modules/purchasing/types.ts
+++ b/apps/erp/app/modules/purchasing/types.ts
@@ -4,6 +4,7 @@ import type {
getPurchaseOrderDelivery,
getPurchaseOrderLines,
getPurchaseOrders,
+ getPurchasingPlanning,
getSupplier,
getSupplierContacts,
getSupplierInteraction,
@@ -43,6 +44,10 @@ export type PurchaseOrderType =
export type PurchaseOrderTransactionType =
Database["public"]["Enums"]["purchaseOrderTransactionType"];
+export type PurchasingPlanningItem = NonNullable<
+ Awaited<ReturnType<typeof getPurchasingPlanning>>["data"]
+>[number];
+
export type Supplier = NonNullable<
Awaited<ReturnType<typeof getSuppliers>>["data"]
>[number];
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
new file mode 100644
index 0000000000..40d07e9ac6
--- /dev/null
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -0,0 +1,984 @@
+import { useCarbon } from "@carbon/auth";
+import {
+ Button,
+ Combobox,
+ DatePicker,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerDescription,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ HStack,
+ IconButton,
+ NumberDecrementStepper,
+ NumberField,
+ NumberIncrementStepper,
+ NumberInput,
+ 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 { Link, useFetcher } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import {
+ LuBookMarked,
+ LuBox,
+ LuCalendar,
+ LuChevronDown,
+ LuChevronUp,
+ LuCircleCheck,
+ LuCirclePlay,
+ LuExternalLink,
+ LuHardHat,
+ LuPackage,
+ LuPlus,
+ LuSquareChartGantt,
+ LuStar,
+ LuTrash2,
+} from "react-icons/lu";
+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 } 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 { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
+import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";
+import {
+ getOrdersFromPlanning,
+ getReorderPolicyDescription,
+ ItemReorderPolicy,
+} from "~/modules/items/ui/Item/ItemReorderPolicy";
+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 { PurchasingPlanningItem } from "../../types";
+import { PurchasingStatus } from "../PurchaseOrder";
+
+type PlanningTableProps = {
+ data: PurchasingPlanningItem[];
+ count: number;
+ locationId: string;
+ periods: { id: string; startDate: string; endDate: string }[];
+};
+
+const OrderDrawer = memo(
+ ({
+ row,
+ orders,
+ setOrders,
+ locationId,
+ periods,
+ isOpen,
+ onClose,
+ }: {
+ row: PurchasingPlanningItem;
+ orders: Order[];
+ setOrders: (item: PurchasingPlanningItem, orders: Order[]) => void;
+ locationId: string;
+ periods: { id: string; startDate: string; endDate: string }[];
+ isOpen: boolean;
+ onClose: () => void;
+ }) => {
+ const fetcher = useFetcher<typeof bulkUpdateAction>();
+ const { carbon } = useCarbon();
+
+ // Memoize getExistingOrders callback
+ const getExistingOrders = useCallback(async () => {
+ if (!carbon || !row.id) return;
+
+ const { data: existingOrderData } = await carbon
+ ?.from("purchaseOrderLine")
+ .select(
+ "*, ...purchaseOrder(purchaseOrderReadableId:purchaseOrderId, status, orderDate, ...purchaseOrderDelivery(receiptRequestedDate, receiptPromisedDate))"
+ )
+ .eq("itemId", row.id)
+ .in("purchaseOrder.status", ["Draft", "Planned"]);
+
+ if (existingOrderData) {
+ const existingOrders: Order[] = existingOrderData
+ .filter(
+ (order) =>
+ !orders.some((existing) => existing.existingId === order.id)
+ )
+ .map((order) => {
+ const dueDate =
+ order.receiptPromisedDate ??
+ order.receiptRequestedDate ??
+ order?.orderDate;
+ // If no due date or due date is before first period, use first period
+ if (
+ !dueDate ||
+ parseDate(dueDate) < parseDate(periods[0].startDate)
+ ) {
+ return {
+ existingId: order.id,
+ existingReadableId: order.purchaseOrderId,
+ existingQuantity:
+ order.status === "Draft"
+ ? 0
+ : (order?.purchaseQuantity ?? 0) *
+ (order.conversionFactor ?? 1),
+ existingStatus: order.status,
+ startDate: order.orderDate ?? null,
+ dueDate: null,
+ quantity:
+ (order.purchaseQuantity ?? 0) * (order.conversionFactor ?? 1),
+ isASAP: false,
+ periodId: periods[0].id,
+ };
+ }
+
+ // Find matching period based on due date
+ const period = periods.find((p) => {
+ const d = parseDate(dueDate!);
+ const startDate = parseDate(p.startDate);
+ const endDate = parseDate(p.endDate);
+ return d >= startDate && d <= endDate;
+ });
+
+ // If no matching period found (date is after last period), use last period
+ return {
+ existingId: order.purchaseOrderId,
+ existingLineId: order.id,
+ existingReadableId: order.purchaseOrderReadableId,
+ existingQuantity:
+ order.status === "Draft"
+ ? 0
+ : (order?.purchaseQuantity ?? 0) *
+ (order.conversionFactor ?? 1),
+ existingStatus: order.status,
+ startDate: order.orderDate ?? null,
+ dueDate: dueDate ?? null,
+ quantity:
+ (order.purchaseQuantity ?? 0) * (order.conversionFactor ?? 1),
+ isASAP: false,
+ periodId: period?.id ?? periods[periods.length - 1].id,
+ };
+ });
+
+ setOrders(
+ row,
+ [...orders, ...existingOrders].sort((a, b) => {
+ return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;
+ })
+ );
+ }
+ }, [carbon, orders, row, setOrders, periods]);
+
+ useMount(() => {
+ if (row.id) {
+ getExistingOrders();
+ }
+ });
+
+ // Memoize handlers
+ const onAddOrder = useCallback(() => {
+ if (row.id) {
+ const newOrder: Order = {
+ quantity: row.lotSize ?? row.minimumOrderQuantity ?? 0,
+ dueDate: today(getLocalTimeZone())
+ .add({ days: row.leadTime ?? 0 })
+ .toString(),
+ startDate: today(getLocalTimeZone()).toString(),
+ isASAP: false,
+ periodId: periods[0].id,
+ };
+ setOrders(row, [...orders, newOrder]);
+ }
+ }, [row, orders, setOrders, periods]);
+
+ const onRemoveOrder = useCallback(
+ (index: number) => {
+ if (row.id) {
+ const newOrders = orders.filter((_, i) => i !== index);
+ setOrders(row, newOrders);
+ }
+ },
+ [row, orders, setOrders]
+ );
+
+ const onSubmit = useCallback(
+ (id: string, orders: Order[]) => {
+ const ordersWithPeriods = orders.map((order) => {
+ // If no due date or due date is before first period, use first period
+ if (
+ !order.dueDate ||
+ parseDate(order.dueDate) < parseDate(periods[0].startDate)
+ ) {
+ return {
+ ...order,
+ periodId: periods[0].id,
+ };
+ }
+
+ // Find matching period based on due date
+ const period = periods.find((p) => {
+ const dueDate = parseDate(order.dueDate!);
+ const startDate = parseDate(p.startDate);
+ const endDate = parseDate(p.endDate);
+ return dueDate >= startDate && dueDate <= endDate;
+ });
+
+ // If no matching period found (date is after last period), use last period
+ return {
+ ...order,
+ periodId: period?.id ?? periods[periods.length - 1].id,
+ };
+ });
+
+ const payload = {
+ locationId,
+ items: [
+ {
+ id: id,
+ orders: ordersWithPeriods,
+ },
+ ],
+ action: "order" as const,
+ };
+ fetcher.submit(payload, {
+ method: "post",
+ action: path.to.bulkUpdatePurchasingPlanning,
+ encType: "application/json",
+ });
+ },
+ [fetcher, locationId, periods]
+ );
+
+ // Memoize order update handler
+ const handleOrderUpdate = useCallback(
+ (index: number, updates: Partial<Order>) => {
+ if (row.id) {
+ const newOrders = [...orders];
+ newOrders[index] = {
+ ...orders[index],
+ ...updates,
+ };
+ setOrders(row, newOrders);
+ }
+ },
+ [row, orders, setOrders]
+ );
+
+ useEffect(() => {
+ if (fetcher.data?.success === false && fetcher?.data?.message) {
+ toast.error(fetcher.data.message);
+ }
+
+ if (fetcher.data?.success === true) {
+ toast.success("Orders submitted");
+ setOrders(row, []);
+ onClose();
+ }
+ }, [fetcher.data, onClose, row, setOrders]);
+
+ // Memoize drawer content
+ const drawerContent = useMemo(
+ () => (
+ <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">
+ <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 pr-1">
+ <div className="flex items-center gap-2">
+ <LuHardHat />
+ <span>PO</span>
+ </div>
+ </Th>
+ <Th className="px-1">
+ <div className="flex items-center gap-2 text-left">
+ <LuStar />
+ <span>Status</span>
+ </div>
+ </Th>
+ <Th className="px-1">
+ <div className="flex items-center gap-2 text-right">
+ <LuPackage />
+ <span>Quantity</span>
+ </div>
+ </Th>
+ <Th className="pr-1">
+ <div className="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 justify-between">
+ {order.existingReadableId && order.existingId ? (
+ <Link to={path.to.purchaseOrder(order.existingId)}>
+ {order.existingReadableId}
+ </Link>
+ ) : (
+ "New PO"
+ )}
+ </Td>
+ <Td className="flex flex-row items-center gap-1 px-1 group-hover:bg-inherit">
+ {/* @ts-expect-error - status is a string because we have a general type for purchase orders and purchaseOrderLines */}
+ <PurchasingStatus status={order.existingStatus} />
+ </Td>
+ <Td className="text-right px-1 group-hover:bg-inherit">
+ <NumberField
+ value={order.quantity}
+ onBlur={(e) => {
+ const datePickerInput = e.target
+ .closest("tr")
+ ?.querySelector(
+ '[role="textbox"]'
+ ) as HTMLElement;
+ if (datePickerInput) {
+ datePickerInput.focus();
+ }
+ }}
+ onChange={(value) => {
+ if (value) {
+ handleOrderUpdate(index, { quantity: value });
+ }
+ }}
+ >
+ <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) => {
+ handleOrderUpdate(index, {
+ dueDate: date ? date.toString() : null,
+ });
+ }}
+ />
+ </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" />}
+ />
+ </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={() => onSubmit(row.id, orders)}
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Order
+ </Button>
+ </DrawerFooter>
+ </DrawerContent>
+ ),
+ [
+ row,
+ orders,
+ locationId,
+ fetcher.state,
+ onClose,
+ onAddOrder,
+ onRemoveOrder,
+ onSubmit,
+ handleOrderUpdate,
+ ]
+ );
+
+ return (
+ <Drawer open={isOpen} onOpenChange={(open) => !open && onClose()}>
+ {drawerContent}
+ </Drawer>
+ );
+ }
+);
+
+OrderDrawer.displayName = "OrderDrawer";
+
+const PlanningTable = memo(
+ ({ data, count, locationId, periods }: PlanningTableProps) => {
+ const permissions = usePermissions();
+
+ const dateFormatter = useDateFormatter({
+ month: "short",
+ day: "numeric",
+ });
+
+ const numberFormatter = useNumberFormatter();
+ const locations = useLocations();
+ const unitOfMeasures = useUnitOfMeasure();
+
+ const mrpFetcher = useFetcher<typeof mrpAction>();
+ const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();
+
+ useEffect(() => {
+ if (
+ bulkUpdateFetcher.data?.success === false &&
+ bulkUpdateFetcher?.data?.message
+ ) {
+ toast.error(bulkUpdateFetcher.data.message);
+ }
+
+ if (bulkUpdateFetcher.data?.success === true) {
+ toast.success("Orders submitted");
+ }
+ }, [bulkUpdateFetcher.data]);
+
+ const isDisabled =
+ !permissions.can("create", "production") ||
+ bulkUpdateFetcher.state !== "idle" ||
+ mrpFetcher.state !== "idle";
+
+ const getOrders = useCallback(() => {
+ const initialMap: Record<string, Order[]> = {};
+ data.forEach((item) => {
+ if (item.id) {
+ initialMap[item.id] = getOrdersFromPlanning(item, periods);
+ }
+ });
+ return initialMap;
+ }, [data, periods]);
+
+ // Store orders in a map keyed by item id
+ const [ordersMap, setOrdersMap] =
+ useState<Record<string, Order[]>>(getOrders);
+
+ useEffect(() => {
+ setOrdersMap(getOrders());
+ }, [data, periods, getOrders]);
+
+ const onBulkUpdate = useCallback(
+ (selectedRows: typeof data, action: "order") => {
+ const payload = {
+ locationId,
+ items: selectedRows
+ .filter((row) => row.id)
+ .map((row) => {
+ const ordersWithPeriods = (ordersMap[row.id!] || []).map(
+ (order) => {
+ // If no due date or due date is before first period, use first period
+ if (
+ !order.dueDate ||
+ parseDate(order.dueDate) < parseDate(periods[0].startDate)
+ ) {
+ return {
+ ...order,
+ periodId: periods[0].id,
+ };
+ }
+
+ // Find matching period based on due date
+ const period = periods.find((p) => {
+ const dueDate = parseDate(order.dueDate!);
+ const startDate = parseDate(p.startDate);
+ const endDate = parseDate(p.endDate);
+ return dueDate >= startDate && dueDate <= endDate;
+ });
+
+ // If no matching period found (date is after last period), use last period
+ return {
+ ...order,
+ periodId: period?.id ?? periods[periods.length - 1].id,
+ };
+ }
+ );
+
+ return {
+ id: row.id,
+ orders: ordersWithPeriods,
+ };
+ }),
+ action: action,
+ };
+ bulkUpdateFetcher.submit(payload, {
+ method: "post",
+ action: path.to.bulkUpdatePurchasingPlanning,
+ encType: "application/json",
+ });
+ },
+ [bulkUpdateFetcher, locationId, ordersMap, periods]
+ );
+
+ const [selectedItem, setSelectedItem] =
+ useState<PurchasingPlanningItem | null>(null);
+
+ const setOrders = useCallback(
+ (item: PurchasingPlanningItem, orders: Order[]) => {
+ if (item.id) {
+ setOrdersMap((prev) => ({
+ ...prev,
+ [item.id!]: orders,
+ }));
+ }
+ },
+ []
+ );
+
+ const columns = useMemo<ColumnDef<PurchasingPlanningItem>[]>(() => {
+ const periodColumns: ColumnDef<PurchasingPlanningItem>[] = periods.map(
+ (period, index) => {
+ const isCurrentWeek = index === 0;
+ const weekNumber = index + 1;
+ const weekKey = `week${weekNumber}` as keyof PurchasingPlanningItem;
+ const startDate = parseDate(period.startDate).toDate(
+ getLocalTimeZone()
+ );
+ const endDate = parseDate(period.endDate).toDate(getLocalTimeZone());
+
+ return {
+ accessorKey: weekKey,
+ header: () => (
+ <VStack spacing={0}>
+ <div>
+ {isCurrentWeek ? "Present Week" : `Week ${weekNumber}`}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {dateFormatter.format(startDate)} -{" "}
+ {dateFormatter.format(endDate)}
+ </div>
+ </VStack>
+ ),
+ cell: ({ row }) => {
+ const value = row.getValue<number>(weekKey);
+ if (value === undefined) return "-";
+ return (
+ <span
+ className={value < 0 ? "text-red-500 font-bold" : undefined}
+ >
+ {numberFormatter.format(value)}
+ </span>
+ );
+ },
+ };
+ }
+ );
+
+ return [
+ {
+ accessorKey: "readableIdWithRevision",
+ header: "Part ID",
+ cell: ({ row }) => (
+ <HStack
+ className="py-1 cursor-pointer"
+ onClick={() => {
+ setSelectedItem(row.original);
+ }}
+ >
+ <ItemThumbnail
+ size="sm"
+ thumbnailPath={row.original.thumbnailPath}
+ // @ts-ignore
+ type={row.original.type}
+ />
+
+ <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",
+ cell: ({ row }) => {
+ return (
+ <HStack>
+ <Tooltip>
+ <TooltipTrigger>
+ <ItemReorderPolicy
+ reorderingPolicy={row.original.reorderingPolicy}
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ {getReorderPolicyDescription(row.original)}
+ </TooltipContent>
+ </Tooltip>
+ </HStack>
+ );
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: itemReorderingPolicies.map((policy) => ({
+ label: <ItemReorderPolicy reorderingPolicy={policy} />,
+ value: policy,
+ })),
+ },
+ icon: <LuCircleCheck />,
+ },
+ },
+ {
+ accessorKey: "quantityOnHand",
+ header: "On Hand",
+ cell: ({ row }) =>
+ numberFormatter.format(row.original.quantityOnHand),
+ meta: {
+ icon: <LuPackage />,
+ },
+ },
+ ...periodColumns,
+ {
+ accessorKey: "type",
+ header: "Type",
+ cell: ({ row }) =>
+ row.original.type && (
+ <HStack>
+ <MethodItemTypeIcon type={row.original.type} />
+ <span>{row.original.type}</span>
+ </HStack>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ 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 />,
+ },
+ },
+ {
+ id: "Order",
+ header: "",
+ cell: ({ row }) => {
+ const orders = row.original.id
+ ? ordersMap[row.original.id] || []
+ : [];
+ const orderQuantity = orders.reduce(
+ (acc, order) =>
+ acc + (order.quantity - (order.existingQuantity ?? 0)),
+ 0
+ );
+ const hasOrders = orders.length > 0 && orderQuantity > 0;
+ return (
+ <div className="flex justify-end">
+ <Button
+ variant="secondary"
+ leftIcon={hasOrders ? undefined : <LuCircleCheck />}
+ isDisabled={isDisabled}
+ onClick={() => {
+ setSelectedItem(row.original);
+ }}
+ >
+ {hasOrders ? (
+ <HStack>
+ <PulsingDot />
+ <span>Order {orderQuantity}</span>
+ </HStack>
+ ) : (
+ "Order"
+ )}
+ </Button>
+ </div>
+ );
+ },
+ },
+ ];
+ }, [
+ periods,
+ dateFormatter,
+ numberFormatter,
+ unitOfMeasures,
+ isDisabled,
+ ordersMap,
+ ]);
+
+ const renderActions = useCallback(
+ (selectedRows: typeof data) => {
+ return (
+ <DropdownMenuContent align="end" className="min-w-[200px]">
+ <DropdownMenuLabel>Update</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+
+ <DropdownMenuItem
+ onSelect={() => onBulkUpdate(selectedRows, "order")}
+ disabled={bulkUpdateFetcher.state !== "idle"}
+ >
+ <DropdownMenuIcon icon={<LuSquareChartGantt />} />
+ Order Parts
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ );
+ },
+ [bulkUpdateFetcher.state, onBulkUpdate]
+ );
+
+ const defaultColumnVisibility = {
+ active: false,
+ type: false,
+ };
+
+ const defaultColumnPinning = {
+ left: ["readableIdWithRevision"],
+ right: ["Order"],
+ };
+
+ return (
+ <>
+ <Table<PurchasingPlanningItem>
+ count={count}
+ columns={columns}
+ data={data}
+ defaultColumnVisibility={defaultColumnVisibility}
+ defaultColumnPinning={defaultColumnPinning}
+ primaryAction={
+ <div className="flex items-center gap-2">
+ <Combobox
+ asButton
+ size="sm"
+ value={locationId}
+ options={locations}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = getLocationPath(selected);
+ }}
+ />
+ <mrpFetcher.Form
+ method="post"
+ action={path.to.api.mrp(locationId)}
+ >
+ <Tooltip>
+ <TooltipTrigger>
+ <Button
+ type="submit"
+ variant="secondary"
+ rightIcon={<LuCirclePlay />}
+ isDisabled={mrpFetcher.state !== "idle"}
+ isLoading={mrpFetcher.state !== "idle"}
+ >
+ Recalculate
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ MRP runs automatically every 3 hours, but you can run it
+ manually here.
+ </TooltipContent>
+ </Tooltip>
+ </mrpFetcher.Form>
+ </div>
+ }
+ renderActions={renderActions}
+ title="Planning"
+ table="planning"
+ withSavedView
+ withSelectableRows
+ />
+
+ {selectedItem && (
+ <OrderDrawer
+ locationId={locationId}
+ row={selectedItem}
+ orders={selectedItem.id ? ordersMap[selectedItem.id] || [] : []}
+ setOrders={setOrders}
+ periods={periods}
+ isOpen={!!selectedItem}
+ onClose={() => setSelectedItem(null)}
+ />
+ )}
+ </>
+ );
+ }
+);
+
+PlanningTable.displayName = "PlanningTable";
+
+export default PlanningTable;
+
+function getLocationPath(locationId: string) {
+ return `${path.to.productionPlanning}?location=${locationId}`;
+}
diff --git a/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx b/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
index 9415226562..9fac453b1d 100644
--- a/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
+++ b/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
@@ -4,6 +4,7 @@ import {
LuLayoutList,
LuPackageSearch,
LuShapes,
+ LuSquareChartGantt,
LuStar,
} from "react-icons/lu";
import { usePermissions } from "~/hooks";
@@ -42,6 +43,17 @@ const purchasingRoutes: AuthenticatedRouteGroup[] = [
},
],
},
+ {
+ name: "Plan",
+ routes: [
+ {
+ name: "Planning",
+ to: path.to.purchasingPlanning,
+ icon: <LuSquareChartGantt />,
+ table: "purchase-planning",
+ },
+ ],
+ },
{
name: "Configure",
routes: [
diff --git a/apps/erp/app/routes/x+/job+/bulk.new.tsx b/apps/erp/app/routes/x+/job+/bulk.new.tsx
index bf4863fea8..02973ecedc 100644
--- a/apps/erp/app/routes/x+/job+/bulk.new.tsx
+++ b/apps/erp/app/routes/x+/job+/bulk.new.tsx
@@ -118,7 +118,9 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
let jobId = nextSequence.data;
- const dueDate = dueDateDistribution[i] || dueDateOfFirstJob;
+ const dueDate = (dueDateDistribution[i] || dueDateOfFirstJob)?.split(
+ "T"
+ )[0];
const createJob = await upsertJob(serviceRole, {
jobId,
diff --git a/apps/erp/app/routes/x+/production+/planning.tsx b/apps/erp/app/routes/x+/production+/planning.tsx
index 6f3de81b80..3fd56ae8d3 100644
--- a/apps/erp/app/routes/x+/production+/planning.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.tsx
@@ -8,7 +8,7 @@ import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import type { ProductionPlanningItem } from "~/modules/production";
import { getProductionPlanning } from "~/modules/production";
-import PlanningTable from "~/modules/production/ui/Planning/PlanningTable";
+import ProductionPlanningTable from "~/modules/production/ui/Planning/ProductionPlanningTable";
import { getLocationsList } from "~/modules/resources";
import { getPeriods } from "~/modules/shared/shared.service";
import { getUserDefaults } from "~/modules/users/users.server";
@@ -42,7 +42,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const userDefaults = await getUserDefaults(client, userId, companyId);
if (userDefaults.error) {
throw redirect(
- path.to.inventory,
+ path.to.production,
await flash(
request,
error(userDefaults.error, "Failed to load default location")
@@ -123,7 +123,7 @@ export default function ProductionPlanningRoute() {
minSize={25}
className="bg-background"
>
- <PlanningTable
+ <ProductionPlanningTable
data={items}
count={items.length}
locationId={locationId}
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.tsx b/apps/erp/app/routes/x+/purchasing+/planning.tsx
new file mode 100644
index 0000000000..d086d8cfeb
--- /dev/null
+++ b/apps/erp/app/routes/x+/purchasing+/planning.tsx
@@ -0,0 +1,137 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { ResizablePanel, ResizablePanelGroup, VStack } from "@carbon/react";
+import { getLocalTimeZone, startOfWeek, today } from "@internationalized/date";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import type { PurchasingPlanningItem } from "~/modules/purchasing";
+import { getPurchasingPlanning } from "~/modules/purchasing";
+import PurchasingPlanningTable from "~/modules/purchasing/ui/Planning/PurchasingPlanningTable";
+import { getLocationsList } from "~/modules/resources";
+import { getPeriods } from "~/modules/shared/shared.service";
+import { getUserDefaults } from "~/modules/users/users.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+const WEEKS_TO_PLAN = 12 * 4;
+
+export const handle: Handle = {
+ breadcrumb: "Planning",
+ to: path.to.purchasingPlanning,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "purchasing",
+ bypassRls: true,
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.inventory,
+ 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.purchasing,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ const startDate = startOfWeek(today(getLocalTimeZone()), "en-US");
+ const endDate = startDate.add({ weeks: WEEKS_TO_PLAN });
+ const periods = await getPeriods(client, {
+ startDate: startDate.toString(),
+ endDate: endDate.toString(),
+ });
+
+ if (periods.error) {
+ redirect(
+ path.to.authenticatedRoot,
+ await flash(request, error(periods.error, "Failed to load periods"))
+ );
+ }
+
+ const [items] = await Promise.all([
+ getPurchasingPlanning(
+ client,
+ locationId,
+ companyId,
+ periods.data?.map((p) => p.id) ?? [],
+ {
+ search,
+ limit,
+ offset,
+ sorts,
+ filters,
+ }
+ ),
+ ]);
+
+ if (items.error) {
+ redirect(
+ path.to.purchasing,
+ await flash(request, error(items.error, "Failed to fetch planning items"))
+ );
+ }
+
+ return json({
+ items: (items.data ?? []) as PurchasingPlanningItem[],
+ periods: periods.data ?? [],
+ locationId,
+ });
+}
+
+export default function PurchasingPlanningRoute() {
+ const { items, locationId, periods } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full ">
+ <ResizablePanelGroup direction="horizontal">
+ <ResizablePanel
+ defaultSize={50}
+ maxSize={70}
+ minSize={25}
+ className="bg-background"
+ >
+ <PurchasingPlanningTable
+ data={items}
+ count={items.length}
+ locationId={locationId}
+ periods={periods}
+ />
+ </ResizablePanel>
+ <Outlet />
+ </ResizablePanelGroup>
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
new file mode 100644
index 0000000000..2cdb184a8a
--- /dev/null
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -0,0 +1,279 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { z } from "zod";
+import { orderValidator } from "~/modules/items/items.models";
+import {
+ recalculateJobRequirements,
+ runMRP,
+ upsertJob,
+ upsertJobMethod,
+} from "~/modules/production";
+import { getNextSequence } from "~/modules/settings/settings.service";
+
+export const config = {
+ maxDuration: 300,
+};
+
+const itemsValidator = z
+ .object({
+ id: z.string(),
+ orders: z.array(orderValidator),
+ })
+ .array();
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production",
+ role: "employee",
+ bypassRls: true,
+ });
+
+ const { items, action, locationId } = await request.json();
+ if (typeof locationId !== "string") {
+ return json({ success: false, message: "Location is required" });
+ }
+
+ if (typeof action !== "string") {
+ return json({ success: false, message: "Invalid form data" });
+ }
+
+ switch (action) {
+ case "order":
+ const parsedItems = itemsValidator.safeParse(items);
+
+ if (!parsedItems.success) {
+ return json({ success: false, message: "Invalid form data" });
+ }
+
+ const itemsToOrder = parsedItems.data;
+ if (itemsToOrder.length === 0) {
+ return json({ success: false, message: "No items to order" });
+ }
+
+ try {
+ const allJobIds: string[] = [];
+ const allSupplyForecasts: Array<{
+ itemId: string;
+ locationId: string;
+ sourceType: "Production Order";
+ forecastQuantity: number;
+ periodId: string;
+ companyId: string;
+ createdBy: string;
+ updatedBy: string;
+ }> = [];
+
+ for (const item of itemsToOrder) {
+ const orders = item.orders;
+ const jobIds: string[] = [];
+ const supplyForecastByPeriod: Record<string, number> = {};
+
+ // Get manufacturing data for this item
+ const manufacturing = await client
+ .from("itemReplenishment")
+ .select(
+ "manufacturingBlocked, scrapPercentage, requiresConfiguration"
+ )
+ .eq("itemId", item.id)
+ .single();
+
+ if (manufacturing.error) {
+ console.error(
+ `Failed to get manufacturing data for item ${item.id}:`,
+ manufacturing.error
+ );
+ continue;
+ }
+
+ if (manufacturing.data?.manufacturingBlocked) {
+ console.warn(`Manufacturing is blocked for item ${item.id}`);
+ continue;
+ }
+
+ if (manufacturing.data?.requiresConfiguration) {
+ console.warn(
+ `Manufacturing requires configuration for item ${item.id}`
+ );
+ continue;
+ }
+
+ // Process each order for this item
+ for (const order of orders) {
+ if (!order.existingId) {
+ // Create new job
+ const nextSequence = await getNextSequence(
+ client,
+ "job",
+ companyId
+ );
+ if (nextSequence.error) {
+ console.error(
+ `Failed to get next sequence for item ${item.id}:`,
+ nextSequence.error
+ );
+ continue;
+ }
+
+ const jobId = nextSequence.data;
+ if (!jobId) {
+ console.error(`Failed to get job ID for item ${item.id}`);
+ continue;
+ }
+
+ const createJob = await upsertJob(
+ client,
+ {
+ itemId: item.id,
+ jobId,
+ quantity: order.quantity,
+ scrapQuantity: Math.ceil(
+ order.quantity * (manufacturing.data?.scrapPercentage ?? 0)
+ ),
+ startDate: order.startDate ?? undefined,
+ dueDate: order.dueDate ?? undefined,
+ deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",
+ locationId,
+ companyId,
+ createdBy: userId,
+ unitOfMeasureCode: "EA",
+ },
+ "Planned"
+ );
+
+ if (createJob.error) {
+ console.error(
+ `Failed to create job for item ${item.id}:`,
+ createJob.error
+ );
+ continue;
+ }
+
+ const id = createJob.data?.id;
+ if (!id) {
+ console.error(
+ `Failed to get created job ID for item ${item.id}`
+ );
+ continue;
+ }
+
+ const upsertMethod = await upsertJobMethod(client, "itemToJob", {
+ sourceId: item.id,
+ targetId: id,
+ companyId,
+ userId,
+ });
+
+ if (upsertMethod.error) {
+ console.error(
+ `Failed to create job method for item ${item.id}:`,
+ upsertMethod.error
+ );
+ continue;
+ }
+
+ jobIds.push(id);
+ } else {
+ // Update existing job
+ jobIds.push(order.existingId);
+ const updateJob = await client
+ .from("job")
+ .update({
+ dueDate: order.dueDate ?? undefined,
+ deadlineType: order.isASAP ? "ASAP" : "Soft Deadline",
+ quantity: order.quantity,
+ scrapQuantity: Math.ceil(
+ order.quantity * (manufacturing.data?.scrapPercentage ?? 0)
+ ),
+ startDate: order.startDate ?? undefined,
+ status: "Planned",
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ .eq("id", order.existingId);
+
+ if (updateJob.error) {
+ console.error(
+ `Failed to update job ${order.existingId}:`,
+ updateJob.error
+ );
+ continue;
+ }
+ }
+
+ // Track supply forecast by period
+ const periodId = order.periodId;
+ supplyForecastByPeriod[periodId] =
+ (supplyForecastByPeriod[periodId] || 0) +
+ (order.quantity - (order.existingQuantity ?? 0));
+ }
+
+ // Add job IDs to the overall list
+ allJobIds.push(...jobIds);
+
+ // Add supply forecasts for this item
+ Object.entries(supplyForecastByPeriod).forEach(
+ ([periodId, quantity]) => {
+ allSupplyForecasts.push({
+ itemId: item.id,
+ locationId,
+ sourceType: "Production Order" as const,
+ forecastQuantity: quantity,
+ periodId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId,
+ });
+ }
+ );
+ }
+
+ // Insert all supply forecasts
+ if (allSupplyForecasts.length > 0) {
+ const insertForecasts = await client
+ .from("supplyForecast")
+ .insert(allSupplyForecasts);
+
+ if (insertForecasts.error) {
+ console.error(
+ "Failed to insert supply forecasts:",
+ insertForecasts.error
+ );
+ }
+ }
+
+ // Trigger recalculation for all jobs
+ if (allJobIds.length > 0) {
+ for (const jobId of allJobIds) {
+ await recalculateJobRequirements(client, {
+ id: jobId,
+ companyId,
+ userId,
+ });
+ }
+
+ await runMRP(client, {
+ type: "company",
+ id: companyId,
+ companyId,
+ userId,
+ });
+ }
+
+ return json({
+ success: true,
+ message: `Successfully processed ${itemsToOrder.length} items with ${allJobIds.length} jobs`,
+ });
+ } catch (error) {
+ console.error("Error processing production orders:", error);
+ return json({
+ success: false,
+ message: `Error processing production orders: ${
+ error instanceof Error ? error.message : "Unknown error"
+ }`,
+ });
+ }
+
+ default:
+ return json({ success: false, message: "Invalid field" });
+ }
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 99f6e0059a..62b086010c 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -319,6 +319,7 @@ export const path = {
bulkEditPermissions: `${x}/users/bulk-edit-permissions`,
bulkUpdateItems: `${x}/items/update`,
bulkUpdateProductionPlanning: `${x}/production/planning/update`,
+ bulkUpdatePurchasingPlanning: `${x}/purchasing/planning/update`,
bulkUpdateProcedure: `${x}/procedure/update`,
bulkUpdateJob: `${x}/job/update`,
bulkUpdateNonConformance: `${x}/non-conformance/update`,
@@ -1014,6 +1015,7 @@ export const path = {
generatePath(`${x}/purchase-order/${id}/status`),
purchaseOrders: `${x}/purchasing/orders`,
purchasing: `${x}/purchasing`,
+ purchasingPlanning: `${x}/purchasing/planning`,
purchasingSettings: `${x}/settings/purchasing`,
quality: `${x}/quality/non-conformances`,
quote: (id: string) => generatePath(`${x}/quote/${id}`),
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 2c7c0e3e32..06b84b20fe 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -38100,14 +38100,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"]
@@ -45203,6 +45203,89 @@ export type Database = {
week52: number
}[]
}
+ get_purchasing_planning: {
+ Args: {
+ company_id: string
+ location_id: string
+ periods: string[]
+ }
+ Returns: {
+ id: string
+ readableIdWithRevision: string
+ name: string
+ active: boolean
+ type: Database["public"]["Enums"]["itemType"]
+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
+ thumbnailPath: string
+ unitOfMeasureCode: string
+ leadTime: number
+ purchasingBlocked: boolean
+ lotSize: number
+ reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]
+ demandAccumulationPeriod: number
+ demandAccumulationSafetyStock: number
+ reorderPoint: number
+ reorderQuantity: number
+ minimumOrderQuantity: number
+ maximumOrderQuantity: number
+ orderMultiple: number
+ quantityOnHand: number
+ maximumInventoryQuantity: number
+ week1: number
+ week2: number
+ week3: number
+ week4: number
+ week5: number
+ week6: number
+ week7: number
+ week8: number
+ week9: number
+ week10: number
+ week11: number
+ week12: number
+ week13: number
+ week14: number
+ week15: number
+ week16: number
+ week17: number
+ week18: number
+ week19: number
+ week20: number
+ week21: number
+ week22: number
+ week23: number
+ week24: number
+ week25: number
+ week26: number
+ week27: number
+ week28: number
+ week29: number
+ week30: number
+ week31: number
+ week32: number
+ week33: number
+ week34: number
+ week35: number
+ week36: number
+ week37: number
+ week38: number
+ week39: number
+ week40: number
+ week41: number
+ week42: number
+ week43: number
+ week44: number
+ week45: number
+ week46: number
+ week47: number
+ week48: number
+ week49: number
+ week50: number
+ week51: number
+ week52: number
+ }[]
+ }
get_quote_methods: {
Args: {
qid: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 2c7c0e3e32..06b84b20fe 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -38100,14 +38100,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"]
@@ -45203,6 +45203,89 @@ export type Database = {
week52: number
}[]
}
+ get_purchasing_planning: {
+ Args: {
+ company_id: string
+ location_id: string
+ periods: string[]
+ }
+ Returns: {
+ id: string
+ readableIdWithRevision: string
+ name: string
+ active: boolean
+ type: Database["public"]["Enums"]["itemType"]
+ itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
+ replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
+ thumbnailPath: string
+ unitOfMeasureCode: string
+ leadTime: number
+ purchasingBlocked: boolean
+ lotSize: number
+ reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]
+ demandAccumulationPeriod: number
+ demandAccumulationSafetyStock: number
+ reorderPoint: number
+ reorderQuantity: number
+ minimumOrderQuantity: number
+ maximumOrderQuantity: number
+ orderMultiple: number
+ quantityOnHand: number
+ maximumInventoryQuantity: number
+ week1: number
+ week2: number
+ week3: number
+ week4: number
+ week5: number
+ week6: number
+ week7: number
+ week8: number
+ week9: number
+ week10: number
+ week11: number
+ week12: number
+ week13: number
+ week14: number
+ week15: number
+ week16: number
+ week17: number
+ week18: number
+ week19: number
+ week20: number
+ week21: number
+ week22: number
+ week23: number
+ week24: number
+ week25: number
+ week26: number
+ week27: number
+ week28: number
+ week29: number
+ week30: number
+ week31: number
+ week32: number
+ week33: number
+ week34: number
+ week35: number
+ week36: number
+ week37: number
+ week38: number
+ week39: number
+ week40: number
+ week41: number
+ week42: number
+ week43: number
+ week44: number
+ week45: number
+ week46: number
+ week47: number
+ week48: number
+ week49: number
+ week50: number
+ week51: number
+ week52: number
+ }[]
+ }
get_quote_methods: {
Args: {
qid: string
diff --git a/packages/database/supabase/migrations/20250623010514_purchasing-planning.sql b/packages/database/supabase/migrations/20250623010514_purchasing-planning.sql
new file mode 100644
index 0000000000..a394dc75a0
--- /dev/null
+++ b/packages/database/supabase/migrations/20250623010514_purchasing-planning.sql
@@ -0,0 +1,320 @@
+DROP FUNCTION IF EXISTS get_purchasing_planning;
+CREATE OR REPLACE FUNCTION get_purchasing_planning(company_id TEXT, location_id TEXT, periods TEXT[])
+ RETURNS TABLE (
+ "id" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "active" BOOLEAN,
+ "type" "itemType",
+ "itemTrackingType" "itemTrackingType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "leadTime" INTEGER,
+ "purchasingBlocked" BOOLEAN,
+ "lotSize" INTEGER,
+ "reorderingPolicy" "itemReorderingPolicy",
+ "demandAccumulationPeriod" INTEGER,
+ "demandAccumulationSafetyStock" NUMERIC,
+ "reorderPoint" INTEGER,
+ "reorderQuantity" INTEGER,
+ "minimumOrderQuantity" INTEGER,
+ "maximumOrderQuantity" INTEGER,
+ "orderMultiple" INTEGER,
+ "quantityOnHand" NUMERIC,
+ "maximumInventoryQuantity" NUMERIC,
+ "week1" NUMERIC,
+ "week2" NUMERIC,
+ "week3" NUMERIC,
+ "week4" NUMERIC,
+ "week5" NUMERIC,
+ "week6" NUMERIC,
+ "week7" NUMERIC,
+ "week8" NUMERIC,
+ "week9" NUMERIC,
+ "week10" NUMERIC,
+ "week11" NUMERIC,
+ "week12" NUMERIC,
+ "week13" NUMERIC,
+ "week14" NUMERIC,
+ "week15" NUMERIC,
+ "week16" NUMERIC,
+ "week17" NUMERIC,
+ "week18" NUMERIC,
+ "week19" NUMERIC,
+ "week20" NUMERIC,
+ "week21" NUMERIC,
+ "week22" NUMERIC,
+ "week23" NUMERIC,
+ "week24" NUMERIC,
+ "week25" NUMERIC,
+ "week26" NUMERIC,
+ "week27" NUMERIC,
+ "week28" NUMERIC,
+ "week29" NUMERIC,
+ "week30" NUMERIC,
+ "week31" NUMERIC,
+ "week32" NUMERIC,
+ "week33" NUMERIC,
+ "week34" NUMERIC,
+ "week35" NUMERIC,
+ "week36" NUMERIC,
+ "week37" NUMERIC,
+ "week38" NUMERIC,
+ "week39" NUMERIC,
+ "week40" NUMERIC,
+ "week41" NUMERIC,
+ "week42" NUMERIC,
+ "week43" NUMERIC,
+ "week44" NUMERIC,
+ "week45" NUMERIC,
+ "week46" NUMERIC,
+ "week47" NUMERIC,
+ "week48" NUMERIC,
+ "week49" NUMERIC,
+ "week50" NUMERIC,
+ "week51" NUMERIC,
+ "week52" NUMERIC
+ ) AS $$
+ WITH RECURSIVE
+ -- Pre-aggregate supply and demand data
+ supply_data AS (
+ SELECT
+ "itemId",
+ "periodId",
+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "supply"
+ FROM (
+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"
+ FROM "supplyActual"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "supplyForecast"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ ) combined
+ GROUP BY "itemId", "periodId"
+ ),
+ demand_data AS (
+ SELECT
+ "itemId",
+ "periodId",
+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "demand"
+ FROM (
+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"
+ FROM "demandActual"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "demandForecast"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ ) combined
+ GROUP BY "itemId", "periodId"
+ ),
+ -- Base data for items with early filtering
+ base_items AS (
+ SELECT DISTINCT ON (i."id")
+ i."id",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."purchasingBlocked",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."orderMultiple",
+ ip."maximumInventoryQuantity",
+ COALESCE((
+ SELECT SUM("quantity")
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "itemId" = i."id"
+ ), 0) AS "quantityOnHand"
+ FROM "item" i
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId"
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+ WHERE i."companyId" = company_id
+ AND 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 joins
+ projections AS (
+ -- Base case: first period
+ SELECT
+ bi.*,
+ periods[1] as "periodId",
+ bi."quantityOnHand" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",
+ 1 as period_index
+ FROM base_items bi
+ LEFT JOIN supply_data s ON bi."id" = s."itemId" AND s."periodId" = periods[1]
+ LEFT JOIN demand_data d ON bi."id" = d."itemId" AND d."periodId" = periods[1]
+
+ UNION ALL
+
+ -- Recursive case: subsequent periods
+ SELECT
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ 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",
+ p.period_index + 1 as period_index
+ FROM projections p
+ LEFT JOIN supply_data s ON p."id" = s."itemId" AND s."periodId" = periods[p.period_index + 1]
+ LEFT JOIN demand_data d ON p."id" = d."itemId" AND d."periodId" = periods[p.period_index + 1]
+ WHERE p.period_index < array_length(periods, 1)
+ )
+ -- Final result with optimized pivot
+ SELECT DISTINCT ON (p."id")
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ 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",
+ MAX(CASE WHEN p."periodId" = periods[4] THEN p."projection" END) AS "week4",
+ MAX(CASE WHEN p."periodId" = periods[5] THEN p."projection" END) AS "week5",
+ MAX(CASE WHEN p."periodId" = periods[6] THEN p."projection" END) AS "week6",
+ MAX(CASE WHEN p."periodId" = periods[7] THEN p."projection" END) AS "week7",
+ MAX(CASE WHEN p."periodId" = periods[8] THEN p."projection" END) AS "week8",
+ MAX(CASE WHEN p."periodId" = periods[9] THEN p."projection" END) AS "week9",
+ MAX(CASE WHEN p."periodId" = periods[10] THEN p."projection" END) AS "week10",
+ MAX(CASE WHEN p."periodId" = periods[11] THEN p."projection" END) AS "week11",
+ MAX(CASE WHEN p."periodId" = periods[12] THEN p."projection" END) AS "week12",
+ MAX(CASE WHEN p."periodId" = periods[13] THEN p."projection" END) AS "week13",
+ MAX(CASE WHEN p."periodId" = periods[14] THEN p."projection" END) AS "week14",
+ MAX(CASE WHEN p."periodId" = periods[15] THEN p."projection" END) AS "week15",
+ MAX(CASE WHEN p."periodId" = periods[16] THEN p."projection" END) AS "week16",
+ MAX(CASE WHEN p."periodId" = periods[17] THEN p."projection" END) AS "week17",
+ MAX(CASE WHEN p."periodId" = periods[18] THEN p."projection" END) AS "week18",
+ MAX(CASE WHEN p."periodId" = periods[19] THEN p."projection" END) AS "week19",
+ MAX(CASE WHEN p."periodId" = periods[20] THEN p."projection" END) AS "week20",
+ MAX(CASE WHEN p."periodId" = periods[21] THEN p."projection" END) AS "week21",
+ MAX(CASE WHEN p."periodId" = periods[22] THEN p."projection" END) AS "week22",
+ MAX(CASE WHEN p."periodId" = periods[23] THEN p."projection" END) AS "week23",
+ MAX(CASE WHEN p."periodId" = periods[24] THEN p."projection" END) AS "week24",
+ MAX(CASE WHEN p."periodId" = periods[25] THEN p."projection" END) AS "week25",
+ MAX(CASE WHEN p."periodId" = periods[26] THEN p."projection" END) AS "week26",
+ MAX(CASE WHEN p."periodId" = periods[27] THEN p."projection" END) AS "week27",
+ MAX(CASE WHEN p."periodId" = periods[28] THEN p."projection" END) AS "week28",
+ MAX(CASE WHEN p."periodId" = periods[29] THEN p."projection" END) AS "week29",
+ MAX(CASE WHEN p."periodId" = periods[30] THEN p."projection" END) AS "week30",
+ MAX(CASE WHEN p."periodId" = periods[31] THEN p."projection" END) AS "week31",
+ MAX(CASE WHEN p."periodId" = periods[32] THEN p."projection" END) AS "week32",
+ MAX(CASE WHEN p."periodId" = periods[33] THEN p."projection" END) AS "week33",
+ MAX(CASE WHEN p."periodId" = periods[34] THEN p."projection" END) AS "week34",
+ MAX(CASE WHEN p."periodId" = periods[35] THEN p."projection" END) AS "week35",
+ MAX(CASE WHEN p."periodId" = periods[36] THEN p."projection" END) AS "week36",
+ MAX(CASE WHEN p."periodId" = periods[37] THEN p."projection" END) AS "week37",
+ MAX(CASE WHEN p."periodId" = periods[38] THEN p."projection" END) AS "week38",
+ MAX(CASE WHEN p."periodId" = periods[39] THEN p."projection" END) AS "week39",
+ MAX(CASE WHEN p."periodId" = periods[40] THEN p."projection" END) AS "week40",
+ MAX(CASE WHEN p."periodId" = periods[41] THEN p."projection" END) AS "week41",
+ MAX(CASE WHEN p."periodId" = periods[42] THEN p."projection" END) AS "week42",
+ MAX(CASE WHEN p."periodId" = periods[43] THEN p."projection" END) AS "week43",
+ MAX(CASE WHEN p."periodId" = periods[44] THEN p."projection" END) AS "week44",
+ MAX(CASE WHEN p."periodId" = periods[45] THEN p."projection" END) AS "week45",
+ MAX(CASE WHEN p."periodId" = periods[46] THEN p."projection" END) AS "week46",
+ MAX(CASE WHEN p."periodId" = periods[47] THEN p."projection" END) AS "week47",
+ MAX(CASE WHEN p."periodId" = periods[48] THEN p."projection" END) AS "week48",
+ MAX(CASE WHEN p."periodId" = periods[49] THEN p."projection" END) AS "week49",
+ MAX(CASE WHEN p."periodId" = periods[50] THEN p."projection" END) AS "week50",
+ MAX(CASE WHEN p."periodId" = periods[51] THEN p."projection" END) AS "week51",
+ MAX(CASE WHEN p."periodId" = periods[52] THEN p."projection" END) AS "week52"
+ FROM projections p
+ GROUP BY
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand",
+ p."maximumInventoryQuantity";
+$$ LANGUAGE sql SECURITY DEFINER;
\ No newline at end of file