feat(agent): 立账凭证检核

(cherry picked from commit f9e2fb5efc1ec7bf4f6e52e08dd3591b4e77edd9)
This commit is contained in:
sophie committed 2026-08-06 10:05:46 +08:00
1 parent 9bcbf9d211
commit f615e56bb9
70 files changed
+4968 -108

No files matched your search

+9
View File
@@ -73,6 +73,15 @@ def create_app(config_name='default'):
ensure_default_file_asset_cleanup_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
try:
from app.services.voucher_check.schedule_seed import (
ensure_default_voucher_check_schedule,
register_voucher_check_schedule_hooks,
)
register_voucher_check_schedule_hooks()
ensure_default_voucher_check_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app)
+4 -1
View File
@@ -39,8 +39,9 @@ def register_blueprints(app: Flask) -> None:
workspace_file_check_bp,
workspace_schedule_bp,
workspace_shipping_notice_bp,
workspace_voucher_check_bp,
)
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp
from app.api.files import files_bp
from app.api.procurement_contract_tools import procurement_contract_bp
@@ -57,10 +58,12 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_voucher_check_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
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')
+38 -27
View File
@@ -1,9 +1,9 @@
"""
backend/app/api/file_check_tools.py
用途:文件检核 Chatflow 显式 HTTP Tool API。
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。
"""
from __future__ import annotations
@@ -74,7 +74,7 @@ def _require_tool_auth() -> None:
"""
校验 Tool API 访问权限。
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
"""
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
if request.path.endswith("/excel"):
@@ -84,26 +84,10 @@ def _require_tool_auth() -> None:
return
raise UnauthorizedError("invalid_auth")
# [STEP 2] Dify / RPA 服务端调用
configured = str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
from app.services.integration_tool_auth import require_integration_tool_auth
bearer = str(request.headers.get("Authorization") or "").strip()
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {api_token, integration_key}:
return
if not api_token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
require_integration_tool_auth()
def _tool_error_code(exc: AppError) -> str:
@@ -382,7 +366,17 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_file_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
"""
立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。
核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到
ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。
Body 关键字段(立账凭证检核):
mode: incremental | force_all | single
invoice_no: mode=single 时发票号
run_options: 可选嵌套对象,与顶层字段合并(顶层优先)
"""
perf_started = time.perf_counter()
data = _prepare_bind_payload(request.get_json(silent=True) or {})
task = _resolve_check_task(data)
@@ -428,16 +422,33 @@ def run_file_check():
)
return jsonify(no_data_response)
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {}
run_options = {}
mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower()
if mode in {"incremental", "force_all", "single"}:
run_options["mode"] = mode
invoice_no = data.get("invoice_no")
if invoice_no is None or not str(invoice_no).strip():
invoice_no = raw_options.get("invoice_no")
if invoice_no is not None and str(invoice_no).strip():
run_options["invoice_no"] = str(invoice_no).strip()
api_request_json = {
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
}
if run_options:
api_request_json["run_options"] = run_options
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type="dify_chatflow",
started_at=datetime.utcnow(),
status="running",
api_request_json={
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
},
api_request_json=api_request_json,
)
db.session.add(run)
db.session.commit()
+3 -2
View File
@@ -2,10 +2,11 @@
backend/app/api/tools/__init__.py
用途:Dify HTTP Tool API Blueprint 聚合。
逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。
逻辑:re-export shipping_notice、file_check、maintenance、voucher_check 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']
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp', 'voucher_check_tools_bp']
+105
View File
@@ -0,0 +1,105 @@
"""
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)
+3 -1
View File
@@ -1,7 +1,7 @@
"""
backend/app/api/workspace/__init__.py
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、voucher_check、announcements)。
依赖:workspace 各子模块 blueprint。
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
"""
@@ -9,10 +9,12 @@ from app.api.workspace.announcements import workspace_announcements_bp
from app.api.workspace.file_check import workspace_file_check_bp
from app.api.workspace.schedule import workspace_schedule_bp
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
from app.api.workspace.voucher_check import workspace_voucher_check_bp
__all__ = [
'workspace_announcements_bp',
'workspace_file_check_bp',
'workspace_schedule_bp',
'workspace_shipping_notice_bp',
'workspace_voucher_check_bp',
]
+58 -1
View File
@@ -57,6 +57,31 @@ def serialize_current_step(payload: dict) -> dict | None:
return None
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
def serialize_progress_metrics(payload: dict) -> list[dict] | None:
"""
序列化领域自定义进度指标(如立账凭证检核的齐全/缺资料)。
核心逻辑:读取 response_summary_json.progress_metrics;非法则返回 None 以回退旧八格。
"""
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
metrics = response_summary.get('progress_metrics')
if not isinstance(metrics, list) or not metrics:
return None
out: list[dict] = []
for item in metrics:
if not isinstance(item, dict):
continue
key = str(item.get('key') or '').strip()
if not key:
continue
out.append({
'key': key,
'label_key': str(item.get('label_key') or ''),
'label': str(item.get('label') or ''),
'value': int(item.get('value') or 0),
})
return out or None
def _serialize_progress_run(run: ScheduleRun) -> dict:
payload = serialize_run(run)
total = int(payload.get('total_count') or 0)
@@ -66,7 +91,39 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
processed = success + failed + skipped
percent = int(round(processed / total * 100)) if total > 0 else 0
percent = max(0, min(percent, 100))
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}}
return {
'run_id': payload['id'],
'run_no': payload['run_no'],
'task_id': payload['schedule_task_id'],
'title': payload.get('schedule_name') or '',
'status': payload['status'],
'total_count': total,
'processed_count': processed,
'success_count': success,
'failed_count': failed,
'skipped_count': skipped,
'judgement': serialize_file_judgement(payload),
'progress_metrics': serialize_progress_metrics(payload),
'current_step': serialize_current_step(payload),
'progress_percent': percent,
'started_at': payload.get('started_at'),
'finished_at': payload.get('finished_at'),
'duration_ms': payload.get('duration_ms'),
'error_message': payload.get('error_message'),
'excel': {
'file_name': payload.get('excel_file_name'),
'file_size': payload.get('excel_file_size'),
'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None,
},
'knowledge_base': {
'sync_status': payload.get('kb_sync_status'),
'group_id': payload.get('kb_group_id'),
'document_id': payload.get('kb_document_id'),
'document_version_id': payload.get('kb_document_version_id'),
'sync_job_id': payload.get('kb_sync_job_id'),
'error_message': payload.get('kb_sync_error'),
},
}
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
def workspace_file_check_run_for_log():
@@ -0,0 +1,70 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核记录查询 API(批次明细 / 最新状态)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核记录页共用;标准 {success,data|error,request_id} envelope。
"""
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.response import ok
from app.services.voucher_check import query_service
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
def _require_user():
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
@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 过滤。
"""
_require_user()
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 ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states", methods=["GET"])
def workspace_voucher_states():
"""
按月份、状态、发票号筛选最新状态。
"""
_require_user()
data = query_service.list_states(
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
status=request.args.get("status"),
invoice_no=request.args.get("invoice_no"),
page=request.args.get("page", default=1, type=int) or 1,
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/states/<path:invoice_no>", methods=["GET"])
def workspace_voucher_state_detail(invoice_no: str):
"""查看单票最近状态和历史批次快照。"""
_require_user()
data = query_service.get_invoice_latest(
invoice_no=invoice_no,
scope_code=str(request.args.get("scope_code") or "HXJM"),
period=request.args.get("period"),
)
return ok(data)
+12
View File
@@ -416,6 +416,18 @@ 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'
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')
# MinIO 配置
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
+4 -1
View File
@@ -2,7 +2,7 @@
backend/app/models/__init__.py
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
依赖:models/* 子模块、app.extensions.db(经 base.Base)。
依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
"""
@@ -32,6 +32,7 @@ from app.models.shipping import (
)
from app.models.training import TrainingRecord
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
__all__ = [
@@ -86,4 +87,6 @@ __all__ = [
'MaintenanceDevice',
'MaintenanceRecord',
'MaintenanceAuditLog',
'VoucherCheckInvoiceState',
'VoucherCheckRunItem',
]
+114
View File
@@ -0,0 +1,114 @@
"""
backend/app/models/voucher_check.py
用途:立账凭证检核单票最新状态与批次明细 ORM。
依赖:models.base.Base、schedule_runs。
逻辑:runner/persistence 写入;query_service 与工作台 API 读取;增量跳过依赖 invoice_states。
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Optional
from sqlalchemy import (
BigInteger,
Boolean,
Date,
DateTime,
ForeignKey,
Index,
JSON,
String,
Text,
UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class VoucherCheckInvoiceState(Base):
"""账套+月份+发票号的最新材料齐全状态(增量跳过真相源)。"""
__tablename__ = "voucher_check_invoice_states"
__table_args__ = (
UniqueConstraint(
"scope_code",
"period_month",
"invoice_no",
name="uq_voucher_check_invoice_states_scope_period_invoice",
),
Index("ix_voucher_check_invoice_states_period_status", "period_month", "status"),
Index("ix_voucher_check_invoice_states_invoice_no", "invoice_no"),
Index("ix_voucher_check_invoice_states_notified_on", "last_missing_notified_on"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
scope_code: Mapped[str] = mapped_column(String(32), nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
status: Mapped[str] = mapped_column(String(24), nullable=False)
folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
last_actual_run_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
)
last_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_seen_erp_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
last_missing_notified_on: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
class VoucherCheckRunItem(Base):
"""单次 ScheduleRun 的发票检核快照(含跳过项,供审计与 Excel)。"""
__tablename__ = "voucher_check_run_items"
__table_args__ = (
UniqueConstraint(
"schedule_run_id",
"invoice_no",
name="uq_voucher_check_run_items_run_invoice",
),
Index("ix_voucher_check_run_items_run_result", "schedule_run_id", "result"),
Index("ix_voucher_check_run_items_period_result", "period_month", "result"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
schedule_run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("schedule_runs.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
invoice_state_id: Mapped[Optional[int]] = mapped_column(
BigInteger,
ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"),
nullable=True,
)
scope_code: Mapped[str] = mapped_column(String(32), nullable=False)
period_month: Mapped[date] = mapped_column(Date, nullable=False)
invoice_no: Mapped[str] = mapped_column(String(128), nullable=False)
invoice_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
result: Mapped[str] = mapped_column(String(24), nullable=False)
folder_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
folder_exists: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
material_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
matched_files_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_materials_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -560,12 +560,40 @@
"type": "string",
"nullable": true,
"description": "HXOPS 会话 ID;可与 sys.conversation_id 二选一,优先显式传入"
},
"mode": {
"type": "string",
"nullable": true,
"enum": ["incremental", "force_all", "single"],
"description": "【Dify 推荐】运行模式(立账凭证检核读取;文件检核忽略)。incremental=增量 / force_all=全量 / single=单发票;单发票时须同时填 invoice_no"
},
"invoice_no": {
"type": "string",
"nullable": true,
"description": "【Dify 推荐】mode=single 时必填的发票号;来自意图识别.invoice_no"
},
"run_options": {
"type": "object",
"nullable": true,
"description": "可选嵌套写法(部分 Dify 版本不展示对象字段;优先用顶层 mode/invoice_no)。mode=incremental|force_all|single;single 时须带 invoice_no",
"properties": {
"mode": {
"type": "string",
"enum": ["incremental", "force_all", "single"],
"default": "incremental"
},
"invoice_no": {
"type": "string",
"nullable": true,
"description": "mode=single 时必填的发票号"
}
}
}
},
"required": [
"task_id"
],
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
"description": "Chatflow Tool 节点绑定 task_id(Integer,来源 解析运行态上下文.task_id_int)、hxops_turn_id(经 agent_runtime_context 解析后传入);立账凭证检核用顶层 mode/invoice_no(Dify 友好)或嵌套 run_options"
},
"RunCheckSuccessResponse": {
"type": "object",
@@ -0,0 +1,44 @@
"""
backend/app/services/integration_tool_auth.py
用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。
依赖:Flask current_app、core.errors。
逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用;
密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。
"""
from __future__ import annotations
from flask import current_app, request
from app.core.errors import ServiceUnavailableError, UnauthorizedError
def require_integration_tool_auth() -> None:
"""
校验 Tool API 访问权限。
核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。
Raises:
ServiceUnavailableError: 服务端未配置密钥。
UnauthorizedError: 缺少或错误的凭证。
"""
configured = str(
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {api_token, integration_key}:
return
if not api_token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
@@ -81,7 +81,10 @@ def _run_platform_job_in_process(task: ScheduleTask, run: ScheduleRun) -> Schedu
from app.services.schedule.job_registry import run_platform_job
key = normalize_platform_api_path(task.platform_api_path)
# [STEP 1] 合并而非覆盖:保留会话触发写入的 run_options 等字段
existing = run.api_request_json if isinstance(run.api_request_json, dict) else {}
payload = {
**existing,
"run_no": run.run_no,
"schedule_task_id": task.id,
"schedule_name": task.name,
+74 -1
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、job_params(执行前校验)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、job_params。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
"""
@@ -132,6 +132,8 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES
register_platform_job(PlatformJobDefinition(
key="shipping-inventory-rpa",
@@ -200,6 +202,77 @@ def _register_builtin_platform_jobs() -> None:
description="按 TTL 清理未建单、未引用的临时 FileAsset 与关联 intake,并删除私有 MinIO 对象。",
category="files",
))
register_platform_job(PlatformJobDefinition(
key="accounting-voucher-check",
label="立账凭证检核",
label_key="admin.schedule.form.platformJobAccountingVoucherCheck",
handler=run_voucher_check_schedule,
description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。",
description_key="admin.schedule.form.accountingVoucherCheckHint",
category="finance",
params_schema=(
{
"key": "scope_code",
"type": "select",
"label": "账套",
"label_key": "admin.schedule.form.voucherCheckScope",
"required": True,
"default": "HXJM",
"options": [{"value": "HXJM", "label": "HXJM"}],
},
{
"key": "directory_template",
"type": "text",
"label": "目录模板",
"label_key": "admin.schedule.form.voucherCheckDirTemplate",
"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,
},
{
"key": "notify_missing_enabled",
"type": "boolean",
"label": "缺资料通知",
"label_key": "admin.schedule.form.voucherCheckNotifyMissing",
"required": False,
"default": True,
},
{
"key": "notify_failure_enabled",
"type": "boolean",
"label": "失败告警",
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
"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),
))
_register_builtin_platform_jobs()
@@ -142,6 +142,11 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
"""
排程完成后的通用企微通知。
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
"""
from app.services.wecom_notify import (
upload_wecom_temp_media,
send_wecom_file_message,
@@ -151,6 +156,12 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
_get_enabled_events,
)
# 领域自行管理通知时跳过通用完成通知,避免重复刷屏
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('domain_notification_managed'):
run.wecom_notify_error = 'domain_notification_managed'
return
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
return
@@ -0,0 +1,44 @@
"""
backend/app/services/schedule/voucher_check_job.py
用途:立账凭证检核 platform_job 薄封装。
依赖:voucher_check.runner、excel_rows 表头注册。
逻辑:job_registry 注册 accounting-voucher-check 后由 schedule worker / 会话触发调用。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import register_schedule_header
from app.services.voucher_check.excel_rows import (
VOUCHER_CHECK_HEADER_LABELS,
VOUCHER_CHECK_HEADER_ORDER,
)
from app.services.voucher_check.runner import run_voucher_check_batch
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
_HEADERS_REGISTERED = False
def _ensure_headers() -> None:
global _HEADERS_REGISTERED
if _HEADERS_REGISTERED:
return
register_schedule_header(
"accounting-voucher-check",
VOUCHER_CHECK_HEADER_ORDER,
VOUCHER_CHECK_HEADER_LABELS,
)
_HEADERS_REGISTERED = True
def run_voucher_check_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证检核排程。
核心逻辑:注册 Excel 表头后委托 runner;日批默认 incremental。
"""
_ensure_headers()
return run_voucher_check_batch(task, run)
@@ -0,0 +1,11 @@
"""
backend/app/services/voucher_check/__init__.py
用途:立账凭证检核领域服务包入口。
依赖:config / runner / query_service 等子模块。
逻辑:platform Job 与 Tool/工作台 API 从此包调用 runner 与查询能力。
"""
from app.services.voucher_check.runner import run_voucher_check_batch
__all__ = ["run_voucher_check_batch"]
@@ -0,0 +1,262 @@
"""
backend/app/services/voucher_check/config.py
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。
依赖:Flask current_app.config、core.errors.ValidationError。
逻辑:runner / share_scanner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID。
"""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass
from typing import Any
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] = {
"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:
"""运行期检核配置快照。"""
scope_code: str
directory_template: str
required_files: tuple[RequiredFileRule, ...]
filename_case_sensitive: bool
notify_missing_enabled: bool
notify_failure_enabled: bool
same_day_dedup_enabled: bool
local_root: str
share_unc: str
healthcheck_relative_path: str
erp_dsn: str
erp_username: str
erp_password: str
erp_timeout_seconds: int = 30
def _config_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError:
return ValidationError(
message,
code="VOUCHER_CHECK.CONFIG_INVALID",
details=details or {},
)
def _as_bool(value: Any, default: bool) -> bool:
if value is None:
return default
if isinstance(value, bool):
return value
text = str(value).strip().lower()
if text in {"1", "true", "yes", "on"}:
return True
if text in {"0", "false", "no", "off"}:
return False
return default
def _parse_required_files(raw: Any) -> list[RequiredFileRule]:
if raw is None:
raw = DEFAULT_REQUIRED_FILES
if isinstance(raw, str):
try:
raw = json.loads(raw)
except json.JSONDecodeError as exc:
raise _config_invalid("required_files JSON 非法", details={"error": str(exc)}) from exc
if not isinstance(raw, list) or not raw:
raise _config_invalid("required_files 至少包含一个必检项")
rules: list[RequiredFileRule] = []
for idx, item in enumerate(raw):
if not isinstance(item, dict):
raise _config_invalid(f"required_files[{idx}] 必须为对象")
code = str(item.get("code") or "").strip()
name = str(item.get("name") or code).strip()
accepted = item.get("accepted_filenames") or []
if not code:
raise _config_invalid(f"required_files[{idx}].code 不能为空")
if not isinstance(accepted, list) or not accepted:
raise _config_invalid(f"required_files[{idx}].accepted_filenames 不能为空")
filenames: list[str] = []
for fname in accepted:
text = str(fname or "").strip()
if not text:
raise _config_invalid(f"required_files[{idx}] 存在空文件名")
if "*" in text or "?" in text or _UNSAFE_FILENAME_RE.search(text):
raise _config_invalid(
f"required_files[{idx}] 文件名禁止通配/路径字符: {text}",
)
filenames.append(text)
rules.append(
RequiredFileRule(
code=code,
name=name or code,
required=_as_bool(item.get("required"), True),
accepted_filenames=tuple(filenames),
)
)
if not any(r.required for r in rules):
raise _config_invalid("required_files 至少包含一个 required=true 项")
return rules
def validate_directory_template(template: str) -> str:
"""
校验目录模板占位符。
核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。
"""
text = str(template or "").strip().replace("\\", "/")
if not text:
raise _config_invalid("directory_template 不能为空")
tokens = _TEMPLATE_TOKEN_RE.findall(text)
unknown = sorted({t for t in tokens if t not in _ALLOWED_TEMPLATE_KEYS})
if unknown:
raise _config_invalid(
"directory_template 含非法占位符",
details={"unknown": unknown},
)
missing = sorted(_ALLOWED_TEMPLATE_KEYS - set(tokens))
if missing:
raise _config_invalid(
"directory_template 缺少必要占位符",
details={"missing": missing},
)
return text
def 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")
or cfg.get("ERP_DB_DSN")
or os.getenv("ERP_DB_DSN")
or ""
).strip()
erp_username = str(
cfg.get("VOUCHER_CHECK_ERP_USERNAME")
or os.getenv("VOUCHER_CHECK_ERP_USERNAME")
or ""
).strip()
erp_password = str(
cfg.get("VOUCHER_CHECK_ERP_PASSWORD")
or os.getenv("VOUCHER_CHECK_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 30
)
return VoucherCheckConfig(
scope_code=scope_code,
directory_template=template,
required_files=tuple(required_files),
filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True),
notify_missing_enabled=_as_bool(params.get("notify_missing_enabled"), True),
notify_failure_enabled=_as_bool(params.get("notify_failure_enabled"), True),
same_day_dedup_enabled=_as_bool(params.get("same_day_dedup_enabled"), True),
local_root=local_root,
share_unc=share_unc,
healthcheck_relative_path=healthcheck,
erp_dsn=erp_dsn,
erp_username=erp_username,
erp_password=erp_password,
erp_timeout_seconds=max(1, timeout),
)
def 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,146 @@
"""
backend/app/services/voucher_check/erp_repository.py
用途:从 Oracle HXJM 套账 apa_file 查询当前自然月发票号集合。
依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。
逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date, datetime
from zoneinfo import ZoneInfo
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.config import VoucherCheckConfig
_TZ = ZoneInfo("Asia/Shanghai")
_INVOICE_SQL = """
SELECT DISTINCT
TRIM(apa08) AS invoice_no,
TRUNC(apa09) AS invoice_date
FROM apa_file
WHERE apa09 >= :period_start
AND apa09 < :next_period_start
AND TRIM(apa08) IS NOT NULL
ORDER BY TRUNC(apa09), TRIM(apa08)
"""
@dataclass(frozen=True)
class ErpInvoiceRow:
"""ERP 当月发票行。"""
invoice_no: str
invoice_date: date | None
def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
"""
按 Asia/Shanghai 计算当前自然月起止。
核心逻辑:不用 Oracle SYSDATE,保证手动触发与日批口径一致。
Returns:
(period_month_first, next_month_first, period_start_dt, next_period_start_dt)
"""
base = now.astimezone(_TZ) if now and now.tzinfo else (now or datetime.now(_TZ))
if base.tzinfo is None:
base = base.replace(tzinfo=_TZ)
else:
base = base.astimezone(_TZ)
period_month = date(base.year, base.month, 1)
if base.month == 12:
next_month = date(base.year + 1, 1, 1)
else:
next_month = date(base.year, base.month + 1, 1)
period_start = datetime(period_month.year, period_month.month, 1, 0, 0, 0, tzinfo=_TZ)
next_start = datetime(next_month.year, next_month.month, 1, 0, 0, 0, tzinfo=_TZ)
return period_month, next_month, period_start, next_start
def fetch_month_invoices(
config: VoucherCheckConfig,
*,
now: datetime | None = None,
) -> tuple[date, list[ErpInvoiceRow]]:
"""
查询当前自然月发票清单。
Args:
config: 含 Oracle DSN/账号的检核配置。
now: 可选时钟(测试注入)。
Returns:
(period_month, invoices)
Raises:
ServiceUnavailableError: Oracle 不可用。
"""
period_month, _next_month, period_start, next_start = current_period_bounds(now)
try:
import oracledb
except ImportError as exc:
raise ServiceUnavailableError(
"Oracle 驱动不可用",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
) from exc
from flask import current_app
from app.services.text2sql import Text2SQLService
connection = None
try:
Text2SQLService._init_oracle_client(oracledb)
connection = oracledb.connect(
user=config.erp_username,
password=config.erp_password,
dsn=config.erp_dsn,
)
connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000
cursor = connection.cursor()
cursor.execute(
_INVOICE_SQL,
{
"period_start": period_start.replace(tzinfo=None),
"next_period_start": next_start.replace(tzinfo=None),
},
)
rows: list[ErpInvoiceRow] = []
seen: set[str] = set()
for raw_no, raw_date in cursor:
invoice_no = str(raw_no or "").strip()
if not invoice_no or invoice_no in seen:
continue
seen.add(invoice_no)
invoice_date: date | None = None
if raw_date is not None:
if isinstance(raw_date, datetime):
invoice_date = raw_date.date()
elif isinstance(raw_date, date):
invoice_date = raw_date
rows.append(ErpInvoiceRow(invoice_no=invoice_no, invoice_date=invoice_date))
return period_month, rows
except ServiceUnavailableError:
raise
except Exception as exc:
try:
current_app.logger.error(
"[voucher-check] ERP query failed dsn=%s error_type=%s",
config.erp_dsn,
type(exc).__name__,
)
except Exception:
pass
raise ServiceUnavailableError(
"Oracle 查询失败",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
details={"error_type": type(exc).__name__},
) from exc
finally:
if connection is not None:
try:
connection.close()
except Exception:
pass
@@ -0,0 +1,93 @@
"""
backend/app/services/voucher_check/excel_rows.py
用途:把批次明细转换为通用 Excel 导出行与表头。
依赖:无。
逻辑:runner 返回 details;schedule excel_service / register_schedule_header 使用本模块表头。
"""
from __future__ import annotations
from typing import Any
VOUCHER_CHECK_HEADER_ORDER = [
"period",
"scope_code",
"invoice_no",
"invoice_date",
"result",
"folder_exists",
"folder_path",
"matched_files",
"missing_materials",
"material_fingerprint",
"checked_at",
"error_code",
"error_message",
]
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": "技术错误摘要",
}
_RESULT_LABELS = {
"complete": "齐全",
"missing": "缺资料",
"skipped": "跳过",
"technical_error": "技术异常",
}
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]:
"""
将内存结果行转为 Excel details 行。
"""
result = str(item.get("result") or "")
checked_at = item.get("checked_at")
invoice_date = item.get("invoice_date")
return {
"period": period,
"scope_code": scope_code,
"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 "",
}
@@ -0,0 +1,34 @@
"""
backend/app/services/voucher_check/fingerprint.py
用途:根据共享盘目录直接子文件的元数据生成稳定 SHA-256 指纹。
依赖:标准库 hashlib / json。
逻辑:share_scanner 枚举文件后调用;runner 用指纹判断齐全票是否可跳过。
"""
from __future__ import annotations
import hashlib
import json
from typing import Iterable, Sequence
def build_material_fingerprint(
entries: Sequence[tuple[str, int, int]] | Iterable[tuple[str, int, int]],
) -> str:
"""
对直接子文件元数据生成 SHA-256。
核心逻辑:按文件名排序后序列化为 UTF-8 JSON,再哈希;不读取文件内容。
Args:
entries: (filename, size, mtime_ns) 列表。
Returns:
64 位十六进制 SHA-256;无文件时对空数组哈希。
"""
normalized = sorted(
[(str(name), int(size), int(mtime_ns)) for name, size, mtime_ns in entries],
key=lambda item: item[0],
)
payload = json.dumps(normalized, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
@@ -0,0 +1,205 @@
"""
backend/app/services/voucher_check/notification.py
用途:立账凭证检核缺资料企微 textcard 与批次失败告警。
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、persistence.mark_missing_notified。
逻辑:runner 落库后调用;同票同日节流;设置 domain_notification_managed 避免通用排程重复通知。
"""
from __future__ import annotations
import uuid
from datetime import date, datetime
from typing import Any
from zoneinfo import ZoneInfo
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
_TZ = ZoneInfo("Asia/Shanghai")
def _recipient_users(task: ScheduleTask) -> list[User]:
user_ids = task.notify_user_ids_json or []
if not user_ids:
return []
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
return [u for u in users if u.wecom_userid]
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(
*,
task: ScheduleTask,
run: ScheduleRun,
scope_code: str,
period_month: date,
missing_items: list[dict[str, Any]],
same_day_dedup: bool,
enabled: bool,
) -> int:
"""
合并发送缺资料 textcard。
核心逻辑:过滤同日已通知票;成功后才写 last_missing_notified_on。
Returns:
本次实际通知的发票数。
"""
if not enabled or not missing_items:
return 0
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
return 0
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()
)
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}"
description = (
f"批次 {run.run_no}\n"
f"检核月份 {period}\n"
f"缺资料 {len(to_notify)} 张\n"
f"示例:{sample}\n"
f"完整清单请查看工作台检核记录或 Excel。"
)
ok_any = False
for user in users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url(
"/workspace/accounting-voucher-check",
trace_id,
{"task_id": task.id, "run_id": run.id},
)
try:
audit = _create_audit("voucher_check_missing", user, title, description, trace_id)
audit.jump_url = jump_url
data = send_wecom_textcard_message(user.wecom_userid, title, description, jump_url)
if data.get("errcode") == 0:
audit.status = "sent"
ok_any = True
else:
audit.error_code = str(data.get("errcode"))
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
except Exception as exc:
current_app.logger.warning(
"[voucher-check] missing 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
def send_failure_alert(
*,
task: ScheduleTask,
run: ScheduleRun,
stage: str,
error_code: str,
error_message: str,
enabled: bool,
) -> None:
"""批次级失败告警(共享盘/Oracle/业务配置异常)。"""
if not enabled:
return
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
return
from app.services.wecom_notify import (
_build_jump_url,
_create_audit,
send_wecom_textcard_message,
)
users = _recipient_users(task)
if not users:
return
title = f"立账凭证检核失败: {task.name}"
description = (
f"批次 {run.run_no}\n"
f"失败阶段:{stage}\n"
f"错误码:{error_code}\n"
f"摘要:{(error_message or '')[:200]}\n"
f"run_id={run.id}\n"
f"请检查 Oracle 连接与共享盘挂载/健康标记。"
)
for user in users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url(
"/admin/schedules",
trace_id,
{"task_id": task.id, "run_id": run.id},
)
try:
audit = _create_audit("voucher_check_failure", user, title, description, trace_id)
audit.jump_url = jump_url
data = send_wecom_textcard_message(user.wecom_userid, title, description, jump_url)
if data.get("errcode") == 0:
audit.status = "sent"
else:
audit.error_code = str(data.get("errcode"))
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
except Exception as exc:
current_app.logger.warning(
"[voucher-check] failure alert failed user=%s err=%s",
user.id,
exc,
)
db.session.commit()
@@ -0,0 +1,316 @@
{
"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" }
}
}
}
}
}
}
@@ -0,0 +1,35 @@
"""
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
@@ -0,0 +1,126 @@
"""
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,220 @@
"""
backend/app/services/voucher_check/query_service.py
用途:查询批次明细、当月缺资料与单票最新状态。
依赖:models.voucher_check、ScheduleRun。
逻辑:Tool API 与工作台 API 调用;不触发扫描。
"""
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,
}
def parse_period_month(raw: str | None) -> date:
"""解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取当前自然月。"""
if not raw:
period_month, *_ = current_period_bounds()
return period_month
text = str(raw).strip()
try:
if len(text) == 7:
dt = datetime.strptime(text, "%Y-%m")
else:
dt = datetime.strptime(text[:10], "%Y-%m-%d")
return date(dt.year, dt.month, 1)
except ValueError as exc:
raise ValidationError(
"period 格式须为 YYYY-MM",
code="VOUCHER_CHECK.CONFIG_INVALID",
) from exc
def list_missing_states(
*,
task_id: int | None = None,
scope_code: str = "HXJM",
period: str | None = None,
limit: int = 200,
) -> dict[str, Any]:
"""
查询指定月份缺资料票(最新状态表)。
task_id 预留与排程绑定校验,本期仅用于响应回显。
"""
period_month = parse_period_month(period)
limit = max(1, min(int(limit or 200), 1000))
q = (
VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
status="missing",
)
.order_by(VoucherCheckInvoiceState.invoice_no.asc())
.limit(limit)
)
items = [_serialize_state(s) for s in q.all()]
return {
"task_id": task_id,
"scope_code": scope_code,
"period": period_month.strftime("%Y-%m"),
"count": len(items),
"items": items,
}
def list_run_items(
*,
run_id: int,
result: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""分页查询批次明细。"""
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()
)
return {
"run_id": run_id,
"run_no": run.run_no,
"page": page,
"page_size": page_size,
"total": total,
"items": [_serialize_run_item(r) for r in rows],
}
def get_invoice_latest(
*,
invoice_no: str,
scope_code: str = "HXJM",
period: str | None = None,
) -> dict[str, Any]:
"""查询单票最新状态及近期批次快照。"""
inv = str(invoice_no or "").strip()
if not inv:
raise ValidationError("invoice_no 必填", code="VOUCHER_CHECK.INVOICE_REQUIRED")
period_month = parse_period_month(period)
state = (
VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
invoice_no=inv,
).one_or_none()
)
if not state:
raise NotFoundError("发票状态不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
history = (
VoucherCheckRunItem.query.filter_by(
scope_code=scope_code,
period_month=period_month,
invoice_no=inv,
)
.order_by(VoucherCheckRunItem.id.desc())
.limit(20)
.all()
)
return {
"state": _serialize_state(state),
"recent_run_items": [_serialize_run_item(h) for h in history],
}
def list_states(
*,
scope_code: str = "HXJM",
period: str | None = None,
status: str | None = None,
invoice_no: str | None = None,
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
"""工作台:按月/状态/发票号筛选最新状态。"""
period_month = parse_period_month(period)
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
q = VoucherCheckInvoiceState.query.filter_by(
scope_code=scope_code,
period_month=period_month,
)
if status:
q = q.filter(VoucherCheckInvoiceState.status == str(status).strip())
if invoice_no:
q = q.filter(VoucherCheckInvoiceState.invoice_no.ilike(f"%{str(invoice_no).strip()}%"))
total = q.count()
rows = (
q.order_by(VoucherCheckInvoiceState.invoice_no.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return {
"scope_code": scope_code,
"period": period_month.strftime("%Y-%m"),
"page": page,
"page_size": page_size,
"total": total,
"items": [_serialize_state(r) for r in rows],
}
@@ -0,0 +1,366 @@
"""
backend/app/services/voucher_check/runner.py
用途:立账凭证检核批次编排(预检、增量、扫描、落库、进度摘要、通知)。
依赖:config、erp_repository、share_scanner、persistence、excel_rows、notification。
逻辑:platform Job 与会话触发共用;两阶段执行保证共享盘失败不污染单票状态。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
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
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _extract_run_options(run: ScheduleRun) -> dict[str, Any]:
payload = run.api_request_json if isinstance(run.api_request_json, dict) else {}
options = payload.get("run_options")
if not isinstance(options, dict):
options = {}
mode = str(options.get("mode") or "incremental").strip().lower()
if mode not in {"incremental", "force_all", "single"}:
mode = "incremental"
invoice_no = options.get("invoice_no")
invoice_no = str(invoice_no).strip() if invoice_no else None
return {"mode": mode, "invoice_no": invoice_no}
def _update_progress(
run: ScheduleRun,
*,
step: str,
label: str,
processed: int = 0,
voucher_summary: dict[str, Any] | None = None,
) -> None:
summary = dict(run.response_summary_json or {})
summary["current_step"] = {
"step": step,
"label": label,
"processed_count": processed,
}
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),
"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)},
]
summary["domain_notification_managed"] = True
run.response_summary_json = summary
db.session.commit()
def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证检核批次。
核心逻辑:阶段 A 只读预检与扫描;阶段 B 事务落库;缺资料不计入 failed_count。
Returns:
ScheduleExecuteResult:(total, success, failed, skipped, details, errors, step_logs)
"""
step_logs: list[dict[str, Any]] = []
errors: list[str] = []
options = _extract_run_options(run)
mode = options["mode"]
single_invoice = options["invoice_no"]
try:
config = load_voucher_check_config(task.job_params if isinstance(task.job_params, dict) else {})
except AppError as exc:
send_failure_alert(
task=task,
run=run,
stage="config",
error_code=exc.code,
error_message=exc.message,
enabled=True,
)
raise
# [STEP 1] 拉取 ERP 当月发票清单
_update_progress(run, step="fetch_erp", label="拉取 ERP 当月立账凭证")
try:
period_month, invoices = fetch_month_invoices(config)
except ServiceUnavailableError as exc:
send_failure_alert(
task=task,
run=run,
stage="fetch_erp",
error_code=exc.code,
error_message=exc.message,
enabled=config.notify_failure_enabled,
)
raise
step_logs.append(
{
"step": "fetch_erp",
"status": "success",
"detail": {"count": len(invoices), "period": period_month.strftime("%Y-%m")},
}
)
if mode == "single":
if not single_invoice:
raise ValidationError(
"single 模式必须提供 invoice_no",
code="VOUCHER_CHECK.INVOICE_REQUIRED",
)
invoices = [row for row in invoices if row.invoice_no == single_invoice]
if not invoices:
raise NotFoundError(
"指定发票不在当前月 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()
)
state_map = {s.invoice_no: s for s in existing_states}
results: list[dict[str, Any]] = []
complete_count = 0
missing_count = 0
skipped_count = 0
technical_error_count = 0
now = datetime.utcnow()
force = mode in {"force_all", "single"}
# [STEP 4] 逐票扫描 / 指纹比对
_update_progress(
run,
step="scan_share",
label="扫描共享盘文件名",
processed=0,
voucher_summary={
"scope_code": config.scope_code,
"period": period_month.strftime("%Y-%m"),
"mode": mode,
"total_count": len(invoices),
"complete_count": 0,
"missing_count": 0,
"scan_count": 0,
"skipped_count": 0,
"technical_error_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,
"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
else:
missing_count += 1
results.append(item)
if idx % 20 == 0 or idx == len(invoices):
scan_count = complete_count + missing_count + technical_error_count
_update_progress(
run,
step="scan_share",
label="扫描共享盘文件名",
processed=idx,
voucher_summary={
"scope_code": config.scope_code,
"period": period_month.strftime("%Y-%m"),
"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,
},
)
step_logs.append(
{
"step": "scan_share",
"status": "success",
"detail": {
"complete": complete_count,
"missing": missing_count,
"skipped": skipped_count,
"technical_error": technical_error_count,
},
}
)
# [STEP 5] 事务落库
_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,
now=now,
)
db.session.commit()
except Exception as exc:
db.session.rollback()
current_app.logger.error("[voucher-check] persist failed run_id=%s: %s", run.id, exc, exc_info=True)
send_failure_alert(
task=task,
run=run,
stage="persist",
error_code="VOUCHER_CHECK.PERSIST_FAILED",
error_message=str(exc),
enabled=config.notify_failure_enabled,
)
raise
# [STEP 6] 缺资料通知
missing_items = [r for r in results if r["result"] == "missing"]
notified = send_missing_notifications(
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,
enabled=config.notify_missing_enabled,
)
step_logs.append(
{
"step": "notify",
"status": "success",
"detail": {"missing": len(missing_items), "notified": notified},
}
)
period = period_month.strftime("%Y-%m")
scan_count = complete_count + missing_count + technical_error_count
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,
}
_update_progress(
run,
step="done",
label="检核完成",
processed=len(invoices),
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)
return (
total_count,
success_count,
technical_error_count,
skipped_count,
details,
errors,
step_logs,
)
@@ -0,0 +1,149 @@
"""
backend/app/services/voucher_check/schedule_seed.py
用途:确保 accounting-voucher-check 默认日批 ScheduleTask 存在(06:00 Asia/Shanghai)。
依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。
逻辑:迁移种子 + create_app / User after_commit 幂等补建。
"""
from __future__ import annotations
import logging
from datetime import datetime
from typing import Any
from sqlalchemy import event
from sqlalchemy.orm import Session
from app import db
from app.models import ScheduleTask, User
from app.services.schedule.timezone_util import compute_next_run_at
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
_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 = "立账凭证检核(日批)"
_HOOKS_REGISTERED = False
_SESSION_INFO_KEY = "_seed_voucher_check_schedule"
def ensure_default_voucher_check_schedule(
*,
commit: bool = True,
session: Any | None = None,
) -> ScheduleTask | None:
"""
幂等确保默认立账凭证检核日批排程存在。
Args:
commit: 是否立即提交。
session: 可选独立 Session。
Returns:
新建或已存在的 ScheduleTask;尚无用户时返回 None。
"""
sess = session if session is not None else db.session
existing = (
sess.query(ScheduleTask)
.filter(
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO)
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
)
.first()
)
if existing is not None:
return existing
owner = (
sess.query(User)
.filter(User.role == "admin")
.order_by(User.id.asc())
.first()
)
if owner is None:
owner = sess.query(User).order_by(User.id.asc()).first()
if owner is None:
_LOGGER.info("skip seed accounting-voucher-check schedule: no users yet")
return None
now = datetime.utcnow()
next_run = compute_next_run_at(
DEFAULT_VOUCHER_CHECK_CRON,
timezone_name="Asia/Shanghai",
) or now
task = ScheduleTask(
schedule_no=DEFAULT_VOUCHER_CHECK_SCHEDULE_NO,
name=DEFAULT_VOUCHER_CHECK_NAME,
schedule_type="platform_job",
owner_user_id=int(owner.id),
cron_expr=DEFAULT_VOUCHER_CHECK_CRON,
schedule_timezone="Asia/Shanghai",
wait_seconds=0,
platform_api_path=DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
job_params=dict(DEFAULT_JOB_PARAMS),
kb_sync_enabled=False,
notify_user_ids_json=[],
notify_enabled=True,
enabled=True,
next_run_at=next_run,
created_by=int(owner.id),
updated_by=int(owner.id),
created_at=now,
updated_at=now,
)
sess.add(task)
if commit:
try:
sess.commit()
except Exception:
sess.rollback()
existing = (
sess.query(ScheduleTask)
.filter(
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO)
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
)
.first()
)
if existing is not None:
return existing
raise
else:
sess.flush()
_LOGGER.info("seeded accounting-voucher-check schedule id=%s", task.id)
return task
def register_voucher_check_schedule_hooks() -> None:
"""注册 User after_commit 补建钩子(幂等)。"""
global _HOOKS_REGISTERED
if _HOOKS_REGISTERED:
return
@event.listens_for(Session, "after_commit")
def _after_commit(session: Session) -> None:
if not session.info.get(_SESSION_INFO_KEY):
return
session.info[_SESSION_INFO_KEY] = False
try:
from sqlalchemy.orm import sessionmaker
bind = session.get_bind()
factory = sessionmaker(bind=bind)
with factory() as new_sess:
ensure_default_voucher_check_schedule(commit=True, session=new_sess)
except Exception:
_LOGGER.exception("voucher-check schedule seed after_commit failed")
@event.listens_for(User, "after_insert")
def _user_after_insert(mapper, connection, target) -> None: # noqa: ARG001
sess = Session.object_session(target)
if sess is not None:
sess.info[_SESSION_INFO_KEY] = True
_HOOKS_REGISTERED = True
@@ -0,0 +1,273 @@
"""
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",
)