Projekt

Obecné

Profil

Stáhnout (22.5 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 [previewDocContent, setPreviewDocContent] = useState<string>();
57
    const [previewDocName, setPreviewDocName] = useState<string>();
58
    const [annotationCount, setAnnotationCount] = useState<number>();
59

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
297
    const menu = (user: DocumentUserInfo, record: DocumentListInfo) => {
298
        return (
299
            <Menu>
300
                <Menu.ItemGroup title={getNameTruncated(user)}>
301
                    <Menu.Item
302
                        icon={<FileSearchOutlined />}
303
                        onClick={() =>
304
                            router.push({
305
                                pathname: '/annotation/[annotationId]',
306
                                query: { annotationId: user.annotationId, final: false },
307
                            })
308
                        }
309
                    >
310
                        Zobrazit anotaci
311
                    </Menu.Item>
312
                    <Menu.Item
313
                        icon={<UserDeleteOutlined />}
314
                        onClick={() => removeUserDocument(user, record)}
315
                    >
316
                        Odebrat
317
                    </Menu.Item>
318
                </Menu.ItemGroup>
319
            </Menu>
320
        );
321
    };
322

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

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

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

    
524
    const rowSelection = {
525
        onChange: (selectedRowKeys: React.Key[], selectedRows: DocumentListInfo[]) => {
526
            // @ts-ignore
527
            setSelectedDocs(selectedRows.map((row) => row.id));
528
        },
529
    };
530

    
531
    return redirecting || role !== 'ADMINISTRATOR' ? null : (
532
        <MainLayout>
533
            <div
534
                style={{
535
                    display: 'flex',
536
                    flexDirection: 'row',
537
                    justifyContent: 'space-between',
538
                    flexWrap: 'wrap',
539
                }}
540
            >
541
                <Typography.Title level={2}>
542
                    <FontAwesomeIcon icon={faFileLines} /> Dokumenty
543
                </Typography.Title>
544

    
545
                <Stack
546
                    style={{
547
                        width: '400px',
548
                        border: '1px solid lightgray',
549
                        borderRadius: 3,
550
                        padding: 10,
551
                        marginBottom: 30,
552
                        display: 'flex',
553
                        flexDirection: 'row',
554
                        justifyContent: 'space-between',
555
                    }}
556
                    direction="horizontal"
557
                    key={annotationCount}
558
                >
559
                    <span>Výchozí požadovaný počet anotací:</span>
560
                    <Input
561
                        style={{ width: '100px' }}
562
                        defaultValue={annotationCount}
563
                        onBlur={changeDefaultAnotationCount}
564
                    />
565
                </Stack>
566
            </div>
567

    
568
            <div
569
                style={{
570
                    padding: '10px',
571
                    display: 'flex',
572
                    flexDirection: 'row',
573
                    justifyContent: 'flex-start',
574
                    gap: '20px',
575
                    marginBottom: '20px',
576
                }}
577
            >
578
                <Button type={'primary'} onClick={showAddModal}>
579
                    Nahrát dokument
580
                </Button>
581

    
582
                <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
583
                    <Button
584
                        danger
585
                        disabled={!(selectedDocs?.length > 0)}
586
                        onClick={() => deleteDocuments()}
587
                    >
588
                        Smazat dokumenty
589
                    </Button>
590

    
591
                    <Button
592
                        disabled={!(selectedDocs?.length > 0)}
593
                        onClick={() => exportDocuments()}
594
                    >
595
                        Export
596
                    </Button>
597
                    <Button
598
                        onClick={showAssignModal}
599
                        disabled={!(selectedDocs?.length > 0)}
600
                    >
601
                        Přiřadit vybrané dokumenty uživatelům
602
                    </Button>
603
                    <Button
604
                        onClick={showRequiredAnnotationsCountModal}
605
                        disabled={!(selectedDocs?.length > 0)}
606
                    >
607
                        Nastavit požadovaný počet anotací vybraným dokumentům
608
                    </Button>
609
                </div>
610
            </div>
611

    
612
            {visibleAdd && <AddDocumentModal onCancel={hideModal} />}
613
            {visibleAssign && (
614
                <AssignDocumentModal documentsIds={selectedDocs} onCancel={hideModal} />
615
            )}
616
            {visiblePreview && (
617
                <DocPreviewModal
618
                    onCancel={hideModal}
619
                    documentName={previewDocName ?? ''}
620
                    content={
621
                        previewDocContent ?? 'Nastala chyba při načítání obsahu dokumentu'
622
                    }
623
                />
624
            )}
625
            {visibleSetCount && (
626
                <SetRequiredAnnotationsCountModal
627
                    documentsIds={selectedDocs}
628
                    onCancel={hideModal}
629
                />
630
            )}
631

    
632
            <Table
633
                locale={{ ...getLocaleProps() }}
634
                rowSelection={{
635
                    type: 'checkbox',
636
                    ...rowSelection,
637
                }}
638
                // @ts-ignore
639
                columns={columns}
640
                dataSource={documents}
641
                size="middle"
642
                scroll={{ y: 'calc(65vh - 4em)' }}
643
                pagination={false}
644
            />
645
        </MainLayout>
646
    );
647
}
648

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