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
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
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));
}