Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

File upload #88

Merged
merged 11 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
"max-lines-per-function": ["warn", { "max": 60, "skipBlankLines": true }],
"no-console": "warn",
"no-duplicate-imports": "error",
"no-magic-numbers": "warn",
"no-self-compare": "error",
"no-var": "error",
"prefer-const": "error",
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@types/node": "^16.7.13",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"axios": "^1.5.0",
"openapi-fetch": "^0.7.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand All @@ -30,12 +31,13 @@
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",
"test:ts": "tsc --noEmit",
"eject": "react-scripts eject",
"lint": "eslint --fix --ext .ts,.tsx .",
"prepare": "husky install",
"pre-commit": "yarn test --watchAll=false && yarn lint-staged"
"pre-commit": "yarn test --watchAll=false && yarn lint-staged",
"generate-schema:radix": "npx openapi-typescript https://api-pepm-dev.radix.equinor.com/swagger/v1/swagger.yaml -o src/models/schema.d.ts"
},
"lint-staged": {
"*.{ts,tsx}": "yarn lint --max-warnings 10"
Expand Down
1 change: 0 additions & 1 deletion src/auth/msalClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable no-magic-numbers */
import {
AuthenticationResult,
EventMessage,
Expand Down
8 changes: 4 additions & 4 deletions src/components/Table.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import { Chip } from '@equinor/eds-core-react'
import { EdsDataGrid } from '@equinor/eds-data-grid-react'
import { useGetAnalogueModels } from '../hooks/useGetAnalogueModels'
import * as Styled from './Table.styled'
import { useAnalogueModels } from '../hooks/useAnalogueModels'

export const Table = () => {
const { data: models } = useGetAnalogueModels()
const { models } = useAnalogueModels()

if (!models) return <p>Loading...</p>
if (models.isLoading || !models.data?.data) return <p>Loading...</p>

return (
<Styled.StyledDiv>
<EdsDataGrid
enableSorting
enablePagination
emptyMessage="Empty :("
rows={models}
rows={models.data.data}
columns={[
{
accessorKey: 'analogueModelId',
Expand Down
12 changes: 10 additions & 2 deletions src/features/AddModelDialog/AddModelDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as Styled from './AddModelDialog.styled'

interface AddModelDialogProps {
isOpen: boolean
confirm: () => void
confirm: (file: File) => Promise<void>
cancel: () => void
}

Expand All @@ -16,6 +16,10 @@ export const AddModelDialog = ({
cancel,
}: AddModelDialogProps) => {
const [isFileDisplay, setFileDisplay] = useState<boolean>(false)
const [files, setFiles] = useState<{ NC?: File; INI?: File }>({
NC: undefined,
INI: undefined,
})

function toggleINIFileContent() {
setFileDisplay(!isFileDisplay)
Expand All @@ -30,6 +34,8 @@ export const AddModelDialog = ({
</Styled.Dialog.Header>
<Styled.DialogCustomContent scrollable>
<ModelInputFilesTable
files={files}
setFiles={setFiles}
fileDisplay={{
isVisible: isFileDisplay,
toggle: toggleINIFileContent,
Expand All @@ -39,7 +45,9 @@ export const AddModelDialog = ({
<ModelMetadata />
</Styled.DialogCustomContent>
<Styled.DialogActions>
<Button onClick={confirm}>Confirm and start uploading</Button>
<Button onClick={() => (files.NC ? confirm(files.NC) : {})}>
Confirm and start uploading
</Button>
<Button variant="outlined" onClick={cancel}>
Cancel
</Button>
Expand Down
2 changes: 1 addition & 1 deletion src/features/FileUploader/FileUploader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const FileUploader = ({
}

return file ? (
<>{file}</>
<>{file.name}</>
) : (
<form method="post" encType="multipart/form-data">
<FileUpload htmlFor="file-upload" className="custom-file-upload">
Expand Down
16 changes: 12 additions & 4 deletions src/features/ModelInputFilesTable/ModelInputFilesTable.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Button, Table } from '@equinor/eds-core-react'
import { delete_to_trash as deleteIcon } from '@equinor/eds-icons'
import { ChangeEvent, useState } from 'react'
import { ChangeEvent } from 'react'
import IconButton from '../../components/IconButton/IconButton'
import { FileUploader } from '../FileUploader/FileUploader'

Expand Down Expand Up @@ -59,14 +59,22 @@ const FileColumn = ({

export const ModelInputFilesTable = ({
fileDisplay,
files,
setFiles,
}: {
fileDisplay: FileDisplay
files: { NC?: File; INI?: File }
setFiles: React.Dispatch<
React.SetStateAction<{
NC?: File | undefined
INI?: File | undefined
}>
>
}) => {
const [files, setFiles] = useState<{ NC?: File; INI?: File }>()

function updateFileDisplay(e: ChangeEvent<HTMLInputElement>) {
e.preventDefault()
const file = e.target.value
if (!e.target.files) return
const file = e.target.files[0]
const type = e.target.name
setFiles({ ...files, [type]: file })
}
Expand Down
63 changes: 63 additions & 0 deletions src/hooks/useAnalogueModels.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import type { ParamsOption, RequestBodyOption } from 'openapi-fetch'
import { useApiClient } from '../context/ApiClientProvider'
import { paths } from '../models/schema'
import { useAccessToken } from './useAccessToken'

type UseQueryOptions<T> = ParamsOption<T> &
RequestBodyOption<T> & {
// custom options
params?: {
path: {
id: string
}
}
}

const ANALOGUEMODELS_KEY = '/api/analogue-models'
const NC_FILE_KEY = '/api/analogue-models/{id}/netcdf-models'

export function useAnalogueModels() {
const apiClient = useApiClient()
const token = useAccessToken()
const headers = new Headers({ Authorization: `Bearer ${token}` })

async function fetchModels() {
const { data } = await apiClient.GET(ANALOGUEMODELS_KEY, {
headers: headers,
})
return data
}

async function createModel({
body,
}: UseQueryOptions<paths[typeof ANALOGUEMODELS_KEY]['post']>) {
const { data } = await apiClient.POST(ANALOGUEMODELS_KEY, {
body,
headers: headers,
})
return data
}

async function uploadNCFile(modelId: string, file: File) {
axios.defaults.baseURL = process.env.REACT_APP_BACKEND_ENV
const form = new FormData()
form.append('file', file)
const { data } = await axios.post(
NC_FILE_KEY.replace('{id}', modelId),
form,
{
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
}
)
return data
}

const models = useQuery([ANALOGUEMODELS_KEY, token], fetchModels)

return { fetchModels, createModel, models, uploadNCFile }
}
21 changes: 0 additions & 21 deletions src/hooks/useGetAnalogueModels.tsx

This file was deleted.

62 changes: 59 additions & 3 deletions src/models/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


export interface paths {
"/api/analoguemodels/{id}/parameters": {
"/api/analogue-models/{id}/parameters": {
post: {
parameters: {
path: {
Expand All @@ -30,7 +30,7 @@ export interface paths {
};
};
};
"/api/analoguemodels": {
"/api/analogue-models": {
/** Get a list of all AnalogueModels */
get: {
responses: {
Expand Down Expand Up @@ -68,7 +68,7 @@ export interface paths {
};
};
};
"/api/analoguemodels/{id}": {
"/api/analogue-models/{id}": {
/** Get AnalogueModel by id */
get: {
parameters: {
Expand Down Expand Up @@ -177,6 +177,62 @@ export interface paths {
404: {
content: {
"application/json": components["schemas"]["ErrorResponse"];
"application/xml": components["schemas"]["ErrorResponse"];
};
};
};
};
};
"/api/analogue-models/{id}/input-models": {
/** Upload model files that later can be converted to PEPM models. */
post: {
parameters: {
path: {
id: string;
};
};
requestBody?: {
content: {
"multipart/form-data": {
/** Format: binary */
File?: string;
FileType?: components["schemas"]["UploadFileType"];
};
};
};
responses: {
/** @description Success */
200: {
content: {
"application/json": components["schemas"]["UploadAnalogueModelCommandResponse"];
"application/xml": components["schemas"]["UploadAnalogueModelCommandResponse"];
};
};
};
};
};
"/api/analogue-models/{id}/netcdf-models": {
/** Upload NetCDF model files that later can be converted to PEPM models. */
post: {
parameters: {
path: {
id: string;
};
};
requestBody?: {
content: {
"multipart/form-data": {
/** Format: binary */
file?: string;
};
};
};
responses: {
/** @description Success */
200: {
content: {
"application/json": components["schemas"]["UploadAnalogueModelCommandResponse"];
"application/xml": components["schemas"]["UploadAnalogueModelCommandResponse"];
};
};
};
Expand Down
43 changes: 32 additions & 11 deletions src/pages/Browse/Browse.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ import { Button, Snackbar } from '@equinor/eds-core-react'
import { useState } from 'react'
import { Table } from '../../components/Table'
import { AddModelDialog } from '../../features/AddModelDialog/AddModelDialog'
import { useAnalogueModels } from '../../hooks/useAnalogueModels'

enum UploadProcess {
STARTED = 'We are uploading your new model. Please keep this browser tab open.',
SUCCESS = 'Model successfully uploaded. You may close this browser tab now.',
FAILED = 'File upload failed.',
}

export const Browse = () => {
const { createModel, uploadNCFile } = useAnalogueModels()
const [isAddModelDialog, setAddModelDialog] = useState<boolean>(false)
const [uploadStatus, setUploadStatus] = useState<string>()

const uploadProcess = {
started:
'We are uploading your new model. Please keep this browser tab open.',
success: 'Model successfully uploaded. You may close this browser tab now.',
}

function clearStatus() {
setUploadStatus(undefined)
}
Expand All @@ -21,11 +23,30 @@ export const Browse = () => {
setAddModelDialog(!isAddModelDialog)
}

function uploadModel() {
toggleDialog()
setUploadStatus(uploadProcess.started)
// TODO: upload model
// setUploadStatus(uploadProcess.success)
async function uploadModel(file: File) {
setUploadStatus(UploadProcess.STARTED)
const modelUpload = await createModel({
// TODO
body: {
name: 'testModel',
description: 'description',
sourceType: 'Deltares',
},
})

if (modelUpload?.success) {
toggleDialog()
const fileUpload = await uploadNCFile(
modelUpload.data.analogueModelId ?? '',
file
)

if (fileUpload.success) setUploadStatus(UploadProcess.SUCCESS)
else if (!fileUpload.success) {
setUploadStatus(UploadProcess.FAILED)
// TODO: show validation message
}
}
}

return (
Expand Down
Loading