import json import logging import docuware from dotenv import load_dotenv from .logging_setup import run_cli logger = logging.getLogger(__name__) load_dotenv() FILE_CABINETS = { "1": "Belegpool Reisacher", "2": "Belegpool Reisacher", "3": "Belegpool Reisacher Electric Mobility", "4": "Belegpool Reisacher SEK", } def main(): dw = docuware.connect() for org in dw.organizations: logger.debug("DocuWare-Organisation verfügbar") for fc in org.file_cabinets: logger.debug("DocuWare-Ablage verfügbar") for b in org.baskets: logger.debug("DocuWare-Briefkorb verfügbar") def get_file_cabinet(client_db: str) -> docuware.FileCabinet: dw = docuware.connect() return dw.organization("1").file_cabinet(FILE_CABINETS[client_db]) def search_files(client_db, customer_no=None, vehicle_no=None, document_no=None): """Return normalized metadata without downloading files or writing exports.""" return get_adapter().search(client_db, customer_no, vehicle_no, document_no) def get_invoice_pdf_by_document_no(client_db: str, document_no: str) -> bytes: adapter = get_adapter() documents = adapter.search(client_db, document_no=document_no) if not documents: raise FileNotFoundError(document_no) return adapter.download(client_db, documents[0])[0] class LiveAdapter: def search(self, client_db, customer_no=None, vehicle_no=None, document_no=None): conditions = { key: value for key, value in ( ("KUNDENNUMMER", customer_no), ("FAHRGESTELLNUMMER", vehicle_no), ("BELEGNUMMER", document_no), ) if value } if not conditions: return [] cabinet = get_file_cabinet(client_db) result = [] for hit in cabinet.search_dialog().search(conditions, quote=docuware.QuoteMode.ALL): doc = hit.document fields = {f.name: f.value for f in doc.fields} def value(name): return str(fields.get(name) or "") # Verify exact matches as archives may configure full-text searches. if any( expected and value(field) != expected for expected, field in ( (document_no, "Belegnummer"), (customer_no, "Kundennummer"), (vehicle_no, "Fahrgestellnummer"), ) ): continue result.append( dict( archive=str(cabinet.id), id=str(doc.id), number=value("Belegnummer"), date=value("Beleg-Datum")[:10], kind=value("Dok.-/ Belegtyp"), editor=value("Bearbeitet von:"), customer=value("Kundennummer"), vehicle=value("Fahrgestellnummer"), name=str(doc.title or doc.id) + ("" if str(doc.title or "").lower().endswith(".pdf") else ".pdf"), ) ) return result def download(self, client_db, document): cabinet = get_file_cabinet(client_db) if str(cabinet.id) != document["archive"]: raise FileNotFoundError("Archiv nicht gefunden") return cabinet.get_document(document["id"]).download(keep_annotations=True) class MockAdapter: def _load(self): from pathlib import Path from .config import settings root = Path(settings.DOCUWARE_MOCK_PATH).resolve() data = json.loads((root / "manifest.json").read_text(encoding="utf-8")) if data.get("version") != 1: raise ValueError("Unbekanntes Mockformat") return root, data def search(self, client_db, customer_no=None, vehicle_no=None, document_no=None): if not any((customer_no, vehicle_no, document_no)): return [] _, data = self._load() if data.get("unavailable"): raise ConnectionError("Mock: DocuWare nicht erreichbar") return [ dict(doc) for doc in data["documents"] if doc["client_db"] == client_db and all( not val or doc.get(key) == val for key, val in (("customer", customer_no), ("vehicle", vehicle_no), ("number", document_no)) ) ] def download(self, client_db, document): root, data = self._load() if data.get("unavailable"): raise ConnectionError("Mock: DocuWare nicht erreichbar") doc = next( ( d for d in data["documents"] if d["client_db"] == client_db and d["id"] == document["id"] and d["archive"] == document["archive"] ), None, ) if not doc or not doc.get("file"): raise FileNotFoundError("Dokumentdatei fehlt") path = (root / doc["file"]).resolve() if root not in path.parents: raise FileNotFoundError("Ungültiger Dokumentpfad") return path.read_bytes(), "application/pdf", doc["name"] def get_adapter(): from .config import settings return MockAdapter() if settings.DOCUWARE_MODE == "mock" else LiveAdapter() if __name__ == "__main__": run_cli(main)