This commit is contained in:
2026-05-11 09:34:50 +08:00
parent 79ca3613ae
commit 5e1d475a22
14 changed files with 336 additions and 264 deletions
+15 -9
View File
@@ -9,18 +9,18 @@
"""
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from sqlalchemy import select, update, func
from typing import Optional, List
from database.database import get_db_session
from services.auth_service import get_current_active_user
from models.database import User, Product, Warehouse, Inventory
from .schemas import InventoryResponse, InventoryCreate, InventoryUpdate
from .schemas import InventoryResponse, InventoryCreate, InventoryUpdate, PaginatedResponse
router = APIRouter(prefix="/inventory", tags=["库存管理"])
@router.get("", response_model=List[InventoryResponse])
@router.get("", response_model=PaginatedResponse[InventoryResponse])
async def list_inventory(
warehouse_id: Optional[int] = None,
product_id: Optional[int] = None,
@@ -30,7 +30,7 @@ async def list_inventory(
db_session: AsyncSession = Depends(get_db_session),
current_user: User = Depends(get_current_active_user)
):
query = (
base_query = (
select(Inventory, Product, Warehouse)
.join(Product, Inventory.product_id == Product.id)
.join(Warehouse, Inventory.warehouse_id == Warehouse.id)
@@ -40,13 +40,16 @@ async def list_inventory(
)
if warehouse_id:
query = query.where(Inventory.warehouse_id == warehouse_id)
base_query = base_query.where(Inventory.warehouse_id == warehouse_id)
if product_id:
query = query.where(Inventory.product_id == product_id)
base_query = base_query.where(Inventory.product_id == product_id)
if low_stock:
query = query.where(Inventory.quantity <= Product.min_stock)
base_query = base_query.where(Inventory.quantity <= Product.min_stock)
query = query.offset(skip).limit(limit)
count_query = select(func.count()).select_from(base_query.subquery())
total = await db_session.scalar(count_query) or 0
query = base_query.offset(skip).limit(limit)
result = await db_session.execute(query)
inventory_list = []
@@ -63,7 +66,7 @@ async def list_inventory(
available_quantity=inv.available_quantity
))
return inventory_list
return PaginatedResponse(items=inventory_list, total=total, skip=skip, limit=limit)
@router.post("", response_model=InventoryResponse, status_code=201)
@@ -140,6 +143,7 @@ async def update_inventory(
.join(Warehouse, Inventory.warehouse_id == Warehouse.id)
.where(Inventory.id == inventory_id)
.where(Product.item_type == "material")
.with_for_update(of=Inventory)
)
row = result.first()
if not row:
@@ -187,6 +191,8 @@ async def delete_inventory(
inventory = result.scalar_one_or_none()
if not inventory:
raise HTTPException(status_code=404, detail="库存记录不存在")
if inventory.quantity > 0:
raise HTTPException(status_code=400, detail="库存数量不为零,无法删除库存记录")
await db_session.delete(inventory)
await db_session.commit()
return {"message": "库存记录已删除"}