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.

46.7 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 {
  Badge,
  Select as CarbonSelect,
  cn,
  FormControl,
  FormLabel,
  HStack,
  IconButton,
  Input,
  Label,
  LabelWithHelp,
  ModalCard,
  ModalCardBody,
  ModalCardContent,
  ModalCardDescription,
  ModalCardFooter,
  ModalCardHeader,
  ModalCardProvider,
  ModalCardTitle,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  toast,
  useDebounce,
  useDisclosure,
  useMount,
  VStack
} from "@carbon/react";
import {
  distinctItemText,
  equals,
  getItemReadableId,
  INPUT_FORMAT,
  INPUT_STEP,
  round
} from "@carbon/utils";
import { parseDate } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useState } from "react";
import {
  LuBox,
  LuChevronRight,
  LuLandmark,
  LuPlus,
  LuTruck
} from "react-icons/lu";
import { useParams } from "react-router";
import type { z } from "zod";
import { ItemLifecycleBadge, MethodIcon } from "~/components";
import type { ConfiguratorValues } from "~/components/Configurator/ConfiguratorForm";
import {
  ItemConfigureButton,
  useItemConfiguration
} from "~/components/Configurator/ItemConfigurator";
import {
  CustomFormFields,
  DatePicker,
  Hidden,
  InputControlled,
  Item,
  Location,
  Number,
  NumberControlled,
  StorageUnit,
  Submit
} from "~/components/Form";
import { itemTypeLabel } from "~/components/Form/itemTypeLabel";
import {
  useCurrencyDecimals,
  useCurrencyFormatter,
  usePercentFormatter,
  usePermissions,
  useRouteData,
  useUser
} from "~/hooks";
import { getDefaultStorageUnitForJob } from "~/modules/inventory/inventory.utils";
import { itemType, methodType } from "~/modules/shared/shared.models";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import {
  isSalesOrderLocked,
  salesOrderLineValidator
} from "../../sales.models";
import type {
  PriceTraceStep,
  SalesOrder,
  SalesOrderLineType
} from "../../types";
import { PriceTraceModal } from "../Pricing/PriceTraceModal";

type SalesOrderLineFormProps = {
  initialValues: z.infer<typeof salesOrderLineValidator> & {
    assetReadableId?: string;
    assetName?: string;
  };
  type?: "card" | "modal";
  onClose?: () => void;
};

