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.

fix(planning): stop listing an existing PO line twice in the supply and demand card (#1631)

Naveen Kashyap4f2212daace7
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
index 33fc3084ab..171ef8b9ea 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
@@ -58,15 +58,12 @@ import { path } from "~/utils/path";
import type { PlannedOrder } from "../../../purchasing/purchasing.models";
import { DemandForecastSourcesPopover } from "./DemandForecastSourcesPopover";
import { PlannedOrderDetailsPopover } from "./PlannedOrderDetailsPopover";
-
-const supplySourceTypes = ["Purchase Order", "Production Order"] as const;
-const demandSourceTypes = ["Sales Order", "Job Material"] as const;
-
-type SourceType =
- | (typeof supplySourceTypes)[number]
- | (typeof demandSourceTypes)[number]
- | "Planned"
- | "Demand Forecast";
+import {
+ demandSourceTypes,
+ mergePlannedOrders,
+ type SourceType,
+ supplySourceTypes
+} from "./planningSupplyDemand";
interface ChartDataPoint {
startDate: string;
@@ -347,7 +344,6 @@ export const ItemPlanningChart = ({
]);
const combinedSupplyAndDemand = useMemo(() => {
- let projectedQuantity = forecastFetcher.data?.quantityOnHand ?? 0;
const periods = forecastFetcher.data?.periods ?? [];
// First get all forecast data
@@ -396,56 +392,12 @@ export const ItemPlanningChart = ({
})
];
- // Filter out planned orders that have matching existing IDs in forecast data
- const filteredPlannedOrders = plannedOrders.filter((order) => {
- if (!order.existingId) return true;
- return !forecastData.some((item) => item.id === order.existingId);
- });
-
- // For planned orders with existing IDs, update the quantity in forecast data
- plannedOrders.forEach((order) => {
- if (order.existingId) {
- const existingIndex = forecastData.findIndex(
- (item) => item.id === order.existingId
- );
- if (existingIndex >= 0) {
- // Convert purchase quantity to inventory quantity
- const purchaseQuantity = order.quantity ?? 0;
- const inventoryQuantity = purchaseQuantity * conversionFactor;
- forecastData[existingIndex].quantity = inventoryQuantity;
- }
- }
- });
-
- // Add remaining planned orders
- const combined = [
- ...forecastData,
- ...filteredPlannedOrders.map((order) => ({
- ...order,
- sourceType: "Planned" as SourceType,
- quantity: (order.quantity ?? 0) * conversionFactor,
- documentReadableId: "Planned",
- documentId: null,
- id: null,
- plannedOrder: order
- }))
- ]
- .sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""))
- .map((item) => {
- if (
- item.sourceType === "Sales Order" ||
- item.sourceType === "Job Material" ||
- item.sourceType === "Demand Forecast"
- ) {
- projectedQuantity -= item.quantity;
- } else {
- projectedQuantity += item.quantity;
- }
- return {
- ...item,
- projectedQuantity
- };
- });
+ const combined = mergePlannedOrders(
+ forecastData,
+ plannedOrders,
+ conversionFactor,
+ forecastFetcher.data?.quantityOnHand ?? 0
+ );
if (!searchTerm) return combined;
diff --git a/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.test.ts b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.test.ts
new file mode 100644
index 0000000000..eeffcebe94
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it } from "vitest";
+import type { PlannedOrder } from "../../../purchasing/purchasing.models";
+import {
+ existingRowId,
+ mergePlannedOrders,
+ type SupplyDemandRow
+} from "./planningSupplyDemand";
+
+const poLine: SupplyDemandRow = {
+ id: "pol_1",
+ sourceType: "Purchase Order",
+ quantity: 100,
+ dueDate: "2026-09-20",
+ documentReadableId: "P000123"
+};
+
+const salesLine: SupplyDemandRow = {
+ id: "sol_1",
+ sourceType: "Sales Order",
+ quantity: 40,
+ dueDate: "2026-09-18",
+ documentReadableId: "S000045"
+};
+
+function order(overrides: Partial<PlannedOrder>): PlannedOrder {
+ return {
+ startDate: "2026-09-11",
+ dueDate: "2026-09-20",
+ periodId: "period_1",
+ quantity: 100,
+ ...overrides
+ };
+}
+
+describe("existingRowId", () => {
+ it("prefers the line id, which is what the forecast rows carry", () => {
+ expect(
+ existingRowId(order({ existingId: "po_1", existingLineId: "pol_1" }))
+ ).toBe("pol_1");
+ });
+
+ it("falls back to existingId for production, where it already is the job id", () => {
+ expect(existingRowId(order({ existingId: "job_1" }))).toBe("job_1");
+ });
+
+ it("is undefined for a brand-new suggestion", () => {
+ expect(existingRowId(order({}))).toBeUndefined();
+ });
+});
+
+describe("mergePlannedOrders", () => {
+ it("lists a converted PO line once, not as Purchase Order + Planned", () => {
+ const converted = order({
+ existingId: "po_1",
+ existingLineId: "pol_1",
+ existingQuantity: 100,
+ quantity: 100
+ });
+
+ const result = mergePlannedOrders([poLine], [converted], 1, 0);
+
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ id: "pol_1",
+ sourceType: "Purchase Order",
+ quantity: 100,
+ projectedQuantity: 100
+ });
+ expect(result.some((r) => r.sourceType === "Planned")).toBe(false);
+ });
+
+ it("does not double-count the projection with the converted line", () => {
+ const converted = order({
+ existingId: "po_1",
+ existingLineId: "pol_1",
+ existingQuantity: 100
+ });
+
+ const result = mergePlannedOrders([salesLine, poLine], [converted], 1, 10);
+ expect(result.map((r) => r.projectedQuantity)).toEqual([-30, 70]);
+ });
+
+ it("does not re-convert an existing line's quantity (view already returns inventory units)", () => {
+ const edited = order({
+ existingId: "po_1",
+ existingLineId: "pol_1",
+ existingQuantity: 100,
+ quantity: 150
+ });
+
+ const result = mergePlannedOrders([poLine], [edited], 5, 0);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].quantity).toBe(150);
+ });
+
+ it("appends a new suggestion as Planned, converted to inventory units", () => {
+ const suggestion = order({ quantity: 20, dueDate: "2026-09-25" });
+
+ const result = mergePlannedOrders([poLine], [suggestion], 5, 0);
+
+ expect(result).toHaveLength(2);
+ expect(result[1]).toMatchObject({
+ id: null,
+ sourceType: "Planned",
+ quantity: 100,
+ projectedQuantity: 200
+ });
+ });
+
+ it("still dedupes production orders matched on existingId alone", () => {
+ const job: SupplyDemandRow = {
+ id: "job_1",
+ sourceType: "Production Order",
+ quantity: 30,
+ dueDate: "2026-09-22",
+ documentReadableId: "J000007"
+ };
+ const existingJob = order({ existingId: "job_1", quantity: 30 });
+
+ const result = mergePlannedOrders([job], [existingJob], 1, 0);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].sourceType).toBe("Production Order");
+ });
+
+ it("keeps a planned order whose existing line is no longer open", () => {
+ const stale = order({ existingId: "po_9", existingLineId: "pol_9" });
+
+ const result = mergePlannedOrders([poLine], [stale], 1, 0);
+
+ expect(result.map((r) => r.sourceType)).toEqual([
+ "Purchase Order",
+ "Planned"
+ ]);
+ });
+
+ it("does not mutate the input rows", () => {
+ const rows = [{ ...poLine }];
+ const edited = order({ existingLineId: "pol_1", quantity: 999 });
+
+ mergePlannedOrders(rows, [edited], 1, 0);
+
+ expect(rows[0].quantity).toBe(100);
+ });
+});
diff --git a/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts
new file mode 100644
index 0000000000..b36374240d
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Item/planningSupplyDemand.ts
@@ -0,0 +1,73 @@
+import type { PlannedOrder } from "../../../purchasing/purchasing.models";
+
+export const supplySourceTypes = [
+ "Purchase Order",
+ "Production Order"
+] as const;
+export const demandSourceTypes = ["Sales Order", "Job Material"] as const;
+
+export type SourceType =
+ | (typeof supplySourceTypes)[number]
+ | (typeof demandSourceTypes)[number]
+ | "Planned"
+ | "Demand Forecast";
+
+export type SupplyDemandRow = {
+ id: string | null;
+ sourceType: SourceType;
+ quantity: number;
+ dueDate: string | null;
+ documentReadableId: string | null;
+};
+
+export function existingRowId(order: PlannedOrder) {
+ return order.existingLineId ?? order.existingId;
+}
+
+export function mergePlannedOrders<T extends SupplyDemandRow>(
+ rows: T[],
+ plannedOrders: PlannedOrder[],
+ conversionFactor: number,
+ quantityOnHand: number
+) {
+ const merged: T[] = rows.map((row) => ({ ...row }));
+
+ for (const order of plannedOrders) {
+ const rowId = existingRowId(order);
+ if (!rowId) continue;
+ const existing = merged.find((row) => row.id === rowId);
+ if (existing) existing.quantity = order.quantity ?? 0;
+ }
+
+ const newPlanned = plannedOrders
+ .filter((order) => {
+ const rowId = existingRowId(order);
+ if (!rowId) return true;
+ return !merged.some((row) => row.id === rowId);
+ })
+ .map((order) => ({
+ ...order,
+ id: null,
+ sourceType: "Planned" as SourceType,
+ quantity: (order.quantity ?? 0) * conversionFactor,
+ documentReadableId: "Planned",
+ documentId: null,
+ plannedOrder: order
+ }));
+
+ let projectedQuantity = quantityOnHand;
+ return [...merged, ...newPlanned]
+ .sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""))
+ .map((item) => {
+ if (
+ item.sourceType === "Sales Order" ||
+ item.sourceType === "Job Material" ||
+ item.sourceType === "Demand Forecast"
+ ) {
+ projectedQuantity -= item.quantity;
+ } else {
+ projectedQuantity += item.quantity;
+ }
+ return { ...item, projectedQuantity };
+ });
+}