All files / src/pages/flowsheet-page/economics/cost-curves/authoring CostCurveDialog.tsx

79.45% Statements 58/73
87.75% Branches 43/49
93.33% Functions 14/15
79.71% Lines 55/69

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                                                                                                          101x 101x 101x 6x   101x 101x     101x 101x 101x 101x 101x 1045x   101x 1045x 62x         101x 770x     101x 101x     62x 41x           101x 649x         101x 401x   101x         101x 18x     101x       2x   2x     101x   1x 1x 1x 1x 1x   11x     101x 18x                               12x 12x 12x   13x   12x         1x 1x               1x 1x         1x   1x                                                                                                                                                                           82x 82x 24x 24x    
import { Edit, Plus } from "lucide-react";
import type { FormEvent, ReactNode } from "react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/ahuora-design-system/ui/dialog";
import { ScrollArea } from "@/ahuora-design-system/ui/scroll-area";
import type {
  CostCurveEquipmentCategoryRead,
  CostCurveRead,
} from "@/api/apiStore.gen";
import {
  apiFieldMessages,
  type CostCurveDraft,
  type CostCurveDraftDefaults,
  costCurveDraftFromRead,
  mutationErrorMessage,
  validateCostCurveDraft,
} from "../model/payloads";
import { unitOptionsOrCurrent } from "../model/unitOptions";
import type { SaveState } from "../types";
import { CostCurveForm } from "./CostCurveForm";
import { CUSTOM_EQUIPMENT_CATEGORY, uniqueOptions } from "./helpers";
 
