All files / src/pages/flowsheet-page/economics/cost-curves/assignment CostCurveDriverInputsControls.tsx

66.37% Statements 75/113
56.41% Branches 88/156
46.15% Functions 6/13
75.64% Lines 59/78

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                                                                                                                                    68x         18x   34x       20x 18x   20x 18x 22x     18x 21x 18x       18x       2x           2x                       2x       2x 2x 50x       2x 18x   22x   17x 17x 17x 17x 17x     17x     17x 17x 17x 17x 17x 17x       17x                                                                                                                                           2x                     171x 34x 69x       17x 16x   1x           3x       16x 16x                           17x           17x                       2x     2x   2x   2x     2x   2x         2x       2x 2x                                                             4x                               1x           17x             3x                  
import { useState } from "react";
import { Label } from "@/ahuora-design-system/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import type {
  CapitalCostDriverInput,
  CapitalCostLineRead,
  CostCurveRead,
  CostDriverRead,
  PatchedCapitalCostLine,
} from "@/api/apiStore.gen";
import {
  BlankEnum,
  SourceCa8Enum as DriverInputSourceEnum,
  RoleEnum,
  SourceOptionsEnum,
  useEconomicsCostDriversPropertyOptionsListQuery,
} from "@/api/apiStore.gen";
import { cn } from "@/lib/utils";
import {
  NO_PROPERTY_VALUE,
  PropertyOptionGroup,
} from "../../cost-driver/EconomicsCostDriverControls";
import { propertyOptionsByPickerGroup } from "../../cost-driver/model/propertyOptionGroups";
import { ValueWithFixedUnitField } from "../../shared/ui/EconomicsFormFields";
import { EconomicsWarningNotice } from "../../shared/ui/EconomicsWarningNotice";
import {
  defaultManualValueForSpec,
  driverSpecIsManualOnly,
  type RequiredDriverSpec,
  requiredDriverSpecsFromCurve,
} from "../model/driverSpecs";
 
type DriverInputSource = Exclude<CapitalCostDriverInput["source"], undefined>;
 
/**
 * User-selected value for one declared cost-curve driver.
 *
 * These records are stored under `CapitalCostLine.driver_inputs[spec.key]` so
 * a multi-driver curve can collect one property/manual choice per declared
 * input.
 */
type DriverInputValue = {
  source: DriverInputSource;
  property_info: number | null;
  manual_value: string;
  unit: string;
};
 
type CostCurveDriverInputsControlsProps = {
  driver: CostDriverRead;
  capitalLine: CapitalCostLineRead;
  selectedCurve: CostCurveRead;
  canEdit: boolean;
  busy?: boolean;
  error?: string;
  sizingWarnings?: string[];
  className?: string;
  onCapitalLinePatch: (patch: PatchedCapitalCostLine) => void;
};
 
