AURORA-1916: Справочники: импорт ГК и ориганизаций из выгрузки ЕЦП #217
@ -21,14 +21,28 @@ type FormValues = {
|
||||
dry_run: boolean;
|
||||
};
|
||||
|
||||
/** Отчёт последнего запуска; dryRun — был ли это пробный прогон (от него зависят заголовок, текст и кнопки сводки). */
|
||||
type ImportResult = {
|
||||
report: ImportReportOut;
|
||||
dryRun: boolean;
|
||||
};
|
||||
|
||||
const ON_EXISTING_OPTIONS: { value: OnExisting; label: string }[] = [
|
||||
{ value: 'skip', 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 }) => {
|
||||
const [form] = Form.useForm<FormValues>();
|
||||
@ -36,7 +50,7 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
|
||||
|
||||
const [fileList, setFileList] = useState<UploadFile[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [dryRunReport, setDryRunReport] = useState<ImportReportOut | null>(null);
|
||||
const [result, setResult] = useState<ImportResult | null>(null);
|
||||
|
||||
const handleOk = async () => {
|
||||
const file = fileList[0]?.originFileObj;
|
||||
@ -47,13 +61,10 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
|
||||
setLoading(true);
|
||||
try {
|
||||
const report = await importDirectory(file, values.dry_run, values.on_existing);
|
||||
if (values.dry_run) {
|
||||
setDryRunReport(report);
|
||||
return;
|
||||
setResult({ report, dryRun: values.dry_run });
|
||||
if (!values.dry_run) {
|
||||
onImported();
|
||||
}
|
||||
notification.success({ description: 'Импорт завершён' });
|
||||
onImported();
|
||||
onCancel();
|
||||
} catch (e) {
|
||||
notification.error({ description: e instanceof ApiError ? e.message : 'Не удалось выполнить импорт' });
|
||||
} finally {
|
||||
@ -69,7 +80,7 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
|
||||
|
||||
return (
|
||||
<AppModal
|
||||
title={dryRunReport ? 'Сводка импорта' : 'Импорт групп компаний из файла'}
|
||||
title={modalTitle(result)}
|
||||
open={open}
|
||||
onCancel={handleCancel}
|
||||
onOk={handleOk}
|
||||
@ -78,11 +89,13 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
|
||||
cancelText='Отмена'
|
||||
cancelButtonProps={{ disabled: loading }}
|
||||
footer={
|
||||
dryRunReport ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
<Button icon={<ArrowLeftOutlined />} onClick={() => setDryRunReport(null)}>
|
||||
К загрузке файла
|
||||
</Button>
|
||||
result ? (
|
||||
<div style={{ display: 'flex', justifyContent: result.dryRun ? 'space-between' : 'flex-end' }}>
|
||||
{result.dryRun && (
|
||||
<Button icon={<ArrowLeftOutlined />} onClick={() => setResult(null)}>
|
||||
К загрузке файла
|
||||
</Button>
|
||||
)}
|
||||
<Button type='primary' onClick={handleCancel}>
|
||||
Закрыть
|
||||
</Button>
|
||||
@ -92,13 +105,13 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
|
||||
confirmLoading={loading}
|
||||
closable={!loading}
|
||||
destroyOnHidden
|
||||
width={dryRunReport ? 880 : 720}>
|
||||
width={result ? 880 : 720}>
|
||||
<Form
|
||||
form={form}
|
||||
layout='vertical'
|
||||
disabled={loading}
|
||||
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 }}>
|
||||
<Select options={ON_EXISTING_OPTIONS} />
|
||||
</Form.Item>
|
||||
@ -128,7 +141,7 @@ export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onIm
|
||||
</Upload.Dragger>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
{dryRunReport && <ImportSummary report={dryRunReport} fileName={fileList[0]?.name ?? ''} />}
|
||||
{result && <ImportSummary report={result.report} dryRun={result.dryRun} fileName={fileList[0]?.name ?? ''} />}
|
||||
</AppModal>
|
||||
);
|
||||
};
|
||||
|
||||
@ -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 { CounterCard } from './CounterCard';
|
||||
import { errorLines } from './utils';
|
||||
import { issueLines } from './utils';
|
||||
|
||||
type Props = {
|
||||
report: ImportReportOut;
|
||||
fileName: string;
|
||||
/** true — пробный прогон (ничего не записано), false — отчёт о выполненной записи. */
|
||||
dryRun: boolean;
|
||||
};
|
||||
|
||||
/** Сводка пробного прогона: счётчики по трём карточкам и строки, пропущенные из-за ошибок. */
|
||||
export function ImportSummary({ report, fileName }: Props) {
|
||||
const DRY_RUN_HINT = 'Предварительная проверка: в справочник ничего не записано. Показано, какие изменения будут внесены.';
|
||||
const WRITTEN_HINT = 'Изменения записаны в справочник.';
|
||||
|
||||
/** Сводка импорта: счётчики по трём карточкам и строки с ошибками (пропущены) и предупреждениями (импортированы). */
|
||||
export function ImportSummary({ report, fileName, dryRun }: Props) {
|
||||
return (
|
||||
<>
|
||||
<Typography.Text type='secondary' style={{ display: 'block', marginBottom: 12 }}>
|
||||
{fileName} · Предварительная проверка. Показано, какие изменения будут внесены.
|
||||
{`${fileName} · ${dryRun ? DRY_RUN_HINT : WRITTEN_HINT}`}
|
||||
</Typography.Text>
|
||||
<Row gutter={12}>
|
||||
<Col span={8}>
|
||||
@ -32,7 +37,8 @@ export function ImportSummary({ report, fileName }: Props) {
|
||||
items={[
|
||||
{ label: 'ГК создано', value: report.groups_created },
|
||||
{ label: 'ГК обновлено', value: report.groups_updated },
|
||||
{ label: 'ГК пропущено', value: report.groups_skipped },
|
||||
// groups_skipped — GK_EXISTS: ГК уже есть и не менялась, это не ошибка
|
||||
{ label: 'ГК без изменений', value: report.groups_skipped },
|
||||
]}
|
||||
/>
|
||||
</Col>
|
||||
@ -42,25 +48,35 @@ export function ImportSummary({ report, fileName }: Props) {
|
||||
items={[
|
||||
{ label: 'ЮЛ создано', value: report.entities_created },
|
||||
{ label: 'ЮЛ обновлено', value: report.entities_updated },
|
||||
{ label: 'ЮЛ пропущено', value: report.entities_skipped },
|
||||
// entities_skipped — LE_EXISTS: ЮЛ уже есть и не менялось, это не ошибка
|
||||
{ label: 'ЮЛ без изменений', value: report.entities_skipped },
|
||||
{ label: 'Включений в ГСК/ГСЗ', value: report.memberships_created },
|
||||
]}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
<Typography.Title level={5} style={{ marginTop: 16 }}>
|
||||
Строки с ошибками
|
||||
Ошибки и предупреждения
|
||||
</Typography.Title>
|
||||
<Table
|
||||
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 }}
|
||||
locale={{ emptyText: 'Ошибок не найдено' }}
|
||||
locale={{ emptyText: 'Ошибок и предупреждений нет' }}
|
||||
columns={[
|
||||
{ title: 'Строка', dataIndex: 'row', width: 80 },
|
||||
{ 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}
|
||||
</>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
/** Коды строк, пропущенных импортом из-за ошибки (§13.2); остальные коды — успешные итоги и сопутствующие события. */
|
||||
/** Коды строк, пропущенных импортом из-за ошибки (§13.2): итоговые коды пропуска, счётчик `errors`. */
|
||||
export const ERROR_CODES = new Set([
|
||||
'UNSUPPORTED_TYPE',
|
||||
'INVALID_INN',
|
||||
@ -7,3 +7,9 @@ export const ERROR_CODES = new Set([
|
||||
'LE_IN_OTHER_GROUP',
|
||||
'GK_NAME_CONFLICT',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Сопутствующие события-предупреждения (§13.2): строка импортирована, но пользователю стоит проверить —
|
||||
* создан новый филиал (возможна опечатка в «Базовый РФ ГК») или флаг ГСК/ГСЗ не распознан и принят как «не входит».
|
||||
*/
|
||||
export const WARNING_CODES = new Set(['RF_CREATED', 'UNKNOWN_FLAG']);
|
||||
|
||||
@ -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'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@ -1,6 +1,18 @@
|
||||
import type { ImportReportLine } from '../../../types/api';
|
||||
import { ERROR_CODES } from './consts';
|
||||
import { ERROR_CODES, WARNING_CODES } from './consts';
|
||||
|
||||
export function errorLines(lines: ImportReportLine[]): ImportReportLine[] {
|
||||
return lines.filter((line) => ERROR_CODES.has(line.code));
|
||||
export type IssueLevel = 'error' | 'warning';
|
||||
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;
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user