Projekt

Obecné

Profil

Stáhnout (22.9 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, Dropdown, Input, Menu, 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
import { FileSearchOutlined, UserDeleteOutlined } from '@ant-design/icons';
41

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

    
51
    const router = useRouter();
52

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

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

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

    
78
        let annotationCountRes =
79
            await documentController.documentsRequiredAnnotationsGlobalGet();
80
        setAnnotationCount(annotationCountRes.data.requiredAnnotationsGlobal);
81

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

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

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

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

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

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

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

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

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

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

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

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

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

    
229
    const deleteDocuments = () => {
230
        const req: DeleteDocumentsRequest = { documentIds: selectedDocs };
231

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

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

    
250
    function download(baseData: string, filename: string) {
251
        if (!baseData) {
252
            console.log('base data null');
253
            return;
254
        }
255

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

    
259
        downloadLink.href = linkSource;
260
        downloadLink.download = filename;
261
        downloadLink.click();
262

    
263
        // Clean up and remove the link
264
        // downloadLink.parentNode.removeChild(downloadLink);
265
    }
266

    
267
    const changeDefaultAnotationCount = (e: FocusEvent<HTMLInputElement>) => {
268
        documentController.documentsRequiredAnnotationsGlobalPost({
269
            requiredAnnotations: parseInt(e.currentTarget.value),
270
        });
271
    };
272

    
273
    const hideModalWithClear = () => {
274
        fetchData();
275
        setVisibleAssign(false);
276
        setVisibleSetCount(false);
277
        clearSelection();
278
    };
279

    
280
    const hideModal = () => {
281
        fetchData();
282
        setVisibleAdd(false);
283
        setVisiblePreview(false);
284
    };
285

    
286
    const removeUserDocument = (user: DocumentUserInfo, record: DocumentListInfo) => {
287
        ShowConfirm(
288
            async () => {
289
                if (!record.id || !user?.id) {
290
                    return;
291
                }
292
                await removeUserFromDocument(record.id, user.id);
293
            },
294
            'odebrat uživatele ' +
295
                user.name +
296
                ' ' +
297
                user.surname +
298
                ' (' +
299
                user.username +
300
                ') z tohoto dokumentu',
301
            'Dosavadní postup tohoto anotátora na daném dokumentu bude nenávratně smazán'
302
        );
303
    };
304

    
305
    const menu = (user: DocumentUserInfo, record: DocumentListInfo) => {
306
        return (
307
            <Menu>
308
                <Menu.ItemGroup title={getNameTruncated(user)}>
309
                    <Menu.Item
310
                        icon={<FileSearchOutlined />}
311
                        onClick={() =>
312
                            router.push({
313
                                pathname: '/annotation/[annotationId]',
314
                                query: { annotationId: user.annotationId, final: false },
315
                            })
316
                        }
317
                    >
318
                        Zobrazit anotaci
319
                    </Menu.Item>
320
                    <Menu.Item
321
                        icon={<UserDeleteOutlined />}
322
                        onClick={() => removeUserDocument(user, record)}
323
                    >
324
                        Odebrat
325
                    </Menu.Item>
326
                </Menu.ItemGroup>
327
            </Menu>
328
        );
329
    };
330

    
331
    function getUserTag(user: DocumentUserInfo, record: DocumentListInfo) {
332
        return (
333
            <Dropdown overlay={menu(user, record)}>
334
                <Space
335
                    size={2}
336
                    style={{
337
                        paddingRight: 10,
338
                        color: getAnnotationStateColor(user.state),
339
                    }}
340
                >
341
                    <FontAwesomeIcon
342
                        icon={faUser}
343
                        title={getUserInfoAlt(user)}
344
                        className={'me-2'}
345
                    />
346
                    {record.finalAnnotations?.some(
347
                        (annot) => annot.userId === user.id
348
                    ) ? (
349
                        <u>{getNameTruncated(user)}</u>
350
                    ) : (
351
                        getNameTruncated(user)
352
                    )}
353
                </Space>
354
            </Dropdown>
355
        );
356
    }
357

    
358
    const columns = [
359
        {
360
            title: 'Název dokumentu',
361
            dataIndex: 'name',
362
            key: 'name',
363
            width: '30%',
364
            ...getColumnSearchProps('name', 'název'),
365
            sorter: {
366
                // @ts-ignore
367
                compare: (a, b) => a.name.localeCompare(b.name),
368
                multiple: 2,
369
            },
370
        },
371
        {
372
            title: 'Délka',
373
            dataIndex: 'length',
374
            key: 'length',
375
            width: '5%',
376
            align: 'center' as 'center',
377
            sorter: {
378
                // @ts-ignore
379
                compare: (a, b) => a.length - b.length,
380
                multiple: 1,
381
            },
382
        },
383
        {
384
            title: 'Dokončeno | přiřazeno | vyžadováno',
385
            key: 'annotationCounts',
386
            width: '15%',
387
            align: 'center' as 'center',
388
            render: (
389
                columnData: DocumentListResponse,
390
                record: DocumentListInfo,
391
                index: number
392
            ) => {
393
                const finished =
394
                    record.annotatingUsers?.filter((d) => d.state === EState.Done)
395
                        .length ?? 0;
396

    
397
                return (
398
                    <div>
399
                        <ABadge
400
                            style={
401
                                finished === record.annotatingUsers?.length
402
                                    ? BadgeStyle.SUCCESS
403
                                    : BadgeStyle.WARNING
404
                            }
405
                        >
406
                            {finished}
407
                        </ABadge>
408
                        {' | '}
409
                        <ABadge
410
                            style={
411
                                (record.annotatingUsers?.length ?? 0) >=
412
                                (record.requiredAnnotations ?? 0)
413
                                    ? BadgeStyle.SUCCESS
414
                                    : BadgeStyle.WARNING
415
                            }
416
                        >
417
                            {record.annotatingUsers?.length}
418
                        </ABadge>
419
                        {' | '}
420
                        <ABadge style={BadgeStyle.GENERAL}>
421
                            {record.requiredAnnotations}
422
                        </ABadge>
423
                    </div>
424
                );
425
            },
426
        },
427
        {
428
            title: 'Anotátoři',
429
            dataIndex: 'annotatingUsers',
430
            key: 'annotatingUsers',
431
            width: '20%',
432
            render: (
433
                columnData: DocumentUserInfo[],
434
                record: DocumentListInfo,
435
                index: number
436
            ) => {
437
                return <div>{columnData.map((e) => getUserTag(e, record))}</div>;
438
            },
439
            filters: userFilters,
440
            filterSearch: true,
441
            // @ts-ignore
442
            onFilter: (value, record) =>
443
                // @ts-ignore
444
                record.annotatingUsers.find((user) => user['username'] === value),
445
            sorter: {
446
                // @ts-ignore
447
                compare: (a, b) => a.annotatingUsers.length - b.annotatingUsers.length,
448
                multiple: 3,
449
            },
450
        },
451
        {
452
            title: '',
453
            key: 'action',
454
            dataIndex: ['id', 'name'],
455
            align: 'center' as 'center',
456
            width: '10%',
457
            // @ts-ignore
458
            render: (text, row) => (
459
                <Button
460
                    style={{ width: '80px' }}
461
                    key={row.id}
462
                    onClick={() => showPreviewModal(row.id, row.name)}
463
                >
464
                    Náhled
465
                </Button>
466
            ),
467
        },
468
        {
469
            title: 'Finální verze dokumentu',
470
            key: 'final',
471
            dataIndex: ['id', 'finalizedExists'],
472
            width: '20%',
473
            // @ts-ignore
474
            render: (text, row) =>
475
                row.finalizedExists ? (
476
                    <>
477
                        <Row>
478
                            <Space>
479
                                <Button
480
                                    disabled={finalizing}
481
                                    onClick={() => finalizeDocumentConfirm(row, true)}
482
                                >
483
                                    Znovu vytvořit
484
                                </Button>
485
                            </Space>
486
                        </Row>
487
                        <Row style={{ marginTop: '5px' }}>
488
                            <Space>
489
                                <Button
490
                                    disabled={finalizing}
491
                                    onClick={() =>
492
                                        editFinalizedDocument(row.finalizedAnnotationId)
493
                                    }
494
                                >
495
                                    Upravit
496
                                </Button>
497
                                {getFinalizationStateIcon(row.finalizedState)}
498
                            </Space>
499
                        </Row>
500
                    </>
501
                ) : (
502
                    <Button
503
                        disabled={finalizing}
504
                        onClick={() => finalizeDocumentConfirm(row, false)}
505
                    >
506
                        Finalizovat
507
                    </Button>
508
                ),
509
            filters: [
510
                {
511
                    text: 'Nefinalizováno',
512
                    value: null,
513
                },
514
                {
515
                    text: 'Nový',
516
                    value: 'NEW',
517
                },
518
                {
519
                    text: 'Rozpracováno',
520
                    value: 'IN_PROGRESS',
521
                },
522
                {
523
                    text: 'Hotovo',
524
                    value: 'DONE',
525
                },
526
            ],
527
            // @ts-ignore
528
            onFilter: (value, record) => record.finalizedState === value,
529
        },
530
    ];
531

    
532
    const clearSelection = () => {
533
        setSelectedRows([]);
534
    };
535

    
536
    const onSelectChange = (
537
        selectedRowKeys: React.Key[],
538
        selectedRows: DocumentListInfo[]
539
    ) => {
540
        // @ts-ignore
541
        setSelectedDocs(selectedRows.map((row) => row.id));
542
        // @ts-ignore
543
        setSelectedRows(selectedRowKeys);
544
    };
545

    
546
    const rowSelection = {
547
        selectedRowKeys: selectedRows,
548
        onChange: onSelectChange,
549
    };
550

    
551
    return redirecting || role !== 'ADMINISTRATOR' ? null : (
552
        <MainLayout>
553
            <div
554
                style={{
555
                    display: 'flex',
556
                    flexDirection: 'row',
557
                    justifyContent: 'space-between',
558
                    flexWrap: 'wrap',
559
                }}
560
            >
561
                <Typography.Title level={2}>
562
                    <FontAwesomeIcon icon={faFileLines} /> Dokumenty
563
                </Typography.Title>
564

    
565
                <Stack
566
                    style={{
567
                        width: '400px',
568
                        border: '1px solid lightgray',
569
                        borderRadius: 3,
570
                        padding: 10,
571
                        marginBottom: 30,
572
                        display: 'flex',
573
                        flexDirection: 'row',
574
                        justifyContent: 'space-between',
575
                    }}
576
                    direction="horizontal"
577
                    key={annotationCount}
578
                >
579
                    <span>Výchozí požadovaný počet anotací:</span>
580
                    <Input
581
                        style={{ width: '100px' }}
582
                        defaultValue={annotationCount}
583
                        onBlur={changeDefaultAnotationCount}
584
                    />
585
                </Stack>
586
            </div>
587

    
588
            <div
589
                style={{
590
                    padding: '10px',
591
                    display: 'flex',
592
                    flexDirection: 'row',
593
                    justifyContent: 'flex-start',
594
                    gap: '20px',
595
                    marginBottom: '20px',
596
                }}
597
            >
598
                <Button type={'primary'} onClick={showAddModal}>
599
                    Nahrát dokument
600
                </Button>
601

    
602
                <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
603
                    <Button
604
                        danger
605
                        disabled={!(selectedDocs?.length > 0)}
606
                        onClick={() => deleteDocuments()}
607
                    >
608
                        Smazat dokumenty
609
                    </Button>
610

    
611
                    <Button
612
                        disabled={!(selectedDocs?.length > 0)}
613
                        onClick={() => exportDocuments()}
614
                    >
615
                        Export
616
                    </Button>
617
                    <Button
618
                        onClick={showAssignModal}
619
                        disabled={!(selectedDocs?.length > 0)}
620
                    >
621
                        Přiřadit vybrané dokumenty uživatelům
622
                    </Button>
623
                    <Button
624
                        onClick={showRequiredAnnotationsCountModal}
625
                        disabled={!(selectedDocs?.length > 0)}
626
                    >
627
                        Nastavit požadovaný počet anotací vybraným dokumentům
628
                    </Button>
629
                </div>
630
            </div>
631

    
632
            {visibleAdd && <AddDocumentModal onCancel={hideModal} />}
633
            {visibleAssign && (
634
                <AssignDocumentModal
635
                    documentsIds={selectedDocs}
636
                    onCancel={hideModalWithClear}
637
                />
638
            )}
639
            {visiblePreview && (
640
                <DocPreviewModal
641
                    onCancel={hideModal}
642
                    documentName={previewDocName ?? ''}
643
                    content={
644
                        previewDocContent ?? 'Nastala chyba při načítání obsahu dokumentu'
645
                    }
646
                />
647
            )}
648
            {visibleSetCount && (
649
                <SetRequiredAnnotationsCountModal
650
                    documentsIds={selectedDocs}
651
                    onCancel={hideModalWithClear}
652
                />
653
            )}
654

    
655
            <Table
656
                locale={{ ...getLocaleProps() }}
657
                rowSelection={rowSelection}
658
                // @ts-ignore
659
                columns={columns}
660
                dataSource={documents}
661
                size="middle"
662
                scroll={{ y: 'calc(65vh - 4em)' }}
663
                pagination={false}
664
            />
665
        </MainLayout>
666
    );
667
}
668

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