All files / src/pages/flowsheet-page/economics/cost-driver EconomicsCostDriverControls.tsx

9.37% Statements 18/192
4.51% Branches 8/177
13.33% Functions 2/15
10.14% Lines 14/138

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                                                              76x   76x   76x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   30x       30x     68x         38x   30x 30x   34x 30x 30x           60x   90x                                  
import { useEffect, useMemo, useRef, useState } from "react";
import { Label } from "@/ahuora-design-system/ui/label";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectSeparator,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import type {
  CostDriverPropertyOption,
  CostDriverRead,
  PatchedCostDriver,
} from "@/api/apiStore.gen";
import {
  CostDriverSourceEnum as SourceEnum,
  useEconomicsCostDriversPropertyOptionsListQuery,
} from "@/api/apiStore.gen";
import { cn } from "@/lib/utils";
import { costCurveUnitsCompatible } from "../shared/model/economicsUnitCompatibility";
import { FormattedNumericInput } from "../shared/ui/EconomicsFormFields";
import { EconomicsWarningNotice } from "../shared/ui/EconomicsWarningNotice";
import {
  type PropertyOptionPickerGroup,
  propertyOptionsByPickerGroup,
} from "./model/propertyOptionGroups";
 
export const NO_PROPERTY_VALUE = "__none__";
const SIZING_PROPERTY_HELP =
  "Select the flowsheet property that provides the sizing value for the cost curve. Choose a property whose unit matches the curve input, or enter a custom sizing value when no suitable property is available.";
const WARNING_INVALID_CLASS =
  "aria-[invalid=true]:border-orange-500 aria-[invalid=true]:focus-visible:border-b-orange-500";
 
type SaveState = {
  kind: "idle" | "saving" | "saved" | "error";
  message?: string;
};
 
type FieldMessages = Record<string, string>;
 
type EconomicsCostDriverControlsProps = {
  driver: CostDriverRead;
  canEdit: boolean;
  selectedCurveInputUnit?: string | null;
  sizingWarnings?: string[];
  optionsRefreshKey?: string;
  busy?: boolean;
  fieldMessages?: FieldMessages;
  saveState?: SaveState;
  className?: string;
  noticeClassName?: string;
  onDriverPatch: (patch: PatchedCostDriver) => void;
};
 
export function EconomicsCostDriverControls({
  driver,
  canEdit,
  selectedCurveInputUnit,
  sizingWarnings = [],
  optionsRefreshKey,
  busy = false,
  fieldMessages = {},
  saveState,
  className,
  noticeClassName,
  onDriverPatch,
}: EconomicsCostDriverControlsProps) {
  const optionsQuery = useEconomicsCostDriversPropertyOptionsListQuery({
    id: driver.id,
  });
  const refetchOptionsRef = useRef(optionsQuery.refetch);
  const mountedRef = useRef(false);
  const [manualValue, setManualValue] = useStableManualValue(driver, saveState);
  const propertyOptionGroups = useMemo(
    () =>
      propertyOptionsByPickerGroup(
        optionsQuery.currentData ?? [],
        selectedCurveInputUnit,
        driver.manual_property_info,
      ),
    [
      driver.manual_property_info,
      optionsQuery.currentData,
      selectedCurveInputUnit,
    ],
  );
  useEffect(() => {
    refetchOptionsRef.current = optionsQuery.refetch;
  }, [optionsQuery.refetch]);
  useEffect(() => {
    if (!mountedRef.current) {
      mountedRef.current = true;
      return;
    }
    void refetchOptionsRef.current();
  }, [optionsRefreshKey]);
  const isUnresolved = driver.source === SourceEnum.Unresolved;
  const disabled = !canEdit || busy;
  const sizingSelectionBlocked = !selectedCurveInputUnit;
  const selectedPropertyCompatible =
    !driver.property_info ||
    driver.property_info === driver.manual_property_info ||
    !selectedCurveInputUnit ||
    !driver.canonical_unit ||
    costCurveUnitsCompatible(driver.canonical_unit, selectedCurveInputUnit);
  const selectedPropertyIncompatible =
    Boolean(driver.property_info) && !selectedPropertyCompatible;
  const hasSizingProperty = Boolean(
    driver.property_info &&
      driver.property_info !== driver.manual_property_info &&
      selectedPropertyCompatible,
  );
  const propertyFieldError =
    fieldMessages.property_info ||
    (selectedPropertyIncompatible
      ? "Choose a compatible sizing property or enter a custom value."
      : "");
  const renderAsContents = className?.split(/\s+/).includes("contents");
  return (
    <div
      className={cn(
        renderAsContents ? "text-sm" : "space-y-3 text-sm",
        className,
      )}
    >
      <div className="grid min-w-0 gap-2">
        <div className="flex min-h-6 items-center gap-2">
          <Label htmlFor={`cost-driver-property-${driver.id}`}>
            Sizing property
          </Label>
          <ToolTipCover content={SIZING_PROPERTY_HELP} asChild side="right">
            <span
              aria-label="Sizing property help"
              className="inline-flex size-4 items-center justify-center rounded-full border text-[10px] text-muted-foreground"
              tabIndex={0}
            >
              ?
            </span>
          </ToolTipCover>
        </div>
        <Select
          value={
            hasSizingProperty ? String(driver.property_info) : NO_PROPERTY_VALUE
          }
          disabled={
            disabled || optionsQuery.isLoading || sizingSelectionBlocked
          }
          onValueChange={(value) =>
            onDriverPatch({
              property_info: value === NO_PROPERTY_VALUE ? null : Number(value),
            })
          }
        >
          <SelectTrigger
            id={`cost-driver-property-${driver.id}`}
            aria-label="Sizing property"
            aria-invalid={Boolean(propertyFieldError)}
            className={cn("min-w-0 [&>span]:min-w-0", WARNING_INVALID_CLASS)}
          >
            <SelectValue placeholder="Select sizing property" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={NO_PROPERTY_VALUE}>
              No sizing property selected
            </SelectItem>
            {propertyOptionGroups.map((group) => (
              <PropertyOptionGroup group={group} key={group.label} />
            ))}
          </SelectContent>
        </Select>
        <FieldError message={propertyFieldError} />
      </div>
      <div className="grid min-w-0 gap-2">
        <div className="flex min-h-6 items-center">
          <Label htmlFor={`manual-driver-${driver.id}`}>
            Custom sizing value
          </Label>
        </div>
        <FormattedNumericInput
          id={`manual-driver-${driver.id}`}
          aria-label="Custom sizing value"
          value={manualValue}
          defaultToZero={false}
          disabled={disabled || sizingSelectionBlocked || hasSizingProperty}
          aria-invalid={Boolean(fieldMessages.design_value)}
          className={WARNING_INVALID_CLASS}
          onValueChange={(value) => {
            setManualValue(value);
            onDriverPatch({
              source: SourceEnum.ManualOverride,
              sizing_mode: "manual",
              design_value: nullableString(value),
            });
          }}
        />
        <FieldError message={fieldMessages.design_value} />
        {!sizingSelectionBlocked && (
          <WarningList
            label="Sizing value warnings"
            warnings={sizingWarnings}
          />
        )}
      </div>
      {!sizingSelectionBlocked && isUnresolved && (
        <EconomicsWarningNotice
          aria-label="Sizing property warning"
          className={noticeClassName}
        >
          Select a compatible sizing property or enter a custom sizing value.
        </EconomicsWarningNotice>
      )}
      {selectedPropertyIncompatible && (
        <EconomicsWarningNotice
          aria-label="Sizing property compatibility warning"
          className={noticeClassName}
        >
          The selected sizing property is not compatible with the cost curve
          input unit. Choose another property or enter a custom sizing value.
        </EconomicsWarningNotice>
      )}
    </div>
  );
}
 
