Merge branch 'dev' of https://gitee.com/justop/hxops into dev
This commit is contained in:
commit
c1e32c9ca6
121 files changed
+6539
-697
No files matched your search
@@ -19,7 +19,7 @@ def test_agent_type_catalog_contains_three_seed_types():
|
||||
"""Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。"""
|
||||
assert {
|
||||
'generic', 'shipping_notice', 'file_check',
|
||||
'procurement_contract_review', 'in_transit_transfer',
|
||||
'procurement_contract_review', 'in_transit_transfer', 'contract_payment',
|
||||
} <= set(AGENT_TYPE_CATALOG.keys())
|
||||
|
||||
|
||||
@@ -28,12 +28,13 @@ def test_list_type_catalog_includes_agent_code_and_label():
|
||||
catalog = list_type_catalog()
|
||||
assert len(catalog) >= 5
|
||||
codes = {entry['agent_code'] for entry in catalog}
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer'} <= codes
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer', 'contract_payment'} <= codes
|
||||
labels = {entry['label'] for entry in catalog}
|
||||
assert '通用问答 / 知识库' in labels
|
||||
assert '在途仓自动调拨' in labels
|
||||
assert '货代发货通知' in labels
|
||||
assert '文件检核' in labels
|
||||
assert '合同付款预警' in labels
|
||||
|
||||
|
||||
def test_get_catalog_entry_returns_runtime_handler_for_hybrid_types():
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_agent_registry_contract_payment.py
|
||||
|
||||
用途:验证 contract_payment 已注册为 builtin Chat Agent 类型。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap。
|
||||
逻辑:只读断言 Catalog 声明与 Handler 绑定;不创建 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.agent_registry import catalog_bindings
|
||||
from app.services.agent_registry.catalog_loader import build_agent_type_catalog, get_catalog_entry
|
||||
from app.services.agent_registry.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_contract_payment_type_in_catalog():
|
||||
"""catalog 必须包含 contract_payment,默认 builtin + task_chat。"""
|
||||
entry = get_catalog_entry('contract_payment')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '合同付款预警'
|
||||
assert entry.get('runtime_provider_default') == 'builtin'
|
||||
assert entry.get('conversation_mode_default') == 'task_chat'
|
||||
assert entry.get('runtime_handler') == 'contract_payment'
|
||||
|
||||
|
||||
def test_contract_payment_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 contract_payment 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['contract_payment'] == 'contract_payment'
|
||||
|
||||
|
||||
def test_contract_payment_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 ContractPaymentHandler。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('contract_payment')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'contract_payment'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_contract_payment_present_in_full_catalog():
|
||||
"""完整 catalog 与既有类型共存。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'contract_payment' in catalog
|
||||
assert 'shipping_notice' in catalog
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_ledger_focus.py
|
||||
|
||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、待补充、本月应付合同后核对计数与 focus 筛选。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,12 +11,12 @@ from __future__ import annotations
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户。"""
|
||||
"""创建已授予合同付款预警 Agent 的落库用户。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
@@ -26,9 +26,22 @@ def _create_user(*, username: str) -> User:
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
@@ -76,7 +89,8 @@ def _seed_focus_contracts() -> None:
|
||||
_add_node(due, due=today.replace(day=14))
|
||||
overdue = _add_contract(contract_no='HT-FOCUS-OVERDUE')
|
||||
_add_node(overdue, due=date(2026, 8, 20))
|
||||
_add_contract(contract_no='HT-FOCUS-NEEDS')
|
||||
active = _add_contract(contract_no='HT-FOCUS-ACTIVE')
|
||||
_add_node(active, due=date(2026, 11, 1))
|
||||
month = _add_contract(contract_no='HT-FOCUS-MONTH')
|
||||
_add_node(month, due=date(2026, 9, 28))
|
||||
db.session.commit()
|
||||
@@ -87,10 +101,10 @@ def test_ledger_focus_counts_by_contract(app):
|
||||
with app.app_context():
|
||||
_seed_focus_contracts()
|
||||
counts = ledger_focus_counts(session=db.session, today=date(2026, 9, 10))
|
||||
# 关键断言:即将到期 1、逾期 1、待补充 1、本月应付为 9/14 与 9/28 两份。
|
||||
# 关键断言:即将到期 1、逾期 1、进行中 2(11/1 与 9/28)、本月应付为 9/14 与 9/28 两份。
|
||||
assert counts['due'] == 1
|
||||
assert counts['overdue'] == 1
|
||||
assert counts['needs_completion'] == 1
|
||||
assert counts['active'] == 2
|
||||
assert counts['due_this_month'] == 2
|
||||
|
||||
|
||||
@@ -106,12 +120,19 @@ def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
||||
|
||||
headers = _auth_headers(user)
|
||||
overdue = client.get('/api/contract-payment/contracts?focus=overdue', headers=headers)
|
||||
active = client.get('/api/contract-payment/contracts?focus=active', headers=headers)
|
||||
summary = client.get('/api/contract-payment/contracts/summary', headers=headers)
|
||||
empty = client.get('/api/contract-payment/contracts?focus=overdue&keyword=NO-SUCH', headers=headers)
|
||||
# 关键断言:逾期卡只筛出逾期合同;汇总仍看全量台账。
|
||||
# 关键断言:逾期卡只筛出逾期合同;进行中含未到期的 11/1 与本月 9/28;汇总仍看全量台账。
|
||||
assert overdue.status_code == 200
|
||||
data = overdue.get_json()['data']
|
||||
assert data['total'] == 1
|
||||
assert data['items'][0]['contract_no'] == 'HT-FOCUS-OVERDUE'
|
||||
assert {item['contract_no'] for item in active.get_json()['data']['items']} == {
|
||||
'HT-FOCUS-ACTIVE',
|
||||
'HT-FOCUS-MONTH',
|
||||
}
|
||||
assert summary.get_json()['data']['overdue'] == 1
|
||||
assert summary.get_json()['data']['active'] == 2
|
||||
assert 'needs_completion' not in summary.get_json()['data']
|
||||
assert empty.get_json()['data']['total'] == 0
|
||||
@@ -2,18 +2,18 @@
|
||||
backend/tests/test_contract_payment_list.py
|
||||
|
||||
用途:验收合同付款台账列表的 keyword 筛选,尤其是按供应商名称模糊匹配。
|
||||
依赖:Flask test client、ContractPaymentContract、用户功能权限。
|
||||
依赖:Flask test client、ContractPaymentContract、Agent 授权。
|
||||
逻辑:构造两份已解析合同,确认供应商片段只命中对应行,且合同号/采购单号检索仍可用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, User
|
||||
from app.models import Agent, ContractPaymentContract, User
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户,供列表接口走 legacy header 认证。"""
|
||||
"""创建已授予合同付款预警 Agent 的落库用户,供列表接口走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
@@ -23,9 +23,22 @@ def _create_user(*, username: str) -> User:
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
|
||||
@@ -1,31 +1,19 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_permissions.py
|
||||
|
||||
用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。
|
||||
依赖:User 功能权限、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账,但不能触发同步/扫描/发送;关闭 admin 覆盖后同样 403。
|
||||
用途:验收合同付款预警改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 无需绑定即可查询;普通用户默认 403;授予 contract_payment Agent 后可查询台账,
|
||||
但不能触发同步/扫描/发送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _make_memory_user(*, role: str, overrides: dict | None = None) -> User:
|
||||
"""构造带功能权限覆盖的内存用户(不落库,仅测 has_feature_permission)。"""
|
||||
user = User(username=f'cp-{role}', role=role)
|
||||
if overrides is not None:
|
||||
user.feature_permissions = overrides
|
||||
return user
|
||||
|
||||
|
||||
def _create_user(
|
||||
*,
|
||||
username: str,
|
||||
role: str = 'user',
|
||||
feature_permissions: dict | None = None,
|
||||
) -> User:
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
"""创建落库用户,供 contract-payment API 走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
@@ -36,11 +24,39 @@ def _create_user(
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions(feature_permissions)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def _ensure_contract_payment_agent() -> Agent:
|
||||
"""确保存在启用中的合同付款预警 Agent,供授权绑定。"""
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if agent:
|
||||
return agent
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(agent)
|
||||
return agent
|
||||
|
||||
|
||||
def _grant_contract_payment_agent(user: User) -> User:
|
||||
"""把合同付款预警 Agent 授权给指定用户并重新取出,避免会话分离后丢失关系。"""
|
||||
agent = _ensure_contract_payment_agent()
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
@@ -62,49 +78,16 @@ def _json_error(response) -> dict:
|
||||
return body['error']
|
||||
|
||||
|
||||
def test_admin_default_has_contract_payment_access(app):
|
||||
"""admin 角色默认具备 contract_payment.access;普通用户默认无。"""
|
||||
with app.app_context():
|
||||
admin = _make_memory_user(role='admin')
|
||||
user = _make_memory_user(role='user')
|
||||
# 关键断言:不新建角色,仅功能键裁剪工作台访问。
|
||||
assert admin.can_access_contract_payment() is True
|
||||
assert user.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_explicit_grant_and_revoke_contract_payment_access(app):
|
||||
"""普通用户可被显式授予;admin 可被显式关闭。"""
|
||||
with app.app_context():
|
||||
granted = _make_memory_user(role='user', overrides={'contract_payment.access': True})
|
||||
revoked_admin = _make_memory_user(role='admin', overrides={'contract_payment.access': False})
|
||||
# 关键断言:显式覆盖优先于角色默认。
|
||||
assert granted.can_access_contract_payment() is True
|
||||
assert revoked_admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_set_feature_permissions_persists_contract_payment_override(app):
|
||||
"""用户表单保存时只持久化与角色默认值不同的 contract_payment.access。"""
|
||||
with app.app_context():
|
||||
user = User(username='cp-override', role='user')
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
# 关键断言:未知键被忽略,已知覆盖项写入 JSON。
|
||||
assert user.feature_permissions == {'contract_payment.access': True}
|
||||
assert user.can_access_contract_payment() is True
|
||||
|
||||
admin = User(username='cp-admin-override', role='admin')
|
||||
admin.set_feature_permissions({'contract_payment.access': False})
|
||||
assert admin.feature_permissions == {'contract_payment.access': False}
|
||||
assert admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
"""无权限用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
def test_contract_payment_api_forbids_user_without_agent(client, app):
|
||||
"""未授予 Agent 的普通用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
with app.app_context():
|
||||
ordinary = _create_user(username='cp_api_denied')
|
||||
_ensure_contract_payment_agent()
|
||||
db.session.expunge(ordinary)
|
||||
|
||||
headers = _auth_headers(ordinary)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:登录不足够,专项权限缺失必须 403。
|
||||
# 关键断言:登录不足够,Agent 授权缺失必须 403。
|
||||
assert list_res.status_code == 403
|
||||
assert _json_error(list_res)['code'] == 'CONTRACT_PAYMENT.FORBIDDEN'
|
||||
|
||||
@@ -114,29 +97,36 @@ def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_granted_user(client, app):
|
||||
"""显式授予后普通用户可以查询台账。"""
|
||||
"""授予 contract_payment Agent 后普通用户可以查询台账。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_granted',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
granted = _grant_contract_payment_agent(_create_user(username='cp_api_granted'))
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:授予后不再 403,返回标准成功 envelope。
|
||||
# 关键断言:Agent 授权后不再 403,返回标准成功 envelope。
|
||||
assert list_res.status_code == 200
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_admin_without_agent_binding(client, app):
|
||||
"""平台 admin 即使未绑定该 Agent 也可查询台账。"""
|
||||
with app.app_context():
|
||||
admin = _create_user(username='cp_api_admin', role='admin')
|
||||
_ensure_contract_payment_agent()
|
||||
db.session.expunge(admin)
|
||||
|
||||
headers = _auth_headers(admin)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
assert list_res.status_code == 200
|
||||
assert list_res.get_json().get('success') is True
|
||||
|
||||
|
||||
def test_contract_payment_jobs_require_admin(client, app):
|
||||
"""已授权的普通用户可查台账,但不能触发同步、扫描或周汇总发送。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_jobs_denied',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
granted = _grant_contract_payment_agent(_create_user(username='cp_api_jobs_denied'))
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
# 关键断言:访问权不等于操作权,手动任务仅管理员。
|
||||
|
||||
@@ -38,6 +38,7 @@ def test_platform_jobs_registered():
|
||||
assert "shipping-inventory-rpa" in keys
|
||||
assert "faq-aggregate-hot" in keys
|
||||
assert "fixed-assets-snapshot" in keys
|
||||
assert "accounting-voucher-po-print" in keys
|
||||
assert get_platform_job("shipping-inventory-rpa") is not None
|
||||
|
||||
|
||||
@@ -217,6 +218,7 @@ def test_get_platform_jobs_api(client, admin_jwt_headers):
|
||||
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
|
||||
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
|
||||
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
|
||||
assert by_key["accounting-voucher-po-print"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherPoPrint"
|
||||
|
||||
defs = client.get("/api/admin/platform-tasks/definitions", headers=admin_jwt_headers)
|
||||
assert defs.status_code == 200
|
||||
|
||||
@@ -18,7 +18,7 @@ import pytest
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, AgentGuide, TrainingConfig, TrainingConfigResource, TrainingRecord, User
|
||||
from app.services import training_config_service, training_service
|
||||
from app.services import lean_training_service, training_config_service, training_service
|
||||
from app.services.training_service import _grade_answer_details, _normalize_question_bank
|
||||
from app.api.chat import preview_support
|
||||
|
||||
@@ -236,6 +236,38 @@ def test_training_user_progress_round_trip_and_completion(client, app):
|
||||
assert record.completion_time is not None
|
||||
|
||||
|
||||
def test_overseas_regulations_video_completion_creates_passed_result(client, app):
|
||||
"""关键断言:自定义编码的出国规章培训完整观看视频后无需题库作答,也必须落库为一次完成。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username="overseas_video_completion")
|
||||
agent = _create_training_agent(name="overseas_video_agent")
|
||||
db.session.add(TrainingConfig(
|
||||
training_type="overseas_policy_v2",
|
||||
name="出国规章培训",
|
||||
version="v1",
|
||||
status="published",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json={
|
||||
"agent_id": agent.id,
|
||||
"type": "overseas_policy_v2",
|
||||
"stage": "result",
|
||||
"score": 100,
|
||||
"passed": True,
|
||||
"attempt_count": 0,
|
||||
"answer_details": [],
|
||||
})
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["training_type"] == "overseas_policy_v2"
|
||||
assert body["stage"] == "result"
|
||||
assert body["passed"] is True
|
||||
assert body["status"] == "passed"
|
||||
assert isinstance(body["completion_time"], str) and body["completion_time"]
|
||||
|
||||
|
||||
def test_safety_training_progress_round_trip(client, app):
|
||||
"""安全培训应持久化培训版本、考试模式、三级状态和级别进度。"""
|
||||
with app.app_context():
|
||||
@@ -583,11 +615,34 @@ def test_training_admin_list_stats_and_export_share_one_fact_source(client, app)
|
||||
workbook = load_workbook(BytesIO(export_res.data))
|
||||
sheet = workbook.active
|
||||
rows = list(sheet.iter_rows(values_only=True))
|
||||
assert rows[0] == ("入职日期", "完成日期", "部门", "姓名", "工号", "分数", "考试次数", "状态")
|
||||
assert rows[0] == ("入职日期", "完成日期", "培训类型", "部门", "姓名", "工号", "分数", "考试次数", "状态")
|
||||
assert len(rows) == 3
|
||||
assert rows[1][2] == "生产一部"
|
||||
assert rows[2][2] == "生产一部"
|
||||
assert {rows[1][7], rows[2][7]} == {"passed", "failed"}
|
||||
assert rows[1][3] == "生产一部"
|
||||
assert rows[2][3] == "生产一部"
|
||||
assert {rows[1][8], rows[2][8]} == {"已通过", "未通过"}
|
||||
|
||||
|
||||
def test_lean_dashboard_export_uses_page_time_and_status_labels(monkeypatch):
|
||||
"""精益看板 Excel 必须复用页面的分钟级时间格式与中文状态文案。"""
|
||||
monkeypatch.setattr(
|
||||
lean_training_service,
|
||||
"list_dashboard",
|
||||
lambda task_id: {
|
||||
"task": {"week_index": 2, "week_key": "2026-09-14", "due_at": "2026-09-20T23:59:59"},
|
||||
"completed": [{"employee_id": "EMP-001", "name": "张三", "department": "生产部", "videos": [{"name": "精益视频", "watched_at": "2026-09-15T08:30:45"}], "status": "completed", "summary_text": "已完成学习", "completed_at": "2026-09-15T09:00:12"}],
|
||||
"incomplete": [{"employee_id": "EMP-002", "name": "李四", "department": "品质部", "videos": [], "status": "overdue", "summary_text": None, "completed_at": None}],
|
||||
"periods": [],
|
||||
},
|
||||
)
|
||||
|
||||
file_data, _ = lean_training_service.export_dashboard_excel(1)
|
||||
rows = list(load_workbook(BytesIO(file_data)).active.iter_rows(values_only=True))
|
||||
|
||||
assert rows[1][2] == "2026-09-20 23:59"
|
||||
assert rows[1][7] == "2026-09-15 08:30"
|
||||
assert rows[1][8] == "已完成"
|
||||
assert rows[1][10] == "2026-09-15 09:00"
|
||||
assert rows[2][8] == "已延期"
|
||||
|
||||
|
||||
def test_training_preview_proxy_reads_kb_storage_without_http_callback(monkeypatch, tmp_path, app):
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_engine_profile_and_scan.py
|
||||
|
||||
用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。
|
||||
依赖:pytest;不连 Oracle / 文档库。
|
||||
逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。
|
||||
逻辑:覆盖上月边界、oma_file 发票 SQL、六类文件名、同一 invoice 多缺件、PO fetch()/OA 仍未接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,11 +18,39 @@ from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryS
|
||||
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.erp_repository import _INVOICE_SQL, is_sales_invoice_no, 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_invoice_sql_reads_confirmed_oma_file():
|
||||
"""销售 invoice 清单来自 oma_file:已确认、未作废、状况码 1、帐款类别 11/12/13;oma10 至少 6 位字母或数字。"""
|
||||
sql = " ".join(_INVOICE_SQL.split())
|
||||
assert "FROM oma_file" in sql
|
||||
assert "TRIM(oma10)" in sql
|
||||
assert "TRUNC(oma02)" in sql
|
||||
assert "REGEXP_LIKE(TRIM(oma10), '^[A-Za-z0-9]{6,}$')" in sql
|
||||
assert "TRIM(omaconf) = 'Y'" in sql
|
||||
assert "TRIM(omavoid) = 'N'" in sql
|
||||
assert "TRIM(oma64) = '1'" in sql
|
||||
assert "TRIM(oma00) IN ('11', '12', '13')" in sql
|
||||
assert "apa_file" not in sql
|
||||
assert "apa08" not in sql
|
||||
|
||||
|
||||
def test_sales_invoice_no_rejects_placeholder_and_chinese():
|
||||
"""正规发票号为至少 6 位字母或数字;0、空值、中文备注不能进主体清单。"""
|
||||
assert is_sales_invoice_no("6975101806") is True
|
||||
assert is_sales_invoice_no("394522129") is True
|
||||
assert is_sales_invoice_no("EWZZ26090002") is True
|
||||
assert is_sales_invoice_no("ewzz26090006") is True
|
||||
assert is_sales_invoice_no("0") is False
|
||||
assert is_sales_invoice_no("泰国HUB仓出货") is False
|
||||
assert is_sales_invoice_no("") is False
|
||||
assert is_sales_invoice_no(" ") is False
|
||||
assert is_sales_invoice_no(None) is False
|
||||
|
||||
|
||||
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"))
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_erp_po_repository.py
|
||||
|
||||
用途:HXJM.oma99 → TGHX.pmm99 采购单取数与字段映射。
|
||||
依赖:pytest;不连 Oracle。
|
||||
逻辑:断言 TRIM 关联、oma99 空走 oga/oea、到货日 pmn34、周检核 fetch 仍未接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.erp_po_repository import (
|
||||
INVOICE_SCHEMA,
|
||||
PO_SCHEMA,
|
||||
_po_detail_sql,
|
||||
fetch_po_documents_for_invoices,
|
||||
map_po_document,
|
||||
resolve_invoice_flows,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
class _NamedCursor:
|
||||
"""按 SQL 关键字返回带列名的预制行。"""
|
||||
|
||||
def __init__(self, scripts: dict[str, tuple[list[str], list[tuple]]]):
|
||||
self.scripts = scripts
|
||||
self.executed: list[tuple[str, dict | None]] = []
|
||||
self.description: list[tuple[str]] = []
|
||||
self._rows: list[tuple] = []
|
||||
|
||||
def execute(self, sql: str, params=None):
|
||||
self.executed.append((sql, params))
|
||||
compact = " ".join(sql.split()).upper()
|
||||
for needle, (columns, rows) in self.scripts.items():
|
||||
if needle.upper() in compact:
|
||||
self.description = [(name,) for name in columns]
|
||||
self._rows = list(rows)
|
||||
return
|
||||
raise AssertionError(f"unexpected sql: {sql}")
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._rows)
|
||||
|
||||
|
||||
def _config():
|
||||
return SimpleNamespace(erp_dsn="host/db", erp_username="ro", erp_password="x", erp_timeout_seconds=5)
|
||||
|
||||
|
||||
_OMA_COLS = ["invoice_no", "oma00", "oma16", "oma99"]
|
||||
_FLOW_COLS = ["doc_no", "flow_no"]
|
||||
|
||||
|
||||
def test_po_sql_targets_tghx_and_trims_flow_no():
|
||||
"""采购单必须查 TGHX,并用 TRIM(pmm99) 对多角序号。"""
|
||||
sql = " ".join(_po_detail_sql(":flow0").split())
|
||||
assert f"FROM {PO_SCHEMA}.pmm_file" in sql
|
||||
assert f"{PO_SCHEMA}.pmn_file" in sql
|
||||
assert "TRIM(pmm.pmm99) IN" in sql
|
||||
assert "TRIM(pmm.pmm18) != 'X'" in sql
|
||||
assert "TRIM(pmm.pmmacti) = 'Y'" in sql
|
||||
assert "BKR" in sql
|
||||
assert "pmn34" in sql
|
||||
assert INVOICE_SCHEMA not in sql
|
||||
|
||||
|
||||
def test_map_po_document_uses_pmn34_and_sample_like_fields():
|
||||
"""到货日用 pmn34;环保等级 RoHS;原始编号优先 ta_ima11。"""
|
||||
document = map_po_document(
|
||||
"EWZZ26090002",
|
||||
[
|
||||
{
|
||||
"po_no": "5220-2609010001",
|
||||
"po_date": date(2026, 9, 1),
|
||||
"po_type": "原料采购单",
|
||||
"pay_term": "月结一个月",
|
||||
"tax_type": "进项(17%含税)",
|
||||
"price_term_code": "A01",
|
||||
"price_term_name": "取核价单价",
|
||||
"currency": "RMB",
|
||||
"vendor_code": "V001",
|
||||
"vendor_name": "测试厂",
|
||||
"vendor_tel": "0512-1",
|
||||
"vendor_fax": "0512-2",
|
||||
"vendor_addr": "苏州",
|
||||
"ship031": "送货路",
|
||||
"ship032": "1号",
|
||||
"bill031": "账单路",
|
||||
"company_name": "TGHX公司",
|
||||
"company_address": "地址",
|
||||
"company_phone": "123",
|
||||
"company_fax": "",
|
||||
"pmn02": 1,
|
||||
"pmn04": "3450541801",
|
||||
"pmn041": "FRAME",
|
||||
"ima021": "H20",
|
||||
"pmn20": 730,
|
||||
"pmn07": "PCS",
|
||||
"pmn34": date(2026, 9, 16),
|
||||
"pmn33": date(2026, 9, 10),
|
||||
"pmn24": "3301-1",
|
||||
"ta_ima11": "RAW-11",
|
||||
"pmnud02": "-0001",
|
||||
"pmn31": "3.35",
|
||||
"pmn31t": "3.9195",
|
||||
"pmn88": "2445.5",
|
||||
"pmn88t": "2861.24",
|
||||
"ta_ima02": "1",
|
||||
"ta_ima03": "1",
|
||||
"pmn06": "VEN-1",
|
||||
"azi03": 6,
|
||||
"azi04": 2,
|
||||
"azi05": 2,
|
||||
}
|
||||
],
|
||||
)
|
||||
assert document.invoice_no == "EWZZ26090002"
|
||||
assert document.po_no == "5220-2609010001"
|
||||
assert document.po_date == "2026/9/1"
|
||||
assert document.price_term == "A01 取核价单价"
|
||||
assert document.ship_address == "送货路1号"
|
||||
assert document.lines[0].arrive == "2026/9/16"
|
||||
assert document.lines[0].halogen == "RoHS"
|
||||
assert document.lines[0].origin_no == "RAW-11"
|
||||
assert document.lines[0].version == "-0001"
|
||||
assert document.untax_total == "2,445.50"
|
||||
assert document.maker == ""
|
||||
|
||||
|
||||
def test_map_po_document_falls_back_origin_and_halogen():
|
||||
"""原始编号空 ta_ima11 时用 pmn24;无环保码时用卤素管控。"""
|
||||
document = map_po_document(
|
||||
"INV0001",
|
||||
[
|
||||
{
|
||||
"po_no": "PO1",
|
||||
"pmn02": 1,
|
||||
"pmn24": "3301-9",
|
||||
"ta_ima11": " ",
|
||||
"ta_ima02": "1",
|
||||
"ta_ima03": "",
|
||||
"pmn88": 0,
|
||||
"pmn88t": 0,
|
||||
}
|
||||
],
|
||||
)
|
||||
assert document.lines[0].origin_no == "3301-9"
|
||||
assert document.lines[0].halogen == "无卤"
|
||||
|
||||
|
||||
def test_resolve_invoice_flows_prefers_oma99():
|
||||
cursor = _NamedCursor(
|
||||
{
|
||||
"OMA_FILE": (
|
||||
_OMA_COLS,
|
||||
[("EWZZ26090002", "12", "8520-2609010002", "S004 -26090001")],
|
||||
)
|
||||
}
|
||||
)
|
||||
flows = resolve_invoice_flows(cursor, ["EWZZ26090002"])
|
||||
assert len(flows) == 1
|
||||
assert flows[0].flow_no == "S004 -26090001"
|
||||
assert not any("OGA_FILE" in sql.upper() or "OEA_FILE" in sql.upper() for sql, _ in cursor.executed)
|
||||
|
||||
|
||||
def test_resolve_invoice_flows_uses_oga99_when_oma99_empty():
|
||||
cursor = _NamedCursor(
|
||||
{
|
||||
"OMA_FILE": (_OMA_COLS, [("EWZZ1A", "12", "8520-1", "")]),
|
||||
"OGA_FILE": (_FLOW_COLS, [("8520-1", "S004-FALLBACK")]),
|
||||
}
|
||||
)
|
||||
flows = resolve_invoice_flows(cursor, ["EWZZ1A"])
|
||||
assert flows[0].flow_no == "S004-FALLBACK"
|
||||
assert any("OGA_FILE" in sql.upper() for sql, _ in cursor.executed)
|
||||
|
||||
|
||||
def test_resolve_invoice_flows_uses_oea99_for_deposit():
|
||||
cursor = _NamedCursor(
|
||||
{
|
||||
"OMA_FILE": (_OMA_COLS, [("EWZZ1B", "11", "1101-1", None)]),
|
||||
"OEA_FILE": (_FLOW_COLS, [("1101-1", "S004-SO")]),
|
||||
}
|
||||
)
|
||||
flows = resolve_invoice_flows(cursor, ["EWZZ1B"])
|
||||
assert flows[0].oma00 == "11"
|
||||
assert flows[0].flow_no == "S004-SO"
|
||||
assert any("OEA_FILE" in sql.upper() for sql, _ in cursor.executed)
|
||||
|
||||
|
||||
def test_fetch_po_documents_crosses_invoice_and_po(monkeypatch):
|
||||
"""同一流程序号下的采购单挂到对应发票;绑定值已 TRIM。"""
|
||||
|
||||
class _Cursor(_NamedCursor):
|
||||
def execute(self, sql, params=None):
|
||||
super().execute(sql, params)
|
||||
compact = " ".join(sql.split()).upper()
|
||||
if "PMM_FILE" in compact:
|
||||
assert params is not None
|
||||
assert "S004-26090001" in params.values()
|
||||
|
||||
class _Conn:
|
||||
def cursor(self):
|
||||
return _Cursor(
|
||||
{
|
||||
"OMA_FILE": (_OMA_COLS, [("EWZZ26090002", "12", "8520-1", "S004-26090001")]),
|
||||
"PMM_FILE": (
|
||||
["flow_no", "po_no", "po_date", "pmn02", "pmn04", "pmn20", "pmn34", "pmn88", "pmn88t"],
|
||||
[
|
||||
("S004-26090001", "5220-2609010001", date(2026, 9, 1), 1, "P1", 10, date(2026, 9, 16), 100, 117),
|
||||
],
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.erp_po_repository.open_erp_connection",
|
||||
lambda config: _Conn(),
|
||||
)
|
||||
docs = fetch_po_documents_for_invoices(_config(), ["EWZZ26090002"])
|
||||
assert len(docs) == 1
|
||||
assert docs[0].invoice_no == "EWZZ26090002"
|
||||
assert docs[0].po_no == "5220-2609010001"
|
||||
assert docs[0].lines[0].arrive == "2026/9/16"
|
||||
|
||||
|
||||
def test_fetch_po_documents_one_invoice_many_pos(monkeypatch):
|
||||
"""一票可对应多张 TGHX 采购单。"""
|
||||
|
||||
class _Conn:
|
||||
def cursor(self):
|
||||
return _NamedCursor(
|
||||
{
|
||||
"OMA_FILE": (_OMA_COLS, [("EWZZ26090002", "12", "8520-1", "S004-26090001")]),
|
||||
"PMM_FILE": (
|
||||
["flow_no", "po_no", "pmn02", "pmn88", "pmn88t"],
|
||||
[
|
||||
("S004-26090001", "5220-2609010001", 1, 10, 11),
|
||||
("S004-26090001", "5220-2609010002", 1, 20, 22),
|
||||
],
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.erp_po_repository.open_erp_connection",
|
||||
lambda config: _Conn(),
|
||||
)
|
||||
docs = fetch_po_documents_for_invoices(_config(), ["EWZZ26090002"])
|
||||
assert [item.po_no for item in docs] == ["5220-2609010001", "5220-2609010002"]
|
||||
|
||||
|
||||
def test_fetch_po_documents_skips_blank_invoice_list(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.erp_po_repository.open_erp_connection",
|
||||
lambda config: (_ for _ in ()).throw(AssertionError("should not connect")),
|
||||
)
|
||||
assert fetch_po_documents_for_invoices(_config(), ["0", " "]) == []
|
||||
|
||||
|
||||
def test_adapter_fetch_stays_unwired_while_documents_work(monkeypatch):
|
||||
adapter = ErpPoPrintAdapter()
|
||||
assert adapter.wired is False
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
adapter.fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.erp_po_repository.fetch_po_documents_for_invoices",
|
||||
lambda config, invoices: [map_po_document("INV0001", [{"po_no": "PO1", "pmn02": 1}])],
|
||||
)
|
||||
docs = adapter.fetch_documents(["INV0001"], config=_config())
|
||||
assert docs[0].po_no == "PO1"
|
||||
|
||||
|
||||
def test_adapter_publish_for_invoices_uploads_each(monkeypatch):
|
||||
adapter = ErpPoPrintAdapter()
|
||||
uploaded: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
adapter,
|
||||
"fetch_documents",
|
||||
lambda invoices, config=None: [
|
||||
map_po_document("EWZZ26090002", [{"po_no": "PO-A", "pmn02": 1}]),
|
||||
map_po_document("EWZZ26090002", [{"po_no": "PO-B", "pmn02": 1}]),
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
adapter,
|
||||
"upload_given",
|
||||
lambda document, period_month: uploaded.append(document.po_no) or document.po_no,
|
||||
)
|
||||
results = adapter.publish_for_invoices(["EWZZ26090002"], period_month=date(2026, 8, 1), config=_config())
|
||||
assert uploaded == ["PO-A", "PO-B"]
|
||||
assert results == ["PO-A", "PO-B"]
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_po_order_pdf.py
|
||||
|
||||
用途:制式采购单 PDF 命名与给定数据落盘。
|
||||
依赖:pytest、pypdf、voucher_check.po_order。
|
||||
逻辑:不连 ERP / 文档库;断言文件名 `{invoice}-{订单号}.pdf` 且正文含采购单号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pypdf import PdfReader
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.po_order import (
|
||||
build_po_order_filename,
|
||||
parse_po_order_document,
|
||||
sample_po_order_document,
|
||||
save_po_order_pdf,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_build_po_order_filename():
|
||||
"""文件名固定 invoice-订单号.pdf。"""
|
||||
assert build_po_order_filename(invoice_no="INV001", order_no="5201-1605280003") == "INV001-5201-1605280003.pdf"
|
||||
|
||||
|
||||
def test_build_po_order_filename_rejects_path_chars():
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
build_po_order_filename(invoice_no="INV/001", order_no="PO1")
|
||||
assert exc.value.code == "VOUCHER_CHECK.PO_PDF_INVALID"
|
||||
|
||||
|
||||
def test_parse_requires_invoice_and_po():
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
parse_po_order_document({"po_no": "PO1"})
|
||||
assert exc.value.code == "VOUCHER_CHECK.PO_PDF_INVALID"
|
||||
|
||||
|
||||
def test_save_po_order_pdf_uses_invoice_order_filename(tmp_path: Path):
|
||||
"""给定样张数据后保存为 {invoice}-{订单号}.pdf,且可抽出采购单号。"""
|
||||
document = sample_po_order_document()
|
||||
path = save_po_order_pdf(document, tmp_path)
|
||||
assert path.name == "INV-SAMPLE-5201-1605280003.pdf"
|
||||
assert path.is_file()
|
||||
assert path.stat().st_size > 1000
|
||||
text = "".join((page.extract_text() or "") for page in PdfReader(str(path)).pages)
|
||||
assert "5201-1605280003" in text
|
||||
assert "北川科技" in text
|
||||
assert "FRAME CUBE CORNER" in text
|
||||
|
||||
|
||||
def test_save_po_order_pdf_from_dict(tmp_path: Path):
|
||||
path = save_po_order_pdf(
|
||||
{"invoice_no": "INV001", "po_no": "PO-9", "company_name": "测试公司", "lines": [{"seq": "1", "item_no": "A1", "qty": "2"}]},
|
||||
tmp_path,
|
||||
)
|
||||
assert path.name == "INV001-PO-9.pdf"
|
||||
|
||||
|
||||
def test_overwrite_false_keeps_existing(tmp_path: Path):
|
||||
first = save_po_order_pdf({"invoice_no": "INV001", "po_no": "PO-9"}, tmp_path)
|
||||
stamp = first.stat().st_mtime_ns
|
||||
again = save_po_order_pdf({"invoice_no": "INV001", "po_no": "PO-9", "maker": "B"}, tmp_path, overwrite=False)
|
||||
assert again == first
|
||||
assert first.stat().st_mtime_ns == stamp
|
||||
|
||||
|
||||
def test_adapter_render_given_does_not_wire_fetch(tmp_path: Path):
|
||||
"""fetch 仍未接线;render_given 只根据给定数据出 PDF。"""
|
||||
adapter = ErpPoPrintAdapter()
|
||||
assert adapter.wired is False
|
||||
path = adapter.render_given(sample_po_order_document(), tmp_path)
|
||||
assert path.name == "INV-SAMPLE-5201-1605280003.pdf"
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_po_order_upload.py
|
||||
|
||||
用途:制式采购单 PDF 上传到文档库「PO订单」目录。
|
||||
依赖:pytest;mock SalesDmsClient,不连文档库。
|
||||
逻辑:同名跳过、年/月/类型目录确保存在、CreateFiles 载荷含 AttachmentID。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.po_order import publish_po_order_pdf, sample_po_order_document
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_ensure_period_type_folder_creates_year_month_type(monkeypatch):
|
||||
"""销售开票附件下按 年/月/PO订单 逐级建目录。"""
|
||||
created: list[tuple[str, str]] = []
|
||||
|
||||
def ensure_folder(*, parent_folder_id: str, leaf_name: str) -> str:
|
||||
created.append((parent_folder_id, leaf_name))
|
||||
return f"{parent_folder_id}/{leaf_name}"
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_configured", lambda: None)
|
||||
monkeypatch.setattr(SalesDmsClient, "root_folder_id", lambda: "sales-root")
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_folder", ensure_folder)
|
||||
folder_id = SalesDmsClient.ensure_period_type_folder(period_month=date(2026, 8, 1), type_folder="PO订单")
|
||||
assert created == [("sales-root", "2026"), ("sales-root/2026", "08"), ("sales-root/2026/08", "PO订单")]
|
||||
assert folder_id.endswith("PO订单")
|
||||
|
||||
|
||||
def test_upload_file_skips_when_same_name_exists(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"find_child_file",
|
||||
lambda **_kwargs: {"ID": "exist-1", "LeafName": "INV001-PO-9.pdf"},
|
||||
)
|
||||
uploads: list[object] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **kwargs: uploads.append(kwargs) or {})
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id="po-folder",
|
||||
leaf_name="INV001-PO-9.pdf",
|
||||
content=b"%PDF-fake",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "exist-1"
|
||||
assert uploads == []
|
||||
|
||||
|
||||
def test_upload_file_creates_when_missing(monkeypatch):
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(**_kwargs):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
return {"ID": "new-1", "LeafName": "INV001-PO-9.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"upload_attachment",
|
||||
lambda **_kwargs: {"ID": "att-1", "Extension": ".pdf", "LeafName": "INV001-PO-9"},
|
||||
)
|
||||
created: list[dict] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "create_files", lambda **kwargs: created.append(kwargs) or {"Code": 0})
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id="po-folder",
|
||||
leaf_name="INV001-PO-9.pdf",
|
||||
content=b"%PDF-fake",
|
||||
)
|
||||
assert skipped is False
|
||||
assert row["ID"] == "new-1"
|
||||
assert created[0]["parent_folder_id"] == "po-folder"
|
||||
assert created[0]["files"][0]["AttachmentID"] == "att-1"
|
||||
assert created[0]["files"][0]["LeafName"] == "INV001-PO-9.pdf"
|
||||
|
||||
|
||||
def test_upload_treats_create_same_name_as_skip(monkeypatch):
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(**_kwargs):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
return {"ID": "exist-2", "LeafName": "INV001-PO-9.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **_kwargs: {"ID": "att-2", "Extension": ".pdf"})
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"create_files",
|
||||
lambda **_kwargs: (_ for _ in ()).throw(
|
||||
ServiceUnavailableError(
|
||||
"存在同名文件",
|
||||
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
details={"dms_data": {"SameLeafNames": ["INV001-PO-9.pdf"]}},
|
||||
)
|
||||
),
|
||||
)
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id="po-folder",
|
||||
leaf_name="INV001-PO-9.pdf",
|
||||
content=b"%PDF-fake",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "exist-2"
|
||||
|
||||
|
||||
def test_upload_finds_leaf_name_without_extension(monkeypatch):
|
||||
"""部分现网 CreateFiles 后 LeafName 不含 .pdf,按无后缀再查一次。"""
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(*, parent_folder_id: str, leaf_name: str):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
if str(leaf_name).endswith(".pdf"):
|
||||
return None
|
||||
return {"ID": "new-stem", "LeafName": leaf_name}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **_kwargs: {"ID": "att-3", "Extension": ".pdf"})
|
||||
monkeypatch.setattr(SalesDmsClient, "create_files", lambda **_kwargs: {"Code": 0})
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id="po-folder",
|
||||
leaf_name="INV001-PO-9.pdf",
|
||||
content=b"%PDF-fake",
|
||||
)
|
||||
assert skipped is False
|
||||
assert row["ID"] == "new-stem"
|
||||
assert row["LeafName"] == "INV001-PO-9"
|
||||
|
||||
|
||||
def test_publish_po_order_pdf_uploads_to_type_folder(monkeypatch):
|
||||
"""给定数据生成后上传到 销售开票附件/{年}/{月}/PO订单/。"""
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_configured", lambda: None)
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_period_type_folder", lambda **_kwargs: "po-folder")
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def upload_file_skip_same_name(*, parent_folder_id: str, leaf_name: str, content: bytes):
|
||||
captured["parent_folder_id"] = parent_folder_id
|
||||
captured["leaf_name"] = leaf_name
|
||||
captured["size"] = len(content)
|
||||
return {"ID": "item-1", "LeafName": leaf_name, "Path": f"销售开票附件/2026/08/PO订单/{leaf_name}"}, False
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "upload_file_skip_same_name", upload_file_skip_same_name)
|
||||
result = publish_po_order_pdf(sample_po_order_document(), period_month=date(2026, 8, 1))
|
||||
assert result.skipped_same_name is False
|
||||
assert result.file.filename == "INV-SAMPLE-5201-1605280003.pdf"
|
||||
assert result.file.folder_id == "po-folder"
|
||||
assert result.file.path == "销售开票附件/2026/08/PO订单/INV-SAMPLE-5201-1605280003.pdf"
|
||||
assert captured["parent_folder_id"] == "po-folder"
|
||||
assert captured["leaf_name"] == "INV-SAMPLE-5201-1605280003.pdf"
|
||||
assert int(captured["size"] or 0) > 1000
|
||||
|
||||
|
||||
def test_adapter_upload_given_does_not_wire_fetch(monkeypatch):
|
||||
"""fetch 仍未接线;upload_given 只根据给定数据上传。"""
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_publish(document, period_month):
|
||||
captured["period_month"] = period_month
|
||||
captured["invoice_no"] = getattr(document, "invoice_no", None)
|
||||
return type("R", (), {"file": None, "skipped_same_name": False})()
|
||||
|
||||
monkeypatch.setattr("app.services.voucher_check.po_order.publish_po_order_pdf", fake_publish)
|
||||
adapter = ErpPoPrintAdapter()
|
||||
assert adapter.wired is False
|
||||
adapter.upload_given(sample_po_order_document(), period_month=date(2026, 8, 1))
|
||||
assert captured["period_month"] == date(2026, 8, 1)
|
||||
assert captured["invoice_no"] == "INV-SAMPLE"
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_po_print_schedule.py
|
||||
|
||||
用途:PO 订单生成周批早于检核,且不走 erp_po_print.fetch。
|
||||
依赖:pytest、app fixture;不连 Oracle / 文档库。
|
||||
逻辑:断言 cron 05:00、种子幂等、取数后上传、无 PO 跳过、检核 fetch 仍关闭。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.erp_po_repository import map_po_document
|
||||
from app.services.voucher_check.po_print_runner import run_po_print_batch
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
DEFAULT_VOUCHER_CHECK_CRON,
|
||||
DEFAULT_VOUCHER_PO_PRINT_CRON,
|
||||
DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH,
|
||||
DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO,
|
||||
ensure_default_voucher_check_schedule,
|
||||
ensure_default_voucher_po_print_schedule,
|
||||
)
|
||||
|
||||
|
||||
def test_po_print_cron_is_earlier_than_check():
|
||||
"""周二 05:00 早于检核 06:00。"""
|
||||
assert DEFAULT_VOUCHER_PO_PRINT_CRON == "0 5 * * 2"
|
||||
assert DEFAULT_VOUCHER_CHECK_CRON == "0 6 * * 2"
|
||||
|
||||
|
||||
def test_ensure_po_print_schedule_is_idempotent(app):
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
if db.session.query(User).first() is None:
|
||||
user = User(
|
||||
username="po-print-seed-admin",
|
||||
email="po-print-seed-admin@example.com",
|
||||
role="admin",
|
||||
status="active",
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
check = ensure_default_voucher_check_schedule(commit=True)
|
||||
first = ensure_default_voucher_po_print_schedule(commit=True)
|
||||
second = ensure_default_voucher_po_print_schedule(commit=True)
|
||||
assert check is not None
|
||||
assert first is not None
|
||||
assert first.id == second.id
|
||||
assert first.schedule_no == DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO
|
||||
assert first.platform_api_path == DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH
|
||||
assert first.cron_expr == DEFAULT_VOUCHER_PO_PRINT_CRON
|
||||
assert check.cron_expr == DEFAULT_VOUCHER_CHECK_CRON
|
||||
assert first.platform_api_path != check.platform_api_path
|
||||
|
||||
|
||||
def test_po_print_batch_uploads_and_skips_no_po(app, monkeypatch):
|
||||
"""有 PO 的发票上传;没有 TGHX 采购单的发票记 skipped_no_po;不调用 fetch()。"""
|
||||
uploaded: list[str] = []
|
||||
|
||||
def fake_fetch_month(config):
|
||||
return (
|
||||
date(2026, 8, 1),
|
||||
[
|
||||
SimpleNamespace(invoice_no="EWZZ26090002"),
|
||||
SimpleNamespace(invoice_no="EWZZ26090099"),
|
||||
],
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.po_print_runner.fetch_month_invoices",
|
||||
fake_fetch_month,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.po_print_runner.SalesDmsClient.ensure_configured",
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.po_print_runner.load_engine_config",
|
||||
lambda params=None: SimpleNamespace(notify_failure_enabled=False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ErpPoPrintAdapter,
|
||||
"fetch_documents",
|
||||
lambda self, invoices, config=None: [map_po_document("EWZZ26090002", [{"po_no": "5220-1", "pmn02": 1}])],
|
||||
)
|
||||
|
||||
def fake_upload(self, document, period_month):
|
||||
uploaded.append(document.po_no)
|
||||
return SimpleNamespace(
|
||||
skipped_same_name=False,
|
||||
file=SimpleNamespace(filename=f"{document.invoice_no}-{document.po_no}.pdf"),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(ErpPoPrintAdapter, "upload_given", fake_upload)
|
||||
monkeypatch.setattr("app.services.voucher_check.po_print_runner.send_failure_alert", lambda **kwargs: None)
|
||||
|
||||
with app.app_context():
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-TEST-PO",
|
||||
name="po print",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-po-print",
|
||||
owner_user_id=1,
|
||||
cron_expr="0 5 * * 2",
|
||||
job_params={"profile_code": "sales", "scope_code": "HXJM", "notify_failure_enabled": False},
|
||||
)
|
||||
run = ScheduleRun(run_no="RUN-PO-1", schedule_task_id=1, status="running")
|
||||
total, success, failed, skipped, details, errors, logs = run_po_print_batch(task, run)
|
||||
|
||||
assert total == 2
|
||||
assert success == 1
|
||||
assert failed == 0
|
||||
assert skipped == 1
|
||||
assert uploaded == ["5220-1"]
|
||||
assert any(item.get("status") == "skipped_no_po" for item in details)
|
||||
assert ErpPoPrintAdapter.wired is False
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
ErpPoPrintAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
|
||||
|
||||
def test_po_print_batch_counts_upload_failure(app, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.po_print_runner.fetch_month_invoices",
|
||||
lambda config: (date(2026, 8, 1), [SimpleNamespace(invoice_no="EWZZ26090002")]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.po_print_runner.SalesDmsClient.ensure_configured",
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.po_print_runner.load_engine_config",
|
||||
lambda params=None: SimpleNamespace(notify_failure_enabled=False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ErpPoPrintAdapter,
|
||||
"fetch_documents",
|
||||
lambda self, invoices, config=None: [map_po_document("EWZZ26090002", [{"po_no": "PO-FAIL", "pmn02": 1}])],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ErpPoPrintAdapter,
|
||||
"upload_given",
|
||||
lambda self, document, period_month: (_ for _ in ()).throw(RuntimeError("dms down")),
|
||||
)
|
||||
alerts: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.po_print_runner.send_failure_alert",
|
||||
lambda **kwargs: alerts.append(kwargs.get("stage") or ""),
|
||||
)
|
||||
with app.app_context():
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-TEST-PO2",
|
||||
name="po print",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-po-print",
|
||||
owner_user_id=1,
|
||||
cron_expr="0 5 * * 2",
|
||||
job_params={},
|
||||
)
|
||||
run = ScheduleRun(run_no="RUN-PO-2", schedule_task_id=1, status="running")
|
||||
total, success, failed, skipped, details, errors, logs = run_po_print_batch(task, run)
|
||||
assert total == 1
|
||||
assert success == 0
|
||||
assert failed == 1
|
||||
assert "upload" in alerts
|
||||
assert errors
|
||||
|
||||
|
||||
def test_platform_job_registered():
|
||||
from app.services.schedule.job_registry import get_platform_job
|
||||
|
||||
job = get_platform_job("accounting-voucher-po-print")
|
||||
assert job is not None
|
||||
assert job.label_key == "admin.schedule.form.platformJobAccountingVoucherPoPrint"
|
||||
assert job.handler is not None
|
||||
@@ -0,0 +1,253 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_workspace_latest_run.py
|
||||
|
||||
用途:工作台「最近一次检核」接口契约(含排队/执行中/终态/建批前失败)。
|
||||
依赖:pytest、Flask client、voucher_check.query_service。
|
||||
逻辑:GET /runs/latest 按 ScheduleRun.id 倒序,不跟列表 period;queued 不得被标成 technical_failed。
|
||||
"""
|
||||
|
||||
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 VoucherCheckRun
|
||||
from app.services.voucher_check.schedule_seed import 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 _add_schedule_run(
|
||||
*,
|
||||
run_no: str,
|
||||
status: str,
|
||||
mode: str | None = None,
|
||||
error_message: str | None = None,
|
||||
summary: dict | None = None,
|
||||
started_at: datetime | None = None,
|
||||
finished_at: datetime | None = None,
|
||||
) -> ScheduleRun:
|
||||
"""为本任务排程插入一条 ScheduleRun。"""
|
||||
task = ensure_default_voucher_check_schedule(commit=True)
|
||||
assert task is not None
|
||||
payload = {"run_options": {"mode": mode}} if mode else None
|
||||
run = ScheduleRun(
|
||||
schedule_task_id=task.id,
|
||||
run_no=run_no,
|
||||
trigger_type="manual",
|
||||
status=status,
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=1 if status == "failed" else 0,
|
||||
error_message=error_message,
|
||||
api_request_json=payload,
|
||||
response_summary_json=summary,
|
||||
started_at=started_at,
|
||||
finished_at=finished_at,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
return run
|
||||
|
||||
|
||||
def _add_engine_run(
|
||||
*,
|
||||
schedule_run: ScheduleRun,
|
||||
status: str = "missing",
|
||||
period_month: date | None = None,
|
||||
subject_count: int = 128,
|
||||
archived_file_count: int = 742,
|
||||
missing_file_count: int = 11,
|
||||
missing_invoice_count: int = 6,
|
||||
) -> VoucherCheckRun:
|
||||
"""为排程批次挂一条引擎快照。"""
|
||||
payload = schedule_run.api_request_json if isinstance(schedule_run.api_request_json, dict) else {}
|
||||
options = payload.get("run_options") if isinstance(payload.get("run_options"), dict) else {}
|
||||
engine = VoucherCheckRun(
|
||||
schedule_run_id=schedule_run.id,
|
||||
run_no=schedule_run.run_no,
|
||||
profile_code="sales",
|
||||
profile_version="1",
|
||||
profile_snapshot_json={"profile_code": "sales"},
|
||||
period_month=period_month or date(2026, 8, 1),
|
||||
mode=str(options.get("mode") or "incremental"),
|
||||
status=status,
|
||||
subject_count=subject_count,
|
||||
archived_file_count=archived_file_count,
|
||||
missing_file_count=missing_file_count,
|
||||
missing_invoice_count=missing_invoice_count,
|
||||
started_at=schedule_run.started_at,
|
||||
finished_at=schedule_run.finished_at,
|
||||
)
|
||||
db.session.add(engine)
|
||||
return engine
|
||||
|
||||
|
||||
def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers):
|
||||
"""入队中的强制重检必须显示 queued,而不是建批前失败口径。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-QUEUED",
|
||||
status="queued",
|
||||
mode="force_all",
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload is not None
|
||||
assert payload["run_no"] == "RUN-LATEST-QUEUED"
|
||||
assert payload["status"] == "queued"
|
||||
assert payload["mode"] == "force_all"
|
||||
assert payload["progress_percent"] == 8
|
||||
assert payload["current_step"]["step"] == "queued"
|
||||
|
||||
|
||||
def test_workspace_latest_run_returns_completed_metrics(app, client, user_headers):
|
||||
"""终态缺件批次返回四指标与 100% 进度。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
sched = _add_schedule_run(
|
||||
run_no="RUN-LATEST-DONE",
|
||||
status="success",
|
||||
mode="incremental",
|
||||
started_at=datetime(2026, 9, 8, 1, 48, 7),
|
||||
finished_at=datetime(2026, 9, 8, 1, 50, 19),
|
||||
summary={
|
||||
"current_step": {"step": "done", "label": "检核完成", "processed_count": 128},
|
||||
"voucher_check": {"period": "2026-08", "mode": "incremental", "subject_count": 128},
|
||||
},
|
||||
)
|
||||
_add_engine_run(schedule_run=sched, status="missing")
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
# 关键断言:卡片数字来自引擎快照,状态用缺件而非排程 success。
|
||||
assert payload["run_no"] == "RUN-LATEST-DONE"
|
||||
assert payload["status"] == "missing"
|
||||
assert payload["period_month"] == "2026-08"
|
||||
assert payload["mode"] == "incremental"
|
||||
assert payload["progress_percent"] == 100
|
||||
assert payload["subject_count"] == 128
|
||||
assert payload["archived_file_count"] == 742
|
||||
assert payload["missing_file_count"] == 11
|
||||
assert payload["missing_invoice_count"] == 6
|
||||
|
||||
|
||||
def test_workspace_latest_run_running_progress_ignores_list_period(app, client, user_headers):
|
||||
"""执行中进度跟 runner 步骤走,且 latest 不吃列表 period。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
old = _add_schedule_run(
|
||||
run_no="RUN-LATEST-OLD-AUG",
|
||||
status="success",
|
||||
mode="incremental",
|
||||
finished_at=datetime(2026, 9, 1, 6, 0, 0),
|
||||
)
|
||||
_add_engine_run(schedule_run=old, status="completed", period_month=date(2026, 8, 1), subject_count=10)
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-RUNNING",
|
||||
status="running",
|
||||
mode="force_all",
|
||||
started_at=datetime(2026, 9, 9, 6, 5, 22),
|
||||
summary={
|
||||
"current_step": {
|
||||
"step": "scan_dms",
|
||||
"label": "扫描销售开票附件类型目录",
|
||||
"processed_count": 54,
|
||||
},
|
||||
"voucher_check": {
|
||||
"period": "2026-07",
|
||||
"mode": "force_all",
|
||||
"subject_count": 128,
|
||||
"missing_file_count": 3,
|
||||
"missing_invoice_count": 2,
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
latest = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert latest.status_code == 200
|
||||
payload = parse_api_data(latest.get_json())
|
||||
assert payload["run_no"] == "RUN-LATEST-RUNNING"
|
||||
assert payload["status"] == "running"
|
||||
assert payload["period_month"] == "2026-07"
|
||||
assert payload["processed_count"] == 54
|
||||
assert payload["progress_percent"] == min(86, 22 + int(64 * 54 / 128))
|
||||
assert payload["finished_at"] is None
|
||||
|
||||
filtered = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert filtered.status_code == 200
|
||||
nos = {item["run_no"] for item in parse_api_data(filtered.get_json())["items"]}
|
||||
# 关键断言:列表按 8 月过滤看不到 7 月执行中批次,但 latest 仍是该批。
|
||||
assert "RUN-LATEST-RUNNING" not in nos
|
||||
assert payload["run_no"] == "RUN-LATEST-RUNNING"
|
||||
|
||||
|
||||
def test_workspace_latest_run_pre_engine_failure(app, client, user_headers):
|
||||
"""建批前失败仍作为最近一次检核,状态为技术失败。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
_add_schedule_run(
|
||||
run_no="RUN-LATEST-FAILED",
|
||||
status="failed",
|
||||
mode="incremental",
|
||||
error_message="未配置销售开票附件文档库根目录",
|
||||
started_at=datetime(2026, 9, 7, 8, 31, 51),
|
||||
finished_at=datetime(2026, 9, 7, 8, 32, 10),
|
||||
summary={
|
||||
"current_step": {"step": "fetch_erp", "label": "拉取上月销售 invoice", "processed_count": 0},
|
||||
"voucher_check": {"period": "2026-08"},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs/latest",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload["run_no"] == "RUN-LATEST-FAILED"
|
||||
assert payload["status"] == "technical_failed"
|
||||
assert payload["error_message"] == "未配置销售开票附件文档库根目录"
|
||||
assert payload["current_step"]["step"] == "fetch_erp"
|
||||
assert payload["progress_percent"] == 18
|
||||
@@ -0,0 +1,185 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_workspace_period_filter.py
|
||||
|
||||
用途:工作台检核任务 / 企微发送记录的期间筛选(YYYY 全年、YYYY-MM 单月)。
|
||||
依赖:pytest、Flask client、voucher_check.query_service。
|
||||
逻辑:同一年多个月份应被 year 筛出;单月筛仍精确;建批前失败记录按年也能命中。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ScheduleRun, User
|
||||
from app.models.voucher_check import VoucherCheckNotification, VoucherCheckRun
|
||||
from app.services.voucher_check.query_service import parse_period_filter
|
||||
from app.services.voucher_check.schedule_seed import 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 _engine_run(*, run_no: str, period_month: date, status: str = "missing") -> VoucherCheckRun:
|
||||
"""构造列表用引擎批次。"""
|
||||
return VoucherCheckRun(
|
||||
run_no=run_no,
|
||||
profile_code="sales",
|
||||
profile_version="1",
|
||||
profile_snapshot_json={"profile_code": "sales"},
|
||||
period_month=period_month,
|
||||
mode="incremental",
|
||||
status=status,
|
||||
subject_count=1,
|
||||
finished_at=datetime(period_month.year, period_month.month, 2, 6, 0, 0),
|
||||
)
|
||||
|
||||
|
||||
def test_parse_period_filter_year_and_month():
|
||||
"""YYYY 覆盖全年,YYYY-MM 只覆盖该月。"""
|
||||
start, end = parse_period_filter("2026")
|
||||
assert start == date(2026, 1, 1)
|
||||
assert end == date(2027, 1, 1)
|
||||
start, end = parse_period_filter("2026-08")
|
||||
assert start == date(2026, 8, 1)
|
||||
assert end == date(2026, 9, 1)
|
||||
start, end = parse_period_filter("2026-12")
|
||||
assert start == date(2026, 12, 1)
|
||||
assert end == date(2027, 1, 1)
|
||||
assert parse_period_filter(None) == (None, None)
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
parse_period_filter("2026-13")
|
||||
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
|
||||
"""任务列表 year 筛出同年多月,month 仍只返回单月。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
db.session.add(_engine_run(run_no="VC-202608-Y", period_month=date(2026, 8, 1)))
|
||||
db.session.add(_engine_run(run_no="VC-202607-Y", period_month=date(2026, 7, 1)))
|
||||
db.session.add(_engine_run(run_no="VC-202512-Y", period_month=date(2025, 12, 1)))
|
||||
db.session.commit()
|
||||
|
||||
year_resp = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert year_resp.status_code == 200
|
||||
year_payload = parse_api_data(year_resp.get_json())
|
||||
year_nos = {item["run_no"] for item in year_payload["items"]}
|
||||
# 关键断言:全年筛选包含 7、8 月,不含跨年 12 月。
|
||||
assert "VC-202608-Y" in year_nos
|
||||
assert "VC-202607-Y" in year_nos
|
||||
assert "VC-202512-Y" not in year_nos
|
||||
|
||||
month_resp = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert month_resp.status_code == 200
|
||||
month_payload = parse_api_data(month_resp.get_json())
|
||||
month_nos = {item["run_no"] for item in month_payload["items"]}
|
||||
assert "VC-202608-Y" in month_nos
|
||||
assert "VC-202607-Y" not in month_nos
|
||||
|
||||
|
||||
def test_workspace_year_filter_includes_pre_engine_failure(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
|
||||
db.session.add(
|
||||
ScheduleRun(
|
||||
schedule_task_id=task.id,
|
||||
run_no="RUN-PREENGINE-YEAR",
|
||||
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.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026&status=technical_failed",
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
nos = {item["run_no"] for item in payload["items"]}
|
||||
assert "RUN-PREENGINE-YEAR" in nos
|
||||
|
||||
|
||||
def test_workspace_lists_notifications_by_year(app, client, user_headers):
|
||||
"""企微发送记录按年筛选应覆盖该年各月。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
august = _engine_run(run_no="VC-202608-N", period_month=date(2026, 8, 1))
|
||||
july = _engine_run(run_no="VC-202607-N", period_month=date(2026, 7, 1), status="completed")
|
||||
db.session.add_all([august, july])
|
||||
db.session.flush()
|
||||
db.session.add_all(
|
||||
[
|
||||
VoucherCheckNotification(
|
||||
run_id=august.id,
|
||||
send_status="sent",
|
||||
summary_json={"period": "2026-08"},
|
||||
),
|
||||
VoucherCheckNotification(
|
||||
run_id=july.id,
|
||||
send_status="skipped_no_missing",
|
||||
summary_json={"period": "2026-07"},
|
||||
),
|
||||
]
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/notifications?period=2026",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
nos = {item["run_no"] for item in payload["items"]}
|
||||
assert "VC-202608-N" in nos
|
||||
assert "VC-202607-N" in nos
|
||||
|
||||
|
||||
def test_workspace_rejects_invalid_period(app, client, user_headers):
|
||||
"""非法 period 返回配置错误,而不是空列表。"""
|
||||
with app.app_context():
|
||||
_ensure_user(username="user", role="user")
|
||||
response = client.get(
|
||||
"/api/workspace/accounting-voucher-check/runs?period=2026-13",
|
||||
headers=user_headers,
|
||||
)
|
||||
assert response.status_code == 400
|
||||
error = parse_api_error(response.get_json())
|
||||
assert error["code"] == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
Reference in new issue
Block a user