feat(invoice-check): 立账凭证检核增加收件人配置并迁移到chat页面
This commit is contained in:
1 parent
18e957545c
commit
7b80b4c395
72 files changed
+2705
-263
No files matched your search
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/api/workspace/voucher_check.py
|
||||
|
||||
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录)。
|
||||
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
|
||||
逻辑:对话与检核任务页共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
|
||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,23 +14,88 @@ from flask import Blueprint, request
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.voucher_check import query_service
|
||||
from app.models import Agent
|
||||
from app.services.voucher_check import notify_config_service, query_service
|
||||
|
||||
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
||||
|
||||
VOUCHER_CHECK_AGENT_CODE = "voucher_check"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
返回当前登录用户。
|
||||
|
||||
Returns:
|
||||
已认证用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_admin():
|
||||
"""工作台强制重检仅管理员可触发,鉴权方式与本蓝图 GET 一致。"""
|
||||
def _user_has_voucher_check_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的立账凭证检核 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
|
||||
Args:
|
||||
user: 已认证用户。
|
||||
|
||||
Returns:
|
||||
已绑定启用中的 voucher_check Agent 时为 True。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=VOUCHER_CHECK_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_voucher_check_access():
|
||||
"""
|
||||
确保当前用户已登录且具备立账凭证检核访问权限。
|
||||
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Returns:
|
||||
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Voucher check agent permission required",
|
||||
code="VOUCHER_CHECK.FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def _require_admin():
|
||||
"""
|
||||
确保当前用户既有立账凭证访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
|
||||
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_voucher_check_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError("Admin privilege required")
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for voucher check jobs",
|
||||
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@@ -39,7 +105,7 @@ def workspace_voucher_runs():
|
||||
分页查看检核任务列表。
|
||||
核心逻辑:委托 query_service.list_runs;period 为 YYYY 或 YYYY-MM,可再按业务方/状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_runs(
|
||||
period=request.args.get("period"),
|
||||
profile_code=request.args.get("profile_code"),
|
||||
@@ -75,7 +141,7 @@ def workspace_voucher_latest_run():
|
||||
读取最近一次立账凭证检核批次(含排队/执行中)。
|
||||
核心逻辑:委托 query_service.get_latest_run;不跟列表 period/status;无批次时 data 为 null。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
return ok(query_service.get_latest_run())
|
||||
|
||||
|
||||
@@ -85,7 +151,7 @@ def workspace_voucher_run_items(run_id: int):
|
||||
分页查看批次明细。
|
||||
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_run_items(
|
||||
run_id=run_id,
|
||||
result=request.args.get("result"),
|
||||
@@ -98,10 +164,10 @@ def workspace_voucher_run_items(run_id: int):
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"])
|
||||
def workspace_voucher_notifications():
|
||||
"""
|
||||
分页查看企微缺件汇总发送记录。
|
||||
分页查看企微缺件通知发送记录。
|
||||
核心逻辑:委托 query_service.list_notifications;period 为 YYYY 或 YYYY-MM,可再按发送状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_notifications(
|
||||
period=request.args.get("period"),
|
||||
send_status=request.args.get("send_status"),
|
||||
@@ -109,3 +175,29 @@ def workspace_voucher_notifications():
|
||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||
)
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
读取按文件类型的企微接收人配置。
|
||||
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
"""
|
||||
_require_admin()
|
||||
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["PUT"])
|
||||
def workspace_voucher_notify_config_put():
|
||||
"""
|
||||
保存按文件类型的企微接收人。
|
||||
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
"""
|
||||
user = _require_admin()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = notify_config_service.save_notify_config(
|
||||
profile_code=payload.get("profile_code") or request.args.get("profile_code"),
|
||||
recipients=payload.get("recipients"),
|
||||
updated_by=getattr(user, "id", None),
|
||||
)
|
||||
return ok(data)
|
||||
@@ -221,6 +221,7 @@ from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgen
|
||||
from app.models.voucher_check import (
|
||||
VoucherCheckFileResult,
|
||||
VoucherCheckNotification,
|
||||
VoucherCheckNotifyConfig,
|
||||
VoucherCheckProfile,
|
||||
VoucherCheckRun,
|
||||
VoucherCheckSubject,
|
||||
@@ -413,6 +414,7 @@ __all__ = [
|
||||
'VoucherCheckSubject',
|
||||
'VoucherCheckFileResult',
|
||||
'VoucherCheckNotification',
|
||||
'VoucherCheckNotifyConfig',
|
||||
'ContractPaymentContract',
|
||||
'ContractPaymentAttachment',
|
||||
'ContractPaymentNode',
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/models/voucher_check.py
|
||||
|
||||
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。
|
||||
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知 / 按类型接收人)。
|
||||
依赖:models.base.Base、schedule_runs。
|
||||
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;工作台与查询服务只读这些表。
|
||||
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;通知配置表供管理员维护文件类型接收人。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +17,7 @@ from sqlalchemy import (
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
@@ -158,13 +159,35 @@ class VoucherCheckFileResult(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class VoucherCheckNotifyConfig(Base):
|
||||
"""按业务方保存文件类型 → 接收人;换人不改 Profile 版本。"""
|
||||
|
||||
__tablename__ = "voucher_check_notify_configs"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
profile_code: Mapped[str] = mapped_column(String(32), nullable=False, unique=True)
|
||||
recipients_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("users.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
default=datetime.utcnow,
|
||||
onupdate=datetime.utcnow,
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class VoucherCheckNotification(Base):
|
||||
"""一个检核批次对应一条企微汇总通知审计。"""
|
||||
"""一个检核批次对应一条企微缺件通知审计(可含多人分信摘要)。"""
|
||||
|
||||
__tablename__ = "voucher_check_notifications"
|
||||
__table_args__ = (Index("ix_voucher_check_notifications_status", "send_status"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
|
||||
|
||||
@@ -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