All files / src/pages/flowsheet-page/economics/operating-lines-panel/editor OperatingLineEditor.tsx

71.95% Statements 136/189
53.03% Branches 105/198
66.66% Functions 20/30
71.51% Lines 118/165

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913                                                                                                                                            76x 76x 76x 76x 456x   76x                                                                         25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x       25x 75x   25x 75x   25x     25x               25x       25x               25x 25x   25x   25x         25x 11x   11x                         4x 4x 4x     4x 4x   3x           2x   1x 1x 1x     25x           25x 1x                           7x 7x 7x 7x 7x 7x       7x 7x 2x 2x   2x 2x 2x                                                                                                                                                                                                                       1x                           1x                                                         2x                                                                                                                                                                     176x                                                                             110x                                                                                                                                         2x                                                                                                                 2x                                                                                                                                                                                         22x                                                                       22x                             22x         22x 22x   22x 22x 22x 44x 154x 1x 22x       23x 66x 24x 66x       22x                 22x 22x   22x                     37x       15x         22x 22x 22x 37x   22x 82x 23x 52x               25x     25x         25x 25x       25x       25x               22x 22x 22x     76x     15x 7x 7x 7x               14x 14x 11x 11x 11x 11x 11x 11x 11x        
import { ChevronDown, Trash2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Button } from "@/ahuora-design-system/ui/button";
import { Checkbox } from "@/ahuora-design-system/ui/checkbox";
import { Label } from "@/ahuora-design-system/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import type {
  EconomicsDefaultRateRead,
  EconomicsSettingsProfileRead,
  OperatingCostLineRead,
  PatchedOperatingCostLine,
} from "@/api/apiStore.gen";
import {
  BasisQuantitySourceEnum,
  BlankEnum,
  EconomicEffectEnum,
  OperatingCostLineCategoryEnum,
  OperatingCostLineOutletStreamDispositionEnum as OutletStreamDispositionEnum,
  RateSourceModeEnum,
  RateTypeEnum,
} from "@/api/apiStore.gen";
import { cn } from "@/lib/utils";
import {
  DEFAULT_RATE_TYPES,
  type DefaultRateType,
  defaultRateOptionLabel,
  rateTypeLabel as defaultRateTypeLabel,
  rateTypeForCategory,
  selectedOperatingDefaultForRateType,
  sourceRatesForType,
} from "../../default-rates/economicsDefaultRates";
import {
  formatNumericInputValue,
  unitLooksMonetary,
} from "../../shared/model/economicsFormatters";
import { scrollElementIntoEconomicsContext } from "../../shared/model/economicsScroll";
import { ValueWithUnitSelectField } from "../../shared/ui/EconomicsFormFields";
import {
  apiFieldMessages,
  defaultBasisUnit,
  defaultRateUnit,
  type FieldMessages,
  lineCanonicalKey,
  lineDraft,
  localFieldMessages,
  MAINTENANCE_RATE_UNIT,
  mutationErrorMessage,
  NONE_SELECT_VALUE,
  nullableString,
  OPERATING_LINE_TYPES,
  type OperatingLineIntent,
  operatingLineType,
  operatingLineTypeForIntent,
  type SaveState,
} from "../model/types";
import {
  FieldError,
  FieldLabel,
  FormState,
  LineInput,
  SourceDefaultBadge,
} from "../ui/fields";
 
const FOCUSED_CONTEXT_SCROLL_CLASS = "scroll-mt-28";
const PROJECT_DEFAULT_SELECT_VALUE = "__project_default__";
const SOURCE_DEFAULT_SELECT_PREFIX = "source:";
const ENERGY_RATE_TYPES = DEFAULT_RATE_TYPES.filter(
  (rateType) => rateType !== RateTypeEnum.Maintenance,
);
const EDITOR_FIELD_MESSAGE_KEYS = new Set([
  "basis_quantity",
  "basis_quantity_source",
  "basis_unit",
  "category",
  "included",
  "label",
  "line_type",
  "outlet_stream_disposition",
  "rate_amount",
  "rate_source_mode",
  "rate_type",
  "rate_unit",
  "source_default_rate",
]);
 
