import asyncio
import logging
import re
from datetime import date
from functools import lru_cache
from pathlib import Path
from urllib.parse import quote
import mammoth
from markupsafe import Markup
from fastapi import APIRouter, Depends, File, Form, Request, UploadFile
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, selectinload
from ..config import settings
from ..convert import ConversionError, convertible, office_to_pdf, pdf_name
from ..convert import enabled as convert_enabled
from ..convert import job_running, pending_conversions
from ..db import get_db
from ..search import index_version
from ..models import Document, DocumentAck, DocumentVersion, User
from ..praxis import doc_categories
from ..security import csrf_protect, get_current_user, require_role
from ..services import active_users, document_review_date
from ..web import audit, due_status, flash, parse_date, parse_int, redirect, render, save_upload, save_upload_or_scan
router = APIRouter(prefix="/qm", dependencies=[Depends(csrf_protect)])
log = logging.getLogger("praxis.qm")
SAFE_HREF = re.compile(r'href="(?!https?:|mailto:|#)[^"]*"', re.I)
@lru_cache(maxsize=64)
def _docx_html(path: str) -> str:
with open(settings.upload_dir / path, "rb") as f:
html = mammoth.convert_to_html(f).value
return SAFE_HREF.sub('href="#"', html)
async def _auto_convert(request: Request, v: DocumentVersion) -> None:
"""Office-Datei beim Upload in PDF umwandeln; Fehler nur als Hinweis, Upload bleibt gültig."""
if not convert_enabled() or not convertible(v.file_path):
return
try:
v.pdf_path = await office_to_pdf(v.file_path)
except ConversionError as e:
log.warning("PDF-Umwandlung fehlgeschlagen: %s", e)
flash(request, f"Die Datei wurde gespeichert, aber nicht in PDF umgewandelt: {e}", "warn")
def _url(path: str, name: str | None) -> str:
return f"/dateien/{path}?name={quote(name or Path(path).name)}"
def version_view(doc_id: int, v: DocumentVersion, is_current: bool) -> dict:
"""Wohin führt „ansehen“ in der Versionsliste?
pdf: PDF im neuen Tab · page: Vorschau auf der Seite · none: nichts anzeigbar."""
if v.pdf_path:
return {"kind": "pdf", "url": _url(v.pdf_path, pdf_name(v.file_name))}
if v.file_path and Path(v.file_path).suffix.lower() == ".pdf":
return {"kind": "pdf", "url": _url(v.file_path, v.file_name)}
viewable = bool(v.content) or (v.file_path and Path(v.file_path).suffix.lower() in
(".png", ".jpg", ".jpeg", ".webp", ".docx", ".txt", ".csv", ".log"))
if viewable:
return {"kind": "page", "url": "#inhalt" if is_current else f"/qm/{doc_id}?version={v.id}#inhalt"}
return {"kind": "none", "convertible": convertible(v.file_path)}
def file_preview(v: DocumentVersion | None) -> dict | None:
"""Art der Vorschau für die Datei einer Version: pdf | image | docx | text | none."""
if not v or not v.file_path:
return None
if v.pdf_path:
return {"kind": "pdf", "url": _url(v.pdf_path, pdf_name(v.file_name)), "converted": True}
ext = Path(v.file_path).suffix.lower()
if ext == ".pdf":
return {"kind": "pdf", "url": _url(v.file_path, v.file_name)}
if ext in (".png", ".jpg", ".jpeg", ".webp"):
return {"kind": "image", "url": _url(v.file_path, v.file_name)}
if ext == ".docx":
try:
return {"kind": "docx", "html": Markup(_docx_html(v.file_path))}
except Exception as e: # noqa: BLE001
log.warning("Word-Vorschau fehlgeschlagen (%s): %s", v.file_path, e)
return {"kind": "none"}
if ext in (".txt", ".csv", ".log"):
try:
text = (settings.upload_dir / v.file_path).read_text(encoding="utf-8", errors="replace")[:200_000]
return {"kind": "text", "text": text}
except OSError:
return {"kind": "none"}
return {"kind": "none"}
leitung = require_role("leitung")
def clean_category(c: str | None) -> str:
c = " ".join((c or "").split())[:60]
return c or "Sonstiges"
def category_list(db: Session, only_used: bool = False) -> list[str]:
"""Kategorien: Standardliste zuerst, dann eigene (z. B. aus Ordnern) alphabetisch."""
used = set(db.scalars(select(Document.category).where(Document.active.is_(True)).distinct()).all())
DOC_CATEGORIES = doc_categories()
if only_used:
return [c for c in DOC_CATEGORIES if c in used] + sorted(used - set(DOC_CATEGORIES), key=str.lower)
return list(DOC_CATEGORIES) + sorted(used - set(DOC_CATEGORIES), key=str.lower)
def _staff(db: Session) -> list[User]:
return [u for u in active_users(db) if u.role != "admin" or u.kiosk_visible]
@router.get("")
def documents(request: Request, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
cat = request.query_params.get("kat") or ""
show_all = request.query_params.get("alle") == "1"
q = select(Document).options(selectinload(Document.versions)).order_by(Document.category, Document.title)
if not show_all:
q = q.where(Document.active.is_(True))
if cat:
q = q.where(Document.category == cat)
docs = db.scalars(q).all()
my_acks = set(db.scalars(select(DocumentAck.version_id).where(DocumentAck.user_id == user.id)).all())
reviews = {d.id: document_review_date(d) for d in docs}
return render(request, "qm/list.html", docs=docs, my_acks=my_acks, reviews=reviews, cat=cat, show_all=show_all,
users=_staff(db), tabs=category_list(db, only_used=True), all_categories=category_list(db),
pending=pending_conversions(db), job_running=job_running())
@router.get("/lesebestaetigungen")
def ack_matrix(request: Request, user: User = Depends(leitung), db: Session = Depends(get_db)):
docs = db.scalars(select(Document).options(selectinload(Document.versions))
.where(Document.active.is_(True), Document.requires_ack.is_(True))
.order_by(Document.category, Document.title)).all()
acks = {(a.version_id, a.user_id): a for a in db.scalars(select(DocumentAck)).all()}
return render(request, "qm/acks.html", docs=docs, users=_staff(db), acks=acks)
@router.post("/neu")
async def doc_create(request: Request, title: str = Form(...), category: str = Form(...), description: str = Form(""),
requires_ack: bool = Form(False), review_months: str = Form(""), owner_id: str = Form(""),
valid_from: str = Form(""), change_note: str = Form(""), content: str = Form(""),
file: UploadFile | None = File(None),
user: User = Depends(leitung), db: Session = Depends(get_db)):
doc = Document(title=title.strip()[:200], category=clean_category(category),
description=description.strip() or None, requires_ack=requires_ack,
review_months=parse_int(review_months), owner_id=parse_int(owner_id))
db.add(doc)
db.flush()
path, name = await save_upload_or_scan(request, file, "qm")
v = DocumentVersion(document_id=doc.id, version_no=1, valid_from=parse_date(valid_from) or date.today(),
change_note=change_note.strip() or "Erstfassung", file_path=path, file_name=name,
content=content.strip() or None, created_by_id=user.id)
db.add(v)
await _auto_convert(request, v)
await asyncio.to_thread(index_version, v)
audit(db, user, "qm.angelegt", "document", doc.id, titel=doc.title, datei=name, pdf=bool(v.pdf_path))
db.commit()
flash(request, f"„{doc.title}“ angelegt." + (f" „{name}“ wurde in PDF umgewandelt." if v.pdf_path else ""))
return redirect(f"/qm/{doc.id}")
@router.get("/{did}")
def doc_detail(did: int, request: Request, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
doc = db.get(Document, did)
if not doc:
return redirect("/qm")
cur = doc.current
acks = {a.user_id: a for a in cur.acks} if cur else {}
review = document_review_date(doc)
vid = parse_int(request.query_params.get("version"))
shown = next((v for v in doc.versions if v.id == vid), cur)
return render(request, "qm/detail.html", doc=doc, cur=cur, acks=acks, users=_staff(db), review=review,
review_status=due_status(review, 30) if review else "none", shown=shown,
preview=file_preview(shown), can_convert=convert_enabled() and shown is not None
and convertible(shown.file_path) and not shown.pdf_path,
views={v.id: version_view(did, v, cur is not None and v.id == cur.id) for v in doc.versions},
converter_on=convert_enabled(), all_categories=category_list(db))
@router.post("/{did}/bestaetigen")
def doc_ack(did: int, request: Request, version_id: int = Form(...),
user: User = Depends(get_current_user), db: Session = Depends(get_db)):
doc = db.get(Document, did)
if not doc.current or doc.current.id != version_id:
flash(request, "Inzwischen gibt es eine neuere Version – bitte diese lesen.", "warn")
return redirect(f"/qm/{did}")
try:
db.add(DocumentAck(version_id=version_id, user_id=user.id))
audit(db, user, "qm.gelesen", "document", did, titel=doc.title, version=doc.current.version_no)
db.commit()
flash(request, f"„{doc.title}“ (Version {doc.current.version_no}) als gelesen bestätigt.")
except IntegrityError:
db.rollback()
return redirect(f"/qm/{did}")
@router.post("/{did}/version")
async def doc_new_version(did: int, request: Request, valid_from: str = Form(""), change_note: str = Form(...),
content: str = Form(""), keep_file: bool = Form(False),
file: UploadFile | None = File(None), user: User = Depends(leitung),
db: Session = Depends(get_db)):
doc = db.get(Document, did)
nr = (doc.current.version_no if doc.current else 0) + 1
path, name = await save_upload_or_scan(request, file, "qm")
pdf = None
if not path and keep_file and doc.current:
path, name, pdf = doc.current.file_path, doc.current.file_name, doc.current.pdf_path
v = DocumentVersion(document_id=doc.id, version_no=nr, valid_from=parse_date(valid_from) or date.today(),
change_note=change_note.strip(), file_path=path, file_name=name, pdf_path=pdf,
content=content.strip() or None, created_by_id=user.id)
db.add(v)
if not pdf:
await _auto_convert(request, v)
await asyncio.to_thread(index_version, v)
audit(db, user, "qm.neue_version", "document", did, titel=doc.title, version=nr, aenderung=change_note.strip(),
datei=name, pdf=bool(v.pdf_path))
db.commit()
flash(request, f"Version {nr} veröffentlicht." + (" Alle müssen neu bestätigen." if doc.requires_ack else ""))
return redirect(f"/qm/{did}")
@router.post("/{did}/pdf")
async def doc_convert(did: int, request: Request, version_id: int = Form(...), user: User = Depends(leitung),
db: Session = Depends(get_db)):
v = db.get(DocumentVersion, version_id)
if not v or v.document_id != did or not convertible(v.file_path):
flash(request, "Für diese Version gibt es keine umwandelbare Datei.", "error")
return redirect(f"/qm/{did}")
try:
v.pdf_path = await office_to_pdf(v.file_path)
await asyncio.to_thread(index_version, v)
audit(db, user, "qm.pdf_erzeugt", "document", did, version=v.version_no, datei=v.file_name)
db.commit()
flash(request, f"„{v.file_name}“ wurde in PDF umgewandelt.")
except ConversionError as e:
log.warning("PDF-Umwandlung fehlgeschlagen: %s", e)
flash(request, f"Umwandlung fehlgeschlagen: {e}", "error")
return redirect(f"/qm/{did}" + (f"?version={v.id}" if v.document.current and v.document.current.id != v.id else ""))
@router.post("/{did}/bearbeiten")
def doc_update(did: int, request: Request, title: str = Form(...), category: str = Form(...),
description: str = Form(""), requires_ack: bool = Form(False), review_months: str = Form(""),
owner_id: str = Form(""), active: bool = Form(False), user: User = Depends(leitung),
db: Session = Depends(get_db)):
doc = db.get(Document, did)
doc.title = title.strip()
doc.category = clean_category(category) if category.strip() else doc.category
doc.description = description.strip() or None
doc.requires_ack = requires_ack
doc.review_months = parse_int(review_months)
doc.owner_id = parse_int(owner_id)
doc.active = active
audit(db, user, "qm.geaendert", "document", did, titel=doc.title, aktiv=active)
db.commit()
flash(request, "Gespeichert.")
return redirect(f"/qm/{did}")