All files / src/pages/flowsheet-page/flowsheet/LeftSideBar/Scenarios useScenarioFileUpload.ts

57.89% Statements 44/76
44.44% Branches 12/27
75% Functions 3/4
57.89% Lines 44/76

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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293                                                                                    7x                     467x 467x 467x 467x 467x 467x 467x 467x 467x   467x 14x                         467x           19x 19x       13x                                                         6x 6x 6x       6x         6x 6x             6x 6x 6x                       467x                           6x 6x     467x 6x     467x               7x 7x 7x     7x             7x 7x                 7x                         7x                                               7x     7x                                         7x 7x                               467x                        
import { useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import {
  api,
  StatusEnum,
  TaskRead,
  useScenariosImportFromUploadCreateMutation,
} from "@/api/apiStore.gen";
import { useUpdateTaskCache } from "@/hooks/cache/useUpdateTaskCache";
import {
  useTaskCancelledSubscription,
  useTaskCompletedSubscription,
  useTaskUpdatedSubscription,
} from "@/hooks/notifications/notificationSubscriptions";
import { scanCsvHeadersLocal } from "@/lib/uploads/csvHeader";
import { isSameUploadedFileSelection } from "@/lib/uploads/isSameUploadedFileSelection";
import { useResumableMultipartUpload } from "@/lib/uploads/useResumableMultipartUpload.ts";
import { useAppDispatch } from "@/store/hooks";
 
type UseScenarioFileUploadArgs = {
  onSuccess: (fileName: string) => void;
  onError: (error: unknown) => void;
  updateUploadedFileName: (name: string) => void;
  flowsheetId: number | string;
  scenarioId: number;
};
 
type UploadTaskRead = TaskRead;
 
export type UseScenarioFileUploadResult = {
  handleFileUpload: (file: File) => Promise<void>;
  abortUpload: () => Promise<void>;
  clearUploadState: () => void;
  retryImport: () => Promise<void>;
  uploadState: ReturnType<typeof useResumableMultipartUpload>["state"];
  importTask: UploadTaskRead | null;
  importStartError: string | null;
  isStartingImport: boolean;
  csvWarnings: string[];
};
 
function isCsvFile(file: File): boolean {
  return file.name.toLowerCase().endsWith(".csv");
}
 
/** Manage scenario CSV upload/import for the multipart object-storage flow. */
export function useScenarioFileUpload({
  onSuccess,
  onError,
  updateUploadedFileName,
  flowsheetId,
  scenarioId,
}: UseScenarioFileUploadArgs): UseScenarioFileUploadResult {
  const dispatch = useAppDispatch();
  const updateTaskCache = useUpdateTaskCache();
  const [startImportTask] = useScenariosImportFromUploadCreateMutation();
  const importTaskRef = useRef<UploadTaskRead | null>(null);
  const pendingFileNameRef = useRef<string | null>(null);
  const [importTask, setImportTask] = useState<UploadTaskRead | null>(null);
  const [importStartError, setImportStartError] = useState<string | null>(null);
  const [isStartingImport, setIsStartingImport] = useState(false);
  const [csvWarnings, setCsvWarnings] = useState<string[]>([]);
 
  const uploadContext = useMemo(
    () => ({
      purpose: "scenario_csv" as const,
      flowsheet_id: Number(flowsheetId),
      scenario_id: scenarioId,
    }),
    [flowsheetId, scenarioId],
  );
 
  const {
    state: uploadState,
    startUpload,
    abortUpload: abortMultipartUpload,
    clearUploadState: clearMultipartUploadState,
  } = useResumableMultipartUpload({
    storageKey: `csv-upload:scenario:${scenarioId}`,
    context: uploadContext,
  });
 
  function setTrackedImportTask(task: UploadTaskRead | null): void {
    importTaskRef.current = task;
    setImportTask(task);
  }
 
  function setTrackedPendingFileName(fileName: string | null): void {
    pendingFileNameRef.current = fileName;
  }
 
  function clearTrackedImportState(): void {
    setTrackedImportTask(null);
    setTrackedPendingFileName(null);
    setImportStartError(null);
  }
 
  async function abortUpload(): Promise<void> {
    clearTrackedImportState();
    setCsvWarnings([]);
    await abortMultipartUpload();
  }
 
  function clearUploadState(): void {
    clearTrackedImportState();
    setCsvWarnings([]);
    clearMultipartUploadState();
  }
 
  function handleImportTaskMessage(
    task: UploadTaskRead,
    expectedTaskId = importTaskRef.current?.id,
  ): void {
    if (expectedTaskId == null || task.id !== expectedTaskId) {
      return;
    }
 
    setTrackedImportTask(task);
    updateTaskCache(task);
    setImportStartError(null);
 
    if (task.status === StatusEnum.Completed) {
      const resolvedFileName =
        pendingFileNameRef.current ??
        uploadState.fileName ??
        uploadState.resumeState?.original_filename ??
        "CSV import";
 
      updateUploadedFileName(resolvedFileName);
      dispatch(
        api.util.invalidateTags([
          "DataColumns" as never,
          "Scenario" as never,
          "Optimizations" as never,
        ]),
      );
      setTrackedPendingFileName(null);
      onSuccess(resolvedFileName);
      return;
    }
 
    if (
      task.status === StatusEnum.Failed ||
      task.status === StatusEnum.Cancelled
    ) {
      setTrackedPendingFileName(null);
      onError(task.error);
    }
  }
 
  useTaskUpdatedSubscription((task) => {
    if (task.id !== importTaskRef.current?.id) {
      return;
    }
 
    if (
      task.status === StatusEnum.Completed ||
      task.status === StatusEnum.Failed ||
      task.status === StatusEnum.Cancelled
    ) {
      handleImportTaskMessage(task);
      return;
    }
 
    setTrackedImportTask(task);
    updateTaskCache(task);
  });
 
  useTaskCompletedSubscription((task) => {
    handleImportTaskMessage(task);
  });
 
  useTaskCancelledSubscription((task) => {
    handleImportTaskMessage(task);
  });
 
  const startImportFromUpload = async (
    uploadSessionId: string,
    fileName: string,
  ): Promise<void> => {
    setImportStartError(null);
    setTrackedPendingFileName(fileName);
    setIsStartingImport(true);
 
    try {
      const task = await startImportTask({
        importScenarioFromUpload: {
          scenario_id: scenarioId,
          upload_session_id: Number(uploadSessionId),
        },
      }).unwrap();
 
      setTrackedImportTask(task);
      updateTaskCache(task);
 
      if (
        task.status === StatusEnum.Completed ||
        task.status === StatusEnum.Failed ||
        task.status === StatusEnum.Cancelled
      ) {
        handleImportTaskMessage(task, task.id);
      } else {
        toast.success("CSV uploaded. Import started.");
      }
    } catch (error) {
      const description =
        error instanceof Error
          ? error.message
          : "The uploaded CSV is waiting, but the import task could not be started.";
      setImportStartError(description);
      toast.error("Import could not be started", {
        description,
      });
      onError(error);
    } finally {
      setIsStartingImport(false);
    }
  };
 
  const retryImport = async (): Promise<void> => {
    if (!uploadState.uploadSessionId || !uploadState.fileName) {
      return;
    }
 
    await startImportFromUpload(
      uploadState.uploadSessionId,
      uploadState.fileName,
    );
  };
 
  const handleFileUpload = async (file: File) => {
    if (!isCsvFile(file)) {
      toast.error("Unsupported file", {
        description: "Please upload a CSV file.",
      });
      return;
    }
 
    try {
      const localHeaders = await scanCsvHeadersLocal(file, {
        warnOnNonNumericColumns: true,
      });
      setCsvWarnings(localHeaders.warnings);
      if (
        localHeaders.guessedDelimiter == null ||
        localHeaders.headers.length === 0
      ) {
        toast.error("Unsupported CSV format", {
          description:
            localHeaders.warnings[0] ??
            "Only UTF-8 CSV files with comma or semicolon delimiters are supported.",
        });
        return;
      }
 
      if (isSameUploadedFileSelection(uploadState, file)) {
        toast.warning("CSV already uploaded", {
          description:
            "This file has already completed uploading. Use Retry import to run the import again.",
        });
        return;
      }
 
      const completedUpload = await startUpload(file);
      await startImportFromUpload(completedUpload.upload_session_id, file.name);
    } catch (error) {
      if (error instanceof DOMException && error.name === "AbortError") {
        return;
      }
 
      toast.error("Upload failed", {
        description:
          error instanceof Error
            ? error.message
            : "The CSV file could not be uploaded.",
      });
      onError(error);
    }
  };
 
  return {
    handleFileUpload,
    abortUpload,
    clearUploadState,
    retryImport,
    uploadState,
    importTask,
    importStartError,
    isStartingImport,
    csvWarnings,
  };
}