All files / src/pages/flowsheet-page/economics/results-panel ProjectBaselinePanel.tsx

68.08% Statements 32/47
64.28% Branches 36/56
80% Functions 4/5
71.42% Lines 30/42

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                                  103x                     20x 20x         20x         20x 20x     20x 20x 43x   20x 23x       20x   23x 20x           1x             1x   1x                         1x 1x               1x 1x 1x                       1x 1x                                                                                                                         1x         19x     9x           37x 19x 37x      
import { AlertTriangle, Check, Loader2 } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import type { EconomicsStudyRead } from "@/api/apiStore.gen";
import {
  BaselineModeEnum,
  EconomicsBaselineMode,
  useEconomicsStudiesPartialUpdateMutation,
  useEconomicsStudiesProjectListQuery,
} from "@/api/apiStore.gen";
import { BaselineModePicker } from "../comparison-panel/BaselineModePicker";
import { GroupedEconomicsStudySelect } from "../shared/ui";
 
type StudyWithBaseline = EconomicsStudyRead & {
  baseline_study?: number | null;
};
 
const NO_BASELINE_STUDY = "__none";
 
export function ProjectBaselinePanel({
  study,
  canEdit,
  onSaved,
}: {
  study: EconomicsStudyRead;
  canEdit: boolean;
  onSaved?: () => void;
}) {
  const studyWithBaseline = study as StudyWithBaseline;
  const [baselineMode, setBaselineMode] = useState<EconomicsBaselineMode>(
    study.baseline_mode === BaselineModeEnum.Study
      ? EconomicsBaselineMode.Study
      : EconomicsBaselineMode.Manual,
  );
  const [baselineStudyId, setBaselineStudyId] = useState(
    studyWithBaseline.baseline_study
      ? String(studyWithBaseline.baseline_study)
      : NO_BASELINE_STUDY,
  );
  const [saveFailed, setSaveFailed] = useState(false);
  const projectStudiesQuery = useEconomicsStudiesProjectListQuery({
    flowsheet: study.flowsheet,
  });
  const [updateStudy, updateState] = useEconomicsStudiesPartialUpdateMutation();
  const candidateStudies = (projectStudiesQuery.currentData ?? []).filter(
    (candidate) => candidate.id !== study.id,
  );
  const selectedPickerStudyId = candidateStudies.some(
    (candidate) => String(candidate.id) === baselineStudyId,
  )
    ? baselineStudyId
    : NO_BASELINE_STUDY;
  const hasStudyBaselineCandidate = (
    projectStudiesQuery.currentData ?? []
  ).some((candidate) => candidate.id !== study.id);
  const saving = updateState.isLoading;
 
  const saveBaseline = async (
    nextMode: EconomicsBaselineMode,
    nextStudyId: string,
  ) => {
    Iif (!canEdit) return;
    if (
      nextMode === EconomicsBaselineMode.Study &&
      nextStudyId === NO_BASELINE_STUDY
    ) {
      return;
    }
    setSaveFailed(false);
    try {
      await updateStudy({
        id: study.id,
        patchedEconomicsStudy: {
          baseline_mode:
            nextMode === EconomicsBaselineMode.Study
              ? BaselineModeEnum.Study
              : BaselineModeEnum.Manual,
          baseline_study:
            nextMode === EconomicsBaselineMode.Study
              ? Number(nextStudyId)
              : null,
        },
      }).unwrap();
      setSaveFailed(false);
      onSaved?.();
    } catch {
      setSaveFailed(true);
      toast.error("Could not save baseline mode");
    }
  };
 
  const handleModeChange = (nextMode: EconomicsBaselineMode) => {
    Iif (saving) return;
    setBaselineMode(nextMode);
    const selectedStudyId = selectedBaselineStudyId(
      baselineStudyId,
      candidateStudies,
    );
    if (
      nextMode === EconomicsBaselineMode.Study &&
      selectedStudyId === NO_BASELINE_STUDY
    ) {
      setBaselineStudyId(NO_BASELINE_STUDY);
      setSaveFailed(true);
      return;
    }
    setBaselineStudyId(selectedStudyId);
    void saveBaseline(nextMode, selectedStudyId);
  };
 
  const handleStudyChange = (nextStudyId: string) => {
    Iif (saving) return;
    setBaselineStudyId(nextStudyId);
    setBaselineMode(EconomicsBaselineMode.Study);
    void saveBaseline(EconomicsBaselineMode.Study, nextStudyId);
  };
 
  return (
    <section
      className="rounded-md border bg-card p-3"
      aria-label="Project baseline"
    >
      <div className="flex min-w-0 flex-wrap items-end justify-between gap-3">
        <BaselineModePicker
          value={baselineMode}
          disabled={!canEdit || saving}
          studyModeDisabled={!hasStudyBaselineCandidate}
          studyModeDisabledReason="Create or access another economics study before using study baseline mode."
          onChange={handleModeChange}
        />
        <SaveState loading={saving} failed={saveFailed} />
      </div>
      {baselineMode === EconomicsBaselineMode.Study && (
        <div className="mt-3">
          <GroupedEconomicsStudySelect
            label="Baseline study"
            ariaLabel="Select project baseline study"
            value={selectedPickerStudyId}
            studies={candidateStudies}
            disabled={
              !canEdit ||
              saving ||
              projectStudiesQuery.isLoading ||
              candidateStudies.length === 0
            }
            placeholder={
              projectStudiesQuery.isLoading ? "Loading studies" : "Select study"
            }
            onChange={handleStudyChange}
          />
        </div>
      )}
    </section>
  );
}
 
function selectedBaselineStudyId(
  currentStudyId: string,
  candidateStudies: EconomicsStudyRead[],
) {
  if (
    currentStudyId !== NO_BASELINE_STUDY &&
    candidateStudies.some(
      (candidate) => String(candidate.id) === currentStudyId,
    )
  ) {
    return currentStudyId;
  }
  return candidateStudies[0]
    ? String(candidateStudies[0].id)
    : NO_BASELINE_STUDY;
}
 
function SaveState({ loading, failed }: { loading: boolean; failed: boolean }) {
  return (
    <div className="flex items-center gap-2 text-xs text-muted-foreground">
      {loading ? (
        <Loader2 className="size-4 animate-spin" />
      ) : failed ? (
        <AlertTriangle className="size-4 text-destructive" />
      ) : (
        <Check className="size-4" />
      )}
      {loading ? "Saving" : failed ? "Not saved" : "Saved"}
    </div>
  );
}