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.

23.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 {
  HStack,
  Input,
  InputGroup,
  InputLeftElement,
  RecordOutlet,
  Spinner,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  useRouteData
} from "@carbon/react";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { Suspense, useState } from "react";
import { LuSearch } from "react-icons/lu";
import type { LoaderFunctionArgs } from "react-router";
import { Await, useLoaderData, useParams } from "react-router";
import { ResizablePanels } from "~/components/Layout";
import { flattenTree } from "~/components/TreeView";
import { isChangeNoticeOpen } from "~/modules/items/items.models";
import {
  findChangeNoticesForItemOnce,
  getItemFiles,
  getMakeMethodByIdOnce,
  getMakeMethodsOnce,
  getMethodTree,
  getPartUsedIn,
  getPickMethods,
  getSupplierParts,
  getTool,
  getUnreleasedChangeOrderForItem,
  streamItemSupersession
} from "~/modules/items/items.service";
import type { ItemFile, ToolSummary } from "~/modules/items/types";
import { BoMActions, BoMExplorer } from "~/modules/items/ui/Item";
import type { UsedInNode } from "~/modules/items/ui/Item/UsedIn";
import {
  changeNoticesUsedInNode,
  UsedInSkeleton,
  UsedInTree
} from "~/modules/items/ui/Item/UsedIn";
import { ToolHeader, ToolProperties } from "~/modules/items/ui/Tools";
import { getTagsList } from "~/modules/shared/shared.service";
import { detailBreadcrumb, type Handle } from "~/utils/handle";
import { path } from "~/utils/path";

export const handle: Handle = {
  breadcrumb: detailBreadcrumb(
    { breadcrumb: msg`Tools`, to: path.to.tools },
    (data) => data?.toolSummary?.readableIdWithRevision
  ),
  module: "items"
};

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

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

  const { supersession, supersededBy } = streamItemSupersession(
    client,
    itemId,
    companyId
  );

  const [
    toolSummary,
    supplierParts,
    pickMethods,
    tags,
    allChangeNotices,
    unreleasedChangeOrder
  ] = await Promise.all([
    getTool(client, itemId, companyId),
    getSupplierParts(client, itemId, companyId),
    getPickMethods(client, itemId, companyId),
    getTagsList(client, companyId, "tool"),
    // Every CO, any status; the open subset (which locks manual version/revision
    // creation) is derived below.
    findChangeNoticesForItemOnce(client, { itemId, companyId }),
    // Locks the Active toggle while the change notice that minted this item is
    // still open — release is what activates it.
    getUnreleasedChangeOrderForItem(client, { itemId, companyId })
  ]);

  if (toolSummary.error) {
    throw redirect(
      path.to.items,
      await flash(
        request,
        error(toolSummary.error, "Failed to load tool summary")
      )
    );
  }

  const changeNotices = allChangeNotices.data ?? [];
  const openChangeNotices = changeNotices.filter((cn) =>
    isChangeNoticeOpen(cn.status)
  );

  const url = new URL(request.url);
  const requestedMethodId = url.searchParams.get("methodId");

  const methodTree = getMakeMethodsOnce(client, itemId, companyId).then(
    async (makeMethods) => {
      const makeMethod = requestedMethodId
        ? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??
          makeMethods.data?.find((m) => m.status === "Active") ??
          makeMethods.data?.[0])
        : (makeMethods.data?.find((m) => m.status === "Active") ??
          makeMethods.data?.[0]);
      if (!makeMethod) return null;

      const fullMethod = await getMakeMethodByIdOnce(
        client,
        makeMethod.id,
        companyId
      );
      if (fullMethod.error || !fullMethod.data) return null;

      const tree = await getMethodTree(client, fullMethod.data.id);
      if (tree.error) return null;

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

      return {
        makeMethod: fullMethod.data,
        methods
      };
    }
  );

  return {
    toolSummary: toolSummary.data,
    supersession,
    supersededBy,
    files: getItemFiles(client, itemId, companyId),
    supplierParts: supplierParts.data ?? [],
    pickMethods: pickMethods.data ?? [],
    makeMethods: getMakeMethodsOnce(client, itemId, companyId),
    tags: tags.data ?? [],
    usedIn: getPartUsedIn(client, itemId, companyId),
    methodTree,
    changeNotices,
    openChangeNotices,
    // Fail closed: a lookup we couldn't read can't prove the item is CO-free.
    changeNoticesUnavailable: allChangeNotices.error !== null,
    unreleasedChangeOrder
  };
}

