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.

40.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 { useCarbon } from "@carbon/auth";
import { useRuleViolations } from "@carbon/ee/rules";
import { Combobox, ValidatedForm } from "@carbon/form";
import {
  Alert,
  AlertTitle,
  Badge,
  cn,
  FormControl,
  FormLabel,
  HStack,
  IconButton,
  Input,
  Label,
  ModalCard,
  ModalCardBody,
  ModalCardContent,
  ModalCardDescription,
  ModalCardFooter,
  ModalCardHeader,
  ModalCardProvider,
  ModalCardTitle,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  toast,
  useDisclosure,
  useMount,
  VStack
} from "@carbon/react";
import {
  distinctItemText,
  getItemReadableId,
  INPUT_FORMAT,
  INPUT_STEP,
  taxableBase,
  taxPairFromPercent
} from "@carbon/utils";
import { parseDate } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import {
  LuBox,
  LuChevronRight,
  LuCircleAlert,
  LuLandmark,
  LuPlus,
  LuTruck
} from "react-icons/lu";
import { useParams } from "react-router";
import type { z } from "zod";
import { MethodIcon } from "~/components";
import {
  CustomFormFields,
  DatePicker,
  Hidden,
  Item,
  Location,
  Number,
  NumberControlled,
  SelectControlled,
  StorageUnit,
  Submit,
  TaxFields,
  useTaxPair
} from "~/components/Form";
import { itemTypeLabel } from "~/components/Form/itemTypeLabel";
import {
  useCurrencyDecimals,
  useCurrencyFormatter,
  usePercentFormatter,
  usePermissions,
  useRouteData,
  useUser
} from "~/hooks";
import { salesInvoiceLineValidator } from "~/modules/invoicing/invoicing.models";
import type { SalesInvoice } from "~/modules/invoicing/types";
import { itemType, methodType } from "~/modules/shared/shared.models";
import type { ItemType } from "~/modules/shared/types";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { isSalesInvoiceLocked } from "../../invoicing.models";
import ContractInvoiceLineSource from "./ContractInvoiceLineSource";
import RentalInvoiceLineSummary from "./RentalInvoiceLineSummary";

/** The unit price after a percent-points discount. An emptied discount field
 *  commits NaN, which reads as no discount rather than poisoning the tax base. */
function netUnitPrice(unitPrice: number, discountPoints: number) {
  const discount = globalThis.Number.isFinite(discountPoints)
    ? discountPoints
    : 0;
  return unitPrice * (1 - discount / 100);
}

type SalesInvoiceLineFormProps = {
  initialValues: z.infer<typeof salesInvoiceLineValidator> & {
    taxPercent?: number;
    assetReadableId?: string;
    assetName?: string;
  };
  isSalesOrderLine?: boolean;
  type?: "card" | "modal";
  onClose?: () => void;
};

// A Rental line is written by rental invoice generation from its agreement's
// billing period or charge — it has no item, and it is never edited here.
const SalesInvoiceLineForm = (props: SalesInvoiceLineFormProps) =>
  props.initialValues.invoiceLineType === "Rental" ? (
    <RentalInvoiceLineSummary
      lineId={props.initialValues.id}
      type={props.type}
      onClose={props.onClose}
    />
  ) : (
    <SalesInvoiceItemLineForm {...props} />
  );

