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,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Seed voucher_check Chat Agent.
|
||||
|
||||
Revision ID: vc5f6a7b8c9d
|
||||
Revises: cp9b0c1d2e3f
|
||||
Create Date: 2026-09-16 13:30:00.000000
|
||||
|
||||
用途:为立账凭证检核注册 builtin Chat Agent。此前入口在工作台且仅 admin 可见,
|
||||
没有独立功能权限键可迁移;普通用户需在用户管理授予该 Agent。
|
||||
依赖:agents 表已存在。
|
||||
逻辑:先按 agent_code 复用已有实例(含停用);没有则插入。插入前把 agents.id
|
||||
序列对齐 MAX(id),避免本地库序列落后时撞主键。admin 仍按运行时角色看到
|
||||
全部 Agent,不必写关联表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy import text
|
||||
|
||||
|
||||
revision = "vc5f6a7b8c9d"
|
||||
down_revision = "cp9b0c1d2e3f"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
AGENT_CODE = "voucher_check"
|
||||
|
||||
|
||||
def _resync_agents_id_sequence() -> None:
|
||||
"""把 agents 主键序列对齐现有最大 id,避免 nextval 撞上已占用主键。"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
op.execute(
|
||||
"""
|
||||
SELECT setval(
|
||||
pg_get_serial_sequence('public.agents', 'id'),
|
||||
COALESCE((SELECT MAX(id) FROM public.agents), 1),
|
||||
true
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""插入或复用立账凭证检核 Agent。"""
|
||||
conn = op.get_bind()
|
||||
agent_id = conn.execute(
|
||||
text(
|
||||
"SELECT id FROM agents WHERE agent_code = :code "
|
||||
"ORDER BY id ASC LIMIT 1"
|
||||
),
|
||||
{"code": AGENT_CODE},
|
||||
).scalar()
|
||||
if agent_id is not None:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE agents
|
||||
SET is_active = true,
|
||||
runtime_provider = 'builtin',
|
||||
conversation_mode = 'task_chat',
|
||||
dify_app_type = 'chatflow',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = :agent_id
|
||||
"""
|
||||
),
|
||||
{"agent_id": agent_id},
|
||||
)
|
||||
return
|
||||
|
||||
_resync_agents_id_sequence()
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO agents (
|
||||
name, description, type, is_active, is_aggregate,
|
||||
agent_code, runtime_provider, conversation_mode, dify_app_type,
|
||||
suggested_questions_style, sort_order, created_at, updated_at
|
||||
) VALUES (
|
||||
:name, :description, 'api', true, false,
|
||||
:code, 'builtin', 'task_chat', 'chatflow',
|
||||
'plain', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"name": "立账凭证",
|
||||
"description": "查看立账凭证检核任务、最近一次检核进度和企业微信发送记录。",
|
||||
"code": AGENT_CODE,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""不删除已创建的 Agent 实例,以免误伤运营配置。"""
|
||||
return
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Add voucher_check_notify_configs.
|
||||
|
||||
Revision ID: vc6a7b8c9d0e
|
||||
Revises: vc5f6a7b8c9d
|
||||
Create Date: 2026-09-16 15:55:00.000000
|
||||
|
||||
用途:按业务方保存立账凭证缺件通知的文件类型接收人。
|
||||
依赖:voucher_check 引擎表、users 表。
|
||||
逻辑:与 Profile 版本解耦,换人不需要发版 file_rules。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "vc6a7b8c9d0e"
|
||||
down_revision = "vc5f6a7b8c9d"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""新增按文件类型配置企微接收人的表。"""
|
||||
op.create_table(
|
||||
"voucher_check_notify_configs",
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("profile_code", sa.String(length=32), nullable=False),
|
||||
sa.Column("recipients_json", sa.JSON(), nullable=False),
|
||||
sa.Column("updated_by", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("profile_code", name="uq_voucher_check_notify_configs_profile"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除按文件类型接收人配置表。"""
|
||||
op.drop_table("voucher_check_notify_configs")
|
||||
@@ -19,7 +19,7 @@ def test_agent_type_catalog_contains_three_seed_types():
|
||||
"""Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。"""
|
||||
assert {
|
||||
'generic', 'shipping_notice', 'file_check',
|
||||
'procurement_contract_review', 'in_transit_transfer', 'contract_payment',
|
||||
'procurement_contract_review', 'in_transit_transfer', 'contract_payment', 'voucher_check',
|
||||
} <= set(AGENT_TYPE_CATALOG.keys())
|
||||
|
||||
|
||||
@@ -28,13 +28,14 @@ def test_list_type_catalog_includes_agent_code_and_label():
|
||||
catalog = list_type_catalog()
|
||||
assert len(catalog) >= 5
|
||||
codes = {entry['agent_code'] for entry in catalog}
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer', 'contract_payment'} <= codes
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer', 'contract_payment', 'voucher_check'} <= codes
|
||||
labels = {entry['label'] for entry in catalog}
|
||||
assert '通用问答 / 知识库' in labels
|
||||
assert '在途仓自动调拨' in labels
|
||||
assert '货代发货通知' in labels
|
||||
assert '文件检核' in labels
|
||||
assert '合同付款预警' in labels
|
||||
assert '立账凭证' in labels
|
||||
|
||||
|
||||
def test_get_catalog_entry_returns_runtime_handler_for_hybrid_types():
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_agent_registry_voucher_check.py
|
||||
|
||||
用途:验证 voucher_check 已注册为 builtin Chat Agent 类型。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap。
|
||||
逻辑:只读断言 Catalog 声明与 Handler 绑定;不创建 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.agent_registry import catalog_bindings
|
||||
from app.services.agent_registry.catalog_loader import build_agent_type_catalog, get_catalog_entry
|
||||
from app.services.agent_registry.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_voucher_check_type_in_catalog():
|
||||
"""catalog 必须包含 voucher_check,默认 builtin + task_chat。"""
|
||||
entry = get_catalog_entry('voucher_check')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '立账凭证'
|
||||
assert entry.get('runtime_provider_default') == 'builtin'
|
||||
assert entry.get('conversation_mode_default') == 'task_chat'
|
||||
assert entry.get('runtime_handler') == 'voucher_check'
|
||||
|
||||
|
||||
def test_voucher_check_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 voucher_check 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['voucher_check'] == 'voucher_check'
|
||||
|
||||
|
||||
def test_voucher_check_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 VoucherCheckHandler。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('voucher_check')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'voucher_check'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_voucher_check_present_in_full_catalog():
|
||||
"""完整 catalog 与既有类型共存。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'voucher_check' in catalog
|
||||
assert 'contract_payment' in catalog
|
||||
@@ -0,0 +1,178 @@
|
||||
"""
|
||||
backend/tests/test_voucher_check_permissions.py
|
||||
|
||||
用途:验收立账凭证改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、workspace voucher_check 蓝图。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表,但不能触发强制重检、也不能改通知配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
"""创建落库用户,供 voucher-check API 走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role=role,
|
||||
status='active',
|
||||
real_name=f'{username}-实名',
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='财务部',
|
||||
)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def _ensure_voucher_check_agent() -> Agent:
|
||||
"""确保存在启用中的立账凭证 Agent,供授权绑定。"""
|
||||
agent = Agent.query.filter_by(agent_code='voucher_check', is_active=True).first()
|
||||
if agent:
|
||||
return agent
|
||||
agent = Agent(
|
||||
name='立账凭证',
|
||||
agent_code='voucher_check',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(agent)
|
||||
return agent
|
||||
|
||||
|
||||
def _grant_voucher_check_agent(user: User) -> User:
|
||||
"""把立账凭证 Agent 授权给指定用户并重新取出,避免会话分离后丢失关系。"""
|
||||
agent = _ensure_voucher_check_agent()
|
||||
user_id = user.id
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.expunge(user)
|
||||
return db.session.get(User, user_id) or user
|
||||
|
||||
|
||||
def _json_error(response) -> dict:
|
||||
"""读取标准 envelope 的 error 对象。"""
|
||||
body = response.get_json()
|
||||
assert body.get('success') is False
|
||||
assert isinstance(body.get('error'), dict)
|
||||
return body['error']
|
||||
|
||||
|
||||
def test_voucher_check_api_forbids_user_without_agent(client, app):
|
||||
"""未授予 Agent 的普通用户查询任务或强制重检均返回 VOUCHER_CHECK.FORBIDDEN。"""
|
||||
with app.app_context():
|
||||
ordinary = _create_user(username='vc_api_denied')
|
||||
ordinary_id = ordinary.id
|
||||
_ensure_voucher_check_agent()
|
||||
db.session.expunge(ordinary)
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(ordinary_id),
|
||||
'X-Username': 'vc_api_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
# 关键断言:登录不足够,Agent 授权缺失必须 403。
|
||||
assert list_res.status_code == 403
|
||||
assert _json_error(list_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
force_res = client.post(
|
||||
'/api/workspace/accounting-voucher-check/runs',
|
||||
headers=headers,
|
||||
json={'mode': 'force_all'},
|
||||
)
|
||||
assert force_res.status_code == 403
|
||||
assert _json_error(force_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
|
||||
def test_voucher_check_api_allows_granted_user(client, app):
|
||||
"""授予 voucher_check Agent 后普通用户可以查询检核任务。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_granted'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_granted',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
# 关键断言:Agent 授权后不再 403,返回标准成功 envelope。
|
||||
assert list_res.status_code == 200
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_voucher_check_api_allows_admin_without_agent_binding(client, app):
|
||||
"""平台 admin 即使未绑定该 Agent 也可查询检核任务。"""
|
||||
with app.app_context():
|
||||
admin = _create_user(username='vc_api_admin', role='admin')
|
||||
admin_id = admin.id
|
||||
_ensure_voucher_check_agent()
|
||||
db.session.expunge(admin)
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(admin_id),
|
||||
'X-Username': 'vc_api_admin',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
assert list_res.status_code == 200
|
||||
assert list_res.get_json().get('success') is True
|
||||
|
||||
|
||||
def test_voucher_check_force_requires_admin(client, app):
|
||||
"""已授权的普通用户可查任务,但不能触发强制重检。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_jobs_denied'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_jobs_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
# 关键断言:访问权不等于操作权,强制重检仅管理员。
|
||||
res = client.post(
|
||||
'/api/workspace/accounting-voucher-check/runs',
|
||||
headers=headers,
|
||||
json={'mode': 'force_all'},
|
||||
)
|
||||
assert res.status_code == 403
|
||||
assert _json_error(res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
|
||||
def test_voucher_check_notify_config_requires_admin(client, app):
|
||||
"""已授权的普通用户可查任务,但不能读取或保存按类型接收人。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_notify_denied'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_notify_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
get_res = client.get('/api/workspace/accounting-voucher-check/notify-config', headers=headers)
|
||||
# 关键断言:通知配置读写均仅管理员。
|
||||
assert get_res.status_code == 403
|
||||
assert _json_error(get_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
put_res = client.put(
|
||||
'/api/workspace/accounting-voucher-check/notify-config',
|
||||
headers=headers,
|
||||
json={'profile_code': 'sales', 'recipients': {'po_order': [granted_id]}},
|
||||
)
|
||||
assert put_res.status_code == 403
|
||||
assert _json_error(put_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
@@ -0,0 +1,300 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_notify_config.py
|
||||
|
||||
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
|
||||
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
|
||||
逻辑:GET/PUT 仅 admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.models.voucher_check import VoucherCheckNotification, VoucherCheckNotifyConfig, VoucherCheckRun
|
||||
from app.services.voucher_check.notify_config_service import (
|
||||
normalize_recipients_json,
|
||||
plan_missing_recipient_messages,
|
||||
)
|
||||
from app.services.voucher_check.notification import send_batch_missing_summary
|
||||
|
||||
|
||||
def _ensure_user(
|
||||
*,
|
||||
username: str,
|
||||
role: str = "user",
|
||||
wecom_userid: str | None = None,
|
||||
department: str | None = None,
|
||||
) -> User:
|
||||
"""
|
||||
测试用户幂等创建。
|
||||
|
||||
Args:
|
||||
username: 登录名。
|
||||
role: 角色,默认普通用户。
|
||||
wecom_userid: 企微 userid,有值即视为已绑定。
|
||||
department: 部门名,供候选人接口与选人弹窗分组。
|
||||
"""
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if user:
|
||||
user.role = role
|
||||
user.status = "active"
|
||||
user.wecom_userid = wecom_userid
|
||||
if department is not None:
|
||||
user.department = department
|
||||
db.session.commit()
|
||||
return user
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role=role,
|
||||
status="active",
|
||||
real_name=username,
|
||||
wecom_userid=wecom_userid,
|
||||
department=department,
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_plan_merges_types_per_user_and_tracks_unmapped():
|
||||
"""同一人管多类时合并到一封;有缺件但无人接收的类型进入 unmapped。"""
|
||||
plan = plan_missing_recipient_messages(
|
||||
by_file_type={
|
||||
"po_order": {
|
||||
"rule_code": "po_order",
|
||||
"rule_name": "PO订单",
|
||||
"missing_file_count": 2,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
"tax_invoice": {
|
||||
"rule_code": "tax_invoice",
|
||||
"rule_name": "发票",
|
||||
"missing_file_count": 3,
|
||||
"missing_invoice_count": 2,
|
||||
},
|
||||
"bill_of_lading": {
|
||||
"rule_code": "bill_of_lading",
|
||||
"rule_name": "提单",
|
||||
"missing_file_count": 1,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
"customs_pack": {
|
||||
"rule_code": "customs_pack",
|
||||
"rule_name": "报关资料",
|
||||
"missing_file_count": 0,
|
||||
"missing_invoice_count": 0,
|
||||
},
|
||||
},
|
||||
recipients_by_rule={
|
||||
"po_order": [11, 12],
|
||||
"tax_invoice": [11],
|
||||
"bill_of_lading": [],
|
||||
},
|
||||
)
|
||||
# 关键断言:11 同时收到 PO 与发票;提单无人配置。
|
||||
assert plan["unmapped_codes"] == ["bill_of_lading"]
|
||||
assert [item["code"] for item in plan["user_rules"][11]] == ["po_order", "tax_invoice"]
|
||||
assert [item["code"] for item in plan["user_rules"][12]] == ["po_order"]
|
||||
|
||||
|
||||
def test_normalize_drops_unknown_rule_codes():
|
||||
"""提交里的未知规则码必须丢弃,不能写进配置表。"""
|
||||
cleaned = normalize_recipients_json(
|
||||
{"po_order": [1, 1, "2", 0, "x"], "unknown": [9]},
|
||||
profile_code="sales",
|
||||
)
|
||||
assert cleaned["po_order"] == [1, 2]
|
||||
assert "unknown" not in cleaned
|
||||
assert "tax_invoice" in cleaned
|
||||
|
||||
|
||||
def test_admin_can_get_and_save_notify_config(app, client, admin_headers):
|
||||
"""管理员可读取六行规则并保存接收人。"""
|
||||
with app.app_context():
|
||||
admin = _ensure_user(username="admin", role="admin")
|
||||
owner = _ensure_user(username="vc_po_owner", wecom_userid="wx-po", department="财务部")
|
||||
owner_id = owner.id
|
||||
admin_id = admin.id
|
||||
|
||||
listed = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notify-config",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
payload = parse_api_data(listed.get_json())
|
||||
owner_row = next(row for row in payload["users"] if row["id"] == owner_id)
|
||||
# 关键断言:候选人带部门,供公共选人弹窗左侧分组。
|
||||
assert owner_row["department"] == "财务部"
|
||||
assert owner_row["wecom_bound"] is True
|
||||
codes = [row["code"] for row in payload["rules"]]
|
||||
# 关键断言:页面行来自销售 Profile 六类必检文件。
|
||||
assert codes == [
|
||||
"po_order",
|
||||
"customs_pack",
|
||||
"sales_release",
|
||||
"tax_invoice",
|
||||
"customs_declaration",
|
||||
"bill_of_lading",
|
||||
]
|
||||
|
||||
saved = client.put(
|
||||
"/api/workspace/accounting-voucher-check/notify-config",
|
||||
headers=admin_headers,
|
||||
json={
|
||||
"profile_code": "sales",
|
||||
"recipients": {"po_order": [owner_id], "unknown": [admin_id]},
|
||||
},
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
saved_payload = parse_api_data(saved.get_json())
|
||||
po_row = next(row for row in saved_payload["rules"] if row["code"] == "po_order")
|
||||
assert po_row["user_ids"] == [owner_id]
|
||||
unknown_codes = [row["code"] for row in saved_payload["rules"] if row["code"] == "unknown"]
|
||||
assert unknown_codes == []
|
||||
|
||||
with app.app_context():
|
||||
row = db.session.query(VoucherCheckNotifyConfig).filter_by(profile_code="sales").one()
|
||||
assert row.recipients_json["po_order"] == [owner_id]
|
||||
assert "unknown" not in row.recipients_json
|
||||
|
||||
|
||||
def test_notify_config_rejects_non_admin_headers(app, client, user_headers):
|
||||
"""仅凭普通用户 header 不能改通知配置。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
|
||||
res = client.get("/api/workspace/accounting-voucher-check/notify-config", headers=user_headers)
|
||||
assert res.status_code == 403
|
||||
assert parse_api_error(res.get_json())["code"] in {
|
||||
"VOUCHER_CHECK.FORBIDDEN",
|
||||
"VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
}
|
||||
|
||||
|
||||
def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
||||
"""缺件通知按人拆信,正文只含该人负责的缺失类型。"""
|
||||
sent: list[tuple[str, str, str]] = []
|
||||
|
||||
def _fake_send(wecom_userid, title, description, jump_url):
|
||||
sent.append((wecom_userid, title, description))
|
||||
return {"errcode": 0}
|
||||
|
||||
monkeypatch.setattr("app.services.wecom_notify.send_wecom_textcard_message", _fake_send)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify._create_audit",
|
||||
lambda *args, **kwargs: SimpleNamespace(
|
||||
jump_url=None, status=None, error_code=None, error_message=None
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr("app.services.wecom_notify._build_jump_url", lambda *args, **kwargs: "https://jump")
|
||||
|
||||
with app.app_context():
|
||||
app.config["WECOM_NOTIFY_ENABLED"] = True
|
||||
owner = _ensure_user(username="vc_notify_owner", role="admin", wecom_userid="wx-owner")
|
||||
po_user = _ensure_user(username="vc_po_recv", wecom_userid="wx-po-recv")
|
||||
bl_user = _ensure_user(username="vc_bl_recv", wecom_userid="wx-bl-recv")
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-VC-NOTIFY-SPLIT",
|
||||
name="立账凭证检核",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-check",
|
||||
owner_user_id=owner.id,
|
||||
cron_expr="0 6 * * 2",
|
||||
notify_enabled=True,
|
||||
notify_user_ids_json=[],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
schedule_run = ScheduleRun(
|
||||
schedule_task_id=task.id,
|
||||
run_no="RUN-VC-NOTIFY-SPLIT",
|
||||
trigger_type="cron",
|
||||
status="success",
|
||||
)
|
||||
db.session.add(schedule_run)
|
||||
db.session.flush()
|
||||
engine_run = VoucherCheckRun(
|
||||
id=1,
|
||||
schedule_run_id=schedule_run.id,
|
||||
run_no="VC-NOTIFY-SPLIT",
|
||||
profile_code="sales",
|
||||
profile_version="1",
|
||||
profile_snapshot_json={"profile_code": "sales"},
|
||||
period_month=date(2026, 8, 1),
|
||||
mode="incremental",
|
||||
status="missing",
|
||||
subject_count=4,
|
||||
missing_file_count=3,
|
||||
missing_invoice_count=2,
|
||||
)
|
||||
db.session.add(engine_run)
|
||||
db.session.flush()
|
||||
notify_row = (
|
||||
db.session.query(VoucherCheckNotifyConfig).filter_by(profile_code="sales").one_or_none()
|
||||
)
|
||||
if notify_row is None:
|
||||
notify_row = VoucherCheckNotifyConfig(profile_code="sales")
|
||||
db.session.add(notify_row)
|
||||
notify_row.recipients_json = {
|
||||
"po_order": [po_user.id],
|
||||
"bill_of_lading": [bl_user.id],
|
||||
}
|
||||
db.session.commit()
|
||||
status = send_batch_missing_summary(
|
||||
task=task,
|
||||
schedule_run=schedule_run,
|
||||
engine_run_id=engine_run.id,
|
||||
profile_code="sales",
|
||||
period_month="2026-08",
|
||||
stats={
|
||||
"subject_count": 4,
|
||||
"missing_file_count": 3,
|
||||
"missing_invoice_count": 2,
|
||||
"by_file_type": {
|
||||
"po_order": {
|
||||
"rule_code": "po_order",
|
||||
"rule_name": "PO订单",
|
||||
"missing_file_count": 2,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
"bill_of_lading": {
|
||||
"rule_code": "bill_of_lading",
|
||||
"rule_name": "提单",
|
||||
"missing_file_count": 1,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
"tax_invoice": {
|
||||
"rule_code": "tax_invoice",
|
||||
"rule_name": "发票",
|
||||
"missing_file_count": 1,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
excel_filename="voucher_check_sales_2026-08.xlsx",
|
||||
enabled=True,
|
||||
)
|
||||
assert status == "sent"
|
||||
audit = db.session.query(VoucherCheckNotification).filter_by(run_id=engine_run.id).one()
|
||||
# 关键断言:仍是一批一条审计;skip_reason 记录未配置类型。
|
||||
assert audit.send_status == "sent"
|
||||
assert audit.skip_reason == "部分文件类型未配置接收人"
|
||||
assert set(audit.recipient_user_ids_json or []) == {po_user.id, bl_user.id}
|
||||
assert "tax_invoice" in (audit.summary_json or {}).get("unmapped_rule_codes", [])
|
||||
|
||||
wecom_ids = {item[0] for item in sent}
|
||||
assert wecom_ids == {"wx-po-recv", "wx-bl-recv"}
|
||||
po_body = next(item[2] for item in sent if item[0] == "wx-po-recv")
|
||||
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
||||
assert "PO订单" in po_body
|
||||
assert "提单" not in po_body
|
||||
assert "发票" not in po_body
|
||||
assert "提单" in bl_body
|
||||
assert "PO订单" not in bl_body
|
||||
@@ -104,10 +104,10 @@ def _add_engine_run(
|
||||
return engine
|
||||
|
||||
|
||||
def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers):
|
||||
def test_workspace_latest_run_returns_queued_force_all(app, client, admin_headers):
|
||||
"""入队中的强制重检必须显示 queued,而不是建批前失败口径。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-QUEUED",
|
||||
status="queued",
|
||||
@@ -117,7 +117,7 @@ def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
@@ -129,10 +129,10 @@ def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers
|
||||
assert payload["current_step"]["step"] == "queued"
|
||||
|
||||
|
||||
def test_workspace_latest_run_returns_completed_metrics(app, client, user_headers):
|
||||
def test_workspace_latest_run_returns_completed_metrics(app, client, admin_headers):
|
||||
"""终态缺件批次返回四指标与 100% 进度。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
sched = _add_schedule_run(
|
||||
run_no="RUN-LATEST-DONE",
|
||||
status="success",
|
||||
@@ -149,7 +149,7 @@ def test_workspace_latest_run_returns_completed_metrics(app, client, user_header
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
@@ -165,10 +165,10 @@ def test_workspace_latest_run_returns_completed_metrics(app, client, user_header
|
||||
assert payload["missing_invoice_count"] == 6
|
||||
|
||||
|
||||
def test_workspace_latest_run_running_progress_ignores_list_period(app, client, user_headers):
|
||||
def test_workspace_latest_run_running_progress_ignores_list_period(app, client, admin_headers):
|
||||
"""执行中进度跟 runner 步骤走,且 latest 不吃列表 period。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
old = _add_schedule_run(
|
||||
run_no="RUN-LATEST-OLD-AUG",
|
||||
status="success",
|
||||
@@ -200,7 +200,7 @@ def test_workspace_latest_run_running_progress_ignores_list_period(app, client,
|
||||
|
||||
latest = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert latest.status_code == 200
|
||||
payload = parse_api_data(latest.get_json())
|
||||
@@ -213,7 +213,7 @@ def test_workspace_latest_run_running_progress_ignores_list_period(app, client,
|
||||
|
||||
filtered = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert filtered.status_code == 200
|
||||
nos = {item["run_no"] for item in parse_api_data(filtered.get_json())["items"]}
|
||||
@@ -222,10 +222,10 @@ def test_workspace_latest_run_running_progress_ignores_list_period(app, client,
|
||||
assert payload["run_no"] == "RUN-LATEST-RUNNING"
|
||||
|
||||
|
||||
def test_workspace_latest_run_pre_engine_failure(app, client, user_headers):
|
||||
def test_workspace_latest_run_pre_engine_failure(app, client, admin_headers):
|
||||
"""建批前失败仍作为最近一次检核,状态为技术失败。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-FAILED",
|
||||
status="failed",
|
||||
@@ -242,7 +242,7 @@ def test_workspace_latest_run_pre_engine_failure(app, client, user_headers):
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
|
||||
@@ -42,7 +42,7 @@ def _ensure_user(*, username: str, role: str, real_name: str | None = None) -> U
|
||||
return user
|
||||
|
||||
|
||||
def test_workspace_lists_wecom_notifications(app, client, user_headers):
|
||||
def test_workspace_lists_wecom_notifications(app, client, admin_headers):
|
||||
"""企微发送记录列表应带出批次统计、接收人姓名,并按发送状态筛选。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
@@ -116,7 +116,7 @@ def test_workspace_lists_wecom_notifications(app, client, user_headers):
|
||||
|
||||
listed = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
payload = parse_api_data(listed.get_json())
|
||||
@@ -132,7 +132,7 @@ def test_workspace_lists_wecom_notifications(app, client, user_headers):
|
||||
|
||||
filtered = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications?period=2026-07&send_status=skipped_no_missing",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert filtered.status_code == 200
|
||||
filtered_payload = parse_api_data(filtered.get_json())
|
||||
|
||||
@@ -74,10 +74,10 @@ def test_parse_period_filter_year_and_month():
|
||||
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
|
||||
def test_workspace_lists_runs_by_year_or_month(app, client, admin_headers):
|
||||
"""任务列表 year 筛出同年多月,month 仍只返回单月。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
db.session.add(_engine_run(run_no="VC-202608-Y", period_month=date(2026, 8, 1)))
|
||||
db.session.add(_engine_run(run_no="VC-202607-Y", period_month=date(2026, 7, 1)))
|
||||
db.session.add(_engine_run(run_no="VC-202512-Y", period_month=date(2025, 12, 1)))
|
||||
@@ -85,7 +85,7 @@ def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
|
||||
|
||||
year_resp = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert year_resp.status_code == 200
|
||||
year_payload = parse_api_data(year_resp.get_json())
|
||||
@@ -97,7 +97,7 @@ def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
|
||||
|
||||
month_resp = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert month_resp.status_code == 200
|
||||
month_payload = parse_api_data(month_resp.get_json())
|
||||
@@ -137,10 +137,10 @@ def test_workspace_year_filter_includes_pre_engine_failure(app, client, admin_he
|
||||
assert "RUN-PREENGINE-YEAR" in nos
|
||||
|
||||
|
||||
def test_workspace_lists_notifications_by_year(app, client, user_headers):
|
||||
def test_workspace_lists_notifications_by_year(app, client, admin_headers):
|
||||
"""企微发送记录按年筛选应覆盖该年各月。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
august = _engine_run(run_no="VC-202608-N", period_month=date(2026, 8, 1))
|
||||
july = _engine_run(run_no="VC-202607-N", period_month=date(2026, 7, 1), status="completed")
|
||||
db.session.add_all([august, july])
|
||||
@@ -163,7 +163,7 @@ def test_workspace_lists_notifications_by_year(app, client, user_headers):
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications?period=2026",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
@@ -172,13 +172,13 @@ def test_workspace_lists_notifications_by_year(app, client, user_headers):
|
||||
assert "VC-202607-N" in nos
|
||||
|
||||
|
||||
def test_workspace_rejects_invalid_period(app, client, user_headers):
|
||||
def test_workspace_rejects_invalid_period(app, client, admin_headers):
|
||||
"""非法 period 返回配置错误,而不是空列表。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-13",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 400
|
||||
error = parse_api_error(response.get_json())
|
||||
|
||||
Reference in new issue
Block a user