All files / src/pages/flowsheet-page/flowsheet/PropertiesSidebar/MachineLearning UploadCSV.tsx

58.62% Statements 34/58
59.09% Branches 26/44
20% Functions 1/5
58.62% Lines 34/58

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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423                                                                                                          6x                 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x   74x             74x             5x     5x           5x   5x 5x       5x                   5x 5x 5x                 5x                           6x                         6x                             6x 5x                                                                                               5x           5x                 74x 74x                       74x                                                                                                                                                                                                                                                                                                                                               5x                    
import { ChevronDown, FolderOpen, MoveRight, RotateCcw, X } from "lucide-react";
import { useRef, useState } from "react";
import { toast } from "sonner";
import { AccessControlledButton as Button } from "@/ahuora-design-system/ui/accessControlled";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
import { Progress } from "@/ahuora-design-system/ui/progress";
import { ScrollArea } from "@/ahuora-design-system/ui/scroll-area";
import {
  MlModelRead,
  ModelTypeEnum,
  TransitionEnum,
  useCoreMlPartialUpdateMutation,
  useCoreMlTransitionWizardCreateMutation,
  useCoreMlUploadMlModelCreateMutation,
  useLazyUploadsCsvInspectRetrieveQuery,
} from "@/api/apiStore.gen";
import { useMLTrainRefresh } from "@/hooks/cache/useMLTrainRefresh";
import { useFlowsheetAccess } from "@/hooks/flowsheetAccess";
import { useFlowsheetId } from "@/hooks/project";
import { scanCsvHeadersLocal } from "@/lib/uploads/csvHeader";
import { formatUploadProgress } from "@/lib/uploads/formatUploadProgress";
import { NUMERIC_COLUMNS_TOOLTIP } from "@/lib/uploads/importNotes";
import { isSameUploadedFileSelection } from "@/lib/uploads/isSameUploadedFileSelection";
import { resolveUploadActivityStatus } from "@/lib/uploads/resolveUploadActivityStatus";
import {
  ML_INPUT_CSV_EXPIRY_NOTE,
  PARTIAL_UPLOAD_EXPIRY_NOTE,
} from "@/lib/uploads/retention";
import { UploadActivityStatus } from "@/lib/uploads/UploadActivityStatus";
import { UploadWarningNotice } from "@/lib/uploads/UploadWarningNotice";
import { useResumableMultipartUpload } from "@/lib/uploads/useResumableMultipartUpload.ts";
import CSVUploader from "@/pages/flowsheet-page/multi-steady-state/CSVUploader";
 
export type CsvHeaderPreviewState = {
  headers: string[];
  delimiter: string | null;
  warnings: string[];
  source: "local" | "backend";
};
 
interface UploadCSVProps {
  model: MlModelRead;
  simulationObject: number;
  onUpdateModelType: (modelType: ModelTypeEnum) => void;
  onCsvHeaderPreviewChange: (preview: CsvHeaderPreviewState | null) => void;
}
 
function isCsvFile(file: File): boolean {
  return file.name.toLowerCase().endsWith(".csv");
}
 
