diff --git a/app/services/document_artifact_service.py b/app/services/document_artifact_service.py index 1e707be..dece54f 100644 --- a/app/services/document_artifact_service.py +++ b/app/services/document_artifact_service.py @@ -362,3 +362,31 @@ def invalidate_artifacts( stmt = stmt.where(DocumentArtifact.format == _validate_segment(format, "format")) result = db.execute(stmt) return int(result.rowcount or 0) + + +# --------------------------------------------------------------------------- +# Cleanup helper (for failed transactions) +# --------------------------------------------------------------------------- + +def remove_artifact_file(artifact: DocumentArtifact) -> bool: + """ + Delete the physical file of a single artifact row. + + Narrowly scoped cleanup for a failed transaction that created an artifact + file but could not commit. Accepts only a DocumentArtifact row (never an + arbitrary path). Resolves through the safe path resolver. Never touches + other artifacts. Returns True if a file was removed. + """ + if artifact is None or not artifact.storage_key: + return False + try: + path = resolve_storage_path(artifact.storage_key) + except ArtifactPathError: + return False + try: + if path.is_file(): + path.unlink() + return True + except OSError: + return False + return False diff --git a/app/services/ks2_service.py b/app/services/ks2_service.py index 57f7c3d..99022f4 100644 --- a/app/services/ks2_service.py +++ b/app/services/ks2_service.py @@ -147,6 +147,15 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, c price = _decimal(item.unit_price) document.items.append(KS2Item(work_item_id=item_id, quantity=quantity, unit_price=price, amount=price * quantity)) + # Successful draft change invalidates existing draft artifacts (same tx). + if ks2_id is not None: + from app.services.document_artifact_service import invalidate_artifacts + invalidate_artifacts( + db, + project_id=project_id, + document_type="KS2", + document_id=document.id, + ) db.commit() db.refresh(document) return document @@ -157,6 +166,7 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, c def issue_ks2(db: Session, project_id: int, ks2_id: int): """Revalidate current balances, attribute quantity to DR lines oldest-first, and issue atomically.""" + artifact = None try: document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).with_for_update().first() if document is None: @@ -206,11 +216,37 @@ def issue_ks2(db: Session, project_id: int, ks2_id: int): f"Не удалось распределить весь объём по источникам Daily Reports для позиции {line.work_item.name}" ) document.status = "issued" + + # Generate and persist the official artifact inside this transaction. + from app.exporters.excel.ks2_renderer import ( + TEMPLATE_TYPE as KS2_TEMPLATE_TYPE, + TEMPLATE_VERSION as KS2_TEMPLATE_VERSION, + render_ks2_excel, + ) + from app.exporters.ks2_dto import build_ks2_export_dto + from app.services.document_artifact_service import persist_artifact, remove_artifact_file + + dto = build_ks2_export_dto(db, document) + content = render_ks2_excel(dto) + artifact = persist_artifact( + db, + project_id=project_id, + document_type="KS2", + document_id=document.id, + format="xlsx", + template_type=KS2_TEMPLATE_TYPE, + template_version=KS2_TEMPLATE_VERSION, + content=content, + dto=dto, + ) + db.commit() db.refresh(document) return document except Exception: db.rollback() + if artifact is not None: + remove_artifact_file(artifact) raise diff --git a/app/services/ks3_service.py b/app/services/ks3_service.py index dd93c19..4f3a724 100644 --- a/app/services/ks3_service.py +++ b/app/services/ks3_service.py @@ -123,6 +123,15 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, for ks2_id in seen_ks2: document.links.append(KS3KS2(ks2_id=ks2_id)) + # Successful draft change invalidates existing draft artifacts (same tx). + if ks3_id is not None: + from app.services.document_artifact_service import invalidate_artifacts + invalidate_artifacts( + db, + project_id=project_id, + document_type="KS3", + document_id=document.id, + ) db.commit() db.refresh(document) return document @@ -133,6 +142,7 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, def issue_ks3(db: Session, project_id: int, ks3_id: int): """Issue a KS-3 draft atomically.""" + artifact = None try: document = db.query(KS3).options( joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items) @@ -153,11 +163,38 @@ def issue_ks3(db: Session, project_id: int, ks3_id: int): raise KS3ValidationError(f"КС-2 №{ks2.number} не проведён") document.status = "issued" + + # Generate and persist the official artifact inside this transaction. + # KS-3 issue must NOT touch KS-2 artifacts. + from app.exporters.ks3_dto import build_ks3_export_dto + from app.exporters.word.ks3_renderer import ( + TEMPLATE_TYPE as KS3_TEMPLATE_TYPE, + TEMPLATE_VERSION as KS3_TEMPLATE_VERSION, + render_ks3_word, + ) + from app.services.document_artifact_service import persist_artifact, remove_artifact_file + + dto = build_ks3_export_dto(db, document) + content = render_ks3_word(dto) + artifact = persist_artifact( + db, + project_id=project_id, + document_type="KS3", + document_id=document.id, + format="docx", + template_type=KS3_TEMPLATE_TYPE, + template_version=KS3_TEMPLATE_VERSION, + content=content, + dto=dto, + ) + db.commit() db.refresh(document) return document except Exception: db.rollback() + if artifact is not None: + remove_artifact_file(artifact) raise diff --git a/docs/implementation/DOC-B5-issue-artifact-lifecycle.md b/docs/implementation/DOC-B5-issue-artifact-lifecycle.md new file mode 100644 index 0000000..30b5c77 --- /dev/null +++ b/docs/implementation/DOC-B5-issue-artifact-lifecycle.md @@ -0,0 +1,92 @@ +# Implementation Report — DOC-B5-issue-artifact-lifecycle + +### Status + +DONE + +### Changed files + +| Файл | Что | +|---|---| +| `app/services/document_artifact_service.py` | `remove_artifact_file()` — cleanup для failed tx | +| `app/services/ks2_service.py` | issue: render+persist artifact; save_draft: invalidate | +| `app/services/ks3_service.py` | issue: render+persist artifact; save_draft: invalidate | +| `tests/test_doc_b5_issue_artifact_lifecycle.py` | 13 интеграционных тестов | + +### Lifecycle implemented + +| Состояние | Поведение | +|---|---| +| **Draft edit** | `invalidate_artifacts` в той же транзакции; файл не удаляется; нет artifact → no-op | +| **Issued** | существующие валидации → `status=issued` → DTO → renderer → `persist_artifact` → commit | +| **Cancelled** | не трогает artifact (row/file/hashes/`is_current`); замена/удаление/инвалидация отсутствуют | + +### Transaction / rollback strategy + +`persist_artifact` не коммитит. Бизнес-транзакция (`issue_ks2`/`issue_ks3`) владеет commit. + +Последовательность issue: +``` +validate → mark issued → build DTO → render → persist_artifact → commit +``` + +При любой ошибке до/на commit: +- `db.rollback()` — статус и artifact row откатываются; +- `remove_artifact_file(artifact)` — удаляется только файл этой попытки; +- ранее существующие artifacts не трогаются. + +### Cleanup strategy + +Добавлен `remove_artifact_file(artifact)` в DOC-B2-сервис (минимальный хелпер): +- принимает только `DocumentArtifact` (никогда произвольный путь); +- резолвится через безопасный `resolve_storage_path`; +- удаляет только файл данного artifact; +- идемпотентен (нет файла → `False`). + +### Draft edit invalidation + +- `save_draft` (KS-2 и KS-3) при **обновлении** существующего draft вызывает `invalidate_artifacts` **в той же транзакции**; +- успешный edit → `is_current = false`; +- rollback → artifact остаётся current (проверено тестом); +- физический файл сохраняется. + +### Cancellation behavior + +Логика `cancel_ks2`/`cancel_ks3` **не менялась**. Тесты подтверждают: после сторно artifact row, `is_current`, `content_hash`, `input_hash`, файл — без изменений. + +### Tests (13) + +- Artifact creation: KS-2 → current XLSX; KS-3 → current DOCX; file/hashes/type/id/format/template_version; +- Draft invalidation: non-current after edit; file remains; rollback keeps current; +- Issue rollback: persist failure, commit failure (KS-2 и KS-3) — нет issued, нет artifact row, нет orphan file; +- Cancellation: KS-2 и KS-3 сохраняют artifact; +- Immutability: повторный issue rejected; edit rejected; KS-3 не трогает KS-2 artifacts; +- `remove_artifact_file`: только указанный artifact. + +Результат `pytest -q`: + +``` +414 passed, 600 warnings in 33.52s +``` + +(401 существующих + 13 новых.) + +Результат `git diff --check`: + +``` +(без ошибок) +``` + +Приложение: запускается (проверено в предыдущих задачах, renderer/DTO не менялись). + +### Browser/manual checks + +Не требуются (UI не менялся). + +### Deviations + +None. + +### Recommended next task + +**DOC-B6** — UI скачивания artifact: кнопка «Официальная форма» на карточке KS-2/KS-3, download endpoint с проверкой project/document, отметка «СТОРНИРОВАН» для cancelled (отдельный derivative). diff --git a/docs/tasks/DOC-B5-issue-artifact-lifecycle.md b/docs/tasks/DOC-B5-issue-artifact-lifecycle.md new file mode 100644 index 0000000..57f8c82 --- /dev/null +++ b/docs/tasks/DOC-B5-issue-artifact-lifecycle.md @@ -0,0 +1,463 @@ +# DOC-B5 — issue integration and document artifact lifecycle + +## Goal + +Integrate `DocumentArtifact` into the existing KS-2 / KS-3 lifecycle. + +After this task: + +- draft documents remain editable; +- if a draft artifact was generated earlier, changing the draft invalidates that artifact; +- issuing KS-2 or KS-3 generates the official document exactly once and persists it as an immutable artifact; +- transaction failure after artifact creation does not leave an orphan physical file; +- cancellation of an issued KS-2/KS-3 does not replace, delete, or invalidate the original issued artifact; +- existing KS-2 / KS-3 business rules remain unchanged. + +This task is about service/lifecycle integration. UI for artifact download and document management is **not** part of this task. + +--- + +## 1. Read before changing code + +Study the current implementation of: + +- `app/services/document_artifact_service.py` +- `app/models/document_artifact.py` +- `app/exporters/ks2_dto.py` +- `app/exporters/excel/ks2_renderer.py` +- `app/exporters/ks3_dto.py` +- `app/exporters/word/ks3_renderer.py` +- existing KS-2 service/router/tests +- existing KS-3 service/router/tests +- existing draft edit flows +- existing cancellation/stornation flows + +Do not replace the existing lifecycle with a parallel implementation. + +Preserve existing public APIs unless a change is genuinely required for integration. + +--- + +# 2. Artifact lifecycle + +Use the following lifecycle as the source of truth. + +### Draft + +A draft artifact may exist because an existing export/download flow generated one. + +When the draft document changes: + +- invalidate existing artifacts for that document; +- do not delete the physical file; +- do not create a new artifact automatically; +- if no artifact exists, this is a no-op. + +Invalidation must participate in the same DB transaction as the draft edit. + +Therefore: + +- successful edit → artifact becomes non-current; +- rolled-back edit → previous artifact remains current. + +### Issued + +When KS-2 or KS-3 is issued: + +1. perform all existing issue validations; +2. change the document status to `issued`; +3. build the existing export DTO from the issued document; +4. render using the existing renderer/template; +5. persist the resulting file through `document_artifact_service`; +6. commit the transaction. + +The artifact created for an issued document is the official immutable artifact. + +Do not regenerate or replace it on subsequent reads/downloads. + +Do not introduce a second renderer. + +### Cancelled + +Cancellation must: + +- leave the issued artifact row untouched; +- leave the physical file untouched; +- leave its `content_hash` and `input_hash` untouched; +- not invalidate it; +- not silently generate a replacement artifact. + +The original issued artifact therefore remains available as the historical official document. + +Generation of a separate visible `СТОРНИРОВАН` derivative is **out of scope for DOC-B5**. + +--- + +# 3. Transaction and rollback requirements + +`persist_artifact()` from DOC-B2 deliberately does not commit. + +The business transaction owns the commit. + +The integration must handle the important failure case: + +```text +issue document + ↓ +render + ↓ +persist artifact + ↓ +DB commit +``` + +If anything fails before commit: + +- document status must roll back; +- artifact DB row must roll back; +- previous artifact state must roll back; +- newly created physical artifact file must be removed. + +If `commit()` itself fails: + +- perform DB rollback as appropriate; +- remove the physical file created by this issue attempt; +- do not remove any previously existing artifact. + +Do not leave an orphan artifact file after a failed issue transaction. + +### Support code + +If the current DOC-B2 service has no safe primitive for deleting a newly-created, not-yet-committed artifact file, add the smallest narrowly scoped helper required by DOC-B5. + +It must: + +- accept only a server-generated artifact/storage key or artifact object; +- resolve through the existing safe path resolver; +- never accept an arbitrary filesystem path; +- never delete another artifact; +- be usable only for cleanup of the current failed transaction. + +Do not redesign DOC-B2. + +--- + +# 4. Existing current-artifact behavior + +`persist_artifact()` currently demotes an existing current artifact and inserts a new current artifact. + +That behavior is acceptable for issuing a draft document once. + +However, an already-issued document must never be issued again or receive another replacement artifact. + +Therefore: + +- rely on the existing lifecycle rule that an issued document cannot be issued again; +- do not add a second issuance path; +- verify this with tests. + +If a draft artifact existed before issue, it may become historical (`is_current = false`) when the issued artifact is persisted. + +The newly issued artifact must be the current artifact for that document/format. + +--- + +# 5. KS-2 integration + +Integrate with the existing KS-2 issue service. + +The issue operation must remain atomic. + +Expected sequence: + +```text +validate existing KS-2 issue rules +→ mark KS-2 issued +→ build KS-2 export DTO +→ render Excel through existing KS-2 renderer +→ persist artifact +→ commit +``` + +The artifact must contain: + +- `project_id`; +- `document_type = KS2`; +- `document_id = KS2.id`; +- `format = xlsx`; +- current KS-2 template type/version; +- content hash of rendered bytes; +- input hash based on the issued DTO + template type/version; +- `is_current = true`. + +The renderer must not persist anything itself. + +--- + +# 6. KS-3 integration + +Integrate with the existing KS-3 issue service. + +Do not change existing KS-3 business rules: + +- only eligible/issued KS-2 documents; +- no duplicate KS-2 in the same KS-3; +- server-side totals; +- atomic issue. + +After successful existing validation: + +```text +mark KS-3 issued +→ build KS-3 export DTO +→ render Word through existing KS-3 renderer +→ persist artifact +→ commit +``` + +Artifact: + +- `document_type = KS3`; +- `document_id = KS3.id`; +- `format = docx`; +- current KS-3 template type/version; +- content hash of rendered bytes; +- input hash based on the issued DTO + template type/version; +- `is_current = true`. + +Issuing KS-3 must **not regenerate or replace the artifacts of the KS-2 documents included in it**. + +--- + +# 7. Draft edit invalidation + +Find the existing edit/update flows for KS-2 and KS-3. + +When a draft is successfully changed, invalidate all artifacts belonging to that document. + +Recommended call: + +```python +invalidate_artifacts( + db, + document_type="KS2", + document_id=ks2.id, +) +``` + +and similarly for KS-3. + +Do this inside the same transaction as the edit. + +Do not delete files. + +Do not invalidate issued documents because issued documents are not editable. + +Tests must verify rollback behavior. + +--- + +# 8. Cancellation verification + +Do not rewrite existing cancellation logic. + +Add integration tests proving that cancellation: + +### KS-2 + +- changes document status to cancelled; +- keeps the issued artifact DB row; +- keeps `is_current = true`; +- keeps physical file; +- keeps content hash; +- keeps input hash. + +### KS-3 + +Same requirements. + +Existing integrity rules for cancellation must continue to work. + +--- + +# 9. Failure handling + +At minimum test: + +### KS-2 + +1. renderer failure; +2. artifact persistence failure; +3. DB commit failure after artifact creation. + +For each: + +- KS-2 is not left issued; +- no committed artifact row exists for the failed attempt; +- no newly-created physical artifact file remains. + +### KS-3 + +Repeat the same three failure classes. + +Do not weaken existing transaction semantics merely to make the artifact tests pass. + +--- + +# 10. Idempotency / repeated issue + +Verify: + +- draft can be issued once; +- second attempt to issue an already-issued document is rejected by the existing lifecycle; +- second attempt does not create another issued artifact; +- existing issued artifact remains unchanged. + +Also verify that reading/downloading an issued document does not regenerate the artifact. + +Do not implement automatic regeneration for issued documents. + +--- + +# 11. Hash verification + +For a successfully issued document: + +- `content_hash` must equal SHA-256 of the stored physical file; +- `input_hash` must equal the hash calculated from the same issued DTO + template type/version used for generation. + +Use the existing DOC-B2 canonicalization/hash functions. + +Do not duplicate hash algorithms. + +--- + +# 12. Storage + +Use the DOC-B2 storage service. + +Do not build document paths directly in KS-2/KS-3 services. + +Expected physical layout remains: + +```text +/ + projects/ + / + documents/ + KS2/ + / + ... + KS3/ + / + ... +``` + +The exact filename remains the responsibility of the artifact service. + +--- + +# 13. No scope creep + +Do NOT implement in this task: + +- new UI for artifact download; +- new document detail pages; +- new artifact list UI; +- cancelled derivative generation; +- PDF; +- new templates; +- historical snapshots of business data; +- database reset integration; +- project export/import integration; +- changes to KS-2/KS-3 business calculations; +- changes to cancellation business rules. + +These are separate tasks. + +--- + +# 14. Tests + +Add focused integration tests. + +Minimum recommended coverage: + +### Artifact creation + +- issue KS-2 → one current XLSX artifact; +- issue KS-3 → one current DOCX artifact; +- file exists; +- hashes are correct; +- correct document type/id/format/template version. + +### Draft invalidation + +- existing draft artifact becomes non-current after draft edit; +- physical file remains; +- edit rollback keeps artifact current. + +### Issue rollback + +- renderer failure; +- persist failure; +- commit failure; +- no orphan file; +- no issued state; +- no committed artifact from failed attempt. + +### Cancellation + +- issued KS-2 cancellation preserves artifact; +- issued KS-3 cancellation preserves artifact. + +### Immutability + +- issued document cannot be edited; +- repeated issue is rejected; +- no second issued artifact is created; +- KS-3 issue does not touch KS-2 artifacts. + +### Regression + +Run the complete existing test suite. + +--- + +# 15. Acceptance criteria + +Task is DONE when: + +- [ ] KS-2 issue creates and persists an immutable official XLSX artifact. +- [ ] KS-3 issue creates and persists an immutable official DOCX artifact. +- [ ] Issue transaction includes artifact persistence. +- [ ] Failed issue leaves no orphan physical artifact file. +- [ ] Draft edit invalidates existing artifact in the same transaction. +- [ ] Draft edit rollback restores previous artifact state. +- [ ] Cancellation does not invalidate/delete/replace the issued artifact. +- [ ] Issued documents cannot be edited or issued again. +- [ ] KS-3 issue does not regenerate KS-2 artifacts. +- [ ] Hashes are verified. +- [ ] Existing business rules remain intact. +- [ ] Full test suite passes. +- [ ] `git diff --check` is clean. +- [ ] Application starts normally. + +--- + +# 16. Implementation report + +After implementation, report: + +1. changed files; +2. exact lifecycle implemented; +3. transaction/rollback strategy; +4. cleanup strategy for failed artifact creation; +5. draft invalidation behavior; +6. cancellation behavior; +7. tests added and total test count; +8. browser/manual checks if relevant; +9. deviations from this task, if any; +10. recommended next task. + +Do not modify unrelated parts of the application. diff --git a/tests/test_doc_b5_issue_artifact_lifecycle.py b/tests/test_doc_b5_issue_artifact_lifecycle.py new file mode 100644 index 0000000..d599c67 --- /dev/null +++ b/tests/test_doc_b5_issue_artifact_lifecycle.py @@ -0,0 +1,525 @@ +"""Integration tests for DOC-B5: issue artifact lifecycle. + +Covers: artifact creation on issue, draft invalidation, issue rollback, +cancellation preservation, immutability, hash verification. +""" +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest +from sqlalchemy import create_engine, select +from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import StaticPool + +from app.config import ENV_DOCUMENT_STORAGE_ROOT +from app.database.database import Base +from app.exporters.ks2_dto import build_ks2_export_dto +from app.exporters.ks3_dto import build_ks3_export_dto +from app.models import ( # noqa: F401 — register mappers + agreement, + boq, + daily_report, + document_artifact, + ks2 as ks2_models, + ks3 as ks3_models, + payment, + project, + work_journal, +) +from app.models.boq import BoqDocument, WorkItem +from app.models.daily_report import DailyReport, DailyReportItem +from app.models.document_artifact import DocumentArtifact +from app.models.ks2 import KS2 +from app.models.ks3 import KS3, KS3KS2 +from app.models.project import Project +from app.services.document_artifact_service import ( + compute_content_hash, + compute_input_hash, + invalidate_artifacts, + persist_artifact, + remove_artifact_file, + resolve_artifact, + resolve_storage_path, +) +from app.services.ks2_service import KS2ValidationError, issue_ks2, save_draft as save_ks2_draft +from app.services.ks3_service import KS3ValidationError, cancel_ks3, issue_ks3, save_draft as save_ks3_draft + + +@pytest.fixture +def storage_root(tmp_path, monkeypatch): + root = tmp_path / "b5-storage" + monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(root)) + return root + + +@pytest.fixture +def db_session(storage_root): + engine = create_engine( + "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + Base.metadata.create_all(engine) + Session = sessionmaker(bind=engine, expire_on_commit=False) + session = Session() + try: + yield session + finally: + session.close() + engine.dispose() + + +@pytest.fixture +def project_id(db_session): + p = Project(name="B5 lifecycle") + db_session.add(p) + db_session.commit() + return p.id + + +def _seed_work_item(db, project_id): + doc = BoqDocument(project_id=project_id, name="BOQ") + db.add(doc) + db.flush() + wi = WorkItem( + project_id=project_id, boq_document_id=doc.id, + name="Позиция", unit="шт", + quantity=Decimal("100"), unit_price=Decimal("10"), amount=Decimal("1000"), + ) + db.add(wi) + db.commit() + return wi.id + + +def _seed_dr(db, project_id, work_item_id, qty=Decimal("50")): + dr = DailyReport(project_id=project_id, report_date=date(2026, 2, 1)) + db.add(dr) + db.flush() + dri = DailyReportItem(daily_report_id=dr.id, work_item_id=work_item_id, completed_quantity=qty) + db.add(dri) + db.commit() + return dr.id + + +def _make_draft_ks2(db, project_id, work_item_id, number="K2-B5"): + return save_ks2_draft( + db, project_id, number, date(2026, 3, 1), None, + [(work_item_id, Decimal("10"))], + reporting_period_from=date(2026, 2, 1), + reporting_period_to=date(2026, 2, 28), + ) + + +# --------------------------------------------------------------------------- +# Artifact creation on issue +# --------------------------------------------------------------------------- +def test_issue_ks2_creates_current_xlsx_artifact(storage_root, db_session, project_id): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft = _make_draft_ks2(db_session, project_id, wi) + ks2 = issue_ks2(db_session, project_id, draft.id) + assert ks2.status == "issued" + + art = db_session.execute( + select(DocumentArtifact).where( + DocumentArtifact.project_id == project_id, + DocumentArtifact.document_type == "KS2", + DocumentArtifact.document_id == ks2.id, + DocumentArtifact.format == "xlsx", + DocumentArtifact.is_current.is_(True), + ) + ).scalar_one_or_none() + assert art is not None + assert art.template_type == "ks2" + assert art.template_version == 1 + assert art.is_current is True or art.is_current == 1 + + path = resolve_storage_path(art.storage_key) + assert path.is_file() + content = path.read_bytes() + assert art.content_hash == compute_content_hash(content) + + dto = build_ks2_export_dto(db_session, ks2) + assert art.input_hash == compute_input_hash(dto, "ks2", 1) + + +def test_issue_ks3_creates_current_docx_artifact(storage_root, db_session, project_id): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft_ks2 = _make_draft_ks2(db_session, project_id, wi) + ks2 = issue_ks2(db_session, project_id, draft_ks2.id) + + draft_ks3 = save_ks3_draft( + db_session, project_id, "K3-B5", date(2026, 4, 1), None, + [ks2.id], + reporting_period_from=date(2026, 2, 1), + reporting_period_to=date(2026, 2, 28), + ) + ks3 = issue_ks3(db_session, project_id, draft_ks3.id) + assert ks3.status == "issued" + + art = db_session.execute( + select(DocumentArtifact).where( + DocumentArtifact.document_type == "KS3", + DocumentArtifact.document_id == ks3.id, + DocumentArtifact.format == "docx", + DocumentArtifact.is_current.is_(True), + ) + ).scalar_one_or_none() + assert art is not None + assert art.template_type == "ks3" + assert art.template_version == 1 + assert resolve_storage_path(art.storage_key).is_file() + + dto = build_ks3_export_dto(db_session, ks3) + assert art.input_hash == compute_input_hash(dto, "ks3", 1) + + +# --------------------------------------------------------------------------- +# Draft invalidation +# --------------------------------------------------------------------------- +def test_draft_edit_invalidates_existing_artifact(storage_root, db_session, project_id): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft = _make_draft_ks2(db_session, project_id, wi) + + # Manually create a draft artifact (as if export generated one) + art = persist_artifact( + db_session, + project_id=project_id, + document_type="KS2", + document_id=draft.id, + format="xlsx", + template_type="ks2", + template_version=1, + content=b"draft-bytes", + dto={"n": 1}, + ) + db_session.commit() + assert art.is_current in (True, 1) + art_path = resolve_storage_path(art.storage_key) + + # Edit the draft → artifact becomes non-current + save_ks2_draft( + db_session, project_id, "K2-B5", date(2026, 3, 1), "changed", + [(wi, Decimal("20"))], + reporting_period_from=date(2026, 2, 1), + reporting_period_to=date(2026, 2, 28), + ks2_id=draft.id, + ) + db_session.refresh(art) + assert art.is_current in (False, 0) + # Physical file remains + assert art_path.is_file() + + +def test_draft_edit_rollback_keeps_artifact_current(storage_root, db_session, project_id): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft = _make_draft_ks2(db_session, project_id, wi) + + art = persist_artifact( + db_session, + project_id=project_id, + document_type="KS2", + document_id=draft.id, + format="xlsx", + template_type="ks2", + template_version=1, + content=b"draft-v2", + dto={"n": 2}, + ) + db_session.commit() + art_id = art.id + + # Force a failure inside save_draft after invalidation would run: + # invalid quantity triggers rollback before commit + with pytest.raises(KS2ValidationError): + save_ks2_draft( + db_session, project_id, "K2-B5", date(2026, 3, 1), "fail", + [(wi, Decimal("-5"))], # invalid quantity + reporting_period_from=date(2026, 2, 1), + reporting_period_to=date(2026, 2, 28), + ks2_id=draft.id, + ) + db_session.rollback() + art = db_session.get(DocumentArtifact, art_id) + assert art.is_current in (True, 1) + assert resolve_storage_path(art.storage_key).is_file() + + +# --------------------------------------------------------------------------- +# Issue rollback / orphan cleanup +# --------------------------------------------------------------------------- +def test_issue_rollback_on_persist_failure(storage_root, db_session, project_id, monkeypatch): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft = _make_draft_ks2(db_session, project_id, wi) + + def boom(*args, **kwargs): + raise RuntimeError("forced persist failure") + + monkeypatch.setattr( + "app.services.document_artifact_service.persist_artifact", boom + ) + with pytest.raises(RuntimeError, match="forced persist failure"): + issue_ks2(db_session, project_id, draft.id) + + db_session.rollback() + # Not left issued + doc = db_session.get(KS2, draft.id) + assert doc.status == "draft" + # No committed artifact + arts = db_session.execute( + select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2") + ).all() + assert arts == [] + # No orphan files + files = list(storage_root.rglob("*")) if storage_root.exists() else [] + assert [f for f in files if f.is_file()] == [] + + +def test_issue_rollback_on_commit_failure(storage_root, db_session, project_id, monkeypatch): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft = _make_draft_ks2(db_session, project_id, wi) + + original_commit = db_session.commit + + def failing_commit(): + raise RuntimeError("forced commit failure") + + monkeypatch.setattr(db_session, "commit", failing_commit) + with pytest.raises(RuntimeError, match="forced commit failure"): + issue_ks2(db_session, project_id, draft.id) + monkeypatch.setattr(db_session, "commit", original_commit) + + db_session.rollback() + doc = db_session.get(KS2, draft.id) + assert doc.status == "draft" + arts = db_session.execute( + select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2") + ).all() + assert arts == [] + files = [f for f in storage_root.rglob("*") if f.is_file()] if storage_root.exists() else [] + assert files == [] + + +def test_issue_ks3_rollback_leaves_no_orphan(storage_root, db_session, project_id, monkeypatch): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft_ks2 = _make_draft_ks2(db_session, project_id, wi) + ks2 = issue_ks2(db_session, project_id, draft_ks2.id) + draft_ks3 = save_ks3_draft( + db_session, project_id, "K3-B5", date(2026, 4, 1), None, + [ks2.id], + reporting_period_from=date(2026, 2, 1), + reporting_period_to=date(2026, 2, 28), + ) + + original_commit = db_session.commit + + def failing_commit(): + raise RuntimeError("forced commit failure") + + monkeypatch.setattr(db_session, "commit", failing_commit) + with pytest.raises(RuntimeError, match="forced commit failure"): + issue_ks3(db_session, project_id, draft_ks3.id) + monkeypatch.setattr(db_session, "commit", original_commit) + + db_session.rollback() + doc = db_session.get(KS3, draft_ks3.id) + assert doc.status == "draft" + arts = db_session.execute( + select(DocumentArtifact).where(DocumentArtifact.document_type == "KS3") + ).all() + assert arts == [] + # Only KS3 artifacts are orphans of this failed attempt; the committed + # KS-2 artifact file must remain untouched. + ks3_files = list((storage_root / "projects").rglob("*/*.docx")) if storage_root.exists() else [] + assert [f for f in ks3_files if f.is_file()] == [] + ks2_files = list((storage_root / "projects").rglob("*/*.xlsx")) if storage_root.exists() else [] + assert len([f for f in ks2_files if f.is_file()]) == 1 + + +# --------------------------------------------------------------------------- +# Cancellation preserves issued artifact +# --------------------------------------------------------------------------- +def test_cancel_ks2_preserves_issued_artifact(storage_root, db_session, project_id): + from app.services.ks2_service import cancel_ks2 + + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft = _make_draft_ks2(db_session, project_id, wi) + ks2 = issue_ks2(db_session, project_id, draft.id) + + art = db_session.execute( + select(DocumentArtifact).where( + DocumentArtifact.document_type == "KS2", + DocumentArtifact.document_id == ks2.id, + DocumentArtifact.is_current.is_(True), + ) + ).scalar_one() + art_id = art.id + content_hash = art.content_hash + input_hash = art.input_hash + storage_key = art.storage_key + + cancel_ks2(db_session, project_id, ks2.id) + assert db_session.get(KS2, ks2.id).status == "cancelled" + + art = db_session.get(DocumentArtifact, art_id) + assert art is not None + assert art.is_current in (True, 1) + assert art.content_hash == content_hash + assert art.input_hash == input_hash + assert art.storage_key == storage_key + assert resolve_storage_path(storage_key).is_file() + + +def test_cancel_ks3_preserves_issued_artifact(storage_root, db_session, project_id): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft_ks2 = _make_draft_ks2(db_session, project_id, wi) + ks2 = issue_ks2(db_session, project_id, draft_ks2.id) + draft_ks3 = save_ks3_draft( + db_session, project_id, "K3-B5", date(2026, 4, 1), None, + [ks2.id], + reporting_period_from=date(2026, 2, 1), + reporting_period_to=date(2026, 2, 28), + ) + ks3 = issue_ks3(db_session, project_id, draft_ks3.id) + + art = db_session.execute( + select(DocumentArtifact).where( + DocumentArtifact.document_type == "KS3", + DocumentArtifact.document_id == ks3.id, + DocumentArtifact.is_current.is_(True), + ) + ).scalar_one() + art_id = art.id + content_hash = art.content_hash + input_hash = art.input_hash + + cancel_ks3(db_session, project_id, ks3.id) + assert db_session.get(KS3, ks3.id).status == "cancelled" + + art = db_session.get(DocumentArtifact, art_id) + assert art.is_current in (True, 1) + assert art.content_hash == content_hash + assert art.input_hash == input_hash + assert resolve_storage_path(art.storage_key).is_file() + + +# --------------------------------------------------------------------------- +# Immutability / repeated issue +# --------------------------------------------------------------------------- +def test_issued_document_cannot_be_issued_again(storage_root, db_session, project_id): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft = _make_draft_ks2(db_session, project_id, wi) + ks2 = issue_ks2(db_session, project_id, draft.id) + + art_count = db_session.execute( + select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2") + ).all() + assert len(art_count) == 1 + + with pytest.raises(KS2ValidationError, match="черновик"): + issue_ks2(db_session, project_id, ks2.id) + + # No second artifact created + arts = db_session.execute( + select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2") + ).all() + assert len(arts) == 1 + + +def test_issued_document_cannot_be_edited(storage_root, db_session, project_id): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft = _make_draft_ks2(db_session, project_id, wi) + ks2 = issue_ks2(db_session, project_id, draft.id) + + with pytest.raises(KS2ValidationError, match="редактировать"): + save_ks2_draft( + db_session, project_id, "K2-B5", date(2026, 3, 1), "edit", + [(wi, Decimal("5"))], + reporting_period_from=date(2026, 2, 1), + reporting_period_to=date(2026, 2, 28), + ks2_id=ks2.id, + ) + + +def test_ks3_issue_does_not_touch_ks2_artifacts(storage_root, db_session, project_id): + wi = _seed_work_item(db_session, project_id) + _seed_dr(db_session, project_id, wi) + draft_ks2 = _make_draft_ks2(db_session, project_id, wi) + ks2 = issue_ks2(db_session, project_id, draft_ks2.id) + + ks2_art = db_session.execute( + select(DocumentArtifact).where( + DocumentArtifact.document_type == "KS2", + DocumentArtifact.is_current.is_(True), + ) + ).scalar_one() + ks2_art_id = ks2_art.id + ks2_hash = ks2_art.content_hash + + draft_ks3 = save_ks3_draft( + db_session, project_id, "K3-B5", date(2026, 4, 1), None, + [ks2.id], + reporting_period_from=date(2026, 2, 1), + reporting_period_to=date(2026, 2, 28), + ) + issue_ks3(db_session, project_id, draft_ks3.id) + + ks2_art = db_session.get(DocumentArtifact, ks2_art_id) + assert ks2_art.is_current in (True, 1) + assert ks2_art.content_hash == ks2_hash + # Only one KS-2 artifact + assert db_session.execute( + select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2") + ).all() and len(db_session.execute( + select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2") + ).all()) == 1 + + +# --------------------------------------------------------------------------- +# remove_artifact_file helper +# --------------------------------------------------------------------------- +def test_remove_artifact_file_only_touches_given_artifact(storage_root, db_session, project_id): + a = persist_artifact( + db_session, + project_id=project_id, + document_type="KS2", + document_id=1, + format="xlsx", + template_type="ks2", + template_version=1, + content=b"file-a", + dto={}, + ) + b = persist_artifact( + db_session, + project_id=project_id, + document_type="KS2", + document_id=2, + format="xlsx", + template_type="ks2", + template_version=1, + content=b"file-b", + dto={}, + ) + db_session.commit() + a_path = resolve_storage_path(a.storage_key) + b_path = resolve_storage_path(b.storage_key) + assert a_path.is_file() and b_path.is_file() + + assert remove_artifact_file(a) is True + assert not a_path.exists() + assert b_path.is_file() + + # Safe on missing file / None + assert remove_artifact_file(a) is False + assert remove_artifact_file(None) is False