forderung_history.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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 = db.execute(
  11. text("SELECT TOP 1 * FROM dbo.Forderungen_Kopf WHERE Client_DB = :client_db AND Beleg_Nr = :beleg_nr"),
  12. values,
  13. ).mappings().first()
  14. if invoice is None:
  15. raise HTTPException(status_code=404, detail="Forderung nicht gefunden")
  16. return section_context(db, pkey, invoice, section, scope)
  17. def section_context(db: Session, pkey: dict[str, str], invoice, section: str, scope: HistoryScope = "invoice") -> dict:
  18. # Neither the customer nor the vehicle can be supplied by the browser.
  19. invoice = getattr(invoice, "_mapping", invoice)
  20. vehicle_missing = not str(invoice["Fahrzeug_Nr"] or "").strip()
  21. values = {"client_db": pkey["Client_DB"], "beleg_nr": pkey["Beleg_Nr"], "scope": scope}
  22. rows = []
  23. if scope != "vehicle" or not vehicle_missing:
  24. query = templates.env.get_template(f"forderungen/details/queries/forderungen_{section}.sql").render(scope=scope)
  25. rows = db.execute(text(query).execution_options(query_name=f'forderungen/details/queries/forderungen_{section}.sql'), values).fetchall()
  26. return {
  27. "forderungen_details": [invoice],
  28. f"forderungen_{section}": rows,
  29. f"{section}_scope": scope,
  30. "vehicle_missing": vehicle_missing,
  31. "detail_url": "/app/forderungen/details/" + quote(f"{pkey['Client_DB']}_{pkey['Beleg_Nr']}", safe=""),
  32. }