238 lines
7.7 KiB
Python
238 lines
7.7 KiB
Python
"""
|
||
backend/app/services/voucher_check/notification.py
|
||
|
||
用途:立账凭证检核批次级企微汇总与技术失败告警。
|
||
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||
逻辑:一个批次一条缺件汇总;未配置接收人不发送;设置 domain_notification_managed 避免通用排程重复通知。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
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 _recipient_users(task: ScheduleTask) -> list[User]:
|
||
user_ids = task.notify_user_ids_json or []
|
||
if not user_ids:
|
||
return []
|
||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||
return [u for u in users if u.wecom_userid]
|
||
|
||
|
||
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,
|
||
enabled: bool,
|
||
) -> str:
|
||
"""
|
||
发送本批缺件汇总 textcard。
|
||
核心逻辑:无缺件或未选接收人则不发空通知,并写入 notification 审计。
|
||
|
||
Returns:
|
||
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
||
"""
|
||
missing_files = int(stats.get("missing_file_count") or 0)
|
||
missing_invoices = int(stats.get("missing_invoice_count") or 0)
|
||
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,
|
||
}
|
||
recipient_ids = [int(u.id) for u in _recipient_users(task)]
|
||
|
||
if not enabled:
|
||
persist_notification(
|
||
run_id=engine_run_id,
|
||
excel_filename=excel_filename,
|
||
recipient_user_ids=recipient_ids,
|
||
send_status="skipped_disabled",
|
||
skip_reason="notify_missing_enabled=false",
|
||
summary=summary,
|
||
sent_at=None,
|
||
)
|
||
db.session.commit()
|
||
return "skipped_disabled"
|
||
|
||
if missing_files <= 0:
|
||
persist_notification(
|
||
run_id=engine_run_id,
|
||
excel_filename=excel_filename,
|
||
recipient_user_ids=recipient_ids,
|
||
send_status="skipped_no_missing",
|
||
skip_reason="本批无缺件",
|
||
summary=summary,
|
||
sent_at=None,
|
||
)
|
||
db.session.commit()
|
||
return "skipped_no_missing"
|
||
|
||
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
|
||
persist_notification(
|
||
run_id=engine_run_id,
|
||
excel_filename=excel_filename,
|
||
recipient_user_ids=recipient_ids,
|
||
send_status="skipped_disabled",
|
||
skip_reason="WECOM_NOTIFY_ENABLED=false",
|
||
summary=summary,
|
||
sent_at=None,
|
||
)
|
||
db.session.commit()
|
||
return "skipped_disabled"
|
||
|
||
users = _recipient_users(task)
|
||
if not users:
|
||
persist_notification(
|
||
run_id=engine_run_id,
|
||
excel_filename=excel_filename,
|
||
recipient_user_ids=[],
|
||
send_status="skipped_no_recipients",
|
||
skip_reason="未配置企业微信接收人",
|
||
summary=summary,
|
||
sent_at=None,
|
||
)
|
||
db.session.commit()
|
||
return "skipped_no_recipients"
|
||
|
||
from app.services.wecom_notify import (
|
||
_build_jump_url,
|
||
_create_audit,
|
||
send_wecom_textcard_message,
|
||
)
|
||
|
||
type_stats = stats.get("by_file_type") or {}
|
||
top_missing = sorted(
|
||
(
|
||
(item.get("rule_name") or key, int(item.get("missing_file_count") or 0))
|
||
for key, item in type_stats.items()
|
||
if isinstance(item, dict)
|
||
),
|
||
key=lambda pair: pair[1],
|
||
reverse=True,
|
||
)
|
||
top_missing = [f"{name}{count}" for name, count in top_missing if count > 0][:4]
|
||
title = f"立账凭证缺件汇总: {task.name}"
|
||
description = (
|
||
f"业务方 {profile_code}\n"
|
||
f"资料所属期间 {period_month}\n"
|
||
f"批次 {schedule_run.run_no}\n"
|
||
f"主体 {int(stats.get('subject_count') or 0)} 张\n"
|
||
f"缺件文件 {missing_files} / 缺件 invoice {missing_invoices}\n"
|
||
f"主要缺失:{'、'.join(top_missing) or '—'}\n"
|
||
f"明细以工作台 Excel 为准。"
|
||
)
|
||
ok_any = False
|
||
for user in users:
|
||
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
|
||
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] batch notify failed user=%s err=%s",
|
||
user.id,
|
||
exc,
|
||
)
|
||
status = "sent" if ok_any else "failed"
|
||
persist_notification(
|
||
run_id=engine_run_id,
|
||
excel_filename=excel_filename,
|
||
recipient_user_ids=recipient_ids,
|
||
send_status=status,
|
||
skip_reason=None if ok_any else "企业微信发送失败",
|
||
summary=summary,
|
||
sent_at=datetime.now(_TZ).replace(tzinfo=None) if ok_any else None,
|
||
)
|
||
db.session.commit()
|
||
return status
|
||
|
||
|
||
def send_failure_alert(
|
||
*,
|
||
task: ScheduleTask,
|
||
run: ScheduleRun,
|
||
stage: str,
|
||
error_code: str,
|
||
error_message: str,
|
||
enabled: bool,
|
||
) -> None:
|
||
"""批次级技术失败告警(ERP/DMS/配置异常),不计入缺件通知。"""
|
||
if not enabled:
|
||
return
|
||
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
|
||
return
|
||
|
||
from app.services.wecom_notify import (
|
||
_build_jump_url,
|
||
_create_audit,
|
||
send_wecom_textcard_message,
|
||
)
|
||
|
||
users = _recipient_users(task)
|
||
if not users:
|
||
return
|
||
|
||
title = 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()
|