Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Ovo je kopija prikaza dokumenata, odnosno liste dokumenta u 79-17 koja sadržava i details dio ćisto ako nam zatreba ikad više, na početku koda moraju se uključiti import { customComparator, parseQuillText, truncateText } from '../../../utils';
- List.jsx:
- import {
- BookOutlined,
- DeleteOutlined,
- ExclamationCircleFilled,
- PlusOutlined,
- SearchOutlined,
- LinkOutlined,
- } from '@ant-design/icons';
- import { App, Button, Input, Table } from 'antd';
- import dayjs from 'dayjs';
- import { isEmpty, map } from 'lodash';
- import React, { useEffect, useMemo, useState } from 'react';
- import { useTranslation } from 'react-i18next';
- import { useDispatch, useSelector } from 'react-redux';
- import { Link, useNavigate, useParams } from 'react-router-dom';
- import CreateCard from '../../../components/common/CreateCard';
- import withLoadStatus from '../../../components/common/withLoadStatus';
- import { pageSizeOptions } from '../../../enviroment';
- import useSearch from '../../../hooks/useSearch';
- import useSearchParamsHandler from '../../../hooks/useSearchParamsHandler';
- import useTableManagement from '../../../hooks/useTableManagement';
- import { selectHasAdminRights, selectHasUserRights } from '../../../store/user/userSlice';
- import {
- deleteWorkspaceDocument,
- getWorkspaceDocuments,
- getWorkspaceNotes,
- } from '../../../store/workspace/workspaceActions';
- import { selectWorkspaceDocuments } from '../../../store/workspace/workspaceSlice';
- import { customComparator, parseQuillText, truncateText } from '../../../utils';
- import { selectFiles } from '../../../store/file/fileSlice';
- import { getFiles, getSelectedMapFiles } from '../../../store/file/fileActions';
- const List = ({ startLoading, stopLoading, isLoading }) => {
- const { workspaceId } = useParams();
- const { t } = useTranslation();
- const dispatch = useDispatch();
- const workspaceDocuments = useSelector(selectWorkspaceDocuments);
- const hasUserRights = useSelector(selectHasUserRights);
- const hasAdminRights = useSelector(selectHasAdminRights);
- const navigate = useNavigate();
- const { modal } = App.useApp();
- const files = useSelector(selectFiles);
- const [folderFiles, setFolderFiles] = useState(null);
- useEffect(() => {
- if (isEmpty(files)) {
- dispatch(getFiles(workspaceId));
- }
- }, [workspaceId]);
- useEffect(() => {
- const fetchData = async () => {
- const documentExportMap = files.find((file) => file.title === 'DocumentExportMap');
- if (documentExportMap) {
- const { selectedMapFiles } = await dispatch(
- getSelectedMapFiles(documentExportMap.id),
- ).unwrap();
- setFolderFiles(selectedMapFiles);
- }
- };
- if (!isEmpty(files)) {
- fetchData();
- }
- }, [files]);
- const { searchTerm, setSearchTerm, filteredData } = useSearch(workspaceDocuments, ['name']);
- useEffect(() => {
- setSearchTerm(getParam('search') ? getParam('search') : '');
- }, [location.search]);
- const { getParam, setParam, setParams } = useSearchParamsHandler();
- const { handleTableChange, pagination, filteredValues } = useTableManagement(['updated_by']);
- useEffect(() => {
- const defaultParams = {
- order: getParam('order', 'updatedAt'),
- dir: getParam('dir', 'DESC'),
- };
- setParams(defaultParams);
- const fetchData = async () => {
- startLoading();
- await dispatch(getWorkspaceDocuments(workspaceId)).unwrap();
- await dispatch(getWorkspaceNotes(workspaceId)).unwrap();
- stopLoading();
- };
- fetchData();
- }, []);
- useEffect(() => {
- setSearchTerm(getParam('search') ? getParam('search') : '');
- }, [location.search]);
- const updatedByFilters = [
- ...new Set(workspaceDocuments?.map((document) => document?.content?.updated_by)),
- ].map((updated_by) => ({ text: updated_by, value: updated_by }));
- const commonColumns = [
- {
- title: t('document.list.table.name'),
- dataIndex: 'name',
- sorter: (a, b) => customComparator(a.name, b.name),
- sortDirections: ['ascend', 'descend'],
- sortOrder:
- getParam('order') === 'name' ? (getParam('dir') === 'ASC' ? 'ascend' : 'descend') : null,
- render: (name) => <div>{name}</div>,
- },
- {
- title: t('document.list.table.details'),
- dataIndex: 'details',
- render: (details) => {
- const plainText = parseQuillText(details);
- const modifiedNote = truncateText(plainText, 3);
- return <p className='whitespace-pre-line'>{modifiedNote}</p>;
- },
- },
- {
- title: t('document.list.table.updatedAt'),
- dataIndex: 'updatedAt',
- sorter: (a, b) => {
- const dateObjA = dayjs(a.updatedAt).isValid()
- ? dayjs(a.updatedAt)
- : dayjs(new Date(a.updatedAt));
- const dateObjB = dayjs(b.updatedAt).isValid()
- ? dayjs(b.updatedAt)
- : dayjs(new Date(b.updatedAt));
- return dateObjA.isBefore(dateObjB) ? -1 : dateObjA.isAfter(dateObjB) ? 1 : 0;
- },
- sortDirections: ['ascend', 'descend'],
- sortOrder:
- getParam('order') === 'updatedAt'
- ? getParam('dir') === 'ASC'
- ? 'ascend'
- : 'descend'
- : null,
- render: (updatedAt) => <div>{updatedAt}</div>,
- },
- {
- title: t('document.list.table.updatedBy'),
- dataIndex: 'updated_by',
- sorter: (a, b) => customComparator(a.updated_by, b.updated_by),
- sortDirections: ['ascend', 'descend'],
- sortOrder:
- getParam('order') === 'updated_by'
- ? getParam('dir') === 'ASC'
- ? 'ascend'
- : 'descend'
- : null,
- filters: updatedByFilters,
- filteredValue: filteredValues['updated_by'],
- onFilter: (value, record) => record.updated_by === value,
- render: (updated_by) => <div>{updated_by}</div>,
- },
- {
- title: t('document.list.table.exportDocumentFile'),
- dataIndex: 'export_file',
- render: (export_file) =>
- export_file && (
- <a
- href={export_file}
- target='_blank'
- rel='noreferrer'
- onClick={(e) => e.stopPropagation()}
- >
- <LinkOutlined />
- </a>
- ),
- },
- ];
- const adminActionsColumn = {
- title: t('note.list.table.actions'),
- dataIndex: '',
- key: 'x',
- render: (record) => (
- <Link
- className='text-gray-600 hover:text-gray-400'
- onClick={(event) => showConfirm(event, record, workspaceId)}
- >
- <DeleteOutlined />
- </Link>
- ),
- };
- const columns = useMemo(() => {
- const baseColumns = [...commonColumns];
- if (hasAdminRights) {
- baseColumns.push(adminActionsColumn);
- }
- return baseColumns;
- }, [commonColumns, hasAdminRights, adminActionsColumn]);
- const showConfirm = (event, record, workspaceId) => {
- event.stopPropagation();
- modal.confirm({
- title: t('note.list.modal.title'),
- icon: <ExclamationCircleFilled />,
- content: <p>{t('note.list.modal.description', { name: record.subject })}</p>,
- okText: t('button.yes'),
- okType: 'danger',
- cancelText: t('button.no'),
- onOk() {
- const successMessage = t('notifications.group.notes.removeNote');
- const documentId = record.id;
- dispatch(deleteWorkspaceDocument({ workspaceId, documentId, successMessage }));
- },
- });
- };
- const data = useMemo(() => {
- const data = map(!isEmpty(filteredData) ? filteredData : [], (document) => ({
- key: document?.id,
- id: document?.id,
- name: document?.name,
- updatedAt: new Date(document?.updatedAt).toLocaleString(),
- details: document?.content?.details,
- updated_by: document?.content?.updated_by,
- export_file: folderFiles?.find((file) =>
- file?.name?.includes(document?.name.replace(/\s+/g, '_')),
- )?.content.url,
- }));
- return data.sort((a, b) => customComparator(a.name, b.name));
- }, [filteredData, folderFiles]);
- const handleRowClick = (record) => {
- navigate(`${record.id}`);
- };
- const searchHandler = (e) => {
- setSearchTerm(e.target.value);
- setParam('search', e.target.value === '' ? null : e.target.value);
- };
- return (
- <>
- {isLoading ? null : isEmpty(workspaceDocuments) && !hasUserRights ? (
- <CreateCard route={'create-document'} title={t('button.create')} icon={<BookOutlined />} />
- ) : (
- <>
- <div className='my-5 flex w-full flex-wrap items-center justify-between gap-2'>
- <Input
- allowClear
- className='order-2 w-full p-1.5 md:order-1 md:w-1/2 lg:w-1/3'
- prefix={<SearchOutlined className='mx-2' />}
- placeholder={t('document.list.searchPlaceholder')}
- value={searchTerm}
- onChange={(e) => {
- searchHandler(e);
- }}
- />
- <div className='order-1 flex gap-3 md:order-2'>
- {!hasUserRights && (
- <Link to={`create-document`}>
- <Button type='primary' htmlType='button' icon={<PlusOutlined />}>
- {t('button.create')}
- </Button>
- </Link>
- )}
- </div>
- </div>
- <Table
- columns={columns}
- dataSource={data}
- onChange={handleTableChange}
- onRow={(record) => ({
- onClick: () => {
- handleRowClick(record);
- },
- className: 'table-row-cursor-pointer',
- })}
- scroll={{ x: 300 }}
- tableLayout='auto'
- pagination={{
- current: pagination.current,
- defaultPageSize: pagination.pageSize,
- total: !isEmpty(data) ? data.length : 0,
- showTotal: (total) => `${t('global.paginationTotal', { total })}`,
- showSizeChanger: true,
- pageSizeOptions: pageSizeOptions,
- }}
- />
- </>
- )}
- </>
- );
- };
- export default withLoadStatus(List);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement