All files / src/pages/flowsheet-page/flowsheet DuplicateFlowsheetCommand.tsx

61.53% Statements 16/26
90% Branches 9/10
0% Functions 0/2
61.53% Lines 16/26

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                                    103x     1013x 1013x 1013x   1013x 1013x                 4x   4x         4x 4x 4x                         4x   1x 1x   3x           1013x                                                                                      
import { defineCommand } from "just-search-it";
import { Fullscreen } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import {
  type ScenarioResultCopySummary,
  useFlowsheetCopyCreateMutation,
  useLazyFlowsheetCopyPreviewRetrieveQuery,
} from "@/api/apiStore.gen";
import { RegisterCommand } from "@/commands/CommandProvider";
import {
  type CloneValidationProblem,
  parseCloneValidationProblem,
} from "@/flowsheet-cloning/cloneValidation";
import { DuplicateWithResultsDialog } from "@/flowsheet-cloning/DuplicateWithResultsDialog";
import { FlowsheetCloneProblemDialog } from "@/flowsheet-cloning/FlowsheetCloneProblemDialog";
import { useFlowsheetId } from "../../../hooks/project";
 
export const DuplicateFlowsheet = defineCommand<[], void>("duplicateFlowsheet");
 
export function DuplicateFlowsheetCommand() {
  const projectId = useFlowsheetId();
  const [copyFlowsheet, copyResult] = useFlowsheetCopyCreateMutation();
  const [loadCopyPreview] = useLazyFlowsheetCopyPreviewRetrieveQuery();
  const [copyConfirmation, setCopyConfirmation] =
    useState<ScenarioResultCopySummary | null>(null);
  const [copyFailure, setCopyFailure] = useState<{
    problem: CloneValidationProblem;
    includeScenarioResults: boolean;
  } | null>(null);
 
  const handleCopyFlowsheet = async (
    includeScenarioResults = false,
    repairLegacyFormulaUnits = false,
  ) => {
    setCopyConfirmation(null);
    try {
      const newFlowsheetId = await copyFlowsheet({
        flowsheet: projectId,
        ...(includeScenarioResults ? { includeScenarioResults: true } : {}),
        ...(repairLegacyFormulaUnits ? { repairLegacyFormulaUnits: true } : {}),
      }).unwrap();
      setCopyFailure(null);
      window.open(`/project/${newFlowsheetId}/flowsheet`);
      toast.success("Flowsheet Duplicated Successfully");
    } catch (error) {
      const problem = parseCloneValidationProblem(error);
      if (problem) {
        setCopyFailure({ problem, includeScenarioResults });
        return;
      }
      toast.error("Something went wrong when duplicating the flowsheet");
    }
  };
 
  const requestCopyFlowsheet = async () => {
    try {
      const summary = await loadCopyPreview({ flowsheet: projectId }).unwrap();
      if (summary.has_results) {
        setCopyConfirmation(summary);
        return;
      }
      await handleCopyFlowsheet();
    } catch {
      toast.error("Scenario result counts could not be loaded");
    }
  };
 
  return (
    <>
      <RegisterCommand
        command={DuplicateFlowsheet}
        args={[]}
        name="Duplicate Flowsheet"
        description="Create a copy of the current flowsheet"
        group="Display & flowsheet controls"
        icon={<Fullscreen className="icon-ls" />}
        action={requestCopyFlowsheet}
        shortcuts={[]}
      />
      {copyConfirmation && (
        <DuplicateWithResultsDialog
          name="the current flowsheet"
          scope="flowsheet"
          summary={copyConfirmation}
          isDuplicating={copyResult.isLoading}
          onCancel={() => setCopyConfirmation(null)}
          onConfirm={handleCopyFlowsheet}
        />
      )}
      <FlowsheetCloneProblemDialog
        problem={copyFailure?.problem ?? null}
        scope="flowsheet"
        isRepairingAutomatically={copyResult.isLoading}
        onDismiss={() => setCopyFailure(null)}
        onRepairManually={(flowsheetId) => {
          setCopyFailure(null);
          window.open(
            `/project/${flowsheetId}/flowsheet?content=group`,
            "_self",
          );
        }}
        onRepairAutomatically={async () => {
          if (copyFailure) {
            await handleCopyFlowsheet(copyFailure.includeScenarioResults, true);
          }
        }}
      />
    </>
  );
}