-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.tsx
More file actions
428 lines (393 loc) · 14.2 KB
/
Copy pathindex.tsx
File metadata and controls
428 lines (393 loc) · 14.2 KB
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
424
425
426
427
428
import './index.scss';
import { schema as schemaDefn } from '@bcgsc-pori/graphkb-schema';
import FileCopyIcon from '@mui/icons-material/FileCopy';
import LocalLibraryIcon from '@mui/icons-material/LocalLibrary';
import {
Alert, Button, CircularProgress,
Paper, Typography,
} from '@mui/material';
import isempty from 'lodash.isempty';
import { useSnackbar } from 'notistack';
import React, {
useCallback, useEffect, useMemo, useState,
} from 'react';
import { useMutation, useQuery } from 'react-query';
import { Link, useNavigate, useParams } from 'react-router';
import ActionButton from '@/components/ActionButton';
import { useAuth } from '@/components/Auth';
import FormContext from '@/components/FormContext';
import FormLayout from '@/components/FormLayout';
import useSchemaForm from '@/components/hooks/useSchemaForm';
import RecordFormStateToggle from '@/components/RecordFormStateToggle';
import { GeneralRecordType } from '@/components/types';
import { cleanPayload, FORM_VARIANT, tuple } from '@/components/util';
import api from '@/services/api';
import CivicEvidenceLink from './CivicEvidenceLink';
import ReviewDialog from './ReviewDialog';
const FIELD_EXCLUSIONS = ['groupRestrictions'];
interface StatementFormProps {
/** the title for this form */
title: string;
onError?: (arg: { error: { name?: string; message?: string }; content: unknown }) => void;
onSubmit?: (record?: GeneralRecordType) => void;
onToggleState?: (newState: FORM_VARIANT | 'graph') => void;
/** values of individual properties of passed class model */
value?: GeneralRecordType;
/** the type of NodeForm to create */
variant?: FORM_VARIANT;
}
/**
* Form/View that displays the contents of a single node
*/
const StatementForm = ({
value: initialValue = {},
title,
onToggleState,
onSubmit,
onError,
variant = FORM_VARIANT.VIEW,
}: StatementFormProps) => {
const params = useParams();
const navigate = useNavigate();
const { data: diagnosticData } = useQuery({
queryKey: tuple(
'/query',
{
queryType: 'similarTo',
target: {
queryType: 'ancestors',
target: 'Vocabulary',
filters: { name: 'diagnostic indicator' },
},
returnProperties: ['name'],
},
),
queryFn: async ({ queryKey: [, body] }) => api.query(body),
});
const { data: therapeuticData } = useQuery({
queryKey: tuple(
'/query',
{
queryType: 'similarTo',
target: {
queryType: 'ancestors',
target: 'Vocabulary',
filters: { name: 'therapeutic efficacy' },
},
returnProperties: ['name'],
},
),
queryFn: async ({ queryKey: [, body] }) => api.query(body),
});
const { data: prognosticData } = useQuery({
queryKey: tuple(
'/query',
{
queryType: 'similarTo',
target: {
queryType: 'ancestors',
target: 'Vocabulary',
filters: { name: 'prognostic indicator' },
},
returnProperties: ['name'],
},
),
queryFn: async ({ queryKey: [, body] }) => api.query(body),
});
// Fetch and populate the fields for quick copy of record
const statementQuery = useQuery({
queryKey: [`/statements/${params.rid}?neighbors=1`],
queryFn: async ({ queryKey: [route] }) => api.get(route),
enabled: (isempty(initialValue) && Boolean(params.rid)),
});
const snackbar = useSnackbar();
const auth = useAuth();
const model = schemaDefn.get('Statement');
const fieldDefs = schemaDefn.getProperties('Statement');
const [reviewDialogOpen, setReviewDialogOpen] = useState(false);
const checkLogicalStatement = useCallback((formContent) => {
try {
const {
relevance: { name: relevanceName },
subject: { '@class': subjectClass, name: subjectName },
} = formContent;
if (relevanceName === 'eligibility') {
if (subjectClass !== 'ClinicalTrial') {
return 'eligibility statements should have a ClinicalTrial subject';
}
} else if (diagnosticData?.some((r) => r.name === relevanceName)) {
if (subjectClass !== 'Disease') {
return 'diagnostic statements should have a Disease subject';
}
} else if (therapeuticData?.some((r) => r.name === relevanceName)) {
if (subjectClass !== 'Therapy') {
return 'therapeutic statements should have a Therapy subject';
}
} else if (prognosticData?.some((r) => r.name === relevanceName)) {
if (subjectName !== 'patient') {
return 'prognostic statements should have the Vocabulary record "patient" for the subject';
}
}
} catch (err) {} // eslint-disable-line no-empty
return '';
}, [diagnosticData, prognosticData, therapeuticData]);
const form = useSchemaForm(fieldDefs, initialValue, {}, {
variant,
additionalValidationFn: checkLogicalStatement,
});
const {
formIsDirty,
setFormIsDirty,
formContent,
formErrors,
updateField,
formHasErrors,
additionalValidationError,
} = form;
useEffect(() => {
if (statementQuery.data) {
navigate('/new/statement', { replace: true });
const keysToIgnore = [
'@rid', '@class',
'createdAt', 'createdBy',
'updatedAt', 'updatedBy',
'deletedAt', 'deletedBy',
'uuid', 'reviews',
];
Object.entries(statementQuery.data).forEach(([key, value]) => {
if (!keysToIgnore.includes(key)) {
updateField(key, value);
}
});
}
}, [navigate, statementQuery.data, updateField]);
const civicEvidenceId = useMemo(() => {
try {
if (variant === FORM_VARIANT.VIEW && formContent.source?.name === 'civic' && formContent.sourceId) {
return formContent.sourceId;
}
} catch (err) {
// pass
}
return '';
}, [variant, formContent]);
const statementReviewCheck = useCallback((currContent, content) => {
const updatedContent = { ...content };
if (!currContent.reviewStatus) {
updatedContent.reviewStatus = 'initial';
}
if (!currContent.reviews) {
const createdBy = auth.user;
updatedContent.reviews = [{
status: 'initial',
comment: '',
createdBy,
}];
}
return updatedContent;
}, [auth]);
const { mutate: addNewAction, isPending: isAdding } = useMutation({
mutationFn: async (content: GeneralRecordType) => {
const payload = cleanPayload(content);
const { routeName } = schemaDefn.get(payload);
return api.post(routeName, payload);
},
onSuccess: (result) => {
snackbar.enqueueSnackbar(`Sucessfully created the record ${result['@rid']}`, { variant: 'success' });
onSubmit?.(result);
},
onError: (err: Error, content) => {
console.error(err);
snackbar.enqueueSnackbar(`Error (${err.name}) in creating the record`, { variant: 'error' });
onError?.({ error: err, content });
},
});
/**
* Handler for submission of a new record
*/
const handleNewAction = useCallback(async () => {
if (formHasErrors) {
// bring up the snackbar for errors
console.error(formErrors);
snackbar.enqueueSnackbar('There are errors in the form which must be resolved before it can be submitted', { variant: 'error' });
setFormIsDirty(true);
} else {
// ok to POST
let content = { ...formContent, '@class': model.name };
content = statementReviewCheck(formContent, content);
addNewAction(content);
}
}, [addNewAction, formContent, formErrors, formHasErrors, model.name, setFormIsDirty, snackbar, statementReviewCheck]);
const { mutate: deleteAction, isPending: isDeleting } = useMutation({
mutationFn: async (content: GeneralRecordType) => {
const { routeName } = schemaDefn.get(content);
return api.delete(`${routeName}/${content['@rid']!.replace(/^#/, '')}`);
},
onSuccess: (_, content) => {
snackbar.enqueueSnackbar(`Sucessfully deleted the record ${content['@rid']}`, { variant: 'success' });
onSubmit?.();
},
onError: (err: Error, content) => {
snackbar.enqueueSnackbar(`Error (${err.name}) in deleting the record (${content['@rid']})`, { variant: 'error' });
onError?.({ error: err, content });
},
});
/**
* Handler for deleting an existing record
*/
const handleDeleteAction = useCallback(async () => {
const content = { ...formContent, '@class': model.name };
deleteAction(content);
}, [deleteAction, formContent, model.name]);
const { mutate: updateAction, isPending: isUpdating } = useMutation({
mutationFn: async (content: GeneralRecordType) => {
const payload = cleanPayload(content);
const { routeName } = schemaDefn.get(payload);
return api.patch(`${routeName}/${content['@rid']!.replace(/^#/, '')}`, payload);
},
onSuccess: (result) => {
snackbar.enqueueSnackbar(`Sucessfully edited the record ${result['@rid']}`, { variant: 'success' });
onSubmit?.(result);
},
onError: (err: Error, content) => {
snackbar.enqueueSnackbar(`Error (${err.name}) in editing the record (${content['@rid']})`, { variant: 'error' });
onError?.({ error: err, content });
},
});
/**
* Handler for edits to an existing record
*/
const handleEditAction = useCallback(async () => {
const content = { ...formContent, '@class': model.name };
if (formHasErrors) {
// bring up the snackbar for errors
console.error(formErrors);
snackbar.enqueueSnackbar('There are errors in the form which must be resolved before it can be submitted', { variant: 'error' });
setFormIsDirty(true);
} else if (!formIsDirty) {
snackbar.enqueueSnackbar('no changes to submit');
onSubmit?.(formContent);
} else {
updateAction(content);
}
}, [formContent, formErrors, formHasErrors, formIsDirty, model.name, onSubmit, setFormIsDirty, snackbar, updateAction]);
const actionInProgress = isAdding || isDeleting || isUpdating;
const handleAddReview = useCallback((content, updateReviewStatus) => {
// add the new value to the field
const reviews = [...(formContent.reviews || []), content];
updateField('reviews', reviews);
if (updateReviewStatus) {
updateField('reviewStatus', content.status);
}
setReviewDialogOpen(false);
setFormIsDirty(true);
}, [formContent.reviews, setFormIsDirty, updateField]);
let pageTitle = title;
if (variant === FORM_VARIANT.VIEW && formContent) {
if (formContent.displayName) {
pageTitle = `${formContent.displayName} (${formContent['@rid']})`;
} else {
pageTitle = `${formContent['@class']} ${formContent['@rid']}`;
}
}
return (
<Paper className="statement-form__wrapper" elevation={4}>
<div className="statement-form__header">
<span className="title">
<Typography variant="h1">{pageTitle}</Typography>
{title !== pageTitle && (<Typography>{title}</Typography>)}
</span>
<div className={`header__actions header__actions--${variant}`}>
{variant === FORM_VARIANT.EDIT && (
<Button
className="header__review-action"
disabled={actionInProgress}
onClick={() => setReviewDialogOpen(true)}
variant="outlined"
>
<LocalLibraryIcon classes={{ root: 'review-icon' }} />
Add Review
</Button>
)}
{variant === FORM_VARIANT.VIEW && (
<Button
className="header__review-action"
component={Link}
target="_blank"
to={!isempty(initialValue) ? `/new/${initialValue!['@class']!.toLowerCase()}/${initialValue!['@rid']!.replace(/^#/, '')}/` : ''}
variant="outlined"
>
<FileCopyIcon classes={{ root: 'review-icon' }} /> Create As Copy
</Button>
)}
{civicEvidenceId && <CivicEvidenceLink evidenceId={civicEvidenceId} />}
{onToggleState && (variant === FORM_VARIANT.VIEW || variant === FORM_VARIANT.EDIT) && (
<RecordFormStateToggle
allowEdit={auth.hasWriteAccess && !formContent.deletedAt}
message="Are you sure? You will lose your changes."
onClick={onToggleState}
requireConfirm={variant === 'edit' && formIsDirty}
value={variant}
/>
)}
</div>
{variant === FORM_VARIANT.EDIT && (
<ReviewDialog
isOpen={reviewDialogOpen}
onClose={() => setReviewDialogOpen(false)}
onSubmit={handleAddReview}
/>
)}
</div>
<FormContext.Provider value={form}>
<FormLayout
collapseExtra
disabled={actionInProgress || variant === FORM_VARIANT.VIEW}
exclusions={FIELD_EXCLUSIONS}
modelName={model.name}
/>
</FormContext.Provider>
<div className="statement-form__action-buttons">
{variant === FORM_VARIANT.EDIT && !formContent.deletedAt
? (
<ActionButton
color="error"
disabled={actionInProgress}
message="Are you sure you want to delete this record?"
onClick={handleDeleteAction}
variant="outlined"
>
DELETE RECORD
</ActionButton>
)
// for spacing issues only
: (<div />)}
{actionInProgress && (
<CircularProgress size={50} />
)}
{additionalValidationError && (
<Alert severity="error">{additionalValidationError}</Alert>
)}
{variant === FORM_VARIANT.NEW || variant === FORM_VARIANT.EDIT && !formContent.deletedAt
? (
<ActionButton
color="primary"
disabled={actionInProgress || (formHasErrors && formIsDirty)}
onClick={variant === FORM_VARIANT.EDIT
? handleEditAction
: handleNewAction}
requireConfirm={false}
variant="contained"
>
{variant === FORM_VARIANT.EDIT
? 'SUBMIT CHANGES'
: 'SUBMIT'}
</ActionButton>
)
// for spacing issues only
: (<div />)}
</div>
</Paper>
);
};
export default StatementForm;