drawer: рабочий стол консолидации, переключатель «Все документы организации», загрузка только в версии в работе (#26)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Andrey Epifancev 2026-10-10 00:55:28 +04:00
parent 79278589d6
commit 6ee1d0e1cb
6 changed files with 73 additions and 29 deletions

View File

@ -1,20 +1,34 @@
import { CloseOutlined, UploadOutlined } from '@ant-design/icons'; import { CloseOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Drawer, Typography } from 'antd'; import { Button, Drawer, Switch, Tooltip, Typography } from 'antd';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { fetchLegalEntity } from '../../services/api/directories/company_groups'; import { fetchLegalEntity } from '../../services/api/directories/company_groups';
import { isInWork, useCurrentConsolidation } from '../../store/slices/consolidations/selectors';
import { useAppSelector } from '../../store/store'; import { useAppSelector } from '../../store/store';
import type { LegalEntityBrief } from '../../types/api'; import type { FileOut, LegalEntityBrief } from '../../types/api';
import { FilesList } from './FilesList'; import { FilesList } from './FilesList';
import { UploadDocumentsModal } from './UploadDocumentsModal'; import { UploadDocumentsModal } from './UploadDocumentsModal';
import { consolidationLabel } from './consolidationLabel';
import { useLegalEntityFiles } from './useLegalEntityFiles'; import { useLegalEntityFiles } from './useLegalEntityFiles';
const UPLOAD_DISABLED_HINT = 'Загрузка доступна только в версии в работе';
export function DocumentsDrawer({ open, onClose }: { open: boolean; onClose: () => void }) { export function DocumentsDrawer({ open, onClose }: { open: boolean; onClose: () => void }) {
const [uploadOpen, setUploadOpen] = useState(false); const [uploadOpen, setUploadOpen] = useState(false);
const [entity, setEntity] = useState<LegalEntityBrief | null>(null); const [entity, setEntity] = useState<LegalEntityBrief | null>(null);
const { current_version_id, current_legal_entity_id } = useAppSelector((s) => s.consolidations); const [showAll, setShowAll] = useState(false);
const { files, loading, reload } = useLegalEntityFiles(current_legal_entity_id, open); const { current_legal_entity_id, consolidations } = useAppSelector((s) => s.consolidations);
const current = useCurrentConsolidation();
// консолидация не определена (версии нет в списке ГК) — режим «все» без переключателя (design D-3)
const desk = current !== null && !showAll;
const consolidationId = desk ? current.consolidation_id : null;
const { files, loading, reload } = useLegalEntityFiles(current_legal_entity_id, consolidationId, open);
const canUpload = current !== null && isInWork(current.version_status);
const labelFor = desk
? undefined
: (f: FileOut) => consolidationLabel(f.consolidation_id, consolidations, current?.consolidation_id ?? null);
useEffect(() => { useEffect(() => {
setShowAll(false); // новая панель открывается столом консоли
setEntity(null); setEntity(null);
if (!open || !current_legal_entity_id) return; if (!open || !current_legal_entity_id) return;
let cancelled = false; let cancelled = false;
@ -30,6 +44,17 @@ export function DocumentsDrawer({ open, onClose }: { open: boolean; onClose: ()
}; };
}, [open, current_legal_entity_id]); }, [open, current_legal_entity_id]);
const uploadButton = (
<Button
type='primary'
icon={<UploadOutlined />}
disabled={!current_legal_entity_id || !canUpload}
onClick={() => setUploadOpen(true)}
style={{ background: canUpload ? '#237804' : undefined }}>
Загрузить документы
</Button>
);
return ( return (
<Drawer <Drawer
open={open} open={open}
@ -53,21 +78,26 @@ export function DocumentsDrawer({ open, onClose }: { open: boolean; onClose: ()
)} )}
</div> </div>
}> }>
<div style={{ marginBottom: 16 }}> <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 16 }}>
<Button {canUpload ? (
type='primary' uploadButton
icon={<UploadOutlined />} ) : (
disabled={!current_legal_entity_id} <Tooltip title={UPLOAD_DISABLED_HINT}>
onClick={() => setUploadOpen(true)} <span>{uploadButton}</span>
style={{ background: '#237804' }}> </Tooltip>
Загрузить документы )}
</Button> {current !== null && (
<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Switch size='small' checked={showAll} onChange={setShowAll} />
<Typography.Text>Все документы организации</Typography.Text>
</span>
)}
</div> </div>
<FilesList files={files} loading={loading} /> <FilesList files={files} loading={loading} labelFor={labelFor} />
{current_legal_entity_id && ( {current_legal_entity_id && (
<UploadDocumentsModal <UploadDocumentsModal
legalEntityId={current_legal_entity_id} legalEntityId={current_legal_entity_id}
versionId={current_version_id} consolidationId={current?.consolidation_id ?? null}
organizationName={entity?.name ?? null} organizationName={entity?.name ?? null}
open={uploadOpen} open={uploadOpen}
onClose={() => setUploadOpen(false)} onClose={() => setUploadOpen(false)}

View File

@ -57,9 +57,9 @@ function StatusPill({ row }: { row: DocumentRow }) {
const HEADER = { fontSize: 11, letterSpacing: 0.5, color: '#8c8c8c', textTransform: 'uppercase' as const }; const HEADER = { fontSize: 11, letterSpacing: 0.5, color: '#8c8c8c', textTransform: 'uppercase' as const };
const head = (text: string) => <span style={HEADER}>{text}</span>; const head = (text: string) => <span style={HEADER}>{text}</span>;
export function FilesList({ files, loading }: { files: FileOut[]; loading: boolean }) { export function FilesList({ files, loading, labelFor }: { files: FileOut[]; loading: boolean; labelFor?: (f: FileOut) => string | null }) {
const navigate = useNavigate(); const navigate = useNavigate();
const rows = buildDocumentRows(files); const rows = buildDocumentRows(files, labelFor);
const columns: ColumnsType<DocumentRow> = [ const columns: ColumnsType<DocumentRow> = [
{ {

View File

@ -7,7 +7,7 @@ import { summarizeUpload, uploadFiles } from '../../services/api/files';
type Props = { type Props = {
legalEntityId: string; legalEntityId: string;
versionId: string | null; consolidationId: string | null;
organizationName?: string | null; organizationName?: string | null;
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
@ -16,7 +16,7 @@ type Props = {
type Summary = ReturnType<typeof summarizeUpload>; type Summary = ReturnType<typeof summarizeUpload>;
export function UploadDocumentsModal({ legalEntityId, versionId, organizationName, open, onClose, onUploaded }: Props) { export function UploadDocumentsModal({ legalEntityId, consolidationId, organizationName, 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 [summary, setSummary] = useState<Summary | null>(null);
@ -36,7 +36,7 @@ export function UploadDocumentsModal({ legalEntityId, versionId, organizationNam
const files = fileList.map((f) => f.originFileObj).filter((f): f is NonNullable<typeof f> => Boolean(f)); const files = fileList.map((f) => f.originFileObj).filter((f): f is NonNullable<typeof f> => Boolean(f));
setUploading(true); setUploading(true);
try { try {
const result = summarizeUpload(await uploadFiles(legalEntityId, files, versionId)); const result = summarizeUpload(await uploadFiles(legalEntityId, files, consolidationId));
setSummary(result); setSummary(result);
if (result.accepted.length > 0) onUploaded(); if (result.accepted.length > 0) onUploaded();
else message.error('Ни один файл не принят'); else message.error('Ни один файл не принят');

View File

@ -105,4 +105,13 @@ describe('buildDocumentRows', () => {
expect(rows[0].subtitle).toBe('Прочий документ · PDF · 12.03.2024'); expect(rows[0].subtitle).toBe('Прочий документ · PDF · 12.03.2024');
expect(rows[0].linkable).toBe(false); expect(rows[0].linkable).toBe(false);
}); });
it('подпись консолидации добавляется в subtitle последней, null — не добавляется', () => {
const rows = buildDocumentRows(
[file({ id: 'f1', documents: [doc()] }), file({ id: 'f2', documents: [], consolidation_id: 'c9' })],
(f) => (f.id === 'f2' ? 'вне консолидации' : null),
);
expect(rows[0].subtitle.endsWith('вне консолидации')).toBe(false);
expect(rows[1].subtitle.endsWith(' · вне консолидации')).toBe(true);
});
}); });

View File

@ -36,8 +36,9 @@ function documentRowStatus(status: DocumentStatus): RowStatus {
} }
/** Файлы → строки таблицы: одна строка на документ, файл без документов — одна строка на файл. */ /** Файлы → строки таблицы: одна строка на документ, файл без документов — одна строка на файл. */
export function buildDocumentRows(files: FileOut[]): DocumentRow[] { export function buildDocumentRows(files: FileOut[], labelFor?: (f: FileOut) => string | null): DocumentRow[] {
return files.flatMap((f): DocumentRow[] => { return files.flatMap((f): DocumentRow[] => {
const extra = labelFor?.(f) ?? null;
const name = f.original_name ?? 'без имени'; const name = f.original_name ?? 'без имени';
const date = formatMoscowDate(f.uploaded_at); const date = formatMoscowDate(f.uploaded_at);
if (f.documents.length === 0) { if (f.documents.length === 0) {
@ -48,7 +49,7 @@ export function buildDocumentRows(files: FileOut[]): DocumentRow[] {
documentId: null, documentId: null,
name, name,
fileType: f.file_type, fileType: f.file_type,
subtitle: join([f.file_type, date]), subtitle: join([f.file_type, date, extra]),
period: '—', period: '—',
status: failed ? 'error' : 'processing', status: failed ? 'error' : 'processing',
statusLabel: failed ? 'Ошибка' : 'Обработка', statusLabel: failed ? 'Ошибка' : 'Обработка',
@ -68,7 +69,7 @@ export function buildDocumentRows(files: FileOut[]): DocumentRow[] {
documentId: d.id, documentId: d.id,
name, name,
fileType: f.file_type, fileType: f.file_type,
subtitle: join([typeText, f.file_type, date]), subtitle: join([typeText, f.file_type, date, extra]),
period: periodLabel(d.period_year, d.period_quarter, d.is_cumulative), period: periodLabel(d.period_year, d.period_quarter, d.is_cumulative),
periodCheck: d.period_check, periodCheck: d.period_check,
counterpartyCheck: d.counterparty_check, counterpartyCheck: d.counterparty_check,

View File

@ -6,8 +6,11 @@ import type { FileOut } from '../../types/api';
const POLL_MS = 5000; const POLL_MS = 5000;
/** Файлы ЮЛ; пока панель открыта и есть UPLOADED/PROCESSING — перечитываем раз в 5 с. */ /**
export function useLegalEntityFiles(legalEntityId: string | null, open: boolean) { * Файлы рабочего стола консолидации (`consolidationId`) или все файлы ЮЛ (`null`);
* пока панель открыта и есть UPLOADED/PROCESSING — перечитываем раз в 5 с.
*/
export function useLegalEntityFiles(legalEntityId: string | null, consolidationId: string | null, open: boolean) {
const [files, setFiles] = useState<FileOut[]>([]); const [files, setFiles] = useState<FileOut[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const requestRef = useRef(0); const requestRef = useRef(0);
@ -20,7 +23,7 @@ export function useLegalEntityFiles(legalEntityId: string | null, open: boolean)
inFlightRef.current = true; inFlightRef.current = true;
setLoading(true); setLoading(true);
try { try {
const items = await listLegalEntityFiles(legalEntityId); const items = await listLegalEntityFiles(legalEntityId, consolidationId);
if (requestId === requestRef.current) { if (requestId === requestRef.current) {
setFiles(items); setFiles(items);
errorShownRef.current = false; errorShownRef.current = false;
@ -37,16 +40,17 @@ export function useLegalEntityFiles(legalEntityId: string | null, open: boolean)
setLoading(false); setLoading(false);
} }
} }
}, [legalEntityId]); }, [legalEntityId, consolidationId]);
// biome-ignore lint/correctness/useExhaustiveDependencies: consolidationId — триггер сброса при смене режима, в теле не читается
useEffect(() => { useEffect(() => {
// при смене ЮЛ / закрытии панели: старые ответы не применяем, файлы прежнего ЮЛ очищаем // при смене ЮЛ, режима (консолидация/все) или закрытии панели: старые ответы не применяем, прежние файлы очищаем
requestRef.current++; requestRef.current++;
inFlightRef.current = false; inFlightRef.current = false;
errorShownRef.current = false; errorShownRef.current = false;
setFiles([]); setFiles([]);
if (open && legalEntityId) void reload(); if (open && legalEntityId) void reload();
}, [open, legalEntityId, reload]); }, [open, legalEntityId, consolidationId, reload]);
const pending = hasPendingFiles(files); const pending = hasPendingFiles(files);
useEffect(() => { useEffect(() => {