from decimal import Decimal from fastapi import HTTPException from sqlalchemy import func, select from sqlalchemy.orm import Session from ..models import Sku, Stock, StockFlow from ..serializers import flow_out, stock_out BIZ_TYPES = ("INIT", "PO_RECEIVE", "SO_SHIP", "ADJUST") def apply_delta( db: Session, sku_id: int, delta: Decimal, biz_type: str, biz_order_no: str | None = None, remark: str | None = None, ) -> Decimal: """在同一事务内更新库存余额并写入流水;调用方负责 commit。""" stock = db.execute( select(Stock).where(Stock.sku_id == sku_id).with_for_update() ).scalar_one_or_none() if stock is None: stock = Stock(sku_id=sku_id, qty_on_hand=Decimal("0")) db.add(stock) db.flush() new_qty = stock.qty_on_hand + delta if new_qty < 0: sku = db.get(Sku, sku_id) raise HTTPException( 409, f"库存不足:{sku.sku_code} {sku.sku_name} 现存 {stock.qty_on_hand},需出库 {abs(delta)}", ) stock.qty_on_hand = new_qty db.add( StockFlow( sku_id=sku_id, biz_type=biz_type, biz_order_no=biz_order_no, qty_delta=delta, qty_after=new_qty, remark=remark, ) ) return new_qty def list_stock(db: Session, q: str | None, low_only: bool, page: int, page_size: int): stmt = select(Stock).join(Sku) if q: like = f"%{q}%" stmt = stmt.where(Sku.sku_code.like(like) | Sku.sku_name.like(like)) if low_only: stmt = stmt.where(Stock.qty_on_hand < Sku.safety_stock) total = db.scalar(select(func.count()).select_from(stmt.subquery())) rows = db.scalars( stmt.order_by(Stock.sku_id).offset((page - 1) * page_size).limit(page_size) ).all() return {"items": [stock_out(r) for r in rows], "total": total, "page": page, "page_size": page_size} def list_flows( db: Session, sku_id: int | None, biz_type: str | None, biz_order_no: str | None, page: int, page_size: int, ): stmt = select(StockFlow) if sku_id: stmt = stmt.where(StockFlow.sku_id == sku_id) if biz_type: stmt = stmt.where(StockFlow.biz_type == biz_type) if biz_order_no: stmt = stmt.where(StockFlow.biz_order_no.like(f"%{biz_order_no}%")) total = db.scalar(select(func.count()).select_from(stmt.subquery())) rows = db.scalars( stmt.order_by(StockFlow.id.desc()).offset((page - 1) * page_size).limit(page_size) ).all() return {"items": [flow_out(r) for r in rows], "total": total, "page": page, "page_size": page_size} def low_stock_list(db: Session): rows = db.scalars( select(Stock).join(Sku).where(Stock.qty_on_hand < Sku.safety_stock).order_by(Stock.sku_id) ).all() return [stock_out(r) for r in rows]