feat(invoice-check): 立账凭证检核增加收件人配置并迁移到chat页面
This commit is contained in:
1 parent
18e957545c
commit
7b80b4c395
72 files changed
+2705
-263
No files matched your search
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/api/workspace/voucher_check.py
|
||||
|
||||
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录)。
|
||||
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
|
||||
逻辑:对话与检核任务页共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
|
||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,23 +14,88 @@ from flask import Blueprint, request
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.voucher_check import query_service
|
||||
from app.models import Agent
|
||||
from app.services.voucher_check import notify_config_service, query_service
|
||||
|
||||
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
||||
|
||||
VOUCHER_CHECK_AGENT_CODE = "voucher_check"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
返回当前登录用户。
|
||||
|
||||
Returns:
|
||||
已认证用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_admin():
|
||||
"""工作台强制重检仅管理员可触发,鉴权方式与本蓝图 GET 一致。"""
|
||||
def _user_has_voucher_check_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的立账凭证检核 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
|
||||
Args:
|
||||
user: 已认证用户。
|
||||
|
||||
Returns:
|
||||
已绑定启用中的 voucher_check Agent 时为 True。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=VOUCHER_CHECK_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_voucher_check_access():
|
||||
"""
|
||||
确保当前用户已登录且具备立账凭证检核访问权限。
|
||||
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Returns:
|
||||
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Voucher check agent permission required",
|
||||
code="VOUCHER_CHECK.FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def _require_admin():
|
||||
"""
|
||||
确保当前用户既有立账凭证访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
|
||||
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_voucher_check_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError("Admin privilege required")
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for voucher check jobs",
|
||||
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@@ -39,7 +105,7 @@ def workspace_voucher_runs():
|
||||
分页查看检核任务列表。
|
||||
核心逻辑:委托 query_service.list_runs;period 为 YYYY 或 YYYY-MM,可再按业务方/状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_runs(
|
||||
period=request.args.get("period"),
|
||||
profile_code=request.args.get("profile_code"),
|
||||
@@ -75,7 +141,7 @@ def workspace_voucher_latest_run():
|
||||
读取最近一次立账凭证检核批次(含排队/执行中)。
|
||||
核心逻辑:委托 query_service.get_latest_run;不跟列表 period/status;无批次时 data 为 null。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
return ok(query_service.get_latest_run())
|
||||
|
||||
|
||||
@@ -85,7 +151,7 @@ def workspace_voucher_run_items(run_id: int):
|
||||
分页查看批次明细。
|
||||
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_run_items(
|
||||
run_id=run_id,
|
||||
result=request.args.get("result"),
|
||||
@@ -98,10 +164,10 @@ def workspace_voucher_run_items(run_id: int):
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"])
|
||||
def workspace_voucher_notifications():
|
||||
"""
|
||||
分页查看企微缺件汇总发送记录。
|
||||
分页查看企微缺件通知发送记录。
|
||||
核心逻辑:委托 query_service.list_notifications;period 为 YYYY 或 YYYY-MM,可再按发送状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_notifications(
|
||||
period=request.args.get("period"),
|
||||
send_status=request.args.get("send_status"),
|
||||
@@ -109,3 +175,29 @@ def workspace_voucher_notifications():
|
||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||
)
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
读取按文件类型的企微接收人配置。
|
||||
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
"""
|
||||
_require_admin()
|
||||
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["PUT"])
|
||||
def workspace_voucher_notify_config_put():
|
||||
"""
|
||||
保存按文件类型的企微接收人。
|
||||
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
"""
|
||||
user = _require_admin()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = notify_config_service.save_notify_config(
|
||||
profile_code=payload.get("profile_code") or request.args.get("profile_code"),
|
||||
recipients=payload.get("recipients"),
|
||||
updated_by=getattr(user, "id", None),
|
||||
)
|
||||
return ok(data)
|
||||
@@ -221,6 +221,7 @@ from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgen
|
||||
from app.models.voucher_check import (
|
||||
VoucherCheckFileResult,
|
||||
VoucherCheckNotification,
|
||||
VoucherCheckNotifyConfig,
|
||||
VoucherCheckProfile,
|
||||
VoucherCheckRun,
|
||||
VoucherCheckSubject,
|
||||
@@ -413,6 +414,7 @@ __all__ = [
|
||||
'VoucherCheckSubject',
|
||||
'VoucherCheckFileResult',
|
||||
'VoucherCheckNotification',
|
||||
'VoucherCheckNotifyConfig',
|
||||
'ContractPaymentContract',
|
||||
'ContractPaymentAttachment',
|
||||
'ContractPaymentNode',
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/models/voucher_check.py
|
||||
|
||||
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。
|
||||
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知 / 按类型接收人)。
|
||||
依赖:models.base.Base、schedule_runs。
|
||||
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;工作台与查询服务只读这些表。
|
||||
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;通知配置表供管理员维护文件类型接收人。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +17,7 @@ from sqlalchemy import (
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
@@ -158,13 +159,35 @@ class VoucherCheckFileResult(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class VoucherCheckNotifyConfig(Base):
|
||||
"""按业务方保存文件类型 → 接收人;换人不改 Profile 版本。"""
|
||||
|
||||
__tablename__ = "voucher_check_notify_configs"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
profile_code: Mapped[str] = mapped_column(String(32), nullable=False, unique=True)
|
||||
recipients_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("users.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
default=datetime.utcnow,
|
||||
onupdate=datetime.utcnow,
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
|
||||
class VoucherCheckNotification(Base):
|
||||
"""一个检核批次对应一条企微汇总通知审计。"""
|
||||
"""一个检核批次对应一条企微缺件通知审计(可含多人分信摘要)。"""
|
||||
|
||||
__tablename__ = "voucher_check_notifications"
|
||||
__table_args__ = (Index("ix_voucher_check_notifications_status", "send_status"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
|
||||
|
||||
@@ -13,5 +13,6 @@ RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
|
||||
'shipping_notice': 'shipping_notice',
|
||||
'file_check': 'file_check',
|
||||
'contract_payment': 'contract_payment',
|
||||
'voucher_check': 'voucher_check',
|
||||
'in_transit_transfer': 'in_transit_transfer',
|
||||
}
|
||||
@@ -145,6 +145,21 @@ agent_types:
|
||||
forced_capabilities:
|
||||
file_upload: false
|
||||
handler_config_schema: {}
|
||||
voucher_check:
|
||||
label: 立账凭证
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: builtin
|
||||
models:
|
||||
- VoucherCheckRun
|
||||
- VoucherCheckNotification
|
||||
required_fields: []
|
||||
default_capabilities:
|
||||
streaming: false
|
||||
file_upload: false
|
||||
task_progress: false
|
||||
forced_capabilities:
|
||||
file_upload: false
|
||||
handler_config_schema: {}
|
||||
in_transit_transfer:
|
||||
label: 在途仓自动调拨
|
||||
conversation_mode_default: task_chat
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/agent_registry/handlers/bootstrap.py
|
||||
|
||||
用途:应用启动时加载 HANDLER_REGISTRY。
|
||||
依赖:handlers.shipping_notice、handlers.contract_payment 等领域 handler 模块。
|
||||
依赖:handlers.shipping_notice、handlers.contract_payment、handlers.voucher_check 等领域 handler 模块。
|
||||
逻辑:create_app 在 load_context_adapters 之后调用 load_handlers()。
|
||||
"""
|
||||
|
||||
@@ -33,10 +33,12 @@ def load_handlers() -> None:
|
||||
import app.services.agent_registry.handlers.file_check as file_check_mod
|
||||
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
|
||||
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
|
||||
import app.services.agent_registry.handlers.voucher_check as voucher_check_mod
|
||||
|
||||
importlib.reload(file_check_mod)
|
||||
importlib.reload(shipping_mod)
|
||||
importlib.reload(contract_payment_mod)
|
||||
importlib.reload(voucher_check_mod)
|
||||
importlib.reload(in_transit_transfer_mod)
|
||||
|
||||
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/voucher_check.py
|
||||
|
||||
用途:立账凭证检核 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
|
||||
依赖:agent_registry.handlers.base / registry。
|
||||
逻辑:Chat 主区渲染检核任务 / 企微发送记录 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
|
||||
from app.services.agent_registry.handlers.registry import register_handler
|
||||
|
||||
|
||||
@register_handler('voucher_check')
|
||||
class VoucherCheckHandler(AgentHandler):
|
||||
"""
|
||||
立账凭证检核业务 Handler。
|
||||
|
||||
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入批次摘要。
|
||||
"""
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
"""第一期无领域 UI State;检核列表由独立 HTTP API 加载。"""
|
||||
return None
|
||||
@@ -375,6 +375,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"type": "boolean",
|
||||
"label": "缺资料通知",
|
||||
"label_key": "admin.schedule.form.voucherCheckNotifyMissing",
|
||||
"help": "总开关。缺件接收人在 Chat「通知配置」按文件类型设置。",
|
||||
"help_key": "admin.schedule.form.voucherCheckNotifyMissingHint",
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
@@ -383,6 +385,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"type": "boolean",
|
||||
"label": "失败告警",
|
||||
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
|
||||
"help": "技术失败发给排程「选择通知人员」。",
|
||||
"help_key": "admin.schedule.form.voucherCheckNotifyFailureHint",
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/engine_persistence.py
|
||||
|
||||
用途:新引擎批次、主体、单文件结果与通知审计的写入。
|
||||
依赖:models.voucher_check 新表。
|
||||
逻辑:runner 在扫描完成后一次性 persist;旧 invoice_states 不再写入。
|
||||
逻辑:runner 在扫描完成后一次性 persist;旧 invoice_states 不再写入。SQLite 测试库的 BigInteger 主键不会自增,persist_notification 会补 id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -131,7 +131,7 @@ def persist_notification(
|
||||
summary: dict[str, Any],
|
||||
sent_at: datetime | None,
|
||||
) -> VoucherCheckNotification:
|
||||
"""写入或覆盖本批次通知审计(一个 run 一条)。"""
|
||||
"""写入或覆盖本批次通知审计(一个 run 一条)。SQLite 测试库需显式补 BigInteger 主键。"""
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotification)
|
||||
.filter_by(run_id=run_id)
|
||||
@@ -139,6 +139,10 @@ def persist_notification(
|
||||
)
|
||||
if row is None:
|
||||
row = VoucherCheckNotification(run_id=run_id, created_at=datetime.utcnow())
|
||||
bind = db.session.get_bind()
|
||||
if bind is not None and bind.dialect.name == "sqlite":
|
||||
max_id = db.session.query(db.func.max(VoucherCheckNotification.id)).scalar() or 0
|
||||
row.id = int(max_id) + 1
|
||||
db.session.add(row)
|
||||
row.excel_filename = excel_filename
|
||||
row.recipient_user_ids_json = recipient_user_ids
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/notification.py
|
||||
|
||||
用途:立账凭证检核缺件汇总、以及检核 / PO 生成排程的技术失败告警。
|
||||
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||
逻辑:检核批次一条缺件汇总;PO 生成只在技术失败时告警;未配置接收人不发送;domain_notification_managed 避免通用排程重复通知。
|
||||
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
||||
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
||||
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,12 +23,52 @@ from app.services.voucher_check.engine_persistence import persist_notification
|
||||
_TZ = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
|
||||
def _recipient_users(task: ScheduleTask) -> list[User]:
|
||||
user_ids = task.notify_user_ids_json or []
|
||||
def _users_by_ids(user_ids: list[int]) -> list[User]:
|
||||
"""按 id 取出已绑定企微的用户,保持传入顺序。"""
|
||||
if not user_ids:
|
||||
return []
|
||||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
return [u for u in users if u.wecom_userid]
|
||||
found = {
|
||||
int(user.id): user
|
||||
for user in db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
if user.wecom_userid
|
||||
}
|
||||
return [found[user_id] for user_id in user_ids if user_id in found]
|
||||
|
||||
|
||||
def _recipient_users(task: ScheduleTask) -> list[User]:
|
||||
"""技术失败告警仍使用排程上的通知人。"""
|
||||
raw = task.notify_user_ids_json or []
|
||||
ids: list[int] = []
|
||||
for item in raw:
|
||||
try:
|
||||
user_id = int(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if user_id > 0 and user_id not in ids:
|
||||
ids.append(user_id)
|
||||
return _users_by_ids(ids)
|
||||
|
||||
|
||||
def _persist_skip(
|
||||
*,
|
||||
engine_run_id: int,
|
||||
excel_filename: str | None,
|
||||
recipient_user_ids: list[int],
|
||||
send_status: str,
|
||||
skip_reason: str,
|
||||
summary: dict[str, Any],
|
||||
) -> str:
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_user_ids,
|
||||
send_status=send_status,
|
||||
skip_reason=skip_reason,
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return send_status
|
||||
|
||||
|
||||
def send_batch_missing_summary(
|
||||
@@ -42,14 +83,24 @@ def send_batch_missing_summary(
|
||||
enabled: bool,
|
||||
) -> str:
|
||||
"""
|
||||
发送本批缺件汇总 textcard。
|
||||
核心逻辑:无缺件或未选接收人则不发空通知,并写入 notification 审计。
|
||||
按文件类型接收人发送缺件 textcard。
|
||||
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;无缺件或无人可发则写审计不发空消息。
|
||||
|
||||
Returns:
|
||||
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
||||
"""
|
||||
from app.services.voucher_check.notify_config_service import (
|
||||
load_recipients_by_rule,
|
||||
plan_missing_recipient_messages,
|
||||
)
|
||||
|
||||
missing_files = int(stats.get("missing_file_count") or 0)
|
||||
missing_invoices = int(stats.get("missing_invoice_count") or 0)
|
||||
plan = plan_missing_recipient_messages(
|
||||
by_file_type=stats.get("by_file_type") or {},
|
||||
recipients_by_rule=load_recipients_by_rule(profile_code),
|
||||
)
|
||||
planned_ids = sorted(int(uid) for uid in plan["user_rules"].keys())
|
||||
summary = {
|
||||
"profile_code": profile_code,
|
||||
"period": period_month,
|
||||
@@ -57,61 +108,64 @@ def send_batch_missing_summary(
|
||||
"missing_file_count": missing_files,
|
||||
"missing_invoice_count": missing_invoices,
|
||||
"run_no": schedule_run.run_no,
|
||||
"unmapped_rule_codes": plan["unmapped_codes"],
|
||||
"by_recipient": [
|
||||
{
|
||||
"user_id": user_id,
|
||||
"rule_codes": [item["code"] for item in plan["user_rules"][user_id]],
|
||||
}
|
||||
for user_id in planned_ids
|
||||
],
|
||||
}
|
||||
recipient_ids = [int(u.id) for u in _recipient_users(task)]
|
||||
|
||||
if not enabled:
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
return _persist_skip(
|
||||
engine_run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_ids,
|
||||
recipient_user_ids=planned_ids,
|
||||
send_status="skipped_disabled",
|
||||
skip_reason="notify_missing_enabled=false",
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return "skipped_disabled"
|
||||
|
||||
if missing_files <= 0:
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
if not getattr(task, "notify_enabled", True):
|
||||
return _persist_skip(
|
||||
engine_run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_ids,
|
||||
recipient_user_ids=planned_ids,
|
||||
send_status="skipped_disabled",
|
||||
skip_reason="notify_enabled=false",
|
||||
summary=summary,
|
||||
)
|
||||
if missing_files <= 0:
|
||||
return _persist_skip(
|
||||
engine_run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=[],
|
||||
send_status="skipped_no_missing",
|
||||
skip_reason="本批无缺件",
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return "skipped_no_missing"
|
||||
|
||||
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
return _persist_skip(
|
||||
engine_run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_ids,
|
||||
recipient_user_ids=planned_ids,
|
||||
send_status="skipped_disabled",
|
||||
skip_reason="WECOM_NOTIFY_ENABLED=false",
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return "skipped_disabled"
|
||||
|
||||
users = _recipient_users(task)
|
||||
users = _users_by_ids(planned_ids)
|
||||
if not users:
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
reason = "有缺件类型未配置接收人" if plan["unmapped_codes"] else "未配置企业微信接收人"
|
||||
return _persist_skip(
|
||||
engine_run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=[],
|
||||
send_status="skipped_no_recipients",
|
||||
skip_reason="未配置企业微信接收人",
|
||||
skip_reason=reason,
|
||||
summary=summary,
|
||||
sent_at=None,
|
||||
)
|
||||
db.session.commit()
|
||||
return "skipped_no_recipients"
|
||||
|
||||
from app.services.wecom_notify import (
|
||||
_build_jump_url,
|
||||
@@ -119,29 +173,23 @@ def send_batch_missing_summary(
|
||||
send_wecom_textcard_message,
|
||||
)
|
||||
|
||||
type_stats = stats.get("by_file_type") or {}
|
||||
top_missing = sorted(
|
||||
(
|
||||
(item.get("rule_name") or key, int(item.get("missing_file_count") or 0))
|
||||
for key, item in type_stats.items()
|
||||
if isinstance(item, dict)
|
||||
),
|
||||
key=lambda pair: pair[1],
|
||||
reverse=True,
|
||||
)
|
||||
top_missing = [f"{name}{count}" for name, count in top_missing if count > 0][:4]
|
||||
title = f"立账凭证缺件汇总: {task.name}"
|
||||
description = (
|
||||
f"业务方 {profile_code}\n"
|
||||
f"资料所属期间 {period_month}\n"
|
||||
f"批次 {schedule_run.run_no}\n"
|
||||
f"主体 {int(stats.get('subject_count') or 0)} 张\n"
|
||||
f"缺件文件 {missing_files} / 缺件 invoice {missing_invoices}\n"
|
||||
f"主要缺失:{'、'.join(top_missing) or '—'}\n"
|
||||
f"明细以工作台 Excel 为准。"
|
||||
)
|
||||
ok_any = False
|
||||
sent_ids: list[int] = []
|
||||
for user in users:
|
||||
items = plan["user_rules"].get(int(user.id)) or []
|
||||
type_lines = [
|
||||
f"{item['name']} {item['missing_file_count']} 份 / {item['missing_invoice_count']} 张 invoice"
|
||||
for item in items
|
||||
]
|
||||
title = f"立账凭证缺件: {task.name}"
|
||||
description = (
|
||||
f"业务方 {profile_code}\n"
|
||||
f"资料所属期间 {period_month}\n"
|
||||
f"批次 {schedule_run.run_no}\n"
|
||||
f"你负责的缺件:\n"
|
||||
+ "\n".join(type_lines)
|
||||
+ "\n明细以工作台 Excel 为准。"
|
||||
)
|
||||
trace_id = uuid.uuid4().hex
|
||||
jump_url = _build_jump_url(
|
||||
"/workspace/accounting-voucher-check",
|
||||
@@ -155,27 +203,33 @@ def send_batch_missing_summary(
|
||||
if data.get("errcode") == 0:
|
||||
audit.status = "sent"
|
||||
ok_any = True
|
||||
sent_ids.append(int(user.id))
|
||||
else:
|
||||
audit.error_code = str(data.get("errcode"))
|
||||
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
|
||||
except Exception as exc:
|
||||
current_app.logger.warning(
|
||||
"[voucher-check] batch notify failed user=%s err=%s",
|
||||
"[voucher-check] type notify failed user=%s err=%s",
|
||||
user.id,
|
||||
exc,
|
||||
)
|
||||
status = "sent" if ok_any else "failed"
|
||||
|
||||
skip_reason = None
|
||||
if not ok_any:
|
||||
skip_reason = "企业微信发送失败"
|
||||
elif plan["unmapped_codes"]:
|
||||
skip_reason = "部分文件类型未配置接收人"
|
||||
persist_notification(
|
||||
run_id=engine_run_id,
|
||||
excel_filename=excel_filename,
|
||||
recipient_user_ids=recipient_ids,
|
||||
send_status=status,
|
||||
skip_reason=None if ok_any else "企业微信发送失败",
|
||||
recipient_user_ids=sent_ids or [int(user.id) for user in users],
|
||||
send_status="sent" if ok_any else "failed",
|
||||
skip_reason=skip_reason,
|
||||
summary=summary,
|
||||
sent_at=datetime.now(_TZ).replace(tzinfo=None) if ok_any else None,
|
||||
)
|
||||
db.session.commit()
|
||||
return status
|
||||
return "sent" if ok_any else "failed"
|
||||
|
||||
|
||||
def send_failure_alert(
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/notify_config_service.py
|
||||
|
||||
用途:立账凭证按文件类型配置企微接收人,以及把本批缺件映射到「每人一封」。
|
||||
依赖:VoucherCheckNotifyConfig、User、sales Profile file_rules。
|
||||
逻辑:配置与 Profile 版本解耦;发送侧只取已绑定企微的用户。Chat 通知配置页把候选人交给公共选人弹窗;runner 共用本模块。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import User
|
||||
from app.models.voucher_check import VoucherCheckNotifyConfig
|
||||
from app.services.voucher_check.profiles.sales import SALES_PROFILE_CODE, required_file_rules
|
||||
|
||||
DEFAULT_NOTIFY_PROFILE = SALES_PROFILE_CODE
|
||||
|
||||
|
||||
def _rule_defs(profile_code: str) -> list[dict[str, Any]]:
|
||||
"""当前业务方必检文件规则。一期仅销售。"""
|
||||
code = str(profile_code or DEFAULT_NOTIFY_PROFILE).strip() or DEFAULT_NOTIFY_PROFILE
|
||||
if code != SALES_PROFILE_CODE:
|
||||
raise ValidationError("不支持的业务方", code="VOUCHER_CHECK.CONFIG_INVALID", details={"profile_code": code})
|
||||
return required_file_rules()
|
||||
|
||||
|
||||
def _known_rule_codes(profile_code: str) -> set[str]:
|
||||
return {str(rule.get("code") or "") for rule in _rule_defs(profile_code)} - {""}
|
||||
|
||||
|
||||
def normalize_recipients_json(raw: Any, *, profile_code: str) -> dict[str, list[int]]:
|
||||
"""
|
||||
把提交的接收人映射收成 {rule_code: [user_id]}。
|
||||
核心逻辑:只保留当前 Profile 的规则码;user_id 去重且必须是正整数。
|
||||
"""
|
||||
payload = raw if isinstance(raw, dict) else {}
|
||||
known = _known_rule_codes(profile_code)
|
||||
cleaned: dict[str, list[int]] = {code: [] for code in known}
|
||||
for key, value in payload.items():
|
||||
code = str(key or "").strip()
|
||||
if code not in known:
|
||||
continue
|
||||
seen: set[int] = set()
|
||||
ids: list[int] = []
|
||||
for item in value if isinstance(value, list) else []:
|
||||
try:
|
||||
user_id = int(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if user_id <= 0 or user_id in seen:
|
||||
continue
|
||||
seen.add(user_id)
|
||||
ids.append(user_id)
|
||||
cleaned[code] = ids
|
||||
return cleaned
|
||||
|
||||
|
||||
def load_recipients_by_rule(profile_code: str) -> dict[str, list[int]]:
|
||||
"""读取某业务方已保存的类型接收人;无行时返回空映射。"""
|
||||
code = str(profile_code or DEFAULT_NOTIFY_PROFILE).strip() or DEFAULT_NOTIFY_PROFILE
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotifyConfig)
|
||||
.filter_by(profile_code=code)
|
||||
.one_or_none()
|
||||
)
|
||||
raw = row.recipients_json if row and isinstance(row.recipients_json, dict) else {}
|
||||
return normalize_recipients_json(raw, profile_code=code)
|
||||
|
||||
|
||||
def plan_missing_recipient_messages(
|
||||
*,
|
||||
by_file_type: dict[str, Any],
|
||||
recipients_by_rule: dict[str, list[int]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把本批缺件类型按接收人聚合。
|
||||
核心逻辑:只处理 missing_file_count>0 的规则;同一人管多类时合并到一封。
|
||||
|
||||
Returns:
|
||||
user_rules: user_id → 该人需要看到的缺件类型列表
|
||||
unmapped_codes: 有缺件但未配置任何人的规则码
|
||||
"""
|
||||
missing_items: list[dict[str, Any]] = []
|
||||
unmapped: list[str] = []
|
||||
for code, item in (by_file_type or {}).items():
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if int(item.get("missing_file_count") or 0) <= 0:
|
||||
continue
|
||||
rule_code = str(item.get("rule_code") or code)
|
||||
payload = {
|
||||
"code": rule_code,
|
||||
"name": str(item.get("rule_name") or rule_code),
|
||||
"missing_file_count": int(item.get("missing_file_count") or 0),
|
||||
"missing_invoice_count": int(item.get("missing_invoice_count") or 0),
|
||||
}
|
||||
user_ids = [int(uid) for uid in (recipients_by_rule.get(rule_code) or []) if int(uid) > 0]
|
||||
if not user_ids:
|
||||
unmapped.append(rule_code)
|
||||
continue
|
||||
missing_items.append({**payload, "user_ids": user_ids})
|
||||
|
||||
user_rules: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
for item in missing_items:
|
||||
snippet = {
|
||||
"code": item["code"],
|
||||
"name": item["name"],
|
||||
"missing_file_count": item["missing_file_count"],
|
||||
"missing_invoice_count": item["missing_invoice_count"],
|
||||
}
|
||||
for user_id in item["user_ids"]:
|
||||
already = {row["code"] for row in user_rules[user_id]}
|
||||
if snippet["code"] not in already:
|
||||
user_rules[user_id].append(snippet)
|
||||
return {"user_rules": dict(user_rules), "unmapped_codes": unmapped}
|
||||
|
||||
|
||||
def _candidate_users() -> list[dict[str, Any]]:
|
||||
"""通知配置页候选人:在职用户,带部门与企微绑定标记,供公共选人弹窗分组。"""
|
||||
rows = (
|
||||
db.session.query(User)
|
||||
.filter(User.status == "active")
|
||||
.order_by(User.username)
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
{
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"real_name": user.real_name,
|
||||
"employee_id": user.employee_id,
|
||||
"department": user.department,
|
||||
"wecom_bound": bool(user.wecom_userid),
|
||||
}
|
||||
for user in rows
|
||||
]
|
||||
|
||||
|
||||
def get_notify_config(*, profile_code: str | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
组装通知配置页数据。
|
||||
核心逻辑:规则来自 Profile;接收人来自独立配置表;候选人带部门与企微绑定标记。
|
||||
"""
|
||||
code = str(profile_code or DEFAULT_NOTIFY_PROFILE).strip() or DEFAULT_NOTIFY_PROFILE
|
||||
recipients = load_recipients_by_rule(code)
|
||||
rules = [
|
||||
{
|
||||
"code": str(rule.get("code") or ""),
|
||||
"name": str(rule.get("name") or rule.get("code") or ""),
|
||||
"type_folder": str(rule.get("type_folder") or ""),
|
||||
"user_ids": list(recipients.get(str(rule.get("code") or ""), [])),
|
||||
}
|
||||
for rule in _rule_defs(code)
|
||||
if rule.get("code")
|
||||
]
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotifyConfig)
|
||||
.filter_by(profile_code=code)
|
||||
.one_or_none()
|
||||
)
|
||||
return {
|
||||
"profile_code": code,
|
||||
"rules": rules,
|
||||
"users": _candidate_users(),
|
||||
"updated_at": row.updated_at.isoformat(sep=" ", timespec="seconds") if row and row.updated_at else None,
|
||||
"updated_by": int(row.updated_by) if row and row.updated_by else None,
|
||||
}
|
||||
|
||||
|
||||
def save_notify_config(
|
||||
*,
|
||||
profile_code: str | None,
|
||||
recipients: Any,
|
||||
updated_by: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""写入文件类型接收人;未知规则码丢弃。"""
|
||||
code = str(profile_code or DEFAULT_NOTIFY_PROFILE).strip() or DEFAULT_NOTIFY_PROFILE
|
||||
cleaned = normalize_recipients_json(recipients, profile_code=code)
|
||||
known_ids = {int(user["id"]) for user in _candidate_users()}
|
||||
for rule_code, user_ids in list(cleaned.items()):
|
||||
cleaned[rule_code] = [user_id for user_id in user_ids if user_id in known_ids]
|
||||
now = datetime.utcnow()
|
||||
row = (
|
||||
db.session.query(VoucherCheckNotifyConfig)
|
||||
.filter_by(profile_code=code)
|
||||
.one_or_none()
|
||||
)
|
||||
if row is None:
|
||||
row = VoucherCheckNotifyConfig(profile_code=code, created_at=now)
|
||||
db.session.add(row)
|
||||
row.recipients_json = cleaned
|
||||
row.updated_by = updated_by
|
||||
row.updated_at = now
|
||||
db.session.commit()
|
||||
return get_notify_config(profile_code=code)
|
||||
@@ -370,7 +370,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
|
||||
for item in stats["excel_rows"]
|
||||
]
|
||||
|
||||
# [STEP 4] 每批一条企微汇总
|
||||
# [STEP 4] 按文件类型接收人拆成每人一封缺件通知
|
||||
notify_status = send_batch_missing_summary(
|
||||
task=task,
|
||||
schedule_run=run,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Seed voucher_check Chat Agent.
|
||||
|
||||
Revision ID: vc5f6a7b8c9d
|
||||
Revises: cp9b0c1d2e3f
|
||||
Create Date: 2026-09-16 13:30:00.000000
|
||||
|
||||
用途:为立账凭证检核注册 builtin Chat Agent。此前入口在工作台且仅 admin 可见,
|
||||
没有独立功能权限键可迁移;普通用户需在用户管理授予该 Agent。
|
||||
依赖:agents 表已存在。
|
||||
逻辑:先按 agent_code 复用已有实例(含停用);没有则插入。插入前把 agents.id
|
||||
序列对齐 MAX(id),避免本地库序列落后时撞主键。admin 仍按运行时角色看到
|
||||
全部 Agent,不必写关联表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy import text
|
||||
|
||||
|
||||
revision = "vc5f6a7b8c9d"
|
||||
down_revision = "cp9b0c1d2e3f"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
AGENT_CODE = "voucher_check"
|
||||
|
||||
|
||||
def _resync_agents_id_sequence() -> None:
|
||||
"""把 agents 主键序列对齐现有最大 id,避免 nextval 撞上已占用主键。"""
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
op.execute(
|
||||
"""
|
||||
SELECT setval(
|
||||
pg_get_serial_sequence('public.agents', 'id'),
|
||||
COALESCE((SELECT MAX(id) FROM public.agents), 1),
|
||||
true
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""插入或复用立账凭证检核 Agent。"""
|
||||
conn = op.get_bind()
|
||||
agent_id = conn.execute(
|
||||
text(
|
||||
"SELECT id FROM agents WHERE agent_code = :code "
|
||||
"ORDER BY id ASC LIMIT 1"
|
||||
),
|
||||
{"code": AGENT_CODE},
|
||||
).scalar()
|
||||
if agent_id is not None:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE agents
|
||||
SET is_active = true,
|
||||
runtime_provider = 'builtin',
|
||||
conversation_mode = 'task_chat',
|
||||
dify_app_type = 'chatflow',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = :agent_id
|
||||
"""
|
||||
),
|
||||
{"agent_id": agent_id},
|
||||
)
|
||||
return
|
||||
|
||||
_resync_agents_id_sequence()
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO agents (
|
||||
name, description, type, is_active, is_aggregate,
|
||||
agent_code, runtime_provider, conversation_mode, dify_app_type,
|
||||
suggested_questions_style, sort_order, created_at, updated_at
|
||||
) VALUES (
|
||||
:name, :description, 'api', true, false,
|
||||
:code, 'builtin', 'task_chat', 'chatflow',
|
||||
'plain', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
),
|
||||
{
|
||||
"name": "立账凭证",
|
||||
"description": "查看立账凭证检核任务、最近一次检核进度和企业微信发送记录。",
|
||||
"code": AGENT_CODE,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""不删除已创建的 Agent 实例,以免误伤运营配置。"""
|
||||
return
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Add voucher_check_notify_configs.
|
||||
|
||||
Revision ID: vc6a7b8c9d0e
|
||||
Revises: vc5f6a7b8c9d
|
||||
Create Date: 2026-09-16 15:55:00.000000
|
||||
|
||||
用途:按业务方保存立账凭证缺件通知的文件类型接收人。
|
||||
依赖:voucher_check 引擎表、users 表。
|
||||
逻辑:与 Profile 版本解耦,换人不需要发版 file_rules。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "vc6a7b8c9d0e"
|
||||
down_revision = "vc5f6a7b8c9d"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""新增按文件类型配置企微接收人的表。"""
|
||||
op.create_table(
|
||||
"voucher_check_notify_configs",
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("profile_code", sa.String(length=32), nullable=False),
|
||||
sa.Column("recipients_json", sa.JSON(), nullable=False),
|
||||
sa.Column("updated_by", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("profile_code", name="uq_voucher_check_notify_configs_profile"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除按文件类型接收人配置表。"""
|
||||
op.drop_table("voucher_check_notify_configs")
|
||||
@@ -19,7 +19,7 @@ def test_agent_type_catalog_contains_three_seed_types():
|
||||
"""Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。"""
|
||||
assert {
|
||||
'generic', 'shipping_notice', 'file_check',
|
||||
'procurement_contract_review', 'in_transit_transfer', 'contract_payment',
|
||||
'procurement_contract_review', 'in_transit_transfer', 'contract_payment', 'voucher_check',
|
||||
} <= set(AGENT_TYPE_CATALOG.keys())
|
||||
|
||||
|
||||
@@ -28,13 +28,14 @@ def test_list_type_catalog_includes_agent_code_and_label():
|
||||
catalog = list_type_catalog()
|
||||
assert len(catalog) >= 5
|
||||
codes = {entry['agent_code'] for entry in catalog}
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer', 'contract_payment'} <= codes
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer', 'contract_payment', 'voucher_check'} <= codes
|
||||
labels = {entry['label'] for entry in catalog}
|
||||
assert '通用问答 / 知识库' in labels
|
||||
assert '在途仓自动调拨' in labels
|
||||
assert '货代发货通知' in labels
|
||||
assert '文件检核' in labels
|
||||
assert '合同付款预警' in labels
|
||||
assert '立账凭证' in labels
|
||||
|
||||
|
||||
def test_get_catalog_entry_returns_runtime_handler_for_hybrid_types():
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_agent_registry_voucher_check.py
|
||||
|
||||
用途:验证 voucher_check 已注册为 builtin Chat Agent 类型。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap。
|
||||
逻辑:只读断言 Catalog 声明与 Handler 绑定;不创建 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.agent_registry import catalog_bindings
|
||||
from app.services.agent_registry.catalog_loader import build_agent_type_catalog, get_catalog_entry
|
||||
from app.services.agent_registry.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_voucher_check_type_in_catalog():
|
||||
"""catalog 必须包含 voucher_check,默认 builtin + task_chat。"""
|
||||
entry = get_catalog_entry('voucher_check')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '立账凭证'
|
||||
assert entry.get('runtime_provider_default') == 'builtin'
|
||||
assert entry.get('conversation_mode_default') == 'task_chat'
|
||||
assert entry.get('runtime_handler') == 'voucher_check'
|
||||
|
||||
|
||||
def test_voucher_check_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 voucher_check 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['voucher_check'] == 'voucher_check'
|
||||
|
||||
|
||||
def test_voucher_check_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 VoucherCheckHandler。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('voucher_check')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'voucher_check'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_voucher_check_present_in_full_catalog():
|
||||
"""完整 catalog 与既有类型共存。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'voucher_check' in catalog
|
||||
assert 'contract_payment' in catalog
|
||||
@@ -0,0 +1,178 @@
|
||||
"""
|
||||
backend/tests/test_voucher_check_permissions.py
|
||||
|
||||
用途:验收立账凭证改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、workspace voucher_check 蓝图。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表,但不能触发强制重检、也不能改通知配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
"""创建落库用户,供 voucher-check API 走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role=role,
|
||||
status='active',
|
||||
real_name=f'{username}-实名',
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='财务部',
|
||||
)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def _ensure_voucher_check_agent() -> Agent:
|
||||
"""确保存在启用中的立账凭证 Agent,供授权绑定。"""
|
||||
agent = Agent.query.filter_by(agent_code='voucher_check', is_active=True).first()
|
||||
if agent:
|
||||
return agent
|
||||
agent = Agent(
|
||||
name='立账凭证',
|
||||
agent_code='voucher_check',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(agent)
|
||||
return agent
|
||||
|
||||
|
||||
def _grant_voucher_check_agent(user: User) -> User:
|
||||
"""把立账凭证 Agent 授权给指定用户并重新取出,避免会话分离后丢失关系。"""
|
||||
agent = _ensure_voucher_check_agent()
|
||||
user_id = user.id
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.expunge(user)
|
||||
return db.session.get(User, user_id) or user
|
||||
|
||||
|
||||
def _json_error(response) -> dict:
|
||||
"""读取标准 envelope 的 error 对象。"""
|
||||
body = response.get_json()
|
||||
assert body.get('success') is False
|
||||
assert isinstance(body.get('error'), dict)
|
||||
return body['error']
|
||||
|
||||
|
||||
def test_voucher_check_api_forbids_user_without_agent(client, app):
|
||||
"""未授予 Agent 的普通用户查询任务或强制重检均返回 VOUCHER_CHECK.FORBIDDEN。"""
|
||||
with app.app_context():
|
||||
ordinary = _create_user(username='vc_api_denied')
|
||||
ordinary_id = ordinary.id
|
||||
_ensure_voucher_check_agent()
|
||||
db.session.expunge(ordinary)
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(ordinary_id),
|
||||
'X-Username': 'vc_api_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
# 关键断言:登录不足够,Agent 授权缺失必须 403。
|
||||
assert list_res.status_code == 403
|
||||
assert _json_error(list_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
force_res = client.post(
|
||||
'/api/workspace/accounting-voucher-check/runs',
|
||||
headers=headers,
|
||||
json={'mode': 'force_all'},
|
||||
)
|
||||
assert force_res.status_code == 403
|
||||
assert _json_error(force_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
|
||||
def test_voucher_check_api_allows_granted_user(client, app):
|
||||
"""授予 voucher_check Agent 后普通用户可以查询检核任务。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_granted'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_granted',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
# 关键断言:Agent 授权后不再 403,返回标准成功 envelope。
|
||||
assert list_res.status_code == 200
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_voucher_check_api_allows_admin_without_agent_binding(client, app):
|
||||
"""平台 admin 即使未绑定该 Agent 也可查询检核任务。"""
|
||||
with app.app_context():
|
||||
admin = _create_user(username='vc_api_admin', role='admin')
|
||||
admin_id = admin.id
|
||||
_ensure_voucher_check_agent()
|
||||
db.session.expunge(admin)
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(admin_id),
|
||||
'X-Username': 'vc_api_admin',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
assert list_res.status_code == 200
|
||||
assert list_res.get_json().get('success') is True
|
||||
|
||||
|
||||
def test_voucher_check_force_requires_admin(client, app):
|
||||
"""已授权的普通用户可查任务,但不能触发强制重检。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_jobs_denied'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_jobs_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
# 关键断言:访问权不等于操作权,强制重检仅管理员。
|
||||
res = client.post(
|
||||
'/api/workspace/accounting-voucher-check/runs',
|
||||
headers=headers,
|
||||
json={'mode': 'force_all'},
|
||||
)
|
||||
assert res.status_code == 403
|
||||
assert _json_error(res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
|
||||
def test_voucher_check_notify_config_requires_admin(client, app):
|
||||
"""已授权的普通用户可查任务,但不能读取或保存按类型接收人。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_notify_denied'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_notify_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
get_res = client.get('/api/workspace/accounting-voucher-check/notify-config', headers=headers)
|
||||
# 关键断言:通知配置读写均仅管理员。
|
||||
assert get_res.status_code == 403
|
||||
assert _json_error(get_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
put_res = client.put(
|
||||
'/api/workspace/accounting-voucher-check/notify-config',
|
||||
headers=headers,
|
||||
json={'profile_code': 'sales', 'recipients': {'po_order': [granted_id]}},
|
||||
)
|
||||
assert put_res.status_code == 403
|
||||
assert _json_error(put_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
@@ -0,0 +1,300 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_notify_config.py
|
||||
|
||||
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
|
||||
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
|
||||
逻辑:GET/PUT 仅 admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.models.voucher_check import VoucherCheckNotification, VoucherCheckNotifyConfig, VoucherCheckRun
|
||||
from app.services.voucher_check.notify_config_service import (
|
||||
normalize_recipients_json,
|
||||
plan_missing_recipient_messages,
|
||||
)
|
||||
from app.services.voucher_check.notification import send_batch_missing_summary
|
||||
|
||||
|
||||
def _ensure_user(
|
||||
*,
|
||||
username: str,
|
||||
role: str = "user",
|
||||
wecom_userid: str | None = None,
|
||||
department: str | None = None,
|
||||
) -> User:
|
||||
"""
|
||||
测试用户幂等创建。
|
||||
|
||||
Args:
|
||||
username: 登录名。
|
||||
role: 角色,默认普通用户。
|
||||
wecom_userid: 企微 userid,有值即视为已绑定。
|
||||
department: 部门名,供候选人接口与选人弹窗分组。
|
||||
"""
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if user:
|
||||
user.role = role
|
||||
user.status = "active"
|
||||
user.wecom_userid = wecom_userid
|
||||
if department is not None:
|
||||
user.department = department
|
||||
db.session.commit()
|
||||
return user
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role=role,
|
||||
status="active",
|
||||
real_name=username,
|
||||
wecom_userid=wecom_userid,
|
||||
department=department,
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_plan_merges_types_per_user_and_tracks_unmapped():
|
||||
"""同一人管多类时合并到一封;有缺件但无人接收的类型进入 unmapped。"""
|
||||
plan = plan_missing_recipient_messages(
|
||||
by_file_type={
|
||||
"po_order": {
|
||||
"rule_code": "po_order",
|
||||
"rule_name": "PO订单",
|
||||
"missing_file_count": 2,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
"tax_invoice": {
|
||||
"rule_code": "tax_invoice",
|
||||
"rule_name": "发票",
|
||||
"missing_file_count": 3,
|
||||
"missing_invoice_count": 2,
|
||||
},
|
||||
"bill_of_lading": {
|
||||
"rule_code": "bill_of_lading",
|
||||
"rule_name": "提单",
|
||||
"missing_file_count": 1,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
"customs_pack": {
|
||||
"rule_code": "customs_pack",
|
||||
"rule_name": "报关资料",
|
||||
"missing_file_count": 0,
|
||||
"missing_invoice_count": 0,
|
||||
},
|
||||
},
|
||||
recipients_by_rule={
|
||||
"po_order": [11, 12],
|
||||
"tax_invoice": [11],
|
||||
"bill_of_lading": [],
|
||||
},
|
||||
)
|
||||
# 关键断言:11 同时收到 PO 与发票;提单无人配置。
|
||||
assert plan["unmapped_codes"] == ["bill_of_lading"]
|
||||
assert [item["code"] for item in plan["user_rules"][11]] == ["po_order", "tax_invoice"]
|
||||
assert [item["code"] for item in plan["user_rules"][12]] == ["po_order"]
|
||||
|
||||
|
||||
def test_normalize_drops_unknown_rule_codes():
|
||||
"""提交里的未知规则码必须丢弃,不能写进配置表。"""
|
||||
cleaned = normalize_recipients_json(
|
||||
{"po_order": [1, 1, "2", 0, "x"], "unknown": [9]},
|
||||
profile_code="sales",
|
||||
)
|
||||
assert cleaned["po_order"] == [1, 2]
|
||||
assert "unknown" not in cleaned
|
||||
assert "tax_invoice" in cleaned
|
||||
|
||||
|
||||
def test_admin_can_get_and_save_notify_config(app, client, admin_headers):
|
||||
"""管理员可读取六行规则并保存接收人。"""
|
||||
with app.app_context():
|
||||
admin = _ensure_user(username="admin", role="admin")
|
||||
owner = _ensure_user(username="vc_po_owner", wecom_userid="wx-po", department="财务部")
|
||||
owner_id = owner.id
|
||||
admin_id = admin.id
|
||||
|
||||
listed = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notify-config",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
payload = parse_api_data(listed.get_json())
|
||||
owner_row = next(row for row in payload["users"] if row["id"] == owner_id)
|
||||
# 关键断言:候选人带部门,供公共选人弹窗左侧分组。
|
||||
assert owner_row["department"] == "财务部"
|
||||
assert owner_row["wecom_bound"] is True
|
||||
codes = [row["code"] for row in payload["rules"]]
|
||||
# 关键断言:页面行来自销售 Profile 六类必检文件。
|
||||
assert codes == [
|
||||
"po_order",
|
||||
"customs_pack",
|
||||
"sales_release",
|
||||
"tax_invoice",
|
||||
"customs_declaration",
|
||||
"bill_of_lading",
|
||||
]
|
||||
|
||||
saved = client.put(
|
||||
"/api/workspace/accounting-voucher-check/notify-config",
|
||||
headers=admin_headers,
|
||||
json={
|
||||
"profile_code": "sales",
|
||||
"recipients": {"po_order": [owner_id], "unknown": [admin_id]},
|
||||
},
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
saved_payload = parse_api_data(saved.get_json())
|
||||
po_row = next(row for row in saved_payload["rules"] if row["code"] == "po_order")
|
||||
assert po_row["user_ids"] == [owner_id]
|
||||
unknown_codes = [row["code"] for row in saved_payload["rules"] if row["code"] == "unknown"]
|
||||
assert unknown_codes == []
|
||||
|
||||
with app.app_context():
|
||||
row = db.session.query(VoucherCheckNotifyConfig).filter_by(profile_code="sales").one()
|
||||
assert row.recipients_json["po_order"] == [owner_id]
|
||||
assert "unknown" not in row.recipients_json
|
||||
|
||||
|
||||
def test_notify_config_rejects_non_admin_headers(app, client, user_headers):
|
||||
"""仅凭普通用户 header 不能改通知配置。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
|
||||
res = client.get("/api/workspace/accounting-voucher-check/notify-config", headers=user_headers)
|
||||
assert res.status_code == 403
|
||||
assert parse_api_error(res.get_json())["code"] in {
|
||||
"VOUCHER_CHECK.FORBIDDEN",
|
||||
"VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
}
|
||||
|
||||
|
||||
def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
||||
"""缺件通知按人拆信,正文只含该人负责的缺失类型。"""
|
||||
sent: list[tuple[str, str, str]] = []
|
||||
|
||||
def _fake_send(wecom_userid, title, description, jump_url):
|
||||
sent.append((wecom_userid, title, description))
|
||||
return {"errcode": 0}
|
||||
|
||||
monkeypatch.setattr("app.services.wecom_notify.send_wecom_textcard_message", _fake_send)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify._create_audit",
|
||||
lambda *args, **kwargs: SimpleNamespace(
|
||||
jump_url=None, status=None, error_code=None, error_message=None
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr("app.services.wecom_notify._build_jump_url", lambda *args, **kwargs: "https://jump")
|
||||
|
||||
with app.app_context():
|
||||
app.config["WECOM_NOTIFY_ENABLED"] = True
|
||||
owner = _ensure_user(username="vc_notify_owner", role="admin", wecom_userid="wx-owner")
|
||||
po_user = _ensure_user(username="vc_po_recv", wecom_userid="wx-po-recv")
|
||||
bl_user = _ensure_user(username="vc_bl_recv", wecom_userid="wx-bl-recv")
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-VC-NOTIFY-SPLIT",
|
||||
name="立账凭证检核",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-check",
|
||||
owner_user_id=owner.id,
|
||||
cron_expr="0 6 * * 2",
|
||||
notify_enabled=True,
|
||||
notify_user_ids_json=[],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
schedule_run = ScheduleRun(
|
||||
schedule_task_id=task.id,
|
||||
run_no="RUN-VC-NOTIFY-SPLIT",
|
||||
trigger_type="cron",
|
||||
status="success",
|
||||
)
|
||||
db.session.add(schedule_run)
|
||||
db.session.flush()
|
||||
engine_run = VoucherCheckRun(
|
||||
id=1,
|
||||
schedule_run_id=schedule_run.id,
|
||||
run_no="VC-NOTIFY-SPLIT",
|
||||
profile_code="sales",
|
||||
profile_version="1",
|
||||
profile_snapshot_json={"profile_code": "sales"},
|
||||
period_month=date(2026, 8, 1),
|
||||
mode="incremental",
|
||||
status="missing",
|
||||
subject_count=4,
|
||||
missing_file_count=3,
|
||||
missing_invoice_count=2,
|
||||
)
|
||||
db.session.add(engine_run)
|
||||
db.session.flush()
|
||||
notify_row = (
|
||||
db.session.query(VoucherCheckNotifyConfig).filter_by(profile_code="sales").one_or_none()
|
||||
)
|
||||
if notify_row is None:
|
||||
notify_row = VoucherCheckNotifyConfig(profile_code="sales")
|
||||
db.session.add(notify_row)
|
||||
notify_row.recipients_json = {
|
||||
"po_order": [po_user.id],
|
||||
"bill_of_lading": [bl_user.id],
|
||||
}
|
||||
db.session.commit()
|
||||
status = send_batch_missing_summary(
|
||||
task=task,
|
||||
schedule_run=schedule_run,
|
||||
engine_run_id=engine_run.id,
|
||||
profile_code="sales",
|
||||
period_month="2026-08",
|
||||
stats={
|
||||
"subject_count": 4,
|
||||
"missing_file_count": 3,
|
||||
"missing_invoice_count": 2,
|
||||
"by_file_type": {
|
||||
"po_order": {
|
||||
"rule_code": "po_order",
|
||||
"rule_name": "PO订单",
|
||||
"missing_file_count": 2,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
"bill_of_lading": {
|
||||
"rule_code": "bill_of_lading",
|
||||
"rule_name": "提单",
|
||||
"missing_file_count": 1,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
"tax_invoice": {
|
||||
"rule_code": "tax_invoice",
|
||||
"rule_name": "发票",
|
||||
"missing_file_count": 1,
|
||||
"missing_invoice_count": 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
excel_filename="voucher_check_sales_2026-08.xlsx",
|
||||
enabled=True,
|
||||
)
|
||||
assert status == "sent"
|
||||
audit = db.session.query(VoucherCheckNotification).filter_by(run_id=engine_run.id).one()
|
||||
# 关键断言:仍是一批一条审计;skip_reason 记录未配置类型。
|
||||
assert audit.send_status == "sent"
|
||||
assert audit.skip_reason == "部分文件类型未配置接收人"
|
||||
assert set(audit.recipient_user_ids_json or []) == {po_user.id, bl_user.id}
|
||||
assert "tax_invoice" in (audit.summary_json or {}).get("unmapped_rule_codes", [])
|
||||
|
||||
wecom_ids = {item[0] for item in sent}
|
||||
assert wecom_ids == {"wx-po-recv", "wx-bl-recv"}
|
||||
po_body = next(item[2] for item in sent if item[0] == "wx-po-recv")
|
||||
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
||||
assert "PO订单" in po_body
|
||||
assert "提单" not in po_body
|
||||
assert "发票" not in po_body
|
||||
assert "提单" in bl_body
|
||||
assert "PO订单" not in bl_body
|
||||
@@ -104,10 +104,10 @@ def _add_engine_run(
|
||||
return engine
|
||||
|
||||
|
||||
def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers):
|
||||
def test_workspace_latest_run_returns_queued_force_all(app, client, admin_headers):
|
||||
"""入队中的强制重检必须显示 queued,而不是建批前失败口径。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-QUEUED",
|
||||
status="queued",
|
||||
@@ -117,7 +117,7 @@ def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
@@ -129,10 +129,10 @@ def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers
|
||||
assert payload["current_step"]["step"] == "queued"
|
||||
|
||||
|
||||
def test_workspace_latest_run_returns_completed_metrics(app, client, user_headers):
|
||||
def test_workspace_latest_run_returns_completed_metrics(app, client, admin_headers):
|
||||
"""终态缺件批次返回四指标与 100% 进度。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
sched = _add_schedule_run(
|
||||
run_no="RUN-LATEST-DONE",
|
||||
status="success",
|
||||
@@ -149,7 +149,7 @@ def test_workspace_latest_run_returns_completed_metrics(app, client, user_header
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
@@ -165,10 +165,10 @@ def test_workspace_latest_run_returns_completed_metrics(app, client, user_header
|
||||
assert payload["missing_invoice_count"] == 6
|
||||
|
||||
|
||||
def test_workspace_latest_run_running_progress_ignores_list_period(app, client, user_headers):
|
||||
def test_workspace_latest_run_running_progress_ignores_list_period(app, client, admin_headers):
|
||||
"""执行中进度跟 runner 步骤走,且 latest 不吃列表 period。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
old = _add_schedule_run(
|
||||
run_no="RUN-LATEST-OLD-AUG",
|
||||
status="success",
|
||||
@@ -200,7 +200,7 @@ def test_workspace_latest_run_running_progress_ignores_list_period(app, client,
|
||||
|
||||
latest = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert latest.status_code == 200
|
||||
payload = parse_api_data(latest.get_json())
|
||||
@@ -213,7 +213,7 @@ def test_workspace_latest_run_running_progress_ignores_list_period(app, client,
|
||||
|
||||
filtered = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert filtered.status_code == 200
|
||||
nos = {item["run_no"] for item in parse_api_data(filtered.get_json())["items"]}
|
||||
@@ -222,10 +222,10 @@ def test_workspace_latest_run_running_progress_ignores_list_period(app, client,
|
||||
assert payload["run_no"] == "RUN-LATEST-RUNNING"
|
||||
|
||||
|
||||
def test_workspace_latest_run_pre_engine_failure(app, client, user_headers):
|
||||
def test_workspace_latest_run_pre_engine_failure(app, client, admin_headers):
|
||||
"""建批前失败仍作为最近一次检核,状态为技术失败。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-FAILED",
|
||||
status="failed",
|
||||
@@ -242,7 +242,7 @@ def test_workspace_latest_run_pre_engine_failure(app, client, user_headers):
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
|
||||
@@ -42,7 +42,7 @@ def _ensure_user(*, username: str, role: str, real_name: str | None = None) -> U
|
||||
return user
|
||||
|
||||
|
||||
def test_workspace_lists_wecom_notifications(app, client, user_headers):
|
||||
def test_workspace_lists_wecom_notifications(app, client, admin_headers):
|
||||
"""企微发送记录列表应带出批次统计、接收人姓名,并按发送状态筛选。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
@@ -116,7 +116,7 @@ def test_workspace_lists_wecom_notifications(app, client, user_headers):
|
||||
|
||||
listed = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
payload = parse_api_data(listed.get_json())
|
||||
@@ -132,7 +132,7 @@ def test_workspace_lists_wecom_notifications(app, client, user_headers):
|
||||
|
||||
filtered = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications?period=2026-07&send_status=skipped_no_missing",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert filtered.status_code == 200
|
||||
filtered_payload = parse_api_data(filtered.get_json())
|
||||
|
||||
@@ -74,10 +74,10 @@ def test_parse_period_filter_year_and_month():
|
||||
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
|
||||
def test_workspace_lists_runs_by_year_or_month(app, client, admin_headers):
|
||||
"""任务列表 year 筛出同年多月,month 仍只返回单月。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
db.session.add(_engine_run(run_no="VC-202608-Y", period_month=date(2026, 8, 1)))
|
||||
db.session.add(_engine_run(run_no="VC-202607-Y", period_month=date(2026, 7, 1)))
|
||||
db.session.add(_engine_run(run_no="VC-202512-Y", period_month=date(2025, 12, 1)))
|
||||
@@ -85,7 +85,7 @@ def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
|
||||
|
||||
year_resp = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert year_resp.status_code == 200
|
||||
year_payload = parse_api_data(year_resp.get_json())
|
||||
@@ -97,7 +97,7 @@ def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
|
||||
|
||||
month_resp = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert month_resp.status_code == 200
|
||||
month_payload = parse_api_data(month_resp.get_json())
|
||||
@@ -137,10 +137,10 @@ def test_workspace_year_filter_includes_pre_engine_failure(app, client, admin_he
|
||||
assert "RUN-PREENGINE-YEAR" in nos
|
||||
|
||||
|
||||
def test_workspace_lists_notifications_by_year(app, client, user_headers):
|
||||
def test_workspace_lists_notifications_by_year(app, client, admin_headers):
|
||||
"""企微发送记录按年筛选应覆盖该年各月。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
august = _engine_run(run_no="VC-202608-N", period_month=date(2026, 8, 1))
|
||||
july = _engine_run(run_no="VC-202607-N", period_month=date(2026, 7, 1), status="completed")
|
||||
db.session.add_all([august, july])
|
||||
@@ -163,7 +163,7 @@ def test_workspace_lists_notifications_by_year(app, client, user_headers):
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications?period=2026",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
@@ -172,13 +172,13 @@ def test_workspace_lists_notifications_by_year(app, client, user_headers):
|
||||
assert "VC-202607-N" in nos
|
||||
|
||||
|
||||
def test_workspace_rejects_invalid_period(app, client, user_headers):
|
||||
def test_workspace_rejects_invalid_period(app, client, admin_headers):
|
||||
"""非法 period 返回配置错误,而不是空列表。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_ensure_user(username="admin", role="admin")
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-13",
|
||||
headers=user_headers,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 400
|
||||
error = parse_api_error(response.get_json())
|
||||
|
||||
+3
-3
@@ -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 货代发货通知库存源补充需求
|
||||
|
||||
@@ -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) |
|
||||
|
||||
@@ -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 销货放行打印仍待接线。
|
||||
+20
-5
@@ -3,7 +3,7 @@
|
||||
docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html
|
||||
用途:立账凭证工作台「最近一次检核」卡片原型(Tab 下方、筛选栏上方)。
|
||||
依赖:浏览器原生 HTML/CSS/JS,无需构建。
|
||||
逻辑:默认展示最近一批终态;点「强制重检上月」切入执行中进度;原型预览可切换完成/执行中/失败。
|
||||
逻辑:终态用矮指标格;点「强制重检上月」切入执行中进度。原型预览可切换完成/执行中/失败。
|
||||
-->
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
@@ -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 @@
|
||||
<body>
|
||||
<div class="page">
|
||||
<div class="proto-note">
|
||||
这是<strong>原型</strong>,不是工作台代码。最近一次检核放在 Tab 下方、筛选栏上方:它是整页状态,不跟着年/月过滤。强制重检放在卡片上,点击后进度就在本卡更新。
|
||||
这是<strong>原型</strong>,不是工作台代码。最近一次检核放在 Tab 下方、筛选栏上方:它是整页状态,不跟着年/月过滤。终态用矮指标格,排队/执行中才展开进度条。强制重检放在卡片上,点击后进度就在本卡更新。
|
||||
<div class="proto-actions">
|
||||
预览状态:
|
||||
<button class="btn" type="button" data-preview="done">完成 · 缺件</button>
|
||||
@@ -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 =
|
||||
'<div class="latest-hd">' +
|
||||
"<div><h2>" + data.title + "</h2>" +
|
||||
'<p class="latest-meta"><span>批次 ' + data.runNo + "</span><span>期间 " + data.period + "</span><span>" + data.mode + "</span></p></div>" +
|
||||
'<div class="latest-actions">' +
|
||||
(data.percent === 100 && data.statusClass !== "fail"
|
||||
? '<button class="link" type="button">查看本批详情</button>'
|
||||
: "") +
|
||||
'<span class="badge ' + data.statusClass + '">' + data.status + "</span>" +
|
||||
'<button class="btn warn" type="button" data-force="1"' + (busy ? " disabled" : "") + ">强制重检上月</button>" +
|
||||
"</div>" +
|
||||
@@ -341,9 +359,6 @@
|
||||
}).join("") +
|
||||
"</div>" +
|
||||
'<p class="step-line">' + data.step + (data.hint ? "<small>" + data.hint + "</small>" : "") + "</p>" +
|
||||
(data.percent === 100 && data.statusClass !== "fail"
|
||||
? '<div class="latest-ft"><button class="link" type="button">查看本批详情</button></div>'
|
||||
: "") +
|
||||
"</div>";
|
||||
}
|
||||
|
||||
|
||||
@@ -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订单」已有相同文件名则不覆盖 |
|
||||
@@ -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 <readonly-user>;
|
||||
- [ ] 二者 `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 <readonly-user>;
|
||||
|
||||
### 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 故障
|
||||
|
||||
@@ -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 注册。
|
||||
|
||||
@@ -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,后续评估管理后台配置 |
|
||||
+2
-2
@@ -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。 |
|
||||
|
||||
### 采购合同审查
|
||||
|
||||
|
||||
@@ -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) |
|
||||
+3
-2
@@ -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)。
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/chat/components/ChatMobileHeader.vue
|
||||
* 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。合同付款预警可隐藏历史入口。
|
||||
* 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。作业面 Agent 可隐藏历史入口。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 依赖:lucide-vue-next、LocaleToggleButton、ExternalSystemLinks、AgentCategoryList、chat.types。
|
||||
* 逻辑:由聊天页面传入当前 Agent、历史记录与用户可用 Agent;通过事件把新会话、切换 Agent、反馈、进入管理控制台等操作回传给页面。
|
||||
* 管理员通过底部右侧工具图标进入管理控制台;用户下拉菜单仅保留退出登录。
|
||||
* 合同付款预警第一期不走对话,hideSessionUi 时隐藏新会话与历史列表。
|
||||
* 合同付款预警、立账凭证第一期不走对话,hideSessionUi 时隐藏新会话与历史列表。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
@@ -205,7 +205,7 @@ const orderExtractionAttentionClass = (item: DisplayHistoryItem) => {
|
||||
</button>
|
||||
</div>
|
||||
<p v-else class="px-4 pb-3 text-xs leading-5 text-muted">
|
||||
{{ $t('admin.contractPayment.sessionHint') }}
|
||||
{{ $t('chat.taskAgent.sessionHint') }}
|
||||
</p>
|
||||
|
||||
<div v-if="!hideSessionUi" class="flex items-center justify-between px-4 py-2">
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
|
||||
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话 Workflow 时间线与内置浏览器。
|
||||
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、chat.context。
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、ContractPaymentChatPanel、VoucherCheckChatPanel、chat.context。
|
||||
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
|
||||
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰;
|
||||
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警 Agent 用 Tab 台账替换消息列表与输入框。
|
||||
* 订单复核工作台异步分包,避免普通对话首屏拉取 PDF.js;合同付款预警、立账凭证 Agent 用 Tab 作业面替换消息列表与输入框。
|
||||
|
||||
*/
|
||||
|
||||
@@ -44,7 +44,7 @@ import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
|
||||
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent } from '@/shared/utils/agent-registry.utils';
|
||||
import { agentHasIntentUiProfile, resolveAgentCode, AGENT_CODE_IN_TRANSIT_TRANSFER, isContractPaymentAgent, isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils';
|
||||
|
||||
import {
|
||||
SHIPPING_WORKFLOW_KEY,
|
||||
@@ -74,6 +74,10 @@ const ContractPaymentChatPanel = defineAsyncComponent(
|
||||
() => import('@/features/contract-payment/components/ContractPaymentChatPanel.vue'),
|
||||
);
|
||||
|
||||
const VoucherCheckChatPanel = defineAsyncComponent(
|
||||
() => import('@/features/voucher-check/components/VoucherCheckChatPanel.vue'),
|
||||
);
|
||||
|
||||
type MaintenanceRecordPanelCommand = {
|
||||
|
||||
mode: 'list' | 'create';
|
||||
@@ -121,6 +125,12 @@ const isInTransitTransferAgent = computed(() => resolveAgentCode(page.currentAge
|
||||
/** 合同付款预警 Agent:主区嵌台账 Tab,隐藏对话输入与历史。 */
|
||||
const isContractPaymentAgentPage = computed(() => isContractPaymentAgent(page.currentAgent));
|
||||
|
||||
/** 立账凭证 Agent:主区嵌检核任务 / 企微发送记录 Tab,隐藏对话输入与历史。 */
|
||||
const isVoucherCheckAgentPage = computed(() => isVoucherCheckAgent(page.currentAgent));
|
||||
|
||||
/** builtin 作业面 Agent 共用:隐藏新会话、历史列表与输入框。 */
|
||||
const hideTaskChatSessionUi = computed(() => isContractPaymentAgentPage.value || isVoucherCheckAgentPage.value);
|
||||
|
||||
/** 在途仓自动调拨业务流激活(来源选择/待处理等子视图)时隐藏聊天输入框,模拟业务页。 */
|
||||
const transferFlowActive = ref(false);
|
||||
watch(isInTransitTransferAgent, (isTransfer) => { if (!isTransfer) transferFlowActive.value = false; });
|
||||
@@ -398,7 +408,7 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
:applied-theme="page.appliedTheme"
|
||||
|
||||
:hide-session-ui="isContractPaymentAgentPage"
|
||||
:hide-session-ui="hideTaskChatSessionUi"
|
||||
|
||||
@new-chat="page.handleSidebarNewChat"
|
||||
|
||||
@@ -440,7 +450,7 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
:user-agents="page.userAgents"
|
||||
|
||||
:hide-history="isContractPaymentAgentPage"
|
||||
:hide-history="hideTaskChatSessionUi"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@@ -486,6 +496,8 @@ watch(() => page.currentAgentId, () => {
|
||||
|
||||
<ContractPaymentChatPanel v-else-if="isContractPaymentAgentPage" />
|
||||
|
||||
<VoucherCheckChatPanel v-else-if="isVoucherCheckAgentPage" />
|
||||
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1" :class="showShippingWorkflowTimeline ? 'shipping-workbench-layout' : ''">
|
||||
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col" :class="showShippingWorkflowTimeline ? 'shipping-chat-column' : ''">
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
<!--
|
||||
features/voucher-check/components/VoucherCheckChatPanel.vue
|
||||
用途:立账凭证 Chat 主区:检核任务 / 企微发送记录 / 通知配置 Tab,当前 Tab 内批次明细下钻。
|
||||
依赖:workspace 立账凭证列表与详情、VoucherCheckNotifyConfigPanel、voucherCheckChat.utils、vue-router query、auth.store。
|
||||
逻辑:由 ChatViewContent 在 agent_code=voucher_check 时替换消息列表与输入框;
|
||||
view / runId / runNo 写入 /chat/:agentId 查询参数;通知配置仅平台管理员可见可改。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import AccountingVoucherCheckDetailView from '@/features/workspace/views/AccountingVoucherCheckDetailView.vue';
|
||||
import AccountingVoucherCheckView from '@/features/workspace/views/AccountingVoucherCheckView.vue';
|
||||
import type { VoucherCheckChatView } from '../constants';
|
||||
import {
|
||||
buildVoucherCheckChatQuery,
|
||||
parseVoucherCheckChatQuery,
|
||||
} from '../utils/voucherCheckChat.utils';
|
||||
import VoucherCheckNotifyConfigPanel from './VoucherCheckNotifyConfigPanel.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const auth = useAuthStore();
|
||||
|
||||
const isAdmin = computed(() => Boolean(auth.isAdmin));
|
||||
const parsedQuery = computed(() => parseVoucherCheckChatQuery(
|
||||
route.query.view,
|
||||
route.query.runId,
|
||||
route.query.runNo,
|
||||
));
|
||||
const activeView = computed<VoucherCheckChatView>(() => parsedQuery.value.view);
|
||||
const detailRunId = computed(() => parsedQuery.value.runId);
|
||||
const detailRunNo = computed(() => parsedQuery.value.runNo);
|
||||
|
||||
const tabs = computed(() => {
|
||||
const items: Array<{ key: VoucherCheckChatView; label: string }> = [
|
||||
{ key: 'tasks', label: t('workspace.voucherCheck.tabTasks') },
|
||||
{ key: 'notifications', label: t('workspace.voucherCheck.tabNotifications') },
|
||||
];
|
||||
if (isAdmin.value) {
|
||||
items.push({ key: 'notifyConfig', label: t('workspace.voucherCheck.tabNotifyConfig') });
|
||||
}
|
||||
return items;
|
||||
});
|
||||
|
||||
/**
|
||||
* 把当前 Tab / 批次明细写入 Chat 路由,保持刷新与旧地址重定向可用。
|
||||
* 核心逻辑:replace 避免 Tab 切换堆积历史;切 Tab 时清掉 runId。
|
||||
*/
|
||||
async function syncQuery(
|
||||
view: VoucherCheckChatView,
|
||||
runId: number | null,
|
||||
runNo: string | null = null,
|
||||
): Promise<void> {
|
||||
const nextQuery = buildVoucherCheckChatQuery(view, runId, runNo);
|
||||
const currentView = String(route.query.view || '');
|
||||
const currentRunId = String(route.query.runId || '');
|
||||
const currentRunNo = String(route.query.runNo || '');
|
||||
if (
|
||||
currentView === nextQuery.view
|
||||
&& currentRunId === (nextQuery.runId || '')
|
||||
&& currentRunNo === (nextQuery.runNo || '')
|
||||
) return;
|
||||
const query = { ...route.query, ...nextQuery };
|
||||
if (!runId) {
|
||||
delete query.runId;
|
||||
delete query.runNo;
|
||||
}
|
||||
await router.replace({ params: { ...route.params }, query });
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换主 Tab;详情下钻随 Tab 关闭,避免第四个隐形页。
|
||||
*/
|
||||
function selectView(view: VoucherCheckChatView): void {
|
||||
void syncQuery(view, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在当前 Tab 内打开批次明细。
|
||||
*/
|
||||
function openDetail(payload: { runId: number; runNo?: string | null }): void {
|
||||
void syncQuery(activeView.value, payload.runId, payload.runNo || null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从明细返回当前 Tab 列表。
|
||||
*/
|
||||
function closeDetail(): void {
|
||||
void syncQuery(activeView.value, null);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => route.query.view,
|
||||
(rawView) => {
|
||||
if (rawView) return;
|
||||
void syncQuery(activeView.value, detailRunId.value, detailRunNo.value);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
[isAdmin, activeView],
|
||||
() => {
|
||||
if (!isAdmin.value && activeView.value === 'notifyConfig') {
|
||||
void syncQuery('tasks', null);
|
||||
}
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-[var(--surface-muted,#f4f7fb)]">
|
||||
<div class="px-5 pt-5">
|
||||
<h1 class="text-xl font-bold text-primary">{{ t('workspace.voucherCheck.title') }}</h1>
|
||||
<p class="mt-1 text-sm text-muted">{{ t('workspace.voucherCheck.subtitle') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex gap-0 border-b border-default px-5">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.key"
|
||||
type="button"
|
||||
class="mb-[-1px] border-b-2 px-4 py-2.5 text-sm font-bold"
|
||||
:class="activeView === tab.key
|
||||
? 'border-brand-500 text-brand-600'
|
||||
: 'border-transparent text-muted hover:text-secondary'"
|
||||
@click="selectView(tab.key)"
|
||||
>
|
||||
{{ tab.label }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-auto px-5 py-4">
|
||||
<VoucherCheckNotifyConfigPanel v-if="activeView === 'notifyConfig' && isAdmin" />
|
||||
<AccountingVoucherCheckDetailView
|
||||
v-else-if="detailRunId"
|
||||
:run-id="detailRunId"
|
||||
:run-no="detailRunNo"
|
||||
embedded
|
||||
@close="closeDetail"
|
||||
/>
|
||||
<AccountingVoucherCheckView
|
||||
v-else
|
||||
:active-tab="activeView === 'notifications' ? 'notifications' : 'tasks'"
|
||||
embedded
|
||||
@open-detail="openDetail"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,201 @@
|
||||
<!--
|
||||
features/voucher-check/components/VoucherCheckNotifyConfigPanel.vue
|
||||
用途:立账凭证 Chat「通知配置」Tab:按六类必检文件分别选择企微接收人。
|
||||
依赖:voucherCheck.api、UserPickerDialog、vue-i18n、useMessage。
|
||||
逻辑:仅平台管理员可见;规则来自销售 Profile,接收人写入独立配置表;
|
||||
行内只展示标签 +「选择」,点选打开公共选人弹窗;未绑企微的人可勾选但发送时会被跳过。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Loader2 } from 'lucide-vue-next';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import UserPickerDialog from '@/shared/components/UserPickerDialog.vue';
|
||||
import { userPickerLabel } from '@/shared/utils/userPicker.utils';
|
||||
import {
|
||||
getVoucherCheckNotifyConfig,
|
||||
saveVoucherCheckNotifyConfig,
|
||||
type VoucherCheckNotifyRule,
|
||||
type VoucherCheckNotifyUser,
|
||||
} from '@/features/workspace/api/voucherCheck.api';
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const profileCode = ref('sales');
|
||||
const rules = ref<VoucherCheckNotifyRule[]>([]);
|
||||
const users = ref<VoucherCheckNotifyUser[]>([]);
|
||||
const updatedAt = ref<string | null>(null);
|
||||
const pickerOpen = ref(false);
|
||||
const pickerRuleCode = ref<string | null>(null);
|
||||
|
||||
const userMap = computed(() => {
|
||||
const next = new Map<number, VoucherCheckNotifyUser>();
|
||||
for (const user of users.value) next.set(user.id, user);
|
||||
return next;
|
||||
});
|
||||
|
||||
const pickerRule = computed(() =>
|
||||
rules.value.find((rule) => rule.code === pickerRuleCode.value) || null,
|
||||
);
|
||||
|
||||
const pickerSelectedIds = computed(() => pickerRule.value?.user_ids || []);
|
||||
|
||||
/**
|
||||
* 打开某文件类型的公共选人弹窗。
|
||||
*/
|
||||
function openPicker(ruleCode: string): void {
|
||||
pickerRuleCode.value = ruleCode;
|
||||
pickerOpen.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹窗确定后写回该行接收人。
|
||||
*/
|
||||
function applyPickerSelection(userIds: number[]): void {
|
||||
const row = rules.value.find((rule) => rule.code === pickerRuleCode.value);
|
||||
if (row) row.user_ids = [...userIds];
|
||||
pickerRuleCode.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从行内标签移除接收人,不必打开弹窗。
|
||||
*/
|
||||
function removeUser(ruleCode: string, userId: number): void {
|
||||
const row = rules.value.find((rule) => rule.code === ruleCode);
|
||||
if (!row) return;
|
||||
row.user_ids = row.user_ids.filter((id) => id !== userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载六行规则与候选人。
|
||||
*/
|
||||
async function loadConfig(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
const data = await getVoucherCheckNotifyConfig(profileCode.value);
|
||||
profileCode.value = data.profile_code || 'sales';
|
||||
rules.value = (data.rules || []).map((rule) => ({
|
||||
...rule,
|
||||
user_ids: Array.isArray(rule.user_ids) ? [...rule.user_ids] : [],
|
||||
}));
|
||||
users.value = data.users || [];
|
||||
updatedAt.value = data.updated_at || null;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('workspace.voucherCheck.notifyConfigLoadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存当前六行选人结果。
|
||||
*/
|
||||
async function saveConfig(): Promise<void> {
|
||||
saving.value = true;
|
||||
try {
|
||||
const recipients: Record<string, number[]> = {};
|
||||
for (const rule of rules.value) recipients[rule.code] = [...rule.user_ids];
|
||||
const data = await saveVoucherCheckNotifyConfig({
|
||||
profile_code: profileCode.value,
|
||||
recipients,
|
||||
});
|
||||
rules.value = (data.rules || []).map((rule) => ({
|
||||
...rule,
|
||||
user_ids: Array.isArray(rule.user_ids) ? [...rule.user_ids] : [],
|
||||
}));
|
||||
users.value = data.users || [];
|
||||
updatedAt.value = data.updated_at || null;
|
||||
msg.success(t('workspace.voucherCheck.notifyConfigSaved'));
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('workspace.voucherCheck.notifyConfigSaveFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadConfig();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="overflow-hidden rounded-2xl border border-default bg-surface">
|
||||
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-default px-4 py-3">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold text-primary">{{ t('workspace.voucherCheck.notifyConfigTitle') }}</h2>
|
||||
<p class="mt-1 text-sm text-muted">{{ t('workspace.voucherCheck.notifyConfigSubtitle') }}</p>
|
||||
<p v-if="updatedAt" class="mt-1 text-xs text-muted">
|
||||
{{ t('workspace.voucherCheck.notifyConfigUpdatedAt', { time: updatedAt }) }}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="loading || saving"
|
||||
@click="saveConfig"
|
||||
>
|
||||
<Loader2 v-if="saving" class="h-3.5 w-3.5 animate-spin" />
|
||||
{{ t('workspace.voucherCheck.notifyConfigSave') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="flex items-center justify-center gap-2 px-4 py-10 text-sm text-muted">
|
||||
<Loader2 class="h-4 w-4 animate-spin" />
|
||||
{{ t('workspace.voucherCheck.loading') }}
|
||||
</div>
|
||||
|
||||
<div v-else class="divide-y divide-default">
|
||||
<div
|
||||
v-for="rule in rules"
|
||||
:key="rule.code"
|
||||
class="grid gap-3 px-4 py-3 md:grid-cols-[220px_minmax(0,1fr)] md:items-center"
|
||||
>
|
||||
<div>
|
||||
<p class="text-sm font-semibold text-primary">{{ rule.name }}</p>
|
||||
<p class="mt-0.5 text-xs text-muted">
|
||||
{{ t('workspace.voucherCheck.notifyConfigFolder', { folder: rule.type_folder || '—' }) }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="inline-flex w-fit min-w-[18rem] max-w-full flex-wrap items-center gap-1.5 rounded-xl border border-default bg-surface px-2 py-1.5">
|
||||
<span
|
||||
v-for="userId in rule.user_ids"
|
||||
:key="userId"
|
||||
class="inline-flex items-center gap-1 rounded-lg bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700"
|
||||
>
|
||||
{{ userPickerLabel(userMap.get(userId), userId) }}
|
||||
<span
|
||||
v-if="userMap.get(userId) && !userMap.get(userId)?.wecom_bound"
|
||||
class="text-amber-600"
|
||||
>!</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-0.5 text-blue-400 hover:text-blue-600"
|
||||
@click="removeUser(rule.code, userId)"
|
||||
>✕</button>
|
||||
</span>
|
||||
<span v-if="rule.user_ids.length === 0" class="text-sm text-muted">
|
||||
{{ t('workspace.voucherCheck.notifyConfigEmptyUsers') }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto shrink-0 rounded-lg border border-blue-200 bg-blue-50 px-2.5 py-1 text-xs font-semibold text-brand-600 hover:bg-blue-100"
|
||||
@click="openPicker(rule.code)"
|
||||
>
|
||||
{{ t('common.userPicker.select') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UserPickerDialog
|
||||
v-model="pickerOpen"
|
||||
:users="users"
|
||||
:selected-ids="pickerSelectedIds"
|
||||
:title="t('workspace.voucherCheck.notifyConfigPickerTitle')"
|
||||
@confirm="applyPickerSelection"
|
||||
/>
|
||||
</article>
|
||||
</template>
|
||||
@@ -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];
|
||||
@@ -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',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<string, string> {
|
||||
const query: Record<string, string> = { view };
|
||||
if (runId) query.runId = String(runId);
|
||||
if (runId && runNo) query.runNo = runNo;
|
||||
return query;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<!--
|
||||
features/voucher-check/views/VoucherCheckChatRedirect.vue
|
||||
用途:把旧工作台立账凭证 URL 转到对应 Chat Agent 深链。
|
||||
依赖:listUserAgents、isVoucherCheckAgent、voucherCheckChat.utils。
|
||||
逻辑:按路径还原 view / runId / runNo,再在当前用户 Agent 列表中定位 voucher_check;
|
||||
未授权时提示并回应用管理。本页不渲染业务 UI。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { listUserAgents } from '@/features/auth/api/user.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { isVoucherCheckAgent } from '@/shared/utils/agent-registry.utils';
|
||||
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
|
||||
import type { VoucherCheckChatView } from '../constants';
|
||||
import { buildVoucherCheckChatQuery } from '../utils/voucherCheckChat.utils';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
/**
|
||||
* 从旧工作台路径还原 Chat Tab 与批次明细。
|
||||
* 核心逻辑:runs/:runId 进入当前 Tab 下钻;?run_id= 兼容旧列表深链;?view=notifications 打开发送记录。
|
||||
*/
|
||||
function resolveLegacyTarget(): {
|
||||
view: VoucherCheckChatView;
|
||||
runId: number | null;
|
||||
runNo: string | null;
|
||||
} {
|
||||
const path = String(route.path || '');
|
||||
const view: VoucherCheckChatView = String(route.query.view || '') === 'notifications'
|
||||
? 'notifications'
|
||||
: 'tasks';
|
||||
const runNo = typeof route.query.runNo === 'string' && route.query.runNo.trim()
|
||||
? route.query.runNo.trim()
|
||||
: null;
|
||||
const detailMatch = path.match(/\/accounting-voucher-check\/runs\/(\d+)/);
|
||||
if (detailMatch) {
|
||||
return { view, runId: Number(detailMatch[1]), runNo };
|
||||
}
|
||||
const queryRunId = Number(Array.isArray(route.query.run_id) ? route.query.run_id[0] : route.query.run_id);
|
||||
if (Number.isInteger(queryRunId) && queryRunId > 0) {
|
||||
return { view, runId: queryRunId, runNo };
|
||||
}
|
||||
return { view, runId: null, runNo: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找当前用户可用的立账凭证 Agent 并跳转 Chat。
|
||||
* 核心逻辑:admin 与已授权用户都能在 /api/agents 看到该 Agent;找不到则视为无权限。
|
||||
*/
|
||||
async function redirectToChat(): Promise<void> {
|
||||
const { view, runId, runNo } = resolveLegacyTarget();
|
||||
try {
|
||||
const agents = await listUserAgents();
|
||||
const agent = Array.isArray(agents) ? agents.find((item) => isVoucherCheckAgent(item)) : null;
|
||||
const agentId = Number(agent?.id);
|
||||
if (!Number.isInteger(agentId) || agentId <= 0) {
|
||||
msg.warning(t('errors.codes.VOUCHER_CHECK_FORBIDDEN'));
|
||||
await router.replace(WORKSPACE_PATHS.applications);
|
||||
return;
|
||||
}
|
||||
await router.replace({
|
||||
path: `/chat/${agentId}`,
|
||||
query: buildVoucherCheckChatQuery(view, runId, runNo),
|
||||
});
|
||||
} catch {
|
||||
msg.warning(t('errors.codes.VOUCHER_CHECK_FORBIDDEN'));
|
||||
await router.replace(WORKSPACE_PATHS.applications);
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void redirectToChat();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-h-[40vh] items-center justify-center text-sm text-muted">
|
||||
{{ t('chat.loadingAgent') }}
|
||||
</div>
|
||||
</template>
|
||||
@@ -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<VoucherCheckNotifyConfig>(
|
||||
`/api/workspace/accounting-voucher-check/notify-config${qs ? `?${qs}` : ''}`,
|
||||
{ headers: getAuthHeaders() },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存按文件类型的企微接收人(仅平台管理员)。
|
||||
*/
|
||||
export function saveVoucherCheckNotifyConfig(payload: {
|
||||
profile_code?: string;
|
||||
recipients: Record<string, number[]>;
|
||||
}) {
|
||||
return requestJson<VoucherCheckNotifyConfig>(
|
||||
'/api/workspace/accounting-voucher-check/notify-config',
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重检上一个自然月(不走增量跳过)。
|
||||
*/
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* features/workspace/constants/routes.ts
|
||||
* 工作台子路由 path 常量,以及旧 ?view= 查询参数到新 path 的映射。
|
||||
* 立账凭证批次明细:accountingVoucherCheckDetail(scheduleRunId)。
|
||||
* 立账凭证路径仍保留,供旧书签落到 Chat 重定向页。
|
||||
* 合同付款路径仍保留,供旧书签落到 Chat 重定向页。
|
||||
*/
|
||||
export const WORKSPACE_PATHS = {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/views/AccountingVoucherCheckView.vue
|
||||
* 用途:立账凭证检核任务列表——按资料所属期间(年 + 月)查看批次统计,并展示最近一次检核进度。
|
||||
* 用途:立账凭证检核任务列表——按资料所属期间(年 + 月)查看批次统计,并展示最近一次检核。
|
||||
* 依赖:voucherCheck.api、vue-i18n、useMessage、DeleteConfirmDialog、PaginationBar、formatLocalDateTime、voucherCheck.display、auth。
|
||||
* 逻辑:路由 /workspace/accounting-voucher-check;进页默认上一个自然月;「最近一次检核」不跟筛选;强制重检仅 admin,进度在本卡轮询。
|
||||
* Chat 嵌入时由 VoucherCheckChatPanel 传入 embedded / activeTab。
|
||||
* 逻辑:独立路由或 Chat 嵌入;进页默认上一个自然月;「最近一次检核」不跟筛选;强制重检仅 admin,进度在本卡轮询。
|
||||
* 终态用矮指标格;排队/执行中才展开进度条与当前步骤。Chat 嵌入时隐藏页头与内层 Tab。
|
||||
*/
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
@@ -32,6 +34,18 @@ import {
|
||||
voucherCheckStepLabel,
|
||||
} from '../utils/voucherCheck.display';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
embedded?: boolean;
|
||||
activeTab?: 'tasks' | 'notifications';
|
||||
}>(), {
|
||||
embedded: false,
|
||||
activeTab: 'tasks',
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'open-detail': [payload: { runId: number; runNo?: string | null }];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const route = useRoute();
|
||||
@@ -47,7 +61,7 @@ const pageSize = ref(50);
|
||||
const periodYear = ref('');
|
||||
const periodMonth = ref('');
|
||||
const status = ref('');
|
||||
const listTab = ref<'tasks' | 'notifications'>('tasks');
|
||||
const listTab = ref<'tasks' | 'notifications'>(props.activeTab);
|
||||
const notifyLoading = ref(false);
|
||||
const notifyItems = ref<VoucherCheckNotificationItem[]>([]);
|
||||
const notifyTotal = ref(0);
|
||||
@@ -74,6 +88,31 @@ const latestCanOpenDetail = computed(() => {
|
||||
return row.status === 'missing' || row.status === 'completed';
|
||||
});
|
||||
|
||||
/**
|
||||
* 最近一次检核的四个指标格,终态矮格与执行中共用。
|
||||
* 核心逻辑:缺件时后两项(缺件文件 / 缺件 invoice)标红。
|
||||
*/
|
||||
const latestMetrics = computed(() => {
|
||||
const row = latestRun.value;
|
||||
if (!row) return [];
|
||||
const warn = latestHasMissing.value;
|
||||
return [
|
||||
{ key: 'subject', value: row.subject_count, labelKey: 'workspace.voucherCheck.subjectCount', warn: false },
|
||||
{ key: 'archived', value: row.archived_file_count, labelKey: 'workspace.voucherCheck.archivedFiles', warn: false },
|
||||
{ key: 'missingFiles', value: row.missing_file_count, labelKey: 'workspace.voucherCheck.missingFiles', warn },
|
||||
{ key: 'missingInvoices', value: row.missing_invoice_count, labelKey: 'workspace.voucherCheck.missingInvoices', warn },
|
||||
];
|
||||
});
|
||||
|
||||
/**
|
||||
* 终态是否展示失败原因:仅技术失败或带 error_message 时占一行,完整/缺件不再重复完成提示。
|
||||
*/
|
||||
const latestShowFailureHint = computed(() => {
|
||||
const row = latestRun.value;
|
||||
if (!row || latestInProgress.value) return false;
|
||||
return row.status === 'technical_failed' || Boolean(row.error_message);
|
||||
});
|
||||
|
||||
const MONTH_VALUES = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] as const;
|
||||
|
||||
/**
|
||||
@@ -218,6 +257,20 @@ function formatRecipientNames(names?: string[]): string {
|
||||
return names.join('、');
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开批次明细:Chat 嵌入时回传父级,独立页则跳转工作台详情路由。
|
||||
*/
|
||||
function navigateToDetail(runId: number, runNo?: string | null) {
|
||||
if (props.embedded) {
|
||||
emit('open-detail', { runId, runNo: runNo || null });
|
||||
return;
|
||||
}
|
||||
void router.push({
|
||||
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(runId),
|
||||
query: runNo ? { runNo } : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从发送记录跳转对应批次明细。
|
||||
* @param row - 企微发送记录
|
||||
@@ -227,10 +280,7 @@ function openNotifyDetail(row: VoucherCheckNotificationItem) {
|
||||
msg.error(t('workspace.voucherCheck.loadFailed'));
|
||||
return;
|
||||
}
|
||||
void router.push({
|
||||
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(row.schedule_run_id),
|
||||
query: row.run_no ? { runNo: row.run_no } : undefined,
|
||||
});
|
||||
navigateToDetail(row.schedule_run_id, row.run_no);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,10 +324,7 @@ function openRunDetail(row: VoucherCheckRunItem) {
|
||||
msg.error(t('workspace.voucherCheck.loadFailed'));
|
||||
return;
|
||||
}
|
||||
void router.push({
|
||||
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(row.schedule_run_id),
|
||||
query: row.run_no ? { runNo: row.run_no } : undefined,
|
||||
});
|
||||
navigateToDetail(row.schedule_run_id, row.run_no);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -406,10 +453,7 @@ function openLatestDetail() {
|
||||
msg.error(t('workspace.voucherCheck.loadFailed'));
|
||||
return;
|
||||
}
|
||||
void router.push({
|
||||
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(row.schedule_run_id),
|
||||
query: row.run_no ? { runNo: row.run_no } : undefined,
|
||||
});
|
||||
navigateToDetail(row.schedule_run_id, row.run_no);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -419,13 +463,27 @@ watch([listTab, latestInProgress], () => {
|
||||
syncLatestPoll();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => props.activeTab,
|
||||
(tab) => {
|
||||
if (!props.embedded) return;
|
||||
if (listTab.value === tab) return;
|
||||
setListTab(tab);
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(async () => {
|
||||
if (redirectLegacyRunQuery()) return;
|
||||
if (!props.embedded && redirectLegacyRunQuery()) return;
|
||||
const previous = previousYearMonth();
|
||||
periodYear.value = previous.year;
|
||||
periodMonth.value = previous.month;
|
||||
const qStatus = route.query.status;
|
||||
if (typeof qStatus === 'string' && qStatus) status.value = qStatus;
|
||||
if (props.embedded) listTab.value = props.activeTab;
|
||||
if (listTab.value === 'notifications') {
|
||||
await loadNotifications();
|
||||
return;
|
||||
}
|
||||
await Promise.all([loadRuns(), loadLatestRun()]);
|
||||
});
|
||||
|
||||
@@ -435,13 +493,13 @@ onUnmounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-5 animate-fade-in-up">
|
||||
<header class="space-y-1">
|
||||
<div class="space-y-4 animate-fade-in-up">
|
||||
<header v-if="!embedded" class="space-y-1">
|
||||
<h1 class="text-2xl font-bold text-primary">{{ $t('workspace.voucherCheck.title') }}</h1>
|
||||
<p class="text-sm text-muted">{{ $t('workspace.voucherCheck.subtitle') }}</p>
|
||||
</header>
|
||||
|
||||
<div class="flex gap-1 border-b border-default" role="tablist">
|
||||
<div v-if="!embedded" class="flex gap-1 border-b border-default" role="tablist">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
@@ -469,19 +527,30 @@ onUnmounted(() => {
|
||||
class="overflow-hidden rounded-2xl border border-default bg-surface"
|
||||
aria-live="polite"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-3 bg-blue-50 px-4 py-3.5">
|
||||
<div
|
||||
class="flex flex-wrap items-start justify-between gap-3 px-4 py-2.5"
|
||||
:class="latestInProgress ? 'bg-blue-50' : ''"
|
||||
>
|
||||
<div>
|
||||
<h2 class="text-[15px] font-semibold text-primary">{{ $t('workspace.voucherCheck.latestTitle') }}</h2>
|
||||
<p v-if="latestRun" class="mt-1 text-xs text-muted">
|
||||
<h2 class="text-sm font-semibold text-primary">{{ $t('workspace.voucherCheck.latestTitle') }}</h2>
|
||||
<p v-if="latestRun" class="mt-0.5 text-xs text-muted">
|
||||
<span class="mr-3">{{ $t('workspace.voucherCheck.latestBatch', { runNo: latestRun.run_no }) }}</span>
|
||||
<span class="mr-3">{{ $t('workspace.voucherCheck.latestPeriod', { period: latestRun.period_month || '-' }) }}</span>
|
||||
<span>{{ voucherCheckModeLabel(t, latestRun.mode) }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
v-if="latestCanOpenDetail"
|
||||
type="button"
|
||||
class="text-sm font-semibold text-brand-700 hover:underline"
|
||||
@click="openLatestDetail"
|
||||
>
|
||||
{{ $t('workspace.voucherCheck.viewLatestDetail') }}
|
||||
</button>
|
||||
<span
|
||||
v-if="latestRun"
|
||||
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
|
||||
class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold"
|
||||
:class="latestBadgeClass(latestRun.status)"
|
||||
>
|
||||
{{ voucherCheckStatusLabel(t, latestRun.status) }}
|
||||
@@ -499,67 +568,50 @@ onUnmounted(() => {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="px-4 py-3.5">
|
||||
<div v-if="latestLoading && !latestRun" class="flex items-center justify-center gap-2 py-8 text-sm text-muted">
|
||||
<Loader2 class="h-4 w-4 animate-spin" />
|
||||
{{ $t('workspace.voucherCheck.loading') }}
|
||||
</div>
|
||||
<p v-else-if="!latestRun" class="py-8 text-center text-sm text-muted">
|
||||
{{ $t('workspace.voucherCheck.latestEmpty') }}
|
||||
</p>
|
||||
<template v-else>
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
|
||||
<div v-if="latestLoading && !latestRun" class="flex items-center justify-center gap-2 px-4 py-6 text-sm text-muted">
|
||||
<Loader2 class="h-4 w-4 animate-spin" />
|
||||
{{ $t('workspace.voucherCheck.loading') }}
|
||||
</div>
|
||||
<p v-else-if="!latestRun" class="px-4 py-6 text-center text-sm text-muted">
|
||||
{{ $t('workspace.voucherCheck.latestEmpty') }}
|
||||
</p>
|
||||
<div v-else class="px-4 pb-3">
|
||||
<template v-if="latestInProgress">
|
||||
<div class="h-2 overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full transition-[width] duration-300"
|
||||
:class="latestRun.status === 'technical_failed' ? 'bg-rose-600' : 'bg-teal-700'"
|
||||
class="h-full rounded-full bg-teal-700 transition-[width] duration-300"
|
||||
:style="{ width: `${latestRun.progress_percent || 0}%` }"
|
||||
/>
|
||||
</div>
|
||||
<div class="mt-2 mb-3.5 flex flex-wrap justify-between gap-3 text-xs text-muted">
|
||||
<div class="mt-1.5 mb-2.5 flex flex-wrap justify-between gap-3 text-xs text-muted">
|
||||
<span>{{ $t('workspace.voucherCheck.progress', { percent: latestRun.progress_percent || 0 }) }}</span>
|
||||
<span>
|
||||
{{ $t('workspace.voucherCheck.startedAt') }}:{{ formatLocalDateTime(latestRun.started_at) }}
|
||||
{{ $t('workspace.voucherCheck.finishedAt') }}:{{ latestInProgress ? $t('workspace.voucherCheck.inProgress') : formatLocalDateTime(latestRun.finished_at) }}
|
||||
{{ $t('workspace.voucherCheck.finishedAt') }}:{{ $t('workspace.voucherCheck.inProgress') }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-2 md:grid-cols-4">
|
||||
<div class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-3">
|
||||
<b class="block text-[22px] font-semibold leading-tight text-primary">{{ latestRun.subject_count }}</b>
|
||||
<span class="text-xs text-muted">{{ $t('workspace.voucherCheck.subjectCount') }}</span>
|
||||
</div>
|
||||
<div class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-3">
|
||||
<b class="block text-[22px] font-semibold leading-tight text-primary">{{ latestRun.archived_file_count }}</b>
|
||||
<span class="text-xs text-muted">{{ $t('workspace.voucherCheck.archivedFiles') }}</span>
|
||||
</div>
|
||||
<div class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-3">
|
||||
<b
|
||||
class="block text-[22px] font-semibold leading-tight"
|
||||
:class="latestHasMissing ? 'text-rose-700' : 'text-primary'"
|
||||
>{{ latestRun.missing_file_count }}</b>
|
||||
<span class="text-xs text-muted">{{ $t('workspace.voucherCheck.missingFiles') }}</span>
|
||||
</div>
|
||||
<div class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-3">
|
||||
<b
|
||||
class="block text-[22px] font-semibold leading-tight"
|
||||
:class="latestHasMissing ? 'text-rose-700' : 'text-primary'"
|
||||
>{{ latestRun.missing_invoice_count }}</b>
|
||||
<span class="text-xs text-muted">{{ $t('workspace.voucherCheck.missingInvoices') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-3 text-[13px] text-slate-700">
|
||||
<p class="mb-2.5 text-[13px] text-slate-700">
|
||||
{{ latestStepText(latestRun) }}
|
||||
<small v-if="latestHintText(latestRun)" class="mt-0.5 block text-muted">{{ latestHintText(latestRun) }}</small>
|
||||
</p>
|
||||
<div v-if="latestCanOpenDetail" class="mt-3 flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class="text-sm font-semibold text-brand-700 hover:underline"
|
||||
@click="openLatestDetail"
|
||||
>
|
||||
{{ $t('workspace.voucherCheck.viewLatestDetail') }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
<div class="grid grid-cols-2 gap-2 md:grid-cols-4">
|
||||
<div
|
||||
v-for="metric in latestMetrics"
|
||||
:key="metric.key"
|
||||
class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-2"
|
||||
>
|
||||
<b
|
||||
class="block text-lg font-semibold leading-tight tabular-nums"
|
||||
:class="metric.warn ? 'text-rose-700' : 'text-primary'"
|
||||
>{{ metric.value }}</b>
|
||||
<span class="text-[11px] text-muted">{{ $t(metric.labelKey) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="latestShowFailureHint" class="mt-2 text-[13px] text-slate-700">
|
||||
{{ latestStepText(latestRun) }}
|
||||
<small v-if="latestHintText(latestRun)" class="mt-0.5 block text-muted">{{ latestHintText(latestRun) }}</small>
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
|
||||
@@ -2370,7 +2370,9 @@
|
||||
"voucherCheckScope": "Ledger scope",
|
||||
"voucherCheckProfile": "Business profile",
|
||||
"voucherCheckNotifyMissing": "Notify on missing materials",
|
||||
"voucherCheckNotifyFailure": "Failure alert"
|
||||
"voucherCheckNotifyMissingHint": "Master switch. Set missing-file recipients in Chat “Accounting voucher check → Notification config” by file type. The schedule people picker is only for failure alerts.",
|
||||
"voucherCheckNotifyFailure": "Failure alert",
|
||||
"voucherCheckNotifyFailureHint": "Technical failures go to the people selected below."
|
||||
},
|
||||
"testRun": {
|
||||
"title": "Test run — {name}",
|
||||
|
||||
@@ -40,6 +40,9 @@
|
||||
},
|
||||
"agentId": "Agent ID:",
|
||||
"loadingAgent": "Loading agent...",
|
||||
"taskAgent": {
|
||||
"sessionHint": "Chat and history are hidden in this phase. Use the tabs above to open the workspace."
|
||||
},
|
||||
"thinking": "Generating response...",
|
||||
"stopGenerating": "Stop generating",
|
||||
"disclaimer": "AI can make mistakes. Please verify important information.",
|
||||
|
||||
@@ -44,5 +44,22 @@
|
||||
"asc": "Ascending, click for descending",
|
||||
"desc": "Descending, click for ascending"
|
||||
},
|
||||
"required": "This field is required"
|
||||
"required": "This field is required",
|
||||
"userPicker": {
|
||||
"title": "Select people",
|
||||
"subtitle": "Filter by department, or search by name or employee ID.",
|
||||
"subtitleWithWecom": "Filter by department, or search by name or employee ID. People without WeCom can still be selected; they are skipped when sending.",
|
||||
"searchPlaceholder": "Search name / employee ID",
|
||||
"allDepartments": "All",
|
||||
"unknownDepartment": "No department",
|
||||
"selectDepartment": "Select this department",
|
||||
"selectVisible": "Select all in view",
|
||||
"select": "Select",
|
||||
"empty": "No matching people",
|
||||
"noneSelected": "None selected",
|
||||
"emptyTrigger": "None selected",
|
||||
"confirmCount": "OK ({count})",
|
||||
"wecomBound": "WeCom bound",
|
||||
"wecomUnbound": "WeCom not bound"
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,8 @@
|
||||
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "Too many attachments (maximum 200). Remove some and try again.",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "Only administrators can sync, scan, or send contract payment alerts.",
|
||||
"VOUCHER_CHECK_FORBIDDEN": "You do not have access to accounting voucher check.",
|
||||
"VOUCHER_CHECK_ADMIN_REQUIRED": "Only administrators can force a voucher recheck or change missing-file notification recipients.",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "Select between 1 and 100 shipping tasks.",
|
||||
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "A reason is required to delete or void tasks.",
|
||||
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "The task is uploading externally or has been uploaded. It can only be archived.",
|
||||
|
||||
@@ -859,6 +859,20 @@
|
||||
"stepDone": "Check complete",
|
||||
"tabTasks": "Check tasks",
|
||||
"tabNotifications": "WeCom send log",
|
||||
"tabNotifyConfig": "Notification config",
|
||||
"notifyConfigTitle": "Recipients by file type",
|
||||
"notifyConfigSubtitle": "The six file types can go to different teams. Each person only sees the missing types they own; the Excel file remains the full detail. The schedule “Enable notifications” switch is the master on/off; the schedule people picker is only for failure alerts.",
|
||||
"notifyConfigSave": "Save",
|
||||
"notifyConfigSaved": "Notification config saved",
|
||||
"notifyConfigLoadFailed": "Failed to load notification config",
|
||||
"notifyConfigSaveFailed": "Failed to save notification config",
|
||||
"notifyConfigSelectUsers": "Select recipients…",
|
||||
"notifyConfigPickerTitle": "Select recipients",
|
||||
"notifyConfigEmptyUsers": "No recipients selected",
|
||||
"notifyConfigNoUsers": "No matching users",
|
||||
"notifyConfigWecomUnbound": "WeCom not bound",
|
||||
"notifyConfigFolder": "Type folder {folder}",
|
||||
"notifyConfigUpdatedAt": "Last saved {time}",
|
||||
"notifyEmpty": "No WeCom send records yet",
|
||||
"notifyLoadFailed": "Failed to load send records",
|
||||
"notifyStatus": "Send status",
|
||||
|
||||
@@ -2248,7 +2248,9 @@
|
||||
"voucherCheckScope": "ชุดบัญชี",
|
||||
"voucherCheckProfile": "โปรไฟล์ฝ่ายธุรกิจ",
|
||||
"voucherCheckNotifyMissing": "แจ้งเตือนเมื่อขาดเอกสาร",
|
||||
"voucherCheckNotifyFailure": "แจ้งเตือนเมื่อล้มเหลว"
|
||||
"voucherCheckNotifyMissingHint": "สวิตช์หลัก กำหนดผู้รับไฟล์ขาดในแชท 「ตรวจเอกสารบัญชี → ตั้งค่าการแจ้งเตือน」 ตามประเภทไฟล์ การเลือกคนด้านล่างใช้สำหรับแจ้งเตือนเมื่อล้มเหลวเท่านั้น",
|
||||
"voucherCheckNotifyFailure": "แจ้งเตือนเมื่อล้มเหลว",
|
||||
"voucherCheckNotifyFailureHint": "เมื่อล้มเหลวทางเทคนิคจะส่งให้ผู้ที่เลือกด้านล่าง"
|
||||
},
|
||||
"status": {
|
||||
"all": "ทุกสถานะ",
|
||||
|
||||
@@ -40,6 +40,9 @@
|
||||
},
|
||||
"agentId": "รหัสตัวแทน:",
|
||||
"loadingAgent": "กำลังโหลดตัวแทน...",
|
||||
"taskAgent": {
|
||||
"sessionHint": "ระยะนี้ยังไม่ใช้แชทและประวัติการสนทนา เปิดเนื้อหาจากแท็บด้านบน"
|
||||
},
|
||||
"thinking": "กำลังสร้างคำตอบ...",
|
||||
"stopGenerating": "หยุดสร้างคำตอบ",
|
||||
"disclaimer": "AI อาจทำผิดพลาดได้ โปรดตรวจสอบข้อมูลสำคัญ",
|
||||
|
||||
@@ -44,5 +44,22 @@
|
||||
"asc": "เรียงจากน้อยไปมาก คลิกเพื่อสลับ",
|
||||
"desc": "เรียงจากมากไปน้อย คลิกเพื่อสลับ"
|
||||
},
|
||||
"required": "กรุณากรอกข้อมูลที่จำเป็น"
|
||||
"required": "กรุณากรอกข้อมูลที่จำเป็น",
|
||||
"userPicker": {
|
||||
"title": "เลือกผู้ใช้",
|
||||
"subtitle": "กรองตามแผนก หรือค้นหาด้วยชื่อ / รหัสพนักงาน",
|
||||
"subtitleWithWecom": "กรองตามแผนก หรือค้นหาด้วยชื่อ / รหัสพนักงาน คนที่ยังไม่ผูก WeCom เลือกได้ แต่ตอนส่งจะข้าม",
|
||||
"searchPlaceholder": "ค้นหาชื่อ / รหัสพนักงาน",
|
||||
"allDepartments": "ทั้งหมด",
|
||||
"unknownDepartment": "ไม่มีแผนก",
|
||||
"selectDepartment": "เลือกทั้งแผนก",
|
||||
"selectVisible": "เลือกทั้งหมดในรายการนี้",
|
||||
"select": "เลือก",
|
||||
"empty": "ไม่พบผู้ใช้ที่ตรงกัน",
|
||||
"noneSelected": "ยังไม่ได้เลือก",
|
||||
"emptyTrigger": "ยังไม่ได้เลือก",
|
||||
"confirmCount": "ตกลง ({count})",
|
||||
"wecomBound": "ผูก WeCom แล้ว",
|
||||
"wecomUnbound": "ยังไม่ผูก WeCom"
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,8 @@
|
||||
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "ไฟล์แนบเกินจำนวนที่อนุญาต (สูงสุด 200 ไฟล์) โปรดลดจำนวนแล้วลองใหม่",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ สแกน หรือส่งการแจ้งเตือนการชำระเงินตามสัญญาได้",
|
||||
"VOUCHER_CHECK_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการตรวจเอกสารบัญชี",
|
||||
"VOUCHER_CHECK_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่บังคับตรวจเอกสารบัญชีใหม่ หรือแก้ผู้รับการแจ้งเตือนไฟล์ขาดได้",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "เลือกงานจัดส่งได้ 1 ถึง 100 งาน",
|
||||
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "ต้องระบุเหตุผลในการลบหรือยกเลิกงาน",
|
||||
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "งานกำลังอัปโหลดภายนอกหรืออัปโหลดแล้ว จึงทำได้เพียงเก็บถาวร",
|
||||
|
||||
@@ -795,6 +795,20 @@
|
||||
"stepDone": "ตรวจเสร็จแล้ว",
|
||||
"tabTasks": "งานตรวจ",
|
||||
"tabNotifications": "ประวัติส่ง WeCom",
|
||||
"tabNotifyConfig": "ตั้งค่าการแจ้งเตือน",
|
||||
"notifyConfigTitle": "กำหนดผู้รับตามประเภทไฟล์",
|
||||
"notifyConfigSubtitle": "ไฟล์ 6 ประเภทอาจเป็นคนละแผนก ผู้รับแต่ละคนจะเห็นเฉพาะประเภทที่ขาดซึ่งตนรับผิดชอบ ส่วนรายละเอียดเต็มยังอยู่ใน Excel สวิตช์ “เปิดการแจ้งเตือน” ในตารางงานเป็นสวิตช์หลัก การเลือกคนในตารางงานใช้สำหรับแจ้งเตือนเมื่อล้มเหลวเท่านั้น",
|
||||
"notifyConfigSave": "บันทึก",
|
||||
"notifyConfigSaved": "บันทึกการตั้งค่าการแจ้งเตือนแล้ว",
|
||||
"notifyConfigLoadFailed": "โหลดการตั้งค่าการแจ้งเตือนไม่สำเร็จ",
|
||||
"notifyConfigSaveFailed": "บันทึกการตั้งค่าการแจ้งเตือนไม่สำเร็จ",
|
||||
"notifyConfigSelectUsers": "เลือกผู้รับ…",
|
||||
"notifyConfigPickerTitle": "เลือกผู้รับ",
|
||||
"notifyConfigEmptyUsers": "ยังไม่ได้เลือกผู้รับ",
|
||||
"notifyConfigNoUsers": "ไม่พบผู้ใช้ที่ตรงกัน",
|
||||
"notifyConfigWecomUnbound": "ยังไม่ผูก WeCom",
|
||||
"notifyConfigFolder": "โฟลเดอร์ประเภท {folder}",
|
||||
"notifyConfigUpdatedAt": "บันทึกล่าสุด {time}",
|
||||
"notifyEmpty": "ยังไม่มีประวัติส่ง WeCom",
|
||||
"notifyLoadFailed": "โหลดประวัติส่งไม่สำเร็จ",
|
||||
"notifyStatus": "สถานะการส่ง",
|
||||
|
||||
@@ -2482,7 +2482,9 @@
|
||||
"voucherCheckScope": "账套",
|
||||
"voucherCheckProfile": "业务方 Profile",
|
||||
"voucherCheckNotifyMissing": "缺资料通知",
|
||||
"voucherCheckNotifyFailure": "失败告警"
|
||||
"voucherCheckNotifyMissingHint": "总开关。缺件接收人请到 Chat「立账凭证 → 通知配置」按文件类型设置;排程选人只用于技术失败告警。",
|
||||
"voucherCheckNotifyFailure": "失败告警",
|
||||
"voucherCheckNotifyFailureHint": "技术失败发给下方「选择通知人员」。"
|
||||
},
|
||||
"testRun": {
|
||||
"title": "测试执行 — {name}",
|
||||
|
||||
@@ -40,6 +40,9 @@
|
||||
},
|
||||
"agentId": "应用 ID:",
|
||||
"loadingAgent": "正在加载应用...",
|
||||
"taskAgent": {
|
||||
"sessionHint": "本期不使用对话和历史会话,请从上方 Tab 查看内容。"
|
||||
},
|
||||
"thinking": "正在生成回答...",
|
||||
"stopGenerating": "停止生成",
|
||||
"disclaimer": "AI 可能会犯错,请核实重要信息。",
|
||||
|
||||
@@ -44,5 +44,22 @@
|
||||
"asc": "升序,点击切换为降序",
|
||||
"desc": "降序,点击切换为升序"
|
||||
},
|
||||
"required": "请填写必填项"
|
||||
"required": "请填写必填项",
|
||||
"userPicker": {
|
||||
"title": "选择人员",
|
||||
"subtitle": "可按部门筛选,或直接搜索姓名、工号。",
|
||||
"subtitleWithWecom": "可按部门筛选,或直接搜索姓名、工号。未绑定企微的人可勾选,发送时会跳过。",
|
||||
"searchPlaceholder": "搜索姓名 / 工号",
|
||||
"allDepartments": "全部",
|
||||
"unknownDepartment": "未分配部门",
|
||||
"selectDepartment": "全选本部门",
|
||||
"selectVisible": "全选当前列表",
|
||||
"select": "选择",
|
||||
"empty": "没有匹配的人员",
|
||||
"noneSelected": "尚未选择",
|
||||
"emptyTrigger": "未选择",
|
||||
"confirmCount": "确定({count})",
|
||||
"wecomBound": "已绑企微",
|
||||
"wecomUnbound": "未绑定企微"
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,8 @@
|
||||
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件数量超过上限(最多 200 个),请减少后重试。",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "仅管理员可执行合同付款预警的同步、扫描或发送操作。",
|
||||
"VOUCHER_CHECK_FORBIDDEN": "你没有立账凭证检核的访问权限。",
|
||||
"VOUCHER_CHECK_ADMIN_REQUIRED": "仅管理员可强制重检或修改立账凭证通知配置。",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "请选择 1 到 100 个发货任务。",
|
||||
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "删除或作废任务必须填写原因。",
|
||||
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "任务正在外部上传或已上传,只能归档,不能作废或删除。",
|
||||
|
||||
@@ -859,6 +859,20 @@
|
||||
"stepDone": "检核完成",
|
||||
"tabTasks": "检核任务",
|
||||
"tabNotifications": "企微发送记录",
|
||||
"tabNotifyConfig": "通知配置",
|
||||
"notifyConfigTitle": "按文件类型配置缺件接收人",
|
||||
"notifyConfigSubtitle": "六类文件可由不同部门接收。每人只收到自己负责且本批缺失的类型;完整明细仍以 Excel 为准。排程里的「启用通知」是总开关,选人只用于技术失败告警。",
|
||||
"notifyConfigSave": "保存",
|
||||
"notifyConfigSaved": "通知配置已保存",
|
||||
"notifyConfigLoadFailed": "加载通知配置失败",
|
||||
"notifyConfigSaveFailed": "保存通知配置失败",
|
||||
"notifyConfigSelectUsers": "选择接收人…",
|
||||
"notifyConfigPickerTitle": "选择接收人",
|
||||
"notifyConfigEmptyUsers": "未选择接收人",
|
||||
"notifyConfigNoUsers": "没有匹配的用户",
|
||||
"notifyConfigWecomUnbound": "未绑定企微",
|
||||
"notifyConfigFolder": "类型目录 {folder}",
|
||||
"notifyConfigUpdatedAt": "最近保存 {time}",
|
||||
"notifyEmpty": "暂无企业微信发送记录",
|
||||
"notifyLoadFailed": "加载发送记录失败",
|
||||
"notifyStatus": "发送状态",
|
||||
|
||||
@@ -2253,7 +2253,9 @@
|
||||
"voucherCheckScope": "帳套",
|
||||
"voucherCheckProfile": "業務方 Profile",
|
||||
"voucherCheckNotifyMissing": "缺資料通知",
|
||||
"voucherCheckNotifyFailure": "失敗告警"
|
||||
"voucherCheckNotifyMissingHint": "總開關。缺件接收人請到 Chat「立帳憑證 → 通知設定」依檔案類型設定;排程選人只用於技術失敗告警。",
|
||||
"voucherCheckNotifyFailure": "失敗告警",
|
||||
"voucherCheckNotifyFailureHint": "技術失敗會發給下方「選擇通知人員」。"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部狀態",
|
||||
|
||||
@@ -40,6 +40,9 @@
|
||||
},
|
||||
"agentId": "應用 ID:",
|
||||
"loadingAgent": "正在加載應用...",
|
||||
"taskAgent": {
|
||||
"sessionHint": "本期不使用對話和歷史會話,請從上方 Tab 查看內容。"
|
||||
},
|
||||
"thinking": "正在生成回答...",
|
||||
"stopGenerating": "停止生成",
|
||||
"disclaimer": "AI 可能會犯錯,請核實重要信息。",
|
||||
|
||||
@@ -44,5 +44,22 @@
|
||||
"asc": "升序,點擊切換為降序",
|
||||
"desc": "降序,點擊切換為升序"
|
||||
},
|
||||
"required": "請填寫必填欄位"
|
||||
"required": "請填寫必填欄位",
|
||||
"userPicker": {
|
||||
"title": "選擇人員",
|
||||
"subtitle": "可依部門篩選,或直接搜尋姓名、工號。",
|
||||
"subtitleWithWecom": "可依部門篩選,或直接搜尋姓名、工號。未綁定企微的人可勾選,發送時會略過。",
|
||||
"searchPlaceholder": "搜尋姓名 / 工號",
|
||||
"allDepartments": "全部",
|
||||
"unknownDepartment": "未分配部門",
|
||||
"selectDepartment": "全選本部門",
|
||||
"selectVisible": "全選目前列表",
|
||||
"select": "選擇",
|
||||
"empty": "沒有符合的人員",
|
||||
"noneSelected": "尚未選擇",
|
||||
"emptyTrigger": "未選擇",
|
||||
"confirmCount": "確定({count})",
|
||||
"wecomBound": "已綁企微",
|
||||
"wecomUnbound": "未綁定企微"
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,8 @@
|
||||
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件數量超過上限(最多 200 個),請減少後重試。",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "僅管理員可執行合約付款預警的同步、掃描或發送操作。",
|
||||
"VOUCHER_CHECK_FORBIDDEN": "你沒有立帳憑證檢核的存取權限。",
|
||||
"VOUCHER_CHECK_ADMIN_REQUIRED": "僅管理員可強制重檢或修改立帳憑證通知設定。",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "請選擇 1 到 100 個發貨任務。",
|
||||
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "刪除或作廢任務必須填寫原因。",
|
||||
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "任務正在外部上傳或已上傳,只能歸檔,不能作廢或刪除。",
|
||||
|
||||
@@ -859,6 +859,20 @@
|
||||
"stepDone": "檢核完成",
|
||||
"tabTasks": "檢核任務",
|
||||
"tabNotifications": "企微發送紀錄",
|
||||
"tabNotifyConfig": "通知設定",
|
||||
"notifyConfigTitle": "依檔案類型設定缺件接收人",
|
||||
"notifyConfigSubtitle": "六類文件可由不同部門接收。每人只會收到自己負責且本批缺失的類型;完整明細仍以 Excel 為準。排程裡的「啟用通知」是總開關,選人只用於技術失敗告警。",
|
||||
"notifyConfigSave": "儲存",
|
||||
"notifyConfigSaved": "通知設定已儲存",
|
||||
"notifyConfigLoadFailed": "載入通知設定失敗",
|
||||
"notifyConfigSaveFailed": "儲存通知設定失敗",
|
||||
"notifyConfigSelectUsers": "選擇接收人…",
|
||||
"notifyConfigPickerTitle": "選擇接收人",
|
||||
"notifyConfigEmptyUsers": "未選擇接收人",
|
||||
"notifyConfigNoUsers": "沒有符合的使用者",
|
||||
"notifyConfigWecomUnbound": "未綁定企微",
|
||||
"notifyConfigFolder": "類型目錄 {folder}",
|
||||
"notifyConfigUpdatedAt": "最近儲存 {time}",
|
||||
"notifyEmpty": "暫無企業微信發送紀錄",
|
||||
"notifyLoadFailed": "載入發送紀錄失敗",
|
||||
"notifyStatus": "發送狀態",
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* shared/components/UserPickerDialog.vue
|
||||
* 用途:跨业务公共选人弹窗:左侧部门、右侧搜索/勾选、底部已选与确定。
|
||||
* 依赖:vue-i18n、dialog-overlay / dialog-panel、userPicker.types / userPicker.utils。
|
||||
* 逻辑:父组件传入候选人并 v-model 控制显隐;确定才回写 selectedIds,取消不改已保存选择。
|
||||
* 不自行拉用户列表,便于凭证检核、排程告警等各自提供数据源。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
USER_PICKER_ALL_DEPT,
|
||||
USER_PICKER_NONE_DEPT,
|
||||
type UserPickerPerson,
|
||||
} from '@/shared/types/userPicker.types';
|
||||
import {
|
||||
filterUserPickerPeople,
|
||||
listUserPickerDepartments,
|
||||
userPickerLabel,
|
||||
} from '@/shared/utils/userPicker.utils';
|
||||
|
||||
interface Props {
|
||||
modelValue: boolean;
|
||||
users: UserPickerPerson[];
|
||||
selectedIds: number[];
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
/** 为 true 强制展示企微标记;为 false 隐藏;缺省时有 wecom_bound 字段才展示 */
|
||||
showWecomStatus?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
users: () => [],
|
||||
selectedIds: () => [],
|
||||
title: '',
|
||||
subtitle: '',
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void;
|
||||
(e: 'confirm', ids: number[]): void;
|
||||
(e: 'cancel'): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const query = ref('');
|
||||
const departmentKey = ref(USER_PICKER_ALL_DEPT);
|
||||
const draftIds = ref<number[]>([]);
|
||||
|
||||
const userMap = computed(() => {
|
||||
const next = new Map<number, UserPickerPerson>();
|
||||
for (const user of props.users) next.set(user.id, user);
|
||||
return next;
|
||||
});
|
||||
|
||||
const departments = computed(() => listUserPickerDepartments(props.users));
|
||||
|
||||
const visibleUsers = computed(() =>
|
||||
filterUserPickerPeople(props.users, {
|
||||
departmentKey: departmentKey.value,
|
||||
query: query.value,
|
||||
}),
|
||||
);
|
||||
|
||||
const showWecom = computed(() => {
|
||||
if (props.showWecomStatus === true) return true;
|
||||
if (props.showWecomStatus === false) return false;
|
||||
return props.users.some((user) => typeof user.wecom_bound === 'boolean');
|
||||
});
|
||||
|
||||
const resolvedTitle = computed(() => props.title || t('common.userPicker.title'));
|
||||
const resolvedSubtitle = computed(() => {
|
||||
if (props.subtitle) return props.subtitle;
|
||||
return showWecom.value ? t('common.userPicker.subtitleWithWecom') : t('common.userPicker.subtitle');
|
||||
});
|
||||
|
||||
const visibleAllSelected = computed(() => {
|
||||
const ids = visibleUsers.value.map((user) => user.id);
|
||||
return ids.length > 0 && ids.every((id) => draftIds.value.includes(id));
|
||||
});
|
||||
|
||||
/**
|
||||
* 「全部」或有搜索时用「全选当前列表」;点了具体部门且未搜索时用「全选本部门」。
|
||||
*/
|
||||
const selectVisibleLabel = computed(() => {
|
||||
const scopedToDept =
|
||||
departmentKey.value !== USER_PICKER_ALL_DEPT && !String(query.value || '').trim();
|
||||
return t(scopedToDept ? 'common.userPicker.selectDepartment' : 'common.userPicker.selectVisible');
|
||||
});
|
||||
|
||||
/**
|
||||
* 把传入 id 收成去重正整数,打开弹窗时作为草稿。
|
||||
*/
|
||||
function normalizeIds(ids: number[]): number[] {
|
||||
const seen = new Set<number>();
|
||||
const next: number[] = [];
|
||||
for (const raw of ids || []) {
|
||||
const id = Number(raw);
|
||||
if (!Number.isInteger(id) || id <= 0 || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
next.push(id);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* 部门筛选项展示名:全部 / 未分配 / 具名部门。
|
||||
*/
|
||||
function departmentLabel(key: string): string {
|
||||
if (key === USER_PICKER_ALL_DEPT) return t('common.userPicker.allDepartments');
|
||||
if (key === USER_PICKER_NONE_DEPT) return t('common.userPicker.unknownDepartment');
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 人员第二行:工号 · 部门。
|
||||
*/
|
||||
function personMeta(person: UserPickerPerson): string {
|
||||
const emp = String(person.employee_id || '').trim();
|
||||
const dept = String(person.department || '').trim() || t('common.userPicker.unknownDepartment');
|
||||
return [emp, dept].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 勾选或取消单个候选人,保留点击顺序。
|
||||
*/
|
||||
function toggleUser(userId: number): void {
|
||||
if (draftIds.value.includes(userId)) {
|
||||
draftIds.value = draftIds.value.filter((id) => id !== userId);
|
||||
return;
|
||||
}
|
||||
draftIds.value = [...draftIds.value, userId];
|
||||
}
|
||||
|
||||
/**
|
||||
* 全选或取消当前可见列表(受部门与搜索约束)。
|
||||
*/
|
||||
function toggleVisibleSelection(): void {
|
||||
const ids = visibleUsers.value.map((user) => user.id);
|
||||
if (!ids.length) return;
|
||||
if (visibleAllSelected.value) {
|
||||
const drop = new Set(ids);
|
||||
draftIds.value = draftIds.value.filter((id) => !drop.has(id));
|
||||
return;
|
||||
}
|
||||
const seen = new Set(draftIds.value);
|
||||
draftIds.value = [...draftIds.value, ...ids.filter((id) => !seen.has(id))];
|
||||
}
|
||||
|
||||
function closeDialog(): void {
|
||||
emit('update:modelValue', false);
|
||||
}
|
||||
|
||||
function handleCancel(): void {
|
||||
emit('cancel');
|
||||
closeDialog();
|
||||
}
|
||||
|
||||
/**
|
||||
* 把草稿 id 回写给父组件后再关闭。
|
||||
*/
|
||||
function handleConfirm(): void {
|
||||
emit('confirm', [...draftIds.value]);
|
||||
closeDialog();
|
||||
}
|
||||
|
||||
function handleEscKey(event: KeyboardEvent): void {
|
||||
if (event.key === 'Escape' && props.modelValue) handleCancel();
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(visible) => {
|
||||
if (visible) {
|
||||
draftIds.value = normalizeIds(props.selectedIds);
|
||||
departmentKey.value = USER_PICKER_ALL_DEPT;
|
||||
query.value = '';
|
||||
document.addEventListener('keydown', handleEscKey);
|
||||
return;
|
||||
}
|
||||
document.removeEventListener('keydown', handleEscKey);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('keydown', handleEscKey);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="modelValue"
|
||||
class="dialog-overlay z-[120] items-center"
|
||||
@click.self="handleCancel"
|
||||
>
|
||||
<div
|
||||
class="dialog-panel flex max-h-[min(620px,calc(100vh-40px))] w-full max-w-[760px] overflow-hidden"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3 border-b border-default px-5 py-4">
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-base font-semibold text-primary">{{ resolvedTitle }}</h3>
|
||||
<p class="mt-1 text-xs text-muted">{{ resolvedSubtitle }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-lg px-1.5 text-xl leading-none text-muted hover:bg-surface-soft hover:text-primary"
|
||||
:aria-label="t('common.close')"
|
||||
@click="handleCancel"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-0 flex-1 flex-col md:flex-row">
|
||||
<aside class="max-h-40 shrink-0 overflow-auto border-b border-default bg-surface-soft md:max-h-none md:w-[200px] md:border-b-0 md:border-r">
|
||||
<button
|
||||
v-for="dept in departments"
|
||||
:key="dept.key"
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between border-l-4 px-3 py-2.5 text-left text-sm text-secondary"
|
||||
:class="departmentKey === dept.key
|
||||
? 'border-brand-600 bg-surface font-semibold text-brand-600'
|
||||
: 'border-transparent hover:bg-surface'"
|
||||
@click="departmentKey = dept.key"
|
||||
>
|
||||
<span>{{ departmentLabel(dept.key) }}</span>
|
||||
<span class="text-xs font-medium text-muted">{{ dept.count }}</span>
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<section class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<div class="flex items-center gap-2 border-b border-default px-3 py-2.5">
|
||||
<input
|
||||
v-model="query"
|
||||
type="search"
|
||||
class="input-field min-w-0 flex-1"
|
||||
:placeholder="t('common.userPicker.searchPlaceholder')"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 whitespace-nowrap text-xs font-semibold text-brand-600 hover:text-brand-700 disabled:opacity-40"
|
||||
:disabled="visibleUsers.length === 0"
|
||||
@click="toggleVisibleSelection"
|
||||
>
|
||||
{{ selectVisibleLabel }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="min-h-[220px] flex-1 overflow-auto">
|
||||
<button
|
||||
v-for="user in visibleUsers"
|
||||
:key="user.id"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2.5 border-b border-default px-3 py-2.5 text-left hover:bg-surface-soft"
|
||||
:class="draftIds.includes(user.id) ? 'bg-blue-50/70' : 'bg-surface'"
|
||||
@click="toggleUser(user.id)"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="pointer-events-none h-3.5 w-3.5 rounded text-brand-600"
|
||||
:checked="draftIds.includes(user.id)"
|
||||
tabindex="-1"
|
||||
readonly
|
||||
/>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block text-sm font-medium text-primary">{{ userPickerLabel(user) }}</span>
|
||||
<span class="block text-xs text-muted">{{ personMeta(user) }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="showWecom && user.wecom_bound"
|
||||
class="shrink-0 text-[11px] font-semibold text-emerald-700"
|
||||
>
|
||||
{{ t('common.userPicker.wecomBound') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="showWecom"
|
||||
class="shrink-0 text-[11px] font-semibold text-amber-700"
|
||||
>
|
||||
{{ t('common.userPicker.wecomUnbound') }}
|
||||
</span>
|
||||
</button>
|
||||
<div v-if="visibleUsers.length === 0" class="px-3 py-10 text-center text-sm text-muted">
|
||||
{{ t('common.userPicker.empty') }}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-3 border-t border-default bg-surface-soft px-5 py-3">
|
||||
<div class="flex min-w-0 flex-1 flex-wrap gap-1.5">
|
||||
<span
|
||||
v-for="userId in draftIds"
|
||||
:key="userId"
|
||||
class="inline-flex items-center gap-1 rounded-lg bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700"
|
||||
>
|
||||
{{ userPickerLabel(userMap.get(userId), userId) }}
|
||||
<button
|
||||
type="button"
|
||||
class="text-blue-400 hover:text-blue-600"
|
||||
@click="toggleUser(userId)"
|
||||
>✕</button>
|
||||
</span>
|
||||
<span v-if="draftIds.length === 0" class="text-sm text-muted">
|
||||
{{ t('common.userPicker.noneSelected') }}
|
||||
</span>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm shrink-0" @click="handleCancel">
|
||||
{{ t('common.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary btn-sm shrink-0" @click="handleConfirm">
|
||||
{{ t('common.userPicker.confirmCount', { count: draftIds.length }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* shared/types/userPicker.types.ts
|
||||
* 用途:公共选人弹窗的人员数据结构,供各业务传入自己的候选人列表。
|
||||
* 依赖:无。
|
||||
* 逻辑:UserPickerDialog / userPicker.utils 共用;wecom_bound 可选,缺省时不展示企微标记。
|
||||
*/
|
||||
export interface UserPickerPerson {
|
||||
id: number;
|
||||
username: string;
|
||||
real_name?: string | null;
|
||||
employee_id?: string | null;
|
||||
department?: string | null;
|
||||
wecom_bound?: boolean;
|
||||
}
|
||||
|
||||
export const USER_PICKER_ALL_DEPT = '__all__';
|
||||
export const USER_PICKER_NONE_DEPT = '__none__';
|
||||
@@ -11,6 +11,7 @@ export const AGENT_CODE_SHIPPING_NOTICE = 'shipping_notice';
|
||||
export const AGENT_CODE_FILE_CHECK = 'file_check';
|
||||
export const AGENT_CODE_PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review';
|
||||
export const AGENT_CODE_CONTRACT_PAYMENT = 'contract_payment';
|
||||
export const AGENT_CODE_VOUCHER_CHECK = 'voucher_check';
|
||||
export const AGENT_CODE_IN_TRANSIT_TRANSFER = 'in_transit_transfer';
|
||||
|
||||
export interface AgentRegistryCapabilities {
|
||||
@@ -243,6 +244,11 @@ export function isContractPaymentAgent(agent: AgentLike): boolean {
|
||||
return resolveAgentCode(agent) === AGENT_CODE_CONTRACT_PAYMENT;
|
||||
}
|
||||
|
||||
/** 是否为立账凭证检核 Agent(agent_code=voucher_check)。 */
|
||||
export function isVoucherCheckAgent(agent: AgentLike): boolean {
|
||||
return resolveAgentCode(agent) === AGENT_CODE_VOUCHER_CHECK;
|
||||
}
|
||||
|
||||
/** 是否启用本地请假表单(后端 leave_feature_enabled)。 */
|
||||
export function canUseLeaveFeature(agent: AgentLike): boolean {
|
||||
return Boolean(agent?.leave_feature_enabled);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* shared/utils/userPicker.utils.test.ts
|
||||
* 用途:锁定公共选人弹窗的部门分组与筛选规则。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
USER_PICKER_ALL_DEPT,
|
||||
USER_PICKER_NONE_DEPT,
|
||||
type UserPickerPerson,
|
||||
} from '@/shared/types/userPicker.types';
|
||||
import {
|
||||
filterUserPickerPeople,
|
||||
listUserPickerDepartments,
|
||||
userPickerLabel,
|
||||
} from './userPicker.utils';
|
||||
|
||||
const people: UserPickerPerson[] = [
|
||||
{ id: 1, username: 'a', real_name: '钟淑惠', employee_id: '0100004', department: '财务部' },
|
||||
{ id: 2, username: 'b', real_name: '成秋兰', employee_id: '0203036', department: '关务部' },
|
||||
{ id: 3, username: 'c', real_name: '刘江', employee_id: '07090745', department: ' ' },
|
||||
];
|
||||
|
||||
describe('userPickerLabel', () => {
|
||||
it('prefers real name and appends employee id', () => {
|
||||
expect(userPickerLabel(people[0])).toBe('钟淑惠(0100004)');
|
||||
expect(userPickerLabel(undefined, 9)).toBe('9');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listUserPickerDepartments', () => {
|
||||
it('puts all first, named departments next, and unnamed last', () => {
|
||||
expect(listUserPickerDepartments(people)).toEqual([
|
||||
{ key: USER_PICKER_ALL_DEPT, count: 3 },
|
||||
{ key: '财务部', count: 1 },
|
||||
{ key: '关务部', count: 1 },
|
||||
{ key: USER_PICKER_NONE_DEPT, count: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterUserPickerPeople', () => {
|
||||
it('filters by department and keyword', () => {
|
||||
expect(filterUserPickerPeople(people, { departmentKey: '财务部' }).map((row) => row.id)).toEqual([1]);
|
||||
expect(filterUserPickerPeople(people, { query: '0203' }).map((row) => row.id)).toEqual([2]);
|
||||
expect(filterUserPickerPeople(people, { departmentKey: USER_PICKER_NONE_DEPT }).map((row) => row.id)).toEqual([3]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* shared/utils/userPicker.utils.ts
|
||||
* 用途:公共选人弹窗的展示名、部门分组与筛选。
|
||||
* 依赖:userPicker.types。
|
||||
* 逻辑:UserPickerDialog 调用;部门为空归入 USER_PICKER_NONE_DEPT。
|
||||
*/
|
||||
import {
|
||||
USER_PICKER_ALL_DEPT,
|
||||
USER_PICKER_NONE_DEPT,
|
||||
type UserPickerPerson,
|
||||
} from '@/shared/types/userPicker.types';
|
||||
|
||||
export interface UserPickerDepartment {
|
||||
key: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 人员展示名:实名优先,附工号。
|
||||
*/
|
||||
export function userPickerLabel(person?: UserPickerPerson | null, fallbackId?: number): string {
|
||||
if (!person) return String(fallbackId || '');
|
||||
const name = String(person.real_name || person.username || '').trim();
|
||||
const emp = String(person.employee_id || '').trim();
|
||||
return emp ? `${name}(${emp})` : name || String(person.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把用户部门归一成筛选键:空部门用 USER_PICKER_NONE_DEPT。
|
||||
*/
|
||||
export function userPickerDepartmentKey(person: UserPickerPerson): string {
|
||||
return String(person.department || '').trim() || USER_PICKER_NONE_DEPT;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计部门列表:全部在前,具名部门按名称排序,未分配部门垫底。
|
||||
*/
|
||||
export function listUserPickerDepartments(users: UserPickerPerson[]): UserPickerDepartment[] {
|
||||
const counts = new Map<string, number>();
|
||||
for (const user of users) {
|
||||
const key = userPickerDepartmentKey(user);
|
||||
counts.set(key, (counts.get(key) || 0) + 1);
|
||||
}
|
||||
const named = [...counts.keys()]
|
||||
.filter((key) => key !== USER_PICKER_NONE_DEPT)
|
||||
.sort((a, b) => a.localeCompare(b, 'zh-CN'));
|
||||
const items: UserPickerDepartment[] = [
|
||||
{ key: USER_PICKER_ALL_DEPT, count: users.length },
|
||||
...named.map((key) => ({ key, count: counts.get(key) || 0 })),
|
||||
];
|
||||
const unnamed = counts.get(USER_PICKER_NONE_DEPT) || 0;
|
||||
if (unnamed) items.push({ key: USER_PICKER_NONE_DEPT, count: unnamed });
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按部门与关键字筛选候选人。
|
||||
* @param options.departmentKey - USER_PICKER_ALL_DEPT 表示不限部门
|
||||
* @param options.query - 匹配姓名、用户名、工号、部门
|
||||
*/
|
||||
export function filterUserPickerPeople(
|
||||
users: UserPickerPerson[],
|
||||
options?: { departmentKey?: string; query?: string },
|
||||
): UserPickerPerson[] {
|
||||
const departmentKey = options?.departmentKey || USER_PICKER_ALL_DEPT;
|
||||
const keyword = String(options?.query || '').trim().toLowerCase();
|
||||
return users.filter((user) => {
|
||||
if (departmentKey !== USER_PICKER_ALL_DEPT && userPickerDepartmentKey(user) !== departmentKey) {
|
||||
return false;
|
||||
}
|
||||
if (!keyword) return true;
|
||||
const hay = [
|
||||
user.real_name,
|
||||
user.username,
|
||||
user.employee_id,
|
||||
user.department,
|
||||
].join(' ').toLowerCase();
|
||||
return hay.includes(keyword);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user