export default function ToolRoute() {
  const { t } = useLingui();
  const { itemId } = useParams();
  if (!itemId) throw new Error("Could not find itemId");

  const toolData = useRouteData<{
    toolSummary: ToolSummary;
    files: Promise<ItemFile[]>;
  }>(path.to.tool(itemId));

  if (!toolData) throw new Error("Could not find tool data");

  const { usedIn, methodTree, changeNotices } = useLoaderData<typeof loader>();

  const isManufactured = toolData.toolSummary?.replenishmentSystem !== "Buy";

  const [filterText, setFilterText] = useState("");

  return (
    <div className="flex flex-col h-[calc(100dvh-var(--topbar-height)-var(--content-inset))] overflow-hidden w-full">
      <ToolHeader key={itemId} />
      <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
            explorerLabel={isManufactured ? t`Manufacturing` : t`Used In`}
            explorer={
              <div className="flex flex-col h-full">
                {isManufactured ? (
                  <Tabs
                    defaultValue="manufacturing"
                    className="flex flex-col h-full"
                  >
                    <div className="px-2 pt-2 flex-shrink-0">
                      <TabsList className="grid grid-cols-2 w-full">
                        <TabsTrigger value="manufacturing">
                          <Trans>Manufacturing</Trans>
                        </TabsTrigger>
                        <TabsTrigger value="used-in">
                          <Trans>Used In</Trans>
                        </TabsTrigger>
                      </TabsList>
                    </div>
                    <HStack className="w-full justify-between flex-shrink-0 p-2 pb-0">
                      <InputGroup size="sm" className="flex flex-grow">
                        <InputLeftElement>
                          <LuSearch className="h-4 w-4" />
                        </InputLeftElement>
                        <Input
                          placeholder={t`Search...`}
                          value={filterText}
                          onChange={(e) => setFilterText(e.target.value)}
                        />
                      </InputGroup>
                      <Suspense fallback={null}>
                        <Await resolve={methodTree}>
                          {(resolved) =>
                            resolved ? (
                              <BoMActions
                                makeMethodId={resolved.makeMethod.id}
                              />
                            ) : null
                          }
                        </Await>
                      </Suspense>
                    </HStack>
                    <div className="flex-1 overflow-y-auto">
                      <TabsContent value="manufacturing">
                        <Suspense
                          fallback={
                            <div className="flex w-full items-center justify-center p-4">
                              <Spinner className="h-6 w-6" />
                            </div>
                          }
                        >
                          <Await resolve={methodTree}>
                            {(resolved) =>
                              resolved ? (
                                <div className="w-full p-2">
                                  <BoMExplorer
                                    itemType="Tool"
                                    makeMethod={resolved.makeMethod}
                                    methods={resolved.methods}
                                    methodId={resolved.makeMethod.id}
                                    filterText={filterText}
                                    hideSearch
                                  />
                                </div>
                              ) : null
                            }
                          </Await>
                        </Suspense>
                      </TabsContent>
                      <TabsContent value="used-in">
                        <Suspense fallback={<UsedInSkeleton />}>
                          <Await resolve={usedIn}>
                            {(resolvedUsedIn) => {
                              const {
                                issues,
                                jobMaterials,
                                jobs,
                                maintenanceDispatchItems,
                                methodMaterials,
                                purchaseOrderLines,
                                receiptLines,
                                quoteLines,
                                quoteMaterials,
                                salesOrderLines,
                                shipmentLines,
                                supplierQuotes,
                                inspections,
                                jobMaterialUsage
                              } = resolvedUsedIn;

                              const tree: UsedInNode[] = [
                                {
                                  key: "issues",
                                  name: t`Issues`,
                                  module: "quality",
                                  children: issues
                                },
                                {
                                  key: "jobs",
                                  name: t`Jobs`,
                                  module: "production",
                                  children: jobs.map((job) => ({
                                    ...job,
                                    methodType: "Make to Order"
                                  }))
                                },
                                {
                                  key: "jobMaterials",
                                  name: t`Job Materials`,
                                  module: "production",
                                  children: jobMaterials
                                },
                                {
                                  key: "maintenanceDispatchItems",
                                  name: t`Maintenance`,
                                  module: "resources",
                                  children: maintenanceDispatchItems
                                },
                                {
                                  key: "methodMaterials",
                                  name: t`Method Materials`,
                                  module: "parts",
                                  // @ts-expect-error
                                  children: methodMaterials
                                },
                                {
                                  key: "purchaseOrderLines",
                                  name: t`Purchase Orders`,
                                  module: "purchasing",
                                  children: purchaseOrderLines.map((po) => ({
                                    ...po,
                                    methodType: "Purchase to Order"
                                  }))
                                },
                                {
                                  key: "receiptLines",
                                  name: t`Receipts`,
                                  module: "inventory",
                                  children: receiptLines.map((receipt) => ({
                                    ...receipt,
                                    methodType: "Pull from Inventory"
                                  }))
                                },
                                {
                                  key: "quoteLines",
                                  name: t`Quotes`,
                                  module: "sales",
                                  children: quoteLines
                                },
                                {
                                  key: "quoteMaterials",
                                  name: t`Quote Materials`,
                                  module: "sales",
                                  children: quoteMaterials?.map((qm) => ({
                                    ...qm,
                                    documentReadableId:
                                      qm.documentReadableId ?? ""
                                  }))
                                },
                                {
                                  key: "salesOrderLines",
                                  name: t`Sales Orders`,
                                  module: "sales",
                                  children: salesOrderLines
                                },
                                {
                                  key: "shipmentLines",
                                  name: t`Shipments`,
                                  module: "inventory",
                                  children: shipmentLines.map((shipment) => ({
                                    ...shipment,
                                    methodType: "Shipment"
                                  }))
                                },
                                {
                                  key: "supplierQuotes",
                                  name: t`Supplier Quotes`,
                                  module: "purchasing",
                                  children: supplierQuotes
                                }
                              ];

                              tree.push({
                                key: "inspections",
                                name: t`Inspections`,
                                module: "quality",
                                children: inspections
                              });

                              tree.push(
                                changeNoticesUsedInNode(
                                  changeNotices,
                                  t`Change Notices`
                                )
                              );

                              return (
                                <UsedInTree
                                  tree={tree}
                                  revisions={toolData.toolSummary?.revisions}
                                  itemReadableId={
                                    toolData.toolSummary?.readableId ?? ""
                                  }
                                  itemReadableIdWithRevision={
                                    toolData.toolSummary
                                      ?.readableIdWithRevision ?? ""
                                  }
                                  jobMaterialUsage={jobMaterialUsage}
                                  filterText={filterText}
                                  hideSearch
                                />
                              );
                            }}
                          </Await>
                        </Suspense>
                      </TabsContent>
                    </div>
                  </Tabs>
                ) : (
                  <>
                    <HStack className="w-full justify-between flex-shrink-0 p-2 pb-0">
                      <InputGroup size="sm" className="flex flex-grow">
                        <InputLeftElement>
                          <LuSearch className="h-4 w-4" />
                        </InputLeftElement>
                        <Input
                          placeholder={t`Search...`}
                          value={filterText}
                          onChange={(e) => setFilterText(e.target.value)}
                        />
                      </InputGroup>
                    </HStack>
                    <div className="flex-1 overflow-y-auto">
                      <Suspense fallback={<UsedInSkeleton />}>
                        <Await resolve={usedIn}>
                          {(resolvedUsedIn) => {
                            const {
                              issues,
                              jobMaterials,
                              jobs,
                              maintenanceDispatchItems,
                              methodMaterials,
                              purchaseOrderLines,
                              receiptLines,
                              quoteLines,
                              quoteMaterials,
                              salesOrderLines,
                              shipmentLines,
                              supplierQuotes,
                              inspections,
                              jobMaterialUsage
                            } = resolvedUsedIn;

                            const tree: UsedInNode[] = [
                              {
                                key: "issues",
                                name: "Issues",
                                module: "quality",
                                children: issues
                              },
                              {
                                key: "jobs",
                                name: "Jobs",
                                module: "production",
                                children: jobs.map((job) => ({
                                  ...job,
                                  methodType: "Make to Order"
                                }))
                              },
                              {
                                key: "jobMaterials",
                                name: "Job Materials",
                                module: "production",
                                children: jobMaterials
                              },
                              {
                                key: "maintenanceDispatchItems",
                                name: "Maintenance",
                                module: "resources",
                                children: maintenanceDispatchItems
                              },
                              {
                                key: "methodMaterials",
                                name: "Method Materials",
                                module: "parts",
                                // @ts-expect-error
                                children: methodMaterials
                              },
                              {
                                key: "purchaseOrderLines",
                                name: "Purchase Orders",
                                module: "purchasing",
                                children: purchaseOrderLines.map((po) => ({
                                  ...po,
                                  methodType: "Purchase to Order"
                                }))
                              },
                              {
                                key: "receiptLines",
                                name: "Receipts",
                                module: "inventory",
                                children: receiptLines.map((receipt) => ({
                                  ...receipt,
                                  methodType: "Pull from Inventory"
                                }))
                              },
                              {
                                key: "quoteLines",
                                name: "Quotes",
                                module: "sales",
                                children: quoteLines
                              },
                              {
                                key: "quoteMaterials",
                                name: "Quote Materials",
                                module: "sales",
                                children: quoteMaterials?.map((qm) => ({
                                  ...qm,
                                  documentReadableId:
                                    qm.documentReadableId ?? ""
                                }))
                              },
                              {
                                key: "salesOrderLines",
                                name: "Sales Orders",
                                module: "sales",
                                children: salesOrderLines
                              },
                              {
                                key: "shipmentLines",
                                name: "Shipments",
                                module: "inventory",
                                children: shipmentLines.map((shipment) => ({
                                  ...shipment,
                                  methodType: "Shipment"
                                }))
                              },
                              {
                                key: "supplierQuotes",
                                name: "Supplier Quotes",
                                module: "purchasing",
                                children: supplierQuotes
                              }
                            ];

                            tree.push({
                              key: "inspections",
                              name: "Inspections",
                              module: "quality",
                              children: inspections
                            });

                            tree.push(
                              changeNoticesUsedInNode(
                                changeNotices,
                                t`Change Notices`
                              )
                            );

                            return (
                              <UsedInTree
                                tree={tree}
                                revisions={toolData.toolSummary?.revisions}
                                itemReadableId={
                                  toolData.toolSummary?.readableId ?? ""
                                }
                                itemReadableIdWithRevision={
                                  toolData.toolSummary
                                    ?.readableIdWithRevision ?? ""
                                }
                                jobMaterialUsage={jobMaterialUsage}
                                filterText={filterText}
                                hideSearch
                              />
                            );
                          }}
                        </Await>
                      </Suspense>
                    </div>
                  </>
                )}
              </div>
            }
            content={
              <div className="bg-card h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))] overflow-y-auto scrollbar-hide w-full">
                <RecordOutlet />
              </div>
            }
            properties={<ToolProperties key={itemId} />}
          />
        </div>
      </div>
    </div>
  );
}