export function OperatingLineEditor({
  line,
  canEdit,
  defaultRates,
  assumptions,
  annualOperatingHours,
  isFocused = false,
  lockCategory = false,
  onPatch,
  onDelete,
}: {
  line: OperatingCostLineRead;
  canEdit: boolean;
  defaultRates: EconomicsDefaultRateRead[];
  assumptions?: EconomicsSettingsProfileRead | null;
  annualOperatingHours: string;
  isFocused?: boolean;
  lockCategory?: boolean;
  onPatch: (patch: PatchedOperatingCostLine) => Promise<void>;
  onDelete?: () => Promise<void>;
}) {
  const [draft, setDraft] = useState(lineDraft(line));
  const [dirty, setDirty] = useState(false);
  const [open, setOpen] = useState(false);
  const [saveState, setSaveState] = useState<SaveState>({ kind: "idle" });
  const [fieldMessages, setFieldMessages] = useState<FieldMessages>({});
  const articleRef = useRef<HTMLElement | null>(null);
  const timeoutRef = useRef<number | null>(null);
  const pendingPatchRef = useRef<PatchedOperatingCostLine>({});
  const canonicalKey = lineCanonicalKey(line);
  const editBaseCanonicalKeyRef = useRef(canonicalKey);
  const type = operatingLineType(
    line.category ?? OperatingCostLineCategoryEnum.Custom,
    line.economic_effect ?? EconomicEffectEnum.Cost,
  );
  const defaultRate = defaultRates.find(
    (rate) => rate.id === line.source_default_rate,
  );
  const draftDefaultRate = defaultRates.find(
    (rate) => String(rate.id) === draft.source_default_rate,
  );
  const selectedRateType = isDefaultRateType(draft.rate_type)
    ? draft.rate_type
    : undefined;
  const projectDefault = selectedRateType
    ? selectedOperatingDefaultForRateType(
        selectedRateType,
        draft.category,
        assumptions,
        defaultRates,
      )
    : undefined;
  const sourceRates = selectedRateType
    ? sourceRatesForType(selectedRateType, defaultRates)
    : defaultRates;
  const sourceSelectValue =
    draft.rate_source_mode === RateSourceModeEnum.ProjectDefault &&
    selectedRateType
      ? PROJECT_DEFAULT_SELECT_VALUE
      : draft.rate_source_mode === RateSourceModeEnum.SourceDefault &&
          draft.source_default_rate
        ? `${SOURCE_DEFAULT_SELECT_PREFIX}${draft.source_default_rate}`
        : NONE_SELECT_VALUE;
  const rateUnitOptions =
    draftDefaultRate?.display_unit_options ?? line.rate_unit_options;
  const hasSourceQuantity = Boolean(line.source_property_info) && !line.manual;
  const isSourceQuantity =
    hasSourceQuantity &&
    draft.basis_quantity_source === BasisQuantitySourceEnum.SourceProperty;
  const inlineMessages = {
    ...fieldMessages,
    ...localFieldMessages(draft, line),
  };
 
  useEffect(() => {
    const canonicalDraft = lineDraft(line);
    const matches =
      draft.label === canonicalDraft.label &&
      draft.category === canonicalDraft.category &&
      draft.economic_effect === canonicalDraft.economic_effect &&
      decimalTextMatches(draft.basis_quantity, canonicalDraft.basis_quantity) &&
      draft.basis_unit === canonicalDraft.basis_unit &&
      draft.basis_quantity_source === canonicalDraft.basis_quantity_source &&
      decimalTextMatches(draft.rate_amount, canonicalDraft.rate_amount) &&
      draft.rate_unit === canonicalDraft.rate_unit &&
      draft.rate_type === canonicalDraft.rate_type &&
      draft.rate_source_mode === canonicalDraft.rate_source_mode &&
      draft.included === canonicalDraft.included &&
      draft.source_default_rate === canonicalDraft.source_default_rate;
    if (matches) {
      editBaseCanonicalKeyRef.current = canonicalKey;
      setDirty(false);
      return;
    }
    if (dirty && saveState.kind === "saving") {
      editBaseCanonicalKeyRef.current = canonicalKey;
      return;
    }
    Iif (dirty && saveState.kind === "error") return;
    if (
      dirty &&
      saveState.kind === "saved" &&
      canonicalKey === editBaseCanonicalKeyRef.current
    ) {
      return;
    }
    setDraft(canonicalDraft);
    editBaseCanonicalKeyRef.current = canonicalKey;
    setDirty(false);
  }, [canonicalKey, dirty, draft, line, saveState.kind]);
 
  useEffect(() => {
    return () => {
      Iif (timeoutRef.current) window.clearTimeout(timeoutRef.current);
    };
  }, []);
 
  useEffect(() => {
    if (!isFocused) return;
    setOpen(true);
    window.requestAnimationFrame(() => {
      if (articleRef.current) {
        scrollElementIntoEconomicsContext(articleRef.current);
      }
      articleRef.current?.focus();
    });
  }, [isFocused, line.id]);
 
  const schedulePatch = (
    patch: PatchedOperatingCostLine,
    nextDraft: Partial<typeof draft>,
  ) => {
    editBaseCanonicalKeyRef.current = canonicalKey;
    setDraft((current) => ({ ...current, ...nextDraft }));
    setDirty(true);
    setFieldMessages({});
    setSaveState({ kind: "saving", message: "Saving operating line" });
    pendingPatchRef.current = {
      ...pendingPatchRef.current,
      ...patch,
    };
    if (timeoutRef.current) window.clearTimeout(timeoutRef.current);
    timeoutRef.current = window.setTimeout(async () => {
      const mergedPatch = pendingPatchRef.current;
      pendingPatchRef.current = {};
      try {
        await onPatch(mergedPatch);
        setFieldMessages({});
        setSaveState({ kind: "saved", message: "Operating line saved" });
      } catch (error) {
        const nextFieldMessages = apiFieldMessages(error);
        setFieldMessages(nextFieldMessages);
        setOpen(true);
        setSaveState(
          allMessagesHandledInline(nextFieldMessages)
            ? { kind: "error" }
            : { kind: "error", message: mutationErrorMessage(error) },
        );
      }
    }, 300);
  };
 
  const projectDefaultPatchForRateType = (
    rateType: DefaultRateType,
    category = draft.category,
  ) => {
    const selectedDefault = selectedOperatingDefaultForRateType(
      rateType,
      category,
      assumptions,
      defaultRates,
    );
    const sourceDefaultRate = selectedDefault?.sourceDefaultRate ?? null;
    return {
      patch: {
        rate_type: rateType,
        rate_source_mode: RateSourceModeEnum.ProjectDefault,
        source_default_rate: sourceDefaultRate?.id ?? null,
        rate_amount: selectedDefault?.rateAmount || null,
        rate_unit: selectedDefault?.rateUnit || defaultRateUnit(category),
      },
      nextDraft: {
        rate_type: rateType,
        rate_source_mode: RateSourceModeEnum.ProjectDefault,
        source_default_rate: sourceDefaultRate
          ? String(sourceDefaultRate.id)
          : "",
        rate_amount: selectedDefault?.rateAmount || "",
        rate_unit: selectedDefault?.rateUnit || defaultRateUnit(category),
      },
    };
  };
 
  return (
    <article
      ref={articleRef}
      tabIndex={-1}
      className={cn(
        "operating-line-card rounded-md border bg-background",
        FOCUSED_CONTEXT_SCROLL_CLASS,
        isFocused ? "bg-primary/5 outline outline-1 outline-primary" : null,
      )}
      aria-label={`Operating line ${line.label}`}
    >
      <div className="grid grid-cols-[minmax(0,1fr)_auto] items-stretch">
        <button
          type="button"
          className="operating-line-card-toggle grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 px-3 py-2 text-left hover:bg-muted/30"
          aria-label={`Toggle operating line ${line.label}`}
          aria-expanded={open}
          aria-controls={`operating-line-details-${line.id}`}
          onClick={() => setOpen((current) => !current)}
        >
          <div className="min-w-0">
            <div className="truncate text-sm font-medium">
              {draft.label || "Untitled operating line"}
            </div>
            <div className="operating-line-card-summary mt-0.5 truncate text-xs text-muted-foreground">
              {type.polarity}
              {line.calculation_method === "work_to_cost"
                ? ` · uses ${annualOperatingHours} annual operating hours`
                : ""}
            </div>
            <div className="operating-line-card-summary mt-0.5 truncate text-xs text-muted-foreground">
              {lineSummary(draft, type)}
            </div>
          </div>
          <div className="operating-line-card-badges hidden min-w-0 flex-wrap justify-end gap-1 sm:flex">
            <SourceDefaultBadge
              rate={defaultRate}
              mode={line.rate_source_mode}
            />
            {hasSourceQuantity && (
              <Badge variant="secondary" size="xs" borderRadius="round">
                {isSourceQuantity ? "Flowsheet quantity" : "Manual override"}
              </Badge>
            )}
            {isFocused && (
              <Badge variant="secondary" size="xs" borderRadius="round">
                Selected line
              </Badge>
            )}
            {Object.values(inlineMessages).length > 0 && (
              <Badge variant="secondary" size="xs" borderRadius="round">
                Needs values
              </Badge>
            )}
          </div>
        </button>
        <div className="flex items-center gap-1 px-2 py-2">
          <OperatingLineInclusionCheckbox
            lineId={line.id}
            label={line.label}
            included={draft.included}
            canEdit={canEdit}
            error={inlineMessages.included}
            onChange={(included) => schedulePatch({ included }, { included })}
          />
          {onDelete ? (
            <>
              <Button
                type="button"
                size="sm"
                variant="ghost"
                className="h-8 px-2 text-muted-foreground"
                aria-label={`${open ? "Collapse" : "Expand"} operating line ${
                  line.label
                }`}
                aria-expanded={open}
                aria-controls={`operating-line-details-${line.id}`}
                onClick={() => setOpen((current) => !current)}
              >
                <ChevronDown
                  className={`size-4 shrink-0 transition-transform ${
                    open ? "rotate-180" : ""
                  }`}
                  aria-hidden="true"
                />
              </Button>
              <OperatingLineDeleteButton
                label={line.label}
                canEdit={canEdit}
                onDelete={onDelete}
              />
            </>
          ) : null}
        </div>
      </div>
      {open && (
        <div id={`operating-line-details-${line.id}`} className="border-t p-3">
          <div className="grid min-w-0 items-start gap-3 md:grid-cols-2 xl:grid-cols-3 [&>*]:min-w-0">
            <LineInput
              id={`operating-label-${line.id}`}
              label="Line label"
              help="Persistent label for this project operating line."
              value={draft.label}
              disabled={!canEdit}
              error={inlineMessages.label}
              onChange={(value) =>
                schedulePatch({ label: value }, { label: value })
              }
            />
            {!lockCategory && (
              <div className="grid gap-1">
                <FieldLabel
                  htmlFor={`operating-category-${line.id}`}
                  label="Operating-line type"
                  help="Controls whether this line is treated as a utility cost, utility credit, material cost, or sold output."
                />
                <Select
                  value={
                    operatingLineType(draft.category, draft.economic_effect)
                      .value
                  }
                  disabled={!canEdit}
                  onValueChange={(value) => {
                    const selectedType = operatingLineTypeForIntent(
                      value as OperatingLineIntent,
                    );
                    const category = selectedType.category;
                    const economicEffect = selectedType.economicEffect;
                    const rateType = rateTypeForCategory(category);
                    const basisUnit = defaultBasisUnit(category);
                    const rateUnit = defaultRateUnit(category);
                    const disposition =
                      category === OperatingCostLineCategoryEnum.OutputRevenue
                        ? OutletStreamDispositionEnum.Sold
                        : category === OperatingCostLineCategoryEnum.Disposal
                          ? OutletStreamDispositionEnum.Disposed
                          : BlankEnum.$;
                    const ratePatch =
                      rateType && isDefaultRateType(rateType)
                        ? projectDefaultPatchForRateType(rateType, category)
                        : {
                            patch: {
                              rate_type: BlankEnum.$,
                              rate_source_mode: RateSourceModeEnum.Custom,
                              source_default_rate: null,
                              rate_amount: null,
                              rate_unit: rateUnit,
                            },
                            nextDraft: {
                              rate_type: "",
                              rate_source_mode: RateSourceModeEnum.Custom,
                              source_default_rate: "",
                              rate_amount: "",
                              rate_unit: rateUnit,
                            },
                          };
                    schedulePatch(
                      {
                        category,
                        economic_effect: economicEffect,
                        line_type: category,
                        outlet_stream_disposition: disposition,
                        basis_quantity: null,
                        basis_unit: basisUnit,
                        basis_quantity_source:
                          BasisQuantitySourceEnum.ManualOverride,
                        source_property_info: null,
                        ...ratePatch.patch,
                      },
                      {
                        category,
                        economic_effect: economicEffect,
                        basis_quantity: "",
                        basis_unit: basisUnit,
                        basis_quantity_source:
                          BasisQuantitySourceEnum.ManualOverride,
                        ...ratePatch.nextDraft,
                      },
                    );
                  }}
                >
                  <SelectTrigger
                    id={`operating-category-${line.id}`}
                    className="min-w-0 [&>span]:min-w-0"
                  >
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {OPERATING_LINE_TYPES.map((typeOption) => (
                      <SelectItem
                        key={typeOption.value}
                        value={typeOption.value}
                      >
                        {typeOption.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError
                  id={`operating-category-${line.id}-error`}
                  message={inlineMessages.category}
                />
              </div>
            )}
            {draft.category === OperatingCostLineCategoryEnum.Energy && (
              <div className="grid gap-1">
                <FieldLabel
                  htmlFor={`operating-rate-type-${line.id}`}
                  label="Utility type"
                  help="Controls which project default and source defaults are available for this operating line."
                />
                <Select
                  value={selectedRateType ?? NONE_SELECT_VALUE}
                  disabled={!canEdit}
                  onValueChange={(value) => {
                    Iif (!isDefaultRateType(value)) return;
                    const ratePatch = projectDefaultPatchForRateType(value);
                    schedulePatch(ratePatch.patch, ratePatch.nextDraft);
                  }}
                >
                  <SelectTrigger
                    id={`operating-rate-type-${line.id}`}
                    className="min-w-0 [&>span]:min-w-0"
                  >
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {ENERGY_RATE_TYPES.map((rateType) => (
                      <SelectItem key={rateType} value={rateType}>
                        {defaultRateTypeLabel(rateType)}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FieldError
                  id={`operating-rate-type-${line.id}-error`}
                  message={inlineMessages.rate_type}
                />
              </div>
            )}
            {hasSourceQuantity && (
              <div className="grid gap-1">
                <FieldLabel
                  htmlFor={`operating-basis-source-${line.id}`}
                  label="Quantity source"
                  help="Controls whether this line follows the flowsheet property or keeps a manual operating quantity."
                />
                <Select
                  value={draft.basis_quantity_source}
                  disabled={!canEdit}
                  onValueChange={(value) => {
                    if (
                      value !== BasisQuantitySourceEnum.SourceProperty &&
                      value !== BasisQuantitySourceEnum.ManualOverride
                    ) {
                      return;
                    }
                    schedulePatch(
                      { basis_quantity_source: value },
                      { basis_quantity_source: value },
                    );
                  }}
                >
                  <SelectTrigger
                    id={`operating-basis-source-${line.id}`}
                    className="min-w-0 [&>span]:min-w-0"
                  >
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={BasisQuantitySourceEnum.SourceProperty}>
                      Flowsheet value
                    </SelectItem>
                    <SelectItem value={BasisQuantitySourceEnum.ManualOverride}>
                      Manual override
                    </SelectItem>
                  </SelectContent>
                </Select>
                <FieldError
                  id={`operating-basis-source-${line.id}-error`}
                  message={inlineMessages.basis_quantity_source}
                />
              </div>
            )}
            <ValueWithUnitSelectField
              id={`operating-basis-quantity-${line.id}`}
              unitId={`operating-basis-unit-${line.id}`}
              label={type.basisLabel}
              help="Quantity or rate used with the price. Flow and power values are annualized using the study operating hours."
              value={draft.basis_quantity}
              unit={draft.basis_unit}
              units={line.basis_unit_options}
              disabled={!canEdit}
              error={inlineMessages.basis_quantity || inlineMessages.basis_unit}
              labelClassName="text-xs font-medium"
              layout="compact"
              onValueChange={(value) =>
                schedulePatch(
                  {
                    basis_quantity: nullableString(value),
                    ...(hasSourceQuantity
                      ? {
                          basis_quantity_source:
                            BasisQuantitySourceEnum.ManualOverride,
                        }
                      : {}),
                  },
                  {
                    basis_quantity: value,
                    ...(hasSourceQuantity
                      ? {
                          basis_quantity_source:
                            BasisQuantitySourceEnum.ManualOverride,
                        }
                      : {}),
                  },
                )
              }
              onUnitChange={(value) =>
                schedulePatch(
                  {
                    basis_unit: value,
                    ...(hasSourceQuantity
                      ? {
                          basis_quantity_source:
                            BasisQuantitySourceEnum.ManualOverride,
                        }
                      : {}),
                  },
                  {
                    basis_unit: value,
                    ...(hasSourceQuantity
                      ? {
                          basis_quantity_source:
                            BasisQuantitySourceEnum.ManualOverride,
                        }
                      : {}),
                  },
                )
              }
            />
            <ValueWithUnitSelectField
              id={`operating-rate-${line.id}`}
              unitId={`operating-rate-unit-${line.id}`}
              label={type.rateLabel}
              help="Rate or price applied to the annualized basis."
              value={draft.rate_amount}
              unit={draft.rate_unit}
              units={rateUnitOptions}
              disabled={!canEdit}
              error={inlineMessages.rate_amount || inlineMessages.rate_unit}
              labelClassName="text-xs font-medium"
              layout="compact"
              onValueChange={(value) =>
                schedulePatch(
                  { rate_amount: nullableString(value) },
                  { rate_amount: value },
                )
              }
              onUnitChange={(value) =>
                schedulePatch({ rate_unit: value }, { rate_unit: value })
              }
            />
            <div className="grid gap-1">
              <FieldLabel
                htmlFor={`operating-default-rate-${line.id}`}
                label="Source/default"
                help="Choose the project default, a specific source, or clear the selection to enter a custom rate."
              />
              <Select
                value={sourceSelectValue}
                disabled={!canEdit}
                onValueChange={(value) => {
                  if (
                    value === PROJECT_DEFAULT_SELECT_VALUE &&
                    selectedRateType
                  ) {
                    const ratePatch =
                      projectDefaultPatchForRateType(selectedRateType);
                    schedulePatch(ratePatch.patch, ratePatch.nextDraft);
                    return;
                  }
                  const sourceRateId = value.startsWith(
                    SOURCE_DEFAULT_SELECT_PREFIX,
                  )
                    ? value.slice(SOURCE_DEFAULT_SELECT_PREFIX.length)
                    : "";
                  const selectedRate = sourceRates.find(
                    (rate) => String(rate.id) === sourceRateId,
                  );
                  if (!selectedRate) {
                    schedulePatch(
                      {
                        rate_source_mode: RateSourceModeEnum.Custom,
                        source_default_rate: null,
                      },
                      {
                        rate_source_mode: RateSourceModeEnum.Custom,
                        source_default_rate: "",
                      },
                    );
                    return;
                  }
                  const rateUnit =
                    selectedRate?.rate_type === RateTypeEnum.Maintenance
                      ? MAINTENANCE_RATE_UNIT
                      : (selectedRate?.display_unit ?? draft.rate_unit);
                  schedulePatch(
                    {
                      rate_type: selectedRate.rate_type,
                      rate_source_mode: RateSourceModeEnum.SourceDefault,
                      source_default_rate: selectedRate?.id ?? null,
                      rate_amount: selectedRate?.is_numeric_default_available
                        ? selectedRate.value
                        : null,
                      rate_unit: rateUnit,
                    },
                    {
                      rate_type: selectedRate.rate_type,
                      rate_source_mode: RateSourceModeEnum.SourceDefault,
                      source_default_rate: selectedRate
                        ? String(selectedRate.id)
                        : "",
                      rate_amount: selectedRate?.is_numeric_default_available
                        ? (selectedRate.value ?? "")
                        : "",
                      rate_unit: rateUnit,
                    },
                  );
                }}
              >
                <SelectTrigger
                  id={`operating-default-rate-${line.id}`}
                  className="min-w-0 [&>span]:min-w-0"
                >
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={NONE_SELECT_VALUE}>
                    No default selected
                  </SelectItem>
                  {selectedRateType && (
                    <SelectItem value={PROJECT_DEFAULT_SELECT_VALUE}>
                      {projectDefaultSourceLabel(projectDefault)}
                    </SelectItem>
                  )}
                  {sourceRates.map((rate) => (
                    <SelectItem
                      key={rate.id}
                      value={`${SOURCE_DEFAULT_SELECT_PREFIX}${rate.id}`}
                    >
                      {defaultRateOptionLabel(rate)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <FieldError
                id={`operating-default-rate-${line.id}-error`}
                message={inlineMessages.source_default_rate}
              />
            </div>
          </div>
          <FormState state={saveState} />
          {Object.values(inlineMessages).length > 0 && (
            <div className="mt-2 text-xs text-muted-foreground">
              Included lines need the highlighted values before they can be
              calculated.
            </div>
          )}
        </div>
      )}
    </article>
  );
}
 
function allMessagesHandledInline(fieldMessages: FieldMessages) {
  const fields = Object.keys(fieldMessages);
  return (
    fields.length > 0 &&
    fields.every((field) => EDITOR_FIELD_MESSAGE_KEYS.has(field))
  );
}
 
function OperatingLineInclusionCheckbox({
  lineId,
  label,
  included,
  canEdit,
  error,
  onChange,
}: {
  lineId: number;
  label: string;
  included: boolean;
  canEdit: boolean;
  error?: string;
  onChange: (included: boolean) => void;
}) {
  const errorId = `operating-included-${lineId}-error`;
 
  return (
    <div className="grid gap-1">
      <div className="inline-flex h-8 items-center gap-2 rounded-md border bg-background px-2">
        <Checkbox
          id={`operating-included-${lineId}`}
          checked={included}
          disabled={!canEdit}
          aria-label={`Include operating line ${label}`}
          aria-describedby={error ? errorId : undefined}
          onCheckedChange={(checked) => onChange(checked === true)}
        />
        <Label
          htmlFor={`operating-included-${lineId}`}
          className="cursor-pointer text-xs font-medium leading-none"
        >
          Included
        </Label>
      </div>
      <FieldError id={errorId} message={error} />
    </div>
  );
}
 
export function OperatingLineDeleteButton({
  label,
  canEdit,
  onDelete,
}: {
  label: string;
  canEdit: boolean;
  onDelete: () => Promise<void>;
}) {
  const [deleteState, setDeleteState] = useState<SaveState>({ kind: "idle" });
  const deleting = deleteState.kind === "saving";
 
  const deleteLine = async () => {
    setDeleteState({ kind: "saving", message: "Deleting operating line" });
    try {
      await onDelete();
      setDeleteState({ kind: "saved", message: "Operating line deleted" });
    } catch (error) {
      setDeleteState({
        kind: "error",
        message: mutationErrorMessage(error),
      });
    }
  };
 
  return (
    <div className="grid justify-items-end gap-1">
      <Button
        type="button"
        size="sm"
        variant="ghost"
        className="h-8 px-2 text-muted-foreground hover:text-destructive"
        disabled={!canEdit || deleting}
        aria-label={`Delete operating line ${label}`}
        title={`Delete operating line ${label}`}
        onClick={() => void deleteLine()}
      >
        <Trash2 className="size-4" aria-hidden="true" />
      </Button>
      {deleteState.kind === "error" ? <FormState state={deleteState} /> : null}
    </div>
  );
}
 
function lineSummary(
  draft: ReturnType<typeof lineDraft>,
  type: (typeof OPERATING_LINE_TYPES)[number],
) {
  const quantity = [draft.basis_quantity, draft.basis_unit]
    .filter(Boolean)
    .join(" ");
  const rateAmount = draft.rate_amount
    ? formatNumericInputValue(draft.rate_amount, {
        useGrouping: unitLooksMonetary(draft.rate_unit),
      })
    : "";
  const rate = [rateAmount, draft.rate_unit].filter(Boolean).join(" ");
  const parts = [
    quantity ? `${type.basisLabel}: ${quantity}` : "",
    rate ? `${type.rateLabel}: ${rate}` : "",
  ].filter(Boolean);
  return parts.length > 0 ? parts.join(" · ") : "No quantity or rate set";
}
 
function isDefaultRateType(value: string): value is DefaultRateType {
  return DEFAULT_RATE_TYPES.includes(value as DefaultRateType);
}
 
function projectDefaultSourceLabel(
  projectDefault:
    | ReturnType<typeof selectedOperatingDefaultForRateType>
    | undefined,
) {
  const rate = projectDefault?.sourceDefaultRate;
  const sourceLabel = rate ? defaultRateOptionLabel(rate) : "";
  return sourceLabel ? `Project default: ${sourceLabel}` : "Project default";
}
 
const DECIMAL_TEXT_PATTERN = /^[+-]?(?:\d+\.?\d*|\.\d+)$/;
 
function decimalTextMatches(draftValue: string, canonicalValue: string) {
  if (draftValue === canonicalValue) return true;
  const normalizedDraft = normalizeDecimalText(draftValue);
  const normalizedCanonical = normalizeDecimalText(canonicalValue);
  return (
    normalizedDraft !== null &&
    normalizedCanonical !== null &&
    normalizedDraft === normalizedCanonical
  );
}
 
function normalizeDecimalText(value: string) {
  const trimmed = value.trim();
  if (!DECIMAL_TEXT_PATTERN.test(trimmed)) return null;
  const isNegative = trimmed.startsWith("-");
  const unsigned = trimmed.replace(/^[+-]/, "");
  const [rawWhole, rawFraction = ""] = unsigned.split(".");
  const whole = rawWhole.replace(/^0+(?=\d)/, "") || "0";
  const fraction = rawFraction.replace(/0+$/, "");
  const normalized = fraction ? `${whole}.${fraction}` : whole;
  return normalized === "0"
    ? normalized
    : `${isNegative ? "-" : ""}${normalized}`;
}