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.

refactor: improve performance of plannign tables

Brad Barbin4a81f55f88f3
diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
index b124556744..f70a0c96cc 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
@@ -77,6 +77,33 @@ type BaseOrderParams = {
periods: { startDate: string; id: string }[];
};
+// Cache for memoizing calculateOrders results
+const ordersCache = new Map<
+ string,
+ {
+ startDate: string;
+ dueDate: string;
+ quantity: number;
+ periodId: string;
+ isASAP: boolean;
+ }[]
+>();
+
+// Generate cache key from itemPlanning and periods
+function getCacheKey(
+ itemPlanning: ProductionPlanningItem | PurchasingPlanningItem,
+ periods: { startDate: string; id: string }[]
+): string {
+ // Include all relevant properties that affect order calculation
+ const periodIds = periods.map((p) => p.id).join(",");
+ const weekValues = Array.from({ length: 48 }, (_, i) => {
+ const key = `week${i + 1}` as keyof typeof itemPlanning;
+ return itemPlanning[key] ?? 0;
+ }).join(",");
+
+ return `${itemPlanning.id}_${itemPlanning.reorderingPolicy}_${itemPlanning.reorderPoint}_${itemPlanning.reorderQuantity}_${itemPlanning.maximumInventoryQuantity}_${itemPlanning.demandAccumulationPeriod}_${itemPlanning.demandAccumulationSafetyStock}_${itemPlanning.leadTime}_${itemPlanning.lotSize}_${itemPlanning.minimumOrderQuantity}_${itemPlanning.maximumOrderQuantity}_${itemPlanning.orderMultiple}_${periodIds}_${weekValues}`;
+}
+
function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
startDate: string;
dueDate: string;
@@ -84,8 +111,22 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
periodId: string;
isASAP: boolean;
}[] {
+ // Check cache first
+ const cacheKey = getCacheKey(itemPlanning, periods);
+ const cached = ordersCache.get(cacheKey);
+ if (cached) {
+ return cached;
+ }
if (itemPlanning.reorderingPolicy === "Manual Reorder") {
- return [];
+ const emptyOrders: {
+ startDate: string;
+ dueDate: string;
+ quantity: number;
+ periodId: string;
+ isASAP: boolean;
+ }[] = [];
+ ordersCache.set(cacheKey, emptyOrders);
+ return emptyOrders;
}
const orders: {
@@ -203,6 +244,7 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
}
}
+ ordersCache.set(cacheKey, orders);
return orders;
case "Fixed Reorder Quantity":
for (let i = 0; i < periods.length; i++) {
@@ -236,6 +278,7 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
}
}
+ ordersCache.set(cacheKey, orders);
return orders;
case "Maximum Quantity":
for (let i = 0; i < periods.length; i++) {
@@ -298,12 +341,19 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
reorderPoint - (projectedQuantity + orderedQuantity);
}
}
+ ordersCache.set(cacheKey, orders);
return orders;
default:
+ ordersCache.set(cacheKey, orders);
return orders;
}
}
+// Export function to clear the cache if needed (e.g., after MRP runs)
+export function clearOrdersCache() {
+ ordersCache.clear();
+}
+
export function getProductionOrdersFromPlanning(
itemPlanning: ProductionPlanningItem,
periods: { startDate: string; id: string }[]
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
index 063bb43930..ba0ac22cb7 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
@@ -35,6 +35,7 @@ import { usePermissions } from "~/hooks";
import { itemTypes } from "~/modules/inventory/inventory.models";
import { itemReorderingPolicies } from "~/modules/items/items.models";
import {
+ clearOrdersCache,
getProductionOrdersFromPlanning,
getReorderPolicyDescription,
ItemReorderPolicy,
@@ -69,6 +70,19 @@ const ProductionPlanningTable = memo(
const mrpFetcher = useFetcher<typeof mrpAction>();
const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();
+ // Clear cache when MRP completes
+ useEffect(() => {
+ if (mrpFetcher.state === "idle" && mrpFetcher.data) {
+ clearOrdersCache();
+ setOrdersMap({}); // Reset local state to force recalculation
+ }
+ }, [mrpFetcher.state, mrpFetcher.data]);
+
+ // Clear local state when data changes (e.g., filters, search)
+ useEffect(() => {
+ setOrdersMap({});
+ }, [data]);
+
useEffect(() => {
if (
bulkUpdateFetcher.data?.success === false &&
@@ -88,32 +102,10 @@ const ProductionPlanningTable = memo(
bulkUpdateFetcher.state !== "idle" ||
mrpFetcher.state !== "idle";
- const getOrders = useCallback(() => {
- const initialMap: Record<string, ProductionOrder[]> = {};
- data.forEach((item) => {
- if (item.id) {
- initialMap[item.id] = getProductionOrdersFromPlanning(item, periods);
- }
- });
- return initialMap;
- }, [data, periods]);
-
- // Store orders in a map keyed by item id
+ // Store orders in a map keyed by item id - calculate on-demand instead of eagerly
const [ordersMap, setOrdersMap] = useState<
Record<string, ProductionOrder[]>
- >(() => {
- const initialMap: Record<string, ProductionOrder[]> = {};
- data.forEach((item) => {
- if (item.id) {
- initialMap[item.id] = getProductionOrdersFromPlanning(item, periods);
- }
- });
- return initialMap;
- });
-
- useEffect(() => {
- setOrdersMap(getOrders());
- }, [getOrders]);
+ >({});
const onBulkUpdate = useCallback(
(selectedRows: typeof data, action: "order") => {
@@ -183,6 +175,15 @@ const ProductionPlanningTable = memo(
);
const columns = useMemo<ColumnDef<ProductionPlanningItem>[]>(() => {
+ // Helper to get orders with on-demand calculation
+ const getOrdersForItem = (itemId: string): ProductionOrder[] => {
+ if (ordersMap[itemId]) {
+ return ordersMap[itemId];
+ }
+ const item = data.find((i) => i.id === itemId);
+ if (!item) return [];
+ return getProductionOrdersFromPlanning(item, periods);
+ };
const periodColumns: ColumnDef<ProductionPlanningItem>[] = periods.map(
(period, index) => {
const isCurrentWeek = index === 0;
@@ -337,7 +338,7 @@ const ProductionPlanningTable = memo(
header: "",
cell: ({ row }) => {
const orders = row.original.id
- ? ordersMap[row.original.id] || []
+ ? getOrdersForItem(row.original.id)
: [];
const orderQuantity = orders.reduce(
(acc, order) =>
@@ -372,13 +373,15 @@ const ProductionPlanningTable = memo(
},
},
];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [
periods,
dateFormatter,
numberFormatter,
unitOfMeasures,
isDisabled,
- ordersMap,
+ // Note: ordersMap is intentionally not in deps to avoid column regeneration
+ // getOrdersForItem inside the cell will access the latest ordersMap via closure
]);
const renderActions = useCallback(
@@ -466,7 +469,12 @@ const ProductionPlanningTable = memo(
<ProductionPlanningOrderDrawer
locationId={locationId}
row={selectedItem}
- orders={selectedItem.id ? ordersMap[selectedItem.id] || [] : []}
+ orders={
+ selectedItem.id
+ ? ordersMap[selectedItem.id] ||
+ getProductionOrdersFromPlanning(selectedItem, periods)
+ : []
+ }
setOrders={setOrders}
periods={periods}
isOpen={!!selectedItem}
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
index 9a41018dcc..31fbf77f30 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -43,6 +43,7 @@ import { itemTypes } from "~/modules/inventory/inventory.models";
import { itemReorderingPolicies } from "~/modules/items/items.models";
import type { SupplierPart } from "~/modules/items/types";
import {
+ clearOrdersCache,
getPurchaseOrdersFromPlanning,
getReorderPolicyDescription,
ItemReorderPolicy,
@@ -110,27 +111,22 @@ const PlanningTable = memo(
const [items] = useItems();
- const getOrders = useCallback(() => {
- const initialMap: Record<string, PlannedOrder[]> = {};
- data.forEach((item) => {
- if (item.id) {
- initialMap[item.id] = getPurchaseOrdersFromPlanning(
- item,
- periods,
- items,
- suppliersMap[item.id]
- );
- }
- });
- return initialMap;
- }, [data, periods, suppliersMap, items]);
+ // Store orders in a map keyed by item id - calculate on-demand instead of eagerly
+ const [ordersMap, setOrdersMap] = useState<Record<string, PlannedOrder[]>>(
+ {}
+ );
- const [ordersMap, setOrdersMap] =
- useState<Record<string, PlannedOrder[]>>(getOrders);
+ // Clear cache when MRP completes
+ useEffect(() => {
+ if (mrpFetcher.state === "idle" && mrpFetcher.data) {
+ clearOrdersCache();
+ setOrdersMap({}); // Reset local state to force recalculation
+ }
+ }, [mrpFetcher.state, mrpFetcher.data]);
+ // Clear local state when data changes (e.g., filters, search)
useEffect(() => {
- setOrdersMap(getOrders());
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ setOrdersMap({});
}, [data]);
const onBulkUpdate = useCallback(
@@ -199,6 +195,21 @@ const PlanningTable = memo(
);
const columns = useMemo<ColumnDef<PurchasingPlanningItem>[]>(() => {
+ // Helper to get orders with on-demand calculation
+ const getOrdersForItem = (itemId: string): PlannedOrder[] => {
+ if (ordersMap[itemId]) {
+ return ordersMap[itemId];
+ }
+ const item = data.find((i) => i.id === itemId);
+ if (!item) return [];
+ return getPurchaseOrdersFromPlanning(
+ item,
+ periods,
+ items,
+ suppliersMap[itemId]
+ );
+ };
+
const periodColumns: ColumnDef<PurchasingPlanningItem>[] = periods.map(
(period, index) => {
const isCurrentWeek = index === 0;
@@ -388,7 +399,7 @@ const PlanningTable = memo(
header: "",
cell: ({ row }) => {
const orders = row.original.id
- ? ordersMap[row.original.id] || []
+ ? getOrdersForItem(row.original.id)
: [];
const orderQuantity = orders.reduce(
(acc, order) =>
@@ -423,6 +434,7 @@ const PlanningTable = memo(
},
},
];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [
periods,
suppliers,
@@ -430,8 +442,9 @@ const PlanningTable = memo(
numberFormatter,
unitOfMeasures,
suppliersMap,
- ordersMap,
isDisabled,
+ // Note: ordersMap is intentionally not in deps to avoid column regeneration
+ // getOrdersForItem inside the cell will access the latest ordersMap via closure
]);
const renderActions = useCallback(
@@ -520,7 +533,17 @@ const PlanningTable = memo(
selectedItem={selectedItem}
setSelectedItem={setSelectedItem}
selectedSupplier={suppliersMap[selectedItem.id]}
- orders={selectedItem.id ? ordersMap[selectedItem.id] || [] : []}
+ orders={
+ selectedItem.id
+ ? ordersMap[selectedItem.id] ||
+ getPurchaseOrdersFromPlanning(
+ selectedItem,
+ periods,
+ items,
+ suppliersMap[selectedItem.id]
+ )
+ : []
+ }
setOrders={setOrders}
periods={periods}
isOpen={!!selectedItem}