""" backend/app/services/voucher_check/notification.py 用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。 依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。 逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型; 卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号; 卡片发出后紧跟本批检核结果 Excel,收件人不用进详情才知道缺哪张票; 排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。 """ from __future__ import annotations import re import uuid from datetime import datetime from typing import Any from zoneinfo import ZoneInfo from flask import current_app from app import db from app.models import ScheduleRun, ScheduleTask, User from app.services.voucher_check.engine_persistence import persist_notification _TZ = ZoneInfo("Asia/Shanghai") def _friendly_period_label(period_month: str) -> str: """ 把 YYYY-MM 收成企微卡片上的中文年月。 核心逻辑:收件人看「2026年8月」,不看 2026-08;解析失败时保留原文。 """ text = str(period_month or "").strip() match = re.fullmatch(r"(\d{4})-(\d{2})", text) if not match: return text or "-" return f"{int(match.group(1))}年{int(match.group(2))}月" def _missing_type_line(item: dict[str, Any]) -> str: """一条缺件类型:名称、缺件份数、涉及发票张数。""" name = str(item.get("name") or item.get("code") or "") files = int(item.get("missing_file_count") or 0) invoices = int(item.get("missing_invoice_count") or 0) return f"{name}:缺 {files} 份,涉及 {invoices} 张发票" def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[str, str]: """ 组装销售开票附件缺件 textcard,标题为「销售开票附件缺件提醒」。 核心逻辑:用纯文本而不是 div 着色。企微 description 约 512 字节, 颜色标签会挤掉后面的缺件类型。 Returns: (title, description) """ body = "\n".join( [ _friendly_period_label(period_month), "销售开票附件已检核,你负责的类型还有缺件:", *[_missing_type_line(item) for item in items], "请尽快补齐。缺件明细见下一条 Excel。", ] ) return "销售开票附件缺件提醒", body def _users_by_ids(user_ids: list[int]) -> list[User]: """按 id 取出已绑定企微的用户,保持传入顺序。""" if not user_ids: return [] found = { int(user.id): user for user in db.session.query(User).filter(User.id.in_(user_ids)).all() if user.wecom_userid } return [found[user_id] for user_id in user_ids if user_id in found] def _recipient_users(task: ScheduleTask) -> list[User]: """技术失败告警仍使用排程上的通知人。""" raw = task.notify_user_ids_json or [] ids: list[int] = [] for item in raw: try: user_id = int(item) except (TypeError, ValueError): continue if user_id > 0 and user_id not in ids: ids.append(user_id) return _users_by_ids(ids) def _persist_skip( *, engine_run_id: int, excel_filename: str | None, recipient_user_ids: list[int], send_status: str, skip_reason: str, summary: dict[str, Any], ) -> str: persist_notification( run_id=engine_run_id, excel_filename=excel_filename, recipient_user_ids=recipient_user_ids, send_status=send_status, skip_reason=skip_reason, summary=summary, sent_at=None, ) db.session.commit() return send_status def _send_excel_file(wecom_userid: str, media_id: str) -> bool: """ 把已上传的检核结果 Excel 发给一个收件人。 核心逻辑:企微文件消息与 textcard 是两条消息,失败只记日志,不回滚已发出的卡片。 Returns: 企业微信 errcode 为 0 时为 True。 """ from app.services.integrations.wecom.notify import send_wecom_file_message try: data = send_wecom_file_message(wecom_userid, media_id) except Exception as exc: current_app.logger.warning( "[voucher-check] excel file failed user=%s err=%s", wecom_userid, exc, ) return False if data.get("errcode") == 0: return True current_app.logger.warning( "[voucher-check] excel file failed user=%s errcode=%s errmsg=%s", wecom_userid, data.get("errcode"), data.get("errmsg"), ) return False def send_batch_missing_summary( *, task: ScheduleTask, schedule_run: ScheduleRun, engine_run_id: int, profile_code: str, period_month: str, stats: dict[str, Any], excel_filename: str | None, excel_bytes: bytes | None = None, enabled: bool, ) -> str: """ 按文件类型接收人发送缺件 textcard,并附上本批检核结果 Excel。 核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。 Excel 全批共用一份,上传一次后随卡片发给每个收件人。附件失败不挡住卡片,原因写入审计。 无缺件或无人可发则写审计不发空消息。 Args: excel_bytes: 与排程落库同一份检核结果。为空时只发卡片。 Returns: send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed """ from app.services.voucher_check.notify_config_service import ( load_recipients_by_rule, plan_missing_recipient_messages, ) missing_files = int(stats.get("missing_file_count") or 0) missing_invoices = int(stats.get("missing_invoice_count") or 0) plan = plan_missing_recipient_messages( by_file_type=stats.get("by_file_type") or {}, recipients_by_rule=load_recipients_by_rule(profile_code), ) planned_ids = sorted(int(uid) for uid in plan["user_rules"].keys()) summary = { "profile_code": profile_code, "period": period_month, "subject_count": int(stats.get("subject_count") or 0), "missing_file_count": missing_files, "missing_invoice_count": missing_invoices, "run_no": schedule_run.run_no, "unmapped_rule_codes": plan["unmapped_codes"], "by_recipient": [ { "user_id": user_id, "rule_codes": [item["code"] for item in plan["user_rules"][user_id]], } for user_id in planned_ids ], } if not enabled: return _persist_skip( engine_run_id=engine_run_id, excel_filename=excel_filename, recipient_user_ids=planned_ids, send_status="skipped_disabled", skip_reason="notify_missing_enabled=false", summary=summary, ) if not getattr(task, "notify_enabled", True): return _persist_skip( engine_run_id=engine_run_id, excel_filename=excel_filename, recipient_user_ids=planned_ids, send_status="skipped_disabled", skip_reason="notify_enabled=false", summary=summary, ) if missing_files <= 0: return _persist_skip( engine_run_id=engine_run_id, excel_filename=excel_filename, recipient_user_ids=[], send_status="skipped_no_missing", skip_reason="本批无缺件", summary=summary, ) if not current_app.config.get("WECOM_NOTIFY_ENABLED", True): return _persist_skip( engine_run_id=engine_run_id, excel_filename=excel_filename, recipient_user_ids=planned_ids, send_status="skipped_disabled", skip_reason="WECOM_NOTIFY_ENABLED=false", summary=summary, ) users = _users_by_ids(planned_ids) if not users: reason = "有缺件类型未配置接收人" if plan["unmapped_codes"] else "未配置企业微信接收人" return _persist_skip( engine_run_id=engine_run_id, excel_filename=excel_filename, recipient_user_ids=[], send_status="skipped_no_recipients", skip_reason=reason, summary=summary, ) from app.services.integrations.wecom.notify import ( _build_jump_url, _create_audit, send_wecom_textcard_message, upload_wecom_temp_media, ) media_id = None file_note = None if excel_bytes and excel_filename: try: media_id = upload_wecom_temp_media(excel_bytes, excel_filename) except Exception as exc: file_note = "Excel 附件上传失败" current_app.logger.warning("[voucher-check] excel upload failed: %s", exc) ok_any = False file_failed = False sent_ids: list[int] = [] for user in users: items = plan["user_rules"].get(int(user.id)) or [] title, description = _missing_textcard(period_month, items) trace_id = uuid.uuid4().hex jump_url = _build_jump_url( "/workspace/accounting-voucher-check", trace_id, {"task_id": task.id, "run_id": schedule_run.id}, ) try: audit = _create_audit("voucher_check_missing", user, title, description, trace_id) audit.jump_url = jump_url data = send_wecom_textcard_message(user.wecom_userid, title, description, jump_url) if data.get("errcode") == 0: audit.status = "sent" ok_any = True sent_ids.append(int(user.id)) if media_id and not _send_excel_file(user.wecom_userid, media_id): file_failed = True else: audit.error_code = str(data.get("errcode")) audit.error_message = str(data.get("errmsg", "unknown"))[:255] except Exception as exc: current_app.logger.warning( "[voucher-check] type notify failed user=%s err=%s", user.id, exc, ) if file_failed and not file_note: file_note = "部分 Excel 附件发送失败" reasons: list[str] = [] if not ok_any: reasons.append("企业微信发送失败") elif plan["unmapped_codes"]: reasons.append("部分文件类型未配置接收人") if file_note: reasons.append(file_note) skip_reason = ";".join(reasons) or None persist_notification( run_id=engine_run_id, excel_filename=excel_filename, recipient_user_ids=sent_ids or [int(user.id) for user in users], send_status="sent" if ok_any else "failed", skip_reason=skip_reason, summary=summary, sent_at=datetime.now(_TZ).replace(tzinfo=None) if ok_any else None, ) db.session.commit() return "sent" if ok_any else "failed" def send_failure_alert( *, task: ScheduleTask, run: ScheduleRun, stage: str, error_code: str, error_message: str, enabled: bool, title: str | None = None, ) -> None: """ 批次级技术失败告警(ERP/DMS/配置/上传异常),不计入缺件通知。 Args: title: 企微标题;默认「立账凭证检核失败」。PO 生成排程传入自己的标题。 """ if not enabled: return if not current_app.config.get("WECOM_NOTIFY_ENABLED", True): return from app.services.integrations.wecom.notify import ( _build_jump_url, _create_audit, send_wecom_textcard_message, ) users = _recipient_users(task) if not users: return title = title or f"立账凭证检核失败: {task.name}" description = ( f"批次 {run.run_no}\n" f"失败阶段:{stage}\n" f"错误码:{error_code}\n" f"摘要:{(error_message or '')[:200]}\n" f"run_id={run.id}\n" f"请检查 Oracle 与文档库连接。" ) for user in users: trace_id = uuid.uuid4().hex jump_url = _build_jump_url( "/admin/schedules", trace_id, {"task_id": task.id, "run_id": run.id}, ) try: audit = _create_audit("voucher_check_failure", user, title, description, trace_id) audit.jump_url = jump_url data = send_wecom_textcard_message(user.wecom_userid, title, description, jump_url) if data.get("errcode") == 0: audit.status = "sent" else: audit.error_code = str(data.get("errcode")) audit.error_message = str(data.get("errmsg", "unknown"))[:255] except Exception as exc: current_app.logger.warning( "[voucher-check] failure alert failed user=%s err=%s", user.id, exc, ) db.session.commit()