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 | 144x 41x 73x 50x 41x 50x 41x 59x 41x 55x 41x 41x 10x 10x 10x 10x 10x 105x 9x 41x 59x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 10x 365x 73x 149x 36x 29x 5x 17x 32x 32x 36x 36x 9x 9x 9x 9x 9x 9x 9x 9x 9x 19x 10x 10x 10x 36x 10x 9x 4x 36x 31x | 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,
CostDriverPropertyOption,
CostDriverRead,
PatchedCapitalCostLine,
} from "@/api/apiStore.gen";
import {
AggregateFunctionEnum,
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 {
FieldLabel,
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;
aggregate_function: CapitalCostDriverInput["aggregate_function"];
aggregate_percentile: string;
aggregate_adjustment_percent: string;
};
type DriverInputPatchPayload = Omit<
DriverInputValue,
"aggregate_function" | "aggregate_percentile" | "aggregate_adjustment_percent"
> &
Partial<
Pick<
DriverInputValue,
| "aggregate_function"
| "aggregate_percentile"
| "aggregate_adjustment_percent"
>
>;
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: driverInputsPatchPayload(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 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,
);
const selectedPropertyOption = selectedDriverPropertyOption(
propertyOptions,
input.property_info,
);
const showAggregateControls =
hasProperty && Boolean(selectedPropertyOption?.schedule_varying);
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) => {
const propertyInfo =
value === NO_PROPERTY_VALUE ? null : Number(value);
const selectedOption = selectedDriverPropertyOption(
propertyOptions,
propertyInfo,
);
updateInput(spec, {
source:
value === NO_PROPERTY_VALUE
? BlankEnum.$
: DriverInputSourceEnum.Property,
property_info: propertyInfo,
...aggregatePatchForProperty(selectedOption),
});
}}
>
<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,
...clearAggregatePatch(),
})
}
/>
)}
{showAggregateControls && (
<ScheduleAggregateControls
capitalLineId={capitalLine.id}
spec={spec}
input={input}
disabled={disabled}
onChange={(patch) => updateInput(spec, patch)}
/>
)}
<FieldError id={fieldErrorId} message={fieldMessage} />
</div>
);
})}
<WarningList warnings={sizingWarnings} />
</div>
);
}
function ScheduleAggregateControls({
capitalLineId,
spec,
input,
disabled,
onChange,
}: {
capitalLineId: number;
spec: RequiredDriverSpec;
input: DriverInputValue;
disabled: boolean;
onChange: (patch: Partial<DriverInputValue>) => void;
}) {
const aggregateFunction =
input.aggregate_function && input.aggregate_function !== BlankEnum.$
? input.aggregate_function
: AggregateFunctionEnum.Max;
return (
<>
<div className="grid gap-2">
<FieldLabel
htmlFor={`capital-driver-aggregate-${capitalLineId}-${spec.key}`}
label="Sizing aggregate"
help="Select how this production schedule should size the equipment."
wrapperClassName="flex items-center gap-2"
/>
<Select
value={aggregateFunction}
disabled={disabled}
onValueChange={(value) =>
onChange({
aggregate_function: value as AggregateFunctionEnum,
aggregate_percentile:
value === AggregateFunctionEnum.Percentile
? input.aggregate_percentile || "50"
: input.aggregate_percentile,
})
}
>
<SelectTrigger
id={`capital-driver-aggregate-${capitalLineId}-${spec.key}`}
className="min-w-0 [&>span]:min-w-0"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={AggregateFunctionEnum.Min}>Min</SelectItem>
<SelectItem value={AggregateFunctionEnum.Max}>Max</SelectItem>
<SelectItem value={AggregateFunctionEnum.Mean}>Mean</SelectItem>
<SelectItem value={AggregateFunctionEnum.Percentile}>
Percentile
</SelectItem>
</SelectContent>
</Select>
</div>
{aggregateFunction === AggregateFunctionEnum.Percentile && (
<ValueWithFixedUnitField
id={`capital-driver-percentile-${capitalLineId}-${spec.key}`}
label="Percentile"
value={input.aggregate_percentile || "50"}
unit="%"
layout="mapping"
unitDisplay="compact-field"
disabled={disabled}
defaultToZero
onValueChange={(value) => onChange({ aggregate_percentile: value })}
/>
)}
<ValueWithFixedUnitField
id={`capital-driver-adjustment-${capitalLineId}-${spec.key}`}
label="Adjustment"
value={input.aggregate_adjustment_percent || "0"}
unit="%"
layout="mapping"
unitDisplay="compact-field"
disabled={disabled}
defaultToZero
onValueChange={(value) =>
onChange({ aggregate_adjustment_percent: value })
}
/>
</>
);
}
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,
aggregate_function: aggregateFunctionValue(
input.aggregate_function,
defaultInput.aggregate_function,
),
aggregate_percentile:
stringValue(input.aggregate_percentile) ||
defaultInput.aggregate_percentile,
aggregate_adjustment_percent:
stringValue(input.aggregate_adjustment_percent) ||
defaultInput.aggregate_adjustment_percent,
},
];
}),
);
}
function defaultDriverInput(spec: RequiredDriverSpec): DriverInputValue {
if (driverSpecIsManualOnly(spec)) {
return {
source: DriverInputSourceEnum.Manual,
property_info: null,
manual_value: defaultManualValueForSpec(spec),
unit: spec.unit,
aggregate_function: BlankEnum.$,
aggregate_percentile: "50",
aggregate_adjustment_percent: "0",
};
}
return {
source: BlankEnum.$,
property_info: null,
manual_value: "",
unit: spec.unit,
aggregate_function: BlankEnum.$,
aggregate_percentile: "50",
aggregate_adjustment_percent: "0",
};
}
function driverInputsPatchPayload(
inputs: Record<string, DriverInputValue>,
): Record<string, DriverInputPatchPayload> {
return Object.fromEntries(
Object.entries(inputs).map(([key, input]) => {
const payload = {
source: input.source,
property_info: input.property_info,
manual_value: input.manual_value,
unit: input.unit,
};
if (
input.aggregate_function &&
input.aggregate_function !== BlankEnum.$
) {
return [
key,
{
...payload,
aggregate_function: input.aggregate_function,
aggregate_percentile: input.aggregate_percentile,
aggregate_adjustment_percent: input.aggregate_adjustment_percent,
},
];
}
return [key, payload];
}),
);
}
function selectedDriverPropertyOption(
options: readonly CostDriverPropertyOption[],
propertyInfoId: number | null,
) {
if (!propertyInfoId) return undefined;
return options.find((option) => option.property_info === propertyInfoId);
}
function aggregatePatchForProperty(
option: CostDriverPropertyOption | undefined,
): Pick<
DriverInputValue,
"aggregate_function" | "aggregate_percentile" | "aggregate_adjustment_percent"
> {
if (option?.schedule_varying) {
return {
aggregate_function: AggregateFunctionEnum.Max,
aggregate_percentile: "50",
aggregate_adjustment_percent: "0",
};
}
return clearAggregatePatch();
}
function clearAggregatePatch(): Pick<
DriverInputValue,
"aggregate_function" | "aggregate_percentile" | "aggregate_adjustment_percent"
> {
return {
aggregate_function: BlankEnum.$,
aggregate_percentile: "50",
aggregate_adjustment_percent: "0",
};
}
function aggregateFunctionValue(
value: unknown,
fallback: CapitalCostDriverInput["aggregate_function"],
): CapitalCostDriverInput["aggregate_function"] {
if (
value === AggregateFunctionEnum.Min ||
value === AggregateFunctionEnum.Max ||
value === AggregateFunctionEnum.Mean ||
value === AggregateFunctionEnum.Percentile ||
value === BlankEnum.$
) {
return value;
}
return fallback;
}
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;
}
|