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.

build: upgrade novu package for better eu support

Brad Barbinabc97e7afc14
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
index 0cc60d48c9..b8c38c6a70 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
@@ -328,6 +328,20 @@ const ProductionPlanningTable = ({
}
},
...periodColumns,
+ {
+ accessorKey: "quantityToOrder",
+ header: "Qty to Order",
+ cell: ({ row }) => {
+ const value = row.original.quantityToOrder;
+ if (value === undefined || value === 0) return "-";
+ return (
+ <span className="font-medium">{numberFormatter.format(value)}</span>
+ );
+ },
+ meta: {
+ icon: <LuCirclePlay />
+ }
+ },
{
accessorKey: "type",
header: "Type",
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
index 13a08cac42..071cf6d492 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -406,6 +406,22 @@ const PlanningTable = memo(
}
},
...periodColumns,
+ {
+ accessorKey: "quantityToOrder",
+ header: "Qty to Order",
+ cell: ({ row }) => {
+ const value = row.original.quantityToOrder;
+ if (value === undefined || value === 0) return "-";
+ return (
+ <span className="font-medium">
+ {numberFormatter.format(value)}
+ </span>
+ );
+ },
+ meta: {
+ icon: <LuCirclePlay />
+ }
+ },
{
accessorKey: "type",
header: "Type",
diff --git a/apps/erp/package.json b/apps/erp/package.json
index a299dc28ac..47b4be3e45 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -31,9 +31,9 @@
"@marsidev/react-turnstile": "^1.1.0",
"@monaco-editor/react": "^4.6.0",
"@nanostores/react": "^0.7.1",
- "@novu/framework": "^2.10.0",
- "@novu/headless": "^2.7.0",
- "@novu/node": "^2.6.6",
+ "@novu/framework": "^2.9.0",
+ "@novu/headless": "^2.7.0-alpha.0",
+ "@novu/node": "^2.0.1",
"@react-aria/i18n": "^3.11.0",
"@react-email/components": "0.3.3",
"@react-router/dev": "7.12.0",
diff --git a/package-lock.json b/package-lock.json
index d40f9be280..051135e7b0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -239,8 +239,8 @@
"@marsidev/react-turnstile": "^1.1.0",
"@monaco-editor/react": "^4.6.0",
"@nanostores/react": "^0.7.1",
- "@novu/framework": "^2.3.0",
- "@novu/headless": "^2.0.0",
+ "@novu/framework": "^2.9.0",
+ "@novu/headless": "^2.7.0-alpha.0",
"@novu/node": "^2.0.1",
"@react-aria/i18n": "^3.11.0",
"@react-email/components": "0.3.3",
@@ -4209,7 +4209,9 @@
"license": "MIT"
},
"node_modules/@novu/headless": {
- "version": "2.6.6",
+ "version": "2.7.0-alpha.0",
+ "resolved": "https://registry.npmjs.org/@novu/headless/-/headless-2.7.0-alpha.0.tgz",
+ "integrity": "sha512-EplFGSvmxb74OqplF0YOKb1sDDOOux7CGRqHH1LpfsOFFG86Gk7Ky7Z7IROf26MxljwNw5hd06p2oTeCzonpAA==",
"license": "MIT",
"dependencies": {
"@novu/client": "2.6.6",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5d7f22a143..16a3fb0450 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -30813,7 +30813,6 @@ export type Database = {
assetId: string | null
companyId: string
convertedAddOnCost: number | null
- convertedNonTaxableAddOnCost: number | null
convertedSetupPrice: number | null
convertedShippingCost: number | null
convertedUnitPrice: number | null
@@ -30831,7 +30830,6 @@ export type Database = {
locationId: string | null
methodType: Database["public"]["Enums"]["methodType"]
modelUploadId: string | null
- nonTaxableAddOnCost: number
opportunityId: string | null
quantity: number
salesOrderId: string | null
@@ -30851,7 +30849,6 @@ export type Database = {
assetId?: string | null
companyId: string
convertedAddOnCost?: number | null
- convertedNonTaxableAddOnCost?: number | null
convertedSetupPrice?: number | null
convertedShippingCost?: number | null
convertedUnitPrice?: number | null
@@ -30869,7 +30866,6 @@ export type Database = {
locationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
- nonTaxableAddOnCost?: number
opportunityId?: string | null
quantity?: number
salesOrderId?: string | null
@@ -30889,7 +30885,6 @@ export type Database = {
assetId?: string | null
companyId?: string
convertedAddOnCost?: number | null
- convertedNonTaxableAddOnCost?: number | null
convertedSetupPrice?: number | null
convertedShippingCost?: number | null
convertedUnitPrice?: number | null
@@ -30907,7 +30902,6 @@ export type Database = {
locationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
- nonTaxableAddOnCost?: number
opportunityId?: string | null
quantity?: number
salesOrderId?: string | null
@@ -31752,7 +31746,6 @@ export type Database = {
assetId: string | null
companyId: string
convertedAddOnCost: number | null
- convertedNonTaxableAddOnCost: number | null
convertedShippingCost: number | null
convertedUnitPrice: number | null
createdAt: string
@@ -31768,7 +31761,6 @@ export type Database = {
locationId: string | null
methodType: Database["public"]["Enums"]["methodType"]
modelUploadId: string | null
- nonTaxableAddOnCost: number
promisedDate: string | null
quantityInvoiced: number | null
quantitySent: number | null
@@ -31796,7 +31788,6 @@ export type Database = {
assetId?: string | null
companyId: string
convertedAddOnCost?: number | null
- convertedNonTaxableAddOnCost?: number | null
convertedShippingCost?: number | null
convertedUnitPrice?: number | null
createdAt?: string
@@ -31812,7 +31803,6 @@ export type Database = {
locationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
- nonTaxableAddOnCost?: number
promisedDate?: string | null
quantityInvoiced?: number | null
quantitySent?: number | null
@@ -31840,7 +31830,6 @@ export type Database = {
assetId?: string | null
companyId?: string
convertedAddOnCost?: number | null
- convertedNonTaxableAddOnCost?: number | null
convertedShippingCost?: number | null
convertedUnitPrice?: number | null
createdAt?: string
@@ -31856,7 +31845,6 @@ export type Database = {
locationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
- nonTaxableAddOnCost?: number
promisedDate?: string | null
quantityInvoiced?: number | null
quantitySent?: number | null
@@ -33341,7 +33329,7 @@ export type Database = {
},
]
}
- searchIndex_7gYaboCg4bgSHUXebP88ah: {
+ searchIndex_3VCMFwYSx4XmioYxbouFts: {
Row: {
createdAt: string
description: string | null
@@ -47961,14 +47949,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"]
@@ -52175,7 +52163,6 @@ export type Database = {
assetId: string | null
companyId: string | null
convertedAddOnCost: number | null
- convertedNonTaxableAddOnCost: number | null
convertedSetupPrice: number | null
convertedShippingCost: number | null
convertedUnitPrice: number | null
@@ -52199,7 +52186,6 @@ export type Database = {
locationId: string | null
methodType: Database["public"]["Enums"]["methodType"] | null
modelUploadId: string | null
- nonTaxableAddOnCost: number | null
opportunityId: string | null
quantity: number | null
salesOrderId: string | null
@@ -52508,7 +52494,7 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -52522,7 +52508,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -52807,7 +52793,6 @@ export type Database = {
autodeskUrn: string | null
companyId: string | null
convertedAddOnCost: number | null
- convertedNonTaxableAddOnCost: number | null
convertedShippingCost: number | null
convertedUnitPrice: number | null
createdAt: string | null
@@ -52831,7 +52816,6 @@ export type Database = {
modelPath: string | null
modelSize: number | null
modelUploadId: string | null
- nonTaxableAddOnCost: number | null
orderDate: string | null
promisedDate: string | null
quantityInvoiced: number | null
@@ -55501,6 +55485,7 @@ export type Database = {
note: string | null
shiftId: string | null
shiftName: string | null
+ status: string | null
updatedAt: string | null
updatedBy: string | null
}
@@ -56269,6 +56254,22 @@ export type Database = {
Args: { sync_functions?: string[]; table_name_text: string }
Returns: undefined
}
+ calculate_quantity_to_order: {
+ Args: {
+ p_demand_accumulation_period: number
+ p_demand_accumulation_safety_stock: number
+ p_lot_size: number
+ p_maximum_inventory_quantity: number
+ p_maximum_order_quantity: number
+ p_minimum_order_quantity: number
+ p_order_multiple: number
+ p_projections: number[]
+ p_reorder_point: number
+ p_reorder_quantity: number
+ p_reordering_policy: Database["public"]["Enums"]["itemReorderingPolicy"]
+ }
+ Returns: number
+ }
check_api_key_rate_limit: {
Args: { p_api_key_id: string; p_limit: number; p_window: string }
Returns: Json
@@ -57244,6 +57245,7 @@ export type Database = {
name: string
orderMultiple: number
quantityOnHand: number
+ quantityToOrder: number
readableIdWithRevision: string
reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]
reorderPoint: number
@@ -57405,6 +57407,7 @@ export type Database = {
purchasingBlocked: boolean
purchasingUnitOfMeasureCode: string
quantityOnHand: number
+ quantityToOrder: number
readableIdWithRevision: string
reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]
reorderPoint: number
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 5d7f22a143..16a3fb0450 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -30813,7 +30813,6 @@ export type Database = {
assetId: string | null
companyId: string
convertedAddOnCost: number | null
- convertedNonTaxableAddOnCost: number | null
convertedSetupPrice: number | null
convertedShippingCost: number | null
convertedUnitPrice: number | null
@@ -30831,7 +30830,6 @@ export type Database = {
locationId: string | null
methodType: Database["public"]["Enums"]["methodType"]
modelUploadId: string | null
- nonTaxableAddOnCost: number
opportunityId: string | null
quantity: number
salesOrderId: string | null
@@ -30851,7 +30849,6 @@ export type Database = {
assetId?: string | null
companyId: string
convertedAddOnCost?: number | null
- convertedNonTaxableAddOnCost?: number | null
convertedSetupPrice?: number | null
convertedShippingCost?: number | null
convertedUnitPrice?: number | null
@@ -30869,7 +30866,6 @@ export type Database = {
locationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
- nonTaxableAddOnCost?: number
opportunityId?: string | null
quantity?: number
salesOrderId?: string | null
@@ -30889,7 +30885,6 @@ export type Database = {
assetId?: string | null
companyId?: string
convertedAddOnCost?: number | null
- convertedNonTaxableAddOnCost?: number | null
convertedSetupPrice?: number | null
convertedShippingCost?: number | null
convertedUnitPrice?: number | null
@@ -30907,7 +30902,6 @@ export type Database = {
locationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
- nonTaxableAddOnCost?: number
opportunityId?: string | null
quantity?: number
salesOrderId?: string | null
@@ -31752,7 +31746,6 @@ export type Database = {
assetId: string | null
companyId: string
convertedAddOnCost: number | null
- convertedNonTaxableAddOnCost: number | null
convertedShippingCost: number | null
convertedUnitPrice: number | null
createdAt: string
@@ -31768,7 +31761,6 @@ export type Database = {
locationId: string | null
methodType: Database["public"]["Enums"]["methodType"]
modelUploadId: string | null
- nonTaxableAddOnCost: number
promisedDate: string | null
quantityInvoiced: number | null
quantitySent: number | null
@@ -31796,7 +31788,6 @@ export type Database = {
assetId?: string | null
companyId: string
convertedAddOnCost?: number | null
- convertedNonTaxableAddOnCost?: number | null
convertedShippingCost?: number | null
convertedUnitPrice?: number | null
createdAt?: string
@@ -31812,7 +31803,6 @@ export type Database = {
locationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
- nonTaxableAddOnCost?: number
promisedDate?: string | null
quantityInvoiced?: number | null
quantitySent?: number | null
@@ -31840,7 +31830,6 @@ export type Database = {
assetId?: string | null
companyId?: string
convertedAddOnCost?: number | null
- convertedNonTaxableAddOnCost?: number | null
convertedShippingCost?: number | null
convertedUnitPrice?: number | null
createdAt?: string
@@ -31856,7 +31845,6 @@ export type Database = {
locationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
- nonTaxableAddOnCost?: number
promisedDate?: string | null
quantityInvoiced?: number | null
quantitySent?: number | null
@@ -33341,7 +33329,7 @@ export type Database = {
},
]
}
- searchIndex_7gYaboCg4bgSHUXebP88ah: {
+ searchIndex_3VCMFwYSx4XmioYxbouFts: {
Row: {
createdAt: string
description: string | null
@@ -47961,14 +47949,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"]
@@ -52175,7 +52163,6 @@ export type Database = {
assetId: string | null
companyId: string | null
convertedAddOnCost: number | null
- convertedNonTaxableAddOnCost: number | null
convertedSetupPrice: number | null
convertedShippingCost: number | null
convertedUnitPrice: number | null
@@ -52199,7 +52186,6 @@ export type Database = {
locationId: string | null
methodType: Database["public"]["Enums"]["methodType"] | null
modelUploadId: string | null
- nonTaxableAddOnCost: number | null
opportunityId: string | null
quantity: number | null
salesOrderId: string | null
@@ -52508,7 +52494,7 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -52522,7 +52508,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -52807,7 +52793,6 @@ export type Database = {
autodeskUrn: string | null
companyId: string | null
convertedAddOnCost: number | null
- convertedNonTaxableAddOnCost: number | null
convertedShippingCost: number | null
convertedUnitPrice: number | null
createdAt: string | null
@@ -52831,7 +52816,6 @@ export type Database = {
modelPath: string | null
modelSize: number | null
modelUploadId: string | null
- nonTaxableAddOnCost: number | null
orderDate: string | null
promisedDate: string | null
quantityInvoiced: number | null
@@ -55501,6 +55485,7 @@ export type Database = {
note: string | null
shiftId: string | null
shiftName: string | null
+ status: string | null
updatedAt: string | null
updatedBy: string | null
}
@@ -56269,6 +56254,22 @@ export type Database = {
Args: { sync_functions?: string[]; table_name_text: string }
Returns: undefined
}
+ calculate_quantity_to_order: {
+ Args: {
+ p_demand_accumulation_period: number
+ p_demand_accumulation_safety_stock: number
+ p_lot_size: number
+ p_maximum_inventory_quantity: number
+ p_maximum_order_quantity: number
+ p_minimum_order_quantity: number
+ p_order_multiple: number
+ p_projections: number[]
+ p_reorder_point: number
+ p_reorder_quantity: number
+ p_reordering_policy: Database["public"]["Enums"]["itemReorderingPolicy"]
+ }
+ Returns: number
+ }
check_api_key_rate_limit: {
Args: { p_api_key_id: string; p_limit: number; p_window: string }
Returns: Json
@@ -57244,6 +57245,7 @@ export type Database = {
name: string
orderMultiple: number
quantityOnHand: number
+ quantityToOrder: number
readableIdWithRevision: string
reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]
reorderPoint: number
@@ -57405,6 +57407,7 @@ export type Database = {
purchasingBlocked: boolean
purchasingUnitOfMeasureCode: string
quantityOnHand: number
+ quantityToOrder: number
readableIdWithRevision: string
reorderingPolicy: Database["public"]["Enums"]["itemReorderingPolicy"]
reorderPoint: number
diff --git a/packages/database/supabase/migrations/20260324120000_planning-quantity-to-order.sql b/packages/database/supabase/migrations/20260324120000_planning-quantity-to-order.sql
new file mode 100644
index 0000000000..3e49e57a15
--- /dev/null
+++ b/packages/database/supabase/migrations/20260324120000_planning-quantity-to-order.sql
@@ -0,0 +1,861 @@
+-- Helper function to calculate total quantity to order based on reorder policy
+CREATE OR REPLACE FUNCTION calculate_quantity_to_order(
+ p_reordering_policy "itemReorderingPolicy",
+ p_reorder_point INTEGER,
+ p_reorder_quantity INTEGER,
+ p_minimum_order_quantity INTEGER,
+ p_maximum_order_quantity INTEGER,
+ p_order_multiple INTEGER,
+ p_lot_size INTEGER,
+ p_maximum_inventory_quantity NUMERIC,
+ p_demand_accumulation_period INTEGER,
+ p_demand_accumulation_safety_stock NUMERIC,
+ p_projections NUMERIC[]
+) RETURNS NUMERIC AS $$
+DECLARE
+ ordered_quantity NUMERIC := 0;
+ num_periods INTEGER;
+ projected_stock NUMERIC;
+ projected_quantity NUMERIC;
+ remaining_needed NUMERIC;
+ total_order_qty NUMERIC;
+ order_qty NUMERIC;
+ required_qty NUMERIC;
+ i INTEGER;
+ j INTEGER;
+ iterations INTEGER;
+BEGIN
+ num_periods := COALESCE(array_length(p_projections, 1), 0);
+ IF num_periods = 0 THEN RETURN 0; END IF;
+
+ CASE p_reordering_policy
+ WHEN 'Manual Reorder' THEN
+ RETURN 0;
+
+ WHEN 'Demand-Based Reorder' THEN
+ i := 1;
+ WHILE i <= num_periods LOOP
+ projected_stock := 0;
+ j := i;
+ WHILE j <= LEAST(i + p_demand_accumulation_period - 1, num_periods) LOOP
+ projected_stock := COALESCE(p_projections[j], 0) + ordered_quantity;
+ j := j + 1;
+ END LOOP;
+
+ IF projected_stock < p_demand_accumulation_safety_stock THEN
+ total_order_qty := p_demand_accumulation_safety_stock - projected_stock;
+
+ IF p_maximum_order_quantity > 0 THEN
+ total_order_qty := LEAST(total_order_qty, p_maximum_order_quantity);
+ END IF;
+ total_order_qty := GREATEST(total_order_qty, p_minimum_order_quantity);
+
+ IF p_order_multiple > 0 THEN
+ total_order_qty := CEIL(total_order_qty / p_order_multiple) * p_order_multiple;
+ END IF;
+
+ ordered_quantity := ordered_quantity + total_order_qty;
+ END IF;
+
+ i := i + p_demand_accumulation_period;
+ END LOOP;
+ RETURN ordered_quantity;
+
+ WHEN 'Fixed Reorder Quantity' THEN
+ FOR i IN 1..num_periods LOOP
+ projected_quantity := COALESCE(p_projections[i], 0);
+ remaining_needed := p_reorder_point - (projected_quantity + ordered_quantity);
+ iterations := 0;
+ WHILE remaining_needed > 0 AND iterations < 5 LOOP
+ IF p_reorder_quantity > 0 THEN
+ order_qty := p_reorder_quantity;
+ ELSE
+ order_qty := p_reorder_point;
+ END IF;
+
+ ordered_quantity := ordered_quantity + order_qty;
+ remaining_needed := p_reorder_point - (projected_quantity + ordered_quantity);
+ iterations := iterations + 1;
+ END LOOP;
+ END LOOP;
+ RETURN ordered_quantity;
+
+ WHEN 'Maximum Quantity' THEN
+ FOR i IN 1..num_periods LOOP
+ projected_quantity := COALESCE(p_projections[i], 0);
+ remaining_needed := p_reorder_point - (projected_quantity + ordered_quantity);
+ iterations := 0;
+ WHILE remaining_needed > 0 AND iterations < 5 LOOP
+ required_qty := p_maximum_inventory_quantity - (projected_quantity + ordered_quantity);
+
+ IF p_reorder_quantity > 0 THEN
+ order_qty := GREATEST(p_minimum_order_quantity, required_qty);
+ ELSE
+ order_qty := p_reorder_point;
+ END IF;
+
+ IF order_qty <= 0 THEN EXIT; END IF;
+
+ IF p_order_multiple > 1 THEN
+ order_qty := CEIL(order_qty / p_order_multiple) * p_order_multiple;
+ END IF;
+
+ IF p_lot_size > 0 THEN
+ order_qty := CEIL(order_qty / p_lot_size) * p_lot_size;
+ END IF;
+
+ IF p_maximum_order_quantity > 0 THEN
+ order_qty := LEAST(order_qty, p_maximum_order_quantity);
+ END IF;
+
+ ordered_quantity := ordered_quantity + order_qty;
+ remaining_needed := p_reorder_point - (projected_quantity + ordered_quantity);
+ iterations := iterations + 1;
+ END LOOP;
+ END LOOP;
+ RETURN ordered_quantity;
+
+ ELSE
+ RETURN 0;
+ END CASE;
+END;
+$$ LANGUAGE plpgsql IMMUTABLE;
+
+-- Update get_purchasing_planning to include quantityToOrder
+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,
+ "quantityToOrder" 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
+ 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_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')
+ )
+ )
+ ),
+ projections AS (
+ 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
+
+ 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)
+ ),
+ order_quantities AS (
+ SELECT
+ p."id",
+ calculate_quantity_to_order(
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ array_agg(p."projection" ORDER BY p.period_index)
+ ) AS "quantityToOrder"
+ FROM projections p
+ GROUP BY
+ p."id",
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock"
+ )
+ 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",
+ COALESCE(oq."quantityToOrder", 0) AS "quantityToOrder",
+ 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
+ LEFT JOIN order_quantities oq ON p."id" = oq."id"
+ 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",
+ oq."quantityToOrder";
+$$ LANGUAGE sql SECURITY DEFINER;
+
+-- Update get_production_planning to include quantityToOrder
+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,
+ "quantityToOrder" 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
+ 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_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')
+ )
+ )
+ ),
+ projections AS (
+ 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
+
+ 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)
+ ),
+ order_quantities AS (
+ SELECT
+ p."id",
+ calculate_quantity_to_order(
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ array_agg(p."projection" ORDER BY p.period_index)
+ ) AS "quantityToOrder"
+ FROM projections p
+ GROUP BY
+ p."id",
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock"
+ )
+ 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",
+ COALESCE(oq."quantityToOrder", 0) AS "quantityToOrder",
+ 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
+ LEFT JOIN order_quantities oq ON p."id" = oq."id"
+ 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",
+ oq."quantityToOrder";
+$$ LANGUAGE sql SECURITY DEFINER;