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 { flash } from "@carbon/auth/session.server";
import { RecordOutlet, VStack } from "@carbon/react";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout";
import { getCurrencyByCode } from "~/modules/accounting/accounting.service";
import {
  getCompanyHasOpenCredits,
  getPurchaseInvoice,
  getPurchaseInvoiceDelivery,
  getPurchaseInvoiceLines
} from "~/modules/invoicing/invoicing.service";
import { PurchaseInvoiceHeader } from "~/modules/invoicing/ui";
import PurchaseInvoiceExplorer from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer";
import PurchaseInvoiceProperties from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties";
import {
  getSupplier,
  getSupplierInteraction,
  getSupplierInteractionDocuments
} from "~/modules/purchasing/purchasing.service";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path, requestReferrer } from "~/utils/path";

export const handle: Handle = {
  realtime: [
    { table: "purchaseInvoice", column: "id", param: "invoiceId" },
    { table: "purchaseInvoiceLine", column: "invoiceId", param: "invoiceId" },
    // What is applied to this invoice, and the payments behind it: voiding a
    // payment changes the payment row only.
    {
      table: "invoiceSettlement",
      column: "targetPurchaseInvoiceId",
      param: "invoiceId"
    },
    { table: "payment", column: "targetPurchaseInvoiceId", param: "invoiceId" }
  ],
  breadcrumb: detailBreadcrumb(
    { breadcrumb: msg`Purchasing Invoices`, to: path.to.invoicingPurchasing },
    (data) => data?.purchaseInvoice?.invoiceId
  ),
  module: "invoicing"
};

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

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

  const [purchaseInvoice, purchaseInvoiceLines, purchaseInvoiceDelivery] =
    await Promise.all([
      getPurchaseInvoice(client, invoiceId),
      getPurchaseInvoiceLines(client, invoiceId),
      getPurchaseInvoiceDelivery(client, invoiceId)
    ]);

  if (purchaseInvoice.error) {
    throw redirect(
      path.to.invoicingPurchasing,
      await flash(
        request,
        error(purchaseInvoice.error, "Failed to load purchase invoice")
      )
    );
  }

  const [supplier, interaction, orgHasCredits, currency, rampMapping] =
    await Promise.all([
      purchaseInvoice.data?.supplierId
        ? getSupplier(client, purchaseInvoice.data.supplierId)
        : null,
      getSupplierInteraction(
        client,
        purchaseInvoice.data.supplierInteractionId!
      ),
      getCompanyHasOpenCredits(client, companyId, "purchase"),
      purchaseInvoice.data?.currencyCode
        ? getCurrencyByCode(
            client,
            companyGroupId,
            purchaseInvoice.data.currencyCode
          )
        : null,
      // Ramp origin/sync badge. Read via the user-scoped client — if RLS denies
      // (or there is no mapping), fall back to null silently.
      client
        .from("externalIntegrationMapping")
        .select("id, externalId, metadata")
        .eq("companyId", companyId)
        .eq("integration", "ramp")
        .eq("entityType", "bill")
        .eq("entityId", invoiceId)
        .maybeSingle()
    ]);

  return {
    purchaseInvoice: purchaseInvoice.data,
    currency: currency?.data ?? null,
    purchaseInvoiceLines: purchaseInvoiceLines.data ?? [],
    purchaseInvoiceDelivery: purchaseInvoiceDelivery.data,
    files: getSupplierInteractionDocuments(
      client,
      companyId,
      purchaseInvoice.data.supplierInteractionId!
    ),
    interaction: interaction.data,
    supplier: supplier?.data ?? null,
    orgHasCredits,
    rampMapping: rampMapping?.data ?? null
  };
}

export async function action({ request }: ActionFunctionArgs) {
  throw redirect(requestReferrer(request) ?? new URL(request.url).pathname);
}

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

  return (
    <PanelProvider>
      <div className="flex flex-col h-[calc(100dvh-var(--topbar-height)-var(--content-inset))] overflow-hidden w-full">
        <PurchaseInvoiceHeader />
        <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={<PurchaseInvoiceExplorer />}
              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={<PurchaseInvoiceProperties key={invoiceId} />}
            />
          </div>
        </div>
      </div>
    </PanelProvider>
  );
}