suche.py

153 Zeilen · 7,4 KB · Python
Rohdatei
"""Globale Suche über Dokumente, Geräte, Prüfungen, Lager, Steri-Chargen und Personal."""
from fastapi import APIRouter, Depends, Request
from sqlalchemy import and_, func, select
from sqlalchemy.orm import Session, selectinload

from ..praxis import enabled
from ..db import get_db
from ..models import Article, Device, Document, DocumentVersion, SteriBatch, Task, User
from ..search import highlight, matches, norm, snippet, split_terms
from ..security import get_current_user, has_role
from ..web import redirect, render
from .qr import scanned_code

router = APIRouter()
LIMIT = 25


def _hay(*parts) -> str:
    return norm(" ".join(str(p) for p in parts if p))


def _hit(title, url, subtitle=None, snip=None, badge=None, terms=None, score=1):
    return {"title": highlight(title, terms), "url": url, "subtitle": highlight(subtitle, terms) if subtitle else None,
            "snippet": snip, "badge": badge, "score": score}


def _documents(db: Session, user: User, terms: list[str]):
    leitung = has_role(user, "leitung")
    q = select(Document).options(selectinload(Document.versions))
    if not leitung:
        q = q.where(Document.active.is_(True))
    docs = {d.id: d for d in db.scalars(q).all()}
    if not docs:
        return []
    latest = select(DocumentVersion.document_id, func.max(DocumentVersion.version_no).label("mv")) \
        .group_by(DocumentVersion.document_id).subquery()
    texts = dict(db.execute(select(DocumentVersion.document_id, DocumentVersion.search_norm).join(
        latest, and_(latest.c.document_id == DocumentVersion.document_id,
                     latest.c.mv == DocumentVersion.version_no))).all())
    hits = []
    for d in docs.values():
        meta = _hay(d.title, d.category, d.description, d.current.file_name if d.current else None)
        body = texts.get(d.id) or ""
        if not matches(meta + " " + body, terms):
            continue
        in_title = matches(_hay(d.title), terms)
        hits.append((d, in_title, matches(meta, terms)))
    hits.sort(key=lambda h: (not h[1], not h[2], h[0].title.lower()))
    hits = hits[:LIMIT]
    # Textausschnitte nur für die angezeigten Treffer laden
    need = [d.current.id for d, _, meta_hit in hits if d.current and not meta_hit]
    plain = dict(db.execute(select(DocumentVersion.id, DocumentVersion.plain_text)
                            .where(DocumentVersion.id.in_(need))).all()) if need else {}
    out = []
    for d, in_title, meta_hit in hits:
        cur = d.current
        sub = f"{d.category} · Version {cur.version_no}" if cur else d.category
        if not d.active:
            sub += " · zurückgezogen"
        snip = snippet(plain.get(cur.id), terms) if cur and cur.id in plain else (
            highlight(d.description, terms) if d.description else None)
        out.append(_hit(d.title, f"/qm/{d.id}", sub, snip, "Volltext" if not meta_hit else None, terms))
    return out


def _devices(db: Session, terms):
    out = []
    for d in db.scalars(select(Device).order_by(Device.active.desc(), Device.name)).all():
        if matches(_hay(d.name, d.category, d.manufacturer, d.model, d.serial_no, d.inventory_no, d.location,
                        d.notes), terms):
            sub = " · ".join(x for x in [d.category, d.location, f"SN {d.serial_no}" if d.serial_no else None,
                                         f"Inv. {d.inventory_no}" if d.inventory_no else None] if x)
            out.append(_hit(d.name, f"/geraete/{d.id}", sub, snippet(d.notes, terms),
                            None if d.active else "ausgemustert", terms))
    return out[:LIMIT]


