Skip to content

Commit

Permalink
feat(website): add review page #273
Browse files Browse the repository at this point in the history
* refactor: prototype for abstracted backend call with proper error handling
  • Loading branch information
TobiasKampmann authored and fengelniederhammer committed Oct 17, 2023
1 parent 1e39980 commit ee28e15
Show file tree
Hide file tree
Showing 30 changed files with 892 additions and 302 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,8 @@ class SubmissionController(
@PathVariable sequenceId: Long,
@PathVariable version: Long,
@RequestParam username: String,
): SequenceReview = databaseService.getReviewData(username, SequenceVersion(sequenceId, version))
): SequenceReview =
databaseService.getReviewData(username, SequenceVersion(sequenceId, version))

@Operation(description = SUBMIT_REVIEWED_SEQUENCE_DESCRIPTION)
@ResponseStatus(HttpStatus.NO_CONTENT)
Expand Down Expand Up @@ -279,19 +280,15 @@ class SubmissionController(
)
fun deleteUserData(
@RequestParam username: String,
) {
databaseService.deleteUserSequences(username)
}
) = databaseService.deleteUserSequences(username)

@Operation(description = "Delete sequences")
@DeleteMapping(
"/delete-sequences",
)
fun deleteSequence(
@RequestParam sequenceIds: List<Long>,
) {
databaseService.deleteSequences(sequenceIds)
}
) = databaseService.deleteSequences(sequenceIds)

data class SequenceIdList(
val sequenceIds: List<Long>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ data class SequenceReview(
val sequenceId: Long,
val version: Long,
val status: Status,
val data: ProcessedData,
val processedData: ProcessedData,
val originalData: OriginalData,
@Schema(description = "The preprocessing will be considered failed if this is not empty")
val errors: List<PreprocessingAnnotation>? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class GetDataToReviewEndpointTest(

assertThat(reviewData.sequenceId, `is`(firstSequence))
assertThat(reviewData.version, `is`(1))
assertThat(reviewData.data, `is`(PreparedProcessedData.withErrors().data))
assertThat(reviewData.processedData, `is`(PreparedProcessedData.withErrors().data))
}

@Test
Expand Down
1 change: 1 addition & 0 deletions website/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,4 @@ docker pull ghcr.io/pathoplexus/website:latest
### General tips

- Available scripts can be browsed in [`package.json`](./package.json) or by running `npm run`
- Tipps & Tricks for using icons from MUI https://mui.com/material-ui/guides/minimizing-bundle-size/
157 changes: 69 additions & 88 deletions website/package-lock.json

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,20 @@
},
"dependencies": {
"@astrojs/node": "^6.0.3",
"@emotion/react": "^11.11.1",
"@mui/icons-material": "^5.14.12",
"@tanstack/react-query": "^4.36.1",
"astro": "^3.3.0",
"change-case": "^5.0.2",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"http-proxy-middleware": "^2.0.6",
"luxon": "^3.4.0",
"neverthrow": "^6.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"winston": "^3.11.0"
"winston": "^3.11.0",
"zod": "^3.22.4"
},
"devDependencies": {
"@astrojs/check": "^0.2.1",
Expand All @@ -39,7 +43,6 @@
"@mui/material": "^5.14.13",
"@mui/x-date-pickers": "^6.16.2",
"@playwright/test": "^1.39.0",
"uuid": "^9.0.1",
"@tanstack/eslint-plugin-query": "^4.36.1",
"@testing-library/dom": "^9.3.1",
"@testing-library/jest-dom": "^6.1.3",
Expand Down Expand Up @@ -69,6 +72,7 @@
"sass": "^1.69.3",
"tailwindcss": "^3.3.3",
"typescript": "^5.2.2",
"uuid": "^9.0.1",
"vitest": "^0.34.6"
}
}
86 changes: 75 additions & 11 deletions website/src/api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { err, ok, type Result } from 'neverthrow';
import type z from 'zod';

