From 7b80b4c3954d63fd1a8ea8ce0022215b025cdc1c Mon Sep 17 00:00:00 2001 From: sophie Date: Thu, 17 Sep 2026 13:17:37 +0800 Subject: [PATCH] =?UTF-8?q?feat(invoice-check):=20=E7=AB=8B=E8=B4=A6?= =?UTF-8?q?=E5=87=AD=E8=AF=81=E6=A3=80=E6=A0=B8=E5=A2=9E=E5=8A=A0=E6=94=B6?= =?UTF-8?q?=E4=BB=B6=E4=BA=BA=E9=85=8D=E7=BD=AE=E5=B9=B6=E8=BF=81=E7=A7=BB?= =?UTF-8?q?=E5=88=B0chat=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/workspace/voucher_check.py | 116 ++++++- backend/app/models/__init__.py | 2 + backend/app/models/voucher_check.py | 31 +- .../agent_registry/catalog_bindings.py | 1 + .../agent_registry/data/catalog_manifest.yaml | 15 + .../agent_registry/handlers/bootstrap.py | 4 +- .../agent_registry/handlers/voucher_check.py | 31 ++ backend/app/services/schedule/job_registry.py | 4 + .../voucher_check/engine_persistence.py | 8 +- .../services/voucher_check/notification.py | 184 ++++++---- .../voucher_check/notify_config_service.py | 200 +++++++++++ backend/app/services/voucher_check/runner.py | 2 +- ...f6a7b8c9d_seed_voucher_check_chat_agent.py | 97 ++++++ ...8c9d0e_add_voucher_check_notify_configs.py | 40 +++ backend/tests/test_agent_registry_catalog.py | 5 +- .../test_agent_registry_voucher_check.py | 48 +++ .../tests/test_voucher_check_permissions.py | 178 ++++++++++ .../tests/voucher_check/test_notify_config.py | 300 ++++++++++++++++ .../test_workspace_latest_run.py | 26 +- .../test_workspace_notifications.py | 6 +- .../test_workspace_period_filter.py | 20 +- docs/demand.md | 6 +- docs/features/README.md | 2 +- .../accounting-voucher-check/README.md | 6 +- ...ng-voucher-check-latest-run-prototype.html | 25 +- .../accounting-voucher-check/demand.md | 40 ++- .../accounting-voucher-check/ops-checklist.md | 12 +- .../technical-design.md | 15 +- .../accounting-voucher-check/technical.md | 18 +- docs/funclist.md | 4 +- docs/platform/README.md | 1 + docs/tec.md | 5 +- .../src/app/router/routes/workspace.routes.ts | 12 +- .../chat/components/ChatMobileHeader.vue | 2 +- .../features/chat/components/ChatSidebar.vue | 4 +- .../chat/components/ChatViewContent.vue | 22 +- .../components/VoucherCheckChatPanel.vue | 153 +++++++++ .../VoucherCheckNotifyConfigPanel.vue | 201 +++++++++++ .../src/features/voucher-check/constants.ts | 10 + .../utils/voucherCheckChat.utils.test.ts | 51 +++ .../utils/voucherCheckChat.utils.ts | 52 +++ .../views/VoucherCheckChatRedirect.vue | 85 +++++ .../workspace/api/voucherCheck.api.ts | 59 +++- .../workspace/components/WorkspaceSidebar.vue | 5 +- .../features/workspace/constants/routes.ts | 2 +- .../AccountingVoucherCheckDetailView.vue | 26 +- .../views/AccountingVoucherCheckView.vue | 194 +++++++---- frontend/src/locales/en/admin.json | 4 +- frontend/src/locales/en/chat.json | 3 + frontend/src/locales/en/common.json | 19 +- frontend/src/locales/en/errors.json | 2 + frontend/src/locales/en/workspace.json | 14 + frontend/src/locales/th/admin.json | 4 +- frontend/src/locales/th/chat.json | 3 + frontend/src/locales/th/common.json | 19 +- frontend/src/locales/th/errors.json | 2 + frontend/src/locales/th/workspace.json | 14 + frontend/src/locales/zh-CN/admin.json | 4 +- frontend/src/locales/zh-CN/chat.json | 3 + frontend/src/locales/zh-CN/common.json | 19 +- frontend/src/locales/zh-CN/errors.json | 2 + frontend/src/locales/zh-CN/workspace.json | 14 + frontend/src/locales/zh-TW/admin.json | 4 +- frontend/src/locales/zh-TW/chat.json | 3 + frontend/src/locales/zh-TW/common.json | 19 +- frontend/src/locales/zh-TW/errors.json | 2 + frontend/src/locales/zh-TW/workspace.json | 14 + .../shared/components/UserPickerDialog.vue | 320 ++++++++++++++++++ frontend/src/shared/types/userPicker.types.ts | 17 + .../src/shared/utils/agent-registry.utils.ts | 6 + .../src/shared/utils/userPicker.utils.test.ts | 47 +++ frontend/src/shared/utils/userPicker.utils.ts | 80 +++++ 72 files changed, 2705 insertions(+), 263 deletions(-) create mode 100644 backend/app/services/agent_registry/handlers/voucher_check.py create mode 100644 backend/app/services/voucher_check/notify_config_service.py create mode 100644 backend/migrations/versions/vc5f6a7b8c9d_seed_voucher_check_chat_agent.py create mode 100644 backend/migrations/versions/vc6a7b8c9d0e_add_voucher_check_notify_configs.py create mode 100644 backend/tests/test_agent_registry_voucher_check.py create mode 100644 backend/tests/test_voucher_check_permissions.py create mode 100644 backend/tests/voucher_check/test_notify_config.py create mode 100644 frontend/src/features/voucher-check/components/VoucherCheckChatPanel.vue create mode 100644 frontend/src/features/voucher-check/components/VoucherCheckNotifyConfigPanel.vue create mode 100644 frontend/src/features/voucher-check/constants.ts create mode 100644 frontend/src/features/voucher-check/utils/voucherCheckChat.utils.test.ts create mode 100644 frontend/src/features/voucher-check/utils/voucherCheckChat.utils.ts create mode 100644 frontend/src/features/voucher-check/views/VoucherCheckChatRedirect.vue create mode 100644 frontend/src/shared/components/UserPickerDialog.vue create mode 100644 frontend/src/shared/types/userPicker.types.ts create mode 100644 frontend/src/shared/utils/userPicker.utils.test.ts create mode 100644 frontend/src/shared/utils/userPicker.utils.ts diff --git a/backend/app/api/workspace/voucher_check.py b/backend/app/api/workspace/voucher_check.py index 6cd20461..799723a8 100644 --- a/backend/app/api/workspace/voucher_check.py +++ b/backend/app/api/workspace/voucher_check.py @@ -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) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 02f71a17..43281a72 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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', diff --git a/backend/app/models/voucher_check.py b/backend/app/models/voucher_check.py index 01a3b757..57eeac8f 100644 --- a/backend/app/models/voucher_check.py +++ b/backend/app/models/voucher_check.py @@ -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"), diff --git a/backend/app/services/agent_registry/catalog_bindings.py b/backend/app/services/agent_registry/catalog_bindings.py index dd5a4eab..116d8763 100644 --- a/backend/app/services/agent_registry/catalog_bindings.py +++ b/backend/app/services/agent_registry/catalog_bindings.py @@ -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', } diff --git a/backend/app/services/agent_registry/data/catalog_manifest.yaml b/backend/app/services/agent_registry/data/catalog_manifest.yaml index 42fac489..73372cc0 100644 --- a/backend/app/services/agent_registry/data/catalog_manifest.yaml +++ b/backend/app/services/agent_registry/data/catalog_manifest.yaml @@ -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 diff --git a/backend/app/services/agent_registry/handlers/bootstrap.py b/backend/app/services/agent_registry/handlers/bootstrap.py index 45bccdf6..2f2127a8 100644 --- a/backend/app/services/agent_registry/handlers/bootstrap.py +++ b/backend/app/services/agent_registry/handlers/bootstrap.py @@ -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())) diff --git a/backend/app/services/agent_registry/handlers/voucher_check.py b/backend/app/services/agent_registry/handlers/voucher_check.py new file mode 100644 index 00000000..c63503c3 --- /dev/null +++ b/backend/app/services/agent_registry/handlers/voucher_check.py @@ -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 diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index 8bee2e30..184ebae1 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -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, }, diff --git a/backend/app/services/voucher_check/engine_persistence.py b/backend/app/services/voucher_check/engine_persistence.py index 2cd6b1e0..e582f3b1 100644 --- a/backend/app/services/voucher_check/engine_persistence.py +++ b/backend/app/services/voucher_check/engine_persistence.py @@ -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 diff --git a/backend/app/services/voucher_check/notification.py b/backend/app/services/voucher_check/notification.py index 7764991d..79d86185 100644 --- a/backend/app/services/voucher_check/notification.py +++ b/backend/app/services/voucher_check/notification.py @@ -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( diff --git a/backend/app/services/voucher_check/notify_config_service.py b/backend/app/services/voucher_check/notify_config_service.py new file mode 100644 index 00000000..92f55cc3 --- /dev/null +++ b/backend/app/services/voucher_check/notify_config_service.py @@ -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) diff --git a/backend/app/services/voucher_check/runner.py b/backend/app/services/voucher_check/runner.py index 58e5aa14..4726b321 100644 --- a/backend/app/services/voucher_check/runner.py +++ b/backend/app/services/voucher_check/runner.py @@ -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, diff --git a/backend/migrations/versions/vc5f6a7b8c9d_seed_voucher_check_chat_agent.py b/backend/migrations/versions/vc5f6a7b8c9d_seed_voucher_check_chat_agent.py new file mode 100644 index 00000000..ba176094 --- /dev/null +++ b/backend/migrations/versions/vc5f6a7b8c9d_seed_voucher_check_chat_agent.py @@ -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 diff --git a/backend/migrations/versions/vc6a7b8c9d0e_add_voucher_check_notify_configs.py b/backend/migrations/versions/vc6a7b8c9d0e_add_voucher_check_notify_configs.py new file mode 100644 index 00000000..e506a017 --- /dev/null +++ b/backend/migrations/versions/vc6a7b8c9d0e_add_voucher_check_notify_configs.py @@ -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") diff --git a/backend/tests/test_agent_registry_catalog.py b/backend/tests/test_agent_registry_catalog.py index 9eacce11..8e309781 100644 --- a/backend/tests/test_agent_registry_catalog.py +++ b/backend/tests/test_agent_registry_catalog.py @@ -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(): diff --git a/backend/tests/test_agent_registry_voucher_check.py b/backend/tests/test_agent_registry_voucher_check.py new file mode 100644 index 00000000..1c514cde --- /dev/null +++ b/backend/tests/test_agent_registry_voucher_check.py @@ -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 diff --git a/backend/tests/test_voucher_check_permissions.py b/backend/tests/test_voucher_check_permissions.py new file mode 100644 index 00000000..d9003217 --- /dev/null +++ b/backend/tests/test_voucher_check_permissions.py @@ -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' diff --git a/backend/tests/voucher_check/test_notify_config.py b/backend/tests/voucher_check/test_notify_config.py new file mode 100644 index 00000000..4482b1f4 --- /dev/null +++ b/backend/tests/voucher_check/test_notify_config.py @@ -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 diff --git a/backend/tests/voucher_check/test_workspace_latest_run.py b/backend/tests/voucher_check/test_workspace_latest_run.py index de950445..fbd981b2 100644 --- a/backend/tests/voucher_check/test_workspace_latest_run.py +++ b/backend/tests/voucher_check/test_workspace_latest_run.py @@ -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()) diff --git a/backend/tests/voucher_check/test_workspace_notifications.py b/backend/tests/voucher_check/test_workspace_notifications.py index 14746518..99571701 100644 --- a/backend/tests/voucher_check/test_workspace_notifications.py +++ b/backend/tests/voucher_check/test_workspace_notifications.py @@ -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()) diff --git a/backend/tests/voucher_check/test_workspace_period_filter.py b/backend/tests/voucher_check/test_workspace_period_filter.py index 84a163b1..df0ada45 100644 --- a/backend/tests/voucher_check/test_workspace_period_filter.py +++ b/backend/tests/voucher_check/test_workspace_period_filter.py @@ -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()) diff --git a/docs/demand.md b/docs/demand.md index 99082979..875dec05 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -219,14 +219,14 @@ ### 3.x 立账凭证检核补充需求 -- AI 工作台中的“立账凭证”入口及页面仅对 `role=admin` 用户开放;普通用户不展示入口,直接访问地址时返回工作台应用页。 +- AI 工作台中的“立账凭证”入口已迁入 Chat:作为 builtin Agent(`agent_code=voucher_check`),主区以 Tab 嵌入检核任务与企微发送记录;平台管理员另有「通知配置」按文件类型用公共选人弹窗(按部门筛选)选人。点击批次在当前 Tab 内下钻明细。第一期隐藏对话输入框与历史会话,不接 Dify。旧地址 `/workspace/accounting-voucher-check*` 重定向到对应 Chat 深链。平台 admin 或被授予该 Agent 的用户可访问;强制重检上月与通知配置仅管理员可见。 - **核心目标**:按业务方 Profile **每周二**增量检核**上一个自然月**;销售 invoice 清单来自 HXJM `oma_file`(`oma10`/`oma02`,已确认、未作废、状况码 1、帐款类别 11/12/13);从 ERP/OA/文档库获取必检资料,按 `invoice` 归入「所有归档」,输出缺件汇总 Excel。 - **销售一期资料**:PO 订单、报关资料、销货放行申请单、发票、报关单、提单。获取后先写入文档库 `销售开票附件/{年}/{月}/{类型目录}/`,再归档到同月 `所有归档/{invoice号}/`。 - **OA**:一期仅模拟页面打销货放行单;后期对接新 OA 接口,规则不变。 - **文档库**:复用现有文档管理系统(全公司一个库,LibraryID 与合同相同);销售开票附件是该库下独立文件夹,只单独配根 FolderID,不得复用合同根目录。 -- **通知**:每个检核批次一条企业微信汇总;接收人在界面从系统用户多选,未配置则不发。 +- **通知**:缺件按文件类型接收人拆成每人一封;平台管理员在 Chat「通知配置」维护。排程选人只用于技术失败告警。未配置则不发。 - **判定边界**:只做文件获取、命名/关联校验和归档结果;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 -- **实现状态**:周二 05:00 独立排程生成 PO PDF 并上传到「PO订单」;周二 06:00 检核周任务按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总。ERP 取数见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)(HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`);OA 打印仍待接线。不做 Chatflow;查询走工作台 API。 +- **实现状态**:周二 05:00 独立排程生成 PO PDF 并上传到「PO订单」;周二 06:00 检核周任务按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总。ERP 取数见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)(HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`);OA 打印仍待接线。不做 Chatflow;查询走 `/api/workspace/accounting-voucher-check/*`,入口在 Chat Agent。 - 权威需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。 ### 3.x 货代发货通知库存源补充需求 diff --git a/docs/features/README.md b/docs/features/README.md index 1cc59e83..9b848dd1 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -9,7 +9,7 @@ | [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) | | [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [原型](shipping-notice/shipping_notice_agent_prototype.md) | | [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) | -| [accounting-voucher-check](accounting-voucher-check/README.md) | 立账凭证资料检核 | [需求说明](accounting-voucher-check/demand.md) · [技术设计](accounting-voucher-check/technical-design.md) · [原型](accounting-voucher-check/accounting-voucher-check-prototype.html) | +| [accounting-voucher-check](accounting-voucher-check/README.md) | 立账凭证资料检核(Chat Agent) | [需求说明](accounting-voucher-check/demand.md) · [技术设计](accounting-voucher-check/technical-design.md) · [原型](accounting-voucher-check/accounting-voucher-check-prototype.html) | | [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) · [履历挂载命令](fixed-assets/history-share-mount.md) | | [procurement-contract](procurement-contract/README.md) | 采购合同审查 Agent(模板比对 / 单份审核) | [用户操作手册](procurement-contract/用户操作手册.md) · [demand.md](procurement-contract/demand.md) · [comprehensive-review-technical.md](procurement-contract/comprehensive-review-technical.md) · [原型](procurement-contract/procurement-contract-review-prototype.html) | | [contract-payment-plan](contract-payment-plan/) | 合同付款计划 / 预警 Agent | [方案 V3](contract-payment-plan/contract-payment-warning-proposal-v3.md) · [工作台原型](contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html) · [Chat Agent 原型](contract-payment-plan/contract-payment-chat-agent-prototype.html) | diff --git a/docs/features/accounting-voucher-check/README.md b/docs/features/accounting-voucher-check/README.md index 853adf28..9d60ddb1 100644 --- a/docs/features/accounting-voucher-check/README.md +++ b/docs/features/accounting-voucher-check/README.md @@ -5,7 +5,7 @@ | **需求说明** | 产品、业务、测试 | [demand.md](demand.md) | | **技术设计** | 研发 | [technical-design.md](technical-design.md) | | **技术规格** | 研发、测试 | [technical.md](technical.md) | -| **原型** | 产品、业务、测试 | [accounting-voucher-check-prototype.html](accounting-voucher-check-prototype.html) · [说明](accounting-voucher-check-prototype.md) · [最近一次检核卡片](accounting-voucher-check-latest-run-prototype.html) | +| **原型** | 产品、业务、测试 | [accounting-voucher-check-prototype.html](accounting-voucher-check-prototype.html) · [说明](accounting-voucher-check-prototype.md) · [最近一次检核卡片](accounting-voucher-check-latest-run-prototype.html) · [终态布局效果图](accounting-voucher-check-latest-run-layout-options.html) · [公共选人弹窗](user-picker-dialog-prototype.html)(已落地 `frontend/src/shared/components/UserPickerDialog.vue`) | | **部署验收清单** | 运维、研发 | [ops-checklist.md](ops-checklist.md) | | **PO 制式 PDF 样张 JSON** | 研发 | [po-order-sample.json](po-order-sample.json) · 入口 `python -m app.services.voucher_check.po_order --out-dir DIR --json FILE` | | **ERP 采购单取数表字段** | 研发 | [technical-design.md §3.4](technical-design.md)(发票 HXJM、采购单 TGHX;`TRIM(oma99)=TRIM(pmm99)`;独立抓取已接线) | @@ -13,6 +13,6 @@ **定位**:以业务方 Profile 驱动的批量资料检核;**每周二**增量处理上一个自然月。销售开票附件先落入文档库类型目录,再按 `invoice` 归入「所有归档」。 **要解决的问题**:不同业务方从 ERP、OA、固定目录等来源获取不同必检资料,统一检核、归档、汇总缺件并通知。 **检核内容**:只做必检文件的获取、存在性和归档结果;不做文件内容解析或金额、供应商等字段一致性核对。 -**结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数;企业微信每批一条汇总通知,完整明细以 Excel 与执行记录为准。 +**结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数;企业微信按文件类型接收人拆成每人一封,完整明细以 Excel 与执行记录为准。 -**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。PO 制式 PDF 由周二 05:00 独立排程生成并上传;06:00 检核只扫描目录。OA 销货放行打印仍待接线。 +**状态**:销售一期需求以 [demand.md](demand.md) 为准;查询入口为 Chat builtin Agent「立账凭证」。采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。PO 制式 PDF 由周二 05:00 独立排程生成并上传;06:00 检核只扫描目录。OA 销货放行打印仍待接线。 diff --git a/docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html b/docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html index 3233554f..04571936 100644 --- a/docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html +++ b/docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html @@ -3,7 +3,7 @@ docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html 用途:立账凭证工作台「最近一次检核」卡片原型(Tab 下方、筛选栏上方)。 依赖:浏览器原生 HTML/CSS/JS,无需构建。 - 逻辑:默认展示最近一批终态;点「强制重检上月」切入执行中进度;原型预览可切换完成/执行中/失败。 + 逻辑:终态用矮指标格;点「强制重检上月」切入执行中进度。原型预览可切换完成/执行中/失败。 --> @@ -106,6 +106,19 @@ padding: 14px 16px 12px; background: var(--brand-soft); } + .latest.compact .latest-hd { + align-items: flex-start; + padding: 10px 16px 8px; + background: transparent; + } + .latest.compact .latest-bd { padding: 0 16px 12px; } + .latest.compact .bar, + .latest.compact .bar-row, + .latest.compact:not(.fail) .step-line { display: none; } + .latest.compact .metrics { margin-top: 0; } + .latest.compact .metric { padding: 8px 10px; } + .latest.compact .metric b { font-size: 18px; } + .latest.compact .step-line { margin-top: 8px; } .latest-hd h2 { margin: 0; font-size: 15px; } .latest-meta { margin: 4px 0 0; color: var(--muted); font-size: 12px; } .latest-meta span { margin-right: 12px; } @@ -170,7 +183,7 @@
- 这是原型,不是工作台代码。最近一次检核放在 Tab 下方、筛选栏上方:它是整页状态,不跟着年/月过滤。强制重检放在卡片上,点击后进度就在本卡更新。 + 这是原型,不是工作台代码。最近一次检核放在 Tab 下方、筛选栏上方:它是整页状态,不跟着年/月过滤。终态用矮指标格,排队/执行中才展开进度条。强制重检放在卡片上,点击后进度就在本卡更新。
预览状态: @@ -322,11 +335,16 @@ function render(data) { const warn = data.metrics[2] > 0 || data.metrics[3] > 0; const labels = ["invoice总数", "已归档文件", "缺件文件数", "缺件 invoice 数"]; + const isMonitor = data.statusClass === "run"; + latestEl.className = "latest" + (isMonitor ? "" : " compact") + (data.statusClass === "fail" ? " fail" : ""); latestEl.innerHTML = '
' + "

" + data.title + "

" + '

批次 ' + data.runNo + "期间 " + data.period + "" + data.mode + "

" + '
' + + (data.percent === 100 && data.statusClass !== "fail" + ? '' + : "") + '' + data.status + "" + '" + "
" + @@ -341,9 +359,6 @@ }).join("") + "
" + '

' + data.step + (data.hint ? "" + data.hint + "" : "") + "

" + - (data.percent === 100 && data.statusClass !== "fail" - ? '
' - : "") + "
"; } diff --git a/docs/features/accounting-voucher-check/demand.md b/docs/features/accounting-voucher-check/demand.md index 20177d58..3722c92b 100644 --- a/docs/features/accounting-voucher-check/demand.md +++ b/docs/features/accounting-voucher-check/demand.md @@ -1,7 +1,7 @@ # 立账凭证资料检核需求说明 -> 文档版本:v1.14 -> 更新时间:2026-09-14 +> 文档版本:v1.15 +> 更新时间:2026-09-16 > 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置。PO 制式 PDF 由独立周批(周二 05:00)生成并上传;检核周批(周二 06:00)只扫描目录。ERP 取数 HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`。 > > 本文是本期需求权威。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘存在性扫描、Chatflow Tool 与一票一状态表已移除,不得再按该口径扩展。 @@ -30,7 +30,7 @@ | 执行频率 | **两段周批(Asia/Shanghai)**:周二 **05:00** 生成并上传 PO 订单 PDF;周二 **06:00** 检核上月附件。 | | 检核期间 | 执行日的上一个自然月;例如 2026-08-18 执行,检核 2026-07 | | 执行方式 | 增量执行:已成功归档且来源文件/规则未变化的 `invoice + 文件规则` 可跳过;新增、缺件、规则变更或来源变更的记录重新检核。归档目录已有同名文件时按「同名跳过」不覆盖 | -| 强制重检 | 支持对上一个自然月全量重检;不跳过任何主体。工作台「强制重检上月」入队 `force_all` | +| 强制重检 | 支持对上一个自然月全量重检;不跳过任何主体。Chat「强制重检上月」入队 `force_all`(仅 admin) | | 归档单位 | 文档库「所有归档」下以 `invoice` 为子目录;同一 `invoice` 的已获取文件集中存放。获取后先落入当月类型目录 | ### 3.2 Profile 驱动扩展 @@ -44,6 +44,8 @@ 新增业务方时优先新增或调整 Profile;只有新增外部系统或获取协议时才开发新的来源 Adapter。 +查询入口在 Chat builtin Agent「立账凭证」(`agent_code=voucher_check`)。平台 admin 默认可访问;普通用户需在用户管理授予该 Agent。第一期不接 Dify、隐藏对话输入与历史。旧 `/workspace/accounting-voucher-check*` 重定向到 Chat;点击批次在当前 Tab 内下钻明细,不新开独立工作台页。强制重检与通知配置仅 admin。 + 销售一期主体清单来自 HXJM 套账只读查询 `oma_file`:`oma10` 为发票号码,须为至少 6 位字母或数字(如 `6975101806`、`EWZZ26090002`;排除 NULL、空串、`0`、中文备注),`oma02` 为帐款日期(DATE),且 `omaconf='Y'`(已确认)、`omavoid='N'`(未作废)、`oma64='1'`(状况码)、`oma00` 为 `11`/`12`/`13` 之一(帐款类别)。检核期间仍按上表取**上一个自然月**(例如周二跑批则检核上个月),不沿用旧实现的「当前月」。 ### 3.3 结果状态 @@ -59,11 +61,11 @@ 检核任务列表是用户查看历史批次和进入详情的主入口。默认展示**上一个自然月**的批次,支持把月份改为「全部」查看该年全部批次,再进入对应的执行明细、企业微信通知附件 Excel 和通知记录。 -「最近一次检核」卡片放在 Tab 下方、筛选栏上方,只出现在「检核任务」Tab:展示**最近一批**(按执行时间,不跟年/月/状态筛选)的批次号、期间、模式、状态、进度、开始/完成时间、当前步骤,以及 invoice 总数 / 已归档 / 缺件文件 / 缺件 invoice。强制重检上月(仅管理员)放在这张卡片上,入队后进度在本卡更新。 +「最近一次检核」卡片放在 Tab 下方、筛选栏上方,只出现在「检核任务」Tab:展示**最近一批**(按执行时间,不跟年/月/状态筛选)。终态用矮指标格(批次号、期间、模式、状态、四格数字、强制重检),不展示进度条和完成说明;排队/执行中才展开进度条、开始/完成时间和当前步骤。强制重检上月(仅管理员)放在这张卡片上,入队后进度在本卡更新。 | 区域 | 内容 | | ------------ | ------------------------------------------------------------------------------------------------- | -| 最近一次检核 | 最近一批进度与四指标;强制重检上月(全量 `force_all`,期间固定上一个自然月,不用筛选栏期间) | +| 最近一次检核 | 终态矮指标格(批次/状态/四格数字,无进度条);执行中展开进度;强制重检上月(全量 `force_all`,期间固定上一个自然月,不用筛选栏期间) | | 筛选条件 | 资料所属期间(年必选、月可选「全部」;进页默认上一个自然月)、任务状态 | | 任务列表字段 | 批次号、资料所属期间、执行时间、主体总数、缺件文件数、缺件 `invoice` 数、状态、失败原因 | | 状态 | 排队中、执行中、缺件、完整、技术失败 | @@ -71,7 +73,7 @@ ### 3.5 企业微信发送记录 -工作台同一入口用 Tab 切换「检核任务」与「企微发送记录」。发送记录以 `voucher_check_notifications` 为真相源,每批一条缺件汇总(已发送 / 失败 / 无缺件未发送 / 未配置接收人 / 通知关闭)。 +Chat 同一入口用 Tab 切换「检核任务」与「企微发送记录」。发送记录以 `voucher_check_notifications` 为真相源,每批一条审计(已发送 / 失败 / 无缺件未发送 / 未配置接收人 / 通知关闭)。企微侧按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型。旧工作台地址重定向到该 Agent。 | 区域 | 内容 | | -------- | --------------------------------------------------------------------------------------------- | @@ -79,6 +81,18 @@ | 列表字段 | 批次号、资料所属期间、invoice 总数、invoice 缺件数、缺件文件数、发送状态、未发送原因、接收人、发送时间、Excel | | 操作 | 有附件时可下载该批 Excel;查看详情进入对应批次明细 | +### 3.6 通知配置(仅平台管理员) + +Chat 第三 Tab「通知配置」按销售一期六类必检文件分行选人。配置写入 `voucher_check_notify_configs`,与 Profile 版本解耦,换人不必发版 `file_rules`。仅 `role=admin` 可见、可改;被授予 Agent 的普通用户看不到该 Tab。 + +| 项目 | 规则 | +| -------- | ---- | +| 行 | PO订单、报关资料、销货放行申请单、发票、报关单、提单,与 Profile `file_rules` 一致 | +| 选人 | 行内展示已选标签,点「选择」打开公共选人弹窗(按部门筛选、搜索姓名/工号、全选当前列表);未绑定企微 userid 的人可保存,发送时跳过 | +| 发送 | 同一人管多类时合并为一封;只列出该人负责且本批 `missing_file_count>0` 的类型 | +| 总开关 | 排程 `notify_missing_enabled` 与「启用通知」仍可关掉整批缺件通知 | +| 失败告警 | 技术失败仍走排程「选择通知人员」,不走本页 | + ## 4. 销售一期文件规则 销售开票附件落在文档管理系统(文档库)中。不论从 ERP 打印、OA 打印还是固定目录扫描,**获取成功后都先写入当月类型存放目录**,再按发票号归档到「所有归档」。 @@ -230,11 +244,11 @@ flowchart TD | 项目 | 规则 | | -------- | ------------------------------------------------------------------------------------------------------- | | 触发 | 本批存在必检文件缺件 | -| 聚合 | 一个检核批次发送一条汇总通知;不在企业微信中逐票展开缺失明细 | -| 内容 | 业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数、主要缺失文件类型、Excel 下载入口 | +| 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 | +| 内容 | 业务方、检核月份、批次号,以及该人负责且本批缺失的文件类型(缺件文件数 / 缺件 invoice 数);完整明细以 Excel 为准 | | 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 | -| 接收人 | 业务可暂不指定具体人;**必须提供配置界面**,从 HXOPS 系统用户中多选(须已绑定企微 userid)。可复用管理后台排程任务的通知人选择器。未配置任何接收人时不发送空通知,并在 Excel 和执行记录标记未发送原因 | -| 技术失败 | 不作为缺件通知;按技术告警规则单独处理 | +| 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 | +| 技术失败 | 不作为缺件通知;按排程通知人单独告警 | ## 7. 企业微信通知附件 Excel @@ -255,9 +269,9 @@ flowchart TD 1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。 2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。 3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。 -4. 企业微信每批仅发送一条缺件汇总通知,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。 +4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。 5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。 -6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、企微选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。 +6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。 7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。 ## 9. 待补充事项 @@ -268,7 +282,7 @@ flowchart TD | ERP 反查 PO 并打印 | **打印、上传与取数已接线(周二 05:00 独立排程 `accounting-voucher-po-print`,06:00 检核不调用)**。采购单在 **TGHX**。关联 **已确认**:`TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)`。`oma99` 为空时才走 `oma16` 备用。到货日 `pmn34`。详见 [technical-design.md §3.4](technical-design.md) | 制表者;卤素/环保是否拆列。原始编号优先 `ta_ima11` 否则 `pmn24`(业务仍略含糊)。`oma99` 为空的备用路径尚未用空值票验证 | | OA 销货放行单 | **已确认方向**:一期只做模拟页面;后期对接新 OA 接口 | 模拟登录、分页、打印落盘细节 | | 文档管理系统 | **已确认**:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、上传 `Attachment/Upload` + `Item/CreateFiles`、复制 `Item/Copy`;同名跳过 | 无 | -| 企微接收人 | **已确认产品**:界面从系统用户多选;人可以后配 | 业务最终勾选哪些人 | +| 企微接收人 | **已确认产品**:Chat「通知配置」按文件类型从系统用户多选;仅平台管理员可改 | 业务最终勾选哪些人 | | 周任务 | **已确认**:周二 05:00 生成 PO PDF;周二 06:00 检核(上海时区) | 无 | | 销售类型目录名 | **已确认固定**:`PO订单`、`报关资料`、`销货单`、`发票`、`报关单`、`提单` | 无 | | 重复文件策略 | **已确认**:同名跳过 | 目标 `所有归档/{invoice}/` 或类型目录「PO订单」已有相同文件名则不覆盖 | diff --git a/docs/features/accounting-voucher-check/ops-checklist.md b/docs/features/accounting-voucher-check/ops-checklist.md index d906b65d..36a138eb 100644 --- a/docs/features/accounting-voucher-check/ops-checklist.md +++ b/docs/features/accounting-voucher-check/ops-checklist.md @@ -15,10 +15,10 @@ | Cron | 检核 `0 6 * * 2`;PO 生成 `0 5 * * 2`(Asia/Shanghai,周二,生成早于检核) | | 检核期间 | 上一个自然月 | | 销售类型目录 | PO订单、报关资料、销货单、发票、报关单、提单 | -| 引擎表 | `voucher_check_profiles` / `runs` / `subjects` / `file_results` / `notifications` | +| 引擎表 | `voucher_check_profiles` / `runs` / `subjects` / `file_results` / `notifications` / `notify_configs` | | 已删除旧表 | `voucher_check_invoice_states`、`voucher_check_run_items`(revision `vc2b3c4d5e6f`) | | 旧 job_params 清洗 | revision `vc3d4e5f6a7b`:去掉共享盘字段;启动种子同样幂等剥离 | -| 工作台入口 | `/workspace/accounting-voucher-check` | +| 工作台入口 | 旧 `/workspace/accounting-voucher-check` 重定向到 Chat Agent `voucher_check` | --- @@ -32,7 +32,7 @@ cd backend flask db upgrade ``` -- [ ] 确认引擎表存在:`voucher_check_profiles`、`voucher_check_runs`、`voucher_check_subjects`、`voucher_check_file_results`、`voucher_check_notifications` +- [ ] 确认引擎表存在:`voucher_check_profiles`、`voucher_check_runs`、`voucher_check_subjects`、`voucher_check_file_results`、`voucher_check_notifications`、`voucher_check_notify_configs` - [ ] 确认旧表已删除:`voucher_check_invoice_states`、`voucher_check_run_items` - [ ] 确认排程 `job_params` 仅含 `profile_code` / `scope_code` / 两个通知开关(无 `directory_template` / `required_files`) - [ ] 确认种子排程存在(有用户时): @@ -106,7 +106,8 @@ GRANT SELECT ON TGHX.zo_file TO ; - [ ] 二者 `enabled=true`,时区 `Asia/Shanghai` - [ ] PO 生成 Cron `0 5 * * 2`;检核 Cron `0 6 * * 2`(生成必须早于检核) - [ ] `kb_sync_enabled=false`(本域不需要进知识库) -- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户;未配置则不发 +- [ ] `notify_enabled=true`;排程选人只用于技术失败告警 +- [ ] Chat「通知配置」已按文件类型填已绑定企微的用户;未配置缺件类型则不发该类 - [ ] 两任务 `job_params.profile_code=sales`,`scope_code=HXJM` --- @@ -128,11 +129,12 @@ GRANT SELECT ON TGHX.zo_file TO ; ### 4.3 工作台记录页 -- [ ] 打开 `/workspace/accounting-voucher-check` +- [ ] Chat Agent「立账凭证」打开后有「检核任务 / 企微发送记录」Tab;管理员另有「通知配置」;旧 `/workspace/accounting-voucher-check` 会重定向 - [ ] 「检核任务」Tab 下方有「最近一次检核」卡片(不跟年/月/状态筛选);排队/执行中进度会更新 - [ ] 「强制重检上月」在卡片上,仅管理员可见;确认后本卡切到排队/执行中 - [ ] 「检核任务」可按年/月/状态筛选(进页默认上月,月份「全部」看该年),分页可用 - [ ] 「企微发送记录」可按年/月/发送状态筛选,能看到接收人、未发送原因与 Excel 下载入口 +- [ ] 「通知配置」仅管理员可见;保存后按类型拆信,每人只看到自己负责的缺件类型 - [ ] 「查看详情」进入 `/workspace/accounting-voucher-check/runs/:runId`(`runId` 为 ScheduleRun.id) ### 4.4 文档库 / ERP 故障 diff --git a/docs/features/accounting-voucher-check/technical-design.md b/docs/features/accounting-voucher-check/technical-design.md index 4ffb49ce..a2613761 100644 --- a/docs/features/accounting-voucher-check/technical-design.md +++ b/docs/features/accounting-voucher-check/technical-design.md @@ -291,7 +291,8 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 | `voucher_check_runs` | 一次执行批次 | `run_no`、`profile_snapshot`、`period_month`、模式、统计快照 | | `voucher_check_subjects` | 批次中的 `invoice` | `run_id`、`invoice`、主体来源字段、主体指纹 | | `voucher_check_file_results` | `invoice + 文件规则 + 文件实例` | 文件规则、期望名、来源、临时/归档路径、状态、缺件/错误原因、指纹 | -| `voucher_check_notifications` | 一次批次通知 | `run_id`、汇总统计、主要缺失文件类型、Excel 文件标识/下载入口、接收人、发送状态、失败原因 | +| `voucher_check_notifications` | 一次批次通知审计 | `run_id`、汇总统计、按人分信摘要、Excel 文件标识/下载入口、实际发出的接收人、发送状态、失败原因 | +| `voucher_check_notify_configs` | 按业务方保存文件类型接收人 | `profile_code`、`recipients_json`(rule_code → user_id[])、`updated_by` | `voucher_check_file_results` 是缺件统计和 Excel 明细的真相源;不得仅保存 `invoice` 级结论,否则无法正确统计同一 `invoice` 的多个缺件。 @@ -317,17 +318,17 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 ### 6.2 通知聚合 -通知以 `run_id` 聚合:一个检核批次仅生成一条企业微信汇总消息。接收人由任务配置界面从系统用户多选(须已绑定企微);未配置则不发送并记录原因。技术失败进入独立运维告警,不混入缺件通知。 +缺件通知按文件类型接收人拆信:同一人管多类时合并为一封,正文只含该人负责且本批缺失的类型。审计仍以 `run_id` 聚合为一条 `voucher_check_notifications`。接收人由 Chat「通知配置」(仅平台管理员)维护,存在 `voucher_check_notify_configs`,不写进 Profile。未配置则不发送并记录原因。排程「启用通知」与 `notify_missing_enabled` 为总开关;排程选人只用于技术失败告警,不混入缺件通知。 ### 6.3 检核任务列表 -检核任务列表以 `voucher_check_runs` 的批次统计快照为数据源,不在列表查询时重新汇总单文件结果。`period` 支持 `YYYY`(该自然年)或 `YYYY-MM`(该自然月),并可按 `profile_code` 和批次状态筛选,按执行时间倒序分页。工作台进页默认上一个自然月;月份选「全部」时传 `YYYY`。建批前失败的 `ScheduleRun` 使用同一期间口径。企微发送记录列表共用该 `period` 参数。 +检核任务列表以 `voucher_check_runs` 的批次统计快照为数据源,不在列表查询时重新汇总单文件结果。`period` 支持 `YYYY`(该自然年)或 `YYYY-MM`(该自然月),并可按 `profile_code` 和批次状态筛选,按执行时间倒序分页。工作台进页默认上一个自然月;月份选「全部」时传 `YYYY`。建批前失败的 `ScheduleRun` 使用同一期间口径。企微发送记录列表共用该 `period` 参数。查询入口已迁入 Chat Agent,旧工作台 URL 重定向到 `/chat/:agentId?view=`。 「最近一次检核」走独立接口 `GET /api/workspace/accounting-voucher-check/runs/latest`:按 `ScheduleRun.id` 倒序取该平台最近一条排程,join 引擎快照与 `response_summary_json.current_step`,**不跟**列表 `period`/`status`。排队中、执行中的排程必须按 `queued`/`running` 返回,不得套用建批前失败的 `technical_failed` 映射。进度百分比由步骤码估算(`scan_dms` 用已处理 invoice / 总数插值),不是精确字节进度。 | 列/操作 | 数据来源或行为 | | --------------------------------------------------- | -------------------------------------------------------------------------- | -| 最近一次检核卡片 | `GET .../runs/latest`;强制重检按钮仅 admin,入队后前端轮询本接口 | +| 最近一次检核卡片 | `GET .../runs/latest`;终态矮指标格,排队/执行中展开进度;强制重检仅 admin,入队后前端轮询本接口 | | 批次号、业务方、资料所属期间、执行时间 | `voucher_check_runs` | | 主体总数、已归档数、缺件文件数、缺件 `invoice` 数 | 批次结束时固化的统计快照;执行中可来自 `response_summary_json.voucher_check` | | 状态 | 列表:`completed`、`missing`、`technical_failed`;卡片另含 `queued`、`running` | @@ -363,7 +364,7 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 ## 9. 实施顺序 -1. **已做**:Profile、文件规则、批次/单文件结果表、上月期间、周二 cron、销售 DMS 只读、directory_scan、缺件聚合、批次企微、工作台任务列表、最近一次检核卡片与企微发送记录。 +1. **已做**:Profile、文件规则、批次/单文件结果表、上月期间、周二 cron、销售 DMS 只读、directory_scan、缺件聚合、按类型接收人拆信、Chat Agent 任务列表 / 企微记录 / 通知配置(admin,公共选人弹窗按部门筛选)、最近一次检核卡片。 2. **已做**:`dms_archive` 建文件夹(`SaveFolder`)+ 复制(`Item/Copy`),重复策略同名跳过;命中文件记 `archived`。 3. **已做**:制式采购单 PDF(`save_po_order_pdf`)及上传到当月「PO订单」目录(`publish_po_order_pdf` / `upload_given`),命名 `{invoice}-{order_no}.pdf`,同名跳过;`erp_po_print.fetch` 与 OA 仍占位,检核 runner 不调用生成或上传。 4. **已做**:ERP PO 取数 + 独立周批 `accounting-voucher-po-print`(周二 05:00,早于检核 06:00)。检核 runner 不要生成或上传 PDF。关联:`TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)`。 @@ -373,9 +374,9 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 - 一次批次中多个 `invoice` 缺件、且单个 `invoice` 缺多个文件时,两个缺件指标均正确。 - Excel 报告以“资料所属期间”筛选,顶部单独展示“执行时间”;每个 `invoice` 一行,动态文件列与 Profile 必检规则一致;所有文件列均为“有”时状态为“完整”。 -- 企业微信每批发送一条汇总通知并提供 Excel 下载入口;完整 `invoice` 明细仅在 Excel 和执行记录中查看。 +- 企业微信按文件类型接收人拆成每人一封,并提供 Excel 下载入口;完整 `invoice` 明细仅在 Excel 和执行记录中查看。 - 每周二任务仅处理上一个自然月;增量、强制重检和跨年期间计算正确。 -- 企微接收人可从系统用户配置;未配置不发空通知。 +- 企微缺件接收人由平台管理员在 Chat「通知配置」按文件类型设置;未配置不发空通知。 - 新增采购或其它业务方无需修改通用检核、汇总、Excel 和通知逻辑。 - Profile 加载后必须生成不可变快照,批次全程使用同一版本。 - `source_type` 必须在 Adapter Registry 注册。 diff --git a/docs/features/accounting-voucher-check/technical.md b/docs/features/accounting-voucher-check/technical.md index acb72bf3..d10c4def 100644 --- a/docs/features/accounting-voucher-check/technical.md +++ b/docs/features/accounting-voucher-check/technical.md @@ -26,7 +26,7 @@ 3. 支持固定目录读取、ERP 查询打印、OA 查询打印、网盘目录读取及后续自定义来源。 4. 支持同一 invoice 下多个订单、多个附件和多个文件实例。 5. 对文件执行获取、命名/关联校验、归档和结果记录。 -6. 缺失文件发送企业微信通知,接收人暂待业务确认。 +6. 缺失文件发送企业微信通知;接收人由平台管理员在 Chat「通知配置」按文件类型维护。 7. 输出一次任务对应的统一 Excel,并保留批次、文件和归档审计记录。 ### 2.2 非目标 @@ -407,10 +407,10 @@ sequenceDiagram ### 9.2 缺件企业微信通知 - 本批存在必检文件缺件时发送企业微信。 -- **一个检核批次只发一条汇总通知**,不在消息正文逐票展开缺失明细。 -- 通知至少包含业务方、检核月份、批次号、主体总数、缺件文件总数、缺件 `invoice` 数、主要缺失文件类型和本批 Excel 下载入口。 -- 完整 `invoice` 与缺失文件清单以企微附件 Excel 和执行记录为准。 -- 接收人、通知模板由 Profile 的 `notification_policy` 管理;未配置接收人时不发送空通知,并在批次日志和 Excel 中保留未发送原因。 +- **审计仍是一个检核批次一条**;企微按文件类型接收人拆成每人一封,正文不逐票展开缺失明细。 +- 每人卡片包含业务方、检核月份、批次号,以及该人负责且本批缺失的文件类型;完整 `invoice` 明细以 Excel 与执行记录为准。 +- 接收人由 Chat「通知配置」维护(`voucher_check_notify_configs`,仅平台管理员可改);未配置接收人时不发送空通知,并在批次审计中保留未发送原因。 +- 排程「启用通知」与 `notify_missing_enabled` 为总开关;排程选人只用于技术失败告警。 - 技术失败使用独立失败告警,不应伪装成业务缺件。 ## 10. API、任务和前端影响 @@ -446,7 +446,7 @@ GET /api/document-check/profiles ### 10.3 前端 -工作台以 `profile_code` 驱动标题、文件类型和结果字段;通用结果表不写死“核价单/采购单”。新增业务方只需要注册 Profile 的展示元数据和四语言文案。 +工作台以 `profile_code` 驱动标题、文件类型和结果字段;通用结果表不写死“核价单/采购单”。新增业务方只需要注册 Profile 的展示元数据和四语言文案。Chat「通知配置」行内只展示已选标签,点「选择」打开公共组件 `UserPickerDialog`(`frontend/src/shared/components`),左侧按 `User.department` 分组;候选人由 notify-config API 提供,弹窗本身不拉用户。 ## 11. 目录与代码迁移建议 @@ -490,7 +490,7 @@ backend/app/domains/document_check/ 1. 先建立 Profile Schema、Adapter 契约和单文件数据模型。 2. 销售文档扫描走 `dms_directory_scan` Adapter(文档库类型目录),不再封装旧共享盘扫描。 3. 将销售 invoice 主体加载和 OA/ERP 获取逻辑分别封装为 Loader/Adapter。 -4. 工作台 API 只读引擎表;已删除 Chatflow Tool 与旧 states 接口。 +4. 工作台 API 只读引擎表,Chat Agent 入口消费同一套接口;已删除 Chatflow Tool 与旧 states 接口。 5. 完成销售回归后增加采购 Profile 和采购专用 Adapter。 6. 已清理只服务旧模型的单票状态、单一共享根配置和重复接口。 @@ -520,7 +520,7 @@ backend/app/domains/document_check/ - 企微附件 Excel 一行一个 `invoice`,动态文件列为「有 / 缺件 / 未检核」;执行记录可另存单文件明细。 - 同一批次多个 `invoice` 缺件、同一 `invoice` 缺多个文件时,缺件文件总数累计、缺件 `invoice` 数去重。 -- 企业微信每批一条汇总通知,提供 Excel 下载入口;接收人未配置时不发送空通知,并记录明确原因。 +- 企业微信按文件类型接收人拆成每人一封,提供 Excel 下载入口;接收人未配置时不发送空通知,并记录明确原因。 - 批次级技术故障不批量伪装成缺件。 ## 13. 待确认事项 @@ -534,5 +534,5 @@ backend/app/domains/document_check/ | ERP PO 查询字段与打印方式 | **打印与取数已接线(周二 05:00 独立排程)**。发票 HXJM、采购单 **TGHX**。关联 `TRIM(oma99)=TRIM(pmm99)`。对照 apmr900。到货日 `pmn34`。检核 runner 不调用 | | OA 登录、报表分页和打印接口 | 一期模拟页面;后期对接新 OA 接口 | | 文档管理系统 | 已确认:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、上传 `Attachment/Upload` + `Item/CreateFiles`、复制 `Item/Copy`;同名跳过 | -| 企业微信通知接收人、模板和频率 | 界面从系统用户多选;每周二;具体人选可后配 | +| 企业微信通知接收人、模板和频率 | Chat「通知配置」按文件类型选人(仅平台管理员);每周二;具体人选可后配 | | Profile 管理方式 | 首期可使用版本化 YAML/JSON,后续评估管理后台配置 | diff --git a/docs/funclist.md b/docs/funclist.md index 119f5695..bfe53a56 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -223,8 +223,8 @@ | 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;OA 销货放行单打印仅占位 | | PO 订单制式 PDF | 已实现(周二 05:00 独立排程) | 排程 `accounting-voucher-po-print`(`SCH-ACCOUNTING-VOUCHER-PO-PRINT`,`0 5 * * 2`)按上月发票从 TGHX 取数并上传到 `销售开票附件/{年}/{月}/PO订单/`;检核 `accounting-voucher-check` 仍为周二 06:00 只扫目录;`erp_po_print.fetch` 不进检核 runner | | 单一共享盘旧检核 | 已移除 | 已删除共享盘扫描、Chatflow Tool、`voucher_check_invoice_states` / `voucher_check_run_items` | -| 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微每批一条汇总 | -| 工作台查询 | 已实现 | 工作台含检核任务与企微发送记录两 Tab;期间为年+月(默认上月,月份可「全部」看该年);Tab 下「最近一次检核」卡片不跟筛选;「强制重检上月」在卡片上(admin);`GET /runs/latest`、`/runs`、`/notifications` | +| 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微按文件类型接收人拆成每人一封,审计仍每批一条 | +| 工作台查询 | 已实现 | 已迁入 Chat Agent「立账凭证」(`agent_code=voucher_check`):Tab 为检核任务、企微发送记录,管理员另有通知配置(按六类文件用公共选人弹窗按部门选人);期间为年+月(默认上月,月份可「全部」看该年);Tab 下「最近一次检核」终态矮指标格、执行中才展开进度,不跟筛选;「强制重检上月」在卡片上(仅 admin);点击批次在当前 Tab 内下钻明细。平台 admin 或被授予该 Agent 的用户可访问;通知配置仅 admin。旧 `/workspace/accounting-voucher-check*` 重定向到 Chat。 | ### 采购合同审查 diff --git a/docs/platform/README.md b/docs/platform/README.md index cf45214b..08cae1fa 100644 --- a/docs/platform/README.md +++ b/docs/platform/README.md @@ -12,3 +12,4 @@ | [progress_contract_platform_prototype.html](progress_contract_platform_prototype.html) | 进度契约平台 HTML 原型 | | [enterprise-integration-center-prototype.md](enterprise-integration-center-prototype.md) | 企业集成中心蓝图(完整愿景,含 HTML 原型) | | [integration-connector-framework-design.md](integration-connector-framework-design.md) | Integration Connector Framework 设计(首期最小可行收敛版) | +| [role-permission-prototype.md](role-permission-prototype.md) | 可配置角色权限包(一期约定);[可点击原型](role-permission-prototype.html) | diff --git a/docs/tec.md b/docs/tec.md index fd5aed2f..46353878 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -214,11 +214,12 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 ### 2.x 立账凭证检核(accounting-voucher-check) -- 前端路由 `/workspace/accounting-voucher-check` 标记 `requiresAdmin`,工作台侧栏按当前用户角色隐藏入口;全局路由守卫负责阻止非管理员直接访问。 +- 前端入口为 Chat builtin Agent `voucher_check`(`task_chat`,第一期不走 completions)。旧路由 `/workspace/accounting-voucher-check*` 重定向到 `/chat/:agentId?view=`;工作台侧栏不再展示该入口。 +- `/api/workspace/accounting-voucher-check/*` 查询校验平台 admin 或 `user_agent_permissions` 中启用的该 Agent。无授权返回 403(`VOUCHER_CHECK.FORBIDDEN`)。`POST /runs` 强制重检与 `GET/PUT /notify-config` 额外要求 `role=admin`(`VOUCHER_CHECK.ADMIN_REQUIRED`)。 - **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `oma_file`(`oma10`/`oma02`,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。 - **销售一期来源**:PO 订单由 HXOPS 按制式采购单生成 PDF 并上传到当月「PO订单」目录。发票在 HXJM,采购单在 **TGHX**(多角);关联已确认 `TRIM(oma99)=TRIM(pmm99)`,见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)。OA 销货放行单一期模拟页面、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。 - **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Attachment/Upload`、`Item/CreateFiles`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。类型目录上传与归档复制均为同名跳过。 -- **通知**:排程/任务界面从系统用户多选企微接收人;未配置不发送。 +- **通知**:缺件按文件类型接收人拆信,配置在 Chat「通知配置」(仅 admin,公共选人弹窗按部门筛选);排程选人只用于技术失败告警。未配置不发送。 - **判定边界**:不读取文件内容、不调用 LLM 判断合格、不回写 ERP。批次级依赖不可用时整批失败,不得把空结果批量判为缺件。 - **当前代码**:周二 05:00 `accounting-voucher-po-print` 按上月 `oma_file` 从 TGHX 取数生成 PO PDF 并上传到「PO订单」;周二 06:00 检核扫描类型目录 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微。`erp_po_print.fetch` / OA 仍为占位,检核 runner 不调用生成。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。 - 详细业务需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md),研发落地设计见 [docs/features/accounting-voucher-check/technical-design.md](features/accounting-voucher-check/technical-design.md)。 diff --git a/frontend/src/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index 90d7d50b..5cb3800c 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -2,12 +2,12 @@ * app/router/routes/workspace.routes.ts * 工作台路由表:/workspace 布局壳 + 各业务子页面懒加载。 * 依赖:vue-router;meta.title 存 i18n key(workspace.*),由 guards 解析为 document.title。 - * 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款旧地址重定向到 Chat Agent。 - * 立账凭证明细为 accounting-voucher-check/runs/:runId。 + * 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款、立账凭证旧地址重定向到 Chat Agent。 */ import type { RouteRecordRaw } from 'vue-router'; const contractPaymentChatRedirect = () => import('@/features/contract-payment/views/ContractPaymentChatRedirect.vue'); +const voucherCheckChatRedirect = () => import('@/features/voucher-check/views/VoucherCheckChatRedirect.vue'); export const workspaceRoutes: RouteRecordRaw[] = [ { @@ -83,14 +83,14 @@ export const workspaceRoutes: RouteRecordRaw[] = [ { path: 'accounting-voucher-check', name: 'workspace-accounting-voucher-check', - component: () => import('@/features/workspace/pages/AccountingVoucherCheckPage.vue'), - meta: { title: 'workspace.nav.accountingVoucherCheck', requiresAdmin: true }, + component: voucherCheckChatRedirect, + meta: { title: 'workspace.nav.accountingVoucherCheck' }, }, { path: 'accounting-voucher-check/runs/:runId', name: 'workspace-accounting-voucher-check-detail', - component: () => import('@/features/workspace/pages/AccountingVoucherCheckDetailPage.vue'), - meta: { title: 'workspace.voucherCheck.detailTitle', requiresAdmin: true }, + component: voucherCheckChatRedirect, + meta: { title: 'workspace.voucherCheck.detailTitle' }, }, { path: 'contract-payment', diff --git a/frontend/src/features/chat/components/ChatMobileHeader.vue b/frontend/src/features/chat/components/ChatMobileHeader.vue index fa25e26b..9e40849d 100644 --- a/frontend/src/features/chat/components/ChatMobileHeader.vue +++ b/frontend/src/features/chat/components/ChatMobileHeader.vue @@ -1,6 +1,6 @@ /** * features/chat/components/ChatMobileHeader.vue - * 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。合同付款预警可隐藏历史入口。 + * 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。作业面 Agent 可隐藏历史入口。 */ + + diff --git a/frontend/src/features/voucher-check/components/VoucherCheckNotifyConfigPanel.vue b/frontend/src/features/voucher-check/components/VoucherCheckNotifyConfigPanel.vue new file mode 100644 index 00000000..b06024c2 --- /dev/null +++ b/frontend/src/features/voucher-check/components/VoucherCheckNotifyConfigPanel.vue @@ -0,0 +1,201 @@ + + + + diff --git a/frontend/src/features/voucher-check/constants.ts b/frontend/src/features/voucher-check/constants.ts new file mode 100644 index 00000000..6600520f --- /dev/null +++ b/frontend/src/features/voucher-check/constants.ts @@ -0,0 +1,10 @@ +/** + * features/voucher-check/constants.ts + * 用途:立账凭证 Chat Tab 与深链约定。 + * 依赖:无。 + * 逻辑:Chat 主区 Tab 与旧工作台重定向共用 view;详情用 runId,可选 runNo 仅作标题展示。 + * notifyConfig 仅管理员可见,解析仍接受该值以便深链打开后由面板做权限回退。 + */ +export const VOUCHER_CHECK_CHAT_VIEWS = ['tasks', 'notifications', 'notifyConfig'] as const; + +export type VoucherCheckChatView = (typeof VOUCHER_CHECK_CHAT_VIEWS)[number]; diff --git a/frontend/src/features/voucher-check/utils/voucherCheckChat.utils.test.ts b/frontend/src/features/voucher-check/utils/voucherCheckChat.utils.test.ts new file mode 100644 index 00000000..39ef60ab --- /dev/null +++ b/frontend/src/features/voucher-check/utils/voucherCheckChat.utils.test.ts @@ -0,0 +1,51 @@ +/** + * features/voucher-check/utils/voucherCheckChat.utils.test.ts + * 用途:锁定立账凭证 Chat 深链 query 的解析与回写规则。 + */ +import { describe, expect, it } from 'vitest'; +import { + buildVoucherCheckChatQuery, + parseVoucherCheckChatQuery, +} from './voucherCheckChat.utils'; + +describe('parseVoucherCheckChatQuery', () => { + it('accepts tasks / notifications / notifyConfig and a positive runId', () => { + expect(parseVoucherCheckChatQuery('notifications', '12', 'VC-202608-001')).toEqual({ + view: 'notifications', + runId: 12, + runNo: 'VC-202608-001', + }); + expect(parseVoucherCheckChatQuery('notifyConfig', null, null)).toEqual({ + view: 'notifyConfig', + runId: null, + runNo: null, + }); + }); + + it('falls back to tasks for unknown view and ignores invalid runId', () => { + expect(parseVoucherCheckChatQuery('unknown', 'abc', ' ')).toEqual({ + view: 'tasks', + runId: null, + runNo: null, + }); + expect(parseVoucherCheckChatQuery(undefined, '0', undefined)).toEqual({ + view: 'tasks', + runId: null, + runNo: null, + }); + }); +}); + +describe('buildVoucherCheckChatQuery', () => { + it('always writes view and omits runId on list pages', () => { + expect(buildVoucherCheckChatQuery('notifications', null)).toEqual({ view: 'notifications' }); + }); + + it('keeps the current tab when drilling into a run', () => { + expect(buildVoucherCheckChatQuery('notifications', 9, 'VC-9')).toEqual({ + view: 'notifications', + runId: '9', + runNo: 'VC-9', + }); + }); +}); diff --git a/frontend/src/features/voucher-check/utils/voucherCheckChat.utils.ts b/frontend/src/features/voucher-check/utils/voucherCheckChat.utils.ts new file mode 100644 index 00000000..4c2cf957 --- /dev/null +++ b/frontend/src/features/voucher-check/utils/voucherCheckChat.utils.ts @@ -0,0 +1,52 @@ +/** + * features/voucher-check/utils/voucherCheckChat.utils.ts + * 用途:解析立账凭证 Chat 的 view / runId / runNo 查询参数。 + * 依赖:voucher-check/constants。 + * 逻辑:旧工作台重定向与 Chat Tab 共用;非法 view 回退检核任务。notifyConfig 为管理员通知配置页。 + */ +import { VOUCHER_CHECK_CHAT_VIEWS, type VoucherCheckChatView } from '../constants'; + +export interface VoucherCheckChatQuery { + view: VoucherCheckChatView; + runId: number | null; + runNo: string | null; +} + +/** + * 把路由 query 归一成立账凭证 Chat 视图。 + * 核心逻辑:只接受 tasks / notifications / notifyConfig;runId 必须是正整数才进入批次明细;runNo 仅展示。 + * @param rawView - 路由 query.view + * @param rawRunId - 路由 query.runId + * @param rawRunNo - 路由 query.runNo + */ +export function parseVoucherCheckChatQuery( + rawView: unknown, + rawRunId: unknown, + rawRunNo: unknown, +): VoucherCheckChatQuery { + const view = VOUCHER_CHECK_CHAT_VIEWS.includes(String(rawView) as VoucherCheckChatView) + ? String(rawView) as VoucherCheckChatView + : 'tasks'; + const parsed = Number(rawRunId); + const runId = Number.isInteger(parsed) && parsed > 0 ? parsed : null; + const runNo = typeof rawRunNo === 'string' && rawRunNo.trim() ? rawRunNo.trim() : null; + return { view, runId, runNo }; +} + +/** + * 把立账凭证视图写回 Chat 路由 query,便于刷新与旧工作台重定向共用同一深链。 + * 核心逻辑:始终带 view;仅在下钻明细时带 runId / runNo,避免空 query 污染地址栏。 + * @param view - 当前 Tab + * @param runId - 明细批次排程 ID;列表态传 null + * @param runNo - 批次号,仅详情标题使用 + */ +export function buildVoucherCheckChatQuery( + view: VoucherCheckChatView, + runId: number | null, + runNo: string | null = null, +): Record { + const query: Record = { view }; + if (runId) query.runId = String(runId); + if (runId && runNo) query.runNo = runNo; + return query; +} diff --git a/frontend/src/features/voucher-check/views/VoucherCheckChatRedirect.vue b/frontend/src/features/voucher-check/views/VoucherCheckChatRedirect.vue new file mode 100644 index 00000000..9c412067 --- /dev/null +++ b/frontend/src/features/voucher-check/views/VoucherCheckChatRedirect.vue @@ -0,0 +1,85 @@ + + + + diff --git a/frontend/src/features/workspace/api/voucherCheck.api.ts b/frontend/src/features/workspace/api/voucherCheck.api.ts index 5cd0056d..6fb59347 100644 --- a/frontend/src/features/workspace/api/voucherCheck.api.ts +++ b/frontend/src/features/workspace/api/voucherCheck.api.ts @@ -1,8 +1,9 @@ /** * features/workspace/api/voucherCheck.api.ts - * 用途:工作台立账凭证检核任务列表、最近一次检核、批次明细、企微发送记录与强制重检 API 客户端。 + * 用途:工作台立账凭证检核任务列表、最近一次检核、批次明细、企微发送记录、通知配置与强制重检 API 客户端。 * 依赖:@/shared/api/client、getAuthHeaders。 - * 逻辑:AccountingVoucherCheckView / DetailView 调用;对应 /api/workspace/accounting-voucher-check/* 与排程 Excel 下载。 + * 逻辑:AccountingVoucherCheckView / DetailView / VoucherCheckNotifyConfigPanel 调用; + * 对应 /api/workspace/accounting-voucher-check/* 与排程 Excel 下载。 */ import { requestJson } from '@/shared/api/client'; import { getAuthHeaders } from '@/shared/utils/auth'; @@ -222,6 +223,60 @@ export async function downloadVoucherCheckExcel(scheduleRunId: number, filename? URL.revokeObjectURL(url); } +export interface VoucherCheckNotifyUser { + id: number; + username: string; + real_name?: string | null; + employee_id?: string | null; + department?: string | null; + wecom_bound: boolean; +} + +export interface VoucherCheckNotifyRule { + code: string; + name: string; + type_folder: string; + user_ids: number[]; +} + +export interface VoucherCheckNotifyConfig { + profile_code: string; + rules: VoucherCheckNotifyRule[]; + users: VoucherCheckNotifyUser[]; + updated_at?: string | null; + updated_by?: number | null; +} + +/** + * 读取按文件类型的企微接收人(仅平台管理员)。 + */ +export function getVoucherCheckNotifyConfig(profileCode?: string) { + const q = new URLSearchParams(); + if (profileCode) q.set('profile_code', profileCode); + const qs = q.toString(); + return requestJson( + `/api/workspace/accounting-voucher-check/notify-config${qs ? `?${qs}` : ''}`, + { headers: getAuthHeaders() }, + ); +} + +/** + * 保存按文件类型的企微接收人(仅平台管理员)。 + */ +export function saveVoucherCheckNotifyConfig(payload: { + profile_code?: string; + recipients: Record; +}) { + return requestJson( + '/api/workspace/accounting-voucher-check/notify-config', + { + method: 'PUT', + headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }, + ); +} + /** * 强制重检上一个自然月(不走增量跳过)。 */ diff --git a/frontend/src/features/workspace/components/WorkspaceSidebar.vue b/frontend/src/features/workspace/components/WorkspaceSidebar.vue index 947710d1..da9145a4 100644 --- a/frontend/src/features/workspace/components/WorkspaceSidebar.vue +++ b/frontend/src/features/workspace/components/WorkspaceSidebar.vue @@ -3,13 +3,13 @@ * features/workspace/components/WorkspaceSidebar.vue * 工作台左侧导航:子路由链接、货代二级菜单、关联服务入口、返回聊天与退出登录。 * 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks。 - * 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐。合同付款已迁入 Chat Agent,不再在此展示。 + * 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐。合同付款、立账凭证已迁入 Chat Agent,不再在此展示。 * 矮屏时中间导航独立滚动,底部返回聊天/退出登录始终留在视口内。 */ import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from 'vue'; import { useRoute } from 'vue-router'; import { - LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen, ClipboardCheck, + LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen, ChevronDown, ChevronRight, ContactRound, Inbox, FileDown, } from 'lucide-vue-next'; import { WORKSPACE_PATHS } from '../constants/routes'; @@ -36,7 +36,6 @@ const primaryLinkItems = [ ] as const; const secondaryLinkItems = [ - { path: WORKSPACE_PATHS.accountingVoucherCheck, labelKey: 'workspace.nav.accountingVoucherCheck', icon: ClipboardCheck, match: ['workspace-accounting-voucher-check', 'workspace-accounting-voucher-check-detail'] }, { path: WORKSPACE_PATHS.feedback, labelKey: 'workspace.nav.feedback', icon: Edit, match: ['workspace-feedback'] }, { path: WORKSPACE_PATHS.updates, labelKey: 'workspace.nav.updates', icon: Megaphone, match: ['workspace-updates'] }, ] as const; diff --git a/frontend/src/features/workspace/constants/routes.ts b/frontend/src/features/workspace/constants/routes.ts index 9f39fb7b..cf86cf67 100644 --- a/frontend/src/features/workspace/constants/routes.ts +++ b/frontend/src/features/workspace/constants/routes.ts @@ -1,7 +1,7 @@ /** * features/workspace/constants/routes.ts * 工作台子路由 path 常量,以及旧 ?view= 查询参数到新 path 的映射。 - * 立账凭证批次明细:accountingVoucherCheckDetail(scheduleRunId)。 + * 立账凭证路径仍保留,供旧书签落到 Chat 重定向页。 * 合同付款路径仍保留,供旧书签落到 Chat 重定向页。 */ export const WORKSPACE_PATHS = { diff --git a/frontend/src/features/workspace/views/AccountingVoucherCheckDetailView.vue b/frontend/src/features/workspace/views/AccountingVoucherCheckDetailView.vue index 00707b7b..ba7546ab 100644 --- a/frontend/src/features/workspace/views/AccountingVoucherCheckDetailView.vue +++ b/frontend/src/features/workspace/views/AccountingVoucherCheckDetailView.vue @@ -3,7 +3,8 @@ * features/workspace/views/AccountingVoucherCheckDetailView.vue * 用途:立账凭证检核批次明细独立页,支持按 invoice 或按文件类型汇总。 * 依赖:voucherCheck.api、PaginationBar、vue-router、vue-i18n、useMessage、voucherCheck.display。 - * 逻辑:路由 /workspace/accounting-voucher-check/runs/:runId;标题下用下划线 Tab 切换汇总维度;状态筛选仅在按 invoice 时出现。 + * 逻辑:独立路由或 Chat 嵌入;标题下用下划线 Tab 切换汇总维度;状态筛选仅在按 invoice 时出现。 + * Chat 嵌入时 runId / runNo 由父级传入,返回列表通过 close 事件。 */ import { computed, onMounted, ref, watch } from 'vue'; import { useRoute, useRouter } from 'vue-router'; @@ -24,6 +25,20 @@ import { voucherCheckStatusLabel, } from '../utils/voucherCheck.display'; +const props = withDefaults(defineProps<{ + embedded?: boolean; + runId?: number; + runNo?: string | null; +}>(), { + embedded: false, + runId: 0, + runNo: null, +}); + +const emit = defineEmits<{ + close: []; +}>(); + const { t } = useI18n(); const msg = useMessage(); const route = useRoute(); @@ -40,12 +55,17 @@ const runNo = ref(''); const viewMode = ref<'invoice' | 'fileType'>('invoice'); const scheduleRunId = computed(() => { + if (props.embedded) { + const id = Number(props.runId); + return Number.isInteger(id) && id > 0 ? id : 0; + } const raw = route.params.runId; const id = Number(Array.isArray(raw) ? raw[0] : raw); return Number.isFinite(id) && id > 0 ? id : 0; }); const titleRunId = computed(() => { + if (props.embedded && props.runNo) return props.runNo; const q = route.query.runNo; if (typeof q === 'string' && q.trim()) return q.trim(); return runNo.value || String(scheduleRunId.value || ''); @@ -111,6 +131,10 @@ function setViewMode(mode: 'invoice' | 'fileType') { * 返回立账凭证检核任务列表。 */ function backToList() { + if (props.embedded) { + emit('close'); + return; + } void router.push(WORKSPACE_PATHS.accountingVoucherCheck); } diff --git a/frontend/src/features/workspace/views/AccountingVoucherCheckView.vue b/frontend/src/features/workspace/views/AccountingVoucherCheckView.vue index 142cc29a..e62476c4 100644 --- a/frontend/src/features/workspace/views/AccountingVoucherCheckView.vue +++ b/frontend/src/features/workspace/views/AccountingVoucherCheckView.vue @@ -1,9 +1,11 @@