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.

5.1 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 { ProductLabelPDF } from "@carbon/documents/pdf";
import { getLogger } from "@carbon/logger";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
import { getShipmentTracking } from "~/modules/inventory/inventory.utils";
import {
  getCompany,
  getCompanyLogoForLabel,
  getCompanySettings,
  getDocumentTemplateConfig,
  resolveLabelLogo
} from "~/modules/settings/settings.service";

const logger = getLogger("erp", "id-labels-pdf");

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

  const { id } = params;
  if (!id) throw new Error("Could not find id");

  const [company, companySettings, shipmentTracking] = await Promise.all([
    getCompany(client, companyId),
    getCompanySettings(client, companyId),
    getShipmentTracking(client, id, companyId)
  ]);

  if (company.error) {
    logger.error(company.error);
    throw new Error("Failed to load company");
  }

  // Get the label size from query params or default to avery5163
  const url = new URL(request.url);
  const labelParam = url.searchParams.get("labelSize");
  const lineIdParam = url.searchParams.get("lineId");
  const labelSizeId =
    labelParam || companySettings.data?.productLabelSize || "avery5163";

  // Find the label size configuration
  let labelSize = labelSizes.find((size) => size.id === labelSizeId);

  if (!labelSize) {
    throw new Error("Invalid label size");
  }

  let filteredTracking = shipmentTracking.data;

  // Filter by lineId if provided
  if (lineIdParam) {
    filteredTracking =
      filteredTracking?.filter(
        (tracking) =>
          tracking.attributes &&
          (tracking.attributes as TrackedEntityAttributes)["Shipment Line"] ===
            lineIdParam
      ) ?? [];
  }

  // Labels are for the RETAINED shelf lots, not the shipped portions. New
  // convention: the shipped child carries "Split From Entity ID" → its parent
  // is the retained lot. Legacy rows: the shipped original carries
  // "Split Entity ID" → the remainder it points at is the retained lot.
  const itemEntityIds = filteredTracking
    ?.flatMap((tracking) => {
      const attributes = (tracking.attributes ?? {}) as TrackedEntityAttributes;
      const retainedId =
        attributes["Split From Entity ID"] ?? attributes["Split Entity ID"];
      return retainedId ? [retainedId] : [];
    })
    .sort((a, b) => a.localeCompare(b))
    .filter(Boolean);

  if (!itemEntityIds || itemEntityIds.length === 0) {
    return new Response(
      `No items found for shipment ${id}${
        lineIdParam ? ` and line ${lineIdParam}` : ""
      }`,
      { status: 404 }
    );
  }

  const trackedEntities = await client
    .from("trackedEntity")
    .select("*")
    .in("id", itemEntityIds)
    .eq("companyId", companyId);

  if (!trackedEntities.data || trackedEntities.data.length === 0) {
    return new Response(
      `No items found for shipment ${id}${
        lineIdParam ? ` and line ${lineIdParam}` : ""
      }`,
      { status: 404 }
    );
  }

  const items = trackedEntities.data
    .map((tracking) => ({
      itemId: tracking.sourceDocumentReadableId ?? "",
      revision: "0",
      number: tracking.readableId ?? "",
      trackedEntityId: tracking.id,
      quantity: tracking.quantity,
      trackingType: tracking.quantity > 1 ? "Batch" : "Serial"
    }))
    .sort((a, b) => {
      if (a.itemId === b.itemId) {
        return a.number.localeCompare(b.number);
      }
      return a.itemId.localeCompare(b.itemId);
    });

  if (!Array.isArray(items) || items.length === 0) {
    return new Response(
      `No items found for shipment ${id}${
        lineIdParam ? ` and line ${lineIdParam}` : ""
      }`,
      { status: 404 }
    );
  }

  const template = await getDocumentTemplateConfig(
    client,
    companyId,
    "trackingLabel"
  );

  const companyLogo = await getCompanyLogoForLabel(client, companyId);
  const logo = await resolveLabelLogo(companyLogo, template, labelSize);

  const stream = await renderToStream(
    <ProductLabelPDF
      items={items ?? []}
      labelSize={labelSize}
      template={template}
      company={company.data as any}
      logo={logo}
    />
  );

  const body: Buffer = await new Promise((resolve, reject) => {
    const buffers: Uint8Array[] = [];
    stream.on("data", (data) => {
      buffers.push(data);
    });
    stream.on("end", () => {
      resolve(Buffer.concat(buffers));
    });
    stream.on("error", reject);
  });

  const headers = new Headers({
    "Content-Type": "application/pdf",
    "Content-Disposition": `inline; filename="${company.data.name} - Shipment Labels.pdf"`
  });
  return new Response(new Uint8Array(body), { status: 200, headers });
}