Files
work-volume-tracker/app/exporters/project_export.py
T
2026-09-28 11:22:11 +03:00

657 lines
23 KiB
Python

"""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)