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.8 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 {
  Badge,
  MENU_ITEM_SHORTCUTS,
  MenuIcon,
  MenuItem,
  useDisclosure
} from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo, useState } from "react";
import { LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate, useParams } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions, useUrlParams } from "~/hooks";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
import type { ProductionQuantity, ScrapReason } from "../../types";

type ProductionQuantitiesTableProps = {
  data: ProductionQuantity[];
  count: number;
  // The loader's cursor for the next page (infinite scroll).
  nextCursor: string | null;
  operations: { id: string; description: string | null }[];
  scrapReasons: ScrapReason[];
};

const ProductionQuantitiesTable = memo(
  ({
    data,
    count,
    nextCursor,
    operations,
    scrapReasons
  }: ProductionQuantitiesTableProps) => {
    const { jobId } = useParams();
    const { t } = useLingui();
    if (!jobId) throw new Error("Job ID is required");
    const [people] = usePeople();

    const columns = useMemo<ColumnDef<ProductionQuantity>[]>(() => {
      return [
        {
          accessorKey: "jobOperationId",
          header: t`Operation`,
          cell: ({ row }) => (
            <Hyperlink to={row.original.id}>
              {row.original.jobOperation?.description ?? null}
            </Hyperlink>
          ),
          meta: {
            mobile: "P1",
            filter: {
              type: "static",
              options: operations.map((operation) => ({
                value: operation.id,
                label: <Enumerable value={operation.description} />
              }))
            }
          }
        },
        {
          id: "item",
          header: t`Item`,
          cell: ({ row }) => {
            return row.original.jobOperation?.jobMakeMethod?.item
              ?.readableIdWithRevision;
          }
        },
        {
          accessorKey: "createdBy",
          header: t`Employee`,
          cell: ({ row }) => (
            <EmployeeAvatar employeeId={row.original.createdBy} />
          ),
          meta: {
            mobile: "P3",
            filter: {
              type: "static",
              options: people.map((employee) => ({
                value: employee.id,
                label: <Enumerable value={employee.name} />
              }))
            }
          }
        },
        {
          accessorKey: "type",
          header: t`Type`,
          cell: ({ row }) => (
            <Badge
              variant={
                row.original.type === "Production"
                  ? "green"
                  : row.original.type === "Rework"
                    ? "orange"
                    : "red"
              }
            >
              {row.original.type}
            </Badge>
          ),
          meta: {
            mobile: "P2",
            filter: {
              type: "static",
              options: ["Production", "Rework", "Scrap"].map((type) => ({
                value: type,
                label: (
                  <Badge
                    variant={
                      type === "Production"
                        ? "green"
                        : type === "Rework"
                          ? "orange"
                          : "red"
                    }
                  >
                    {type}
                  </Badge>
                )
              }))
            }
          }
        },
        {
          accessorKey: "quantity",
          header: t`Quantity`,
          cell: ({ row }) => row.original.quantity,
          meta: { mobile: "P2" }
        },
        {
          accessorKey: "scrapReasonId",
          header: t`Scrap Reason`,
          cell: ({ row }) => {
            const scrapReason = scrapReasons.find(
              (reason) => reason.id === row.original.scrapReasonId
            );
            return <Enumerable value={scrapReason?.name ?? ""} />;
          },
          meta: {
            filter: {
              type: "static",
              options: scrapReasons?.map((reason) => ({
                value: reason.id,
                label: <Enumerable value={reason.name ?? ""} />
              }))
            }
          }
        },
        {
          accessorKey: "notes",
          header: t`Notes`,
          cell: ({ row }) => (
            <span className="max-w-[200px] truncate block">
              {row.original.notes}
            </span>
          )
        },
        {
          accessorKey: "createdAt",
          header: t`Created At`,
          cell: ({ row }) => (
            <DateTime value={row.original.createdAt} variant="absolute" />
          )
        }
      ];
    }, [operations, people, scrapReasons, t]);

    const permissions = usePermissions();

    const deleteModal = useDisclosure();
    const [selectedEvent, setSelectedEvent] =
      useState<ProductionQuantity | null>(null);

    const onDelete = (data: ProductionQuantity) => {
      setSelectedEvent(data);
      deleteModal.onOpen();
    };

    const onDeleteCancel = () => {
      setSelectedEvent(null);
      deleteModal.onClose();
    };

    const navigate = useNavigate();
    const [params] = useUrlParams();

    // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
    const renderContextMenu = useCallback<
      (row: ProductionQuantity) => JSX.Element
    >(
      (row) => (
        <>
          <MenuItem
            shortcut={MENU_ITEM_SHORTCUTS.edit}
            disabled={!permissions.can("update", "production")}
            onClick={() => navigate(row.id)}
          >
            <MenuIcon icon={<LuPencil />} />
            Edit Quantity
          </MenuItem>
          <MenuItem
            shortcut={MENU_ITEM_SHORTCUTS.delete}
            destructive
            disabled={!permissions.can("delete", "production")}
            onClick={() => onDelete(row)}
          >
            <MenuIcon icon={<LuTrash />} />
            Delete Quantity
          </MenuItem>
        </>
      ),

      [permissions]
    );

    return (
      <>
        <Table<ProductionQuantity>
          compact
          count={count}
          // Scoped to one job: no list registry entry, so no `listKey`.
          infinite={{ dataKey: "events", nextCursor }}
          columns={columns}
          data={data}
          primaryAction={
            permissions.can("create", "production") && (
              <New
                label={t`Production Quantity`}
                to={`new?${params.toString()}`}
              />
            )
          }
          renderContextMenu={renderContextMenu}
          title={t`Production Quantities`}
        />
        {deleteModal.isOpen && selectedEvent && (
          <ConfirmDelete
            action={path.to.deleteProductionQuantity(selectedEvent.id)}
            isOpen
            name={`${
              selectedEvent.jobOperation?.description ?? "Operation"
            } by ${
              people.find((p) => p.id === selectedEvent.createdBy)?.name ??
              "Unknown Employee"
            }`}
            text="Are you sure you want to delete this production quantity? This action cannot be undone."
            onCancel={onDeleteCancel}
            onSubmit={onDeleteCancel}
          />
        )}
      </>
    );
  }
);

ProductionQuantitiesTable.displayName = "ProductionQuantitiesTable";

export default ProductionQuantitiesTable;