feat(invoice-check): 立账凭证检核增加收件人配置并迁移到chat页面
This commit is contained in:
1 parent
18e957545c
commit
7b80b4c395
72 files changed
+2705
-263
No files matched your search
@@ -13,5 +13,6 @@ RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
|
||||
'shipping_notice': 'shipping_notice',
|
||||
'file_check': 'file_check',
|
||||
'contract_payment': 'contract_payment',
|
||||
'voucher_check': 'voucher_check',
|
||||
'in_transit_transfer': 'in_transit_transfer',
|
||||
}
|
||||
@@ -145,6 +145,21 @@ agent_types:
|
||||
forced_capabilities:
|
||||
file_upload: false
|
||||
handler_config_schema: {}
|
||||
voucher_check:
|
||||
label: 立账凭证
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: builtin
|
||||
models:
|
||||
- VoucherCheckRun
|
||||
- VoucherCheckNotification
|
||||
required_fields: []
|
||||
default_capabilities:
|
||||
streaming: false
|
||||
file_upload: false
|
||||
task_progress: false
|
||||
forced_capabilities:
|
||||
file_upload: false
|
||||
handler_config_schema: {}
|
||||
in_transit_transfer:
|
||||
label: 在途仓自动调拨
|
||||
conversation_mode_default: task_chat
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/agent_registry/handlers/bootstrap.py
|
||||
|
||||
用途:应用启动时加载 HANDLER_REGISTRY。
|
||||
依赖:handlers.shipping_notice、handlers.contract_payment 等领域 handler 模块。
|
||||
依赖:handlers.shipping_notice、handlers.contract_payment、handlers.voucher_check 等领域 handler 模块。
|
||||
逻辑:create_app 在 load_context_adapters 之后调用 load_handlers()。
|
||||
"""
|
||||
|
||||
@@ -33,10 +33,12 @@ def load_handlers() -> None:
|
||||
import app.services.agent_registry.handlers.file_check as file_check_mod
|
||||
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
|
||||
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
|
||||
import app.services.agent_registry.handlers.voucher_check as voucher_check_mod
|
||||
|
||||
importlib.reload(file_check_mod)
|
||||
importlib.reload(shipping_mod)
|
||||
importlib.reload(contract_payment_mod)
|
||||
importlib.reload(voucher_check_mod)
|
||||
importlib.reload(in_transit_transfer_mod)
|
||||
|
||||
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/voucher_check.py
|
||||
|
||||
用途:立账凭证检核 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
|
||||
依赖:agent_registry.handlers.base / registry。
|
||||
逻辑:Chat 主区渲染检核任务 / 企微发送记录 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
|
||||
from app.services.agent_registry.handlers.registry import register_handler
|
||||
|
||||
|
||||
@register_handler('voucher_check')
|
||||
class VoucherCheckHandler(AgentHandler):
|
||||
"""
|
||||
立账凭证检核业务 Handler。
|
||||
|
||||
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入批次摘要。
|
||||
"""
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
"""第一期无领域 UI State;检核列表由独立 HTTP API 加载。"""
|
||||
return None
|
||||
@@ -375,6 +375,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"type": "boolean",
|
||||
"label": "缺资料通知",
|
||||
"label_key": "admin.schedule.form.voucherCheckNotifyMissing",
|
||||
"help": "总开关。缺件接收人在 Chat「通知配置」按文件类型设置。",
|
||||
"help_key": "admin.schedule.form.voucherCheckNotifyMissingHint",
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
@@ -383,6 +385,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"type": "boolean",
|
||||
"label": "失败告警",
|
||||
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
|
||||
"help": "技术失败发给排程「选择通知人员」。",
|
||||
"help_key": "admin.schedule.form.voucherCheckNotifyFailureHint",
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/engine_persistence.py
|
||||
|
||||
用途:新引擎批次、主体、单文件结果与通知审计的写入。
|
||||
依赖:models.voucher_check 新表。
|
||||
逻辑:runner 在扫描完成后一次性 persist;旧 invoice_states 不再写入。
|
||||
逻辑:runner 在扫描完成后一次性 persist;旧 invoice_states 不再写入。SQLite 测试库的 BigInteger 主键不会自增,persist_notification 会补 id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -131,7 +131,7 @@ def persist_notification(
|
||||
summary: dict[str, Any],
|
||||
sent_at: datetime | None,
|
||||
) -> VoucherCheckNotification:
|
||||
"""写入或覆盖本批次通知审计(一个 run 一条)。"""
|
||||
"""写入或覆盖本批次通知审计(一个 run 一条)。SQLite 测试库需显式补 BigInteger 主键。"""
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotification)
|
||||
.filter_by(run_id=run_id)
|
||||
@@ -139,6 +139,10 @@ def persist_notification(
|
||||
)
|
||||
if row is None:
|
||||
row = VoucherCheckNotification(run_id=run_id, created_at=datetime.utcnow())
|
||||
bind = db.session.get_bind()
|
||||
if bind is not None and bind.dialect.name == "sqlite":
|
||||
max_id = db.session.query(db.func.max(VoucherCheckNotification.id)).scalar() or 0
|
||||
row.id = int(max_id) + 1
|
||||
db.session.add(row)
|
||||
row.excel_filename = excel_filename
|
||||
row.recipient_user_ids_json = recipient_user_ids
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/notify_config_service.py
|
||||
|
||||
用途:立账凭证按文件类型配置企微接收人,以及把本批缺件映射到「每人一封」。
|
||||
依赖:VoucherCheckNotifyConfig、User、sales Profile file_rules。
|
||||
逻辑:配置与 Profile 版本解耦;发送侧只取已绑定企微的用户。Chat 通知配置页把候选人交给公共选人弹窗;runner 共用本模块。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import User
|
||||
from app.models.voucher_check import VoucherCheckNotifyConfig
|
||||
from app.services.voucher_check.profiles.sales import SALES_PROFILE_CODE, required_file_rules
|
||||
|
||||
DEFAULT_NOTIFY_PROFILE = SALES_PROFILE_CODE
|
||||
|
||||
|
||||
def _rule_defs(profile_code: str) -> list[dict[str, Any]]:
|
||||
"""当前业务方必检文件规则。一期仅销售。"""
|
||||
code = str(profile_code or DEFAULT_NOTIFY_PROFILE).strip() or DEFAULT_NOTIFY_PROFILE
|
||||
if code != SALES_PROFILE_CODE:
|
||||
raise ValidationError("不支持的业务方", code="VOUCHER_CHECK.CONFIG_INVALID", details={"profile_code": code})
|
||||
return required_file_rules()
|
||||
|
||||
|
||||
def _known_rule_codes(profile_code: str) -> set[str]:
|
||||
return {str(rule.get("code") or "") for rule in _rule_defs(profile_code)} - {""}
|
||||
|
||||
|
||||
def normalize_recipients_json(raw: Any, *, profile_code: str) -> dict[str, list[int]]:
|
||||
"""
|
||||
把提交的接收人映射收成 {rule_code: [user_id]}。
|
||||
核心逻辑:只保留当前 Profile 的规则码;user_id 去重且必须是正整数。
|
||||
"""
|
||||
payload = raw if isinstance(raw, dict) else {}
|
||||
known = _known_rule_codes(profile_code)
|
||||
cleaned: dict[str, list[int]] = {code: [] for code in known}
|
||||
for key, value in payload.items():
|
||||
code = str(key or "").strip()
|
||||
if code not in known:
|
||||
continue
|
||||
seen: set[int] = set()
|
||||
ids: list[int] = []
|
||||
for item in value if isinstance(value, list) else []:
|
||||
try:
|
||||
user_id = int(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if user_id <= 0 or user_id in seen:
|
||||
continue
|
||||
seen.add(user_id)
|
||||
ids.append(user_id)
|
||||
cleaned[code] = ids
|
||||
return cleaned
|
||||
|
||||
|
||||
def load_recipients_by_rule(profile_code: str) -> dict[str, list[int]]:
|
||||
"""读取某业务方已保存的类型接收人;无行时返回空映射。"""
|
||||
code = str(profile_code or DEFAULT_NOTIFY_PROFILE).strip() or DEFAULT_NOTIFY_PROFILE
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotifyConfig)
|
||||
.filter_by(profile_code=code)
|
||||
.one_or_none()
|
||||
)
|
||||
raw = row.recipients_json if row and isinstance(row.recipients_json, dict) else {}
|
||||
return normalize_recipients_json(raw, profile_code=code)
|
||||
|
||||
|
||||
def plan_missing_recipient_messages(
|
||||
*,
|
||||
by_file_type: dict[str, Any],
|
||||
recipients_by_rule: dict[str, list[int]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把本批缺件类型按接收人聚合。
|
||||
核心逻辑:只处理 missing_file_count>0 的规则;同一人管多类时合并到一封。
|
||||
|
||||
Returns:
|
||||
user_rules: user_id → 该人需要看到的缺件类型列表
|
||||
unmapped_codes: 有缺件但未配置任何人的规则码
|
||||
"""
|
||||
missing_items: list[dict[str, Any]] = []
|
||||
unmapped: list[str] = []
|
||||
for code, item in (by_file_type or {}).items():
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if int(item.get("missing_file_count") or 0) <= 0:
|
||||
continue
|
||||
rule_code = str(item.get("rule_code") or code)
|
||||
payload = {
|
||||
"code": rule_code,
|
||||
"name": str(item.get("rule_name") or rule_code),
|
||||
"missing_file_count": int(item.get("missing_file_count") or 0),
|
||||
"missing_invoice_count": int(item.get("missing_invoice_count") or 0),
|
||||
}
|
||||
user_ids = [int(uid) for uid in (recipients_by_rule.get(rule_code) or []) if int(uid) > 0]
|
||||
if not user_ids:
|
||||
unmapped.append(rule_code)
|
||||
continue
|
||||
missing_items.append({**payload, "user_ids": user_ids})
|
||||
|
||||
user_rules: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
for item in missing_items:
|
||||
snippet = {
|
||||
"code": item["code"],
|
||||
"name": item["name"],
|
||||
"missing_file_count": item["missing_file_count"],
|
||||
"missing_invoice_count": item["missing_invoice_count"],
|
||||
}
|
||||
for user_id in item["user_ids"]:
|
||||
already = {row["code"] for row in user_rules[user_id]}
|
||||
if snippet["code"] not in already:
|
||||
user_rules[user_id].append(snippet)
|
||||
return {"user_rules": dict(user_rules), "unmapped_codes": unmapped}
|
||||
|
||||
|
||||
def _candidate_users() -> list[dict[str, Any]]:
|
||||
"""通知配置页候选人:在职用户,带部门与企微绑定标记,供公共选人弹窗分组。"""
|
||||
rows = (
|
||||
db.session.query(User)
|
||||
.filter(User.status == "active")
|
||||
.order_by(User.username)
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"real_name": user.real_name,
|
||||
"employee_id": user.employee_id,
|
||||
"department": user.department,
|
||||
"wecom_bound": bool(user.wecom_userid),
|
||||
}
|
||||
for user in rows
|
||||
]
|
||||
|
||||
|
||||
def get_notify_config(*, profile_code: str | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
组装通知配置页数据。
|
||||
核心逻辑:规则来自 Profile;接收人来自独立配置表;候选人带部门与企微绑定标记。
|
||||
"""
|
||||
code = str(profile_code or DEFAULT_NOTIFY_PROFILE).strip() or DEFAULT_NOTIFY_PROFILE
|
||||
recipients = load_recipients_by_rule(code)
|
||||
rules = [
|
||||
{
|
||||
"code": str(rule.get("code") or ""),
|
||||
"name": str(rule.get("name") or rule.get("code") or ""),
|
||||
"type_folder": str(rule.get("type_folder") or ""),
|
||||
"user_ids": list(recipients.get(str(rule.get("code") or ""), [])),
|
||||
}
|
||||
for rule in _rule_defs(code)
|
||||
if rule.get("code")
|
||||
]
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotifyConfig)
|
||||
.filter_by(profile_code=code)
|
||||
.one_or_none()
|
||||
)
|
||||
return {
|
||||
"profile_code": code,
|
||||
"rules": rules,
|
||||
"users": _candidate_users(),
|
||||
"updated_at": row.updated_at.isoformat(sep=" ", timespec="seconds") if row and row.updated_at else None,
|
||||
"updated_by": int(row.updated_by) if row and row.updated_by else None,
|
||||
}
|
||||
|
||||
|
||||
def save_notify_config(
|
||||
*,
|
||||
profile_code: str | None,
|
||||
recipients: Any,
|
||||
updated_by: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""写入文件类型接收人;未知规则码丢弃。"""
|
||||
code = str(profile_code or DEFAULT_NOTIFY_PROFILE).strip() or DEFAULT_NOTIFY_PROFILE
|
||||
cleaned = normalize_recipients_json(recipients, profile_code=code)
|
||||
known_ids = {int(user["id"]) for user in _candidate_users()}
|
||||
for rule_code, user_ids in list(cleaned.items()):
|
||||
cleaned[rule_code] = [user_id for user_id in user_ids if user_id in known_ids]
|
||||
now = datetime.utcnow()
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotifyConfig)
|
||||
.filter_by(profile_code=code)
|
||||
.one_or_none()
|
||||
)
|
||||
if row is None:
|
||||
row = VoucherCheckNotifyConfig(profile_code=code, created_at=now)
|
||||
db.session.add(row)
|
||||
row.recipients_json = cleaned
|
||||
row.updated_by = updated_by
|
||||
row.updated_at = now
|
||||
db.session.commit()
|
||||
return get_notify_config(profile_code=code)
|
||||
@@ -370,7 +370,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
|
||||
for item in stats["excel_rows"]
|
||||
]
|
||||
|
||||
# [STEP 4] 每批一条企微汇总
|
||||
# [STEP 4] 按文件类型接收人拆成每人一封缺件通知
|
||||
notify_status = send_batch_missing_summary(
|
||||
task=task,
|
||||
schedule_run=run,
|
||||
|
||||
Reference in new issue
Block a user