import csv
import io
from datetime import date
from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import StreamingResponse
from sqlalchemy import or_, select
from sqlalchemy.orm import Session, selectinload
from ..praxis import require_module
from ..db import get_db
from ..models import Article, StockLot, StockMovement, User
from ..security import Forbidden, csrf_protect, get_current_user, require_role
from ..services import stock_alerts
from ..web import audit, flash, parse_date, parse_float, parse_int, redirect, render
router = APIRouter(prefix="/lager", dependencies=[Depends(csrf_protect), require_module("lager")])
leitung = require_role("leitung")
def _categories(db: Session) -> list[str]:
return sorted({c for c in db.scalars(select(Article.category).where(Article.category.is_not(None))).all() if c})
@router.get("")
def articles(request: Request, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
qp = request.query_params
search = (qp.get("q") or "").strip()
cat = qp.get("kat") or ""
q = select(Article).options(selectinload(Article.lots)).where(Article.active.is_(True)).order_by(Article.name)
if search:
from .qr import scanned_code
if code := scanned_code(search):
return redirect(code)
exact = db.scalars(select(Article).where(Article.active.is_(True),
or_(Article.barcode == search, Article.article_no == search))).all()
if len(exact) == 1:
return redirect(f"/lager/{exact[0].id}")
like = f"%{search}%"
q = q.where(or_(Article.name.ilike(like), Article.article_no.ilike(like), Article.barcode.ilike(like),
Article.supplier.ilike(like)))
if cat:
q = q.where(Article.category == cat)
low, lots = stock_alerts(db)
exp_ids = {l.article_id for l in lots}
return render(request, "lager/list.html", articles=db.scalars(q).all(), search=search, cat=cat,
categories=_categories(db), low_ids={a.id for a in low}, exp_ids=exp_ids)
@router.get("/bestellliste")
def order_list(request: Request, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
low, lots = stock_alerts(db)
if "csv" in request.query_params:
buf = io.StringIO()
w = csv.writer(buf, delimiter=";")
w.writerow(["Artikel", "Art.-Nr.", "Lieferant", "Bestand", "Mindestbestand", "Bestellmenge", "Einheit"])
for a in low:
w.writerow([a.name, a.article_no or "", a.supplier or "", f"{a.stock:g}", f"{a.min_stock:g}",
f"{a.order_qty:g}" if a.order_qty else "", a.unit])
return StreamingResponse(iter(["" + buf.getvalue()]), media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="bestellliste_{date.today():%Y%m%d}.csv"'})
by_supplier: dict[str, list[Article]] = {}
for a in low:
by_supplier.setdefault(a.supplier or "Ohne Lieferant", []).append(a)
return render(request, "lager/orders.html", by_supplier=by_supplier, lots=lots)
@router.get("/neu")
def article_new(request: Request, user: User = Depends(leitung), db: Session = Depends(get_db)):
return render(request, "lager/form.html", a=None, categories=_categories(db),
prefill_barcode=(request.query_params.get("barcode") or "").strip()[:120])
def _apply(a: Article, f) -> None:
a.name = f["name"].strip()
for k in ("article_no", "barcode", "supplier", "category", "location", "notes"):
setattr(a, k, (f.get(k) or "").strip() or None)
a.unit = (f.get("unit") or "Stück").strip()
a.min_stock = parse_float(f.get("min_stock"), 0) or 0
a.order_qty = parse_float(f.get("order_qty"))
a.track_lots = f.get("track_lots") == "1"
def _check_barcode(db: Session, a: Article) -> None:
"""Ein Barcode darf nur zu einem aktiven Artikel gehören (sonst ist der Scan mehrdeutig)."""
if not a.barcode:
return
from .scan import barcode_variants
other = db.scalar(select(Article).where(Article.active.is_(True), Article.id != (a.id or 0),
Article.barcode.in_(barcode_variants(a.barcode))))
if other:
raise Forbidden(f"Der Barcode {a.barcode} ist schon dem Artikel „{other.name}“ zugeordnet.")
@router.post("/neu")
async def article_create(request: Request, user: User = Depends(leitung), db: Session = Depends(get_db)):
f = await request.form()
a = Article()
_apply(a, f)
_check_barcode(db, a)
db.add(a)
db.flush()
audit(db, user, "artikel.angelegt", "article", a.id, name=a.name)
db.commit()
flash(request, f"„{a.name}“ angelegt.")
return redirect(f"/lager/{a.id}")
@router.get("/{aid}")
def article_detail(aid: int, request: Request, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
a = db.get(Article, aid)
if not a:
return redirect("/lager")
moves = db.scalars(select(StockMovement).options(selectinload(StockMovement.user), selectinload(StockMovement.lot))
.where(StockMovement.article_id == aid)
.order_by(StockMovement.created_at.desc(), StockMovement.id.desc()).limit(50)).all()
qp = request.query_params
scan = None
if qp.get("gescannt"):
try:
exp = date.fromisoformat(qp["verfall"]) if qp.get("verfall") else None
except ValueError:
exp = None
lot_no = (qp.get("lot") or "").strip()[:80] or None
match = next((l for l in a.lots if l.quantity > 0 and lot_no and l.lot_no == lot_no), None)
scan = {"lot": lot_no, "expiry": exp, "lot_id": match.id if match else None,
"expired": bool(exp and exp < date.today())}
return render(request, "lager/detail.html", a=a, moves=moves, lots=[l for l in a.lots if l.quantity > 0],
scan=scan)
@router.get("/{aid}/bearbeiten")
def article_edit(aid: int, request: Request, user: User = Depends(leitung), db: Session = Depends(get_db)):
return render(request, "lager/form.html", a=db.get(Article, aid), categories=_categories(db))
@router.post("/{aid}/bearbeiten")
async def article_update(aid: int, request: Request, user: User = Depends(leitung), db: Session = Depends(get_db)):
f = await request.form()
a = db.get(Article, aid)
_apply(a, f)
a.active = f.get("active") == "1"
if a.active:
_check_barcode(db, a)
audit(db, user, "artikel.geaendert", "article", aid, name=a.name, aktiv=a.active)
db.commit()
flash(request, "Gespeichert.")
return redirect(f"/lager/{aid}")
def _move(db, a: Article, lot: StockLot, delta: float, kind: str, user: User, note: str | None):
lot.quantity = round(lot.quantity + delta, 3)
db.add(StockMovement(article_id=a.id, lot_id=lot.id, delta=delta, kind=kind, user_id=user.id, note=note))
@router.post("/{aid}/zugang")
def stock_in(aid: int, request: Request, qty: str = Form(...), lot_no: str = Form(""), expiry: str = Form(""),
note: str = Form(""), user: User = Depends(get_current_user), db: Session = Depends(get_db)):
a = db.get(Article, aid)
amount = parse_float(qty)
if not amount or amount <= 0:
flash(request, "Bitte eine Menge größer 0 angeben.", "error")
return redirect(f"/lager/{aid}")
lot_no = lot_no.strip() or None
exp = parse_date(expiry)
if a.track_lots and not lot_no:
flash(request, "Für diesen Artikel bitte Charge/LOT angeben.", "error")
return redirect(f"/lager/{aid}")
lot = next((l for l in a.lots if l.lot_no == lot_no and l.expiry == exp), None)
if lot is None:
lot = StockLot(article_id=a.id, lot_no=lot_no, expiry=exp, quantity=0)
db.add(lot)
db.flush()
_move(db, a, lot, amount, "zugang", user, note.strip() or None)
a.ordered_on = None
audit(db, user, "lager.zugang", "article", aid, artikel=a.name, menge=amount, charge=lot_no, verfall=exp)
db.commit()
flash(request, f"+{amount:g} {a.unit} gebucht.")
return redirect(f"/lager/{aid}")
@router.post("/{aid}/entnahme")
def stock_out(aid: int, request: Request, qty: str = Form(...), lot_id: str = Form(""), note: str = Form(""),
user: User = Depends(get_current_user), db: Session = Depends(get_db)):
a = db.get(Article, aid)
amount = parse_float(qty)
if not amount or amount <= 0:
flash(request, "Bitte eine Menge größer 0 angeben.", "error")
return redirect(f"/lager/{aid}")
if amount > a.stock + 1e-9:
flash(request, f"Nicht genug Bestand (vorhanden: {a.stock:g} {a.unit}).", "error")
return redirect(f"/lager/{aid}")
lid = parse_int(lot_id)
if lid:
lots = [l for l in a.lots if l.id == lid]
if not lots or lots[0].quantity < amount - 1e-9:
flash(request, "In dieser Charge ist nicht genug Bestand.", "error")
return redirect(f"/lager/{aid}")
else: # First expired, first out
lots = sorted([l for l in a.lots if l.quantity > 0], key=lambda l: (l.expiry or date.max, l.id))
rest = amount
for lot in lots:
take = min(rest, lot.quantity)
if take > 0:
_move(db, a, lot, -take, "entnahme", user, note.strip() or None)
rest = round(rest - take, 3)
if rest <= 0:
break
audit(db, user, "lager.entnahme", "article", aid, artikel=a.name, menge=amount)
db.commit()
flash(request, f"−{amount:g} {a.unit} entnommen. Bestand jetzt {a.stock:g}.")
if a.min_stock and a.stock <= a.min_stock:
flash(request, f"Mindestbestand erreicht – „{a.name}“ steht auf der Bestellliste.", "warn")
return redirect(f"/lager/{aid}")
@router.post("/{aid}/inventur")
async def stock_count(aid: int, request: Request, user: User = Depends(leitung), db: Session = Depends(get_db)):
f = await request.form()
a = db.get(Article, aid)
changed = 0
for lot in a.lots:
key = f"lot_{lot.id}"
if key not in f or f[key] == "":
continue
new = parse_float(f[key])
if new is None or new < 0:
raise Forbidden("Bestand darf nicht negativ sein.")
delta = round(new - lot.quantity, 3)
if delta:
_move(db, a, lot, delta, "korrektur", user, "Inventur")
changed += 1
audit(db, user, "lager.inventur", "article", aid, artikel=a.name, geaenderte_chargen=changed, bestand=a.stock)
db.commit()
flash(request, f"Inventur gespeichert ({changed} Änderung(en)).")
return redirect(f"/lager/{aid}")
@router.post("/{aid}/verfall/{lid}")
def stock_dispose(aid: int, lid: int, request: Request, user: User = Depends(get_current_user),
db: Session = Depends(get_db)):
a = db.get(Article, aid)
lot = db.get(StockLot, lid)
if lot.article_id != a.id or lot.quantity <= 0:
return redirect(f"/lager/{aid}")
qty = lot.quantity
_move(db, a, lot, -qty, "verfall", user, "Verfallen / entsorgt")
audit(db, user, "lager.verfall", "article", aid, artikel=a.name, charge=lot.lot_no, menge=qty)
db.commit()
flash(request, f"Charge {lot.lot_no or '–'} ({qty:g} {a.unit}) als entsorgt gebucht.")
return redirect(f"/lager/{aid}")
@router.post("/{aid}/bestellt")
def mark_ordered(aid: int, request: Request, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
a = db.get(Article, aid)
a.ordered_on = None if a.ordered_on else date.today()
audit(db, user, "lager.bestellt" if a.ordered_on else "lager.bestellt_zurueck", "article", aid, artikel=a.name)
db.commit()
back = request.query_params.get("back", f"/lager/{aid}")
return redirect(back if back.startswith("/") and not back.startswith("//") else f"/lager/{aid}")