Verwaltbare Einheiten mit Umrechnung + Chargen bearbeiten + gezieltes Auslagern
Einheiten (neu):
- Tabelle units (name, kind=count|weight|volume, factor, is_builtin); eingebaut
Stueck/Gramm/Kilogramm/Milliliter/Liter, Admin kann eigene anlegen (z.B. Pfund=500g).
- Bestaende bleiben intern in kanonischer Basis (Stueck/Gramm/Milliliter);
Product.display_unit_id und Group.min_stock_unit_id als nullable FKs.
- Neuer Umrechnungs-Service (services/conversion.py) ersetzt die feste Einheitenlogik;
Ein-/Auslagern und Gruppen-Mindestbestand rechnen ueber den Faktor.
- Gruppen-Mindestbestand mit Einheit; Gruppenbestand summiert nur Produkte
passender Art. Neue Verwaltungsseite "Einheiten" (Admin).
- Schonende Migration beim Start: ADD COLUMN IF NOT EXISTS (Postgres), damit
bestehende Installationen ihre Daten behalten.
Chargen:
- PATCH /lots/{id} und DELETE /lots/{id}: Menge/MHD korrigieren, Charge loeschen
(wird als Korrektur-Bewegung protokolliert). Bearbeitung im Produktdetail.
Auslagern:
- Optionales lot_id: gezielt aus einer bestimmten Charge/MHD abbuchen statt FEFO;
Auswahl-Dropdown in der Auslagern-Seite.
Sonstiges: Roadmap aktualisiert, Tests fuer die Umrechnung.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,7 @@ from ..database import get_db
|
||||
from ..deps import get_current_user, require_admin
|
||||
from ..models import Group, Product, User
|
||||
from ..schemas import GroupCreate, GroupOut, GroupUpdate
|
||||
from ..services.conversion import BASE_OF_KIND
|
||||
from ..services.stock import current_stock
|
||||
|
||||
router = APIRouter(prefix="/groups", tags=["groups"])
|
||||
@@ -14,7 +15,17 @@ def _group_to_out(db: Session, group: Group) -> GroupOut:
|
||||
out = GroupOut.model_validate(group)
|
||||
products = db.query(Product).filter(Product.group_id == group.id).all()
|
||||
out.product_count = len(products)
|
||||
out.stock = float(sum(current_stock(db, p.id) for p in products))
|
||||
unit = group.min_stock_unit
|
||||
if unit is not None:
|
||||
# Bestand nur über Produkte gleicher Art, in der Gruppen-Einheit ausgedrückt.
|
||||
base = BASE_OF_KIND[unit.kind]
|
||||
matching = [p for p in products if p.base_unit == base]
|
||||
stock_base = float(sum(current_stock(db, p.id) for p in matching))
|
||||
out.stock = stock_base / unit.factor
|
||||
out.min_stock_unit_name = unit.name
|
||||
out.kind = unit.kind.value
|
||||
else:
|
||||
out.stock = float(sum(current_stock(db, p.id) for p in products))
|
||||
return out
|
||||
|
||||
|
||||
@@ -34,7 +45,11 @@ def create_group(
|
||||
) -> GroupOut:
|
||||
if db.query(Group).filter(Group.name == payload.name).first():
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, "Gruppe existiert bereits")
|
||||
group = Group(name=payload.name, min_stock=payload.min_stock)
|
||||
group = Group(
|
||||
name=payload.name,
|
||||
min_stock=payload.min_stock,
|
||||
min_stock_unit_id=payload.min_stock_unit_id,
|
||||
)
|
||||
db.add(group)
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
|
||||
@@ -7,6 +7,7 @@ from ..deps import get_current_user, require_admin
|
||||
from ..models import BaseUnit, Product, User
|
||||
from ..off import lookup_barcode
|
||||
from ..schemas import LookupResult, ProductCreate, ProductOut, ProductUpdate
|
||||
from ..services.conversion import ConversionError, resolve_product_unit
|
||||
|
||||
router = APIRouter(prefix="/products", tags=["products"])
|
||||
|
||||
@@ -66,12 +67,20 @@ def create_product(
|
||||
raise HTTPException(
|
||||
status.HTTP_409_CONFLICT, "Ein Produkt mit diesem Barcode existiert bereits"
|
||||
)
|
||||
base_unit = payload.base_unit
|
||||
display_unit_id = None
|
||||
if payload.unit_id is not None:
|
||||
try:
|
||||
base_unit, display_unit_id = resolve_product_unit(db, payload.unit_id)
|
||||
except ConversionError as exc:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
|
||||
product = Product(
|
||||
barcode=payload.barcode or None,
|
||||
name=payload.name,
|
||||
brand=payload.brand,
|
||||
image_url=payload.image_url,
|
||||
base_unit=payload.base_unit,
|
||||
base_unit=base_unit,
|
||||
display_unit_id=display_unit_id,
|
||||
package_size=payload.package_size,
|
||||
group_id=payload.group_id,
|
||||
min_stock=payload.min_stock,
|
||||
@@ -105,6 +114,17 @@ def update_product(
|
||||
raise HTTPException(
|
||||
status.HTTP_409_CONFLICT, "Ein anderes Produkt hat diesen Barcode bereits"
|
||||
)
|
||||
# Einheit: unit_id (falls gesetzt) bestimmt base_unit + Anzeigeeinheit.
|
||||
if "unit_id" in data:
|
||||
unit_id = data.pop("unit_id")
|
||||
data.pop("base_unit", None) # unit_id hat Vorrang
|
||||
if unit_id is None:
|
||||
product.display_unit_id = None
|
||||
else:
|
||||
try:
|
||||
product.base_unit, product.display_unit_id = resolve_product_unit(db, unit_id)
|
||||
except ConversionError as exc:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
|
||||
for field, value in data.items():
|
||||
setattr(product, field, value)
|
||||
db.commit()
|
||||
|
||||
@@ -4,7 +4,7 @@ from sqlalchemy.orm import Session
|
||||
from ..crud import resolve_product
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user
|
||||
from ..models import Lot, User
|
||||
from ..models import Lot, Movement, MovementType, User
|
||||
from ..schemas import (
|
||||
BatchCheckInRequest,
|
||||
BatchCheckInResponse,
|
||||
@@ -13,9 +13,16 @@ from ..schemas import (
|
||||
CheckOutRequest,
|
||||
CheckOutResponse,
|
||||
LotOut,
|
||||
LotUpdate,
|
||||
)
|
||||
from ..services.conversion import ConversionError
|
||||
from ..services.stock import (
|
||||
StockError,
|
||||
check_in,
|
||||
check_out,
|
||||
check_out_lot,
|
||||
current_stock,
|
||||
)
|
||||
from ..services.stock import StockError, check_in, check_out, current_stock
|
||||
from ..services.units import UnitError
|
||||
|
||||
router = APIRouter(tags=["stock"])
|
||||
|
||||
@@ -38,7 +45,7 @@ def stock_checkin(
|
||||
user=user,
|
||||
note=payload.note,
|
||||
)
|
||||
except UnitError as exc:
|
||||
except ConversionError as exc:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
|
||||
db.commit()
|
||||
db.refresh(lot)
|
||||
@@ -74,7 +81,7 @@ def stock_checkin_batch(
|
||||
note=payload.note,
|
||||
)
|
||||
)
|
||||
except UnitError as exc:
|
||||
except ConversionError as exc:
|
||||
db.rollback()
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
|
||||
db.commit()
|
||||
@@ -94,15 +101,31 @@ def stock_checkout(
|
||||
) -> CheckOutResponse:
|
||||
product = resolve_product(db, payload.product_id, payload.barcode)
|
||||
try:
|
||||
affected = check_out(
|
||||
db,
|
||||
product=product,
|
||||
quantity=payload.quantity,
|
||||
unit=payload.unit,
|
||||
user=user,
|
||||
note=payload.note,
|
||||
)
|
||||
except UnitError as exc:
|
||||
if payload.lot_id is not None:
|
||||
lot = db.get(Lot, payload.lot_id)
|
||||
if lot is None or lot.product_id != product.id:
|
||||
raise HTTPException(
|
||||
status.HTTP_404_NOT_FOUND, "Charge gehört nicht zu diesem Produkt"
|
||||
)
|
||||
affected = check_out_lot(
|
||||
db,
|
||||
product=product,
|
||||
lot=lot,
|
||||
quantity=payload.quantity,
|
||||
unit=payload.unit,
|
||||
user=user,
|
||||
note=payload.note,
|
||||
)
|
||||
else:
|
||||
affected = check_out(
|
||||
db,
|
||||
product=product,
|
||||
quantity=payload.quantity,
|
||||
unit=payload.unit,
|
||||
user=user,
|
||||
note=payload.note,
|
||||
)
|
||||
except ConversionError as exc:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc)) from exc
|
||||
except StockError as exc:
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc
|
||||
@@ -122,3 +145,63 @@ def list_lots(
|
||||
if product_id is not None:
|
||||
query = query.filter(Lot.product_id == product_id)
|
||||
return query.order_by(Lot.best_before.is_(None), Lot.best_before).all()
|
||||
|
||||
|
||||
@router.patch("/lots/{lot_id}", response_model=LotOut)
|
||||
def update_lot(
|
||||
lot_id: int,
|
||||
payload: LotUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
) -> Lot:
|
||||
"""Korrigiert eine Charge (Menge in Basiseinheiten, MHD, Lagerort)."""
|
||||
lot = db.get(Lot, lot_id)
|
||||
if lot is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Charge nicht gefunden")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
old_quantity = lot.quantity
|
||||
for field, value in data.items():
|
||||
setattr(lot, field, value)
|
||||
|
||||
delta = lot.quantity - old_quantity
|
||||
if abs(delta) > 1e-9:
|
||||
db.add(
|
||||
Movement(
|
||||
product_id=lot.product_id,
|
||||
lot_id=lot.id,
|
||||
user_id=user.id,
|
||||
type=MovementType.adjust,
|
||||
quantity=delta,
|
||||
unit_used="base",
|
||||
note="Charge korrigiert",
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(lot)
|
||||
return lot
|
||||
|
||||
|
||||
@router.delete("/lots/{lot_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_lot(
|
||||
lot_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
) -> None:
|
||||
"""Entfernt eine Charge komplett aus dem Bestand."""
|
||||
lot = db.get(Lot, lot_id)
|
||||
if lot is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Charge nicht gefunden")
|
||||
db.add(
|
||||
Movement(
|
||||
product_id=lot.product_id,
|
||||
lot_id=None,
|
||||
user_id=user.id,
|
||||
type=MovementType.adjust,
|
||||
quantity=-lot.quantity,
|
||||
unit_used="base",
|
||||
note="Charge gelöscht",
|
||||
)
|
||||
)
|
||||
db.delete(lot)
|
||||
db.commit()
|
||||
|
||||
56
backend/app/routers/units.py
Normal file
56
backend/app/routers/units.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user, require_admin
|
||||
from ..models import Group, Product, Unit, User
|
||||
from ..schemas import UnitCreate, UnitOut
|
||||
|
||||
router = APIRouter(prefix="/units", tags=["units"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[UnitOut])
|
||||
def list_units(
|
||||
db: Session = Depends(get_db), _: User = Depends(get_current_user)
|
||||
) -> list[Unit]:
|
||||
return db.query(Unit).order_by(Unit.kind, Unit.factor).all()
|
||||
|
||||
|
||||
@router.post("", response_model=UnitOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_unit(
|
||||
payload: UnitCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_admin),
|
||||
) -> Unit:
|
||||
exists = db.query(Unit).filter(func.lower(Unit.name) == payload.name.lower()).first()
|
||||
if exists:
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, "Einheit existiert bereits")
|
||||
unit = Unit(name=payload.name, kind=payload.kind, factor=payload.factor, is_builtin=False)
|
||||
db.add(unit)
|
||||
db.commit()
|
||||
db.refresh(unit)
|
||||
return unit
|
||||
|
||||
|
||||
@router.delete("/{unit_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_unit(
|
||||
unit_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_admin),
|
||||
) -> None:
|
||||
unit = db.get(Unit, unit_id)
|
||||
if unit is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Einheit nicht gefunden")
|
||||
if unit.is_builtin:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Eingebaute Einheiten können nicht gelöscht werden")
|
||||
in_use = (
|
||||
db.query(Product).filter(Product.display_unit_id == unit_id).first()
|
||||
or db.query(Group).filter(Group.min_stock_unit_id == unit_id).first()
|
||||
)
|
||||
if in_use:
|
||||
raise HTTPException(
|
||||
status.HTTP_409_CONFLICT, "Einheit wird noch von Produkten/Gruppen verwendet"
|
||||
)
|
||||
db.delete(unit)
|
||||
db.commit()
|
||||
@@ -7,6 +7,7 @@ from ..database import get_db
|
||||
from ..deps import get_current_user
|
||||
from ..models import Group, Lot, Movement, Product, User
|
||||
from ..schemas import ExpiringItem, GroupShoppingItem, MovementOut, ShoppingItem
|
||||
from ..services.conversion import BASE_OF_KIND
|
||||
from ..services.stock import current_stock
|
||||
from .settings import get_expiry_warning_days
|
||||
|
||||
@@ -56,8 +57,16 @@ def group_shopping_list(
|
||||
db.query(Group).filter(Group.min_stock.isnot(None), Group.min_stock > 0).all()
|
||||
)
|
||||
for group in groups:
|
||||
products = db.query(Product).filter(Product.group_id == group.id).all()
|
||||
stock = float(sum(current_stock(db, p.id) for p in products))
|
||||
unit = group.min_stock_unit
|
||||
if unit is not None:
|
||||
base = BASE_OF_KIND[unit.kind]
|
||||
products = [p for p in group.products if p.base_unit == base]
|
||||
stock = float(sum(current_stock(db, p.id) for p in products)) / unit.factor
|
||||
unit_name = unit.name
|
||||
else:
|
||||
products = list(group.products)
|
||||
stock = float(sum(current_stock(db, p.id) for p in products))
|
||||
unit_name = ""
|
||||
if stock < group.min_stock:
|
||||
items.append(
|
||||
GroupShoppingItem(
|
||||
@@ -66,6 +75,7 @@ def group_shopping_list(
|
||||
stock=stock,
|
||||
min_stock=group.min_stock,
|
||||
deficit=group.min_stock - stock,
|
||||
unit_name=unit_name,
|
||||
product_count=len(products),
|
||||
)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user