function WarningList({
  label,
  warnings,
}: {
  label: string;
  warnings: string[];
}) {
  Iif (warnings.length === 0) return null;
  return (
    <div className="space-y-1" aria-label={label}>
      {warnings.map((warning) => (
        <EconomicsWarningNotice key={warning} aria-label={warning}>
          <span>{warning}</span>
        </EconomicsWarningNotice>
      ))}
    </div>
  );
}
 
function useStableManualValue(
  driver: CostDriverRead,
  saveState?: SaveState,
): [string, (value: string) => void] {
  const [manualValue, setManualValue] = useState(driver.design_value ?? "");
  const [manualDirty, setManualDirty] = useState(false);
  const canonicalManualValue = driver.design_value ?? "";
  const canonicalManualKey = `${canonicalManualValue}|${driver.updated_at ?? ""}`;
  const editBaseCanonicalKeyRef = useRef(canonicalManualKey);
  const pending = saveState?.kind === "saving";
  useEffect(() => {
    if (manualValue === canonicalManualValue) {
      editBaseCanonicalKeyRef.current = canonicalManualKey;
      setManualDirty(false);
      return;
    }
    if (manualDirty && pending) {
      editBaseCanonicalKeyRef.current = canonicalManualKey;
      return;
    }
    Iif (manualDirty && saveState?.kind === "error") return;
    if (
      manualDirty &&
      saveState?.kind === "saved" &&
      canonicalManualKey === editBaseCanonicalKeyRef.current
    ) {
      return;
    }
    setManualValue(canonicalManualValue);
    editBaseCanonicalKeyRef.current = canonicalManualKey;
    setManualDirty(false);
  }, [
    canonicalManualKey,
    canonicalManualValue,
    driver.id,
    manualDirty,
    manualValue,
    pending,
    saveState?.kind,
  ]);
 
  const setDirtyManualValue = (value: string) => {
    editBaseCanonicalKeyRef.current = canonicalManualKey;
    setManualValue(value);
    setManualDirty(true);
  };
 
  return [manualValue, setDirtyManualValue];
}
 
function propertyOptionLabel(
  option: CostDriverPropertyOption,
  group: PropertyOptionPickerGroup,
) {
  const propertyName = `${option.display_name}${option.unit ? ` (${option.unit})` : ""}`;
  if (group.label === "Unit properties") {
    return propertyName;
  }
  return `${option.object_name} ยท ${propertyName}`;
}
 
export function PropertyOptionGroup({
  group,
}: {
  group: PropertyOptionPickerGroup;
}) {
  Iif (group.options.length === 0) return null;
  return (
    <>
      <SelectSeparator />
      <SelectGroup>
        <SelectLabel>{group.label}</SelectLabel>
        {group.options.map((option) => (
          <SelectItem
            key={`${option.scope}-${option.property_info}`}
            value={String(option.property_info)}
          >
            {propertyOptionLabel(option, group)}
          </SelectItem>
        ))}
      </SelectGroup>
    </>
  );
}
 
function FieldError({ message }: { message?: string }) {
  Iif (!message) return null;
  return (
    <div className="text-xs text-orange-700 dark:text-orange-300" role="status">
      {message}
    </div>
  );
}
 
function nullableString(value: string) {
  const trimmed = value.trim();
  return trimmed ? trimmed : null;
}