Skip to content

Commit

Permalink
Merge pull request #364 from hpi-dhc/issue/340-control-panel
Browse files Browse the repository at this point in the history
`anni`: Control Panel
  • Loading branch information
jannis-baum authored Jun 22, 2022
2 parents 8306778 + 864bc3c commit fdcd4a5
Show file tree
Hide file tree
Showing 22 changed files with 419 additions and 64 deletions.
2 changes: 1 addition & 1 deletion annotation-interface/components/common/WithIcon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function WithIcon<T>({
...additionalProps
}: PropsWithChildren<Props<T>>) {
const iconElement = createElement(icon, {
className: `h-5 w-5 ${reverse ? 'ml-2' : 'mr-2'}`,
className: `h-5 w-5 ${children && (reverse ? 'ml-2' : 'mr-2')}`,
});
return createElement(
parent ?? 'span',
Expand Down
94 changes: 94 additions & 0 deletions annotation-interface/components/home/ControlPanel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { CloudDownloadIcon } from '@heroicons/react/solid';
import axios from 'axios';
import { useState } from 'react';
import { useSWRConfig } from 'swr';

import { FetchTarget, LastUpdatesDto } from '../../pages/api/server-update';
import WithIcon from '../common/WithIcon';

type Props = {
updates: LastUpdatesDto | undefined;
hide: () => void;
};

const ControlPanel = ({ updates, hide }: Props) => {
const { mutate } = useSWRConfig();
const [isLoading, setIsLoading] = useState(false);
const [message, setMessage] = useState('');
const fetchServerData = async (target: FetchTarget) => {
setIsLoading(true);
setMessage('');
try {
await axios.post('/api/server-update', { target });
setMessage('Success!');
} catch {
setMessage(
`An unexpected error occured. Try again or contact the Annotation Server's maintainer`,
);
}
mutate('/api/server-update');
setIsLoading(false);
};
return (
<div
className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-80 text-white text-opacity-80 backdrop-blur-sm"
onClick={() => !isLoading && hide()}
>
<div
className="max-w-screen-md m-auto py-20 space-y-6"
onClick={(e) => e.stopPropagation()}
>
<h2 className="text-2xl font-bold">Fetch new data</h2>
<p>
Note that fetching data may take up to ten minutes and users
may experience undefined behavior during this time period.
Use with caution and keep this page open while fetching
data.
</p>
<p>{message}</p>
{isLoading ? (
<div className="flex justify-center">
<div className="relative">
<WithIcon
icon={CloudDownloadIcon}
className="absolute animate-ping top-0 left-0"
/>
<WithIcon icon={CloudDownloadIcon}>
Fetching data ...
</WithIcon>
</div>
</div>
) : (
<>
<div>
<WithIcon
as="button"
icon={CloudDownloadIcon}
onClick={() => fetchServerData('all')}
>
{updates?.medications ? 'Update' : 'Fetch'} all
data
</WithIcon>
</div>
{updates?.medications && (
<div>
<WithIcon
as="button"
icon={CloudDownloadIcon}
onClick={() =>
fetchServerData('guidelines')
}
>
{updates?.guidelines ? 'Update' : 'Fetch'}{' '}
CPIC guidelines
</WithIcon>
</div>
)}
</>
)}
</div>
</div>
);
};

export default ControlPanel;
4 changes: 3 additions & 1 deletion annotation-interface/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
"@headlessui/react": "^1.6.4",
"@heroicons/react": "^1.0.6",
"axios": "^0.27.2",
"dayjs": "^1.11.3",
"mongoose": "^6.3.5",
"next": "12.1.6",
"react": "^18.1.0",
"react-dom": "^18.1.0"
"react-dom": "^18.1.0",
"swr": "^1.3.0"
},
"devDependencies": {
"@types/node": "^17.0.31",
Expand Down
40 changes: 15 additions & 25 deletions annotation-interface/pages/api/bricks/[id].ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,35 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { NextApiHandler } from 'next';

import dbConnect from '../../../database/connect';
import TextBrick from '../../../database/models/TextBrick';

const brickApi = async (
req: NextApiRequest,
res: NextApiResponse,
): Promise<void> => {
const brickApi: NextApiHandler = async (req, res) => {
const {
query: { id },
method,
} = req;
await dbConnect();

switch (method) {
case 'PUT':
try {
try {
switch (method) {
case 'PUT':
const brick = await TextBrick!
.findByIdAndUpdate(id, req.body, {
new: true,
runValidators: true,
})
.orFail();
res.status(200).json({ success: true, data: brick });
} catch (error) {
res.status(400).json({ success: false });
}
break;

case 'DELETE':
try {
res.status(200).json({ brick });
return;
case 'DELETE':
await TextBrick!.deleteOne({ _id: id }).orFail();
res.status(200).json({ success: true, data: {} });
} catch (error) {
res.status(400).json({ success: false });
}
break;

default:
res.status(400).json({ success: false });
break;
res.status(200).json({ success: true });
return;
default:
throw new Error();
}
} catch {
res.status(400).json({ success: false });
}
};

Expand Down
28 changes: 12 additions & 16 deletions annotation-interface/pages/api/bricks/index.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,23 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { NextApiHandler } from 'next';

import dbConnect from '../../../database/connect';
import TextBrick from '../../../database/models/TextBrick';

const brickApi = async (
req: NextApiRequest,
res: NextApiResponse,
): Promise<void> => {
const brickApi: NextApiHandler = async (req, res) => {
const { method } = req;
await dbConnect();

switch (method) {
case 'POST':
try {
try {
switch (method) {
case 'POST':
const brick = await TextBrick!.create(req.body);
res.status(201).json({ success: true, data: brick });
} catch (error) {
res.status(400).json({ success: false });
}
break;
default:
res.status(400).json({ success: false });
break;
res.status(201).json({ brick });
return;
default:
throw new Error();
}
} catch (error) {
res.status(400).json({ success: false });
}
};

Expand Down
55 changes: 55 additions & 0 deletions annotation-interface/pages/api/server-update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import axios from 'axios';
import { NextApiHandler } from 'next';

export type FetchDate = Date | null;
export type FetchTarget = 'all' | 'guidelines';
export interface LastUpdatesDto {
medications: FetchDate;
guidelines: FetchDate;
}

const serverUpdateApi: NextApiHandler = async (req, res) => {
const { method } = req;
try {
switch (method) {
case 'GET':
const [medicationsRes, guidelinesRes] = await Promise.all([
axios.get<FetchDate>(
`http://${process.env.AS_API}/medications/last_update`,
),
axios.get<FetchDate>(
`http://${process.env.AS_API}/guidelines/last_update`,
),
]);
const lastUpdates: LastUpdatesDto = {
medications: medicationsRes.data,
guidelines: guidelinesRes.data,
};
res.status(200).json(lastUpdates);
return;

case 'POST':
const target = req.body.target as FetchTarget;
switch (target) {
case 'all':
await axios.post(`http://${process.env.AS_API}/init`);
break;
case 'guidelines':
await axios.post(
`http://${process.env.AS_API}/guidelines`,
);
break;
default:
throw new Error();
}
res.status(201).json({ success: true });
return;
default:
throw new Error();
}
} catch {
res.status(400).json({ success: false });
}
};

export default serverUpdateApi;
103 changes: 102 additions & 1 deletion annotation-interface/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,106 @@
import { CloudDownloadIcon, ExclamationIcon } from '@heroicons/react/solid';
import axios from 'axios';
import dayjs from 'dayjs';
import LocalizedFormat from 'dayjs/plugin/localizedFormat';
import RelativeTime from 'dayjs/plugin/relativeTime';
import { useState } from 'react';
import useSWR from 'swr';

import PageHeading from '../components/common/PageHeading';
import WithIcon from '../components/common/WithIcon';
import ControlPanel from '../components/home/ControlPanel';
import { LastUpdatesDto } from './api/server-update';

dayjs.extend(RelativeTime);
dayjs.extend(LocalizedFormat);

const fetchLastUpdateDates = async (url: string) =>
await axios.get<LastUpdatesDto>(url);

const dateDisplay = (
lastUpdates: LastUpdatesDto | undefined,
key: keyof LastUpdatesDto,
) => {
if (!lastUpdates) return null;
const date = lastUpdates[key];
if (!date) return <WithIcon icon={ExclamationIcon}>missing</WithIcon>;
return (
<p
data-bs-toggle="tooltip"
data-bs-placement="bottom"
title={dayjs(date).format('lll')}
>
Last updated {dayjs(date).fromNow()}
</p>
);
};

const Home = () => {
return <div>TODO</div>;
const { data: updatesResponse, error } = useSWR(
'/api/server-update',
fetchLastUpdateDates,
);
const lastUpdates = updatesResponse?.data;
const [controlVisible, setControlVisible] = useState(false);
return (
<>
<PageHeading title="PharMe's Annotation Interface">
Welcome to the curator&apos;s interface to the{' '}
<span className="italic">Annotation Server</span>: PharMe&apos;s
hub for all user-agnostic data. PharMe uses{' '}
<span className="italic">external data</span> from{' '}
<a className="underline" href="https://go.drugbank.com">
DrugBank
</a>{' '}
and{' '}
<a className="underline" href="https://cpicpgx.org">
CPIC
</a>{' '}
as well as <span className="italic">internal data</span> defined
by{' '}
<a className="underline" href="https://cpicpgx.org">
Annotations
</a>
.
</PageHeading>

<div className="pb-2 border-b border-black border-opacity-10 flex justify-between">
<h2 className="font-bold">External data status</h2>
{!error && (
<WithIcon
as="button"
icon={CloudDownloadIcon}
reverse
onClick={() => setControlVisible(true)}
>
Fetch new data
</WithIcon>
)}
</div>
{error ? (
<WithIcon as="p" icon={ExclamationIcon} className="p-2">
Unable to connect to Annotation Server.
</WithIcon>
) : (
<>
<div className="p-2 flex justify-between">
<p>DrugBank: drug names, synonyms, descriptions</p>
{dateDisplay(lastUpdates, 'medications')}
</div>
<div className="p-2 flex justify-between">
<p>CPIC: PGx guidelines</p>
{dateDisplay(lastUpdates, 'guidelines')}
</div>
</>
)}
{controlVisible && (
<ControlPanel
updates={lastUpdates}
hide={() => setControlVisible(false)}
/>
)}
</>
);
};

export default Home;
1 change: 0 additions & 1 deletion annotation-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
"@nestjs/cli": "^8.0.0",
"@nestjs/schematics": "^8.0.0",
"@nestjs/testing": "^8.0.0",
"@types/cron": "^1.7.3",
"@types/express": "^4.17.13",
"@types/jest": "27.4.1",
"@types/jsonstream": "^0.8.30",
Expand Down
Loading

0 comments on commit fdcd4a5

Please sign in to comment.