Compare commits
5 Commits
codex/heal
...
feature/mo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e712494c3f | ||
| bad64fe001 | |||
|
|
a00ecec936 | ||
| 448b2c2f7c | |||
|
|
3d10e806eb |
15
docs/all-years-source-exports.md
Normal file
15
docs/all-years-source-exports.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Выгрузка за все годы
|
||||
|
||||
Годовая задача `organizations.tasks.refresh_source_record_export_artifacts` сохраняет прежнее поведение.
|
||||
|
||||
Новая задача `organizations.tasks.refresh_all_years_source_record_export_artifacts` собирает все доступные записи каждого поддерживаемого источника без ограничения по году, включая все финансовые строки. Для источников с заменяемыми snapshot выгружается текущее опубликованное состояние: удалённые прежние snapshot не восстанавливаются.
|
||||
|
||||
Результат размещается в `SOURCE_RECORD_EXPORT_DIRECTORY/all-years`. У него отдельные `current.json`, `generations` и очистка старых поколений. Публикация атомарна; незавершённая сборка не заменяет опубликованные файлы. Общий lock с годовой задачей ограничивает одновременную нагрузку. Manifest содержит `export_scope: all_years` и `export_year: null`; годовой manifest — `export_scope: current_year` и числовой год. Старые годовые manifest без `export_scope` продолжают читаться.
|
||||
|
||||
Ручной запуск:
|
||||
|
||||
```sh
|
||||
python src/manage.py build_source_record_exports --all-years
|
||||
```
|
||||
|
||||
Периодический запуск настраивается отдельной записью django-celery-beat либо системным таймером на контуре без Beat. Задачу следует ставить после годовой сборки. Имена файлов, группировка JSON по ОКПО и форматы CSV/XLSX/JSON сохраняются. API скачивания продолжает отдавать годовой пакет; доступ к полному пакету предоставляется отдельно.
|
||||
15
docs/dashboard-performance.md
Normal file
15
docs/dashboard-performance.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# Повторные расчеты dashboard
|
||||
|
||||
`/api/v1/parsers/dashboard/` использует один расчет соответствий организаций
|
||||
источникам для покрытия и аналитики обогащения. Последние логи также читаются
|
||||
один раз на запрос. Между запросами результаты не кешируются.
|
||||
|
||||
На одном снимке данных внутреннего main число SQL-запросов уменьшилось с 51
|
||||
до 37, время обработчика — с 1,76 до 1,14 секунды. Полные JSON-ответы до и после
|
||||
совпали. Сравнение выполнено в отдельном процессе, в транзакции REPEATABLE READ,
|
||||
READ ONLY, с фиксированным временем. Сеть и аутентификация не измерялись.
|
||||
|
||||
В этой версии main нет дорогого поиска последних фоновых задач из dev.
|
||||
Выборка карточек источников этим патчем не меняется. Миграций, новых зависимостей
|
||||
и настроек нет. Регрессия в `test_views.py` проверяет отсутствие повторных
|
||||
обходов записей источников вместе с прежними значениями аналитики.
|
||||
@@ -53,9 +53,22 @@ XLSX или JSON заново. Он упаковывает файлы после
|
||||
больше из-за разбиения крупных XLSX. Если финансовые показатели выбраны вместе
|
||||
с другим форматом, в ZIP для них всё равно включается JSON.
|
||||
|
||||
Все форматы начинают строку организации с полей `Наименование`, `ИНН`, `ОГРН`,
|
||||
CSV и XLSX начинают строку организации с полей `Наименование`, `ИНН`, `ОГРН`,
|
||||
`КПП`, `ОКПО`, после которых следуют поля исходной записи и развёрнутого
|
||||
`payload`. Все записи текущего года включаются в публичные файлы, а техническое
|
||||
`payload`. JSON каждого источника — массив организаций с `okpo` и массивом
|
||||
записей под ключом группы API. Например, `bankruptcy-procedures.json`:
|
||||
|
||||
```json
|
||||
[{"okpo":"12345678","bankruptcy":[{"uid":"...","source_group":"bankruptcy","payload.case_number":"..."}]}]
|
||||
```
|
||||
|
||||
Записи одной организации собираются вместе независимо от порядка чтения из БД.
|
||||
`ОКПО` переносится из записи в `okpo` оболочки; остальные поля записи остаются
|
||||
в прежнем виде. При отсутствии ОКПО экспортируется `null`, а для группировки
|
||||
используются ИНН, ОГРН и наименование, чтобы не смешивать разные организации.
|
||||
Вложенные финансовые строки `financial_lines` сохраняются внутри финансовой
|
||||
записи. При выборе нескольких источников ZIP содержит отдельный JSON-файл для
|
||||
каждого. Все записи текущего года включаются в публичные файлы, а техническое
|
||||
наименование внешнего поставщика нейтрализуется. Исходные значения в БД
|
||||
сохраняются для работы интеграции и дедупликации.
|
||||
|
||||
@@ -71,8 +84,9 @@ Celery Beat запускает
|
||||
1. читает каждую группу из БД один раз без глобальной сортировки миллионов строк;
|
||||
выборка текущего года использует функциональный индекс по году строковой
|
||||
`record_date`, а записи без предметной даты — индекс `created_at`;
|
||||
2. пишет compact JSON-массив на диск и использует его как готовый JSON без второй копии;
|
||||
3. потоково создаёт CSV и XLSX без накопления всех строк в памяти;
|
||||
2. пишет плоский spool на диск, затем группирует JSON по ОКПО через временный
|
||||
дисковый индекс SQLite без накопления всех строк в памяти;
|
||||
3. потоково создаёт CSV и XLSX из того же spool;
|
||||
4. разбивает XLSX по умолчанию по 100 000 строк на отдельные файлы, ограничивая временный XML и не превышая лимит Excel;
|
||||
5. записывает размеры файлов, номера частей и календарный `export_year` в manifest;
|
||||
6. атомарно переключает `current.json` только после готовности всей матрицы;
|
||||
@@ -84,9 +98,11 @@ Celery Beat запускает
|
||||
### Расчёт диска
|
||||
|
||||
Атомарная публикация требует одновременно хранить уже опубликованные поколения
|
||||
и одно новое поколение в staging. Минимальный запас под артефакты рассчитывается
|
||||
как `(SOURCE_RECORD_EXPORT_GENERATIONS_TO_KEEP + 1) * размер поколения`, плюс
|
||||
рабочий запас файловой системы. Исторический снимок dev от 2026-08-03 до
|
||||
и одно новое поколение в staging. Во время группировки JSON дополнительно
|
||||
создаётся временная база SQLite размером порядка исходного spool. Минимальный
|
||||
запас под артефакты рассчитывается как
|
||||
`(SOURCE_RECORD_EXPORT_GENERATIONS_TO_KEEP + 1) * размер поколения`, плюс
|
||||
spool, временная база SQLite и рабочий запас файловой системы. Исторический снимок dev от 2026-08-03 до
|
||||
ограничения по году занимал 16,55 ГБ (54 физических файла); актуальный размер
|
||||
годового поколения нужно брать из `total_size` результата команды сборки.
|
||||
Временная копия целого ZIP при скачивании не создаётся.
|
||||
@@ -104,7 +120,10 @@ Celery Beat запускает
|
||||
Celery worker. В Docker Compose используется `./media:/app/media`.
|
||||
|
||||
После первого развёртывания готовое поколение можно создать сразу, не ожидая
|
||||
ночного расписания:
|
||||
ночного расписания. После обновления формата JSON поколения с manifest версии 2
|
||||
не раздаются: до первой успешной сборки версии 3 API возвращает
|
||||
`503 source_export_not_ready`. Запустите команду ниже после развёртывания,
|
||||
чтобы восстановить доступность выгрузок сразу:
|
||||
|
||||
```bash
|
||||
PYTHONPATH=src uv run python src/manage.py build_source_record_exports
|
||||
|
||||
@@ -1986,8 +1986,9 @@ def _registry_source_matrix_rows(
|
||||
return matrix_rows
|
||||
|
||||
|
||||
def _registry_data_coverage() -> dict:
|
||||
registry_organization_ids, by_inn, by_ogrn = _active_registry_organization_indexes()
|
||||
def _registry_data_coverage(
|
||||
registry_organization_ids: set[str], source_matches: dict[str, set[str]]
|
||||
) -> dict:
|
||||
total_organizations = len(registry_organization_ids)
|
||||
descriptor_titles: dict[str, str] = {}
|
||||
for descriptor in PARSER_SOURCES.values():
|
||||
@@ -1998,9 +1999,7 @@ def _registry_data_coverage() -> dict:
|
||||
for source, _label in ParserLoadLog.Source.choices:
|
||||
if source in REGISTRY_COVERAGE_EXCLUDED_SOURCES:
|
||||
continue
|
||||
organizations_count = len(
|
||||
_matched_source_record_registry_organization_ids(source, by_inn, by_ogrn)
|
||||
)
|
||||
organizations_count = len(source_matches.get(source, set()))
|
||||
coverage_percent = (
|
||||
round(organizations_count / total_organizations * 100, 1)
|
||||
if total_organizations
|
||||
@@ -2021,10 +2020,14 @@ def _registry_data_coverage() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _registry_enrichment_analytics(jobs, schedules: list[dict]) -> dict:
|
||||
registry_organization_ids, by_inn, by_ogrn = _active_registry_organization_indexes()
|
||||
def _registry_enrichment_analytics(
|
||||
jobs,
|
||||
schedules: list[dict],
|
||||
registry_organization_ids: set[str],
|
||||
source_matches: dict[str, set[str]],
|
||||
latest_loads: list[ParserLoadLog],
|
||||
) -> dict:
|
||||
total_organizations = len(registry_organization_ids)
|
||||
source_matches = _source_registry_matches(by_inn, by_ogrn)
|
||||
descriptor_titles: dict[str, str] = {}
|
||||
for descriptor in PARSER_SOURCES.values():
|
||||
descriptor_titles.setdefault(descriptor.source, descriptor.title)
|
||||
@@ -2113,7 +2116,6 @@ def _registry_enrichment_analytics(jobs, schedules: list[dict]) -> dict:
|
||||
enrichment_sources=enrichment_sources,
|
||||
)
|
||||
|
||||
latest_loads = list(ParserLoadLog.objects.all().order_by("-created_at")[:30])
|
||||
recent_success = sum(
|
||||
1 for load in latest_loads if load.status == ParserLoadLog.Status.SUCCESS
|
||||
)
|
||||
@@ -2948,6 +2950,9 @@ class ParserDashboardDataView(APIView):
|
||||
_periodic_task_to_dict(task)
|
||||
for task in _parser_periodic_tasks_for_user(request.user)
|
||||
]
|
||||
load_logs = list(ParserLoadLog.objects.all().order_by("-created_at")[:30])
|
||||
registry_ids, by_inn, by_ogrn = _active_registry_organization_indexes()
|
||||
source_matches = _source_registry_matches(by_inn, by_ogrn)
|
||||
return api_response(
|
||||
{
|
||||
"sources": sources,
|
||||
@@ -2960,13 +2965,18 @@ class ParserDashboardDataView(APIView):
|
||||
"schedules": ParserScheduleSerializer(schedules, many=True).data,
|
||||
"jobs": BackgroundJobListSerializer(jobs, many=True).data,
|
||||
"source_counts": source_counts,
|
||||
"registry_data_coverage": _registry_data_coverage(),
|
||||
"registry_data_coverage": _registry_data_coverage(
|
||||
registry_ids, source_matches
|
||||
),
|
||||
"registry_enrichment_analytics": _registry_enrichment_analytics(
|
||||
jobs,
|
||||
schedules,
|
||||
registry_ids,
|
||||
source_matches,
|
||||
load_logs,
|
||||
),
|
||||
"load_logs": ParserLoadLogSerializer(
|
||||
ParserLoadLog.objects.all().order_by("-created_at")[:30],
|
||||
load_logs,
|
||||
many=True,
|
||||
).data,
|
||||
}
|
||||
|
||||
@@ -15,8 +15,18 @@ class Command(BaseAppCommand):
|
||||
help = "Формирует готовые CSV/XLSX/JSON выгрузки источников"
|
||||
use_transaction = False
|
||||
|
||||
def add_arguments(self, parser) -> None:
|
||||
super().add_arguments(parser)
|
||||
parser.add_argument(
|
||||
"--all-years",
|
||||
action="store_true",
|
||||
help="Все доступные годы в отдельном каталоге all-years",
|
||||
)
|
||||
|
||||
def execute_command(self, *args, **options) -> str:
|
||||
generation = build_source_record_export_artifacts()
|
||||
generation = build_source_record_export_artifacts(
|
||||
all_years=options["all_years"]
|
||||
)
|
||||
rendered = json.dumps(
|
||||
{
|
||||
"generation_id": generation.generation_id,
|
||||
|
||||
@@ -8,6 +8,7 @@ import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import sqlite3
|
||||
import zipfile
|
||||
from collections.abc import Iterable, Iterator, Sequence
|
||||
from dataclasses import dataclass
|
||||
@@ -38,7 +39,7 @@ EXPORT_FORMAT_XLSX = "xlsx"
|
||||
EXPORT_FORMAT_JSON = "json"
|
||||
EXPORT_FORMATS = (EXPORT_FORMAT_CSV, EXPORT_FORMAT_XLSX, EXPORT_FORMAT_JSON)
|
||||
FINANCIAL_SOURCE_GROUP = SourceGroup.FINANCIAL_INDICATORS.value
|
||||
EXPORT_MANIFEST_VERSION = 2
|
||||
EXPORT_MANIFEST_VERSION = 3
|
||||
CURRENT_EXPORT_MANIFEST_FILE_NAME = "current.json"
|
||||
GENERATION_MANIFEST_FILE_NAME = "manifest.json"
|
||||
GENERATION_DIRECTORY_NAME = "generations"
|
||||
@@ -126,7 +127,7 @@ class SourceRecordExportGeneration:
|
||||
|
||||
generation_id: str
|
||||
generated_at: str
|
||||
export_year: int
|
||||
export_year: int | None
|
||||
artifacts: tuple[SourceRecordExportArtifact, ...]
|
||||
records_count: int
|
||||
|
||||
@@ -196,16 +197,19 @@ def build_source_record_export_artifacts(
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
export_directory: str | Path | None = None,
|
||||
all_years: bool = False,
|
||||
) -> SourceRecordExportGeneration:
|
||||
"""Build all files on disk and atomically publish a new generation."""
|
||||
"""Build annual or all-years files and atomically publish their generation."""
|
||||
|
||||
root_directory = _resolve_export_directory(export_directory)
|
||||
if all_years:
|
||||
root_directory /= "all-years"
|
||||
generations_directory = root_directory / GENERATION_DIRECTORY_NAME
|
||||
root_directory.mkdir(parents=True, exist_ok=True)
|
||||
generations_directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
generated_at_datetime = _normalize_generation_datetime(now or timezone.now())
|
||||
export_year = _export_year(generated_at_datetime)
|
||||
export_year = None if all_years else _export_year(generated_at_datetime)
|
||||
generation_id = (
|
||||
f"{generated_at_datetime.strftime('%Y%m%dT%H%M%SZ')}-{uuid4().hex[:8]}"
|
||||
)
|
||||
@@ -233,6 +237,7 @@ def build_source_record_export_artifacts(
|
||||
file_format=file_format,
|
||||
)
|
||||
artifact_paths = _render_source_group_artifact(
|
||||
source_group=source_group,
|
||||
row_spool_path=row_spool_path,
|
||||
output_path=staging_directory / file_name,
|
||||
headers=headers,
|
||||
@@ -543,7 +548,7 @@ def _build_source_group_file_name(*, source_group: str, file_format: str) -> str
|
||||
def _source_group_queryset(
|
||||
source_group: str,
|
||||
*,
|
||||
export_year: int,
|
||||
export_year: int | None,
|
||||
) -> QuerySet[OrganizationSourceRecord]:
|
||||
queryset = (
|
||||
OrganizationSourceRecord.objects.filter(extension__source_group=source_group)
|
||||
@@ -553,6 +558,8 @@ def _source_group_queryset(
|
||||
# source groups with millions of rows.
|
||||
.order_by()
|
||||
)
|
||||
if export_year is None:
|
||||
return queryset
|
||||
if source_group == FINANCIAL_SOURCE_GROUP:
|
||||
return queryset.filter(financial_lines__year=export_year).distinct()
|
||||
|
||||
@@ -579,7 +586,7 @@ def _iter_source_records(
|
||||
*,
|
||||
source_group: str,
|
||||
include_financial_lines: bool,
|
||||
export_year: int,
|
||||
export_year: int | None,
|
||||
) -> Iterator[OrganizationSourceRecord]:
|
||||
iterator = _source_group_queryset(
|
||||
source_group,
|
||||
@@ -595,7 +602,7 @@ def _iter_source_records(
|
||||
Prefetch(
|
||||
"financial_lines",
|
||||
queryset=OrganizationSourceFinancialLine.objects.filter(
|
||||
year=export_year
|
||||
**({"year": export_year} if export_year is not None else {})
|
||||
).order_by(),
|
||||
),
|
||||
)
|
||||
@@ -606,7 +613,7 @@ def _spool_source_group_rows(
|
||||
*,
|
||||
source_group: str,
|
||||
output_path: Path,
|
||||
export_year: int,
|
||||
export_year: int | None,
|
||||
) -> tuple[list[str], int]:
|
||||
include_financial_lines = source_group == FINANCIAL_SOURCE_GROUP
|
||||
payload_headers: set[str] = set()
|
||||
@@ -645,6 +652,7 @@ def _spool_source_group_rows(
|
||||
|
||||
def _render_source_group_artifact(
|
||||
*,
|
||||
source_group: str,
|
||||
row_spool_path: Path,
|
||||
output_path: Path,
|
||||
headers: Sequence[str],
|
||||
@@ -665,7 +673,11 @@ def _render_source_group_artifact(
|
||||
headers=headers,
|
||||
records_count=records_count,
|
||||
)
|
||||
_render_json_file(row_spool_path=row_spool_path, output_path=output_path)
|
||||
_render_json_file(
|
||||
source_group=source_group,
|
||||
row_spool_path=row_spool_path,
|
||||
output_path=output_path,
|
||||
)
|
||||
return (output_path,)
|
||||
|
||||
|
||||
@@ -767,10 +779,75 @@ def _build_xlsx_part_path(
|
||||
|
||||
def _render_json_file(
|
||||
*,
|
||||
source_group: str,
|
||||
row_spool_path: Path,
|
||||
output_path: Path,
|
||||
) -> None:
|
||||
os.link(row_spool_path, output_path)
|
||||
grouping_path = output_path.with_name(f".{output_path.name}.grouping.sqlite3")
|
||||
grouping = sqlite3.connect(grouping_path)
|
||||
try:
|
||||
# The published spool can contain millions of unsorted records. Sort on
|
||||
# local disk instead of sorting the source queryset or loading it in RAM.
|
||||
grouping.execute("PRAGMA journal_mode=OFF")
|
||||
grouping.execute(
|
||||
"CREATE TABLE rows (group_key TEXT, position INTEGER, okpo TEXT, data TEXT)"
|
||||
)
|
||||
batch: list[tuple[str, int, str | None, str]] = []
|
||||
for position, row in enumerate(_iter_spooled_rows(row_spool_path)):
|
||||
raw_okpo = row.pop("ОКПО", None)
|
||||
okpo = str(raw_okpo) if raw_okpo else None
|
||||
fallback = [row.get("ИНН"), row.get("ОГРН"), row.get("Наименование")]
|
||||
if not any(fallback):
|
||||
fallback.append(row.get("uid"))
|
||||
group_key = json.dumps(
|
||||
[okpo] if okpo else [None, *fallback],
|
||||
ensure_ascii=False,
|
||||
)
|
||||
batch.append(
|
||||
(
|
||||
group_key,
|
||||
position,
|
||||
okpo,
|
||||
json.dumps(row, ensure_ascii=False, separators=(",", ":")),
|
||||
)
|
||||
)
|
||||
if len(batch) >= SOURCE_RECORD_EXPORT_ITERATOR_CHUNK_SIZE:
|
||||
grouping.executemany("INSERT INTO rows VALUES (?, ?, ?, ?)", batch)
|
||||
batch.clear()
|
||||
if batch:
|
||||
grouping.executemany("INSERT INTO rows VALUES (?, ?, ?, ?)", batch)
|
||||
grouping.commit()
|
||||
grouping.execute("CREATE INDEX rows_by_group ON rows (group_key, position)")
|
||||
|
||||
with output_path.open("w", encoding="utf-8") as output:
|
||||
output.write("[")
|
||||
current_group: str | None = None
|
||||
first_record = True
|
||||
for group_key, okpo, data in grouping.execute(
|
||||
"SELECT group_key, okpo, data FROM rows ORDER BY group_key, position"
|
||||
):
|
||||
if group_key != current_group:
|
||||
if current_group is not None:
|
||||
output.write("]},")
|
||||
output.write(
|
||||
'{"okpo":'
|
||||
+ json.dumps(okpo, ensure_ascii=False)
|
||||
+ ","
|
||||
+ json.dumps(source_group)
|
||||
+ ":["
|
||||
)
|
||||
current_group = group_key
|
||||
first_record = True
|
||||
if not first_record:
|
||||
output.write(",")
|
||||
output.write(data)
|
||||
first_record = False
|
||||
if current_group is not None:
|
||||
output.write("]}")
|
||||
output.write("]")
|
||||
finally:
|
||||
grouping.close()
|
||||
grouping_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _build_record_row(
|
||||
@@ -881,6 +958,9 @@ def _generation_manifest_payload(
|
||||
"generation_id": generation.generation_id,
|
||||
"generated_at": generation.generated_at,
|
||||
"export_year": generation.export_year,
|
||||
"export_scope": "all_years"
|
||||
if generation.export_year is None
|
||||
else "current_year",
|
||||
"records_count": generation.records_count,
|
||||
"artifacts_count": generation.artifacts_count,
|
||||
"files_count": generation.files_count,
|
||||
@@ -901,6 +981,19 @@ def _generation_manifest_payload(
|
||||
}
|
||||
|
||||
|
||||
def _manifest_export_year(payload: dict[str, Any]) -> int | None:
|
||||
raw_year = payload["export_year"]
|
||||
scope = payload.get("export_scope", "current_year")
|
||||
if scope == "all_years" and raw_year is None:
|
||||
return None
|
||||
if scope != "current_year" or raw_year is None or isinstance(raw_year, bool):
|
||||
raise ValueError("Source-record export scope is invalid.")
|
||||
year = int(raw_year)
|
||||
if not 1 <= year <= 9999:
|
||||
raise ValueError("Source-record export year is invalid.")
|
||||
return year
|
||||
|
||||
|
||||
def _generation_from_manifest(
|
||||
payload: Any,
|
||||
*,
|
||||
@@ -912,9 +1005,7 @@ def _generation_from_manifest(
|
||||
generation_id = str(payload["generation_id"])
|
||||
generated_at = str(payload["generated_at"])
|
||||
datetime.fromisoformat(generated_at)
|
||||
export_year = int(payload["export_year"])
|
||||
if not 1 <= export_year <= 9999:
|
||||
raise ValueError("Source-record export year is invalid.")
|
||||
export_year = _manifest_export_year(payload)
|
||||
records_count = int(payload["records_count"])
|
||||
artifact_payloads = payload["artifacts"]
|
||||
if not isinstance(artifact_payloads, list):
|
||||
|
||||
@@ -20,6 +20,16 @@ logger = logging.getLogger(__name__)
|
||||
@shared_task(bind=True, base=CorePeriodicTask)
|
||||
def refresh_source_record_export_artifacts(self) -> dict: # noqa: ARG001
|
||||
"""Build and atomically publish the nightly source-record export matrix."""
|
||||
return _refresh_source_record_export_artifacts(self, all_years=False)
|
||||
|
||||
|
||||
@shared_task(bind=True, base=CorePeriodicTask)
|
||||
def refresh_all_years_source_record_export_artifacts(self) -> dict:
|
||||
"""Publish all available years independently of the annual generation."""
|
||||
return _refresh_source_record_export_artifacts(self, all_years=True)
|
||||
|
||||
|
||||
def _refresh_source_record_export_artifacts(task, *, all_years: bool) -> dict:
|
||||
lock_key = getattr(
|
||||
settings,
|
||||
"SOURCE_RECORD_EXPORT_LOCK_KEY",
|
||||
@@ -29,11 +39,13 @@ def refresh_source_record_export_artifacts(self) -> dict: # noqa: ARG001
|
||||
getattr(settings, "SOURCE_RECORD_EXPORT_LOCK_TTL_SECONDS", 6 * 60 * 60)
|
||||
)
|
||||
if not cache.add(lock_key, "1", timeout=lock_ttl):
|
||||
if all_years:
|
||||
raise task.retry(countdown=60, max_retries=lock_ttl // 60 + 2)
|
||||
logger.info("Source-record export generation skipped: lock is already held")
|
||||
return {"status": "skipped", "reason": "locked"}
|
||||
|
||||
try:
|
||||
generation = build_source_record_export_artifacts()
|
||||
generation = build_source_record_export_artifacts(all_years=all_years)
|
||||
result = {
|
||||
"status": "success",
|
||||
"generation_id": generation.generation_id,
|
||||
|
||||
@@ -38,6 +38,10 @@ from rest_framework.test import APITestCase
|
||||
from tests.apps.user.factories import UserFactory
|
||||
|
||||
|
||||
def _source_records(groups, source_group):
|
||||
return [record for group in groups for record in group[source_group]]
|
||||
|
||||
|
||||
class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
"""Checks admin-only source-record export contract."""
|
||||
|
||||
@@ -95,6 +99,17 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
self.assertEqual(generation.export_year, timezone.localdate().year)
|
||||
self.assertIn('"artifacts_count": 25', command_output.getvalue())
|
||||
|
||||
def test_previous_json_generation_requires_rebuild(self):
|
||||
build_source_record_export_artifacts()
|
||||
manifest_path = Path(self.export_directory.name) / "current.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
self.assertEqual(manifest["version"], 3)
|
||||
manifest["version"] = 2
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
with self.assertRaises(SourceRecordExportArtifactsUnavailable):
|
||||
load_current_source_record_export_generation()
|
||||
|
||||
def test_generation_contains_only_records_from_its_calendar_year(self):
|
||||
export_year = 2026
|
||||
generated_at = datetime(export_year, 8, 4, 6, 0, tzinfo=UTC)
|
||||
@@ -174,7 +189,10 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
if artifact.source_group == SourceGroup.PLANNED_INSPECTIONS.value
|
||||
and artifact.file_format == "json"
|
||||
)
|
||||
inspection_rows = json.loads(inspection_path.read_text(encoding="utf-8"))
|
||||
inspection_rows = _source_records(
|
||||
json.loads(inspection_path.read_text(encoding="utf-8")),
|
||||
SourceGroup.PLANNED_INSPECTIONS.value,
|
||||
)
|
||||
self.assertEqual(
|
||||
{row["uid"] for row in inspection_rows},
|
||||
{str(current_record.pk), str(dateless_current_record.pk)},
|
||||
@@ -185,7 +203,10 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
for artifact in generation.artifacts
|
||||
if artifact.source_group == SourceGroup.FINANCIAL_INDICATORS.value
|
||||
)
|
||||
financial_rows = json.loads(financial_path.read_text(encoding="utf-8"))
|
||||
financial_rows = _source_records(
|
||||
json.loads(financial_path.read_text(encoding="utf-8")),
|
||||
SourceGroup.FINANCIAL_INDICATORS.value,
|
||||
)
|
||||
self.assertEqual(
|
||||
[row["uid"] for row in financial_rows],
|
||||
[str(current_financial_record.pk)],
|
||||
@@ -195,6 +216,126 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
{export_year},
|
||||
)
|
||||
|
||||
def test_all_years_generation_is_separate_and_keeps_historical_financial_lines(
|
||||
self,
|
||||
):
|
||||
organization = Organization.objects.create(name="Export", inn="7707083899")
|
||||
extension = PlannedInspectionExtension.objects.create(organization=organization)
|
||||
for year in (2020, 2026):
|
||||
OrganizationSourceRecord.objects.create(
|
||||
extension=extension,
|
||||
record_type="inspection",
|
||||
source="inspections",
|
||||
external_id=str(year),
|
||||
record_date=f"{year}-01-01",
|
||||
)
|
||||
finance = FinancialIndicatorsExtension.objects.create(organization=organization)
|
||||
report = OrganizationSourceRecord.objects.create(
|
||||
extension=finance,
|
||||
record_type="financial_report",
|
||||
source="fns_reports",
|
||||
external_id="full",
|
||||
)
|
||||
for year in (2020, 2026):
|
||||
OrganizationSourceFinancialLine.objects.create(
|
||||
source_record=report,
|
||||
year=year,
|
||||
form_code="1",
|
||||
line_code=str(year),
|
||||
)
|
||||
source = SourceGroup.PLANNED_INSPECTIONS.value
|
||||
annual = build_source_record_export_artifacts(
|
||||
now=datetime(2026, 8, 4, tzinfo=UTC)
|
||||
)
|
||||
annual_manifest = Path(self.export_directory.name) / "current.json"
|
||||
before = annual_manifest.read_bytes()
|
||||
full = build_source_record_export_artifacts(
|
||||
now=datetime(2026, 8, 4, tzinfo=UTC),
|
||||
all_years=True,
|
||||
)
|
||||
self.assertIsNone(full.export_year)
|
||||
self.assertEqual(annual_manifest.read_bytes(), before)
|
||||
full_root = Path(self.export_directory.name) / "all-years"
|
||||
loaded = load_current_source_record_export_generation(
|
||||
export_directory=full_root
|
||||
)
|
||||
self.assertEqual(loaded.generation_id, full.generation_id)
|
||||
self.assertIsNone(loaded.export_year)
|
||||
|
||||
def rows(generation, group):
|
||||
artifact = next(
|
||||
a
|
||||
for a in generation.artifacts
|
||||
if a.source_group == group and a.file_format == "json"
|
||||
)
|
||||
return _source_records(json.loads(artifact.path.read_text()), group)
|
||||
|
||||
self.assertEqual(len(rows(annual, source)), 1)
|
||||
self.assertEqual(len(rows(full, source)), 2)
|
||||
self.assertEqual(
|
||||
{
|
||||
line["year"]
|
||||
for line in rows(full, "financial_indicators")[0]["financial_lines"]
|
||||
},
|
||||
{2020, 2026},
|
||||
)
|
||||
self.assertEqual(
|
||||
{
|
||||
line["year"]
|
||||
for line in rows(annual, "financial_indicators")[0]["financial_lines"]
|
||||
},
|
||||
{2026},
|
||||
)
|
||||
# Retention in either scope must not delete the other's files.
|
||||
for _ in range(3):
|
||||
build_source_record_export_artifacts(all_years=True)
|
||||
self.assertTrue(all(a.path.is_file() for a in annual.artifacts))
|
||||
|
||||
def test_all_years_command_does_not_publish_an_annual_manifest(self):
|
||||
call_command("build_source_record_exports", all_years=True, stdout=StringIO())
|
||||
self.assertFalse((Path(self.export_directory.name) / "current.json").exists())
|
||||
full = load_current_source_record_export_generation(
|
||||
export_directory=Path(self.export_directory.name) / "all-years",
|
||||
)
|
||||
self.assertIsNone(full.export_year)
|
||||
|
||||
def test_full_export_task_publishes_separate_manifest_and_waits_for_lock(self):
|
||||
from celery.exceptions import Retry
|
||||
from django.core.cache import cache
|
||||
from organizations.tasks import refresh_all_years_source_record_export_artifacts
|
||||
|
||||
lock = "test-full-export-lock"
|
||||
with self.settings(SOURCE_RECORD_EXPORT_LOCK_KEY=lock):
|
||||
cache.delete(lock)
|
||||
cache.add(lock, "held", timeout=30)
|
||||
try:
|
||||
with self.assertRaises(Retry):
|
||||
refresh_all_years_source_record_export_artifacts.run()
|
||||
self.assertFalse(
|
||||
(
|
||||
Path(self.export_directory.name) / "all-years/current.json"
|
||||
).exists()
|
||||
)
|
||||
finally:
|
||||
cache.delete(lock)
|
||||
result = refresh_all_years_source_record_export_artifacts.run()
|
||||
self.assertEqual(result["status"], "success")
|
||||
self.assertIsNone(result["export_year"])
|
||||
self.assertIsNone(cache.get(lock))
|
||||
self.assertFalse(
|
||||
(Path(self.export_directory.name) / "current.json").exists()
|
||||
)
|
||||
|
||||
def test_manifest_rejects_ambiguous_all_years_scope(self):
|
||||
build_source_record_export_artifacts(all_years=True)
|
||||
directory = Path(self.export_directory.name) / "all-years"
|
||||
manifest_path = directory / "current.json"
|
||||
payload = json.loads(manifest_path.read_text())
|
||||
payload["export_year"] = 2026
|
||||
manifest_path.write_text(json.dumps(payload))
|
||||
with self.assertRaises(SourceRecordExportArtifactsUnavailable):
|
||||
load_current_source_record_export_generation(export_directory=directory)
|
||||
|
||||
def test_new_calendar_year_requires_a_new_prepared_generation(self):
|
||||
generated_at = datetime(2026, 12, 31, 23, 59, tzinfo=UTC)
|
||||
build_source_record_export_artifacts(now=generated_at)
|
||||
@@ -308,8 +449,12 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
self.assertIn("payload.risk.score", rows[0])
|
||||
self.assertIn("payload.tags", rows[0])
|
||||
|
||||
financial_rows = json.loads(
|
||||
archive.read("financial-indicators.json").decode("utf-8"),
|
||||
financial_groups = json.loads(
|
||||
archive.read("financial-indicators.json").decode("utf-8")
|
||||
)
|
||||
self.assertEqual(financial_groups[0]["okpo"], "12345678")
|
||||
financial_rows = _source_records(
|
||||
financial_groups, SourceGroup.FINANCIAL_INDICATORS.value
|
||||
)
|
||||
self.assertEqual(financial_rows[0]["Наименование"], organization.full_name)
|
||||
self.assertEqual(
|
||||
@@ -582,6 +727,7 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
for file_format in ("json", "csv", "xlsx"):
|
||||
artifact_path = export_directory / f"artifact.{file_format}"
|
||||
_render_source_group_artifact(
|
||||
source_group=SourceGroup.PLANNED_INSPECTIONS.value,
|
||||
row_spool_path=spool_path,
|
||||
output_path=artifact_path,
|
||||
headers=headers,
|
||||
@@ -623,18 +769,30 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
self.assertFalse(queryset.ordered)
|
||||
self.assertFalse(queryset.query.default_ordering)
|
||||
|
||||
def test_json_artifact_reuses_valid_canonical_spool_without_copying_it(self):
|
||||
def test_json_artifact_groups_nonadjacent_records_by_okpo(self):
|
||||
organization = Organization.objects.create(
|
||||
name='ООО "JSON без копии"',
|
||||
inn="7707083813",
|
||||
okpo="00123456",
|
||||
)
|
||||
other_organization = Organization.objects.create(
|
||||
name='ООО "Вторая организация"',
|
||||
inn="7707083814",
|
||||
okpo="87654321",
|
||||
)
|
||||
extension = PlannedInspectionExtension.objects.create(
|
||||
organization=organization,
|
||||
title="Плановые проверки Генпрокуратуры России",
|
||||
)
|
||||
for index in range(2):
|
||||
other_extension = PlannedInspectionExtension.objects.create(
|
||||
organization=other_organization,
|
||||
title="Плановые проверки Генпрокуратуры России",
|
||||
)
|
||||
for index, record_extension in enumerate(
|
||||
(extension, other_extension, extension)
|
||||
):
|
||||
OrganizationSourceRecord.objects.create(
|
||||
extension=extension,
|
||||
extension=record_extension,
|
||||
record_type="inspection",
|
||||
source="inspections",
|
||||
external_id=f"INSP-JSON-{index}",
|
||||
@@ -652,6 +810,7 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
)
|
||||
|
||||
_render_source_group_artifact(
|
||||
source_group=SourceGroup.PLANNED_INSPECTIONS.value,
|
||||
row_spool_path=spool_path,
|
||||
output_path=artifact_path,
|
||||
headers=headers,
|
||||
@@ -659,9 +818,21 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
records_count=records_count,
|
||||
)
|
||||
|
||||
self.assertEqual(records_count, 2)
|
||||
self.assertEqual(len(json.loads(spool_path.read_text())), 2)
|
||||
self.assertTrue(os.path.samefile(spool_path, artifact_path))
|
||||
self.assertEqual(records_count, 3)
|
||||
self.assertEqual(len(json.loads(spool_path.read_text())), 3)
|
||||
groups = json.loads(artifact_path.read_text(encoding="utf-8"))
|
||||
self.assertEqual(
|
||||
{group["okpo"] for group in groups}, {"00123456", "87654321"}
|
||||
)
|
||||
grouped = {
|
||||
group["okpo"]: group[SourceGroup.PLANNED_INSPECTIONS.value]
|
||||
for group in groups
|
||||
}
|
||||
self.assertEqual(len(grouped["00123456"]), 2)
|
||||
self.assertEqual(len(grouped["87654321"]), 1)
|
||||
self.assertNotIn("ОКПО", grouped["00123456"][0])
|
||||
self.assertFalse(os.path.samefile(spool_path, artifact_path))
|
||||
self.assertFalse(list(Path(temporary_directory).glob("*.sqlite3")))
|
||||
|
||||
def test_generation_publishes_complete_matrix_and_keeps_previous_on_failure(self):
|
||||
first_generation = build_source_record_export_artifacts()
|
||||
|
||||
@@ -20,6 +20,8 @@ from apps.parsers.models import (
|
||||
ProcurementRecord,
|
||||
)
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.db import connection
|
||||
from django.test.utils import CaptureQueriesContext
|
||||
from django.urls import reverse
|
||||
from openpyxl import Workbook
|
||||
from organizations.models import Organization, OrganizationSourceRecord
|
||||
@@ -697,7 +699,17 @@ class ParsersViewSetTest(APITestCase):
|
||||
)
|
||||
self.client.force_authenticate(self.user)
|
||||
|
||||
response = self.client.get("/api/v1/parsers/dashboard/")
|
||||
with CaptureQueriesContext(connection) as queries:
|
||||
response = self.client.get("/api/v1/parsers/dashboard/")
|
||||
|
||||
source_scans = [
|
||||
query["sql"]
|
||||
for query in queries
|
||||
if "SELECT DISTINCT" in query["sql"]
|
||||
and "organizations_source_record" in query["sql"]
|
||||
]
|
||||
self.assertTrue(source_scans)
|
||||
self.assertEqual(len(source_scans), len(set(source_scans)))
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
coverage = response.data["data"]["registry_data_coverage"]
|
||||
|
||||
Reference in New Issue
Block a user