export function CostCurveDriverInputsControls({
  driver,
  capitalLine,
  selectedCurve,
  canEdit,
  busy = false,
  error,
  sizingWarnings = [],
  className,
  onCapitalLinePatch,
}: CostCurveDriverInputsControlsProps) {
  const specs = requiredDriverSpecsFromCurve(selectedCurve);
  const optionsQuery = useEconomicsCostDriversPropertyOptionsListQuery({
    id: driver.id,
  });
  const [driverInputs, setDriverInputs] = useState(() =>
    normalizedDriverInputs(capitalLine.driver_inputs, specs),
  );
 
  const disabled = !canEdit || busy;
  const propertyOptions = optionsQuery.currentData ?? [];
  const renderAsContents = className?.split(/\s+/).includes("contents");
  const requiredInputMessage =
    "Select a compatible property or enter a custom value.";
 
  const updateInput = (
    spec: RequiredDriverSpec,
    patch: Partial<DriverInputValue>,
  ) => {
    const rawNextInput = {
      ...defaultDriverInput(spec),
      ...driverInputs[spec.key],
      ...patch,
      unit: spec.unit,
    };
    const nextInput = {
      ...rawNextInput,
      property_info:
        rawNextInput.source === DriverInputSourceEnum.Property
          ? rawNextInput.property_info
          : null,
      manual_value:
        rawNextInput.source === DriverInputSourceEnum.Manual
          ? rawNextInput.manual_value
          : "",
      unit: spec.unit,
    };
    const nextInputs = {
      ...driverInputs,
      [spec.key]: nextInput,
    };
    setDriverInputs(nextInputs);
    onCapitalLinePatch({ driver_inputs: nextInputs });
  };
 
  return (
    <div
      className={cn(
        renderAsContents ? "contents text-sm" : "space-y-3 text-sm",
        className,
      )}
    >
      {specs.map((spec) => {
        const input = driverInputs[spec.key] ?? defaultDriverInput(spec);
        const hasProperty = Boolean(input.property_info);
        const inputMissing = spec.required && !hasDriverInputValue(input);
        const allowProperty = spec.sourceOptions.includes(
          SourceOptionsEnum.Property,
        );
        const allowManual = spec.sourceOptions.includes(
          SourceOptionsEnum.Manual,
        );
        const manualOnly = driverSpecIsManualOnly(spec);
        const propertyLabel = driverInputPropertyLabel(spec);
        const manualLabel = driverInputManualLabel(spec);
        const fieldMessage = error && inputMissing ? requiredInputMessage : "";
        const fieldErrorId = `capital-driver-input-${capitalLine.id}-${spec.key}-error`;
        const optionGroups = propertyOptionsByPickerGroup(
          propertyOptions,
          spec.unit,
          driver.manual_property_info,
        );
        return (
          <div
            key={spec.key}
            className="economics-driver-input-row economics-mapping-controls-grid-full grid min-w-0 gap-2"
          >
            {allowProperty && (
              <div className="grid min-w-0 gap-2">
                <Label
                  htmlFor={`capital-driver-property-${capitalLine.id}-${spec.key}`}
                >
                  {propertyLabel}
                </Label>
                <Select
                  value={
                    hasProperty
                      ? String(input.property_info)
                      : NO_PROPERTY_VALUE
                  }
                  disabled={disabled || optionsQuery.isLoading}
                  onValueChange={(value) =>
                    updateInput(spec, {
                      source:
                        value === NO_PROPERTY_VALUE
                          ? BlankEnum.$
                          : DriverInputSourceEnum.Property,
                      property_info:
                        value === NO_PROPERTY_VALUE ? null : Number(value),
                    })
                  }
                >
                  <SelectTrigger
                    id={`capital-driver-property-${capitalLine.id}-${spec.key}`}
                    aria-label={propertyLabel}
                    aria-invalid={Boolean(fieldMessage) || inputMissing}
                    aria-describedby={fieldMessage ? fieldErrorId : undefined}
                    className="min-w-0 aria-[invalid=true]:border-orange-500 aria-[invalid=true]:focus-visible:border-b-orange-500 [&>span]:min-w-0"
                  >
                    <SelectValue
                      placeholder={`Select ${spec.label.toLowerCase()}`}
                    />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={NO_PROPERTY_VALUE}>
                      No property selected
                    </SelectItem>
                    {optionGroups.map((group) => (
                      <PropertyOptionGroup group={group} key={group.label} />
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
            {allowManual && (
              <ValueWithFixedUnitField
                id={`capital-driver-manual-${capitalLine.id}-${spec.key}`}
                label={manualLabel}
                value={input.manual_value}
                unit={spec.unit}
                layout="mapping"
                unitDisplay="compact-field"
                disabled={disabled || hasProperty}
                defaultToZero={Boolean(defaultManualValueForSpec(spec))}
                error={fieldMessage}
                invalid={Boolean(fieldMessage) || inputMissing}
                messageId={fieldErrorId}
                renderError={false}
                valueAriaLabel={manualLabel}
                unitAriaLabel={`${manualLabel} unit`}
                onValueChange={(value) =>
                  updateInput(spec, {
                    source: DriverInputSourceEnum.Manual,
                    property_info: null,
                    manual_value: value,
                  })
                }
              />
            )}
            <FieldError id={fieldErrorId} message={fieldMessage} />
          </div>
        );
      })}
      <WarningList warnings={sizingWarnings} />
    </div>
  );
}
 
function FieldError({ id, message }: { id: string; message?: string }) {
  Iif (!message) return null;
  return (
    <div
      id={id}
      className="col-span-full text-xs text-orange-700 dark:text-orange-300"
      role="status"
    >
      {message}
    </div>
  );
}
 
function WarningList({ warnings }: { warnings: string[] }) {
  Iif (warnings.length === 0) return null;
  return (
    <div className="economics-mapping-controls-grid-full col-span-full space-y-2">
      {warnings.map((warning) => (
        <EconomicsWarningNotice key={warning} aria-label={warning}>
          {warning}
        </EconomicsWarningNotice>
      ))}
    </div>
  );
}
 
function driverInputPropertyLabel(spec: RequiredDriverSpec) {
  if (spec.primary && spec.role === RoleEnum.FormulaInput) {
    return "Sizing property";
  }
  return `${spec.label} property`;
}
 
function driverInputManualLabel(spec: RequiredDriverSpec) {
  return spec.primary && spec.role === RoleEnum.FormulaInput
    ? "Custom sizing value"
    : `${spec.label} manual value`;
}
 
function normalizedDriverInputs(
  rawInputs: unknown,
  specs: RequiredDriverSpec[],
): Record<string, DriverInputValue> {
  // `driver_inputs` is intentionally a keyed JSON object. Keep parsing local
  // and curve-scoped so keys not declared by the selected curve are dropped.
  const existing =
    rawInputs && typeof rawInputs === "object"
      ? (rawInputs as Record<string, unknown>)
      : {};
  return Object.fromEntries(
    specs.map((spec) => {
      const rawInput = existing[spec.key];
      const input =
        rawInput && typeof rawInput === "object"
          ? (rawInput as Record<string, unknown>)
          : {};
      const defaultInput = defaultDriverInput(spec);
      const candidateSource =
        input.source === DriverInputSourceEnum.Property ||
        input.source === DriverInputSourceEnum.Manual
          ? input.source
          : null;
      const rawSource =
        candidateSource &&
        driverInputSourceAllowedForSpec(spec, candidateSource)
          ? candidateSource
          : null;
      const source = rawSource ?? defaultInput.source;
      return [
        spec.key,
        {
          ...defaultInput,
          source,
          property_info:
            source === DriverInputSourceEnum.Property
              ? numberValue(input.property_info)
              : null,
          manual_value:
            source === DriverInputSourceEnum.Manual
              ? rawSource === DriverInputSourceEnum.Manual
                ? stringValue(input.manual_value)
                : defaultInput.manual_value
              : "",
          unit: stringValue(input.unit) || spec.unit,
        },
      ];
    }),
  );
}
 
function defaultDriverInput(spec: RequiredDriverSpec): DriverInputValue {
  if (driverSpecIsManualOnly(spec)) {
    return {
      source: DriverInputSourceEnum.Manual,
      property_info: null,
      manual_value: defaultManualValueForSpec(spec),
      unit: spec.unit,
    };
  }
  return {
    source: BlankEnum.$,
    property_info: null,
    manual_value: "",
    unit: spec.unit,
  };
}
 
function driverInputSourceAllowedForSpec(
  spec: RequiredDriverSpec,
  source: DriverInputSource,
) {
  if (source === DriverInputSourceEnum.Property) {
    return spec.sourceOptions.includes(SourceOptionsEnum.Property);
  }
  if (source === DriverInputSourceEnum.Manual) {
    return spec.sourceOptions.includes(SourceOptionsEnum.Manual);
  }
  return false;
}
 
function hasDriverInputValue(input: DriverInputValue) {
  return input.source === DriverInputSourceEnum.Property
    ? Boolean(input.property_info)
    : input.source === DriverInputSourceEnum.Manual &&
        Boolean(input.manual_value);
}
 
function stringValue(value: unknown) {
  return value == null ? "" : String(value);
}
 
function numberValue(value: unknown) {
  Iif (typeof value === "number" && Number.isFinite(value)) return value;
  Iif (typeof value !== "string" || !value.trim()) return null;
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : null;
}