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

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

No files matched your search

@@ -1,106 +0,0 @@
"""
backend/tests/voucher_check/test_share_and_fingerprint.py
用途:立账凭证检核目录模板、文件名精确匹配与指纹稳定性单测。
依赖:pytest、临时目录、voucher_check 领域模块。
逻辑:不连 Oracle/共享盘;覆盖精确匹配、0 字节齐全、子目录不计、指纹变化。
"""
from __future__ import annotations
from datetime import date
from pathlib import Path
import pytest
from app.core.errors import ValidationError
from app.services.voucher_check.config import (
RequiredFileRule,
validate_directory_template,
)
from app.services.voucher_check.fingerprint import build_material_fingerprint
from app.services.voucher_check.share_scanner import (
FileMeta,
match_required_files,
scan_invoice_folder,
)
def test_directory_template_rejects_unknown_placeholder():
with pytest.raises(ValidationError) as exc:
validate_directory_template("{root}/{YYYY}/{MM}/{invoice_no}/{extra}")
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
def test_exact_filename_match_and_zero_byte_counts():
rules = (
RequiredFileRule(
code="price_check_sheet",
name="核价单",
required=True,
accepted_filenames=("核价单.pdf",),
),
RequiredFileRule(
code="purchase_order",
name="采购单",
required=True,
accepted_filenames=("采购单.pdf",),
),
)
files = [
FileMeta(name="核价单.pdf", size=0, mtime_ns=1),
FileMeta(name="采购单.pdf", size=10, mtime_ns=2),
]
matched, missing = match_required_files(files, rules, case_sensitive=True)
assert matched["price_check_sheet"] == "核价单.pdf"
assert matched["purchase_order"] == "采购单.pdf"
assert missing == []
def test_subdir_same_name_does_not_count(tmp_path: Path):
"""直接子文件才命中;子目录内同名文件不算。"""
from app.services.voucher_check.config import VoucherCheckConfig
root = tmp_path / "vouche"
inv_dir = root / "2026" / "08" / "INV001"
inv_dir.mkdir(parents=True)
nested = inv_dir / "nested"
nested.mkdir()
(nested / "核价单.pdf").write_bytes(b"x")
(inv_dir / "采购单.pdf").write_bytes(b"y")
cfg = VoucherCheckConfig(
scope_code="HXJM",
directory_template="{root}/{YYYY}/{MM}/{invoice_no}",
required_files=(
RequiredFileRule("price_check_sheet", "核价单", True, ("核价单.pdf",)),
RequiredFileRule("purchase_order", "采购单", True, ("采购单.pdf",)),
),
filename_case_sensitive=True,
notify_missing_enabled=False,
notify_failure_enabled=False,
same_day_dedup_enabled=False,
local_root=str(root),
share_unc="",
healthcheck_relative_path=".hxops-share-ready",
erp_dsn="x",
erp_username="u",
erp_password="p",
)
result = scan_invoice_folder(
cfg,
root=str(root),
period_month=date(2026, 8, 1),
invoice_no="INV001",
)
assert result.result == "missing"
assert any(m["code"] == "price_check_sheet" for m in result.missing_materials)
assert result.matched_files.get("purchase_order") == "采购单.pdf"
def test_fingerprint_stable_and_changes_on_mtime():
a = build_material_fingerprint([("a.pdf", 1, 100), ("b.pdf", 2, 200)])
b = build_material_fingerprint([("b.pdf", 2, 200), ("a.pdf", 1, 100)])
assert a == b
c = build_material_fingerprint([("a.pdf", 1, 101), ("b.pdf", 2, 200)])
assert a != c
@@ -1,52 +0,0 @@
"""
backend/tests/voucher_check/test_tool_auth_and_openapi.py
用途:立账凭证检核 Tool OpenAPI 静态规格校验(不依赖 Flask venv)。
依赖:pytest、openapi_base.json。
逻辑:直接读 JSON,校验 operationId 与 securitySchemes。
"""
from __future__ import annotations
import json
from pathlib import Path
_SPEC = (
Path(__file__).resolve().parents[2]
/ "app"
/ "services"
/ "voucher_check"
/ "openapi_base.json"
)
def test_openapi_base_contains_expected_operations():
spec = json.loads(_SPEC.read_text(encoding="utf-8"))
paths = spec["paths"]
assert (
paths["/api/accounting-voucher-check/tools/tasks/{task_id}/missing"]["get"]["operationId"]
== "list_voucher_missing"
)
assert (
paths["/api/accounting-voucher-check/tools/runs/{run_id}/items"]["get"]["operationId"]
== "list_voucher_run_items"
)
assert (
paths["/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest"]["get"]["operationId"]
== "get_voucher_invoice_latest"
)
assert "BearerAuth" in spec["components"]["securitySchemes"]
assert "IntegrationKey" in spec["components"]["securitySchemes"]
def test_docs_openapi_export_in_sync():
docs = (
Path(__file__).resolve().parents[3]
/ "docs"
/ "openapi"
/ "accounting_voucher_check_tools_openapi.json"
)
assert docs.is_file(), "请运行 python backend/scripts/export_voucher_check_openapi.py"
exported = json.loads(docs.read_text(encoding="utf-8"))
base = json.loads(_SPEC.read_text(encoding="utf-8"))
assert exported["paths"].keys() == base["paths"].keys()
@@ -167,3 +167,37 @@ def test_workspace_lists_pre_engine_failure_for_selected_period(app, client, adm
assert item["run_no"] == "RUN-PREENGINE-FAILED"
assert item["status"] == "technical_failed"
assert item["error_message"] == "未配置销售开票附件文档库根目录"
def test_seed_strips_legacy_share_job_params(app):
"""已有排程若仍带共享盘旧字段,启动/入队种子必须剥掉,否则 worker 会 unknown params。"""
with app.app_context():
_ensure_user(username="admin", role="admin")
task = ensure_default_voucher_check_schedule(commit=True)
assert task is not None
task.job_params = {
"scope_code": "HXJM",
"profile_code": "sales",
"notify_missing_enabled": True,
"notify_failure_enabled": True,
"directory_template": "{root}/{YYYY}/{MM}/{invoice_no}",
"dir_template": "{root}/{YYYY}/{MM}/{invoice_no}",
"required_files": ["核价单.pdf", "采购单.pdf"],
"filename_case_sensitive": True,
"case_sensitive": False,
"same_day_dedup_enabled": True,
"same_day_dedup": True,
}
db.session.commit()
refreshed = ensure_default_voucher_check_schedule(commit=True)
params = refreshed.job_params if isinstance(refreshed.job_params, dict) else {}
assert "directory_template" not in params
assert "dir_template" not in params
assert "required_files" not in params
assert "filename_case_sensitive" not in params
assert "case_sensitive" not in params
assert "same_day_dedup_enabled" not in params
assert "same_day_dedup" not in params
assert params["scope_code"] == "HXJM"
assert params["profile_code"] == "sales"