def _tasks(db: Session, terms):
    out = []
    for t in db.scalars(select(Task).options(selectinload(Task.device)).where(Task.active.is_(True))
                        .order_by(Task.next_due)).all():
        if matches(_hay(t.title, t.description, t.device.name if t.device else "allgemein"), terms):
            sub = f"{t.device.name if t.device else 'allgemein'} · {t.interval_label} · fällig {t.next_due:%d.%m.%Y}"
            out.append(_hit(t.title, f"/pruefungen/{t.id}", sub,
                            snippet(t.description, terms) if t.description else None, None, terms))
    return out[:LIMIT]


def _articles(db: Session, terms):
    out = []
    for a in db.scalars(select(Article).options(selectinload(Article.lots)).where(Article.active.is_(True))
                        .order_by(Article.name)).all():
        lots = " ".join(l.lot_no or "" for l in a.lots if l.quantity > 0)
        if matches(_hay(a.name, a.article_no, a.barcode, a.supplier, a.category, a.location, a.notes, lots), terms):
            sub = " · ".join(x for x in [a.category, a.location, f"Bestand {a.stock:g} {a.unit}"] if x)
            out.append(_hit(a.name, f"/lager/{a.id}", sub, None,
                            "nachbestellen" if a.min_stock and a.stock <= a.min_stock else None, terms))
    return out[:LIMIT]


def _batches(db: Session, q: str, terms):
    raw = q.strip()
    if not any(ch.isdigit() for ch in raw):
        return []
    like = f"%{raw.replace('%', '').replace('_', '')}%"
    rows = db.scalars(select(SteriBatch).options(selectinload(SteriBatch.device))
                      .where((SteriBatch.batch_no.like(like)) | (SteriBatch.cycle_no.like(like)))
                      .order_by(SteriBatch.started_at.desc()).limit(LIMIT)).all()
    return [_hit(b.batch_no, f"/steri/{b.id}",
                 f"{b.device.name} · {b.started_at:%d.%m.%Y %H:%M}" + (f" · Zyklus {b.cycle_no}" if b.cycle_no else ""),
                 None, b.status, [norm(raw)]) for b in rows]


def _staff(db: Session, user: User, terms):
    if not has_role(user, "leitung"):
        return []
    out = []
    for u in db.scalars(select(User).order_by(User.active.desc(), User.full_name)).all():
        if matches(_hay(u.full_name, u.username, u.job_title, u.email), terms):
            out.append(_hit(u.full_name, f"/personal/{u.id}", " · ".join(x for x in [u.job_title, u.username] if x),
                            None, None if u.active else "ausgeschieden", terms))
    return out[:LIMIT]


@router.get("/suche")
def search(request: Request, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    q = (request.query_params.get("q") or "").strip()[:200]
    terms = split_terms(q)
    if not terms:
        return render(request, "suche.html", q=q, search_q=q, groups=[], total=0, scanned=False)
    # Eingescannte QR-Codes und exakte Nummern führen direkt zum Objekt
    if code := scanned_code(q):
        return redirect(code)
    steri, lager = enabled("steri"), enabled("lager")
    exact = db.scalar(select(SteriBatch.id).where(SteriBatch.batch_no == q)) if steri else None
    if exact:
        return redirect(f"/steri/{exact}")
    art = db.scalars(select(Article.id).where(Article.active.is_(True), Article.barcode == q)).all() if lager else []
    if len(art) == 1:
        return redirect(f"/lager/{art[0]}")

    groups = [
        ("QM-Dokumente", "doc", _documents(db, user, terms)),
        ("Geräte", "device", _devices(db, terms)),
        ("Prüfungen & Wartung", "tasks", _tasks(db, terms)),
        ("Lager", "box", _articles(db, terms) if lager else []),
        ("Steri-Chargen", "steri", _batches(db, q, terms) if steri else []),
        ("Mitarbeiter", "users", _staff(db, user, terms)),
    ]
    groups = [g for g in groups if g[2]]
    total = sum(len(g[2]) for g in groups)
    return render(request, "suche.html", q=q, search_q=q, groups=groups, total=total, limit=LIMIT,
                  scanned=request.query_params.get("scan") == "1")