[1916] Импорт ЕЦП: сводка и после записи, предупреждения в таблице

Ревью PR #217, раунд 2:
- после записи (без «Пробного прогона») показывается та же сводка с заголовком
  «Импорт завершён» и одной кнопкой «Закрыть»; список справочника обновляется сразу;
- «ГК/ЮЛ пропущено» → «без изменений»: это GK_EXISTS/LE_EXISTS, не ошибки;
- таблица «Ошибки и предупреждения»: кроме шести кодов пропуска — предупреждения
  RF_CREATED и UNKNOWN_FLAG (§13.2) с тегом уровня;
- тесты issueLines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Andrey Epifancev 2026-11-06 17:40:34 +04:00
parent 03803e98fd
commit a8ea8c6cc2
5 changed files with 122 additions and 33 deletions

View File

@ -21,14 +21,28 @@ type FormValues = {
dry_run: boolean; dry_run: boolean;
}; };
/** Отчёт последнего запуска; dryRun — был ли это пробный прогон (от него зависят заголовок, текст и кнопки сводки). */
type ImportResult = {
report: ImportReportOut;
dryRun: boolean;
};
const ON_EXISTING_OPTIONS: { value: OnExisting; label: string }[] = [ const ON_EXISTING_OPTIONS: { value: OnExisting; label: string }[] = [
{ value: 'skip', label: 'Пропустить существующие' }, { value: 'skip', label: 'Пропустить существующие' },
{ value: 'update', label: 'Обновить существующие' }, { value: 'update', label: 'Обновить существующие' },
]; ];
function modalTitle(result: ImportResult | null): string {
if (!result) {
return 'Импорт групп компаний из файла';
}
return result.dryRun ? 'Сводка импорта' : 'Импорт завершён';
}
/** /**
* Импорт выгрузки ЕЦП CRM. Пробный прогон заменяет форму сводкой: из неё — закрытие окна или возврат к форме * Импорт выгрузки ЕЦП CRM. Ответ заменяет форму сводкой (отчёт §13.3). После пробного прогона из сводки — закрытие окна
* («К загрузке файла», файл и значения формы сохраняются); после записи — уведомление и закрытие окна. * или возврат к форме («К загрузке файла», файл и значения формы сохраняются); после записи — только закрытие,
* список справочника обновляется сразу.
*/ */
export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onImported }) => { export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onImported }) => {
const [form] = Form.useForm<FormValues>(); const [form] = Form.useForm<FormValues>();
@ -36,7 +50,7 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
const [fileList, setFileList] = useState<UploadFile[]>([]); const [fileList, setFileList] = useState<UploadFile[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [dryRunReport, setDryRunReport] = useState<ImportReportOut | null>(null); const [result, setResult] = useState<ImportResult | null>(null);
const handleOk = async () => { const handleOk = async () => {
const file = fileList[0]?.originFileObj; const file = fileList[0]?.originFileObj;
@ -47,13 +61,10 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
setLoading(true); setLoading(true);
try { try {
const report = await importDirectory(file, values.dry_run, values.on_existing); const report = await importDirectory(file, values.dry_run, values.on_existing);
if (values.dry_run) { setResult({ report, dryRun: values.dry_run });
setDryRunReport(report); if (!values.dry_run) {
return;
}
notification.success({ description: 'Импорт завершён' });
onImported(); onImported();
onCancel(); }
} catch (e) { } catch (e) {
notification.error({ description: e instanceof ApiError ? e.message : 'Не удалось выполнить импорт' }); notification.error({ description: e instanceof ApiError ? e.message : 'Не удалось выполнить импорт' });
} finally { } finally {
@ -69,7 +80,7 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
return ( return (
<AppModal <AppModal
title={dryRunReport ? 'Сводка импорта' : 'Импорт групп компаний из файла'} title={modalTitle(result)}
open={open} open={open}
onCancel={handleCancel} onCancel={handleCancel}
onOk={handleOk} onOk={handleOk}
@ -78,11 +89,13 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
cancelText='Отмена' cancelText='Отмена'
cancelButtonProps={{ disabled: loading }} cancelButtonProps={{ disabled: loading }}
footer={ footer={
dryRunReport ? ( result ? (
<div style={{ display: 'flex', justifyContent: 'space-between' }}> <div style={{ display: 'flex', justifyContent: result.dryRun ? 'space-between' : 'flex-end' }}>
<Button icon={<ArrowLeftOutlined />} onClick={() => setDryRunReport(null)}> {result.dryRun && (
<Button icon={<ArrowLeftOutlined />} onClick={() => setResult(null)}>
К загрузке файла К загрузке файла
</Button> </Button>
)}
<Button type='primary' onClick={handleCancel}> <Button type='primary' onClick={handleCancel}>
Закрыть Закрыть
</Button> </Button>
@ -92,13 +105,13 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
confirmLoading={loading} confirmLoading={loading}
closable={!loading} closable={!loading}
destroyOnHidden destroyOnHidden
width={dryRunReport ? 880 : 720}> width={result ? 880 : 720}>
<Form <Form
form={form} form={form}
layout='vertical' layout='vertical'
disabled={loading} disabled={loading}
initialValues={{ on_existing: 'skip', dry_run: true }} initialValues={{ on_existing: 'skip', dry_run: true }}
style={{ display: dryRunReport ? 'none' : undefined }}> style={{ display: result ? 'none' : undefined }}>
<Form.Item name='on_existing' label='При дублировании' style={{ marginBottom: 12 }}> <Form.Item name='on_existing' label='При дублировании' style={{ marginBottom: 12 }}>
<Select options={ON_EXISTING_OPTIONS} /> <Select options={ON_EXISTING_OPTIONS} />
</Form.Item> </Form.Item>
@ -128,7 +141,7 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
</Upload.Dragger> </Upload.Dragger>
</Form.Item> </Form.Item>
</Form> </Form>
{dryRunReport && <ImportSummary report={dryRunReport} fileName={fileList[0]?.name ?? ''} />} {result && <ImportSummary report={result.report} dryRun={result.dryRun} fileName={fileList[0]?.name ?? ''} />}
</AppModal> </AppModal>
); );
}; };

View File

@ -1,19 +1,24 @@
import { Col, Row, Table, Typography } from 'antd'; import { Col, Row, Table, Tag, Typography } from 'antd';
import type { ImportReportOut } from '../../../types/api'; import type { ImportReportOut } from '../../../types/api';
import { CounterCard } from './CounterCard'; import { CounterCard } from './CounterCard';
import { errorLines } from './utils'; import { issueLines } from './utils';
type Props = { type Props = {
report: ImportReportOut; report: ImportReportOut;
fileName: string; fileName: string;
/** true — пробный прогон (ничего не записано), false — отчёт о выполненной записи. */
dryRun: boolean;
}; };
/** Сводка пробного прогона: счётчики по трём карточкам и строки, пропущенные из-за ошибок. */ const DRY_RUN_HINT = 'Предварительная проверка: в справочник ничего не записано. Показано, какие изменения будут внесены.';
export function ImportSummary({ report, fileName }: Props) { const WRITTEN_HINT = 'Изменения записаны в справочник.';
/** Сводка импорта: счётчики по трём карточкам и строки с ошибками (пропущены) и предупреждениями (импортированы). */
export function ImportSummary({ report, fileName, dryRun }: Props) {
return ( return (
<> <>
<Typography.Text type='secondary' style={{ display: 'block', marginBottom: 12 }}> <Typography.Text type='secondary' style={{ display: 'block', marginBottom: 12 }}>
{fileName} · Предварительная проверка. Показано, какие изменения будут внесены. {`${fileName} · ${dryRun ? DRY_RUN_HINT : WRITTEN_HINT}`}
</Typography.Text> </Typography.Text>
<Row gutter={12}> <Row gutter={12}>
<Col span={8}> <Col span={8}>
@ -32,7 +37,8 @@ export function ImportSummary({ report, fileName }: Props) {
items={[ items={[
{ label: 'ГК создано', value: report.groups_created }, { label: 'ГК создано', value: report.groups_created },
{ label: 'ГК обновлено', value: report.groups_updated }, { label: 'ГК обновлено', value: report.groups_updated },
{ label: 'ГК пропущено', value: report.groups_skipped }, // groups_skipped — GK_EXISTS: ГК уже есть и не менялась, это не ошибка
{ label: 'ГК без изменений', value: report.groups_skipped },
]} ]}
/> />
</Col> </Col>
@ -42,25 +48,35 @@ export function ImportSummary({ report, fileName }: Props) {
items={[ items={[
{ label: 'ЮЛ создано', value: report.entities_created }, { label: 'ЮЛ создано', value: report.entities_created },
{ label: 'ЮЛ обновлено', value: report.entities_updated }, { label: 'ЮЛ обновлено', value: report.entities_updated },
{ label: 'ЮЛ пропущено', value: report.entities_skipped }, // entities_skipped — LE_EXISTS: ЮЛ уже есть и не менялось, это не ошибка
{ label: 'ЮЛ без изменений', value: report.entities_skipped },
{ label: 'Включений в ГСК/ГСЗ', value: report.memberships_created }, { label: 'Включений в ГСК/ГСЗ', value: report.memberships_created },
]} ]}
/> />
</Col> </Col>
</Row> </Row>
<Typography.Title level={5} style={{ marginTop: 16 }}> <Typography.Title level={5} style={{ marginTop: 16 }}>
Строки с ошибками Ошибки и предупреждения
</Typography.Title> </Typography.Title>
<Table <Table
size='small' size='small'
// ключ — позиция: одна строка файла может дать несколько записей отчёта // ключ — позиция: одна строка файла может дать несколько записей отчёта
dataSource={errorLines(report.lines).map((line, key) => ({ ...line, key }))} dataSource={issueLines(report.lines).map((line, key) => ({ ...line, key }))}
pagination={{ pageSize: 5, hideOnSinglePage: true, showSizeChanger: false }} pagination={{ pageSize: 5, hideOnSinglePage: true, showSizeChanger: false }}
locale={{ emptyText: 'Ошибок не найдено' }} locale={{ emptyText: 'Ошибок и предупреждений нет' }}
columns={[ columns={[
{ title: 'Строка', dataIndex: 'row', width: 80 }, { title: 'Строка', dataIndex: 'row', width: 80 },
{ title: 'ИНН', dataIndex: 'inn', width: 140 }, { title: 'ИНН', dataIndex: 'inn', width: 140 },
{ title: 'Результат', dataIndex: 'message' }, {
title: 'Результат',
dataIndex: 'message',
render: (message: string, line) => (
<>
{line.level === 'error' ? <Tag color='error'>ошибка</Tag> : <Tag color='warning'>предупреждение</Tag>}
{message}
</>
),
},
]} ]}
/> />
</> </>

View File

@ -1,4 +1,4 @@
/** Коды строк, пропущенных импортом из-за ошибки (§13.2); остальные коды — успешные итоги и сопутствующие события. */ /** Коды строк, пропущенных импортом из-за ошибки (§13.2): итоговые коды пропуска, счётчик `errors`. */
export const ERROR_CODES = new Set([ export const ERROR_CODES = new Set([
'UNSUPPORTED_TYPE', 'UNSUPPORTED_TYPE',
'INVALID_INN', 'INVALID_INN',
@ -7,3 +7,9 @@ export const ERROR_CODES = new Set([
'LE_IN_OTHER_GROUP', 'LE_IN_OTHER_GROUP',
'GK_NAME_CONFLICT', 'GK_NAME_CONFLICT',
]); ]);
/**
* Сопутствующие события-предупреждения (§13.2): строка импортирована, но пользователю стоит проверить —
* создан новый филиал (возможна опечатка в «Базовый РФ ГК») или флаг ГСК/ГСЗ не распознан и принят как «не входит».
*/
export const WARNING_CODES = new Set(['RF_CREATED', 'UNKNOWN_FLAG']);

View File

@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest';
import type { ImportReportLine } from '../../../types/api';
import { issueLines } from './utils';
const line = (row: number, code: string): ImportReportLine => ({ row, inn: '7700000000', code, message: code });
describe('issueLines', () => {
it('оставляет шесть кодов пропуска (§13.2) с уровнем error', () => {
const codes = ['UNSUPPORTED_TYPE', 'INVALID_INN', 'INVALID_KPP', 'DUPLICATE_IN_FILE', 'LE_IN_OTHER_GROUP', 'GK_NAME_CONFLICT'];
const result = issueLines(codes.map((code, i) => line(i + 2, code)));
expect(result.map((item) => item.level)).toEqual(Array(6).fill('error'));
expect(result.map((item) => item.code)).toEqual(codes);
});
it('оставляет предупреждения RF_CREATED и UNKNOWN_FLAG с уровнем warning', () => {
const result = issueLines([line(2, 'RF_CREATED'), line(3, 'UNKNOWN_FLAG')]);
expect(result.map((item) => [item.code, item.level])).toEqual([
['RF_CREATED', 'warning'],
['UNKNOWN_FLAG', 'warning'],
]);
});
it('отбрасывает успешные итоги и прочие сопутствующие события, порядок файла сохраняет', () => {
const result = issueLines([
line(2, 'LE_CREATED'),
line(2, 'GK_CREATED'),
line(3, 'UNKNOWN_FLAG'),
line(3, 'LE_EXISTS'),
line(4, 'INVALID_INN'),
line(5, 'GSK_CREATED'),
line(5, 'MEMBER_ADDED'),
line(5, 'LE_UPDATED'),
line(5, 'GK_UPDATED'),
line(5, 'GK_EXISTS'),
line(5, 'GSZ_CREATED'),
]);
expect(result.map((item) => [item.row, item.code])).toEqual([
[3, 'UNKNOWN_FLAG'],
[4, 'INVALID_INN'],
]);
});
});

View File

@ -1,6 +1,18 @@
import type { ImportReportLine } from '../../../types/api'; import type { ImportReportLine } from '../../../types/api';
import { ERROR_CODES } from './consts'; import { ERROR_CODES, WARNING_CODES } from './consts';
export function errorLines(lines: ImportReportLine[]): ImportReportLine[] { export type IssueLevel = 'error' | 'warning';
return lines.filter((line) => ERROR_CODES.has(line.code)); export type IssueLine = ImportReportLine & { level: IssueLevel };
/** Строки отчёта для таблицы «Ошибки и предупреждения»: пропуски и предупреждения в порядке файла, успешные итоги отброшены. */
export function issueLines(lines: ImportReportLine[]): IssueLine[] {
const result: IssueLine[] = [];
for (const line of lines) {
if (ERROR_CODES.has(line.code)) {
result.push({ ...line, level: 'error' });
} else if (WARNING_CODES.has(line.code)) {
result.push({ ...line, level: 'warning' });
}
}
return result;
} }