Projekt

Obecné

Profil

Stáhnout (17.3 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, Row, Space, Table, Tag, Typography, Input } from 'antd';
7
import { 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
    DocumentListInfo,
14
    DocumentListResponse,
15
    DocumentUserInfo,
16
    EState,
17
} from '../../../api';
18
import { documentController, userController } from '../../../controllers';
19
import AssignDocumentModal from '../../../components/modals/AssignDocumentModal';
20
import { ShowConfirm, ShowToast } from '../../../utils/alerts';
21
import { TableDocInfo } from '../../../components/types/TableDocInfo';
22
import {
23
    getAnnotationStateColor,
24
    getAnnotationStateString,
25
    getNameTruncated,
26
    getUserInfoAlt,
27
} from '../../../utils/strings';
28
import { ABadge, BadgeStyle } from '../../../components/common/ABadge';
29
import SetRequiredAnnotationsCountModal from '../../../components/modals/SetRequiredAnnotationsCountModal';
30
import DocPreviewModal from '../../../components/modals/DocPreviewModal';
31
import { UserFilter } from '../../../components/types/UserFilter';
32
import { getColumnSearchProps, getLocaleProps } from '../../../utils/tableUtils';
33
import {
34
    CheckCircleOutlined,
35
    ClockCircleOutlined,
36
    SyncOutlined,
37
    UserOutlined,
38
} from '@ant-design/icons';
39
import { SweetAlertIcon } from 'sweetalert2';
40
import { Stack } from 'react-bootstrap';
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(0, 1000)).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.name + ' ' + user.surname,
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
    const getFinalizationStateIcon = (state: EState) => {
165
        const color = getAnnotationStateColor(state);
166
        const label = getAnnotationStateString(state);
167
        let icon = <CheckCircleOutlined />;
168
        if (state === 'NEW') {
169
            icon = <ClockCircleOutlined />;
170
        }
171
        if (state === 'IN_PROGRESS') {
172
            icon = <SyncOutlined />;
173
        }
174

    
175
        return (
176
            <Tag icon={icon} color={color} key={label}>
177
                {label.toUpperCase()}
178
            </Tag>
179
        );
180
    };
181

    
182
    const showAssignModal = () => {
183
        if (selectedDocs.length == 0) {
184
            ShowToast('Vyberte dokument pro přiřazení', 'warning', 3000, 'top-end');
185
        } else {
186
            setVisibleAssign(true);
187
        }
188
    };
189
    const showRequiredAnnotationsCountModal = () => {
190
        if (selectedDocs.length == 0) {
191
            ShowToast(
192
                'Vyberte dokument, pro které chcete nastavit požadovaný počet anotací',
193
                'warning',
194
                3000,
195
                'top-end'
196
            );
197
        } else {
198
            setVisibleSetCount(true);
199
        }
200
    };
201
    const showAddModal = () => {
202
        setVisibleAdd(true);
203
    };
204

    
205
    const showPreviewModal = async (id: string, name: string) => {
206
        const documentContent = (await documentController.documentDocumentIdGet(id)).data
207
            .content;
208
        if (documentContent) {
209
            setPreviewDocName(name);
210
            setPreviewDocContent(documentContent);
211
            setVisiblePreview(true);
212
        }
213
    };
214

    
215
    const changeDefaultAnotationCount = (e: FocusEvent<HTMLInputElement>) => {
216
        documentController.documentsRequiredAnnotationsGlobalPost({
217
            requiredAnnotations: parseInt(e.currentTarget.value),
218
        });
219
    };
220

    
221
    const hideModal = () => {
222
        fetchData();
223
        setVisibleAdd(false);
224
        setVisibleAssign(false);
225
        setVisibleSetCount(false);
226
        setVisiblePreview(false);
227
    };
