Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix: include fixed reorder quantity parts in planning even if there's no demand
Brad Barbin68080a392ee3
diff --git a/apps/erp/app/components/RichText.tsx b/apps/erp/app/components/RichText.tsxindex e2ea56d5d7..999aca5060 100644--- a/apps/erp/app/components/RichText.tsx+++ b/apps/erp/app/components/RichText.tsx@@ -76,7 +76,7 @@ const RichText = ({ documentId, notes }: RichTextProps) => {<RichTextForm name="note" className="min-h-[160px]" /></div><div className="flex justify-end w-full">- <Submit>Add Note</Submit>+ <Submit withBlocker={false}>Add Note</Submit></div></VStack></ValidatedForm>diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex c43e6a91b7..1c4e5834f0 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -1,4 +1,4 @@-import { z } from 'zod/v3';+import { z } from "zod/v3";import { zfd } from "zod-form-data";import {methodItemType,@@ -399,6 +399,18 @@ export const itemPlanningValidator = zmessage: "Maximum inventory quantity must be greater than reorder point",path: ["maximumInventoryQuantity"],}+ )+ .refine(+ (data) => {+ if (data.reorderingPolicy === "Fixed Reorder Quantity") {+ return data.reorderQuantity && data.reorderQuantity > 0;+ }+ return true;+ },+ {+ message: "Reorder quantity must be greater than 0",+ path: ["reorderQuantity"],+ });export const itemPurchasingValidator = z.object({diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsxindex 3300819941..7eb62f23aa 100644--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx@@ -107,7 +107,11 @@ export const ItemPlanningChart = ({});const chartData = useMemo(() => {- if (!forecastFetcher.data?.demand || !forecastFetcher.data?.periods)+ if (+ !forecastFetcher.data?.demand ||+ !forecastFetcher.data?.periods ||+ forecastFetcher.data.periods.length === 0+ )return [];const periods = forecastFetcher.data.periods;@@ -145,6 +149,7 @@ export const ItemPlanningChart = ({// If no period found or order date is before first period, use first periodif (!periodId || !order.dueDate) {+ if (periods.length === 0) return;periodId = periods[0].id;}@@ -322,9 +327,10 @@ export const ItemPlanningChart = ({}, [forecastFetcher.data, searchTerm, plannedOrders, conversionFactor]);if (- forecastFetcher.data?.demand.length === 0 &&- forecastFetcher.data?.supply.length === 0 &&- (forecastFetcher.data?.demandForecast?.length ?? 0) === 0+ (forecastFetcher.data?.periods?.length ?? 0) === 0 ||+ (forecastFetcher.data?.demand.length === 0 &&+ forecastFetcher.data?.supply.length === 0 &&+ (forecastFetcher.data?.demandForecast?.length ?? 0) === 0)) {return (<Card>diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsxindex f0739eedb6..59d5f5a7be 100644--- a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx@@ -1,7 +1,7 @@import type { Database } from "@carbon/database";import { Status } from "@carbon/react";import { getLocalTimeZone, parseDate, today } from "@internationalized/date";-import { z } from 'zod/v3';+import { z } from "zod/v3";import type {ProductionOrder,ProductionPlanningItem,@@ -264,15 +264,19 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {days: leadTime,});+ // If reorder quantity is 0, order the same quantity as the reorder point+ const orderQuantity =+ reorderQuantity > 0 ? reorderQuantity : reorderPoint;+orders.push({startDate: startDate.toString(),dueDate: dueDate.toString(),- quantity: reorderQuantity,+ quantity: orderQuantity,periodId: period.id,isASAP: startDate.compare(todaysDate) < 0,});day++;- orderedQuantity += reorderQuantity;+ orderedQuantity += orderQuantity;remainingQuantityNeeded =reorderPoint - (projectedQuantity + orderedQuantity);}@@ -302,8 +306,11 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {const requiredQuantity =maximumInventoryQuantity - (projectedQuantity + orderedQuantity);- // Adjust quantity based on order constraints- let orderQuantity = Math.max(minimumOrderQuantity, requiredQuantity);+ // If reorder quantity is 0, use reorder point as the base order quantity+ let orderQuantity =+ reorderQuantity > 0+ ? Math.max(minimumOrderQuantity, requiredQuantity)+ : reorderPoint;// Ensure orderQuantity is positive to prevent infinite loopif (orderQuantity <= 0) {diff --git a/packages/database/supabase/migrations/20251205000037_include-reorder-quantity-in-planning.sql b/packages/database/supabase/migrations/20251205000037_include-reorder-quantity-in-planning.sqlnew file mode 100644index 0000000000..15c18deae2--- /dev/null+++ b/packages/database/supabase/migrations/20251205000037_include-reorder-quantity-in-planning.sql@@ -0,0 +1,680 @@+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,+ "suppliers" jsonb,+ "preferredSupplierId" TEXT,+ "purchasingUnitOfMeasureCode" TEXT,+ "conversionFactor" 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",+ ir."preferredSupplierId",+ ir."purchasingUnitOfMeasureCode",+ ir."conversionFactor",+ ip."reorderingPolicy",+ ip."demandAccumulationPeriod",+ ip."demandAccumulationSafetyStock",+ ip."reorderPoint",+ ip."reorderQuantity",+ ip."minimumOrderQuantity",+ ip."maximumOrderQuantity",+ ip."orderMultiple",+ ip."maximumInventoryQuantity",+ COALESCE(ps."suppliers", '[]'::jsonb) as "suppliers",+ 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" AND ip."locationId" = location_id+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"+ LEFT JOIN (+ SELECT+ ps."itemId",+ jsonb_agg(+ jsonb_build_object(+ 'id', ps."id",+ 'minimumOrderQuantity', ps."minimumOrderQuantity",+ 'supplierUnitOfMeasureCode', ps."supplierUnitOfMeasureCode",+ 'conversionFactor', ps."conversionFactor",+ 'unitPrice', ps."unitPrice",+ 'supplierId', ps."supplierId",+ 'supplierPartId', ps."supplierPartId"+ )+ ) AS "suppliers"+ FROM "supplierPart" ps+ WHERE ps."companyId" = company_id+ AND ps.active = true+ GROUP BY ps."itemId"+ ) ps ON ps."itemId" = i."id"+ WHERE i."companyId" = company_id+ AND i."replenishmentSystem" != 'Make'+ AND i."itemTrackingType" != 'Non-Inventory'+ AND i."active" = TRUE+ AND (+ EXISTS (+ SELECT 1 FROM demand_data d+ WHERE d."itemId" = i."id"+ )+ OR (+ ip."reorderPoint" > 0+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')+ )+ )+ ),+ -- 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."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."maximumInventoryQuantity",+ p."suppliers",+ 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",+ p."suppliers",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ 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",+ p."suppliers",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor";+$$ LANGUAGE sql SECURITY DEFINER;++DROP FUNCTION IF EXISTS get_production_planning;+CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id TEXT, periods TEXT[])+ RETURNS TABLE (+ "id" TEXT,+ "readableIdWithRevision" TEXT,+ "name" TEXT,+ "active" BOOLEAN,+ "type" "itemType",+ "itemTrackingType" "itemTrackingType",+ "replenishmentSystem" "itemReplenishmentSystem",+ "thumbnailPath" TEXT,+ "unitOfMeasureCode" TEXT,+ "leadTime" INTEGER,+ "manufacturingBlocked" 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."manufacturingBlocked",+ 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" AND ip."locationId" = location_id+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"+ WHERE i."companyId" = company_id+ AND i."replenishmentSystem" = 'Make'+ AND i."itemTrackingType" != 'Non-Inventory'+ AND i."active" = TRUE+ AND (+ EXISTS (+ SELECT 1 FROM demand_data d+ WHERE d."itemId" = i."id"+ )+ OR (+ ip."reorderPoint" > 0+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')+ )+ )+ ),+ -- 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."manufacturingBlocked",+ 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."manufacturingBlocked",+ 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."manufacturingBlocked",+ 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