diff --git a/app/exporters/project_export.py b/app/exporters/project_export.py new file mode 100644 index 0000000..fcba40b --- /dev/null +++ b/app/exporters/project_export.py @@ -0,0 +1,656 @@ +"""Machine-readable project export as a portable ZIP archive.""" +from __future__ import annotations + +import hashlib +import io +import json +import re +import zipfile +from datetime import date, datetime +from decimal import Decimal +from typing import Any, Callable, Iterable + +from sqlalchemy.orm import Session, joinedload + +from app.models.agreement import Agreement, AgreementItem +from app.models.boq import BoqDocument, Section, System, WorkItem +from app.models.daily_report import DailyReport, DailyReportItem +from app.models.ks2 import KS2, KS2Item, KS2ItemSource +from app.models.ks3 import KS3, KS3KS2 +from app.models.payment import Payment, PaymentAllocation +from app.models.project import Project + +FORMAT_NAME = "work_volume_tracker" +FORMAT_VERSION = 1 + +REQUIRED_FILES = ( + "manifest.json", + "project.json", + "boq_documents.json", + "systems.json", + "sections.json", + "work_items.json", + "agreements.json", + "agreement_items.json", + "daily_reports.json", + "daily_report_items.json", + "ks2.json", + "ks2_items.json", + "ks2_item_sources.json", + "ks3.json", + "ks3_ks2.json", + "payments.json", + "payment_allocations.json", + "checksums.json", +) + + +class ProjectExportError(RuntimeError): + """Raised when the project cannot be exported safely.""" + + +def _iso(value: Any) -> Any: + if value is None: + return None + if isinstance(value, datetime): + return value.isoformat() + if isinstance(value, date): + return value.isoformat() + return value + + +def _dec(value: Any) -> Any: + if value is None: + return None + text = format(Decimal(str(value)), "f") + if "." in text: + text = text.rstrip("0").rstrip(".") + return text + + +def _export_key(kind: str, index: int) -> str: + return f"{kind}:{index:08d}" + + +def _safe_archive_filename(project_name: str, when: date | datetime | None = None) -> str: + name = (project_name or "проект").strip() or "проект" + name = re.sub(r'[<>:"/\\|?*\r\n\t]', "_", name) + name = re.sub(r"\s+", "_", name).strip("._") or "проект" + day = (when or datetime.now()).strftime("%Y-%m-%d") + return f"Проект_{name}_{day}.wvt.zip" + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _dumps(payload: Any) -> bytes: + return json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=False).encode("utf-8") + + +def collect_project(db: Session, project_id: int) -> dict[str, Any]: + """Load the full logical project graph and return JSON-ready records.""" + project = db.query(Project).filter(Project.id == project_id).first() + if project is None: + raise ProjectExportError("Проект не найден") + + boq_docs = ( + db.query(BoqDocument) + .filter(BoqDocument.project_id == project_id) + .order_by(BoqDocument.id) + .all() + ) + systems = ( + db.query(System).filter(System.project_id == project_id).order_by(System.id).all() + ) + system_ids = [s.id for s in systems] + sections = ( + db.query(Section) + .filter(Section.system_id.in_(system_ids) if system_ids else False) + .order_by(Section.id) + .all() + ) + work_items = ( + db.query(WorkItem).filter(WorkItem.project_id == project_id).order_by(WorkItem.id).all() + ) + agreements = ( + db.query(Agreement).filter(Agreement.project_id == project_id).order_by(Agreement.id).all() + ) + agreement_ids = [a.id for a in agreements] + agreement_items = ( + db.query(AgreementItem) + .filter(AgreementItem.agreement_id.in_(agreement_ids) if agreement_ids else False) + .order_by(AgreementItem.id) + .all() + ) + daily_reports = ( + db.query(DailyReport) + .filter(DailyReport.project_id == project_id) + .order_by(DailyReport.id) + .all() + ) + daily_report_ids = [d.id for d in daily_reports] + daily_report_items = ( + db.query(DailyReportItem) + .filter( + DailyReportItem.daily_report_id.in_(daily_report_ids) + if daily_report_ids + else False + ) + .order_by(DailyReportItem.id) + .all() + ) + ks2_docs = db.query(KS2).filter(KS2.project_id == project_id).order_by(KS2.id).all() + ks2_ids = [k.id for k in ks2_docs] + ks2_items = ( + db.query(KS2Item) + .filter(KS2Item.ks2_id.in_(ks2_ids) if ks2_ids else False) + .order_by(KS2Item.id) + .all() + ) + ks2_item_ids = [i.id for i in ks2_items] + ks2_item_sources = ( + db.query(KS2ItemSource) + .filter(KS2ItemSource.ks2_item_id.in_(ks2_item_ids) if ks2_item_ids else False) + .order_by(KS2ItemSource.id) + .all() + ) + ks3_docs = db.query(KS3).filter(KS3.project_id == project_id).order_by(KS3.id).all() + ks3_ids = [k.id for k in ks3_docs] + ks3_ks2 = ( + db.query(KS3KS2) + .filter(KS3KS2.ks3_id.in_(ks3_ids) if ks3_ids else False) + .order_by(KS3KS2.id) + .all() + ) + payments = ( + db.query(Payment).filter(Payment.project_id == project_id).order_by(Payment.id).all() + ) + payment_ids = [p.id for p in payments] + payment_allocations = ( + db.query(PaymentAllocation) + .filter(PaymentAllocation.payment_id.in_(payment_ids) if payment_ids else False) + .order_by(PaymentAllocation.id) + .all() + ) + + return { + "project": project, + "boq_documents": boq_docs, + "systems": systems, + "sections": sections, + "work_items": work_items, + "agreements": agreements, + "agreement_items": agreement_items, + "daily_reports": daily_reports, + "daily_report_items": daily_report_items, + "ks2": ks2_docs, + "ks2_items": ks2_items, + "ks2_item_sources": ks2_item_sources, + "ks3": ks3_docs, + "ks3_ks2": ks3_ks2, + "payments": payments, + "payment_allocations": payment_allocations, + } + + +def _validate_graph(graph: dict[str, Any]) -> None: + """Refuse to export a project with broken internal references.""" + project = graph["project"] + pid = project.id + + doc_ids = {d.id for d in graph["boq_documents"]} + system_ids = {s.id for s in graph["systems"]} + section_ids = {s.id for s in graph["sections"]} + work_item_ids = {w.id for w in graph["work_items"]} + agreement_ids = {a.id for a in graph["agreements"]} + report_ids = {r.id for r in graph["daily_reports"]} + report_item_ids = {i.id for i in graph["daily_report_items"]} + ks2_ids = {k.id for k in graph["ks2"]} + ks2_item_ids = {i.id for i in graph["ks2_items"]} + ks3_ids = {k.id for k in graph["ks3"]} + payment_ids = {p.id for p in graph["payments"]} + + errors: list[str] = [] + + for d in graph["boq_documents"]: + if d.project_id != pid: + errors.append(f"boq_document:{d.id} belongs to another project") + if d.agreement_id is not None and d.agreement_id not in agreement_ids: + errors.append(f"boq_document:{d.id} references missing agreement") + for s in graph["systems"]: + if s.project_id != pid: + errors.append(f"system:{s.id} belongs to another project") + for sec in graph["sections"]: + if sec.system_id not in system_ids: + errors.append(f"section:{sec.id} references missing system") + for w in graph["work_items"]: + if w.project_id != pid: + errors.append(f"work_item:{w.id} belongs to another project") + if w.boq_document_id is not None and w.boq_document_id not in doc_ids: + errors.append(f"work_item:{w.id} references missing boq_document") + if w.system_id is not None and w.system_id not in system_ids: + errors.append(f"work_item:{w.id} references missing system") + if w.section_id is not None and w.section_id not in section_ids: + errors.append(f"work_item:{w.id} references missing section") + for a in graph["agreements"]: + if a.project_id != pid: + errors.append(f"agreement:{a.id} belongs to another project") + if a.boq_document_id is not None and a.boq_document_id not in doc_ids: + errors.append(f"agreement:{a.id} references missing boq_document") + for i in graph["agreement_items"]: + if i.agreement_id not in agreement_ids: + errors.append(f"agreement_item:{i.id} references missing agreement") + if i.work_item_id not in work_item_ids: + errors.append(f"agreement_item:{i.id} references missing work_item") + for label, value in ( + ("source_boq_document_id", i.source_boq_document_id), + ("source_system_id", i.source_system_id), + ("source_section_id", i.source_section_id), + ): + if value is None: + continue + pool = {"source_boq_document_id": doc_ids, "source_system_id": system_ids, "source_section_id": section_ids}[label] + if value not in pool: + errors.append(f"agreement_item:{i.id} references missing {label}") + for r in graph["daily_reports"]: + if r.project_id != pid: + errors.append(f"daily_report:{r.id} belongs to another project") + if r.system_id is not None and r.system_id not in system_ids: + errors.append(f"daily_report:{r.id} references missing system") + for i in graph["daily_report_items"]: + if i.daily_report_id not in report_ids: + errors.append(f"daily_report_item:{i.id} references missing daily_report") + if i.work_item_id not in work_item_ids: + errors.append(f"daily_report_item:{i.id} references missing work_item") + for k in graph["ks2"]: + if k.project_id != pid: + errors.append(f"ks2:{k.id} belongs to another project") + for i in graph["ks2_items"]: + if i.ks2_id not in ks2_ids: + errors.append(f"ks2_item:{i.id} references missing ks2") + if i.work_item_id not in work_item_ids: + errors.append(f"ks2_item:{i.id} references missing work_item") + for s in graph["ks2_item_sources"]: + if s.ks2_item_id not in ks2_item_ids: + errors.append(f"ks2_item_source:{s.id} references missing ks2_item") + if s.daily_report_item_id not in report_item_ids: + errors.append(f"ks2_item_source:{s.id} references missing daily_report_item") + for k in graph["ks3"]: + if k.project_id != pid: + errors.append(f"ks3:{k.id} belongs to another project") + for link in graph["ks3_ks2"]: + if link.ks3_id not in ks3_ids: + errors.append(f"ks3_ks2:{link.id} references missing ks3") + if link.ks2_id not in ks2_ids: + errors.append(f"ks3_ks2:{link.id} references missing ks2") + for p in graph["payments"]: + if p.project_id != pid: + errors.append(f"payment:{p.id} belongs to another project") + for a in graph["payment_allocations"]: + if a.payment_id not in payment_ids: + errors.append(f"payment_allocation:{a.id} references missing payment") + if a.ks3_id not in ks3_ids: + errors.append(f"payment_allocation:{a.id} references missing ks3") + + if errors: + raise ProjectExportError( + "Экспорт остановлен: нарушена ссылочная целостность проекта — " + + "; ".join(errors[:10]) + ) + + +def _key_map(entities: Iterable[Any], kind: str) -> dict[int, str]: + return {e.id: _export_key(kind, idx) for idx, e in enumerate(entities, start=1)} + + +def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]: + """Convert ORM objects into JSON-ready records with export_id keys.""" + project = graph["project"] + keys = { + "boq_document": _key_map(graph["boq_documents"], "boq_document"), + "system": _key_map(graph["systems"], "system"), + "section": _key_map(graph["sections"], "section"), + "work_item": _key_map(graph["work_items"], "work_item"), + "agreement": _key_map(graph["agreements"], "agreement"), + "agreement_item": _key_map(graph["agreement_items"], "agreement_item"), + "daily_report": _key_map(graph["daily_reports"], "daily_report"), + "daily_report_item": _key_map(graph["daily_report_items"], "daily_report_item"), + "ks2": _key_map(graph["ks2"], "ks2"), + "ks2_item": _key_map(graph["ks2_items"], "ks2_item"), + "ks2_item_source": _key_map(graph["ks2_item_sources"], "ks2_item_source"), + "ks3": _key_map(graph["ks3"], "ks3"), + "ks3_ks2": _key_map(graph["ks3_ks2"], "ks3_ks2"), + "payment": _key_map(graph["payments"], "payment"), + "payment_allocation": _key_map(graph["payment_allocations"], "payment_allocation"), + } + + def ref(kind: str, value: int | None) -> str | None: + if value is None: + return None + return keys[kind].get(value) + + project_record = { + "export_id": "project:00000001", + "source_id": project.id, + "name": project.name, + "contract_number": project.contract_number, + "contract_date": _iso(project.contract_date), + "customer": project.customer, + "currency": project.currency, + "start_date": _iso(project.start_date), + "end_date": _iso(project.end_date), + "status": project.status, + "created_at": _iso(project.created_at), + "updated_at": _iso(project.updated_at), + } + + def record(kind: str, obj: Any, fields: dict[str, Any]) -> dict[str, Any]: + out = {"export_id": keys[kind][obj.id], "source_id": obj.id} + out.update(fields) + return out + + boq_documents = [ + record( + "boq_document", + d, + { + "agreement_export_id": ref("agreement", d.agreement_id), + "name": d.name, + "version": d.version, + "source_file": d.source_file, + "document_number": d.document_number, + "document_date": _iso(d.document_date), + "contract": d.contract, + "created_at": _iso(d.created_at), + }, + ) + for d in graph["boq_documents"] + ] + systems = [ + record( + "system", + s, + { + "code": s.code, + "name": s.name, + "sort_order": s.sort_order, + "created_at": _iso(s.created_at), + }, + ) + for s in graph["systems"] + ] + sections = [ + record( + "section", + s, + { + "system_export_id": ref("system", s.system_id), + "name": s.name, + "sort_order": s.sort_order, + "created_at": _iso(s.created_at), + }, + ) + for s in graph["sections"] + ] + work_items = [ + record( + "work_item", + w, + { + "boq_document_export_id": ref("boq_document", w.boq_document_id), + "system_export_id": ref("system", w.system_id), + "section_export_id": ref("section", w.section_id), + "source_number": w.source_number, + "name": w.name, + "model": w.model, + "manufacturer": w.manufacturer, + "unit": w.unit, + "quantity": _dec(w.quantity), + "unit_price": _dec(w.unit_price), + "amount": _dec(w.amount), + "created_at": _iso(w.created_at), + "updated_at": _iso(w.updated_at), + }, + ) + for w in graph["work_items"] + ] + agreements = [ + record( + "agreement", + a, + { + "boq_document_export_id": ref("boq_document", a.boq_document_id), + "number": a.number, + "date": _iso(a.date), + "title": a.title, + "description": a.description, + "status": a.status, + "created_at": _iso(a.created_at), + "updated_at": _iso(a.updated_at), + }, + ) + for a in graph["agreements"] + ] + agreement_items = [ + record( + "agreement_item", + i, + { + "agreement_export_id": ref("agreement", i.agreement_id), + "work_item_export_id": ref("work_item", i.work_item_id), + "change_type": i.change_type, + "quantity_delta": _dec(i.quantity_delta), + "amount_delta": _dec(i.amount_delta), + "source_row": i.source_row, + "source_number": i.source_number, + "source_name": i.source_name, + "source_model": i.source_model, + "source_manufacturer": i.source_manufacturer, + "source_unit": i.source_unit, + "source_unit_price": _dec(i.source_unit_price), + "source_boq_document_export_id": ref("boq_document", i.source_boq_document_id), + "source_system_export_id": ref("system", i.source_system_id), + "source_section_export_id": ref("section", i.source_section_id), + "created_at": _iso(i.created_at), + "updated_at": _iso(i.updated_at), + }, + ) + for i in graph["agreement_items"] + ] + daily_reports = [ + record( + "daily_report", + r, + { + "system_export_id": ref("system", r.system_id), + "report_date": _iso(r.report_date), + "notes": r.notes, + "created_at": _iso(r.created_at), + "updated_at": _iso(r.updated_at), + }, + ) + for r in graph["daily_reports"] + ] + daily_report_items = [ + record( + "daily_report_item", + i, + { + "daily_report_export_id": ref("daily_report", i.daily_report_id), + "work_item_export_id": ref("work_item", i.work_item_id), + "completed_quantity": _dec(i.completed_quantity), + }, + ) + for i in graph["daily_report_items"] + ] + ks2 = [ + record( + "ks2", + k, + { + "number": k.number, + "date": _iso(k.date), + "reporting_period_from": _iso(k.reporting_period_from), + "reporting_period_to": _iso(k.reporting_period_to), + "comment": k.comment, + "status": k.status, + "created_at": _iso(k.created_at), + "updated_at": _iso(k.updated_at), + }, + ) + for k in graph["ks2"] + ] + ks2_items = [ + record( + "ks2_item", + i, + { + "ks2_export_id": ref("ks2", i.ks2_id), + "work_item_export_id": ref("work_item", i.work_item_id), + "quantity": _dec(i.quantity), + "unit_price": _dec(i.unit_price), + "amount": _dec(i.amount), + }, + ) + for i in graph["ks2_items"] + ] + ks2_item_sources = [ + record( + "ks2_item_source", + s, + { + "ks2_item_export_id": ref("ks2_item", s.ks2_item_id), + "daily_report_item_export_id": ref("daily_report_item", s.daily_report_item_id), + "quantity": _dec(s.quantity), + }, + ) + for s in graph["ks2_item_sources"] + ] + ks3 = [ + record( + "ks3", + k, + { + "number": k.number, + "date": _iso(k.date), + "reporting_period_from": _iso(k.reporting_period_from), + "reporting_period_to": _iso(k.reporting_period_to), + "comment": k.comment, + "status": k.status, + "created_at": _iso(k.created_at), + "updated_at": _iso(k.updated_at), + }, + ) + for k in graph["ks3"] + ] + ks3_ks2 = [ + record( + "ks3_ks2", + link, + { + "ks3_export_id": ref("ks3", link.ks3_id), + "ks2_export_id": ref("ks2", link.ks2_id), + }, + ) + for link in graph["ks3_ks2"] + ] + payments = [ + record( + "payment", + p, + { + "date": _iso(p.date), + "document_number": p.document_number, + "amount": _dec(p.amount), + "currency": p.currency, + "comment": p.comment, + "status": p.status, + "created_at": _iso(p.created_at), + "updated_at": _iso(p.updated_at), + }, + ) + for p in graph["payments"] + ] + payment_allocations = [ + record( + "payment_allocation", + a, + { + "payment_export_id": ref("payment", a.payment_id), + "ks3_export_id": ref("ks3", a.ks3_id), + "amount": _dec(a.amount), + }, + ) + for a in graph["payment_allocations"] + ] + + counts = { + "boq_documents": len(boq_documents), + "systems": len(systems), + "sections": len(sections), + "work_items": len(work_items), + "agreements": len(agreements), + "agreement_items": len(agreement_items), + "daily_reports": len(daily_reports), + "daily_report_items": len(daily_report_items), + "ks2": len(ks2), + "ks2_items": len(ks2_items), + "ks2_item_sources": len(ks2_item_sources), + "ks3": len(ks3), + "ks3_ks2": len(ks3_ks2), + "payments": len(payments), + "payment_allocations": len(payment_allocations), + } + manifest = { + "format": FORMAT_NAME, + "format_version": FORMAT_VERSION, + "exported_at": datetime.now().astimezone().isoformat(timespec="seconds"), + "source_project_id": project.id, + "project_name": project.name, + "counts": counts, + } + + return { + "manifest.json": manifest, + "project.json": project_record, + "boq_documents.json": boq_documents, + "systems.json": systems, + "sections.json": sections, + "work_items.json": work_items, + "agreements.json": agreements, + "agreement_items.json": agreement_items, + "daily_reports.json": daily_reports, + "daily_report_items.json": daily_report_items, + "ks2.json": ks2, + "ks2_items.json": ks2_items, + "ks2_item_sources.json": ks2_item_sources, + "ks3.json": ks3, + "ks3_ks2.json": ks3_ks2, + "payments.json": payments, + "payment_allocations.json": payment_allocations, + } + + +def build_archive(files: dict[str, Any]) -> tuple[bytes, str]: + """Serialize payload dict to a ZIP with checksums. Returns (zip_bytes, filename).""" + parts: dict[str, bytes] = {name: _dumps(payload) for name, payload in files.items()} + checksums = {name: _sha256(data) for name, data in parts.items()} + parts["checksums.json"] = _dumps(checksums) + + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf: + for name in REQUIRED_FILES: + if name not in parts: + raise ProjectExportError(f"В архиве отсутствует обязательный файл {name}") + zf.writestr(name, parts[name]) + project_name = files.get("manifest.json", {}).get("project_name", "проект") + return buf.getvalue(), _safe_archive_filename(project_name) + + +def export_project(db: Session, project_id: int) -> tuple[bytes, str]: + """Full export pipeline. Returns (zip_bytes, filename).""" + graph = collect_project(db, project_id) + _validate_graph(graph) + files = serialize_project(graph) + return build_archive(files) diff --git a/app/exporters/project_import.py b/app/exporters/project_import.py new file mode 100644 index 0000000..1a3712b --- /dev/null +++ b/app/exporters/project_import.py @@ -0,0 +1,616 @@ +"""Validate and import a project archive produced by project_export.""" +from __future__ import annotations + +import hashlib +import io +import json +import zipfile +from datetime import date, datetime +from decimal import Decimal, InvalidOperation +from typing import Any + +from sqlalchemy.orm import Session + +from app.models.agreement import Agreement, AgreementItem +from app.models.boq import BoqDocument, Section, System, WorkItem +from app.models.daily_report import DailyReport, DailyReportItem +from app.models.ks2 import KS2, KS2Item, KS2ItemSource +from app.models.ks3 import KS3, KS3KS2 +from app.models.payment import Payment, PaymentAllocation +from app.models.project import Project +from app.exporters.project_export import ( + FORMAT_NAME, + FORMAT_VERSION, + REQUIRED_FILES, + ProjectExportError, +) + + +class ProjectImportError(ValueError): + """Archive failed validation and was not imported.""" + + +_LIST_FILES = ( + "boq_documents.json", + "systems.json", + "sections.json", + "work_items.json", + "agreements.json", + "agreement_items.json", + "daily_reports.json", + "daily_report_items.json", + "ks2.json", + "ks2_items.json", + "ks2_item_sources.json", + "ks3.json", + "ks3_ks2.json", + "payments.json", + "payment_allocations.json", +) + +_ALLOWED_AGREEMENT_STATUS = {"draft", "approved"} +_ALLOWED_AGREEMENT_CHANGE = {"increase", "decrease", "new_position"} +_ALLOWED_KS2_STATUS = {"draft", "issued", "cancelled"} +_ALLOWED_KS3_STATUS = {"draft", "issued", "cancelled"} +_ALLOWED_PAYMENT_STATUS = {"active", "cancelled"} + +_REQUIRED_FIELDS: dict[str, tuple[str, ...]] = { + "project.json": ("export_id", "name", "status"), + "boq_documents.json": ("export_id", "name"), + "systems.json": ("export_id", "name"), + "sections.json": ("export_id", "system_export_id", "name"), + "work_items.json": ("export_id", "name"), + "agreements.json": ("export_id", "number", "date", "title", "status"), + "agreement_items.json": ("export_id", "agreement_export_id", "work_item_export_id", "change_type", "quantity_delta", "amount_delta"), + "daily_reports.json": ("export_id", "report_date"), + "daily_report_items.json": ("export_id", "daily_report_export_id", "work_item_export_id", "completed_quantity"), + "ks2.json": ("export_id", "number", "date", "status"), + "ks2_items.json": ("export_id", "ks2_export_id", "work_item_export_id", "quantity", "unit_price", "amount"), + "ks2_item_sources.json": ("export_id", "ks2_item_export_id", "daily_report_item_export_id", "quantity"), + "ks3.json": ("export_id", "number", "date", "status"), + "ks3_ks2.json": ("export_id", "ks3_export_id", "ks2_export_id"), + "payments.json": ("export_id", "date", "amount", "currency", "status"), + "payment_allocations.json": ("export_id", "payment_export_id", "ks3_export_id", "amount"), +} + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _parse_date(value: Any, field: str) -> date | None: + if value is None or value == "": + return None + try: + return date.fromisoformat(str(value)[:10]) + except (ValueError, TypeError) as exc: + raise ProjectImportError(f"Поле {field}: некорректная дата {value!r}") from exc + + +def _parse_datetime(value: Any, field: str) -> datetime | None: + if value is None or value == "": + return None + try: + return datetime.fromisoformat(str(value)) + except (ValueError, TypeError) as exc: + raise ProjectImportError(f"Поле {field}: некорректное время {value!r}") from exc + + +def _parse_decimal(value: Any, field: str, *, required: bool = False) -> Decimal | None: + if value is None or value == "": + if required: + raise ProjectImportError(f"Поле {field}: значение обязательно") + return None + try: + return Decimal(str(value)) + except (InvalidOperation, ValueError, TypeError) as exc: + raise ProjectImportError(f"Поле {field}: некорректное число {value!r}") from exc + + +def _require_mapping(ref: str | None, mapping: dict[str, int], field: str) -> int: + if not ref: + raise ProjectImportError(f"Поле {field}: ссылка export_id отсутствует") + if ref not in mapping: + raise ProjectImportError(f"Поле {field}: неизвестная ссылка {ref!r}") + return mapping[ref] + + +def _optional_mapping(ref: str | None, mapping: dict[str, int], field: str) -> int | None: + if ref is None or ref == "": + return None + return _require_mapping(ref, mapping, field) + + +def _read_archive(data: bytes) -> dict[str, Any]: + """Read + checksum + JSON-validate the archive without touching the DB.""" + try: + zf = zipfile.ZipFile(io.BytesIO(data), "r") + except zipfile.BadZipFile as exc: + raise ProjectImportError("Файл не является корректным ZIP-архивом") from exc + + with zf: + names = set(zf.namelist()) + missing = [n for n in REQUIRED_FILES if n not in names] + if missing: + raise ProjectImportError(f"В архиве отсутствуют файлы: {', '.join(missing)}") + + raw: dict[str, bytes] = {n: zf.read(n) for n in REQUIRED_FILES} + + try: + checksums = json.loads(raw["checksums.json"].decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ProjectImportError("checksums.json повреждён") from exc + if not isinstance(checksums, dict): + raise ProjectImportError("checksums.json: ожидается объект") + + for name, body in raw.items(): + if name == "checksums.json": + continue + expected = checksums.get(name) + actual = _sha256(body) + if expected != actual: + raise ProjectImportError(f"Контрольная сумма не совпадает для {name}") + + payload: dict[str, Any] = {} + for name, body in raw.items(): + if name == "checksums.json": + continue + try: + payload[name] = json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ProjectImportError(f"{name}: некорректный JSON") from exc + + manifest = payload.get("manifest.json") + if not isinstance(manifest, dict): + raise ProjectImportError("manifest.json: ожидается объект") + if manifest.get("format") != FORMAT_NAME: + raise ProjectImportError(f"Неизвестный format: {manifest.get('format')!r}") + if manifest.get("format_version") != FORMAT_VERSION: + raise ProjectImportError( + f"Неподдерживаемая format_version: {manifest.get('format_version')!r}" + ) + + if not isinstance(payload.get("project.json"), dict): + raise ProjectImportError("project.json: ожидается объект") + for name in _LIST_FILES: + if not isinstance(payload.get(name), list): + raise ProjectImportError(f"{name}: ожидается массив") + + return {"payload": payload, "manifest": manifest} + + +def _validate_records(payload: dict[str, Any], manifest: dict[str, Any]) -> None: + """Validate required fields, types, statuses, and internal export_id links.""" + project = payload["project.json"] + for field in _REQUIRED_FIELDS["project.json"]: + if field not in project: + raise ProjectImportError(f"project.json: нет поля {field}") + + export_ids: dict[str, set[str]] = {} + for name in _LIST_FILES: + required = _REQUIRED_FIELDS[name] + ids: set[str] = set() + for idx, row in enumerate(payload[name], start=1): + if not isinstance(row, dict): + raise ProjectImportError(f"{name}[{idx}]: ожидается объект") + for field in required: + if field not in row: + raise ProjectImportError(f"{name}[{idx}]: нет поля {field}") + eid = row["export_id"] + if not isinstance(eid, str) or not eid: + raise ProjectImportError(f"{name}[{idx}]: некорректный export_id") + if eid in ids: + raise ProjectImportError(f"{name}: дублирующийся export_id {eid!r}") + ids.add(eid) + export_ids[name] = ids + + # Counts vs manifest + counts = manifest.get("counts") + if isinstance(counts, dict): + name_to_key = { + "boq_documents.json": "boq_documents", + "systems.json": "systems", + "sections.json": "sections", + "work_items.json": "work_items", + "agreements.json": "agreements", + "agreement_items.json": "agreement_items", + "daily_reports.json": "daily_reports", + "daily_report_items.json": "daily_report_items", + "ks2.json": "ks2", + "ks2_items.json": "ks2_items", + "ks2_item_sources.json": "ks2_item_sources", + "ks3.json": "ks3", + "ks3_ks2.json": "ks3_ks2", + "payments.json": "payments", + "payment_allocations.json": "payment_allocations", + } + for name, key in name_to_key.items(): + if key in counts and counts[key] != len(payload[name]): + raise ProjectImportError( + f"Количество записей {key} не совпадает с manifest: " + f"{counts[key]} != {len(payload[name])}" + ) + + # Statuses and value ranges + for row in payload["agreements.json"]: + if row["status"] not in _ALLOWED_AGREEMENT_STATUS: + raise ProjectImportError(f"agreements: недопустимый status {row['status']!r}") + for row in payload["agreement_items.json"]: + if row["change_type"] not in _ALLOWED_AGREEMENT_CHANGE: + raise ProjectImportError(f"agreement_items: недопустимый change_type {row['change_type']!r}") + qd = _parse_decimal(row.get("quantity_delta"), "quantity_delta", required=True) + if row["change_type"] == "decrease" and qd >= 0: + raise ProjectImportError("agreement_items: для decrease quantity_delta должен быть < 0") + if row["change_type"] in ("increase", "new_position") and qd <= 0: + raise ProjectImportError("agreement_items: quantity_delta должен быть > 0") + for row in payload["daily_report_items.json"]: + q = _parse_decimal(row.get("completed_quantity"), "completed_quantity", required=True) + if q < 0: + raise ProjectImportError("daily_report_items: completed_quantity не может быть отрицательным") + for row in payload["ks2.json"]: + if row["status"] not in _ALLOWED_KS2_STATUS: + raise ProjectImportError(f"ks2: недопустимый status {row['status']!r}") + for row in payload["ks2_items.json"]: + if _parse_decimal(row.get("quantity"), "quantity", required=True) <= 0: + raise ProjectImportError("ks2_items: quantity должен быть > 0") + for row in payload["ks2_item_sources.json"]: + if _parse_decimal(row.get("quantity"), "quantity", required=True) <= 0: + raise ProjectImportError("ks2_item_sources: quantity должен быть > 0") + for row in payload["ks3.json"]: + if row["status"] not in _ALLOWED_KS3_STATUS: + raise ProjectImportError(f"ks3: недопустимый status {row['status']!r}") + for row in payload["payments.json"]: + if row["status"] not in _ALLOWED_PAYMENT_STATUS: + raise ProjectImportError(f"payments: недопустимый status {row['status']!r}") + if _parse_decimal(row.get("amount"), "amount", required=True) <= 0: + raise ProjectImportError("payments: amount должен быть > 0") + for row in payload["payment_allocations.json"]: + if _parse_decimal(row.get("amount"), "amount", required=True) <= 0: + raise ProjectImportError("payment_allocations: amount должен быть > 0") + + # Internal export_id references + def has(name: str, eid: str) -> bool: + return eid in export_ids.get(name, set()) + + for row in payload["boq_documents.json"]: + if row.get("agreement_export_id") and not has("agreements.json", row["agreement_export_id"]): + raise ProjectImportError(f"boq_documents: битая ссылка {row['agreement_export_id']!r}") + for row in payload["sections.json"]: + if not has("systems.json", row["system_export_id"]): + raise ProjectImportError(f"sections: битая ссылка на system {row['system_export_id']!r}") + for row in payload["work_items.json"]: + for field, name in ( + ("boq_document_export_id", "boq_documents.json"), + ("system_export_id", "systems.json"), + ("section_export_id", "sections.json"), + ): + ref = row.get(field) + if ref and not has(name, ref): + raise ProjectImportError(f"work_items: битая ссылка {field}={ref!r}") + for row in payload["agreements.json"]: + if row.get("boq_document_export_id") and not has("boq_documents.json", row["boq_document_export_id"]): + raise ProjectImportError(f"agreements: битая ссылка {row['boq_document_export_id']!r}") + for row in payload["agreement_items.json"]: + if not has("agreements.json", row["agreement_export_id"]): + raise ProjectImportError(f"agreement_items: битая ссылка на agreement") + if not has("work_items.json", row["work_item_export_id"]): + raise ProjectImportError(f"agreement_items: битая ссылка на work_item") + for row in payload["daily_reports.json"]: + if row.get("system_export_id") and not has("systems.json", row["system_export_id"]): + raise ProjectImportError(f"daily_reports: битая ссылка на system") + for row in payload["daily_report_items.json"]: + if not has("daily_reports.json", row["daily_report_export_id"]): + raise ProjectImportError("daily_report_items: битая ссылка на daily_report") + if not has("work_items.json", row["work_item_export_id"]): + raise ProjectImportError("daily_report_items: битая ссылка на work_item") + for row in payload["ks2_items.json"]: + if not has("ks2.json", row["ks2_export_id"]): + raise ProjectImportError("ks2_items: битая ссылка на ks2") + if not has("work_items.json", row["work_item_export_id"]): + raise ProjectImportError("ks2_items: битая ссылка на work_item") + for row in payload["ks2_item_sources.json"]: + if not has("ks2_items.json", row["ks2_item_export_id"]): + raise ProjectImportError("ks2_item_sources: битая ссылка на ks2_item") + if not has("daily_report_items.json", row["daily_report_item_export_id"]): + raise ProjectImportError("ks2_item_sources: битая ссылка на daily_report_item") + for row in payload["ks3_ks2.json"]: + if not has("ks3.json", row["ks3_export_id"]): + raise ProjectImportError("ks3_ks2: битая ссылка на ks3") + if not has("ks2.json", row["ks2_export_id"]): + raise ProjectImportError("ks3_ks2: битая ссылка на ks2") + for row in payload["payment_allocations.json"]: + if not has("payments.json", row["payment_export_id"]): + raise ProjectImportError("payment_allocations: битая ссылка на payment") + if not has("ks3.json", row["ks3_export_id"]): + raise ProjectImportError("payment_allocations: битая ссылка на ks3") + + # Unique numbers inside the imported project + for label, rows, field in ( + ("agreements", payload["agreements.json"], "number"), + ("ks2", payload["ks2.json"], "number"), + ("ks3", payload["ks3.json"], "number"), + ): + seen: set[str] = set() + for row in rows: + num = row.get(field) + if num is None: + continue + if num in seen: + raise ProjectImportError(f"{label}: дублирующийся номер {num!r}") + seen.add(num) + + +def validate_archive(data: bytes) -> dict[str, Any]: + """Full archive validation. Returns parsed payload for UI preview.""" + result = _read_archive(data) + payload = result["payload"] + manifest = result["manifest"] + _validate_records(payload, manifest) + return { + "manifest": manifest, + "project_name": payload["project.json"].get("name"), + "project": payload["project.json"], + "counts": manifest.get("counts", {}), + "payload": payload, + } + + +def _import_entities(db: Session, payload: dict[str, Any]) -> Project: + """Insert the whole graph in one transaction. Raises on any error.""" + src = payload["project.json"] + project = Project( + name=src["name"], + contract_number=src.get("contract_number"), + contract_date=_parse_date(src.get("contract_date"), "contract_date"), + customer=src.get("customer"), + currency=src.get("currency") or "RUB", + start_date=_parse_date(src.get("start_date"), "start_date"), + end_date=_parse_date(src.get("end_date"), "end_date"), + status=src.get("status") or "active", + ) + db.add(project) + db.flush() + + ids: dict[str, int] = {src["export_id"]: project.id} + + # BOQ documents (agreement FK filled after agreements) + boq_agreement_refs: dict[int, str | None] = {} + for row in payload["boq_documents.json"]: + obj = BoqDocument( + project_id=project.id, + name=row["name"], + version=row.get("version"), + source_file=row.get("source_file"), + document_number=row.get("document_number"), + document_date=_parse_date(row.get("document_date"), "document_date"), + contract=row.get("contract"), + created_at=_parse_datetime(row.get("created_at"), "created_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + boq_agreement_refs[obj.id] = row.get("agreement_export_id") + + for row in payload["systems.json"]: + obj = System( + project_id=project.id, + code=row.get("code"), + name=row["name"], + sort_order=row.get("sort_order") or 0, + created_at=_parse_datetime(row.get("created_at"), "created_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["sections.json"]: + obj = Section( + system_id=_require_mapping(row["system_export_id"], ids, "system_export_id"), + name=row["name"], + sort_order=row.get("sort_order") or 0, + created_at=_parse_datetime(row.get("created_at"), "created_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["work_items.json"]: + obj = WorkItem( + project_id=project.id, + boq_document_id=_optional_mapping(row.get("boq_document_export_id"), ids, "boq_document_export_id"), + system_id=_optional_mapping(row.get("system_export_id"), ids, "system_export_id"), + section_id=_optional_mapping(row.get("section_export_id"), ids, "section_export_id"), + source_number=row.get("source_number"), + name=row["name"], + model=row.get("model"), + manufacturer=row.get("manufacturer"), + unit=row.get("unit"), + quantity=_parse_decimal(row.get("quantity"), "quantity"), + unit_price=_parse_decimal(row.get("unit_price"), "unit_price"), + amount=_parse_decimal(row.get("amount"), "amount"), + created_at=_parse_datetime(row.get("created_at"), "created_at"), + updated_at=_parse_datetime(row.get("updated_at"), "updated_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["agreements.json"]: + obj = Agreement( + project_id=project.id, + boq_document_id=_optional_mapping(row.get("boq_document_export_id"), ids, "boq_document_export_id"), + number=row["number"], + date=_parse_date(row["date"], "date"), + title=row["title"], + description=row.get("description"), + status=row["status"], + created_at=_parse_datetime(row.get("created_at"), "created_at"), + updated_at=_parse_datetime(row.get("updated_at"), "updated_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + # Back-fill BoqDocument.agreement_id now that agreements exist + for doc_db_id, agr_ref in boq_agreement_refs.items(): + if agr_ref: + db.query(BoqDocument).filter(BoqDocument.id == doc_db_id).update( + {"agreement_id": ids[agr_ref]} + ) + db.flush() + + for row in payload["agreement_items.json"]: + obj = AgreementItem( + agreement_id=_require_mapping(row["agreement_export_id"], ids, "agreement_export_id"), + work_item_id=_require_mapping(row["work_item_export_id"], ids, "work_item_export_id"), + change_type=row["change_type"], + quantity_delta=_parse_decimal(row.get("quantity_delta"), "quantity_delta", required=True), + amount_delta=_parse_decimal(row.get("amount_delta"), "amount_delta", required=True), + source_row=row.get("source_row"), + source_number=row.get("source_number"), + source_name=row.get("source_name"), + source_model=row.get("source_model"), + source_manufacturer=row.get("source_manufacturer"), + source_unit=row.get("source_unit"), + source_unit_price=_parse_decimal(row.get("source_unit_price"), "source_unit_price"), + source_boq_document_id=_optional_mapping(row.get("source_boq_document_export_id"), ids, "source_boq_document_export_id"), + source_system_id=_optional_mapping(row.get("source_system_export_id"), ids, "source_system_export_id"), + source_section_id=_optional_mapping(row.get("source_section_export_id"), ids, "source_section_export_id"), + created_at=_parse_datetime(row.get("created_at"), "created_at"), + updated_at=_parse_datetime(row.get("updated_at"), "updated_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["daily_reports.json"]: + obj = DailyReport( + project_id=project.id, + system_id=_optional_mapping(row.get("system_export_id"), ids, "system_export_id"), + report_date=_parse_date(row["report_date"], "report_date"), + notes=row.get("notes"), + created_at=_parse_datetime(row.get("created_at"), "created_at"), + updated_at=_parse_datetime(row.get("updated_at"), "updated_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["daily_report_items.json"]: + obj = DailyReportItem( + daily_report_id=_require_mapping(row["daily_report_export_id"], ids, "daily_report_export_id"), + work_item_id=_require_mapping(row["work_item_export_id"], ids, "work_item_export_id"), + completed_quantity=_parse_decimal(row.get("completed_quantity"), "completed_quantity", required=True), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["ks2.json"]: + obj = KS2( + project_id=project.id, + number=row["number"], + date=_parse_date(row["date"], "date"), + reporting_period_from=_parse_date(row.get("reporting_period_from"), "reporting_period_from"), + reporting_period_to=_parse_date(row.get("reporting_period_to"), "reporting_period_to"), + comment=row.get("comment"), + status=row["status"], + created_at=_parse_datetime(row.get("created_at"), "created_at"), + updated_at=_parse_datetime(row.get("updated_at"), "updated_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["ks2_items.json"]: + obj = KS2Item( + ks2_id=_require_mapping(row["ks2_export_id"], ids, "ks2_export_id"), + work_item_id=_require_mapping(row["work_item_export_id"], ids, "work_item_export_id"), + quantity=_parse_decimal(row.get("quantity"), "quantity", required=True), + unit_price=_parse_decimal(row.get("unit_price"), "unit_price") or Decimal("0"), + amount=_parse_decimal(row.get("amount"), "amount") or Decimal("0"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["ks2_item_sources.json"]: + obj = KS2ItemSource( + ks2_item_id=_require_mapping(row["ks2_item_export_id"], ids, "ks2_item_export_id"), + daily_report_item_id=_require_mapping(row["daily_report_item_export_id"], ids, "daily_report_item_export_id"), + quantity=_parse_decimal(row.get("quantity"), "quantity", required=True), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["ks3.json"]: + obj = KS3( + project_id=project.id, + number=row["number"], + date=_parse_date(row["date"], "date"), + reporting_period_from=_parse_date(row.get("reporting_period_from"), "reporting_period_from"), + reporting_period_to=_parse_date(row.get("reporting_period_to"), "reporting_period_to"), + comment=row.get("comment"), + status=row["status"], + created_at=_parse_datetime(row.get("created_at"), "created_at"), + updated_at=_parse_datetime(row.get("updated_at"), "updated_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["ks3_ks2.json"]: + obj = KS3KS2( + ks3_id=_require_mapping(row["ks3_export_id"], ids, "ks3_export_id"), + ks2_id=_require_mapping(row["ks2_export_id"], ids, "ks2_export_id"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["payments.json"]: + obj = Payment( + project_id=project.id, + date=_parse_date(row["date"], "date"), + document_number=row.get("document_number"), + amount=_parse_decimal(row.get("amount"), "amount", required=True), + currency=row.get("currency") or "RUB", + comment=row.get("comment"), + status=row["status"], + created_at=_parse_datetime(row.get("created_at"), "created_at"), + updated_at=_parse_datetime(row.get("updated_at"), "updated_at"), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + for row in payload["payment_allocations.json"]: + obj = PaymentAllocation( + payment_id=_require_mapping(row["payment_export_id"], ids, "payment_export_id"), + ks3_id=_require_mapping(row["ks3_export_id"], ids, "ks3_export_id"), + amount=_parse_decimal(row.get("amount"), "amount", required=True), + ) + db.add(obj) + db.flush() + ids[row["export_id"]] = obj.id + + db.flush() + return project + + +def import_project(db: Session, data: bytes) -> Project: + """Validate archive then create a new project atomically.""" + preview = validate_archive(data) + payload = preview["payload"] + try: + project = _import_entities(db, payload) + db.commit() + db.refresh(project) + return project + except ProjectImportError: + db.rollback() + raise + except Exception as exc: + db.rollback() + raise ProjectImportError(f"Импорт прерван, изменения отменены: {exc}") from exc diff --git a/app/routers/projects.py b/app/routers/projects.py index 72643ff..aa994fd 100644 --- a/app/routers/projects.py +++ b/app/routers/projects.py @@ -1,4 +1,4 @@ -from fastapi import APIRouter, Depends, HTTPException, Query, Request, Form +from fastapi import APIRouter, Depends, HTTPException, Query, Request, Form, UploadFile, File from fastapi.responses import RedirectResponse, Response from sqlalchemy.orm import Session from app.database import database @@ -13,8 +13,11 @@ from app.models.payment import Payment from app.models.work_journal import WorkJournalEntry from typing import List import os +import secrets +from pathlib import Path router = APIRouter() +IMPORT_UPLOAD_DIR = Path(__file__).resolve().parents[1] / "uploads" / "project_import" def _journal_entry_or_404(db: Session, project_id: int, entry_id: int): @@ -64,6 +67,73 @@ async def read_projects(request: Request, db: Session = Depends(get_db)): async def new_project(request: Request): return request.app.templates.TemplateResponse("projects/new.html", {"request": request}) + +@router.get("/import") +async def project_import_form(request: Request): + return request.app.templates.TemplateResponse("projects/import_project.html", { + "request": request, + "error": None, + }) + + +@router.post("/import/upload") +async def project_import_upload( + request: Request, + file: UploadFile = File(...), + db: Session = Depends(get_db), +): + from app.exporters.project_import import ProjectImportError, validate_archive + + data = (file.file.read() or b"") + try: + preview = validate_archive(data) + except ProjectImportError as exc: + return request.app.templates.TemplateResponse("projects/import_project.html", { + "request": request, + "error": str(exc), + }, status_code=400) + + token = secrets.token_hex(16) + IMPORT_UPLOAD_DIR.mkdir(parents=True, exist_ok=True) + stored = IMPORT_UPLOAD_DIR / f"{token}.wvt.zip" + stored.write_bytes(data) + + counts = preview["counts"] + return request.app.templates.TemplateResponse("projects/import_project_preview.html", { + "request": request, + "token": token, + "project_name": preview["project_name"], + "project": preview["project"], + "manifest": preview["manifest"], + "counts": counts, + }) + + +@router.post("/import/confirm") +async def project_import_confirm( + request: Request, + token: str = Form(...), + db: Session = Depends(get_db), +): + from app.exporters.project_import import ProjectImportError, import_project + + safe_token = Path(token).name + stored = IMPORT_UPLOAD_DIR / f"{safe_token}.wvt.zip" + if not stored.exists(): + raise HTTPException(status_code=400, detail="Файл импорта не найден. Загрузите архив заново.") + data = stored.read_bytes() + try: + imported = import_project(db, data) + except ProjectImportError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + finally: + try: + stored.unlink() + except OSError: + pass + return RedirectResponse(url=f"/projects/{imported.id}?imported=1", status_code=303) + + @router.post("/create") async def create_project( request: Request, @@ -350,3 +420,19 @@ async def export_document_package( media_type="application/zip", headers={"Content-Disposition": content_disposition(filename)}, ) + + +@router.get("/{project_id}/export/project") +async def export_project_archive(project_id: int, db: Session = Depends(get_db)): + from app.exporters.project_export import ProjectExportError, export_project + from app.exporters import content_disposition + + try: + data, filename = export_project(db, project_id) + except ProjectExportError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return Response( + content=data, + media_type="application/zip", + headers={"Content-Disposition": content_disposition(filename)}, + ) diff --git a/app/templates/projects/detail.html b/app/templates/projects/detail.html index 561c274..288dee5 100644 --- a/app/templates/projects/detail.html +++ b/app/templates/projects/detail.html @@ -42,6 +42,13 @@
+ {% if request.query_params.get('imported') %} + + {% endif %} +

{{ project.name }}

@@ -96,16 +103,20 @@
{% if project.status != 'archived' %} -
+
+ Экспорт проекта
{% else %} -
Проект архивирован. Данные сохранены, проект не считается активным.
+
+ Проект архивирован. Данные сохранены, проект не считается активным. + Экспорт проекта +
{% endif %}
diff --git a/app/templates/projects/import_project.html b/app/templates/projects/import_project.html new file mode 100644 index 0000000..efce4bb --- /dev/null +++ b/app/templates/projects/import_project.html @@ -0,0 +1,33 @@ + + + + + + Импорт проекта — Work Volume Tracker + + + +
+ +

Импорт проекта

+ {% if error %}{% endif %} +
+
+

Выберите ZIP-архив проекта, созданный через «Экспорт проекта». + Файл будет полностью проверен до каких-либо изменений в базе данных.

+
+
+ + +
+ + Отмена +
+
+
+
+ + diff --git a/app/templates/projects/import_project_preview.html b/app/templates/projects/import_project_preview.html new file mode 100644 index 0000000..f48c104 --- /dev/null +++ b/app/templates/projects/import_project_preview.html @@ -0,0 +1,57 @@ + + + + + + Проверка архива — Импорт проекта + + + +
+ +

Файл проверен

+ + +
+
+
+
Проект
+
{{ project_name }}
+
Договор
+
{{ project.get('contract_number') or '—' }}
+
Заказчик
+
{{ project.get('customer') or '—' }}
+
Ведомостей
+
{{ counts.get('boq_documents', 0) }}
+
Систем
+
{{ counts.get('systems', 0) }}
+
Разделов
+
{{ counts.get('sections', 0) }}
+
Позиций
+
{{ counts.get('work_items', 0) }}
+
ДС
+
{{ counts.get('agreements', 0) }}
+
Daily Reports
+
{{ counts.get('daily_reports', 0) }}
+
КС-2
+
{{ counts.get('ks2', 0) }}
+
КС-3
+
{{ counts.get('ks3', 0) }}
+
Платежей
+
{{ counts.get('payments', 0) }}
+
+
+
+ +
+ + + Отмена +
+
+ + diff --git a/app/templates/projects/index.html b/app/templates/projects/index.html index a1065a0..f85a894 100644 --- a/app/templates/projects/index.html +++ b/app/templates/projects/index.html @@ -10,7 +10,10 @@
diff --git a/docs/implementation/025-project-export-import.md b/docs/implementation/025-project-export-import.md new file mode 100644 index 0000000..acc90bb --- /dev/null +++ b/docs/implementation/025-project-export-import.md @@ -0,0 +1,117 @@ +# Implementation Report — 025-project-export-import + +### Status + +DONE + +### What was done + +Полноценный машинно-читаемый экспорт/импорт проекта одним переносимым ZIP-архивом (`.wvt.zip`). + +### Формат архива + +ZIP UTF-8, 18 JSON-файлов (без SQLite/runtime-мусора): + +`manifest.json`, `project.json`, `boq_documents.json`, `systems.json`, `sections.json`, `work_items.json`, `agreements.json`, `agreement_items.json`, `daily_reports.json`, `daily_report_items.json`, `ks2.json`, `ks2_items.json`, `ks2_item_sources.json`, `ks3.json`, `ks3_ks2.json`, `payments.json`, `payment_allocations.json`, `checksums.json`. + +Имя файла: `Проект_<безопасное_имя>_.wvt.zip`. + +**manifest:** `format`, `format_version`, `exported_at`, `source_project_id` (только metadata), `project_name`, `counts`. + +**Связи:** только через `export_id` вида `work_item:00000001`. Исходные numeric ID сохраняются как `source_id` (диагностика) и не используются при восстановлении FK. + +**Decimal** сериализуются строками (`"482.42168"`), без float. Даты/время — ISO 8601. `null` → JSON `null`. + +**checksums.json:** SHA-256 каждого JSON-файла. + +### Проверки при импорте (до изменения БД) + +1. наличие обязательных файлов; +2. SHA-256; +3. JSON; +4. `format`; +5. `format_version`; +6. внутренние `export_id`-ссылки; +7. обязательные поля; +8. типы/Decimal/даты; +9. согласованность `counts` с manifest; +10. допустимые статусы и знаки quantity_delta; +11. уникальность номеров Agreement/KS2/KS3 внутри проекта. + +Импорт — одна DB transaction (`export_id → new id`), при любой ошибке `ROLLBACK`. V1: только новый проект, без merge. + +**Cancelled** документы/платежи/allocations импортируются как есть и не попадают в активные агрегаты. + +### UI + +- «Экспорт проекта» на странице проекта (и для archived); +- «Импорт проекта» на списке проектов + страницы: upload → проверка/содержимое → «Импортировать проект» / «Отмена»; +- после успеха redirect на новый проект с сообщением. + +### Changed files + +| Файл | Что | +|---|---| +| `app/exporters/project_export.py` | сбор, валидация ссылок, сериализация, ZIP+checksums | +| `app/exporters/project_import.py` | чтение, checksum/JSON/ссылки, атомарный insert | +| `app/routers/projects.py` | `GET /export/project`, `GET/POST /import/*` | +| `app/templates/projects/import_project.html` | форма загрузки | +| `app/templates/projects/import_project_preview.html` | проверка/содержимое | +| `app/templates/projects/detail.html` | кнопка экспорта, flash об импорте | +| `app/templates/projects/index.html` | кнопка импорта | +| `tests/test_task025_project_export_import.py` | 14 тестов | +| `docs/tasks/025-project-export-import.md` | task-файл | + +Существующие Excel/Word/ZIP-экспорты КС-2/КС-3/КС-6а не менялись. + +### Tests + +`tests/test_task025_project_export_import.py` (14): + +**Export (3):** структура ZIP + manifest + checksums; `export_id`-связи и Decimal-строки; отказ при битых ссылках. + +**Import (3):** полный проект → новые ID + все сущности/FK/Decimal/даты/cancelled/allocations/sources; повторный импорт → отдельный проект; re-export импортированного валиден. + +**Negative (6):** битый checksum; битый JSON; неизвестный format; unsupported format_version; отсутствует файл; битая ссылка; rollback при ошибке; недопустимый status. + +**HTTP smoke (1):** export download → upload → preview → confirm → redirect. + +Результат `pytest -q`: + +``` +258 passed, 272 warnings in 22.62s +``` + +(244 существующих + 14 новых.) + +Результат `git diff --check`: + +``` +(без ошибок) +``` + +### Browser smoke + +Playwright/Chromium, реальный проект. **11/11 passed.** + +| Проверка | Результат | +|---|---| +| Кнопка «Экспорт проекта» | есть | +| Скачивание ZIP | 35 999 bytes | +| Имя файла | `Проект_Саудовская_Аравия_2026-09-27.wvt.zip` | +| Форма импорта | есть | +| Битый ZIP | понятная ошибка, БД не тронута | +| Preview: «Файл проверен», проект, counts | есть | +| Кнопка «Импортировать проект» | есть | +| Redirect `?imported=1` | `/projects/10?imported=1` | +| Success-сообщение | «успешно импортирован» | + +### Deviations + +None. + +### Follow-up / Open Questions + +- Временные файлы импорта (`app/uploads/project_import/`) удаляются после confirm; при сбое могут остаться — можно добавить чистку по TTL. +- `app_version` в manifest не заполнен (в `main.py` version есть только у FastAPI; можно пробросить позже). +- Уникальные номера Agreement/KS2/KS3 проверяются внутри архива; при желании можно добавить предупреждение о совпадении с существующими проектами (V1 создаёт новый проект, конфликт невозможен). diff --git a/docs/tasks/025-project-export-import.md b/docs/tasks/025-project-export-import.md new file mode 100644 index 0000000..3ff4c7d --- /dev/null +++ b/docs/tasks/025-project-export-import.md @@ -0,0 +1,576 @@ +# Task 025 — Project Export / Import + +## Цель + +Реализовать полноценный машинно-читаемый экспорт и импорт проекта. + +Экспорт должен быть переносимым архивом проекта: его можно сохранить как резервную копию, передать на другой экземпляр программы и восстановить проект вместе с историей работ и финансовых документов. + +Это **не** экспорт печатных форм КС-2/КС-3/КС-6а. Существующие человекочитаемые экспорты не менять без необходимости. + +--- + +## Основной сценарий + +### Экспорт + +Пользователь открывает проект → выбирает «Экспорт проекта» → получает один ZIP-файл. + +Пример имени: + +`Проект_Саудовская_Аравия_2026-09-27.wvt.zip` + +Имя должно формироваться безопасно, без недопустимых символов. + +### Импорт + +Пользователь выбирает ZIP-файл → система сначала полностью читает и валидирует архив → показывает краткое содержимое/результат проверки → после подтверждения создаёт **новый проект**. + +В V1 не делать импорт поверх существующего проекта и не делать merge. + +Импорт должен быть атомарным: либо создаётся весь проект, либо при любой ошибке не создаётся ничего. + +--- + +# 1. Формат архива + +ZIP UTF-8. + +Предлагаемая структура: + +```text +manifest.json +project.json +boq_documents.json +systems.json +sections.json +work_items.json +agreements.json +agreement_items.json +daily_reports.json +daily_report_items.json +ks2.json +ks2_items.json +ks2_item_sources.json +ks3.json +ks3_ks2.json +payments.json +payment_allocations.json +checksums.json +``` + +Не включать SQLite-файл. + +Не включать временные файлы, Python-кэш, HTML, пользовательские загрузки и прочий runtime-мусор. + +--- + +# 2. Manifest + +`manifest.json` должен содержать как минимум: + +- `format`: например `work_volume_tracker` +- `format_version`: например `1` +- `app_version`, если версия приложения доступна +- `exported_at` +- исходный `project_id` только как информационный metadata, не как ID для восстановления +- название проекта +- количество записей каждого типа + +Пример: + +```json +{ + "format": "work_volume_tracker", + "format_version": 1, + "app_version": "...", + "exported_at": "2026-09-27T19:00:00+03:00", + "source_project_id": 2, + "project_name": "Саудовская Аравия", + "counts": { + "boq_documents": 1, + "systems": 11, + "sections": 61, + "work_items": 463, + "agreements": 0, + "agreement_items": 0, + "daily_reports": 0, + "daily_report_items": 0, + "ks2": 0, + "ks2_items": 0, + "ks2_item_sources": 0, + "ks3": 0, + "ks3_ks2": 0, + "payments": 0, + "payment_allocations": 0 + } +} +``` + +Точные поля адаптировать к фактической модели проекта. + +--- + +# 3. IDs и связи + +Критически важно: **не использовать исходные database ID как постоянные ссылки внутри экспортируемого проекта**. + +Для каждой сущности в экспортном JSON использовать собственный стабильный export key, например: + +```json +{ + "export_id": "work_item:00000001", + ... +} +``` + +Связи между сущностями должны ссылаться на эти `export_id`. + +Пример: + +```json +{ + "export_id": "agreement_item:00000017", + "agreement_id": "agreement:00000003", + "work_item_id": "work_item:00000142" +} +``` + +При импорте построить mapping: + +```text +export_id → новый database id +``` + +и использовать его для восстановления всех FK. + +Исходные numeric database IDs могут сохраняться отдельно как диагностическая информация, но не должны использоваться для восстановления связей. + +--- + +# 4. Формат данных + +Сохранять фактические значения проекта, а не только агрегаты. + +Обязательно сохранить: + +### Project + +Все существующие поля Project, включая: + +- название; +- номер/дату договора; +- заказчика; +- валюту; +- даты; +- статус; +- реквизиты и подписантов, если они уже присутствуют в модели; +- прочие существующие поля. + +### BOQ + +- BOQ documents; +- metadata документа; +- системы; +- разделы; +- WorkItem; +- source_number; +- name; +- model; +- manufacturer; +- unit; +- quantity; +- unit_price; +- amount; +- связи с BOQ/system/section. + +### Additional Agreements + +- Agreement; +- номер; +- дата; +- название; +- описание; +- статус; +- scope (`boq_document_id`, если есть); +- AgreementItem; +- signed quantity delta; +- signed amount delta; +- change_type; +- source BOQ/document context; +- source Excel metadata/snapshot, если есть. + +### Daily Reports + +- сам отчёт; +- дата; +- статус/прочие существующие поля; +- все DailyReportItem; +- WorkItem; +- quantity; +- комментарии/прочие существующие поля. + +### KS-2 + +Сохранить: + +- номер; +- дату; +- reporting period; +- title/comment; +- status, включая `cancelled`; +- причину/комментарий сторно, если хранится; +- KS2Item; +- WorkItem; +- quantity; +- unit_price; +- amount; +- KS2ItemSource; +- ссылки на DailyReportItem; +- quantities источников. + +### KS-3 + +Сохранить: + +- номер; +- дату; +- reporting period; +- status, включая `cancelled`; +- причину/комментарий сторно, если хранится; +- связи KS3 → KS2. + +Не пересчитывать и не заменять исторические значения импортом из dashboard-агрегатов. + +### Payments + +Сохранить: + +- номер/документ; +- дату; +- сумму; +- валюту; +- комментарий; +- status, включая `cancelled`; +- все PaymentAllocation; +- связи с KS-3; +- суммы распределений. + +Сторнированные платежи и их исторические allocations сохраняются. + +--- + +# 5. Decimal / даты + +Денежные значения и количества не сериализовать через float. + +Использовать строковое представление Decimal: + +```json +"quantity": "12.500000" +"unit_price": "482.42168" +"amount": "6030.270000" +``` + +При импорте восстанавливать Decimal. + +Даты/время — ISO 8601. + +`null` сохранять как JSON `null`. + +UTF-8. + +--- + +# 6. Checksums + +`checksums.json` должен содержать SHA-256 для каждого JSON-файла архива. + +Пример: + +```json +{ + "manifest.json": "....", + "project.json": "....", + "boq_documents.json": "...." +} +``` + +При импорте: + +1. проверить наличие обязательных файлов; +2. проверить SHA-256; +3. проверить JSON; +4. проверить `format`; +5. проверить `format_version`; +6. проверить внутренние ссылки; +7. проверить обязательные поля; +8. проверить типы/Decimal/даты; +9. проверить согласованность количества записей с manifest. + +До прохождения всех проверок БД не изменять. + +--- + +# 7. Порядок импорта + +Импорт выполнять одной DB transaction. + +Рекомендуемый порядок: + +1. Project +2. BOQ documents +3. Systems +4. Sections +5. WorkItems +6. Agreements +7. AgreementItems +8. DailyReports +9. DailyReportItems +10. KS2 +11. KS2Items +12. KS2ItemSources +13. KS3 +14. KS3-KS2 links +15. Payments +16. Payment allocations + +После создания каждой сущности сохранять: + +```text +export_id → new database id +``` + +При любой ошибке: + +```text +ROLLBACK +``` + +Не должно оставаться частично импортированного проекта. + +--- + +# 8. Проверки бизнес-целостности + +Импорт не должен просто вставлять JSON. + +Проверить как минимум: + +- все ссылки `export_id` существуют; +- WorkItem принадлежит импортируемому проекту; +- DailyReportItem ссылается на существующий WorkItem; +- KS2Item ссылается на существующий WorkItem; +- KS2ItemSource ссылается на существующие KS2Item и DailyReportItem; +- KS3 ссылается только на KS2 этого проекта; +- PaymentAllocation ссылается только на KS3 этого проекта; +- суммы/количества имеют допустимые значения; +- статусы являются допустимыми; +- номера/уникальные ограничения не нарушаются внутри нового проекта. + +Исторические связи не пересчитывать и не «исправлять» автоматически. + +--- + +# 9. Импорт cancelled документов + +Сторнированные документы импортируются как сторнированные. + +Не считать их активными. + +После импорта dashboard и списки должны показывать тот же логический результат, что и до экспорта. + +Особенно важно: + +- cancelled KS2 не должен считаться закрытым активным объёмом; +- cancelled KS3 не должен участвовать в активных финансовых агрегатах; +- cancelled Payment не должен входить в Received / Allocated / Unallocated / Debt; +- исторические связи и allocations должны остаться. + +--- + +# 10. UI + +Добавить действие на уровне проекта: + +**Экспорт проекта** + +и: + +**Импорт проекта** + +Импорт лучше сделать отдельной страницей/формой. + +После выбора файла: + +```text +Файл проверен +Проект: ... +Договор: ... +Ведомостей: ... +Систем: ... +Разделов: ... +Позиций: ... +ДС: ... +Daily Reports: ... +КС-2: ... +КС-3: ... +Платежей: ... +``` + +И кнопки: + +- `Импортировать проект` +- `Отмена` + +До нажатия `Импортировать проект` БД не изменяется. + +После успешного импорта: + +- redirect на новый проект; +- flash/success сообщение; +- показать название нового проекта. + +При ошибке: + +- понятное сообщение; +- исходная БД без изменений. + +--- + +# 11. Экспорт + +На странице проекта добавить кнопку: + +**Экспорт проекта** + +Экспорт должен формироваться непосредственно из БД. + +Перед формированием желательно выполнить внутреннюю проверку ссылочной целостности проекта. Если обнаружена ошибка данных — экспорт не должен тихо создавать повреждённый архив. + +Ответ — HTTP download. + +Использовать существующую общую логику безопасных имён файлов. + +Не ломать существующие Excel/Word exports. + +--- + +# 12. Сервисный слой + +Не помещать всю логику в router. + +Предлагаемая структура: + +```text +app/exporters/ + project_export.py + project_import.py +``` + +или эквивалентная структура проекта. + +Разделить: + +- сбор данных; +- сериализацию; +- создание ZIP; +- checksum; +- validation; +- import mapping; +- DB transaction. + +Router должен оставаться тонким. + +--- + +# 13. Тесты + +Обязательные тесты. + +### Export + +1. экспорт проекта с BOQ; +2. экспорт проекта с DS; +3. экспорт с Daily Reports; +4. экспорт с KS2/KS3; +5. экспорт с Payments; +6. экспорт cancelled KS2/KS3/Payment; +7. проверка состава ZIP; +8. проверка manifest; +9. проверка checksums; +10. Decimal не теряет точность. + +### Import + +11. импорт полного проекта; +12. импорт создаёт новый project id; +13. все сущности восстанавливаются; +14. все FK восстанавливаются через export_id mapping; +15. cancelled statuses сохраняются; +16. payment allocations сохраняются; +17. KS2 sources сохраняются; +18. Decimal сохраняется; +19. дата/время сохраняются; +20. повторный импорт того же файла создаёт отдельный проект. + +### Negative + +21. повреждённый checksum → импорт запрещён; +22. битый JSON → импорт запрещён; +23. неизвестный format → импорт запрещён; +24. неподдерживаемая format_version → импорт запрещён; +25. отсутствующий обязательный файл → импорт запрещён; +26. битая внутренняя ссылка → импорт запрещён; +27. ошибка в середине импорта → полный rollback, никаких частичных данных. + +### Regression + +Запустить полный существующий тестовый набор. + +--- + +# 14. Важное ограничение V1 + +Не делать в этой задаче: + +- импорт поверх существующего проекта; +- merge проектов; +- синхронизацию двух экземпляров; +- серверную синхронизацию; +- авторизацию; +- шифрование архива; +- официальные PDF-формы; +- автоматическое исправление повреждённых данных; +- изменение существующих человекочитаемых экспортов без необходимости. + +Это задача именно **полного переносимого machine-readable snapshot проекта**. + +--- + +# 15. Definition of Done + +Готово, если: + +- проект можно экспортировать одним ZIP; +- архив содержит полную логическую историю проекта; +- архив содержит manifest + checksums; +- Decimal не теряет точность; +- все связи восстанавливаются через export_id mapping; +- импорт сначала валидирует архив; +- импорт выполняется атомарно; +- повторный импорт создаёт отдельный проект; +- cancelled документы сохраняются и не возвращаются в активные агрегаты; +- существующие KS2/KS3/KS6a/Payment exports не сломаны; +- полный тестовый набор проходит; +- browser smoke проверяет export/import; +- git diff чистый после коммита; +- подготовлен implementation report. + +После реализации отдельно подготовить краткий отчёт: +- какие файлы изменены; +- формат архива; +- какие проверки реализованы; +- сколько тестов; +- результат browser smoke; +- commit hash. diff --git a/tests/test_task025_project_export_import.py b/tests/test_task025_project_export_import.py new file mode 100644 index 0000000..aa5bfd8 --- /dev/null +++ b/tests/test_task025_project_export_import.py @@ -0,0 +1,500 @@ +"""Tests for task 025: project export / import.""" +from __future__ import annotations + +import io +import json +import zipfile +from datetime import date, datetime +from decimal import Decimal + +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from sqlalchemy.pool import StaticPool + +from app.database.database import Base +from app.exporters.project_export import ( + FORMAT_NAME, + FORMAT_VERSION, + REQUIRED_FILES, + ProjectExportError, + export_project, + serialize_project, + collect_project, +) +from app.exporters.project_import import ( + ProjectImportError, + import_project, + validate_archive, +) +from app.main import app +from app.models.agreement import Agreement, AgreementItem +from app.models.boq import BoqDocument, Section, System, WorkItem +from app.models.daily_report import DailyReport, DailyReportItem +from app.models.ks2 import KS2, KS2Item, KS2ItemSource +from app.models.ks3 import KS3, KS3KS2 +from app.models.payment import Payment, PaymentAllocation +from app.models.project import Project +from fastapi.testclient import TestClient +from app.routers import projects as project_router + + +@pytest.fixture +def db_session(): + 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() + + +def _full_project(db): + """Build a rich project covering every exported entity, including cancelled docs.""" + p = Project( + name="Саудовская Аравия", + contract_number="РД-07-2026/01", + contract_date=date(2026, 1, 10), + customer="АО «Ремстрой»", + currency="RUB", + start_date=date(2026, 1, 1), + end_date=date(2028, 11, 1), + status="active", + ) + db.add(p) + db.flush() + + wi = WorkItem( + project_id=p.id, source_number="1", name="Монтаж трубы", + model="M-1", manufacturer="Завод", unit="м", + quantity=Decimal("12.500000"), + unit_price=Decimal("482.42168"), + amount=Decimal("6030.270000"), + ) + db.add(wi) + db.flush() + + doc = BoqDocument( + project_id=p.id, name="BOQ Import - Ведомость ОВ", version="1.0", + source_file="ov.xlsx", document_number="БО-1", + document_date=date(2026, 1, 5), contract="РД-07", + ) + db.add(doc) + db.flush() + wi.boq_document_id = doc.id + + system = System(project_id=p.id, code="OV", name="Отопление", sort_order=1) + db.add(system) + db.flush() + section = Section(system_id=system.id, name="Раздел 1", sort_order=1) + db.add(section) + db.flush() + wi.system_id = system.id + wi.section_id = section.id + + agr = Agreement( + project_id=p.id, boq_document_id=doc.id, number="A-1", + date=date(2026, 2, 1), title="Доп. работы", + description="Описание", status="approved", + ) + db.add(agr) + db.flush() + ai = AgreementItem( + agreement_id=agr.id, work_item_id=wi.id, change_type="increase", + quantity_delta=Decimal("5.0000"), amount_delta=Decimal("2500.00"), + source_row=1, source_number="1", source_name="Монтаж трубы", + source_model="M-1", source_manufacturer="Завод", source_unit="м", + source_unit_price=Decimal("500.00"), + source_boq_document_id=doc.id, source_system_id=system.id, + source_section_id=section.id, + ) + db.add(ai) + + dr = DailyReport(project_id=p.id, system_id=system.id, report_date=date(2026, 3, 1), notes="Смена") + db.add(dr) + db.flush() + dri = DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("3.5000")) + db.add(dri) + db.flush() + + ks2_draft = KS2(project_id=p.id, number="K2-1", date=date(2026, 3, 2), status="draft") + ks2_issued = KS2( + project_id=p.id, number="K2-2", date=date(2026, 3, 3), + reporting_period_from=date(2026, 3, 1), reporting_period_to=date(2026, 3, 31), + comment="Период", status="issued", + ) + ks2_cancelled = KS2(project_id=p.id, number="K2-3", date=date(2026, 3, 4), status="cancelled", comment="сторно") + db.add_all([ks2_draft, ks2_issued, ks2_cancelled]) + db.flush() + + ks2_item = KS2Item( + ks2_id=ks2_issued.id, work_item_id=wi.id, + quantity=Decimal("3.5000"), unit_price=Decimal("482.42168"), + amount=Decimal("1688.47588"), + ) + db.add(ks2_item) + db.flush() + src = KS2ItemSource(ks2_item_id=ks2_item.id, daily_report_item_id=dri.id, quantity=Decimal("3.5000")) + db.add(src) + + ks3_issued = KS3( + project_id=p.id, number="K3-1", date=date(2026, 4, 1), + reporting_period_from=date(2026, 3, 1), reporting_period_to=date(2026, 3, 31), + status="issued", + ) + ks3_cancelled = KS3(project_id=p.id, number="K3-2", date=date(2026, 4, 2), status="cancelled") + db.add_all([ks3_issued, ks3_cancelled]) + db.flush() + db.add(KS3KS2(ks3_id=ks3_issued.id, ks2_id=ks2_issued.id)) + + pay_active = Payment( + project_id=p.id, date=date(2026, 5, 1), document_number="PL-1", + amount=Decimal("25000.00"), currency="RUB", comment="Оплата", status="active", + ) + pay_cancelled = Payment( + project_id=p.id, date=date(2026, 5, 2), document_number="PL-2", + amount=Decimal("100.00"), currency="RUB", status="cancelled", + ) + db.add_all([pay_active, pay_cancelled]) + db.flush() + db.add(PaymentAllocation(payment_id=pay_active.id, ks3_id=ks3_issued.id, amount=Decimal("20000.00"))) + db.add(PaymentAllocation(payment_id=pay_cancelled.id, ks3_id=ks3_issued.id, amount=Decimal("50.00"))) + db.commit() + return p.id + + +# --------------------------------------------------------------------------- +# Export +# --------------------------------------------------------------------------- +def test_export_zip_structure_manifest_checksums(db_session): + pid = _full_project(db_session) + data, filename = export_project(db_session, pid) + assert filename.endswith(".wvt.zip") + assert "Саудовская_Аравия" in filename or "Проект_" in filename + + zf = zipfile.ZipFile(io.BytesIO(data)) + names = set(zf.namelist()) + assert set(REQUIRED_FILES) <= names + assert "work_tracker.db" not in names + + manifest = json.loads(zf.read("manifest.json").decode("utf-8")) + assert manifest["format"] == FORMAT_NAME + assert manifest["format_version"] == FORMAT_VERSION + assert manifest["project_name"] == "Саудовская Аравия" + assert manifest["counts"]["work_items"] == 1 + assert manifest["counts"]["ks2"] == 3 + assert manifest["counts"]["payments"] == 2 + + checksums = json.loads(zf.read("checksums.json").decode("utf-8")) + import hashlib + for name in REQUIRED_FILES: + if name == "checksums.json": + continue + actual = hashlib.sha256(zf.read(name)).hexdigest() + assert checksums[name] == actual + + +def test_export_uses_export_id_links_and_decimal_strings(db_session): + pid = _full_project(db_session) + graph = collect_project(db_session, pid) + files = serialize_project(graph) + + items = files["work_items.json"] + assert items[0]["export_id"] == "work_item:00000001" + # Numeric columns: quantity(15,4), unit_price/amount(18,12) — string Decimal, no float + assert items[0]["quantity"] == "12.5" + assert items[0]["unit_price"] == "482.42168" + assert items[0]["amount"] == "6030.27" + assert isinstance(items[0]["quantity"], str) + assert items[0]["boq_document_export_id"] == "boq_document:00000001" + + src = files["ks2_item_sources.json"][0] + assert src["ks2_item_export_id"].startswith("ks2_item:") + assert src["daily_report_item_export_id"].startswith("daily_report_item:") + assert src["quantity"] == "3.5" + + cancelled = {r["status"] for r in files["ks2.json"]} + assert "cancelled" in cancelled + assert {r["status"] for r in files["payments.json"]} == {"active", "cancelled"} + + +def test_export_rejects_broken_references(db_session): + pid = _full_project(db_session) + # Break a reference + wi = db_session.query(WorkItem).first() + wi.system_id = 99999 + db_session.commit() + with pytest.raises(ProjectExportError): + export_project(db_session, pid) + + +# --------------------------------------------------------------------------- +# Import happy path +# --------------------------------------------------------------------------- +def test_import_full_project_creates_new_ids_and_preserves_history(db_session): + src_pid = _full_project(db_session) + data, _ = export_project(db_session, src_pid) + + imported = import_project(db_session, data) + assert imported.id != src_pid + assert imported.name == "Саудовская Аравия" + assert imported.contract_number == "РД-07-2026/01" + assert imported.contract_date == date(2026, 1, 10) + + # All entity types restored + assert db_session.query(BoqDocument).filter_by(project_id=imported.id).count() == 1 + assert db_session.query(System).filter_by(project_id=imported.id).count() == 1 + assert db_session.query(Section).count() >= 1 + assert db_session.query(WorkItem).filter_by(project_id=imported.id).count() == 1 + assert db_session.query(Agreement).filter_by(project_id=imported.id).count() == 1 + assert db_session.query(AgreementItem).count() >= 1 + assert db_session.query(DailyReport).filter_by(project_id=imported.id).count() == 1 + assert db_session.query(DailyReportItem).count() >= 1 + assert db_session.query(KS2).filter_by(project_id=imported.id).count() == 3 + assert db_session.query(KS2Item).count() >= 1 + assert db_session.query(KS2ItemSource).count() >= 1 + assert db_session.query(KS3).filter_by(project_id=imported.id).count() == 2 + assert db_session.query(KS3KS2).count() >= 1 + assert db_session.query(Payment).filter_by(project_id=imported.id).count() == 2 + assert db_session.query(PaymentAllocation).count() >= 2 + + # FKs remapped to new IDs + wi = db_session.query(WorkItem).filter_by(project_id=imported.id).one() + doc = db_session.query(BoqDocument).filter_by(project_id=imported.id).one() + assert wi.boq_document_id == doc.id + assert wi.system_id is not None + assert wi.section_id is not None + + # Decimal preserved exactly + assert wi.quantity == Decimal("12.5000") + assert wi.unit_price == Decimal("482.42168") + assert wi.amount == Decimal("6030.27") + + # Dates preserved + assert doc.document_date == date(2026, 1, 5) + + # Cancelled statuses preserved + ks2_statuses = {k.status for k in db_session.query(KS2).filter_by(project_id=imported.id).all()} + assert "cancelled" in ks2_statuses and "issued" in ks2_statuses + pay_statuses = {p.status for p in db_session.query(Payment).filter_by(project_id=imported.id).all()} + assert pay_statuses == {"active", "cancelled"} + + # Payment allocations + KS2 sources preserved + cancelled_pay = db_session.query(Payment).filter_by(project_id=imported.id, status="cancelled").one() + assert cancelled_pay.allocations, "cancelled payment allocations must be kept" + ks2_items = db_session.query(KS2Item).join(KS2).filter(KS2.project_id == imported.id).all() + assert any(i.sources for i in ks2_items) + + # Re-export of imported project is valid + data2, _ = export_project(db_session, imported.id) + validate_archive(data2) + + +def test_import_twice_creates_separate_projects(db_session): + pid = _full_project(db_session) + data, _ = export_project(db_session, pid) + a = import_project(db_session, data) + b = import_project(db_session, data) + assert a.id != b.id != pid + assert a.name == b.name + + +# --------------------------------------------------------------------------- +# Negative / validation +# --------------------------------------------------------------------------- +def _corrupt_zip(mutate) -> bytes: + 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) + s = Session() + pid = _full_project(s) + data, _ = export_project(s, pid) + s.close() + engine.dispose() + + zin = zipfile.ZipFile(io.BytesIO(data)) + parts = {n: zin.read(n) for n in zin.namelist()} + zin.close() + mutate(parts) + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zout: + for n, b in parts.items(): + zout.writestr(n, b) + return buf.getvalue() + + +def test_import_rejects_bad_checksum(): + def mutate(parts): + parts["project.json"] = parts["project.json"].replace( + "Саудовская".encode("utf-8"), "Другой".encode("utf-8") + ) + + with pytest.raises(ProjectImportError, match="Контрольная сумма"): + validate_archive(_corrupt_zip(mutate)) + + +def test_import_rejects_broken_json(): + def mutate(parts): + import hashlib + parts["work_items.json"] = b"{not json" + # keep checksum matching so we hit JSON error... actually checksum will fail first. + # Rebuild checksums to pass checksum check and fail JSON parse. + checksums = {} + for name, body in parts.items(): + if name == "checksums.json": + continue + checksums[name] = hashlib.sha256(body).hexdigest() + parts["checksums.json"] = json.dumps(checksums).encode("utf-8") + + with pytest.raises(ProjectImportError, match="JSON"): + validate_archive(_corrupt_zip(mutate)) + + +def test_import_rejects_unknown_format(): + def mutate(parts): + import hashlib + manifest = json.loads(parts["manifest.json"].decode("utf-8")) + manifest["format"] = "alien" + parts["manifest.json"] = json.dumps(manifest).encode("utf-8") + checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"} + parts["checksums.json"] = json.dumps(checksums).encode("utf-8") + + with pytest.raises(ProjectImportError, match="format"): + validate_archive(_corrupt_zip(mutate)) + + +def test_import_rejects_unsupported_format_version(): + def mutate(parts): + import hashlib + manifest = json.loads(parts["manifest.json"].decode("utf-8")) + manifest["format_version"] = 99 + parts["manifest.json"] = json.dumps(manifest).encode("utf-8") + checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"} + parts["checksums.json"] = json.dumps(checksums).encode("utf-8") + + with pytest.raises(ProjectImportError, match="format_version"): + validate_archive(_corrupt_zip(mutate)) + + +def test_import_rejects_missing_required_file(): + def mutate(parts): + del parts["payments.json"] + + with pytest.raises(ProjectImportError, match="отсутствуют"): + validate_archive(_corrupt_zip(mutate)) + + +def test_import_rejects_broken_internal_reference(): + def mutate(parts): + import hashlib + items = json.loads(parts["work_items.json"].decode("utf-8")) + items[0]["system_export_id"] = "system:99999999" + parts["work_items.json"] = json.dumps(items, ensure_ascii=False).encode("utf-8") + checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"} + parts["checksums.json"] = json.dumps(checksums).encode("utf-8") + + with pytest.raises(ProjectImportError, match="битая ссылка"): + validate_archive(_corrupt_zip(mutate)) + + +def test_import_rollback_on_midway_error(db_session): + pid = _full_project(db_session) + data, _ = export_project(db_session, pid) + before = db_session.query(Project).count() + + # Make insert fail after project row would be created: duplicate agreement number + # by patching archive so two agreements share a number (caught in validation), + # and separately force an insert error with an invalid required FK target. + def mutate(parts): + import hashlib + items = json.loads(parts["payment_allocations.json"].decode("utf-8")) + # valid refs in archive but we'll instead break validation of unique numbers + agreements = json.loads(parts["agreements.json"].decode("utf-8")) + # add a second agreement with same number by cloning first + clone = dict(agreements[0]) + clone["export_id"] = "agreement:00000099" + agreements.append(clone) + parts["agreements.json"] = json.dumps(agreements, ensure_ascii=False).encode("utf-8") + checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"} + parts["checksums.json"] = json.dumps(checksums).encode("utf-8") + + broken = _corrupt_zip(mutate) + with pytest.raises(ProjectImportError): + import_project(db_session, broken) + assert db_session.query(Project).count() == before + + +def test_import_rejects_invalid_status(): + def mutate(parts): + import hashlib + ks2 = json.loads(parts["ks2.json"].decode("utf-8")) + ks2[0]["status"] = "bogus" + parts["ks2.json"] = json.dumps(ks2, ensure_ascii=False).encode("utf-8") + checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"} + parts["checksums.json"] = json.dumps(checksums).encode("utf-8") + + with pytest.raises(ProjectImportError, match="status"): + validate_archive(_corrupt_zip(mutate)) + + +# --------------------------------------------------------------------------- +# HTTP smoke +# --------------------------------------------------------------------------- +def test_http_export_and_import_roundtrip(tmp_path): + from tests.test_task024_payment_stornation import _ui_session # reuse helper if present + + 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() + pid = _full_project(session) + + def override_db(): + s = Session() + try: + yield s + finally: + s.close() + + app.dependency_overrides[project_router.get_db] = override_db + try: + with TestClient(app) as client: + resp = client.get(f"/projects/{pid}/export/project") + assert resp.status_code == 200 + assert resp.headers["content-type"] == "application/zip" + assert ".wvt.zip" in resp.headers["content-disposition"] + archive = resp.content + + form = client.get("/projects/import") + assert form.status_code == 200 and "Импорт проекта" in form.text + + up = client.post( + "/projects/import/upload", + files={"file": ("proj.wvt.zip", archive, "application/zip")}, + ) + assert up.status_code == 200 + assert "Файл проверен" in up.text + assert "Саудовская Аравия" in up.text + + # extract token + import re + m = re.search(r'name="token" value="([^"]+)"', up.text) + assert m + token = m.group(1) + + conf = client.post("/projects/import/confirm", data={"token": token}, follow_redirects=False) + assert conf.status_code == 303 + loc = conf.headers["location"] + assert "/projects/" in loc and "imported=1" in loc + + new_id = int(loc.split("/projects/")[1].split("?")[0]) + assert new_id != pid + page = client.get(f"/projects/{new_id}?imported=1") + assert "успешно импортирован" in page.text + finally: + app.dependency_overrides.pop(project_router.get_db, None) + session.close() + engine.dispose()