import type { BaseType, Config, InsertionCount, MutationProportionCount, SequenceType, ServiceUrls } from './types';
import { parseFasta } from './utils/parseFasta';
import { isAlignedSequence, isUnalignedSequence } from './utils/sequenceTypeHelpers';
Expand Down Expand Up @@ -36,18 +39,29 @@ export async function fetchInsertions(
export type Log = {
level: string;
message: string;
instance?: string;
};

type ClientLogger = {
log: (log: Log) => Promise<Response>;
error: (message: string) => Promise<Response>;
info: (message: string) => Promise<Response>;
};
export const clientLogger = {
log: async ({ message, level }: Log): Promise<Response> =>
fetch('/admin/logs.txt', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ level, message }),
}),
error: async (message: string): Promise<Response> => clientLogger.log({ level: 'error', message }),
info: async (message: string) => clientLogger.log({ level: 'info', message }),

export const getClientLogger = (instance: string = 'client'): ClientLogger => {
const clientLogger = {
log: async ({ message, level, instance }: Log): Promise<Response> =>
fetch('/admin/logs.txt', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ level, message, instance }),
}),
error: async (message: string): Promise<Response> => clientLogger.log({ level: 'error', instance, message }),
info: async (message: string) => clientLogger.log({ level: 'info', instance, message }),
};
return clientLogger;
};

export async function fetchSequence(
Expand All @@ -74,3 +88,53 @@ export async function fetchSequence(
}
return fastaEntries[0].sequence;
}

type FetchParameter<ResponseType> = {
endpoint: `/${string}`;
backendUrl: string;
zodSchema?: z.Schema<ResponseType>;
options?: RequestInit;
};

export const clientFetch = async <ResponseType>({
endpoint,
backendUrl,
zodSchema,
options,
}: FetchParameter<ResponseType>): Promise<Result<ResponseType, string>> => {
const logger = getClientLogger('clientFetch ' + endpoint);
try {
const response = await fetch(`${backendUrl}${endpoint}`, options);

if (!response.ok) {
await logger.error(`Failed to fetch user sequences with status ${response.status}`);
return err(`Failed to fetch user sequences ${JSON.stringify(await response.text())}`);
}

try {
if (zodSchema === undefined) {
return ok(undefined as unknown as ResponseType);
}

const parser = (candidate: unknown) => {
try {
return ok(zodSchema.parse(candidate));
} catch (error) {
return err((error as Error).message);
}
};

const responseJson = await response.json();

return parser(responseJson);
} catch (error) {
await logger.error(
`Parsing the response review for sequence version failed with error '${JSON.stringify(error)}'`,
);
return err(`Parsing the response review for sequence version failed with error '${JSON.stringify(error)}'`);
}
} catch (error) {
await logger.error(`Failed to fetch user sequences with error '${JSON.stringify(error)}'`);
return err(`Failed to fetch user sequences with error '${JSON.stringify(error)}'`);
}
};
4 changes: 3 additions & 1 deletion website/src/components/DataUploadForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { CircularProgress, TextField } from '@mui/material';
import { type ChangeEvent, type FormEvent, useState } from 'react';

import { clientLogger } from '../api.ts';
import { getClientLogger } from '../api.ts';

const clientLogger = getClientLogger('DataUploadForm');

