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.

7.3 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.

import { requirePermissions } from "@carbon/auth/auth.server";
import type { LoaderFunctionArgs } from "react-router";
import { flattenTree } from "~/components/TreeView";
import type { BomItemAttributes } from "~/modules/items/items.service";
import { getBomItemAttributes } from "~/modules/items/items.service";
import { getJobMethodTree } from "~/modules/production/production.utils";
import type { JobOperation } from "~/modules/production/types";
import type { BomOperation } from "~/utils/bom";
import {
  calculateMadePartCosts,
  calculateTotalQuantity,
  generateBomIds,
  stripCsvFormulaPrefix
} from "~/utils/bom";
import { makeDurations } from "~/utils/duration";

const bomHeaders = [
  "ID",
  "Item ID",
  "Revision",
  "Description",
  "Quantity",
  "Total",
  "Unit Cost",
  "Total Cost",
  "UOM",
  "Method Type",
  "Item Type",
  "Tracking Type",
  "Replenishment",
  "Item Group",
  "Batch Size",
  "Lead Time",
  "Level",
  "Version"
];

const operationHeaders = [
  "Operation",
  "Process",
  "Work Center",
  "Operation Type",
  "Setup Time",
  "Setup Unit",
  "Labor Time",
  "Labor Unit",
  "Machine Time",
  "Machine Unit",
  "Total Duration x 1 (ms)",
  "Total Duration x 100 (ms)",
  "Total Duration x 1000 (ms)"
];

export async function loader({ request, params }: LoaderFunctionArgs) {
  const { client, companyId } = await requirePermissions(request, {
    view: "parts"
  });

  const { id } = params;
  const withOperations = request.url.includes("withOperations=true");

  const headers =
    (withOperations
      ? [...bomHeaders, ...operationHeaders].join(",")
      : bomHeaders.join(",")) + "\n";

  if (!id) {
    return new Response(headers, {
      headers: {
        "Content-Type": "text/csv",
        "Content-Disposition": "attachment; filename=bom.csv"
      }
    });
  }

  const methodTree = await getJobMethodTree(client, id);
  if (methodTree.error) {
    return new Response(headers, {
      headers: {
        "Content-Type": "text/csv",
        "Content-Disposition": "attachment; filename=bom.csv"
      }
    });
  }

  const fileName = `${methodTree.data[0].data.itemReadableId}-bom.csv`;

  const methods =
    methodTree.data.length > 0 ? flattenTree(methodTree.data[0]) : [];

  const makeMethodIds = [
    ...new Set(methods.map((method) => method.data.jobMakeMethodId))
  ];

  const itemIds = [...new Set(methods.map((method) => method.data.itemId))];

  // Get the job quantity for batch size calculation
  const rootNode = methods[0];
  const jobId = rootNode?.data.jobId;

  const [methodOperations, jobResult, itemAttributesResult] = await Promise.all(
    [
      client
        .from("jobOperation")
        .select(
          "*, ...process(processName:name), ...workCenter(workCenterName:name), ...jobMakeMethod(parentMaterialId, item(readableIdWithRevision))"
        )
        .in("jobMakeMethodId", makeMethodIds)
        .eq("companyId", companyId),
      jobId
        ? client.from("job").select("quantity").eq("id", jobId).single()
        : null,
      getBomItemAttributes(client, companyId, itemIds)
    ]
  );

  const itemAttributes =
    itemAttributesResult.data ?? new Map<string, BomItemAttributes>();

  const batchSizesByItemId = new Map<string, number>();
  if (rootNode && jobResult?.data?.quantity) {
    batchSizesByItemId.set(rootNode.data.itemId, jobResult.data.quantity);
  }

  let operationsByMakeMethodId: Record<
    string,
    Array<
      JobOperation & {
        processName: string;
        workCenterName: string | null;
      }
    >
  > = {};

  if (methodOperations.data) {
    operationsByMakeMethodId = methodOperations.data.reduce<
      typeof operationsByMakeMethodId
    >((acc, operation) => {
      const transformedOperation = {
        ...operation,
        jobMakeMethod: operation.item
          ? {
              parentMaterialId: operation.parentMaterialId,
              item: {
                readableIdWithRevision: operation.item.readableIdWithRevision
              }
            }
          : null
      };
      acc[operation.jobMakeMethodId ?? ""] = [
        ...(acc[operation.jobMakeMethodId ?? ""] || []),
        transformedOperation
      ];
      return acc;
    }, {});
  }

  // Build BomOperation map for cost calculation
  const bomOperationsByKey: Record<string, BomOperation[]> = {};
  for (const [key, ops] of Object.entries(operationsByMakeMethodId)) {
    bomOperationsByKey[key] = ops.map((op) => ({
      operationType: op.operationType,
      setupTime: op.setupTime,
      setupUnit: op.setupUnit,
      laborTime: op.laborTime,
      laborUnit: op.laborUnit,
      machineTime: op.machineTime,
      machineUnit: op.machineUnit,
      operationUnitCost: op.operationUnitCost,
      operationMinimumCost: op.operationMinimumCost,
      laborRate: op.laborRate ?? 0,
      machineRate: op.machineRate ?? 0,
      overheadRate: op.overheadRate ?? 0
    }));
  }

  const computedCosts = calculateMadePartCosts(
    methods,
    bomOperationsByKey,
    (node) => node.data.jobMaterialMakeMethodId,
    batchSizesByItemId
  );

  const bomIds = generateBomIds(methods);

  let csv = headers;

  methods.forEach((node, index) => {
    const total = calculateTotalQuantity(node, methods);
    const unitCost = computedCosts.get(node.id) ?? node.data.unitCost ?? 0;
    const totalCost = total * unitCost;

    const attrs = itemAttributes.get(node.data.itemId);
    const revision = attrs?.revision || "0";
    const itemGroup = stripCsvFormulaPrefix(
      attrs?.itemPostingGroup ?? ""
    ).replace(/"/g, '""');

    csv += `${bomIds[index]},${
      attrs?.readableId ?? node.data.itemReadableId
    },${revision},"${node.data.description?.replace(/"/g, '""')}",${
      node.data.quantity
    },${total},${unitCost},${totalCost},,${node.data.methodType},${
      node.data.itemType
    },${attrs?.itemTrackingType ?? ""},${
      attrs?.replenishmentSystem ?? ""
    },"${itemGroup}",${attrs?.lotSize ?? ""},${
      attrs?.leadTime ?? ""
    },${node.level},${node.data.version || ""}\n`;

    if (withOperations) {
      const operations =
        operationsByMakeMethodId[node.data.jobMaterialMakeMethodId];
      if (operations) {
        operations.forEach((operation) => {
          const op1 = makeDurations({ ...operation, operationQuantity: total });
          const op100 = makeDurations({
            ...operation,
            operationQuantity: total * 100
          });
          const op1000 = makeDurations({
            ...operation,
            operationQuantity: total * 1000
          });

          csv += Array(bomHeaders.length).fill(",").join("");
          csv += `${operation.description},${operation.processName},${
            operation.workCenterName ?? ""
          },${operation.operationType},${operation.setupTime},${
            operation.setupUnit
          },${operation.laborTime},${operation.laborUnit},${
            operation.machineTime
          },${operation.machineUnit},${op1.duration},${op100.duration},${
            op1000.duration
          }\n`;
        });
      }
    }
  });

  return new Response(csv, {
    headers: {
      "Content-Type": "text/csv",
      "Content-Disposition": `attachment; filename=${fileName}`
    }
  });
}