All files / src/pages/flowsheet-page/economics/lang-factor EconomicsLangFactorControls.tsx

62.06% Statements 90/145
46.32% Branches 63/136
35.29% Functions 6/17
61.73% Lines 71/115

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                                            76x 76x 76x   76x   76x                                                                                               100x   25x 25x                   25x 27x   25x 27x 25x 25x 25x 25x           25x   4x 4x                                   49x             25x 53x             25x     27x 25x 1x 25x     26x 25x 25x 25x                                                 1x 25x       25x 26x 25x 25x                                                                                     75x 175x 75x   1x 25x 26x 25x 25x     25x 25x     25x               75x 175x 1x               27x 100x                                                           175x 125x                 25x 75x   25x 225x     225x     25x                 25x             225x                     225x                   200x 200x 25x                             25x                                                 3x                         50x 50x    
import { useEffect, useRef, useState } from "react";
import { Button } from "@/ahuora-design-system/ui/button";
import { Label } from "@/ahuora-design-system/ui/label";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectSeparator,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import type {
  EconomicsLangFactorDefaultRead,
  EquipmentMappingRead,
  PatchedEquipmentMapping,
} from "@/api/apiStore.gen";
import { cn } from "@/lib/utils";
import { FormattedNumericInput } from "../shared/ui/EconomicsFormFields";
import { EconomicsWarningNotice } from "../shared/ui/EconomicsWarningNotice";
 
const GLOBAL_DEFAULT_FACTOR_VALUE = "__global_default__";
const CUSTOM_FACTOR_VALUE = "__custom__";
const INSTALLED_COST_NO_FACTOR_VALUE = "__installed_cost_no_factor__";
const WARNING_INVALID_CLASS =
  "aria-[invalid=true]:border-orange-500 aria-[invalid=true]:focus-visible:border-b-orange-500";
 
const INSTALLATION_FACTOR_PRESETS = [
  {
    value: "2",
    label: "2x",
    profile: "typical_existing_infrastructure",
    guidance: "Existing foundations and services are mostly reusable.",
  },
  {
    value: "3",
    label: "3x",
    profile: "typical_new_integration",
    guidance: "Supporting infrastructure is materially incomplete.",
  },
  {
    value: "4",
    label: "4x",
    profile: "complex_or_high_risk",
    guidance: "Integration is complex, risky, or unusually site-specific.",
  },
] as const;
 
type LangFactorPreset = {
  value: string;
  label: string;
  profile: string;
  guidance: string;
  group: "general" | "equipment";
};
 
type SaveState = {
  kind: "idle" | "saving" | "saved" | "error";
  message?: string;
};
 
type EconomicsLangFactorControlsProps = {
  mapping: EquipmentMappingRead;
  unitObjectType?: string;
  langFactorDefaults?: readonly EconomicsLangFactorDefaultRead[];
  installedBasis: boolean;
  showInstalledBasisNotice: boolean;
  canEdit: boolean;
  fieldError?: string;
  saveState?: SaveState;
  className?: string;
  noticeClassName?: string;
  onMappingPatch: (patch: PatchedEquipmentMapping) => void;
};
 