type DataUploadFormProps<ResultType> = {
targetUrl: string;
Expand Down
76 changes: 76 additions & 0 deletions website/src/components/Review/DataRow.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import DangerousTwoToneIcon from '@mui/icons-material/DangerousTwoTone';
import WarningAmberIcon from '@mui/icons-material/WarningAmber';
import { sentenceCase, snakeCase } from 'change-case';
import { type FC } from 'react';

import { InputField, type KeyValuePair, type Row } from './InputField.tsx';

type NonEditableRowProps = {
row: Row;
editable: false;
customKey?: string;
};

type EditableRowProps = {
row: Row;
editable: (editedRow: Row) => void;
customKey?: string;
};

type RowProps = NonEditableRowProps | EditableRowProps;
export const DataRow: FC<RowProps> = ({ row, editable, customKey }) => {
const colorClassName = row.errors.length > 0 ? 'text-red-600' : row.warnings.length > 0 ? 'text-yellow-600' : '';

return (
<tr key={snakeCase(customKey ?? row.key)}>
<td className={`w-1/4 ${colorClassName}`}>{sentenceCase(row.key)}:</td>
<td className='pr-3 text-right '>
<ErrorAndWarningIcons row={row} />
</td>
<td className='w-full'>
{editable === false ? (
<div className='px-3'>{row.value}</div>
) : (
<InputField row={row} onChange={editable} colorClassName={colorClassName} />
)}
</td>
</tr>
);
};

type ErrorAndWarningIconsProps = {
row: Row;
};
const ErrorAndWarningIcons: FC<ErrorAndWarningIconsProps> = ({ row }) => {
return (
<>
{row.warnings.length > 0 ? (
<div className='tooltip tooltip-warning whitespace-pre-line' data-tip={row.warnings.join('\n')}>
<WarningAmberIcon color='warning' />
</div>
) : null}
{row.errors.length > 0 ? (
<div className='tooltip tooltip-error whitespace-pre-line' data-tip={row.errors.join('\n')}>
<DangerousTwoToneIcon color='error' />
</div>
) : null}
</>
);
};

type ProcessedDataRowProps = {
row: KeyValuePair;
customKey?: string;
};

export const ProcessedDataRow: FC<ProcessedDataRowProps> = ({ row, customKey }) => {
return (
<tr key={snakeCase(customKey ?? row.key)}>
<td className={`w-1/4 `}>{sentenceCase(row.key)}:</td>
<td />
<td className='w-full'>
<div className='px-3'>{row.value}</div>{' '}
</td>
</tr>
);
};
64 changes: 64 additions & 0 deletions website/src/components/Review/InputField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import UndoTwoToneIcon from '@mui/icons-material/UndoTwoTone';
import { type FC, useState } from 'react';

export type KeyValuePair = {
value: string;
key: string;
};

export type Row = {
warnings: string[];
errors: string[];
initialValue: string;
} & KeyValuePair;

type InputFieldProps = {
row: Row;
onChange: (editedRow: Row) => void;
colorClassName: string;
};

export const InputField: FC<InputFieldProps> = ({ row, onChange, colorClassName }) => {
const [isFocused, setIsFocused] = useState(false);
return (
<>
<input
name={row.key}
className={`border border-gray-200 rounded-md w-full ${
row.value !== row.initialValue ? 'pl-3 pr-12' : 'px-3'
} ${colorClassName}`}
value={row.value}
onChange={(e) => onChange({ ...row, value: e.target.value })}
onFocus={() => setIsFocused(() => true)}
onBlur={() => setIsFocused(() => false)}
/>
<button
className='bg-white bg-opacity-50 rounded-lg -m-12 px-3'
onClick={() => onChange({ ...row, value: row.initialValue })}
>
{row.value !== row.initialValue && (
<div
className='tooltip tooltip-info whitespace-pre-line'
data-tip={'Revert to: ' + row.initialValue}
>
<UndoTwoToneIcon color='action' />
</div>
)}
</button>
{isFocused && row.warnings.length + row.errors.length > 0 ? (
<div className='absolute bg-white border border-gray-400 rounded-md p-2 mt-1 align-top'>
{row.errors.map((error) => (
<div key={error} className='text-red-600'>
{error}
</div>
))}
{row.warnings.map((warning) => (
<div key={warning} className='text-yellow-600'>
{warning}
</div>
))}
</div>
) : null}
</>
);
};
Loading

0 comments on commit ee28e15

Please sign in to comment.