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.6 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 { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { getLogger } from "@carbon/logger";
import { type JSONContent, RecordOutlet, VStack } from "@carbon/react";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
import {
  getLinkedSupplierQuotes,
  getPurchasingRFQ,
  getPurchasingRFQLines,
  getPurchasingRFQSuppliersWithLinks,
  getSupplierInteractionDocuments
} from "~/modules/purchasing/purchasing.service";
import type { PurchasingRFQLine } from "~/modules/purchasing/types";
import {
  PurchasingRFQExplorer,
  PurchasingRFQHeader,
  PurchasingRFQProperties
} from "~/modules/purchasing/ui/PurchasingRfq";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";

const logger = getLogger("erp", "purchasing-rfq");

export const handle: Handle = {
  realtime: [
    { table: "purchasingRfq", column: "id", param: "rfqId" },
    { table: "purchasingRfqLine", column: "purchasingRfqId", param: "rfqId" }
  ],
  breadcrumb: detailBreadcrumb(
    { breadcrumb: msg`RFQs`, to: path.to.purchasingRfqs },
    (data) => data?.rfqSummary?.rfqId
  ),
  module: "purchasing"
};

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

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

  const serviceRole = await getCarbonServiceRole();

  const [rfqSummary, lines, suppliers, linkedQuotes] = await Promise.all([
    getPurchasingRFQ(serviceRole, rfqId),
    getPurchasingRFQLines(serviceRole, rfqId),
    getPurchasingRFQSuppliersWithLinks(serviceRole, rfqId),
    getLinkedSupplierQuotes(serviceRole, rfqId)
  ]);

  if (rfqSummary.error) {
    throw redirect(
      path.to.purchasingRfqs,
      await flash(
        request,
        error(rfqSummary.error, "Failed to load purchasing RFQ summary")
      )
    );
  }

  // The service role bypasses RLS and rfqId comes from the URL.
  if (rfqSummary.data.companyId !== companyId) {
    logger.error("Purchasing RFQ not found for company", { companyId, rfqId });
    throw redirect(path.to.purchasingRfqs);
  }

  if (lines.error) {
    throw redirect(
      path.to.purchasingRfqs,
      await flash(request, error(lines.error, "Failed to load RFQ lines"))
    );
  }

  // Extract supplier quotes from the linked data
  const supplierQuotes =
    linkedQuotes.data?.map((link) => link.supplierQuote).filter(Boolean) ?? [];

  // Create a map of supplierId -> quote externalLinkId for the header
  const quoteExternalLinkBySupplierId = new Map<string, string>();
  for (const quote of supplierQuotes) {
    if (quote && (quote as any).supplierId && (quote as any).externalLinkId) {
      quoteExternalLinkBySupplierId.set(
        (quote as any).supplierId,
        (quote as any).externalLinkId
      );
    }
  }

  return {
    rfqSummary: rfqSummary.data,
    lines:
      lines.data.map((line: PurchasingRFQLine) => ({
        ...line,
        id: line.id ?? "",
        order: line.order ?? 0,
        purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode ?? "",
        inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode ?? "",
        conversionFactor: line.conversionFactor ?? 1,
        description: line.description ?? "",
        externalNotes: (line.externalNotes ?? {}) as JSONContent,
        internalNotes: (line.internalNotes ?? {}) as JSONContent,
        itemId: line.itemId ?? "",
        quantity: line.quantity ?? [1]
      })) ?? [],
    suppliers:
      suppliers.data?.map((s) => ({
        id: s.id,
        supplierId: s.supplierId,
        supplier: s.supplier,
        // Use the supplier quote's external link (for sharing), not the rfqSupplier's
        quoteExternalLinkId: quoteExternalLinkBySupplierId.get(s.supplierId)
      })) ?? [],
    linkedQuotes: supplierQuotes,
    // Use rfqId as the interaction ID for document storage
    files: getSupplierInteractionDocuments(serviceRole, companyId, rfqId)
  };
}

export default function PurchasingRFQRoute() {
  const { rfqId } = useParams();
  if (!rfqId) throw new Error("Could not find rfqId");

  return (
    <PanelProvider>
      <div className="flex flex-col h-[calc(100dvh-var(--topbar-height)-var(--content-inset))] overflow-hidden w-full">
        <PurchasingRFQHeader />
        <div className="flex h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))] overflow-hidden w-full">
          <div className="flex flex-grow overflow-hidden">
            <ResizablePanels
              explorer={<PurchasingRFQExplorer />}
              content={
                <div className="bg-card h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full">
                  <VStack spacing={4} className="p-4">
                    <RecordOutlet />
                  </VStack>
                </div>
              }
              properties={<PurchasingRFQProperties key={rfqId} />}
            />
          </div>
        </div>
      </div>
    </PanelProvider>
  );
}