Merge pull request 'fix: group JSON source exports by organization (dev)' (#43) from hotfix/json-source-export-dev-20260927 into dev
All checks were successful
Mostovik Backend CI/CD / Tests and lint (push) Successful in 4m2s
Mostovik Backend CI/CD / Build linux/amd64 release images (push) Successful in 3m33s
Mostovik Backend CI/CD / Deploy and verify internal main (push) Has been skipped
Mostovik Backend CI/CD / Deploy dev (push) Successful in 2m48s
All checks were successful
Mostovik Backend CI/CD / Tests and lint (push) Successful in 4m2s
Mostovik Backend CI/CD / Build linux/amd64 release images (push) Successful in 3m33s
Mostovik Backend CI/CD / Deploy and verify internal main (push) Has been skipped
Mostovik Backend CI/CD / Deploy dev (push) Successful in 2m48s
This commit was merged in pull request #43.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -10,6 +10,7 @@ import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import sqlite3
|
||||
import time
|
||||
import zipfile
|
||||
from collections.abc import Iterable, Iterator, Sequence
|
||||
@@ -56,7 +57,7 @@ ALL_HISTORY_SOURCE_GROUPS = {
|
||||
SourceGroup.INTEGRATED_STRUCTURE_DOCUMENTS.value,
|
||||
SourceGroup.FEDRESURS_COMPANY_PROFILE.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"
|
||||
@@ -330,6 +331,7 @@ def build_source_record_export_artifacts(
|
||||
artifact_paths = (output_path,)
|
||||
else:
|
||||
artifact_paths = _render_source_group_artifact(
|
||||
source_group=source_group,
|
||||
row_spool_path=row_spool_path,
|
||||
output_path=staging_directory / file_name,
|
||||
headers=headers,
|
||||
@@ -844,6 +846,7 @@ def _spool_source_group_rows(
|
||||
|
||||
def _render_source_group_artifact(
|
||||
*,
|
||||
source_group: str,
|
||||
row_spool_path: Path,
|
||||
output_path: Path,
|
||||
headers: Sequence[str],
|
||||
@@ -866,7 +869,11 @@ def _render_source_group_artifact(
|
||||
records_count=records_count,
|
||||
display_headers=display_headers,
|
||||
)
|
||||
_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,)
|
||||
|
||||
|
||||
@@ -1156,10 +1163,79 @@ 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) or row.pop("okpo", None)
|
||||
okpo = str(raw_okpo) if raw_okpo else None
|
||||
fallback = [
|
||||
row.get("ИНН") or row.get("inn"),
|
||||
row.get("ОГРН") or row.get("ogrn"),
|
||||
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(
|
||||
|
||||
@@ -220,7 +220,10 @@ def test_sro_export_keeps_all_years_and_identifier_strings(export_client, file_f
|
||||
assert archive.namelist() == [f"sro-membership-check.{file_format}"]
|
||||
content = archive.read(archive.namelist()[0])
|
||||
if file_format == "json":
|
||||
rows = json.loads(content)
|
||||
organizations = json.loads(content)
|
||||
assert len(organizations) == 1
|
||||
assert organizations[0]["okpo"] == "00000001"
|
||||
rows = organizations[0]["sro_membership"]
|
||||
elif file_format == "csv":
|
||||
rows = list(csv.DictReader(StringIO(content.decode("utf-8-sig"))))
|
||||
else:
|
||||
@@ -231,7 +234,10 @@ def test_sro_export_keeps_all_years_and_identifier_strings(export_client, file_f
|
||||
assert len(rows) == 1
|
||||
assert rows[0]["ИНН"] == "0012345678"
|
||||
assert rows[0]["ОГРН"] == "0012345678901"
|
||||
assert rows[0]["ОКПО"] == "00000001"
|
||||
if file_format == "json":
|
||||
assert "ОКПО" not in rows[0]
|
||||
else:
|
||||
assert rows[0]["ОКПО"] == "00000001"
|
||||
|
||||
|
||||
def test_publication_during_render_retries_then_builds_latest_snapshot(export_client):
|
||||
|
||||
@@ -42,6 +42,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."""
|
||||
|
||||
@@ -81,7 +85,8 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
json.dumps(
|
||||
{"uid": "record-1", "payload.rendered_page.text": value},
|
||||
ensure_ascii=False,
|
||||
) + "\n",
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
paths = _render_xlsx_files(
|
||||
@@ -91,10 +96,12 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
records_count=1,
|
||||
)
|
||||
workbook = load_workbook(paths[0], read_only=True)
|
||||
self.assertEqual(workbook["data"]["B2"].value, "См. overflow_values: payload.rendered_page.text")
|
||||
self.assertEqual(
|
||||
workbook["data"]["B2"].value,
|
||||
"См. overflow_values: payload.rendered_page.text",
|
||||
)
|
||||
chunks = [
|
||||
row[4][4:]
|
||||
for row in list(workbook["overflow_values_1"].values)[1:]
|
||||
row[4][4:] for row in list(workbook["overflow_values_1"].values)[1:]
|
||||
]
|
||||
self.assertEqual(base64.b64decode("".join(chunks)).decode("utf-8"), value)
|
||||
workbook.close()
|
||||
@@ -270,13 +277,24 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
rows = (
|
||||
list(csv.DictReader(StringIO(content)))
|
||||
if file_format == "csv"
|
||||
else json.loads(content)
|
||||
else _source_records(json.loads(content), "sanctions")
|
||||
)
|
||||
self.assertEqual(len(rows), 2)
|
||||
self.assertEqual({row["rn"] for row in rows}, {"0000", "0001"})
|
||||
self.assertEqual(rows[0]["inn"], "0001234567")
|
||||
self.assertNotIn("Регистрационный номер", rows[0])
|
||||
|
||||
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)
|
||||
@@ -356,7 +374,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)},
|
||||
@@ -366,7 +387,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)],
|
||||
@@ -408,7 +432,10 @@ class OrganizationSourceRecordExportApiV2Test(APITestCase):
|
||||
if artifact.source_group == SourceGroup.MEDIA_MENTIONS.value
|
||||
and artifact.file_format == "json"
|
||||
)
|
||||
rows = json.loads(media_path.read_text(encoding="utf-8"))
|
||||
rows = _source_records(
|
||||
json.loads(media_path.read_text(encoding="utf-8")),
|
||||
SourceGroup.MEDIA_MENTIONS.value,
|
||||
)
|
||||
exported = next(row for row in rows if row["uid"] == str(old_record.pk))
|
||||
self.assertEqual(exported["record_date"], "2023-02-15")
|
||||
self.assertEqual(
|
||||
@@ -529,8 +556,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(
|
||||
@@ -803,6 +834,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,
|
||||
@@ -844,18 +876,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}",
|
||||
@@ -873,6 +917,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,
|
||||
@@ -880,9 +925,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()
|
||||
|
||||
Reference in New Issue
Block a user