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.2 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 type { CreatableMultiSelectProps } from "@carbon/form";
import { CreatableMultiSelect } from "@carbon/form";
import {
  Button,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  useDisclosure
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { useMemo, useRef, useState } from "react";
import ConsumableForm from "~/modules/items/ui/Consumables/ConsumableForm";
import MaterialForm from "~/modules/items/ui/Materials/MaterialForm";
import PartForm from "~/modules/items/ui/Parts/PartForm";
import ServiceForm from "~/modules/items/ui/Services/ServiceForm";
import ToolForm from "~/modules/items/ui/Tools/ToolForm";
import { itemType } from "~/modules/shared/shared.models";
import type { ItemType } from "~/modules/shared/types";
import { useItems } from "~/stores";
import { MethodItemTypeIcon } from "../Icons";
import { useEmptyState } from "./emptyStates";

type ItemsSelectProps = Omit<CreatableMultiSelectProps, "options">;

const Items = (props: ItemsSelectProps) => {
  const { t } = useLingui();
  const translateType = (type: ItemType) => {
    switch (type) {
      case "Part":
        return t`Part`;
      case "Material":
        return t`Material`;
      case "Tool":
        return t`Tool`;
      case "Consumable":
        return t`Consumable`;
      case "Service":
        return t`Service`;
      default:
        return type;
    }
  };
  const [items] = useItems();
  const selectTypeModal = useDisclosure();
  const newItemsModal = useDisclosure();
  const [created, setCreated] = useState<string>("");
  const [type, setType] = useState<ItemType>("Part");
  const triggerRef = useRef<HTMLButtonElement>(null);

  const options = useMemo(
    () =>
      items
        .filter((item) => item.active)
        .map((item) => ({
          value: item.id,
          label: item.readableIdWithRevision,
          helper: item.name
        })),
    [items]
  );

  const handleCreateClose = () => {
    setCreated("");
    newItemsModal.onClose();
    triggerRef.current?.click();
  };

  const storeEmptyMessage = useEmptyState("item", {
    onCreate: () => selectTypeModal.onOpen()
  });
  // Suppress when the store has inactive items but no active ones (filter
  // narrowed to zero) — see Item.tsx for the same pattern.
  const emptyMessage = items.length === 0 ? storeEmptyMessage : undefined;

  return (
    <>
      <CreatableMultiSelect
        ref={triggerRef}
        options={options}
        {...props}
        label={props?.label ?? "Items"}
        createLabel={t`Item`}
        emptyMessage={emptyMessage}
        onCreateOption={(value) => {
          setCreated(value);
          selectTypeModal.onOpen();
        }}
      />

      {selectTypeModal.isOpen && (
        <Modal
          open
          onOpenChange={(open) => {
            if (!open) selectTypeModal.onClose();
          }}
        >
          <ModalContent>
            <ModalHeader>
              <ModalTitle>
                <Trans>Select Item Type</Trans>
              </ModalTitle>
            </ModalHeader>
            <ModalBody>
              <div className="grid grid-cols-1 gap-4">
                {itemType.map((option) => (
                  <Button
                    key={option}
                    leftIcon={<MethodItemTypeIcon type={option} />}
                    className="flex w-full"
                    variant={type === option ? "primary" : "secondary"}
                    size="lg"
                    onClick={() => setType(option)}
                  >
                    {translateType(option)}
                  </Button>
                ))}
              </div>
            </ModalBody>
            <ModalFooter>
              <Button
                variant="secondary"
                onClick={() => selectTypeModal.onClose()}
              >
                <Trans>Cancel</Trans>
              </Button>
              <Button
                onClick={() => {
                  selectTypeModal.onClose();
                  newItemsModal.onOpen();
                }}
              >
                <Trans>Create</Trans>
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
      )}

      {type === "Part" && newItemsModal.isOpen && (
        <PartForm
          type="modal"
          onClose={handleCreateClose}
          initialValues={{
            id: "",
            revision: "0",
            name: created,
            description: "",
            itemTrackingType: "Inventory",
            replenishmentSystem: "Make",
            unitOfMeasureCode: "EA",
            defaultMethodType: "Make to Order",
            unitCost: 0,
            lotSize: 0,
            shelfLifeCalculateFromBom: false,
            tags: []
          }}
        />
      )}
      {type === "Material" && newItemsModal.isOpen && (
        <MaterialForm
          type="modal"
          onClose={handleCreateClose}
          initialValues={{
            id: "",
            name: created,
            description: "",
            materialFormId: "",
            materialSubstanceId: "",
            itemTrackingType: "Inventory",
            unitOfMeasureCode: "EA",
            replenishmentSystem: "Buy",
            defaultMethodType: "Pull from Inventory",
            unitCost: 0,
            shelfLifeCalculateFromBom: false,
            tags: []
          }}
        />
      )}
      {type === "Tool" && newItemsModal.isOpen && (
        <ToolForm
          type="modal"
          onClose={handleCreateClose}
          initialValues={{
            id: "",
            revision: "0",
            name: created,
            description: "",
            itemTrackingType: "Inventory",
            unitOfMeasureCode: "EA",
            replenishmentSystem: "Buy",
            defaultMethodType: "Pull from Inventory",
            unitCost: 0,
            shelfLifeCalculateFromBom: false,
            tags: []
          }}
        />
      )}
      {type === "Consumable" && newItemsModal.isOpen && (
        <ConsumableForm
          type="modal"
          onClose={handleCreateClose}
          initialValues={{
            id: "",
            name: created,
            description: "",
            itemTrackingType: "Non-Inventory",
            unitOfMeasureCode: "EA",
            replenishmentSystem: "Buy",
            defaultMethodType: "Pull from Inventory",
            unitCost: 0,
            shelfLifeCalculateFromBom: false,
            tags: []
          }}
        />
      )}
      {type === "Service" && newItemsModal.isOpen && (
        <ServiceForm
          type="modal"
          onClose={handleCreateClose}
          initialValues={{
            name: created,
            description: "",
            itemTrackingType: "Non-Inventory",
            unitOfMeasureCode: "EA",
            replenishmentSystem: "Buy",
            defaultMethodType: "Purchase to Order",
            unitCost: 0,
            shelfLifeCalculateFromBom: false,
            tags: []
          }}
        />
      )}
    </>
  );
};

Items.displayName = "Items";

export default Items;