1
This commit is contained in:
1 parent
78576f5745
commit
63b997a7e4
68 files changed
+3680
-1413
No files matched your search
@@ -1,15 +1,15 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/notification.py
|
||||
|
||||
用途:立账凭证检核缺资料企微 textcard 与批次失败告警。
|
||||
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、persistence.mark_missing_notified。
|
||||
逻辑:runner 落库后调用;同票同日节流;设置 domain_notification_managed 避免通用排程重复通知。
|
||||
用途:立账凭证检核批次级企微汇总与技术失败告警。
|
||||
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||
逻辑:一个批次一条缺件汇总;未配置接收人不发送;设置 domain_notification_managed 避免通用排程重复通知。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
@@ -17,7 +17,7 @@ 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
|
||||
from app.services.voucher_check.engine_persistence import persist_notification
|
||||
|
||||
_TZ = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
@@ -30,85 +30,115 @@ def _recipient_users(task: ScheduleTask) -> list[User]:
|
||||
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(
|
||||
def send_batch_missing_summary(
|
||||
*,
|
||||
task: ScheduleTask,
|
||||
run: ScheduleRun,
|
||||
scope_code: str,
|
||||
period_month: date,
|
||||
missing_items: list[dict[str, Any]],
|
||||
same_day_dedup: bool,
|
||||
schedule_run: ScheduleRun,
|
||||
engine_run_id: int,
|
||||
profile_code: str,
|
||||
period_month: str,
|
||||
stats: dict[str, Any],
|
||||
excel_filename: str | None,
|
||||
enabled: bool,
|
||||
) -> int:
|
||||
) -> str:
|
||||
"""
|
||||
合并发送缺资料 textcard。
|
||||
核心逻辑:过滤同日已通知票;成功后才写 last_missing_notified_on。
|
||||
发送本批缺件汇总 textcard。
|
||||
核心逻辑:无缺件或未选接收人则不发空通知,并写入 notification 审计。
|
||||
|
||||
Returns:
|
||||
本次实际通知的发票数。
|
||||
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
||||
"""
|
||||
if not enabled or not missing_items:
|
||||
return 0
|
||||
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):
|
||||
return 0
|
||||
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.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()
|
||||
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,
|
||||
)
|
||||
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}"
|
||||
top_missing = [f"{name}{count}" for name, count in top_missing if count > 0][:4]
|
||||
title = f"立账凭证缺件汇总: {task.name}"
|
||||
description = (
|
||||
f"批次 {run.run_no}\n"
|
||||
f"检核月份 {period}\n"
|
||||
f"缺资料 {len(to_notify)} 张\n"
|
||||
f"示例:{sample}\n"
|
||||
f"完整清单请查看工作台检核记录或 Excel。"
|
||||
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:
|
||||
@@ -116,7 +146,7 @@ def send_missing_notifications(
|
||||
jump_url = _build_jump_url(
|
||||
"/workspace/accounting-voucher-check",
|
||||
trace_id,
|
||||
{"task_id": task.id, "run_id": run.id},
|
||||
{"task_id": task.id, "run_id": schedule_run.id},
|
||||
)
|
||||
try:
|
||||
audit = _create_audit("voucher_check_missing", user, title, description, trace_id)
|
||||
@@ -130,20 +160,22 @@ def send_missing_notifications(
|
||||
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",
|
||||
"[voucher-check] batch 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
|
||||
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(
|
||||
@@ -155,7 +187,7 @@ def send_failure_alert(
|
||||
error_message: str,
|
||||
enabled: bool,
|
||||
) -> None:
|
||||
"""批次级失败告警(共享盘/Oracle/业务配置异常)。"""
|
||||
"""批次级技术失败告警(ERP/DMS/配置异常),不计入缺件通知。"""
|
||||
if not enabled:
|
||||
return
|
||||
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
|
||||
@@ -178,7 +210,7 @@ def send_failure_alert(
|
||||
f"错误码:{error_code}\n"
|
||||
f"摘要:{(error_message or '')[:200]}\n"
|
||||
f"run_id={run.id}\n"
|
||||
f"请检查 Oracle 连接与共享盘挂载/健康标记。"
|
||||
f"请检查 Oracle 与文档库连接。"
|
||||
)
|
||||
for user in users:
|
||||
trace_id = uuid.uuid4().hex
|
||||
|
||||
Reference in new issue
Block a user