Merge branch 'invoice-check' into dev

This commit is contained in:
sophie committed 2026-09-08 10:53:03 +08:00
commit 9570197378
104 files changed
+5844 -4271

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)
+54 -23
View File
@@ -1,9 +1,9 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核记录查询 API(批次明细 / 最新状态)。
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核记录页共用;标准 {success,data|error,request_id} envelope。
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
"""
from __future__ import annotations
@@ -11,7 +11,7 @@ from __future__ import annotations
from flask import Blueprint, request
from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.voucher_check import query_service
@@ -25,11 +25,55 @@ def _require_user():
return user
def _require_admin():
"""工作台强制重检仅管理员可触发,鉴权方式与本蓝图 GET 一致。"""
user = _require_user()
if getattr(user, "role", None) != "admin":
raise ForbiddenError("Admin privilege required")
return user
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs", methods=["GET"])
def workspace_voucher_runs():
"""
分页查看检核任务列表。
核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。
"""
_require_user()
data = query_service.list_runs(
period=request.args.get("period"),
profile_code=request.args.get("profile_code"),
status=request.args.get("status"),
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/runs", methods=["POST"])
def workspace_voucher_force_run():
"""
强制重检上一个自然月(不走增量跳过)。
核心逻辑:body.mode 仅接受 force_all;入队默认周批排程,由 schedule worker 执行。
"""
user = _require_admin()
payload = request.get_json(silent=True) or {}
mode = str(payload.get("mode") or "force_all").strip().lower()
if mode != "force_all":
raise ValidationError(
"工作台仅支持 force_all",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"mode": mode},
)
data = query_service.enqueue_force_all_run(triggered_by_user_id=getattr(user, "id", None))
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
def workspace_voucher_run_items(run_id: int):
"""
分页查看批次明细。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
"""
_require_user()
data = query_service.list_run_items(
@@ -41,30 +85,17 @@ def workspace_voucher_run_items(run_id: int):
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"])
def workspace_voucher_states():
@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"])
def workspace_voucher_notifications():
"""
按月份、状态、发票号筛选最新状态。
分页查看企微缺件汇总发送记录。
核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。
"""
_require_user()
data = query_service.list_states(
scope_code=str(request.args.get("scope_code") or "HXJM"),
data = query_service.list_notifications(
period=request.args.get("period"),
status=request.args.get("status"),
invoice_no=request.args.get("invoice_no"),
send_status=request.args.get("send_status"),
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)
+21 -12
View File
@@ -216,8 +216,8 @@ class Config:
# 统一改用通用 ERP 连接变量(ERP_DB_DSN / ERP_USERNAME / ERP_PASSWORD / ERP_TIMEOUT_SECONDS,已并入 env.shared),
# 并保留模块级 CONTRACT_PAYMENT_ERP_* 覆盖与旧回退(VOUCHER_CHECK_ERP_*)兼容。
CONTRACT_PAYMENT_ERP_DSN = os.getenv('CONTRACT_PAYMENT_ERP_DSN') or os.getenv('ERP_DB_DSN', '')
CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME') or os.getenv('VOUCHER_CHECK_ERP_USERNAME', '')
CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD') or os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '')
CONTRACT_PAYMENT_ERP_USERNAME = os.getenv('CONTRACT_PAYMENT_ERP_USERNAME') or os.getenv('ERP_USERNAME')
CONTRACT_PAYMENT_ERP_PASSWORD = os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD') or os.getenv('ERP_PASSWORD')
CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS = int(os.getenv('CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS') or os.getenv('ERP_TIMEOUT_SECONDS', '30') or '30')
CONTRACT_DMS_BASE_URL = os.getenv('CONTRACT_DMS_BASE_URL', '').strip().rstrip('/')
CONTRACT_DMS_USERNAME = os.getenv('CONTRACT_DMS_USERNAME', '')
@@ -652,17 +652,26 @@ class Config:
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
# 立账凭证检核:共享盘只读根 + Oracle 只读账号(密码仅 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'
# 立账凭证检核:ERP 只读 + 销售开票附件文档库根目录(密码仅 env)
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', '').strip()
VOUCHER_CHECK_ERP_PASSWORD = os.getenv('VOUCHER_CHECK_ERP_PASSWORD', '')
VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int(os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS', '30') or '30')
VOUCHER_CHECK_ERP_USERNAME = (
os.getenv('VOUCHER_CHECK_ERP_USERNAME')
or os.getenv('ERP_USERNAME')
or os.getenv('CONTRACT_PAYMENT_ERP_USERNAME', '')
).strip()
VOUCHER_CHECK_ERP_PASSWORD = (
os.getenv('VOUCHER_CHECK_ERP_PASSWORD')
or os.getenv('ERP_PASSWORD')
or os.getenv('CONTRACT_PAYMENT_ERP_PASSWORD', '')
)
VOUCHER_CHECK_ERP_TIMEOUT_SECONDS = int(
os.getenv('VOUCHER_CHECK_ERP_TIMEOUT_SECONDS') or os.getenv('ERP_TIMEOUT_SECONDS', '30') or '30'
)
VOUCHER_CHECK_DMS_BASE_URL = os.getenv('VOUCHER_CHECK_DMS_BASE_URL', '').strip().rstrip('/')
VOUCHER_CHECK_DMS_USERNAME = os.getenv('VOUCHER_CHECK_DMS_USERNAME', '').strip()
VOUCHER_CHECK_DMS_PASSWORD = os.getenv('VOUCHER_CHECK_DMS_PASSWORD', '')
VOUCHER_CHECK_DMS_LIBRARY_ID = os.getenv('VOUCHER_CHECK_DMS_LIBRARY_ID', '').strip()
VOUCHER_CHECK_DMS_ROOT_FOLDER_ID = os.getenv('VOUCHER_CHECK_DMS_ROOT_FOLDER_ID', '').strip()
# MinIO 配置
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
+12 -3
View File
@@ -209,7 +209,13 @@ from app.models.integration_connector import (
)
from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckNotification,
VoucherCheckProfile,
VoucherCheckRun,
VoucherCheckSubject,
)
from app.models.contract_payment import (
ContractPaymentAlert,
ContractPaymentAlertBatch,
@@ -393,8 +399,11 @@ __all__ = [
'ShippingInventoryCandidateSource',
'ShippingInventoryCandidateLine',
'ShippingTaskInventoryRpaAttempt',
'VoucherCheckInvoiceState',
'VoucherCheckRunItem',
'VoucherCheckProfile',
'VoucherCheckRun',
'VoucherCheckSubject',
'VoucherCheckFileResult',
'VoucherCheckNotification',
'ContractPaymentContract',
'ContractPaymentAttachment',
'ContractPaymentNode',
+1
View File
@@ -34,6 +34,7 @@ class QuickQuestion(Base):
"""
常用问题表
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
"""
__tablename__ = 'quick_questions'
+124 -58
View File
@@ -1,9 +1,9 @@
"""
backend/app/models/voucher_check.py
用途:立账凭证检核单票最新状态与批次明细 ORM。
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。
依赖:models.base.Base、schedule_runs。
逻辑:runner/persistence 写入;query_service 与工作台 API 读取;增量跳过依赖 invoice_states。
逻辑:引擎写入 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,41 +27,20 @@ from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class VoucherCheckInvoiceState(Base):
"""账套+月份+发票号的最新材料齐全状态(增量跳过真相源)。"""
class VoucherCheckProfile(Base):
"""已发布 Profile 版本;批次绑定不可变快照,运行时不以本表热更新覆盖。"""
__tablename__ = "voucher_check_invoice_states"
__tablename__ = "voucher_check_profiles"
__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"),
UniqueConstraint("profile_code", "version", name="uq_voucher_check_profiles_code_version"),
Index("ix_voucher_check_profiles_status", "status"),
)
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)
profile_code: Mapped[str] = mapped_column(String(32), nullable=False)
version: Mapped[str] = mapped_column(String(32), nullable=False)
definition_json: Mapped[dict] = mapped_column(JSON, nullable=False)
status: Mapped[str] = mapped_column(String(24), nullable=False, default="published")
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
@@ -72,43 +50,131 @@ class VoucherCheckInvoiceState(Base):
)
class VoucherCheckRunItem(Base):
"""单次 ScheduleRun 的发票检核快照(含跳过项,供审计与 Excel)。"""
class VoucherCheckRun(Base):
"""一次检核批次;列表统计取本表快照,不在查询时重算单文件结果。"""
__tablename__ = "voucher_check_run_items"
__tablename__ = "voucher_check_runs"
__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"),
Index("ix_voucher_check_runs_period_profile", "period_month", "profile_code"),
Index("ix_voucher_check_runs_status", "status"),
Index("ix_voucher_check_runs_finished_at", "finished_at"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
schedule_run_id: Mapped[int] = mapped_column(
schedule_run_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="CASCADE"),
ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
index=True,
)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
profile_code: Mapped[str] = mapped_column(String(32), nullable=False)
profile_version: Mapped[str] = mapped_column(String(32), nullable=False)
profile_snapshot_json: Mapped[dict] = mapped_column(JSON, nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
mode: Mapped[str] = mapped_column(String(24), nullable=False, default="incremental")
status: Mapped[str] = mapped_column(String(24), nullable=False, default="running")
subject_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
archived_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
skipped_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
missing_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
missing_invoice_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
technical_error_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
staged_file_count: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
stats_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class VoucherCheckSubject(Base):
"""批次内一张销售 invoice 主体。"""
__tablename__ = "voucher_check_subjects"
__table_args__ = (
UniqueConstraint("run_id", "invoice_no", name="uq_voucher_check_subjects_run_invoice"),
Index("ix_voucher_check_subjects_invoice_no", "invoice_no"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("voucher_check_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)
source_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
attributes_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class VoucherCheckFileResult(Base):
"""invoice × 文件规则 的单文件结果,是缺件统计与 Excel 的真相源。"""
__tablename__ = "voucher_check_file_results"
__table_args__ = (
UniqueConstraint(
"run_id",
"invoice_no",
"rule_code",
name="uq_voucher_check_file_results_run_invoice_rule",
),
Index("ix_voucher_check_file_results_status", "run_id", "status"),
Index("ix_voucher_check_file_results_invoice", "invoice_no"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
subject_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("voucher_check_subjects.id", ondelete="SET NULL"),
nullable=True,
)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
rule_code: Mapped[str] = mapped_column(String(64), nullable=False)
rule_name: Mapped[str] = mapped_column(String(128), nullable=False)
source_type: Mapped[str] = mapped_column(String(32), nullable=False)
expected_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
matched_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
source_folder_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
archive_folder_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
archive_item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
source_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
archive_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
status: Mapped[str] = mapped_column(String(24), nullable=False)
missing_reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
source_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), 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 VoucherCheckNotification(Base):
"""一个检核批次对应一条企微汇总通知审计。"""
__tablename__ = "voucher_check_notifications"
__table_args__ = (Index("ix_voucher_check_notifications_status", "send_status"),)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
nullable=False,
unique=True,
)
excel_filename: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
recipient_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
send_status: Mapped[str] = mapped_column(String(32), nullable=False)
skip_reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
+2 -2
View File
@@ -3,7 +3,7 @@ backend/app/services/faq_cache.py
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match;命中则 stream_chat 返回预置答案。
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled);命中则 stream_chat 返回预置答案。
"""
import json
import time
@@ -66,6 +66,7 @@ class FaqCacheService:
"""
尝试为指定 Agent 命中全局 FAQ 缓存条目。
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。
is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。
@param query - 用户提问
@param agent_id - 当前 Agent 主键
@returns 命中的 QuickQuestion;未命中返回 None
@@ -80,7 +81,6 @@ class FaqCacheService:
QuickQuestion.user_id.is_(None),
QuickQuestion.agent_id == agent_id,
QuickQuestion.cache_enabled.is_(True),
QuickQuestion.is_enabled.is_(True),
QuickQuestion.answer.isnot(None),
QuickQuestion.answer != "",
QuickQuestion.stale_at.is_(None),
+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),
))
+134 -21
View File
@@ -4,11 +4,14 @@ backend/app/services/schedule/queue_service.py
用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。
逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。
domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入
business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from flask import current_app
@@ -28,6 +31,86 @@ from app.services.schedule.freight_receipt_rpa_finalize import (
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
_worker_initialized = False
_BUSINESS_REF_SLUG_MAX = 80
def _schedule_job_slug(task: ScheduleTask) -> str:
"""
从排程任务生成写入 jobs.business_ref 的业务短码。
核心逻辑:优先 platform_api_path(如 accounting-voucher-check);无 path 时用 untagged。
冒号替换为连字符,避免破坏 `schedule_run:{id}:{slug}` 三段格式。
Args:
task: 排程任务。
Returns:
最长 80 字符的 slug。
"""
from app.services.schedule import normalize_platform_api_path
slug = normalize_platform_api_path(getattr(task, "platform_api_path", None)) or "untagged"
slug = slug.replace(":", "-").replace("/", "-")
return slug[:_BUSINESS_REF_SLUG_MAX]
def _schedule_task_label(task: ScheduleTask) -> str:
"""
jobs.message 与 worker 日志用的任务显示名。
核心逻辑:优先中文 name(如「立账凭证检核」);否则回落到 platform_api_path。
Args:
task: 排程任务。
Returns:
非空显示名。
"""
name = str(getattr(task, "name", None) or "").strip()
if name:
return name
slug = _schedule_job_slug(task)
return slug if slug != "untagged" else "未命名排程"
def schedule_job_business_ref(run_id: int, task: ScheduleTask) -> str:
"""
生成 schedule Job 的 business_ref。
格式:`schedule_run:{run_id}:{platform_api_path}`,便于在 jobs 表区分立账凭证检核等任务。
仍保留 run_id,取消/回收可按前缀精确匹配,避免 `schedule_run:1` 误伤 `schedule_run:13`。
Args:
run_id: ScheduleRun 主键。
task: 排程任务。
Returns:
长度不超过 128 的 business_ref。
"""
return f"schedule_run:{int(run_id)}:{_schedule_job_slug(task)}"
def query_jobs_for_schedule_run(run_id: int):
"""
按 ScheduleRun 主键查找对应通用 Job。
核心逻辑:兼容旧格式 `schedule_run:{id}` 与新格式 `schedule_run:{id}:{path}`。
新格式必须带 `id` 后的冒号,避免 run_id=1 匹配到 10/11/13。
Args:
run_id: ScheduleRun 主键。
Returns:
已过滤 domain/job_type/business_ref 的 Query;调用方可继续按 status 收窄。
"""
run_id = int(run_id)
legacy = f"schedule_run:{run_id}"
prefix = f"schedule_run:{run_id}:"
return db.session.query(Job).filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
db.or_(Job.business_ref == legacy, Job.business_ref.startswith(prefix)),
)
def _active_run(task_id: int) -> ScheduleRun | None:
@@ -61,14 +144,19 @@ def _create_queued_run(
*,
trigger_type: str,
triggered_by_user_id: int | None,
api_request_json: dict[str, Any] | None = None,
) -> tuple[ScheduleRun, int]:
"""
在当前事务创建 ScheduleRun 与对应通用 Job。
核心逻辑:worker 认领仍靠 domain=schedule + job_type=schedule_run;
业务身份写入 business_ref / payload.platform_api_path / message,避免 jobs 表全是 schedule。
Args:
task: 已由调用方锁定的排程任务。
trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。
triggered_by_user_id: 手动触发用户 ID;Cron 为 None。
api_request_json: 可选运行参数(如立账凭证 `run_options.mode=force_all`),须在入队前写入以免 worker 抢跑。
Returns:
`(ScheduleRun, job_id)`;调用方负责提交事务。
@@ -86,22 +174,29 @@ def _create_queued_run(
triggered_by_user_id=triggered_by_user_id,
started_at=None,
status="queued",
api_request_json=api_request_json,
)
db.session.add(run)
db.session.flush()
task_label = _schedule_task_label(task)
platform_path = str(getattr(task, "platform_api_path", None) or "").strip()
job_id = enqueue(
JobType.SCHEDULE_RUN,
{
"schedule_task_id": task.id,
"schedule_run_id": run.id,
"schedule_no": task.schedule_no,
"run_no": run.run_no,
"task_name": task_label,
"platform_api_path": platform_path,
"trigger_type": normalized_trigger,
"triggered_by_user_id": triggered_by_user_id,
},
domain="schedule",
business_ref=f"schedule_run:{run.id}",
business_ref=schedule_job_business_ref(run.id, task),
created_by_id=triggered_by_user_id,
max_attempts=3,
message="排程等待后台执行",
message=f"{task_label}等待后台执行",
dedupe_active=False,
commit=False,
)
@@ -112,6 +207,7 @@ def enqueue_manual_schedule_run(
task_id: int,
*,
triggered_by_user_id: int | None,
api_request_json: dict[str, Any] | None = None,
) -> tuple[ScheduleRun, int, bool]:
"""
手动触发排程并写入 schedule 队列。
@@ -119,6 +215,11 @@ def enqueue_manual_schedule_run(
核心逻辑:锁定 ScheduleTask 后复检 queued/running;已有活动记录时直接返回,
否则同事务创建 ScheduleRun 与 Job,避免接口线程承担长耗时执行。
Args:
task_id: 排程任务主键。
triggered_by_user_id: 触发人;系统触发可为空。
api_request_json: 写入新 run 的请求快照;已有活动 run 时不会覆盖。
Returns:
`(run, job_id, created)`;created=False 表示已有活动 run。
"""
@@ -135,13 +236,8 @@ def enqueue_manual_schedule_run(
active = _active_run(task.id)
if active is not None:
job = (
db.session.query(Job)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.status.in_(("queued", "running")),
Job.business_ref == f"schedule_run:{active.id}",
)
query_jobs_for_schedule_run(active.id)
.filter(Job.status.in_(("queued", "running")))
.order_by(Job.id.asc())
.first()
)
@@ -151,6 +247,7 @@ def enqueue_manual_schedule_run(
task,
trigger_type="manual",
triggered_by_user_id=triggered_by_user_id,
api_request_json=api_request_json,
)
db.session.commit()
return run, job_id, True
@@ -242,13 +339,9 @@ def prepare_schedule_queue() -> int:
if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run):
continue
active_job = (
db.session.query(Job.id)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.business_ref == f"schedule_run:{run.id}",
Job.status.in_(("queued", "running")),
)
query_jobs_for_schedule_run(run.id)
.filter(Job.status.in_(("queued", "running")))
.with_entities(Job.id)
.first()
)
if active_job is None:
@@ -308,11 +401,13 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
if task is None:
finish_job(job_id, result={"schedule_run_id": run_id, "status": "task_deleted"}, message="排程已删除")
return None
task_label = _schedule_task_label(task)
platform_path = str(getattr(task, "platform_api_path", None) or "").strip() or "untagged"
if run.status in {"success", "failed", "partial_failed"}:
finish_job(
job_id,
result={"schedule_run_id": run.id, "status": run.status},
message="排程已处于终态",
result={"schedule_run_id": run.id, "status": run.status, "platform_api_path": platform_path},
message=f"{task_label}已处于终态",
)
return run
@@ -323,6 +418,14 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
run.started_at = run.started_at or datetime.utcnow()
run.error_message = None
db.session.commit()
logger.info(
"[schedule-run] start name=%s path=%s run_no=%s run_id=%s job_id=%s",
task_label,
platform_path,
run.run_no,
run.id,
job_id,
)
result_run = run_task_now(
task,
trigger_type=run.trigger_type,
@@ -331,8 +434,12 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
)
finish_job(
job_id,
result={"schedule_run_id": result_run.id, "status": result_run.status},
message="排程执行完成",
result={
"schedule_run_id": result_run.id,
"status": result_run.status,
"platform_api_path": platform_path,
},
message=f"{task_label}执行完成",
)
return result_run
except Exception as exc:
@@ -355,5 +462,11 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
retryable=True,
owned_attempt=owned_attempt,
)
logger.exception("schedule run failed run_id=%s job_id=%s", run_id, job_id)
logger.exception(
"[schedule-run] failed name=%s path=%s run_id=%s job_id=%s",
task_label,
platform_path,
run_id,
job_id,
)
return run
@@ -5,7 +5,8 @@ backend/app/services/schedule/scheduler_service.py
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。
逻辑: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。
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler;
handler 抛错时 failed_count=1、排程记 failed,并把 error= 打进 worker 日志。
"""
from __future__ import annotations
@@ -43,20 +44,16 @@ def request_cancel_run(run_id: int) -> None:
持久化取消指定排程运行,供 Web 与独立 worker 跨进程协作。
核心逻辑:将对应 queued/running 通用 Job 标记为 cancelled;执行器通过
ScheduleRun 状态/存在性复检停止可中断的长循环。
ScheduleRun 状态/存在性复检停止可中断的长循环。business_ref 兼容
`schedule_run:{id}` 与 `schedule_run:{id}:{platform_api_path}`。
"""
from app.jobs.types import JobType
from app.models import Job
from app.services.schedule.queue_service import query_jobs_for_schedule_run
now = datetime.utcnow()
jobs = (
db.session.query(Job)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.business_ref == f"schedule_run:{int(run_id)}",
Job.status.in_(("queued", "running")),
)
query_jobs_for_schedule_run(run_id)
.filter(Job.status.in_(("queued", "running")))
.all()
)
for job in jobs:
@@ -493,6 +490,12 @@ def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
"""
立即执行一条排程并写入 ScheduleRun 终态。
核心逻辑:handler 未捕获异常记 failed_count=1,避免配置错误被标成 success;
该路径原先只写库不打日志,worker 汇总行看不到失败原因。
"""
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
@@ -527,8 +530,16 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
executor = resolve_schedule_executor(task)
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run)
except Exception as exc:
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(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)
@@ -563,9 +574,18 @@ 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] run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d",
run.run_no, total_count, success_count, failed_count, skipped_count, len(errors),
"[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,
total_count,
success_count,
failed_count,
skipped_count,
len(errors or []),
error_preview or "-",
)
if total_count == 0 and not errors:
status = "success"
@@ -38,7 +38,7 @@ def _ensure_headers() -> None:
def run_voucher_check_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证检核排程。
核心逻辑:注册 Excel 表头后委托 runner;日批默认 incremental。
核心逻辑:注册 Excel 表头后委托 runner;周批默认 incremental。
"""
_ensure_headers()
return run_voucher_check_batch(task, run)
@@ -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
@@ -0,0 +1,47 @@
"""
backend/app/services/voucher_check/adapters/__init__.py
用途:登记销售一期 Adapter(主体、目录扫描、PO/OA 占位、归档占位)。
依赖:各 adapter 模块。
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例。
"""
from app.services.voucher_check.adapters.base import (
AcquireAdapter,
ArchiveAdapter,
DirectoryScanAdapter,
ScanOutcome,
ScannedFile,
SubjectAdapter,
SubjectRow,
)
from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter
from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.adapters.hxjm_apa_subject import HxjmApaSubjectAdapter
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
from app.services.voucher_check.adapters.registry import get_adapter, register_adapter, registered_adapter_names
register_adapter("hxjm_apa", HxjmApaSubjectAdapter)
register_adapter("directory_scan", DmsDirectoryScanAdapter)
register_adapter("erp_po_print", ErpPoPrintAdapter)
register_adapter("oa_sales_release", OaSalesReleaseAdapter)
register_adapter("dms_archive", DmsArchiveAdapter)
__all__ = [
"AcquireAdapter",
"ArchiveAdapter",
"DirectoryScanAdapter",
"DmsArchiveAdapter",
"DmsDirectoryScanAdapter",
"ErpPoPrintAdapter",
"HxjmApaSubjectAdapter",
"OaSalesReleaseAdapter",
"ScanOutcome",
"ScannedFile",
"SubjectAdapter",
"SubjectRow",
"get_adapter",
"register_adapter",
"registered_adapter_names",
]
@@ -0,0 +1,113 @@
"""
backend/app/services/voucher_check/adapters/base.py
用途:立账凭证来源 Adapter 统一数据结构与协议。
依赖:无。
逻辑:引擎只消费这些类型;ERP/OA/DMS 细节留在各 Adapter 内。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date
from typing import Any, Protocol
@dataclass(frozen=True)
class SubjectRow:
"""应检 invoice 主体。"""
invoice_no: str
invoice_date: date | None
source_fingerprint: str
attributes: dict[str, Any] = field(default_factory=dict)
@dataclass(frozen=True)
class ScannedFile:
"""类型目录中命中的一个文件。"""
filename: str
item_id: str | None = None
folder_id: str | None = None
path: str | None = None
fingerprint: str | None = None
extra: dict[str, Any] = field(default_factory=dict)
@dataclass(frozen=True)
class ScanOutcome:
"""一条文件规则对一张 invoice 的扫描结果。"""
status: str # matched / missing / technical_error
file: ScannedFile | None = None
error_code: str | None = None
error_message: str | None = None
folder_id: str | None = None
folder_path: str | None = None
class SubjectAdapter(Protocol):
"""获取期间内应检主体。"""
source_type: str
def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]:
"""
拉取一个自然月的 invoice 清单。
【AI 触发时机】周任务或强制重检需要本期主体时调用。
"""
...
class DirectoryScanAdapter(Protocol):
"""扫描文档库类型目录。"""
source_type: str
def scan(
self,
*,
period_month: date,
invoice_no: str,
rule: dict[str, Any],
) -> ScanOutcome:
"""
在对应类型目录中按命名模板匹配文件。
【AI 触发时机】周任务对每张 invoice 的每条 directory_scan 规则调用。
"""
...
class AcquireAdapter(Protocol):
"""把外部单据打印后写入类型目录;PO / 销货放行单一期仅占位。"""
source_type: str
wired: bool
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
"""
获取并落入类型目录。
【AI 触发时机】仅当独立抓取任务启用且 Adapter.wired=True 时调用;周任务不调用。
"""
...
class ArchiveAdapter(Protocol):
"""把已匹配文件复制到所有归档/{invoice}/。"""
wired: bool
def archive(
self,
*,
period_month: date,
invoice_no: str,
file: ScannedFile,
rule: dict[str, Any],
) -> ScannedFile:
"""
复制到归档子目录;目标已有同名文件则跳过覆盖。
【AI 触发时机】扫描命中且命名校验通过后调用。
"""
...
@@ -0,0 +1,81 @@
"""
backend/app/services/voucher_check/adapters/dms_archive.py
用途:把类型目录中的命中文件复制到「所有归档/{invoice}/」。
依赖:dms_client(SaveFolder + Copy);不调用 Move。
逻辑:wired=True;目标目录已有同名文件则跳过并记 archived,复制失败记技术失败。
"""
from __future__ import annotations
from datetime import date
from typing import Any
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.base import ScannedFile
from app.services.voucher_check.dms_client import SalesDmsClient
class DmsArchiveAdapter:
"""按票归档:建「所有归档/{invoice}/」并复制,同名跳过。"""
source_type = "dms_archive"
wired = True
def __init__(self) -> None:
self._archive_root_ids: dict[str, str] = {}
def _archive_root_id(self, period_month: date) -> str:
key = period_month.strftime("%Y-%m")
if key not in self._archive_root_ids:
self._archive_root_ids[key] = SalesDmsClient.ensure_month_archive_root(
period_month=period_month
)
return self._archive_root_ids[key]
def archive(
self,
*,
period_month: date,
invoice_no: str,
file: ScannedFile,
rule: dict[str, Any],
) -> ScannedFile:
"""
确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。
【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有同 LeafName 则跳过覆盖。
"""
yyyy = f"{period_month.year:04d}"
mm = f"{period_month.month:02d}"
archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{invoice_no}/{file.filename}"
source_item_id = str(file.item_id or "").strip()
if not source_item_id:
raise ServiceUnavailableError(
"命中文件缺少文档库条目 ID,无法复制",
code="VOUCHER_CHECK.ARCHIVE_FAILED",
details={"adapter": self.source_type, "rule": rule.get("code")},
)
archive_root_id = self._archive_root_id(period_month)
dest_folder_id = SalesDmsClient.ensure_folder(
parent_folder_id=archive_root_id,
leaf_name=str(invoice_no).strip(),
)
dest_row, skipped = SalesDmsClient.copy_file_skip_same_name(
source_item_id=source_item_id,
dest_folder_id=dest_folder_id,
leaf_name=file.filename,
)
return ScannedFile(
filename=file.filename,
item_id=str(dest_row.get("ID") or "").strip() or None,
folder_id=dest_folder_id,
path=archive_path,
fingerprint=file.fingerprint,
extra={
"skipped_same_name": skipped,
"source_item_id": source_item_id,
"dest_version_id": dest_row.get("VersionID"),
"rule": rule.get("code"),
},
)
@@ -0,0 +1,110 @@
"""
backend/app/services/voucher_check/adapters/dms_directory_scan.py
用途:扫描销售开票附件/{年}/{月}/{类型目录} 并按命名模板匹配 invoice。
依赖:dms_client、filename_match、fingerprint。
逻辑:目录不存在视为该规则缺件;登录/Page 失败视为技术失败。
"""
from __future__ import annotations
from datetime import date
from typing import Any
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.base import ScanOutcome, ScannedFile
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.filename_match import first_match
from app.services.voucher_check.fingerprint import build_material_fingerprint
class DmsDirectoryScanAdapter:
"""文档库类型目录扫描 Adapter。"""
source_type = "directory_scan"
def __init__(self) -> None:
self._month_folder_ids: dict[str, str | None] = {}
self._type_folder_ids: dict[str, str | None] = {}
self._type_files: dict[str, list[dict[str, Any]]] = {}
def _period_key(self, period_month: date) -> str:
return period_month.strftime("%Y-%m")
def _month_folder_id(self, period_month: date) -> str | None:
key = self._period_key(period_month)
if key not in self._month_folder_ids:
_year_id, month_id = SalesDmsClient.resolve_period_folder(period_month=period_month)
self._month_folder_ids[key] = month_id
return self._month_folder_ids[key]
def _type_folder_id(self, period_month: date, type_folder: str) -> str | None:
cache_key = f"{self._period_key(period_month)}/{type_folder}"
if cache_key not in self._type_folder_ids:
month_id = self._month_folder_id(period_month)
if not month_id:
self._type_folder_ids[cache_key] = None
else:
self._type_folder_ids[cache_key] = SalesDmsClient.find_child_folder(
parent_folder_id=month_id,
leaf_name=type_folder,
)
return self._type_folder_ids[cache_key]
def scan(
self,
*,
period_month: date,
invoice_no: str,
rule: dict[str, Any],
) -> ScanOutcome:
"""
在类型目录中匹配当前 invoice 的文件。
核心逻辑:缓存月目录与类型目录列表,避免每票重复 Page。
"""
type_folder = str(rule.get("type_folder") or "").strip()
template = str(rule.get("filename_template") or "").strip()
yyyy = f"{period_month.year:04d}"
mm = f"{period_month.month:02d}"
folder_path = f"销售开票附件/{yyyy}/{mm}/{type_folder}"
try:
folder_id = self._type_folder_id(period_month, type_folder)
if not folder_id:
return ScanOutcome(
status="missing",
folder_path=folder_path,
)
cache_key = folder_id
if cache_key not in self._type_files:
self._type_files[cache_key] = SalesDmsClient.list_files(folder_id=folder_id)
rows = self._type_files[cache_key]
names = [str(row.get("LeafName") or "").strip() for row in rows]
hit = first_match(names, template=template, invoice_no=invoice_no)
if hit is None:
return ScanOutcome(status="missing", folder_id=folder_id, folder_path=folder_path)
row = next((item for item in rows if str(item.get("LeafName") or "").strip() == hit.filename), {})
item_id = str((row or {}).get("ID") or "") or None
version_id = str((row or {}).get("VersionID") or "")
fingerprint = build_material_fingerprint(
[(f"{hit.filename}|{item_id or ''}|{version_id}", 0, 0)]
)
return ScanOutcome(
status="matched",
folder_id=folder_id,
folder_path=folder_path,
file=ScannedFile(
filename=hit.filename,
item_id=item_id,
folder_id=folder_id,
path=str((row or {}).get("Path") or folder_path),
fingerprint=fingerprint,
extra={"version_id": (row or {}).get("VersionID")},
),
)
except ServiceUnavailableError as exc:
return ScanOutcome(
status="technical_error",
folder_path=folder_path,
error_code=exc.code,
error_message=exc.message,
)
@@ -0,0 +1,36 @@
"""
backend/app/services/voucher_check/adapters/erp_po_print.py
用途:ERP 反查 PO 并打印 PDF 写入「PO订单」类型目录的占位 Adapter。
依赖:adapters.base。
逻辑:查询/打印方式待确认,周任务不调用;独立抓取任务启用前 wired=False。
"""
from __future__ import annotations
from datetime import date
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
class ErpPoPrintAdapter:
"""PO 打印占位;未接线时禁止生成假 PDF。"""
source_type = "erp_po_print"
wired = False
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
"""
预留:按 invoice 反查 PO 并打印到类型目录。
【AI 触发时机】仅当独立「抓取 PO」任务上线后调用,不要在周检核 runner 中调用。
"""
raise ServiceUnavailableError(
"ERP PO 打印尚未接线",
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
details={
"adapter": self.source_type,
"period": period_month.isoformat(),
"subject_count": len(subjects),
},
)
@@ -0,0 +1,61 @@
"""
backend/app/services/voucher_check/adapters/hxjm_apa_subject.py
用途:从 HXJM apa_file 拉取上一个月销售 invoice 清单。
依赖:erp_repository.fetch_month_invoices、fingerprint。
逻辑:周任务 subject_adapter=hxjm_apa;期间由 erp_repository 按上月计算。
"""
from __future__ import annotations
from datetime import date
from typing import Any
from app.services.voucher_check.adapters.base import SubjectRow
from app.services.voucher_check.erp_repository import fetch_month_invoices
from app.services.voucher_check.fingerprint import build_material_fingerprint
class HxjmApaSubjectAdapter:
"""HXJM apa08/apa09 主体 Adapter。"""
source_type = "hxjm_apa"
def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]:
"""
查询上月发票号集合并生成主体指纹。
核心逻辑:委托 fetch_month_invoices;返回期间必须与传入 period_month 一致。
Args:
period_month: 检核月首日,由 runner 预先算好。
config: 含 ERP 连接的运行配置。
Returns:
SubjectRow 列表。
"""
actual_period, rows = fetch_month_invoices(config)
if actual_period != period_month:
from app.core.errors import ServiceUnavailableError
raise ServiceUnavailableError(
"ERP 期间与批次期间不一致",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
details={
"expected": period_month.isoformat(),
"actual": actual_period.isoformat(),
},
)
subjects: list[SubjectRow] = []
for row in rows:
fingerprint = build_material_fingerprint(
[(row.invoice_no, 0, int((row.invoice_date or period_month).toordinal()))]
)
subjects.append(
SubjectRow(
invoice_no=row.invoice_no,
invoice_date=row.invoice_date,
source_fingerprint=fingerprint,
attributes={"scope_code": getattr(config, "scope_code", "HXJM")},
)
)
return subjects
@@ -0,0 +1,36 @@
"""
backend/app/services/voucher_check/adapters/oa_sales_release.py
用途:OA 销货放行单模拟页面打印的占位 Adapter。
依赖:adapters.base。
逻辑:一期规则已定但页面自动化未实现;周任务不调用,只扫描「销货单」目录。
"""
from __future__ import annotations
from datetime import date
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
class OaSalesReleaseAdapter:
"""销货放行单打印占位;未接线时禁止生成假 PDF。"""
source_type = "oa_sales_release"
wired = False
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
"""
预留:按上月/归档/HXJM/发票号非空过滤后逐条打印。
【AI 触发时机】仅当独立「抓取销货放行单」任务上线后调用。
"""
raise ServiceUnavailableError(
"OA 销货放行单打印尚未接线",
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
details={
"adapter": self.source_type,
"period": period_month.isoformat(),
"subject_count": len(subjects),
},
)
@@ -0,0 +1,44 @@
"""
backend/app/services/voucher_check/adapters/registry.py
用途:按 source_type / adapter 名解析已注册 Adapter。
依赖:adapters.base。
逻辑:模块 import 时 register;引擎禁止使用未登记的 source_type。
"""
from __future__ import annotations
from typing import Any, Callable
from app.core.errors import ValidationError
_REGISTRY: dict[str, Callable[[], Any]] = {}
def register_adapter(name: str, factory: Callable[[], Any]) -> None:
"""登记 Adapter 工厂。同名后注册覆盖,便于测试注入。"""
key = str(name or "").strip()
if not key:
raise ValidationError("Adapter 名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
_REGISTRY[key] = factory
def get_adapter(name: str) -> Any:
"""
按名称构造 Adapter。
核心逻辑:未注册则配置失败,避免引擎落到未知来源。
"""
key = str(name or "").strip()
factory = _REGISTRY.get(key)
if factory is None:
raise ValidationError(
f"未注册的 Adapter: {key}",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"adapter": key},
)
return factory()
def registered_adapter_names() -> tuple[str, ...]:
"""返回已登记名称,供测试断言。"""
return tuple(sorted(_REGISTRY))
@@ -0,0 +1,114 @@
"""
backend/app/services/voucher_check/aggregator.py
用途:按单文件结果计算缺件双口径、invoice 行 Excel 值与批次状态。
依赖:无 IO。
逻辑:缺件文件数计 missing 条数;缺件 invoice 数对 missing 去重;技术失败/跳过/待归档不计缺件。
"""
from __future__ import annotations
from collections import defaultdict
from typing import Any
EXCEL_PRESENT = "有"
EXCEL_MISSING = "缺件"
EXCEL_PENDING = "未检核"
INVOICE_COMPLETE = "完整"
INVOICE_MISSING = "缺件"
INVOICE_PENDING = "待处理"
_MISSING = "missing"
_ARCHIVED = "archived"
_SKIPPED = "skipped"
_TECH = "technical_error"
_STAGED = "staged"
def excel_cell_for_rule(statuses: list[str]) -> str:
"""一条规则在 Excel 中的单元格:缺件优先于有,其余为未检核。"""
if any(status == _MISSING for status in statuses):
return EXCEL_MISSING
if statuses and all(status == _ARCHIVED for status in statuses):
return EXCEL_PRESENT
return EXCEL_PENDING
def invoice_conclusion(cells: list[str]) -> str:
"""invoice 行总体状态。"""
if cells and all(cell == EXCEL_PRESENT for cell in cells):
return INVOICE_COMPLETE
if any(cell == EXCEL_MISSING for cell in cells):
return INVOICE_MISSING
return INVOICE_PENDING
def aggregate_file_results(
results: list[dict[str, Any]],
*,
rules: list[dict[str, Any]],
) -> dict[str, Any]:
"""
聚合单文件结果。
核心逻辑:只认 status 字段;同一 invoice 多条缺件文件计多份、invoice 只计一次。
"""
missing_files = [row for row in results if row.get("status") == _MISSING]
missing_invoices = {str(row.get("invoice_no") or "") for row in missing_files}
missing_invoices.discard("")
by_type: dict[str, dict[str, Any]] = {}
for rule in rules:
code = str(rule.get("code") or "")
type_rows = [row for row in results if row.get("rule_code") == code]
type_missing = [row for row in type_rows if row.get("status") == _MISSING]
by_type[code] = {
"rule_code": code,
"rule_name": rule.get("name") or code,
"missing_file_count": len(type_missing),
"missing_invoice_count": len({str(row.get("invoice_no") or "") for row in type_missing} - {""}),
}
invoices: dict[str, list[dict[str, Any]]] = defaultdict(list)
for row in results:
invoices[str(row.get("invoice_no") or "")].append(row)
excel_rows: list[dict[str, Any]] = []
for invoice_no, rows in invoices.items():
if not invoice_no:
continue
cells: dict[str, str] = {}
ordered_cells: list[str] = []
for rule in rules:
code = str(rule.get("code") or "")
cell = excel_cell_for_rule(
[str(item.get("status") or "") for item in rows if item.get("rule_code") == code]
)
cells[code] = cell
ordered_cells.append(cell)
excel_rows.append(
{
"invoice_no": invoice_no,
"invoice_date": next((item.get("invoice_date") for item in rows if item.get("invoice_date")), None),
"cells": cells,
"status": invoice_conclusion(ordered_cells),
}
)
excel_rows.sort(key=lambda item: str(item["invoice_no"]))
batch_status = "completed"
if missing_files:
batch_status = "missing"
elif any(row.get("status") == _TECH for row in results):
batch_status = "technical_failed"
return {
"subject_count": len([key for key in invoices if key]),
"archived_file_count": sum(1 for row in results if row.get("status") == _ARCHIVED),
"skipped_file_count": sum(1 for row in results if row.get("status") == _SKIPPED),
"missing_file_count": len(missing_files),
"missing_invoice_count": len(missing_invoices),
"technical_error_count": sum(1 for row in results if row.get("status") == _TECH),
"staged_file_count": sum(1 for row in results if row.get("status") == _STAGED),
"by_file_type": by_type,
"excel_rows": excel_rows,
"batch_status": batch_status,
}
+39 -172
View File
@@ -1,16 +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
@@ -18,60 +17,22 @@ 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": True,
}
@dataclass(frozen=True)
class RequiredFileRule:
"""单条必检材料规则。"""
code: str
name: str
required: bool
accepted_filenames: tuple[str, ...]
@dataclass(frozen=True)
class VoucherCheckConfig:
"""运行期检核配置快照。"""
class VoucherCheckEngineConfig:
"""销售一期引擎运行配置:ERP + 通知开关。"""
scope_code: str
directory_template: str
required_files: tuple[RequiredFileRule, ...]
filename_case_sensitive: bool
profile_code: str
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
@@ -99,114 +60,13 @@ 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:
def _erp_settings() -> tuple[str, str, str, int]:
"""
校验目录模板占位符。
核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。
读取 ERP 只读连接;密码只来自环境/配置,不写日志。
核心逻辑:VOUCHER_CHECK_ERP_* 优先,其次通用 ERP_*,再回退合同付款同一套只读账号。
"""
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 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 = str(
cfg.get("VOUCHER_CHECK_ERP_DSN")
or os.getenv("VOUCHER_CHECK_ERP_DSN")
@@ -217,46 +77,53 @@ def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> Vouch
erp_username = str(
cfg.get("VOUCHER_CHECK_ERP_USERNAME")
or os.getenv("VOUCHER_CHECK_ERP_USERNAME")
or cfg.get("ERP_USERNAME")
or os.getenv("ERP_USERNAME")
or cfg.get("CONTRACT_PAYMENT_ERP_USERNAME")
or os.getenv("CONTRACT_PAYMENT_ERP_USERNAME")
or ""
).strip()
erp_password = str(
cfg.get("VOUCHER_CHECK_ERP_PASSWORD")
or os.getenv("VOUCHER_CHECK_ERP_PASSWORD")
or cfg.get("ERP_PASSWORD")
or os.getenv("ERP_PASSWORD")
or cfg.get("CONTRACT_PAYMENT_ERP_PASSWORD")
or os.getenv("CONTRACT_PAYMENT_ERP_PASSWORD")
or ""
)
if not erp_dsn or not erp_username:
raise _config_invalid("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME")
timeout = int(
cfg.get("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS")
or os.getenv("VOUCHER_CHECK_ERP_TIMEOUT_SECONDS")
or cfg.get("ERP_TIMEOUT_SECONDS")
or os.getenv("ERP_TIMEOUT_SECONDS")
or 30
)
return erp_dsn, erp_username, erp_password, max(1, timeout)
return VoucherCheckConfig(
def load_engine_config(job_params: dict[str, Any] | None = None) -> VoucherCheckEngineConfig:
"""
加载销售一期引擎配置。
核心逻辑:不要求共享盘;DMS 根目录由 SalesDmsClient.ensure_configured 在 runner 中校验。
"""
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})
profile_code = str(params.get("profile_code") or "sales").strip() or "sales"
erp_dsn, erp_username, erp_password, timeout = _erp_settings()
return VoucherCheckEngineConfig(
scope_code=scope_code,
directory_template=template,
required_files=tuple(required_files),
filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True),
profile_code=profile_code,
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),
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
@@ -0,0 +1,402 @@
"""
backend/app/services/voucher_check/dms_client.py
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。
依赖:requests、Flask 配置;登录接口与合同库相同。
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。
"""
from __future__ import annotations
import threading
import time
from datetime import date
from typing import Any
import requests
from flask import current_app
from app.core.errors import ServiceUnavailableError, ValidationError
_LOCK = threading.Lock()
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
ARCHIVE_ROOT_LEAF = "所有归档"
def _extract_item_id(payload: dict[str, Any]) -> str:
"""
从 DMS SaveFolder / Copy 响应中取出条目 ID。
核心逻辑:现网 Data 可能是对象或字符串;缺字段时返回空串,由调用方再 Page 回查。
"""
data = payload.get("Data")
if isinstance(data, str) and data.strip():
return data.strip()
if not isinstance(data, dict):
return ""
for key in ("ID", "ItemID", "FolderID"):
value = str(data.get(key) or "").strip()
if value:
return value
nested = data.get("Item") or data.get("Folder") or {}
if isinstance(nested, dict):
return str(nested.get("ID") or "").strip()
return ""
def _is_name_conflict(message: str) -> bool:
"""判断 DMS 返回是否为同名/已存在冲突,便于按「同名跳过」回收。"""
text = str(message or "").strip()
if not text:
return False
lowered = text.lower()
return any(
needle in text
for needle in ("已存在", "同名", "重复名称", "名称重复")
) or any(
needle in lowered
for needle in ("already exist", "already exists", "duplicate name")
)
class SalesDmsClient:
"""销售开票附件 DMS 客户端;不把账号密码返回给 API。"""
@classmethod
def _cfg(cls, key: str, fallback: str = "") -> str:
value = current_app.config.get(key) or fallback
return str(value or "").strip()
@classmethod
def base_url(cls) -> str:
return (cls._cfg("VOUCHER_CHECK_DMS_BASE_URL") or cls._cfg("CONTRACT_DMS_BASE_URL")).rstrip("/")
@classmethod
def library_id(cls) -> str:
return cls._cfg("VOUCHER_CHECK_DMS_LIBRARY_ID") or cls._cfg("CONTRACT_DMS_LIBRARY_ID")
@classmethod
def root_folder_id(cls) -> str:
return cls._cfg("VOUCHER_CHECK_DMS_ROOT_FOLDER_ID")
@classmethod
def username(cls) -> str:
return cls._cfg("VOUCHER_CHECK_DMS_USERNAME") or cls._cfg("CONTRACT_DMS_USERNAME")
@classmethod
def password(cls) -> str:
return str(
current_app.config.get("VOUCHER_CHECK_DMS_PASSWORD")
or current_app.config.get("CONTRACT_DMS_PASSWORD")
or ""
)
@classmethod
def is_configured(cls) -> bool:
"""判断销售 DMS 基址、账号、文档库 ID 和销售根目录是否齐全。"""
return bool(cls.base_url() and cls.username() and cls.password() and cls.library_id() and cls.root_folder_id())
@classmethod
def ensure_configured(cls) -> None:
"""
配置缺失时在批次开始前失败,并返回可操作的缺失项。
核心逻辑:避免把空扫当成业务缺件;同时不能将任意凭据值写入错误响应。
"""
missing = [
key
for key, value in (
("VOUCHER_CHECK_DMS_BASE_URL", cls.base_url()),
("VOUCHER_CHECK_DMS_LIBRARY_ID", cls.library_id()),
("VOUCHER_CHECK_DMS_ROOT_FOLDER_ID", cls.root_folder_id()),
("VOUCHER_CHECK_DMS_USERNAME", cls.username()),
("VOUCHER_CHECK_DMS_PASSWORD", cls.password()),
)
if not value
]
if missing:
raise ValidationError(
"销售开票附件文档库配置不完整",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"missing": missing},
)
@classmethod
def _session(cls, *, refresh: bool = False) -> requests.Session:
"""登录 DMS 并缓存会话。"""
with _LOCK:
session = _CACHE.get("session")
if not refresh and isinstance(session, requests.Session) and time.time() - float(_CACHE.get("created_at") or 0) < 1200:
return session
session = requests.Session()
try:
response = session.post(
f"{cls.base_url()}/Login/_api/Login",
json={"LoginName": cls.username(), "Pwd": cls.password()},
timeout=20,
)
response.raise_for_status()
payload = response.json()
except requests.RequestException as exc:
raise ServiceUnavailableError(
"文档库登录失败",
code="VOUCHER_CHECK.DMS_UNAVAILABLE",
) from exc
if int(payload.get("Code") or 0) != 0:
raise ServiceUnavailableError(
payload.get("Msg") or "文档库登录失败",
code="VOUCHER_CHECK.DMS_UNAVAILABLE",
)
_CACHE.update({"session": session, "created_at": time.time()})
return session
@classmethod
def _post_json(
cls,
path: str,
payload: dict[str, Any],
*,
timeout: int = 30,
failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE",
failure_message: str = "文档库请求失败",
) -> dict[str, Any]:
"""
POST JSON 到现网 DMS,并统一处理 401 刷新与 Code!=0。
核心逻辑:路径相对基址;失败抛 ServiceUnavailableError,不把凭据写入异常。
"""
url = f"{cls.base_url()}{path}"
try:
session = cls._session()
response = session.post(url, json=payload, timeout=timeout)
if response.status_code in {401, 403}:
session = cls._session(refresh=True)
response = session.post(url, json=payload, timeout=timeout)
response.raise_for_status()
data = response.json()
except (requests.RequestException, ValueError) as exc:
raise ServiceUnavailableError(failure_message, code=failure_code) from exc
if int(data.get("Code") or 0) != 0:
raise ServiceUnavailableError(
data.get("Msg") or failure_message,
code=failure_code,
)
return data
@classmethod
def page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]:
"""
查询一个父目录下的条目。
核心逻辑:POST Item/Page,按页累加直到本页不足 Size 或达到 Total;避免「所有归档」超过 200 个子目录时漏建/漏跳过。
"""
items: list[dict[str, Any]] = []
page_size = 200
index = 1
while index <= 50:
payload = {
"LibraryID": cls.library_id(),
"ParentFolderID": parent_folder_id,
"Keywords": "",
"Page": {"Size": page_size, "Index": index},
"Total": 0,
"Recursion": recursion,
"OrderBy": [],
"FieldQuery": [],
"LeafName": leaf_name,
}
data = cls._post_json("/Api/_api/APS/Public/Item/Page", payload, timeout=30)
section = data.get("Data") or {}
batch = section.get("Rows") or section.get("Items") or (section.get("Page") or {}).get("Items") or []
items.extend(batch)
total = int(section.get("Total") or 0)
if len(batch) < page_size:
break
if total and len(items) >= total:
break
index += 1
return items
@classmethod
def find_child_folder(cls, *, parent_folder_id: str, leaf_name: str) -> str | None:
"""在父目录下按 LeafName 找文件夹 ID,找不到返回 None。"""
wanted = str(leaf_name or "").strip()
if not wanted:
return None
for row in cls.page(parent_folder_id=parent_folder_id, recursion=False):
if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == wanted:
folder_id = str(row.get("ID") or "").strip()
if folder_id:
return folder_id
return None
@classmethod
def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None:
"""在父目录下按 LeafName 找非文件夹条目,找不到返回 None。"""
wanted = str(leaf_name or "").strip()
if not wanted:
return None
for row in cls.list_files(folder_id=parent_folder_id):
if str(row.get("LeafName") or "").strip() == wanted:
return row
return None
@classmethod
def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]:
"""
解析销售开票附件/{yyyy}/{MM} 的 FolderID。
核心逻辑:从销售根逐级找年、月目录;缺层返回 (None, None),由扫描记缺件而非技术失败。
"""
root = cls.root_folder_id()
year_name = f"{period_month.year:04d}"
month_name = f"{period_month.month:02d}"
year_id = cls.find_child_folder(parent_folder_id=root, leaf_name=year_name)
if not year_id:
return None, None
month_id = cls.find_child_folder(parent_folder_id=year_id, leaf_name=month_name)
return year_id, month_id
@classmethod
def list_files(cls, *, folder_id: str) -> list[dict[str, Any]]:
"""列出目录下的非文件夹条目。"""
rows = cls.page(parent_folder_id=folder_id, recursion=False)
return [row for row in rows if not row.get("IsFolder")]
@classmethod
def ensure_folder(cls, *, parent_folder_id: str, leaf_name: str) -> str:
"""
确保父目录下存在指定 LeafName 的文件夹;没有则 SaveFolder。
核心逻辑:先 Page 查找;已存在直接返回。创建时若接口报同名,再查一次当作成功。
"""
wanted = str(leaf_name or "").strip()
if not wanted:
raise ValidationError("文件夹名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted)
if existing:
return existing
try:
payload = cls._post_json(
"/Api/_api/APS/Public/Item/SaveFolder",
{
"ID": "",
"LibraryID": cls.library_id(),
"ParentFolderID": parent_folder_id,
"LeafName": wanted,
"FieldValues": [],
},
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
failure_message="文档库创建文件夹失败",
)
except ServiceUnavailableError as exc:
existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted)
if existing:
return existing
if _is_name_conflict(exc.message):
existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted)
if existing:
return existing
raise
created_id = _extract_item_id(payload)
if created_id:
return created_id
existing = cls.find_child_folder(parent_folder_id=parent_folder_id, leaf_name=wanted)
if existing:
return existing
raise ServiceUnavailableError(
"创建文件夹后未能解析 FolderID",
code="VOUCHER_CHECK.ARCHIVE_FAILED",
details={"leaf_name": wanted},
)
@classmethod
def ensure_month_archive_root(cls, *, period_month: date) -> str:
"""
确保销售开票附件/{yyyy}/{MM}/所有归档 存在并返回 FolderID。
核心逻辑:月目录必须已存在(扫描命中才归档);缺月目录视为技术失败,不降级为缺件。
"""
_year_id, month_id = cls.resolve_period_folder(period_month=period_month)
if not month_id:
raise ServiceUnavailableError(
"销售开票附件年/月目录不存在,无法创建归档文件夹",
code="VOUCHER_CHECK.ARCHIVE_FAILED",
)
return cls.ensure_folder(parent_folder_id=month_id, leaf_name=ARCHIVE_ROOT_LEAF)
@classmethod
def ensure_invoice_archive_folder(cls, *, period_month: date, invoice_no: str) -> str:
"""
确保所有归档/{invoice}/ 存在并返回 FolderID。
核心逻辑:先保证「所有归档」,再按发票号建子目录。
"""
invoice = str(invoice_no or "").strip()
if not invoice:
raise ValidationError("归档发票号不能为空", code="VOUCHER_CHECK.INVOICE_REQUIRED")
archive_root_id = cls.ensure_month_archive_root(period_month=period_month)
return cls.ensure_folder(parent_folder_id=archive_root_id, leaf_name=invoice)
@classmethod
def copy_items(cls, *, item_ids: list[str], dest_folder_id: str) -> dict[str, Any]:
"""
把文档库条目复制到目标文件夹(不移动原件)。
核心逻辑:POST Item/Copy;ItemID 为数组,与现网前端 CopyFileFolder 一致。
"""
ids = [str(item_id).strip() for item_id in item_ids if str(item_id).strip()]
dest = str(dest_folder_id or "").strip()
if not ids:
raise ValidationError("复制源条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
if not dest:
raise ValidationError("复制目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
return cls._post_json(
"/Api/_api/APS/Public/Item/Copy",
{"ItemID": ids, "ParentFolderID": dest},
timeout=60,
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
failure_message="文档库复制文件失败",
)
@classmethod
def copy_file_skip_same_name(
cls,
*,
source_item_id: str,
dest_folder_id: str,
leaf_name: str,
) -> tuple[dict[str, Any], bool]:
"""
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
核心逻辑:先按 LeafName 查目标;没有再 Copy。Copy 报同名或复制后已能查到,一律视为跳过成功。
Returns:
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有同名文件。
"""
wanted = str(leaf_name or "").strip()
source = str(source_item_id or "").strip()
dest = str(dest_folder_id or "").strip()
if not source:
raise ValidationError("复制源条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
if not dest:
raise ValidationError("复制目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
if not wanted:
raise ValidationError("复制文件名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if existing:
return existing, True
try:
cls.copy_items(item_ids=[source], dest_folder_id=dest)
except ServiceUnavailableError as exc:
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if existing:
return existing, True
if _is_name_conflict(exc.message):
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if existing:
return existing, True
raise
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if not dest_row:
raise ServiceUnavailableError(
"复制成功但目标目录未找到同名文件",
code="VOUCHER_CHECK.ARCHIVE_FAILED",
details={"leaf_name": wanted},
)
return dest_row, False
@@ -0,0 +1,182 @@
"""
backend/app/services/voucher_check/engine_persistence.py
用途:新引擎批次、主体、单文件结果与通知审计的写入。
依赖:models.voucher_check 新表。
逻辑:runner 在扫描完成后一次性 persist;旧 invoice_states 不再写入。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Any
from app import db
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckNotification,
VoucherCheckRun,
VoucherCheckSubject,
)
def create_run(
*,
schedule_run_id: int | None,
run_no: str,
profile_code: str,
profile_version: str,
profile_snapshot: dict[str, Any],
period_month: date,
mode: str,
started_at: datetime,
) -> VoucherCheckRun:
"""创建 running 状态的检核批次。"""
run = VoucherCheckRun(
schedule_run_id=schedule_run_id,
run_no=run_no,
profile_code=profile_code,
profile_version=profile_version,
profile_snapshot_json=profile_snapshot,
period_month=period_month,
mode=mode,
status="running",
started_at=started_at,
created_at=started_at,
)
db.session.add(run)
db.session.flush()
return run
def persist_engine_results(
*,
run: VoucherCheckRun,
subjects: list[dict[str, Any]],
file_results: list[dict[str, Any]],
stats: dict[str, Any],
now: datetime | None = None,
) -> None:
"""
写入主体与单文件结果,并固化批次统计快照。
核心逻辑:file_results 是缺件/Excel 真相源;列表查询不再重算。
"""
ts = now or datetime.utcnow()
subject_ids: dict[str, int] = {}
for item in subjects:
invoice_no = str(item["invoice_no"]).strip()
row = VoucherCheckSubject(
run_id=run.id,
invoice_no=invoice_no,
invoice_date=item.get("invoice_date"),
source_fingerprint=item.get("source_fingerprint"),
attributes_json=item.get("attributes") or {},
created_at=ts,
)
db.session.add(row)
db.session.flush()
subject_ids[invoice_no] = row.id
for item in file_results:
invoice_no = str(item["invoice_no"]).strip()
db.session.add(
VoucherCheckFileResult(
run_id=run.id,
subject_id=subject_ids.get(invoice_no),
invoice_no=invoice_no,
rule_code=str(item["rule_code"]),
rule_name=str(item.get("rule_name") or item["rule_code"]),
source_type=str(item.get("source_type") or "directory_scan"),
expected_name=item.get("expected_name"),
matched_name=item.get("matched_name"),
source_folder_id=item.get("source_folder_id"),
source_item_id=item.get("source_item_id"),
archive_folder_id=item.get("archive_folder_id"),
archive_item_id=item.get("archive_item_id"),
source_path=item.get("source_path"),
archive_path=item.get("archive_path"),
status=str(item["status"]),
missing_reason=item.get("missing_reason"),
error_code=item.get("error_code"),
error_message=item.get("error_message"),
source_fingerprint=item.get("source_fingerprint"),
checked_at=item.get("checked_at") or ts,
created_at=ts,
)
)
run.subject_count = int(stats.get("subject_count") or 0)
run.archived_file_count = int(stats.get("archived_file_count") or 0)
run.skipped_file_count = int(stats.get("skipped_file_count") or 0)
run.missing_file_count = int(stats.get("missing_file_count") or 0)
run.missing_invoice_count = int(stats.get("missing_invoice_count") or 0)
run.technical_error_count = int(stats.get("technical_error_count") or 0)
run.staged_file_count = int(stats.get("staged_file_count") or 0)
run.stats_json = {
"by_file_type": stats.get("by_file_type") or {},
"batch_status": stats.get("batch_status"),
}
run.status = str(stats.get("batch_status") or "completed")
run.finished_at = ts
db.session.flush()
def persist_notification(
*,
run_id: int,
excel_filename: str | None,
recipient_user_ids: list[int],
send_status: str,
skip_reason: str | None,
summary: dict[str, Any],
sent_at: datetime | None,
) -> VoucherCheckNotification:
"""写入或覆盖本批次通知审计(一个 run 一条)。"""
row = (
db.session.query(VoucherCheckNotification)
.filter_by(run_id=run_id)
.one_or_none()
)
if row is None:
row = VoucherCheckNotification(run_id=run_id, created_at=datetime.utcnow())
db.session.add(row)
row.excel_filename = excel_filename
row.recipient_user_ids_json = recipient_user_ids
row.send_status = send_status
row.skip_reason = skip_reason
row.summary_json = summary
row.sent_at = sent_at
db.session.flush()
return row
def load_previous_archived_fingerprints(
*,
profile_code: str,
period_month: date,
exclude_run_id: int | None = None,
) -> dict[tuple[str, str], str]:
"""
读取同 Profile+期间已归档文件的最新指纹,供增量跳过。
核心逻辑:按 file_results.id 倒序,每个 invoice+rule 只留一条 archived。
"""
query = (
db.session.query(VoucherCheckFileResult, VoucherCheckRun)
.join(VoucherCheckRun, VoucherCheckFileResult.run_id == VoucherCheckRun.id)
.filter(
VoucherCheckRun.profile_code == profile_code,
VoucherCheckRun.period_month == period_month,
VoucherCheckFileResult.status == "archived",
)
.order_by(VoucherCheckFileResult.id.desc())
)
if exclude_run_id:
query = query.filter(VoucherCheckFileResult.run_id != exclude_run_id)
found: dict[tuple[str, str], str] = {}
for result, _run in query.all():
key = (result.invoice_no, result.rule_code)
if key in found:
continue
if result.source_fingerprint:
found[key] = result.source_fingerprint
return found
@@ -1,7 +1,7 @@
"""
backend/app/services/voucher_check/erp_repository.py
用途:从 Oracle HXJM 套账 apa_file 查询当前自然月发票号集合。
用途:从 Oracle HXJM 套账 apa_file 查询上一个自然月发票号集合。
依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。
逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
"""
@@ -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")
@@ -31,7 +31,7 @@ SELECT DISTINCT
@dataclass(frozen=True)
class ErpInvoiceRow:
"""ERP 当月发票行。"""
"""ERP 发票行。"""
invoice_no: str
invoice_date: date | None
@@ -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)
@@ -60,13 +60,32 @@ def current_period_bounds(now: datetime | None = None) -> tuple[date, date, date
return period_month, next_month, period_start, next_start
def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
"""
按 Asia/Shanghai 计算上一个自然月起止。
核心逻辑:周二跑批检核上个月;跨年时 1 月回退到上年 12 月。
Returns:
(period_month_first, current_month_first, period_start_dt, next_period_start_dt)
其中 next_period_start 为当前月 1 日,即上月结束边界。
"""
current_month, _next_month, _current_start, _next_start = current_period_bounds(now)
if current_month.month == 1:
period_month = date(current_month.year - 1, 12, 1)
else:
period_month = date(current_month.year, current_month.month - 1, 1)
period_start = datetime(period_month.year, period_month.month, 1, 0, 0, 0, tzinfo=_TZ)
next_start = datetime(current_month.year, current_month.month, 1, 0, 0, 0, tzinfo=_TZ)
return period_month, current_month, period_start, next_start
def fetch_month_invoices(
config: VoucherCheckConfig,
config: VoucherCheckEngineConfig,
*,
now: datetime | None = None,
) -> tuple[date, list[ErpInvoiceRow]]:
"""
查询当前自然月发票清单。
查询上一个自然月发票清单。
Args:
config: 含 Oracle DSN/账号的检核配置。
@@ -78,7 +97,7 @@ def fetch_month_invoices(
Raises:
ServiceUnavailableError: Oracle 不可用。
"""
period_month, _next_month, period_start, next_start = current_period_bounds(now)
period_month, _current_month, period_start, next_start = previous_period_bounds(now)
try:
import oracledb
except ImportError as exc:
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/excel_rows.py
用途:把批次明细转换为通用 Excel 导出行与表头。
依赖:无。
逻辑:runner 返回 details;schedule excel_service / register_schedule_header 使用本模块表头。
用途:把按 invoice 聚合的检核结果转为排程 Excel 行与表头。
依赖:aggregator 单元格文案。
逻辑:一行一张 invoice;六类必检列为有/缺件/未检核;资料所属期间与执行时间单独成列以兼容现有排程导出。
"""
from __future__ import annotations
@@ -12,82 +12,57 @@ from typing import Any
VOUCHER_CHECK_HEADER_ORDER = [
"period",
"scope_code",
"executed_at",
"invoice_no",
"invoice_date",
"result",
"folder_exists",
"folder_path",
"matched_files",
"missing_materials",
"material_fingerprint",
"checked_at",
"error_code",
"error_message",
"po_order",
"customs_pack",
"sales_release",
"tax_invoice",
"customs_declaration",
"bill_of_lading",
"status",
]
VOUCHER_CHECK_HEADER_LABELS = {
"period": "检核月份",
"scope_code": "账套",
"invoice_no": "发票号",
"invoice_date": "发票日期",
"result": "结论",
"folder_exists": "发票目录是否存在",
"folder_path": "共享盘相对路径",
"matched_files": "已找到材料",
"missing_materials": "缺失材料",
"material_fingerprint": "目录元数据指纹",
"checked_at": "实际检核时间",
"error_code": "技术错误码",
"error_message": "技术错误摘要",
"period": "资料所属期间",
"executed_at": "执行时间",
"invoice_no": "invoice",
"po_order": "PO订单",
"customs_pack": "报关资料",
"sales_release": "销货放行申请单",
"tax_invoice": "发票",
"customs_declaration": "报关单",
"bill_of_lading": "提单",
"status": "状态",
}
_RESULT_LABELS = {
"complete": "齐全",
"missing": "缺资料",
"skipped": "跳过",
"technical_error": "技术异常",
}
_RULE_COLUMNS = (
"po_order",
"customs_pack",
"sales_release",
"tax_invoice",
"customs_declaration",
"bill_of_lading",
)
def _fmt_matched(matched: dict[str, Any] | None) -> str:
if not matched:
return ""
return "; ".join(f"{k}={v}" for k, v in matched.items())
def _fmt_missing(missing: list[dict[str, Any]] | None) -> str:
if not missing:
return ""
parts = []
for item in missing:
name = item.get("name") or item.get("code") or ""
code = item.get("code") or ""
parts.append(f"{name}({code})" if code and name != code else str(name or code))
return "; ".join(parts)
def to_excel_detail_row(item: dict[str, Any], *, period: str, scope_code: str) -> dict[str, Any]:
def to_excel_invoice_row(
item: dict[str, Any],
*,
period: str,
executed_at: str,
) -> dict[str, Any]:
"""
将内存结果行转为 Excel details 行。
将聚合后的 invoice 行转为排程 Excel details。
核心逻辑:cells 按 rule_code 取值;缺列填未检核。
"""
result = str(item.get("result") or "")
checked_at = item.get("checked_at")
invoice_date = item.get("invoice_date")
return {
cells = item.get("cells") or {}
row = {
"period": period,
"scope_code": scope_code,
"executed_at": executed_at,
"invoice_no": item.get("invoice_no"),
"invoice_date": invoice_date.isoformat() if hasattr(invoice_date, "isoformat") else invoice_date,
"result": _RESULT_LABELS.get(result, result),
"folder_exists": "是" if item.get("folder_exists") else "否",
"folder_path": item.get("folder_path") or "",
"matched_files": _fmt_matched(item.get("matched_files")),
"missing_materials": _fmt_missing(item.get("missing_materials")),
"material_fingerprint": item.get("material_fingerprint") or "",
"checked_at": checked_at.isoformat(sep=" ", timespec="seconds")
if hasattr(checked_at, "isoformat")
else (checked_at or ""),
"error_code": item.get("error_code") or "",
"error_message": item.get("error_message") or "",
"status": item.get("status") or "",
}
for code in _RULE_COLUMNS:
row[code] = cells.get(code) or "未检核"
return row
@@ -0,0 +1,89 @@
"""
backend/app/services/voucher_check/filename_match.py
用途:按 Profile 命名模板匹配文档库文件名,并校验文件名中的 invoice。
依赖:标准库 re。
逻辑:{invoice} 替换为当前票号;其余 {token} 视为一段非路径字符;禁止路径穿越。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
_PLACEHOLDER_RE = re.compile(r"\{([^{}]+)\}")
_UNSAFE_RE = re.compile(r"[/\\\x00]|(\.\.)")
@dataclass(frozen=True)
class FilenameMatch:
"""单次文件名命中。"""
filename: str
groups: dict[str, str]
def compile_filename_pattern(template: str, *, invoice_no: str) -> re.Pattern[str]:
"""
把命名模板编译为整名匹配正则。
核心逻辑:先替换 invoice,再把剩余占位符变成捕获组,字面量全部转义。
Args:
template: 如 `{invoice}-{order_no}.pdf`。
invoice_no: 当前发票号,禁止含路径字符。
Returns:
锚定的正则。
Raises:
ValueError: 模板或发票号非法。
"""
invoice = str(invoice_no or "").strip()
if not invoice or _UNSAFE_RE.search(invoice):
raise ValueError("invoice_no 非法")
text = str(template or "").strip()
if not text or _UNSAFE_RE.search(_PLACEHOLDER_RE.sub("", text)):
raise ValueError("filename_template 非法")
parts: list[str] = []
cursor = 0
for match in _PLACEHOLDER_RE.finditer(text):
parts.append(re.escape(text[cursor : match.start()]))
name = match.group(1)
if name in {"invoice", "invoice号"}:
parts.append(re.escape(invoice))
else:
parts.append(rf"(?P<{re.escape(name)}>[^/\\]+)")
cursor = match.end()
parts.append(re.escape(text[cursor:]))
return re.compile(r"^" + "".join(parts) + r"$")
def match_filename(filename: str, *, template: str, invoice_no: str) -> FilenameMatch | None:
"""
判断文件名是否属于该 invoice 的规则。
核心逻辑:整名匹配;命中后要求文件名包含 invoice 原文。
"""
name = str(filename or "").strip()
if not name:
return None
try:
pattern = compile_filename_pattern(template, invoice_no=invoice_no)
except ValueError:
return None
matched = pattern.match(name)
if not matched:
return None
invoice = str(invoice_no).strip()
if invoice not in name:
return None
return FilenameMatch(filename=name, groups=matched.groupdict())
def first_match(filenames: list[str], *, template: str, invoice_no: str) -> FilenameMatch | None:
"""在文件名列表中返回第一条命中,保持目录返回顺序。"""
for name in filenames:
hit = match_filename(name, template=template, invoice_no=invoice_no)
if hit is not None:
return hit
return None
@@ -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,15 +1,15 @@
"""
backend/app/services/voucher_check/notification.py
用途:立账凭证检核缺资料企微 textcard 与批次失败告警。
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、persistence.mark_missing_notified。
逻辑:runner 落库后调用;同票同日节流;设置 domain_notification_managed 避免通用排程重复通知。
用途:立账凭证检核批次级企微汇总与技术失败告警。
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。
逻辑:一个批次一条缺件汇总;未配置接收人不发送;设置 domain_notification_managed 避免通用排程重复通知。
"""
from __future__ import annotations
import uuid
from datetime import date, datetime
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
@@ -17,7 +17,7 @@ from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.voucher_check.persistence import mark_missing_notified
from app.services.voucher_check.engine_persistence import persist_notification
_TZ = ZoneInfo("Asia/Shanghai")
@@ -30,85 +30,115 @@ def _recipient_users(task: ScheduleTask) -> list[User]:
return [u for u in users if u.wecom_userid]
def _today_shanghai(now: datetime | None = None) -> date:
base = now or datetime.now(_TZ)
if base.tzinfo is None:
base = base.replace(tzinfo=_TZ)
else:
base = base.astimezone(_TZ)
return base.date()
def send_missing_notifications(
def send_batch_missing_summary(
*,
task: ScheduleTask,
run: ScheduleRun,
scope_code: str,
period_month: date,
missing_items: list[dict[str, Any]],
same_day_dedup: bool,
schedule_run: ScheduleRun,
engine_run_id: int,
profile_code: str,
period_month: str,
stats: dict[str, Any],
excel_filename: str | None,
enabled: bool,
) -> int:
) -> str:
"""
合并发送缺资料 textcard。
核心逻辑:过滤同日已通知票;成功后才写 last_missing_notified_on。
发送本批缺件汇总 textcard。
核心逻辑:无缺件或未选接收人则不发空通知,并写入 notification 审计。
Returns:
本次实际通知的发票数。
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
"""
if not enabled or not missing_items:
return 0
missing_files = int(stats.get("missing_file_count") or 0)
missing_invoices = int(stats.get("missing_invoice_count") or 0)
summary = {
"profile_code": profile_code,
"period": period_month,
"subject_count": int(stats.get("subject_count") or 0),
"missing_file_count": missing_files,
"missing_invoice_count": missing_invoices,
"run_no": schedule_run.run_no,
}
recipient_ids = [int(u.id) for u in _recipient_users(task)]
if not enabled:
persist_notification(
run_id=engine_run_id,
excel_filename=excel_filename,
recipient_user_ids=recipient_ids,
send_status="skipped_disabled",
skip_reason="notify_missing_enabled=false",
summary=summary,
sent_at=None,
)
db.session.commit()
return "skipped_disabled"
if missing_files <= 0:
persist_notification(
run_id=engine_run_id,
excel_filename=excel_filename,
recipient_user_ids=recipient_ids,
send_status="skipped_no_missing",
skip_reason="本批无缺件",
summary=summary,
sent_at=None,
)
db.session.commit()
return "skipped_no_missing"
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
return 0
persist_notification(
run_id=engine_run_id,
excel_filename=excel_filename,
recipient_user_ids=recipient_ids,
send_status="skipped_disabled",
skip_reason="WECOM_NOTIFY_ENABLED=false",
summary=summary,
sent_at=None,
)
db.session.commit()
return "skipped_disabled"
users = _recipient_users(task)
if not users:
persist_notification(
run_id=engine_run_id,
excel_filename=excel_filename,
recipient_user_ids=[],
send_status="skipped_no_recipients",
skip_reason="未配置企业微信接收人",
summary=summary,
sent_at=None,
)
db.session.commit()
return "skipped_no_recipients"
from app.models.voucher_check import VoucherCheckInvoiceState
from app.services.wecom_notify import (
_build_jump_url,
_create_audit,
send_wecom_textcard_message,
)
today = _today_shanghai()
invoice_nos = [str(i["invoice_no"]).strip() for i in missing_items]
states = (
db.session.query(VoucherCheckInvoiceState)
.filter(
VoucherCheckInvoiceState.scope_code == scope_code,
VoucherCheckInvoiceState.period_month == period_month,
VoucherCheckInvoiceState.invoice_no.in_(invoice_nos),
)
.all()
type_stats = stats.get("by_file_type") or {}
top_missing = sorted(
(
(item.get("rule_name") or key, int(item.get("missing_file_count") or 0))
for key, item in type_stats.items()
if isinstance(item, dict)
),
key=lambda pair: pair[1],
reverse=True,
)
state_map = {s.invoice_no: s for s in states}
to_notify: list[dict[str, Any]] = []
for item in missing_items:
inv = str(item["invoice_no"]).strip()
state = state_map.get(inv)
if same_day_dedup and state and state.last_missing_notified_on == today:
continue
to_notify.append(item)
if not to_notify:
return 0
users = _recipient_users(task)
if not users:
current_app.logger.warning(
"[voucher-check] missing notify skipped: no wecom recipients run_id=%s",
run.id,
)
return 0
sample = "、".join(i["invoice_no"] for i in to_notify[:8])
if len(to_notify) > 8:
sample += "…"
period = period_month.strftime("%Y-%m")
title = f"立账凭证缺资料: {task.name}"
top_missing = [f"{name}{count}" for name, count in top_missing if count > 0][:4]
title = f"立账凭证缺件汇总: {task.name}"
description = (
f"批次 {run.run_no}\n"
f"检核月份 {period}\n"
f"缺资料 {len(to_notify)} 张\n"
f"示例:{sample}\n"
f"完整清单请查看工作台检核记录或 Excel。"
f"业务方 {profile_code}\n"
f"资料所属期间 {period_month}\n"
f"批次 {schedule_run.run_no}\n"
f"主体 {int(stats.get('subject_count') or 0)} 张\n"
f"缺件文件 {missing_files} / 缺件 invoice {missing_invoices}\n"
f"主要缺失:{'、'.join(top_missing) or '—'}\n"
f"明细以工作台 Excel 为准。"
)
ok_any = False
for user in users:
@@ -116,7 +146,7 @@ def send_missing_notifications(
jump_url = _build_jump_url(
"/workspace/accounting-voucher-check",
trace_id,
{"task_id": task.id, "run_id": run.id},
{"task_id": task.id, "run_id": schedule_run.id},
)
try:
audit = _create_audit("voucher_check_missing", user, title, description, trace_id)
@@ -130,20 +160,22 @@ def send_missing_notifications(
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
except Exception as exc:
current_app.logger.warning(
"[voucher-check] missing notify failed user=%s err=%s",
"[voucher-check] batch notify failed user=%s err=%s",
user.id,
exc,
)
if ok_any:
mark_missing_notified(
scope_code=scope_code,
period_month=period_month,
invoice_nos=[str(i["invoice_no"]).strip() for i in to_notify],
notified_on=today,
)
db.session.commit()
return len(to_notify)
return 0
status = "sent" if ok_any else "failed"
persist_notification(
run_id=engine_run_id,
excel_filename=excel_filename,
recipient_user_ids=recipient_ids,
send_status=status,
skip_reason=None if ok_any else "企业微信发送失败",
summary=summary,
sent_at=datetime.now(_TZ).replace(tzinfo=None) if ok_any else None,
)
db.session.commit()
return status
def send_failure_alert(
@@ -155,7 +187,7 @@ def send_failure_alert(
error_message: str,
enabled: bool,
) -> None:
"""批次级失败告警(共享盘/Oracle/业务配置异常)。"""
"""批次级技术失败告警(ERP/DMS/配置异常),不计入缺件通知。"""
if not enabled:
return
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
@@ -178,7 +210,7 @@ def send_failure_alert(
f"错误码:{error_code}\n"
f"摘要:{(error_message or '')[:200]}\n"
f"run_id={run.id}\n"
f"请检查 Oracle 连接与共享盘挂载/健康标记。"
f"请检查 Oracle 与文档库连接。"
)
for user in users:
trace_id = uuid.uuid4().hex
@@ -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()
@@ -0,0 +1,70 @@
"""
backend/app/services/voucher_check/profile_loader.py
用途:加载销售 Profile 并确保数据库中有对应已发布快照。
依赖:profiles 目录、models.VoucherCheckProfile。
逻辑:批次绑定 definition_json 快照;运行中不以表热更新覆盖已开始的批次。
"""
from __future__ import annotations
import copy
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models.voucher_check import VoucherCheckProfile
from app.services.voucher_check.profiles import PROFILE_CATALOG
def load_profile_definition(profile_code: str = "sales") -> dict[str, Any]:
"""
读取内置 Profile 定义的深拷贝。
核心逻辑:未知 profile_code 在批次开始前失败。
"""
code = str(profile_code or "sales").strip() or "sales"
definition = PROFILE_CATALOG.get(code)
if not definition:
raise ValidationError(
f"未知 Profile: {code}",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"profile_code": code},
)
snapshot = copy.deepcopy(definition)
if not snapshot.get("file_rules"):
raise ValidationError("Profile 缺少 file_rules", code="VOUCHER_CHECK.CONFIG_INVALID")
return snapshot
def ensure_published_profile(profile_code: str = "sales") -> VoucherCheckProfile:
"""
幂等写入已发布 Profile 行,供审计;批次仍使用内存快照。
"""
snapshot = load_profile_definition(profile_code)
code = str(snapshot["profile_code"])
version = str(snapshot["profile_version"])
row = (
db.session.query(VoucherCheckProfile)
.filter_by(profile_code=code, version=version)
.one_or_none()
)
now = datetime.utcnow()
if row is None:
row = VoucherCheckProfile(
profile_code=code,
version=version,
definition_json=snapshot,
status="published",
created_at=now,
updated_at=now,
)
db.session.add(row)
db.session.flush()
return row
if row.status != "published" or row.definition_json != snapshot:
row.definition_json = snapshot
row.status = "published"
row.updated_at = now
db.session.flush()
return row
@@ -0,0 +1,15 @@
"""
backend/app/services/voucher_check/profiles/__init__.py
用途:业务方 Profile 包入口。
依赖:sales 销售一期定义。
逻辑:profile_loader 按 profile_code 加载;新增业务方在此登记。
"""
from app.services.voucher_check.profiles.sales import SALES_PROFILE, SALES_PROFILE_CODE, SALES_PROFILE_VERSION
PROFILE_CATALOG = {
SALES_PROFILE_CODE: SALES_PROFILE,
}
__all__ = ["PROFILE_CATALOG", "SALES_PROFILE", "SALES_PROFILE_CODE", "SALES_PROFILE_VERSION"]
@@ -0,0 +1,92 @@
"""
backend/app/services/voucher_check/profiles/sales.py
用途:销售一期 Profile 定义(六类必检文件、类型目录、命名模板)。
依赖:无外部 IO;由 profile_loader 发布快照。
逻辑:周任务扫描 source_type=directory_scan;erp_po_print / oa_sales_release 仅登记,不在周二 runner 调用。
"""
from __future__ import annotations
from typing import Any
SALES_PROFILE_CODE = "sales"
SALES_PROFILE_VERSION = "v1"
SALES_PROFILE: dict[str, Any] = {
"profile_code": SALES_PROFILE_CODE,
"profile_version": SALES_PROFILE_VERSION,
"scope_code": "HXJM",
"subject_adapter": "hxjm_apa",
"dms": {
"year_folder_template": "{yyyy}",
"month_folder_template": "{MM}",
"archive_folder": "所有归档",
},
"file_rules": [
{
"code": "po_order",
"name": "PO订单",
"required": True,
"source_type": "directory_scan",
"acquire_adapter": "erp_po_print",
"type_folder": "PO订单",
"filename_template": "{invoice}-{order_no}.pdf",
},
{
"code": "customs_pack",
"name": "报关资料",
"required": True,
"source_type": "directory_scan",
"acquire_adapter": None,
"type_folder": "报关资料",
"filename_template": "{invoice}.pdf",
},
{
"code": "sales_release",
"name": "销货放行申请单",
"required": True,
"source_type": "directory_scan",
"acquire_adapter": "oa_sales_release",
"type_folder": "销货单",
"filename_template": "{invoice}-{delivery_no}.pdf",
},
{
"code": "tax_invoice",
"name": "发票",
"required": True,
"source_type": "directory_scan",
"acquire_adapter": None,
"type_folder": "发票",
"filename_template": "{invoice}-{tax_invoice_no}.pdf",
},
{
"code": "customs_declaration",
"name": "报关单",
"required": True,
"source_type": "directory_scan",
"acquire_adapter": None,
"type_folder": "报关单",
"filename_template": "{invoice}-{customs_no}.pdf",
},
{
"code": "bill_of_lading",
"name": "提单",
"required": True,
"source_type": "directory_scan",
"acquire_adapter": None,
"type_folder": "提单",
"filename_template": "{invoice}-提单.pdf",
},
],
}
def required_file_rules(definition: dict[str, Any] | None = None) -> list[dict[str, Any]]:
"""
返回必检文件规则列表。
核心逻辑:过滤 required=true,保持 Profile 声明顺序供 Excel 动态列使用。
"""
payload = definition or SALES_PROFILE
rules = payload.get("file_rules") or []
return [rule for rule in rules if isinstance(rule, dict) and rule.get("required", True)]
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/query_service.py
用途:查询批次明细、当月缺资料与单票最新状态。
依赖:models.voucher_check、ScheduleRun。
逻辑:Tool API 与工作台 API 调用;不触发扫描。
用途:查询检核批次列表、批次明细、企微发送记录,以及工作台强制重检入队。
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。
逻辑:只读引擎表;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
"""
from __future__ import annotations
@@ -11,61 +11,21 @@ from __future__ import annotations
from datetime import date, datetime
from typing import Any
from app.core.errors import NotFoundError, ValidationError
from app.models import ScheduleRun
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
from app.services.voucher_check.erp_repository import current_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]:
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 [],
"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,
}
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ScheduleRun, ScheduleTask, User
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckNotification,
VoucherCheckRun,
)
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.erp_repository import previous_period_bounds
def parse_period_month(raw: str | None) -> date:
"""解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取当前自然月。"""
"""解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取上一个自然月。"""
if not raw:
period_month, *_ = current_period_bounds()
period_month, *_ = previous_period_bounds()
return period_month
text = str(raw).strip()
try:
@@ -81,38 +41,191 @@ def parse_period_month(raw: str | None) -> date:
) from exc
def list_missing_states(
def _serialize_engine_run(run: VoucherCheckRun) -> dict[str, Any]:
return {
"id": run.id,
"schedule_run_id": run.schedule_run_id,
"run_no": run.run_no,
"profile_code": run.profile_code,
"period_month": run.period_month.strftime("%Y-%m") if run.period_month else None,
"mode": run.mode,
"status": run.status,
"subject_count": int(run.subject_count or 0),
"archived_file_count": int(run.archived_file_count or 0),
"missing_file_count": int(run.missing_file_count or 0),
"missing_invoice_count": int(run.missing_invoice_count or 0),
"technical_error_count": int(run.technical_error_count or 0),
"staged_file_count": int(run.staged_file_count or 0),
"skipped_file_count": int(run.skipped_file_count or 0),
"started_at": run.started_at.isoformat() if run.started_at else None,
"finished_at": run.finished_at.isoformat() if run.finished_at else None,
}
def _serialize_schedule_fallback_run(run: ScheduleRun) -> dict[str, Any]:
"""
序列化尚未创建引擎批次的立账凭证排程记录。
核心逻辑:配置或外部依赖在引擎建批前失败时,仍须在工作台展示失败原因,
避免用户只能看到空列表而无法判断强制重检是否已执行。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
voucher_summary = summary.get("voucher_check") if isinstance(summary.get("voucher_check"), dict) else {}
period_month, *_ = previous_period_bounds()
return {
"id": run.id,
"schedule_run_id": run.id,
"run_no": run.run_no,
"profile_code": str(voucher_summary.get("profile_code") or "sales"),
"period_month": str(voucher_summary.get("period") or period_month.strftime("%Y-%m")),
"mode": str(voucher_summary.get("mode") or "incremental"),
# 工作台按引擎状态筛选;排程在建批前失败统一映射为技术失败。
"status": "technical_failed",
"subject_count": int(run.total_count or 0),
"archived_file_count": 0,
"missing_file_count": 0,
"missing_invoice_count": 0,
"technical_error_count": 1 if run.status == "failed" else 0,
"staged_file_count": 0,
"skipped_file_count": int(run.skipped_count or 0),
"started_at": run.started_at.isoformat() if run.started_at else None,
"finished_at": run.finished_at.isoformat() if run.finished_at else None,
"error_message": run.error_message,
}
def list_runs(
*,
task_id: int | None = None,
scope_code: str = "HXJM",
period: str | None = None,
limit: int = 200,
profile_code: str | None = None,
status: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""
查询指定月份缺资料票(最新状态表)。
task_id 预留与排程绑定校验,本期仅用于响应回显。
工作台任务列表:按执行时间倒序返回引擎批次及建批前失败的排程记录。
核心逻辑:正常场景读取 VoucherCheckRun 统计快照;若配置校验等错误发生在
create_run 之前,则回退显示对应 ScheduleRun,保证强制重检结果可见。
"""
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",
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
q = VoucherCheckRun.query
if period:
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
if profile_code:
q = q.filter(VoucherCheckRun.profile_code == str(profile_code).strip())
if status:
q = q.filter(VoucherCheckRun.status == str(status).strip())
engine_rows = q.order_by(VoucherCheckRun.id.desc()).all()
engine_schedule_run_ids = {row.schedule_run_id for row in engine_rows if row.schedule_run_id}
fallback_query = (
ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id)
.filter(
ScheduleTask.platform_api_path == "accounting-voucher-check",
ScheduleRun.status == "failed",
)
.order_by(VoucherCheckInvoiceState.invoice_no.asc())
.limit(limit)
)
items = [_serialize_state(s) for s in q.all()]
if status and str(status).strip() != "technical_failed":
fallback_rows: list[ScheduleRun] = []
else:
fallback_rows = fallback_query.order_by(ScheduleRun.id.desc()).all()
fallback_rows = [
row
for row in fallback_rows
if row.id not in engine_schedule_run_ids
and (not period or _serialize_schedule_fallback_run(row)["period_month"] == parse_period_month(period).strftime("%Y-%m"))
]
merged = [_serialize_engine_run(row) for row in engine_rows]
merged.extend(_serialize_schedule_fallback_run(row) for row in fallback_rows)
merged.sort(key=lambda row: row.get("finished_at") or row.get("started_at") or "", reverse=True)
total = len(merged)
rows = merged[(page - 1) * page_size : page * page_size]
return {
"task_id": task_id,
"scope_code": scope_code,
"period": period_month.strftime("%Y-%m"),
"count": len(items),
"items": items,
"page": page,
"page_size": page_size,
"total": total,
"items": rows,
}
def _serialize_file_type_rows(aggregated: dict[str, Any]) -> list[dict[str, Any]]:
"""
将聚合器的 by_file_type 转成工作台「按文件类型」表格行。
核心逻辑:缺失占比 = 该类型缺件 invoice 数 / 本批主体总数。
"""
subject_count = int(aggregated.get("subject_count") or 0)
by_type = aggregated.get("by_file_type") or {}
rows: list[dict[str, Any]] = []
for item in by_type.values():
if not isinstance(item, dict):
continue
missing_invoices = int(item.get("missing_invoice_count") or 0)
ratio = (missing_invoices / subject_count) if subject_count else 0.0
rows.append(
{
"rule_code": item.get("rule_code"),
"rule_name": item.get("rule_name"),
"missing_file_count": int(item.get("missing_file_count") or 0),
"missing_invoice_count": missing_invoices,
"missing_ratio": round(ratio, 4),
}
)
return rows
def _engine_invoice_items(engine_run: VoucherCheckRun) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""
将单文件结果聚合成 invoice 行,并返回同一批的类型汇总。
核心逻辑:按 invoice 汇总缺件材料;类型汇总来自聚合器,不受 invoice 行筛选影响。
"""
rows = (
VoucherCheckFileResult.query.filter_by(run_id=engine_run.id)
.order_by(VoucherCheckFileResult.invoice_no.asc(), VoucherCheckFileResult.id.asc())
.all()
)
payload = [
{
"invoice_no": row.invoice_no,
"rule_code": row.rule_code,
"rule_name": row.rule_name,
"status": row.status,
"invoice_date": None,
}
for row in rows
]
rules = (engine_run.profile_snapshot_json or {}).get("file_rules") or []
aggregated = aggregate_file_results(payload, rules=rules)
items: list[dict[str, Any]] = []
for excel_row in aggregated["excel_rows"]:
missing = [
{"code": code, "name": next((r.get("name") for r in rules if r.get("code") == code), code)}
for code, cell in (excel_row.get("cells") or {}).items()
if cell == "缺件"
]
mapped_status = {
"完整": "complete",
"缺件": "missing",
"待处理": "pending",
}.get(str(excel_row.get("status") or ""), "pending")
items.append(
{
"id": 0,
"invoice_no": excel_row["invoice_no"],
"invoice_date": None,
"result": mapped_status,
"cells": excel_row.get("cells") or {},
"status_label": excel_row.get("status"),
"missing_materials": missing,
"missing_count": len(missing),
"folder_path": None,
"folder_exists": False,
"error_code": None,
"error_message": None,
"checked_at": engine_run.finished_at.isoformat() if engine_run.finished_at else None,
}
)
return items, aggregated
def list_run_items(
*,
run_id: int,
@@ -120,101 +233,202 @@ def list_run_items(
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""分页查询批次明细。"""
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。"""
run = ScheduleRun.query.get(run_id)
if not run:
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
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()
engine_run = (
VoucherCheckRun.query.filter_by(schedule_run_id=run_id)
.order_by(VoucherCheckRun.id.desc())
.first()
)
if engine_run is None:
return {
"run_id": run_id,
"run_no": run.run_no,
"page": page,
"page_size": page_size,
"total": 0,
"items": [],
"subject_count": 0,
"by_file_type": [],
}
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],
"items": sliced,
"subject_count": int(aggregated.get("subject_count") or 0),
"by_file_type": _serialize_file_type_rows(aggregated),
}
def get_invoice_latest(
def list_notifications(
*,
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,
send_status: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""工作台:按月/状态/发票号筛选最新状态。"""
period_month = parse_period_month(period)
"""
分页查询企微缺件汇总发送记录。
核心逻辑:以 voucher_check_notifications 为真相源,关联引擎批次取期间/批次号,并回填接收人姓名。
"""
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,
q = VoucherCheckNotification.query.join(
VoucherCheckRun,
VoucherCheckNotification.run_id == VoucherCheckRun.id,
)
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()}%"))
if period:
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
status_filter = str(send_status or "").strip()
if status_filter:
q = q.filter(VoucherCheckNotification.send_status == status_filter)
total = q.count()
rows = (
q.order_by(VoucherCheckInvoiceState.invoice_no.asc())
q.order_by(VoucherCheckNotification.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
engine_runs = {
run.id: run
for run in VoucherCheckRun.query.filter(
VoucherCheckRun.id.in_([row.run_id for row in rows] or [0])
).all()
}
schedule_ids = [
engine_runs[row.run_id].schedule_run_id
for row in rows
if row.run_id in engine_runs and engine_runs[row.run_id].schedule_run_id
]
schedule_map = {
item.id: item
for item in ScheduleRun.query.filter(ScheduleRun.id.in_(schedule_ids or [0])).all()
}
recipient_ids: set[int] = set()
for row in rows:
for raw in row.recipient_user_ids_json or []:
try:
recipient_ids.add(int(raw))
except (TypeError, ValueError):
continue
users = {
user.id: user
for user in (User.query.filter(User.id.in_(recipient_ids)).all() if recipient_ids else [])
}
items: list[dict[str, Any]] = []
for row in rows:
engine_run = engine_runs.get(row.run_id)
summary = row.summary_json if isinstance(row.summary_json, dict) else {}
names: list[str] = []
for raw in row.recipient_user_ids_json or []:
try:
user = users.get(int(raw))
except (TypeError, ValueError):
user = None
if user:
names.append(str(user.real_name or user.username or user.id))
schedule_run_id = engine_run.schedule_run_id if engine_run else None
schedule_run = schedule_map.get(schedule_run_id) if schedule_run_id else None
items.append(
{
"id": row.id,
"run_id": row.run_id,
"schedule_run_id": schedule_run_id,
"run_no": (
(engine_run.run_no if engine_run else None)
or summary.get("run_no")
or (schedule_run.run_no if schedule_run else None)
),
"period_month": (
engine_run.period_month.strftime("%Y-%m")
if engine_run and engine_run.period_month
else summary.get("period")
),
"subject_count": int(
(engine_run.subject_count if engine_run else None) or summary.get("subject_count") or 0
),
"missing_file_count": int(
(engine_run.missing_file_count if engine_run else None)
or summary.get("missing_file_count")
or 0
),
"missing_invoice_count": int(
(engine_run.missing_invoice_count if engine_run else None)
or summary.get("missing_invoice_count")
or 0
),
"send_status": row.send_status,
"skip_reason": row.skip_reason,
"excel_filename": row.excel_filename or (schedule_run.excel_file_name if schedule_run else None),
"has_excel": bool(schedule_run and schedule_run.excel_file_name),
"recipient_names": names,
"sent_at": row.sent_at.isoformat() if row.sent_at else None,
"created_at": row.created_at.isoformat() if row.created_at else None,
}
)
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": items,
}
def enqueue_force_all_run(*, triggered_by_user_id: int | None) -> dict[str, Any]:
"""
将默认立账凭证排程以 force_all 入队,全量重检上一个自然月。
核心逻辑:复用周批 ScheduleTask;已有 queued/running 时冲突失败,不覆盖进行中的批次。
"""
from app.services.schedule.queue_service import enqueue_manual_schedule_run
from app.services.voucher_check.config import load_engine_config
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule
task = ensure_default_voucher_check_schedule(commit=True)
if task is None:
raise NotFoundError(
"未找到立账凭证检核排程任务",
code="VOUCHER_CHECK.SCHEDULE_NOT_FOUND",
)
# [STEP 1] 入队前完成不依赖外部 IO 的配置预校验,避免 worker 失败后页面空白。
config = load_engine_config(task.job_params if isinstance(task.job_params, dict) else {})
profile = load_profile_definition(config.profile_code)
ensure_published_profile(config.profile_code)
SalesDmsClient.ensure_configured()
run, job_id, created = enqueue_manual_schedule_run(
task.id,
triggered_by_user_id=triggered_by_user_id,
api_request_json={
"trigger_source": "workspace_force_all",
"run_options": {"mode": "force_all"},
},
)
if not created:
raise ConflictError(
"立账凭证检核正在执行或排队中",
code="VOUCHER_CHECK.RUN_IN_PROGRESS",
details={"schedule_run_id": run.id, "run_no": run.run_no},
)
return {
"schedule_task_id": task.id,
"schedule_run_id": run.id,
"run_no": run.run_no,
"job_id": job_id,
"mode": "force_all",
"status": run.status,
}
+232 -174
View File
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/runner.py
用途:立账凭证检核批次编排(预检、增量、扫描、落库、进度摘要、通知)。
依赖:config、erp_repository、share_scanner、persistence、excel_rows、notification。
逻辑:platform Job 与会话触发共用;两阶段执行保证共享盘失败不污染单票状态。
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
逻辑:不调用 erp_po_print / oa_sales_release;命中文件复制到所有归档,同名跳过仍记 archived。
"""
from __future__ import annotations
@@ -16,13 +16,21 @@ from flask import current_app
from app import db
from app.core.errors import AppError, NotFoundError, ServiceUnavailableError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.models.voucher_check import VoucherCheckInvoiceState
from app.services.voucher_check.config import load_voucher_check_config
from app.services.voucher_check.erp_repository import fetch_month_invoices
from app.services.voucher_check.excel_rows import to_excel_detail_row
from app.services.voucher_check.notification import send_failure_alert, send_missing_notifications
from app.services.voucher_check.persistence import persist_batch_results
from app.services.voucher_check.share_scanner import ensure_share_healthy, scan_invoice_folder
from app.services.voucher_check import adapters as _register_adapters # noqa: F401
from app.services.voucher_check.adapters.registry import get_adapter
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.config import load_engine_config
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.engine_persistence import (
create_run,
load_previous_archived_fingerprints,
persist_engine_results,
)
from app.services.voucher_check.erp_repository import previous_period_bounds
from app.services.voucher_check.excel_rows import to_excel_invoice_row
from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
from app.services.voucher_check.profiles.sales import required_file_rules
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -57,17 +65,16 @@ def _update_progress(
if voucher_summary:
summary["voucher_check"] = voucher_summary
summary["file_judgement"] = {
"qualified_count": int(voucher_summary.get("complete_count") or 0),
"unqualified_count": int(voucher_summary.get("missing_count") or 0),
"qualified_count": int(voucher_summary.get("complete_invoice_count") or 0),
"unqualified_count": int(voucher_summary.get("missing_invoice_count") or 0),
"manual_count": 0,
"system_error_count": int(voucher_summary.get("technical_error_count") or 0),
}
summary["progress_metrics"] = [
{"key": "total", "label_key": "chat.voucherCheck.total", "value": int(voucher_summary.get("total_count") or 0)},
{"key": "scan", "label_key": "chat.voucherCheck.scanned", "value": int(voucher_summary.get("scan_count") or 0)},
{"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_count") or 0)},
{"key": "complete", "label_key": "chat.voucherCheck.complete", "value": int(voucher_summary.get("complete_count") or 0)},
{"key": "missing", "label_key": "chat.voucherCheck.missing", "value": int(voucher_summary.get("missing_count") or 0)},
{"key": "total", "label_key": "chat.voucherCheck.total", "value": int(voucher_summary.get("subject_count") or 0)},
{"key": "missing_files", "label_key": "chat.voucherCheck.missingFiles", "value": int(voucher_summary.get("missing_file_count") or 0)},
{"key": "missing", "label_key": "chat.voucherCheck.missingInvoices", "value": int(voucher_summary.get("missing_invoice_count") or 0)},
{"key": "skip", "label_key": "chat.voucherCheck.skipped", "value": int(voucher_summary.get("skipped_file_count") or 0)},
]
summary["domain_notification_managed"] = True
run.response_summary_json = summary
@@ -76,8 +83,9 @@ def _update_progress(
def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证检核批次。
核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。
执行立账凭证周批次。
核心逻辑:上月 invoice × 必检规则扫描文档库类型目录,命中后复制到所有归档(同名跳过)。
启动日志带 path=accounting-voucher-check,便于在全是 schedule 的 worker 输出中识别本任务。
Returns:
ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs)
@@ -87,9 +95,19 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
options = _extract_run_options(run)
mode = options["mode"]
single_invoice = options["invoice_no"]
now = datetime.utcnow()
current_app.logger.info(
"[voucher-check] start name=%s path=accounting-voucher-check run_no=%s mode=%s",
getattr(task, "name", None) or "立账凭证检核",
run.run_no,
mode,
)
try:
config = load_voucher_check_config(task.job_params if isinstance(task.job_params, dict) else {})
config = load_engine_config(task.job_params if isinstance(task.job_params, dict) else {})
profile = load_profile_definition(config.profile_code)
ensure_published_profile(config.profile_code)
SalesDmsClient.ensure_configured()
except AppError as exc:
send_failure_alert(
task=task,
@@ -101,10 +119,15 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
)
raise
# [STEP 1] 拉取 ERP 当月发票清单
_update_progress(run, step="fetch_erp", label="拉取 ERP 当月立账凭证")
rules = required_file_rules(profile)
period_month, _current, _start, _end = previous_period_bounds()
period = period_month.strftime("%Y-%m")
# [STEP 1] 拉取上月销售 invoice 清单
_update_progress(run, step="fetch_erp", label="拉取上月销售 invoice")
try:
period_month, invoices = fetch_month_invoices(config)
subject_adapter = get_adapter(str(profile.get("subject_adapter") or "hxjm_apa"))
subjects = subject_adapter.fetch(period_month=period_month, config=config)
except ServiceUnavailableError as exc:
send_failure_alert(
task=task,
@@ -119,7 +142,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
{
"step": "fetch_erp",
"status": "success",
"detail": {"count": len(invoices), "period": period_month.strftime("%Y-%m")},
"detail": {"count": len(subjects), "period": period},
}
)
@@ -129,169 +152,200 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
"single 模式必须提供 invoice_no",
code="VOUCHER_CHECK.INVOICE_REQUIRED",
)
invoices = [row for row in invoices if row.invoice_no == single_invoice]
if not invoices:
subjects = [row for row in subjects if row.invoice_no == single_invoice]
if not subjects:
raise NotFoundError(
"指定发票不在当前月 ERP 集合",
"指定发票不在上一个月 ERP 集合",
code="VOUCHER_CHECK.INVOICE_NOT_IN_PERIOD",
)
# [STEP 2] 共享盘健康检查(失败则整批失败,不写单票 missing)
_update_progress(run, step="share_health", label="检查共享盘可用性")
try:
root = ensure_share_healthy(config)
except ServiceUnavailableError as exc:
send_failure_alert(
task=task,
run=run,
stage="share_health",
error_code=exc.code,
error_message=exc.message,
enabled=config.notify_failure_enabled,
)
raise
step_logs.append({"step": "share_health", "status": "success", "detail": {"root_ok": True}})
# [STEP 3] 读取历史状态,供增量判定
existing_states = (
db.session.query(VoucherCheckInvoiceState)
.filter_by(scope_code=config.scope_code, period_month=period_month)
.all()
engine_run = create_run(
schedule_run_id=run.id,
run_no=str(run.run_no or f"VC-{run.id}"),
profile_code=str(profile["profile_code"]),
profile_version=str(profile["profile_version"]),
profile_snapshot=profile,
period_month=period_month,
mode=mode,
started_at=now,
)
state_map = {s.invoice_no: s for s in existing_states}
db.session.commit()
results: list[dict[str, Any]] = []
complete_count = 0
missing_count = 0
skipped_count = 0
technical_error_count = 0
now = datetime.utcnow()
scan_adapter = get_adapter("directory_scan")
archive_adapter = get_adapter("dms_archive")
force = mode in {"force_all", "single"}
previous_fp = {} if force else load_previous_archived_fingerprints(
profile_code=str(profile["profile_code"]),
period_month=period_month,
exclude_run_id=engine_run.id,
)
# [STEP 4] 逐票扫描 / 指纹比对
# [STEP 2] 扫描六类类型目录(不调用 PO/OA 打印 Adapter)
_update_progress(
run,
step="scan_share",
label="扫描共享盘文件名",
step="scan_dms",
label="扫描销售开票附件类型目录",
processed=0,
voucher_summary={
"scope_code": config.scope_code,
"period": period_month.strftime("%Y-%m"),
"period": period,
"mode": mode,
"total_count": len(invoices),
"complete_count": 0,
"missing_count": 0,
"scan_count": 0,
"skipped_count": 0,
"subject_count": len(subjects),
"missing_file_count": 0,
"missing_invoice_count": 0,
"skipped_file_count": 0,
"technical_error_count": 0,
"complete_invoice_count": 0,
},
)
for idx, row in enumerate(invoices, start=1):
hist = state_map.get(row.invoice_no)
scan = scan_invoice_folder(
config,
root=root,
period_month=period_month,
invoice_no=row.invoice_no,
)
# 增量:齐全且指纹未变 → skipped(仍访问共享盘取指纹)
can_skip = (
not force
and hist is not None
and hist.status == "complete"
and hist.material_fingerprint
and scan.result == "complete"
and scan.material_fingerprint == hist.material_fingerprint
)
if can_skip:
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": "skipped",
"folder_path": scan.folder_path,
"folder_exists": scan.folder_exists,
"material_fingerprint": scan.material_fingerprint,
"matched_files": scan.matched_files,
"missing_materials": [],
"checked_at": None,
}
skipped_count += 1
elif scan.result == "technical_error":
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": "technical_error",
"folder_path": scan.folder_path,
"folder_exists": False,
"material_fingerprint": None,
"matched_files": {},
"missing_materials": [],
"error_code": scan.error_code,
"error_message": scan.error_message,
file_results: list[dict[str, Any]] = []
yyyy = f"{period_month.year:04d}"
mm = f"{period_month.month:02d}"
for idx, subject in enumerate(subjects, start=1):
for rule in rules:
rule_code = str(rule["code"])
expected = str(rule.get("filename_template") or "").replace("{invoice}", subject.invoice_no)
prev_key = (subject.invoice_no, rule_code)
outcome = scan_adapter.scan(
period_month=period_month,
invoice_no=subject.invoice_no,
rule=rule,
)
result: dict[str, Any] = {
"invoice_no": subject.invoice_no,
"invoice_date": subject.invoice_date,
"rule_code": rule_code,
"rule_name": rule.get("name") or rule_code,
"source_type": "directory_scan",
"expected_name": expected,
"source_folder_id": outcome.folder_id,
"source_path": outcome.folder_path,
"checked_at": now,
}
technical_error_count += 1
else:
item = {
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"result": scan.result,
"folder_path": scan.folder_path,
"folder_exists": scan.folder_exists,
"material_fingerprint": scan.material_fingerprint,
"matched_files": scan.matched_files,
"missing_materials": scan.missing_materials,
"checked_at": now,
}
if scan.result == "complete":
complete_count += 1
if (
not force
and outcome.status == "matched"
and outcome.file
and outcome.file.fingerprint
and previous_fp.get(prev_key) == outcome.file.fingerprint
):
result.update(
{
"status": "skipped",
"matched_name": outcome.file.filename,
"source_item_id": outcome.file.item_id,
"source_fingerprint": outcome.file.fingerprint,
}
)
elif outcome.status == "technical_error":
result.update(
{
"status": "technical_error",
"error_code": outcome.error_code,
"error_message": outcome.error_message,
}
)
elif outcome.status != "matched" or outcome.file is None:
result.update(
{
"status": "missing",
"missing_reason": "类型目录未找到匹配文件",
}
)
else:
missing_count += 1
results.append(item)
scanned = outcome.file
result.update(
{
"matched_name": scanned.filename,
"source_item_id": scanned.item_id,
"source_fingerprint": scanned.fingerprint,
}
)
archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{subject.invoice_no}/{scanned.filename}"
result["archive_path"] = archive_path
if getattr(archive_adapter, "wired", False):
try:
archived = archive_adapter.archive(
period_month=period_month,
invoice_no=subject.invoice_no,
file=scanned,
rule=rule,
)
extra = archived.extra or {}
result.update(
{
"status": "archived",
"archive_item_id": archived.item_id,
"archive_folder_id": archived.folder_id,
"archive_skipped_same_name": bool(extra.get("skipped_same_name")),
}
)
except ServiceUnavailableError as exc:
result.update(
{
"status": "technical_error",
"error_code": exc.code,
"error_message": exc.message,
}
)
else:
result["status"] = "staged"
file_results.append(result)
if idx % 20 == 0 or idx == len(invoices):
scan_count = complete_count + missing_count + technical_error_count
if idx % 20 == 0 or idx == len(subjects):
preview = aggregate_file_results(file_results, rules=rules)
_update_progress(
run,
step="scan_share",
label="扫描共享盘文件名",
step="scan_dms",
label="扫描销售开票附件类型目录",
processed=idx,
voucher_summary={
"scope_code": config.scope_code,
"period": period_month.strftime("%Y-%m"),
"period": period,
"mode": mode,
"total_count": len(invoices),
"complete_count": complete_count,
"missing_count": missing_count,
"scan_count": scan_count,
"skipped_count": skipped_count,
"technical_error_count": technical_error_count,
"subject_count": len(subjects),
"missing_file_count": preview["missing_file_count"],
"missing_invoice_count": preview["missing_invoice_count"],
"skipped_file_count": preview["skipped_file_count"],
"technical_error_count": preview["technical_error_count"],
"complete_invoice_count": sum(
1 for row in preview["excel_rows"] if row["status"] == "完整"
),
},
)
stats = aggregate_file_results(file_results, rules=rules)
step_logs.append(
{
"step": "scan_share",
"step": "scan_dms",
"status": "success",
"detail": {
"complete": complete_count,
"missing": missing_count,
"skipped": skipped_count,
"technical_error": technical_error_count,
"missing_files": stats["missing_file_count"],
"missing_invoices": stats["missing_invoice_count"],
"staged": stats["staged_file_count"],
"skipped": stats["skipped_file_count"],
"technical_error": stats["technical_error_count"],
},
}
)
# [STEP 5] 事务落库
# [STEP 3] 落库单文件结果
_update_progress(run, step="persist", label="写入检核记录")
try:
persist_batch_results(
schedule_run_id=run.id,
scope_code=config.scope_code,
period_month=period_month,
items=results,
persist_engine_results(
run=engine_run,
subjects=[
{
"invoice_no": row.invoice_no,
"invoice_date": row.invoice_date,
"source_fingerprint": row.source_fingerprint,
"attributes": row.attributes,
}
for row in subjects
],
file_results=file_results,
stats=stats,
now=now,
)
db.session.commit()
@@ -308,58 +362,62 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
)
raise
# [STEP 6] 缺资料通知
missing_items = [r for r in results if r["result"] == "missing"]
notified = send_missing_notifications(
excel_filename = f"voucher_check_{profile['profile_code']}_{period}_{run.run_no}.xlsx"
executed_at = now.strftime("%Y-%m-%d %H:%M:%S")
details = [
to_excel_invoice_row(item, period=period, executed_at=executed_at)
for item in stats["excel_rows"]
]
# [STEP 4] 每批一条企微汇总
notify_status = send_batch_missing_summary(
task=task,
run=run,
scope_code=config.scope_code,
period_month=period_month,
missing_items=missing_items,
same_day_dedup=config.same_day_dedup_enabled,
schedule_run=run,
engine_run_id=engine_run.id,
profile_code=str(profile["profile_code"]),
period_month=period,
stats=stats,
excel_filename=excel_filename,
enabled=config.notify_missing_enabled,
)
step_logs.append(
{
"step": "notify",
"status": "success",
"detail": {"missing": len(missing_items), "notified": notified},
"detail": {"send_status": notify_status, "missing_files": stats["missing_file_count"]},
}
)
period = period_month.strftime("%Y-%m")
scan_count = complete_count + missing_count + technical_error_count
complete_invoices = sum(1 for row in stats["excel_rows"] if row["status"] == "完整")
voucher_summary = {
"scope_code": config.scope_code,
"period": period,
"mode": mode,
"total_count": len(invoices),
"complete_count": complete_count,
"missing_count": missing_count,
"scan_count": scan_count,
"skipped_count": skipped_count,
"technical_error_count": technical_error_count,
"missing_notification_count": notified,
"engine_run_id": engine_run.id,
"subject_count": stats["subject_count"],
"missing_file_count": stats["missing_file_count"],
"missing_invoice_count": stats["missing_invoice_count"],
"skipped_file_count": stats["skipped_file_count"],
"technical_error_count": stats["technical_error_count"],
"staged_file_count": stats["staged_file_count"],
"complete_invoice_count": complete_invoices,
"notify_status": notify_status,
}
_update_progress(
run,
step="done",
label="检核完成",
processed=len(invoices),
processed=len(subjects),
voucher_summary=voucher_summary,
)
details = [
to_excel_detail_row(item, period=period, scope_code=config.scope_code) for item in results
]
# success_count = complete + missing(业务成功);failed_count 仅技术异常
success_count = complete_count + missing_count
total_count = len(invoices)
success_count = stats["subject_count"]
failed_count = 1 if stats["batch_status"] == "technical_failed" and stats["missing_file_count"] == 0 else 0
return (
total_count,
stats["subject_count"],
success_count,
technical_error_count,
skipped_count,
failed_count,
stats["skipped_file_count"],
details,
errors,
step_logs,
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/schedule_seed.py
用途:确保 accounting-voucher-check 默认日批 ScheduleTask 存在(06:00 Asia/Shanghai)。
用途:确保 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
@@ -24,20 +25,40 @@ _LOGGER = logging.getLogger(__name__)
DEFAULT_VOUCHER_CHECK_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK"
DEFAULT_VOUCHER_CHECK_PLATFORM_PATH = "accounting-voucher-check"
DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * *"
DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(日批)"
DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * 2"
DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(周批)"
_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,29 @@ 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 == "立账凭证检核(日批)":
existing.name = DEFAULT_VOUCHER_CHECK_NAME
existing.next_run_at = compute_next_run_at(
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()
return existing
owner = (
@@ -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,30 @@
"""合并立账凭证引擎表与 dev 集成连接器两条 Alembic 头。
Revision ID: na0b1c2d3e4f5
Revises: n9a0b1c2d3e4, vc1a2b3c4d5e
Create Date: 2026-09-07 14:25:00.000000
用途:将 ``invoice-check`` 的 ``vc1a2b3c4d5e``(立账凭证引擎表)与
``dev`` 的 ``n9a0b1c2d3e4``(集成连接器 / 合同付款 head 合并)收成单一升级路径,
避免 ``flask db upgrade`` / pre-commit 因 Multiple head revisions 失败。
依赖:``n9a0b1c2d3e4``、``vc1a2b3c4d5e``。
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
"""
from alembic import op # noqa: F401 - Alembic migration module contract
revision = "na0b1c2d3e4f5"
down_revision = ("n9a0b1c2d3e4", "vc1a2b3c4d5e")
branch_labels = None
depends_on = None
def upgrade() -> None:
"""合并立账凭证引擎 head 与 dev 集成连接器 head,不执行数据库结构变更。"""
pass
def downgrade() -> None:
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
pass
@@ -0,0 +1,237 @@
"""
backend/migrations/versions/vc1a2b3c4d5e_add_voucher_check_engine_tables.py
用途:新增立账凭证检核引擎表(Profile/批次/主体/单文件结果/通知),并把默认排程改为每周二。
依赖:Alembic revision n8f9a0b1c2d3;旧 voucher_check_invoice_states / run_items 保留只读。
逻辑:建五张新表;仅当默认任务仍是日批 cron 时改为周二 06:00。
Revision ID: vc1a2b3c4d5e
Revises: n8f9a0b1c2d3
Create Date: 2026-09-04 10:30:00.000000
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import sqlalchemy as sa
from alembic import op
revision = "vc1a2b3c4d5e"
down_revision = "n8f9a0b1c2d3"
branch_labels = None
depends_on = None
_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK"
_OLD_CRON = "0 6 * * *"
_NEW_CRON = "0 6 * * 2"
_TZ_NAME = "Asia/Shanghai"
def _compute_next_run_at_utc_naive() -> datetime:
try:
from croniter import croniter
from zoneinfo import ZoneInfo
tz = ZoneInfo(_TZ_NAME)
base = datetime.now(tz)
next_local = croniter(_NEW_CRON, base).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)
next_local = now_local.replace(hour=6, minute=0, second=0, microsecond=0)
while next_local <= now_local or next_local.weekday() != 1:
next_local = next_local + timedelta(days=1)
next_local = next_local.replace(hour=6, minute=0, second=0, microsecond=0)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
def upgrade() -> None:
op.create_table(
"voucher_check_profiles",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("profile_code", sa.String(length=32), nullable=False),
sa.Column("version", sa.String(length=32), nullable=False),
sa.Column("definition_json", sa.JSON(), nullable=False),
sa.Column("status", sa.String(length=24), nullable=False, server_default="published"),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint("profile_code", "version", name="uq_voucher_check_profiles_code_version"),
)
op.create_index("ix_voucher_check_profiles_status", "voucher_check_profiles", ["status"])
op.create_table(
"voucher_check_runs",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column(
"schedule_run_id",
sa.BigInteger(),
sa.ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
),
sa.Column("run_no", sa.String(length=64), nullable=False),
sa.Column("profile_code", sa.String(length=32), nullable=False),
sa.Column("profile_version", sa.String(length=32), nullable=False),
sa.Column("profile_snapshot_json", sa.JSON(), nullable=False),
sa.Column("period_month", sa.Date(), nullable=False),
sa.Column("mode", sa.String(length=24), nullable=False, server_default="incremental"),
sa.Column("status", sa.String(length=24), nullable=False, server_default="running"),
sa.Column("subject_count", sa.BigInteger(), nullable=False, server_default="0"),
sa.Column("archived_file_count", sa.BigInteger(), nullable=False, server_default="0"),
sa.Column("skipped_file_count", sa.BigInteger(), nullable=False, server_default="0"),
sa.Column("missing_file_count", sa.BigInteger(), nullable=False, server_default="0"),
sa.Column("missing_invoice_count", sa.BigInteger(), nullable=False, server_default="0"),
sa.Column("technical_error_count", sa.BigInteger(), nullable=False, server_default="0"),
sa.Column("staged_file_count", sa.BigInteger(), nullable=False, server_default="0"),
sa.Column("stats_json", sa.JSON(), nullable=True),
sa.Column("started_at", sa.DateTime(), nullable=True),
sa.Column("finished_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
)
op.create_index("ix_voucher_check_runs_schedule_run_id", "voucher_check_runs", ["schedule_run_id"])
op.create_index(
"ix_voucher_check_runs_period_profile",
"voucher_check_runs",
["period_month", "profile_code"],
)
op.create_index("ix_voucher_check_runs_status", "voucher_check_runs", ["status"])
op.create_index("ix_voucher_check_runs_finished_at", "voucher_check_runs", ["finished_at"])
op.create_table(
"voucher_check_subjects",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column(
"run_id",
sa.BigInteger(),
sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("invoice_no", sa.String(length=128), nullable=False),
sa.Column("invoice_date", sa.Date(), nullable=True),
sa.Column("source_fingerprint", sa.String(length=64), nullable=True),
sa.Column("attributes_json", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint("run_id", "invoice_no", name="uq_voucher_check_subjects_run_invoice"),
)
op.create_index("ix_voucher_check_subjects_run_id", "voucher_check_subjects", ["run_id"])
op.create_index("ix_voucher_check_subjects_invoice_no", "voucher_check_subjects", ["invoice_no"])
op.create_table(
"voucher_check_file_results",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column(
"run_id",
sa.BigInteger(),
sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column(
"subject_id",
sa.BigInteger(),
sa.ForeignKey("voucher_check_subjects.id", ondelete="SET NULL"),
nullable=True,
),
sa.Column("invoice_no", sa.String(length=128), nullable=False),
sa.Column("rule_code", sa.String(length=64), nullable=False),
sa.Column("rule_name", sa.String(length=128), nullable=False),
sa.Column("source_type", sa.String(length=32), nullable=False),
sa.Column("expected_name", sa.String(length=512), nullable=True),
sa.Column("matched_name", sa.String(length=512), nullable=True),
sa.Column("source_folder_id", sa.String(length=64), nullable=True),
sa.Column("source_item_id", sa.String(length=64), nullable=True),
sa.Column("archive_folder_id", sa.String(length=64), nullable=True),
sa.Column("archive_item_id", sa.String(length=64), nullable=True),
sa.Column("source_path", sa.String(length=1024), nullable=True),
sa.Column("archive_path", sa.String(length=1024), nullable=True),
sa.Column("status", sa.String(length=24), nullable=False),
sa.Column("missing_reason", sa.String(length=255), nullable=True),
sa.Column("error_code", sa.String(length=64), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("source_fingerprint", sa.String(length=64), nullable=True),
sa.Column("checked_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint(
"run_id",
"invoice_no",
"rule_code",
name="uq_voucher_check_file_results_run_invoice_rule",
),
)
op.create_index("ix_voucher_check_file_results_run_id", "voucher_check_file_results", ["run_id"])
op.create_index(
"ix_voucher_check_file_results_status",
"voucher_check_file_results",
["run_id", "status"],
)
op.create_index("ix_voucher_check_file_results_invoice", "voucher_check_file_results", ["invoice_no"])
op.create_table(
"voucher_check_notifications",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column(
"run_id",
sa.BigInteger(),
sa.ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("excel_filename", sa.String(length=255), nullable=True),
sa.Column("recipient_user_ids_json", sa.JSON(), nullable=True),
sa.Column("send_status", sa.String(length=32), nullable=False),
sa.Column("skip_reason", sa.String(length=255), nullable=True),
sa.Column("summary_json", sa.JSON(), nullable=True),
sa.Column("sent_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint("run_id", name="uq_voucher_check_notifications_run_id"),
)
op.create_index(
"ix_voucher_check_notifications_status",
"voucher_check_notifications",
["send_status"],
)
conn = op.get_bind()
conn.execute(
sa.text(
"""
UPDATE schedule_tasks
SET cron_expr = :new_cron,
name = CASE
WHEN name = '立账凭证检核(日批)' THEN '立账凭证检核(周批)'
ELSE name
END,
next_run_at = :next_run,
updated_at = :now
WHERE schedule_no = :sno
AND cron_expr = :old_cron
"""
),
{
"new_cron": _NEW_CRON,
"next_run": _compute_next_run_at_utc_naive(),
"now": datetime.utcnow(),
"sno": _SCHEDULE_NO,
"old_cron": _OLD_CRON,
},
)
def downgrade() -> None:
op.drop_index("ix_voucher_check_notifications_status", table_name="voucher_check_notifications")
op.drop_table("voucher_check_notifications")
op.drop_index("ix_voucher_check_file_results_invoice", table_name="voucher_check_file_results")
op.drop_index("ix_voucher_check_file_results_status", table_name="voucher_check_file_results")
op.drop_index("ix_voucher_check_file_results_run_id", table_name="voucher_check_file_results")
op.drop_table("voucher_check_file_results")
op.drop_index("ix_voucher_check_subjects_invoice_no", table_name="voucher_check_subjects")
op.drop_index("ix_voucher_check_subjects_run_id", table_name="voucher_check_subjects")
op.drop_table("voucher_check_subjects")
op.drop_index("ix_voucher_check_runs_finished_at", table_name="voucher_check_runs")
op.drop_index("ix_voucher_check_runs_status", table_name="voucher_check_runs")
op.drop_index("ix_voucher_check_runs_period_profile", table_name="voucher_check_runs")
op.drop_index("ix_voucher_check_runs_schedule_run_id", table_name="voucher_check_runs")
op.drop_table("voucher_check_runs")
op.drop_index("ix_voucher_check_profiles_status", table_name="voucher_check_profiles")
op.drop_table("voucher_check_profiles")
@@ -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()
+64 -5
View File
@@ -1,7 +1,7 @@
"""
backend/tests/jobs/test_schedule_queue.py
用途:验证排程迁出 Web 后的手动入队、Cron 扫描与 Job handler 状态闭环。
用途:验证排程迁出 Web 后的手动入队、Cron 扫描、Job 业务身份字段与 handler 状态闭环。
依赖:通用 app fixture、models.Job/ScheduleRun/ScheduleTask、schedule.queue_service。
逻辑:只替换真正的排程执行器,不启动后台线程,断言 API/worker 之间的数据契约。
"""
@@ -16,8 +16,16 @@ from app.models import Job, ScheduleRun, ScheduleTask, User
from app.services.schedule.queue_service import enqueue_due_schedule_runs, enqueue_manual_schedule_run
def _create_task(*, due: bool = False) -> ScheduleTask:
"""创建测试用户与排程;due=True 时令 next_run_at 已到期。"""
def _create_task(*, due: bool = False, platform_api_path: str | None = None, name: str = "schedule queue test") -> ScheduleTask:
"""
创建测试用户与排程。
核心逻辑:due=True 时令 next_run_at 已到期;可指定 platform_api_path 覆盖默认 data_pipeline。
Args:
due: 是否立即到期,供 Cron 扫描测试。
platform_api_path: 平台任务 key;有值时 schedule_type 改为 platform_job。
name: 排程显示名,写入 jobs.message。
"""
suffix = str(datetime.utcnow().timestamp()).replace(".", "-")
user = User(
username=f"schedule-owner-{suffix}",
@@ -30,8 +38,9 @@ def _create_task(*, due: bool = False) -> ScheduleTask:
db.session.flush()
task = ScheduleTask(
schedule_no=f"SCH-TEST-{datetime.utcnow().timestamp()}",
name="schedule queue test",
schedule_type="data_pipeline",
name=name,
schedule_type="platform_job" if platform_api_path else "data_pipeline",
platform_api_path=platform_api_path,
owner_user_id=user.id,
cron_expr="0 3 * * *",
schedule_timezone="Asia/Shanghai",
@@ -57,6 +66,8 @@ def test_manual_schedule_run_creates_queued_job(app):
assert job.domain == "schedule"
assert job.job_type == JobType.SCHEDULE_RUN.value
assert job.payload_json["schedule_run_id"] == run.id
assert job.business_ref == f"schedule_run:{run.id}:untagged"
assert job.message == "schedule queue test等待后台执行"
def test_due_schedule_scan_is_idempotent(app):
@@ -101,3 +112,51 @@ def test_schedule_handler_finishes_generic_job(app, monkeypatch):
db.session.expire_all()
assert db.session.get(ScheduleRun, run.id).status == "success"
assert db.session.get(Job, job_id).status == "success"
def test_schedule_job_identity_uses_platform_api_path(app):
"""关键断言:立账凭证等平台任务在 jobs 表用 business_ref/payload 区分,不改 job_type。"""
from app.services.schedule.queue_service import query_jobs_for_schedule_run
from app.services.schedule.scheduler_service import request_cancel_run
with app.app_context():
task = _create_task(platform_api_path="accounting-voucher-check", name="立账凭证检核")
run, job_id, created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id)
job = db.session.get(Job, job_id)
assert created is True
assert job.domain == "schedule"
assert job.job_type == JobType.SCHEDULE_RUN.value
assert job.business_ref == f"schedule_run:{run.id}:accounting-voucher-check"
assert job.payload_json["platform_api_path"] == "accounting-voucher-check"
assert job.payload_json["task_name"] == "立账凭证检核"
assert job.payload_json["schedule_no"] == task.schedule_no
assert job.message == "立账凭证检核等待后台执行"
assert query_jobs_for_schedule_run(run.id).filter(Job.status == "queued").one().id == job_id
request_cancel_run(run.id)
db.session.commit()
db.session.expire_all()
cancelled = db.session.get(Job, job_id)
assert cancelled.status == "cancelled"
def test_query_jobs_for_schedule_run_matches_legacy_business_ref(app):
"""关键断言:取消/回收仍能命中升级前 `schedule_run:{id}` 旧格式。"""
from app.services.schedule.queue_service import query_jobs_for_schedule_run
from app.services.schedule.scheduler_service import request_cancel_run
with app.app_context():
task = _create_task()
run, job_id, _created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id)
job = db.session.get(Job, job_id)
job.business_ref = f"schedule_run:{run.id}"
db.session.commit()
found = query_jobs_for_schedule_run(run.id).one()
assert found.id == job_id
request_cancel_run(run.id)
db.session.commit()
db.session.expire_all()
assert db.session.get(Job, job_id).status == "cancelled"
+60
View File
@@ -0,0 +1,60 @@
"""
backend/tests/test_faq_cache.py
用途:FAQ 缓存在线匹配规则。
逻辑:验证 cache_enabled 决定是否直答,is_enabled 只影响首页展示、不阻断命中。
"""
from app import db
from app.models import Agent, QuickQuestion
from app.services.faq_cache import FaqCacheService
def _create_agent() -> Agent:
"""写入测试 Agent,供 FAQ 条目关联。"""
agent = Agent(name='faq-cache-agent', type='api', dify_app_id='app-faq-cache', dify_api_key='key-faq-cache')
db.session.add(agent)
db.session.commit()
return agent
def _create_faq(agent_id: int, **overrides) -> QuickQuestion:
"""写入一条全局 FAQ,默认启用缓存且有标准答案。"""
payload = {
'user_id': None,
'agent_id': agent_id,
'title': '公司的企业文化',
'question': '公司的企业文化',
'answer': '客户满意、员工乐意、经营得意',
'aliases': ['企业文化'],
'cache_enabled': True,
'is_enabled': True,
}
payload.update(overrides)
faq = QuickQuestion(**payload)
db.session.add(faq)
db.session.commit()
return faq
def test_try_match_hits_when_cache_on_even_if_not_shown_on_home(app):
"""关闭前台展示时,启用缓存的问句仍应直答,不走 Dify。"""
with app.app_context():
agent = _create_agent()
_create_faq(agent.id, is_enabled=False)
hit = FaqCacheService.try_match('公司的企业文化', agent.id)
alias_hit = FaqCacheService.try_match('企业文化', agent.id)
assert hit is not None
assert hit.answer == '客户满意、员工乐意、经营得意'
assert alias_hit is not None
assert alias_hit.id == hit.id
def test_try_match_skips_when_cache_disabled(app):
"""仅在首页展示、未启用缓存时,提问仍应回退 Dify。"""
with app.app_context():
agent = _create_agent()
_create_faq(agent.id, cache_enabled=False, is_enabled=True)
assert FaqCacheService.try_match('公司的企业文化', agent.id) is None
@@ -0,0 +1,43 @@
"""
backend/tests/test_schedule_run_executor_error.py
用途:排程 handler 抛错时 ScheduleRun 必须记 failed,不能因 failed_count=0 标成 success。
依赖:scheduler_service.run_task_now、ScheduleTask/ScheduleRun。
逻辑:monkeypatch executor 抛出配置错误,断言 status=failed 且 error_message 保留原文。
"""
from __future__ import annotations
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.scheduler_service import run_task_now
def test_run_task_now_marks_executor_exception_as_failed(app, monkeypatch):
"""handler 抛 RuntimeError 时,批次状态应为 failed 且 failed_count=1。"""
def _boom(_task: ScheduleTask, _run: ScheduleRun):
raise RuntimeError("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME")
monkeypatch.setattr(
"app.services.schedule.scheduler_service.resolve_schedule_executor",
lambda _task: _boom,
)
with app.app_context():
user = User(username="sched-exec-err", email="sched-exec-err@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-TEST-EXECUTOR-ERROR",
name="executor error fixture",
schedule_type="platform_job",
platform_api_path="accounting-voucher-check",
owner_user_id=user.id,
cron_expr="0 6 * * 2",
enabled=True,
)
db.session.add(task)
db.session.commit()
result = run_task_now(task, trigger_type="manual", triggered_by_user_id=user.id)
assert result.status == "failed"
assert result.failed_count == 1
assert "VOUCHER_CHECK_ERP" in (result.error_message or "")
@@ -0,0 +1,186 @@
"""
backend/tests/voucher_check/test_dms_archive.py
用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。
依赖:pytest;不连文档库。
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy;断言同名不覆盖、缺月目录为技术失败。
"""
from __future__ import annotations
from datetime import date
import pytest
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.base import ScannedFile
from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter
from app.services.voucher_check.dms_client import (
SalesDmsClient,
_extract_item_id,
_is_name_conflict,
)
def test_extract_item_id_from_nested_data():
assert _extract_item_id({"Data": {"ID": "folder-1"}}) == "folder-1"
assert _extract_item_id({"Data": "folder-2"}) == "folder-2"
assert _extract_item_id({"Data": {"Item": {"ID": "folder-3"}}}) == "folder-3"
assert _extract_item_id({"Data": {}}) == ""
def test_name_conflict_detects_same_name_messages():
assert _is_name_conflict("文件夹已存在")
assert _is_name_conflict("同名文件")
assert _is_name_conflict("The name already exists")
assert _is_name_conflict("网络超时") is False
def test_ensure_folder_returns_existing_without_save(monkeypatch):
monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: "folder-1")
calls: list[object] = []
monkeypatch.setattr(SalesDmsClient, "_post_json", lambda *_args, **_kwargs: calls.append(1) or {})
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "folder-1"
assert calls == []
def test_ensure_folder_creates_when_missing(monkeypatch):
monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: None)
monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1")
monkeypatch.setattr(
SalesDmsClient,
"_post_json",
lambda path, payload, **_kwargs: {"Code": 0, "Data": {"ID": "new-folder"}},
)
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder"
def test_copy_skips_when_dest_has_same_name(monkeypatch):
monkeypatch.setattr(
SalesDmsClient,
"find_child_file",
lambda **_kwargs: {"ID": "dest-1", "LeafName": "INV001.pdf"},
)
calls: list[object] = []
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs))
row, skipped = SalesDmsClient.copy_file_skip_same_name(
source_item_id="src-1",
dest_folder_id="inv-folder",
leaf_name="INV001.pdf",
)
assert skipped is True
assert row["ID"] == "dest-1"
assert calls == []
def test_copy_when_dest_has_no_same_name(monkeypatch):
listing = {"n": 0}
def find_child_file(**_kwargs):
listing["n"] += 1
if listing["n"] == 1:
return None
return {"ID": "dest-2", "LeafName": "INV001.pdf"}
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
copied: list[dict] = []
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0})
row, skipped = SalesDmsClient.copy_file_skip_same_name(
source_item_id="src-1",
dest_folder_id="inv-folder",
leaf_name="INV001.pdf",
)
assert skipped is False
assert row["ID"] == "dest-2"
assert copied == [{"item_ids": ["src-1"], "dest_folder_id": "inv-folder"}]
def test_copy_treats_api_same_name_error_as_skip(monkeypatch):
listing = {"n": 0}
def find_child_file(**_kwargs):
listing["n"] += 1
if listing["n"] == 1:
return None
return {"ID": "dest-3", "LeafName": "INV001.pdf"}
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
monkeypatch.setattr(
SalesDmsClient,
"copy_items",
lambda **_kwargs: (_ for _ in ()).throw(
ServiceUnavailableError("目标已存在同名文件", code="VOUCHER_CHECK.ARCHIVE_FAILED")
),
)
row, skipped = SalesDmsClient.copy_file_skip_same_name(
source_item_id="src-1",
dest_folder_id="inv-folder",
leaf_name="INV001.pdf",
)
assert skipped is True
assert row["ID"] == "dest-3"
def test_archive_adapter_is_wired_and_skips_same_name(monkeypatch):
monkeypatch.setattr(SalesDmsClient, "ensure_month_archive_root", lambda **_kwargs: "archive-root")
monkeypatch.setattr(SalesDmsClient, "ensure_folder", lambda **_kwargs: "inv-folder")
monkeypatch.setattr(
SalesDmsClient,
"copy_file_skip_same_name",
lambda **_kwargs: ({"ID": "dest-9", "LeafName": "INV001-PO9.pdf"}, True),
)
adapter = DmsArchiveAdapter()
assert adapter.wired is True
archived = adapter.archive(
period_month=date(2026, 8, 1),
invoice_no="INV001",
file=ScannedFile(filename="INV001-PO9.pdf", item_id="src-9", fingerprint="fp1"),
rule={"code": "po_order"},
)
assert archived.item_id == "dest-9"
assert archived.folder_id == "inv-folder"
assert archived.extra["skipped_same_name"] is True
assert archived.path == "销售开票附件/2026/08/所有归档/INV001/INV001-PO9.pdf"
def test_archive_adapter_missing_source_id_is_technical():
adapter = DmsArchiveAdapter()
with pytest.raises(ServiceUnavailableError) as exc:
adapter.archive(
period_month=date(2026, 8, 1),
invoice_no="INV001",
file=ScannedFile(filename="INV001.pdf"),
rule={"code": "tax_invoice"},
)
assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED"
def test_month_archive_root_missing_month_is_technical(monkeypatch):
monkeypatch.setattr(SalesDmsClient, "resolve_period_folder", lambda **_kwargs: (None, None))
with pytest.raises(ServiceUnavailableError) as exc:
SalesDmsClient.ensure_month_archive_root(period_month=date(2026, 8, 1))
assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED"
def test_page_walks_until_short_batch(monkeypatch):
"""「所有归档」超过一页时必须翻页,否则同名跳过会漏检已有发票目录。"""
calls = {"n": 0}
def post(_path, payload, **_kwargs):
calls["n"] += 1
index = payload["Page"]["Index"]
if index == 1:
return {
"Code": 0,
"Data": {"Items": [{"ID": "a", "IsFolder": True, "LeafName": "x"}] * 200, "Total": 201},
}
return {
"Code": 0,
"Data": {"Items": [{"ID": "b", "IsFolder": True, "LeafName": "y"}], "Total": 201},
}
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1")
rows = SalesDmsClient.page(parent_folder_id="archive-root")
assert len(rows) == 201
assert calls["n"] == 2
@@ -0,0 +1,127 @@
"""
backend/tests/voucher_check/test_engine_profile_and_scan.py
用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。
依赖:pytest;不连 Oracle / 文档库。
逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。
"""
from __future__ import annotations
from datetime import date, datetime
from zoneinfo import ZoneInfo
import pytest
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.erp_repository import previous_period_bounds
from app.services.voucher_check.filename_match import first_match, match_filename
from app.services.voucher_check.profiles.sales import SALES_PROFILE, required_file_rules
def test_previous_period_bounds_from_early_september():
"""周二跑批时检核上个月;2026-09-01 应得到 2026-08。"""
now = datetime(2026, 9, 1, 6, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
period_month, current_month, period_start, next_start = previous_period_bounds(now)
assert period_month.isoformat() == "2026-08-01"
assert current_month.isoformat() == "2026-09-01"
assert period_start.isoformat().startswith("2026-08-01T00:00:00")
assert next_start.isoformat().startswith("2026-09-01T00:00:00")
def test_previous_period_bounds_january_cross_year():
now = datetime(2026, 1, 6, 10, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
period_month, current_month, _, _ = previous_period_bounds(now)
assert period_month.isoformat() == "2025-12-01"
assert current_month.isoformat() == "2026-01-01"
def test_filename_templates_match_sales_rules():
assert match_filename("INV001-PO9.pdf", template="{invoice}-{order_no}.pdf", invoice_no="INV001")
assert match_filename("INV001.pdf", template="{invoice}.pdf", invoice_no="INV001")
assert match_filename("INV001-DN8.pdf", template="{invoice}-{delivery_no}.pdf", invoice_no="INV001")
assert match_filename("INV001-TAX1.pdf", template="{invoice}-{tax_invoice_no}.pdf", invoice_no="INV001")
assert match_filename("INV001-CD2.pdf", template="{invoice}-{customs_no}.pdf", invoice_no="INV001")
assert match_filename("INV001-提单.pdf", template="{invoice}-提单.pdf", invoice_no="INV001")
assert match_filename("INV002.pdf", template="{invoice}.pdf", invoice_no="INV001") is None
assert first_match(["other.pdf", "INV001-提单.pdf"], template="{invoice}-提单.pdf", invoice_no="INV001")
def test_aggregator_dual_missing_metrics():
"""同一 invoice 缺两类文件:缺件文件=2,缺件 invoice=1。"""
rules = required_file_rules(SALES_PROFILE)
results = [
{"invoice_no": "A", "rule_code": "po_order", "status": "missing"},
{"invoice_no": "A", "rule_code": "customs_pack", "status": "missing"},
{"invoice_no": "A", "rule_code": "sales_release", "status": "staged"},
{"invoice_no": "A", "rule_code": "tax_invoice", "status": "archived"},
{"invoice_no": "A", "rule_code": "customs_declaration", "status": "archived"},
{"invoice_no": "A", "rule_code": "bill_of_lading", "status": "archived"},
{"invoice_no": "B", "rule_code": "po_order", "status": "archived"},
{"invoice_no": "B", "rule_code": "customs_pack", "status": "archived"},
{"invoice_no": "B", "rule_code": "sales_release", "status": "archived"},
{"invoice_no": "B", "rule_code": "tax_invoice", "status": "archived"},
{"invoice_no": "B", "rule_code": "customs_declaration", "status": "archived"},
{"invoice_no": "B", "rule_code": "bill_of_lading", "status": "archived"},
]
stats = aggregate_file_results(results, rules=rules)
assert stats["missing_file_count"] == 2
assert stats["missing_invoice_count"] == 1
by_invoice = {row["invoice_no"]: row for row in stats["excel_rows"]}
assert by_invoice["A"]["status"] == "缺件"
assert by_invoice["B"]["status"] == "完整"
assert by_invoice["A"]["cells"]["po_order"] == "缺件"
assert by_invoice["A"]["cells"]["sales_release"] == "未检核"
assert by_invoice["B"]["cells"]["po_order"] == "有"
assert stats["by_file_type"]["po_order"]["missing_file_count"] == 1
assert stats["by_file_type"]["po_order"]["missing_invoice_count"] == 1
assert stats["by_file_type"]["tax_invoice"]["missing_file_count"] == 0
def test_po_and_oa_adapters_are_placeholders():
with pytest.raises(ServiceUnavailableError) as po_exc:
ErpPoPrintAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
assert po_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
with pytest.raises(ServiceUnavailableError) as oa_exc:
OaSalesReleaseAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
assert oa_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
assert ErpPoPrintAdapter.wired is False
assert OaSalesReleaseAdapter.wired is False
def test_directory_scan_matches_cached_listing(monkeypatch):
adapter = DmsDirectoryScanAdapter()
monkeypatch.setattr(
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.resolve_period_folder",
lambda **kwargs: ("year-id", "month-id"),
)
monkeypatch.setattr(
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.find_child_folder",
lambda **kwargs: "type-id",
)
monkeypatch.setattr(
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.list_files",
lambda **kwargs: [
{"LeafName": "INV001-PO9.pdf", "ID": "item-1", "IsFolder": False, "Path": "销售开票附件/2026/08/PO订单/INV001-PO9.pdf", "VersionID": "v1"},
{"LeafName": "OTHER.pdf", "ID": "item-2", "IsFolder": False},
],
)
hit = adapter.scan(
period_month=date(2026, 8, 1),
invoice_no="INV001",
rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"},
)
assert hit.status == "matched"
assert hit.file is not None
assert hit.file.filename == "INV001-PO9.pdf"
missed = adapter.scan(
period_month=date(2026, 8, 1),
invoice_no="INV999",
rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"},
)
assert missed.status == "missing"
@@ -0,0 +1,29 @@
"""
backend/tests/voucher_check/test_erp_settings.py
用途:立账凭证 ERP 凭据回退到通用 ERP_* / 合同付款同一套只读账号。
依赖:voucher_check.config._erp_settings、Flask app。
逻辑:清空 VOUCHER_CHECK_ERP_USERNAME 后仍能从 CONTRACT_PAYMENT_ERP_* 读到账号。
"""
from __future__ import annotations
from app.services.voucher_check.config import _erp_settings
def test_erp_settings_falls_back_to_contract_payment_credentials(app):
"""未单独配 VOUCHER_CHECK_ERP_USERNAME 时,应复用合同付款已有的只读账号。"""
with app.app_context():
app.config["VOUCHER_CHECK_ERP_DSN"] = ""
app.config["VOUCHER_CHECK_ERP_USERNAME"] = ""
app.config["VOUCHER_CHECK_ERP_PASSWORD"] = ""
app.config["ERP_DB_DSN"] = "192.168.8.24:1521/topprod"
app.config["ERP_USERNAME"] = ""
app.config["ERP_PASSWORD"] = ""
app.config["CONTRACT_PAYMENT_ERP_USERNAME"] = "hxjm_ro"
app.config["CONTRACT_PAYMENT_ERP_PASSWORD"] = "secret-from-contract-payment"
dsn, username, password, timeout = _erp_settings()
assert dsn == "192.168.8.24:1521/topprod"
assert username == "hxjm_ro"
assert password == "secret-from-contract-payment"
assert timeout >= 1
@@ -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()
@@ -0,0 +1,203 @@
"""
backend/tests/voucher_check/test_workspace_force_recheck.py
用途:工作台强制重检入队(force_all)与并发冲突。
依赖:pytest、Flask client;不执行真实周任务。
逻辑:POST /api/workspace/accounting-voucher-check/runs 写入 run_options.mode=force_all;已有 queued 时 409。
"""
from __future__ import annotations
from tests.conftest import parse_api_data, parse_api_error
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.core.errors import ValidationError
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.schedule_seed import (
DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
DEFAULT_VOUCHER_CHECK_SCHEDULE_NO,
ensure_default_voucher_check_schedule,
)
def _ensure_user(*, username: str, role: str) -> User:
user = db.session.query(User).filter_by(username=username).first()
if user:
user.role = role
user.status = "active"
db.session.commit()
return user
user = User(
username=username,
email=f"{username}@example.com",
role=role,
status="active",
)
user.set_password("test")
db.session.add(user)
db.session.commit()
return user
def _stub_force_run_preflight(monkeypatch) -> None:
"""隔离配置预校验,只验证工作台入队和失败可见性契约。"""
monkeypatch.setattr(
"app.services.voucher_check.config.load_engine_config",
lambda _params: type("Config", (), {"profile_code": "sales"})(),
)
monkeypatch.setattr(
"app.services.voucher_check.profile_loader.load_profile_definition",
lambda _code: {"profile_code": "sales"},
)
monkeypatch.setattr(
"app.services.voucher_check.profile_loader.ensure_published_profile",
lambda _code: None,
)
monkeypatch.setattr("app.services.voucher_check.dms_client.SalesDmsClient.ensure_configured", lambda: None)
def test_dms_preflight_reports_missing_keys_without_secret_values(app, monkeypatch):
"""DMS 配置缺失时要指出变量名,且不在错误内容中泄露凭据值。"""
with app.app_context():
monkeypatch.setattr(SalesDmsClient, "base_url", classmethod(lambda _cls: "https://dms.example"))
monkeypatch.setattr(SalesDmsClient, "library_id", classmethod(lambda _cls: "library-id"))
monkeypatch.setattr(SalesDmsClient, "root_folder_id", classmethod(lambda _cls: "folder-id"))
monkeypatch.setattr(SalesDmsClient, "username", classmethod(lambda _cls: ""))
monkeypatch.setattr(SalesDmsClient, "password", classmethod(lambda _cls: ""))
try:
SalesDmsClient.ensure_configured()
except ValidationError as exc:
assert exc.code == "VOUCHER_CHECK.CONFIG_INVALID"
assert exc.details["missing"] == ["VOUCHER_CHECK_DMS_USERNAME", "VOUCHER_CHECK_DMS_PASSWORD"]
else:
raise AssertionError("expected missing DMS configuration to fail")
def test_workspace_force_recheck_enqueues_force_all(app, client, admin_headers, monkeypatch):
"""工作台按钮入队后,ScheduleRun 必须带 force_all,供 runner 跳过增量。"""
with app.app_context():
_ensure_user(username="admin", role="admin")
task = ensure_default_voucher_check_schedule(commit=True)
assert task is not None
assert task.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO
assert task.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH
_stub_force_run_preflight(monkeypatch)
first = client.post(
"/api/workspace/accounting-voucher-check/runs",
json={"mode": "force_all"},
headers=admin_headers,
)
assert first.status_code == 200
data = parse_api_data(first.get_json())
assert data["mode"] == "force_all"
assert data["status"] == "queued"
assert data["run_no"]
with app.app_context():
run = db.session.get(ScheduleRun, data["schedule_run_id"])
assert run is not None
options = (run.api_request_json or {}).get("run_options") or {}
assert options.get("mode") == "force_all"
second = client.post(
"/api/workspace/accounting-voucher-check/runs",
json={"mode": "force_all"},
headers=admin_headers,
)
assert second.status_code == 409
error = parse_api_error(second.get_json())
assert error["code"] == "VOUCHER_CHECK.RUN_IN_PROGRESS"
def test_workspace_force_recheck_rejects_non_admin_and_invalid_mode(app, client, admin_headers, user_headers, monkeypatch):
with app.app_context():
_ensure_user(username="admin", role="admin")
_ensure_user(username="user", role="user")
ensure_default_voucher_check_schedule(commit=True)
_stub_force_run_preflight(monkeypatch)
forbidden = client.post(
"/api/workspace/accounting-voucher-check/runs",
json={"mode": "force_all"},
headers=user_headers,
)
assert forbidden.status_code == 403
invalid = client.post(
"/api/workspace/accounting-voucher-check/runs",
json={"mode": "incremental"},
headers=admin_headers,
)
assert invalid.status_code == 400
error = parse_api_error(invalid.get_json())
assert error["code"] == "VOUCHER_CHECK.CONFIG_INVALID"
def test_workspace_lists_pre_engine_failure_for_selected_period(app, client, admin_headers):
"""配置校验在建引擎批次前失败时,页面仍应展示技术失败与原因。"""
with app.app_context():
_ensure_user(username="admin", role="admin")
task = ensure_default_voucher_check_schedule(commit=True)
assert task is not None
run = ScheduleRun(
schedule_task_id=task.id,
run_no="RUN-PREENGINE-FAILED",
trigger_type="manual",
status="failed",
total_count=0,
success_count=0,
failed_count=1,
error_message="未配置销售开票附件文档库根目录",
response_summary_json={"voucher_check": {"period": "2026-08"}},
)
db.session.add(run)
db.session.commit()
response = client.get(
"/api/workspace/accounting-voucher-check/runs?period=2026-08&status=technical_failed",
headers=admin_headers,
)
assert response.status_code == 200
payload = parse_api_data(response.get_json())
assert payload["total"] == 1
item = payload["items"][0]
# 关键断言:前端列表读取的 run 数据保留失败原因,而非呈现为“暂无检核批次”。
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"
@@ -0,0 +1,144 @@
"""
backend/tests/voucher_check/test_workspace_notifications.py
用途:工作台企微发送记录列表 API。
依赖:pytest、Flask client;不发送真实企微。
逻辑:GET /api/workspace/accounting-voucher-check/notifications 读 voucher_check_notifications,
回填接收人姓名与 has_excel,并可按期间、发送状态筛选。
"""
from __future__ import annotations
from datetime import date, datetime
from tests.conftest import parse_api_data
from app import db
from app.models import ScheduleRun, User
from app.models.voucher_check import VoucherCheckNotification, VoucherCheckRun
from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule
def _ensure_user(*, username: str, role: str, real_name: str | None = None) -> User:
"""测试用户幂等创建。"""
user = db.session.query(User).filter_by(username=username).first()
if user:
user.role = role
user.status = "active"
if real_name:
user.real_name = real_name
db.session.commit()
return user
user = User(
username=username,
email=f"{username}@example.com",
role=role,
status="active",
real_name=real_name,
)
user.set_password("test")
db.session.add(user)
db.session.commit()
return user
def test_workspace_lists_wecom_notifications(app, client, user_headers):
"""企微发送记录列表应带出批次统计、接收人姓名,并按发送状态筛选。"""
with app.app_context():
_ensure_user(username="admin", role="admin")
recipient = _ensure_user(username="user", role="user", real_name="Zhang San")
task = ensure_default_voucher_check_schedule(commit=True)
assert task is not None
schedule_run = ScheduleRun(
schedule_task_id=task.id,
run_no="RUN-VC-NOTIFY-1",
trigger_type="cron",
status="success",
excel_file_name="voucher-check-2026-08.xlsx",
excel_file_size=12,
excel_file_data=b"xlsx-bytes",
)
db.session.add(schedule_run)
db.session.flush()
engine_run = VoucherCheckRun(
id=1,
schedule_run_id=schedule_run.id,
run_no="VC-202608-001",
profile_code="sales",
profile_version="1",
profile_snapshot_json={"profile_code": "sales"},
period_month=date(2026, 8, 1),
mode="incremental",
status="missing",
subject_count=10,
missing_file_count=4,
missing_invoice_count=2,
)
db.session.add(engine_run)
db.session.flush()
db.session.add(
VoucherCheckNotification(
id=1,
run_id=engine_run.id,
excel_filename="voucher-check-2026-08.xlsx",
recipient_user_ids_json=[recipient.id],
send_status="sent",
skip_reason=None,
summary_json={"period": "2026-08", "subject_count": 10},
sent_at=datetime(2026, 9, 1, 6, 10, 0),
)
)
skipped_run = VoucherCheckRun(
id=2,
run_no="VC-202607-001",
profile_code="sales",
profile_version="1",
profile_snapshot_json={"profile_code": "sales"},
period_month=date(2026, 7, 1),
mode="incremental",
status="completed",
subject_count=8,
missing_file_count=0,
missing_invoice_count=0,
)
db.session.add(skipped_run)
db.session.flush()
db.session.add(
VoucherCheckNotification(
id=2,
run_id=skipped_run.id,
send_status="skipped_no_missing",
skip_reason="本批无缺件",
summary_json={"period": "2026-07"},
)
)
db.session.commit()
listed = client.get(
"/api/workspace/accounting-voucher-check/notifications",
headers=user_headers,
)
assert listed.status_code == 200
payload = parse_api_data(listed.get_json())
assert payload["total"] >= 2
sent = next(item for item in payload["items"] if item["run_no"] == "VC-202608-001")
# 关键断言:工作台汇总列表能看到发送状态、接收人姓名和 Excel 入口。
assert sent["send_status"] == "sent"
assert sent["missing_invoice_count"] == 2
assert sent["missing_file_count"] == 4
assert sent["recipient_names"] == ["Zhang San"]
assert sent["has_excel"] is True
assert sent["schedule_run_id"]
filtered = client.get(
"/api/workspace/accounting-voucher-check/notifications?period=2026-07&send_status=skipped_no_missing",
headers=user_headers,
)
assert filtered.status_code == 200
filtered_payload = parse_api_data(filtered.get_json())
assert filtered_payload["total"] == 1
item = filtered_payload["items"][0]
assert item["run_no"] == "VC-202607-001"
assert item["send_status"] == "skipped_no_missing"
assert item["skip_reason"] == "本批无缺件"
assert item["has_excel"] is False
+31 -10
View File
@@ -4,6 +4,7 @@ backend/worker.py
用途:统一后台 worker 入口(方案 D)。
依赖:app.create_app、app.jobs.runner、app.jobs.handlers。
逻辑:--queues kb,shipping,contract,schedule;经 jobs.runner 统一 poll → dispatch。
启动诊断按队列打印,避免 schedule worker 误刷合同付款预警 ERP 配置。
"""
from __future__ import annotations
@@ -55,6 +56,35 @@ def _resolve_config_name() -> str:
return mapping.get(env_name, 'production')
def _log_queue_startup_diagnostics(logger: logging.Logger, app, queue_names: list[str]) -> None:
"""
按实际消费队列打印启动诊断,避免 schedule worker 刷出合同付款预警配置造成误判。
核心逻辑:contract 队列才打印合同付款 ERP 就绪状态;schedule 队列说明 jobs 表身份字段。
只标记配置是否就绪,不输出密码或连接串。
Args:
logger: worker logger。
app: Flask 应用,读取 config。
queue_names: 本次启动消费的队列名。
"""
if 'contract' in queue_names:
erp_dsn = str(app.config.get('CONTRACT_PAYMENT_ERP_DSN') or '').strip()
erp_user = str(app.config.get('CONTRACT_PAYMENT_ERP_USERNAME') or '').strip()
erp_pwd = str(app.config.get('CONTRACT_PAYMENT_ERP_PASSWORD') or '')
logger.info(
'合同付款预警 ERP 回查配置: dsn=%s 用户名=%s 密码=%s',
'✓就绪' if erp_dsn else '✗缺失',
'✓就绪' if erp_user else '✗缺失',
'✓就绪' if erp_pwd else '✗缺失',
)
if 'schedule' in queue_names:
logger.info(
'schedule 队列身份:domain/job_type 固定为 schedule/schedule_run;'
'立账凭证检核看 business_ref 后缀 accounting-voucher-check 或 payload.platform_api_path'
)
def main(
*,
queues: list[str] | None = None,
@@ -75,16 +105,7 @@ def main(
app = create_app(resolved_config)
queue_names = queues or ['kb']
# 启动期诊断:确认合同付款 ERP 回查的运行时配置状态(只标记是否就绪,不输出密码)。
_erp_dsn = str(app.config.get("CONTRACT_PAYMENT_ERP_DSN") or "").strip()
_erp_user = str(app.config.get("CONTRACT_PAYMENT_ERP_USERNAME") or "").strip()
_erp_pwd = str(app.config.get("CONTRACT_PAYMENT_ERP_PASSWORD") or "")
logger.info(
"合同付款预警 ERP 回查配置: dsn=%s 用户名=%s 密码=%s",
"✓就绪" if _erp_dsn else "✗缺失",
"✓就绪" if _erp_user else "✗缺失",
"✓就绪" if _erp_pwd else "✗缺失",
)
_log_queue_startup_diagnostics(logger, app, queue_names)
if queue_names == ['schedule'] and not bool(app.config.get('SCHEDULE_WORKER_ENABLED', True)):
logger.info('Schedule worker disabled by SCHEDULE_WORKER_ENABLED=false')