"""biz_work_order 工单仓储:查工单 + 流转条件更新(防并发,不 commit)。""" from __future__ import annotations from sqlalchemy import func, select, update from model.biz_work_order import BizWorkOrder from repositories.base import BaseRepository class BizWorkOrderRepo(BaseRepository): model = BizWorkOrder async def get_by_work_order_no(self, work_order_no: str) -> BizWorkOrder | None: return await self.db.scalar( select(BizWorkOrder).where(BizWorkOrder.work_order_no == work_order_no) ) async def list_with_filter( self, *, handler_id: int | None = None, status: str | None = None, customer_id: int | None = None, limit: int = 10, offset: int = 0, ) -> list[BizWorkOrder]: stmt = select(BizWorkOrder) if handler_id is not None: stmt = stmt.where(BizWorkOrder.handler_id == handler_id) if status is not None: stmt = stmt.where(BizWorkOrder.status == status) if customer_id is not None: stmt = stmt.where(BizWorkOrder.customer_id == customer_id) stmt = stmt.order_by(BizWorkOrder.id.desc()).limit(limit).offset(offset) return list((await self.db.scalars(stmt)).all()) async def count_with_filter( self, *, handler_id: int | None = None, status: str | None = None, customer_id: int | None = None, ) -> int: """统计工单筛选结果总数,供分页响应使用。""" stmt = select(func.count()).select_from(BizWorkOrder) if handler_id is not None: stmt = stmt.where(BizWorkOrder.handler_id == handler_id) if status is not None: stmt = stmt.where(BizWorkOrder.status == status) if customer_id is not None: stmt = stmt.where(BizWorkOrder.customer_id == customer_id) return int((await self.db.scalar(stmt)) or 0) async def conditional_transition( self, work_order_id: int, *, from_status: str, to_status: str, **fields ) -> bool: """工单流转:条件更新 WHERE id=? AND status=from_status。 不 commit,由 service 层事务统一提交;rowcount==0 表示状态已变(并发冲突), 返回 False 供上层提示,避免跳步流转。 """ result = await self.db.execute( update(BizWorkOrder) .where( BizWorkOrder.id == work_order_id, BizWorkOrder.status == from_status, ) .values(status=to_status, **fields) ) return result.rowcount > 0