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

+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"