docuware_search.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import json
  2. import logging
  3. import docuware
  4. from dotenv import load_dotenv
  5. from .logging_setup import run_cli
  6. logger = logging.getLogger(__name__)
  7. load_dotenv()
  8. FILE_CABINETS = {
  9. "1": "Belegpool Reisacher",
  10. "2": "Belegpool Reisacher",
  11. "3": "Belegpool Reisacher Electric Mobility",
  12. "4": "Belegpool Reisacher SEK",
  13. }
  14. def main():
  15. dw = docuware.connect()
  16. for org in dw.organizations:
  17. logger.debug("DocuWare-Organisation verfügbar")
  18. for fc in org.file_cabinets:
  19. logger.debug("DocuWare-Ablage verfügbar")
  20. for b in org.baskets:
  21. logger.debug("DocuWare-Briefkorb verfügbar")
  22. def get_file_cabinet(client_db: str) -> docuware.FileCabinet:
  23. dw = docuware.connect()
  24. return dw.organization("1").file_cabinet(FILE_CABINETS[client_db])
  25. def search_files(client_db, customer_no=None, vehicle_no=None, document_no=None):
  26. """Return normalized metadata without downloading files or writing exports."""
  27. return get_adapter().search(client_db, customer_no, vehicle_no, document_no)
  28. def get_invoice_pdf_by_document_no(client_db: str, document_no: str) -> bytes:
  29. adapter = get_adapter()
  30. documents = adapter.search(client_db, document_no=document_no)
  31. if not documents:
  32. raise FileNotFoundError(document_no)
  33. return adapter.download(client_db, documents[0])[0]
  34. class LiveAdapter:
  35. def search(self, client_db, customer_no=None, vehicle_no=None, document_no=None):
  36. conditions = {
  37. key: value
  38. for key, value in (
  39. ("KUNDENNUMMER", customer_no),
  40. ("FAHRGESTELLNUMMER", vehicle_no),
  41. ("BELEGNUMMER", document_no),
  42. )
  43. if value
  44. }
  45. if not conditions:
  46. return []
  47. cabinet = get_file_cabinet(client_db)
  48. result = []
  49. for hit in cabinet.search_dialog().search(conditions, quote=docuware.QuoteMode.ALL):
  50. doc = hit.document
  51. fields = {f.name: f.value for f in doc.fields}
  52. def value(name):
  53. return str(fields.get(name) or "")
  54. # Verify exact matches as archives may configure full-text searches.
  55. if any(
  56. expected and value(field) != expected
  57. for expected, field in (
  58. (document_no, "Belegnummer"),
  59. (customer_no, "Kundennummer"),
  60. (vehicle_no, "Fahrgestellnummer"),
  61. )
  62. ):
  63. continue
  64. result.append(
  65. dict(
  66. archive=str(cabinet.id),
  67. id=str(doc.id),
  68. number=value("Belegnummer"),
  69. date=value("Beleg-Datum")[:10],
  70. kind=value("Dok.-/ Belegtyp"),
  71. editor=value("Bearbeitet von:"),
  72. customer=value("Kundennummer"),
  73. vehicle=value("Fahrgestellnummer"),
  74. name=str(doc.title or doc.id) + ("" if str(doc.title or "").lower().endswith(".pdf") else ".pdf"),
  75. )
  76. )
  77. return result
  78. def download(self, client_db, document):
  79. cabinet = get_file_cabinet(client_db)
  80. if str(cabinet.id) != document["archive"]:
  81. raise FileNotFoundError("Archiv nicht gefunden")
  82. return cabinet.get_document(document["id"]).download(keep_annotations=True)
  83. class MockAdapter:
  84. def _load(self):
  85. from pathlib import Path
  86. from .config import settings
  87. root = Path(settings.DOCUWARE_MOCK_PATH).resolve()
  88. data = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
  89. if data.get("version") != 1:
  90. raise ValueError("Unbekanntes Mockformat")
  91. return root, data
  92. def search(self, client_db, customer_no=None, vehicle_no=None, document_no=None):
  93. if not any((customer_no, vehicle_no, document_no)):
  94. return []
  95. _, data = self._load()
  96. if data.get("unavailable"):
  97. raise ConnectionError("Mock: DocuWare nicht erreichbar")
  98. return [
  99. dict(doc)
  100. for doc in data["documents"]
  101. if doc["client_db"] == client_db
  102. and all(
  103. not val or doc.get(key) == val
  104. for key, val in (("customer", customer_no), ("vehicle", vehicle_no), ("number", document_no))
  105. )
  106. ]
  107. def download(self, client_db, document):
  108. root, data = self._load()
  109. if data.get("unavailable"):
  110. raise ConnectionError("Mock: DocuWare nicht erreichbar")
  111. doc = next(
  112. (
  113. d
  114. for d in data["documents"]
  115. if d["client_db"] == client_db and d["id"] == document["id"] and d["archive"] == document["archive"]
  116. ),
  117. None,
  118. )
  119. if not doc or not doc.get("file"):
  120. raise FileNotFoundError("Dokumentdatei fehlt")
  121. path = (root / doc["file"]).resolve()
  122. if root not in path.parents:
  123. raise FileNotFoundError("Ungültiger Dokumentpfad")
  124. return path.read_bytes(), "application/pdf", doc["name"]
  125. def get_adapter():
  126. from .config import settings
  127. return MockAdapter() if settings.DOCUWARE_MODE == "mock" else LiveAdapter()
  128. if __name__ == "__main__":
  129. run_cli(main)