58 行
2.1 KiB
Python
58 行
2.1 KiB
Python
from __future__ import annotations
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy import func as sqlfunc
|
|
|
|
from app.database import get_db
|
|
from app.auth import get_current_user
|
|
from app.models.pricing import PricingItem
|
|
from app.schemas.pricing import PricingItemSchema, PricingItemResponse
|
|
|
|
router = APIRouter(prefix="/api/pricing", tags=["价格信息"], dependencies=[Depends(get_current_user)])
|
|
|
|
|
|
@router.get("/", response_model=list[PricingItemResponse])
|
|
def list_pricing(db: Session = Depends(get_db)):
|
|
items = db.query(PricingItem).order_by(PricingItem.sort_order).all()
|
|
return [PricingItemResponse.model_validate(item) for item in items]
|
|
|
|
|
|
@router.post("/", response_model=PricingItemResponse, status_code=201)
|
|
def create_pricing(req: PricingItemSchema, db: Session = Depends(get_db)):
|
|
max_order = db.query(sqlfunc.max(PricingItem.sort_order)).scalar() or 0
|
|
item = PricingItem(**req.model_dump(), sort_order=max_order + 1)
|
|
db.add(item)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return PricingItemResponse.model_validate(item)
|
|
|
|
|
|
@router.put("/{item_id}", response_model=PricingItemResponse)
|
|
def update_pricing(item_id: int, req: PricingItemSchema, db: Session = Depends(get_db)):
|
|
item = db.query(PricingItem).get(item_id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="价格信息不存在")
|
|
for key, val in req.model_dump().items():
|
|
setattr(item, key, val)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return PricingItemResponse.model_validate(item)
|
|
|
|
|
|
@router.delete("/{item_id}")
|
|
def delete_pricing(item_id: int, db: Session = Depends(get_db)):
|
|
item = db.query(PricingItem).get(item_id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="价格信息不存在")
|
|
db.delete(item)
|
|
db.commit()
|
|
return {"message": "删除成功"}
|
|
|
|
|
|
@router.put("/reorder/batch")
|
|
def reorder_pricing(ids: list[int], db: Session = Depends(get_db)):
|
|
for i, pid in enumerate(ids):
|
|
db.query(PricingItem).filter(PricingItem.id == pid).update({"sort_order": i})
|
|
db.commit()
|
|
return {"message": "排序更新成功"}
|