Merge pull request 'fix: group JSON source exports by organization (main)' (#21) from hotfix/json-source-export-20260927 into main
Some checks failed
Deploy Customer Main / Build, Push, Deploy (push) Failing after 51s
CI/CD Pipeline / Code Quality Checks (push) Successful in 1m34s
CI/CD Pipeline / Run Tests (push) Successful in 3m33s
CI/CD Pipeline / Build and Push Dev Images (push) Has been skipped
CI/CD Pipeline / Deploy Dev via Compose (push) Has been skipped

This commit was merged in pull request #21.
This commit is contained in:
avm
2026-09-27 11:43:48 +03:00
3 changed files with 180 additions and 22 deletions

View File

@@ -47,9 +47,20 @@ JavaScript. Ticket не попадает в URL и после первого з
Итого формируется 25 логических артефактов. Финансовые показатели всегда Итого формируется 25 логических артефактов. Финансовые показатели всегда
выгружаются в JSON с вложенным массивом `financial_lines`. Промышленная группа выгружаются в JSON с вложенным массивом `financial_lines`. Промышленная группа
объединяет три таблицы, а поле `record_type` различает тип строки. Все строки объединяет три таблицы, а поле `record_type` различает тип строки. CSV и XLSX
используют тот же контракт, что и Mostovik: реквизиты организации, включая ОКПО, сохраняют плоские строки с реквизитами организации и полями `payload.*`.
общие поля записи источника и специфичные поля в `payload.*`. JSON каждого источника использует тот же контракт, что и Mostovik: массив
организаций с `okpo` и массивом записей под ключом группы API. Например:
```json
[{"okpo":"12345678","bankruptcy":[{"uid":"...","source_group":"bankruptcy","payload.case_number":"..."}]}]
```
`ОКПО` переносится из записи в `okpo` оболочки; остальные поля записи остаются
в прежнем виде. Записи одной организации собираются вместе независимо от
порядка чтения таблиц. При отсутствии ОКПО экспортируется `null`, а для
группировки используются ИНН, ОГРН и наименование. При выборе нескольких
источников ZIP содержит отдельный JSON-файл для каждого.
Все записи текущего года включаются в публичные файлы, а техническое Все записи текущего года включаются в публичные файлы, а техническое
наименование внешнего поставщика нейтрализуется. Исходные значения в БД наименование внешнего поставщика нейтрализуется. Исходные значения в БД
@@ -68,8 +79,9 @@ Celery Beat запускает
1. читает каждую нормализованную таблицу один раз без model-level сортировки; 1. читает каждую нормализованную таблицу один раз без model-level сортировки;
предметные даты и fallback по `created_at` индексированы; предметные даты и fallback по `created_at` индексированы;
2. создаёт компактный JSON-массив и переиспользует его как готовый JSON; 2. создаёт плоский spool и группирует JSON по ОКПО через временный дисковый
3. потоково формирует CSV и write-only XLSX; индекс SQLite, без загрузки всех строк в память;
3. потоково формирует CSV и write-only XLSX из того же spool;
4. записывает календарный `export_year` в manifest; 4. записывает календарный `export_year` в manifest;
5. атомарно публикует `current.json` только после готовности всей матрицы; 5. атомарно публикует `current.json` только после готовности всей матрицы;
6. при ошибке удаляет staging и продолжает отдавать предыдущее поколение того же года; 6. при ошибке удаляет staging и продолжает отдавать предыдущее поколение того же года;
@@ -79,7 +91,10 @@ Web и Celery worker должны использовать общий read-write
## Первый запуск и настройки ## Первый запуск и настройки
Первое поколение можно сформировать вручную: Первое поколение можно сформировать вручную. После обновления формата JSON
поколения с manifest версии 2 не раздаются: до первой успешной сборки версии 3
API возвращает `503 source_export_not_ready`. Запустите команду ниже после
развёртывания, чтобы восстановить доступность выгрузок сразу:
```bash ```bash
PYTHONPATH=src uv run python src/manage.py build_source_record_exports PYTHONPATH=src uv run python src/manage.py build_source_record_exports
@@ -94,7 +109,8 @@ PYTHONPATH=src uv run python src/manage.py build_source_record_exports
| `SOURCE_RECORD_EXPORT_DOWNLOAD_TICKET_TTL_SECONDS` | `300` | Срок действия download-ticket | | `SOURCE_RECORD_EXPORT_DOWNLOAD_TICKET_TTL_SECONDS` | `300` | Срок действия download-ticket |
Для атомарной генерации требуется свободное место не меньше Для атомарной генерации требуется свободное место не меньше
`(GENERATIONS_TO_KEEP + 1) * размер поколения` плюс запас файловой системы. `(GENERATIONS_TO_KEEP + 1) * размер поколения` плюс исходный spool,
временная база SQLite размером порядка spool и рабочий запас файловой системы.
На локальном снимке от 2026-08-04 поколение за 2026 год содержит 1 962 записи На локальном снимке от 2026-08-04 поколение за 2026 год содержит 1 962 записи
и занимает 4 738 872 байта (4,52 MiB) для всей матрицы. Архив со всеми и занимает 4 738 872 байта (4,52 MiB) для всей матрицы. Архив со всеми

View File

@@ -8,6 +8,7 @@ import os
import re import re
import secrets import secrets
import shutil import shutil
import sqlite3
import zipfile import zipfile
from collections.abc import Iterable, Iterator, Sequence from collections.abc import Iterable, Iterator, Sequence
from dataclasses import dataclass from dataclasses import dataclass
@@ -44,7 +45,7 @@ EXPORT_FORMAT_XLSX = "xlsx"
EXPORT_FORMAT_JSON = "json" EXPORT_FORMAT_JSON = "json"
EXPORT_FORMATS = (EXPORT_FORMAT_CSV, EXPORT_FORMAT_XLSX, EXPORT_FORMAT_JSON) EXPORT_FORMATS = (EXPORT_FORMAT_CSV, EXPORT_FORMAT_XLSX, EXPORT_FORMAT_JSON)
FINANCIAL_SOURCE_GROUP = "financial_indicators" FINANCIAL_SOURCE_GROUP = "financial_indicators"
EXPORT_MANIFEST_VERSION = 2 EXPORT_MANIFEST_VERSION = 3
CURRENT_EXPORT_MANIFEST_FILE_NAME = "current.json" CURRENT_EXPORT_MANIFEST_FILE_NAME = "current.json"
GENERATION_MANIFEST_FILE_NAME = "manifest.json" GENERATION_MANIFEST_FILE_NAME = "manifest.json"
GENERATION_DIRECTORY_NAME = "generations" GENERATION_DIRECTORY_NAME = "generations"
@@ -548,6 +549,7 @@ def build_source_record_export_artifacts(
file_format=file_format, file_format=file_format,
) )
artifact_paths = _render_source_group_artifact( artifact_paths = _render_source_group_artifact(
source_group=source_group,
row_spool_path=row_spool_path, row_spool_path=row_spool_path,
output_path=staging_directory / file_name, output_path=staging_directory / file_name,
headers=headers, headers=headers,
@@ -964,6 +966,7 @@ def _spool_source_group_rows(
def _render_source_group_artifact( def _render_source_group_artifact(
*, *,
source_group: str,
row_spool_path: Path, row_spool_path: Path,
output_path: Path, output_path: Path,
headers: Sequence[str], headers: Sequence[str],
@@ -984,10 +987,87 @@ def _render_source_group_artifact(
headers=headers, headers=headers,
records_count=records_count, records_count=records_count,
) )
os.link(row_spool_path, output_path) _render_json_file(
source_group=source_group,
row_spool_path=row_spool_path,
output_path=output_path,
)
return (output_path,) return (output_path,)
def _render_json_file(
*,
source_group: str,
row_spool_path: Path,
output_path: Path,
) -> None:
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 _iter_spooled_rows(row_spool_path: Path) -> Iterator[dict[str, Any]]: def _iter_spooled_rows(row_spool_path: Path) -> Iterator[dict[str, Any]]:
with row_spool_path.open("r", encoding="utf-8") as rows_file: with row_spool_path.open("r", encoding="utf-8") as rows_file:
for line in rows_file: for line in rows_file:

View File

@@ -4,6 +4,7 @@ import json
import zipfile import zipfile
from datetime import UTC, datetime from datetime import UTC, datetime
from io import BytesIO, StringIO from io import BytesIO, StringIO
from pathlib import Path
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from unittest.mock import patch from unittest.mock import patch
@@ -12,6 +13,7 @@ from apps.external_data.source_record_export import (
SOURCE_GROUP_EXPORT_SPECS, SOURCE_GROUP_EXPORT_SPECS,
SOURCE_RECORD_EXPORT_FIELDS, SOURCE_RECORD_EXPORT_FIELDS,
SourceRecordExportArtifactsUnavailable, SourceRecordExportArtifactsUnavailable,
_render_json_file,
_source_group_headers, _source_group_headers,
build_source_record_export_artifacts, build_source_record_export_artifacts,
build_source_records_export_archive, build_source_records_export_archive,
@@ -39,6 +41,40 @@ from tests.apps.organization.factories import OrganizationFactory
from tests.apps.user.factories import UserFactory 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]]
def test_json_groups_interleaved_rows_by_okpo():
rows = [
{"ОКПО": "00123456", "ИНН": "111", "uid": "first"},
{"ОКПО": "87654321", "ИНН": "222", "uid": "other"},
{"ОКПО": "00123456", "ИНН": "111", "uid": "last"},
]
with TemporaryDirectory() as directory:
spool_path = Path(directory) / "rows.json"
output_path = Path(directory) / "output.json"
spool_path.write_text(
"[\n" + ",\n".join(json.dumps(row) for row in rows) + "\n]",
encoding="utf-8",
)
_render_json_file(
source_group="bankruptcy",
row_spool_path=spool_path,
output_path=output_path,
)
groups = json.loads(output_path.read_text(encoding="utf-8"))
self_groups = {group["okpo"]: group["bankruptcy"] for group in groups}
assert [row["uid"] for row in self_groups["00123456"]] == ["first", "last"]
assert [row["uid"] for row in self_groups["87654321"]] == ["other"]
assert all(
"ОКПО" not in record for record in _source_records(groups, "bankruptcy")
)
assert not list(Path(directory).glob("*.sqlite3"))
class SourceRecordExportApiTest(APITestCase): class SourceRecordExportApiTest(APITestCase):
"""Check admin access and zero-query delivery of prepared files.""" """Check admin access and zero-query delivery of prepared files."""
@@ -121,7 +157,8 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "industrial_production" if artifact.source_group == "industrial_production"
and artifact.file_format == "json" and artifact.file_format == "json"
) )
industrial_rows = json.loads(industrial_path.read_text(encoding="utf-8")) industrial_groups = json.loads(industrial_path.read_text(encoding="utf-8"))
industrial_rows = _source_records(industrial_groups, "industrial_production")
self.assertEqual( self.assertEqual(
{row["record_type"] for row in industrial_rows}, {row["record_type"] for row in industrial_rows},
{ {
@@ -130,11 +167,8 @@ class SourceRecordExportApiTest(APITestCase):
"manufacturer_registry_entry", "manufacturer_registry_entry",
}, },
) )
self.assertEqual({row["ОКПО"] for row in industrial_rows}, {"12345678"}) self.assertEqual([group["okpo"] for group in industrial_groups], ["12345678"])
self.assertEqual( self.assertNotIn("ОКПО", industrial_rows[0])
list(industrial_rows[0])[: len(expected_prefix)],
expected_prefix,
)
self.assertNotIn("organization", industrial_rows[0]) self.assertNotIn("organization", industrial_rows[0])
self.assertIn("payload.product_name", industrial_rows[0]) self.assertIn("payload.product_name", industrial_rows[0])
@@ -143,7 +177,10 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts for artifact in generation.artifacts
if artifact.source_group == "financial_indicators" if artifact.source_group == "financial_indicators"
) )
financial_rows = json.loads(financial_path.read_text(encoding="utf-8")) financial_rows = _source_records(
json.loads(financial_path.read_text(encoding="utf-8")),
"financial_indicators",
)
self.assertEqual(financial_rows[0]["financial_lines"][0]["line_code"], "1600") self.assertEqual(financial_rows[0]["financial_lines"][0]["line_code"], "1600")
arbitration_path = next( arbitration_path = next(
@@ -151,7 +188,9 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts for artifact in generation.artifacts
if artifact.source_group == "arbitration" and artifact.file_format == "json" if artifact.source_group == "arbitration" and artifact.file_format == "json"
) )
arbitration_row = json.loads(arbitration_path.read_text(encoding="utf-8"))[0] arbitration_row = _source_records(
json.loads(arbitration_path.read_text(encoding="utf-8")), "arbitration"
)[0]
self.assertEqual(arbitration_row["source"], "arbitration") self.assertEqual(arbitration_row["source"], "arbitration")
self.assertEqual( self.assertEqual(
arbitration_row["external_id"], arbitration_row["payload.case_number"] arbitration_row["external_id"], arbitration_row["payload.case_number"]
@@ -219,7 +258,9 @@ class SourceRecordExportApiTest(APITestCase):
) )
for artifact in artifacts: for artifact in artifacts:
if artifact.file_format == "json": if artifact.file_format == "json":
exported_values = json.loads(artifact.path.read_text(encoding="utf-8")) groups = json.loads(artifact.path.read_text(encoding="utf-8"))
self.assertEqual([group["okpo"] for group in groups], ["11223344"])
exported_values = _source_records(groups, "bankruptcy")
self.assertEqual( self.assertEqual(
[key for key in exported_values[0] if key.startswith("payload.")], [key for key in exported_values[0] if key.startswith("payload.")],
[ [
@@ -244,7 +285,8 @@ class SourceRecordExportApiTest(APITestCase):
serialized_values = str(exported_values) serialized_values = str(exported_values)
self.assertIn(str(excluded_record.id), serialized_values) self.assertIn(str(excluded_record.id), serialized_values)
self.assertIn(str(included_record.id), str(exported_values)) self.assertIn(str(included_record.id), str(exported_values))
self.assertIn("11223344", str(exported_values)) if artifact.file_format != "json":
self.assertIn("11223344", str(exported_values))
self.assertNotRegex( self.assertNotRegex(
serialized_values, serialized_values,
r"(?i)(?<![a-zа-яё0-9])(?:checko(?:\.ru)?|чеко|чекало|чекко)" r"(?i)(?<![a-zа-яё0-9])(?:checko(?:\.ru)?|чеко|чекало|чекко)"
@@ -261,6 +303,17 @@ class SourceRecordExportApiTest(APITestCase):
self.assertEqual(generation.export_year, timezone.localdate().year) self.assertEqual(generation.export_year, timezone.localdate().year)
self.assertIn('"artifacts_count": 25', command_output.getvalue()) 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): def test_generation_contains_only_records_from_its_calendar_year(self):
export_year = 2026 export_year = 2026
generated_at = datetime(export_year, 8, 4, 6, 0, tzinfo=UTC) generated_at = datetime(export_year, 8, 4, 6, 0, tzinfo=UTC)
@@ -301,7 +354,10 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "government_procurements" if artifact.source_group == "government_procurements"
and artifact.file_format == "json" and artifact.file_format == "json"
) )
procurement_rows = json.loads(procurements_path.read_text(encoding="utf-8")) procurement_rows = _source_records(
json.loads(procurements_path.read_text(encoding="utf-8")),
"government_procurements",
)
self.assertEqual( self.assertEqual(
[row["uid"] for row in procurement_rows], [row["uid"] for row in procurement_rows],
[str(current_procurement.pk)], [str(current_procurement.pk)],
@@ -313,7 +369,10 @@ class SourceRecordExportApiTest(APITestCase):
if artifact.source_group == "industrial_production" if artifact.source_group == "industrial_production"
and artifact.file_format == "json" and artifact.file_format == "json"
) )
industrial_rows = json.loads(industrial_path.read_text(encoding="utf-8")) industrial_rows = _source_records(
json.loads(industrial_path.read_text(encoding="utf-8")),
"industrial_production",
)
self.assertEqual( self.assertEqual(
[row["uid"] for row in industrial_rows], [row["uid"] for row in industrial_rows],
[str(current_product.pk)], [str(current_product.pk)],
@@ -324,7 +383,10 @@ class SourceRecordExportApiTest(APITestCase):
for artifact in generation.artifacts for artifact in generation.artifacts
if artifact.source_group == "financial_indicators" if artifact.source_group == "financial_indicators"
) )
financial_rows = json.loads(financial_path.read_text(encoding="utf-8")) financial_rows = _source_records(
json.loads(financial_path.read_text(encoding="utf-8")),
"financial_indicators",
)
self.assertEqual( self.assertEqual(
[row["uid"] for row in financial_rows], [row["uid"] for row in financial_rows],
[str(current_report.pk)], [str(current_report.pk)],