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(items): include demand projections in the item planning chart demand (#1720)

Naveen Kashyape08d51f5b532
diff --git a/apps/erp/app/modules/items/demand-projection.test.ts b/apps/erp/app/modules/items/demand-projection.test.ts
new file mode 100644
index 0000000000..b012cce439
--- /dev/null
+++ b/apps/erp/app/modules/items/demand-projection.test.ts
@@ -0,0 +1,163 @@
+import { describe, expect, it } from "vitest";
+import { mergeDemandProjections } from "./demand-projection";
+
+const forecast = (periodId: string, forecastQuantity: number | null) => ({
+ id: `df_${periodId}`,
+ itemId: "item_1",
+ locationId: "loc_1",
+ periodId,
+ forecastQuantity
+});
+
+const projection = (
+ periodId: string,
+ forecastQuantity: number | null,
+ id = `dp_${periodId}`
+) => ({
+ id,
+ itemId: "item_1",
+ locationId: "loc_1",
+ periodId,
+ forecastQuantity
+});
+
+describe("mergeDemandProjections", () => {
+ it("returns nothing when there are neither forecasts nor projections", () => {
+ expect(mergeDemandProjections([], [])).toEqual([]);
+ });
+
+ it("charts a projection-only item: a period with no forecast row gets a synthetic row", () => {
+ const merged = mergeDemandProjections([], [projection("p1", 40)]);
+
+ expect(merged).toHaveLength(1);
+ expect(merged[0]).toMatchObject({
+ itemId: "item_1",
+ locationId: "loc_1",
+ periodId: "p1",
+ forecastQuantity: 40
+ });
+ expect(merged[0]).not.toHaveProperty("id");
+ });
+
+ it("adds a projection onto the existing forecast row of the same period, not as a second row", () => {
+ const merged = mergeDemandProjections(
+ [forecast("p1", 10)],
+ [projection("p1", 5)]
+ );
+
+ expect(merged).toEqual([{ ...forecast("p1", 10), forecastQuantity: 15 }]);
+ });
+
+ it("leaves forecast rows without a projection untouched", () => {
+ const rows = [forecast("p1", 10), forecast("p2", 3)];
+ const merged = mergeDemandProjections(rows, [projection("p2", 4)]);
+
+ expect(merged).toEqual([
+ forecast("p1", 10),
+ { ...forecast("p2", 3), forecastQuantity: 7 }
+ ]);
+ });
+
+ it("accumulates several projections in one period before merging", () => {
+ const merged = mergeDemandProjections(
+ [],
+ [projection("p1", 5, "dp_a"), projection("p1", 7, "dp_b")]
+ );
+
+ expect(merged).toHaveLength(1);
+ expect(merged[0].forecastQuantity).toBe(12);
+ });
+
+ it("applies a period's projection to only the first forecast row of that period", () => {
+ const merged = mergeDemandProjections(
+ [forecast("p1", 10), { ...forecast("p1", 2), id: "df_p1_dup" }],
+ [projection("p1", 5)]
+ );
+
+ expect(merged).toEqual([
+ { ...forecast("p1", 10), forecastQuantity: 15 },
+ { ...forecast("p1", 2), id: "df_p1_dup" }
+ ]);
+ });
+
+ it("ignores zero, negative and null projections", () => {
+ const merged = mergeDemandProjections(
+ [forecast("p1", 10)],
+ [
+ projection("p1", 0, "dp_zero"),
+ projection("p1", -3, "dp_neg"),
+ projection("p2", null, "dp_null"),
+ projection("p3", 0, "dp_zero_2")
+ ]
+ );
+
+ expect(merged).toEqual([forecast("p1", 10)]);
+ });
+
+ it("treats a null forecast quantity as zero when adding a projection", () => {
+ const merged = mergeDemandProjections(
+ [forecast("p1", null)],
+ [projection("p1", 6)]
+ );
+
+ expect(merged).toEqual([{ ...forecast("p1", null), forecastQuantity: 6 }]);
+ });
+
+ it("interleaves periods correctly: forecast-only, both, and projection-only", () => {
+ const merged = mergeDemandProjections(
+ [forecast("p1", 10), forecast("p2", 20)],
+ [projection("p2", 5), projection("p3", 8)],
+ ["p1", "p2", "p3"]
+ );
+
+ expect(merged.map((r) => [r.periodId, r.forecastQuantity])).toEqual([
+ ["p1", 10],
+ ["p2", 25],
+ ["p3", 8]
+ ]);
+ });
+
+ it("places projection-only rows by the requested period sequence, not after the forecasts", () => {
+ const merged = mergeDemandProjections(
+ [forecast("p2", 20), forecast("p4", 40)],
+ [projection("p1", 5), projection("p3", 8)],
+ ["p1", "p2", "p3", "p4"]
+ );
+
+ expect(merged.map((r) => [r.periodId, r.forecastQuantity])).toEqual([
+ ["p1", 5],
+ ["p2", 20],
+ ["p3", 8],
+ ["p4", 40]
+ ]);
+ });
+
+ it("reorders forecast rows that arrive out of period sequence", () => {
+ const merged = mergeDemandProjections(
+ [forecast("p3", 30), forecast("p1", 10)],
+ [],
+ ["p1", "p2", "p3"]
+ );
+
+ expect(merged.map((r) => r.periodId)).toEqual(["p1", "p3"]);
+ });
+
+ it("keeps rows for periods outside the sequence after the ordered ones, in input order", () => {
+ const merged = mergeDemandProjections(
+ [forecast("zz", 1), forecast("p2", 20), forecast("yy", 2)],
+ [projection("p1", 5)],
+ ["p1", "p2"]
+ );
+
+ expect(merged.map((r) => r.periodId)).toEqual(["p1", "p2", "zz", "yy"]);
+ });
+
+ it("keeps insertion order when no period sequence is given", () => {
+ const merged = mergeDemandProjections(
+ [forecast("p2", 20)],
+ [projection("p1", 5)]
+ );
+
+ expect(merged.map((r) => r.periodId)).toEqual(["p2", "p1"]);
+ });
+});
diff --git a/apps/erp/app/modules/items/demand-projection.ts b/apps/erp/app/modules/items/demand-projection.ts
new file mode 100644
index 0000000000..0442711423
--- /dev/null
+++ b/apps/erp/app/modules/items/demand-projection.ts
@@ -0,0 +1,52 @@
+export type DemandForecastLike = {
+ periodId: string;
+ forecastQuantity: number | null;
+};
+
+export function mergeDemandProjections<
+ TForecast extends DemandForecastLike,
+ TProjection extends DemandForecastLike & { id: string }
+>(
+ forecasts: TForecast[],
+ projections: TProjection[],
+ periodOrder: string[] = []
+): Array<TForecast | Omit<TProjection, "id">> {
+ const projectionByPeriod = new Map<string, number>();
+ for (const projection of projections) {
+ const quantity = projection.forecastQuantity ?? 0;
+ if (quantity > 0) {
+ projectionByPeriod.set(
+ projection.periodId,
+ (projectionByPeriod.get(projection.periodId) ?? 0) + quantity
+ );
+ }
+ }
+
+ const mergedPeriodIds = new Set<string>();
+ const merged: Array<TForecast | Omit<TProjection, "id">> = forecasts.map(
+ (forecast) => {
+ const quantity = projectionByPeriod.get(forecast.periodId);
+ if (!quantity || mergedPeriodIds.has(forecast.periodId)) return forecast;
+ mergedPeriodIds.add(forecast.periodId);
+ return {
+ ...forecast,
+ forecastQuantity: (forecast.forecastQuantity ?? 0) + quantity
+ };
+ }
+ );
+
+ for (const projection of projections) {
+ const quantity = projectionByPeriod.get(projection.periodId);
+ if (!quantity || mergedPeriodIds.has(projection.periodId)) continue;
+ mergedPeriodIds.add(projection.periodId);
+ const { id: _id, ...forecastFields } = projection;
+ merged.push({ ...forecastFields, forecastQuantity: quantity });
+ }
+
+ if (periodOrder.length === 0) return merged;
+
+ const rank = new Map(periodOrder.map((periodId, index) => [periodId, index]));
+ const position = (row: DemandForecastLike) =>
+ rank.get(row.periodId) ?? periodOrder.length;
+ return [...merged].sort((a, b) => position(a) - position(b));
+}
diff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.ts
index 7826cf7a76..4b0a522fbb 100644
--- a/apps/erp/app/modules/items/items.service.test.ts
+++ b/apps/erp/app/modules/items/items.service.test.ts
@@ -512,3 +512,89 @@ describe("diffMethod — attributes", () => {
expect(attributes[0].after).toEqual(target);
});
});
+
+describe("getItemDemand", () => {
+ function mockClient(rowsByTable: Record<string, unknown[]>) {
+ const reads: Array<{
+ table: string;
+ filters: Array<[string, string, unknown]>;
+ }> = [];
+ const client: any = {
+ from: (table: string) => {
+ const read = { table, filters: [] as Array<[string, string, unknown]> };
+ reads.push(read);
+ const builder: any = {
+ select: () => builder,
+ eq: (column: string, value: unknown) => {
+ read.filters.push(["eq", column, value]);
+ return builder;
+ },
+ in: (column: string, value: unknown) => {
+ read.filters.push(["in", column, value]);
+ return builder;
+ },
+ order: () => builder,
+ then: (resolve: (v: unknown) => void) =>
+ resolve({ data: rowsByTable[table] ?? [], error: null })
+ };
+ return builder;
+ }
+ };
+ return { client, reads };
+ }
+
+ const args = {
+ itemId: "item_1",
+ locationId: "loc_1",
+ companyId: "co_1",
+ periods: ["p1", "p2"]
+ };
+
+ it("reads demandProjection alongside demandActual and demandForecast", async () => {
+ const { getItemDemand } = await import("./items.service");
+ const { client, reads } = mockClient({});
+
+ await getItemDemand(client, args);
+
+ expect(reads.map((r) => r.table).sort()).toEqual([
+ "demandActual",
+ "demandForecast",
+ "demandProjection"
+ ]);
+ });
+
+ it("scopes the projection read to the item, location, company and periods", async () => {
+ const { getItemDemand } = await import("./items.service");
+ const { client, reads } = mockClient({});
+
+ await getItemDemand(client, args);
+
+ const projectionRead = reads.find((r) => r.table === "demandProjection");
+ expect(projectionRead?.filters).toEqual([
+ ["eq", "itemId", "item_1"],
+ ["eq", "locationId", "loc_1"],
+ ["eq", "companyId", "co_1"],
+ ["in", "periodId", ["p1", "p2"]]
+ ]);
+ });
+
+ it("returns the projection rows as `projections`, defaulting every series to []", async () => {
+ const { getItemDemand } = await import("./items.service");
+ const projectionRow = {
+ id: "dp_1",
+ itemId: "item_1",
+ locationId: "loc_1",
+ periodId: "p1",
+ forecastQuantity: 40
+ };
+ const { client } = mockClient({ demandProjection: [projectionRow] });
+
+ const demand = await getItemDemand(client, args);
+
+ expect(demand).toEqual({
+ actuals: [],
+ forecasts: [],
+ projections: [projectionRow]
+ });
+ });
+});
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 519e27d8e3..958fa32fe4 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -660,7 +660,7 @@ export async function getItemDemand(
companyId: string;
}
) {
- const [actuals, forecasts] = await Promise.all([
+ const [actuals, forecasts, projections] = await Promise.all([
client
.from("demandActual")
.select("*")
@@ -675,12 +675,20 @@ export async function getItemDemand(
.eq("locationId", locationId)
.eq("companyId", companyId)
.in("periodId", periods)
- .order("periodId")
+ .order("periodId"),
+ client
+ .from("demandProjection")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .in("periodId", periods)
]);
return {
actuals: actuals.data ?? [],
- forecasts: forecasts.data ?? []
+ forecasts: forecasts.data ?? [],
+ projections: projections.data ?? []
};
}
diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
index 429e359527..50a66b3014 100644
--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
@@ -6,6 +6,7 @@ import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick"
import { datetime } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
+import { mergeDemandProjections } from "~/modules/items/demand-projection";
import {
getDemandForecastSources,
getItemDemand,
@@ -203,7 +204,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
})
]);
- if (demand.actuals.length === 0 && demand.forecasts.length === 0) {
+ const demandForecast = mergeDemandProjections(
+ demand.forecasts,
+ demand.projections,
+ periods.map((p) => p.id ?? "")
+ );
+
+ if (demand.actuals.length === 0 && demandForecast.length === 0) {
return data(
defaultResponse,
await flash(request, error(null, "Failed to load demand"))
@@ -224,7 +231,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
demand: demand.actuals,
- demandForecast: demand.forecasts,
+ demandForecast,
demandForecastSources: demandForecastSources.data ?? [],
supply: [
...supply.actuals,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index e7afbe341c..c1666fd9fa 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -433,7 +433,7 @@
{"name":"items_getItemCostHistory","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"37830a1bad13","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemCustomerPart","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4c6e08919580","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemCustomerParts","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"458a8cdb47f2","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"d669af1cc644","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"a45dda8bd7a2","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemFiles","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c8f657a900dd","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemManufacturing","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f399bb7eda67","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getItemMpnsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3ff28fd20707","injectAuth":"companyId","permission":"parts:view","paginates":false},