feat(invoice check): 立账凭证检核优化部分代码

This commit is contained in:
sophie committed 2026-09-08 10:25:11 +08:00
1 parent 21d41acf50
commit d123d9cdf6
45 files changed
+498 -2508

No files matched your search

-4
View File
@@ -75,10 +75,6 @@ CONTRACT_PAYMENT_OA_MATRIX_ROUND2_FIELD=zz
CONTRACT_PAYMENT_OA_MATRIX_ROUND3_FIELD=jfl
# 立账凭证检核:销售开票附件与合同同一文档库,仅根 FolderID 不同(账号复用 CONTRACT_DMS_*)
VOUCHER_CHECK_LOCAL_ROOT=
VOUCHER_CHECK_SHARE_UNC=
VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=
# VOUCHER_CHECK_ERP_DSN=
# VOUCHER_CHECK_ERP_USERNAME=
# VOUCHER_CHECK_ERP_PASSWORD=
+1 -2
View File
@@ -41,7 +41,7 @@ def register_blueprints(app: Flask) -> None:
workspace_shipping_notice_bp,
workspace_voucher_check_bp,
)
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
from app.api.files import files_bp
from app.api.procurement_contract_tools import procurement_contract_bp
from app.api.contract_payment import contract_payment_bp
@@ -66,7 +66,6 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(voucher_check_tools_bp, url_prefix='/api/accounting-voucher-check')
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
+2 -3
View File
@@ -2,11 +2,10 @@
backend/app/api/tools/__init__.py
用途:Dify HTTP Tool API Blueprint 聚合。
逻辑:re-export shipping_notice、file_check、maintenance、voucher_check tools。
逻辑:re-export shipping_notice、file_check、maintenance tools。
"""
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
from app.api.tools.file_check import file_check_bp # noqa: F401
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
from app.api.tools.voucher_check import voucher_check_tools_bp # noqa: F401
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp', 'voucher_check_tools_bp']
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp']
-105
View File
@@ -1,105 +0,0 @@
"""
backend/app/api/tools/voucher_check.py
用途:立账凭证检核 Dify Tool API(缺资料/批次明细/单票最新状态查询 + OpenAPI)。
依赖:voucher_check.query_service、openapi_spec、integration_tool_auth;启动检核复用 file-check。
逻辑:非 envelope 契约(ok/error_code);与 file-check 共用 Tool API Key;register_blueprints 挂到 /api/accounting-voucher-check。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request
from app.core.errors import AppError
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.integration_tool_auth import require_integration_tool_auth
from app.services.voucher_check import query_service
from app.services.voucher_check.openapi_spec import build_voucher_check_openapi_spec
voucher_check_tools_bp = Blueprint("voucher_check_tools", __name__)
@voucher_check_tools_bp.before_request
def _verify_tool_access():
"""openapi.json 免鉴权,其余端点校验 Tool API Key。"""
if request.path.endswith("/openapi.json"):
return None
require_integration_tool_auth()
return None
def _tool_error(exc: AppError):
"""将 AppError 映射为 Tool 非 envelope 错误体。"""
code = str(exc.code or "").lower().replace(".", "_")
message = str(exc.message or "").strip()
# 与 file-check 对齐:鉴权类错误码用 message 短码,便于 Dify 分支
if message in {"missing_auth", "invalid_auth"}:
code = message
return jsonify({
"ok": False,
"error_code": code,
"message": message or code,
"details": exc.details or {},
}), exc.http_status
@voucher_check_tools_bp.route("/tools/openapi.json", methods=["GET"])
def voucher_check_openapi_spec():
"""
返回 Dify 可 URL 导入的 OpenAPI(无需鉴权)。
【AI 触发时机】:不由对话调用;运维/Dify 导入工具时访问。
"""
return jsonify(build_voucher_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
@voucher_check_tools_bp.route("/tools/tasks/<int:task_id>/missing", methods=["GET"])
def tool_list_missing(task_id: int):
"""
查询当前月或指定月缺资料票。
【AI 触发时机】:用户说「查询缺资料发票」时调用。
"""
try:
data = query_service.list_missing_states(
task_id=task_id,
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
limit=request.args.get("limit", default=200, type=int) or 200,
)
return jsonify({"ok": True, **data})
except AppError as exc:
return _tool_error(exc)
@voucher_check_tools_bp.route("/tools/runs/<int:run_id>/items", methods=["GET"])
def tool_list_run_items(run_id: int):
"""
查询批次明细,可按 result 过滤。
【AI 触发时机】:用户查询某批次结果明细时调用。
"""
try:
data = query_service.list_run_items(
run_id=run_id,
result=request.args.get("result"),
page=request.args.get("page", default=1, type=int) or 1,
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return jsonify({"ok": True, **data})
except AppError as exc:
return _tool_error(exc)
@voucher_check_tools_bp.route("/tools/invoices/<path:invoice_no>/latest", methods=["GET"])
def tool_invoice_latest(invoice_no: str):
"""
查询指定发票最新状态。
【AI 触发时机】:用户询问某张发票检核结论时调用。
"""
try:
data = query_service.get_invoice_latest(
invoice_no=invoice_no,
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
)
return jsonify({"ok": True, **data})
except AppError as exc:
return _tool_error(exc)
+1 -30
View File
@@ -1,7 +1,7 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 兼容旧状态)。
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
"""
@@ -99,32 +99,3 @@ 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/states", methods=["GET"])
def workspace_voucher_states():
"""
按月份、状态、发票号筛选最新状态。
"""
_require_user()
data = query_service.list_states(
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
status=request.args.get("status"),
invoice_no=request.args.get("invoice_no"),
page=request.args.get("page", default=1, type=int) or 1,
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states/<path:invoice_no>", methods=["GET"])
def workspace_voucher_state_detail(invoice_no: str):
"""查看单票最近状态和历史批次快照。"""
_require_user()
data = query_service.get_invoice_latest(
invoice_no=invoice_no,
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
)
return ok(data)
-7
View File
@@ -653,13 +653,6 @@ class Config:
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
# 立账凭证检核:ERP 只读 + 销售开票附件文档库根目录(密码仅 env)
VOUCHER_CHECK_SHARE_UNC = os.getenv('VOUCHER_CHECK_SHARE_UNC', '').strip()
VOUCHER_CHECK_LOCAL_ROOT = os.getenv('VOUCHER_CHECK_LOCAL_ROOT', '').strip()
VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH = os.getenv(
'VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH',
'.hxops-share-ready',
).strip() or '.hxops-share-ready'
# 专用 VOUCHER_CHECK_ERP_* 优先;否则复用通用 ERP_*,再回退合同付款已配置的同一套只读账号。
VOUCHER_CHECK_ERP_DSN = os.getenv('VOUCHER_CHECK_ERP_DSN') or os.getenv('ERP_DB_DSN', '')
VOUCHER_CHECK_ERP_USERNAME = (
os.getenv('VOUCHER_CHECK_ERP_USERNAME')
-4
View File
@@ -211,11 +211,9 @@ from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigRe
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckInvoiceState,
VoucherCheckNotification,
VoucherCheckProfile,
VoucherCheckRun,
VoucherCheckRunItem,
VoucherCheckSubject,
)
from app.models.contract_payment import (
@@ -401,8 +399,6 @@ __all__ = [
'ShippingInventoryCandidateSource',
'ShippingInventoryCandidateLine',
'ShippingTaskInventoryRpaAttempt',
'VoucherCheckInvoiceState',
'VoucherCheckRunItem',
'VoucherCheckProfile',
'VoucherCheckRun',
'VoucherCheckSubject',
+2 -89
View File
@@ -1,9 +1,9 @@
"""
backend/app/models/voucher_check.py
用途:立账凭证检核 ORM。含旧一票一状态表,以及销售一期单文件结果引擎表。
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。
依赖:models.base.Base、schedule_runs。
逻辑:旧 runner 写 invoice_states/run_items;新引擎写 profiles/runs/subjects/file_results/notifications。
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;工作台与查询服务只读这些表。
"""
from __future__ import annotations
@@ -13,7 +13,6 @@ from typing import Optional
from sqlalchemy import (
BigInteger,
Boolean,
Date,
DateTime,
ForeignKey,
@@ -28,92 +27,6 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class VoucherCheckInvoiceState(Base):
"""账套+月份+发票号的最新材料齐全状态(增量跳过真相源)。"""
__tablename__ = "voucher_check_invoice_states"
__table_args__ = (
UniqueConstraint(
"scope_code",
"period_month",
"invoice_no",
name="uq_voucher_check_invoice_states_scope_period_invoice",
),
Index("ix_voucher_check_invoice_states_period_status", "period_month", "status"),
Index("ix_voucher_check_invoice_states_invoice_no", "invoice_no"),
Index("ix_voucher_check_invoice_states_notified_on", "last_missing_notified_on"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
scope_code: Mapped[str] = mapped_column(String(32), nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
status: Mapped[str] = mapped_column(String(24), nullable=False)
folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
last_actual_run_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
)
last_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_seen_erp_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_missing_notified_on: Mapped[Optional[date]] = mapped_column(Date, 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 VoucherCheckRunItem(Base):
"""单次 ScheduleRun 的发票检核快照(含跳过项,供审计与 Excel)。"""
__tablename__ = "voucher_check_run_items"
__table_args__ = (
UniqueConstraint(
"schedule_run_id",
"invoice_no",
name="uq_voucher_check_run_items_run_invoice",
),
Index("ix_voucher_check_run_items_run_result", "schedule_run_id", "result"),
Index("ix_voucher_check_run_items_period_result", "period_month", "result"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
schedule_run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
invoice_state_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"),
nullable=True,
)
scope_code: Mapped[str] = mapped_column(String(32), nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
result: Mapped[str] = mapped_column(String(24), nullable=False)
folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class VoucherCheckProfile(Base):
"""已发布 Profile 版本;批次绑定不可变快照,运行时不以本表热更新覆盖。"""
+6 -32
View File
@@ -144,7 +144,7 @@ def _register_builtin_platform_jobs() -> None:
run_contract_payment_alert_schedule,
run_contract_payment_sync_schedule,
)
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
from app.services.schedule.contract_payment_job import (
run_contract_payment_alert_schedule,
run_contract_payment_sync_schedule,
@@ -339,7 +339,7 @@ def _register_builtin_platform_jobs() -> None:
label="立账凭证检核",
label_key="admin.schedule.form.platformJobAccountingVoucherCheck",
handler=run_voucher_check_schedule,
description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。",
description="每周二检核上一个自然月的销售开票附件,扫描文档库类型目录并按 invoice 归档。",
description_key="admin.schedule.form.accountingVoucherCheckHint",
category="finance",
params_schema=(
@@ -353,30 +353,12 @@ def _register_builtin_platform_jobs() -> None:
"options": [{"value": "HXJM", "label": "HXJM"}],
},
{
"key": "directory_template",
"key": "profile_code",
"type": "text",
"label": "目录模板",
"label_key": "admin.schedule.form.voucherCheckDirTemplate",
"label": "业务方 Profile",
"label_key": "admin.schedule.form.voucherCheckProfile",
"required": True,
"default": "{root}/{YYYY}/{MM}/{invoice_no}",
"help": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}",
"help_key": "admin.schedule.form.voucherCheckDirTemplateHelp",
},
{
"key": "required_files",
"type": "json",
"label": "必检材料",
"label_key": "admin.schedule.form.voucherCheckRequiredFiles",
"required": True,
"default": DEFAULT_REQUIRED_FILES,
},
{
"key": "filename_case_sensitive",
"type": "boolean",
"label": "文件名区分大小写",
"label_key": "admin.schedule.form.voucherCheckCaseSensitive",
"required": True,
"default": True,
"default": "sales",
},
{
"key": "notify_missing_enabled",
@@ -394,14 +376,6 @@ def _register_builtin_platform_jobs() -> None:
"required": False,
"default": True,
},
{
"key": "same_day_dedup_enabled",
"type": "boolean",
"label": "同票同日去重",
"label_key": "admin.schedule.form.voucherCheckSameDayDedup",
"required": False,
"default": True,
},
),
defaults=dict(DEFAULT_JOB_PARAMS),
))
@@ -6,7 +6,7 @@ backend/app/services/schedule/scheduler_service.py
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler;
handler 抛错时 failed_count=1,排程记 failed。
handler 抛错时 failed_count=1、排程记 failed,并把 error= 打进 worker 日志。
"""
from __future__ import annotations
@@ -493,7 +493,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
"""
立即执行一条排程并写入 ScheduleRun 终态。
核心逻辑:handler 未捕获异常记 failed_count=1,避免配置错误被标成 success。
核心逻辑:handler 未捕获异常记 failed_count=1,避免配置错误被标成 success;
该路径原先只写库不打日志,worker 汇总行看不到失败原因。
"""
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
@@ -531,6 +532,14 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
except Exception as exc:
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 1, 0, [], [str(exc)]
step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}]
if current_app:
current_app.logger.exception(
"[schedule-run] executor failed name=%s path=%s run_no=%s error=%s",
task.name,
task.platform_api_path,
run.run_no,
exc,
)
try:
db.session.refresh(run)
@@ -565,8 +574,9 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
duration_ms = int((time.time() - start_ts) * 1000)
if current_app:
error_preview = "; ".join(str(item) for item in (errors or [])[:3])
current_app.logger.info(
"[schedule-run] name=%s path=%s run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d",
"[schedule-run] name=%s path=%s run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d error=%s",
task.name,
task.platform_api_path,
run.run_no,
@@ -574,7 +584,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
success_count,
failed_count,
skipped_count,
len(errors),
len(errors or []),
error_preview or "-",
)
if total_count == 0 and not errors:
status = "success"
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/__init__.py
用途:立账凭证检核领域服务包入口。
依赖:config / runner / query_service 等子模块。
逻辑:platform Job 与 Tool/工作台 API 从此包调用 runner 与查询能力。
逻辑:platform Job 与工作台 API 从此包调用 runner 与查询能力。
"""
from app.services.voucher_check.runner import run_voucher_check_batch
+3 -197
View File
@@ -1,17 +1,15 @@
"""
backend/app/services/voucher_check/config.py
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params。
依赖:Flask current_app.config、core.errors.ValidationError。
逻辑:runner / share_scanner / erp_repository / 新引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
逻辑:runner / erp_repository / 引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
ERP 账号优先 VOUCHER_CHECK_ERP_*,否则 ERP_*,再回退 CONTRACT_PAYMENT_ERP_*。
"""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass
from typing import Any
@@ -19,70 +17,17 @@ from flask import has_app_context, current_app
from app.core.errors import ValidationError
_ALLOWED_TEMPLATE_KEYS = {"root", "YYYY", "MM", "invoice_no"}
_TEMPLATE_TOKEN_RE = re.compile(r"\{([^{}]+)\}")
_UNSAFE_FILENAME_RE = re.compile(r"[/\\\x00]|(\.\.)")
DEFAULT_REQUIRED_FILES: list[dict[str, Any]] = [
{
"code": "price_check_sheet",
"name": "核价单",
"required": True,
"accepted_filenames": ["核价单.pdf"],
},
{
"code": "purchase_order",
"name": "采购单",
"required": True,
"accepted_filenames": ["采购单.pdf"],
},
]
DEFAULT_JOB_PARAMS: dict[str, Any] = {
"profile_code": "sales",
"scope_code": "HXJM",
"directory_template": "{root}/{YYYY}/{MM}/{invoice_no}",
"required_files": DEFAULT_REQUIRED_FILES,
"filename_case_sensitive": True,
"notify_missing_enabled": True,
"notify_failure_enabled": True,
"same_day_dedup_enabled": False,
}
@dataclass(frozen=True)
class RequiredFileRule:
"""单条必检材料规则。"""
code: str
name: str
required: bool
accepted_filenames: tuple[str, ...]
@dataclass(frozen=True)
class VoucherCheckConfig:
"""运行期检核配置快照。"""
scope_code: str
directory_template: str
required_files: tuple[RequiredFileRule, ...]
filename_case_sensitive: bool
notify_missing_enabled: bool
notify_failure_enabled: bool
same_day_dedup_enabled: bool
local_root: str
share_unc: str
healthcheck_relative_path: str
erp_dsn: str
erp_username: str
erp_password: str
erp_timeout_seconds: int = 30
@dataclass(frozen=True)
class VoucherCheckEngineConfig:
"""销售一期引擎运行配置:ERP + 通知开关,不再依赖共享盘。"""
"""销售一期引擎运行配置:ERP + 通知开关。"""
scope_code: str
profile_code: str
@@ -115,75 +60,6 @@ def _as_bool(value: Any, default: bool) -> bool:
return default
def _parse_required_files(raw: Any) -> list[RequiredFileRule]:
if raw is None:
raw = DEFAULT_REQUIRED_FILES
if isinstance(raw, str):
try:
raw = json.loads(raw)
except json.JSONDecodeError as exc:
raise _config_invalid("required_files JSON 非法", details={"error": str(exc)}) from exc
if not isinstance(raw, list) or not raw:
raise _config_invalid("required_files 至少包含一个必检项")
rules: list[RequiredFileRule] = []
for idx, item in enumerate(raw):
if not isinstance(item, dict):
raise _config_invalid(f"required_files[{idx}] 必须为对象")
code = str(item.get("code") or "").strip()
name = str(item.get("name") or code).strip()
accepted = item.get("accepted_filenames") or []
if not code:
raise _config_invalid(f"required_files[{idx}].code 不能为空")
if not isinstance(accepted, list) or not accepted:
raise _config_invalid(f"required_files[{idx}].accepted_filenames 不能为空")
filenames: list[str] = []
for fname in accepted:
text = str(fname or "").strip()
if not text:
raise _config_invalid(f"required_files[{idx}] 存在空文件名")
if "*" in text or "?" in text or _UNSAFE_FILENAME_RE.search(text):
raise _config_invalid(
f"required_files[{idx}] 文件名禁止通配/路径字符: {text}",
)
filenames.append(text)
rules.append(
RequiredFileRule(
code=code,
name=name or code,
required=_as_bool(item.get("required"), True),
accepted_filenames=tuple(filenames),
)
)
if not any(r.required for r in rules):
raise _config_invalid("required_files 至少包含一个 required=true 项")
return rules
def validate_directory_template(template: str) -> str:
"""
校验目录模板占位符。
核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。
"""
text = str(template or "").strip().replace("\\", "/")
if not text:
raise _config_invalid("directory_template 不能为空")
tokens = _TEMPLATE_TOKEN_RE.findall(text)
unknown = sorted({t for t in tokens if t not in _ALLOWED_TEMPLATE_KEYS})
if unknown:
raise _config_invalid(
"directory_template 含非法占位符",
details={"unknown": unknown},
)
missing = sorted(_ALLOWED_TEMPLATE_KEYS - set(tokens))
if missing:
raise _config_invalid(
"directory_template 缺少必要占位符",
details={"missing": missing},
)
return text
def _erp_settings() -> tuple[str, str, str, int]:
"""
读取 ERP 只读连接;密码只来自环境/配置,不写日志。
@@ -228,65 +104,6 @@ def _erp_settings() -> tuple[str, str, str, int]:
return erp_dsn, erp_username, erp_password, max(1, timeout)
def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> VoucherCheckConfig:
"""
合并 env 与 job_params,返回校验后的检核配置。
核心逻辑:敏感凭据只读环境变量;业务规则以 job_params 为准,缺省用 DEFAULT_JOB_PARAMS。
"""
params = dict(DEFAULT_JOB_PARAMS)
if isinstance(job_params, dict):
params.update({k: v for k, v in job_params.items() if v is not None})
scope_code = str(params.get("scope_code") or "HXJM").strip().upper() or "HXJM"
if scope_code != "HXJM":
raise _config_invalid("一期仅支持 scope_code=HXJM", details={"scope_code": scope_code})
template = validate_directory_template(
str(params.get("directory_template") or DEFAULT_JOB_PARAMS["directory_template"])
)
required_files = _parse_required_files(params.get("required_files"))
cfg = current_app.config if has_app_context() else {}
local_root = str(
cfg.get("VOUCHER_CHECK_LOCAL_ROOT")
or os.getenv("VOUCHER_CHECK_LOCAL_ROOT")
or ""
).strip()
share_unc = str(
cfg.get("VOUCHER_CHECK_SHARE_UNC")
or os.getenv("VOUCHER_CHECK_SHARE_UNC")
or ""
).strip()
healthcheck = str(
cfg.get("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH")
or os.getenv("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH")
or ".hxops-share-ready"
).strip() or ".hxops-share-ready"
# 开发机可临时用 UNC;Linux/容器必须 LOCAL_ROOT
if not local_root and not share_unc:
raise _config_invalid("未配置 VOUCHER_CHECK_LOCAL_ROOT 或 VOUCHER_CHECK_SHARE_UNC")
erp_dsn, erp_username, erp_password, timeout = _erp_settings()
return VoucherCheckConfig(
scope_code=scope_code,
directory_template=template,
required_files=tuple(required_files),
filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True),
notify_missing_enabled=_as_bool(params.get("notify_missing_enabled"), True),
notify_failure_enabled=_as_bool(params.get("notify_failure_enabled"), True),
same_day_dedup_enabled=_as_bool(params.get("same_day_dedup_enabled"), True),
local_root=local_root,
share_unc=share_unc,
healthcheck_relative_path=healthcheck,
erp_dsn=erp_dsn,
erp_username=erp_username,
erp_password=erp_password,
erp_timeout_seconds=max(1, timeout),
)
def load_engine_config(job_params: dict[str, Any] | None = None) -> VoucherCheckEngineConfig:
"""
加载销售一期引擎配置。
@@ -310,14 +127,3 @@ def load_engine_config(job_params: dict[str, Any] | None = None) -> VoucherCheck
erp_password=erp_password,
erp_timeout_seconds=timeout,
)
def resolve_share_root(config: VoucherCheckConfig) -> str:
"""
解析实际扫描根路径。
核心逻辑:优先 LOCAL_ROOT(容器/Linux);无则回退 share_unc(开发机)。
"""
root = (config.local_root or config.share_unc or "").strip()
if not root:
raise _config_invalid("共享盘根路径为空")
return root
@@ -13,7 +13,7 @@ from datetime import date, datetime
from zoneinfo import ZoneInfo
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.config import VoucherCheckConfig
from app.services.voucher_check.config import VoucherCheckEngineConfig
_TZ = ZoneInfo("Asia/Shanghai")
@@ -40,7 +40,7 @@ class ErpInvoiceRow:
def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
"""
按 Asia/Shanghai 计算当前自然月起止。
核心逻辑:不用 Oracle SYSDATE,保证手动触发与日批口径一致。
核心逻辑:不用 Oracle SYSDATE,作为 previous_period_bounds 的基准。
Returns:
(period_month_first, next_month_first, period_start_dt, next_period_start_dt)
@@ -80,7 +80,7 @@ def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, dat
def fetch_month_invoices(
config: VoucherCheckConfig,
config: VoucherCheckEngineConfig,
*,
now: datetime | None = None,
) -> tuple[date, list[ErpInvoiceRow]]:
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/fingerprint.py
用途:根据共享盘目录直接子文件的元数据生成稳定 SHA-256 指纹。
用途:根据文件名与元数据生成稳定 SHA-256 指纹。
依赖:标准库 hashlib / json。
逻辑:share_scanner 枚举文件后调用;runner 用指纹判断齐全票是否可跳过。
逻辑:DMS 目录扫描与 HXJM 主体 Adapter 调用,供增量跳过比对。
"""
from __future__ import annotations
@@ -1,316 +0,0 @@
{
"openapi": "3.0.3",
"info": {
"title": "HXOPS Accounting Voucher Check Tool API",
"description": "立账凭证检核查询 Tool API:缺资料清单、批次明细、单票最新状态。启动检核请复用 File Check 的 run_file_check(可传 run_options)。鉴权:Authorization Bearer 或 X-Integration-Key(与 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY 相同)。",
"version": "1.0.0"
},
"servers": [
{
"url": "http://127.0.0.1:5052",
"description": "HXOPS_TOOLS_API_BASE"
}
],
"security": [
{
"BearerAuth": []
},
{
"IntegrationKey": []
}
],
"paths": {
"/api/accounting-voucher-check/tools/tasks/{task_id}/missing": {
"get": {
"operationId": "list_voucher_missing",
"summary": "查询缺资料发票(最新状态)",
"description": "按账套与月份查询 status=missing 的发票;默认当前自然月。",
"tags": ["Accounting Voucher Check"],
"parameters": [
{
"name": "task_id",
"in": "path",
"required": true,
"schema": { "type": "integer", "example": 12 },
"description": "排程任务 ID(Agent 绑定的 schedule_task_id,用于回显)"
},
{
"name": "period",
"in": "query",
"required": false,
"schema": { "type": "string", "example": "2026-08" },
"description": "检核月份 YYYY-MM;缺省为当前自然月"
},
{
"name": "scope_code",
"in": "query",
"required": false,
"schema": { "type": "string", "default": "HXJM", "example": "HXJM" }
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": { "type": "integer", "default": 200, "minimum": 1, "maximum": 1000 }
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/MissingListResponse" }
}
}
},
"400": { "$ref": "#/components/responses/BadRequest" },
"401": { "$ref": "#/components/responses/Unauthorized" },
"503": { "$ref": "#/components/responses/MissingAuth" }
}
}
},
"/api/accounting-voucher-check/tools/runs/{run_id}/items": {
"get": {
"operationId": "list_voucher_run_items",
"summary": "查询批次发票明细",
"description": "分页返回某 ScheduleRun 的单票结论;可按 result 过滤。",
"tags": ["Accounting Voucher Check"],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": { "type": "integer", "example": 1001 }
},
{
"name": "result",
"in": "query",
"required": false,
"schema": {
"type": "string",
"enum": ["complete", "missing", "skipped", "technical_error"],
"example": "missing"
}
},
{
"name": "page",
"in": "query",
"required": false,
"schema": { "type": "integer", "default": 1, "minimum": 1 }
},
{
"name": "page_size",
"in": "query",
"required": false,
"schema": { "type": "integer", "default": 50, "minimum": 1, "maximum": 200 }
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/RunItemsResponse" }
}
}
},
"401": { "$ref": "#/components/responses/Unauthorized" },
"404": { "$ref": "#/components/responses/NotFound" },
"503": { "$ref": "#/components/responses/MissingAuth" }
}
}
},
"/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest": {
"get": {
"operationId": "get_voucher_invoice_latest",
"summary": "查询指定发票最新检核状态",
"description": "返回单票最新状态及近期批次快照;invoice_no 保持业务原值(仅 trim)。",
"tags": ["Accounting Voucher Check"],
"parameters": [
{
"name": "invoice_no",
"in": "path",
"required": true,
"schema": { "type": "string", "example": "INV-20260803001" },
"description": "发票号(apa08 原值)"
},
{
"name": "period",
"in": "query",
"required": false,
"schema": { "type": "string", "example": "2026-08" }
},
{
"name": "scope_code",
"in": "query",
"required": false,
"schema": { "type": "string", "default": "HXJM" }
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/InvoiceLatestResponse" }
}
}
},
"400": { "$ref": "#/components/responses/BadRequest" },
"401": { "$ref": "#/components/responses/Unauthorized" },
"404": { "$ref": "#/components/responses/NotFound" },
"503": { "$ref": "#/components/responses/MissingAuth" }
}
}
}
},
"components": {
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"description": "Authorization: Bearer <FILE_CHECK_TOOL_API_KEY 或 INTEGRATION_API_KEY>"
},
"IntegrationKey": {
"type": "apiKey",
"in": "header",
"name": "X-Integration-Key",
"description": "与 Bearer 二选一"
}
},
"schemas": {
"MissingMaterial": {
"type": "object",
"properties": {
"code": { "type": "string", "example": "price_check_sheet" },
"name": { "type": "string", "example": "核价单" }
}
},
"InvoiceState": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"scope_code": { "type": "string" },
"period_month": { "type": "string", "nullable": true },
"invoice_no": { "type": "string" },
"invoice_date": { "type": "string", "nullable": true },
"status": { "type": "string", "enum": ["complete", "missing"] },
"folder_path": { "type": "string", "nullable": true },
"folder_exists": { "type": "boolean" },
"matched_files": { "type": "object", "additionalProperties": { "type": "string" } },
"missing_materials": {
"type": "array",
"items": { "$ref": "#/components/schemas/MissingMaterial" }
},
"last_checked_at": { "type": "string", "nullable": true }
}
},
"MissingListResponse": {
"type": "object",
"required": ["ok", "items", "count"],
"properties": {
"ok": { "type": "boolean", "example": true },
"task_id": { "type": "integer", "nullable": true },
"scope_code": { "type": "string" },
"period": { "type": "string", "example": "2026-08" },
"count": { "type": "integer" },
"items": {
"type": "array",
"items": { "$ref": "#/components/schemas/InvoiceState" }
}
}
},
"RunItem": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"schedule_run_id": { "type": "integer" },
"invoice_no": { "type": "string" },
"result": {
"type": "string",
"enum": ["complete", "missing", "skipped", "technical_error"]
},
"folder_path": { "type": "string", "nullable": true },
"matched_files": { "type": "object", "additionalProperties": { "type": "string" } },
"missing_materials": {
"type": "array",
"items": { "$ref": "#/components/schemas/MissingMaterial" }
},
"error_code": { "type": "string", "nullable": true },
"error_message": { "type": "string", "nullable": true }
}
},
"RunItemsResponse": {
"type": "object",
"required": ["ok", "items", "total"],
"properties": {
"ok": { "type": "boolean" },
"run_id": { "type": "integer" },
"run_no": { "type": "string" },
"page": { "type": "integer" },
"page_size": { "type": "integer" },
"total": { "type": "integer" },
"items": {
"type": "array",
"items": { "$ref": "#/components/schemas/RunItem" }
}
}
},
"InvoiceLatestResponse": {
"type": "object",
"required": ["ok", "state"],
"properties": {
"ok": { "type": "boolean" },
"state": { "$ref": "#/components/schemas/InvoiceState" },
"recent_run_items": {
"type": "array",
"items": { "$ref": "#/components/schemas/RunItem" }
}
}
},
"ToolError": {
"type": "object",
"properties": {
"ok": { "type": "boolean", "example": false },
"error_code": { "type": "string" },
"message": { "type": "string" },
"details": { "type": "object" }
}
}
},
"responses": {
"BadRequest": {
"description": "参数错误",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ToolError" }
}
}
},
"Unauthorized": {
"description": "鉴权失败",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ToolError" }
}
}
},
"NotFound": {
"description": "资源不存在",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ToolError" }
}
}
},
"MissingAuth": {
"description": "服务端未配置 Tool API Key",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ToolError" }
}
}
}
}
}
}
@@ -1,35 +0,0 @@
"""
backend/app/services/voucher_check/openapi_spec.py
用途:构建立账凭证检核 Chatflow 查询 Tool 的 OpenAPI 3.0 规范。
依赖:openapi_base.json。
逻辑:GET /api/accounting-voucher-check/tools/openapi.json 调用本模块;Dify URL 导入。
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
_BASE_SPEC_PATH = Path(__file__).with_name("openapi_base.json")
def _load_base_spec() -> dict[str, Any]:
with _BASE_SPEC_PATH.open("r", encoding="utf-8") as fp:
return json.load(fp)
def build_voucher_check_openapi_spec(base_url: str) -> dict[str, Any]:
"""
构建立账凭证检核 Tool OpenAPI。
核心逻辑:深拷贝静态规格,并将 servers[0].url 替换为当前 HXOPS_TOOLS_API_BASE。
"""
spec = copy.deepcopy(_load_base_spec())
base = str(base_url or "").strip().rstrip("/")
servers = spec.get("servers")
if base and isinstance(servers, list) and servers:
servers[0]["url"] = base
servers[0]["description"] = "HXOPS_TOOLS_API_BASE"
return spec
@@ -1,126 +0,0 @@
"""
backend/app/services/voucher_check/persistence.py
用途:立账凭证检核单票状态与批次明细的事务写入。
依赖:models.voucher_check、ScheduleRun、SQLAlchemy session。
逻辑:runner 阶段 B 调用;skipped 只更新 last_seen_erp_at;批次级失败不进入本模块。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Any
from app import db
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
def persist_batch_results(
*,
schedule_run_id: int,
scope_code: str,
period_month: date,
items: list[dict[str, Any]],
now: datetime | None = None,
) -> None:
"""
单事务写入批次明细并 upsert 最新状态。
核心逻辑:先写 run_items;非 skipped/technical_error 再 upsert states;
skipped 仅刷新 last_seen_erp_at。
Args:
schedule_run_id: ScheduleRun.id
scope_code: 账套
period_month: 当月首日
items: 内存中的结果行(含 result / fingerprint / missing 等)
now: 可选时钟
"""
ts = now or datetime.utcnow()
for item in items:
invoice_no = str(item["invoice_no"]).strip()
result = str(item["result"])
run_item = VoucherCheckRunItem(
schedule_run_id=schedule_run_id,
scope_code=scope_code,
period_month=period_month,
invoice_no=invoice_no,
invoice_date=item.get("invoice_date"),
result=result,
folder_path=item.get("folder_path"),
folder_exists=bool(item.get("folder_exists")),
material_fingerprint=item.get("material_fingerprint"),
matched_files_json=item.get("matched_files") or {},
missing_materials_json=item.get("missing_materials") or [],
error_code=item.get("error_code"),
error_message=item.get("error_message"),
checked_at=item.get("checked_at"),
created_at=ts,
)
db.session.add(run_item)
state = (
db.session.query(VoucherCheckInvoiceState)
.filter_by(
scope_code=scope_code,
period_month=period_month,
invoice_no=invoice_no,
)
.one_or_none()
)
if state is None:
state = VoucherCheckInvoiceState(
scope_code=scope_code,
period_month=period_month,
invoice_no=invoice_no,
created_at=ts,
)
db.session.add(state)
state.last_seen_erp_at = ts
state.invoice_date = item.get("invoice_date") or state.invoice_date
state.updated_at = ts
if result == "skipped":
# 跳过:不改写齐全结论与实际扫描时间
continue
if result == "technical_error":
continue
state.status = "complete" if result == "complete" else "missing"
state.folder_path = item.get("folder_path")
state.folder_exists = bool(item.get("folder_exists"))
state.material_fingerprint = item.get("material_fingerprint")
state.matched_files_json = item.get("matched_files") or {}
state.missing_materials_json = item.get("missing_materials") or []
state.last_actual_run_id = schedule_run_id
state.last_checked_at = item.get("checked_at") or ts
db.session.flush()
run_item.invoice_state_id = state.id
db.session.flush()
def mark_missing_notified(
*,
scope_code: str,
period_month: date,
invoice_nos: list[str],
notified_on: date,
) -> None:
"""发送缺资料通知成功后更新同票同日节流字段。"""
if not invoice_nos:
return
states = (
db.session.query(VoucherCheckInvoiceState)
.filter(
VoucherCheckInvoiceState.scope_code == scope_code,
VoucherCheckInvoiceState.period_month == period_month,
VoucherCheckInvoiceState.invoice_no.in_(invoice_nos),
)
.all()
)
for state in states:
state.last_missing_notified_on = notified_on
state.updated_at = datetime.utcnow()
db.session.flush()
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/query_service.py
用途:查询检核批次列表、批次明细、兼容旧状态表,以及工作台强制重检入队。
用途:查询检核批次列表、批次明细、企微发送记录,以及工作台强制重检入队。
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。
逻辑:优先读新引擎表;明细同时返回 invoice 行与 by_file_type;工作台可查企微发送记录;无引擎批次时回退旧 run_items / invoice_states;强制重检写入 run_options.mode=force_all。
逻辑:只读引擎表;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
"""
from __future__ import annotations
@@ -15,62 +15,13 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ScheduleRun, ScheduleTask, User
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckInvoiceState,
VoucherCheckNotification,
VoucherCheckRun,
VoucherCheckRunItem,
)
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.erp_repository import previous_period_bounds
def _serialize_state(state: VoucherCheckInvoiceState) -> dict[str, Any]:
return {
"id": state.id,
"scope_code": state.scope_code,
"period_month": state.period_month.isoformat() if state.period_month else None,
"invoice_no": state.invoice_no,
"invoice_date": state.invoice_date.isoformat() if state.invoice_date else None,
"status": state.status,
"folder_path": state.folder_path,
"folder_exists": state.folder_exists,
"material_fingerprint": state.material_fingerprint,
"matched_files": state.matched_files_json or {},
"missing_materials": state.missing_materials_json or [],
"last_actual_run_id": state.last_actual_run_id,
"last_checked_at": state.last_checked_at.isoformat() if state.last_checked_at else None,
"last_seen_erp_at": state.last_seen_erp_at.isoformat() if state.last_seen_erp_at else None,
"last_missing_notified_on": (
state.last_missing_notified_on.isoformat() if state.last_missing_notified_on else None
),
"updated_at": state.updated_at.isoformat() if state.updated_at else None,
}
def _serialize_run_item(item: VoucherCheckRunItem) -> dict[str, Any]:
"""序列化旧批次 invoice 行,并带上缺件数量便于明细表展示。"""
return {
"id": item.id,
"schedule_run_id": item.schedule_run_id,
"invoice_state_id": item.invoice_state_id,
"scope_code": item.scope_code,
"period_month": item.period_month.isoformat() if item.period_month else None,
"invoice_no": item.invoice_no,
"invoice_date": item.invoice_date.isoformat() if item.invoice_date else None,
"result": item.result,
"folder_path": item.folder_path,
"folder_exists": item.folder_exists,
"material_fingerprint": item.material_fingerprint,
"matched_files": item.matched_files_json or {},
"missing_materials": item.missing_materials_json or [],
"missing_count": len(item.missing_materials_json or []),
"error_code": item.error_code,
"error_message": item.error_message,
"checked_at": item.checked_at.isoformat() if item.checked_at else None,
"created_at": item.created_at.isoformat() if item.created_at else None,
}
def parse_period_month(raw: str | None) -> date:
"""解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取上一个自然月。"""
if not raw:
@@ -90,38 +41,6 @@ def parse_period_month(raw: str | None) -> date:
) from exc
def list_missing_states(
*,
task_id: int | None = None,
scope_code: str = "HXJM",
period: str | None = None,
limit: int = 200,
) -> dict[str, Any]:
"""
查询指定月份缺资料票(最新状态表)。
task_id 预留与排程绑定校验,本期仅用于响应回显。
"""
period_month = parse_period_month(period)
limit = max(1, min(int(limit or 200), 1000))
q = (
VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
status="missing",
)
.order_by(VoucherCheckInvoiceState.invoice_no.asc())
.limit(limit)
)
items = [_serialize_state(s) for s in q.all()]
return {
"task_id": task_id,
"scope_code": scope_code,
"period": period_month.strftime("%Y-%m"),
"count": len(items),
"items": items,
}
def _serialize_engine_run(run: VoucherCheckRun) -> dict[str, Any]:
return {
"id": run.id,
@@ -314,7 +233,7 @@ def list_run_items(
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""分页查询批次明细;优先返回新引擎按 invoice 聚合行,并附带按文件类型汇总。"""
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。"""
run = ScheduleRun.query.get(run_id)
if not run:
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
@@ -325,117 +244,33 @@ def list_run_items(
.order_by(VoucherCheckRun.id.desc())
.first()
)
if engine_run is not None:
items, aggregated = _engine_invoice_items(engine_run)
result_filter = str(result).strip() if result else ""
if result_filter:
items = [row for row in items if row.get("result") == result_filter]
total = len(items)
sliced = items[(page - 1) * page_size : page * page_size]
if engine_run is None:
return {
"run_id": run_id,
"engine_run_id": engine_run.id,
"run_no": run.run_no,
"page": page,
"page_size": page_size,
"total": total,
"items": sliced,
"subject_count": int(aggregated.get("subject_count") or 0),
"by_file_type": _serialize_file_type_rows(aggregated),
"total": 0,
"items": [],
"subject_count": 0,
"by_file_type": [],
}
q = VoucherCheckRunItem.query.filter_by(schedule_run_id=run_id)
if result:
q = q.filter(VoucherCheckRunItem.result == str(result).strip())
total = q.count()
rows = (
q.order_by(VoucherCheckRunItem.invoice_no.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
items, aggregated = _engine_invoice_items(engine_run)
result_filter = str(result).strip() if result else ""
if result_filter:
items = [row for row in items if row.get("result") == result_filter]
total = len(items)
sliced = items[(page - 1) * page_size : page * page_size]
return {
"run_id": run_id,
"engine_run_id": engine_run.id,
"run_no": run.run_no,
"page": page,
"page_size": page_size,
"total": total,
"items": [_serialize_run_item(r) for r in rows],
"subject_count": 0,
"by_file_type": [],
}
def get_invoice_latest(
*,
invoice_no: str,
scope_code: str = "HXJM",
period: str | None = None,
) -> dict[str, Any]:
"""查询单票最新状态及近期批次快照。"""
inv = str(invoice_no or "").strip()
if not inv:
raise ValidationError("invoice_no 必填", code="VOUCHER_CHECK.INVOICE_REQUIRED")
period_month = parse_period_month(period)
state = (
VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
invoice_no=inv,
).one_or_none()
)
if not state:
raise NotFoundError("发票状态不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
history = (
VoucherCheckRunItem.query.filter_by(
scope_code=scope_code,
period_month=period_month,
invoice_no=inv,
)
.order_by(VoucherCheckRunItem.id.desc())
.limit(20)
.all()
)
return {
"state": _serialize_state(state),
"recent_run_items": [_serialize_run_item(h) for h in history],
}
def list_states(
*,
scope_code: str = "HXJM",
period: str | None = None,
status: str | None = None,
invoice_no: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""工作台:按月/状态/发票号筛选最新状态。"""
period_month = parse_period_month(period)
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
q = VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
)
if status:
q = q.filter(VoucherCheckInvoiceState.status == str(status).strip())
if invoice_no:
q = q.filter(VoucherCheckInvoiceState.invoice_no.ilike(f"%{str(invoice_no).strip()}%"))
total = q.count()
rows = (
q.order_by(VoucherCheckInvoiceState.invoice_no.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return {
"scope_code": scope_code,
"period": period_month.strftime("%Y-%m"),
"page": page,
"page_size": page_size,
"total": total,
"items": [_serialize_state(r) for r in rows],
"items": sliced,
"subject_count": int(aggregated.get("subject_count") or 0),
"by_file_type": _serialize_file_type_rows(aggregated),
}
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/schedule_seed.py
用途:确保 accounting-voucher-check 默认周批 ScheduleTask 存在(周二 06:00 Asia/Shanghai)。
依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。
逻辑:迁移种子 + create_app / User after_commit 幂等补建;已存在的日批默认任务会改成周二。
逻辑:迁移种子 + create_app / User after_commit 幂等补建;已存在的日批改成周二,并剥离 schema 外的旧 job_params。
"""
from __future__ import annotations
@@ -14,6 +14,7 @@ from typing import Any
from sqlalchemy import event
from sqlalchemy.orm import Session
from sqlalchemy.orm.attributes import flag_modified
from app import db
from app.models import ScheduleTask, User
@@ -31,13 +32,33 @@ _HOOKS_REGISTERED = False
_SESSION_INFO_KEY = "_seed_voucher_check_schedule"
def _normalize_existing_job_params(raw: Any) -> tuple[dict[str, Any], bool]:
"""
把已有排程的 job_params 收成当前 schema。
核心逻辑:保留 DEFAULT_JOB_PARAMS 与 _advanced;丢掉共享盘时代的未知字段。
"""
from app.services.schedule.job_params import ADVANCED_PARAMS_KEY
current = dict(raw) if isinstance(raw, dict) else {}
cleaned: dict[str, Any] = {}
for key, default in DEFAULT_JOB_PARAMS.items():
value = current.get(key)
cleaned[key] = default if value is None else value
advanced = current.get(ADVANCED_PARAMS_KEY)
if isinstance(advanced, dict):
cleaned[ADVANCED_PARAMS_KEY] = advanced
return cleaned, current != cleaned
def ensure_default_voucher_check_schedule(
*,
commit: bool = True,
session: Any | None = None,
) -> ScheduleTask | None:
"""
幂等确保默认立账凭证检核日批排程存在。
幂等确保默认立账凭证检核周批排程存在。
核心逻辑:已存在任务会把日批 cron 改成周二,并剥离 schema 外的旧 job_params,
避免 worker 执行前校验 unknown params 整批失败。
Args:
commit: 是否立即提交。
@@ -56,6 +77,7 @@ def ensure_default_voucher_check_schedule(
.first()
)
if existing is not None:
changed = False
if existing.cron_expr == "0 6 * * *":
existing.cron_expr = DEFAULT_VOUCHER_CHECK_CRON
if existing.name == "立账凭证检核(日批)":
@@ -64,6 +86,17 @@ def ensure_default_voucher_check_schedule(
DEFAULT_VOUCHER_CHECK_CRON,
timezone_name="Asia/Shanghai",
) or existing.next_run_at
changed = True
cleaned_params, params_changed = _normalize_existing_job_params(existing.job_params)
if params_changed:
existing.job_params = cleaned_params
flag_modified(existing, "job_params")
changed = True
_LOGGER.info(
"stripped legacy accounting-voucher-check job_params id=%s",
existing.id,
)
if changed:
existing.updated_at = datetime.utcnow()
if commit:
sess.commit()
@@ -1,273 +0,0 @@
"""
backend/app/services/voucher_check/share_scanner.py
用途:共享盘健康检查、路径构造、目录枚举与精确文件名匹配。
依赖:config、fingerprint、core.errors.ServiceUnavailableError / ValidationError。
逻辑:runner 阶段 A 调用;健康失败整批失败;单票目录缺失记业务缺资料。
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from datetime import date
from pathlib import Path
from app.core.errors import ServiceUnavailableError, ValidationError
from app.services.voucher_check.config import (
RequiredFileRule,
VoucherCheckConfig,
resolve_share_root,
)
from app.services.voucher_check.fingerprint import build_material_fingerprint
@dataclass
class FileMeta:
"""直接子文件元数据。"""
name: str
size: int
mtime_ns: int
@dataclass
class InvoiceScanResult:
"""单票扫描结果。"""
invoice_no: str
folder_path: str
absolute_path: str
folder_exists: bool
material_fingerprint: str | None
matched_files: dict[str, str] = field(default_factory=dict)
missing_materials: list[dict[str, str]] = field(default_factory=list)
result: str = "missing" # complete / missing / technical_error
error_code: str | None = None
error_message: str | None = None
def ensure_share_healthy(config: VoucherCheckConfig) -> str:
"""
校验共享盘根目录可用。
核心逻辑:根存在、可 scandir、健康标记文件存在;失败抛 SHARE_UNAVAILABLE。
Returns:
解析后的绝对根路径。
"""
root = resolve_share_root(config)
root_path = Path(root)
try:
if not root_path.exists() or not root_path.is_dir():
raise ServiceUnavailableError(
"共享盘根目录不可用",
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
)
# [STEP 1] 轻量枚举证明 I/O 可用
with os.scandir(root_path) as it:
_ = next(it, None)
root_path.stat()
# [STEP 2] 健康标记:避免挂载丢失后空目录被误判为业务缺件
marker = (root_path / config.healthcheck_relative_path).resolve()
if not str(marker).startswith(str(root_path.resolve())):
raise ServiceUnavailableError(
"共享盘健康标记路径非法",
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
)
if not marker.is_file():
raise ServiceUnavailableError(
"共享盘健康标记文件缺失",
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
)
except ServiceUnavailableError:
raise
except OSError as exc:
raise ServiceUnavailableError(
"共享盘健康检查失败",
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
details={"error_type": type(exc).__name__},
) from exc
return str(root_path)
def _render_invoice_relative_path(
template: str,
*,
year: str,
month: str,
invoice_no: str,
) -> str:
"""渲染相对业务路径(不含 root 实际值,报告用)。"""
rendered = (
template.replace("{root}", "vouche")
.replace("{YYYY}", year)
.replace("{MM}", month)
.replace("{invoice_no}", invoice_no)
)
return rendered.strip("/").replace("\\", "/")
def build_invoice_absolute_path(
config: VoucherCheckConfig,
*,
root: str,
period_month: date,
invoice_no: str,
) -> tuple[str, str]:
"""
构造单票绝对路径与相对业务路径。
核心逻辑:invoice_no 仅 trim;含路径分隔符则视为非法(调用方记 technical_error)。
"""
year = f"{period_month.year:04d}"
month = f"{period_month.month:02d}"
invoice = str(invoice_no or "").strip()
if not invoice or "/" in invoice or "\\" in invoice or "\x00" in invoice or ".." in invoice:
raise ValidationError(
"发票号含非法路径字符",
code="VOUCHER_CHECK.INVOICE_PATH_INVALID",
details={"invoice_no": invoice_no},
)
relative = _render_invoice_relative_path(
config.directory_template,
year=year,
month=month,
invoice_no=invoice,
)
# 实际落盘:用真实 root 替换模板中的 {root}
absolute_template = (
config.directory_template.replace("{root}", root.rstrip("/\\"))
.replace("{YYYY}", year)
.replace("{MM}", month)
.replace("{invoice_no}", invoice)
)
absolute = str(Path(absolute_template))
resolved_root = Path(root).resolve()
resolved_abs = Path(absolute).resolve()
try:
resolved_abs.relative_to(resolved_root)
except ValueError as exc:
raise ValidationError(
"发票目录逃逸共享根",
code="VOUCHER_CHECK.INVOICE_PATH_INVALID",
details={"invoice_no": invoice},
) from exc
return absolute, relative
def list_direct_files(folder: Path) -> list[FileMeta]:
"""枚举发票目录直接子文件(忽略子目录与非普通文件)。"""
files: list[FileMeta] = []
if not folder.is_dir():
return files
with os.scandir(folder) as it:
for entry in it:
try:
if not entry.is_file(follow_symlinks=False):
continue
stat = entry.stat(follow_symlinks=False)
files.append(
FileMeta(
name=entry.name,
size=int(stat.st_size),
mtime_ns=int(getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))),
)
)
except OSError:
continue
return files
def match_required_files(
files: list[FileMeta],
rules: tuple[RequiredFileRule, ...],
*,
case_sensitive: bool,
) -> tuple[dict[str, str], list[dict[str, str]]]:
"""
按完整文件名精确匹配必检材料。
核心逻辑:任一候选命中即算该材料存在;不支持模糊/前缀匹配。
"""
if case_sensitive:
available = {f.name: f.name for f in files}
else:
available = {f.name.lower(): f.name for f in files}
matched: dict[str, str] = {}
missing: list[dict[str, str]] = []
for rule in rules:
if not rule.required:
continue
hit: str | None = None
for candidate in rule.accepted_filenames:
key = candidate if case_sensitive else candidate.lower()
if key in available:
hit = available[key]
break
if hit:
matched[rule.code] = hit
else:
missing.append({"code": rule.code, "name": rule.name})
return matched, missing
def scan_invoice_folder(
config: VoucherCheckConfig,
*,
root: str,
period_month: date,
invoice_no: str,
) -> InvoiceScanResult:
"""
扫描单票目录并判定齐全/缺资料。
核心逻辑:目录不存在→missing;存在则精确匹配必检文件名并生成指纹。
"""
try:
absolute, relative = build_invoice_absolute_path(
config,
root=root,
period_month=period_month,
invoice_no=invoice_no,
)
except ValidationError as exc:
return InvoiceScanResult(
invoice_no=str(invoice_no or "").strip(),
folder_path="",
absolute_path="",
folder_exists=False,
material_fingerprint=None,
result="technical_error",
error_code=exc.code,
error_message=exc.message,
)
folder = Path(absolute)
if not folder.exists() or not folder.is_dir():
missing = [{"code": r.code, "name": r.name} for r in config.required_files if r.required]
return InvoiceScanResult(
invoice_no=str(invoice_no).strip(),
folder_path=relative,
absolute_path=absolute,
folder_exists=False,
material_fingerprint=None,
missing_materials=missing,
result="missing",
)
files = list_direct_files(folder)
fingerprint = build_material_fingerprint([(f.name, f.size, f.mtime_ns) for f in files])
matched, missing = match_required_files(
files,
config.required_files,
case_sensitive=config.filename_case_sensitive,
)
return InvoiceScanResult(
invoice_no=str(invoice_no).strip(),
folder_path=relative,
absolute_path=absolute,
folder_exists=True,
material_fingerprint=fingerprint,
matched_files=matched,
missing_materials=missing,
result="complete" if not missing else "missing",
)
@@ -0,0 +1,133 @@
"""
backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py
用途:删除旧共享盘方案的 voucher_check_invoice_states / voucher_check_run_items。
依赖:Alembic revision na0b1c2d3e4f5。
逻辑:先删 run_items(外键指向 states),再删 states;引擎表不受影响。
Revision ID: vc2b3c4d5e6f
Revises: na0b1c2d3e4f5
Create Date: 2026-09-08 09:20:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "vc2b3c4d5e6f"
down_revision = "na0b1c2d3e4f5"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除旧一票一状态表;检核结果以 voucher_check_file_results 为准。"""
op.drop_index("ix_voucher_check_run_items_period_result", table_name="voucher_check_run_items")
op.drop_index("ix_voucher_check_run_items_run_result", table_name="voucher_check_run_items")
op.drop_index("ix_voucher_check_run_items_schedule_run_id", table_name="voucher_check_run_items")
op.drop_table("voucher_check_run_items")
op.drop_index("ix_voucher_check_invoice_states_notified_on", table_name="voucher_check_invoice_states")
op.drop_index("ix_voucher_check_invoice_states_invoice_no", table_name="voucher_check_invoice_states")
op.drop_index("ix_voucher_check_invoice_states_period_status", table_name="voucher_check_invoice_states")
op.drop_table("voucher_check_invoice_states")
def downgrade() -> None:
"""回建旧表结构,不恢复历史数据。"""
op.create_table(
"voucher_check_invoice_states",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("scope_code", sa.String(length=32), nullable=False),
sa.Column("period_month", sa.Date(), nullable=False),
sa.Column("invoice_no", sa.String(length=128), nullable=False),
sa.Column("invoice_date", sa.Date(), nullable=True),
sa.Column("status", sa.String(length=24), nullable=False),
sa.Column("folder_path", sa.String(length=1024), nullable=True),
sa.Column("folder_exists", sa.Boolean(), nullable=False, server_default=sa.text("false")),
sa.Column("material_fingerprint", sa.String(length=64), nullable=True),
sa.Column("matched_files_json", sa.JSON(), nullable=True),
sa.Column("missing_materials_json", sa.JSON(), nullable=True),
sa.Column(
"last_actual_run_id",
sa.BigInteger(),
sa.ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
),
sa.Column("last_checked_at", sa.DateTime(), nullable=True),
sa.Column("last_seen_erp_at", sa.DateTime(), nullable=True),
sa.Column("last_missing_notified_on", sa.Date(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint(
"scope_code",
"period_month",
"invoice_no",
name="uq_voucher_check_invoice_states_scope_period_invoice",
),
)
op.create_index(
"ix_voucher_check_invoice_states_period_status",
"voucher_check_invoice_states",
["period_month", "status"],
)
op.create_index(
"ix_voucher_check_invoice_states_invoice_no",
"voucher_check_invoice_states",
["invoice_no"],
)
op.create_index(
"ix_voucher_check_invoice_states_notified_on",
"voucher_check_invoice_states",
["last_missing_notified_on"],
)
op.create_table(
"voucher_check_run_items",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column(
"schedule_run_id",
sa.BigInteger(),
sa.ForeignKey("schedule_runs.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column(
"invoice_state_id",
sa.BigInteger(),
sa.ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"),
nullable=True,
),
sa.Column("scope_code", sa.String(length=32), nullable=False),
sa.Column("period_month", sa.Date(), nullable=False),
sa.Column("invoice_no", sa.String(length=128), nullable=False),
sa.Column("invoice_date", sa.Date(), nullable=True),
sa.Column("result", sa.String(length=24), nullable=False),
sa.Column("folder_path", sa.String(length=1024), nullable=True),
sa.Column("folder_exists", sa.Boolean(), nullable=False, server_default=sa.text("false")),
sa.Column("material_fingerprint", sa.String(length=64), nullable=True),
sa.Column("matched_files_json", sa.JSON(), nullable=True),
sa.Column("missing_materials_json", sa.JSON(), nullable=True),
sa.Column("error_code", sa.String(length=64), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("checked_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint(
"schedule_run_id",
"invoice_no",
name="uq_voucher_check_run_items_run_invoice",
),
)
op.create_index(
"ix_voucher_check_run_items_schedule_run_id",
"voucher_check_run_items",
["schedule_run_id"],
)
op.create_index(
"ix_voucher_check_run_items_run_result",
"voucher_check_run_items",
["schedule_run_id", "result"],
)
op.create_index(
"ix_voucher_check_run_items_period_result",
"voucher_check_run_items",
["period_month", "result"],
)
@@ -0,0 +1,146 @@
"""
backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py
用途:清掉立账凭证检核排程里共享盘时代的 job_params,避免 worker 报 unknown params。
依赖:Alembic revision vc2b3c4d5e6f;schedule_tasks 已存在。
逻辑:保留 scope_code / profile_code / 通知开关 / _advanced;日批 cron 改为周二。
Revision ID: vc3d4e5f6a7b
Revises: vc2b3c4d5e6f
Create Date: 2026-09-08 10:10:00.000000
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
import sqlalchemy as sa
from alembic import op
revision = "vc3d4e5f6a7b"
down_revision = "vc2b3c4d5e6f"
branch_labels = None
depends_on = None
_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK"
_WEEKLY_CRON = "0 6 * * 2"
_WEEKLY_NAME = "立账凭证检核(周批)"
_DAILY_CRON = "0 6 * * *"
_DAILY_NAME = "立账凭证检核(日批)"
_TZ_NAME = "Asia/Shanghai"
_DEFAULTS = {
"profile_code": "sales",
"scope_code": "HXJM",
"notify_missing_enabled": True,
"notify_failure_enabled": True,
}
def _as_dict(raw) -> dict:
"""把 JSON 列读成 dict;驱动可能返回 dict 或字符串。"""
if raw is None:
return {}
if isinstance(raw, dict):
return dict(raw)
if isinstance(raw, str):
text = raw.strip()
if not text:
return {}
loaded = json.loads(text)
return dict(loaded) if isinstance(loaded, dict) else {}
return {}
def _clean_job_params(raw) -> dict:
"""只保留当前 schema 字段,丢掉 directory_template / required_files 等旧键。"""
current = _as_dict(raw)
cleaned = {}
for key, default in _DEFAULTS.items():
value = current.get(key)
cleaned[key] = default if value is None else value
advanced = current.get("_advanced")
if isinstance(advanced, dict):
cleaned["_advanced"] = advanced
return cleaned
def _next_weekly_run_utc_naive() -> datetime:
"""计算下一个周二 06:00 Asia/Shanghai,写入 naive UTC。"""
try:
from croniter import croniter
from zoneinfo import ZoneInfo
tz = ZoneInfo(_TZ_NAME)
next_local = croniter(_WEEKLY_CRON, datetime.now(tz)).get_next(datetime)
if next_local.tzinfo is None:
next_local = next_local.replace(tzinfo=tz)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
except Exception:
tz = timezone(timedelta(hours=8))
now_local = datetime.now(tz)
days = (1 - now_local.weekday()) % 7
next_local = (now_local + timedelta(days=days)).replace(
hour=6, minute=0, second=0, microsecond=0
)
if next_local <= now_local:
next_local = next_local + timedelta(days=7)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
def upgrade() -> None:
"""清洗 accounting-voucher-check 排程参数;无任务时跳过。"""
conn = op.get_bind()
rows = conn.execute(
sa.text(
"""
SELECT id, job_params, cron_expr, name
FROM schedule_tasks
WHERE schedule_no = :sno
OR platform_api_path = 'accounting-voucher-check'
"""
),
{"sno": _SCHEDULE_NO},
).mappings().all()
now = datetime.utcnow()
next_run = _next_weekly_run_utc_naive()
for row in rows:
cleaned = _clean_job_params(row["job_params"])
cron_expr = row["cron_expr"]
name = row["name"]
next_run_at = None
if cron_expr == _DAILY_CRON:
cron_expr = _WEEKLY_CRON
next_run_at = next_run
if name == _DAILY_NAME:
name = _WEEKLY_NAME
conn.execute(
sa.text(
"""
UPDATE schedule_tasks
SET job_params = CAST(:job_params AS JSONB),
cron_expr = :cron_expr,
name = :name,
next_run_at = COALESCE(:next_run_at, next_run_at),
updated_at = :now
WHERE id = :id
"""
).bindparams(
sa.bindparam("job_params", type_=sa.String()),
sa.bindparam("next_run_at", type_=sa.DateTime(), required=False),
),
{
"id": int(row["id"]),
"job_params": json.dumps(cleaned, ensure_ascii=False),
"cron_expr": cron_expr,
"name": name,
"now": now,
"next_run_at": next_run_at,
},
)
def downgrade() -> None:
"""旧共享盘字段无法无损恢复,downgrade 为空操作。"""
return
@@ -1,39 +0,0 @@
"""
backend/scripts/export_voucher_check_openapi.py
用途:导出立账凭证检核 Tool OpenAPI 到 docs/openapi,供 Dify 粘贴/对比。
依赖:voucher_check.openapi_spec。
逻辑:仓库静态 JSON 使用占位地址;各环境请用 URL 导入 GET .../openapi.json。
"""
from __future__ import annotations
import json
import os
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
# 不经 app 包导入,避免导出脚本依赖本机 Flask venv
_SPEC_PATH = ROOT / "backend" / "app" / "services" / "voucher_check" / "openapi_base.json"
def main() -> None:
base = (
os.getenv("HXOPS_TOOLS_API_BASE")
or os.getenv("PUBLIC_BASE_URL")
or "http://127.0.0.1:5052"
).rstrip("/")
spec = json.loads(_SPEC_PATH.read_text(encoding="utf-8"))
if isinstance(spec.get("servers"), list) and spec["servers"]:
spec["servers"][0]["url"] = base
spec["servers"][0]["description"] = "HXOPS_TOOLS_API_BASE"
out_dir = ROOT / "docs" / "openapi"
out_dir.mkdir(parents=True, exist_ok=True)
json_path = out_dir / "accounting_voucher_check_tools_openapi.json"
json_path.write_text(json.dumps(spec, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Wrote {json_path}")
print(f"Import URL: {base}/api/accounting-voucher-check/tools/openapi.json")
if __name__ == "__main__":
main()
@@ -1,106 +0,0 @@
"""
backend/tests/voucher_check/test_share_and_fingerprint.py
用途:立账凭证检核目录模板、文件名精确匹配与指纹稳定性单测。
依赖:pytest、临时目录、voucher_check 领域模块。
逻辑:不连 Oracle/共享盘;覆盖精确匹配、0 字节齐全、子目录不计、指纹变化。
"""
from __future__ import annotations
from datetime import date
from pathlib import Path
import pytest
from app.core.errors import ValidationError
from app.services.voucher_check.config import (
RequiredFileRule,
validate_directory_template,
)
from app.services.voucher_check.fingerprint import build_material_fingerprint
from app.services.voucher_check.share_scanner import (
FileMeta,
match_required_files,
scan_invoice_folder,
)
def test_directory_template_rejects_unknown_placeholder():
with pytest.raises(ValidationError) as exc:
validate_directory_template("{root}/{YYYY}/{MM}/{invoice_no}/{extra}")
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
def test_exact_filename_match_and_zero_byte_counts():
rules = (
RequiredFileRule(
code="price_check_sheet",
name="核价单",
required=True,
accepted_filenames=("核价单.pdf",),
),
RequiredFileRule(
code="purchase_order",
name="采购单",
required=True,
accepted_filenames=("采购单.pdf",),
),
)
files = [
FileMeta(name="核价单.pdf", size=0, mtime_ns=1),
FileMeta(name="采购单.pdf", size=10, mtime_ns=2),
]
matched, missing = match_required_files(files, rules, case_sensitive=True)
assert matched["price_check_sheet"] == "核价单.pdf"
assert matched["purchase_order"] == "采购单.pdf"
assert missing == []
def test_subdir_same_name_does_not_count(tmp_path: Path):
"""直接子文件才命中;子目录内同名文件不算。"""
from app.services.voucher_check.config import VoucherCheckConfig
root = tmp_path / "vouche"
inv_dir = root / "2026" / "08" / "INV001"
inv_dir.mkdir(parents=True)
nested = inv_dir / "nested"
nested.mkdir()
(nested / "核价单.pdf").write_bytes(b"x")
(inv_dir / "采购单.pdf").write_bytes(b"y")
cfg = VoucherCheckConfig(
scope_code="HXJM",
directory_template="{root}/{YYYY}/{MM}/{invoice_no}",
required_files=(
RequiredFileRule("price_check_sheet", "核价单", True, ("核价单.pdf",)),
RequiredFileRule("purchase_order", "采购单", True, ("采购单.pdf",)),
),
filename_case_sensitive=True,
notify_missing_enabled=False,
notify_failure_enabled=False,
same_day_dedup_enabled=False,
local_root=str(root),
share_unc="",
healthcheck_relative_path=".hxops-share-ready",
erp_dsn="x",
erp_username="u",
erp_password="p",
)
result = scan_invoice_folder(
cfg,
root=str(root),
period_month=date(2026, 8, 1),
invoice_no="INV001",
)
assert result.result == "missing"
assert any(m["code"] == "price_check_sheet" for m in result.missing_materials)
assert result.matched_files.get("purchase_order") == "采购单.pdf"
def test_fingerprint_stable_and_changes_on_mtime():
a = build_material_fingerprint([("a.pdf", 1, 100), ("b.pdf", 2, 200)])
b = build_material_fingerprint([("b.pdf", 2, 200), ("a.pdf", 1, 100)])
assert a == b
c = build_material_fingerprint([("a.pdf", 1, 101), ("b.pdf", 2, 200)])
assert a != c
@@ -1,52 +0,0 @@
"""
backend/tests/voucher_check/test_tool_auth_and_openapi.py
用途:立账凭证检核 Tool OpenAPI 静态规格校验(不依赖 Flask venv)。
依赖:pytest、openapi_base.json。
逻辑:直接读 JSON,校验 operationId 与 securitySchemes。
"""
from __future__ import annotations
import json
from pathlib import Path
_SPEC = (
Path(__file__).resolve().parents[2]
/ "app"
/ "services"
/ "voucher_check"
/ "openapi_base.json"
)
def test_openapi_base_contains_expected_operations():
spec = json.loads(_SPEC.read_text(encoding="utf-8"))
paths = spec["paths"]
assert (
paths["/api/accounting-voucher-check/tools/tasks/{task_id}/missing"]["get"]["operationId"]
== "list_voucher_missing"
)
assert (
paths["/api/accounting-voucher-check/tools/runs/{run_id}/items"]["get"]["operationId"]
== "list_voucher_run_items"
)
assert (
paths["/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest"]["get"]["operationId"]
== "get_voucher_invoice_latest"
)
assert "BearerAuth" in spec["components"]["securitySchemes"]
assert "IntegrationKey" in spec["components"]["securitySchemes"]
def test_docs_openapi_export_in_sync():
docs = (
Path(__file__).resolve().parents[3]
/ "docs"
/ "openapi"
/ "accounting_voucher_check_tools_openapi.json"
)
assert docs.is_file(), "请运行 python backend/scripts/export_voucher_check_openapi.py"
exported = json.loads(docs.read_text(encoding="utf-8"))
base = json.loads(_SPEC.read_text(encoding="utf-8"))
assert exported["paths"].keys() == base["paths"].keys()
@@ -167,3 +167,37 @@ def test_workspace_lists_pre_engine_failure_for_selected_period(app, client, adm
assert item["run_no"] == "RUN-PREENGINE-FAILED"
assert item["status"] == "technical_failed"
assert item["error_message"] == "未配置销售开票附件文档库根目录"
def test_seed_strips_legacy_share_job_params(app):
"""已有排程若仍带共享盘旧字段,启动/入队种子必须剥掉,否则 worker 会 unknown params。"""
with app.app_context():
_ensure_user(username="admin", role="admin")
task = ensure_default_voucher_check_schedule(commit=True)
assert task is not None
task.job_params = {
"scope_code": "HXJM",
"profile_code": "sales",
"notify_missing_enabled": True,
"notify_failure_enabled": True,
"directory_template": "{root}/{YYYY}/{MM}/{invoice_no}",
"dir_template": "{root}/{YYYY}/{MM}/{invoice_no}",
"required_files": ["核价单.pdf", "采购单.pdf"],
"filename_case_sensitive": True,
"case_sensitive": False,
"same_day_dedup_enabled": True,
"same_day_dedup": True,
}
db.session.commit()
refreshed = ensure_default_voucher_check_schedule(commit=True)
params = refreshed.job_params if isinstance(refreshed.job_params, dict) else {}
assert "directory_template" not in params
assert "dir_template" not in params
assert "required_files" not in params
assert "filename_case_sensitive" not in params
assert "case_sensitive" not in params
assert "same_day_dedup_enabled" not in params
assert "same_day_dedup" not in params
assert params["scope_code"] == "HXJM"
assert params["profile_code"] == "sales"
+2 -13
View File
@@ -61,10 +61,7 @@ services:
# 固资履历:必须注入 LOCAL_ROOT,避免只加载 .env.shared 时回退到 Linux 不可达的 UNC
- FIXED_ASSET_HISTORY_LOCAL_ROOT=${FIXED_ASSET_HISTORY_LOCAL_ROOT:-}
- FIXED_ASSET_HISTORY_SHARE_ROOT=${FIXED_ASSET_HISTORY_SHARE_ROOT:-}
# 立账凭证检核:容器必须读 LOCAL_ROOT,不能依赖 UNC
- VOUCHER_CHECK_LOCAL_ROOT=${VOUCHER_CHECK_LOCAL_ROOT:-}
- VOUCHER_CHECK_SHARE_UNC=${VOUCHER_CHECK_SHARE_UNC:-}
- VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=${VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH:-.hxops-share-ready}
# 立账凭证检核:ERP 只读;文档库走 DMS 环境变量
- VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-}
- VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-}
- VOUCHER_CHECK_ERP_PASSWORD=${VOUCHER_CHECK_ERP_PASSWORD:-}
@@ -81,9 +78,6 @@ services:
# test/prod 的 FIXED_ASSET_HISTORY_LOCAL_ROOT 分别指向对应路径;未使用的一侧为空目录无影响。
- /mnt/hxops-fixed-asset-history-test:/mnt/hxops-fixed-asset-history-test:ro
- /mnt/hxops-fixed-asset-history-prod:/mnt/hxops-fixed-asset-history-prod:ro
# 立账凭证检核共享盘:宿主机 CIFS 挂载后再 bind 只读进容器
- /mnt/hxops-voucher-check-test:/mnt/hxops-voucher-check-test:ro
- /mnt/hxops-voucher-check-prod:/mnt/hxops-voucher-check-prod:ro
# 货代发货通知 RPA:分别挂载 test/prod Worker 的共享数据目录
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
@@ -180,10 +174,7 @@ services:
- SHIPPING_NOTICE_STORAGE_ROOT=${SHIPPING_NOTICE_STORAGE_ROOT:-/app/data/shipping_notice}
- FREIGHT_INVENTORY_DROP_DIR=${FREIGHT_INVENTORY_DROP_DIR:-/app/data/shipping_notice/freight_rpa/inventory_drop}
- FREIGHT_RPA_INVENTORY_TRIGGER_DIR=${FREIGHT_RPA_INVENTORY_TRIGGER_DIR:-/app/data/shipping_notice/freight_rpa/inventory_triggers}
# 立账凭证检核:日批在 schedule-worker 内执行,必须与 backend 同挂载
- VOUCHER_CHECK_LOCAL_ROOT=${VOUCHER_CHECK_LOCAL_ROOT:-}
- VOUCHER_CHECK_SHARE_UNC=${VOUCHER_CHECK_SHARE_UNC:-}
- VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=${VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH:-.hxops-share-ready}
# 立账凭证检核:周批在 schedule-worker 内执行
- VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-}
- VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-}
- VOUCHER_CHECK_ERP_PASSWORD=${VOUCHER_CHECK_ERP_PASSWORD:-}
@@ -192,8 +183,6 @@ services:
volumes:
- ./oracle_client:/app/oracle_client:ro
- hxops_runtime_data:/app/data
- /mnt/hxops-voucher-check-test:/mnt/hxops-voucher-check-test:ro
- /mnt/hxops-voucher-check-prod:/mnt/hxops-voucher-check-prod:ro
# 库存 RPA trigger 由 schedule-worker 写入,必须与 backend 同挂 CIFS,否则 Windows Worker 看不到
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
+1 -1
View File
@@ -216,7 +216,7 @@
- **文档库**:复用现有文档管理系统(全公司一个库,LibraryID 与合同相同);销售开票附件是该库下独立文件夹,只单独配根 FolderID,不得复用合同根目录。
- **通知**:每个检核批次一条企业微信汇总;接收人在界面从系统用户多选,未配置则不发。
- **判定边界**:只做文件获取、命名/关联校验和归档结果;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。
- **实现状态**:周任务已按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总迁移;PO/OA 打印仍待接线。Dify Chatflow 待按新口径重编。
- **实现状态**:周任务已按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总落地;PO/OA 打印仍待接线。不做 Chatflow;查询走工作台 API。
- 权威需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。
### 3.x 货代发货通知库存源补充需求
@@ -6,12 +6,11 @@
| **技术设计** | 研发 | [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) |
| **当前代码部署清单(旧实现)** | 运维、研发 | [ops-checklist.md](ops-checklist.md) |
| **Dify 编排草稿(旧引擎 Tool)** | 研发 | [dify-chatflow-draft.md](dify-chatflow-draft.md) |
| **部署验收清单** | 运维、研发 | [ops-checklist.md](ops-checklist.md) |
**定位**:以业务方 Profile 驱动的批量资料检核;**每周二**增量处理上一个自然月。销售开票附件先落入文档库类型目录,再按 `invoice` 归入「所有归档」。
**要解决的问题**:不同业务方从 ERP、OA、固定目录等来源获取不同必检资料,统一检核、归档、汇总缺件并通知。
**检核内容**:只做必检文件的获取、存在性和归档结果;不做文件内容解析或金额、供应商等字段一致性核对。
**结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数;企业微信每批一条汇总通知,完整明细以 Excel 与执行记录为准。
**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。仓库内现有代码仍是旧实现(当前自然月共享盘文件名存在性),实施前须按 [technical-design.md](technical-design.md) 改造,不得按旧口径扩展。
**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。ERP PO / OA 销货放行打印仍待接线。
@@ -4,7 +4,7 @@
> 更新时间:2026-09-08
> 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置
>
> 本文是本期需求权威。仓库里现有「当前自然月 + 单一共享盘 + 固定文件名存在性」是旧实现,不得作为本期验收口径;旧实现部署见 [ops-checklist.md](ops-checklist.md)。
> 本文是本期需求权威。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘存在性扫描、Chatflow Tool 与一票一状态表已移除,不得再按该口径扩展。
## 1. 背景与目标
@@ -1,197 +0,0 @@
# 立账凭证检核 — Dify Chatflow 编排草稿
> **状态**:草稿(待 Dify 画布落地)
> **口径**:本文对应仓库内**旧引擎** Tool(当月共享盘存在性、`mode`/`invoice_no`)。销售一期按 Profile、上一个月、批次汇总通知改造后,须重编意图与 Tool,不得把本文当作新方案编排手册。
> **前提**:HXOPS Tool / 工作台 API 已就绪;本文件只约定意图 → Tool 映射与节点配置,不参与文件是否齐全的判定。
> **参考**:文件检核 Chatflow 手册 [../file-check/technical.md](../file-check/technical.md) 第二部分;新方案设计 [technical-design.md](technical-design.md)。
---
## 1. 设计原则
1. Dify **只做**意图识别、调 Tool、组织自然语言回复。
2. **禁止**让 LLM 判断「文件在不在」或读取共享盘/附件内容。
3. 启动检核复用现有 `POST /api/file-check/tools/tasks/run`,通过顶层 `mode` / `invoice_no` 区分模式(Dify 友好;亦兼容嵌套 `run_options`)。
4. 缺资料/单票查询走 `/api/accounting-voucher-check/tools/*`。
5. 进度卡仍走工作台 file-check 轮询链路(`ChatToolRun` 绑定 + `progress_metrics`)。
---
## 2. 意图清单
| 意图 code | 示例话术 | Tool | 关键参数 |
| --- | --- | --- | --- |
| `run_incremental` | 执行今日立账凭证检核 | `run_file_check` | 顶层 `mode=incremental` |
| `run_force_all` | 重新检核当月全部 | `run_file_check` | 顶层 `mode=force_all` |
| `run_single` | 检核发票 INV-xxx | `run_file_check` | 顶层 `mode=single` + `invoice_no` |
| `query_latest` | 查询最新检核结果 | `get_latest_file_check_run` | `task_id` |
| `query_run` | 查询批次 xxx | `get_file_check_run` | `run_id` |
| `query_missing` | 查询缺资料发票 | `list_voucher_missing` | `task_id`,可选 `period` |
| `query_invoice` | 发票 INV-xxx 检核结果 | `get_voucher_invoice_latest` | `invoice_no` |
| `capability` | 你能做什么 | (无 Tool) | 固定能力说明文案 |
| `fallback` | 无法识别 | (无 Tool) | 引导上述话术 |
---
## 3. Tool 注册(建议 OpenAPI 操作)
### 3.1 复用 file-check(已有)
| operationId(建议) | Method / Path | 说明 |
| --- | --- | --- |
| `run_file_check` | `POST /api/file-check/tools/tasks/run` | Body 增加顶层 `mode` / `invoice_no`(兼容 `run_options`) |
| `get_file_check_run` | `GET /api/file-check/tools/runs/{run_id}` | 查批次 |
| `get_latest_file_check_run` | `GET /api/file-check/tools/tasks/{task_id}/latest-run` | 最新批次 |
| `download_file_check_excel` | `GET /api/file-check/tools/runs/{run_id}/excel` | Excel(可选,前端也可下) |
> **Dify 注意**:部分版本对 OpenAPI **嵌套 object**(`run_options`)不展示输入框。请绑定顶层 `mode`、`invoice_no`。改完 OpenAPI 后须在 Dify **重新导入/更新** file-check 工具包。
`RunCheckRequest`(Dify 推荐写法):
```json
{
"task_id": 12,
"hxops_turn_id": "{{#ctx.hxops_turn_id#}}",
"conversation_id": "{{#sys.conversation_id#}}",
"user_message": "{{#sys.query#}}",
"mode": "incremental",
"invoice_no": null
}
```
### 3.2 本域新增(HXOPS 已实现,可 URL 导入)
| operationId | Method / Path | 说明 |
| --- | --- | --- |
| `list_voucher_missing` | `GET /api/accounting-voucher-check/tools/tasks/{task_id}/missing` | Query: `period`, `limit` |
| `list_voucher_run_items` | `GET /api/accounting-voucher-check/tools/runs/{run_id}/items` | Query: `result`, `page` |
| `get_voucher_invoice_latest` | `GET /api/accounting-voucher-check/tools/invoices/{invoice_no}/latest` | Query: `period` |
**Dify 导入**:
```text
GET {HXOPS_TOOLS_API_BASE}/api/accounting-voucher-check/tools/openapi.json
```
鉴权与 file-check **同一密钥**:`FILE_CHECK_TOOL_API_KEY` 或 `INTEGRATION_API_KEY`(Bearer / `X-Integration-Key`)。`openapi.json` 本身无需鉴权。
---
## 4. 画布节点建议顺序
```text
开始
→ 解析运行态上下文(agent_runtime_context:task_id / hxops_turn_id)
→ 意图识别 LLM(输出 intent + invoice_no?)
→ 意图分支
├─ run_* → HTTP Tool 启动检核 → 回复「已启动,请看进度卡」
├─ query_latest → latest-run Tool → 摘要回复(齐全/缺资料/跳过)
├─ query_missing→ missing Tool → 列表摘要 + 引导打开工作台记录
├─ query_invoice→ invoice latest Tool → 单票结论卡文案
├─ capability → 固定能力说明
└─ fallback → 引导话术
→ 结束
```
要点:
- `task_id` 必须来自 **Agent 绑定的 `bound_schedule_task_id` / runtime refs**,禁止让用户随口编造或 LLM 瞎填。
- `hxops_turn_id` 必传,保证进度卡能绑到本轮助手消息。
- 启动成功后**不要**在 Chatflow 里同步轮询到结束;进度由前端 `ToolRunProgressCard` 负责。
---
## 5. 意图识别 Prompt 草稿
```text
你是「立账凭证检核」助手的意图分类器。只输出 JSON,不要解释。
可选 intent:
- run_incremental:执行今日/当月增量检核
- run_force_all:重新检核当月全部(不跳过)
- run_single:检核指定发票(需抽取 invoice_no)
- query_latest:查最新检核结果
- query_run:查指定批次(若用户给出 run_no/run_id,放入 run_ref)
- query_missing:查缺资料发票
- query_invoice:查某发票最近结论(需 invoice_no)
- capability:询问能力
- fallback:其它
规则:
1. 本助手只做「共享盘必检材料是否存在」,不核对金额/供应商,不回写 ERP。
2. 无法确定发票号时,run_single / query_invoice 不要猜,改用 fallback 并追问。
3. invoice_no 保持用户原文(仅去首尾空白),不要改写。
输出 schema:
{
"intent": "...",
"invoice_no": null,
"run_ref": null,
"period": null
}
```
`[PARAM_TUNING]` 建议 Temperature ≤ 0.2,避免发散意图。
---
## 6. 回复文案要点(Answer 节点)
| 场景 | 回复应包含 |
| --- | --- |
| 启动成功 | 已启动、批次号、提示查看进度卡(当月总数/待检/跳过/齐全/缺资料) |
| `check_running` | 已有任务执行中,请稍候或查最新结果 |
| 最新结果 | 月份、齐全/缺资料/跳过计数;有 Excel 则提示下载 |
| 缺资料列表 | 票数 + 前几张发票号 + 缺项;引导 `/workspace/accounting-voucher-check` |
| 单票 | 齐全或缺资料 + 缺项名;目录相对路径(勿暴露宿主机绝对路径) |
| 能力说明 | 明确「只查文件在不在」「不读内容」「不回写 ERP」 |
| 共享盘/ERP 失败 | 转述错误码友好文案,提示联系运维检查挂载/Oracle |
---
## 7. Agent Registry 配置(HXOPS 侧)
落地 Chatflow 时同步:
| 项 | 建议值 |
| --- | --- |
| Agent 名称 | 立账凭证检核 |
| `bound_schedule_task_id` | `SCH-ACCOUNTING-VOUCHER-CHECK` 对应 id |
| `capabilities.task_progress` | `true` |
| Dify app | 本 Chatflow 应用 |
| 知识库同步 | 关闭(任务级 `kb_sync_enabled=false`) |
进度展示:服务端已写 `progress_metrics`(齐全/缺资料等),前端进度卡自动切换,无需 RoHS 八格文案。
---
## 8. 联调检查单(Chatflow)
- [ ] 话术「执行今日立账凭证检核」→ `mode=incremental`,进度卡出现
- [ ] 「重新检核当月全部」→ `force_all`,完成后 `skipped_count=0`
- [ ] 「检核发票 {真实 apa08}」→ `single`,可跳过历史不影响
- [ ] 「查询缺资料发票」→ missing Tool,列表与工作台一致
- [ ] 运行中重复启动 → `check_running`,不双开批次
- [ ] LLM 未被要求/未尝试判断文件内容
---
## 9. 与文件检核 Chatflow 的差异(编排时勿混)
| 点 | 文件检核 | 立账凭证检核 |
| --- | --- | --- |
| 队列 | SRM 未检核 | ERP 当月发票清单 |
| 判定 | Dify Workflow/字段规则 | **仅 HXOPS 文件名存在性** |
| 启动 Body | 通常无 mode | **须传顶层 `mode`(单票再加 `invoice_no`)** |
| 历史知识库检索 | 有 | **无**(默认不入 KB) |
| 进度格 | 合格/不合格/人工 | 齐全/缺资料/跳过 |
---
## 10. 落地待办(给编排同学)
1. 在 Dify 新建独立 Chatflow(勿直接改 RoHS 画布)。
2. 导入/配置上述 HTTP Tools(file-check + accounting-voucher-check)。
3. 按 §4 搭意图分支与 Prompt。
4. HXOPS 注册 Agent 并绑定排程任务。
5. 用 §8 联调;通过后把本文状态改为「已落地」,并链到正式导出 OpenAPI(若另出 voucher OpenAPI 文件)。
@@ -1,11 +1,10 @@
# 立账凭证检核 — 当前代码(旧实现)部署验收清单
# 立账凭证检核 — 部署验收清单
> **不是**销售一期新需求的验收清单。本文只覆盖仓库内现有实现:当前自然月、HXJM `apa_file` 发票清单、共享盘固定文件名存在性(核价单/采购单)。
> 覆盖当前引擎:每周二检核**上一个自然月**、HXJM `apa_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。
>
> 产品需求与目标设计见 [demand.md](demand.md)、[technical-design.md](technical-design.md)。按新方案上线前须重写本文。
> 产品需求见 [demand.md](demand.md),设计见 [technical-design.md](technical-design.md)。
>
> 适用环境:dev / test / prod
> 目标:完成 DB 迁移、环境变量、共享盘挂载后,能跑通**旧实现**日批/手动触发并看到进度与记录。
> 适用环境:dev / test / prod
## 0. 变更摘要(上线前确认)
@@ -13,27 +12,29 @@
| --- | --- |
| Job key | `accounting-voucher-check` |
| 默认排程号 | `SCH-ACCOUNTING-VOUCHER-CHECK` |
| Cron | `0 6 * * *`(Asia/Shanghai) |
| 必检材料(暂定) | `核价单.pdf`、`采购单.pdf` |
| 迁移 revision | `a0b1c2d3e4f5` |
| Cron | `0 6 * * 2`(Asia/Shanghai,每周二 06:00) |
| 检核期间 | 上一个自然月 |
| 销售类型目录 | PO订单、报关资料、销货单、发票、报关单、提单 |
| 引擎表 | `voucher_check_profiles` / `runs` / `subjects` / `file_results` / `notifications` |
| 已删除旧表 | `voucher_check_invoice_states`、`voucher_check_run_items`(revision `vc2b3c4d5e6f`) |
| 旧 job_params 清洗 | revision `vc3d4e5f6a7b`:去掉共享盘字段;启动种子同样幂等剥离 |
| 工作台入口 | `/workspace/accounting-voucher-check` |
---
## 1. 数据库迁移
- [ ] 备份目标库(至少 `schedule_tasks` / 相关 schema)
- [ ] 备份目标库
- [ ] 后端目录执行:
```bash
cd backend
# 激活对应环境 venv
flask db upgrade
```
- [ ] 确认表存在:
- `voucher_check_invoice_states`
- `voucher_check_run_items`
- [ ] 确认引擎表存在:`voucher_check_profiles`、`voucher_check_runs`、`voucher_check_subjects`、`voucher_check_file_results`、`voucher_check_notifications`
- [ ] 确认旧表已删除:`voucher_check_invoice_states`、`voucher_check_run_items`
- [ ] 确认排程 `job_params` 仅含 `profile_code` / `scope_code` / 两个通知开关(无 `directory_template` / `required_files`)
- [ ] 确认种子排程存在(有用户时):
```sql
@@ -44,121 +45,78 @@ SELECT id, schedule_no, name, cron_expr, platform_api_path, enabled, next_run_at
```
- [ ] 若无用户时尚无种子:先建管理员账号,再重启 `hxops-backend`(启动钩子会补建)
- [ ] 管理后台 → 排程:可见「立账凭证检核」,`job_params` 含必检材料 JSON
- [ ] 管理后台 → 排程:可见「立账凭证检核」,`job_params` 含 `profile_code=sales`、`scope_code=HXJM`
---
## 2. 环境变量
写入 `.env.<env>`(密码勿提交仓库):
写入 `.env.<env>`(密码勿提交仓库)。文档库登录可复用 `CONTRACT_DMS_*`;销售开票附件根目录必须单独配置:
```bash
# 共享盘(Linux/容器必须 LOCAL_ROOT)
VOUCHER_CHECK_SHARE_UNC=\\192.168.100.230\ai_file\vouche
VOUCHER_CHECK_LOCAL_ROOT=/mnt/hxops-voucher-check-test # prod 换 prod 路径
VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH=.hxops-share-ready
# Oracle(只读;未单独配置 VOUCHER_CHECK_ERP_* 时复用 ERP_DB_DSN / ERP_USERNAME,再回退 CONTRACT_PAYMENT_ERP_*)
VOUCHER_CHECK_ERP_DSN=${ERP_DB_DSN}
VOUCHER_CHECK_ERP_USERNAME=<readonly-user> # 可省略,回退 ERP_USERNAME 或 CONTRACT_PAYMENT_ERP_USERNAME
VOUCHER_CHECK_ERP_USERNAME=<readonly-user>
VOUCHER_CHECK_ERP_PASSWORD=<secret>
VOUCHER_CHECK_ERP_TIMEOUT_SECONDS=30
# 文档库(LibraryID 与合同相同;只单独配销售根 FolderID)
VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=<sales-root-folder-id>
# 如需覆盖合同 DMS 登录:
# VOUCHER_CHECK_DMS_BASE_URL=
# VOUCHER_CHECK_DMS_LIBRARY_ID=
# VOUCHER_CHECK_DMS_USERNAME=
# VOUCHER_CHECK_DMS_PASSWORD=
```
检查:
- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_*`
- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_ERP_*` / `VOUCHER_CHECK_DMS_*`
- [ ] 密码未出现在 `job_params`、日志样例、Excel 字段中
- [ ] 不再配置 `VOUCHER_CHECK_LOCAL_ROOT` / `VOUCHER_CHECK_SHARE_*`(旧共享盘方案已移除)
---
## 3. 共享盘挂载(当前阻塞项)
## 3. 排程与通知配置
对齐固资履历思路:宿主机 CIFS → bind 进容器只读。
示意(路径按环境替换):
```bash
# 宿主机
sudo mkdir -p /mnt/hxops-voucher-check-test
# 使用只读 SMB 账号挂载 ai_file 或 vouche 子路径到 LOCAL_ROOT
# 健康标记(根目录下)
sudo touch /mnt/hxops-voucher-check-test/.hxops-share-ready
# 容器内验收
docker exec hxops-backend test -f /mnt/hxops-voucher-check-test/.hxops-share-ready
docker exec hxops-schedule-worker test -f /mnt/hxops-voucher-check-test/.hxops-share-ready
# 抽查当月目录(示例)
docker exec hxops-backend ls "/mnt/hxops-voucher-check-test/$(date +%Y)/$(date +%m)" | head
```
- [ ] backend 与 schedule-worker 均可读健康标记
- [ ] 用真实 `apa08`(含 `+` 等特殊字符)抽查子目录名一致
- [ ] Compose 已挂载 `/mnt/hxops-voucher-check-test|prod`(见根目录 `docker-compose.yml`)
- [ ] recreate backend + schedule-worker 使 env/volume 生效
> 未挂载或缺少健康标记时:批次应 **整批 failed**,且不写入业务「缺资料」单票状态。
---
## 4. 排程与通知配置
- [ ] 管理后台打开任务「立账凭证检核(日批)」
- [ ] `enabled=true`,时区 `Asia/Shanghai`,Cron `0 6 * * *`
- [ ] 管理后台打开任务「立账凭证检核(周批)」
- [ ] `enabled=true`,时区 `Asia/Shanghai`,Cron `0 6 * * 2`
- [ ] `kb_sync_enabled=false`(本域不需要进知识库)
- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户
- [ ] `job_params.required_files` 确认为核价单/采购单(或业务最终定稿)
- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户;未配置则不发
- [ ] `job_params.profile_code=sales`,`scope_code=HXJM`
---
## 5. 功能冒烟
## 4. 功能冒烟
### 5.1 管理台手动跑一批(共享盘可用后)
### 4.1 管理台手动跑一批
- [ ] 「立即执行」创建 `ScheduleRun`
- [ ] `response_summary_json.voucher_check` 含 `complete_count` / `missing_count` / `skipped_count`
- [ ] Excel 可下载,表头含发票号/结论/缺失材料
- [ ] `failed_count` **不含**缺资料票(仅技术异常)
- [ ] `response_summary_json.voucher_check` 含缺件文件数 / 缺件 invoice 数
- [ ] Excel 可下载,以 invoice 为行、文件类型为列
- [ ] 技术失败不计入缺件
### 5.2 增量跳过
### 4.2 增量与强制重检
- [ ] 第一次跑后,第二次对未变更齐全票:`skipped_count > 0`
- [ ] 强制语义(会话/Tool `mode=force_all`):跳过为 0
- [ ] 第一次跑后,第二次对未变更齐全票:跳过数 > 0
- [ ] 工作台「强制重检上月」:`mode=force_all`,跳过为 0
- [ ] 仅管理员可触发强制重检
### 5.3 共享盘故障
- [ ] 临时移除健康标记或卸载挂载
- [ ] 再跑:批次 `failed`,不产生批量 missing 状态覆盖
- [ ] 企微失败告警到达(若开启)
### 5.4 工作台记录页
### 4.3 工作台记录页
- [ ] 打开 `/workspace/accounting-voucher-check`
- [ ] 「检核任务」可按月/状态筛选
- [ ] 「检核任务」可按月/状态筛选,分页可用
- [ ] 「企微发送记录」可按月/发送状态筛选,能看到接收人、未发送原因与 Excel 下载入口
- [ ] 缺资料票的缺失材料列非空
- [ ] 「查看详情」进入 `/workspace/accounting-voucher-check/runs/:runId`(`runId` 为 ScheduleRun.id)
### 5.5 Tool API(可用 curl / Postman)
### 4.4 文档库 / ERP 故障
```bash
# 启动(增量)— 复用 file-check
POST /api/file-check/tools/tasks/run
{ "task_id": <id>, "run_options": { "mode": "incremental" }, "hxops_turn_id": "..." }
# 缺资料查询
GET /api/accounting-voucher-check/tools/tasks/<task_id>/missing
# 批次明细
GET /api/accounting-voucher-check/tools/runs/<run_id>/items?result=missing
```
- [ ] 上述接口返回符合约定(Tool 非 envelope / 工作台 envelope)
- [ ] DMS 或 ERP 不可用时批次 `failed`,不得把空结果批量判为缺件
- [ ] 企微失败告警到达(若开启)
---
## 5.6 在 jobs 表识别立账凭证检核
## 5. 在 jobs 表识别立账凭证检核
平台排程(含立账凭证)仍走统一 `schedule` 队列,**`domain`/`job_type` 会一直是 `schedule` / `schedule_run`**,这是 worker 认领约定,不要按这两列区分业务。
@@ -185,17 +143,14 @@ SELECT id, status, business_ref, message, payload_json
```
Worker 日志关键字:`[voucher-check]` 或 `[schedule-run] name=立账凭证检核 path=accounting-voucher-check`。
启动 `python worker.py --queues schedule` 时不应再刷「合同付款预警 ERP」;那条只属于 `--queues contract`。
升级前已写入的旧行仍可能是 `business_ref=schedule_run:{id}`,可按 `payload_json.schedule_task_id` 关联 `schedule_tasks.platform_api_path`。
---
## 6. 回滚要点
- [ ] 代码回滚后:可 `flask db downgrade` 到上一 revision(会删本域两表 + 种子 `schedule_no`)
- [ ] **勿**在有生产检核数据时贸然 downgrade;优先停用任务 `enabled=false`
- [ ] 共享盘挂载可保留,不影响其它服务
- [ ] **勿**在有生产检核数据时贸然 `flask db downgrade`(会回建空的旧表,不恢复历史数据)
- [ ] 优先停用任务 `enabled=false`
- [ ] 旧共享盘挂载与 `VOUCHER_CHECK_SHARE_*` 已不再使用,可从宿主机/Compose 移除
---
@@ -204,6 +159,6 @@ Worker 日志关键字:`[voucher-check]` 或 `[schedule-run] name=立账凭证
| 角色 | 确认项 | 签名/日期 |
| --- | --- | --- |
| 研发 | 迁移 + Job 注册 + 冒烟 | |
| 运维 | env + 挂载 + 双容器可读 | |
| 业务 | 必检文件名 + 通知接收人 | |
| 测试 | T1–T12 关键场景抽样 | |
| 运维 | env + DMS/ERP 连通 | |
| 业务 | 类型目录 + 通知接收人 | |
| 测试 | 周批 / 强制重检 / 企微记录抽样 | |
@@ -1,11 +1,11 @@
# 立账凭证资料检核技术设计
> 文档版本:v2.2
> 更新时间:2026-09-04
> 状态:目标设计,销售一期待实施
> 文档版本:v2.3
> 更新时间:2026-09-08
> 状态:销售一期引擎已落地;ERP PO / OA 打印仍待接线
> 需求基线:[demand.md](demand.md)
>
> 本文替代旧实现「当月 + 单一共享盘 + 固定文件名存在性」。现有 `voucher_check` 代码见 §11,不得按旧口径扩展。
> 本文替代旧实现「当月 + 单一共享盘 + 固定文件名存在性」。旧表、共享盘扫描与 Chatflow Tool 已删除,不得按旧口径扩展。
## 1. 设计目标
@@ -136,7 +136,7 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成
`voucher_check_file_results` 是缺件统计和 Excel 明细的真相源;不得仅保存 `invoice` 级结论,否则无法正确统计同一 `invoice` 的多个缺件。
现有表 `voucher_check_invoice_states` / `voucher_check_run_items` 是旧实现的一票一状态模型,迁移时由上述单文件结果表替代,不得继续扩展旧表语义。
旧表 `voucher_check_invoice_states` / `voucher_check_run_items` 已由迁移 `vc2b3c4d5e6f` 删除,不得再恢复为写入目标。
## 6. 批量缺件统计
@@ -221,21 +221,21 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成
- 配置错误在批次开始前失败,不产生批量业务缺失结果。
- 密码、Token、Cookie 不允许出现在 Profile 文件、数据库 JSON、Excel 或日志中。
## 11. 现有代码(旧实现)与迁移
## 11. 与旧实现的差异(已完成清理)
当前 `backend/app/services/voucher_check/` 仍按旧模型运行,**不是**本期设计的实现:
当前 `backend/app/services/voucher_check/` 按本期引擎运行。与旧共享盘方案的差异:
| 旧实现 | 本期设计 |
| 旧实现 | 当前实现 |
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| 每日 `0 6 * * *`,检核**当前自然月** | **每周二** `0 6 * * 2`,检核**上一个自然月** |
| HXJM `apa_file.apa08/apa09` 拉发票清单 | **沿用该口径**,仅把期间改为上一个月 |
| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从 ERP/OA/固定目录**获取**,先写入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` |
| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从文档库类型目录扫描(ERP/OA 打印一期未接线),先落入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` |
| 必检「核价单.pdf」「采购单.pdf」 | 销售一期:PO、报关资料、销货放行申请单、发票、报关单、提单 |
| 一票一状态;缺资料按票发企微 textcard、同票同日节流 | 单文件结果;每批一条汇总通知 + invoice 行 Excel |
| Chatflow Tool `/api/accounting-voucher-check/tools/*` | 已删除;查询走工作台 `/api/workspace/accounting-voucher-check/*` |
迁移约束:
约束:
- 旧入口 `/api/accounting-voucher-check/*` 与 `POST /api/file-check/tools/tasks/run` 在销售迁移期保留,内部映射 `profile_code=sales`。
- 现有共享盘扫描可收成 `directory_scan` Adapter,不得继续作为唯一检核路径。
- 不得按旧「核价单/采购单」文件名或**当前月**期间扩展;销售主体仍用 `apa_file` 上月清单。
- 部署与冒烟清单 [ops-checklist.md](ops-checklist.md)、Chatflow 草稿 [dify-chatflow-draft.md](dify-chatflow-draft.md) 仅描述旧引擎,迁移后需重写。
- 不得再写入 `voucher_check_invoice_states` / `voucher_check_run_items`。
- 部署与冒烟见 [ops-checklist.md](ops-checklist.md)。
@@ -5,7 +5,7 @@
> 需求基线:[demand.md](demand.md)
> 落地设计:[technical-design.md](technical-design.md)
>
> 本文描述**新方案**通用实现目标。仓库内现有「当前自然月 + 单一共享盘 + 固定文件名」代码只是迁移对象,见 [ops-checklist.md](ops-checklist.md),不得作为新业务方扩展基础。
> 本文描述通用实现目标。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘扫描与一票一状态表已移除。
## 1. 设计结论
@@ -488,11 +488,11 @@ backend/app/domains/document_check/
迁移顺序:
1. 先建立 Profile Schema、Adapter 契约和单文件数据模型。
2. 将现有销售共享盘扫描逻辑封装为 `directory_scan` Adapter。
2. 销售文档扫描走 `dms_directory_scan` Adapter(文档库类型目录),不再封装旧共享盘扫描。
3. 将销售 invoice 主体加载和 OA/ERP 获取逻辑分别封装为 Loader/Adapter。
4. 保留旧 `voucher_check` API 兼容层,内部调用通用引擎。
4. 工作台 API 只读引擎表;已删除 Chatflow Tool 与旧 states 接口。
5. 完成销售回归后增加采购 Profile 和采购专用 Adapter。
6. 最后清理只服务旧模型的单票状态、单一共享根配置和重复接口。
6. 已清理只服务旧模型的单票状态、单一共享根配置和重复接口。
## 12. 测试与验收
+2 -3
View File
@@ -216,10 +216,9 @@
| --- | --- | --- |
| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个月,按 Profile 从 ERP、OA、目录获取并归档 |
| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;ERP PO / OA 销货放行单打印仅占位 |
| 单一共享盘旧检核 | 已停用主路径 | 旧共享盘扫描保留模块但周任务不再调用;不得按核价单/采购单口径扩展 |
| 单一共享盘旧检核 | 已移除 | 已删除共享盘扫描、Chatflow Tool、`voucher_check_invoice_states` / `voucher_check_run_items` |
| 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微每批一条汇总 |
| Tool / 工作台查询 | 实施中 | 工作台含检核任务与企微发送记录两 Tab;「强制重检上月」;`/runs` 读新引擎批次,`/notifications` 读每批一条企微汇总;旧 states 查询保留兼容 |
| Dify Chatflow 编排 | 待完成 | 须按新口径(上月、Profile、批次汇总)编排;现有草稿仅对应旧引擎 Tool |
| 工作台查询 | 已实现 | 工作台含检核任务与企微发送记录两 Tab;「强制重检上月」;`/runs`、`/notifications` 只读引擎表 |
### 采购合同审查
@@ -1,518 +0,0 @@
{
"openapi": "3.0.3",
"info": {
"title": "HXOPS Accounting Voucher Check Tool API",
"description": "立账凭证检核查询 Tool API:缺资料清单、批次明细、单票最新状态。启动检核请复用 File Check 的 run_file_check(可传 run_options)。鉴权:Authorization Bearer 或 X-Integration-Key(与 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY 相同)。",
"version": "1.0.0"
},
"servers": [
{
"url": "http://127.0.0.1:5052",
"description": "HXOPS_TOOLS_API_BASE"
}
],
"security": [
{
"BearerAuth": []
},
{
"IntegrationKey": []
}
],
"paths": {
"/api/accounting-voucher-check/tools/tasks/{task_id}/missing": {
"get": {
"operationId": "list_voucher_missing",
"summary": "查询缺资料发票(最新状态)",
"description": "按账套与月份查询 status=missing 的发票;默认当前自然月。",
"tags": [
"Accounting Voucher Check"
],
"parameters": [
{
"name": "task_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"example": 12
},
"description": "排程任务 ID(Agent 绑定的 schedule_task_id,用于回显)"
},
{
"name": "period",
"in": "query",
"required": false,
"schema": {
"type": "string",
"example": "2026-08"
},
"description": "检核月份 YYYY-MM;缺省为当前自然月"
},
{
"name": "scope_code",
"in": "query",
"required": false,
"schema": {
"type": "string",
"default": "HXJM",
"example": "HXJM"
}
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"default": 200,
"minimum": 1,
"maximum": 1000
}
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/MissingListResponse"
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"503": {
"$ref": "#/components/responses/MissingAuth"
}
}
}
},
"/api/accounting-voucher-check/tools/runs/{run_id}/items": {
"get": {
"operationId": "list_voucher_run_items",
"summary": "查询批次发票明细",
"description": "分页返回某 ScheduleRun 的单票结论;可按 result 过滤。",
"tags": [
"Accounting Voucher Check"
],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"example": 1001
}
},
{
"name": "result",
"in": "query",
"required": false,
"schema": {
"type": "string",
"enum": [
"complete",
"missing",
"skipped",
"technical_error"
],
"example": "missing"
}
},
{
"name": "page",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"default": 1,
"minimum": 1
}
},
{
"name": "page_size",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"default": 50,
"minimum": 1,
"maximum": 200
}
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RunItemsResponse"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"503": {
"$ref": "#/components/responses/MissingAuth"
}
}
}
},
"/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest": {
"get": {
"operationId": "get_voucher_invoice_latest",
"summary": "查询指定发票最新检核状态",
"description": "返回单票最新状态及近期批次快照;invoice_no 保持业务原值(仅 trim)。",
"tags": [
"Accounting Voucher Check"
],
"parameters": [
{
"name": "invoice_no",
"in": "path",
"required": true,
"schema": {
"type": "string",
"example": "INV-20260803001"
},
"description": "发票号(apa08 原值)"
},
{
"name": "period",
"in": "query",
"required": false,
"schema": {
"type": "string",
"example": "2026-08"
}
},
{
"name": "scope_code",
"in": "query",
"required": false,
"schema": {
"type": "string",
"default": "HXJM"
}
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/InvoiceLatestResponse"
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"503": {
"$ref": "#/components/responses/MissingAuth"
}
}
}
}
},
"components": {
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"description": "Authorization: Bearer <FILE_CHECK_TOOL_API_KEY 或 INTEGRATION_API_KEY>"
},
"IntegrationKey": {
"type": "apiKey",
"in": "header",
"name": "X-Integration-Key",
"description": "与 Bearer 二选一"
}
},
"schemas": {
"MissingMaterial": {
"type": "object",
"properties": {
"code": {
"type": "string",
"example": "price_check_sheet"
},
"name": {
"type": "string",
"example": "核价单"
}
}
},
"InvoiceState": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"scope_code": {
"type": "string"
},
"period_month": {
"type": "string",
"nullable": true
},
"invoice_no": {
"type": "string"
},
"invoice_date": {
"type": "string",
"nullable": true
},
"status": {
"type": "string",
"enum": [
"complete",
"missing"
]
},
"folder_path": {
"type": "string",
"nullable": true
},
"folder_exists": {
"type": "boolean"
},
"matched_files": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"missing_materials": {
"type": "array",
"items": {
"$ref": "#/components/schemas/MissingMaterial"
}
},
"last_checked_at": {
"type": "string",
"nullable": true
}
}
},
"MissingListResponse": {
"type": "object",
"required": [
"ok",
"items",
"count"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"task_id": {
"type": "integer",
"nullable": true
},
"scope_code": {
"type": "string"
},
"period": {
"type": "string",
"example": "2026-08"
},
"count": {
"type": "integer"
},
"items": {
"type": "array",
"items": {
"$ref": "#/components/schemas/InvoiceState"
}
}
}
},
"RunItem": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"schedule_run_id": {
"type": "integer"
},
"invoice_no": {
"type": "string"
},
"result": {
"type": "string",
"enum": [
"complete",
"missing",
"skipped",
"technical_error"
]
},
"folder_path": {
"type": "string",
"nullable": true
},
"matched_files": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"missing_materials": {
"type": "array",
"items": {
"$ref": "#/components/schemas/MissingMaterial"
}
},
"error_code": {
"type": "string",
"nullable": true
},
"error_message": {
"type": "string",
"nullable": true
}
}
},
"RunItemsResponse": {
"type": "object",
"required": [
"ok",
"items",
"total"
],
"properties": {
"ok": {
"type": "boolean"
},
"run_id": {
"type": "integer"
},
"run_no": {
"type": "string"
},
"page": {
"type": "integer"
},
"page_size": {
"type": "integer"
},
"total": {
"type": "integer"
},
"items": {
"type": "array",
"items": {
"$ref": "#/components/schemas/RunItem"
}
}
}
},
"InvoiceLatestResponse": {
"type": "object",
"required": [
"ok",
"state"
],
"properties": {
"ok": {
"type": "boolean"
},
"state": {
"$ref": "#/components/schemas/InvoiceState"
},
"recent_run_items": {
"type": "array",
"items": {
"$ref": "#/components/schemas/RunItem"
}
}
}
},
"ToolError": {
"type": "object",
"properties": {
"ok": {
"type": "boolean",
"example": false
},
"error_code": {
"type": "string"
},
"message": {
"type": "string"
},
"details": {
"type": "object"
}
}
}
},
"responses": {
"BadRequest": {
"description": "参数错误",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ToolError"
}
}
}
},
"Unauthorized": {
"description": "鉴权失败",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ToolError"
}
}
}
},
"NotFound": {
"description": "资源不存在",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ToolError"
}
}
}
},
"MissingAuth": {
"description": "服务端未配置 Tool API Key",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ToolError"
}
}
}
}
}
}
}
+1 -1
View File
@@ -220,7 +220,7 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由
- **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。归档复制策略为同名跳过。
- **通知**:排程/任务界面从系统用户多选企微接收人;未配置不发送。
- **判定边界**:不读取文件内容、不调用 LLM 判断合格、不回写 ERP。批次级依赖不可用时整批失败,不得把空结果批量判为缺件。
- **当前代码**:周任务已切到上月清单 + 文档库类型目录扫描 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微;ERP PO / OA 打印仍为占位 Adapter。
- **当前代码**:周任务已切到上月清单 + 文档库类型目录扫描 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微;ERP PO / OA 打印仍为占位 Adapter。旧共享盘扫描、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.x 货代发货通知批次库存能力
+3 -7
View File
@@ -2359,15 +2359,11 @@
"difySystemPromptHint": "Available when a Dify Agent is enabled. Saved as system_prompt in the Workflow; LLM nodes must reference this variable.",
"difySystemPromptPlaceholder": "e.g. You are a material compliance assistant. Based on record test data, return JSON with dify_result (pass/fail/manual review) and dify_message.",
"platformJobAccountingVoucherCheck": "Accounting voucher check",
"accountingVoucherCheckHint": "Fetch the current-month ERP invoice list and scan the share for required filenames (no file content reading).",
"accountingVoucherCheckHint": "Every Tuesday, check the previous calendar month of sales invoice attachments: load the ERP invoice list, scan document-library type folders, and archive by invoice (skip same names).",
"voucherCheckScope": "Ledger scope",
"voucherCheckDirTemplate": "Directory template",
"voucherCheckDirTemplateHelp": "Only {root}/{YYYY}/{MM}/{invoice_no} placeholders are allowed",
"voucherCheckRequiredFiles": "Required materials",
"voucherCheckCaseSensitive": "Case-sensitive filenames",
"voucherCheckProfile": "Business profile",
"voucherCheckNotifyMissing": "Notify on missing materials",
"voucherCheckNotifyFailure": "Failure alert",
"voucherCheckSameDayDedup": "Same-invoice same-day dedup"
"voucherCheckNotifyFailure": "Failure alert"
},
"testRun": {
"title": "Test run — {name}",
+1 -3
View File
@@ -513,14 +513,12 @@
"VOUCHER_CHECK_CONFIG_INVALID": "Accounting voucher check configuration is invalid.",
"VOUCHER_CHECK_INVOICE_REQUIRED": "Invoice number is required.",
"VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "The invoice is not in the previous-month ERP set.",
"VOUCHER_CHECK_INVOICE_PATH_INVALID": "Invoice number contains illegal path characters.",
"VOUCHER_CHECK_SHARE_UNAVAILABLE": "Shared folder is unavailable. Check the mount and health marker.",
"VOUCHER_CHECK_ERP_UNAVAILABLE": "ERP (Oracle) is unavailable. Please try again later.",
"VOUCHER_CHECK_DMS_UNAVAILABLE": "The sales invoice attachment library is unavailable. Please try again later.",
"VOUCHER_CHECK_ADAPTER_NOT_WIRED": "This document source is not wired yet.",
"VOUCHER_CHECK_ARCHIVE_NOT_WIRED": "Document library copy/create-folder API is not wired yet.",
"VOUCHER_CHECK_ARCHIVE_FAILED": "Failed to create a folder or copy a file in the document library.",
"VOUCHER_CHECK_RUN_NOT_FOUND": "Voucher check run or invoice state was not found.",
"VOUCHER_CHECK_RUN_NOT_FOUND": "The voucher check run was not found.",
"VOUCHER_CHECK_RUN_IN_PROGRESS": "An accounting voucher check is already queued or running. Try again later.",
"VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "The accounting voucher check schedule was not found.",
"VOUCHER_CHECK_PERSIST_FAILED": "Failed to persist voucher check results.",
+3 -7
View File
@@ -2237,15 +2237,11 @@
"difySystemPromptHint": "ใช้ได้เมื่อเปิดใช้ Dify Agent จะบันทึกเป็น system_prompt ใน Workflow; โหนด LLM ต้องอ้างอิงตัวแปรนี้",
"difySystemPromptPlaceholder": "เช่น คุณเป็นผู้ช่วยตรวจสอบความสอดคล้องของวัสดุ จากข้อมูล record ให้คืน JSON: dify_result (ผ่าน/ไม่ผ่าน/ตรวจด้วยมือ) และ dify_message",
"platformJobAccountingVoucherCheck": "ตรวจสอบเอกสารบัญชี",
"accountingVoucherCheckHint": "ดึงรายการใบแจ้งหนี้ ERP ของเดือนปัจจุบัน และสแกนไฟล์ที่ต้องมีบนแชร์ (ไม่อ่านเนื้อหาไฟล์)",
"accountingVoucherCheckHint": "ทุกวันอังคาร ตรวจเอกสารใบแจ้งหนี้ขายของเดือนก่อน: ดึงรายการใบแจ้งหนี้จาก ERP สแกนโฟลเดอร์ประเภทในคลังเอกสาร แล้วจัดเก็บตาม invoice (ข้ามชื่อซ้ำ)",
"voucherCheckScope": "ชุดบัญชี",
"voucherCheckDirTemplate": "เทมเพลตโฟลเดอร์",
"voucherCheckDirTemplateHelp": "อนุญาตเฉพาะ {root}/{YYYY}/{MM}/{invoice_no}",
"voucherCheckRequiredFiles": "เอกสารที่ต้องมี",
"voucherCheckCaseSensitive": "แยกตัวพิมพ์เล็ก/ใหญ่ในชื่อไฟล์",
"voucherCheckProfile": "โปรไฟล์ฝ่ายธุรกิจ",
"voucherCheckNotifyMissing": "แจ้งเตือนเมื่อขาดเอกสาร",
"voucherCheckNotifyFailure": "แจ้งเตือนเมื่อล้มเหลว",
"voucherCheckSameDayDedup": "ไม่แจ้งซ้ำใบเดียวกันในวันเดียวกัน"
"voucherCheckNotifyFailure": "แจ้งเตือนเมื่อล้มเหลว"
},
"status": {
"all": "ทุกสถานะ",
+1 -3
View File
@@ -513,14 +513,12 @@
"VOUCHER_CHECK_CONFIG_INVALID": "การตั้งค่าการตรวจสอบเอกสารบัญชีไม่ถูกต้อง",
"VOUCHER_CHECK_INVOICE_REQUIRED": "ต้องระบุเลขที่ใบแจ้งหนี้",
"VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "ใบแจ้งหนี้ไม่อยู่ในชุด ERP ของเดือนที่แล้ว",
"VOUCHER_CHECK_INVOICE_PATH_INVALID": "เลขที่ใบแจ้งหนี้มีอักขระเส้นทางที่ไม่ถูกต้อง",
"VOUCHER_CHECK_SHARE_UNAVAILABLE": "โฟลเดอร์แชร์ใช้ไม่ได้ โปรดตรวจสอบการเมานต์และไฟล์สุขภาพ",
"VOUCHER_CHECK_ERP_UNAVAILABLE": "ERP (Oracle) ใช้ไม่ได้ โปรดลองใหม่ภายหลัง",
"VOUCHER_CHECK_DMS_UNAVAILABLE": "คลังเอกสารใบแจ้งหนี้ขายใช้ไม่ได้ โปรดลองใหม่ภายหลัง",
"VOUCHER_CHECK_ADAPTER_NOT_WIRED": "แหล่งเอกสารนี้ยังไม่ได้ต่อระบบ",
"VOUCHER_CHECK_ARCHIVE_NOT_WIRED": "API คัดลอก/สร้างโฟลเดอร์ของคลังเอกสารยังไม่ได้ต่อระบบ",
"VOUCHER_CHECK_ARCHIVE_FAILED": "สร้างโฟลเดอร์หรือคัดลอกไฟล์ในคลังเอกสารไม่สำเร็จ",
"VOUCHER_CHECK_RUN_NOT_FOUND": "ไม่พบรอบการตรวจหรือสถานะใบแจ้งหนี้",
"VOUCHER_CHECK_RUN_NOT_FOUND": "ไม่พบรอบการตรวจเอกสารบัญชี",
"VOUCHER_CHECK_RUN_IN_PROGRESS": "งานตรวจเอกสารบัญชียังอยู่ในคิวหรือกำลังทำงาน โปรดลองใหม่ภายหลัง",
"VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "ไม่พบตารางงานตรวจเอกสารบัญชี",
"VOUCHER_CHECK_PERSIST_FAILED": "บันทึกผลการตรวจไม่สำเร็จ",
+3 -7
View File
@@ -2471,15 +2471,11 @@
"difySystemPromptHint": "仅在启用 Dify Agent 时可配置。保存后将作为 system_prompt 传入 Workflow;编排中 LLM 节点需引用该变量。",
"difySystemPromptPlaceholder": "例如:你是物料合规判定助手。根据 record 中的检测数据判定是否合格,仅返回 JSON:dify_result(合格/不合格/人工判定)与 dify_message。",
"platformJobAccountingVoucherCheck": "立账凭证检核",
"accountingVoucherCheckHint": "按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。",
"accountingVoucherCheckHint": "每周二检核上一个自然月的销售开票附件:拉取 ERP 发票清单,扫描文档库类型目录并按 invoice 归档(同名跳过)。",
"voucherCheckScope": "账套",
"voucherCheckDirTemplate": "目录模板",
"voucherCheckDirTemplateHelp": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}",
"voucherCheckRequiredFiles": "必检材料",
"voucherCheckCaseSensitive": "文件名区分大小写",
"voucherCheckProfile": "业务方 Profile",
"voucherCheckNotifyMissing": "缺资料通知",
"voucherCheckNotifyFailure": "失败告警",
"voucherCheckSameDayDedup": "同票同日去重"
"voucherCheckNotifyFailure": "失败告警"
},
"testRun": {
"title": "测试执行 — {name}",
+1 -3
View File
@@ -513,14 +513,12 @@
"VOUCHER_CHECK_CONFIG_INVALID": "立账凭证检核配置无效。",
"VOUCHER_CHECK_INVOICE_REQUIRED": "请提供发票号。",
"VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "指定发票不在上一个月 ERP 集合中。",
"VOUCHER_CHECK_INVOICE_PATH_INVALID": "发票号含非法路径字符。",
"VOUCHER_CHECK_SHARE_UNAVAILABLE": "共享盘不可用,请检查挂载与健康标记。",
"VOUCHER_CHECK_ERP_UNAVAILABLE": "ERP(Oracle)不可用,请稍后重试。",
"VOUCHER_CHECK_DMS_UNAVAILABLE": "销售开票附件文档库不可用,请稍后重试。",
"VOUCHER_CHECK_ADAPTER_NOT_WIRED": "该资料获取方式尚未接线。",
"VOUCHER_CHECK_ARCHIVE_NOT_WIRED": "文档库复制/建文件夹接口尚未接线。",
"VOUCHER_CHECK_ARCHIVE_FAILED": "文档库建文件夹或复制失败。",
"VOUCHER_CHECK_RUN_NOT_FOUND": "检核批次或发票状态不存在。",
"VOUCHER_CHECK_RUN_NOT_FOUND": "检核批次不存在。",
"VOUCHER_CHECK_RUN_IN_PROGRESS": "立账凭证检核正在执行或排队中,请稍后再试。",
"VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "未找到立账凭证检核排程任务。",
"VOUCHER_CHECK_PERSIST_FAILED": "检核结果落库失败。",
+3 -7
View File
@@ -2242,15 +2242,11 @@
"difySystemPromptHint": "僅在啟用 Dify Agent 時可配置。保存後將作為 system_prompt 傳入 Workflow;編排中 LLM 節點需引用該變數。",
"difySystemPromptPlaceholder": "例如:你是物料合規判定助手。根據 record 中的檢測資料判定是否合格,僅返回 JSON:dify_result(合格/不合格/人工判定)與 dify_message。",
"platformJobAccountingVoucherCheck": "立帳憑證檢核",
"accountingVoucherCheckHint": "依當前自然月拉取 ERP 發票清單,掃描共用磁碟必檢材料是否存在(不讀檔案內容)。",
"accountingVoucherCheckHint": "每週二檢核上一個自然月的銷售開票附件:拉取 ERP 發票清單,掃描文件庫類型目錄並依 invoice 歸檔(同名略過)。",
"voucherCheckScope": "帳套",
"voucherCheckDirTemplate": "目錄範本",
"voucherCheckDirTemplateHelp": "僅允許 {root}/{YYYY}/{MM}/{invoice_no}",
"voucherCheckRequiredFiles": "必檢材料",
"voucherCheckCaseSensitive": "檔名區分大小寫",
"voucherCheckProfile": "業務方 Profile",
"voucherCheckNotifyMissing": "缺資料通知",
"voucherCheckNotifyFailure": "失敗告警",
"voucherCheckSameDayDedup": "同票同日去重"
"voucherCheckNotifyFailure": "失敗告警"
},
"status": {
"all": "全部狀態",
+1 -3
View File
@@ -513,14 +513,12 @@
"VOUCHER_CHECK_CONFIG_INVALID": "立帳憑證檢核設定無效。",
"VOUCHER_CHECK_INVOICE_REQUIRED": "請提供發票號。",
"VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "指定發票不在上一月 ERP 集合中。",
"VOUCHER_CHECK_INVOICE_PATH_INVALID": "發票號含非法路徑字元。",
"VOUCHER_CHECK_SHARE_UNAVAILABLE": "共用磁碟不可用,請檢查掛載與健康標記。",
"VOUCHER_CHECK_ERP_UNAVAILABLE": "ERP(Oracle)不可用,請稍後重試。",
"VOUCHER_CHECK_DMS_UNAVAILABLE": "銷售開票附件文件庫不可用,請稍後重試。",
"VOUCHER_CHECK_ADAPTER_NOT_WIRED": "該資料取得方式尚未接線。",
"VOUCHER_CHECK_ARCHIVE_NOT_WIRED": "文件庫複製/建立資料夾介面尚未接線。",
"VOUCHER_CHECK_ARCHIVE_FAILED": "文件庫建立資料夾或複製失敗。",
"VOUCHER_CHECK_RUN_NOT_FOUND": "檢核批次或發票狀態不存在。",
"VOUCHER_CHECK_RUN_NOT_FOUND": "檢核批次不存在。",
"VOUCHER_CHECK_RUN_IN_PROGRESS": "立帳憑證檢核正在執行或排隊中,請稍後再試。",
"VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "找不到立帳憑證檢核排程任務。",
"VOUCHER_CHECK_PERSIST_FAILED": "檢核結果寫入失敗。",