export default function UploadCSV({
  model,
  simulationObject,
  onUpdateModelType,
  onCsvHeaderPreviewChange,
}: UploadCSVProps) {
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const access = useFlowsheetAccess();
  const canMutate = access?.can_edit ?? true;
  const flowsheetId = Number(useFlowsheetId());
  const { refreshMLTrainDependencies } = useMLTrainRefresh();
  const [isFinalizingUpload, setIsFinalizingUpload] = useState(false);
  const [isUploadComplete, setIsUploadComplete] = useState(false);
  const [updateMLModel] = useCoreMlPartialUpdateMutation();
  const [transitionWizard] = useCoreMlTransitionWizardCreateMutation();
  const [uploadModel] = useCoreMlUploadMlModelCreateMutation();
  const [inspectUploadedCsv] = useLazyUploadsCsvInspectRetrieveQuery();
 
  const uploadContext = {
    purpose: "ml_training_csv" as const,
    flowsheet_id: flowsheetId,
    simulationObject_id: simulationObject,
  };
 
  const { state, startUpload, abortUpload, clearUploadState } =
    useResumableMultipartUpload({
      storageKey: `csv-upload:ml:${model.id}`,
      context: uploadContext,
    });
 
  /** Submit a completed object-storage upload session to the ML model and refresh headers. */
  async function finalizeUploadedCsv(uploadSessionId: string): Promise<void> {
    setIsFinalizingUpload(true);
 
    try {
      await updateMLModel({
        id: model.id,
        patchedPatchMlModel: {
          csv_upload_session: Number(uploadSessionId),
        },
      }).unwrap();
      refreshMLTrainDependencies();
 
      try {
        const confirmedHeaders = await inspectUploadedCsv(
          { uploadSessionId: Number(uploadSessionId) },
          true,
        ).unwrap();
        onCsvHeaderPreviewChange({
          headers: confirmedHeaders.headers,
          delimiter: confirmedHeaders.detected_delimiter,
          warnings: confirmedHeaders.warnings ?? [],
          source: "backend",
        });
      } catch {
        // The backend header endpoint remains the source of truth in the next wizard step.
      }
 
      clearUploadState();
      setIsUploadComplete(true);
      toast.success("CSV upload complete.");
    } catch (error) {
      toast.error("Upload finalization failed", {
        description:
          error instanceof Error
            ? error.message
            : "The uploaded CSV could not be attached to the ML model.",
      });
    } finally {
      setIsFinalizingUpload(false);
    }
  }
 
  /** Upload a CSV to object storage, attach it to the ML model, and refresh headers. */
  async function handleUpload(file: File): Promise<void> {
    if (!isCsvFile(file)) {
      toast.error("Unsupported file", {
        description: "Please upload a CSV file.",
      });
      return;
    }
 
    try {
      const localHeaders = await scanCsvHeadersLocal(file);
      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;
      }
 
      onCsvHeaderPreviewChange({
        headers: localHeaders.headers,
        delimiter: localHeaders.guessedDelimiter,
        warnings: localHeaders.warnings,
        source: "local",
      });
 
      if (isSameUploadedFileSelection(state, file)) {
        toast.warning("CSV already uploaded", {
          description:
            "This file has already completed uploading. Use Finish upload if you still need to attach it.",
        });
        return;
      }
 
      const completedUpload = await startUpload(file);
      await finalizeUploadedCsv(completedUpload.upload_session_id);
    } 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.",
      });
    }
  }
 
  const handleImportClick = () => {
    fileInputRef.current?.click();
  };
 
  const importModel = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const raw = e.target?.result;
          const parsedJson = typeof raw === "string" ? JSON.parse(raw) : raw;
          await uploadModel({
            uploadModel: {
              model: model.id,
              json_data: parsedJson,
            },
          }).unwrap();
          onCsvHeaderPreviewChange(null);
          refreshMLTrainDependencies();
        } catch (error) {
          toast.error("Model import failed", {
            description: "Choose a valid exported ML model file.",
          });
        }
      };
      reader.readAsText(file);
    }
  };
 
  const handlePrepareData = async () => {
    if (isUploadComplete) {
      try {
        await transitionWizard({
          mlWizardTransition: {
            model: model.id,
            transition: TransitionEnum.AdvanceToMappings,
          },
        }).unwrap();
        refreshMLTrainDependencies();
      } catch {
        toast.error("Unable to set mappings", {
          description: "Attach a completed CSV before mapping its columns.",
        });
      }
    }
  };
 
  const showMultipartStatus = state.status !== "idle";
  const uploadActivityStatus = resolveUploadActivityStatus({
    uploadStatus: state.status,
    progressPercentage: state.progress.percentage,
    uploadingLabel: "Uploading the CSV to object storage.",
    finalizingUploadLabel:
      "Finishing the CSV upload before attaching it to the ML model.",
    processingLabel: isFinalizingUpload
      ? "Finalizing the upload and attaching the CSV to the ML model."
      : null,
    isProcessing: isFinalizingUpload,
  });
 
  return (
    <ScrollArea>
      <div className="flex min-h-full flex-col justify-between gap-10">
        <div className="flex flex-col gap-10">
          <div className="flex flex-col gap-4">
            <div className="flex flex-row items-center justify-between align-middle w-full my-2">
              <div className="flex flex-col gap-1">
                <h1>File Upload</h1>
                <p className="font-light">{ML_INPUT_CSV_EXPIRY_NOTE}</p>
              </div>
              <div>
                <input
                  type="file"
                  accept=".json"
                  onChange={importModel}
                  disabled={!canMutate}
                  ref={fileInputRef}
                  className="hidden"
                />
                <Button
                  variant="outline"
                  disabled={!canMutate}
                  onClick={handleImportClick}
                >
                  <FolderOpen />
                  Import Model
                </Button>
              </div>
            </div>
            <CSVUploader
              onUpload={handleUpload}
              disabled={!canMutate}
              accept=".csv,text/csv"
              inputAriaLabel="Upload CSV file"
              tooltipContent={NUMERIC_COLUMNS_TOOLTIP}
              promptText={
                state.status === "resume_available"
                  ? "Resume upload by selecting the same CSV file again"
                  : "Drag a CSV file here, or click to upload"
              }
            />
            {model && (
              <p className="text-sm font-light mt-2">
                Uploaded File: {model?.csv_file_name}
              </p>
            )}
            {showMultipartStatus && (
              <div className="rounded-lg border bg-muted/40 p-3 flex flex-col gap-3">
                <div className="flex items-center justify-between gap-3">
                  <div className="flex flex-col gap-1">
                    <p className="text-sm font-medium">
                      {state.status === "uploading"
                        ? "Uploading CSV to object storage"
                        : state.status === "resume_available"
                          ? "A resumable upload is waiting"
                          : state.status === "uploaded"
                            ? "CSV uploaded"
                            : state.status === "failed"
                              ? "Upload failed"
                              : "Upload cancelled"}
                    </p>
                    {state.fileName && (
                      <p className="text-xs text-muted-foreground">
                        {state.fileName}
                      </p>
                    )}
                  </div>
                  <div className="flex items-center gap-2">
                    {state.status === "uploading" && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => void abortUpload()}
                      >
                        <X className="w-4 h-4" />
                        Cancel
                      </Button>
                    )}
                    {(state.status === "resume_available" ||
                      state.status === "failed") && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={clearUploadState}
                      >
                        <RotateCcw className="w-4 h-4" />
                        Start over
                      </Button>
                    )}
                    {state.status === "uploaded" && state.uploadSessionId && (
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={isFinalizingUpload}
                        onClick={() =>
                          void finalizeUploadedCsv(state.uploadSessionId!)
                        }
                      >
                        Finish upload
                      </Button>
                    )}
                  </div>
                </div>
 
                <Progress
                  value={state.progress.percentage}
                  aria-label="ml-upload-progress"
                />
                <div className="flex items-center justify-between text-xs text-muted-foreground">
                  <span>{state.progress.percentage}%</span>
                  <span>
                    {formatUploadProgress(
                      state.progress.uploadedBytes,
                      state.progress.totalBytes,
                    )}
                  </span>
                </div>
 
                {state.error && <UploadWarningNotice message={state.error} />}
                {state.status === "uploading" && (
                  <p className="text-xs text-muted-foreground">
                    {PARTIAL_UPLOAD_EXPIRY_NOTE}
                  </p>
                )}
                <UploadActivityStatus {...uploadActivityStatus} />
              </div>
            )}
          </div>
          <div className="flex flex-col gap-5">
            <div className="flex flex-col gap-1">
              <h1>Model Type</h1>
              <p className="font-light">
                Select the type of machine learning model you want to use.
              </p>
            </div>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="outline"
                  className="flex flex-row items-center justify-between w-1/2"
                  disabled={!canMutate}
                >
                  <p>{model.model_type}</p>
                  <ChevronDown />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
                <DropdownMenuItem
                  onClick={() => onUpdateModelType(ModelTypeEnum.RbfRegression)}
                >
                  RBF
                </DropdownMenuItem>
                <DropdownMenuItem
                  onClick={() =>
                    onUpdateModelType(ModelTypeEnum.PolynomialRegression)
                  }
                >
                  Polynomial
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
        <div className="flex justify-end pt-4">
          <Button
            disabled={!canMutate || !isUploadComplete}
            className="w-max p-6 gap-3 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed"
            aria-label="set-mappings"
            onClick={() => void handlePrepareData()}
          >
            Set Mappings
            <MoveRight />
          </Button>
        </div>
      </div>
    </ScrollArea>
  );
}