This commit is contained in:
sophie committed 2026-09-07 11:13:33 +08:00
1 parent 78576f5745
commit 63b997a7e4
68 files changed
+3680 -1413

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
"""
backend/tests/test_faq_cache.py
用途:FAQ 缓存在线匹配规则。
逻辑:验证 cache_enabled 决定是否直答,is_enabled 只影响首页展示、不阻断命中。
"""
from app import db
from app.models import Agent, QuickQuestion
from app.services.faq_cache import FaqCacheService
def _create_agent() -> Agent:
"""写入测试 Agent,供 FAQ 条目关联。"""
agent = Agent(name='faq-cache-agent', type='api', dify_app_id='app-faq-cache', dify_api_key='key-faq-cache')
db.session.add(agent)
db.session.commit()
return agent
def _create_faq(agent_id: int, **overrides) -> QuickQuestion:
"""写入一条全局 FAQ,默认启用缓存且有标准答案。"""
payload = {
'user_id': None,
'agent_id': agent_id,
'title': '公司的企业文化',
'question': '公司的企业文化',
'answer': '客户满意、员工乐意、经营得意',
'aliases': ['企业文化'],
'cache_enabled': True,
'is_enabled': True,
}
payload.update(overrides)
faq = QuickQuestion(**payload)
db.session.add(faq)
db.session.commit()
return faq
def test_try_match_hits_when_cache_on_even_if_not_shown_on_home(app):
"""关闭前台展示时,启用缓存的问句仍应直答,不走 Dify。"""
with app.app_context():
agent = _create_agent()
_create_faq(agent.id, is_enabled=False)
hit = FaqCacheService.try_match('公司的企业文化', agent.id)
alias_hit = FaqCacheService.try_match('企业文化', agent.id)
assert hit is not None
assert hit.answer == '客户满意、员工乐意、经营得意'
assert alias_hit is not None
assert alias_hit.id == hit.id
def test_try_match_skips_when_cache_disabled(app):
"""仅在首页展示、未启用缓存时,提问仍应回退 Dify。"""
with app.app_context():
agent = _create_agent()
_create_faq(agent.id, cache_enabled=False, is_enabled=True)
assert FaqCacheService.try_match('公司的企业文化', agent.id) is None
@@ -0,0 +1,186 @@
"""
backend/tests/voucher_check/test_dms_archive.py
用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。
依赖:pytest;不连文档库。
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy;断言同名不覆盖、缺月目录为技术失败。
"""
from __future__ import annotations
from datetime import date
import pytest
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.base import ScannedFile
from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter
from app.services.voucher_check.dms_client import (
SalesDmsClient,
_extract_item_id,
_is_name_conflict,
)
def test_extract_item_id_from_nested_data():
assert _extract_item_id({"Data": {"ID": "folder-1"}}) == "folder-1"
assert _extract_item_id({"Data": "folder-2"}) == "folder-2"
assert _extract_item_id({"Data": {"Item": {"ID": "folder-3"}}}) == "folder-3"
assert _extract_item_id({"Data": {}}) == ""
def test_name_conflict_detects_same_name_messages():
assert _is_name_conflict("文件夹已存在")
assert _is_name_conflict("同名文件")
assert _is_name_conflict("The name already exists")
assert _is_name_conflict("网络超时") is False
def test_ensure_folder_returns_existing_without_save(monkeypatch):
monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: "folder-1")
calls: list[object] = []
monkeypatch.setattr(SalesDmsClient, "_post_json", lambda *_args, **_kwargs: calls.append(1) or {})
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "folder-1"
assert calls == []
def test_ensure_folder_creates_when_missing(monkeypatch):
monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: None)
monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1")
monkeypatch.setattr(
SalesDmsClient,
"_post_json",
lambda path, payload, **_kwargs: {"Code": 0, "Data": {"ID": "new-folder"}},
)
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder"
def test_copy_skips_when_dest_has_same_name(monkeypatch):
monkeypatch.setattr(
SalesDmsClient,
"find_child_file",
lambda **_kwargs: {"ID": "dest-1", "LeafName": "INV001.pdf"},
)
calls: list[object] = []
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs))
row, skipped = SalesDmsClient.copy_file_skip_same_name(
source_item_id="src-1",
dest_folder_id="inv-folder",
leaf_name="INV001.pdf",
)
assert skipped is True
assert row["ID"] == "dest-1"
assert calls == []
def test_copy_when_dest_has_no_same_name(monkeypatch):
listing = {"n": 0}
def find_child_file(**_kwargs):
listing["n"] += 1
if listing["n"] == 1:
return None
return {"ID": "dest-2", "LeafName": "INV001.pdf"}
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
copied: list[dict] = []
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0})
row, skipped = SalesDmsClient.copy_file_skip_same_name(
source_item_id="src-1",
dest_folder_id="inv-folder",
leaf_name="INV001.pdf",
)
assert skipped is False
assert row["ID"] == "dest-2"
assert copied == [{"item_ids": ["src-1"], "dest_folder_id": "inv-folder"}]
def test_copy_treats_api_same_name_error_as_skip(monkeypatch):
listing = {"n": 0}
def find_child_file(**_kwargs):
listing["n"] += 1
if listing["n"] == 1:
return None
return {"ID": "dest-3", "LeafName": "INV001.pdf"}
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
monkeypatch.setattr(
SalesDmsClient,
"copy_items",
lambda **_kwargs: (_ for _ in ()).throw(
ServiceUnavailableError("目标已存在同名文件", code="VOUCHER_CHECK.ARCHIVE_FAILED")
),
)
row, skipped = SalesDmsClient.copy_file_skip_same_name(
source_item_id="src-1",
dest_folder_id="inv-folder",
leaf_name="INV001.pdf",
)
assert skipped is True
assert row["ID"] == "dest-3"
def test_archive_adapter_is_wired_and_skips_same_name(monkeypatch):
monkeypatch.setattr(SalesDmsClient, "ensure_month_archive_root", lambda **_kwargs: "archive-root")
monkeypatch.setattr(SalesDmsClient, "ensure_folder", lambda **_kwargs: "inv-folder")
monkeypatch.setattr(
SalesDmsClient,
"copy_file_skip_same_name",
lambda **_kwargs: ({"ID": "dest-9", "LeafName": "INV001-PO9.pdf"}, True),
)
adapter = DmsArchiveAdapter()
assert adapter.wired is True
archived = adapter.archive(
period_month=date(2026, 8, 1),
invoice_no="INV001",
file=ScannedFile(filename="INV001-PO9.pdf", item_id="src-9", fingerprint="fp1"),
rule={"code": "po_order"},
)
assert archived.item_id == "dest-9"
assert archived.folder_id == "inv-folder"
assert archived.extra["skipped_same_name"] is True
assert archived.path == "销售开票附件/2026/08/所有归档/INV001/INV001-PO9.pdf"
def test_archive_adapter_missing_source_id_is_technical():
adapter = DmsArchiveAdapter()
with pytest.raises(ServiceUnavailableError) as exc:
adapter.archive(
period_month=date(2026, 8, 1),
invoice_no="INV001",
file=ScannedFile(filename="INV001.pdf"),
rule={"code": "tax_invoice"},
)
assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED"
def test_month_archive_root_missing_month_is_technical(monkeypatch):
monkeypatch.setattr(SalesDmsClient, "resolve_period_folder", lambda **_kwargs: (None, None))
with pytest.raises(ServiceUnavailableError) as exc:
SalesDmsClient.ensure_month_archive_root(period_month=date(2026, 8, 1))
assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED"
def test_page_walks_until_short_batch(monkeypatch):
"""「所有归档」超过一页时必须翻页,否则同名跳过会漏检已有发票目录。"""
calls = {"n": 0}
def post(_path, payload, **_kwargs):
calls["n"] += 1
index = payload["Page"]["Index"]
if index == 1:
return {
"Code": 0,
"Data": {"Items": [{"ID": "a", "IsFolder": True, "LeafName": "x"}] * 200, "Total": 201},
}
return {
"Code": 0,
"Data": {"Items": [{"ID": "b", "IsFolder": True, "LeafName": "y"}], "Total": 201},
}
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1")
rows = SalesDmsClient.page(parent_folder_id="archive-root")
assert len(rows) == 201
assert calls["n"] == 2
@@ -0,0 +1,124 @@
"""
backend/tests/voucher_check/test_engine_profile_and_scan.py
用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。
依赖:pytest;不连 Oracle / 文档库。
逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。
"""
from __future__ import annotations
from datetime import date, datetime
from zoneinfo import ZoneInfo
import pytest
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.erp_repository import previous_period_bounds
from app.services.voucher_check.filename_match import first_match, match_filename
from app.services.voucher_check.profiles.sales import SALES_PROFILE, required_file_rules
def test_previous_period_bounds_from_early_september():
"""周二跑批时检核上个月;2026-09-01 应得到 2026-08。"""
now = datetime(2026, 9, 1, 6, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
period_month, current_month, period_start, next_start = previous_period_bounds(now)
assert period_month.isoformat() == "2026-08-01"
assert current_month.isoformat() == "2026-09-01"
assert period_start.isoformat().startswith("2026-08-01T00:00:00")
assert next_start.isoformat().startswith("2026-09-01T00:00:00")
def test_previous_period_bounds_january_cross_year():
now = datetime(2026, 1, 6, 10, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
period_month, current_month, _, _ = previous_period_bounds(now)
assert period_month.isoformat() == "2025-12-01"
assert current_month.isoformat() == "2026-01-01"
def test_filename_templates_match_sales_rules():
assert match_filename("INV001-PO9.pdf", template="{invoice}-{order_no}.pdf", invoice_no="INV001")
assert match_filename("INV001.pdf", template="{invoice}.pdf", invoice_no="INV001")
assert match_filename("INV001-DN8.pdf", template="{invoice}-{delivery_no}.pdf", invoice_no="INV001")
assert match_filename("INV001-TAX1.pdf", template="{invoice}-{tax_invoice_no}.pdf", invoice_no="INV001")
assert match_filename("INV001-CD2.pdf", template="{invoice}-{customs_no}.pdf", invoice_no="INV001")
assert match_filename("INV001-提单.pdf", template="{invoice}-提单.pdf", invoice_no="INV001")
assert match_filename("INV002.pdf", template="{invoice}.pdf", invoice_no="INV001") is None
assert first_match(["other.pdf", "INV001-提单.pdf"], template="{invoice}-提单.pdf", invoice_no="INV001")
def test_aggregator_dual_missing_metrics():
"""同一 invoice 缺两类文件:缺件文件=2,缺件 invoice=1。"""
rules = required_file_rules(SALES_PROFILE)
results = [
{"invoice_no": "A", "rule_code": "po_order", "status": "missing"},
{"invoice_no": "A", "rule_code": "customs_pack", "status": "missing"},
{"invoice_no": "A", "rule_code": "sales_release", "status": "staged"},
{"invoice_no": "A", "rule_code": "tax_invoice", "status": "archived"},
{"invoice_no": "A", "rule_code": "customs_declaration", "status": "archived"},
{"invoice_no": "A", "rule_code": "bill_of_lading", "status": "archived"},
{"invoice_no": "B", "rule_code": "po_order", "status": "archived"},
{"invoice_no": "B", "rule_code": "customs_pack", "status": "archived"},
{"invoice_no": "B", "rule_code": "sales_release", "status": "archived"},
{"invoice_no": "B", "rule_code": "tax_invoice", "status": "archived"},
{"invoice_no": "B", "rule_code": "customs_declaration", "status": "archived"},
{"invoice_no": "B", "rule_code": "bill_of_lading", "status": "archived"},
]
stats = aggregate_file_results(results, rules=rules)
assert stats["missing_file_count"] == 2
assert stats["missing_invoice_count"] == 1
by_invoice = {row["invoice_no"]: row for row in stats["excel_rows"]}
assert by_invoice["A"]["status"] == "缺件"
assert by_invoice["B"]["status"] == "完整"
assert by_invoice["A"]["cells"]["po_order"] == "缺件"
assert by_invoice["A"]["cells"]["sales_release"] == "未检核"
assert by_invoice["B"]["cells"]["po_order"] == "有"
def test_po_and_oa_adapters_are_placeholders():
with pytest.raises(ServiceUnavailableError) as po_exc:
ErpPoPrintAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
assert po_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
with pytest.raises(ServiceUnavailableError) as oa_exc:
OaSalesReleaseAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
assert oa_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
assert ErpPoPrintAdapter.wired is False
assert OaSalesReleaseAdapter.wired is False
def test_directory_scan_matches_cached_listing(monkeypatch):
adapter = DmsDirectoryScanAdapter()
monkeypatch.setattr(
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.resolve_period_folder",
lambda **kwargs: ("year-id", "month-id"),
)
monkeypatch.setattr(
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.find_child_folder",
lambda **kwargs: "type-id",
)
monkeypatch.setattr(
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.list_files",
lambda **kwargs: [
{"LeafName": "INV001-PO9.pdf", "ID": "item-1", "IsFolder": False, "Path": "销售开票附件/2026/08/PO订单/INV001-PO9.pdf", "VersionID": "v1"},
{"LeafName": "OTHER.pdf", "ID": "item-2", "IsFolder": False},
],
)
hit = adapter.scan(
period_month=date(2026, 8, 1),
invoice_no="INV001",
rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"},
)
assert hit.status == "matched"
assert hit.file is not None
assert hit.file.filename == "INV001-PO9.pdf"
missed = adapter.scan(
period_month=date(2026, 8, 1),
invoice_no="INV999",
rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"},
)
assert missed.status == "missing"
@@ -0,0 +1,97 @@
"""
backend/tests/voucher_check/test_workspace_force_recheck.py
用途:工作台强制重检入队(force_all)与并发冲突。
依赖:pytest、Flask client;不执行真实周任务。
逻辑:POST /api/workspace/accounting-voucher-check/runs 写入 run_options.mode=force_all;已有 queued 时 409。
"""
from __future__ import annotations
from tests.conftest import parse_api_data, parse_api_error
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.voucher_check.schedule_seed import (
DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
DEFAULT_VOUCHER_CHECK_SCHEDULE_NO,
ensure_default_voucher_check_schedule,
)
def _ensure_user(*, username: str, role: str) -> User:
user = db.session.query(User).filter_by(username=username).first()
if user:
user.role = role
user.status = "active"
db.session.commit()
return user
user = User(
username=username,
email=f"{username}@example.com",
role=role,
status="active",
)
user.set_password("test")
db.session.add(user)
db.session.commit()
return user
def test_workspace_force_recheck_enqueues_force_all(app, client, admin_headers):
"""工作台按钮入队后,ScheduleRun 必须带 force_all,供 runner 跳过增量。"""
with app.app_context():
_ensure_user(username="admin", role="admin")
task = ensure_default_voucher_check_schedule(commit=True)
assert task is not None
assert task.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO
assert task.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH
first = client.post(
"/api/workspace/accounting-voucher-check/runs",
json={"mode": "force_all"},
headers=admin_headers,
)
assert first.status_code == 200
data = parse_api_data(first.get_json())
assert data["mode"] == "force_all"
assert data["status"] == "queued"
assert data["run_no"]
with app.app_context():
run = db.session.get(ScheduleRun, data["schedule_run_id"])
assert run is not None
options = (run.api_request_json or {}).get("run_options") or {}
assert options.get("mode") == "force_all"
second = client.post(
"/api/workspace/accounting-voucher-check/runs",
json={"mode": "force_all"},
headers=admin_headers,
)
assert second.status_code == 409
error = parse_api_error(second.get_json())
assert error["code"] == "VOUCHER_CHECK.RUN_IN_PROGRESS"
def test_workspace_force_recheck_rejects_non_admin_and_invalid_mode(app, client, admin_headers, user_headers):
with app.app_context():
_ensure_user(username="admin", role="admin")
_ensure_user(username="user", role="user")
ensure_default_voucher_check_schedule(commit=True)
forbidden = client.post(
"/api/workspace/accounting-voucher-check/runs",
json={"mode": "force_all"},
headers=user_headers,
)
assert forbidden.status_code == 403
invalid = client.post(
"/api/workspace/accounting-voucher-check/runs",
json={"mode": "incremental"},
headers=admin_headers,
)
assert invalid.status_code == 400
error = parse_api_error(invalid.get_json())
assert error["code"] == "VOUCHER_CHECK.CONFIG_INVALID"