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 | 76x 36x | import { Trash2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/ahuora-design-system/ui/button";
import { Checkbox } from "@/ahuora-design-system/ui/checkbox";
import { Input } from "@/ahuora-design-system/ui/input";
import { Label } from "@/ahuora-design-system/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/ahuora-design-system/ui/select";
import type {
CapitalCostLine,
CapitalCostLineRead,
PatchedCapitalCostLine,
} from "@/api/apiStore.gen";
import { CalculationBasisEnum, DepreciationModeEnum } from "@/api/apiStore.gen";
import { apiFieldMessages, mutationErrorMessage } from "../../cost-curves";
import {
formatAmount,
formatNumericInputValue,
} from "../../shared/model/economicsFormatters";
import { ValueWithFixedUnitField } from "../../shared/ui/EconomicsFormFields";
import { CapitalDepreciationControls } from "../depreciation/CapitalDepreciationControls";
import {
type CapitalDepreciationDraft,
capitalDepreciationDraftFromLine,
} from "../model/capitalDepreciationDraft";
import type { FieldMessages, SaveState } from "../model/capitalLineTypes";
import {
CUSTOM_CAPITAL_LINE_SOURCE,
CUSTOM_CAPITAL_LINE_TYPE,
} from "../model/customCapitalLineModel";
import {
EmptyState,
FieldError,
FormState,
SectionHeading,
} from "../ui/CapitalLineUi";
const SAVE_DELAY_MS = 300;
type CustomCapitalDraft = {
label: string;
calculation_basis: CalculationBasisEnum;
amount: string;
basis_percent: string;
included: boolean;
} & CapitalDepreciationDraft;
export function CustomCapitalLinesPanel({
studyId,
lines,
canEdit,
onCreate,
onPatch,
onDelete,
}: {
studyId: number;
lines: CapitalCostLineRead[];
canEdit: boolean;
onCreate: (line: CapitalCostLine) => Promise<void>;
onPatch: (
line: CapitalCostLineRead,
patch: PatchedCapitalCostLine,
) => Promise<void>;
onDelete: (line: CapitalCostLineRead) => Promise<void>;
}) {
const [createState, setCreateState] = useState<SaveState>({ kind: "idle" });
const createLine = async (calculationBasis: CalculationBasisEnum) => {
setCreateState({ kind: "saving", message: "Creating custom capital line" });
try {
await onCreate({
study: studyId,
label:
calculationBasis === CalculationBasisEnum.BaseCapexPercent
? "Custom percentage capital line"
: "Custom fixed capital line",
line_type: CUSTOM_CAPITAL_LINE_TYPE,
calculation_basis: calculationBasis,
amount: null,
basis_percent:
calculationBasis === CalculationBasisEnum.BaseCapexPercent
? "0.0000"
: null,
currency: "NZD",
included: true,
depreciation_mode: DepreciationModeEnum.StudyDefault,
depreciation_life_years: null,
depreciation_salvage_percent: null,
manual: true,
source: CUSTOM_CAPITAL_LINE_SOURCE,
confidence: "manual",
warning_payload: {},
});
setCreateState({ kind: "saved", message: "Custom capital line created" });
} catch (error) {
setCreateState({ kind: "error", message: mutationErrorMessage(error) });
}
};
return (
<section className="space-y-3" aria-label="Custom capital lines">
<SectionHeading
title="Custom capital lines"
count={lines.length}
help="Project capital additions entered as fixed dollar amounts or percentages of generated unit-operation CAPEX."
/>
<div className="flex flex-wrap gap-2">
<Button
type="button"
size="sm"
disabled={!canEdit || createState.kind === "saving"}
onClick={() => void createLine(CalculationBasisEnum.Fixed)}
>
Add fixed line
</Button>
<Button
type="button"
size="sm"
variant="secondary"
disabled={!canEdit || createState.kind === "saving"}
onClick={() => void createLine(CalculationBasisEnum.BaseCapexPercent)}
>
Add percentage line
</Button>
</div>
<FormState state={createState} />
{lines.length === 0 ? (
<EmptyState text="No custom capital lines have been added." />
) : (
<div className="space-y-2">
{lines.map((line) => (
<CustomCapitalLineEditor
key={line.id}
line={line}
canEdit={canEdit}
onPatch={onPatch}
onDelete={onDelete}
/>
))}
</div>
)}
</section>
);
}
function CustomCapitalLineEditor({
line,
canEdit,
onPatch,
onDelete,
}: {
line: CapitalCostLineRead;
canEdit: boolean;
onPatch: (
line: CapitalCostLineRead,
patch: PatchedCapitalCostLine,
) => Promise<void>;
onDelete: (line: CapitalCostLineRead) => Promise<void>;
}) {
const [draft, setDraft] = useState(() => draftFromLine(line));
const [fieldMessages, setFieldMessages] = useState<FieldMessages>({});
const [saveState, setSaveState] = useState<SaveState>({ kind: "idle" });
const saveTimeoutRef = useRef<number | null>(null);
const pendingPatchRef = useRef<PatchedCapitalCostLine>({});
const basisIsPercent =
draft.calculation_basis === CalculationBasisEnum.BaseCapexPercent;
useEffect(() => {
return () => {
Iif (saveTimeoutRef.current) window.clearTimeout(saveTimeoutRef.current);
};
}, []);
const schedulePatch = (
patch: PatchedCapitalCostLine,
draftPatch: Partial<CustomCapitalDraft>,
) => {
setDraft((current) => ({ ...current, ...draftPatch }));
setFieldMessages({});
setSaveState({ kind: "saving", message: "Saving custom capital line" });
pendingPatchRef.current = { ...pendingPatchRef.current, ...patch };
Iif (saveTimeoutRef.current) window.clearTimeout(saveTimeoutRef.current);
saveTimeoutRef.current = window.setTimeout(async () => {
const mergedPatch = pendingPatchRef.current;
pendingPatchRef.current = {};
try {
await onPatch(line, mergedPatch);
setFieldMessages({});
setSaveState({ kind: "saved", message: "Custom capital line saved" });
} catch (error) {
setFieldMessages(apiFieldMessages(error));
setSaveState({ kind: "error", message: mutationErrorMessage(error) });
}
}, SAVE_DELAY_MS);
};
const deleteLine = async () => {
setSaveState({ kind: "saving", message: "Deleting custom capital line" });
try {
await onDelete(line);
setSaveState({ kind: "saved", message: "Custom capital line deleted" });
} catch (error) {
setSaveState({ kind: "error", message: mutationErrorMessage(error) });
}
};
return (
<article
className="rounded-md border bg-background p-3"
aria-label={`Custom capital line ${draft.label}`}
>
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<div className="truncate text-sm font-medium">
{draft.label || "Untitled custom capital line"}
</div>
<div className="text-xs text-muted-foreground">
{basisIsPercent
? `${draft.basis_percent || "0"}% of base CAPEX`
: `${formatNumericInputValue(draft.amount, {
useGrouping: true,
})} ${line.currency ?? "NZD"}`}
</div>
</div>
<div className="flex items-center gap-2">
<div className="inline-flex h-8 items-center gap-2 rounded-md border bg-background px-2">
<Checkbox
id={`custom-capital-included-${line.id}`}
checked={draft.included}
disabled={!canEdit}
aria-label={`Include custom capital line ${draft.label}`}
onCheckedChange={(checked) =>
schedulePatch(
{ included: checked === true },
{ included: checked === true },
)
}
/>
<Label
htmlFor={`custom-capital-included-${line.id}`}
className="cursor-pointer text-xs font-medium leading-none"
>
Included
</Label>
</div>
<Button
type="button"
size="sm"
variant="ghost"
className="h-8 px-2 text-muted-foreground hover:text-destructive"
disabled={!canEdit || saveState.kind === "saving"}
aria-label={`Delete custom capital line ${draft.label}`}
onClick={() => void deleteLine()}
>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</div>
<div className="grid gap-3 md:grid-cols-3">
<div className="space-y-2">
<Label htmlFor={`custom-capital-label-${line.id}`}>Line label</Label>
<Input
id={`custom-capital-label-${line.id}`}
value={draft.label}
disabled={!canEdit}
aria-invalid={Boolean(fieldMessages.label)}
onChange={(event) =>
schedulePatch(
{ label: event.target.value },
{ label: event.target.value },
)
}
/>
<FieldError
id={`custom-capital-label-${line.id}-error`}
message={fieldMessages.label}
/>
</div>
<div className="space-y-2">
<Label htmlFor={`custom-capital-basis-${line.id}`}>Basis</Label>
<Select
value={draft.calculation_basis}
disabled={!canEdit}
onValueChange={(value) => {
const calculationBasis = value as CalculationBasisEnum;
schedulePatch(
{
calculation_basis: calculationBasis,
amount:
calculationBasis === CalculationBasisEnum.Fixed
? draft.amount || null
: null,
basis_percent:
calculationBasis === CalculationBasisEnum.BaseCapexPercent
? draft.basis_percent || "0.0000"
: null,
},
{
calculation_basis: calculationBasis,
amount:
calculationBasis === CalculationBasisEnum.Fixed
? draft.amount
: "",
basis_percent:
calculationBasis === CalculationBasisEnum.BaseCapexPercent
? draft.basis_percent || "0.0000"
: "",
},
);
}}
>
<SelectTrigger id={`custom-capital-basis-${line.id}`}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={CalculationBasisEnum.Fixed}>
Fixed amount
</SelectItem>
<SelectItem value={CalculationBasisEnum.BaseCapexPercent}>
Percent of base CAPEX
</SelectItem>
</SelectContent>
</Select>
<FieldError
id={`custom-capital-basis-${line.id}-error`}
message={fieldMessages.calculation_basis}
/>
</div>
{basisIsPercent ? (
<ValueWithFixedUnitField
id={`custom-capital-percent-${line.id}`}
label="Percentage"
value={draft.basis_percent}
unit="%"
unitDisplay="suffix"
disabled={!canEdit}
error={fieldMessages.basis_percent}
errorTone="destructive"
onValueChange={(value) =>
schedulePatch(
{ basis_percent: value || null },
{ basis_percent: value },
)
}
/>
) : (
<ValueWithFixedUnitField
id={`custom-capital-amount-${line.id}`}
label="Amount"
value={draft.amount}
unit={line.currency ?? "NZD"}
disabled={!canEdit}
error={fieldMessages.amount}
errorTone="destructive"
onValueChange={(value) =>
schedulePatch({ amount: value || null }, { amount: value })
}
/>
)}
</div>
<div className="mt-3 grid gap-3 md:grid-cols-3">
<CapitalDepreciationControls
idPrefix={`custom-capital-${line.id}`}
draft={draft}
disabled={!canEdit}
fieldMessages={fieldMessages}
onPatch={schedulePatch}
/>
</div>
{basisIsPercent && line.amount ? (
<div className="mt-2 text-xs text-muted-foreground">
Current result: {formatAmount(line.amount)} {line.currency ?? "NZD"}
</div>
) : null}
<FormState state={saveState} />
</article>
);
}
function draftFromLine(line: CapitalCostLineRead): CustomCapitalDraft {
return {
label: line.label,
calculation_basis: line.calculation_basis ?? CalculationBasisEnum.Fixed,
amount: line.amount ?? "",
basis_percent: line.basis_percent ?? "",
included: line.included ?? true,
...capitalDepreciationDraftFromLine(line),
};
}
|