Projekt

Obecné

Profil

Stáhnout (21.8 KB) Statistiky
| Větev: | Tag: | Revize:
1
import 'antd/dist/antd.css';
2
import React, { FocusEvent, useContext, useEffect, useState } from 'react';
3

    
4
import { useUnauthRedirect } from '../../../hooks';
5
import { useRouter } from 'next/router';
6
import { Button, Input, Row, Space, Table, Tag, Typography } from 'antd';
7
import { faArrowsRotate, faFileLines, faUser } from '@fortawesome/free-solid-svg-icons';
8
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
9
import { LoggedUserContext } from '../../../contexts/LoggedUserContext';
10
import { MainLayout } from '../../../layouts/MainLayout';
11
import AddDocumentModal from '../../../components/modals/AddDocumentModal';
12
import {
13
    DeleteDocumentsRequest,
14
    DocumentListInfo,
15
    DocumentListResponse,
16
    DocumentUserInfo,
17
    EState,
18
    ExportRequest,
19
} from '../../../api';
20
import { documentController, userController } from '../../../controllers';
21
import AssignDocumentModal from '../../../components/modals/AssignDocumentModal';
22
import { ShowConfirm, ShowConfirmDelete, ShowToast } from '../../../utils/alerts';
23
import { TableDocInfo } from '../../../components/types/TableDocInfo';
24
import {
25
    getAnnotationStateColor,
26
    getAnnotationStateString,
27
    getNameTruncated,
28
    getUserInfoAlt,
29
} from '../../../utils/strings';
30
import { ABadge, BadgeStyle } from '../../../components/common/ABadge';
31
import SetRequiredAnnotationsCountModal from '../../../components/modals/SetRequiredAnnotationsCountModal';
32
import DocPreviewModal from '../../../components/modals/DocPreviewModal';
33
import { UserFilter } from '../../../components/types/UserFilter';
34
import { getColumnSearchProps, getLocaleProps } from '../../../utils/tableUtils';
35
import { SweetAlertIcon } from 'sweetalert2';
36
import { Stack } from 'react-bootstrap';
37

    
38
import { faCircleCheck, faClock } from '@fortawesome/free-regular-svg-icons';
39
import styles from '/styles/Icon.module.scss';
40

    
41
function AdminDocumentPage() {
42
    const redirecting = useUnauthRedirect('/login');
43
    const { logout, role } = useContext(LoggedUserContext);
44
    const [finalizing, setFinalizing] = React.useState(false);
45
    const [visibleAdd, setVisibleAdd] = React.useState(false);
46
    const [visibleAssign, setVisibleAssign] = React.useState(false);
47
    const [visiblePreview, setVisiblePreview] = React.useState(false);
48
    const [visibleSetCount, setVisibleSetCount] = React.useState(false);
49

    
50
    const router = useRouter();
51

    
52
    const [documents, setDocuments] = useState<TableDocInfo[]>([]);
53
    const [userFilters, setUserFilters] = useState<UserFilter[]>([]);
54
    const [selectedDocs, setSelectedDocs] = useState<string[]>([]);
55
    const [previewDocContent, setPreviewDocContent] = useState<string>();
56
    const [previewDocName, setPreviewDocName] = useState<string>();
57
    const [annotationCount, setAnnotationCount] = useState<number>();
58

    
59
    async function fetchData() {
60
        const docs = (await documentController.documentsGet()).data.documents;
61
        // @ts-ignore
62
        const tableDocs: TableDocInfo[] = docs?.map((doc, index) => {
63
            return { key: index, ...doc };
64
        });
65

    
66
        const users = (await userController.usersGet()).data.users;
67
        // @ts-ignore
68
        const filters: UserFilter[] = users?.map((user) => {
69
            return {
70
                text: user.surname + ' ' + user.name,
71
                value: user.username,
72
            };
73
        });
74
        setUserFilters(filters);
75

    
76
        let annotationCountRes =
77
            await documentController.documentsRequiredAnnotationsGlobalGet();
78
        setAnnotationCount(annotationCountRes.data.requiredAnnotationsGlobal);
79

    
80
        if (!docs) {
81
            setDocuments([]);
82
        } else {
83
            setDocuments(tableDocs);
84
        }
85
    }
86

    
87
    useEffect(() => {
88
        if (!redirecting && role === 'ADMINISTRATOR') {
89
            fetchData();
90
        }
91
    }, [logout, redirecting, role, router]);
92

    
93
    const finalizeDocumentConfirm = async (
94
        document: DocumentListInfo,
95
        recreate: boolean
96
    ) => {
97
        let desc = recreate ? 'Dosavadní změny finální verze budou smazány' : '';
98
        let icon: SweetAlertIcon = recreate ? 'warning' : 'question';
99

    
100
        const doneAnnotations = document.annotatingUsers?.filter(
101
            (usr) => usr.state === EState.Done
102
        ).length;
103

    
104
        if (
105
            doneAnnotations !== undefined &&
106
            document.requiredAnnotations !== undefined &&
107
            doneAnnotations < document.requiredAnnotations
108
        ) {
109
            icon = 'warning';
110
            desc =
111
                'Není dokončen požadovaný počet anotací <br /> (dokončeno ' +
112
                doneAnnotations +
113
                ' z ' +
114
                document.requiredAnnotations +
115
                ')';
116
        }
117
        recreate
118
            ? ShowConfirm(
119
                  () => finalizeDocument(document.id),
120
                  'vytvořit novou finální verzi dokumentu',
121
                  desc,
122
                  icon
123
              )
124
            : ShowConfirm(
125
                  () => finalizeDocument(document.id),
126
                  'vytvořit finální verzi dokumentu',
127
                  desc,
128
                  icon
129
              );
130
    };
131

    
132
    const finalizeDocument = async (documentId: string | undefined) => {
133
        setFinalizing(true);
134
        const finalAnnotationId = (
135
            await documentController.documentDocumentIdFinalPost(
136
                documentId ? documentId : ''
137
            )
138
        ).data.finalAnnotationId;
139
        if (!finalAnnotationId) {
140
            ShowToast('Finální verzi se nepovedlo vytvořit', 'error');
141
        } else {
142
            router.push({
143
                pathname: '/annotation/[annotationId]',
144
                query: { annotationId: finalAnnotationId, final: true },
145
            });
146
        }
147
        setFinalizing(false);
148
    };
149

    
150
    const editFinalizedDocument = async (finalAnnotationId: string) => {
151
        setFinalizing(true);
152
        if (!finalAnnotationId) {
153
            ShowToast('Finální verze dosud neexistuje', 'warning');
154
        } else {
155
            router.push({
156
                pathname: '/annotation/[annotationId]',
157
                query: { annotationId: finalAnnotationId, final: true },
158
            });
159
        }
160
        setFinalizing(false);
161
    };
162

    
163
    async function removeUserFromDocument(documentID: string, annotatorID: string) {
164
        const res =
165
            await documentController.documentsDocumentIdAnnotatorsAnnotatorIdDelete(
166
                documentID,
167
                annotatorID
168
            );
169

    
170
        if (res.status === 200) {
171
            ShowToast('Uživatel byl úspěšně odebrán z dokumentu');
172
        }
173
        await fetchData();
174
    }
175

    
176
    const getFinalizationStateIcon = (state: EState) => {
177
        const color = getAnnotationStateColor(state);
178
        const label = getAnnotationStateString(state);
179
        let icon = <FontAwesomeIcon icon={faCircleCheck} className={styles.iconLeft} />;
180
        if (state === 'NEW') {
181
            icon = <FontAwesomeIcon icon={faClock} className={styles.iconLeft} />;
182
        }
183
        if (state === 'IN_PROGRESS') {
184
            icon = <FontAwesomeIcon icon={faArrowsRotate} className={styles.iconLeft} />;
185
        }
186

    
187
        return (
188
            <Tag icon={icon} color={color} key={label}>
189
                {label.toUpperCase()}
190
            </Tag>
191
        );
192
    };
193

    
194
    const showAssignModal = () => {
195
        if (selectedDocs.length == 0) {
196
            ShowToast('Vyberte dokument pro přiřazení', 'warning', 3000, 'top-end');
197
        } else {
198
            setVisibleAssign(true);
199
        }
200
    };
201
    const showRequiredAnnotationsCountModal = () => {
202
        if (selectedDocs.length == 0) {
203
            ShowToast(
204
                'Vyberte dokument, pro které chcete nastavit požadovaný počet anotací',
205
                'warning',
206
                3000,
207
                'top-end'
208
            );
209
        } else {
210
            setVisibleSetCount(true);
211
        }
212
    };
213
    const showAddModal = () => {
214
        setVisibleAdd(true);
215
    };
216

    
217
    const showPreviewModal = async (id: string, name: string) => {
218
        const documentContent = (await documentController.documentDocumentIdGet(id)).data
219
            .content;
220
        if (documentContent) {
221
            setPreviewDocName(name);
222
            setPreviewDocContent(documentContent);
223
            setVisiblePreview(true);
224
        }
225
    };
226

    
227
    const deleteDocuments = () => {
228
        const req: DeleteDocumentsRequest = { documentIds: selectedDocs };
229

    
230
        ShowConfirmDelete(() => {
231
            documentController.documentsDelete(req).then(() => {
232
                ShowToast('Dokumenty byly úspěšně odstraněny');
233
                fetchData();
234
            });
235
        }, 'dokumenty');
236
    };
237

    
238
    const exportDocuments = async () => {
239
        const req: ExportRequest = { documentIds: selectedDocs };
240
        const res = await documentController.documentsExportPost(req);
241
        if (res?.data) {
242
            download(res.data, 'export.zip');
243
        }
244
    };
245

    
246
    function download(baseData: string, filename: string) {
247
        if (!baseData) {
248
            console.log('base data null');
249
            return;
250
        }
251

    
252
        const linkSource = `data:application/zip;base64,${baseData}`;
253
        const downloadLink = document.createElement('a');
254

    
255
        downloadLink.href = linkSource;
256
        downloadLink.download = filename;
257
        downloadLink.click();
258

    
259
        // Clean up and remove the link
260
        // downloadLink.parentNode.removeChild(downloadLink);
261
    }
262

    
263
    const changeDefaultAnotationCount = (e: FocusEvent<HTMLInputElement>) => {
264
        documentController.documentsRequiredAnnotationsGlobalPost({
265
            requiredAnnotations: parseInt(e.currentTarget.value),
266
        });
267
    };
268

    
269
    const hideModal = () => {
270
        fetchData();
271
        setVisibleAdd(false);
272
        setVisibleAssign(false);
273
        setVisibleSetCount(false);
274
        setVisiblePreview(false);
275
    };
276

    
277
    function getUserTag(user: DocumentUserInfo, record: DocumentListInfo) {
278
        return (
279
            <span
280
                className={'userTagWrapper'}
281
                title={getUserInfoAlt(user) + '\nStav: ' + user.state}
282
                onClick={() => {
283
                    ShowConfirm(
284
                        async () => {
285
                            if (!record.id || !user?.id) {
286
                                return;
287
                            }
288
                            await removeUserFromDocument(record.id, user.id);
289
                        },
290
                        'odebrat uživatele ' +
291
                            user.name +
292
                            ' ' +
293
                            user.surname +
294
                            ' (' +
295
                            user.username +
296
                            ') z tohoto dokumentu',
297
                        'Dosavadní postup tohoto anotátora na daném dokumentu bude nenávratně smazán'
298
                    );
299
                }}
300
            >
301
                <span
302
                    key={user.username + '.' + record.id}
303
                    style={{
304
                        color: getAnnotationStateColor(user.state),
305
                    }}
306
                    className={'me-3 userTag'}
307
                >
308
                    <FontAwesomeIcon
309
                        icon={faUser}
310
                        title={getUserInfoAlt(user)}
311
                        className={'me-2'}
312
                    />
313
                    {record.finalAnnotations?.some(
314
                        (annot) => annot.userId === user.id
315
                    ) ? (
316
                        <u>{getNameTruncated(user)}</u>
317
                    ) : (
318
                        getNameTruncated(user)
319
                    )}
320
                </span>
321
                <span className={'remove'}>Odebrat</span>
322
            </span>
323
        );
324
    }
325

    
326
    const columns = [
327
        {
328
            title: 'Název dokumentu',
329
            dataIndex: 'name',
330
            key: 'name',
331
            width: '30%',
332
            ...getColumnSearchProps('name', 'název'),
333
            sorter: {
334
                // @ts-ignore
335
                compare: (a, b) => a.name.localeCompare(b.name),
336
                multiple: 2,
337
            },
338
        },
339
        {
340
            title: 'Délka',
341
            dataIndex: 'length',
342
            key: 'length',
343
            width: '5%',
344
            align: 'center' as 'center',
345
            sorter: {
346
                // @ts-ignore
347
                compare: (a, b) => a.length - b.length,
348
                multiple: 1,
349
            },
350
        },
351
        {
352
            title: 'Dokončeno | přiřazeno | vyžadováno',
353
            key: 'annotationCounts',
354
            width: '15%',
355
            align: 'center' as 'center',
356
            render: (
357
                columnData: DocumentListResponse,
358
                record: DocumentListInfo,
359
                index: number
360
            ) => {
361
                const finished =
362
                    record.annotatingUsers?.filter((d) => d.state === EState.Done)
363
                        .length ?? 0;
364

    
365
                return (
366
                    <div>
367
                        <ABadge
368
                            style={
369
                                finished === record.annotatingUsers?.length
370
                                    ? BadgeStyle.SUCCESS
371
                                    : BadgeStyle.WARNING
372
                            }
373
                        >
374
                            {finished}
375
                        </ABadge>
376
                        {' | '}
377
                        <ABadge
378
                            style={
379
                                (record.annotatingUsers?.length ?? 0) >=
380
                                (record.requiredAnnotations ?? 0)
381
                                    ? BadgeStyle.SUCCESS
382
                                    : BadgeStyle.WARNING
383
                            }
384
                        >
385
                            {record.annotatingUsers?.length}
386
                        </ABadge>
387
                        {' | '}
388
                        <ABadge style={BadgeStyle.GENERAL}>
389
                            {record.requiredAnnotations}
390
                        </ABadge>
391
                    </div>
392
                );
393
            },
394
        },
395
        {
396
            title: 'Anotátoři',
397
            dataIndex: 'annotatingUsers',
398
            key: 'annotatingUsers',
399
            width: '20%',
400
            render: (
401
                columnData: DocumentUserInfo[],
402
                record: DocumentListInfo,
403
                index: number
404
            ) => {
405
                return <div>{columnData.map((e) => getUserTag(e, record))}</div>;
406
            },
407
            filters: userFilters,
408
            filterSearch: true,
409
            // @ts-ignore
410
            onFilter: (value, record) =>
411
                // @ts-ignore
412
                record.annotatingUsers.find((user) => user['username'] === value),
413
            sorter: {
414
                // @ts-ignore
415
                compare: (a, b) => a.annotatingUsers.length - b.annotatingUsers.length,
416
                multiple: 3,
417
            },
418
        },
419
        {
420
            title: '',
421
            key: 'action',
422
            dataIndex: ['id', 'name'],
423
            align: 'center' as 'center',
424
            width: '10%',
425
            // @ts-ignore
426
            render: (text, row) => (
427
                <Button
428
                    style={{ width: '80px' }}
429
                    key={row.id}
430
                    onClick={() => showPreviewModal(row.id, row.name)}
431
                >
432
                    Náhled
433
                </Button>
434
            ),
435
        },
436
        {
437
            title: 'Finální verze dokumentu',
438
            key: 'final',
439
            dataIndex: ['id', 'finalizedExists'],
440
            width: '20%',
441
            // @ts-ignore
442
            render: (text, row) =>
443
                row.finalizedExists ? (
444
                    <>
445
                        <Row>
446
                            <Space>
447
                                <Button
448
                                    disabled={finalizing}
449
                                    onClick={() => finalizeDocumentConfirm(row.id, true)}
450
                                >
451
                                    Znovu vytvořit
452
                                </Button>
453
                            </Space>
454
                        </Row>
455
                        <Row style={{ marginTop: '5px' }}>
456
                            <Space>
457
                                <Button
458
                                    disabled={finalizing}
459
                                    onClick={() =>
460
                                        editFinalizedDocument(row.finalizedAnnotationId)
461
                                    }
462
                                >
463
                                    Upravit
464
                                </Button>
465
                                {getFinalizationStateIcon(row.finalizedState)}
466
                            </Space>
467
                        </Row>
468
                    </>
469
                ) : (
470
                    <Button
471
                        disabled={finalizing}
472
                        onClick={() => finalizeDocumentConfirm(row, false)}
473
                    >
474
                        Finalizovat
475
                    </Button>
476
                ),
477
            filters: [
478
                {
479
                    text: 'Nefinalizováno',
480
                    value: null,
481
                },
482
                {
483
                    text: 'Nový',
484
                    value: 'NEW',
485
                },
486
                {
487
                    text: 'Rozpracováno',
488
                    value: 'IN_PROGRESS',
489
                },
490
                {
491
                    text: 'Hotovo',
492
                    value: 'DONE',
493
                },
494
            ],
495
            // @ts-ignore
496
            onFilter: (value, record) => record.finalizedState === value,
497
        },
498
    ];
499

    
500
    const rowSelection = {
501
        onChange: (selectedRowKeys: React.Key[], selectedRows: DocumentListInfo[]) => {
502
            // @ts-ignore
503
            setSelectedDocs(selectedRows.map((row) => row.id));
504
        },
505
    };
506

    
507
    return redirecting || role !== 'ADMINISTRATOR' ? null : (
508
        <MainLayout>
509
            <div
510
                style={{
511
                    display: 'flex',
512
                    flexDirection: 'row',
513
                    justifyContent: 'space-between',
514
                    flexWrap: 'wrap',
515
                }}
516
            >
517
                <Typography.Title level={2}>
518
                    <FontAwesomeIcon icon={faFileLines} /> Dokumenty
519
                </Typography.Title>
520

    
521
                <Stack
522
                    style={{
523
                        width: '400px',
524
                        border: '1px solid lightgray',
525
                        borderRadius: 3,
526
                        padding: 10,
527
                        marginBottom: 30,
528
                        display: 'flex',
529
                        flexDirection: 'row',
530
                        justifyContent: 'space-between',
531
                    }}
532
                    direction="horizontal"
533
                    key={annotationCount}
534
                >
535
                    <span>Výchozí požadovaný počet anotací:</span>
536
                    <Input
537
                        style={{ width: '100px' }}
538
                        defaultValue={annotationCount}
539
                        onBlur={changeDefaultAnotationCount}
540
                    />
541
                </Stack>
542
            </div>
543

    
544
            <div
545
                style={{
546
                    padding: '10px',
547
                    display: 'flex',
548
                    flexDirection: 'row',
549
                    justifyContent: 'flex-start',
550
                    gap: '20px',
551
                    marginBottom: '20px',
552
                }}
553
            >
554
                <Button type={'primary'} onClick={showAddModal}>
555
                    Nahrát dokument
556
                </Button>
557

    
558
                <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
559
                    <Button
560
                        danger
561
                        disabled={!(selectedDocs?.length > 0)}
562
                        onClick={() => deleteDocuments()}
563
                    >
564
                        Smazat dokumenty
565
                    </Button>
566

    
567
                    <Button
568
                        disabled={!(selectedDocs?.length > 0)}
569
                        onClick={() => exportDocuments()}
570
                    >
571
                        Export
572
                    </Button>
573
                    <Button
574
                        onClick={showAssignModal}
575
                        disabled={!(selectedDocs?.length > 0)}
576
                    >
577
                        Přiřadit vybrané dokumenty uživatelům
578
                    </Button>
579
                    <Button
580
                        onClick={showRequiredAnnotationsCountModal}
581
                        disabled={!(selectedDocs?.length > 0)}
582
                    >
583
                        Nastavit požadovaný počet anotací vybraným dokumentům
584
                    </Button>
585
                </div>
586
            </div>
587

    
588
            {visibleAdd && <AddDocumentModal onCancel={hideModal} />}
589
            {visibleAssign && (
590
                <AssignDocumentModal documentsIds={selectedDocs} onCancel={hideModal} />
591
            )}
592
            {visiblePreview && (
593
                <DocPreviewModal
594
                    onCancel={hideModal}
595
                    documentName={previewDocName ?? ''}
596
                    content={
597
                        previewDocContent ?? 'Nastala chyba při načítání obsahu dokumentu'
598
                    }
599
                />
600
            )}
601
            {visibleSetCount && (
602
                <SetRequiredAnnotationsCountModal
603
                    documentsIds={selectedDocs}
604
                    onCancel={hideModal}
605
                />
606
            )}
607

    
608
            <Table
609
                locale={{ ...getLocaleProps() }}
610
                rowSelection={{
611
                    type: 'checkbox',
612
                    ...rowSelection,
613
                }}
614
                // @ts-ignore
615
                columns={columns}
616
                dataSource={documents}
617
                size="middle"
618
                scroll={{ y: 'calc(65vh - 4em)' }}
619
                pagination={false}
620
            />
621
        </MainLayout>
622
    );
623
}
624

    
625
export default AdminDocumentPage;
    (1-1/1)