const SalesOrderLineForm = ({
  initialValues,
  type,
  onClose
}: SalesOrderLineFormProps) => {
  const { t, i18n } = useLingui();
  const permissions = usePermissions();
  const { carbon } = useCarbon();
  const { company } = useUser();
  const { orderId } = useParams();

  if (!orderId) throw new Error("orderId 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.salesOrderLine(orderId, initialValues.id)
      : path.to.newSalesOrderLine(orderId),
    onSuccess: () => {
      if (type === "modal") onClose?.();
    }
  });

  const routeData = useRouteData<{
    salesOrder: SalesOrder;
  }>(path.to.salesOrder(orderId));

  const isLocked = isSalesOrderLocked(routeData?.salesOrder?.status);
  const isEditable = !isLocked;

  const baseCurrency = company?.baseCurrencyCode ?? "USD";
  const currencyDecimals = useCurrencyDecimals(baseCurrency);
  const [items] = useItems();

  const [lineType, setLineType] = useState(initialValues.salesOrderLineType);
  // 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<SalesOrderLineType | "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(initialValues.locationId ?? "");
  const [saleQuantity, setSaleQuantity] = useState(
    initialValues.saleQuantity ?? 1
  );
  const [isPriceResolving, setIsPriceResolving] = useState(false);
  const [itemData, setItemData] = useState<{
    itemId: string;
    methodType: string;
    description: string;
    unitPrice: number;
    uom: string;
    storageUnitId: string;
    modelUploadId: string | null;
    priceListId: string | null;
    priceListName: string | null;
    priceTrace: PriceTraceStep[] | null;
  }>({
    itemId: initialValues.itemId ?? "",
    description: initialValues.description ?? "",
    methodType: initialValues.methodType ?? "",
    unitPrice: initialValues.unitPrice ?? 0,
    uom: initialValues.unitOfMeasureCode ?? "",
    storageUnitId: initialValues.storageUnitId ?? "",
    modelUploadId: initialValues.modelUploadId ?? null,
    priceListId:
      (initialValues as { priceListId?: string | null }).priceListId ?? null,
    priceListName: null,
    priceTrace: initialValues.priceTrace ?? null
  });

  const configurator = useItemConfiguration({
    itemId: initialValues.itemId,
    configuration: initialValues.configuration as ConfiguratorValues | null
  });
  const { configuration } = configurator;
  const requiresConfiguration = configurator.parameters !== null;

  const isEditing = initialValues.id !== undefined;
  const isFixedAsset = initialValues.salesOrderLineType === "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;
    saleQuantity: number;
    unitPrice: number;
    taxPercent: number;
    shippingCost: number;
    addOnCost: number;
    nonTaxableAddOnCost: number;
  }>({
    assetId: initialValues.assetId ?? "",
    description: initialValues.description ?? "",
    saleQuantity: initialValues.saleQuantity ?? 1,
    unitPrice: initialValues.unitPrice ?? 0,
    taxPercent: initialValues.taxPercent ?? 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 pricingRuleId = (initialValues as { priceListId?: string | null })
    .priceListId;

  useEffect(() => {
    if (!pricingRuleId || !carbon) return;
    carbon
      .from("pricingRule")
      .select("name")
      .eq("id", pricingRuleId)
      .single()
      .then(({ data }) => {
        if (data?.name) {
          setItemData((d) => ({ ...d, priceListName: data.name }));
        }
      });
  }, [pricingRuleId, carbon]);

  const onTypeChange = (t: SalesOrderLineType | "Item") => {
    setItemFilter(t);
    // "Item" is the "All Items" filter, always compatible with the selection.
    if (t === "Item") return;
    setLineType(t as typeof lineType);
    // Clear itemData only when the new filter excludes the currently selected
    // item — otherwise a stale itemId of the old type would post with the new
    // salesOrderLineType.
    if (!itemData.itemId) return;
    const currentType = items.find((i) => i.id === itemData.itemId)?.type;
    if (currentType && currentType === t) return;
    setItemData({
      itemId: "",
      description: "",
      unitPrice: 0,
      methodType: "",
      uom: "EA",
      storageUnitId: "",
      modelUploadId: null,
      priceListId: null,
      priceListName: null,
      priceTrace: null
    });
  };

  const isService = lineType === "Service";

  const currencyFormatter = useCurrencyFormatter();
  const percentFormatter = usePercentFormatter();

  const resolvePrice = useCallback(
    async (
      itemId: string,
      quantity: number,
      lineConfiguration: Record<string, unknown> | null
    ) => {
      const customerId = routeData?.salesOrder?.customerId;
      if (!customerId) return null;

      try {
        const response = await fetch(path.to.api.salesResolvePrice, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            customerId,
            itemId,
            quantity,
            ...(lineConfiguration ? { configuration: lineConfiguration } : {})
          })
        });
        if (response.ok) {
          const result = await response.json();
          return {
            finalPrice: result.finalPrice as number,
            priceListId: null as string | null,
            priceListName: "Pricing Rules" as string | null,
            trace: result.trace ?? null
          };
        }
        toast.error("Couldn't apply pricing rules — using base price");
      } catch {
        // Fall back to itemUnitSalePrice on any error
        toast.error("Couldn't apply pricing rules — using base price");
      }
      return null;
    },
    [routeData?.salesOrder?.customerId]
  );

  const applyResolvedPrice = (
    result: NonNullable<Awaited<ReturnType<typeof resolvePrice>>>
  ) =>
    setItemData((d) => ({
      ...d,
      unitPrice: result.finalPrice,
      priceListId: result.priceListId,
      priceListName: result.priceListName,
      priceTrace: result.trace
    }));

  const debouncedQuantityResolve = useDebounce(async (qty: number) => {
    if (!itemData.itemId) {
      setIsPriceResolving(false);
      return;
    }
    const result = await resolvePrice(itemData.itemId, qty, configuration);
    if (result) applyResolvedPrice(result);
    setIsPriceResolving(false);
  }, 400);

  const onQuantityChange = (qty: number) => {
    setSaleQuantity(qty);
    setIsPriceResolving(true);
    debouncedQuantityResolve(qty);
  };

  // A new configuration changes the configuration prices.
  const onConfigured = async (values: ConfiguratorValues) => {
    if (!itemData.itemId) return;
    setIsPriceResolving(true);
    const result = await resolvePrice(itemData.itemId, saleQuantity, values);
    if (result) applyResolvedPrice(result);
    setIsPriceResolving(false);
  };

  const onChange = async (itemId: string) => {
    if (!itemId) return;
    if (!carbon || !company.id) return;
    setIsPriceResolving(true);
    configurator.changeItem(itemId);
    const [item, price] = await Promise.all([
      carbon
        .from("item")
        .select(
          "name, readableIdWithRevision, type, defaultMethodType, unitOfMeasureCode, modelUploadId"
        )
        .eq("id", itemId)
        .eq("companyId", company.id)
        .single(),
      carbon
        .from("itemUnitSalePrice")
        .select("unitSalePrice")
        .eq("itemId", itemId)
        .eq("companyId", company.id)
        .maybeSingle()
    ]);

    // Get default storage unit or storage unit with highest quantity
    const defaultStorageUnitId = locationId
      ? await getDefaultStorageUnitForJob(
          carbon,
          itemId,
          locationId,
          company.id
        )
      : null;

    let resolvedPrice = price.data?.unitSalePrice ?? 0;
    let priceListId: string | null = null;

    const result = await resolvePrice(itemId, saleQuantity, null);
    if (result) {
      resolvedPrice = result.finalPrice;
      priceListId = result.priceListId;
    }

    if (item.data?.type) {
      setLineType(item.data.type as typeof lineType);
    }
    setItemData({
      itemId,
      description: item.data?.name ?? "",
      methodType: item.data?.defaultMethodType ?? "",
      unitPrice: resolvedPrice,
      // A service is always sold in "EA"
      uom:
        item.data?.type === "Service"
          ? "EA"
          : (item.data?.unitOfMeasureCode ?? "EA"),
      storageUnitId: defaultStorageUnitId ?? "",
      modelUploadId: item.data?.modelUploadId ?? null,
      priceListId,
      priceListName: result?.priceListName ?? null,
      priceTrace: result?.trace ?? null
    });
    setIsPriceResolving(false);
  };

  const onAssetChange = async (assetId: string) => {
    if (!assetId) {
      setAssetData((d) => ({ ...d, assetId: "" }));
      return;
    }
    if (!carbon || !company.id) return;

    const asset = await carbon
      .from("fixedAsset")
      .select("name, acquisitionCost, accumulatedDepreciation")
      .eq("id", assetId)
      .eq("companyId", company.id)
      .single();

    // Net book value = acquisition cost − accumulated depreciation (the same
    // figure shown in FixedAssetsTable), used as the default sale unit price.
    // NB: `Number` is the form component in this file, so rely on the numeric
    // column types rather than the global `Number()`.
    const netBookValue =
      (asset.data?.acquisitionCost ?? 0) -
      (asset.data?.accumulatedDepreciation ?? 0);

    setAssetData((d) => ({
      ...d,
      assetId,
      description: asset.data?.name ?? "",
      unitPrice: netBookValue
    }));
  };

  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;

    // Get default storage unit or storage unit with highest quantity for the new location
    const defaultStorageUnitId = await getDefaultStorageUnitForJob(
      carbon,
      itemData.itemId,
      newLocation.value,
      company.id
    );

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

  const costsDisclosure = useDisclosure();
  const assetCostsDisclosure = useDisclosure();

  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={salesOrderLineValidator}
                method="post"
                action={
                  isEditing
                    ? path.to.salesOrderLine(orderId, initialValues.id!)
                    : path.to.newSalesOrderLine(orderId)
                }
                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"
                        ) : (
                          <span className="inline-flex items-center gap-2">
                            {getItemReadableId(items, itemData?.itemId) ||
                              "..."}
                            <ItemLifecycleBadge
                              mode={
                                items.find((i) => i.id === itemData?.itemId)
                                  ?.supersessionMode
                              }
                            />
                          </span>
                        )
                      ) : (
                        t`New Sales Order Line`
                      )}
                    </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?.saleQuantity}
                              {!isFixedAsset && (
                                <MethodIcon type={itemData.methodType} />
                              )}
                            </Badge>
                            <Badge variant="green">
                              {currencyFormatter.format(
                                initialValues?.unitPrice ?? 0
                              )}{" "}
                              {initialValues?.unitOfMeasureCode}
                            </Badge>
                            {initialValues?.taxPercent > 0 ? (
                              <Badge variant="red">
                                {percentFormatter.format(
                                  initialValues?.taxPercent
                                )}{" "}
                                <Trans>Tax</Trans>
                              </Badge>
                            ) : null}
                          </div>
                        </div>
                      ) : (
                        <Trans>
                          A sales order line contains order details for a
                          particular item
                        </Trans>
                      )}
                    </ModalCardDescription>
                  </ModalCardHeader>
                  <div className="flex-shrink-0 flex items-center gap-2 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="salesOrderId" />
                  {/* Lives outside TabsContent so the value survives Item↔Asset
                      tab toggles — TabsContent unmounts inactive children, and
                      useControlField's unregister cleanup resets the field. */}
                  <Hidden name="methodType" value={itemData.methodType ?? ""} />

                  <TabsContent value="item">
                    {!isEditing && (
                      <Hidden
                        name="description"
                        value={itemData?.description ?? ""}
                      />
                    )}
                    <Hidden
                      name="modelUploadId"
                      value={itemData?.modelUploadId ?? undefined}
                    />
                    <Hidden
                      name="priceListId"
                      value={itemData?.priceListId ?? undefined}
                    />
                    {/* Always posted: "null" clears a stored trace once the
                        price is typed rather than resolved. */}
                    <Hidden
                      name="priceTrace"
                      value={JSON.stringify(itemData?.priceTrace ?? null)}
                    />
                    <Hidden name="salesOrderLineType" value={lineType} />
                    <Hidden
                      name="unitOfMeasureCode"
                      value={isService ? "EA" : itemData.uom}
                    />
                    <Hidden
                      name="configuration"
                      value={configuration ? JSON.stringify(configuration) : ""}
                    />
                    <VStack>
                      <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 as "Part"))}
                          type={itemFilter as "Part"}
                          validItemTypes={[...itemType]}
                          // The line type is posted above; the filter is not it.
                          typeFieldName="itemFilter"
                          value={itemData.itemId}
                          locationId={locationId}
                          onChange={(value) => {
                            onChange(value?.value as string);
                          }}
                          onTypeChange={onTypeChange}
                        />

                        {isEditing && (
                          <InputControlled
                            name="description"
                            label={t`Short Description`}
                            onChange={(value) => {
                              setItemData((d) => ({
                                ...d,
                                description: value
                              }));
                            }}
                            value={itemData.description}
                          />
                        )}

                        {lineType !== "Comment" && (
                          <>
                            <FormControl>
                              <FormLabel htmlFor="methodTypePicker">
                                {t`Method`}
                              </FormLabel>
                              <CarbonSelect
                                value={itemData.methodType || undefined}
                                onValueChange={(v) =>
                                  setItemData((d) => ({
                                    ...d,
                                    methodType: v
                                  }))
                                }
                              >
                                <SelectTrigger
                                  id="methodTypePicker"
                                  className="w-full"
                                >
                                  <SelectValue
                                    placeholder={t`Select method...`}
                                  />
                                </SelectTrigger>
                                <SelectContent>
                                  {methodType.map((m) => (
                                    <SelectItem key={m} value={m}>
                                      <span className="flex items-center gap-2">
                                        <MethodIcon type={m} />
                                        {m}
                                      </span>
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </CarbonSelect>
                            </FormControl>
                            <NumberControlled
                              name="saleQuantity"
                              label={t`Quantity`}
                              value={saleQuantity}
                              onChange={onQuantityChange}
                            />
                            <div className="flex flex-col gap-y-2 w-full">
                              <div className="flex items-center justify-between min-h-[16px]">
                                <span className="text-xs font-medium text-muted-foreground">
                                  <LabelWithHelp
                                    termId="sales-order-line-unit-price"
                                    variant="inline"
                                  >
                                    <Trans>Unit Price</Trans>
                                  </LabelWithHelp>
                                </span>
                                <PriceTraceModal
                                  trace={itemData.priceTrace}
                                  currencyCode={baseCurrency}
                                />
                              </div>
                              <NumberControlled
                                name="unitPrice"
                                value={itemData.unitPrice}
                                formatOptions={INPUT_FORMAT.rate(
                                  baseCurrency,
                                  currencyDecimals
                                )}
                                onChange={(value) =>
                                  setItemData((d) =>
                                    // The field commits at the storage scale,
                                    // so a resolved price with more digits
                                    // comes back rounded on blur — not a typed
                                    // price.
                                    equals(round(value), round(d.unitPrice))
                                      ? d
                                      : {
                                          ...d,
                                          unitPrice: value,
                                          // A typed price is not the resolved one.
                                          priceTrace: null
                                        }
                                  )
                                }
                              />
                            </div>
                            {/* A service is promised for the day it starts, so
                                the server copies the start date across. */}
                            {!isService && (
                              <DatePicker
                                name="promisedDate"
                                label={t`Promised Date`}
                                termId="sales-order-line-promised-date"
                              />
                            )}
                            {isService && (
                              <>
                                <DatePicker
                                  name="serviceStartDate"
                                  label={t`Service start`}
                                  onChange={(date) =>
                                    setServiceStartDate(date ?? undefined)
                                  }
                                />
                                <DatePicker
                                  name="serviceEndDate"
                                  label={t`Service end`}
                                  minValue={
                                    serviceStartDate
                                      ? parseDate(serviceStartDate)
                                      : undefined
                                  }
                                />
                              </>
                            )}
                            {[
                              "Part",
                              "Material",
                              "Service",
                              "Tool",
                              "Consumable"
                            ].includes(lineType) && (
                              <Location
                                name="locationId"
                                label={t`Shipping Location`}
                                onChange={onLocationChange}
                                termId="sales-order-line-fulfillment-location"
                              />
                            )}
                            {[
                              "Part",
                              "Material",
                              "Tool",
                              "Fixture",
                              "Consumable"
                            ].includes(lineType) && (
                              <StorageUnit
                                name="storageUnitId"
                                label={t`Storage Unit`}
                                locationId={locationId}
                                itemId={itemData.itemId}
                                value={itemData.storageUnitId ?? undefined}
                                onChange={(newValue) => {
                                  if (newValue) {
                                    setItemData((d) => ({
                                      ...d,
                                      storageUnitId: newValue?.id
                                    }));
                                  }
                                }}
                                termId="sales-order-line-storage-unit"
                              />
                            )}
                          </>
                        )}
                        <CustomFormFields table="salesOrderLine" />
                      </div>

                      {lineType !== "Comment" && (
                        <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 &amp; Additional Costs</Trans>
                              </Label>
                              <HStack>
                                {(initialValues?.taxPercent ?? 0) > 0 && (
                                  <Badge variant="red">
                                    {percentFormatter.format(
                                      initialValues?.taxPercent ?? 0
                                    )}{" "}
                                    <Trans>Tax</Trans>
                                  </Badge>
                                )}
                                {(initialValues?.shippingCost ?? 0) > 0 && (
                                  <Badge
                                    variant="secondary"
                                    className="flex items-center gap-1"
                                  >
                                    <LuTruck />
                                    <span>
                                      {currencyFormatter.format(
                                        initialValues?.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"
                              }`}
                            >
                              <Number
                                name="taxPercent"
                                label={t`Tax Percent`}
                                minValue={0}
                                maxValue={1}
                                step={INPUT_STEP.percent}
                                formatOptions={INPUT_FORMAT.percent}
                              />
                              <Number
                                name="shippingCost"
                                label={t`Shipping Cost`}
                                minValue={0}
                                formatOptions={INPUT_FORMAT.money(
                                  baseCurrency,
                                  currencyDecimals
                                )}
                                termId="sales-order-line-shipping"
                              />
                              <Number
                                name="addOnCost"
                                label={t`Add-On Cost`}
                                formatOptions={INPUT_FORMAT.money(
                                  baseCurrency,
                                  currencyDecimals
                                )}
                                termId="sales-order-line-add-on-cost"
                              />
                              <Number
                                name="nonTaxableAddOnCost"
                                label={t`Non-Taxable Add-On Cost`}
                                formatOptions={INPUT_FORMAT.money(
                                  baseCurrency,
                                  currencyDecimals
                                )}
                                termId="sales-order-line-non-taxable-add-on-cost"
                              />
                            </div>
                          </div>
                        </div>
                      )}
                    </VStack>
                  </TabsContent>

                  {activeTab === "asset" && (
                    <>
                      <Hidden name="salesOrderLineType" 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`}
                            isOptional={false}
                            options={assetOptions}
                            value={assetData.assetId}
                            onChange={(selected) => {
                              onAssetChange((selected?.value as string) ?? "");
                            }}
                            termId="sales-order-line-asset"
                          />
                          <Location
                            name="locationId"
                            label={t`Shipping Location`}
                            onChange={onLocationChange}
                            termId="sales-order-line-fulfillment-location"
                          />
                          <FormControl>
                            <FormLabel>
                              <Trans>Description</Trans>
                            </FormLabel>
                            <Input
                              value={assetData.description}
                              onChange={(e) =>
                                setAssetData((d) => ({
                                  ...d,
                                  description: e.target.value
                                }))
                              }
                            />
                          </FormControl>
                          <DatePicker
                            name="promisedDate"
                            label={t`Promised Date`}
                            termId="sales-order-line-promised-date"
                          />
                          <NumberControlled
                            name="saleQuantity"
                            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(
                              baseCurrency,
                              currencyDecimals
                            )}
                            onChange={(value) =>
                              setAssetData((d) => ({
                                ...d,
                                unitPrice: value
                              }))
                            }
                            termId="sales-order-line-unit-price"
                          />
                          <CustomFormFields table="salesOrderLine" />
                        </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>
                              )}
                              {assetData.shippingCost > 0 && (
                                <Badge
                                  variant="secondary"
                                  className="flex items-center gap-1"
                                >
                                  <LuTruck />
                                  <span>
                                    {currencyFormatter.format(
                                      assetData.shippingCost
                                    )}
                                  </span>
                                </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(
                                baseCurrency,
                                currencyDecimals
                              )}
                              onChange={(value) =>
                                setAssetData((d) => ({
                                  ...d,
                                  shippingCost: value
                                }))
                              }
                              termId="sales-order-line-shipping"
                            />
                            <NumberControlled
                              name="addOnCost"
                              label={t`Add-On Cost`}
                              value={assetData.addOnCost}
                              formatOptions={INPUT_FORMAT.money(
                                baseCurrency,
                                currencyDecimals
                              )}
                              onChange={(value) =>
                                setAssetData((d) => ({
                                  ...d,
                                  addOnCost: value
                                }))
                              }
                              termId="sales-order-line-add-on-cost"
                            />
                            <NumberControlled
                              name="nonTaxableAddOnCost"
                              label={t`Non-Taxable Add-On Cost`}
                              value={assetData.nonTaxableAddOnCost}
                              formatOptions={INPUT_FORMAT.money(
                                baseCurrency,
                                currencyDecimals
                              )}
                              onChange={(value) =>
                                setAssetData((d) => ({
                                  ...d,
                                  nonTaxableAddOnCost: value
                                }))
                              }
                              termId="sales-order-line-non-taxable-add-on-cost"
                            />
                          </div>
                        </div>
                      </VStack>
                    </>
                  )}
                </ModalCardBody>
                <ModalCardFooter>
                  {activeTab === "item" && (
                    <ItemConfigureButton
                      configurator={configurator}
                      isDisabled={
                        !isEditable ||
                        (isEditing
                          ? !permissions.can("update", "sales")
                          : !permissions.can("create", "sales"))
                      }
                      onConfigured={onConfigured}
                    />
                  )}
                  <Submit
                    isDisabled={
                      isPriceResolving ||
                      (!isEditing &&
                        requiresConfiguration &&
                        activeTab === "item" &&
                        !configuration) ||
                      !isEditable ||
                      (isEditing
                        ? !permissions.can("update", "sales")
                        : !permissions.can("create", "sales"))
                    }
                  >
                    <Trans>Save</Trans>
                  </Submit>
                </ModalCardFooter>
              </ValidatedForm>
            </ModalCardContent>
          </ModalCard>
        </ModalCardProvider>
      </Tabs>
      <rules.ViolationModal />
    </>
  );
};

export default SalesOrderLineForm;