export function EconomicsLangFactorControls({
  mapping,
  unitObjectType = "",
  langFactorDefaults = [],
  installedBasis,
  showInstalledBasisNotice,
  canEdit,
  fieldError,
  saveState,
  className,
  noticeClassName,
  onMappingPatch,
}: EconomicsLangFactorControlsProps) {
  const [langFactorValue, setLangFactorValue] = useState(() =>
    canonicalLangFactorForMapping(mapping),
  );
  const [langFactorDirty, setLangFactorDirty] = useState(false);
  const canonicalLangFactor = canonicalLangFactorForMapping(mapping);
  const canonicalLangFactorKey = `${canonicalLangFactor}|${mapping.updated_at ?? ""}`;
  const editBaseCanonicalKeyRef = useRef(canonicalLangFactorKey);
  const pending = saveState?.kind === "saving";
  const factorPresets = langFactorPresetOptions(
    mapping,
    langFactorDefaults,
    unitObjectType,
  );
 
  useEffect(() => {
    if (langFactorValue === canonicalLangFactor) {
      editBaseCanonicalKeyRef.current = canonicalLangFactorKey;
      setLangFactorDirty(false);
      return;
    }
    if (langFactorDirty && pending) {
      editBaseCanonicalKeyRef.current = canonicalLangFactorKey;
      return;
    }
    Iif (langFactorDirty && saveState?.kind === "error") return;
    if (
      langFactorDirty &&
      saveState?.kind === "saved" &&
      canonicalLangFactorKey === editBaseCanonicalKeyRef.current
    ) {
      return;
    }
    setLangFactorValue(canonicalLangFactor);
    editBaseCanonicalKeyRef.current = canonicalLangFactorKey;
    setLangFactorDirty(false);
  }, [
    canonicalLangFactorKey,
    canonicalLangFactor,
    langFactorDirty,
    langFactorValue,
    mapping.id,
    pending,
    saveState?.kind,
  ]);
 
  const changeLangFactor = (value: string) => {
    editBaseCanonicalKeyRef.current = canonicalLangFactorKey;
    setLangFactorValue(value);
    setLangFactorDirty(true);
  };
  const renderAsContents = className?.split(/\s+/).includes("contents");
 
  return (
    <div className={cn(renderAsContents ? null : "space-y-3", className)}>
      <div className="grid min-w-0 gap-2">
        <div className="flex min-h-6 items-center">
          <Label htmlFor={`lang-factor-preset-${mapping.id}`}>
            Lang factor source
          </Label>
        </div>
        <Select
          value={factorPresetValue(mapping, factorPresets, installedBasis)}
          disabled={!canEdit || installedBasis}
          onValueChange={(value) => {
            editBaseCanonicalKeyRef.current = canonicalLangFactorKey;
            if (value === GLOBAL_DEFAULT_FACTOR_VALUE) {
              changeLangFactor("");
              onMappingPatch({
                use_study_lang_factor: true,
                install_factor: null,
                install_factor_profile: "",
              });
              return;
            }
            if (value === CUSTOM_FACTOR_VALUE) {
              onMappingPatch({ use_study_lang_factor: false });
              return;
            }
            const preset = factorPresets.find((item) => item.value === value);
            changeLangFactor(value);
            onMappingPatch({
              use_study_lang_factor: false,
              install_factor: value,
              install_factor_profile: preset?.profile,
            });
          }}
        >
          <SelectTrigger
            id={`lang-factor-preset-${mapping.id}`}
            aria-label="Lang factor source"
            className="min-w-0 [&>span]:min-w-0"
          >
            <SelectValue placeholder="Factor preset" />
          </SelectTrigger>
          <SelectContent>
            {installedBasis ? (
              <SelectItem value={INSTALLED_COST_NO_FACTOR_VALUE}>
                Not applied for installed cost
              </SelectItem>
            ) : (
              <>
                <SelectItem value={GLOBAL_DEFAULT_FACTOR_VALUE}>
                  Use global default
                </SelectItem>
                <SelectGroup>
                  <SelectLabel>General recommendations</SelectLabel>
                  {factorPresets
                    .filter((preset) => preset.group === "general")
                    .map((preset) => (
                      <SelectItem key={preset.profile} value={preset.value}>
                        {preset.label} · {preset.guidance}
                      </SelectItem>
                    ))}
                </SelectGroup>
                {factorPresets.some(
                  (preset) => preset.group === "equipment",
                ) && (
                  <>
                    <SelectSeparator />
                    <SelectGroup>
                      <SelectLabel>
                        Unit/equipment-specific recommendations
                      </SelectLabel>
                      {factorPresets
                        .filter((preset) => preset.group === "equipment")
                        .map((preset) => (
                          <SelectItem key={preset.profile} value={preset.value}>
                            {preset.label} · {preset.guidance}
                          </SelectItem>
                        ))}
                    </SelectGroup>
                  </>
                )}
                <SelectItem value={CUSTOM_FACTOR_VALUE}>
                  Custom value
                </SelectItem>
              </>
            )}
          </SelectContent>
        </Select>
      </div>
      <div className="grid min-w-0 gap-2">
        <div className="flex min-h-6 items-center">
          <Label htmlFor={`lang-factor-${mapping.id}`}>Lang factor value</Label>
        </div>
        <FormattedNumericInput
          id={`lang-factor-${mapping.id}`}
          aria-label="Lang factor value"
          value={langFactorValue}
          disabled={!canEdit || installedBasis}
          aria-invalid={Boolean(fieldError)}
          className={WARNING_INVALID_CLASS}
          aria-describedby={
            fieldError ? `lang-factor-${mapping.id}-error` : undefined
          }
          onValueChange={(value) => {
            changeLangFactor(value);
            onMappingPatch({
              use_study_lang_factor: false,
              install_factor: nullableString(value),
            });
          }}
        />
        {fieldError && (
          <div
            id={`lang-factor-${mapping.id}-error`}
            className="text-xs text-orange-700 dark:text-orange-300"
            role="status"
          >
            {fieldError}
          </div>
        )}
      </div>
      {showInstalledBasisNotice && (
        <EconomicsWarningNotice
          aria-label="Lang factor double-counting warning"
          className={noticeClassName}
        >
          <span>
            Installed-cost basis already includes installation. Lang factors are
            not applied to this capital line to avoid double counting.
          </span>
          {mapping.install_factor && (
            <Button
              type="button"
              size="sm"
              variant="outline"
              className="mt-2"
              disabled={!canEdit}
              onClick={() => {
                changeLangFactor("");
                onMappingPatch({
                  use_study_lang_factor: false,
                  install_factor: null,
                  install_factor_profile: "installed_cost_no_factor",
                });
              }}
            >
              Clear factor
            </Button>
          )}
        </EconomicsWarningNotice>
      )}
    </div>
  );
}
 
