"""fin_risk_alert 仓储:按状态查预警 + 处置条件更新(防并发,不 commit)。""" from __future__ import annotations from datetime import datetime from sqlalchemy import select, update from model.fin_risk_alert import FinRiskAlert from repositories.base import BaseRepository class FinRiskAlertRepo(BaseRepository): model = FinRiskAlert async def list_by_status( self, status: str | None = None, customer_id: int | None = None ) -> list[FinRiskAlert]: stmt = select(FinRiskAlert) if status is not None: stmt = stmt.where(FinRiskAlert.status == status) if customer_id is not None: stmt = stmt.where(FinRiskAlert.customer_id == customer_id) stmt = stmt.order_by(FinRiskAlert.id.desc()) return list((await self.db.scalars(stmt)).all()) async def conditional_handle( self, alert_id: int, *, handler_id: int, new_status: str, handle_result: str, handle_time: datetime, ) -> bool: """处置预警:条件更新 WHERE id=? AND status='未处理'。 不 commit,由 service 层事务统一提交。rowcount==0 表示已被他人处置, 返回 False 供上层提示「已被处理」,避免重复落账/工单/通知。 """ result = await self.db.execute( update(FinRiskAlert) .where( FinRiskAlert.id == alert_id, FinRiskAlert.status == "未处理", ) .values( status=new_status, handler_id=handler_id, handle_result=handle_result, handle_time=handle_time, ) ) return result.rowcount > 0 async def update_status(self, alert_id: int, *, status: str, **fields) -> int: """无条件更新预警状态(放行失败回写「已确认」等场景)。不 commit。""" result = await self.db.execute( update(FinRiskAlert) .where(FinRiskAlert.id == alert_id) .values(status=status, **fields) ) return result.rowcount