"""在途调拨企业微信汇总通知。 用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录 notification_failed 且不改变 外部系统 业务结果(run.status 保持)。 依赖:models、audit、typing.Protocol。 逻辑:通知状态独立于 外部系统 状态;已成功投递幂等(每个 Run 一条)。 """ from __future__ import annotations from typing import Any, Protocol from app import db from app.core.errors import NotFoundError from app.models import TransferRun from app.services.in_transit_transfer.audit import build_transfer_audit_event from app.services.in_transit_transfer.status import TransferNotificationStatus class WeComSender(Protocol): """企业微信汇总通知协议(测试注入 FakeWeCom)。""" def send_summary(self, *, run_no: str, summary: dict[str, Any], recipients: list[str], excel_path: str | None = None) -> dict[str, Any]: """发送一次汇总通知。""" def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str] | None = None, excel_path: str | None = None) -> dict[str, Any]: """为 Run 发送一条汇总通知(幂等)。 Args: run_no: Run 编号。 sender: 企微发送器。 recipients: 接收人列表(缺省空)。 excel_path: 异常 Excel 附件路径(可空)。 Returns: {"run_no", "notification_status", "delivered"};空数据返回 skipped。 Raises: NotFoundError: Run 不存在。 """ run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() if run is None: raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") if not run.items: # 空数据 Run:不通知(产品决策 C5:仅非空 Run 通知)。 return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False, "skipped": "no_data"} if run.notification_status == TransferNotificationStatus.SUCCESS.value: # 已成功投递:幂等跳过,保证每个 Run 恰好一条。 return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False} summary = { "run_no": run.run_no, "status": run.status, "business_date": run.business_date, "counts": dict(run.counts_json or {}), "result_summary": dict(run.result_summary_json or {}), } outcome = sender.send_summary( run_no=run.run_no, summary=summary, recipients=list(recipients or []), excel_path=excel_path, ) outcome = outcome if isinstance(outcome, dict) else {} failed = str(outcome.get("status") or "success") != "success" run.notification_status = TransferNotificationStatus.FAILED.value if failed else TransferNotificationStatus.SUCCESS.value if failed: run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED") run.notification_error_message = str(outcome.get("error_message") or "") # 关键:通知失败绝不修改 run.status(外部系统 业务结果保持)。 db.session.add(build_transfer_audit_event( event_type="TRANSFER_NOTIFICATION", aggregate_type="transfer_run", aggregate_id=run.run_no, run_no=run.run_no, actor_type="worker", result="failure" if failed else "success", before={"status": run.status, "notification_status": "pending"}, after={"status": run.status, "notification_status": run.notification_status}, )) db.session.commit() return { "run_no": run.run_no, "notification_status": run.notification_status, "delivered": True, }