export function CostCurveDialog({
  curve,
  canEdit,
  saving,
  open: controlledOpen,
  onOpenChange,
  trigger,
  draftDefaults,
  equipmentOptions = [],
  existingCurves = [],
  onSubmit,
}: {
  curve?: CostCurveRead;
  canEdit: boolean;
  saving: boolean;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  trigger?: ReactNode | null;
  draftDefaults?: CostCurveDraftDefaults;
  equipmentOptions?: readonly CostCurveEquipmentCategoryRead[];
  existingCurves?: readonly CostCurveRead[];
  onSubmit: (draft: CostCurveDraft) => Promise<void>;
}) {
  const [internalOpen, setInternalOpen] = useState(false);
  const open = controlledOpen ?? internalOpen;
  const [draft, setDraft] = useState<CostCurveDraft>(() =>
    costCurveDraftFromRead(curve, draftDefaults),
  );
  const [state, setState] = useState<SaveState>({ kind: "idle" });
  const [fieldMessages, setFieldMessages] = useState<Record<string, string>>(
    {},
  );
  const [selectedTemplateKey, setSelectedTemplateKey] = useState("");
  const formRef = useRef<HTMLFormElement | null>(null);
  const scrollToFirstFieldErrorRef = useRef(false);
  const mode = curve ? "edit" : "create";
  const categoryLabels = new Map(
    equipmentOptions.map((option) => [option.value, option.label]),
  );
  const effectiveCategoryOptions = uniqueOptions([
    ...equipmentOptions.map((option) => option.value),
    ...existingCurves.map((item) => item.equipment_category),
    draftDefaults?.equipment_category,
    curve?.equipment_category,
    draft.equipment_category,
  ]);
  const selectedCategoryOption = equipmentOptions.find(
    (option) => option.value === draft.equipment_category,
  );
  const hideSubtype =
    mode === "create" && draft.equipment_category === CUSTOM_EQUIPMENT_CATEGORY;
  const effectiveSubtypeOptions = uniqueOptions([
    ...(selectedCategoryOption?.subtypes ?? []),
    ...existingCurves
      .filter((item) => item.equipment_category === draft.equipment_category)
      .map((item) => item.equipment_subtype),
    draftDefaults?.equipment_subtype,
    curve?.equipment_subtype,
    draft.equipment_subtype,
  ]);
  const templateOptions =
    selectedCategoryOption?.templates.filter((template) =>
      draft.equipment_subtype
        ? template.equipment_subtype === draft.equipment_subtype
        : true,
    ) ?? [];
  const selectedTemplate =
    templateOptions.find(
      (template) => template.value === selectedTemplateKey,
    ) ?? templateOptions[0];
  const outputUnitOptions = unitOptionsOrCurrent(
    curve?.output_unit_options ?? templateOutputUnitOptions(selectedTemplate),
    draft.output_unit || draft.currency,
  );
  const defaultDriverUnitOptions =
    selectedCategoryOption?.driver_unit_options ??
    equipmentOptions.find((option) => option.driver_unit_options?.length)
      ?.driver_unit_options ??
    [];
  const wasOpenRef = useRef(open);
 
  const setOpen = (nextOpen: boolean) => {
    if (controlledOpen === undefined) {
      setInternalOpen(nextOpen);
    }
    onOpenChange?.(nextOpen);
  };
 
  useEffect(() => {
    if (open && !wasOpenRef.current) {
      setDraft(costCurveDraftFromRead(curve, draftDefaults));
      setState({ kind: "idle" });
      setFieldMessages({});
      setSelectedTemplateKey("");
      scrollToFirstFieldErrorRef.current = false;
    }
    wasOpenRef.current = open;
  }, [curve, draftDefaults, open]);
 
  useEffect(() => {
    if (!scrollToFirstFieldErrorRef.current) return;
    Iif (Object.keys(fieldMessages).length === 0) return;
    scrollToFirstFieldErrorRef.current = false;
    window.requestAnimationFrame(() => {
      const firstInvalidField = formRef.current?.querySelector<HTMLElement>(
        '[aria-invalid="true"]',
      );
      firstInvalidField?.scrollIntoView({
        block: "center",
        inline: "nearest",
      });
      firstInvalidField?.focus({ preventScroll: true });
    });
  }, [fieldMessages]);
 
  const updateDraft = (patch: Partial<CostCurveDraft>) => {
    setDraft((current) => ({ ...current, ...patch }));
    setFieldMessages((current) => {
      const next = { ...current };
      for (const key of Object.keys(patch)) {
        delete next[key];
      }
      return next;
    });
  };
 
  const submit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const validationError = validateCostCurveDraft(draft);
    if (validationError) {
      scrollToFirstFieldErrorRef.current = true;
      setFieldMessages({ [validationError.field]: validationError.message });
      setState({ kind: "idle" });
      return;
    }
    try {
      await onSubmit(draft);
      setState({
        kind: "saved",
        message: curve ? "Cost curve updated" : "Cost curve created",
      });
      if (!curve) {
        setDraft(costCurveDraftFromRead(undefined, draftDefaults));
      }
      setOpen(false);
    } catch (error) {
      const nextFieldMessages = apiFieldMessages(error);
      if (Object.keys(nextFieldMessages).length > 0) {
        scrollToFirstFieldErrorRef.current = true;
      }
      setFieldMessages(nextFieldMessages);
      setState({
        kind: "error",
        message: mutationErrorMessage(error),
      });
    }
  };
 
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      {trigger !== null && (
        <DialogTrigger asChild>
          {trigger ?? (
            <Button
              type="button"
              size="sm"
              variant={curve ? "outline" : "default"}
              disabled={!canEdit}
              aria-label={
                curve ? `Edit cost curve ${curve.name}` : "Create cost curve"
              }
            >
              {curve ? (
                <Edit className="size-4" />
              ) : (
                <Plus className="size-4" />
              )}
              {curve ? "Edit" : "Create curve"}
            </Button>
          )}
        </DialogTrigger>
      )}
      <DialogContent
        aria-label={
          curve ? "Edit cost curve dialog" : "Create cost curve dialog"
        }
        className="max-h-[90vh] overflow-hidden p-0 sm:max-w-3xl"
      >
        <ScrollArea className="max-h-[90vh]">
          <div className="grid gap-4 p-6">
            <DialogHeader>
              <DialogTitle>
                {mode === "edit" ? "Edit cost curve" : "Create cost curve"}
              </DialogTitle>
              <DialogDescription>
                Define the curve metadata, expression form, validity range, and
                notes used by unit capital lines.
              </DialogDescription>
            </DialogHeader>
            <CostCurveForm
              formRef={formRef}
              mode={mode}
              curveId={curve?.id}
              draft={draft}
              fieldMessages={fieldMessages}
              state={state}
              canEdit={canEdit}
              saving={saving}
              categoryLabels={categoryLabels}
              effectiveCategoryOptions={effectiveCategoryOptions}
              hideSubtype={hideSubtype}
              effectiveSubtypeOptions={effectiveSubtypeOptions}
              templateOptions={templateOptions}
              selectedTemplate={selectedTemplate}
              outputUnitOptions={outputUnitOptions}
              defaultDriverUnitOptions={defaultDriverUnitOptions}
              updateDraft={updateDraft}
              setSelectedTemplateKey={setSelectedTemplateKey}
              onSubmit={submit}
            />
          </div>
        </ScrollArea>
      </DialogContent>
    </Dialog>
  );
}
 
function templateOutputUnitOptions(
  template?: CostCurveEquipmentCategoryRead["templates"][number],
) {
  const outputUnitOptions = template?.output_unit_options ?? [];
  if (outputUnitOptions.length > 0) return outputUnitOptions;
  const outputUnit = template?.output_unit?.trim();
  return outputUnit ? [{ value: outputUnit, label: outputUnit }] : [];
}