228

    
229
    const columns = [
230
        {
231
            title: 'Název dokumentu',
232
            dataIndex: 'name',
233
            key: 'name',
234
            width: '30%',
235
            ...getColumnSearchProps('name', 'název'),
236
            sorter: {
237
                // @ts-ignore
238
                compare: (a, b) => a.name.localeCompare(b.name),
239
                multiple: 2,
240
            },
241
        },
242
        {
243
            title: 'Délka',
244
            dataIndex: 'length',
245
            key: 'length',
246
            width: '5%',
247
            align: 'center' as 'center',
248
            sorter: {
249
                // @ts-ignore
250
                compare: (a, b) => a.length - b.length,
251
                multiple: 1,
252
            },
253
        },
254
        {
255
            title: 'Dokončeno | přiřazeno | vyžadováno',
256
            key: 'annotationCounts',
257
            width: '15%',
258
            align: 'center' as 'center',
259
            render: (
260
                columnData: DocumentListResponse,
261
                record: DocumentListInfo,
262
                index: number
263
            ) => {
264
                const finished =
265
                    record.annotatingUsers?.filter((d) => d.state === EState.Done)
266
                        .length ?? 0;
267

    
268
                return (
269
                    <div>
270
                        <ABadge
271
                            style={
272
                                finished === record.annotatingUsers?.length
273
                                    ? BadgeStyle.SUCCESS
274
                                    : BadgeStyle.WARNING
275
                            }
276
                        >
277
                            {finished}
278
                        </ABadge>
279
                        {' | '}
280
                        <ABadge
281
                            style={
282
                                (record.annotatingUsers?.length ?? 0) >=
283
                                (record.requiredAnnotations ?? 0)
284
                                    ? BadgeStyle.SUCCESS
285
                                    : BadgeStyle.WARNING
286
                            }
287
                        >
288
                            {record.annotatingUsers?.length}
289
                        </ABadge>
290
                        {' | '}
291
                        <ABadge style={BadgeStyle.GENERAL}>
292
                            {record.requiredAnnotations}
293
                        </ABadge>
294
                    </div>
295
                );
296
            },
297
        },
298
        {
299
            title: 'Anotátoři',
300
            dataIndex: 'annotatingUsers',
301
            key: 'annotatingUsers',
302
            width: '30%',
303
            render: (
304
                columnData: DocumentUserInfo[],
305
                record: DocumentListInfo,
306
                index: number
307
            ) => {
308
                return (
309
                    <div>
310
                        {columnData.map((e) => (
311
                            <span
312
                                key={e.username + '.' + record.id}
313
                                title={getUserInfoAlt(e) + '\nStav: ' + e.state}
314
                                style={{
315
                                    color: getAnnotationStateColor(e.state),
316
                                    padding: 3,
317
                                }}
318
                                className={'me-3'}
319
                            >
320
                                <FontAwesomeIcon
321
                                    icon={faUser}
322
                                    title={getUserInfoAlt(e)}
323
                                    className={'me-2'}
324
                                />
325
                                {record.finalAnnotations?.some(
326
                                    (annot) => annot.userId === e.id
327
                                ) ? (
328
                                    <u>{getNameTruncated(e)}</u>
329
                                ) : (
330
                                    getNameTruncated(e)
331
                                )}
332
                            </span>
333
                        ))}
334
                    </div>
335
                );
336
            },
337
            filters: userFilters,
338
            filterSearch: true,
339
            // @ts-ignore
340
            onFilter: (value, record) =>
341
                // @ts-ignore
342
                record.annotatingUsers.find((user) => user['username'] === value),
343
            sorter: {
344
                // @ts-ignore
345
                compare: (a, b) => a.annotatingUsers.length - b.annotatingUsers.length,
346
                multiple: 3,
347
            },
348
        },
349
        {
350
            title: '',
351
            key: 'action',
352
            dataIndex: ['id', 'name'],
353
            align: 'center' as 'center',
354
            width: '5%',
355
            // @ts-ignore
356
            render: (text, row) => (
357
                <Button
358
                    style={{ width: '80px' }}
359
                    key={row.id}
360
                    onClick={() => showPreviewModal(row.id, row.name)}
361
                >
362
                    Náhled
363
                </Button>
364
            ),
365
        },
366
        {
367
            title: 'Finální verze dokumentu',
368
            key: 'final',
369
            dataIndex: ['id', 'finalizedExists'],
370
            width: '15%',
371
            // @ts-ignore
372
            render: (text, row) =>
373
                row.finalizedExists ? (
374
                    <>
375
                        <Row>
376
                            <Space>
377
                                <Button
378
                                    disabled={finalizing}
379
                                    onClick={() => finalizeDocumentConfirm(row.id, true)}
380
                                >
381
                                    Znovu vytvořit
382
                                </Button>
383
                            </Space>
384
                        </Row>
385
                        <Row style={{ marginTop: '5px' }}>
386
                            <Space>
387
                                <Button
388
                                    disabled={finalizing}
389
                                    onClick={() =>
390
                                        editFinalizedDocument(row.finalizedAnnotationId)
391
                                    }
392
                                >
393
                                    Upravit
394
                                </Button>
395
                                {getFinalizationStateIcon(row.finalizedState)}
396
                            </Space>
397
                        </Row>
398
                    </>
399
                ) : (
400
                    <Button
401
                        disabled={finalizing}
402
                        onClick={() => finalizeDocumentConfirm(row, false)}
403
                    >
404
                        Finalizovat
405
                    </Button>
406
                ),
407
            filters: [
408
                {
409
                    text: 'Nefinalizováno',
410
                    value: null,
411
                },
412
                {
413
                    text: 'Nový',
414
                    value: 'NEW',
415
                },
416
                {
417
                    text: 'Rozpracováno',
418
                    value: 'IN_PROGRESS',
419
                },
420
                {
421
                    text: 'Hotovo',
422
                    value: 'DONE',
423
                },
424
            ],
425
            // @ts-ignore
426
            onFilter: (value, record) => record.finalizedState === value,
427
        },
428
    ];
