feat: панель файлов ЮЛ — загрузка с итогом, документы, опрос до окончания распознавания (#3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EAKRDNzXtRrwmWz9z6PZu3
This commit is contained in:
parent
c11ef663e9
commit
c7867277d8
@ -122,3 +122,4 @@ docs#58 O-1 на фронте обходится). В контуре SPA отд
|
|||||||
- 08.10.2026 — D-6 worker pdf.js из пакета, без CDN. Обоснование: в контуре нет внешнего интернета. Цена ошибки: низкая.
|
- 08.10.2026 — D-6 worker pdf.js из пакета, без CDN. Обоснование: в контуре нет внешнего интернета. Цена ошибки: низкая.
|
||||||
- 08.10.2026 — D-7 правка ячеек пакетом по «Сохранить», а не по каждой ячейке. Обоснование: меньше запросов, сервер
|
- 08.10.2026 — D-7 правка ячеек пакетом по «Сохранить», а не по каждой ячейке. Обоснование: меньше запросов, сервер
|
||||||
принимает до 5000 ячеек и пересчитывает проверки один раз. Цена ошибки: низкая — поведение меняется в одном хуке.
|
принимает до 5000 ячеек и пересчитывает проверки один раз. Цена ошибки: низкая — поведение меняется в одном хуке.
|
||||||
|
- 08.10.2026 — D-8: слайс Redux `files` заменён локальным хуком `useLegalEntityFiles` (список нужен только открытой панели). Цена ошибки: низкая.
|
||||||
|
|||||||
@ -13,6 +13,7 @@ import { DocumentsDrawer } from '../widgets/FilesDrawer/FilesDrawer';
|
|||||||
|
|
||||||
export function ConsolidationPage() {
|
export function ConsolidationPage() {
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
const [reloadKey, setReloadKey] = useState(0);
|
||||||
const { group_id } = useParams();
|
const { group_id } = useParams();
|
||||||
const [searchParams] = useSearchParams();
|
const [searchParams] = useSearchParams();
|
||||||
const versionParam = searchParams.get('version');
|
const versionParam = searchParams.get('version');
|
||||||
@ -84,6 +85,7 @@ export function ConsolidationPage() {
|
|||||||
minHeight: 0,
|
minHeight: 0,
|
||||||
}}>
|
}}>
|
||||||
<ConsoleLegalEntitiesTable
|
<ConsoleLegalEntitiesTable
|
||||||
|
reloadKey={reloadKey}
|
||||||
onDrawerOpen={() => {
|
onDrawerOpen={() => {
|
||||||
setDrawerOpen(true);
|
setDrawerOpen(true);
|
||||||
}}
|
}}
|
||||||
@ -94,6 +96,7 @@ export function ConsolidationPage() {
|
|||||||
open={drawerOpen}
|
open={drawerOpen}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
setDrawerOpen(false);
|
setDrawerOpen(false);
|
||||||
|
setReloadKey((k) => k + 1);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,45 +0,0 @@
|
|||||||
import { createSlice } from '@reduxjs/toolkit';
|
|
||||||
import type { PayloadAction } from '@reduxjs/toolkit';
|
|
||||||
import type { FileOut } from '../../../types/api';
|
|
||||||
import { getFilesThunk } from './thunks';
|
|
||||||
|
|
||||||
interface FilesState {
|
|
||||||
currentOpenFiles: FileOut[];
|
|
||||||
loading: boolean;
|
|
||||||
error: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const initialState: FilesState = {
|
|
||||||
currentOpenFiles: [],
|
|
||||||
loading: false,
|
|
||||||
error: null,
|
|
||||||
};
|
|
||||||
|
|
||||||
const filesSlice = createSlice({
|
|
||||||
name: 'files',
|
|
||||||
initialState,
|
|
||||||
reducers: {
|
|
||||||
setCurrentFiles: (state, action: PayloadAction<FileOut[]>) => {
|
|
||||||
state.currentOpenFiles = action.payload;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
extraReducers(builder) {
|
|
||||||
builder
|
|
||||||
.addCase(getFilesThunk.pending, (state) => {
|
|
||||||
state.loading = true;
|
|
||||||
state.error = null;
|
|
||||||
})
|
|
||||||
.addCase(getFilesThunk.fulfilled, (state, action) => {
|
|
||||||
state.currentOpenFiles = action.payload;
|
|
||||||
state.loading = false;
|
|
||||||
})
|
|
||||||
.addCase(getFilesThunk.rejected, (state, action) => {
|
|
||||||
state.error = action.payload ?? 'Неизвестная ошибка';
|
|
||||||
state.currentOpenFiles = [];
|
|
||||||
state.loading = false;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
export const { setCurrentFiles } = filesSlice.actions;
|
|
||||||
export default filesSlice.reducer;
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
import { createAsyncThunk } from '@reduxjs/toolkit';
|
|
||||||
import { listLegalEntityFiles } from '../../../services/api/files';
|
|
||||||
import type { FileOut } from '../../../types/api';
|
|
||||||
|
|
||||||
export const getFilesThunk = createAsyncThunk<FileOut[], string, { rejectValue: string }>(
|
|
||||||
'files/getCurrentFiles',
|
|
||||||
async (legalEntityId, thunkApi) => {
|
|
||||||
try {
|
|
||||||
return await listLegalEntityFiles(legalEntityId);
|
|
||||||
} catch (e) {
|
|
||||||
return thunkApi.rejectWithValue(e instanceof Error ? e.message : 'Ошибка');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
@ -2,11 +2,9 @@ import { configureStore } from '@reduxjs/toolkit';
|
|||||||
import { useDispatch, useSelector } from 'react-redux';
|
import { useDispatch, useSelector } from 'react-redux';
|
||||||
import comGroupsReducer from './slices/companyGroupsSlice/companyGroupsSlice';
|
import comGroupsReducer from './slices/companyGroupsSlice/companyGroupsSlice';
|
||||||
import consolidationsReducer from './slices/consolidations/consolidationsSlice';
|
import consolidationsReducer from './slices/consolidations/consolidationsSlice';
|
||||||
import filesReducer from './slices/files/fileSlice';
|
|
||||||
|
|
||||||
export const store = configureStore({
|
export const store = configureStore({
|
||||||
reducer: {
|
reducer: {
|
||||||
files: filesReducer,
|
|
||||||
company_groups: comGroupsReducer,
|
company_groups: comGroupsReducer,
|
||||||
consolidations: consolidationsReducer,
|
consolidations: consolidationsReducer,
|
||||||
},
|
},
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
import { Button, Space } from 'antd';
|
import { Button, Space, message } from 'antd';
|
||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { ApiError } from '../../api/client';
|
||||||
import { ColumnSettings, DataTable, useFilteredRows, useVisibleColumns } from '../../components/GenericTable';
|
import { ColumnSettings, DataTable, useFilteredRows, useVisibleColumns } from '../../components/GenericTable';
|
||||||
import { useTableFilters } from '../../components/GenericTable/useTableFilters';
|
import { useTableFilters } from '../../components/GenericTable/useTableFilters';
|
||||||
import { getVersionCard } from '../../services/api/consolidations';
|
import { getVersionCard } from '../../services/api/consolidations';
|
||||||
@ -9,7 +10,7 @@ import type { IVersionCard, MemberRow } from '../../types/consolidations/version
|
|||||||
import { membersConfig } from './config';
|
import { membersConfig } from './config';
|
||||||
import { normalizeData } from './normalize';
|
import { normalizeData } from './normalize';
|
||||||
|
|
||||||
export function ConsoleLegalEntitiesTable({ onDrawerOpen }: { onDrawerOpen: () => void }) {
|
export function ConsoleLegalEntitiesTable({ onDrawerOpen, reloadKey }: { onDrawerOpen: () => void; reloadKey: number }) {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const consolidation_id = useAppSelector((s) => s.consolidations.current_version_id);
|
const consolidation_id = useAppSelector((s) => s.consolidations.current_version_id);
|
||||||
@ -20,12 +21,16 @@ export function ConsoleLegalEntitiesTable({ onDrawerOpen }: { onDrawerOpen: () =
|
|||||||
async function getLegalEntities() {
|
async function getLegalEntities() {
|
||||||
if (!consolidation_id) return;
|
if (!consolidation_id) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const res = await getVersionCard(consolidation_id);
|
try {
|
||||||
setConsolidationData(res);
|
setConsolidationData(await getVersionCard(consolidation_id));
|
||||||
setLoading(false);
|
} catch (e: unknown) {
|
||||||
|
message.error(e instanceof ApiError ? e.message : 'Не удалось загрузить карточку версии');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
getLegalEntities();
|
getLegalEntities();
|
||||||
}, [consolidation_id]);
|
}, [consolidation_id, reloadKey]);
|
||||||
const rawRows = useMemo(() => normalizeData(consolidationData), [consolidationData]);
|
const rawRows = useMemo(() => normalizeData(consolidationData), [consolidationData]);
|
||||||
const { visibleKeys, setVisibleKeys } = useVisibleColumns(membersConfig);
|
const { visibleKeys, setVisibleKeys } = useVisibleColumns(membersConfig);
|
||||||
const { rawQuery, columnFilters, setColumnFilters, sort, setSort, resetAll, hasActiveFilters } = useTableFilters<MemberRow>();
|
const { rawQuery, columnFilters, setColumnFilters, sort, setSort, resetAll, hasActiveFilters } = useTableFilters<MemberRow>();
|
||||||
|
|||||||
@ -1,57 +1,36 @@
|
|||||||
// DocumentsDrawer.tsx
|
import { UploadOutlined } from '@ant-design/icons';
|
||||||
import { Button, Drawer, List } from 'antd';
|
import { Button, Drawer } from 'antd';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { getFilesThunk } from '../../store/slices/files/thunks';
|
import { useAppSelector } from '../../store/store';
|
||||||
import { useAppDispatch, useAppSelector } from '../../store/store';
|
import { FilesList } from './FilesList';
|
||||||
import { UploadDocumentsModal } from './UploadDocumentsModal';
|
import { UploadDocumentsModal } from './UploadDocumentsModal';
|
||||||
import { useDocumentsPolling } from './useDocumentsPolling';
|
import { useLegalEntityFiles } from './useLegalEntityFiles';
|
||||||
|
|
||||||
export function DocumentsDrawer({
|
export function DocumentsDrawer({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||||
open,
|
|
||||||
onClose,
|
|
||||||
}: {
|
|
||||||
open: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
}) {
|
|
||||||
const dispatch = useAppDispatch();
|
|
||||||
const [uploadOpen, setUploadOpen] = useState(false);
|
const [uploadOpen, setUploadOpen] = useState(false);
|
||||||
const { current_version_id, current_legal_entity_id } = useAppSelector((state) => state.consolidations);
|
const { current_version_id, current_legal_entity_id } = useAppSelector((s) => s.consolidations);
|
||||||
|
const { files, loading, reload } = useLegalEntityFiles(current_legal_entity_id, open);
|
||||||
const { data, loading } = useDocumentsPolling(current_legal_entity_id, open);
|
|
||||||
const handleClose = () => {
|
|
||||||
// optional: clear on close so next open doesn't flash stale list
|
|
||||||
// dispatch(clearDocuments());
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Drawer
|
<Drawer
|
||||||
open={open}
|
open={open}
|
||||||
onClose={handleClose}
|
onClose={onClose}
|
||||||
destroyOnClose
|
destroyOnHidden
|
||||||
title='Документы'
|
width={560}
|
||||||
|
title='Файлы организации'
|
||||||
extra={
|
extra={
|
||||||
<Button type='primary' onClick={() => setUploadOpen(true)}>
|
<Button type='primary' icon={<UploadOutlined />} disabled={!current_legal_entity_id} onClick={() => setUploadOpen(true)}>
|
||||||
Upload documents
|
Загрузить
|
||||||
</Button>
|
</Button>
|
||||||
}>
|
}>
|
||||||
<List
|
<FilesList files={files} loading={loading} />
|
||||||
loading={loading && !data.length}
|
|
||||||
dataSource={data}
|
|
||||||
renderItem={(item) => (
|
|
||||||
<List.Item>
|
|
||||||
{item.original_name} - {item.file_type} - {item.status}
|
|
||||||
</List.Item>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{current_legal_entity_id && (
|
{current_legal_entity_id && (
|
||||||
<UploadDocumentsModal
|
<UploadDocumentsModal
|
||||||
entityId={current_legal_entity_id}
|
legalEntityId={current_legal_entity_id}
|
||||||
consolidation_version_id={current_version_id}
|
versionId={current_version_id}
|
||||||
open={uploadOpen}
|
open={uploadOpen}
|
||||||
onClose={() => setUploadOpen(false)}
|
onClose={() => setUploadOpen(false)}
|
||||||
onUploaded={() => dispatch(getFilesThunk(current_legal_entity_id))} // instant refresh, polling covers steady state
|
onUploaded={() => void reload()}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|||||||
47
src/widgets/FilesDrawer/FilesList.tsx
Normal file
47
src/widgets/FilesDrawer/FilesList.tsx
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
import { List, Space, Tag, Typography } from 'antd';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import type { DocumentBrief, FileOut } from '../../types/api';
|
||||||
|
import { documentStatusLabel, documentTypeLabel, fileStatusLabel, periodLabel } from '../../utils/labels';
|
||||||
|
|
||||||
|
const LINKABLE = new Set(['OSV', 'BALANCE', 'INCOME']);
|
||||||
|
|
||||||
|
const FILE_COLORS: Record<string, string> = { ERROR: 'red', PROCESSED: 'default' };
|
||||||
|
const DOC_COLORS: Record<string, string> = { CONFIRMED: 'green', ERROR: 'red' };
|
||||||
|
|
||||||
|
const fileColor = (f: FileOut) => FILE_COLORS[f.status] ?? 'processing';
|
||||||
|
const docColor = (d: DocumentBrief) => DOC_COLORS[d.status] ?? 'orange';
|
||||||
|
|
||||||
|
function errorReason(f: FileOut): string | null {
|
||||||
|
if (f.status !== 'ERROR' || !f.job) return null;
|
||||||
|
return f.job.mapping_error ?? f.job.error_message ?? f.job.error_code ?? f.job.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FilesList({ files, loading }: { files: FileOut[]; loading: boolean }) {
|
||||||
|
return (
|
||||||
|
<List
|
||||||
|
loading={loading && files.length === 0}
|
||||||
|
locale={{ emptyText: 'Файлов нет' }}
|
||||||
|
dataSource={files}
|
||||||
|
renderItem={(f) => (
|
||||||
|
<List.Item key={f.id}>
|
||||||
|
<Space direction='vertical' style={{ width: '100%' }} size={4}>
|
||||||
|
<Space wrap>
|
||||||
|
<Typography.Text strong>{f.original_name ?? 'без имени'}</Typography.Text>
|
||||||
|
<Tag color={fileColor(f)}>{fileStatusLabel(f.status)}</Tag>
|
||||||
|
</Space>
|
||||||
|
{errorReason(f) && <Typography.Text type='danger'>{errorReason(f)}</Typography.Text>}
|
||||||
|
{f.documents.map((d) => {
|
||||||
|
const title = `${documentTypeLabel(d.document_type, d.osv_account_code)} · ${periodLabel(d.period_year, d.period_quarter, d.is_cumulative)}`;
|
||||||
|
return (
|
||||||
|
<Space key={d.id} wrap style={{ paddingLeft: 12 }}>
|
||||||
|
{LINKABLE.has(d.document_type) ? <Link to={`/documents/${d.id}`}>{title}</Link> : <span>{title}</span>}
|
||||||
|
<Tag color={docColor(d)}>{documentStatusLabel(d.status)}</Tag>
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Space>
|
||||||
|
</List.Item>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,91 +1,106 @@
|
|||||||
import { InboxOutlined } from '@ant-design/icons';
|
import { InboxOutlined } from '@ant-design/icons';
|
||||||
// UploadDocumentsModal.tsx
|
import { Alert, Modal, Upload, message } from 'antd';
|
||||||
import { Modal, Upload, message } from 'antd';
|
import type { UploadFile } from 'antd/es/upload/interface';
|
||||||
import type { RcFile, UploadFile } from 'antd/es/upload/interface';
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
import { ApiError } from '../../api/client';
|
||||||
import { summarizeUpload, uploadFiles } from '../../services/api/files';
|
import { summarizeUpload, uploadFiles } from '../../services/api/files';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
entityId: string;
|
legalEntityId: string;
|
||||||
|
versionId: string | null;
|
||||||
open: boolean;
|
open: boolean;
|
||||||
consolidation_version_id: string | null;
|
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onUploaded?: () => void; // trigger refetch after done
|
onUploaded: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function UploadDocumentsModal({ entityId, open, onClose, onUploaded, consolidation_version_id = null }: Props) {
|
type Summary = ReturnType<typeof summarizeUpload>;
|
||||||
|
|
||||||
|
export function UploadDocumentsModal({ legalEntityId, versionId, open, onClose, onUploaded }: Props) {
|
||||||
const [fileList, setFileList] = useState<UploadFile[]>([]);
|
const [fileList, setFileList] = useState<UploadFile[]>([]);
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [summary, setSummary] = useState<Summary | null>(null);
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
if (uploading) return;
|
||||||
|
setFileList([]);
|
||||||
|
setSummary(null);
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
const handleOk = async () => {
|
const handleOk = async () => {
|
||||||
if (!fileList.length) {
|
if (summary) {
|
||||||
message.warning('No files selected');
|
close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const files = fileList.map((f) => f.originFileObj).filter((f): f is NonNullable<typeof f> => Boolean(f));
|
||||||
setUploading(true);
|
setUploading(true);
|
||||||
|
|
||||||
const files = fileList.map((f) => (f.originFileObj ?? f) as RcFile);
|
|
||||||
try {
|
try {
|
||||||
const result = await uploadFiles(entityId, files, consolidation_version_id);
|
const result = summarizeUpload(await uploadFiles(legalEntityId, files, versionId));
|
||||||
const { accepted, rejected } = summarizeUpload(result);
|
setSummary(result);
|
||||||
|
if (result.accepted.length > 0) onUploaded();
|
||||||
if (rejected.length) {
|
else message.error('Ни один файл не принят');
|
||||||
const rejectedMsg = rejected.map((r) => `${r.name}: ${r.reason}`).join('; ');
|
} catch (e: unknown) {
|
||||||
message.warning(`Загружено: ${accepted.length}, отклонено: ${rejectedMsg}`);
|
message.error(e instanceof ApiError ? e.message : 'Не удалось загрузить файлы');
|
||||||
setFileList((prev) => prev.filter((f) => rejected.some((r) => r.name === f.name)));
|
|
||||||
setUploading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.success('Все документы загружены');
|
|
||||||
setFileList([]);
|
|
||||||
onUploaded?.();
|
|
||||||
onClose();
|
|
||||||
} catch (e) {
|
|
||||||
message.error(e instanceof Error ? e.message : 'Ошибка загрузки');
|
|
||||||
} finally {
|
} finally {
|
||||||
setUploading(false);
|
setUploading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCancel = () => {
|
|
||||||
if (uploading) return; // block closing mid-upload
|
|
||||||
setFileList([]);
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={open}
|
||||||
title='Загрузить документы'
|
title='Загрузка файлов'
|
||||||
onOk={handleOk}
|
onOk={handleOk}
|
||||||
onCancel={handleCancel}
|
onCancel={close}
|
||||||
okText='Upload'
|
okText={summary ? 'Готово' : 'Загрузить'}
|
||||||
|
cancelText='Отмена'
|
||||||
confirmLoading={uploading}
|
confirmLoading={uploading}
|
||||||
okButtonProps={{ disabled: !fileList.length }}
|
okButtonProps={{ disabled: !summary && fileList.length === 0 }}
|
||||||
closable={!uploading}
|
closable={!uploading}
|
||||||
destroyOnHidden>
|
destroyOnHidden>
|
||||||
<Upload.Dragger
|
{summary ? (
|
||||||
multiple
|
<>
|
||||||
fileList={fileList}
|
{summary.accepted.length > 0 && (
|
||||||
accept='.xlsx,.xls,.pdf,.jpg,.jpeg'
|
<Alert type='success' showIcon message={`Принято: ${summary.accepted.length}`} description={summary.accepted.join(', ')} />
|
||||||
beforeUpload={(file) => {
|
)}
|
||||||
// dedupe by uid protects from React StrictMode double invoke
|
{summary.rejected.length > 0 && (
|
||||||
setFileList((prev) => (prev.some((f) => f.uid === file.uid) ? prev : [...prev, file as UploadFile]));
|
<Alert
|
||||||
return false; // prevent antd auto-upload
|
style={{ marginTop: 8 }}
|
||||||
}}
|
type='error'
|
||||||
onRemove={(file) => {
|
showIcon
|
||||||
setFileList((prev) => prev.filter((f) => f.uid !== file.uid));
|
message={`Отклонено: ${summary.rejected.length}`}
|
||||||
}}
|
description={
|
||||||
// we manage fileList ourselves, so disable antd status updates
|
<ul style={{ margin: 0, paddingLeft: 16 }}>
|
||||||
showUploadList={{ showRemoveIcon: !uploading }}
|
{summary.rejected.map((r) => (
|
||||||
>
|
<li key={r.name}>
|
||||||
<p className='ant-upload-drag-icon'>
|
{r.name} — {r.reason}
|
||||||
<InboxOutlined />
|
</li>
|
||||||
</p>
|
))}
|
||||||
<p className='ant-upload-text'>Выберите файлы</p>
|
</ul>
|
||||||
</Upload.Dragger>
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Upload.Dragger
|
||||||
|
multiple
|
||||||
|
fileList={fileList}
|
||||||
|
accept='.xls,.xlsx,.xlsb,.pdf,.png,.jpg,.jpeg'
|
||||||
|
beforeUpload={(file) => {
|
||||||
|
setFileList((prev) =>
|
||||||
|
prev.some((f) => f.uid === file.uid) ? prev : [...prev, { uid: file.uid, name: file.name, originFileObj: file }],
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}}
|
||||||
|
onRemove={(file) => setFileList((prev) => prev.filter((f) => f.uid !== file.uid))}
|
||||||
|
showUploadList={{ showRemoveIcon: !uploading }}>
|
||||||
|
<p className='ant-upload-drag-icon'>
|
||||||
|
<InboxOutlined />
|
||||||
|
</p>
|
||||||
|
<p className='ant-upload-text'>Перетащите файлы или нажмите, чтобы выбрать</p>
|
||||||
|
<p className='ant-upload-hint'>ОСВ, ББ, ОФР: xls, xlsx, xlsb, pdf, png, jpg — тип и период определятся автоматически</p>
|
||||||
|
</Upload.Dragger>
|
||||||
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,27 +0,0 @@
|
|||||||
// useDocumentsPolling.ts
|
|
||||||
import { useEffect } from 'react';
|
|
||||||
import { getFilesThunk } from '../../store/slices/files/thunks';
|
|
||||||
import { useAppDispatch, useAppSelector } from '../../store/store';
|
|
||||||
|
|
||||||
const POLL_INTERVAL = 5000;
|
|
||||||
|
|
||||||
export function useDocumentsPolling(rowId: string | null, enabled: boolean) {
|
|
||||||
const dispatch = useAppDispatch();
|
|
||||||
const data = useAppSelector((s) => s.files.currentOpenFiles);
|
|
||||||
const loading = useAppSelector((s) => s.files.loading);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!enabled || !rowId) return;
|
|
||||||
|
|
||||||
// immediate fetch
|
|
||||||
dispatch(getFilesThunk(rowId));
|
|
||||||
|
|
||||||
const id = window.setInterval(() => {
|
|
||||||
dispatch(getFilesThunk(rowId));
|
|
||||||
}, POLL_INTERVAL);
|
|
||||||
|
|
||||||
return () => clearInterval(id);
|
|
||||||
}, [dispatch, rowId, enabled]);
|
|
||||||
|
|
||||||
return { data, loading };
|
|
||||||
}
|
|
||||||
54
src/widgets/FilesDrawer/useLegalEntityFiles.ts
Normal file
54
src/widgets/FilesDrawer/useLegalEntityFiles.ts
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
import { message } from 'antd';
|
||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { ApiError } from '../../api/client';
|
||||||
|
import { hasPendingFiles, listLegalEntityFiles } from '../../services/api/files';
|
||||||
|
import type { FileOut } from '../../types/api';
|
||||||
|
|
||||||
|
const POLL_MS = 5000;
|
||||||
|
|
||||||
|
/** Файлы ЮЛ; пока панель открыта и есть UPLOADED/PROCESSING — перечитываем раз в 5 с. */
|
||||||
|
export function useLegalEntityFiles(legalEntityId: string | null, open: boolean) {
|
||||||
|
const [files, setFiles] = useState<FileOut[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const requestRef = useRef(0);
|
||||||
|
const inFlightRef = useRef(false);
|
||||||
|
|
||||||
|
const reload = useCallback(async () => {
|
||||||
|
if (!legalEntityId) return;
|
||||||
|
const requestId = ++requestRef.current;
|
||||||
|
inFlightRef.current = true;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const items = await listLegalEntityFiles(legalEntityId);
|
||||||
|
if (requestId === requestRef.current) setFiles(items);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
if (requestId === requestRef.current) message.error(e instanceof ApiError ? e.message : 'Не удалось получить файлы');
|
||||||
|
} finally {
|
||||||
|
if (requestId === requestRef.current) {
|
||||||
|
inFlightRef.current = false;
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [legalEntityId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
void reload();
|
||||||
|
} else {
|
||||||
|
requestRef.current++; // ответы после закрытия не применяем
|
||||||
|
inFlightRef.current = false;
|
||||||
|
setFiles([]);
|
||||||
|
}
|
||||||
|
}, [open, reload]);
|
||||||
|
|
||||||
|
const pending = hasPendingFiles(files);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || !pending) return;
|
||||||
|
const timer = window.setInterval(() => {
|
||||||
|
if (!inFlightRef.current) void reload(); // не копим параллельные запросы при медленном ответе
|
||||||
|
}, POLL_MS);
|
||||||
|
return () => window.clearInterval(timer);
|
||||||
|
}, [open, pending, reload]);
|
||||||
|
|
||||||
|
return { files, loading, reload };
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user