const SalesInvoiceItemLineForm = ({
  initialValues,
  type,
  isSalesOrderLine = false,
  onClose
}: SalesInvoiceLineFormProps) => {
  const { t, i18n } = useLingui();
  const permissions = usePermissions();
  const { carbon } = useCarbon();

  const { company, defaults } = useUser();
  const { invoiceId } = useParams();

  if (!invoiceId) throw new Error("invoiceId not found");

  // Sales-rule enforcement: submissions run through the violation hook's
  // fetcher so a blocked response opens <rules.ViolationModal /> with an
  // acknowledge-and-resubmit path for warns. Modal close happens on success
  // (not on submit) so violations can surface first.
  const rules = useRuleViolations({
    action: initialValues.id
      ? path.to.salesInvoiceLine(invoiceId, initialValues.id)
      : path.to.newSalesInvoiceLine(invoiceId),
    onSuccess: () => {
      if (type === "modal") onClose?.();
    }
  });

  const [items] = useItems();
  const routeData = useRouteData<{
    salesInvoice: SalesInvoice;
    currency: { decimalPlaces: number } | null;
  }>(path.to.salesInvoice(invoiceId));

  // Settlement decimals come from the document currency's row (loader data);
  // 2 is only the last resort for a currency-less document
  // The loader's currency row is the primary source — it is correct on first
  // paint, which matters because these formatters take part in the blur commit.
  // The hook covers documents whose loader doesn't carry the row; the single
  // documented last-resort lives inside it rather than as a literal here.
  const invoiceCurrency =
    routeData?.salesInvoice?.currencyCode ?? company.baseCurrencyCode;
  const configuredDecimals = useCurrencyDecimals(invoiceCurrency);
  const currencyDecimals =
    routeData?.currency?.decimalPlaces ?? configuredDecimals;

  const isLocked = isSalesInvoiceLocked(routeData?.salesInvoice?.status);
  const isEditable = !isLocked;

  const [lineType, setLineType] = useState<ItemType>(
    initialValues.invoiceLineType as ItemType
  );
  // The picker's type filter. It starts on every item type; the line's own
  // type is a real enum value — "Item" is not one — and follows the selected
  // item.
  const [itemFilter, setItemFilter] = useState<ItemType | "Item">("Item");
  // A service can run a single day, so its end may equal its start.
  const [serviceStartDate, setServiceStartDate] = useState(
    initialValues.serviceStartDate
  );
  const [locationId, setLocationId] = useState(defaults.locationId ?? "");
  const [itemData, setItemData] = useState<{
    itemId: string;
    methodType: string;
    description: string;
    quantity: number;
    unitPrice: number;
    /** Percent points (0–100), as the field types it. */
    discountPercent: number;
    shippingCost: number;
    unitOfMeasureCode: string;
    storageUnitId: string | null;
    taxAmount: number;
    taxPercent: number;
  }>({
    itemId: initialValues.itemId ?? "",
    methodType: initialValues.methodType ?? "",
    description: initialValues.description ?? "",
    quantity: initialValues.quantity ?? 1,
    unitPrice: initialValues.unitPrice ?? 0,
    discountPercent: initialValues.discountPercent ?? 0,
    shippingCost: initialValues.shippingCost ?? 0,
    unitOfMeasureCode: initialValues.unitOfMeasureCode ?? "",
    storageUnitId: initialValues.storageUnitId ?? "",
    // Seeded through the same coupling every later edit uses, so the opening
    // amount is rounded to the currency's decimals rather than a raw product.
    taxAmount: taxPairFromPercent(
      taxableBase(
        netUnitPrice(
          initialValues.unitPrice ?? 0,
          initialValues.discountPercent ?? 0
        ),
        initialValues.quantity ?? 1,
        initialValues.shippingCost ?? 0
      ),
      initialValues.taxPercent ?? 0,
      currencyDecimals
    ).amount,
    taxPercent: initialValues.taxPercent ?? 0
  });

  // Tax is charged on the discounted merchandise, so the pair's base takes the
  // NET unit price.
  const itemTax = useTaxPair({
    unitPrice: netUnitPrice(itemData.unitPrice, itemData.discountPercent),
    quantity: itemData.quantity,
    shippingCost: itemData.shippingCost,
    percent: itemData.taxPercent,
    amount: itemData.taxAmount,
    currency: invoiceCurrency,
    currencyDecimals,
    onChange: ({ percent, amount }) =>
      setItemData((d) => ({ ...d, taxPercent: percent, taxAmount: amount }))
  });

  const isFixedAsset = initialValues.invoiceLineType === "Fixed Asset";
  const [activeTab, setActiveTab] = useState<"item" | "asset">(
    isFixedAsset ? "asset" : "item"
  );

  const [assetOptions, setAssetOptions] = useState<
    { value: string; label: string }[]
  >([]);
  const [assetData, setAssetData] = useState<{
    assetId: string;
    description: string;
    quantity: number;
    unitPrice: number;
    taxPercent: number;
    taxAmount: number;
    shippingCost: number;
    addOnCost: number;
    nonTaxableAddOnCost: number;
  }>({
    assetId: initialValues.assetId ?? "",
    description: initialValues.description ?? "",
    quantity: initialValues.quantity ?? 1,
    unitPrice: initialValues.unitPrice ?? 0,
    taxPercent: initialValues.taxPercent ?? 0,
    taxAmount: 0,
    shippingCost: initialValues.shippingCost ?? 0,
    addOnCost: initialValues.addOnCost ?? 0,
    nonTaxableAddOnCost: initialValues.nonTaxableAddOnCost ?? 0
  });

  useMount(() => {
    if (!carbon || !company.id) return;
    (async () => {
      const assets = await carbon
        .from("fixedAsset")
        .select("id, fixedAssetId, name")
        .eq("companyId", company.id)
        .in("status", ["Active", "Fully Depreciated"])
        .order("fixedAssetId");
      const options = (assets.data ?? []).map((a) => ({
        value: a.id,
        label: `${a.fixedAssetId} — ${a.name}`
      }));
      if (
        initialValues.assetId &&
        !options.some((o) => o.value === initialValues.assetId)
      ) {
        const current = await carbon
          .from("fixedAsset")
          .select("id, fixedAssetId, name")
          .eq("id", initialValues.assetId)
          .single();
        if (current.data) {
          options.unshift({
            value: current.data.id,
            label: `${current.data.fixedAssetId} — ${current.data.name}`
          });
        }
      }
      setAssetOptions(options);
    })();
  });

  const costsDisclosure = useDisclosure();
  const assetCostsDisclosure = useDisclosure();
  const isEditing = initialValues.id !== undefined;
  const hasInvalidMethodType =
    itemData.methodType === "Make to Order" && !isSalesOrderLine;
  const isDisabled = !isEditable
    ? true
    : hasInvalidMethodType
      ? true
      : isEditing
        ? !permissions.can("update", "purchasing")
        : !permissions.can("create", "purchasing");

  const onTypeChange = (t: ItemType | "Item") => {
    if (t === itemFilter) return;
    setItemFilter(t);
    // Widening to every type keeps the selected item; narrowing to another
    // type clears it.
    if (t === "Item" || t === lineType) return;
    setLineType(t as ItemType);
    setItemData({
      itemId: "",
      methodType: "",
      description: "",
      quantity: 1,
      unitPrice: 0,
      discountPercent: 0,
      shippingCost: 0,
      unitOfMeasureCode: "",
      storageUnitId: "",
      taxAmount: 0,
      taxPercent: 0
    });
  };

  const onItemChange = async (itemId: string) => {
    if (!carbon) throw new Error("Carbon client not found");
    switch (lineType) {
      // @ts-expect-error
      case "Item":
      case "Consumable":
      case "Material":
      case "Part":
      case "Tool":
      case "Service":
      // @ts-expect-error
      case "Fixture":
        const [item, inventory] = await Promise.all([
          carbon
            .from("item")
            .select(
              "name, readableIdWithRevision, type, unitOfMeasureCode, defaultMethodType, itemTrackingType, itemCost(unitCost)"
            )
            .eq("id", itemId)
            .eq("companyId", company.id)
            .single(),
          carbon
            .from("pickMethod")
            .select("defaultStorageUnitId")
            .eq("itemId", itemId)
            .eq("companyId", company.id)
            .eq("locationId", locationId!)
            .maybeSingle()
        ]);

        const itemCost = item?.data?.itemCost?.[0];
        const trackingType = item?.data?.itemTrackingType;

        // Check if item requires a sales order (excluding Make items which can be changed to Pick)
        if (trackingType === "Batch" || trackingType === "Serial") {
          const errorMessage =
            trackingType === "Batch"
              ? t`Batch items require a sales order`
              : t`Serial items require a sales order`;
          toast.error(errorMessage);
          setItemData({
            itemId: "",
            methodType: "",
            description: "",
            quantity: 1,
            unitPrice: 0,
            discountPercent: 0,
            shippingCost: 0,
            unitOfMeasureCode: "",
            storageUnitId: "",
            taxAmount: 0,
            taxPercent: 0
          });
          return;
        }

        setItemData((prev) => ({
          ...prev,
          itemId: itemId,
          description: item.data?.name ?? "",
          methodType: item.data?.defaultMethodType ?? "",
          unitPrice:
            (itemCost?.unitCost ?? 0) /
            (routeData?.salesInvoice?.exchangeRate ?? 1),
          shippingCost: 0,
          // A service is always sold in "EA"
          unitOfMeasureCode:
            item.data?.type === "Service"
              ? "EA"
              : (item.data?.unitOfMeasureCode ?? "EA"),
          storageUnitId: inventory.data?.defaultStorageUnitId ?? null,
          taxAmount: 0,
          taxPercent: 0
        }));

        if (item.data?.type) {
          setLineType(item.data.type as ItemType);
        }

        break;
      default:
        throw new Error(
          `Invalid invoice line type: ${lineType} is not implemented`
        );
    }
  };

  const onLocationChange = async (newLocation: { value: string } | null) => {
    if (!carbon) throw new Error("carbon is not defined");
    if (typeof newLocation?.value !== "string")
      throw new Error("locationId is not a string");

    setLocationId(newLocation.value);
    if (!itemData.itemId) return;
    const storageUnit = await carbon
      .from("pickMethod")
      .select("defaultStorageUnitId")
      .eq("itemId", itemData.itemId)
      .eq("companyId", company.id)
      .eq("locationId", newLocation.value)
      .maybeSingle();

    setItemData((d) => ({
      ...d,
      storageUnitId: storageUnit?.data?.defaultStorageUnitId ?? ""
    }));
  };

  // These badges render DOCUMENT-currency values, so both formatters take the
  // document's currency and decimals. Defaulting to base currency is what
  // printed a JPY shipping cost as "$20.00".
  const currencyFormatter = useCurrencyFormatter({
    currency: routeData?.salesInvoice?.currencyCode ?? company.baseCurrencyCode,
    decimalPlaces: currencyDecimals
  });
  const priceFormatter = useCurrencyFormatter({
    rate: true,
    currency: routeData?.salesInvoice?.currencyCode ?? company.baseCurrencyCode,
    decimalPlaces: currencyDecimals
  });
  const percentFormatter = usePercentFormatter();

  return (
    <Tabs
      value={activeTab}
      onValueChange={(v) => setActiveTab(v as "item" | "asset")}
      className="w-full"
    >
      <ModalCardProvider type={type}>
        <ModalCard
          onClose={onClose}
          isCollapsible={isEditing}
          defaultCollapsed={false}
        >
          <ModalCardContent size="xxlarge">
            <ValidatedForm
              fetcher={rules.fetcher}
              defaultValues={initialValues}
              validator={salesInvoiceLineValidator}
              method="post"
              action={
                isEditing
                  ? path.to.salesInvoiceLine(invoiceId, initialValues.id!)
                  : path.to.newSalesInvoiceLine(invoiceId)
              }
              className="w-full"
              isDisabled={isEditing && isLocked}
            >
              <HStack
                className={cn(
                  "w-full justify-between items-start max-md:flex-col max-md:items-stretch max-md:space-x-0",
                  type === "modal" && "pr-16"
                )}
              >
                <ModalCardHeader className="flex flex-1">
                  <ModalCardTitle
                    className={cn(
                      isEditing &&
                        !isFixedAsset &&
                        !itemData?.itemId &&
                        "text-muted-foreground"
                    )}
                  >
                    {isEditing ? (
                      isFixedAsset ? (
                        initialValues.assetReadableId || "Fixed Asset"
                      ) : (
                        (getItemReadableId(items, itemData?.itemId) ?? "...")
                      )
                    ) : (
                      <Trans>New Sales Invoice Line</Trans>
                    )}
                  </ModalCardTitle>
                  <ModalCardDescription>
                    {isEditing ? (
                      <div className="flex flex-col items-start gap-1">
                        {isFixedAsset ? (
                          <span>
                            {initialValues.assetName || assetData.description}
                          </span>
                        ) : (
                          distinctItemText(
                            getItemReadableId(items, itemData?.itemId),
                            itemData?.description
                          ) && <span>{itemData?.description}</span>
                        )}
                        <div className="flex items-center gap-2">
                          <Badge
                            variant="outline"
                            className="flex items-center gap-2"
                          >
                            {initialValues?.quantity}{" "}
                            {!isFixedAsset && (
                              <MethodIcon type={itemData.methodType} />
                            )}
                          </Badge>
                          <Badge variant="green">
                            {priceFormatter.format(
                              initialValues?.unitPrice ?? 0
                            )}{" "}
                            {initialValues?.unitOfMeasureCode}
                          </Badge>
                          {(initialValues?.taxPercent ?? 0) > 0 ? (
                            <Badge variant="red">
                              {percentFormatter.format(
                                initialValues?.taxPercent ?? 0
                              )}{" "}
                              {t`Tax`}
                            </Badge>
                          ) : null}
                        </div>
                        <ContractInvoiceLineSource lineId={initialValues.id} />
                      </div>
                    ) : (
                      t`A sales invoice line contains invoice details for a particular item`
                    )}
                  </ModalCardDescription>
                </ModalCardHeader>
                <div className="flex-shrink-0 max-md:min-w-0 max-md:overflow-x-auto max-md:scroll-fade-x max-md:px-4 max-md:pb-2 max-md:empty:hidden">
                  {!isEditing && (
                    <TabsList>
                      <TabsTrigger value="item">
                        <LuBox className="mr-1" />
                        <Trans>Item</Trans>
                      </TabsTrigger>
                      <TabsTrigger value="asset">
                        <LuLandmark className="mr-1" />
                        <Trans>Asset</Trans>
                      </TabsTrigger>
                    </TabsList>
                  )}
                </div>
              </HStack>
              <ModalCardBody>
                <Hidden name="id" />
                <Hidden name="invoiceId" />
                <Hidden
                  name="exchangeRate"
                  value={routeData?.salesInvoice?.exchangeRate ?? 1}
                />

                <TabsContent value="item">
                  <Hidden name="invoiceLineType" value={lineType} />
                  <Hidden name="description" value={itemData.description} />
                  <Hidden
                    name="unitOfMeasureCode"
                    value={
                      lineType === "Service"
                        ? "EA"
                        : itemData?.unitOfMeasureCode
                    }
                  />

                  <VStack>
                    {hasInvalidMethodType && (
                      <Alert variant="destructive" className="mb-4">
                        <LuCircleAlert className="w-4 h-4" />
                        <AlertTitle>
                          <Trans>
                            Make items cannot be invoiced directly. Change
                            method to Pick to continue.
                          </Trans>
                        </AlertTitle>
                      </Alert>
                    )}
                    <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
                      <Item
                        autoFocus={!isEditing}
                        name="itemId"
                        label={i18n._(itemTypeLabel(itemFilter))}
                        type={itemFilter}
                        validItemTypes={[...itemType]}
                        locationId={locationId}
                        // Required by a refine rather than the schema object,
                        // so the field can't infer this for itself.
                        isOptional={false}
                        onChange={(value) => {
                          onItemChange(value?.value as string);
                        }}
                        onTypeChange={onTypeChange}
                      />

                      <FormControl className="col-span-2 max-md:col-span-full">
                        <FormLabel isOptional>
                          <Trans>Description</Trans>
                        </FormLabel>
                        <Input
                          value={itemData.description}
                          onChange={(e) =>
                            setItemData((d) => ({
                              ...d,
                              description: e.target.value
                            }))
                          }
                        />
                      </FormControl>

                      {[
                        "Item",
                        "Part",
                        "Material",
                        "Tool",
                        "Consumable",
                        "Service",
                        "Fixture"
                      ].includes(lineType) && (
                        <>
                          <div className="space-y-2">
                            <SelectControlled
                              name="methodType"
                              label={t`Method`}
                              termId="method-type"
                              options={
                                methodType.map((m) => ({
                                  label: (
                                    <span className="flex items-center gap-2">
                                      <MethodIcon type={m} />
                                      {m}
                                    </span>
                                  ),
                                  value: m
                                })) ?? []
                              }
                              value={itemData.methodType}
                              onChange={(newValue) => {
                                if (newValue)
                                  setItemData((d) => ({
                                    ...d,
                                    methodType: newValue?.value
                                  }));
                              }}
                            />
                          </div>

                          <NumberControlled
                            name="quantity"
                            label={t`Quantity`}
                            value={itemData.quantity}
                            onChange={(value) => {
                              setItemData((d) => ({
                                ...d,
                                quantity: value
                              }));
                            }}
                          />

                          <NumberControlled
                            name="unitPrice"
                            label={t`Unit Price`}
                            value={itemData.unitPrice}
                            formatOptions={INPUT_FORMAT.rate(
                              invoiceCurrency,
                              currencyDecimals
                            )}
                            onChange={(value) =>
                              setItemData((d) => ({
                                ...d,
                                unitPrice: value
                              }))
                            }
                          />
                          <NumberControlled
                            name="discountPercent"
                            label={t`Discount (%)`}
                            value={itemData.discountPercent}
                            minValue={0}
                            maxValue={100}
                            step={INPUT_STEP.percent}
                            formatOptions={INPUT_FORMAT.percentPoints}
                            onChange={(value) =>
                              setItemData((d) => ({
                                ...d,
                                discountPercent: value
                              }))
                            }
                          />
                          {lineType === "Service" && (
                            <>
                              <DatePicker
                                name="serviceStartDate"
                                label={t`Service start`}
                                onChange={(date) =>
                                  setServiceStartDate(date ?? undefined)
                                }
                              />
                              <DatePicker
                                name="serviceEndDate"
                                label={t`Service end`}
                                minValue={
                                  serviceStartDate
                                    ? parseDate(serviceStartDate)
                                    : undefined
                                }
                              />
                            </>
                          )}
                          <Location
                            name="locationId"
                            label={t`Shipping Location`}
                            value={locationId}
                            onChange={onLocationChange}
                          />
                          {lineType !== "Service" && (
                            <StorageUnit
                              name="storageUnitId"
                              label={t`Storage Unit`}
                              locationId={locationId}
                              value={itemData.storageUnitId ?? undefined}
                              onChange={(newValue) => {
                                if (newValue) {
                                  setItemData((d) => ({
                                    ...d,
                                    storageUnitId: newValue?.id
                                  }));
                                }
                              }}
                            />
                          )}
                        </>
                      )}
                      <CustomFormFields table="salesInvoiceLine" />
                    </div>

                    {[
                      "Item",
                      "Part",
                      "Material",
                      "Tool",
                      "Consumable",
                      "Service",
                      "Fixture"
                    ].includes(lineType) && (
                      <div className="w-full">
                        <div className="w-full border border-border rounded-md shadow-sm p-4 flex flex-col gap-4 mt-4">
                          <HStack
                            className="w-full justify-between cursor-pointer"
                            onClick={costsDisclosure.onToggle}
                          >
                            <Label>
                              <Trans>Tax & Additional Costs</Trans>
                            </Label>
                            <HStack>
                              {(itemData.taxPercent ?? 0) > 0 && (
                                <Badge variant="red">
                                  {percentFormatter.format(
                                    itemData.taxPercent ?? 0
                                  )}{" "}
                                  <Trans>Tax</Trans>
                                </Badge>
                              )}
                              {(itemData.shippingCost ?? 0) > 0 && (
                                <Badge
                                  variant="secondary"
                                  className="flex items-center gap-1"
                                >
                                  <LuTruck />
                                  <span>
                                    {currencyFormatter.format(
                                      itemData.shippingCost ?? 0
                                    )}
                                  </span>
                                </Badge>
                              )}
                              {(initialValues?.addOnCost ?? 0) > 0 ||
                                ((initialValues?.nonTaxableAddOnCost ?? 0) >
                                  0 && (
                                  <Badge
                                    variant="secondary"
                                    className="flex items-center gap-1"
                                  >
                                    <LuPlus />
                                    <span>
                                      {currencyFormatter.format(
                                        (initialValues?.addOnCost ?? 0) +
                                          (initialValues?.nonTaxableAddOnCost ??
                                            0)
                                      )}{" "}
                                      <Trans>Add-On</Trans>
                                    </span>
                                  </Badge>
                                ))}

                              <IconButton
                                icon={<LuChevronRight />}
                                aria-label={
                                  costsDisclosure.isOpen
                                    ? t`Collapse Costs`
                                    : t`Expand Costs`
                                }
                                variant="ghost"
                                size="md"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  costsDisclosure.onToggle();
                                }}
                                className={`transition-transform ${
                                  costsDisclosure.isOpen ? "rotate-90" : ""
                                }`}
                              />
                            </HStack>
                          </HStack>
                          <div
                            className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
                              costsDisclosure.isOpen ? "" : "hidden"
                            }`}
                          >
                            <TaxFields
                              {...itemTax}
                              amountName="taxAmount"
                              percentName="taxPercent"
                            />
                            <NumberControlled
                              name="shippingCost"
                              label={t`Shipping Cost`}
                              value={itemData.shippingCost}
                              minValue={0}
                              formatOptions={INPUT_FORMAT.money(
                                invoiceCurrency,
                                currencyDecimals
                              )}
                              onChange={(value) =>
                                setItemData((d) => ({
                                  ...d,
                                  shippingCost: value
                                }))
                              }
                            />
                            <Number
                              name="addOnCost"
                              label={t`Add-On Cost`}
                              formatOptions={INPUT_FORMAT.money(
                                invoiceCurrency,
                                currencyDecimals
                              )}
                            />
                            <Number
                              name="nonTaxableAddOnCost"
                              label={t`Non-Taxable Add-On Cost`}
                              formatOptions={INPUT_FORMAT.money(
                                invoiceCurrency,
                                currencyDecimals
                              )}
                            />
                          </div>
                        </div>
                      </div>
                    )}
                  </VStack>
                </TabsContent>

                {activeTab === "asset" && (
                  <>
                    <Hidden name="invoiceLineType" value="Fixed Asset" />
                    <Hidden name="description" value={assetData.description} />
                    <VStack>
                      <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
                        <Combobox
                          name="assetId"
                          label={t`Fixed Asset`}
                          termId="fixed-asset"
                          isOptional={false}
                          options={assetOptions}
                          value={assetData.assetId}
                          onChange={(selected) => {
                            setAssetData((d) => ({
                              ...d,
                              assetId: (selected?.value as string) ?? ""
                            }));
                          }}
                        />
                        <Location
                          name="locationId"
                          label={t`Shipping Location`}
                          value={locationId}
                          onChange={onLocationChange}
                        />
                        <FormControl>
                          <FormLabel>
                            <Trans>Description</Trans>
                          </FormLabel>
                          <Input
                            value={assetData.description}
                            onChange={(e) =>
                              setAssetData((d) => ({
                                ...d,
                                description: e.target.value
                              }))
                            }
                          />
                        </FormControl>
                        <NumberControlled
                          name="quantity"
                          label={t`Quantity`}
                          isOptional={false}
                          isDisabled
                          value={1}
                          onChange={() => undefined}
                        />
                        <NumberControlled
                          name="unitPrice"
                          label={t`Unit Price`}
                          isOptional={false}
                          value={assetData.unitPrice}
                          formatOptions={INPUT_FORMAT.rate(
                            invoiceCurrency,
                            currencyDecimals
                          )}
                          onChange={(value) =>
                            setAssetData((d) => ({ ...d, unitPrice: value }))
                          }
                        />
                        <CustomFormFields table="salesInvoiceLine" />
                      </div>

                      <div className="h-4" />

                      <div className="w-full border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
                        <HStack
                          className="w-full justify-between cursor-pointer"
                          onClick={assetCostsDisclosure.onToggle}
                        >
                          <Label>
                            <Trans>Tax &amp; Additional Costs</Trans>
                          </Label>
                          <HStack>
                            {assetData.taxPercent > 0 && (
                              <Badge variant="red">
                                {percentFormatter.format(assetData.taxPercent)}{" "}
                                <Trans>Tax</Trans>
                              </Badge>
                            )}
                            <IconButton
                              icon={<LuChevronRight />}
                              aria-label={
                                assetCostsDisclosure.isOpen
                                  ? t`Collapse Costs`
                                  : t`Expand Costs`
                              }
                              variant="ghost"
                              size="md"
                              onClick={(e) => {
                                e.stopPropagation();
                                assetCostsDisclosure.onToggle();
                              }}
                              className={`transition-transform ${assetCostsDisclosure.isOpen ? "rotate-90" : ""}`}
                            />
                          </HStack>
                        </HStack>
                        <div
                          className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
                            assetCostsDisclosure.isOpen ? "" : "hidden"
                          }`}
                        >
                          <NumberControlled
                            name="taxPercent"
                            label={t`Tax Percent`}
                            value={assetData.taxPercent}
                            minValue={0}
                            maxValue={1}
                            step={INPUT_STEP.percent}
                            formatOptions={INPUT_FORMAT.percent}
                            onChange={(value) =>
                              setAssetData((d) => ({
                                ...d,
                                taxPercent: value
                              }))
                            }
                          />
                          <NumberControlled
                            name="shippingCost"
                            label={t`Shipping Cost`}
                            value={assetData.shippingCost}
                            minValue={0}
                            formatOptions={INPUT_FORMAT.money(
                              invoiceCurrency,
                              currencyDecimals
                            )}
                            onChange={(value) =>
                              setAssetData((d) => ({
                                ...d,
                                shippingCost: value
                              }))
                            }
                          />
                          <NumberControlled
                            name="addOnCost"
                            label={t`Add-On Cost`}
                            value={assetData.addOnCost}
                            formatOptions={INPUT_FORMAT.money(
                              invoiceCurrency,
                              currencyDecimals
                            )}
                            onChange={(value) =>
                              setAssetData((d) => ({
                                ...d,
                                addOnCost: value
                              }))
                            }
                          />
                          <NumberControlled
                            name="nonTaxableAddOnCost"
                            label={t`Non-Taxable Add-On Cost`}
                            value={assetData.nonTaxableAddOnCost}
                            formatOptions={INPUT_FORMAT.money(
                              invoiceCurrency,
                              currencyDecimals
                            )}
                            onChange={(value) =>
                              setAssetData((d) => ({
                                ...d,
                                nonTaxableAddOnCost: value
                              }))
                            }
                          />
                        </div>
                      </div>
                    </VStack>
                  </>
                )}
              </ModalCardBody>
              <ModalCardFooter>
                <Submit isDisabled={isDisabled} withBlocker={false}>
                  <Trans>Save</Trans>
                </Submit>
              </ModalCardFooter>
            </ValidatedForm>
          </ModalCardContent>
        </ModalCard>
      </ModalCardProvider>
      <rules.ViolationModal />
    </Tabs>
  );
};

export default SalesInvoiceLineForm;