feat(invoice-check): 立账凭证检核增加收件人配置并迁移到chat页面

This commit is contained in:
sophie committed 2026-09-17 13:17:37 +08:00
1 parent 18e957545c
commit 7b80b4c395
72 files changed
+2705 -263

No files matched your search

@@ -1,9 +1,10 @@
"""
backend/app/services/voucher_check/notification.py
用途:立账凭证检核缺件汇总、以及检核 / PO 生成排程的技术失败告警。
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。
逻辑:检核批次一条缺件汇总;PO 生成只在技术失败时告警;未配置接收人不发送;domain_notification_managed 避免通用排程重复通知。
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
"""
from __future__ import annotations
@@ -22,12 +23,52 @@ 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 []
def _users_by_ids(user_ids: list[int]) -> list[User]:
"""按 id 取出已绑定企微的用户,保持传入顺序。"""
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]
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(
@@ -42,14 +83,24 @@ def send_batch_missing_summary(
enabled: bool,
) -> str:
"""
发送本批缺件汇总 textcard。
核心逻辑:无缺件或未选接收人则不发空通知,并写入 notification 审计。
按文件类型接收人发送缺件 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,
@@ -57,61 +108,64 @@ def send_batch_missing_summary(
"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
],
}
recipient_ids = [int(u.id) for u in _recipient_users(task)]
if not enabled:
persist_notification(
run_id=engine_run_id,
return _persist_skip(
engine_run_id=engine_run_id,
excel_filename=excel_filename,
recipient_user_ids=recipient_ids,
recipient_user_ids=planned_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,
if not getattr(task, "notify_enabled", True):
return _persist_skip(
engine_run_id=engine_run_id,
excel_filename=excel_filename,
recipient_user_ids=recipient_ids,
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,
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,
return _persist_skip(
engine_run_id=engine_run_id,
excel_filename=excel_filename,
recipient_user_ids=recipient_ids,
recipient_user_ids=planned_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)
users = _users_by_ids(planned_ids)
if not users:
persist_notification(
run_id=engine_run_id,
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="未配置企业微信接收人",
skip_reason=reason,
summary=summary,
sent_at=None,
)
db.session.commit()
return "skipped_no_recipients"
from app.services.wecom_notify import (
_build_jump_url,
@@ -119,29 +173,23 @@ def send_batch_missing_summary(
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
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",
@@ -155,27 +203,33 @@ def send_batch_missing_summary(
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] batch notify failed user=%s err=%s",
"[voucher-check] type notify failed user=%s err=%s",
user.id,
exc,
)
status = "sent" if ok_any else "failed"
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=recipient_ids,
send_status=status,
skip_reason=None if ok_any else "企业微信发送失败",
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 status
return "sent" if ok_any else "failed"
def send_failure_alert(