Skip to content

Commit

Permalink
feat: Rewritten add model to use analogue model as global state
Browse files Browse the repository at this point in the history
  • Loading branch information
thomaslf97 committed Dec 4, 2024
1 parent 65340f9 commit fb78466
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useEffect } from 'react';
import { AnalogueModelDetail } from '../../../api/generated';
import { ErrorType, FilesProps } from './HandleModelComponent';
export const useHandleModelComponent = (
setMetadata: React.Dispatch<React.SetStateAction<AnalogueModelDetail>>,
setMetadata: (analogueModel: AnalogueModelDetail) => void,
existingData?: AnalogueModelDetail,
) => {
useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,13 @@ import {
validateValues,
} from './HandleModelComponent.hooks';
import * as Styled from './HandleModelComponent.styled';
import {
analogueModelDefault,
usePepmContextStore,
} from '../../../hooks/GlobalState';
import { usePepmContextStore } from '../../../hooks/GlobalState';
import { readFileAsText } from '../../../utils/ReadIniFile';
import { IniFileTextField } from './HandleModelComponent.styled';
Icon.add({ error_outlined });

interface AddModelDialogProps {
confirm?: (
file: File,
metadata: AnalogueModelDetail,
iniFile?: File,
) => Promise<void>;
confirm?: (file: File, iniFile?: File) => Promise<void>;
progress?: number;
uploading?: boolean;
isAddUploading?: boolean;
Expand Down Expand Up @@ -72,26 +65,30 @@ export const HandleModelComponent = ({
isAddUploading,
modelId,
}: AddModelDialogProps) => {
const { setAnalogueModelDefault } = usePepmContextStore();
const { setAnalogueModelDefault, analogueModel, setAnalogueModel } =
usePepmContextStore();
const [isFileDisplay, setFileDisplay] = useState<boolean>(false);
const [files, setFiles] = useState<FilesProps>(defaultFiles);
const [iniFileString, setIniFileString] = useState<string>();
const [metadata, setMetadata] =
useState<AnalogueModelDetail>(analogueModelDefault);
const [submitting, setSubmitting] = useState(false);

const [errors, setErrors] = useState<ErrorType>({});
const navigate = useNavigate();

useHandleModelComponent(setMetadata);
useHandleModelComponent(setAnalogueModel);

const handleSubmit = () => {
setErrors(validateValues(metadata, files));
setErrors(validateValues(analogueModel, files));
setSubmitting(true);
};

const fileAdded = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) return;
if (
!e.target.files[0].name.endsWith('.nc') &&
!e.target.files[0].name.endsWith('.ini')
)
return;
const file = e.target.files[0];
const type = e.target.name;
setFiles({ ...files, [type]: file });
Expand All @@ -105,15 +102,15 @@ export const HandleModelComponent = ({

const finishSubmit = () => {
if (files.NC && confirm && files.INI) {
confirm(files.NC, metadata, files.INI);
} else if (files.NC && confirm) confirm(files.NC, metadata);
confirm(files.NC, files.INI);
} else if (files.NC && confirm) confirm(files.NC);
cleanupStates();
};

if (Object.keys(errors).length === 0 && submitting) {
finishSubmit();
}
}, [confirm, errors, files, metadata, submitting]);
}, [confirm, errors, files, analogueModel, submitting]);

