All files / src/pages/flowsheet-page/economics/schedule-selector EconomicsScheduleSelector.tsx

86.2% Statements 25/29
81.81% Branches 9/11
100% Functions 0/0
89.28% Lines 25/28

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                                                                          274x     274x 274x 274x 274x 274x 274x 274x 274x 274x     5x   1x 1x 1x   1x           1x                   1x   1x   4x   4x                         4x 4x       4x                                                                                                           2x 2x                    
import { CalendarClock } from "lucide-react";
import { useState } from "react";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/ahuora-design-system/ui/accordion";
import type { EconomicsStudyRead } from "@/api/apiStore.gen";
import {
  ScheduleModeEnum,
  useEconomicsStudiesPartialUpdateMutation,
  useEconomicsStudiesScheduleOptionsListQuery,
  useEconomicsStudiesSchedulePlanUpdateMutation,
} from "@/api/apiStore.gen";
import { CompositeScheduleEditor } from "./CompositeScheduleEditor";
import { ScheduleModeSelect } from "./ScheduleModeSelect";
import { SchedulePreviewSummary } from "./SchedulePreviewSummary";
import {
  COMPOSITE_SCHEDULE_VALUE,
  defaultRule,
  rulesPayloadForSave,
  type ScheduleSelectValue,
  STEADY_SCHEDULE_VALUE,
  scheduleSelectValueForStudy,
} from "./scheduleEditorModel";
import { scheduleMutationErrorMessage } from "./scheduleErrors";
 
export function EconomicsScheduleSelector({
  study,
  canEdit,
  onSaved,
}: {
  study: EconomicsStudyRead;
  canEdit: boolean;
  onSaved?: () => void;
}) {
  const optionsQuery = useEconomicsStudiesScheduleOptionsListQuery({
    id: study.id,
  });
  const options = optionsQuery.currentData ?? [];
  const [updateStudy] = useEconomicsStudiesPartialUpdateMutation();
  const [saveCompositePlan] = useEconomicsStudiesSchedulePlanUpdateMutation();
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);
  const [draftMode, setDraftMode] = useState<ScheduleSelectValue | null>(null);
  const backendScheduleValue = scheduleSelectValueForStudy(study);
  const scheduleValue = draftMode ?? backendScheduleValue;
  const editorVisible = scheduleValue === COMPOSITE_SCHEDULE_VALUE;
 
  const updateSchedule = async (value: ScheduleSelectValue) => {
    setError("");
    if (value === COMPOSITE_SCHEDULE_VALUE) {
      setDraftMode(COMPOSITE_SCHEDULE_VALUE);
      Iif (!options.length) return;
      setSaving(true);
      try {
        await saveCompositePlan({
          id: study.id,
          compositeSchedulePlanRequest: {
            rules: rulesPayloadForSave([defaultRule(options)]),
          },
        }).unwrap();
        onSaved?.();
      } catch (saveError) {
        setDraftMode(null);
        setError(
          scheduleMutationErrorMessage(
            saveError,
            "Production schedule could not be saved.",
          ),
        );
      } finally {
        setSaving(false);
      }
      return;
    }
    setSaving(true);
    try {
      await updateStudy({
        id: study.id,
        patchedEconomicsStudy:
          value === STEADY_SCHEDULE_VALUE
            ? {
                schedule_mode: ScheduleModeEnum.SteadyState,
                schedule_scenario: null,
              }
            : {
                schedule_mode: ScheduleModeEnum.Scenario,
                schedule_scenario: Number(value),
              },
      }).unwrap();
      setDraftMode(null);
      onSaved?.();
    } catch {
      setError("Production schedule could not be saved.");
    } finally {
      setSaving(false);
    }
  };
 
  return (
    <section
      className="rounded-md border bg-background p-3"
      aria-label="Production schedule"
    >
      <div className="mb-3 flex items-center gap-2">
        <div className="flex min-w-0 items-center gap-2">
          <CalendarClock className="size-4 shrink-0 text-primary" />
          <h4 className="truncate text-sm font-semibold">
            Production schedule
          </h4>
        </div>
      </div>
      <div className="grid gap-3 md:grid-cols-[minmax(0,22rem)_minmax(0,1fr)]">
        <ScheduleModeSelect
          studyId={study.id}
          value={scheduleValue}
          options={options}
          canEdit={canEdit}
          loading={optionsQuery.isLoading}
          saving={saving}
          error={error}
          onValueChange={updateSchedule}
        />
        <SchedulePreviewSummary study={study} selectedValue={scheduleValue} />
      </div>
      {editorVisible && (
        <Accordion
          type="single"
          collapsible
          defaultValue="weekly-composite-timetable"
          className="mt-4 border-t pt-4"
        >
          <AccordionItem
            value="weekly-composite-timetable"
            className="border-0 text-sm"
          >
            <AccordionTrigger className="px-0 py-0 text-sm font-semibold text-foreground hover:bg-transparent [&[data-state=open]]:bg-transparent">
              Weekly composite timetable
            </AccordionTrigger>
            <AccordionContent className="mt-0 px-0 pb-0 pt-4">
              <CompositeScheduleEditor
                studyId={study.id}
                canEdit={canEdit}
                options={options}
                requiresSavedPlan={
                  backendScheduleValue === COMPOSITE_SCHEDULE_VALUE &&
                  draftMode === null
                }
                onSaved={() => {
                  setDraftMode(null);
                  onSaved?.();
                }}
              />
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      )}
    </section>
  );
}