from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from app.core.database import get_db from app.models.attachment import AttachmentCategory from app.schemas.attachment import ( AttachmentBoxSaveRequest, AttachmentBoxSaveResponse, AttachmentConfigRequest, AttachmentLocationRequest, AttachmentLocationResponse, AttachmentStatusResponse, CategoryResponse, ) from app.schemas.common import ErrorResponse from app.services.attachment_service import ( configure_attachment, get_attachment_status, register_attachment_location, save_attachment_box, ) router = APIRouter(tags=["attachment"]) @router.get("/attachment/categories", response_model=list[CategoryResponse]) def list_categories(db: Session = Depends(get_db)): """列出启用中的附件类型,按 sort_order、name 排序。""" rows = ( db.query(AttachmentCategory) .filter(AttachmentCategory.is_active == True) .order_by(AttachmentCategory.sort_order, AttachmentCategory.name) .all() ) return [ CategoryResponse(id=r.id, name=r.name, sort_order=r.sort_order) for r in rows ] @router.get("/attachment/status", response_model=AttachmentStatusResponse) def attachment_status(zongpai_no: str, db: Session = Depends(get_db)): return get_attachment_status(db, zongpai_no) @router.put("/attachment/config", response_model=AttachmentStatusResponse) def put_attachment_config(req: AttachmentConfigRequest, db: Session = Depends(get_db)): return configure_attachment(db, req) @router.post( "/attachment/location", response_model=AttachmentLocationResponse, responses={ 400: {"description": "参数非法", "model": ErrorResponse}, 404: {"description": "类型不存在", "model": ErrorResponse}, 409: {"description": "重复上架或已下架", "model": ErrorResponse}, }, ) def post_attachment_location( req: AttachmentLocationRequest, db: Session = Depends(get_db) ): record = register_attachment_location(db, req) return AttachmentLocationResponse( zongpai_no=record.zongpai_no, category_id=record.category_id, location_code=record.location_code, created_at=record.created_at.isoformat(), previous_location=getattr(record, "previous_location", None), ) @router.post( "/attachment/box", response_model=AttachmentBoxSaveResponse, responses={ 400: {"description": "参数非法或超量", "model": ErrorResponse}, 404: {"description": "总排号/类型不存在", "model": ErrorResponse}, 409: {"description": "同箱同类型重复", "model": ErrorResponse}, }, ) def post_attachment_box( req: AttachmentBoxSaveRequest, db: Session = Depends(get_db) ): return save_attachment_box(db, req)