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.

2.4 KB
Raw Blame
// 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.

// Pro-rata split of one physical material pick across a batch's member
// operations, weighted by each member's REMAINING requirement so a multi-lot
// pick sequence converges on exactly the per-member BOM quantities.
// See .ai/specs/2026-09-16-batch-materials-and-output-lots.md.

import {
  distributeRoundingResidual,
  EPSILON,
  round
} from "@carbon/database/precision";

export interface PickMember {
  jobOperationId: string;
  /** This member's remaining requirement for the picked item (estimated − already consumed). */
  remaining: number;
}

export interface PickShare {
  jobOperationId: string;
  quantity: number;
}

/**
 * Split `pickedQuantity` across members pro-rata by remaining requirement.
 * Members with no remaining requirement are skipped; the returned shares are
 * rounded at internal scale and sum EXACTLY to `pickedQuantity`
 * (largest-remainder via distributeRoundingResidual — parts are never rounded
 * independently). Throws when nothing remains or the pick exceeds the total
 * remaining; callers surface the message verbatim.
 */
export function splitPickAcrossMembers(
  members: PickMember[],
  pickedQuantity: number
): PickShare[] {
  if (!Number.isFinite(pickedQuantity) || pickedQuantity <= 0) {
    throw new Error("Pick quantity must be greater than zero");
  }

  const open = members.filter((m) => m.remaining > 0);
  const exactRemaining = open.reduce((sum, m) => sum + m.remaining, 0);
  // Compared at internal scale: a requirement can carry more digits than a
  // quantity input accepts (24 mg in KG is 0.000024), so the exact figure can
  // never be picked; what is left below scale counts as covered.
  const totalRemaining = round(exactRemaining);
  if (open.length === 0 || totalRemaining <= 0) {
    throw new Error("No member operation still requires this item");
  }
  if (pickedQuantity > totalRemaining + EPSILON) {
    throw new Error(
      `Pick of ${pickedQuantity} exceeds the batch's remaining requirement of ${totalRemaining}`
    );
  }

  const exact = open.map(
    (m) => (pickedQuantity * m.remaining) / exactRemaining
  );
  const shares = distributeRoundingResidual(exact, pickedQuantity);

  return open.map((m, i) => ({
    jobOperationId: m.jobOperationId,
    quantity: shares[i] ?? 0
  }));
}