feat: add portable project export/import ZIP with checksums and atomic restore
This commit is contained in:
@@ -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)
|
||||
@@ -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
|
||||
+87
-1
@@ -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)},
|
||||
)
|
||||
|
||||
@@ -42,6 +42,13 @@
|
||||
<main class="container-fluid container-xxl py-4">
|
||||
<nav class="mb-3"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="/projects/">Проекты</a></li><li class="breadcrumb-item active">{{ project.name }}</li></ol></nav>
|
||||
|
||||
{% if request.query_params.get('imported') %}
|
||||
<div class="alert alert-success alert-dismissible fade show" role="alert">
|
||||
Проект «{{ project.name }}» успешно импортирован как новый проект.
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<header class="mb-4">
|
||||
<!-- Block 1: project title -->
|
||||
<h1 class="h2 mb-2">{{ project.name }}</h1>
|
||||
@@ -96,16 +103,20 @@
|
||||
</header>
|
||||
|
||||
{% if project.status != 'archived' %}
|
||||
<div class="mb-3 d-flex gap-2">
|
||||
<div class="mb-3 d-flex flex-wrap gap-2">
|
||||
<form method="post" action="/projects/{{ project.id }}/archive" class="d-inline">
|
||||
<button type="submit" class="btn btn-outline-warning btn-sm" onclick="return confirm('Архивировать проект? Данные будут сохранены.')">Архивировать</button>
|
||||
</form>
|
||||
<form method="post" action="/projects/{{ project.id }}/delete" class="d-inline" id="delete-project-form">
|
||||
<button type="submit" class="btn btn-outline-danger btn-sm">Удалить проект</button>
|
||||
</form>
|
||||
<a class="btn btn-outline-primary btn-sm" href="/projects/{{ project.id }}/export/project">Экспорт проекта</a>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-warning mb-3">Проект архивирован. Данные сохранены, проект не считается активным.</div>
|
||||
<div class="alert alert-warning mb-3 d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||
<span>Проект архивирован. Данные сохранены, проект не считается активным.</span>
|
||||
<a class="btn btn-outline-primary btn-sm" href="/projects/{{ project.id }}/export/project">Экспорт проекта</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<section class="mt-3" aria-live="polite">
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Импорт проекта — Work Volume Tracker</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<main class="container py-4">
|
||||
<nav class="mb-3"><ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="/projects/">Проекты</a></li>
|
||||
<li class="breadcrumb-item active">Импорт проекта</li>
|
||||
</ol></nav>
|
||||
<h1 class="h2 mb-3">Импорт проекта</h1>
|
||||
{% if error %}<div class="alert alert-danger" role="alert">{{ error }}</div>{% endif %}
|
||||
<div class="card border-0 shadow-sm mb-3">
|
||||
<div class="card-body">
|
||||
<p class="text-muted">Выберите ZIP-архив проекта, созданный через «Экспорт проекта».
|
||||
Файл будет полностью проверен до каких-либо изменений в базе данных.</p>
|
||||
<form method="post" action="/projects/import/upload" enctype="multipart/form-data">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="file">Архив проекта (.wvt.zip)</label>
|
||||
<input class="form-control" type="file" id="file" name="file" accept=".zip,application/zip" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Проверить файл</button>
|
||||
<a href="/projects/" class="btn btn-outline-secondary">Отмена</a>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,57 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Проверка архива — Импорт проекта</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<main class="container py-4">
|
||||
<nav class="mb-3"><ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="/projects/">Проекты</a></li>
|
||||
<li class="breadcrumb-item"><a href="/projects/import">Импорт проекта</a></li>
|
||||
<li class="breadcrumb-item active">Проверка</li>
|
||||
</ol></nav>
|
||||
<h1 class="h2 mb-3">Файл проверен</h1>
|
||||
<div class="alert alert-success" role="alert">Архив корректен. После подтверждения будет создан новый проект.</div>
|
||||
|
||||
<div class="card border-0 shadow-sm mb-3">
|
||||
<div class="card-body">
|
||||
<dl class="row mb-0">
|
||||
<dt class="col-sm-4">Проект</dt>
|
||||
<dd class="col-sm-8">{{ project_name }}</dd>
|
||||
<dt class="col-sm-4">Договор</dt>
|
||||
<dd class="col-sm-8">{{ project.get('contract_number') or '—' }}</dd>
|
||||
<dt class="col-sm-4">Заказчик</dt>
|
||||
<dd class="col-sm-8">{{ project.get('customer') or '—' }}</dd>
|
||||
<dt class="col-sm-4">Ведомостей</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('boq_documents', 0) }}</dd>
|
||||
<dt class="col-sm-4">Систем</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('systems', 0) }}</dd>
|
||||
<dt class="col-sm-4">Разделов</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('sections', 0) }}</dd>
|
||||
<dt class="col-sm-4">Позиций</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('work_items', 0) }}</dd>
|
||||
<dt class="col-sm-4">ДС</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('agreements', 0) }}</dd>
|
||||
<dt class="col-sm-4">Daily Reports</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('daily_reports', 0) }}</dd>
|
||||
<dt class="col-sm-4">КС-2</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('ks2', 0) }}</dd>
|
||||
<dt class="col-sm-4">КС-3</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('ks3', 0) }}</dd>
|
||||
<dt class="col-sm-4">Платежей</dt>
|
||||
<dd class="col-sm-8">{{ counts.get('payments', 0) }}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/projects/import/confirm" class="d-flex gap-2">
|
||||
<input type="hidden" name="token" value="{{ token }}">
|
||||
<button type="submit" class="btn btn-primary">Импортировать проект</button>
|
||||
<a href="/projects/" class="btn btn-outline-secondary">Отмена</a>
|
||||
</form>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -10,7 +10,10 @@
|
||||
<div class="container mt-5">
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1>Projects</h1>
|
||||
<a href="/projects/new" class="btn btn-primary">+ Новый проект</a>
|
||||
<div class="d-flex gap-2">
|
||||
<a href="/projects/import" class="btn btn-outline-primary">Импорт проекта</a>
|
||||
<a href="/projects/new" class="btn btn-primary">+ Новый проект</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
|
||||
Reference in New Issue
Block a user