feat(invoice check): 立账凭证检核优化部分代码
This commit is contained in:
1 parent
21d41acf50
commit
d123d9cdf6
45 files changed
+498
-2508
No files matched your search
@@ -144,7 +144,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
run_contract_payment_alert_schedule,
|
||||
run_contract_payment_sync_schedule,
|
||||
)
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
|
||||
from app.services.schedule.contract_payment_job import (
|
||||
run_contract_payment_alert_schedule,
|
||||
run_contract_payment_sync_schedule,
|
||||
@@ -339,7 +339,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
label="立账凭证检核",
|
||||
label_key="admin.schedule.form.platformJobAccountingVoucherCheck",
|
||||
handler=run_voucher_check_schedule,
|
||||
description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。",
|
||||
description="每周二检核上一个自然月的销售开票附件,扫描文档库类型目录并按 invoice 归档。",
|
||||
description_key="admin.schedule.form.accountingVoucherCheckHint",
|
||||
category="finance",
|
||||
params_schema=(
|
||||
@@ -353,30 +353,12 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"options": [{"value": "HXJM", "label": "HXJM"}],
|
||||
},
|
||||
{
|
||||
"key": "directory_template",
|
||||
"key": "profile_code",
|
||||
"type": "text",
|
||||
"label": "目录模板",
|
||||
"label_key": "admin.schedule.form.voucherCheckDirTemplate",
|
||||
"label": "业务方 Profile",
|
||||
"label_key": "admin.schedule.form.voucherCheckProfile",
|
||||
"required": True,
|
||||
"default": "{root}/{YYYY}/{MM}/{invoice_no}",
|
||||
"help": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}",
|
||||
"help_key": "admin.schedule.form.voucherCheckDirTemplateHelp",
|
||||
},
|
||||
{
|
||||
"key": "required_files",
|
||||
"type": "json",
|
||||
"label": "必检材料",
|
||||
"label_key": "admin.schedule.form.voucherCheckRequiredFiles",
|
||||
"required": True,
|
||||
"default": DEFAULT_REQUIRED_FILES,
|
||||
},
|
||||
{
|
||||
"key": "filename_case_sensitive",
|
||||
"type": "boolean",
|
||||
"label": "文件名区分大小写",
|
||||
"label_key": "admin.schedule.form.voucherCheckCaseSensitive",
|
||||
"required": True,
|
||||
"default": True,
|
||||
"default": "sales",
|
||||
},
|
||||
{
|
||||
"key": "notify_missing_enabled",
|
||||
@@ -394,14 +376,6 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
{
|
||||
"key": "same_day_dedup_enabled",
|
||||
"type": "boolean",
|
||||
"label": "同票同日去重",
|
||||
"label_key": "admin.schedule.form.voucherCheckSameDayDedup",
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
),
|
||||
defaults=dict(DEFAULT_JOB_PARAMS),
|
||||
))
|
||||
|
||||
@@ -6,7 +6,7 @@ backend/app/services/schedule/scheduler_service.py
|
||||
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
|
||||
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
|
||||
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler;
|
||||
handler 抛错时 failed_count=1,排程记 failed。
|
||||
handler 抛错时 failed_count=1、排程记 failed,并把 error= 打进 worker 日志。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -493,7 +493,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
"""
|
||||
立即执行一条排程并写入 ScheduleRun 终态。
|
||||
|
||||
核心逻辑:handler 未捕获异常记 failed_count=1,避免配置错误被标成 success。
|
||||
核心逻辑:handler 未捕获异常记 failed_count=1,避免配置错误被标成 success;
|
||||
该路径原先只写库不打日志,worker 汇总行看不到失败原因。
|
||||
"""
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
@@ -531,6 +532,14 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
except Exception as exc:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 1, 0, [], [str(exc)]
|
||||
step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}]
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[schedule-run] executor failed name=%s path=%s run_no=%s error=%s",
|
||||
task.name,
|
||||
task.platform_api_path,
|
||||
run.run_no,
|
||||
exc,
|
||||
)
|
||||
|
||||
try:
|
||||
db.session.refresh(run)
|
||||
@@ -565,8 +574,9 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
|
||||
duration_ms = int((time.time() - start_ts) * 1000)
|
||||
if current_app:
|
||||
error_preview = "; ".join(str(item) for item in (errors or [])[:3])
|
||||
current_app.logger.info(
|
||||
"[schedule-run] name=%s path=%s run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d",
|
||||
"[schedule-run] name=%s path=%s run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d error=%s",
|
||||
task.name,
|
||||
task.platform_api_path,
|
||||
run.run_no,
|
||||
@@ -574,7 +584,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
success_count,
|
||||
failed_count,
|
||||
skipped_count,
|
||||
len(errors),
|
||||
len(errors or []),
|
||||
error_preview or "-",
|
||||
)
|
||||
if total_count == 0 and not errors:
|
||||
status = "success"
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/__init__.py
|
||||
|
||||
用途:立账凭证检核领域服务包入口。
|
||||
依赖:config / runner / query_service 等子模块。
|
||||
逻辑:platform Job 与 Tool/工作台 API 从此包调用 runner 与查询能力。
|
||||
逻辑:platform Job 与工作台 API 从此包调用 runner 与查询能力。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.runner import run_voucher_check_batch
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/config.py
|
||||
|
||||
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params,校验目录模板与文件名规则。
|
||||
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params。
|
||||
依赖:Flask current_app.config、core.errors.ValidationError。
|
||||
逻辑:runner / share_scanner / erp_repository / 新引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
|
||||
逻辑:runner / erp_repository / 引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
|
||||
ERP 账号优先 VOUCHER_CHECK_ERP_*,否则 ERP_*,再回退 CONTRACT_PAYMENT_ERP_*。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
@@ -19,70 +17,17 @@ from flask import has_app_context, current_app
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
_ALLOWED_TEMPLATE_KEYS = {"root", "YYYY", "MM", "invoice_no"}
|
||||
_TEMPLATE_TOKEN_RE = re.compile(r"\{([^{}]+)\}")
|
||||
_UNSAFE_FILENAME_RE = re.compile(r"[/\\\x00]|(\.\.)")
|
||||
|
||||
DEFAULT_REQUIRED_FILES: list[dict[str, Any]] = [
|
||||
{
|
||||
"code": "price_check_sheet",
|
||||
"name": "核价单",
|
||||
"required": True,
|
||||
"accepted_filenames": ["核价单.pdf"],
|
||||
},
|
||||
{
|
||||
"code": "purchase_order",
|
||||
"name": "采购单",
|
||||
"required": True,
|
||||
"accepted_filenames": ["采购单.pdf"],
|
||||
},
|
||||
]
|
||||
|
||||
DEFAULT_JOB_PARAMS: dict[str, Any] = {
|
||||
"profile_code": "sales",
|
||||
"scope_code": "HXJM",
|
||||
"directory_template": "{root}/{YYYY}/{MM}/{invoice_no}",
|
||||
"required_files": DEFAULT_REQUIRED_FILES,
|
||||
"filename_case_sensitive": True,
|
||||
"notify_missing_enabled": True,
|
||||
"notify_failure_enabled": True,
|
||||
"same_day_dedup_enabled": False,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RequiredFileRule:
|
||||
"""单条必检材料规则。"""
|
||||
|
||||
code: str
|
||||
name: str
|
||||
required: bool
|
||||
accepted_filenames: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VoucherCheckConfig:
|
||||
"""运行期检核配置快照。"""
|
||||
|
||||
scope_code: str
|
||||
directory_template: str
|
||||
required_files: tuple[RequiredFileRule, ...]
|
||||
filename_case_sensitive: bool
|
||||
notify_missing_enabled: bool
|
||||
notify_failure_enabled: bool
|
||||
same_day_dedup_enabled: bool
|
||||
local_root: str
|
||||
share_unc: str
|
||||
healthcheck_relative_path: str
|
||||
erp_dsn: str
|
||||
erp_username: str
|
||||
erp_password: str
|
||||
erp_timeout_seconds: int = 30
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VoucherCheckEngineConfig:
|
||||
"""销售一期引擎运行配置:ERP + 通知开关,不再依赖共享盘。"""
|
||||
"""销售一期引擎运行配置:ERP + 通知开关。"""
|
||||
|
||||
scope_code: str
|
||||
profile_code: str
|
||||
@@ -115,75 +60,6 @@ def _as_bool(value: Any, default: bool) -> bool:
|
||||
return default
|
||||
|
||||
|
||||
def _parse_required_files(raw: Any) -> list[RequiredFileRule]:
|
||||
if raw is None:
|
||||
raw = DEFAULT_REQUIRED_FILES
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise _config_invalid("required_files JSON 非法", details={"error": str(exc)}) from exc
|
||||
if not isinstance(raw, list) or not raw:
|
||||
raise _config_invalid("required_files 至少包含一个必检项")
|
||||
|
||||
rules: list[RequiredFileRule] = []
|
||||
for idx, item in enumerate(raw):
|
||||
if not isinstance(item, dict):
|
||||
raise _config_invalid(f"required_files[{idx}] 必须为对象")
|
||||
code = str(item.get("code") or "").strip()
|
||||
name = str(item.get("name") or code).strip()
|
||||
accepted = item.get("accepted_filenames") or []
|
||||
if not code:
|
||||
raise _config_invalid(f"required_files[{idx}].code 不能为空")
|
||||
if not isinstance(accepted, list) or not accepted:
|
||||
raise _config_invalid(f"required_files[{idx}].accepted_filenames 不能为空")
|
||||
filenames: list[str] = []
|
||||
for fname in accepted:
|
||||
text = str(fname or "").strip()
|
||||
if not text:
|
||||
raise _config_invalid(f"required_files[{idx}] 存在空文件名")
|
||||
if "*" in text or "?" in text or _UNSAFE_FILENAME_RE.search(text):
|
||||
raise _config_invalid(
|
||||
f"required_files[{idx}] 文件名禁止通配/路径字符: {text}",
|
||||
)
|
||||
filenames.append(text)
|
||||
rules.append(
|
||||
RequiredFileRule(
|
||||
code=code,
|
||||
name=name or code,
|
||||
required=_as_bool(item.get("required"), True),
|
||||
accepted_filenames=tuple(filenames),
|
||||
)
|
||||
)
|
||||
if not any(r.required for r in rules):
|
||||
raise _config_invalid("required_files 至少包含一个 required=true 项")
|
||||
return rules
|
||||
|
||||
|
||||
def validate_directory_template(template: str) -> str:
|
||||
"""
|
||||
校验目录模板占位符。
|
||||
核心逻辑:仅允许 {root}/{YYYY}/{MM}/{invoice_no} 四类占位符,且四者皆须出现。
|
||||
"""
|
||||
text = str(template or "").strip().replace("\\", "/")
|
||||
if not text:
|
||||
raise _config_invalid("directory_template 不能为空")
|
||||
tokens = _TEMPLATE_TOKEN_RE.findall(text)
|
||||
unknown = sorted({t for t in tokens if t not in _ALLOWED_TEMPLATE_KEYS})
|
||||
if unknown:
|
||||
raise _config_invalid(
|
||||
"directory_template 含非法占位符",
|
||||
details={"unknown": unknown},
|
||||
)
|
||||
missing = sorted(_ALLOWED_TEMPLATE_KEYS - set(tokens))
|
||||
if missing:
|
||||
raise _config_invalid(
|
||||
"directory_template 缺少必要占位符",
|
||||
details={"missing": missing},
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
def _erp_settings() -> tuple[str, str, str, int]:
|
||||
"""
|
||||
读取 ERP 只读连接;密码只来自环境/配置,不写日志。
|
||||
@@ -228,65 +104,6 @@ def _erp_settings() -> tuple[str, str, str, int]:
|
||||
return erp_dsn, erp_username, erp_password, max(1, timeout)
|
||||
|
||||
|
||||
def load_voucher_check_config(job_params: dict[str, Any] | None = None) -> VoucherCheckConfig:
|
||||
"""
|
||||
合并 env 与 job_params,返回校验后的检核配置。
|
||||
核心逻辑:敏感凭据只读环境变量;业务规则以 job_params 为准,缺省用 DEFAULT_JOB_PARAMS。
|
||||
"""
|
||||
params = dict(DEFAULT_JOB_PARAMS)
|
||||
if isinstance(job_params, dict):
|
||||
params.update({k: v for k, v in job_params.items() if v is not None})
|
||||
|
||||
scope_code = str(params.get("scope_code") or "HXJM").strip().upper() or "HXJM"
|
||||
if scope_code != "HXJM":
|
||||
raise _config_invalid("一期仅支持 scope_code=HXJM", details={"scope_code": scope_code})
|
||||
|
||||
template = validate_directory_template(
|
||||
str(params.get("directory_template") or DEFAULT_JOB_PARAMS["directory_template"])
|
||||
)
|
||||
required_files = _parse_required_files(params.get("required_files"))
|
||||
|
||||
cfg = current_app.config if has_app_context() else {}
|
||||
local_root = str(
|
||||
cfg.get("VOUCHER_CHECK_LOCAL_ROOT")
|
||||
or os.getenv("VOUCHER_CHECK_LOCAL_ROOT")
|
||||
or ""
|
||||
).strip()
|
||||
share_unc = str(
|
||||
cfg.get("VOUCHER_CHECK_SHARE_UNC")
|
||||
or os.getenv("VOUCHER_CHECK_SHARE_UNC")
|
||||
or ""
|
||||
).strip()
|
||||
healthcheck = str(
|
||||
cfg.get("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH")
|
||||
or os.getenv("VOUCHER_CHECK_SHARE_HEALTHCHECK_RELATIVE_PATH")
|
||||
or ".hxops-share-ready"
|
||||
).strip() or ".hxops-share-ready"
|
||||
|
||||
# 开发机可临时用 UNC;Linux/容器必须 LOCAL_ROOT
|
||||
if not local_root and not share_unc:
|
||||
raise _config_invalid("未配置 VOUCHER_CHECK_LOCAL_ROOT 或 VOUCHER_CHECK_SHARE_UNC")
|
||||
|
||||
erp_dsn, erp_username, erp_password, timeout = _erp_settings()
|
||||
|
||||
return VoucherCheckConfig(
|
||||
scope_code=scope_code,
|
||||
directory_template=template,
|
||||
required_files=tuple(required_files),
|
||||
filename_case_sensitive=_as_bool(params.get("filename_case_sensitive"), True),
|
||||
notify_missing_enabled=_as_bool(params.get("notify_missing_enabled"), True),
|
||||
notify_failure_enabled=_as_bool(params.get("notify_failure_enabled"), True),
|
||||
same_day_dedup_enabled=_as_bool(params.get("same_day_dedup_enabled"), True),
|
||||
local_root=local_root,
|
||||
share_unc=share_unc,
|
||||
healthcheck_relative_path=healthcheck,
|
||||
erp_dsn=erp_dsn,
|
||||
erp_username=erp_username,
|
||||
erp_password=erp_password,
|
||||
erp_timeout_seconds=max(1, timeout),
|
||||
)
|
||||
|
||||
|
||||
def load_engine_config(job_params: dict[str, Any] | None = None) -> VoucherCheckEngineConfig:
|
||||
"""
|
||||
加载销售一期引擎配置。
|
||||
@@ -310,14 +127,3 @@ def load_engine_config(job_params: dict[str, Any] | None = None) -> VoucherCheck
|
||||
erp_password=erp_password,
|
||||
erp_timeout_seconds=timeout,
|
||||
)
|
||||
|
||||
|
||||
def resolve_share_root(config: VoucherCheckConfig) -> str:
|
||||
"""
|
||||
解析实际扫描根路径。
|
||||
核心逻辑:优先 LOCAL_ROOT(容器/Linux);无则回退 share_unc(开发机)。
|
||||
"""
|
||||
root = (config.local_root or config.share_unc or "").strip()
|
||||
if not root:
|
||||
raise _config_invalid("共享盘根路径为空")
|
||||
return root
|
||||
@@ -13,7 +13,7 @@ from datetime import date, datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.config import VoucherCheckConfig
|
||||
from app.services.voucher_check.config import VoucherCheckEngineConfig
|
||||
|
||||
_TZ = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
@@ -40,7 +40,7 @@ class ErpInvoiceRow:
|
||||
def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
|
||||
"""
|
||||
按 Asia/Shanghai 计算当前自然月起止。
|
||||
核心逻辑:不用 Oracle SYSDATE,保证手动触发与日批口径一致。
|
||||
核心逻辑:不用 Oracle SYSDATE,作为 previous_period_bounds 的基准。
|
||||
|
||||
Returns:
|
||||
(period_month_first, next_month_first, period_start_dt, next_period_start_dt)
|
||||
@@ -80,7 +80,7 @@ def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, dat
|
||||
|
||||
|
||||
def fetch_month_invoices(
|
||||
config: VoucherCheckConfig,
|
||||
config: VoucherCheckEngineConfig,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> tuple[date, list[ErpInvoiceRow]]:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/fingerprint.py
|
||||
|
||||
用途:根据共享盘目录直接子文件的元数据生成稳定 SHA-256 指纹。
|
||||
用途:根据文件名与元数据生成稳定 SHA-256 指纹。
|
||||
依赖:标准库 hashlib / json。
|
||||
逻辑:share_scanner 枚举文件后调用;runner 用指纹判断齐全票是否可跳过。
|
||||
逻辑:DMS 目录扫描与 HXJM 主体 Adapter 调用,供增量跳过比对。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,316 +0,0 @@
|
||||
{
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "HXOPS Accounting Voucher Check Tool API",
|
||||
"description": "立账凭证检核查询 Tool API:缺资料清单、批次明细、单票最新状态。启动检核请复用 File Check 的 run_file_check(可传 run_options)。鉴权:Authorization Bearer 或 X-Integration-Key(与 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY 相同)。",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"url": "http://127.0.0.1:5052",
|
||||
"description": "HXOPS_TOOLS_API_BASE"
|
||||
}
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
},
|
||||
{
|
||||
"IntegrationKey": []
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/api/accounting-voucher-check/tools/tasks/{task_id}/missing": {
|
||||
"get": {
|
||||
"operationId": "list_voucher_missing",
|
||||
"summary": "查询缺资料发票(最新状态)",
|
||||
"description": "按账套与月份查询 status=missing 的发票;默认当前自然月。",
|
||||
"tags": ["Accounting Voucher Check"],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "integer", "example": 12 },
|
||||
"description": "排程任务 ID(Agent 绑定的 schedule_task_id,用于回显)"
|
||||
},
|
||||
{
|
||||
"name": "period",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "string", "example": "2026-08" },
|
||||
"description": "检核月份 YYYY-MM;缺省为当前自然月"
|
||||
},
|
||||
{
|
||||
"name": "scope_code",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "string", "default": "HXJM", "example": "HXJM" }
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "integer", "default": 200, "minimum": 1, "maximum": 1000 }
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/MissingListResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": { "$ref": "#/components/responses/BadRequest" },
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"503": { "$ref": "#/components/responses/MissingAuth" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/accounting-voucher-check/tools/runs/{run_id}/items": {
|
||||
"get": {
|
||||
"operationId": "list_voucher_run_items",
|
||||
"summary": "查询批次发票明细",
|
||||
"description": "分页返回某 ScheduleRun 的单票结论;可按 result 过滤。",
|
||||
"tags": ["Accounting Voucher Check"],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "run_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "integer", "example": 1001 }
|
||||
},
|
||||
{
|
||||
"name": "result",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": ["complete", "missing", "skipped", "technical_error"],
|
||||
"example": "missing"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "page",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "integer", "default": 1, "minimum": 1 }
|
||||
},
|
||||
{
|
||||
"name": "page_size",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "integer", "default": 50, "minimum": 1, "maximum": 200 }
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/RunItemsResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/NotFound" },
|
||||
"503": { "$ref": "#/components/responses/MissingAuth" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest": {
|
||||
"get": {
|
||||
"operationId": "get_voucher_invoice_latest",
|
||||
"summary": "查询指定发票最新检核状态",
|
||||
"description": "返回单票最新状态及近期批次快照;invoice_no 保持业务原值(仅 trim)。",
|
||||
"tags": ["Accounting Voucher Check"],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "invoice_no",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "string", "example": "INV-20260803001" },
|
||||
"description": "发票号(apa08 原值)"
|
||||
},
|
||||
{
|
||||
"name": "period",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "string", "example": "2026-08" }
|
||||
},
|
||||
{
|
||||
"name": "scope_code",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "string", "default": "HXJM" }
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/InvoiceLatestResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": { "$ref": "#/components/responses/BadRequest" },
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/NotFound" },
|
||||
"503": { "$ref": "#/components/responses/MissingAuth" }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"securitySchemes": {
|
||||
"BearerAuth": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"description": "Authorization: Bearer <FILE_CHECK_TOOL_API_KEY 或 INTEGRATION_API_KEY>"
|
||||
},
|
||||
"IntegrationKey": {
|
||||
"type": "apiKey",
|
||||
"in": "header",
|
||||
"name": "X-Integration-Key",
|
||||
"description": "与 Bearer 二选一"
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"MissingMaterial": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": { "type": "string", "example": "price_check_sheet" },
|
||||
"name": { "type": "string", "example": "核价单" }
|
||||
}
|
||||
},
|
||||
"InvoiceState": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": { "type": "integer" },
|
||||
"scope_code": { "type": "string" },
|
||||
"period_month": { "type": "string", "nullable": true },
|
||||
"invoice_no": { "type": "string" },
|
||||
"invoice_date": { "type": "string", "nullable": true },
|
||||
"status": { "type": "string", "enum": ["complete", "missing"] },
|
||||
"folder_path": { "type": "string", "nullable": true },
|
||||
"folder_exists": { "type": "boolean" },
|
||||
"matched_files": { "type": "object", "additionalProperties": { "type": "string" } },
|
||||
"missing_materials": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/MissingMaterial" }
|
||||
},
|
||||
"last_checked_at": { "type": "string", "nullable": true }
|
||||
}
|
||||
},
|
||||
"MissingListResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "items", "count"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"task_id": { "type": "integer", "nullable": true },
|
||||
"scope_code": { "type": "string" },
|
||||
"period": { "type": "string", "example": "2026-08" },
|
||||
"count": { "type": "integer" },
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/InvoiceState" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunItem": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": { "type": "integer" },
|
||||
"schedule_run_id": { "type": "integer" },
|
||||
"invoice_no": { "type": "string" },
|
||||
"result": {
|
||||
"type": "string",
|
||||
"enum": ["complete", "missing", "skipped", "technical_error"]
|
||||
},
|
||||
"folder_path": { "type": "string", "nullable": true },
|
||||
"matched_files": { "type": "object", "additionalProperties": { "type": "string" } },
|
||||
"missing_materials": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/MissingMaterial" }
|
||||
},
|
||||
"error_code": { "type": "string", "nullable": true },
|
||||
"error_message": { "type": "string", "nullable": true }
|
||||
}
|
||||
},
|
||||
"RunItemsResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "items", "total"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean" },
|
||||
"run_id": { "type": "integer" },
|
||||
"run_no": { "type": "string" },
|
||||
"page": { "type": "integer" },
|
||||
"page_size": { "type": "integer" },
|
||||
"total": { "type": "integer" },
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/RunItem" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"InvoiceLatestResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "state"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean" },
|
||||
"state": { "$ref": "#/components/schemas/InvoiceState" },
|
||||
"recent_run_items": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/RunItem" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"ToolError": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": false },
|
||||
"error_code": { "type": "string" },
|
||||
"message": { "type": "string" },
|
||||
"details": { "type": "object" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"BadRequest": {
|
||||
"description": "参数错误",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ToolError" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"Unauthorized": {
|
||||
"description": "鉴权失败",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ToolError" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"NotFound": {
|
||||
"description": "资源不存在",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ToolError" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"MissingAuth": {
|
||||
"description": "服务端未配置 Tool API Key",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ToolError" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/openapi_spec.py
|
||||
|
||||
用途:构建立账凭证检核 Chatflow 查询 Tool 的 OpenAPI 3.0 规范。
|
||||
依赖:openapi_base.json。
|
||||
逻辑:GET /api/accounting-voucher-check/tools/openapi.json 调用本模块;Dify URL 导入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
_BASE_SPEC_PATH = Path(__file__).with_name("openapi_base.json")
|
||||
|
||||
|
||||
def _load_base_spec() -> dict[str, Any]:
|
||||
with _BASE_SPEC_PATH.open("r", encoding="utf-8") as fp:
|
||||
return json.load(fp)
|
||||
|
||||
|
||||
def build_voucher_check_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"""
|
||||
构建立账凭证检核 Tool OpenAPI。
|
||||
核心逻辑:深拷贝静态规格,并将 servers[0].url 替换为当前 HXOPS_TOOLS_API_BASE。
|
||||
"""
|
||||
spec = copy.deepcopy(_load_base_spec())
|
||||
base = str(base_url or "").strip().rstrip("/")
|
||||
servers = spec.get("servers")
|
||||
if base and isinstance(servers, list) and servers:
|
||||
servers[0]["url"] = base
|
||||
servers[0]["description"] = "HXOPS_TOOLS_API_BASE"
|
||||
return spec
|
||||
@@ -1,126 +0,0 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/persistence.py
|
||||
|
||||
用途:立账凭证检核单票状态与批次明细的事务写入。
|
||||
依赖:models.voucher_check、ScheduleRun、SQLAlchemy session。
|
||||
逻辑:runner 阶段 B 调用;skipped 只更新 last_seen_erp_at;批次级失败不进入本模块。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
|
||||
|
||||
|
||||
def persist_batch_results(
|
||||
*,
|
||||
schedule_run_id: int,
|
||||
scope_code: str,
|
||||
period_month: date,
|
||||
items: list[dict[str, Any]],
|
||||
now: datetime | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
单事务写入批次明细并 upsert 最新状态。
|
||||
核心逻辑:先写 run_items;非 skipped/technical_error 再 upsert states;
|
||||
skipped 仅刷新 last_seen_erp_at。
|
||||
|
||||
Args:
|
||||
schedule_run_id: ScheduleRun.id
|
||||
scope_code: 账套
|
||||
period_month: 当月首日
|
||||
items: 内存中的结果行(含 result / fingerprint / missing 等)
|
||||
now: 可选时钟
|
||||
"""
|
||||
ts = now or datetime.utcnow()
|
||||
for item in items:
|
||||
invoice_no = str(item["invoice_no"]).strip()
|
||||
result = str(item["result"])
|
||||
run_item = VoucherCheckRunItem(
|
||||
schedule_run_id=schedule_run_id,
|
||||
scope_code=scope_code,
|
||||
period_month=period_month,
|
||||
invoice_no=invoice_no,
|
||||
invoice_date=item.get("invoice_date"),
|
||||
result=result,
|
||||
folder_path=item.get("folder_path"),
|
||||
folder_exists=bool(item.get("folder_exists")),
|
||||
material_fingerprint=item.get("material_fingerprint"),
|
||||
matched_files_json=item.get("matched_files") or {},
|
||||
missing_materials_json=item.get("missing_materials") or [],
|
||||
error_code=item.get("error_code"),
|
||||
error_message=item.get("error_message"),
|
||||
checked_at=item.get("checked_at"),
|
||||
created_at=ts,
|
||||
)
|
||||
db.session.add(run_item)
|
||||
|
||||
state = (
|
||||
db.session.query(VoucherCheckInvoiceState)
|
||||
.filter_by(
|
||||
scope_code=scope_code,
|
||||
period_month=period_month,
|
||||
invoice_no=invoice_no,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
if state is None:
|
||||
state = VoucherCheckInvoiceState(
|
||||
scope_code=scope_code,
|
||||
period_month=period_month,
|
||||
invoice_no=invoice_no,
|
||||
created_at=ts,
|
||||
)
|
||||
db.session.add(state)
|
||||
|
||||
state.last_seen_erp_at = ts
|
||||
state.invoice_date = item.get("invoice_date") or state.invoice_date
|
||||
state.updated_at = ts
|
||||
|
||||
if result == "skipped":
|
||||
# 跳过:不改写齐全结论与实际扫描时间
|
||||
continue
|
||||
if result == "technical_error":
|
||||
continue
|
||||
|
||||
state.status = "complete" if result == "complete" else "missing"
|
||||
state.folder_path = item.get("folder_path")
|
||||
state.folder_exists = bool(item.get("folder_exists"))
|
||||
state.material_fingerprint = item.get("material_fingerprint")
|
||||
state.matched_files_json = item.get("matched_files") or {}
|
||||
state.missing_materials_json = item.get("missing_materials") or []
|
||||
state.last_actual_run_id = schedule_run_id
|
||||
state.last_checked_at = item.get("checked_at") or ts
|
||||
|
||||
db.session.flush()
|
||||
run_item.invoice_state_id = state.id
|
||||
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def mark_missing_notified(
|
||||
*,
|
||||
scope_code: str,
|
||||
period_month: date,
|
||||
invoice_nos: list[str],
|
||||
notified_on: date,
|
||||
) -> None:
|
||||
"""发送缺资料通知成功后更新同票同日节流字段。"""
|
||||
if not invoice_nos:
|
||||
return
|
||||
states = (
|
||||
db.session.query(VoucherCheckInvoiceState)
|
||||
.filter(
|
||||
VoucherCheckInvoiceState.scope_code == scope_code,
|
||||
VoucherCheckInvoiceState.period_month == period_month,
|
||||
VoucherCheckInvoiceState.invoice_no.in_(invoice_nos),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for state in states:
|
||||
state.last_missing_notified_on = notified_on
|
||||
state.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/query_service.py
|
||||
|
||||
用途:查询检核批次列表、批次明细、兼容旧状态表,以及工作台强制重检入队。
|
||||
用途:查询检核批次列表、批次明细、企微发送记录,以及工作台强制重检入队。
|
||||
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。
|
||||
逻辑:优先读新引擎表;明细同时返回 invoice 行与 by_file_type;工作台可查企微发送记录;无引擎批次时回退旧 run_items / invoice_states;强制重检写入 run_options.mode=force_all。
|
||||
逻辑:只读引擎表;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,62 +15,13 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.models.voucher_check import (
|
||||
VoucherCheckFileResult,
|
||||
VoucherCheckInvoiceState,
|
||||
VoucherCheckNotification,
|
||||
VoucherCheckRun,
|
||||
VoucherCheckRunItem,
|
||||
)
|
||||
from app.services.voucher_check.aggregator import aggregate_file_results
|
||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||
|
||||
|
||||
def _serialize_state(state: VoucherCheckInvoiceState) -> dict[str, Any]:
|
||||
return {
|
||||
"id": state.id,
|
||||
"scope_code": state.scope_code,
|
||||
"period_month": state.period_month.isoformat() if state.period_month else None,
|
||||
"invoice_no": state.invoice_no,
|
||||
"invoice_date": state.invoice_date.isoformat() if state.invoice_date else None,
|
||||
"status": state.status,
|
||||
"folder_path": state.folder_path,
|
||||
"folder_exists": state.folder_exists,
|
||||
"material_fingerprint": state.material_fingerprint,
|
||||
"matched_files": state.matched_files_json or {},
|
||||
"missing_materials": state.missing_materials_json or [],
|
||||
"last_actual_run_id": state.last_actual_run_id,
|
||||
"last_checked_at": state.last_checked_at.isoformat() if state.last_checked_at else None,
|
||||
"last_seen_erp_at": state.last_seen_erp_at.isoformat() if state.last_seen_erp_at else None,
|
||||
"last_missing_notified_on": (
|
||||
state.last_missing_notified_on.isoformat() if state.last_missing_notified_on else None
|
||||
),
|
||||
"updated_at": state.updated_at.isoformat() if state.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_run_item(item: VoucherCheckRunItem) -> dict[str, Any]:
|
||||
"""序列化旧批次 invoice 行,并带上缺件数量便于明细表展示。"""
|
||||
return {
|
||||
"id": item.id,
|
||||
"schedule_run_id": item.schedule_run_id,
|
||||
"invoice_state_id": item.invoice_state_id,
|
||||
"scope_code": item.scope_code,
|
||||
"period_month": item.period_month.isoformat() if item.period_month else None,
|
||||
"invoice_no": item.invoice_no,
|
||||
"invoice_date": item.invoice_date.isoformat() if item.invoice_date else None,
|
||||
"result": item.result,
|
||||
"folder_path": item.folder_path,
|
||||
"folder_exists": item.folder_exists,
|
||||
"material_fingerprint": item.material_fingerprint,
|
||||
"matched_files": item.matched_files_json or {},
|
||||
"missing_materials": item.missing_materials_json or [],
|
||||
"missing_count": len(item.missing_materials_json or []),
|
||||
"error_code": item.error_code,
|
||||
"error_message": item.error_message,
|
||||
"checked_at": item.checked_at.isoformat() if item.checked_at else None,
|
||||
"created_at": item.created_at.isoformat() if item.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def parse_period_month(raw: str | None) -> date:
|
||||
"""解析 YYYY-MM 或 YYYY-MM-DD 为当月首日;空则取上一个自然月。"""
|
||||
if not raw:
|
||||
@@ -90,38 +41,6 @@ def parse_period_month(raw: str | None) -> date:
|
||||
) from exc
|
||||
|
||||
|
||||
def list_missing_states(
|
||||
*,
|
||||
task_id: int | None = None,
|
||||
scope_code: str = "HXJM",
|
||||
period: str | None = None,
|
||||
limit: int = 200,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询指定月份缺资料票(最新状态表)。
|
||||
task_id 预留与排程绑定校验,本期仅用于响应回显。
|
||||
"""
|
||||
period_month = parse_period_month(period)
|
||||
limit = max(1, min(int(limit or 200), 1000))
|
||||
q = (
|
||||
VoucherCheckInvoiceState.query.filter_by(
|
||||
scope_code=scope_code,
|
||||
period_month=period_month,
|
||||
status="missing",
|
||||
)
|
||||
.order_by(VoucherCheckInvoiceState.invoice_no.asc())
|
||||
.limit(limit)
|
||||
)
|
||||
items = [_serialize_state(s) for s in q.all()]
|
||||
return {
|
||||
"task_id": task_id,
|
||||
"scope_code": scope_code,
|
||||
"period": period_month.strftime("%Y-%m"),
|
||||
"count": len(items),
|
||||
"items": items,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_engine_run(run: VoucherCheckRun) -> dict[str, Any]:
|
||||
return {
|
||||
"id": run.id,
|
||||
@@ -314,7 +233,7 @@ def list_run_items(
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""分页查询批次明细;优先返回新引擎按 invoice 聚合行,并附带按文件类型汇总。"""
|
||||
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。"""
|
||||
run = ScheduleRun.query.get(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||
@@ -325,117 +244,33 @@ def list_run_items(
|
||||
.order_by(VoucherCheckRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if engine_run is not None:
|
||||
items, aggregated = _engine_invoice_items(engine_run)
|
||||
result_filter = str(result).strip() if result else ""
|
||||
if result_filter:
|
||||
items = [row for row in items if row.get("result") == result_filter]
|
||||
total = len(items)
|
||||
sliced = items[(page - 1) * page_size : page * page_size]
|
||||
if engine_run is None:
|
||||
return {
|
||||
"run_id": run_id,
|
||||
"engine_run_id": engine_run.id,
|
||||
"run_no": run.run_no,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total": total,
|
||||
"items": sliced,
|
||||
"subject_count": int(aggregated.get("subject_count") or 0),
|
||||
"by_file_type": _serialize_file_type_rows(aggregated),
|
||||
"total": 0,
|
||||
"items": [],
|
||||
"subject_count": 0,
|
||||
"by_file_type": [],
|
||||
}
|
||||
q = VoucherCheckRunItem.query.filter_by(schedule_run_id=run_id)
|
||||
if result:
|
||||
q = q.filter(VoucherCheckRunItem.result == str(result).strip())
|
||||
total = q.count()
|
||||
rows = (
|
||||
q.order_by(VoucherCheckRunItem.invoice_no.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
items, aggregated = _engine_invoice_items(engine_run)
|
||||
result_filter = str(result).strip() if result else ""
|
||||
if result_filter:
|
||||
items = [row for row in items if row.get("result") == result_filter]
|
||||
total = len(items)
|
||||
sliced = items[(page - 1) * page_size : page * page_size]
|
||||
return {
|
||||
"run_id": run_id,
|
||||
"engine_run_id": engine_run.id,
|
||||
"run_no": run.run_no,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total": total,
|
||||
"items": [_serialize_run_item(r) for r in rows],
|
||||
"subject_count": 0,
|
||||
"by_file_type": [],
|
||||
}
|
||||
|
||||
|
||||
def get_invoice_latest(
|
||||
*,
|
||||
invoice_no: str,
|
||||
scope_code: str = "HXJM",
|
||||
period: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""查询单票最新状态及近期批次快照。"""
|
||||
inv = str(invoice_no or "").strip()
|
||||
if not inv:
|
||||
raise ValidationError("invoice_no 必填", code="VOUCHER_CHECK.INVOICE_REQUIRED")
|
||||
period_month = parse_period_month(period)
|
||||
state = (
|
||||
VoucherCheckInvoiceState.query.filter_by(
|
||||
scope_code=scope_code,
|
||||
period_month=period_month,
|
||||
invoice_no=inv,
|
||||
).one_or_none()
|
||||
)
|
||||
if not state:
|
||||
raise NotFoundError("发票状态不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||
history = (
|
||||
VoucherCheckRunItem.query.filter_by(
|
||||
scope_code=scope_code,
|
||||
period_month=period_month,
|
||||
invoice_no=inv,
|
||||
)
|
||||
.order_by(VoucherCheckRunItem.id.desc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"state": _serialize_state(state),
|
||||
"recent_run_items": [_serialize_run_item(h) for h in history],
|
||||
}
|
||||
|
||||
|
||||
def list_states(
|
||||
*,
|
||||
scope_code: str = "HXJM",
|
||||
period: str | None = None,
|
||||
status: str | None = None,
|
||||
invoice_no: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""工作台:按月/状态/发票号筛选最新状态。"""
|
||||
period_month = parse_period_month(period)
|
||||
page = max(1, int(page or 1))
|
||||
page_size = max(1, min(int(page_size or 50), 200))
|
||||
q = VoucherCheckInvoiceState.query.filter_by(
|
||||
scope_code=scope_code,
|
||||
period_month=period_month,
|
||||
)
|
||||
if status:
|
||||
q = q.filter(VoucherCheckInvoiceState.status == str(status).strip())
|
||||
if invoice_no:
|
||||
q = q.filter(VoucherCheckInvoiceState.invoice_no.ilike(f"%{str(invoice_no).strip()}%"))
|
||||
total = q.count()
|
||||
rows = (
|
||||
q.order_by(VoucherCheckInvoiceState.invoice_no.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"scope_code": scope_code,
|
||||
"period": period_month.strftime("%Y-%m"),
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total": total,
|
||||
"items": [_serialize_state(r) for r in rows],
|
||||
"items": sliced,
|
||||
"subject_count": int(aggregated.get("subject_count") or 0),
|
||||
"by_file_type": _serialize_file_type_rows(aggregated),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/schedule_seed.py
|
||||
|
||||
用途:确保 accounting-voucher-check 默认周批 ScheduleTask 存在(周二 06:00 Asia/Shanghai)。
|
||||
依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建;已存在的日批默认任务会改成周二。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建;已存在的日批改成周二,并剥离 schema 外的旧 job_params。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,6 +14,7 @@ from typing import Any
|
||||
|
||||
from sqlalchemy import event
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
@@ -31,13 +32,33 @@ _HOOKS_REGISTERED = False
|
||||
_SESSION_INFO_KEY = "_seed_voucher_check_schedule"
|
||||
|
||||
|
||||
def _normalize_existing_job_params(raw: Any) -> tuple[dict[str, Any], bool]:
|
||||
"""
|
||||
把已有排程的 job_params 收成当前 schema。
|
||||
核心逻辑:保留 DEFAULT_JOB_PARAMS 与 _advanced;丢掉共享盘时代的未知字段。
|
||||
"""
|
||||
from app.services.schedule.job_params import ADVANCED_PARAMS_KEY
|
||||
|
||||
current = dict(raw) if isinstance(raw, dict) else {}
|
||||
cleaned: dict[str, Any] = {}
|
||||
for key, default in DEFAULT_JOB_PARAMS.items():
|
||||
value = current.get(key)
|
||||
cleaned[key] = default if value is None else value
|
||||
advanced = current.get(ADVANCED_PARAMS_KEY)
|
||||
if isinstance(advanced, dict):
|
||||
cleaned[ADVANCED_PARAMS_KEY] = advanced
|
||||
return cleaned, current != cleaned
|
||||
|
||||
|
||||
def ensure_default_voucher_check_schedule(
|
||||
*,
|
||||
commit: bool = True,
|
||||
session: Any | None = None,
|
||||
) -> ScheduleTask | None:
|
||||
"""
|
||||
幂等确保默认立账凭证检核日批排程存在。
|
||||
幂等确保默认立账凭证检核周批排程存在。
|
||||
核心逻辑:已存在任务会把日批 cron 改成周二,并剥离 schema 外的旧 job_params,
|
||||
避免 worker 执行前校验 unknown params 整批失败。
|
||||
|
||||
Args:
|
||||
commit: 是否立即提交。
|
||||
@@ -56,6 +77,7 @@ def ensure_default_voucher_check_schedule(
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
changed = False
|
||||
if existing.cron_expr == "0 6 * * *":
|
||||
existing.cron_expr = DEFAULT_VOUCHER_CHECK_CRON
|
||||
if existing.name == "立账凭证检核(日批)":
|
||||
@@ -64,6 +86,17 @@ def ensure_default_voucher_check_schedule(
|
||||
DEFAULT_VOUCHER_CHECK_CRON,
|
||||
timezone_name="Asia/Shanghai",
|
||||
) or existing.next_run_at
|
||||
changed = True
|
||||
cleaned_params, params_changed = _normalize_existing_job_params(existing.job_params)
|
||||
if params_changed:
|
||||
existing.job_params = cleaned_params
|
||||
flag_modified(existing, "job_params")
|
||||
changed = True
|
||||
_LOGGER.info(
|
||||
"stripped legacy accounting-voucher-check job_params id=%s",
|
||||
existing.id,
|
||||
)
|
||||
if changed:
|
||||
existing.updated_at = datetime.utcnow()
|
||||
if commit:
|
||||
sess.commit()
|
||||
|
||||
@@ -1,273 +0,0 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/share_scanner.py
|
||||
|
||||
用途:共享盘健康检查、路径构造、目录枚举与精确文件名匹配。
|
||||
依赖:config、fingerprint、core.errors.ServiceUnavailableError / ValidationError。
|
||||
逻辑:runner 阶段 A 调用;健康失败整批失败;单票目录缺失记业务缺资料。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.voucher_check.config import (
|
||||
RequiredFileRule,
|
||||
VoucherCheckConfig,
|
||||
resolve_share_root,
|
||||
)
|
||||
from app.services.voucher_check.fingerprint import build_material_fingerprint
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileMeta:
|
||||
"""直接子文件元数据。"""
|
||||
|
||||
name: str
|
||||
size: int
|
||||
mtime_ns: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class InvoiceScanResult:
|
||||
"""单票扫描结果。"""
|
||||
|
||||
invoice_no: str
|
||||
folder_path: str
|
||||
absolute_path: str
|
||||
folder_exists: bool
|
||||
material_fingerprint: str | None
|
||||
matched_files: dict[str, str] = field(default_factory=dict)
|
||||
missing_materials: list[dict[str, str]] = field(default_factory=list)
|
||||
result: str = "missing" # complete / missing / technical_error
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
def ensure_share_healthy(config: VoucherCheckConfig) -> str:
|
||||
"""
|
||||
校验共享盘根目录可用。
|
||||
核心逻辑:根存在、可 scandir、健康标记文件存在;失败抛 SHARE_UNAVAILABLE。
|
||||
|
||||
Returns:
|
||||
解析后的绝对根路径。
|
||||
"""
|
||||
root = resolve_share_root(config)
|
||||
root_path = Path(root)
|
||||
try:
|
||||
if not root_path.exists() or not root_path.is_dir():
|
||||
raise ServiceUnavailableError(
|
||||
"共享盘根目录不可用",
|
||||
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
|
||||
)
|
||||
# [STEP 1] 轻量枚举证明 I/O 可用
|
||||
with os.scandir(root_path) as it:
|
||||
_ = next(it, None)
|
||||
root_path.stat()
|
||||
# [STEP 2] 健康标记:避免挂载丢失后空目录被误判为业务缺件
|
||||
marker = (root_path / config.healthcheck_relative_path).resolve()
|
||||
if not str(marker).startswith(str(root_path.resolve())):
|
||||
raise ServiceUnavailableError(
|
||||
"共享盘健康标记路径非法",
|
||||
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
|
||||
)
|
||||
if not marker.is_file():
|
||||
raise ServiceUnavailableError(
|
||||
"共享盘健康标记文件缺失",
|
||||
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
|
||||
)
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except OSError as exc:
|
||||
raise ServiceUnavailableError(
|
||||
"共享盘健康检查失败",
|
||||
code="VOUCHER_CHECK.SHARE_UNAVAILABLE",
|
||||
details={"error_type": type(exc).__name__},
|
||||
) from exc
|
||||
return str(root_path)
|
||||
|
||||
|
||||
def _render_invoice_relative_path(
|
||||
template: str,
|
||||
*,
|
||||
year: str,
|
||||
month: str,
|
||||
invoice_no: str,
|
||||
) -> str:
|
||||
"""渲染相对业务路径(不含 root 实际值,报告用)。"""
|
||||
rendered = (
|
||||
template.replace("{root}", "vouche")
|
||||
.replace("{YYYY}", year)
|
||||
.replace("{MM}", month)
|
||||
.replace("{invoice_no}", invoice_no)
|
||||
)
|
||||
return rendered.strip("/").replace("\\", "/")
|
||||
|
||||
|
||||
def build_invoice_absolute_path(
|
||||
config: VoucherCheckConfig,
|
||||
*,
|
||||
root: str,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
构造单票绝对路径与相对业务路径。
|
||||
核心逻辑:invoice_no 仅 trim;含路径分隔符则视为非法(调用方记 technical_error)。
|
||||
"""
|
||||
year = f"{period_month.year:04d}"
|
||||
month = f"{period_month.month:02d}"
|
||||
invoice = str(invoice_no or "").strip()
|
||||
if not invoice or "/" in invoice or "\\" in invoice or "\x00" in invoice or ".." in invoice:
|
||||
raise ValidationError(
|
||||
"发票号含非法路径字符",
|
||||
code="VOUCHER_CHECK.INVOICE_PATH_INVALID",
|
||||
details={"invoice_no": invoice_no},
|
||||
)
|
||||
|
||||
relative = _render_invoice_relative_path(
|
||||
config.directory_template,
|
||||
year=year,
|
||||
month=month,
|
||||
invoice_no=invoice,
|
||||
)
|
||||
# 实际落盘:用真实 root 替换模板中的 {root}
|
||||
absolute_template = (
|
||||
config.directory_template.replace("{root}", root.rstrip("/\\"))
|
||||
.replace("{YYYY}", year)
|
||||
.replace("{MM}", month)
|
||||
.replace("{invoice_no}", invoice)
|
||||
)
|
||||
absolute = str(Path(absolute_template))
|
||||
resolved_root = Path(root).resolve()
|
||||
resolved_abs = Path(absolute).resolve()
|
||||
try:
|
||||
resolved_abs.relative_to(resolved_root)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
"发票目录逃逸共享根",
|
||||
code="VOUCHER_CHECK.INVOICE_PATH_INVALID",
|
||||
details={"invoice_no": invoice},
|
||||
) from exc
|
||||
return absolute, relative
|
||||
|
||||
|
||||
def list_direct_files(folder: Path) -> list[FileMeta]:
|
||||
"""枚举发票目录直接子文件(忽略子目录与非普通文件)。"""
|
||||
files: list[FileMeta] = []
|
||||
if not folder.is_dir():
|
||||
return files
|
||||
with os.scandir(folder) as it:
|
||||
for entry in it:
|
||||
try:
|
||||
if not entry.is_file(follow_symlinks=False):
|
||||
continue
|
||||
stat = entry.stat(follow_symlinks=False)
|
||||
files.append(
|
||||
FileMeta(
|
||||
name=entry.name,
|
||||
size=int(stat.st_size),
|
||||
mtime_ns=int(getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))),
|
||||
)
|
||||
)
|
||||
except OSError:
|
||||
continue
|
||||
return files
|
||||
|
||||
|
||||
def match_required_files(
|
||||
files: list[FileMeta],
|
||||
rules: tuple[RequiredFileRule, ...],
|
||||
*,
|
||||
case_sensitive: bool,
|
||||
) -> tuple[dict[str, str], list[dict[str, str]]]:
|
||||
"""
|
||||
按完整文件名精确匹配必检材料。
|
||||
核心逻辑:任一候选命中即算该材料存在;不支持模糊/前缀匹配。
|
||||
"""
|
||||
if case_sensitive:
|
||||
available = {f.name: f.name for f in files}
|
||||
else:
|
||||
available = {f.name.lower(): f.name for f in files}
|
||||
|
||||
matched: dict[str, str] = {}
|
||||
missing: list[dict[str, str]] = []
|
||||
for rule in rules:
|
||||
if not rule.required:
|
||||
continue
|
||||
hit: str | None = None
|
||||
for candidate in rule.accepted_filenames:
|
||||
key = candidate if case_sensitive else candidate.lower()
|
||||
if key in available:
|
||||
hit = available[key]
|
||||
break
|
||||
if hit:
|
||||
matched[rule.code] = hit
|
||||
else:
|
||||
missing.append({"code": rule.code, "name": rule.name})
|
||||
return matched, missing
|
||||
|
||||
|
||||
def scan_invoice_folder(
|
||||
config: VoucherCheckConfig,
|
||||
*,
|
||||
root: str,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
) -> InvoiceScanResult:
|
||||
"""
|
||||
扫描单票目录并判定齐全/缺资料。
|
||||
核心逻辑:目录不存在→missing;存在则精确匹配必检文件名并生成指纹。
|
||||
"""
|
||||
try:
|
||||
absolute, relative = build_invoice_absolute_path(
|
||||
config,
|
||||
root=root,
|
||||
period_month=period_month,
|
||||
invoice_no=invoice_no,
|
||||
)
|
||||
except ValidationError as exc:
|
||||
return InvoiceScanResult(
|
||||
invoice_no=str(invoice_no or "").strip(),
|
||||
folder_path="",
|
||||
absolute_path="",
|
||||
folder_exists=False,
|
||||
material_fingerprint=None,
|
||||
result="technical_error",
|
||||
error_code=exc.code,
|
||||
error_message=exc.message,
|
||||
)
|
||||
|
||||
folder = Path(absolute)
|
||||
if not folder.exists() or not folder.is_dir():
|
||||
missing = [{"code": r.code, "name": r.name} for r in config.required_files if r.required]
|
||||
return InvoiceScanResult(
|
||||
invoice_no=str(invoice_no).strip(),
|
||||
folder_path=relative,
|
||||
absolute_path=absolute,
|
||||
folder_exists=False,
|
||||
material_fingerprint=None,
|
||||
missing_materials=missing,
|
||||
result="missing",
|
||||
)
|
||||
|
||||
files = list_direct_files(folder)
|
||||
fingerprint = build_material_fingerprint([(f.name, f.size, f.mtime_ns) for f in files])
|
||||
matched, missing = match_required_files(
|
||||
files,
|
||||
config.required_files,
|
||||
case_sensitive=config.filename_case_sensitive,
|
||||
)
|
||||
return InvoiceScanResult(
|
||||
invoice_no=str(invoice_no).strip(),
|
||||
folder_path=relative,
|
||||
absolute_path=absolute,
|
||||
folder_exists=True,
|
||||
material_fingerprint=fingerprint,
|
||||
matched_files=matched,
|
||||
missing_materials=missing,
|
||||
result="complete" if not missing else "missing",
|
||||
)
|
||||
Reference in new issue
Block a user