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

73.07% Statements 76/104
63.1% Branches 65/103
36.84% Functions 7/19
87.5% Lines 63/72

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                                                        20x                         20x   22x 20x 20x       20x 20x   20x 20x 20x 20x 20x 20x 53x 20x   20x 20x       29x   20x       2x   4x     31x   20x           42x   20x 3x 3x 3x   3x           2x 2x 2x 1x 1x             84x   20x       2x 58x   20x 1x                 77x   20x             77x   20x   1x 1x 1x 1x     23x         20x 32x                 2x       1x   240x 19x               20x     58x 60x 3x       23x 36x 26x 100x      
import { Plus } from "lucide-react";
import { useState } from "react";
import { useSearchParams } from "react-router-dom";
import { Button } from "@/ahuora-design-system/ui/button";
import type {
  CompositeScheduleRuleDraft,
  ScheduleScenarioOption,
} from "@/api/apiStore.gen";
import {
  useEconomicsStudiesSchedulePlanRetrieveQuery,
  useEconomicsStudiesSchedulePlanUpdateMutation,
} from "@/api/apiStore.gen";
import { ContentTypes } from "../../flowsheet/LeftSideBar/LeftSideBarTabDefinitions";
import { CompositeScheduleRuleRow } from "./CompositeScheduleRuleRow";
import {
  CompositeScheduleDiagnostics,
  CompositeScheduleTimetable,
} from "./CompositeScheduleTimetable";
import {
  compositeEditorMessage,
  defaultRule,
  defaultRuleForAppend,
  normalizeRuleSortOrder,
  rulesPayloadForSave,
  savedRulesForEditing,
} from "./scheduleEditorModel";
import { scheduleMutationErrorMessage } from "./scheduleErrors";
 
export function CompositeScheduleEditor({
  studyId,
  canEdit,
  options,
  requiresSavedPlan,
  onSaved,
}: {
  studyId: number;
  canEdit: boolean;
  options: ScheduleScenarioOption[];
  requiresSavedPlan: boolean;
  onSaved: () => void;
}) {
  const planQuery = useEconomicsStudiesSchedulePlanRetrieveQuery({
    id: studyId,
  });
  const [savePlan, saveState] = useEconomicsStudiesSchedulePlanUpdateMutation();
  const [editedRulesByStudy, setEditedRulesByStudy] = useState<{
    studyId: number;
    rules: CompositeScheduleRuleDraft[];
  } | null>(null);
  const [localError, setLocalError] = useState("");
  const plan = planQuery.currentData;
  const editedRules =
    editedRulesByStudy?.studyId === studyId ? editedRulesByStudy.rules : null;
  const [, setSearchParams] = useSearchParams();
  const loadingPlan = (planQuery.isLoading || planQuery.isFetching) && !plan;
  const savedPlanError = requiresSavedPlan && planQuery.isError;
  const planUnavailable = loadingPlan || savedPlanError;
  const hasSourceSchedules = options.length > 0;
  const rules = editedRules ?? savedRulesForEditing(plan, options);
  const saving = saveState.isLoading;
  const controlsDisabled =
    !canEdit || saving || planUnavailable || !hasSourceSchedules;
  const editorMessage = compositeEditorMessage({
    hasSourceSchedules,
    loadingPlan,
    planError: savedPlanError,
  });
 
  const rulesWithPatch = (
    index: number,
    patch: Partial<CompositeScheduleRuleDraft>,
  ) => {
    return normalizeRuleSortOrder(
      rules.map((rule, ruleIndex) =>
        ruleIndex === index ? { ...rule, ...patch } : rule,
      ),
    );
  };
 
  const updateRuleDraft = (
    index: number,
    patch: Partial<CompositeScheduleRuleDraft>,
  ) => {
    setLocalError("");
    setEditedRulesByStudy({ studyId, rules: rulesWithPatch(index, patch) });
  };
 
  const saveRules = async (nextRules: CompositeScheduleRuleDraft[]) => {
    const normalizedRules = normalizeRuleSortOrder(nextRules);
    setLocalError("");
    setEditedRulesByStudy({ studyId, rules: normalizedRules });
    try {
      await savePlan({
        id: studyId,
        compositeSchedulePlanRequest: {
          rules: rulesPayloadForSave(normalizedRules),
        },
      }).unwrap();
      setEditedRulesByStudy(null);
      await planQuery.refetch();
      onSaved();
    } catch (error) {
      setLocalError(
        scheduleMutationErrorMessage(
          error,
          "Composite schedule could not be saved.",
        ),
      );
    }
  };
 
  const updateAndSaveRule = (
    index: number,
    patch: Partial<CompositeScheduleRuleDraft>,
  ) => {
    void saveRules(rulesWithPatch(index, patch));
  };
 
  const addRule = () => {
    void saveRules(
      normalizeRuleSortOrder([
        ...rules,
        {
          ...defaultRuleForAppend(options, rules),
          sort_order: rules.length,
        },
      ]),
    );
  };
 
  const removeRule = (index: number) => {
    const nextRules = rules.filter((_rule, ruleIndex) => ruleIndex !== index);
    void saveRules(
      normalizeRuleSortOrder(
        nextRules.length ? nextRules : [defaultRule(options)],
      ),
    );
  };
 
  const openSourceScenario = (scenarioId: number) => {
    Iif (!scenarioId) return;
    setSearchParams((params) => {
      const next = new URLSearchParams(params);
      next.set("content", ContentTypes.scenarios);
      next.set("scenario", String(scenarioId));
      return next;
    });
  };
 
  return (
    <div className="grid gap-4">
      <div className="grid gap-3">
        {rules.map((rule, index) => (
          <CompositeScheduleRuleRow
            key={`${index}-${rule.sort_order ?? index}`}
            rule={rule}
            index={index}
            canEdit={
              canEdit && !saving && !planUnavailable && hasSourceSchedules
            }
            options={options}
            sourceNavigationDisabled={editedRules !== null}
            onChange={(patch) => updateAndSaveRule(index, patch)}
            onDraftChange={(patch) => updateRuleDraft(index, patch)}
            onCommit={(patch) => updateAndSaveRule(index, patch)}
            onRemove={() => removeRule(index)}
            onOpenSource={() => openSourceScenario(rule.source_scenario)}
          />
        ))}
        <div className="flex flex-wrap items-center justify-between gap-2">
          <Button
            type="button"
            variant="secondary"
            size="sm"
            onClick={addRule}
            disabled={controlsDisabled}
          >
            <Plus className="mr-1.5 size-4" />
            Add rule
          </Button>
        </div>
      </div>
      {editorMessage && (
        <div className="text-sm text-muted-foreground" aria-live="polite">
          {editorMessage}
        </div>
      )}
      <CompositeScheduleDiagnostics plan={plan} fallbackError={localError} />
      <CompositeScheduleTimetable plan={plan} />
    </div>
  );
}