forderung_history.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from typing import Literal
  2. from urllib.parse import quote
  3. from fastapi import HTTPException
  4. from sqlalchemy import text
  5. from sqlalchemy.orm import Session
  6. from .jinja_templates import templates
  7. HistoryScope = Literal["invoice", "open", "vehicle", "debtor"]
  8. def history_context(db: Session, pkey: dict[str, str], section: str, scope: HistoryScope = "invoice") -> dict:
  9. values = {"client_db": pkey["Client_DB"], "beleg_nr": pkey["Beleg_Nr"], "scope": scope}
  10. invoice = (
  11. db.execute(
  12. text("SELECT TOP 1 * FROM dbo.Forderungen_Kopf WHERE Client_DB = :client_db AND Beleg_Nr = :beleg_nr"),
  13. values,
  14. )
  15. .mappings()
  16. .first()
  17. )
  18. if invoice is None:
  19. raise HTTPException(status_code=404, detail="Forderung nicht gefunden")
  20. return section_context(db, pkey, invoice, section, scope)
  21. def section_context(db: Session, pkey: dict[str, str], invoice, section: str, scope: HistoryScope = "invoice") -> dict:
  22. # Neither the customer nor the vehicle can be supplied by the browser.
  23. invoice = getattr(invoice, "_mapping", invoice)
  24. vehicle_missing = not str(invoice["Fahrzeug_Nr"] or "").strip()
  25. values = {"client_db": pkey["Client_DB"], "beleg_nr": pkey["Beleg_Nr"], "scope": scope}
  26. rows = []
  27. if scope != "vehicle" or not vehicle_missing:
  28. query = templates.env.get_template(f"forderungen/details/queries/forderungen_{section}.sql").render(scope=scope)
  29. rows = db.execute(
  30. text(query).execution_options(query_name=f"forderungen/details/queries/forderungen_{section}.sql"), values
  31. ).fetchall()
  32. return {
  33. "forderungen_details": [invoice],
  34. f"forderungen_{section}": rows,
  35. f"{section}_scope": scope,
  36. "vehicle_missing": vehicle_missing,
  37. "detail_url": "/app/forderungen/details/" + quote(f"{pkey['Client_DB']}_{pkey['Beleg_Nr']}", safe=""),
  38. }