AURORA-1916: Справочники: импорт ГК и ориганизаций из выгрузки ЕЦП #217

Merged
aep merged 4 commits from feat/1916-import-directory into main 2026-11-06 16:50:18 +03:00
11 changed files with 404 additions and 4 deletions

View File

@ -1,3 +1,4 @@
// Коды прав, от которых зависит интерфейс (как в `GET /me` → `permissions`). Доступ на самом деле решает сервер:
// проверки на клиенте только прячут то, что пользователю всё равно не разрешат.
export const USERS_ADMIN = 'USERS_ADMIN';
export const DIRECTORY_ADMIN = 'DIRECTORY_ADMIN';

View File

@ -1,7 +1,9 @@
import { PlusOutlined } from '@ant-design/icons';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Empty, Space } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { ApiError } from '../api/client';
import { useCurrentUser } from '../auth/MeContext';
import { DIRECTORY_ADMIN } from '../auth/permissions';
import PageTitle from '../components/PageTitle';
import { createCatalogueJur } from '../services/api/directories/catalogue_jur';
import {
@ -30,6 +32,7 @@ import {
} from '../widgets/CatalogueCompanyGroup/CatalogueCompanyGroupTabs/CatalogueCompanyGroupTabs';
import { CompanyGroupForm } from '../widgets/CatalogueCompanyGroup/CompanyGroupForm/CompanyGroupForm';
import { CompanyGroupsList } from '../widgets/CatalogueCompanyGroup/CompanyGroupsList/CompanyGroupsList';
import { ImportCompanyGroupsModal } from '../widgets/CatalogueCompanyGroup/ImportCompanyGroupsModal/ImportCompanyGroupsModal';
import { CatalogueJurForm } from '../widgets/CatalogueJur/CatalogueJurForm/CatalogueJurForm';
import { CatalogueJurTable } from '../widgets/CatalogueJur/CatalogueJurTable/CatalogueJurTable';
import { CreateEntityPickerModal } from '../widgets/CreateEntityPickerModal/CreateEntityPickerModal';
@ -39,10 +42,12 @@ import { RelatedGroupTable } from '../widgets/RelatedGroup/RelatedGroupTable/Rel
export function CatalogueGroup() {
const dispatch = useAppDispatch();
const notification = useNotificationApi();
const me = useCurrentUser();
const isGettingArchive = useAppSelector((state) => state.catalogue_jur.isGettingArchive);
const [entityCreateModalOpen, setEntityCreateModalOpen] = useState(false);
const [importModalOpen, setImportModalOpen] = useState(false);
const [kindForm, setKindForm] = useState<CreateEntityKind | null>(null);
const [relatedGroupLoading, setRelatedGroupLoading] = useState(false);
const [companyGroupEditFormOpen, setCompanyGroupEditFormOpen] = useState(false);
@ -93,6 +98,18 @@ export function CatalogueGroup() {
}
}
function importedHandler() {
dispatch(getCompanyGroupsThunk());
dispatch(
getCatalogueJurThunk({
closed: isGettingArchive,
outside_group: false,
company_group_id: activeCompanyGroup?.id,
}),
);
getRelatedGroupsHandler();
}
async function archiveCompanyGroupHandler() {
if (!activeCompanyGroup) {
return;
@ -168,9 +185,16 @@ export function CatalogueGroup() {
}}>
<Space style={{ justifyContent: 'space-between' }}>
<PageTitle header='Группы компаний и организаций' location='Справочники' />
<Button type='primary' icon={<PlusOutlined />} onClick={() => setEntityCreateModalOpen(true)}>
Создать ГК/ЮЛ
</Button>
<Space>
{me.permissions.includes(DIRECTORY_ADMIN) && (
<Button icon={<UploadOutlined />} onClick={() => setImportModalOpen(true)}>
Импорт из файла
</Button>
)}
<Button type='primary' icon={<PlusOutlined />} onClick={() => setEntityCreateModalOpen(true)}>
Создать ГК/ЮЛ
</Button>
</Space>
</Space>
<div
style={{
@ -231,6 +255,9 @@ export function CatalogueGroup() {
)}
</div>
</div>
{importModalOpen && (
<ImportCompanyGroupsModal open={importModalOpen} onCancel={() => setImportModalOpen(false)} onImported={importedHandler} />
)}
<CreateEntityPickerModal
open={entityCreateModalOpen}
onCancel={() => {

View File

@ -0,0 +1,10 @@
import { apiFetch } from '../../../api/client';
import type { ImportReportOut, OnExisting } from '../../../types/api';
export function importDirectory(file: File, dryRun: boolean, onExisting: OnExisting): Promise<ImportReportOut> {
const form = new FormData();
form.append('file', file);
form.append('dry_run', String(dryRun));
form.append('on_existing', onExisting);
return apiFetch<ImportReportOut>('/directories/import', { method: 'POST', body: form });
}

View File

@ -30,6 +30,27 @@ export interface UploadResult {
rejected: RejectedOut[];
}
export type OnExisting = 'skip' | 'update';
export interface ImportReportLine {
row: number;
inn: string;
code: string;
message: string;
}
export interface ImportReportOut {
rows: number;
groups_created: number;
groups_updated: number;
groups_skipped: number;
entities_created: number;
entities_updated: number;
entities_skipped: number;
memberships_created: number;
offices_created: number;
errors: number;
lines: ImportReportLine[];
}
/** Статусы строки формы (v5.19): ok — строка бланка; unreadable — код не распознан; missing — кода нет; detail — расшифровка. */
export type LineStatus = 'ok' | 'unreadable' | 'missing' | 'detail';
export type Severity = 'error' | 'info';

View File

@ -0,0 +1,16 @@
import { Typography } from 'antd';
type Props = {
label: string;
value: number;
};
/** Строка карточки: подпись серым, число справа — чёрным, если не 0. */
export function Counter({ label, value }: Props) {
return (
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
<Typography.Text type='secondary'>{label}</Typography.Text>
<Typography.Text type={value === 0 ? 'secondary' : undefined}>{value}</Typography.Text>
</div>
);
}

View File

@ -0,0 +1,19 @@
import { Card } from 'antd';
import { Counter } from './Counter';
type Props = {
title: string;
items: { label: string; value: number }[];
};
export function CounterCard({ title, items }: Props) {
return (
<Card size='small' title={title} style={{ height: '100%' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{items.map((item) => (
<Counter key={item.label} label={item.label} value={item.value} />
))}
</div>
</Card>
);
}

View File

@ -0,0 +1,147 @@
import { ArrowLeftOutlined, FileAddOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Select, Upload } from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import type React from 'react';
import { useState } from 'react';
import { ApiError } from '../../../api/client';
import { AppModal } from '../../../components/AppModal/AppModal';
import { importDirectory } from '../../../services/api/directories/directory_import';
import type { ImportReportOut, OnExisting } from '../../../types/api';
import { useNotificationApi } from '../../../utils/useNotification';
import { ImportSummary } from './ImportSummary';
type Props = {
open: boolean;
onCancel: () => void;
onImported: () => void;
};
type FormValues = {
on_existing: OnExisting;
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. Ответ заменяет форму сводкой (отчёт §13.3). После пробного прогона из сводки — закрытие окна
* или возврат к форме («К загрузке файла», файл и значения формы сохраняются); после записи — только закрытие,
* список справочника обновляется сразу.
*/
export const ImportCompanyGroupsModal: React.FC<Props> = ({ open, onCancel, onImported }) => {
const [form] = Form.useForm<FormValues>();
const notification = useNotificationApi();
const [fileList, setFileList] = useState<UploadFile[]>([]);
const [loading, setLoading] = useState(false);
const [result, setResult] = useState<ImportResult | null>(null);
const handleOk = async () => {
const file = fileList[0]?.originFileObj;
if (!file) {
return;
}
const values = form.getFieldsValue();
setLoading(true);
try {
const report = await importDirectory(file, values.dry_run, values.on_existing);
setResult({ report, dryRun: values.dry_run });
if (!values.dry_run) {
onImported();
}
} catch (e) {
notification.error({ description: e instanceof ApiError ? e.message : 'Не удалось выполнить импорт' });
} finally {
setLoading(false);
}
};
const handleCancel = () => {
if (!loading) {
onCancel();
}
};
return (
<AppModal
title={modalTitle(result)}
open={open}
onCancel={handleCancel}
onOk={handleOk}
okText='Загрузить'
okButtonProps={{ disabled: fileList.length === 0 }}
cancelText='Отмена'
cancelButtonProps={{ disabled: loading }}
footer={
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>
</div>
) : undefined
}
confirmLoading={loading}
closable={!loading}
destroyOnHidden
width={result ? 880 : 720}>
<Form
form={form}
layout='vertical'
disabled={loading}
initialValues={{ on_existing: 'skip', dry_run: true }}
style={{ display: result ? 'none' : undefined }}>
<Form.Item name='on_existing' label='При дублировании' style={{ marginBottom: 12 }}>
<Select options={ON_EXISTING_OPTIONS} />
</Form.Item>
<Form.Item name='dry_run' valuePropName='checked' style={{ marginBottom: 12 }}>
<Checkbox>Пробный прогон</Checkbox>
</Form.Item>
<Form.Item label='Файл' required style={{ marginBottom: 0 }}>
<Upload.Dragger
accept='.xlsx,.csv'
maxCount={1}
fileList={fileList}
beforeUpload={(file) => {
setFileList([{ uid: file.uid, name: file.name, originFileObj: file }]);
return false;
}}
onRemove={() => {
setFileList([]);
}}>
<p className='ant-upload-drag-icon'>
<FileAddOutlined />
</p>
<p className='ant-upload-text'>Перетащите файл сюда</p>
<Button>Выбрать файл</Button>
<p className='ant-upload-hint' style={{ marginTop: 12 }}>
Формат: .xlsx, .csv
</p>
</Upload.Dragger>
</Form.Item>
</Form>
{result && <ImportSummary report={result.report} dryRun={result.dryRun} fileName={fileList[0]?.name ?? ''} />}
</AppModal>
);
};

View File

@ -0,0 +1,84 @@
import { Col, Row, Table, Tag, Typography } from 'antd';
import type { ImportReportOut } from '../../../types/api';
import { CounterCard } from './CounterCard';
import { issueLines } from './utils';
type Props = {
report: ImportReportOut;
fileName: string;
/** true — пробный прогон (ничего не записано), false — отчёт о выполненной записи. */
dryRun: boolean;
};
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} · ${dryRun ? DRY_RUN_HINT : WRITTEN_HINT}`}
</Typography.Text>
<Row gutter={12}>
<Col span={8}>
<CounterCard
title='Системные показатели'
items={[
{ label: 'Строк в файле', value: report.rows },
{ label: 'Пропущено строк с ошибками', value: report.errors },
{ label: 'РФ создано', value: report.offices_created },
]}
/>
</Col>
<Col span={8}>
<CounterCard
title='ГК'
items={[
{ label: 'ГК создано', value: report.groups_created },
{ label: 'ГК обновлено', value: report.groups_updated },
// groups_skipped — GK_EXISTS: ГК уже есть и не менялась, это не ошибка
{ label: 'ГК без изменений', value: report.groups_skipped },
]}
/>
</Col>
<Col span={8}>
<CounterCard
title='Организации'
items={[
{ label: 'ЮЛ создано', value: report.entities_created },
{ label: 'ЮЛ обновлено', value: report.entities_updated },
// 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={issueLines(report.lines).map((line, key) => ({ ...line, key }))}
pagination={{ pageSize: 5, hideOnSinglePage: true, showSizeChanger: false }}
locale={{ emptyText: 'Ошибок и предупреждений нет' }}
columns={[
{ title: 'Строка', dataIndex: 'row', width: 80 },
{ title: 'ИНН', dataIndex: 'inn', width: 140 },
{
title: 'Результат',
dataIndex: 'message',
render: (message: string, line) => (
<>
{line.level === 'error' ? <Tag color='error'>ошибка</Tag> : <Tag color='warning'>предупреждение</Tag>}
{message}
</>
),
},
]}
/>
</>
);
}

View File

@ -0,0 +1,15 @@
/** Коды строк, пропущенных импортом из-за ошибки (§13.2): итоговые коды пропуска, счётчик `errors`. */
export const ERROR_CODES = new Set([
'UNSUPPORTED_TYPE',
'INVALID_INN',
'INVALID_KPP',
'DUPLICATE_IN_FILE',
'LE_IN_OTHER_GROUP',
'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

@ -0,0 +1,18 @@
import type { ImportReportLine } from '../../../types/api';
import { ERROR_CODES, WARNING_CODES } from './consts';
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;
}