Merge branch 'invoice-check' into dev
This commit is contained in:
commit
9570197378
104 files changed
+5844
-4271
No files matched your search
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/tests/jobs/test_schedule_queue.py
|
||||
|
||||
用途:验证排程迁出 Web 后的手动入队、Cron 扫描与 Job handler 状态闭环。
|
||||
用途:验证排程迁出 Web 后的手动入队、Cron 扫描、Job 业务身份字段与 handler 状态闭环。
|
||||
依赖:通用 app fixture、models.Job/ScheduleRun/ScheduleTask、schedule.queue_service。
|
||||
逻辑:只替换真正的排程执行器,不启动后台线程,断言 API/worker 之间的数据契约。
|
||||
"""
|
||||
@@ -16,8 +16,16 @@ from app.models import Job, ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.queue_service import enqueue_due_schedule_runs, enqueue_manual_schedule_run
|
||||
|
||||
|
||||
def _create_task(*, due: bool = False) -> ScheduleTask:
|
||||
"""创建测试用户与排程;due=True 时令 next_run_at 已到期。"""
|
||||
def _create_task(*, due: bool = False, platform_api_path: str | None = None, name: str = "schedule queue test") -> ScheduleTask:
|
||||
"""
|
||||
创建测试用户与排程。
|
||||
核心逻辑:due=True 时令 next_run_at 已到期;可指定 platform_api_path 覆盖默认 data_pipeline。
|
||||
|
||||
Args:
|
||||
due: 是否立即到期,供 Cron 扫描测试。
|
||||
platform_api_path: 平台任务 key;有值时 schedule_type 改为 platform_job。
|
||||
name: 排程显示名,写入 jobs.message。
|
||||
"""
|
||||
suffix = str(datetime.utcnow().timestamp()).replace(".", "-")
|
||||
user = User(
|
||||
username=f"schedule-owner-{suffix}",
|
||||
@@ -30,8 +38,9 @@ def _create_task(*, due: bool = False) -> ScheduleTask:
|
||||
db.session.flush()
|
||||
task = ScheduleTask(
|
||||
schedule_no=f"SCH-TEST-{datetime.utcnow().timestamp()}",
|
||||
name="schedule queue test",
|
||||
schedule_type="data_pipeline",
|
||||
name=name,
|
||||
schedule_type="platform_job" if platform_api_path else "data_pipeline",
|
||||
platform_api_path=platform_api_path,
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
schedule_timezone="Asia/Shanghai",
|
||||
@@ -57,6 +66,8 @@ def test_manual_schedule_run_creates_queued_job(app):
|
||||
assert job.domain == "schedule"
|
||||
assert job.job_type == JobType.SCHEDULE_RUN.value
|
||||
assert job.payload_json["schedule_run_id"] == run.id
|
||||
assert job.business_ref == f"schedule_run:{run.id}:untagged"
|
||||
assert job.message == "schedule queue test等待后台执行"
|
||||
|
||||
|
||||
def test_due_schedule_scan_is_idempotent(app):
|
||||
@@ -101,3 +112,51 @@ def test_schedule_handler_finishes_generic_job(app, monkeypatch):
|
||||
db.session.expire_all()
|
||||
assert db.session.get(ScheduleRun, run.id).status == "success"
|
||||
assert db.session.get(Job, job_id).status == "success"
|
||||
|
||||
|
||||
def test_schedule_job_identity_uses_platform_api_path(app):
|
||||
"""关键断言:立账凭证等平台任务在 jobs 表用 business_ref/payload 区分,不改 job_type。"""
|
||||
from app.services.schedule.queue_service import query_jobs_for_schedule_run
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
|
||||
with app.app_context():
|
||||
task = _create_task(platform_api_path="accounting-voucher-check", name="立账凭证检核")
|
||||
run, job_id, created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id)
|
||||
job = db.session.get(Job, job_id)
|
||||
|
||||
assert created is True
|
||||
assert job.domain == "schedule"
|
||||
assert job.job_type == JobType.SCHEDULE_RUN.value
|
||||
assert job.business_ref == f"schedule_run:{run.id}:accounting-voucher-check"
|
||||
assert job.payload_json["platform_api_path"] == "accounting-voucher-check"
|
||||
assert job.payload_json["task_name"] == "立账凭证检核"
|
||||
assert job.payload_json["schedule_no"] == task.schedule_no
|
||||
assert job.message == "立账凭证检核等待后台执行"
|
||||
assert query_jobs_for_schedule_run(run.id).filter(Job.status == "queued").one().id == job_id
|
||||
|
||||
request_cancel_run(run.id)
|
||||
db.session.commit()
|
||||
db.session.expire_all()
|
||||
cancelled = db.session.get(Job, job_id)
|
||||
assert cancelled.status == "cancelled"
|
||||
|
||||
|
||||
def test_query_jobs_for_schedule_run_matches_legacy_business_ref(app):
|
||||
"""关键断言:取消/回收仍能命中升级前 `schedule_run:{id}` 旧格式。"""
|
||||
from app.services.schedule.queue_service import query_jobs_for_schedule_run
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
|
||||
with app.app_context():
|
||||
task = _create_task()
|
||||
run, job_id, _created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id)
|
||||
job = db.session.get(Job, job_id)
|
||||
job.business_ref = f"schedule_run:{run.id}"
|
||||
db.session.commit()
|
||||
|
||||
found = query_jobs_for_schedule_run(run.id).one()
|
||||
assert found.id == job_id
|
||||
|
||||
request_cancel_run(run.id)
|
||||
db.session.commit()
|
||||
db.session.expire_all()
|
||||
assert db.session.get(Job, job_id).status == "cancelled"
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
backend/tests/test_faq_cache.py
|
||||
|
||||
用途:FAQ 缓存在线匹配规则。
|
||||
逻辑:验证 cache_enabled 决定是否直答,is_enabled 只影响首页展示、不阻断命中。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import Agent, QuickQuestion
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
|
||||
|
||||
def _create_agent() -> Agent:
|
||||
"""写入测试 Agent,供 FAQ 条目关联。"""
|
||||
agent = Agent(name='faq-cache-agent', type='api', dify_app_id='app-faq-cache', dify_api_key='key-faq-cache')
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
return agent
|
||||
|
||||
|
||||
def _create_faq(agent_id: int, **overrides) -> QuickQuestion:
|
||||
"""写入一条全局 FAQ,默认启用缓存且有标准答案。"""
|
||||
payload = {
|
||||
'user_id': None,
|
||||
'agent_id': agent_id,
|
||||
'title': '公司的企业文化',
|
||||
'question': '公司的企业文化',
|
||||
'answer': '客户满意、员工乐意、经营得意',
|
||||
'aliases': ['企业文化'],
|
||||
'cache_enabled': True,
|
||||
'is_enabled': True,
|
||||
}
|
||||
payload.update(overrides)
|
||||
faq = QuickQuestion(**payload)
|
||||
db.session.add(faq)
|
||||
db.session.commit()
|
||||
return faq
|
||||
|
||||
|
||||
def test_try_match_hits_when_cache_on_even_if_not_shown_on_home(app):
|
||||
"""关闭前台展示时,启用缓存的问句仍应直答,不走 Dify。"""
|
||||
with app.app_context():
|
||||
agent = _create_agent()
|
||||
_create_faq(agent.id, is_enabled=False)
|
||||
|
||||
hit = FaqCacheService.try_match('公司的企业文化', agent.id)
|
||||
alias_hit = FaqCacheService.try_match('企业文化', agent.id)
|
||||
|
||||
assert hit is not None
|
||||
assert hit.answer == '客户满意、员工乐意、经营得意'
|
||||
assert alias_hit is not None
|
||||
assert alias_hit.id == hit.id
|
||||
|
||||
|
||||
def test_try_match_skips_when_cache_disabled(app):
|
||||
"""仅在首页展示、未启用缓存时,提问仍应回退 Dify。"""
|
||||
with app.app_context():
|
||||
agent = _create_agent()
|
||||
_create_faq(agent.id, cache_enabled=False, is_enabled=True)
|
||||
|
||||
assert FaqCacheService.try_match('公司的企业文化', agent.id) is None
|
||||
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
backend/tests/test_schedule_run_executor_error.py
|
||||
|
||||
用途:排程 handler 抛错时 ScheduleRun 必须记 failed,不能因 failed_count=0 标成 success。
|
||||
依赖:scheduler_service.run_task_now、ScheduleTask/ScheduleRun。
|
||||
逻辑:monkeypatch executor 抛出配置错误,断言 status=failed 且 error_message 保留原文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.scheduler_service import run_task_now
|
||||
|
||||
|
||||
def test_run_task_now_marks_executor_exception_as_failed(app, monkeypatch):
|
||||
"""handler 抛 RuntimeError 时,批次状态应为 failed 且 failed_count=1。"""
|
||||
def _boom(_task: ScheduleTask, _run: ScheduleRun):
|
||||
raise RuntimeError("未配置 VOUCHER_CHECK_ERP_DSN / VOUCHER_CHECK_ERP_USERNAME")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.scheduler_service.resolve_schedule_executor",
|
||||
lambda _task: _boom,
|
||||
)
|
||||
with app.app_context():
|
||||
user = User(username="sched-exec-err", email="sched-exec-err@example.com")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-TEST-EXECUTOR-ERROR",
|
||||
name="executor error fixture",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-check",
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 6 * * 2",
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
result = run_task_now(task, trigger_type="manual", triggered_by_user_id=user.id)
|
||||
assert result.status == "failed"
|
||||
assert result.failed_count == 1
|
||||
assert "VOUCHER_CHECK_ERP" in (result.error_message or "")
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_dms_archive.py
|
||||
|
||||
用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。
|
||||
依赖:pytest;不连文档库。
|
||||
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy;断言同名不覆盖、缺月目录为技术失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile
|
||||
from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter
|
||||
from app.services.voucher_check.dms_client import (
|
||||
SalesDmsClient,
|
||||
_extract_item_id,
|
||||
_is_name_conflict,
|
||||
)
|
||||
|
||||
|
||||
def test_extract_item_id_from_nested_data():
|
||||
assert _extract_item_id({"Data": {"ID": "folder-1"}}) == "folder-1"
|
||||
assert _extract_item_id({"Data": "folder-2"}) == "folder-2"
|
||||
assert _extract_item_id({"Data": {"Item": {"ID": "folder-3"}}}) == "folder-3"
|
||||
assert _extract_item_id({"Data": {}}) == ""
|
||||
|
||||
|
||||
def test_name_conflict_detects_same_name_messages():
|
||||
assert _is_name_conflict("文件夹已存在")
|
||||
assert _is_name_conflict("同名文件")
|
||||
assert _is_name_conflict("The name already exists")
|
||||
assert _is_name_conflict("网络超时") is False
|
||||
|
||||
|
||||
def test_ensure_folder_returns_existing_without_save(monkeypatch):
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: "folder-1")
|
||||
calls: list[object] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "_post_json", lambda *_args, **_kwargs: calls.append(1) or {})
|
||||
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "folder-1"
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_ensure_folder_creates_when_missing(monkeypatch):
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_folder", lambda **_kwargs: None)
|
||||
monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1")
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"_post_json",
|
||||
lambda path, payload, **_kwargs: {"Code": 0, "Data": {"ID": "new-folder"}},
|
||||
)
|
||||
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder"
|
||||
|
||||
|
||||
def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"find_child_file",
|
||||
lambda **_kwargs: {"ID": "dest-1", "LeafName": "INV001.pdf"},
|
||||
)
|
||||
calls: list[object] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs))
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "dest-1"
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_copy_when_dest_has_no_same_name(monkeypatch):
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(**_kwargs):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
return {"ID": "dest-2", "LeafName": "INV001.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
copied: list[dict] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0})
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is False
|
||||
assert row["ID"] == "dest-2"
|
||||
assert copied == [{"item_ids": ["src-1"], "dest_folder_id": "inv-folder"}]
|
||||
|
||||
|
||||
def test_copy_treats_api_same_name_error_as_skip(monkeypatch):
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(**_kwargs):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
return {"ID": "dest-3", "LeafName": "INV001.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"copy_items",
|
||||
lambda **_kwargs: (_ for _ in ()).throw(
|
||||
ServiceUnavailableError("目标已存在同名文件", code="VOUCHER_CHECK.ARCHIVE_FAILED")
|
||||
),
|
||||
)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "dest-3"
|
||||
|
||||
|
||||
def test_archive_adapter_is_wired_and_skips_same_name(monkeypatch):
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_month_archive_root", lambda **_kwargs: "archive-root")
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_folder", lambda **_kwargs: "inv-folder")
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"copy_file_skip_same_name",
|
||||
lambda **_kwargs: ({"ID": "dest-9", "LeafName": "INV001-PO9.pdf"}, True),
|
||||
)
|
||||
adapter = DmsArchiveAdapter()
|
||||
assert adapter.wired is True
|
||||
archived = adapter.archive(
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV001",
|
||||
file=ScannedFile(filename="INV001-PO9.pdf", item_id="src-9", fingerprint="fp1"),
|
||||
rule={"code": "po_order"},
|
||||
)
|
||||
assert archived.item_id == "dest-9"
|
||||
assert archived.folder_id == "inv-folder"
|
||||
assert archived.extra["skipped_same_name"] is True
|
||||
assert archived.path == "销售开票附件/2026/08/所有归档/INV001/INV001-PO9.pdf"
|
||||
|
||||
|
||||
def test_archive_adapter_missing_source_id_is_technical():
|
||||
adapter = DmsArchiveAdapter()
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
adapter.archive(
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV001",
|
||||
file=ScannedFile(filename="INV001.pdf"),
|
||||
rule={"code": "tax_invoice"},
|
||||
)
|
||||
assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED"
|
||||
|
||||
|
||||
def test_month_archive_root_missing_month_is_technical(monkeypatch):
|
||||
monkeypatch.setattr(SalesDmsClient, "resolve_period_folder", lambda **_kwargs: (None, None))
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
SalesDmsClient.ensure_month_archive_root(period_month=date(2026, 8, 1))
|
||||
assert exc.value.code == "VOUCHER_CHECK.ARCHIVE_FAILED"
|
||||
|
||||
|
||||
def test_page_walks_until_short_batch(monkeypatch):
|
||||
"""「所有归档」超过一页时必须翻页,否则同名跳过会漏检已有发票目录。"""
|
||||
calls = {"n": 0}
|
||||
|
||||
def post(_path, payload, **_kwargs):
|
||||
calls["n"] += 1
|
||||
index = payload["Page"]["Index"]
|
||||
if index == 1:
|
||||
return {
|
||||
"Code": 0,
|
||||
"Data": {"Items": [{"ID": "a", "IsFolder": True, "LeafName": "x"}] * 200, "Total": 201},
|
||||
}
|
||||
return {
|
||||
"Code": 0,
|
||||
"Data": {"Items": [{"ID": "b", "IsFolder": True, "LeafName": "y"}], "Total": 201},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
|
||||
monkeypatch.setattr(SalesDmsClient, "library_id", lambda: "lib-1")
|
||||
rows = SalesDmsClient.page(parent_folder_id="archive-root")
|
||||
assert len(rows) == 201
|
||||
assert calls["n"] == 2
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_engine_profile_and_scan.py
|
||||
|
||||
用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。
|
||||
依赖:pytest;不连 Oracle / 文档库。
|
||||
逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
|
||||
from app.services.voucher_check.aggregator import aggregate_file_results
|
||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||
from app.services.voucher_check.filename_match import first_match, match_filename
|
||||
from app.services.voucher_check.profiles.sales import SALES_PROFILE, required_file_rules
|
||||
|
||||
|
||||
def test_previous_period_bounds_from_early_september():
|
||||
"""周二跑批时检核上个月;2026-09-01 应得到 2026-08。"""
|
||||
now = datetime(2026, 9, 1, 6, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
|
||||
period_month, current_month, period_start, next_start = previous_period_bounds(now)
|
||||
assert period_month.isoformat() == "2026-08-01"
|
||||
assert current_month.isoformat() == "2026-09-01"
|
||||
assert period_start.isoformat().startswith("2026-08-01T00:00:00")
|
||||
assert next_start.isoformat().startswith("2026-09-01T00:00:00")
|
||||
|
||||
|
||||
def test_previous_period_bounds_january_cross_year():
|
||||
now = datetime(2026, 1, 6, 10, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
|
||||
period_month, current_month, _, _ = previous_period_bounds(now)
|
||||
assert period_month.isoformat() == "2025-12-01"
|
||||
assert current_month.isoformat() == "2026-01-01"
|
||||
|
||||
|
||||
def test_filename_templates_match_sales_rules():
|
||||
assert match_filename("INV001-PO9.pdf", template="{invoice}-{order_no}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001.pdf", template="{invoice}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001-DN8.pdf", template="{invoice}-{delivery_no}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001-TAX1.pdf", template="{invoice}-{tax_invoice_no}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001-CD2.pdf", template="{invoice}-{customs_no}.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV001-提单.pdf", template="{invoice}-提单.pdf", invoice_no="INV001")
|
||||
assert match_filename("INV002.pdf", template="{invoice}.pdf", invoice_no="INV001") is None
|
||||
assert first_match(["other.pdf", "INV001-提单.pdf"], template="{invoice}-提单.pdf", invoice_no="INV001")
|
||||
|
||||
|
||||
def test_aggregator_dual_missing_metrics():
|
||||
"""同一 invoice 缺两类文件:缺件文件=2,缺件 invoice=1。"""
|
||||
rules = required_file_rules(SALES_PROFILE)
|
||||
results = [
|
||||
{"invoice_no": "A", "rule_code": "po_order", "status": "missing"},
|
||||
{"invoice_no": "A", "rule_code": "customs_pack", "status": "missing"},
|
||||
{"invoice_no": "A", "rule_code": "sales_release", "status": "staged"},
|
||||
{"invoice_no": "A", "rule_code": "tax_invoice", "status": "archived"},
|
||||
{"invoice_no": "A", "rule_code": "customs_declaration", "status": "archived"},
|
||||
{"invoice_no": "A", "rule_code": "bill_of_lading", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "po_order", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "customs_pack", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "sales_release", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "tax_invoice", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "customs_declaration", "status": "archived"},
|
||||
{"invoice_no": "B", "rule_code": "bill_of_lading", "status": "archived"},
|
||||
]
|
||||
stats = aggregate_file_results(results, rules=rules)
|
||||
assert stats["missing_file_count"] == 2
|
||||
assert stats["missing_invoice_count"] == 1
|
||||
by_invoice = {row["invoice_no"]: row for row in stats["excel_rows"]}
|
||||
assert by_invoice["A"]["status"] == "缺件"
|
||||
assert by_invoice["B"]["status"] == "完整"
|
||||
assert by_invoice["A"]["cells"]["po_order"] == "缺件"
|
||||
assert by_invoice["A"]["cells"]["sales_release"] == "未检核"
|
||||
assert by_invoice["B"]["cells"]["po_order"] == "有"
|
||||
assert stats["by_file_type"]["po_order"]["missing_file_count"] == 1
|
||||
assert stats["by_file_type"]["po_order"]["missing_invoice_count"] == 1
|
||||
assert stats["by_file_type"]["tax_invoice"]["missing_file_count"] == 0
|
||||
|
||||
|
||||
def test_po_and_oa_adapters_are_placeholders():
|
||||
with pytest.raises(ServiceUnavailableError) as po_exc:
|
||||
ErpPoPrintAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert po_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
with pytest.raises(ServiceUnavailableError) as oa_exc:
|
||||
OaSalesReleaseAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert oa_exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
assert ErpPoPrintAdapter.wired is False
|
||||
assert OaSalesReleaseAdapter.wired is False
|
||||
|
||||
|
||||
def test_directory_scan_matches_cached_listing(monkeypatch):
|
||||
adapter = DmsDirectoryScanAdapter()
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.resolve_period_folder",
|
||||
lambda **kwargs: ("year-id", "month-id"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.find_child_folder",
|
||||
lambda **kwargs: "type-id",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.adapters.dms_directory_scan.SalesDmsClient.list_files",
|
||||
lambda **kwargs: [
|
||||
{"LeafName": "INV001-PO9.pdf", "ID": "item-1", "IsFolder": False, "Path": "销售开票附件/2026/08/PO订单/INV001-PO9.pdf", "VersionID": "v1"},
|
||||
{"LeafName": "OTHER.pdf", "ID": "item-2", "IsFolder": False},
|
||||
],
|
||||
)
|
||||
hit = adapter.scan(
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV001",
|
||||
rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"},
|
||||
)
|
||||
assert hit.status == "matched"
|
||||
assert hit.file is not None
|
||||
assert hit.file.filename == "INV001-PO9.pdf"
|
||||
|
||||
missed = adapter.scan(
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV999",
|
||||
rule={"type_folder": "PO订单", "filename_template": "{invoice}-{order_no}.pdf"},
|
||||
)
|
||||
assert missed.status == "missing"
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_erp_settings.py
|
||||
|
||||
用途:立账凭证 ERP 凭据回退到通用 ERP_* / 合同付款同一套只读账号。
|
||||
依赖:voucher_check.config._erp_settings、Flask app。
|
||||
逻辑:清空 VOUCHER_CHECK_ERP_USERNAME 后仍能从 CONTRACT_PAYMENT_ERP_* 读到账号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.voucher_check.config import _erp_settings
|
||||
|
||||
|
||||
def test_erp_settings_falls_back_to_contract_payment_credentials(app):
|
||||
"""未单独配 VOUCHER_CHECK_ERP_USERNAME 时,应复用合同付款已有的只读账号。"""
|
||||
with app.app_context():
|
||||
app.config["VOUCHER_CHECK_ERP_DSN"] = ""
|
||||
app.config["VOUCHER_CHECK_ERP_USERNAME"] = ""
|
||||
app.config["VOUCHER_CHECK_ERP_PASSWORD"] = ""
|
||||
app.config["ERP_DB_DSN"] = "192.168.8.24:1521/topprod"
|
||||
app.config["ERP_USERNAME"] = ""
|
||||
app.config["ERP_PASSWORD"] = ""
|
||||
app.config["CONTRACT_PAYMENT_ERP_USERNAME"] = "hxjm_ro"
|
||||
app.config["CONTRACT_PAYMENT_ERP_PASSWORD"] = "secret-from-contract-payment"
|
||||
dsn, username, password, timeout = _erp_settings()
|
||||
assert dsn == "192.168.8.24:1521/topprod"
|
||||
assert username == "hxjm_ro"
|
||||
assert password == "secret-from-contract-payment"
|
||||
assert timeout >= 1
|
||||
@@ -1,106 +0,0 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_share_and_fingerprint.py
|
||||
|
||||
用途:立账凭证检核目录模板、文件名精确匹配与指纹稳定性单测。
|
||||
依赖:pytest、临时目录、voucher_check 领域模块。
|
||||
逻辑:不连 Oracle/共享盘;覆盖精确匹配、0 字节齐全、子目录不计、指纹变化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.voucher_check.config import (
|
||||
RequiredFileRule,
|
||||
validate_directory_template,
|
||||
)
|
||||
from app.services.voucher_check.fingerprint import build_material_fingerprint
|
||||
from app.services.voucher_check.share_scanner import (
|
||||
FileMeta,
|
||||
match_required_files,
|
||||
scan_invoice_folder,
|
||||
)
|
||||
|
||||
|
||||
def test_directory_template_rejects_unknown_placeholder():
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
validate_directory_template("{root}/{YYYY}/{MM}/{invoice_no}/{extra}")
|
||||
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_exact_filename_match_and_zero_byte_counts():
|
||||
rules = (
|
||||
RequiredFileRule(
|
||||
code="price_check_sheet",
|
||||
name="核价单",
|
||||
required=True,
|
||||
accepted_filenames=("核价单.pdf",),
|
||||
),
|
||||
RequiredFileRule(
|
||||
code="purchase_order",
|
||||
name="采购单",
|
||||
required=True,
|
||||
accepted_filenames=("采购单.pdf",),
|
||||
),
|
||||
)
|
||||
files = [
|
||||
FileMeta(name="核价单.pdf", size=0, mtime_ns=1),
|
||||
FileMeta(name="采购单.pdf", size=10, mtime_ns=2),
|
||||
]
|
||||
matched, missing = match_required_files(files, rules, case_sensitive=True)
|
||||
assert matched["price_check_sheet"] == "核价单.pdf"
|
||||
assert matched["purchase_order"] == "采购单.pdf"
|
||||
assert missing == []
|
||||
|
||||
|
||||
def test_subdir_same_name_does_not_count(tmp_path: Path):
|
||||
"""直接子文件才命中;子目录内同名文件不算。"""
|
||||
from app.services.voucher_check.config import VoucherCheckConfig
|
||||
|
||||
root = tmp_path / "vouche"
|
||||
inv_dir = root / "2026" / "08" / "INV001"
|
||||
inv_dir.mkdir(parents=True)
|
||||
nested = inv_dir / "nested"
|
||||
nested.mkdir()
|
||||
(nested / "核价单.pdf").write_bytes(b"x")
|
||||
(inv_dir / "采购单.pdf").write_bytes(b"y")
|
||||
|
||||
cfg = VoucherCheckConfig(
|
||||
scope_code="HXJM",
|
||||
directory_template="{root}/{YYYY}/{MM}/{invoice_no}",
|
||||
required_files=(
|
||||
RequiredFileRule("price_check_sheet", "核价单", True, ("核价单.pdf",)),
|
||||
RequiredFileRule("purchase_order", "采购单", True, ("采购单.pdf",)),
|
||||
),
|
||||
filename_case_sensitive=True,
|
||||
notify_missing_enabled=False,
|
||||
notify_failure_enabled=False,
|
||||
same_day_dedup_enabled=False,
|
||||
local_root=str(root),
|
||||
share_unc="",
|
||||
healthcheck_relative_path=".hxops-share-ready",
|
||||
erp_dsn="x",
|
||||
erp_username="u",
|
||||
erp_password="p",
|
||||
)
|
||||
result = scan_invoice_folder(
|
||||
cfg,
|
||||
root=str(root),
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV001",
|
||||
)
|
||||
assert result.result == "missing"
|
||||
assert any(m["code"] == "price_check_sheet" for m in result.missing_materials)
|
||||
assert result.matched_files.get("purchase_order") == "采购单.pdf"
|
||||
|
||||
|
||||
def test_fingerprint_stable_and_changes_on_mtime():
|
||||
a = build_material_fingerprint([("a.pdf", 1, 100), ("b.pdf", 2, 200)])
|
||||
b = build_material_fingerprint([("b.pdf", 2, 200), ("a.pdf", 1, 100)])
|
||||
assert a == b
|
||||
c = build_material_fingerprint([("a.pdf", 1, 101), ("b.pdf", 2, 200)])
|
||||
assert a != c
|
||||
@@ -1,52 +0,0 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_tool_auth_and_openapi.py
|
||||
|
||||
用途:立账凭证检核 Tool OpenAPI 静态规格校验(不依赖 Flask venv)。
|
||||
依赖:pytest、openapi_base.json。
|
||||
逻辑:直接读 JSON,校验 operationId 与 securitySchemes。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
_SPEC = (
|
||||
Path(__file__).resolve().parents[2]
|
||||
/ "app"
|
||||
/ "services"
|
||||
/ "voucher_check"
|
||||
/ "openapi_base.json"
|
||||
)
|
||||
|
||||
|
||||
def test_openapi_base_contains_expected_operations():
|
||||
spec = json.loads(_SPEC.read_text(encoding="utf-8"))
|
||||
paths = spec["paths"]
|
||||
assert (
|
||||
paths["/api/accounting-voucher-check/tools/tasks/{task_id}/missing"]["get"]["operationId"]
|
||||
== "list_voucher_missing"
|
||||
)
|
||||
assert (
|
||||
paths["/api/accounting-voucher-check/tools/runs/{run_id}/items"]["get"]["operationId"]
|
||||
== "list_voucher_run_items"
|
||||
)
|
||||
assert (
|
||||
paths["/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest"]["get"]["operationId"]
|
||||
== "get_voucher_invoice_latest"
|
||||
)
|
||||
assert "BearerAuth" in spec["components"]["securitySchemes"]
|
||||
assert "IntegrationKey" in spec["components"]["securitySchemes"]
|
||||
|
||||
|
||||
def test_docs_openapi_export_in_sync():
|
||||
docs = (
|
||||
Path(__file__).resolve().parents[3]
|
||||
/ "docs"
|
||||
/ "openapi"
|
||||
/ "accounting_voucher_check_tools_openapi.json"
|
||||
)
|
||||
assert docs.is_file(), "请运行 python backend/scripts/export_voucher_check_openapi.py"
|
||||
exported = json.loads(docs.read_text(encoding="utf-8"))
|
||||
base = json.loads(_SPEC.read_text(encoding="utf-8"))
|
||||
assert exported["paths"].keys() == base["paths"].keys()
|
||||
@@ -0,0 +1,203 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_workspace_force_recheck.py
|
||||
|
||||
用途:工作台强制重检入队(force_all)与并发冲突。
|
||||
依赖:pytest、Flask client;不执行真实周任务。
|
||||
逻辑:POST /api/workspace/accounting-voucher-check/runs 写入 run_options.mode=force_all;已有 queued 时 409。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
|
||||
DEFAULT_VOUCHER_CHECK_SCHEDULE_NO,
|
||||
ensure_default_voucher_check_schedule,
|
||||
)
|
||||
|
||||
|
||||
def _ensure_user(*, username: str, role: str) -> User:
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if user:
|
||||
user.role = role
|
||||
user.status = "active"
|
||||
db.session.commit()
|
||||
return user
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role=role,
|
||||
status="active",
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _stub_force_run_preflight(monkeypatch) -> None:
|
||||
"""隔离配置预校验,只验证工作台入队和失败可见性契约。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.config.load_engine_config",
|
||||
lambda _params: type("Config", (), {"profile_code": "sales"})(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.profile_loader.load_profile_definition",
|
||||
lambda _code: {"profile_code": "sales"},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.profile_loader.ensure_published_profile",
|
||||
lambda _code: None,
|
||||
)
|
||||
monkeypatch.setattr("app.services.voucher_check.dms_client.SalesDmsClient.ensure_configured", lambda: None)
|
||||
|
||||
|
||||
def test_dms_preflight_reports_missing_keys_without_secret_values(app, monkeypatch):
|
||||
"""DMS 配置缺失时要指出变量名,且不在错误内容中泄露凭据值。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(SalesDmsClient, "base_url", classmethod(lambda _cls: "https://dms.example"))
|
||||
monkeypatch.setattr(SalesDmsClient, "library_id", classmethod(lambda _cls: "library-id"))
|
||||
monkeypatch.setattr(SalesDmsClient, "root_folder_id", classmethod(lambda _cls: "folder-id"))
|
||||
monkeypatch.setattr(SalesDmsClient, "username", classmethod(lambda _cls: ""))
|
||||
monkeypatch.setattr(SalesDmsClient, "password", classmethod(lambda _cls: ""))
|
||||
try:
|
||||
SalesDmsClient.ensure_configured()
|
||||
except ValidationError as exc:
|
||||
assert exc.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
assert exc.details["missing"] == ["VOUCHER_CHECK_DMS_USERNAME", "VOUCHER_CHECK_DMS_PASSWORD"]
|
||||
else:
|
||||
raise AssertionError("expected missing DMS configuration to fail")
|
||||
|
||||
|
||||
def test_workspace_force_recheck_enqueues_force_all(app, client, admin_headers, monkeypatch):
|
||||
"""工作台按钮入队后,ScheduleRun 必须带 force_all,供 runner 跳过增量。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
task = ensure_default_voucher_check_schedule(commit=True)
|
||||
assert task is not None
|
||||
assert task.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO
|
||||
assert task.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH
|
||||
_stub_force_run_preflight(monkeypatch)
|
||||
|
||||
first = client.post(
|
||||
"/api/workspace/accounting-voucher-check/runs",
|
||||
json={"mode": "force_all"},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert first.status_code == 200
|
||||
data = parse_api_data(first.get_json())
|
||||
assert data["mode"] == "force_all"
|
||||
assert data["status"] == "queued"
|
||||
assert data["run_no"]
|
||||
|
||||
with app.app_context():
|
||||
run = db.session.get(ScheduleRun, data["schedule_run_id"])
|
||||
assert run is not None
|
||||
options = (run.api_request_json or {}).get("run_options") or {}
|
||||
assert options.get("mode") == "force_all"
|
||||
|
||||
second = client.post(
|
||||
"/api/workspace/accounting-voucher-check/runs",
|
||||
json={"mode": "force_all"},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert second.status_code == 409
|
||||
error = parse_api_error(second.get_json())
|
||||
assert error["code"] == "VOUCHER_CHECK.RUN_IN_PROGRESS"
|
||||
|
||||
|
||||
def test_workspace_force_recheck_rejects_non_admin_and_invalid_mode(app, client, admin_headers, user_headers, monkeypatch):
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
_ensure_user(username="user", role="user")
|
||||
ensure_default_voucher_check_schedule(commit=True)
|
||||
_stub_force_run_preflight(monkeypatch)
|
||||
|
||||
forbidden = client.post(
|
||||
"/api/workspace/accounting-voucher-check/runs",
|
||||
json={"mode": "force_all"},
|
||||
headers=user_headers,
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
invalid = client.post(
|
||||
"/api/workspace/accounting-voucher-check/runs",
|
||||
json={"mode": "incremental"},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
error = parse_api_error(invalid.get_json())
|
||||
assert error["code"] == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_workspace_lists_pre_engine_failure_for_selected_period(app, client, admin_headers):
|
||||
"""配置校验在建引擎批次前失败时,页面仍应展示技术失败与原因。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
task = ensure_default_voucher_check_schedule(commit=True)
|
||||
assert task is not None
|
||||
run = ScheduleRun(
|
||||
schedule_task_id=task.id,
|
||||
run_no="RUN-PREENGINE-FAILED",
|
||||
trigger_type="manual",
|
||||
status="failed",
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=1,
|
||||
error_message="未配置销售开票附件文档库根目录",
|
||||
response_summary_json={"voucher_check": {"period": "2026-08"}},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08&status=technical_failed",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload["total"] == 1
|
||||
item = payload["items"][0]
|
||||
# 关键断言:前端列表读取的 run 数据保留失败原因,而非呈现为“暂无检核批次”。
|
||||
assert item["run_no"] == "RUN-PREENGINE-FAILED"
|
||||
assert item["status"] == "technical_failed"
|
||||
assert item["error_message"] == "未配置销售开票附件文档库根目录"
|
||||
|
||||
|
||||
def test_seed_strips_legacy_share_job_params(app):
|
||||
"""已有排程若仍带共享盘旧字段,启动/入队种子必须剥掉,否则 worker 会 unknown params。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
task = ensure_default_voucher_check_schedule(commit=True)
|
||||
assert task is not None
|
||||
task.job_params = {
|
||||
"scope_code": "HXJM",
|
||||
"profile_code": "sales",
|
||||
"notify_missing_enabled": True,
|
||||
"notify_failure_enabled": True,
|
||||
"directory_template": "{root}/{YYYY}/{MM}/{invoice_no}",
|
||||
"dir_template": "{root}/{YYYY}/{MM}/{invoice_no}",
|
||||
"required_files": ["核价单.pdf", "采购单.pdf"],
|
||||
"filename_case_sensitive": True,
|
||||
"case_sensitive": False,
|
||||
"same_day_dedup_enabled": True,
|
||||
"same_day_dedup": True,
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
refreshed = ensure_default_voucher_check_schedule(commit=True)
|
||||
params = refreshed.job_params if isinstance(refreshed.job_params, dict) else {}
|
||||
assert "directory_template" not in params
|
||||
assert "dir_template" not in params
|
||||
assert "required_files" not in params
|
||||
assert "filename_case_sensitive" not in params
|
||||
assert "case_sensitive" not in params
|
||||
assert "same_day_dedup_enabled" not in params
|
||||
assert "same_day_dedup" not in params
|
||||
assert params["scope_code"] == "HXJM"
|
||||
assert params["profile_code"] == "sales"
|
||||
@@ -0,0 +1,144 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_workspace_notifications.py
|
||||
|
||||
用途:工作台企微发送记录列表 API。
|
||||
依赖:pytest、Flask client;不发送真实企微。
|
||||
逻辑:GET /api/workspace/accounting-voucher-check/notifications 读 voucher_check_notifications,
|
||||
回填接收人姓名与 has_excel,并可按期间、发送状态筛选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from tests.conftest import parse_api_data
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, User
|
||||
from app.models.voucher_check import VoucherCheckNotification, VoucherCheckRun
|
||||
from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule
|
||||
|
||||
|
||||
def _ensure_user(*, username: str, role: str, real_name: str | None = None) -> User:
|
||||
"""测试用户幂等创建。"""
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if user:
|
||||
user.role = role
|
||||
user.status = "active"
|
||||
if real_name:
|
||||
user.real_name = real_name
|
||||
db.session.commit()
|
||||
return user
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role=role,
|
||||
status="active",
|
||||
real_name=real_name,
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_workspace_lists_wecom_notifications(app, client, user_headers):
|
||||
"""企微发送记录列表应带出批次统计、接收人姓名,并按发送状态筛选。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="admin", role="admin")
|
||||
recipient = _ensure_user(username="user", role="user", real_name="Zhang San")
|
||||
task = ensure_default_voucher_check_schedule(commit=True)
|
||||
assert task is not None
|
||||
schedule_run = ScheduleRun(
|
||||
schedule_task_id=task.id,
|
||||
run_no="RUN-VC-NOTIFY-1",
|
||||
trigger_type="cron",
|
||||
status="success",
|
||||
excel_file_name="voucher-check-2026-08.xlsx",
|
||||
excel_file_size=12,
|
||||
excel_file_data=b"xlsx-bytes",
|
||||
)
|
||||
db.session.add(schedule_run)
|
||||
db.session.flush()
|
||||
engine_run = VoucherCheckRun(
|
||||
id=1,
|
||||
schedule_run_id=schedule_run.id,
|
||||
run_no="VC-202608-001",
|
||||
profile_code="sales",
|
||||
profile_version="1",
|
||||
profile_snapshot_json={"profile_code": "sales"},
|
||||
period_month=date(2026, 8, 1),
|
||||
mode="incremental",
|
||||
status="missing",
|
||||
subject_count=10,
|
||||
missing_file_count=4,
|
||||
missing_invoice_count=2,
|
||||
)
|
||||
db.session.add(engine_run)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
VoucherCheckNotification(
|
||||
id=1,
|
||||
run_id=engine_run.id,
|
||||
excel_filename="voucher-check-2026-08.xlsx",
|
||||
recipient_user_ids_json=[recipient.id],
|
||||
send_status="sent",
|
||||
skip_reason=None,
|
||||
summary_json={"period": "2026-08", "subject_count": 10},
|
||||
sent_at=datetime(2026, 9, 1, 6, 10, 0),
|
||||
)
|
||||
)
|
||||
skipped_run = VoucherCheckRun(
|
||||
id=2,
|
||||
run_no="VC-202607-001",
|
||||
profile_code="sales",
|
||||
profile_version="1",
|
||||
profile_snapshot_json={"profile_code": "sales"},
|
||||
period_month=date(2026, 7, 1),
|
||||
mode="incremental",
|
||||
status="completed",
|
||||
subject_count=8,
|
||||
missing_file_count=0,
|
||||
missing_invoice_count=0,
|
||||
)
|
||||
db.session.add(skipped_run)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
VoucherCheckNotification(
|
||||
id=2,
|
||||
run_id=skipped_run.id,
|
||||
send_status="skipped_no_missing",
|
||||
skip_reason="本批无缺件",
|
||||
summary_json={"period": "2026-07"},
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
listed = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
payload = parse_api_data(listed.get_json())
|
||||
assert payload["total"] >= 2
|
||||
sent = next(item for item in payload["items"] if item["run_no"] == "VC-202608-001")
|
||||
# 关键断言:工作台汇总列表能看到发送状态、接收人姓名和 Excel 入口。
|
||||
assert sent["send_status"] == "sent"
|
||||
assert sent["missing_invoice_count"] == 2
|
||||
assert sent["missing_file_count"] == 4
|
||||
assert sent["recipient_names"] == ["Zhang San"]
|
||||
assert sent["has_excel"] is True
|
||||
assert sent["schedule_run_id"]
|
||||
|
||||
filtered = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications?period=2026-07&send_status=skipped_no_missing",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert filtered.status_code == 200
|
||||
filtered_payload = parse_api_data(filtered.get_json())
|
||||
assert filtered_payload["total"] == 1
|
||||
item = filtered_payload["items"][0]
|
||||
assert item["run_no"] == "VC-202607-001"
|
||||
assert item["send_status"] == "skipped_no_missing"
|
||||
assert item["skip_reason"] == "本批无缺件"
|
||||
assert item["has_excel"] is False
|
||||
Reference in new issue
Block a user