function langFactorPresetOptions(
  mapping: EquipmentMappingRead,
  langFactorDefaults: readonly EconomicsLangFactorDefaultRead[],
  unitObjectType: string,
): LangFactorPreset[] {
  const generalPresets: LangFactorPreset[] = INSTALLATION_FACTOR_PRESETS.map(
    (preset) => ({ ...preset, group: "general" }),
  );
  const equipmentPresets = langFactorDefaults
    .filter((item) => item.review_status === "reviewed")
    .filter(
      (item) =>
        unitDefaultMatchesMapping(item, unitObjectType) ||
        equipmentDefaultMatchesMapping(item, mapping),
    )
    .map((item) => ({
      value: normalizeDecimal(item.value),
      label: `${normalizeDecimal(item.value)}x`,
      profile: item.key,
      guidance: item.equipment_subtype
        ? `${item.label} (${item.equipment_subtype})`
        : item.label,
      group: "equipment" as const,
    }));
  return [...generalPresets, ...equipmentPresets];
}
 
function unitDefaultMatchesMapping(
  item: EconomicsLangFactorDefaultRead,
  unitObjectType: string,
) {
  return (
    item.scope === "unit_operation_type" &&
    Boolean(unitObjectType) &&
    item.unit_operation_type === unitObjectType
  );
}
 
function equipmentDefaultMatchesMapping(
  item: EconomicsLangFactorDefaultRead,
  mapping: EquipmentMappingRead,
) {
  return (
    item.scope === "equipment_category" &&
    equipmentTargetMatchesMapping(item, mapping)
  );
}
 
function equipmentTargetMatchesMapping(
  item: EconomicsLangFactorDefaultRead,
  mapping: EquipmentMappingRead,
) {
  Iif (!mapping.equipment_category) return false;
  if (item.equipment_category !== mapping.equipment_category) return false;
  if (!item.equipment_subtype || !mapping.equipment_subtype) return true;
  return mapping.equipment_subtype
    .toLowerCase()
    .startsWith(item.equipment_subtype.toLowerCase());
}
 
function factorPresetValue(
  mapping: EquipmentMappingRead,
  presets: readonly LangFactorPreset[],
  installedBasis: boolean,
) {
  if (installedBasis) {
    return INSTALLED_COST_NO_FACTOR_VALUE;
  }
  if (mapping.use_study_lang_factor !== false) {
    return GLOBAL_DEFAULT_FACTOR_VALUE;
  }
  Iif (!mapping.install_factor) return CUSTOM_FACTOR_VALUE;
  const profilePreset = presets.find(
    (preset) => preset.profile === mapping.install_factor_profile,
  );
  Iif (profilePreset) return profilePreset.value;
  const matchesKnownDefault =
    mapping.lang_factor_default_value != null &&
    normalizeDecimal(mapping.install_factor) ===
      normalizeDecimal(mapping.lang_factor_default_value);
  if (mapping.lang_factor_is_custom && !matchesKnownDefault) {
    return CUSTOM_FACTOR_VALUE;
  }
  return presets.some(
    (preset) =>
      normalizeDecimal(preset.value) ===
      normalizeDecimal(mapping.install_factor ?? ""),
  )
    ? normalizeDecimal(mapping.install_factor)
    : CUSTOM_FACTOR_VALUE;
}
 
function canonicalLangFactorForMapping(mapping: EquipmentMappingRead) {
  if (mapping.use_study_lang_factor !== false) {
    return (
      mapping.effective_lang_factor ?? mapping.lang_factor_default_value ?? ""
    );
  }
  return mapping.install_factor ?? "";
}
 
function nullableString(value: string) {
  const trimmed = value.trim();
  return trimmed ? trimmed : null;
}
 
function normalizeDecimal(value: string) {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? String(parsed) : value;
}