298 lines
9.8 KiB
Python
298 lines
9.8 KiB
Python
"""
|
||
backend/app/services/voucher_check/notification.py
|
||
|
||
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
||
依赖:wecom_notify、notify_config_service、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 _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_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。
|
||
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;无缺件或无人可发则写审计不发空消息。
|
||
|
||
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,
|
||
)
|
||
|
||
ok_any = False
|
||
sent_ids: list[int] = []
|
||
for user in users:
|
||
items = plan["user_rules"].get(int(user.id)) or []
|
||
type_lines = [
|
||
f"{item['name']} {item['missing_file_count']} 份 / {item['missing_invoice_count']} 张 invoice"
|
||
for item in items
|
||
]
|
||
title = f"立账凭证缺件: {task.name}"
|
||
description = (
|
||
f"业务方 {profile_code}\n"
|
||
f"资料所属期间 {period_month}\n"
|
||
f"批次 {schedule_run.run_no}\n"
|
||
f"你负责的缺件:\n"
|
||
+ "\n".join(type_lines)
|
||
+ "\n明细以工作台 Excel 为准。"
|
||
)
|
||
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))
|
||
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,
|
||
)
|
||
|
||
skip_reason = None
|
||
if not ok_any:
|
||
skip_reason = "企业微信发送失败"
|
||
elif plan["unmapped_codes"]:
|
||
skip_reason = "部分文件类型未配置接收人"
|
||
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()
|