Files
syops/backend/app/services/voucher_check/notification.py
T
sophie f615e56bb9 feat(agent): 立账凭证检核
(cherry picked from commit f9e2fb5efc1ec7bf4f6e52e08dd3591b4e77edd9)
2026-08-06 10:05:46 +08:00

206 lines
6.4 KiB
Python

"""
backend/app/services/voucher_check/notification.py
用途:立账凭证检核缺资料企微 textcard 与批次失败告警。
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、persistence.mark_missing_notified。
逻辑:runner 落库后调用;同票同日节流;设置 domain_notification_managed 避免通用排程重复通知。
"""
from __future__ import annotations
import uuid
from datetime import date, 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.persistence import mark_missing_notified
_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 _today_shanghai(now: datetime | None = None) -> date:
base = now or datetime.now(_TZ)
if base.tzinfo is None:
base = base.replace(tzinfo=_TZ)
else:
base = base.astimezone(_TZ)
return base.date()
def send_missing_notifications(
*,
task: ScheduleTask,
run: ScheduleRun,
scope_code: str,
period_month: date,
missing_items: list[dict[str, Any]],
same_day_dedup: bool,
enabled: bool,
) -> int:
"""
合并发送缺资料 textcard。
核心逻辑:过滤同日已通知票;成功后才写 last_missing_notified_on。
Returns:
本次实际通知的发票数。
"""
if not enabled or not missing_items:
return 0
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
return 0
from app.models.voucher_check import VoucherCheckInvoiceState
from app.services.wecom_notify import (
_build_jump_url,
_create_audit,
send_wecom_textcard_message,
)
today = _today_shanghai()
invoice_nos = [str(i["invoice_no"]).strip() for i in missing_items]
states = (
db.session.query(VoucherCheckInvoiceState)
.filter(
VoucherCheckInvoiceState.scope_code == scope_code,
VoucherCheckInvoiceState.period_month == period_month,
VoucherCheckInvoiceState.invoice_no.in_(invoice_nos),
)
.all()
)
state_map = {s.invoice_no: s for s in states}
to_notify: list[dict[str, Any]] = []
for item in missing_items:
inv = str(item["invoice_no"]).strip()
state = state_map.get(inv)
if same_day_dedup and state and state.last_missing_notified_on == today:
continue
to_notify.append(item)
if not to_notify:
return 0
users = _recipient_users(task)
if not users:
current_app.logger.warning(
"[voucher-check] missing notify skipped: no wecom recipients run_id=%s",
run.id,
)
return 0
sample = "、".join(i["invoice_no"] for i in to_notify[:8])
if len(to_notify) > 8:
sample += "…"
period = period_month.strftime("%Y-%m")
title = f"立账凭证缺资料: {task.name}"
description = (
f"批次 {run.run_no}\n"
f"检核月份 {period}\n"
f"缺资料 {len(to_notify)} 张\n"
f"示例:{sample}\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": 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] missing notify failed user=%s err=%s",
user.id,
exc,
)
if ok_any:
mark_missing_notified(
scope_code=scope_code,
period_month=period_month,
invoice_nos=[str(i["invoice_no"]).strip() for i in to_notify],
notified_on=today,
)
db.session.commit()
return len(to_notify)
return 0
def send_failure_alert(
*,
task: ScheduleTask,
run: ScheduleRun,
stage: str,
error_code: str,
error_message: str,
enabled: bool,
) -> None:
"""批次级失败告警(共享盘/Oracle/业务配置异常)。"""
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()