429

    
430
    const rowSelection = {
431
        onChange: (selectedRowKeys: React.Key[], selectedRows: DocumentListInfo[]) => {
432
            // @ts-ignore
433
            setSelectedDocs(selectedRows.map((row) => row.id));
434
        },
435
    };
436

    
437
    return redirecting || role !== 'ADMINISTRATOR' ? null : (
438
        <MainLayout>
439
            <Typography.Title level={2}>
440
                <FontAwesomeIcon icon={faFileLines} /> Dokumenty
441
            </Typography.Title>
442
            <Stack style={{ width: '30%' }} direction="horizontal" key={annotationCount}>
443
                <span style={{ width: '70%' }}>Výchozí počet anotací:</span>
444
                <Input
445
                    defaultValue={annotationCount}
446
                    onBlur={changeDefaultAnotationCount}
447
                />
448
            </Stack>
449

    
450
            <Button type={'primary'} onClick={showAddModal}>
451
                Nahrát dokument
452
            </Button>
453
            <Button onClick={showAssignModal}>Přiřadit dokumenty</Button>
454
            <Button onClick={showRequiredAnnotationsCountModal}>
455
                Nastavit požadovaný počet anotací
456
            </Button>
457
            {visibleAdd && <AddDocumentModal onCancel={hideModal} />}
458
            {visibleAssign && (
459
                <AssignDocumentModal documentsIds={selectedDocs} onCancel={hideModal} />
460
            )}
461
            {visiblePreview && (
462
                <DocPreviewModal
463
                    onCancel={hideModal}
464
                    documentName={previewDocName ?? ''}
465
                    content={
466
                        previewDocContent ?? 'Nastala chyba při načítání obsahu dokumentu'
467
                    }
468
                />
469
            )}
470
            {visibleSetCount && (
471
                <SetRequiredAnnotationsCountModal
472
                    documentsIds={selectedDocs}
473
                    onCancel={hideModal}
474
                />
475
            )}
476

    
477
            <Table
478
                locale={{ ...getLocaleProps() }}
479
                rowSelection={{
480
                    type: 'checkbox',
481
                    ...rowSelection,
482
                }}
483
                // @ts-ignore
484
                columns={columns}
485
                dataSource={documents}
486
                size="middle"
487
                scroll={{ y: 600 }}
488
            />
489
        </MainLayout>
490
    );
491
}
492

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