function toggleINIFileContent() {
setFileDisplay(!isFileDisplay);
Expand Down Expand Up @@ -154,9 +151,9 @@ export const HandleModelComponent = ({
{!isAddUploading && (
<>
<ModelMetadata
metadata={analogueModel}
setMetadata={setAnalogueModel}
errors={errors}
metadata={metadata}
setMetadata={setMetadata}
/>
<Styled.ErrorDiv>{errors.file && errors.file}</Styled.ErrorDiv>
</>
Expand All @@ -171,7 +168,6 @@ export const HandleModelComponent = ({
</Button>
</div>
)}

{uploading && (
<Styled.UploadDiv>
<p className="warning-message">
Expand All @@ -184,7 +180,6 @@ export const HandleModelComponent = ({
{<LinearProgress variant="indeterminate" value={progress} />}
</Styled.UploadDiv>
)}

{progress === 100 && modelId && (
<Styled.InfoNavigation>
<Typography variant="h4" as="h2">
Expand Down
119 changes: 65 additions & 54 deletions src/pages/AddModel/AddModel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { useEffect, useState } from 'react';
import {
AddAnalogueModelMetadataCommandForm,
AddMetadataDto,
AnalogueModelDetail,
AnalogueModelMetadataService,
AnalogueModelsService,
ConvertAnalogueModelCommand,
Expand All @@ -23,26 +22,23 @@ import { SidePane } from '../../features/HandleModel/SidePane/SidePane';
import { ModelMetadataView } from '../../features/ModelView/ModelMetadataView/ModelMetadataView';
import * as Styled from './AddModel.styled';
import { postIniFile } from '../../api/custom/postIniFile';
import { usePepmContextStore } from '../../hooks/GlobalState';

enum UploadProcess {
SUCCESS = 'Model successfully uploaded and is now beeing processed.',
FAILED = 'File upload failed.',
}

const defaultCounterValue = 1;
const defaultBeginningOfchunk = 0;
export const AddModel = () => {
const { analogueModel, setAnalogueModel } = usePepmContextStore();
const [progress, setProgress] = useState(0);
const [modelId, setModelId] = useState<string>('');
const [uploading, setUploading] = useState<boolean>(false);
const [counter, setCounter] = useState<number>(defaultCounterValue);
const [counter, setCounter] = useState<number>(1);
const [iniFile, setIniFile] = useState<File>();
const [iniFileUploading, setIniFileUploading] = useState<boolean>(false);
const [iniFileSucceeded, setIniFileSucceeded] = useState<boolean>(false);
const [fileToBeUpload, setFileToBeUpload] = useState<File>();
const [beginingOfTheChunk, setBeginingOfTheChunk] = useState<number>(
defaultBeginningOfchunk,
);
const [beginingOfTheChunk, setBeginingOfTheChunk] = useState<number>(0);
const [endOfTheChunk, setEndOfTheChunk] = useState<number>();
const [fileSize, setFileSize] = useState(0);
const [chunkSize, setChunkSize] = useState(0);
Expand Down Expand Up @@ -114,55 +110,52 @@ export const AddModel = () => {
metadataList.push(...obj);
}

async function uploadMetadata(
modelId: string,
metadata: AnalogueModelDetail,
) {
addMetadataFields(metadata.metadata);
async function uploadMetadata(id: string) {
addMetadataFields(analogueModel.metadata);

const readyMetadata: AddAnalogueModelMetadataCommandForm = {
metadata: metadataList,
};

await uploadModelMetadata.mutateAsync({
id: modelId,
id: id,
requestBody: readyMetadata,
});
}

async function uploadModel(
file: File,
metadata: AnalogueModelDetail,
iniFile?: File,
) {
async function uploadModel(file: File, iniFile?: File) {
if (file === undefined) return;
setUploading(true);
const ModelBody: CreateAnalogueModelCommand = {
name: metadata.name ? metadata.name : '',
description: metadata.description,
sourceType: 'Deltares',
};

const modelUpload = await createModel.mutateAsync(ModelBody);
if (analogueModel.analogueModelId === '') {
const ModelBody: CreateAnalogueModelCommand = {
name: analogueModel.name ? analogueModel.name : '',
description: analogueModel.description,
sourceType: 'Deltares',
};

const modelUpload = await createModel.mutateAsync(ModelBody);

if (createModel.error === null && modelUpload.success) {
const id = modelUpload.data.analogueModelId;
setModelId(id);
setProgress(1);
uploadMetadata(id, metadata);
if (createModel.error === null && modelUpload.success) {
setAnalogueModel({
...analogueModel,
analogueModelId: modelUpload.data.analogueModelId,
});
setProgress(1);
uploadMetadata(modelUpload.data.analogueModelId);
}

if (counter >= chunkCount) {
setCounter(defaultCounterValue);
setBeginingOfTheChunk(defaultBeginningOfchunk);
setCounter(1);
setBeginingOfTheChunk(0);
}

if (file === undefined) return;

const fileType = UploadFileType.NET_CDF;
const filenameExtention = file.name.split('.').pop();
const fileExtention = '.' + filenameExtention;

const data = {
ModelId: id,
ModelId: modelUpload.data.analogueModelId,
FileSize: file.size,
FileName: file.name,
FileExtension: fileExtention,
Expand All @@ -188,7 +181,17 @@ export const AddModel = () => {
}
}

const resetUpload = () => {
setUploadStatus(UploadProcess.FAILED);
setProgress(-99);
setUploading(false);
};

const fileUpload = (counter: number) => {
if (endOfTheChunk === undefined) return;
setBeginingOfTheChunk(endOfTheChunk);
setEndOfTheChunk(endOfTheChunk + chunkSize);

setCounter(counter + 1);
if (counter <= chunkCount) {
if (fileToBeUpload === undefined) return;
Expand All @@ -200,30 +203,27 @@ export const AddModel = () => {
};

const uploadChunk = async ({ Blob }: { Blob: Blob }) => {
if (modelId === '' && uploadId === '') return;
if (analogueModel.analogueModelId === '' && uploadId === '') return;
const chunkData = {
ModelId: modelId,
ModelId: analogueModel.analogueModelId,
UploadId: uploadId,
Blob: Blob,
ChunkNumber: counter,
};
try {
const uploadChunks = await chunkUpload.mutateAsync(chunkData);
if (chunkUpload.error === null && uploadChunks.success) {
if (endOfTheChunk === undefined) return;
setBeginingOfTheChunk(endOfTheChunk);
setEndOfTheChunk(endOfTheChunk + chunkSize);
if (counter === chunkCount) {
const finishBody = {
ModelId: modelId,
ModelId: analogueModel.analogueModelId,
UploadId: uploadId,
};
const finishedUpload = await uploadFinished.mutateAsync(finishBody);
if (uploadFinished.error === null && finishedUpload.success) {
// eslint-disable-next-line max-depth
try {
const convert = await convertModelFile.mutateAsync({
modelId: modelId,
modelId: analogueModel.analogueModelId,
});

// eslint-disable-next-line max-depth
Expand All @@ -232,16 +232,12 @@ export const AddModel = () => {
setUploadStatus(UploadProcess.SUCCESS);
setUploading(false);
} else {
setUploadStatus(UploadProcess.FAILED);
setProgress(-99);
setUploading(false);
resetUpload();
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
setUploadStatus(UploadProcess.FAILED);
setProgress(-99);
setUploading(false);
resetUpload();
}
}
} else {
Expand All @@ -252,6 +248,7 @@ export const AddModel = () => {
} catch (error) {
// eslint-disable-next-line no-console
console.log('error', error);
resetUpload();
}
};

Expand All @@ -273,9 +270,17 @@ export const AddModel = () => {
return response;
};

if (!iniFileUploading && !iniFileSucceeded && iniFile && modelId) {
if (
!iniFileUploading &&
!iniFileSucceeded &&
iniFile &&
analogueModel.analogueModelId
) {
setIniFileUploading(true);
const response = uploadIniFileAsync(iniFile, modelId);
const response = uploadIniFileAsync(
iniFile,
analogueModel.analogueModelId,
);
response.then(
(res) => {
setIniFileSucceeded(true);
Expand All @@ -285,7 +290,13 @@ export const AddModel = () => {
},
);
}
}, [modelId, iniFile, iniFileUploading, iniFileSucceeded, uploadIniFile]);
}, [
analogueModel.analogueModelId,
iniFile,
iniFileUploading,
iniFileSucceeded,
uploadIniFile,
]);

function clearStatus() {
setUploadStatus(undefined);
Expand All @@ -304,12 +315,12 @@ export const AddModel = () => {
uploading={uploading}
progress={progress}
isAddUploading={progress > 0}
modelId={modelId}
modelId={analogueModel.analogueModelId}
/>
{modelId !== '' && (
{analogueModel.analogueModelId !== '' && (
<>
<ModelMetadataView
modelIdParent={modelId}
modelIdParent={analogueModel.analogueModelId}
uploadingProgress={progress}
/>
</>
Expand Down

0 comments on commit fb78466

Please sign in to comment.