Merge branch 'dev' of https://gitee.com/justop/hxops into dev
This commit is contained in:
commit
27e2608c5e
606 files changed
+52167
-36839
No files matched your search
@@ -56,6 +56,28 @@ def test_claim_next_shipping_recovers_stale_layout_jobs(app, monkeypatch):
|
||||
assert recovered == [True]
|
||||
|
||||
|
||||
def test_claim_next_shipping_claims_inventory_callback_process_job(app):
|
||||
"""库存 RPA 回调收件 Job 必须由 shipping worker 消费,不能永久停在 queued。"""
|
||||
from app import db
|
||||
from app.jobs import store
|
||||
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type=JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS.value,
|
||||
status='queued',
|
||||
payload_json={'callback_id': 'callback-test'},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
claimed = store.claim_next(queues=['shipping'])
|
||||
|
||||
assert claimed is not None
|
||||
assert claimed['id'] == job.id
|
||||
assert claimed['job_type'] == JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS
|
||||
|
||||
|
||||
def test_find_shipping_notice_job_id_matches_task_no(app):
|
||||
from app import db
|
||||
from app.jobs.queue import _find_shipping_notice_job_id
|
||||
|
||||
@@ -26,7 +26,6 @@ from app.services.shipping_notice.stp_line_inventory_match import prepare_candid
|
||||
def _task(task_no: str) -> ShippingNotice:
|
||||
task = ShippingNotice(
|
||||
task_no=task_no,
|
||||
process_status='created',
|
||||
source_type='manual',
|
||||
)
|
||||
db.session.add(task)
|
||||
|
||||
@@ -19,7 +19,7 @@ tests/services/shipping_notice/test_reconciliation_phase34_contract.py
|
||||
b) legacy_job_id=999 + is_admin=False → 422
|
||||
[P4 T7] ownership_anomaly BRANCH F:
|
||||
断言触发路径最终 outcome=ownership_anomaly_rejected 且不会脏写
|
||||
(这里只测 ValidationError 降级情形 hasattr(case,process_status)=False)。
|
||||
(这里只测 ValidationError 降级情形,Review Case 不含旧流程字段)。
|
||||
全部为 pure_unit 或 DB 无关单测,不启动 Flask/Worker,不写 DB。
|
||||
"""
|
||||
|
||||
@@ -132,6 +132,20 @@ def test_p3_t4_primary_action_matrix(bcode, actions_in, retryable, expected_pa_c
|
||||
assert got['variant'] == variant, label
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_resolved_field_conflict_has_no_current_task_cta():
|
||||
"""字段冲突清零后,保存校验留在底栏,当前任务不得再制造 CTA。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import project_case_primary_action
|
||||
|
||||
action = project_case_primary_action(
|
||||
'waiting_human',
|
||||
{},
|
||||
['view', 'validate'],
|
||||
)
|
||||
|
||||
assert action is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_p3_t2_allowed_actions_inject_reconcile_and_remove_retry():
|
||||
"""[P3 T2] 业务阻断 → REMOVE_SET 删除 retry_stp_auto_create 且注入 reconcile_and_progress。"""
|
||||
@@ -183,6 +197,95 @@ def test_p3_t5_bundle_six_fields_shapes():
|
||||
assert bundle['primary_action'] is None or isinstance(bundle['primary_action'], dict)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
"""正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'_project_case_formal_gate_summary',
|
||||
lambda _case: {
|
||||
'current_gate': {
|
||||
'gate_code': 'field_completeness',
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'required_field_missing',
|
||||
'next_action_code': 'edit_order_fields',
|
||||
},
|
||||
'current_blocking_gate': {
|
||||
'gate_code': 'field_completeness',
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'required_field_missing',
|
||||
'next_action_code': 'edit_order_fields',
|
||||
},
|
||||
'blocking_reason_code': 'required_field_missing',
|
||||
'next_action_code': 'edit_order_fields',
|
||||
},
|
||||
)
|
||||
|
||||
bundle = reconciliation_projector.project_review_case_projection_bundle(
|
||||
case,
|
||||
validation={'can_build': False, 'can_auto_create': False},
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
assert bundle['current_gate']['gate_code'] == 'field_completeness'
|
||||
assert bundle['current_gate']['blocking_reason_code'] == 'required_field_missing'
|
||||
assert bundle['blocking_reason']['code'] == 'required_field_missing'
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
|
||||
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
_project_case_formal_gate_facts,
|
||||
)
|
||||
|
||||
facts = _project_case_formal_gate_facts({
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_source_routing',
|
||||
'status': 'pending',
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': None,
|
||||
},
|
||||
'current_blocking_gate': None,
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': None,
|
||||
})
|
||||
|
||||
assert facts is not None
|
||||
current_gate, blocking_reason, user_status = facts
|
||||
assert current_gate['gate_code'] == 'inventory_source_routing'
|
||||
assert blocking_reason['code'] is None
|
||||
assert user_status == 'running'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_order_freeze_readiness_waits_for_the_user_to_submit_validation():
|
||||
"""建单前校验未提交时必须提示人工保存,不能伪装为自动处理中。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
_project_case_formal_gate_facts,
|
||||
)
|
||||
|
||||
facts = _project_case_formal_gate_facts({
|
||||
'current_gate': {
|
||||
'gate_code': 'order_freeze_readiness',
|
||||
'status': 'pending',
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': None,
|
||||
},
|
||||
})
|
||||
|
||||
assert facts is not None
|
||||
current_gate, blocking_reason, user_status = facts
|
||||
assert current_gate['gate_code'] == 'order_freeze_readiness'
|
||||
assert blocking_reason['code'] is None
|
||||
assert user_status == 'waiting_human'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询)
|
||||
# ============================================================
|
||||
@@ -336,7 +439,7 @@ def test_p4_t6c_legacy_job_requires_failed_or_dead(monkeypatch):
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [P4 T7] BRANCH F ownership_anomaly 422 降级(process_status 不存在)
|
||||
# [P4 T7] BRANCH F ownership_anomaly 422 降级(Review Case 不含旧流程字段)
|
||||
# ============================================================
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -363,8 +466,7 @@ def test_p4_t7_branch_f_ownership_anomaly_throws_validation(monkeypatch):
|
||||
{'step': 'L3_AMBIGUOUS', 'matched': True},
|
||||
],
|
||||
}
|
||||
# 关键:模拟 ReviewCase 没有 process_status 列 → BRANCH F 必须抛 422(而非软返回 outcome)
|
||||
assert not hasattr(case, 'process_status')
|
||||
# 关键:Review Case 不含旧流程字段 → BRANCH F 必须抛 422(而非软返回 outcome)
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
reconcile_and_progress(
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
"""
|
||||
tests/services/shipping_notice/test_recovery_contract_phase1.py
|
||||
|
||||
用途:Phase 1 合同测试 — 锁定错误分类白名单与阻断→动作映射的纯函数矩阵。
|
||||
依赖:recovery_contract(is_tech_retryable_error、build_stp_job_blocked_manual_result、
|
||||
should_general_retry_be_removed、derive_blocking_next_actions)。
|
||||
逻辑:纯单元测,不依赖 DB/Worker,确保 T1 错误分类矩阵与 T3 动作注入判定
|
||||
与 Phase 1 冻结契约一致;一旦白名单/阻断规则被误修改将立即红。
|
||||
用途:恢复契约测试——失败必须停止,用户通过明确动作恢复。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,56 +13,11 @@ from app.services.shipping_notice.recovery_contract import (
|
||||
BLOCKING_REASON_TO_ACTION_CODES,
|
||||
REMOVE_ACTIONS_WHEN_BLOCKED,
|
||||
build_stp_job_blocked_manual_result,
|
||||
build_stp_job_failed_transient_result,
|
||||
derive_blocking_next_actions,
|
||||
is_tech_retryable_error,
|
||||
should_general_retry_be_removed,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# T1:is_tech_retryable_error 白名单矩阵(fail-closed)
|
||||
# ============================================================
|
||||
|
||||
T1_MATRIX = [
|
||||
# (error_code, category_hint, expected_retryable, case_label)
|
||||
('SHIPPING.TRANSIENT_NETWORK_TIMEOUT', None, True, 'TRANSIENT_ 前缀 → 技术临时网络'),
|
||||
('SHIPPING.TRANSIENT_STORAGE_CONNECTION', None, True, 'TRANSIENT_ 前缀 → 技术存储'),
|
||||
('SHIPPING.WORKER_TIMEOUT_LEASE_EXPIRED', None, True, 'WORKER_TIMEOUT_ 前缀'),
|
||||
('worker_timeout', 'worker_timeout', True, 'category_hint=worker_timeout'),
|
||||
('queue_unavailable', 'queue_unavailable', True, 'category_hint=queue_unavailable'),
|
||||
('temporary_network_error', 'temporary_network_error', True, 'category_hint 网络临时'),
|
||||
('temporary_storage_error', 'temporary_storage_error', True, 'category_hint 存储临时'),
|
||||
('external_service_5xx', 'external_service_5xx', True, 'category_hint 外部 5xx'),
|
||||
('lease_expired', 'lease_expired', True, 'category_hint 租约过期'),
|
||||
# 业务阻断码:默认不可重试(Q5 白名单制,不在即拒绝)
|
||||
('SHIPPING.NOTICE_EXACT_DUPLICATE', None, False, '精确重复 — 业务阻断,不可重试'),
|
||||
('SHIPPING.STP_NOT_ELIGIBLE', None, False, 'STP 资格不足 — 业务阻断'),
|
||||
('SHIPPING.REVIEW_DRAFT_MISSING', None, False, '草稿缺失 — 业务阻断'),
|
||||
('SHIPPING.REVIEW_RUN_MISSING', None, False, 'Run 缺失 — 业务阻断'),
|
||||
('SHIPPING.REVIEW_DOCUMENT_INVALID', None, False, '文档无效 — 业务阻断'),
|
||||
('SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT', None, False, '版本冲突 — 业务阻断,应 409 让前端刷新'),
|
||||
('profile_schema_mismatch', None, False, 'Profile 模板不匹配 — 业务阻断'),
|
||||
('final_required_field_missing', None, False, '关键字段缺失 — 业务阻断'),
|
||||
('duplicate_decision_required', None, False, '等待重复裁决 — 业务阻断'),
|
||||
# 空码/未知码:fail-closed(默认不可重试,不能因空码回退到 retryable=true)
|
||||
('', None, False, '空码 → fail-closed 不可重试'),
|
||||
('RANDOM.UNKNOWN_ERROR_XYZ', None, False, '未知码 → fail-closed 不可重试'),
|
||||
(None, None, False, 'None 码 → fail-closed 不可重试'),
|
||||
# category_hint 与前缀冲突:前缀优先(空码除外)
|
||||
('SHIPPING.TRANSIENT_NETWORK', 'worker_timeout', True, '前缀命中即使 hint 不同也可重试'),
|
||||
('trigger_not_claimed_missing', None, True, '库存 Trigger 缺失 → 技术重试'),
|
||||
('trigger_not_claimed_timeout', None, True, '库存 Trigger 超时 → 技术重试'),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('error_code, category_hint, expected, label', T1_MATRIX, ids=[m[3] for m in T1_MATRIX])
|
||||
def test_t1_is_tech_retryable_error_matrix(error_code, category_hint, expected, label):
|
||||
"""T1:错误码 → 是否允许技术自动重试(白名单制,fail-closed)。"""
|
||||
_ = label
|
||||
assert is_tech_retryable_error(error_code, category_hint=category_hint) is expected
|
||||
|
||||
|
||||
# ============================================================
|
||||
# T1-ext:build_stp_job_*_result 的结构契约(Q4 Job.result_json schema)
|
||||
# ============================================================
|
||||
@@ -92,20 +43,6 @@ def test_t1_blocked_manual_result_shape():
|
||||
assert 'decision_trace' in result
|
||||
|
||||
|
||||
def test_t1_transient_result_shape():
|
||||
"""技术临时错误 → retryable=true,blocking_reason/next_action 置空。"""
|
||||
result = build_stp_job_failed_transient_result(
|
||||
error_code='SHIPPING.TRANSIENT_NETWORK_TIMEOUT',
|
||||
message='Dify API 503',
|
||||
category_hint='external_service_5xx',
|
||||
)
|
||||
assert result['status'] == 'failed'
|
||||
assert result['retryable'] is True
|
||||
assert result['blocking_reason'] is None
|
||||
assert result['next_action'] is None
|
||||
assert result['contract_version'] == RECOVERY_CONTRACT_VERSION
|
||||
|
||||
|
||||
# ============================================================
|
||||
# T3:should_general_retry_be_removed + derive 动作矩阵(Q9 后端注入/删除动作)
|
||||
# ============================================================
|
||||
|
||||
@@ -522,7 +522,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CORRECTION-API', shipping_case_id=case.id,
|
||||
source_type='manual', process_status='parsed', customer_resolution_status='pending',
|
||||
source_type='manual', customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
收料报表配置管理接口测试。
|
||||
|
||||
用途:验证站点内独立收料配置的权限、DBS/Crane 规则及不可影响库存配置的边界。
|
||||
依赖:Flask 管理 API、库存站点测试种子、货代统一审计事件。
|
||||
逻辑:配置保存只更新 shipping_receipt_report_configs,并留存前后快照审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingAuditEvent, ShippingInventorySource, User
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
|
||||
def _headers(username: str, role: str) -> dict[str, str]:
|
||||
"""构造当前管理 API 使用的 Header 身份上下文。"""
|
||||
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def _create_users() -> None:
|
||||
"""创建管理员和普通接收人,验证收料配置不向业务用户开放。"""
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
User(username='receipt-admin', email='receipt-admin@example.com', role='admin', status='active'),
|
||||
User(username='receipt-user', email='receipt-user@example.com', role='user', status='active'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _dbs_payload() -> dict:
|
||||
"""构造 DBS 收料配置;日期未出现表示保持系统页面默认 NULL。"""
|
||||
return {
|
||||
'enabled': True,
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
|
||||
},
|
||||
'warehouse_ids_json': ['AWSDU', 'AWSDU-02'],
|
||||
'query_parameters_json': [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}],
|
||||
}
|
||||
|
||||
|
||||
def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
"""DBS 收料配置按站点保存,不能变更既有库存路径、条件或版本。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
inventory_before = {
|
||||
'path': dict(source.report_path_json), 'parameters': list(source.query_parameters_json),
|
||||
'config_version': source.config_version,
|
||||
}
|
||||
|
||||
forbidden = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json=_dbs_payload(), headers=_headers('receipt-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json=_dbs_payload(), headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = parse_api_data(response.get_json())
|
||||
assert config['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
assert config['report_path_json']['report_group'] == 'Inbound'
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.get(source_id)
|
||||
# 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义。
|
||||
assert source.report_path_json == inventory_before['path']
|
||||
assert source.query_parameters_json == inventory_before['parameters']
|
||||
assert source.config_version == inventory_before['config_version']
|
||||
audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
).one()
|
||||
assert audit.before_snapshot_json is None
|
||||
assert audit.after_snapshot_json['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
|
||||
|
||||
def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, client):
|
||||
"""拒绝日期/selector 等 Driver 细节;DBS 与 Crane 的 Warehouse 规则必须分开。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
dbs_id = dbs.id
|
||||
from app import db
|
||||
crane_profile = dbs.rpa_profile.__class__(
|
||||
profile_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane',
|
||||
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
source_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane',
|
||||
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
|
||||
report_path_json={}, query_parameters_json=[], enabled=False,
|
||||
)
|
||||
db.session.add(crane_source)
|
||||
db.session.commit()
|
||||
crane_id = crane_source.id
|
||||
|
||||
invalid_date = _dbs_payload()
|
||||
invalid_date['query_parameters_json'] = [{'name': 'Report Date', 'mode': 'single', 'values': ['2026-08-19'], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=invalid_date, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
invalid_selector = _dbs_payload()
|
||||
invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=invalid_selector, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
invalid_crane = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Other Report'},
|
||||
'warehouse_ids_json': ['NOT-ALLOWED'], 'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
json=invalid_crane, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
"""Crane 固定使用页面默认值直接 Run Report,管理员不能维护查询条件。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
from app import db
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = dbs.rpa_profile.__class__(
|
||||
profile_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane',
|
||||
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
source_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane',
|
||||
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
|
||||
report_path_json={}, query_parameters_json=[], enabled=False,
|
||||
)
|
||||
db.session.add(crane_source)
|
||||
db.session.commit()
|
||||
crane_id = crane_source.id
|
||||
|
||||
default_query = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Inbound Details'}, 'warehouse_ids_json': [],
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
json=default_query, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert parse_api_data(response.get_json())['query_parameters_json'] == []
|
||||
|
||||
configured = {**default_query, 'query_parameters_json': [
|
||||
{'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False},
|
||||
]}
|
||||
rejected = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
json=configured, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert rejected.status_code == 400
|
||||
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
@@ -111,7 +111,6 @@ def test_hybrid_executor_injects_shipping_agent_runtime_context(app, monkeypatch
|
||||
user_id=user.id,
|
||||
conversation_id='conv-shipping-start-001',
|
||||
source_type='manual',
|
||||
process_status='created',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -57,7 +57,6 @@ def _create_task_for_user(user_id: int) -> str:
|
||||
task_no="SN-20260706-ABCD1234",
|
||||
user_id=user_id,
|
||||
source_type="manual",
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
"""
|
||||
tests/test_conversation_retry_auto_progress.py
|
||||
|
||||
用途:锁定对话级重试自动推进的 eligible 判定、跳过原因与汇总结构。
|
||||
依赖:conversation_retry_auto_progress_service。
|
||||
逻辑:纯单元测跳过映射与 summary;不依赖完整 DB 工厂。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
ACTION_RETRY_AUTO_PROGRESS,
|
||||
_skip_reason_from_automation,
|
||||
_summarize_items,
|
||||
project_conversation_allowed_actions,
|
||||
)
|
||||
|
||||
|
||||
def test_formal_trigger_failure_overrides_stale_automation(monkeypatch):
|
||||
"""最新 Attempt 的 Trigger 缺失事实优先于历史 Job 的 needs_human 投影。"""
|
||||
from app.services.shipping_notice import conversation_retry_auto_progress_service as service
|
||||
|
||||
task = type('Task', (), {'task_no': 'OT-TRIGGER', 'id': 1})()
|
||||
class _Query:
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return task
|
||||
|
||||
monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts',
|
||||
lambda *_args, **_kwargs: {
|
||||
'latest_attempts': {
|
||||
'DSV360_AWSSL': {
|
||||
'status': 'failed',
|
||||
'error_code': 'trigger_not_claimed_missing',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert service._formal_task_has_retryable_inventory_trigger_failure('OT-TRIGGER') is True
|
||||
|
||||
|
||||
def test_failed_gate_job_does_not_count_as_active_attempt(monkeypatch):
|
||||
"""Attempt 残留 queued 但正式 Job 已失败时,不得继续投影 already_running。"""
|
||||
from app.services.shipping_notice import conversation_retry_auto_progress_service as service
|
||||
|
||||
task = type('Task', (), {'task_no': 'OT-STALE', 'id': 1})()
|
||||
|
||||
class _Query:
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return task
|
||||
|
||||
monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts',
|
||||
lambda *_args, **_kwargs: {'active_attempt_count': 0},
|
||||
)
|
||||
assert service._formal_task_has_active_attempt('OT-STALE') is False
|
||||
|
||||
|
||||
def test_skip_reason_maps_queued_and_not_retryable():
|
||||
"""queued → already_running;retryable=false → not_retryable。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'queued', 'retryable': False},
|
||||
task_missing=False,
|
||||
) == 'already_running'
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'waiting_to_start', 'retryable': False},
|
||||
task_missing=False,
|
||||
) == 'not_retryable'
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'failed', 'retryable': True},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_manual_fallback_human_owner_still_retryable():
|
||||
"""manual_fallback 虽 owner=human,但 retryable 时不得跳过。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'manual_fallback', 'retryable': True, 'owner_type': 'human'},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_inventory_needs_human_remains_retryable():
|
||||
"""库存快照/RPA 暂态 needs_human 必须继续进入库存重试决策器。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'reason_code': 'inventory_snapshot_prepare_failed',
|
||||
},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_missing_inventory_trigger_needs_human_remains_retryable():
|
||||
"""Trigger 未被领取的技术失败必须继续触发正式 OT 库存重试。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'error_code': 'trigger_not_claimed_missing',
|
||||
},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_business_needs_human_stays_skipped():
|
||||
"""重复/短缺等业务裁决的 needs_human 不得触发库存 RPA。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'reason_code': 'inventory_shortage',
|
||||
},
|
||||
task_missing=False,
|
||||
) == 'human_blocking'
|
||||
|
||||
|
||||
def test_task_missing_always_skipped():
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'failed', 'retryable': True},
|
||||
task_missing=True,
|
||||
) == 'task_missing'
|
||||
|
||||
|
||||
def test_summarize_items_counts_outcomes():
|
||||
summary = _summarize_items([
|
||||
{'outcome': 'queued'},
|
||||
{'outcome': 'queued'},
|
||||
{'outcome': 'skipped', 'reason_code': 'already_running'},
|
||||
{'outcome': 'failed'},
|
||||
])
|
||||
assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1, 'blocked': 0}
|
||||
|
||||
|
||||
def test_project_conversation_allowed_actions_empty_without_conversation():
|
||||
"""无 conversation_id 时不返回禁用空按钮。"""
|
||||
assert project_conversation_allowed_actions(user_id=1, conversation_id='') == []
|
||||
assert ACTION_RETRY_AUTO_PROGRESS == 'retry_auto_progress'
|
||||
@@ -16,13 +16,17 @@ from app.services.shipping_notice.order_supplement_merge import merge_email_supp
|
||||
SCHEMA = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']},
|
||||
{'field_id': 'customer-part', 'field_code': 'customer_part_number', 'scope': 'line', 'aliases': ['AMPN']},
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'aliases': ['Reservation ID', 'External reservation ID'],
|
||||
'aliases': ['Reservation ID', 'External reservation ID', 'Reservation Number'],
|
||||
},
|
||||
{'field_id': 'allocation', 'field_code': 'allocation_id'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
|
||||
{'field_id': 'source-party', 'field_code': 'source_from_party', 'scope': 'line', 'aliases': ['source_from_party']},
|
||||
{'field_id': 'allocated-entity', 'field_code': 'allocated_entity', 'scope': 'line', 'aliases': ['allocated_entity']},
|
||||
{'field_id': 'allocated-qty', 'field_code': 'allocated_qty', 'scope': 'line', 'aliases': ['allocated_qty']},
|
||||
]}
|
||||
|
||||
|
||||
@@ -83,6 +87,125 @@ def test_email_supplement_external_reservation_id_alias_merges_real_mail_header(
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_ampn_alias_matches_customer_part_number():
|
||||
"""邮件 AMPN 应能与订单客户料号交叉关联并补入预约号。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'][0]['observations'][0]['value'] = 'D4-A08AR12000002'
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'customer-part', 'observations': [{'value': 'AMTEMP-S000218922'}],
|
||||
})
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='f' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>AMPN</th><th>Reservation Number</th></tr><tr><td>4518738152</td><td>AMTEMP-S000218922</td><td>33874</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: {**supplement, 'document_id': 44}}, schema_definition=SCHEMA,
|
||||
)
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == '33874'
|
||||
|
||||
|
||||
def test_email_supplement_schema_field_fills_missing_part_number_from_pdf_customer_part_match():
|
||||
"""PDF 缺内部料号时,EML 的 Schema 内部料号应由 PO+客户料号唯一补齐。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'] = [
|
||||
{'field_id': 'customer-part', 'observations': [{'value': 'AMTEMP-S000218922'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 1}]},
|
||||
]
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='g' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>AMPN</th><th>Reservation Number</th></tr><tr><td>4518738152</td><td>D4-A08AR12000001</td><td>AMTEMP-S000218922</td><td>33874</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: {**supplement, 'document_id': 44}}, schema_definition=SCHEMA,
|
||||
)
|
||||
fields = merged[0]['lines'][0]['fields']
|
||||
assert _value(fields, 'part') == 'D4-A08AR12000001'
|
||||
assert _value(fields, 'reservation') == '33874'
|
||||
|
||||
|
||||
def test_email_supplement_conflicting_schema_field_does_not_overwrite_pdf_or_pick_a_value():
|
||||
"""同一已关联行的 EML 字段多值必须逐字段转复核,禁止顺序覆盖。"""
|
||||
order = _order()
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'reservation_id': '33874', 'evidence': {}},
|
||||
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'reservation_id': '33875', 'evidence': {}},
|
||||
],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert not any(item['field_id'] == 'reservation' for item in merged['lines'][0]['fields'])
|
||||
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
|
||||
|
||||
|
||||
def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
|
||||
"""PDF 与 EML 对同一 Schema 字段给出不同唯一值时不得静默接受任一方。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'reservation', 'observations': [{'value': 'PDF-33873'}],
|
||||
})
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': 'EML-33874',
|
||||
'evidence': {},
|
||||
}],
|
||||
}
|
||||
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == 'PDF-33873'
|
||||
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
|
||||
|
||||
|
||||
def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_numbers():
|
||||
"""邮件 PN/AMPN 均可与订单内部/客户料号交叉匹配,不依赖字段名称相同。"""
|
||||
scenarios = [
|
||||
('part_number', 'D4-A08AR12000002', 'part'),
|
||||
('part_number', 'AMTEMP-S000218922', 'customer-part'),
|
||||
('customer_part_number', 'D4-A08AR12000002', 'part'),
|
||||
('customer_part_number', 'AMTEMP-S000218922', 'customer-part'),
|
||||
]
|
||||
for index, (mail_field, value, order_field) in enumerate(scenarios, start=1):
|
||||
order = _order()
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'customer-part', 'observations': [{'value': 'AMTEMP-S000218922'}],
|
||||
})
|
||||
if order_field == 'part':
|
||||
order['lines'][0]['fields'][0]['observations'][0]['value'] = value
|
||||
supplement = {'document_id': 44, 'rows': [{
|
||||
'po_number': '4518738152', mail_field: value,
|
||||
'reservation_id': f'30000{index}', 'evidence': {},
|
||||
}]}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == f'30000{index}'
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_po_fallback_writes_unique_reservation_without_part_match():
|
||||
"""唯一 PO 兜底不得在写入阶段重新要求邮件料号匹配。"""
|
||||
result = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000001',
|
||||
'reservation_id': '33874', 'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '33874'
|
||||
assert result['_hxops_email_supplement_relation'] == 'po_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
"""缺 MPN 时只有唯一 Reservation 的 PO 可广播;多 Reservation 必须复核。"""
|
||||
one = {'document_id': 44, 'rows': [{'po_number': '4518738152', 'reservation_id': '2000484577', 'evidence': {}}]}
|
||||
@@ -103,15 +226,15 @@ def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'po_number': '4518738152', 'mpn': 'D4-A08AR12000002',
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'po_number': '4518738152', 'mpn': 'D4-A08AR12000002',
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'po_number': '4518838154', 'mpn': 'B3-AR1000270A1',
|
||||
'customer_po_number': '4518838154', 'part_number': 'B3-AR1000270A1',
|
||||
'reservation_id': '4000111701', 'evidence': {},
|
||||
},
|
||||
],
|
||||
@@ -133,9 +256,9 @@ def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_b
|
||||
)
|
||||
assert supplement['rows'] == [{
|
||||
'allocation_id': 'A-1', 'reservation_id': '2000484577',
|
||||
'source_from_party': 'Welltrust', 'source_type': 'DSB CMH',
|
||||
'allocated_entity': 'IEC-CJS', 'mpn': 'D4-A08AR12000002',
|
||||
'allocated_qty': '30', 'po_number': '4518838152',
|
||||
'source_from_party': 'Welltrust', 'inventory_source_hint': 'DSB CMH',
|
||||
'allocated_entity': 'IEC-CJS', 'part_number': 'D4-A08AR12000002',
|
||||
'allocated_qty': '30', 'customer_po_number': '4518838152',
|
||||
'evidence': supplement['rows'][0]['evidence'], 'table_index': None, 'row_index': 1,
|
||||
}]
|
||||
|
||||
|
||||
@@ -416,7 +416,8 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
|
||||
assert resolve_run_id_for_chat_log(session_id='bind-on-start', query='执行 RoHS 检核') == run_id
|
||||
|
||||
|
||||
def test_file_check_tool_no_data_does_not_create_run_or_bind_context(app, client, monkeypatch):
|
||||
def test_file_check_tool_no_data_creates_bound_completed_run_with_full_progress(app, client, monkeypatch):
|
||||
"""无待检资料也要给本轮对话一条可展示 100% 进度的完成批次。"""
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
@@ -446,15 +447,29 @@ def test_file_check_tool_no_data_does_not_create_run_or_bind_context(app, client
|
||||
data = res.get_json()
|
||||
assert data['ok'] is False
|
||||
assert data['error_code'] == 'no_data_to_check'
|
||||
assert 'run' not in data
|
||||
run_id = data['run']['run_id']
|
||||
|
||||
with app.app_context():
|
||||
after_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
|
||||
assert after_count == before_count
|
||||
assert after_count == before_count + 1
|
||||
run = db.session.get(ScheduleRun, run_id)
|
||||
assert run.status == 'success'
|
||||
assert run.total_count == 0
|
||||
assert run.success_count == 0
|
||||
assert run.failed_count == 0
|
||||
assert run.skipped_count == 0
|
||||
assert run.finished_at is not None
|
||||
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
|
||||
|
||||
assert resolve_run_id_for_chat_log(turn_id='no-data-turn') is None
|
||||
assert resolve_run_id_for_chat_log(session_id='no-data-session', query='立即执行检核') is None
|
||||
assert resolve_run_id_for_chat_log(turn_id='no-data-turn') == run_id
|
||||
assert resolve_run_id_for_chat_log(session_id='no-data-session', query='立即执行检核') == run_id
|
||||
|
||||
progress_res = client.get(
|
||||
f'/api/workspace/file-check/runs/{run_id}',
|
||||
headers={'X-Username': 'admin'},
|
||||
)
|
||||
assert progress_res.status_code == 200
|
||||
assert progress_res.get_json()['run']['progress_percent'] == 100
|
||||
|
||||
|
||||
def test_file_check_tool_no_data_keeps_existing_running_conflict_priority(app, client, monkeypatch):
|
||||
@@ -661,6 +676,66 @@ def test_file_check_tool_lists_runs_without_task_filter(app, client):
|
||||
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002', 'RUN-OTHER-001'}
|
||||
|
||||
|
||||
def test_latest_file_check_run_binds_existing_run_to_query_turn(app, client):
|
||||
"""查询最近批次只绑定当前对话,不得改写定时任务的原始执行上下文。"""
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-CRON-EMPTY',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='cron',
|
||||
total_count=0,
|
||||
api_request_json={'trigger_source': 'cron'},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
run_id = run.id
|
||||
|
||||
from app.models import ChatToolRun
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
|
||||
|
||||
register_file_check_chat_turn(
|
||||
turn_id='turn-query-latest',
|
||||
session_id='session-query-latest',
|
||||
user_id=admin.id,
|
||||
agent_id=1,
|
||||
query='查看最近执行记录',
|
||||
)
|
||||
register_pending_turn(
|
||||
turn_id='turn-query-latest',
|
||||
session_id='session-query-latest',
|
||||
user_id=admin.id,
|
||||
agent_id=1,
|
||||
user_message='查看最近执行记录',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
|
||||
res = client.get(
|
||||
f'/api/file-check/tools/tasks/{task_id}/latest-run',
|
||||
query_string={
|
||||
'hxops_turn_id': 'turn-query-latest',
|
||||
'conversation_id': 'session-query-latest',
|
||||
'user_message': '查看最近执行记录',
|
||||
},
|
||||
headers={'X-Integration-Key': 'secret'},
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
assert res.get_json()['run']['run_id'] == run_id
|
||||
|
||||
with app.app_context():
|
||||
binding = ChatToolRun.query.filter_by(turn_id='turn-query-latest').first()
|
||||
rebound_run = db.session.get(ScheduleRun, run_id)
|
||||
assert binding.schedule_run_id == run_id
|
||||
assert rebound_run.api_request_json == {'trigger_source': 'cron'}
|
||||
|
||||
|
||||
def test_workspace_file_check_active_run_returns_progress(app, client):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
@@ -702,6 +777,35 @@ def test_workspace_file_check_active_run_returns_progress(app, client):
|
||||
assert data['run']['current_step']['row_id'] == 'ROW-16'
|
||||
|
||||
|
||||
def test_workspace_file_check_successful_empty_run_reports_complete_progress(app, client):
|
||||
"""已完成的空批次应展示 100% 进度,避免被误解为尚未执行。"""
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-EMPTY',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='cron',
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
|
||||
res = client.get(
|
||||
f'/api/workspace/file-check/runs/{run_id}',
|
||||
headers={'X-Username': 'admin'},
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
assert res.get_json()['run']['progress_percent'] == 100
|
||||
|
||||
|
||||
def test_workspace_file_check_active_run_filters_by_task_id(app, client):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""收料文件下载和人工补偿的权限/审计契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _headers(username: str, role: str) -> dict[str, str]:
|
||||
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client, monkeypatch):
|
||||
"""排程接收人可下载原样文件;非接收人不可通过猜测 ID 越权。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-download-user', email='receipt-download@example.com', role='user', status='active')
|
||||
other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
file_id = report_file.id
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_access.file_asset_storage.get_bytes', lambda _key: b'xlsx')
|
||||
|
||||
allowed = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user'))
|
||||
denied = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user'))
|
||||
assert allowed.status_code == 200
|
||||
assert allowed.data == b'xlsx'
|
||||
assert denied.status_code == 403
|
||||
|
||||
|
||||
def test_receipt_recipient_lists_only_own_archived_files(app, client):
|
||||
"""接收人文件列表仅返回本人排程归档,并且不得泄露对象存储定位。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-list-user', email='receipt-list@example.com', role='user', status='active')
|
||||
other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
db.session.add_all([own_run, other_run]); db.session.flush()
|
||||
own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={})
|
||||
other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={})
|
||||
db.session.add_all([own_unit, other_unit]); db.session.flush()
|
||||
own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64)
|
||||
db.session.add_all([own_file, ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)])
|
||||
db.session.commit()
|
||||
own_file_id = own_file.id
|
||||
|
||||
response = client.get('/api/workspace/receipt-report-files', headers=_headers('receipt-list-user', 'user'))
|
||||
|
||||
assert response.status_code == 200
|
||||
items = response.get_json()['data']['items']
|
||||
# 关键断言:列表投影不能泄露非接收人的文件或对象存储定位。
|
||||
assert [item['id'] for item in items] == [own_file_id]
|
||||
assert 'storage_key' not in items[0]
|
||||
assert items[0]['download_url'].endswith(f'/receipt-report-files/{own_file_id}/download')
|
||||
|
||||
|
||||
def test_receipt_file_list_filters_before_applying_limit(app):
|
||||
"""其他人的新文件再多,也不能挤掉接收人较早的可见归档。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-limit-user', email='receipt-limit@example.com', role='user', status='active')
|
||||
other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
db.session.add_all([own_run, other_run]); db.session.flush()
|
||||
own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={})
|
||||
other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={})
|
||||
db.session.add_all([own_unit, other_unit]); db.session.flush()
|
||||
own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64)
|
||||
db.session.add(own_file); db.session.flush()
|
||||
for index in range(3):
|
||||
db.session.add(ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64))
|
||||
db.session.commit()
|
||||
|
||||
items = list_receipt_report_files(recipient, limit=1)
|
||||
|
||||
# 关键断言:授权过滤发生在截断之前,避免被其他排程的归档饿死。
|
||||
assert [item['id'] for item in items] == [own_file.id]
|
||||
|
||||
|
||||
def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
|
||||
"""管理员重发只调用文件投递,不创建 RPA 单元或 trigger。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
file_id = report_file.id
|
||||
calls = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.deliver_receipt_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0})
|
||||
|
||||
response = client.post(f'/api/admin/receipt-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
assert calls == [(file_id, True)]
|
||||
|
||||
|
||||
def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, client, monkeypatch):
|
||||
"""失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-retry-admin', email='receipt-retry-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RETRY', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
failed = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []})
|
||||
db.session.add(failed); db.session.commit()
|
||||
failed_id = failed.id
|
||||
captured = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
|
||||
|
||||
response = client.post(f'/api/admin/receipt-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
with app.app_context():
|
||||
retry = ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=failed_id).one()
|
||||
assert retry.status == 'awaiting_rpa'
|
||||
assert retry.callback_id != 'receipt-failed'
|
||||
assert captured and captured[0][1][0]['callback_id'] == retry.callback_id
|
||||
|
||||
|
||||
def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client):
|
||||
"""管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-units-admin', email='receipt-units-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
unit_id = unit.id
|
||||
|
||||
response = client.get('/api/admin/receipt-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin'))
|
||||
|
||||
assert response.status_code == 200
|
||||
assert [item['id'] for item in response.get_json()['data']['items']] == [unit_id]
|
||||
with app.app_context():
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_units_listed').count() == 1
|
||||
@@ -0,0 +1,46 @@
|
||||
"""收料 RPA callback 的归档和幂等契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch):
|
||||
"""同一 callback 重放只归档一条收料文件,绝不创建库存快照。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
first = ingest_receipt_callback(payload)
|
||||
second = ingest_receipt_callback(payload)
|
||||
assert first['file_id'] == second['file_id']
|
||||
assert ShippingInventoryFile.query.count() == 0
|
||||
|
||||
|
||||
def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
|
||||
"""Callback cannot read arbitrary local xlsx files outside the receipt-only drop root."""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file
|
||||
|
||||
with app.app_context():
|
||||
allowed_root = tmp_path / 'receipt-drop'
|
||||
allowed_root.mkdir()
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'not-a-real-xlsx')
|
||||
|
||||
with pytest.raises(ValidationError, match='receipt callback file'):
|
||||
_read_receipt_callback_file(str(outside))
|
||||
@@ -0,0 +1,65 @@
|
||||
"""收料文件企微投递和授权下载契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipients(app, monkeypatch):
|
||||
"""同一文件只向排程接收人发送一次,重放不会重复调用企微。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-recipient', email='recipient@example.com', role='user', status='active', wecom_userid='receipt-user')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-notify-callback', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.upload_wecom_temp_media', lambda *_args: 'media-1')
|
||||
calls: list[tuple] = []
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0})
|
||||
|
||||
assert deliver_receipt_file(report_file.id)['success_count'] == 1
|
||||
assert deliver_receipt_file(report_file.id)['success_count'] == 1
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
"""企微投递失败也必须保留接收人、时间、失败码和文件身份审计。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-unbound-recipient', email='receipt-unbound@example.com', role='user', status='active')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY-FAIL', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-notify-fail', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
|
||||
outcome = deliver_receipt_file(report_file.id)
|
||||
|
||||
assert outcome['failed_count'] == 1
|
||||
audit = ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_file_notification_attempted', aggregate_id=str(report_file.id)).one()
|
||||
# 审计结果遵循统一枚举;业务投递状态仍保留为 failed。
|
||||
assert audit.result == 'failure'
|
||||
assert audit.after_snapshot_json['error_code'] == 'WECOM_USER_UNBOUND'
|
||||
@@ -0,0 +1,106 @@
|
||||
"""独立收料 RPA 排程的单元展开和 trigger 契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch):
|
||||
"""DBS 必须按 Warehouse 展开;Crane 固定为每站点一个单元。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
|
||||
with app.app_context():
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = ShippingRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'})
|
||||
crane = ShippingInventorySource(
|
||||
source_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', rpa_profile=crane_profile,
|
||||
parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, enabled=True, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, warehouse_ids_json=['A', 'B']),])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, enabled=True, report_path_json={'report_name': 'Inbound Details'}, warehouse_ids_json=[]))
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', job_params={'source_codes': [dbs.source_code, crane.source_code]})
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-1', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.commit()
|
||||
|
||||
captured = {}
|
||||
monkeypatch.setattr('app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json')
|
||||
total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run)
|
||||
|
||||
assert (total, success, failed, skipped, errors) == (3, 0, 0, 0, [])
|
||||
assert {(item['source_code'], item['warehouse_id']) for item in details} == {(dbs.source_code, 'A'), (dbs.source_code, 'B'), (crane.source_code, None)}
|
||||
assert captured['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert len(captured['units']) == 3
|
||||
dbs_unit = next(item for item in captured['units'] if item['source_code'] == dbs.source_code)
|
||||
# Worker only receives this frozen execution snapshot, not a later mutable site config.
|
||||
assert dbs_unit['rpa_profile_code'] == 'DBS_DUB_TEST'
|
||||
assert dbs_unit['login_url'] == 'https://test.invalid/dbs'
|
||||
assert dbs_unit['credential_envelope'] == {
|
||||
'username_ciphertext': None,
|
||||
'password_ciphertext': None,
|
||||
}
|
||||
assert dbs_unit['report_path_json']['report_name'] == 'Receipt Detail'
|
||||
assert dbs_unit['warehouse_id'] == 'A'
|
||||
|
||||
|
||||
def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
"""动态排程选项只暴露库存站点已启用且收料配置也启用的站点。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'},
|
||||
warehouse_ids_json=['A'],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
options = list_job_options('shipping_receipt_sources')
|
||||
|
||||
assert any(item['value'] == source.source_code for item in options)
|
||||
|
||||
|
||||
def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
"""无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
|
||||
assert recover_stale_receipt_rpa_schedule_runs(task) == 1
|
||||
db.session.refresh(run); db.session.refresh(unit)
|
||||
|
||||
assert run.status == 'failed'
|
||||
assert unit.status == 'failed'
|
||||
assert unit.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT'
|
||||
assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1
|
||||
|
||||
|
||||
def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
||||
"""Worker 只能观察到完整 JSON;临时写入文件不会匹配其 *.json 扫描。"""
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
|
||||
written = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'receipt:atomic'}])
|
||||
|
||||
assert written is not None
|
||||
assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').is_file()
|
||||
assert not list(tmp_path.glob('*.tmp'))
|
||||
@@ -0,0 +1,43 @@
|
||||
"""独立收料 Worker 静态契约。"""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
|
||||
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'freight_receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
assert 'shipping_receipt_rpa.v1' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-batch-ready' in text
|
||||
assert 'freight_rpa_worker' not in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
|
||||
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
receipt_driver = (root / 'freight_receipt_crane_export.py').read_text(encoding='utf-8')
|
||||
crane_driver = (root / 'crane_report_export.py').read_text(encoding='utf-8')
|
||||
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
|
||||
assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver
|
||||
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
module_path = root / 'freight_receipt_crane_export.py'
|
||||
sys.path.insert(0, str(root))
|
||||
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
assert module._inbound_details_entry_url('https://wms-portal.craneww.com/#/') == (
|
||||
'https://wms-portal.craneww.com/#/inbound-details-query'
|
||||
)
|
||||
assert module._inbound_details_entry_url('https://wms-portal.craneww.com/') == (
|
||||
'https://wms-portal.craneww.com/#/inbound-details-query'
|
||||
)
|
||||
@@ -4,6 +4,8 @@ from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -60,3 +62,44 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
|
||||
content = sentinel.read_text(encoding="utf-8")
|
||||
assert "scope_id=hxops-rpa-test-data" in content
|
||||
assert "host=WIN-RPA-01" in content
|
||||
|
||||
|
||||
def test_maybe_send_heartbeat_does_not_block_trigger_loop_when_http_stalls(tmp_path, monkeypatch):
|
||||
"""断言底层 HTTP 卡住时,主 Worker 仍能立即继续扫描 Trigger。"""
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
release_request = threading.Event()
|
||||
request_started = threading.Event()
|
||||
calls: list[dict] = []
|
||||
|
||||
def stalled_post(payload):
|
||||
calls.append(payload)
|
||||
request_started.set()
|
||||
release_request.wait(timeout=2)
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(module, "post_heartbeat", stalled_post)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "15")
|
||||
started = time.monotonic()
|
||||
sent_at = module.maybe_send_heartbeat(
|
||||
trigger_dir=tmp_path,
|
||||
drop_dir=tmp_path,
|
||||
last_sent_mono=0.0,
|
||||
force=True,
|
||||
)
|
||||
|
||||
# 核心断言:投递而非等待卡住的 HTTP 请求,扫描循环可立即继续。
|
||||
assert time.monotonic() - started < 0.2
|
||||
assert sent_at > 0
|
||||
assert request_started.wait(timeout=0.5)
|
||||
|
||||
module.maybe_send_heartbeat(
|
||||
trigger_dir=tmp_path,
|
||||
drop_dir=tmp_path,
|
||||
last_sent_mono=0.0,
|
||||
force=True,
|
||||
)
|
||||
# 同一时刻只允许一个后台请求,避免后端异常时线程无限累积。
|
||||
assert len(calls) == 1
|
||||
release_request.set()
|
||||
assert module._HEARTBEAT_THREAD is not None
|
||||
module._HEARTBEAT_THREAD.join(timeout=1)
|
||||
@@ -185,6 +185,138 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
}
|
||||
|
||||
|
||||
def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_path):
|
||||
"""Crane 动态 Warehouse 在导出前未知时,v2 trigger 不应被身份校验拒绝。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_crane_dynamic.json"
|
||||
source = {
|
||||
"source_code": "CRANE",
|
||||
"connector_type": "crane",
|
||||
"task_no": "SN-CRANE-DYNAMIC",
|
||||
"callback_id": "PSR-CRANE-DYNAMIC:C1",
|
||||
"source_run_no": "PSR-CRANE-DYNAMIC",
|
||||
"attempt_no": 2,
|
||||
"lease_token": "lease-crane",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "BATCH-CRANE-DYNAMIC:batch:C1",
|
||||
"batch_run_no": "BATCH-CRANE-DYNAMIC",
|
||||
"task_no": "SN-CRANE-DYNAMIC",
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
assert completed["results"][0]["callback_id"] == "PSR-CRANE-DYNAMIC:C1"
|
||||
assert completed["results"][0]["expected_warehouse_id"] is None
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
|
||||
|
||||
def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch, tmp_path):
|
||||
"""可识别的非法 batch trigger 必须回传 batch callback_id,供平台记录拒绝终态。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_invalid.json"
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "BATCH-INVALID:batch:C1",
|
||||
"batch_run_no": "BATCH-INVALID",
|
||||
"task_no": "SN-BATCH-INVALID",
|
||||
"inventory_sources": [{
|
||||
"source_code": "DBS",
|
||||
"connector_type": "dbs",
|
||||
"task_no": "SN-BATCH-INVALID",
|
||||
"callback_id": "PSR-BATCH-INVALID:C1",
|
||||
"source_run_no": "PSR-BATCH-INVALID",
|
||||
"attempt_no": 2,
|
||||
"lease_token": "lease-batch",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
}],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks[0][1]["callback_id"] == "BATCH-INVALID:batch:C1"
|
||||
assert callbacks[0][1]["identity_errors"] == ["inventory_sources[0].expected_warehouse_id"]
|
||||
|
||||
|
||||
def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path):
|
||||
"""Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_interrupt.json"
|
||||
source = {
|
||||
"source_code": "CRANE",
|
||||
"connector_type": "crane",
|
||||
"task_no": "SN-CRANE-INTERRUPT",
|
||||
"callback_id": "PSR-CRANE-INTERRUPT:C1",
|
||||
"source_run_no": "PSR-CRANE-INTERRUPT",
|
||||
"attempt_no": 1,
|
||||
"lease_token": "lease-interrupt",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "BATCH-INTERRUPT:batch:C1",
|
||||
"batch_run_no": "BATCH-INTERRUPT",
|
||||
"task_no": "SN-CRANE-INTERRUPT",
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
stopped = []
|
||||
|
||||
class _Context:
|
||||
def close(self):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
class _Playwright:
|
||||
def stop(self):
|
||||
stopped.append(True)
|
||||
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda *_args, **_kwargs: (_Playwright(), _Context(), object(), tmp_path / "profile"))
|
||||
monkeypatch.setattr(worker, "_ensure_crane_session", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(worker, "_export_crane_inventory_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
with pytest.raises(KeyboardInterrupt):
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert stopped == [True]
|
||||
assert [path for path, _body in callbacks] == ["/api/shipping-notice/rpa/inventory-batch-claimed"]
|
||||
assert trigger_path.is_file()
|
||||
assert not (processed_dir / trigger_path.name).exists()
|
||||
|
||||
|
||||
def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -1108,6 +1240,45 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
}
|
||||
|
||||
|
||||
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
|
||||
"""DSV 会话复用开关开启时应使用固定 profile,且固定 profile 不能按临时目录清理。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
class _FakePage:
|
||||
def set_default_timeout(self, value: int) -> None:
|
||||
observed["timeout"] = value
|
||||
|
||||
class _FakeContext:
|
||||
pages = [_FakePage()]
|
||||
|
||||
class _FakeChromium:
|
||||
def launch_persistent_context(self, profile: str, **kwargs):
|
||||
observed["profile"] = profile
|
||||
return _FakeContext()
|
||||
|
||||
class _FakePlaywright:
|
||||
chromium = _FakeChromium()
|
||||
|
||||
class _FakeStarter:
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "true")
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
tmp_path / "downloads", reuse_dsv_session=True
|
||||
)
|
||||
|
||||
assert context is not None
|
||||
assert page is not None
|
||||
assert profile_dir == tmp_path / "profile" / "dsv360_session"
|
||||
assert observed["profile"] == str(profile_dir)
|
||||
assert worker._should_cleanup_browser_profile(profile_dir) is False
|
||||
|
||||
|
||||
def test_is_dsv_username_page_ignores_login_method_page_text():
|
||||
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -16,6 +16,10 @@ def _load_dsv_report_export():
|
||||
return _load_rpa_module("dsv_report_export")
|
||||
|
||||
|
||||
def _load_dsv_auth_login_flow():
|
||||
return _load_rpa_module("dsv_auth_login_flow")
|
||||
|
||||
|
||||
def _load_rpa_module(module_name: str):
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py"
|
||||
scripts_dir = str(module_path.parent)
|
||||
@@ -195,6 +199,128 @@ def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(
|
||||
reset.assert_not_called()
|
||||
|
||||
|
||||
def test_dsv_session_prepare_emits_elapsed_stage_logs(monkeypatch):
|
||||
"""DSV session 准备应记录完整耗时,供真实运行区分认证和首页等待。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
chain = MagicMock()
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
|
||||
monkeypatch.setattr(worker, "_is_dsv_session_active", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(worker, "_is_dsv_in_report_navigation_context", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_home_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_reports_nav_stable", MagicMock())
|
||||
|
||||
worker._ensure_dsv_session(page, "https://s360.dbschenker.com/")
|
||||
|
||||
assert [call.args[:2] for call in chain.call_args_list] == [
|
||||
("session_prepare", "start"),
|
||||
("session_prepare", "end"),
|
||||
]
|
||||
|
||||
|
||||
def test_dsv_navigation_emits_elapsed_stage_logs(monkeypatch):
|
||||
"""Reports 到参数页的整段导航应记录耗时,不能只依赖零散 DOM 调试日志。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
chain = MagicMock()
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
|
||||
monkeypatch.setattr(worker, "_env", lambda _key, default=None: "")
|
||||
monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
|
||||
worker._navigate_dsv_to_report_form(
|
||||
page,
|
||||
{"navigation": {"program_label": "AWS", "report_name": "On Hand Inventory by Location"}},
|
||||
)
|
||||
|
||||
assert [call.args[:2] for call in chain.call_args_list] == [
|
||||
("report_navigation", "start"),
|
||||
("report_navigation", "end"),
|
||||
]
|
||||
|
||||
|
||||
def test_dsv_menu_item_uses_compatibility_fallback_only_after_fast_path_misses(monkeypatch):
|
||||
"""快速菜单点击未确认下一级时,必须保留原兼容路径,避免降低 DSV 成功率。"""
|
||||
navigation = _load_rpa_module("dsv_navigation")
|
||||
page = MagicMock()
|
||||
compatibility = MagicMock()
|
||||
monkeypatch.setattr(navigation, "_try_dsv_menu_item_fast_path", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(navigation, "_click_dsv_menu_item_compat", compatibility)
|
||||
|
||||
navigation._click_dsv_menu_item(page, "AWS", next_text="Inventory")
|
||||
|
||||
compatibility.assert_called_once_with(page, "AWS", next_text="Inventory")
|
||||
|
||||
|
||||
def test_dsv_report_group_skips_compatibility_fallback_after_fast_path_confirms(monkeypatch):
|
||||
"""快速路径确认报表已展开后,不应再触发耗时的 Report Group 兼容点击。"""
|
||||
navigation = _load_rpa_module("dsv_navigation")
|
||||
page = MagicMock()
|
||||
compatibility = MagicMock()
|
||||
monkeypatch.setattr(navigation, "_try_dsv_report_group_fast_path", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(navigation, "_click_dsv_report_group_compat", compatibility)
|
||||
|
||||
navigation._click_dsv_report_group(page, "Inventory", next_text="On Hand Inventory by Location")
|
||||
|
||||
compatibility.assert_not_called()
|
||||
|
||||
|
||||
def test_dsv_report_execution_emits_parameter_and_download_stage_logs(monkeypatch):
|
||||
"""报表结果就绪与 Excel 下载应分段计时,且不应等待不可靠的 networkidle。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
download = MagicMock()
|
||||
download_context = MagicMock()
|
||||
download_context.__enter__.return_value = MagicMock(value=download)
|
||||
download_context.__exit__.return_value = False
|
||||
page.expect_download.return_value = download_context
|
||||
chain = MagicMock()
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
|
||||
monkeypatch.setattr(worker, "_fill_report_parameters", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_view_report", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_dsv_report_has_inventory_data_rows", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(worker, "_click_dsv_export_excel", MagicMock())
|
||||
|
||||
assert worker._run_dsv_inventory_export_from_form(page, {}) is download
|
||||
|
||||
assert [call.args[:2] for call in chain.call_args_list] == [
|
||||
("report_parameter_fill", "start"),
|
||||
("report_parameter_fill", "end"),
|
||||
("report_execute_and_download", "start"),
|
||||
("report_result_ready", "start"),
|
||||
("report_result_ready", "end"),
|
||||
("excel_export_and_download", "start"),
|
||||
("excel_download_event", "start"),
|
||||
("excel_download_event", "end"),
|
||||
("excel_export_and_download", "end"),
|
||||
("report_execute_and_download", "end"),
|
||||
]
|
||||
page.wait_for_load_state.assert_not_called()
|
||||
|
||||
|
||||
def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch):
|
||||
"""持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。"""
|
||||
flow = _load_dsv_auth_login_flow()
|
||||
page = MagicMock()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "user")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "password")
|
||||
selector_wait = MagicMock()
|
||||
auth_ready = MagicMock()
|
||||
monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True)
|
||||
monkeypatch.setattr(flow, "_wait_for_visible_selector", selector_wait)
|
||||
monkeypatch.setattr(flow, "_wait_for_dsv_auth_page_ready", auth_ready)
|
||||
|
||||
flow._maybe_auto_login_dsv(page)
|
||||
|
||||
# 核心断言:会话已在 Portal 时,不能走用户名 15 秒探测或认证页轮询。
|
||||
selector_wait.assert_not_called()
|
||||
auth_ready.assert_not_called()
|
||||
|
||||
|
||||
def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatch):
|
||||
"""program/report 变化时仍应回 portal 首页。"""
|
||||
worker = _load_dsv_report_export()
|
||||
|
||||
@@ -26,6 +26,7 @@ def test_empty_rpa_snapshot_is_auditable_but_never_available_for_matching(app):
|
||||
)
|
||||
|
||||
# 关键断言:重放同一空结果不重复写审计;空快照不能污染匹配可用库存池。
|
||||
assert first.identity_status == 'unknown'
|
||||
assert repeated.id == first.id
|
||||
assert first.snapshot_status == 'empty'
|
||||
assert first.line_count == 0
|
||||
|
||||
@@ -152,7 +152,7 @@ def test_waiting_inventory_maps_to_inventory_fetching_stage():
|
||||
)
|
||||
|
||||
status, stage = map_notice_to_processing_status_stage(
|
||||
SimpleNamespace(process_status='waiting_inventory', current_step=None, export_file_path=None),
|
||||
SimpleNamespace(current_step=None, export_file_path=None),
|
||||
)
|
||||
assert status == 'automating'
|
||||
assert stage == 'inventory_fetching'
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from tests.test_shipping_order_document_profile_service import _bind_ready_profile_sample, _schema_version
|
||||
|
||||
|
||||
@@ -86,8 +87,36 @@ def test_wizard_completion_invalid_main_table_rolls_back_without_profile(app):
|
||||
assert ShippingOrderDocumentProfileEditLease.query.count() == 0
|
||||
|
||||
|
||||
def test_wizard_xfa_mode_requires_authoritative_collection_not_table(app, monkeypatch):
|
||||
"""关键断言:XFA 样本向导拒绝缺失权威集合,且不要求 main_table_id。"""
|
||||
def test_public_identity_signature_owns_coordinate_run_lifecycle(app, monkeypatch):
|
||||
"""关键断言:坐标模板也不得回退到旧 layout runner 的独立生命周期。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
seed = ShippingOrderDocumentProfile(
|
||||
profile_code='SEED_SIGN', display_name='Seed', version=1, status='draft',
|
||||
schema_version_id=schema.id, structure_fingerprint='c' * 64,
|
||||
definition_json={}, template_mode='coordinate', lock_version=1,
|
||||
)
|
||||
db.session.add(seed)
|
||||
db.session.commit()
|
||||
sample = _bind_ready_profile_sample(seed.id)
|
||||
created = creation_service.complete_wizard(_wizard_payload(schema.id, sample.document_id), actor_id=None)
|
||||
lease = created['edit_lease']
|
||||
|
||||
def _legacy_runner_must_not_run(*_args, **_kwargs):
|
||||
raise AssertionError('public identity lifecycle must not dispatch to legacy coordinate runner')
|
||||
|
||||
monkeypatch.setattr(validation_service, 'run_layout_signature', _legacy_runner_must_not_run)
|
||||
signature = validation_service.run_profile_identity_signature(
|
||||
created['id'], data={}, actor_id=None, browser_session_id='wizard-tab-a',
|
||||
lease_token=lease['lease_token'], operation_id='coordinate-public-identity',
|
||||
)
|
||||
|
||||
assert signature['stored_status'] == 'passed'
|
||||
assert signature['run_type'] == 'layout_signature'
|
||||
|
||||
|
||||
def test_wizard_xfa_mode_creates_visual_main_table_draft_before_dataset_mapping(app, monkeypatch):
|
||||
"""关键断言:XFA 向导只冻结视觉主表;datasets 选择留给编辑映射,发布仍 fail-closed。"""
|
||||
from hashlib import sha256
|
||||
|
||||
from app.models import User
|
||||
@@ -130,28 +159,50 @@ def test_wizard_xfa_mode_requires_authoritative_collection_not_table(app, monkey
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
layout = dict(outcome.snapshot)
|
||||
layout['status'] = 'ready'
|
||||
layout['provider'] = 'xfa'
|
||||
layout['provider'] = 'mineru'
|
||||
layout['tables'] = [{'table_id': 'xfa-visual-main', 'page_no': 1}]
|
||||
layout['capability'] = {}
|
||||
layout['coordinate_evidence'] = {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
}
|
||||
layout.setdefault('xfa_capability', {})['structure_analysis_ready'] = True
|
||||
layout_version = record_inline_layout_snapshot(document, layout)
|
||||
persist_xfa_structure_analysis(
|
||||
document_id=document.id, layout_version_id=layout_version.id,
|
||||
source_content_hash=content_hash, outcome=outcome,
|
||||
)
|
||||
# 生产 Job 会在持久化 XFA analysis 后把 analysis_id 合并回同一视觉 Layout 快照。
|
||||
frozen_layout = dict(layout_version.payload_json)
|
||||
frozen_xfa_capability = dict(frozen_layout['xfa_capability'])
|
||||
frozen_xfa_capability['structure_analysis_id'] = outcome.analysis_record.id
|
||||
frozen_layout['xfa_capability'] = frozen_xfa_capability
|
||||
layout_version.payload_json = frozen_layout
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(Exception) as missing:
|
||||
with pytest.raises(Exception) as missing_table:
|
||||
creation_service.complete_wizard({
|
||||
'display_name': 'XFA', 'schema_version_id': schema.id, 'document_id': document.id,
|
||||
'browser_session_id': 'tab', 'operation_id': 'op-missing-auth',
|
||||
'authoritative_collection_path_id': _path_id_for('/data/ITEMS/DATA'),
|
||||
'browser_session_id': 'tab', 'operation_id': 'op-missing-table',
|
||||
}, actor_id=user.id)
|
||||
assert getattr(missing.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
assert getattr(missing_table.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'XFA', 'schema_version_id': schema.id, 'document_id': document.id,
|
||||
'authoritative_collection_path_id': _path_id_for('/data/ITEMS/DATA'),
|
||||
'browser_session_id': 'tab', 'operation_id': 'op-xfa-ok',
|
||||
'main_table_id': 'xfa-visual-main',
|
||||
'browser_session_id': 'tab', 'operation_id': 'op-xfa-draft-without-source',
|
||||
}, actor_id=user.id)
|
||||
assert created['template_mode'] == 'xfa_dataset'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=created['id'], sample_role='annotation', table_id=None,
|
||||
profile_id=created['id'], sample_role='annotation', table_id='xfa-visual-main',
|
||||
).count() == 1
|
||||
assert created['definition']['main_table_id'] == 'xfa-visual-main'
|
||||
assert created['definition']['source_contract']['authoritative_line_collection_path'] is None
|
||||
assert created['definition']['line_mapping']['row_path'] is None
|
||||
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, created['id'])
|
||||
blocking = get_value_adapter(profile.definition_json).publish_checks(profile, validation=None)
|
||||
assert 'xfa_authoritative_collection_missing' in {item['key'] for item in blocking}
|
||||
@@ -35,7 +35,8 @@ def test_draft_save_creates_immutable_revision_and_same_operation_is_idempotent(
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='create-op')
|
||||
lease = _lease(draft['id'], session_id='tab-a', operation_id='lease-op')
|
||||
payload = _data(schema.id)
|
||||
payload['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.6
|
||||
# 保持两列不重叠:该测试验证 Revision/幂等而非覆盖坐标校验。
|
||||
payload['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.15
|
||||
payload.update({'expected_lock_version': draft['lock_version'], 'change_note': 'first edit'})
|
||||
first = profile_service.save_draft(
|
||||
payload,
|
||||
@@ -73,7 +74,8 @@ def test_edit_lease_conflict_takeover_and_restore_append_new_revision(app):
|
||||
|
||||
changed = _data(schema.id)
|
||||
changed['display_name'] = 'Changed profile name'
|
||||
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.7
|
||||
# 保持两列不重叠:该测试验证租约接管与历史恢复。
|
||||
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.15
|
||||
changed['expected_lock_version'] = draft['lock_version']
|
||||
saved = profile_service.save_draft(
|
||||
changed,
|
||||
|
||||
@@ -8,6 +8,11 @@ tests/test_order_document_profile_overlap_summary.py
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_document_profile_validation_service import build_cross_template_overlap_summary
|
||||
from app.services.shipping_notice.order_document_profile_validation_service import _evaluate_self_sample_match
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
ProfileMatchCandidate,
|
||||
ProfileMatchResult,
|
||||
)
|
||||
|
||||
|
||||
def test_overlap_summary_passes_when_all_self_unique():
|
||||
@@ -49,3 +54,24 @@ def test_overlap_summary_fails_on_false_hit_and_builds_conflicts():
|
||||
assert summary['false_hit_other_count'] == 1
|
||||
assert snapshot['conflict_profiles'][0]['profile_code'] == 'PO_B'
|
||||
assert 'false_hit' in snapshot['conflict_profiles'][0]['reason_codes']
|
||||
|
||||
|
||||
def test_overlap_ignores_ineligible_candidate_when_unique_match_has_no_eligible_rival():
|
||||
"""已判唯一命中时,未达自身资格的候选不得制造虚假 margin 失败。"""
|
||||
result = ProfileMatchResult(
|
||||
status='unique_match', profile_code='PO_A', version=1, margin=0.01,
|
||||
candidates=[ProfileMatchCandidate(
|
||||
profile_code='PO_A', version=1, score=1.0, evidence_coverage=0.8,
|
||||
hard_match=True, margin_to_next=0.01,
|
||||
)],
|
||||
)
|
||||
|
||||
outcome = _evaluate_self_sample_match(
|
||||
profile_code='PO_A', profile_version=1, match_result=result,
|
||||
parse_result={'passed': True},
|
||||
thresholds={'minimum_score': 0.9, 'minimum_margin': 0.12, 'evidence_coverage_minimum': 0.7},
|
||||
)
|
||||
|
||||
assert outcome['self_unique'] is True
|
||||
assert outcome['margin'] == 1.0
|
||||
assert outcome['margin_ok'] is True
|
||||
@@ -296,6 +296,59 @@ def test_frozen_sample_region_diagnostics_reads_only_configured_regions_in_visua
|
||||
}
|
||||
|
||||
|
||||
def test_frozen_region_diagnostics_retries_only_empty_hybrid_xfa_value_region_with_ocr(app, monkeypatch):
|
||||
"""Hybrid XFA 的原生标签不能掩盖同页视觉值框的 OCR 样本值。"""
|
||||
profile = SimpleNamespace(id=9, definition_json={
|
||||
'document_match': {'required_anchors': [{
|
||||
'anchor_id': 'po', 'label': 'ORDER NO', 'value': None, 'page_no': 1,
|
||||
'label_region': {'x0': .05, 'y0': .05, 'x1': .40, 'y1': .25},
|
||||
'value_region': {'x0': .45, 'y0': .05, 'x1': .95, 'y1': .25},
|
||||
}]},
|
||||
'table_regions': [], 'order_field_layouts': [], 'draft_unbound_order_field_layouts': [],
|
||||
})
|
||||
sample = SimpleNamespace(id=8)
|
||||
document = SimpleNamespace(id=7, filename='hybrid-xfa.pdf')
|
||||
asset = SimpleNamespace(id=6)
|
||||
native_label_glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 8, 'y0': 10, 'x1': 16 + index * 8, 'y1': 20}}
|
||||
for index, char in enumerate('ORDER NO')
|
||||
]
|
||||
ocr_value_glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 100 + index * 8, 'y0': 10, 'x1': 106 + index * 8, 'y1': 20}}
|
||||
for index, char in enumerate('4510039227')
|
||||
]
|
||||
layout = SimpleNamespace(payload_json={
|
||||
'tables': [],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': native_label_glyphs},
|
||||
},
|
||||
})
|
||||
calls: list[bool] = []
|
||||
|
||||
def recover(**kwargs):
|
||||
calls.append(bool(kwargs.get('force_ocr')))
|
||||
assert kwargs['force_ocr'] is True
|
||||
return {'width': 200, 'height': 100}, ocr_value_glyphs, 'ocr_coordinate'
|
||||
|
||||
monkeypatch.setattr(
|
||||
preview_service, '_frozen_sample_context',
|
||||
lambda **_kwargs: (profile, sample, document, layout, asset),
|
||||
)
|
||||
monkeypatch.setattr(preview_service, '_recover_frozen_page_coordinates', recover)
|
||||
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
|
||||
|
||||
with app.app_context():
|
||||
result = preview_service.frozen_sample_region_diagnostics(
|
||||
9, sample_binding_id=8, page_no=1, actor_id=1,
|
||||
)
|
||||
|
||||
by_id = {item['region_id']: item for item in result['items']}
|
||||
assert by_id['po_label']['recognized_value'] == 'ORDER NO'
|
||||
assert by_id['po_value']['recognized_value'] == '4510039227'
|
||||
assert calls == [True]
|
||||
|
||||
|
||||
def test_frozen_sample_region_diagnostics_without_coordinate_evidence_returns_empty(app, monkeypatch):
|
||||
"""缺少字符坐标证据时诊断为空,但不能把可预览 PDF 误报为页面不存在。"""
|
||||
profile = SimpleNamespace(id=9, definition_json={})
|
||||
|
||||
@@ -12,6 +12,26 @@ import pytest
|
||||
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileValidationRun
|
||||
from app.services.shipping_notice import order_document_profile_publish_check_service as checks
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
|
||||
|
||||
def test_adapter_publish_checks_keeps_xfa_rules_behind_a_common_hook():
|
||||
"""关键断言:公共发布编排只调用 adapter hook,不直接分叉 XFA 控制流。"""
|
||||
coordinate = ShippingOrderDocumentProfile(
|
||||
profile_code='COORDINATE_HOOK', display_name='Coordinate', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='a' * 64, definition_json={}, template_mode='coordinate',
|
||||
)
|
||||
xfa = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_HOOK', display_name='XFA', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='b' * 64,
|
||||
definition_json={'template_mode': 'xfa_dataset'}, template_mode='xfa_dataset',
|
||||
)
|
||||
xfa.schema_version = type('SV', (), {'definition_json': {'fields': []}})()
|
||||
|
||||
assert checks._adapter_publish_checks(coordinate, validation=None) == []
|
||||
assert 'xfa_structure_identity_missing' in {
|
||||
item['key'] for item in xfa_dataset.publish_checks(profile=xfa, validation=None)
|
||||
}
|
||||
|
||||
|
||||
def test_blocking_xfa_definition_flags_missing_paths_and_collection():
|
||||
@@ -47,13 +67,49 @@ def test_blocking_xfa_definition_flags_missing_paths_and_collection():
|
||||
profile.schema_version = type('SV', (), {'definition_json': {'fields': [
|
||||
{'field_id': 'f-po', 'field_code': 'customer_po_no', 'enabled': True, 'required': True},
|
||||
]}})()
|
||||
blocking = checks._blocking_xfa_definition(profile, None)
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
keys = {item['key'] for item in blocking}
|
||||
assert 'xfa_structure_identity_missing' in keys
|
||||
assert 'xfa_authoritative_collection_missing' in keys
|
||||
assert 'xfa_required_path_coverage_incomplete' in keys
|
||||
|
||||
|
||||
def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
"""关键断言:同名 header/line 字段缺路径时,发布诊断必须保留真实字段身份。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_SCOPE_DIAGNOSTIC', display_name='XFA Scope', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='c' * 64, template_mode='xfa_dataset',
|
||||
definition_json={
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:template', 'dataset_structure_fingerprint': 'sha256:structure',
|
||||
'dataset_root_path': '/data', 'authoritative_line_collection_path': '/data/ITEMS',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'bindings': [{
|
||||
'binding_id': 'header-reservation', 'field_id': 'reservation-header',
|
||||
'field_code': 'reservation_id', 'scope': 'header', 'field_layout_id': 'header-reservation',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'header-path', 'data_path': '/data/HEADER/RESERVATION'},
|
||||
}],
|
||||
'header_mappings': [], 'line_mapping': {'row_path': '/data/ITEMS', 'fields': []},
|
||||
'cross_checks': {},
|
||||
},
|
||||
)
|
||||
profile.schema_version = type('SV', (), {'definition_json': {'fields': [
|
||||
{'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header', 'enabled': True, 'required': False},
|
||||
{'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'required': True},
|
||||
]}})()
|
||||
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
coverage = next(item for item in blocking if item['key'] == 'xfa_required_path_coverage_incomplete')
|
||||
|
||||
# 同名显示码只是辅助信息;管理员必须能识别真正缺失的是 line 的 reservation_id。
|
||||
assert coverage['field_codes'] == ['reservation_id']
|
||||
assert coverage['missing_fields'] == [{
|
||||
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
}]
|
||||
|
||||
|
||||
def test_blocking_xfa_definition_flags_stale_and_reconciliation():
|
||||
"""关键断言:stale 验证与对账失败码进入发布阻断。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
@@ -102,7 +158,7 @@ def test_blocking_xfa_definition_flags_stale_and_reconciliation():
|
||||
result_snapshot_json={},
|
||||
operation_id='recon',
|
||||
)
|
||||
blocking = checks._blocking_xfa_definition(profile, validation)
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=validation)
|
||||
keys = {item['key'] for item in blocking}
|
||||
assert 'current_validation_stale' in keys
|
||||
assert 'xfa_collection_ambiguity' in keys
|
||||
|
||||
@@ -8,13 +8,17 @@ backend/tests/test_order_document_profile_suggestion_service.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingOrderDocumentProfileSuggestionDecision
|
||||
from app.extensions import db
|
||||
from app.models import Job, ShippingOrderDocument, ShippingOrderDocumentProfileSuggestionDecision
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from tests.test_shipping_order_document_profile_service import _data, _schema_version
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from tests.test_shipping_order_document_profile_service import _bind_ready_profile_sample, _data, _schema_version
|
||||
|
||||
|
||||
def _input() -> dict:
|
||||
@@ -48,3 +52,194 @@ def test_suggestion_decision_requires_active_lease(app):
|
||||
with pytest.raises(Exception) as missing:
|
||||
suggestion_service.decide(draft['id'], data=_input(), actor_id=None, browser_session_id='missing-tab', lease_token='invalid', operation_id='suggestion-missing')
|
||||
assert getattr(missing.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED'
|
||||
|
||||
|
||||
def test_suggestion_decision_audits_selected_visual_evidence_source(app):
|
||||
"""关键断言:多证据中确认的视觉来源进入审计,但不是正式值源绑定。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-evidence-create')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-evidence-tab', operation_id='suggestion-evidence-lease')
|
||||
payload = _input()
|
||||
summary = {**payload['suggestion_summary'], 'selected_evidence_source': 'opencv_geometry'}
|
||||
payload = {**payload, **suggestion_service.suggestion_identity(summary), 'suggestion_summary': summary}
|
||||
suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-evidence-tab', lease_token=lease['lease_token'], operation_id='suggestion-evidence-decision')
|
||||
decision = ShippingOrderDocumentProfileSuggestionDecision.query.filter_by(profile_id=draft['id']).one()
|
||||
assert decision.detail_json['selected_evidence_source'] == 'opencv_geometry'
|
||||
|
||||
|
||||
def test_suggestion_decision_accepts_xfa_widget_geometry_as_audited_visual_source(app):
|
||||
"""XFA Widget 几何仅作为已选视觉行来源,可审计但不改变 datasets 正式值源。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-widget-create')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-widget-tab', operation_id='suggestion-widget-lease')
|
||||
payload = _input()
|
||||
summary = {**payload['suggestion_summary'], 'selected_evidence_source': 'acroform_widget_geometry'}
|
||||
payload = {**payload, **suggestion_service.suggestion_identity(summary), 'suggestion_summary': summary}
|
||||
suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-widget-tab', lease_token=lease['lease_token'], operation_id='suggestion-widget-decision')
|
||||
decision = ShippingOrderDocumentProfileSuggestionDecision.query.filter_by(profile_id=draft['id']).one()
|
||||
assert decision.detail_json['selected_evidence_source'] == 'acroform_widget_geometry'
|
||||
|
||||
|
||||
def test_suggestion_decision_rejects_accept_without_required_visual_source(app):
|
||||
"""关键断言:后端不能被绕过前端,未选择多证据来源不得接受建议。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-required-create')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-required-tab', operation_id='suggestion-required-lease')
|
||||
payload = _input()
|
||||
summary = {**payload['suggestion_summary'], 'evidence_source_required': True, 'selected_evidence_source': None}
|
||||
payload = {**payload, **suggestion_service.suggestion_identity(summary), 'suggestion_summary': summary}
|
||||
with pytest.raises(Exception) as caught:
|
||||
suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-required-tab', lease_token=lease['lease_token'], operation_id='suggestion-required-decision')
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_suggestion_decision_recomputes_source_requirement_from_automark_job(app):
|
||||
"""关键断言:浏览器不能把 evidence_source_required 改为 false 绕过并行候选。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-job-create')
|
||||
sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-job-tab', operation_id='suggestion-job-lease')
|
||||
job = Job(
|
||||
domain='shipping_notice', job_type='shipping_pdf_automark', status='success',
|
||||
payload_json={
|
||||
'profile_id': draft['id'], 'document_id': sample.document_id, 'table_id': sample.table_id, 'page_no': 1,
|
||||
'layout_version_id': sample.layout_version_id, 'layout_payload_checksum': sample.layout_payload_checksum,
|
||||
},
|
||||
result_json={'candidates': [
|
||||
{'candidate_kind': 'table_reconstruction', 'evidence_sources': ['pdf_coordinate']},
|
||||
{'candidate_kind': 'table_reconstruction', 'evidence_sources': ['ocr_coordinate']},
|
||||
]},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
payload = _input()
|
||||
summary = {**payload['suggestion_summary'], 'automark_job_id': job.id, 'document_id': sample.document_id, 'table_id': sample.table_id, 'page_no': 1, 'evidence_source_required': False, 'selected_evidence_source': None}
|
||||
payload = {**payload, **suggestion_service.suggestion_identity(summary), 'suggestion_summary': summary}
|
||||
with pytest.raises(Exception) as caught:
|
||||
suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-decision')
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
selected = {**summary, 'selected_evidence_source': 'opencv_geometry'}
|
||||
invalid_payload = {**payload, **suggestion_service.suggestion_identity(selected), 'suggestion_summary': selected}
|
||||
with pytest.raises(Exception) as invalid:
|
||||
suggestion_service.decide(draft['id'], data=invalid_payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-invalid-source')
|
||||
assert getattr(invalid.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
sample.layout_payload_checksum = 'f' * 64
|
||||
db.session.commit()
|
||||
valid_source = {**summary, 'selected_evidence_source': 'pdf_coordinate'}
|
||||
stale_payload = {**payload, **suggestion_service.suggestion_identity(valid_source), 'suggestion_summary': valid_source}
|
||||
with pytest.raises(Exception) as stale:
|
||||
suggestion_service.decide(draft['id'], data=stale_payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-stale-layout')
|
||||
assert getattr(stale.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
# 恢复样本冻结身份后,模拟文档重解析完成而样本尚未重新冻结。
|
||||
sample.layout_payload_checksum = job.payload_json['layout_payload_checksum']
|
||||
document = db.session.get(ShippingOrderDocument, sample.document_id)
|
||||
document.current_layout_version.payload_checksum = 'e' * 64
|
||||
db.session.commit()
|
||||
with pytest.raises(Exception) as stale_current_checksum:
|
||||
suggestion_service.decide(draft['id'], data=stale_payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-stale-current-checksum')
|
||||
assert getattr(stale_current_checksum.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
# 恢复当前 Layout checksum 后,继续验证完整重解析导致的版本号失效。
|
||||
document.current_layout_version.payload_checksum = job.payload_json['layout_payload_checksum']
|
||||
db.session.commit()
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'status': 'ready',
|
||||
'pages': [{'page_no': 1}],
|
||||
'tables': [{
|
||||
'table_id': sample.table_id,
|
||||
'page_no': 1,
|
||||
'rows': [{'cells': [{'text': 'reparsed'}]}],
|
||||
'html': '<table><tr><td>reparsed</td></tr></table>',
|
||||
}],
|
||||
})
|
||||
db.session.commit()
|
||||
assert document.current_layout_version_id != sample.layout_version_id
|
||||
with pytest.raises(Exception) as stale_current_layout:
|
||||
suggestion_service.decide(draft['id'], data=stale_payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-stale-current-layout')
|
||||
assert getattr(stale_current_layout.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_suggestion_decision_requires_frozen_field_conflict_source_selection(app):
|
||||
"""关键断言:字段多证据冲突不能靠浏览器省略或伪造来源后直接接受。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-field-conflict-create')
|
||||
sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-field-conflict-tab', operation_id='suggestion-field-conflict-lease')
|
||||
job = Job(
|
||||
domain='shipping_notice', job_type='shipping_pdf_automark', status='success',
|
||||
payload_json={
|
||||
'profile_id': draft['id'], 'document_id': sample.document_id, 'table_id': sample.table_id, 'page_no': 1,
|
||||
'layout_version_id': sample.layout_version_id, 'layout_payload_checksum': sample.layout_payload_checksum,
|
||||
},
|
||||
result_json={
|
||||
'candidates': [
|
||||
{'candidate_kind': 'field_binding', 'evidence_sources': ['pdf_coordinate'], 'binding': {'field_id': 'f-po'}},
|
||||
{'candidate_kind': 'field_binding', 'evidence_sources': ['ocr_coordinate'], 'binding': {'field_id': 'f-po'}},
|
||||
],
|
||||
'diagnostics': {'field_conflicts': [{
|
||||
'code': 'field_binding_source_conflict', 'field_id': 'f-po',
|
||||
'sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
}]},
|
||||
},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
base = {**_input()['suggestion_summary'], 'automark_job_id': job.id, 'document_id': sample.document_id, 'table_id': sample.table_id, 'page_no': 1}
|
||||
missing = {**_input(), **suggestion_service.suggestion_identity(base), 'suggestion_summary': base}
|
||||
with pytest.raises(Exception) as caught:
|
||||
suggestion_service.decide(draft['id'], data=missing, actor_id=None, browser_session_id='suggestion-field-conflict-tab', lease_token=lease['lease_token'], operation_id='suggestion-field-conflict-missing')
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
forged_summary = {**base, 'selected_field_evidence_sources': {'f-po': 'opencv_geometry'}}
|
||||
forged = {**_input(), **suggestion_service.suggestion_identity(forged_summary), 'suggestion_summary': forged_summary}
|
||||
with pytest.raises(Exception) as invalid:
|
||||
suggestion_service.decide(draft['id'], data=forged, actor_id=None, browser_session_id='suggestion-field-conflict-tab', lease_token=lease['lease_token'], operation_id='suggestion-field-conflict-invalid')
|
||||
assert getattr(invalid.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_verify_automark_evidence_rejects_job_when_current_layout_checksum_changed(monkeypatch):
|
||||
"""关键断言:当前 Layout 版本相同但内容已变化时,旧自动标记建议必须失效。"""
|
||||
job = SimpleNamespace(
|
||||
job_type='shipping_pdf_automark', status='success',
|
||||
payload_json={
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
|
||||
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
|
||||
},
|
||||
result_json={'candidates': []},
|
||||
)
|
||||
document = SimpleNamespace(
|
||||
current_layout_version_id=88,
|
||||
current_layout_version=SimpleNamespace(payload_checksum='b' * 64),
|
||||
)
|
||||
annotation = SimpleNamespace(layout_version_id=88, layout_payload_checksum='a' * 64)
|
||||
monkeypatch.setattr(
|
||||
suggestion_service.db.session,
|
||||
'get',
|
||||
lambda model, _ident: job if model is Job else document,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
suggestion_service, 'ShippingOrderDocumentProfileSample',
|
||||
SimpleNamespace(id=SimpleNamespace(asc=lambda: None), query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(first=lambda: annotation),
|
||||
),
|
||||
)),
|
||||
)
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
suggestion_service._verify_automark_evidence_source(
|
||||
profile_id=12,
|
||||
summary={'automark_job_id': 9001, 'document_id': 77, 'table_id': 'table-1'},
|
||||
selected_evidence_source=None,
|
||||
)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
@@ -8,6 +8,8 @@ tests/test_order_document_profile_validation_service.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
@@ -68,6 +70,21 @@ def test_current_sample_rejects_blind_test_binding(app):
|
||||
assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
|
||||
|
||||
def test_frozen_sample_layout_survives_source_document_retention_cleanup(monkeypatch):
|
||||
"""反向匹配只需冻结 Layout 时,原文档清理不能使发布模板失去可验证性。"""
|
||||
sample = SimpleNamespace(document_id=991, layout_version_id=771)
|
||||
frozen_layout = {'status': 'ready', 'tables': [], 'coordinate_evidence': {'pages': {}}}
|
||||
|
||||
def _get(model, identity):
|
||||
if model.__name__ == 'ShippingDocumentLayoutVersion' and identity == 771:
|
||||
return SimpleNamespace(payload_json=frozen_layout)
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(validation_service.db.session, 'get', _get)
|
||||
|
||||
assert validation_service._load_sample_layout(sample) == frozen_layout
|
||||
|
||||
|
||||
def test_failed_current_sample_run_remains_queryable(app):
|
||||
"""关键断言:运行时样本证据不可用也必须保存 failed 摘要,方便后续审计而非吞掉失败。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
tests/test_order_document_profile_validation_service_xfa_phase4.py
|
||||
|
||||
用途:阶段 4 XFA current_sample / xfa_structure_signature / stale 门禁 focused 验收。
|
||||
用途:阶段 4 XFA current_sample / 共同 layout_signature / stale 门禁 focused 验收。
|
||||
依赖:validation_service、creation_service、xfa helpers、pytest app fixture。
|
||||
逻辑:合成 XFA PDF → 向导草稿 → 保存映射 → 验证运行与结构签名;definition 变更后旧签名 stale。
|
||||
逻辑:合成 XFA PDF → 向导草稿 → 保存映射 → 共同验证运行与 layout signature;definition 变更后旧签名 stale。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,6 +15,7 @@ import pytest
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderDocumentProfileValidationRun,
|
||||
ShippingOrderSchema,
|
||||
@@ -68,10 +69,20 @@ def _schema_with_auto_create() -> ShippingOrderSchemaVersion:
|
||||
def _create_mapped_draft(*, user: User, schema: ShippingOrderSchemaVersion) -> tuple[dict, dict[str, str], str]:
|
||||
"""创建已映射 Header/Line 的 XFA 草稿并返回 lease token。"""
|
||||
document, paths, _ = _seed_xfa_sample(user=user)
|
||||
current_layout = dict(document.current_layout_version.payload_json)
|
||||
current_layout['tables'] = [{
|
||||
'table_id': 'visual-main-table',
|
||||
'page_no': 1,
|
||||
'html': '<table><tr><th>Material</th><th>Quantity</th></tr></table>',
|
||||
}]
|
||||
document.current_layout_version.payload_json = current_layout
|
||||
db.session.flush()
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'XFA Phase4 Draft',
|
||||
'schema_version_id': schema.id,
|
||||
'document_id': document.id,
|
||||
# 统一生命周期先冻结视觉主表;datasets 仅作为 bindings 的最终值源。
|
||||
'main_table_id': 'visual-main-table',
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
|
||||
'browser_session_id': 'xfa-p4-tab',
|
||||
@@ -79,26 +90,47 @@ def _create_mapped_draft(*, user: User, schema: ShippingOrderSchemaVersion) -> t
|
||||
}, actor_id=user.id)
|
||||
lease = created['edit_lease']
|
||||
definition = dict(created['definition'])
|
||||
definition['header_mappings'] = [{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': paths['EBELN'],
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
}]
|
||||
definition['line_mapping'] = {
|
||||
'row_path': '/data/ITEMS/DATA',
|
||||
'fields': [
|
||||
{
|
||||
'mapping_id': 'm-mat', 'field_id': 'f-mat', 'field_code': 'material_no',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR', 'path_id': paths['MATNR'],
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-qty', 'field_id': 'f-qty', 'field_code': 'quantity',
|
||||
'data_path': '/data/ITEMS/DATA/MENGE', 'path_id': _path_id_for('/data/ITEMS/DATA/MENGE'),
|
||||
'value_type': 'decimal', 'normalizer_key': 'trim',
|
||||
},
|
||||
definition['header_mappings'] = []
|
||||
definition['line_mapping'] = {'row_path': '/data/ITEMS/DATA', 'fields': []}
|
||||
definition['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': 'header_customer_po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'fallback_value_region': {'x0': 0.10, 'y0': 0.10, 'x1': 0.35, 'y1': 0.16},
|
||||
},
|
||||
]
|
||||
definition['table_regions'][0]['line_layouts'] = [{
|
||||
'layout_id': 'main_line', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0.05, 'y0': 0.35, 'x1': 0.60, 'y1': 0.50},
|
||||
'field_regions': [
|
||||
{'field_id': 'f-mat', 'field_code': 'material_no', 'scope': 'line',
|
||||
'region': {'x0': 0.10, 'y0': 0.35, 'x1': 0.35, 'y1': 0.42},
|
||||
'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'f-qty', 'field_code': 'quantity', 'scope': 'line',
|
||||
'region': {'x0': 0.40, 'y0': 0.35, 'x1': 0.55, 'y1': 0.42},
|
||||
'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
}
|
||||
'new_line_anchor': None, 'continuation_conditions': [],
|
||||
'required_fields': [], 'allowed_empty_fields': [],
|
||||
}]
|
||||
definition['table_regions'][0]['line_start_field_code'] = 'material_no'
|
||||
definition['bindings'] = [
|
||||
{
|
||||
'binding_id': 'bind-po-001', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'scope': 'header', 'field_layout_id': 'header_customer_po',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': paths['EBELN'], 'data_path': '/data/HEADER/EBELN'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-mat-001', 'field_id': 'f-mat', 'field_code': 'material_no',
|
||||
'scope': 'line', 'field_layout_id': 'main_line:material_no',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': paths['MATNR'], 'data_path': '/data/ITEMS/DATA/MATNR'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-qty-001', 'field_id': 'f-qty', 'field_code': 'quantity',
|
||||
'scope': 'line', 'field_layout_id': 'main_line:quantity',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': paths['MENGE'], 'data_path': '/data/ITEMS/DATA/MENGE'},
|
||||
},
|
||||
]
|
||||
definition['cross_checks'] = {
|
||||
'acroform_enabled': False,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -125,14 +157,65 @@ def test_current_sample_summary_still_supports_coordinate_schema_gate():
|
||||
status, summary, _ = validation_service._current_sample_summary(
|
||||
line_field_count=2, line_value_count=2, header_field_count=1, header_value_count=1,
|
||||
header_required_missing_count=0, auto_create_key_missing_count=1,
|
||||
sample_role='annotation', template_mode='xfa_dataset',
|
||||
sample_role='annotation', value_adapter='xfa_dataset',
|
||||
)
|
||||
assert status == 'failed'
|
||||
assert summary['failure_code'] == 'order_profile_current_sample_auto_create_key_missing'
|
||||
|
||||
|
||||
def test_xfa_current_sample_and_structure_signature_pass(app, _patch_xfa_io):
|
||||
"""关键断言:XFA current_sample 与 xfa_structure_signature 可通过并写入匹配引用。"""
|
||||
def test_instant_check_delegates_to_the_profile_value_adapter():
|
||||
"""关键断言:公共验证编排只调用 adapter 协议,不维护 datasets 分发表。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
|
||||
assert callable(get_value_adapter('coordinate').instant_summary)
|
||||
assert callable(get_value_adapter('xfa_dataset').instant_summary)
|
||||
|
||||
|
||||
def test_coordinate_validation_evidence_uses_the_same_field_and_line_shape_as_xfa():
|
||||
"""关键断言:坐标试读也输出 validation_evidence,页面无需按模板模式另取结果。"""
|
||||
evidence = validation_service._build_coordinate_validation_evidence(
|
||||
rows=[['MAT-1', '2']],
|
||||
field_codes=['material_no', 'quantity'],
|
||||
header_fields=[{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'value': 'PO-1', 'status': 'confirmed',
|
||||
}],
|
||||
)
|
||||
|
||||
assert evidence == {
|
||||
'header_fields': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'raw_value': 'PO-1',
|
||||
'normalized_value': 'PO-1', 'status': 'passed', 'issues': [],
|
||||
}],
|
||||
'lines': [{'row_index': 0, 'fields': [
|
||||
{'field_id': '', 'field_code': 'material_no', 'raw_value': 'MAT-1', 'normalized_value': 'MAT-1', 'status': 'passed', 'issues': []},
|
||||
{'field_id': '', 'field_code': 'quantity', 'raw_value': '2', 'normalized_value': '2', 'status': 'passed', 'issues': []},
|
||||
]}],
|
||||
'cross_checks': {},
|
||||
}
|
||||
|
||||
|
||||
def test_xfa_match_summary_keeps_the_shared_visual_match_contract(app, _patch_xfa_io):
|
||||
"""关键断言:XFA 摘要保留共同 matcher 字段,datasets 身份只能作为附加证据。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-summary', email='xfa-p4-summary@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = _schema_with_auto_create()
|
||||
draft, _paths, _lease_token = _create_mapped_draft(user=user, schema=schema)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
|
||||
summary = dict(profile.match_strategy_summary_json or {})
|
||||
|
||||
assert summary['template_mode'] == 'xfa_dataset'
|
||||
assert summary['main_table_id'] == 'visual-main-table'
|
||||
assert 'required_anchor_count' in summary
|
||||
assert 'table_region_count' in summary
|
||||
assert 'order_field_layout_count' in summary
|
||||
assert summary['value_adapter_evidence']['template_packet_checksum']
|
||||
assert summary['value_adapter_evidence']['dataset_structure_fingerprint']
|
||||
|
||||
|
||||
def test_xfa_current_sample_and_shared_layout_signature_pass(app, _patch_xfa_io):
|
||||
"""关键断言:XFA current_sample 与共同 layout_signature 可通过并写入匹配引用。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-val', email='xfa-p4-val@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
@@ -148,49 +231,99 @@ def test_xfa_current_sample_and_structure_signature_pass(app, _patch_xfa_io):
|
||||
lease_token=lease_token, operation_id='xfa-p4-instant',
|
||||
)
|
||||
assert instant['status'] == 'passed'
|
||||
assert instant['summary']['template_mode'] == 'xfa_dataset'
|
||||
assert instant['summary']['value_adapter'] == 'xfa_dataset'
|
||||
|
||||
current = validation_service.run_current_sample(
|
||||
draft['id'], data={'sample_binding_id': sample.id}, actor_id=user.id,
|
||||
browser_session_id='xfa-p4-tab', lease_token=lease_token, operation_id='xfa-p4-current',
|
||||
)
|
||||
assert current['status'] == 'passed'
|
||||
assert current['summary']['template_mode'] == 'xfa_dataset'
|
||||
assert current['summary']['value_adapter'] == 'xfa_dataset'
|
||||
assert current['summary']['validation_evidence']['header_fields']
|
||||
assert current['summary']['validation_evidence']['lines']
|
||||
assert int(current['summary'].get('header_required_missing_count') or 0) == 0
|
||||
assert int(current['summary'].get('auto_create_key_missing_count') or 0) == 0
|
||||
|
||||
signature = validation_service.run_xfa_structure_signature(
|
||||
signature = validation_service.run_profile_identity_signature(
|
||||
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease_token, operation_id='xfa-p4-sig',
|
||||
)
|
||||
assert signature['status'] == 'passed'
|
||||
assert signature['run_type'] == 'xfa_structure_signature'
|
||||
assert signature['run_type'] == 'layout_signature'
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
|
||||
assert profile.matching_signature_run_id == signature['id']
|
||||
assert profile.matching_signature_checksum
|
||||
assert profile.matching_signature_version.startswith('xfa-structure-signature')
|
||||
# Profile identity is the shared visual layout contract. The XFA
|
||||
# datasets fingerprint remains adapter evidence, never the matcher key.
|
||||
assert profile.matching_signature_version == 'order-profile-layout-signature'
|
||||
signature_run = db.session.get(
|
||||
ShippingOrderDocumentProfileValidationRun, signature['id'],
|
||||
)
|
||||
assert signature_run is not None
|
||||
signature_snapshot = signature_run.result_snapshot_json
|
||||
assert signature_snapshot['signature']['table_patterns']
|
||||
assert signature_snapshot['value_adapter_evidence']['adapter'] == 'xfa_dataset'
|
||||
|
||||
|
||||
def test_xfa_structure_signature_becomes_stale_after_definition_change(app, _patch_xfa_io):
|
||||
"""关键断言:definition checksum 变化后旧 xfa_structure_signature 查询态为 stale。"""
|
||||
def test_profile_identity_signature_resolves_xfa_adapter_run(app, _patch_xfa_io):
|
||||
"""关键断言:发布层只调用统一身份签名入口,XFA adapter 保留不可变审计 run_type。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-identity', email='xfa-p4-identity@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = _schema_with_auto_create()
|
||||
draft, _paths, lease_token = _create_mapped_draft(user=user, schema=schema)
|
||||
validation_service.run_profile_identity_signature(
|
||||
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease_token, operation_id='xfa-p4-identity-signature',
|
||||
)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile.id,
|
||||
).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first()
|
||||
assert revision is not None
|
||||
resolved = validation_service.resolve_profile_identity_signature(profile, revision)
|
||||
assert resolved.run_type == 'layout_signature'
|
||||
assert resolved.id == profile.matching_signature_run_id
|
||||
|
||||
|
||||
def test_public_identity_signature_entry_owns_xfa_run_lifecycle(app, _patch_xfa_io, monkeypatch):
|
||||
"""统一入口自己创建 Run;旧 XFA 入口不能再成为业务生命周期分支。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-public', email='xfa-p4-public@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = _schema_with_auto_create()
|
||||
draft, _paths, lease_token = _create_mapped_draft(user=user, schema=schema)
|
||||
|
||||
signature = validation_service.run_profile_identity_signature(
|
||||
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease_token, operation_id='xfa-p4-public-identity',
|
||||
)
|
||||
|
||||
assert signature['stored_status'] == 'passed'
|
||||
assert signature['run_type'] == 'layout_signature'
|
||||
|
||||
|
||||
def test_xfa_layout_signature_becomes_stale_after_definition_change(app, _patch_xfa_io):
|
||||
"""关键断言:definition checksum 变化后共同 layout_signature 查询态为 stale。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-stale', email='xfa-p4-stale@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = _schema_with_auto_create()
|
||||
draft, paths, lease_token = _create_mapped_draft(user=user, schema=schema)
|
||||
signature = validation_service.run_xfa_structure_signature(
|
||||
signature = validation_service.run_profile_identity_signature(
|
||||
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease_token, operation_id='xfa-p4-sig-stale',
|
||||
)
|
||||
stored = db.session.get(ShippingOrderDocumentProfileValidationRun, signature['id'])
|
||||
frozen = stored.definition_checksum
|
||||
definition = dict(draft['definition'])
|
||||
definition['header_mappings'] = [{
|
||||
'mapping_id': 'm-po2', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': paths['EBELN'],
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
}]
|
||||
definition['bindings'][0] = {
|
||||
**definition['bindings'][0],
|
||||
'binding_id': 'bind-po-002',
|
||||
}
|
||||
# 重新获取租约(保存后可能仍有效)
|
||||
lease = lease_service.acquire_lease(
|
||||
draft['id'], actor_id=user.id, browser_session_id='xfa-p4-tab', operation_id='xfa-p4-release',
|
||||
|
||||
@@ -8,12 +8,10 @@ tests/test_order_document_profile_version_service_xfa_phase4.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_document_profile_preview_service import (
|
||||
build_xfa_readonly_mapping_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.order_document_profile_version_service import (
|
||||
_definition_scale_summary,
|
||||
_xfa_structure_identity_summary,
|
||||
_value_source_identity_summary,
|
||||
)
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
|
||||
@@ -33,11 +31,11 @@ def test_xfa_definition_scale_and_identity_summary():
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': [{'mapping_id': 'm2'}]},
|
||||
}
|
||||
stats = _definition_scale_summary(definition)
|
||||
assert stats['template_mode'] == 'xfa_dataset'
|
||||
assert stats['value_adapter'] == 'xfa_dataset'
|
||||
assert stats['header_mapping_count'] == 1
|
||||
assert stats['line_mapping_count'] == 1
|
||||
assert stats['table_region_count'] == 0
|
||||
identity = _xfa_structure_identity_summary(definition)
|
||||
identity = _value_source_identity_summary(definition)
|
||||
assert identity['template_packet_checksum'] == 'sha256:tpl'
|
||||
assert identity['dataset_structure_fingerprint'] == 'sha256:fp'
|
||||
assert 'blind' not in str(identity).lower()
|
||||
@@ -79,9 +77,9 @@ def test_xfa_readonly_mapping_evidence_allows_pdf_preview():
|
||||
},
|
||||
},
|
||||
)
|
||||
evidence = build_xfa_readonly_mapping_evidence(profile)
|
||||
evidence = get_value_adapter('xfa_dataset').readonly_mapping_evidence(profile)
|
||||
assert evidence['pdf_preview_available'] is True
|
||||
assert evidence['template_mode'] == 'xfa_dataset'
|
||||
assert evidence['value_adapter'] == 'xfa_dataset'
|
||||
assert 'expected_rows' not in evidence
|
||||
assert 'expected_order_fields' not in evidence
|
||||
assert evidence['header_mappings'][0]['field_code'] == 'customer_po_no'
|
||||
@@ -99,6 +99,47 @@ def test_persist_prefers_formal_draft_line_key_over_matcher_temporary_key(app):
|
||||
assert added[0].shortage_qty == '16'
|
||||
|
||||
|
||||
def test_persist_derives_line_file_number_from_snapshot_when_matcher_omits_it(app):
|
||||
"""行级匹配结果漏带文件号时,持久化必须从已绑定快照补齐下载证据。"""
|
||||
from app.services.shipping_notice import line_inventory_match_persistence as svc
|
||||
|
||||
task = SimpleNamespace(id=1, inventory_snapshot_id=7)
|
||||
added = []
|
||||
snapshot = SimpleNamespace(inventory_file_no='SIF-SNAPSHOT-7')
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(svc, 'resolve_review_case_for_task', return_value=None),
|
||||
patch.object(svc, 'get_active_candidate_set', return_value=None),
|
||||
patch.object(svc, 'get_active_candidate_lines', return_value=[]),
|
||||
patch.object(svc, 'ShippingInventoryFile') as file_model,
|
||||
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
patch.object(svc.db.session, 'flush'),
|
||||
):
|
||||
file_model.query.get.return_value = snapshot
|
||||
match_q.filter_by.return_value.first.return_value = None
|
||||
match_q.filter_by.return_value.update.return_value = None
|
||||
svc.persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
inventory_snapshot_id=7,
|
||||
match_payload={
|
||||
'line_results': [{
|
||||
'line_index': 0,
|
||||
'disposition': 'shortage',
|
||||
'part_number': 'PN1',
|
||||
'reservation_id': 'R1',
|
||||
'required_qty': 2,
|
||||
'available_qty': 1,
|
||||
'shortage_qty': 1,
|
||||
}],
|
||||
'resolutions': [],
|
||||
},
|
||||
)
|
||||
|
||||
assert added[0].matched_file_no == 'SIF-SNAPSHOT-7'
|
||||
|
||||
|
||||
def test_unit_participates_in_match_key():
|
||||
"""BE-6:同料号预约单但单位不同不得命中。"""
|
||||
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
|
||||
|
||||
@@ -45,8 +45,8 @@ def _preview_intake(intake_no: str, attachments: list[dict], *, subject: str = '
|
||||
)
|
||||
|
||||
|
||||
def test_attachment_selection_snapshot_prefers_po_hints_and_skips_risky_duplicates():
|
||||
"""首轮仅选 2 个高相关附件;后续候选进入未来批次,风险附件和重复哈希必须稳定跳过。"""
|
||||
def test_attachment_selection_snapshot_materializes_all_budgeted_attachments_before_execution():
|
||||
"""预算内业务附件均在首轮物化;执行并发 2 不得把第三份附件推入扩批。"""
|
||||
snapshot = build_attachment_selection_snapshot(intakes=[
|
||||
_preview_intake(
|
||||
'SNI-A',
|
||||
@@ -121,19 +121,24 @@ def test_attachment_selection_snapshot_prefers_po_hints_and_skips_risky_duplicat
|
||||
# 内嵌签名资源不属于业务附件,不计入选择计划数量。
|
||||
assert snapshot['total_attachment_count'] == 5
|
||||
assert snapshot['eligible_attachment_count'] == 3
|
||||
assert snapshot['selected_attachment_count'] == 2
|
||||
assert snapshot['selected_attachment_count'] == 3
|
||||
assert snapshot['planned_attachment_count'] == 3
|
||||
assert snapshot['pending_expansion_attachment_count'] == 1
|
||||
assert snapshot['pending_expansion_batches'] == {'2': 1}
|
||||
assert snapshot['pending_expansion_attachment_count'] == 0
|
||||
assert snapshot['pending_expansion_batches'] == {}
|
||||
selected = [item for item in snapshot['items'] if item['selected']]
|
||||
assert [item['filename'] for item in selected] == ['PO_451883815A.pdf', 'booking_451883816.xlsx']
|
||||
assert [item['filename'] for item in selected] == [
|
||||
'PO_451883815A.pdf',
|
||||
'booking_451883816.xlsx',
|
||||
'order_notes.docx',
|
||||
]
|
||||
|
||||
by_name = {item['filename']: item for item in snapshot['items']}
|
||||
assert by_name['PO_451883815A_copy.pdf']['skip_reason_codes'] == ['duplicate_content_hash']
|
||||
assert 'customer-logo.png' not in by_name
|
||||
assert by_name['orders.zip']['skip_reason_codes'] == ['catalog_reason:archive']
|
||||
assert by_name['order_notes.docx']['skip_reason_codes'] == []
|
||||
assert by_name['order_notes.docx']['planned_selection_batch'] == 2
|
||||
assert by_name['order_notes.docx']['selection_batch'] == 1
|
||||
assert by_name['order_notes.docx']['planned_selection_batch'] is None
|
||||
assert by_name['PO_451883815A.pdf']['group_key'] == '451883815A'
|
||||
|
||||
|
||||
|
||||
@@ -29,6 +29,37 @@ TERMINAL_CASE_STATUSES = frozenset({
|
||||
})
|
||||
|
||||
|
||||
def test_stale_gate_job_stops_at_a_manual_failure_gate(app, monkeypatch):
|
||||
"""超时只记录失败并停在当前 Gate,不能伪装成“自动重试已耗尽”或自动续跑。"""
|
||||
from datetime import datetime, timedelta
|
||||
from app.services.shipping_notice import auto_progress_controller as controller
|
||||
|
||||
now = datetime.utcnow()
|
||||
job = SimpleNamespace(
|
||||
status='running',
|
||||
started_at=now - timedelta(seconds=600),
|
||||
gate_id=9,
|
||||
message=None,
|
||||
error_message=None,
|
||||
finished_at=None,
|
||||
locked_by='worker-1',
|
||||
locked_at=now,
|
||||
updated_at=None,
|
||||
)
|
||||
gate = SimpleNamespace(status='running', blocking_reason_code=None, updated_at=None)
|
||||
monkeypatch.setattr(controller, '_utc_now', lambda: now)
|
||||
monkeypatch.setitem(controller.current_app.config, 'SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 420)
|
||||
monkeypatch.setattr(controller.db.session, 'get', lambda *_args: gate)
|
||||
monkeypatch.setattr(controller.db.session, 'flush', lambda: None)
|
||||
|
||||
assert controller._recover_stale_active_job(job) is True
|
||||
assert job.status == 'failed'
|
||||
assert job.error_message == 'shipping_auto_progress_timeout'
|
||||
assert '允许重新入队' not in job.message
|
||||
assert gate.status == 'blocked_manual'
|
||||
assert gate.blocking_reason_code == 'technical_failure_present'
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# 后端核心合同(9 项)
|
||||
# =========================================================================
|
||||
@@ -175,48 +206,135 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
|
||||
ensure_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(app):
|
||||
"""合同 4:Worker 启动 Sweeper → 扫描漏入队 Case → 协调器补偿建 STP Job。"""
|
||||
def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app):
|
||||
"""合同 4:恢复扫描只收敛超时事实,不能在失败后自动补建 STP Job。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=4, case_no='SORC-P1-04', status='ready', confirmed_task_id=None,
|
||||
document_id=400, updated_at=None,
|
||||
)
|
||||
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch.object(
|
||||
sw, '_scan_stale_inventory_attempts', return_value=0,
|
||||
), patch.object(sw, '_recover_auto_progress_jobs', return_value=0), patch(
|
||||
with patch.object(sw, '_scan_stale_inventory_attempts', return_value=0), patch(
|
||||
'app.services.shipping_notice.shipping_recovery_sweeper_service.db',
|
||||
) as mock_db, patch.object(sw, 'ShippingOrderReviewCase') as ReviewCase, patch(
|
||||
) as mock_db, patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
|
||||
'reconcile_single_case_for_auto_progress',
|
||||
return_value={'case_no': 'SORC-P1-04', 'enqueue_status': 'queued',
|
||||
'job_id': 4404},
|
||||
) as coord_mock:
|
||||
mock_session = MagicMock()
|
||||
loaded = SimpleNamespace(id=4, status='ready', confirmed_task_id=None)
|
||||
mock_session.execute.return_value.scalar.return_value = None
|
||||
mock_session.begin_nested.return_value = MagicMock()
|
||||
type(mock_db).session = mock_session
|
||||
ReviewCase.query.filter_by.return_value.with_for_update.return_value.first.return_value = loaded
|
||||
count = sw.shipping_recovery_tick()
|
||||
|
||||
assert coord_mock.call_count == 1
|
||||
assert count >= 1
|
||||
assert coord_mock.call_count == 0
|
||||
assert count == 0
|
||||
|
||||
|
||||
def test_contract_04a_sweeper_only_commits_attempt_timeout_facts(app):
|
||||
"""恢复扫描没有 Case 自动推进入口,只提交库存 Attempt 的超时收敛结果。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
with patch.object(sw, '_scan_stale_inventory_attempts', return_value=0), patch.object(
|
||||
sw.db.session, 'commit',
|
||||
) as commit_mock:
|
||||
assert sw.shipping_recovery_tick() == 0
|
||||
|
||||
commit_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
|
||||
"""批量协调也不得为人工草稿重复写入 validation 版本。"""
|
||||
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
|
||||
|
||||
run = SimpleNamespace(id=42, run_no='SNER-P1-04B')
|
||||
case = SimpleNamespace(
|
||||
id=42,
|
||||
case_no='SORC-P1-04B',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
document_id=420,
|
||||
candidate_id=42,
|
||||
run_id=42,
|
||||
run=run,
|
||||
owner_user_id=1,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=8,
|
||||
header_values_json={},
|
||||
lines_json=[{'values': {'part_number': {'source': 'manual', 'value': 'P-1'}}}],
|
||||
),
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.ShippingOrderReviewCase',
|
||||
) as review_case, patch.object(
|
||||
coord.db, 'session', MagicMock(),
|
||||
) as session_mock, patch.object(
|
||||
coord, '_customer_step_for_case', return_value=('skipped', None),
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.validate_draft',
|
||||
) as validate_mock, patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
|
||||
return_value={'status': 'waiting_manual_validation'},
|
||||
):
|
||||
review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
|
||||
SimpleNamespace(id=42),
|
||||
]
|
||||
session_mock.get.return_value = case
|
||||
|
||||
result = coord.reconcile_run_review_cases_for_auto_progress(run=run)
|
||||
|
||||
validate_mock.assert_not_called()
|
||||
assert result[0]['validate_status'] == 'waiting_manual_validation'
|
||||
|
||||
|
||||
def test_contract_05_recovery_tick_scans_stale_inventory_attempts(app):
|
||||
"""合同 5:shipping recovery tick 必须调用逐源库存超时扫描。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
with patch.object(sw, '_scan_stale_inventory_attempts', return_value=2) as scan_mock, \
|
||||
patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[]):
|
||||
with patch.object(sw, '_scan_stale_inventory_attempts', return_value=2) as scan_mock:
|
||||
count = sw.shipping_recovery_tick()
|
||||
|
||||
scan_mock.assert_called_once()
|
||||
assert count == 2
|
||||
|
||||
|
||||
def test_contract_05a_sweeper_has_no_stp_candidate_query(app):
|
||||
"""失败链不再由 Sweeper 查询 Case 或补建 STP Job。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
assert not hasattr(sw, '_fetch_sweeper_case_candidates')
|
||||
|
||||
|
||||
def test_contract_05b_stp_schema_failure_stays_at_task_creation(app):
|
||||
"""后续 STP Schema 阻断不应把当前节点投影回客户识别。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=505, case_no='SORC-P1-05B', status='ready', confirmed_task_id=None,
|
||||
document_id=505, run=SimpleNamespace(run_no='SNER-P1-05B'),
|
||||
candidate_id=None, current_draft=SimpleNamespace(draft_version=1),
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.reconciliation_projector.project_case_automation_status',
|
||||
return_value={
|
||||
'status': 'failed', 'retryable': False, 'can_auto_create': True,
|
||||
'can_build': True, 'job_id': 505,
|
||||
'reason_code': 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
'blocking_reason': 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
):
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case, validation={'status': 'ready', 'can_auto_create': True}, post_confirm=None,
|
||||
)
|
||||
|
||||
assert bundle['user_stage'] == 'pre_ot_stp'
|
||||
assert bundle['user_current_gate_code'] == 'task_creation'
|
||||
assert bundle['current_gate']['gate_code'] == 'task_creation'
|
||||
assert bundle['current_gate']['next_action_code'] == 'retry_stp_auto_create'
|
||||
|
||||
|
||||
def test_contract_06_concurrent_sweep_produces_single_active_job_via_idempotency(app):
|
||||
"""合同 5:并发 Sweeper 扫描 + 部分唯一索引约束 → 只产生一个活动 STP Job。"""
|
||||
from app.jobs.queue import enqueue
|
||||
@@ -241,8 +359,6 @@ def test_contract_06_concurrent_sweep_produces_single_active_job_via_idempotency
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.'
|
||||
'_persist_case_candidate_qualification', return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service._is_xfa_case', return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service._draft_has_manual_edits', return_value=False,
|
||||
), patch(
|
||||
@@ -437,7 +553,7 @@ def test_fe_01_stp_enqueue_missing_injects_blocking_reason(app):
|
||||
assert bundle is not None
|
||||
assert bundle['blocking_reason']['code'] == 'stp_enqueue_missing'
|
||||
assert bundle['user_status'] == 'retryable'
|
||||
assert bundle['primary_action']['code'] == 'retry_auto_progress'
|
||||
assert bundle['primary_action']['code'] == 'retry_stp_auto_create'
|
||||
assert bundle['user_stage'] == 'pre_ot_stp'
|
||||
|
||||
|
||||
@@ -466,7 +582,7 @@ def test_fe_02_retryable_shows_single_primary_action_only(app):
|
||||
assert bundle['user_status'] == 'retryable'
|
||||
primary = bundle.get('primary_action') or {}
|
||||
assert isinstance(primary, dict)
|
||||
assert primary.get('code') in {'retry_auto_progress', 'retry_stp_auto_create'}
|
||||
assert primary.get('code') == 'retry_stp_auto_create'
|
||||
# 短路由返回的 bundle 只包含 primary_action,不应出现 reconcile_and_progress
|
||||
assert primary.get('code') != 'reconcile_and_progress'
|
||||
|
||||
@@ -544,4 +660,4 @@ def test_fe_05_no_contradictory_waiting_manual_and_waiting_auto_together(app):
|
||||
# retryable 与 waiting_human 互斥:命中短路 stp_enqueue_missing 时,只能二选一
|
||||
assert status in {'retryable', 'waiting_human', 'running', 'failed', 'completed', 'cancelled'}
|
||||
assert not (status == 'retryable' and bundle.get('blocking_reason', {}).get('code') == 'order_review_required')
|
||||
assert not (status == 'waiting_human' and bundle.get('primary_action', {}).get('code') == 'retry_auto_progress')
|
||||
assert not (status == 'waiting_human' and bundle.get('primary_action', {}).get('code') == 'retry_stp_auto_create')
|
||||
@@ -9,6 +9,8 @@ tests/test_shipping_auto_progress_p0_3.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
Job,
|
||||
@@ -30,7 +32,7 @@ from app.services.shipping_notice.process_gate_service import ensure_execution_f
|
||||
|
||||
def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice:
|
||||
"""创建正式 Task;可选择是否补齐订单解析与冻结快照事实。"""
|
||||
task = ShippingNotice(task_no='APX-P0-3-001', process_status='created')
|
||||
task = ShippingNotice(task_no='APX-P0-3-001')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
@@ -137,6 +139,34 @@ def test_formal_execution_queues_one_gate_attempt_job(app):
|
||||
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 1
|
||||
|
||||
|
||||
def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app):
|
||||
"""人工导航动作不得因 Gate 责任方为 worker 而被自动投递执行。"""
|
||||
task = _task_with_candidate()
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=903, task_id=int(task.id))
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'inventory_rpa_timeout'
|
||||
gate.next_action_code = 'upload_inventory_file'
|
||||
execution.status = 'blocked'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'upload_inventory_file'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
# 同步事实是本用例之外的职责;这里固定复现“同步后仍需人工导航”的当前 Gate。
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
):
|
||||
result = submit_auto_progress(task=task, trigger='callback_recovery')
|
||||
|
||||
assert result['status'] == 'waiting_human'
|
||||
assert result['gate_code'] == 'inventory_preparation'
|
||||
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0
|
||||
|
||||
|
||||
def test_active_stp_job_without_retry_metadata_is_reused(app):
|
||||
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -37,7 +37,6 @@ def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
|
||||
shipping_case_id=case.id,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -79,7 +78,6 @@ def test_revision_inherits_and_force_case_uses_next_sequence(app):
|
||||
supersedes_task_id=task.id,
|
||||
customer_resolution_status="confirmed",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending")
|
||||
db.session.add_all([revision, forced_case])
|
||||
@@ -89,7 +87,6 @@ def test_revision_inherits_and_force_case_uses_next_sequence(app):
|
||||
shipping_case_id=forced_case.id,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(forced_task)
|
||||
db.session.commit()
|
||||
@@ -157,7 +154,6 @@ def test_business_number_query_returns_latest_revision(app):
|
||||
document_version=2,
|
||||
customer_resolution_status="confirmed",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
@@ -6,268 +6,34 @@ backend/tests/test_shipping_chat_action_handlers.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.chat.action_schema import TurnInput
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice.chat_action_handlers import (
|
||||
ShippingCreateBatchFromIntakesAction,
|
||||
ShippingFreezeOrderAction,
|
||||
ShippingGenerateExcelAction,
|
||||
ShippingMarkManualUploadedAction,
|
||||
ShippingRetryUploadAction,
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_CODE,
|
||||
)
|
||||
from app.services.chat.action_registry import ensure_handlers_loaded, list_action_types
|
||||
|
||||
|
||||
def _create_task(user_id: int) -> str:
|
||||
from app.models import ShippingBatch, ShippingNotice
|
||||
def test_legacy_fulfillment_chat_actions_are_not_registered():
|
||||
"""正式 OT 的履约写只能经 Gate API,旧 Chat Turn 不得再有可解析处理器。"""
|
||||
ensure_handlers_loaded()
|
||||
|
||||
batch = ShippingBatch(batch_no="BATCH-HANDLER-001", user_id=user_id, file_count=1)
|
||||
task = ShippingNotice(
|
||||
task_no="SN-20260706-EFGH5678",
|
||||
batch=batch,
|
||||
user_id=user_id,
|
||||
source_type="manual",
|
||||
process_status="matched",
|
||||
match_status="ok",
|
||||
)
|
||||
db.session.add_all([batch, task])
|
||||
db.session.commit()
|
||||
return task.task_no
|
||||
action_types = set(list_action_types())
|
||||
assert {
|
||||
"shipping.freeze_order",
|
||||
"shipping.generate_excel",
|
||||
"shipping.retry_upload",
|
||||
"shipping.match_inventory",
|
||||
"shipping.confirm_inventory_source",
|
||||
"shipping.submit_decision",
|
||||
"shipping.mark_manual_uploaded",
|
||||
}.isdisjoint(action_types)
|
||||
|
||||
|
||||
def test_generate_excel_handler_rejects_chat_turn(app, monkeypatch):
|
||||
"""关键断言:Chat Turn 不得再执行 generate_excel,须改走任务工作台。"""
|
||||
user = User(username="handler_user", email="handler_user@example.com", role="admin", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="货代发货通知 Agent",
|
||||
description="t",
|
||||
dify_api_key="k",
|
||||
api_base_url="http://example.com",
|
||||
agent_code="shipping_notice",
|
||||
runtime_provider="hybrid",
|
||||
conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
def test_legacy_workspace_fulfillment_routes_are_not_registered(app):
|
||||
"""正式 OT 只能通过 Gate API 写入,旧直写与转发路由不得回归。"""
|
||||
routes = {str(rule.rule) for rule in app.url_map.iter_rules()}
|
||||
|
||||
called = {"generate_excel": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.generate_excel",
|
||||
lambda payload: called.update({"generate_excel": True}) or {"status": "ok"},
|
||||
)
|
||||
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-001",
|
||||
run_id="turn-001",
|
||||
session_id="sess-001",
|
||||
request_id="req-001",
|
||||
user=user,
|
||||
agent=agent,
|
||||
input=TurnInput(
|
||||
type="action",
|
||||
display_text="生成发货 Excel",
|
||||
action_type="shipping.generate_excel",
|
||||
payload={"task_no": task_no},
|
||||
),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingGenerateExcelAction().stream(ctx))
|
||||
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["generate_excel"] is False
|
||||
|
||||
|
||||
def test_create_batch_from_intakes_handler_forwards_candidate_nos(app, monkeypatch):
|
||||
"""Chat Turn Candidate 建批必须把选择集合透传后端,且不得引用未定义局部变量。"""
|
||||
user = User(username="candidate_handler", email="candidate-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
agent = Agent(
|
||||
name="货代发货通知 Agent",
|
||||
description="t",
|
||||
dify_api_key="k",
|
||||
api_base_url="http://example.com",
|
||||
agent_code="shipping_notice",
|
||||
runtime_provider="hybrid",
|
||||
conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.commit()
|
||||
captured: dict = {}
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": None,
|
||||
"message": "已打开已有任务,未创建新批次",
|
||||
"opened_existing": [{"candidate_no": "SNC-1", "task_no": "SN-EXISTING"}],
|
||||
"data": {"focus_task": {"task_no": "SN-EXISTING"}},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_intakes",
|
||||
_fake_create,
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-candidate",
|
||||
run_id="turn-candidate",
|
||||
session_id="sess-candidate",
|
||||
request_id="req-candidate",
|
||||
user=user,
|
||||
agent=agent,
|
||||
input=TurnInput(
|
||||
type="action",
|
||||
display_text="确认两个订单",
|
||||
action_type="shipping.create_batch_from_intakes",
|
||||
payload={
|
||||
"intake_nos": ["SNI-1"],
|
||||
"candidate_nos": ["SNC-1", "SNC-2"],
|
||||
"idempotency_key": "idem-candidate-handler",
|
||||
},
|
||||
),
|
||||
refs={},
|
||||
)
|
||||
|
||||
events = list(ShippingCreateBatchFromIntakesAction().stream(ctx))
|
||||
|
||||
assert captured["intake_nos"] == ["SNI-1"]
|
||||
assert captured["candidate_nos"] == ["SNC-1", "SNC-2"]
|
||||
assert captured["conversation_id"] == "sess-candidate"
|
||||
assert any(event.event == "message.completed" for event in events)
|
||||
|
||||
|
||||
def test_freeze_order_handler_requires_the_chat_version_and_emits_snapshot(app):
|
||||
"""关键断言:Chat 冻结传递展示版本,成功后只以 Snapshot 继续履约。"""
|
||||
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
|
||||
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order()
|
||||
task.user_id = user.id
|
||||
agent = Agent(
|
||||
name="冻结订单 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_freeze", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-freeze", run_id="turn-freeze", session_id="sess-freeze", request_id="req-freeze",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(
|
||||
type="action", display_text="冻结订单", action_type="shipping.freeze_order",
|
||||
payload={"task_no": task.task_no, "expected_order_data_version": 7},
|
||||
),
|
||||
refs={"task_no": task.task_no},
|
||||
)
|
||||
|
||||
events = list(ShippingFreezeOrderAction().stream(ctx))
|
||||
|
||||
db.session.refresh(task)
|
||||
assert task.order_snapshot_id is not None
|
||||
assert "ui_state.updated" in [event.event for event in events]
|
||||
assert "message.completed" in [event.event for event in events]
|
||||
|
||||
|
||||
def test_manual_upload_handler_rejects_chat_turn_with_evidence(app, monkeypatch):
|
||||
"""关键断言:即便携带回执证据,Chat 也不得调用 upload_to_freight。"""
|
||||
user = User(username="manual-handler", email="manual-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="手工上传 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_manual", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
called = {"upload": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.upload_to_freight",
|
||||
lambda payload: called.update({"upload": True}) or {"status": "ok", "message": "已登记"},
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-manual", run_id="turn-manual", session_id="sess-manual", request_id="req-manual",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(
|
||||
type="action", display_text="已上传", action_type="shipping.mark_manual_uploaded",
|
||||
payload={"task_no": task_no, "evidence_asset_no": "FA-RECEIPT-001"},
|
||||
),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingMarkManualUploadedAction().stream(ctx))
|
||||
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["upload"] is False
|
||||
|
||||
|
||||
def test_manual_upload_handler_rejects_chat_turn_without_evidence(app):
|
||||
"""关键断言:不能借助 Chat action 绕过人工上传截图/回执门禁。"""
|
||||
user = User(username="manual-handler-no-evidence", email="manual-handler-no-evidence@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="手工上传无证据 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_manual_missing", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-manual-missing", run_id="turn-manual-missing", session_id="sess-manual-missing", request_id="req-manual-missing",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(type="action", display_text="已上传", action_type="shipping.mark_manual_uploaded", payload={"task_no": task_no}),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingMarkManualUploadedAction().stream(ctx))
|
||||
|
||||
assert error.value.code == "SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED"
|
||||
|
||||
|
||||
def test_retry_upload_handler_rejects_chat_turn(app, monkeypatch):
|
||||
"""关键断言:Chat Turn 不得重试货代上传。"""
|
||||
user = User(username="retry-handler", email="retry-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="重试上传 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_retry", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
called = {"upload": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.upload_to_freight",
|
||||
lambda payload: called.update({"upload": True}) or {"status": "ok"},
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-retry", run_id="turn-retry", session_id="sess-retry", request_id="req-retry",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(
|
||||
type="action", display_text="重试上传", action_type="shipping.retry_upload",
|
||||
payload={"task_no": task_no},
|
||||
),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingRetryUploadAction().stream(ctx))
|
||||
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["upload"] is False
|
||||
assert {
|
||||
'/api/workspace/shipping-tasks/<task_no>/confirm-inventory-source',
|
||||
'/api/workspace/shipping-tasks/<task_no>/submit-decision',
|
||||
'/api/workspace/shipping-tasks/<task_no>/freeze-order',
|
||||
'/api/workspace/shipping-tasks/<task_no>/match-inventory',
|
||||
'/api/workspace/shipping-tasks/<task_no>/generate-excel',
|
||||
'/api/workspace/shipping-tasks/<task_no>/retry-upload',
|
||||
}.isdisjoint(routes)
|
||||
@@ -948,7 +948,7 @@ def test_table_region_profile_allows_binding_internal_line_no():
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{
|
||||
'field_id': 'line', 'field_code': 'line_no',
|
||||
'field_id': 'line', 'field_code': 'line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
@@ -957,3 +957,30 @@ def test_table_region_profile_allows_binding_internal_line_no():
|
||||
profile = TableRegionProfile.model_validate(payload)
|
||||
assert profile.line_layouts[0].field_regions[0].field_code == 'line_no'
|
||||
assert profile.line_start_field_code == 'line_no'
|
||||
|
||||
|
||||
def test_table_region_profile_freezes_confirmed_visual_geometry_source_only():
|
||||
"""关键断言:视觉来源随 Layout 版本冻结,但不进入字段 allowed_sources。"""
|
||||
payload = {
|
||||
'region_id': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'line_start_field_code': 'line_no',
|
||||
'visual_evidence_source': 'opencv_geometry',
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{
|
||||
'field_id': 'line', 'field_code': 'line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
profile = TableRegionProfile.model_validate(payload)
|
||||
assert profile.visual_evidence_source == 'opencv_geometry'
|
||||
assert profile.line_layouts[0].field_regions[0].allowed_sources == ['pdf_coordinate']
|
||||
assert TableRegionProfile.model_validate({
|
||||
**payload, 'visual_evidence_source': 'acroform_widget_geometry',
|
||||
}).visual_evidence_source == 'acroform_widget_geometry'
|
||||
with pytest.raises(ValueError, match='visual_evidence_source'):
|
||||
TableRegionProfile.model_validate({**payload, 'visual_evidence_source': 'xfa_dataset'})
|
||||
@@ -127,7 +127,7 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id,
|
||||
user_id=user.id, source_type="email_attachment", process_status="parsed",
|
||||
user_id=user.id, source_type="email_attachment",
|
||||
customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -418,13 +418,13 @@ def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
|
||||
db.session.flush()
|
||||
first = ShippingNotice(
|
||||
task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1,
|
||||
source_type="manual", process_status="parsed", customer_resolution_status="pending",
|
||||
source_type="manual", customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(first)
|
||||
db.session.flush()
|
||||
latest = ShippingNotice(
|
||||
task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2,
|
||||
supersedes_task_id=first.id, source_type="manual", process_status="waiting_upload",
|
||||
supersedes_task_id=first.id, source_type="manual", upload_status="pending",
|
||||
customer_resolution_status="pending", inventory_source_code="DSV",
|
||||
inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}],
|
||||
match_status="fulfillable", line_results_json=[{"sku": "A"}],
|
||||
@@ -457,7 +457,7 @@ def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
|
||||
assert latest.inventory_source_status is None
|
||||
assert latest.inventory_lines_json is None
|
||||
assert latest.export_file_path is None
|
||||
assert latest.process_status == "parsed"
|
||||
assert latest.source_type == "manual"
|
||||
assert get_task_by_ref(old_business_no).id == latest.id
|
||||
assert get_task_by_ref(replacement.business_no).id == latest.id
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
|
||||
@@ -476,7 +476,7 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id,
|
||||
source_type="manual", process_status="parsed", customer_resolution_status="pending",
|
||||
source_type="manual", customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -487,7 +487,7 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
|
||||
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED"
|
||||
db.session.rollback()
|
||||
|
||||
task.process_status = "uploaded"
|
||||
task.upload_status = "uploaded"
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
|
||||
|
||||
@@ -47,7 +47,6 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCusto
|
||||
task_no=f'SN-GATE-{user.id}', user_id=user.id,
|
||||
shipping_case_id=case.id if case else None,
|
||||
customer_resolution_status='pending' if case else None,
|
||||
process_status='parsed',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
|
||||
inventory_source_status='user_confirmed', inventory_source_code='DSV',
|
||||
)
|
||||
@@ -60,7 +59,7 @@ def _assert_customer_gate_response(result: dict) -> None:
|
||||
"""断言 Tool 入口返回统一客户检查点。"""
|
||||
assert result['status'] == 'needs_human'
|
||||
assert result['checkpoint'] == 'customer_review'
|
||||
assert result['human_options'] == ['confirm_customer']
|
||||
assert 'human_options' not in result
|
||||
|
||||
|
||||
def test_pending_customer_blocks_every_downstream_entry(app):
|
||||
@@ -119,7 +118,6 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
|
||||
revision = ShippingNotice(
|
||||
task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id,
|
||||
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
|
||||
process_status='parsed',
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
@@ -185,8 +185,8 @@ def test_layout_job_exhaustion_fails_version_without_leaking_provider_error(app)
|
||||
assert 'shipping_document_layout_job_exhausted' in version.issues_json
|
||||
|
||||
|
||||
def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
"""XFA hybrid 文档不得进入 MinerU/PDFium 表格路径。"""
|
||||
def test_layout_job_xfa_hybrid_keeps_xfa_identity_and_builds_visual_layout(app):
|
||||
"""XFA hybrid 必须保留 datasets 身份,同时进入统一视觉表格/Layout 管线。"""
|
||||
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
|
||||
|
||||
with app.app_context():
|
||||
@@ -197,7 +197,20 @@ def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
return_value=pdf_bytes,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
|
||||
) as mineru_mock:
|
||||
) as visual_layout_mock:
|
||||
visual_layout_mock.return_value = {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru',
|
||||
'status': 'ready',
|
||||
'tables': [{'table_id': 'visual-main', 'page_no': 1}],
|
||||
'capability': {},
|
||||
'layout_candidate': {'schema_version': 'shipping_document_layout.v1'},
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
},
|
||||
'issues': [],
|
||||
}
|
||||
run_shipping_document_layout(
|
||||
JobContext(config=dict(app.config), logger=None, extras={}),
|
||||
{'job_id': job.id},
|
||||
@@ -206,10 +219,10 @@ def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
db.session.refresh(version)
|
||||
db.session.refresh(document)
|
||||
db.session.refresh(job)
|
||||
mineru_mock.assert_not_called()
|
||||
visual_layout_mock.assert_called_once()
|
||||
assert version.status == 'ready'
|
||||
assert version.payload_json.get('provider') == 'xfa'
|
||||
assert version.payload_json.get('tables') == []
|
||||
assert version.payload_json.get('provider') == 'mineru'
|
||||
assert version.payload_json.get('tables') == [{'table_id': 'visual-main', 'page_no': 1}]
|
||||
assert version.payload_json['xfa_capability']['structure_analysis_ready'] is True
|
||||
assert document.current_layout_version_id == version.id
|
||||
assert job.status == 'success'
|
||||
@@ -221,16 +234,22 @@ def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
assert 'counts' not in version.payload_json
|
||||
|
||||
|
||||
def test_runtime_xfa_probe_skips_mineru_for_hybrid(app):
|
||||
"""runtime 在 XFA hybrid 探测成功后不得调用 MinerU。"""
|
||||
def test_runtime_xfa_visual_layout_does_not_create_unfrozen_value_source_capability(app):
|
||||
"""runtime 只提供共享视觉 Layout;正式 Job 才能冻结并附加 datasets capability。"""
|
||||
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
|
||||
|
||||
from tests.test_shipping_document_layout_runtime import _candidate
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL'] = 'http://mineru.test'
|
||||
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient',
|
||||
) as mineru_client:
|
||||
) as mineru_client, patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
|
||||
return_value=_candidate(),
|
||||
):
|
||||
from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot
|
||||
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
@@ -239,7 +258,7 @@ def test_runtime_xfa_probe_skips_mineru_for_hybrid(app):
|
||||
document_id=1,
|
||||
content_hash='a' * 64,
|
||||
)
|
||||
mineru_client.assert_not_called()
|
||||
mineru_client.return_value.parse_file_async.assert_called_once()
|
||||
assert snapshot is not None
|
||||
assert snapshot['provider'] == 'xfa'
|
||||
assert snapshot['tables'] == []
|
||||
assert 'xfa_capability' not in snapshot
|
||||
assert snapshot['provider'] != 'xfa'
|
||||
@@ -93,6 +93,75 @@ def test_layout_snapshot_checksum_and_idempotent_current_version(app):
|
||||
assert current_layout_snapshot(document)['marker'] == 'v1'
|
||||
|
||||
|
||||
def test_inline_derived_xfa_layout_localizes_structure_analysis_identity(app):
|
||||
"""坐标补证派生 Layout 必须克隆 XFA Analysis,样本可安全冻结到新版本。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
analysis = ShippingXfaStructureAnalysis(
|
||||
document_id=document.id,
|
||||
layout_version_id=None,
|
||||
source_content_hash=document.content_hash,
|
||||
document_kind='xfa_hybrid',
|
||||
analysis_status='ready',
|
||||
template_packet_checksum='sha256:template',
|
||||
datasets_packet_checksum='sha256:datasets',
|
||||
dataset_structure_fingerprint='sha256:structure',
|
||||
packet_checksums_json={'datasets': 'sha256:datasets'},
|
||||
stats_json={}, security_summary_json={}, tree_summary_json={},
|
||||
parser_identity='xfa-parser.v1', contract_version='xfa-contract.v1',
|
||||
)
|
||||
db.session.add(analysis)
|
||||
db.session.flush()
|
||||
first = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(marker='xfa-base'),
|
||||
'xfa_capability': {'structure_analysis_id': analysis.id},
|
||||
'capability': {'structure_analysis_id': analysis.id},
|
||||
})
|
||||
assert analysis.layout_version_id == first.id
|
||||
|
||||
derived = record_inline_layout_snapshot(document, {
|
||||
**dict(first.payload_json),
|
||||
'marker': 'xfa-coordinate-evidence',
|
||||
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
|
||||
db.session.commit()
|
||||
|
||||
derived_analysis_id = derived.payload_json['xfa_capability']['structure_analysis_id']
|
||||
derived_analysis = db.session.get(ShippingXfaStructureAnalysis, derived_analysis_id)
|
||||
# 关键断言:新 Layout 与新 Analysis 一一绑定,旧分析仍保留原 Layout 审计身份。
|
||||
assert derived.id != first.id
|
||||
assert derived_analysis_id != analysis.id
|
||||
assert derived_analysis.layout_version_id == derived.id
|
||||
assert analysis.layout_version_id == first.id
|
||||
assert derived.payload_json['capability']['structure_analysis_id'] == derived_analysis.id
|
||||
|
||||
# 修复部署前已落库的派生快照按原 checksum 重放时,同样必须补齐新 identity。
|
||||
stale = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(marker='xfa-pre-fix-stale'),
|
||||
'xfa_capability': {'structure_analysis_id': analysis.id},
|
||||
'capability': {'structure_analysis_id': analysis.id},
|
||||
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
|
||||
stale_payload = {
|
||||
**_snapshot(marker='xfa-pre-fix-stale'),
|
||||
'xfa_capability': {'structure_analysis_id': analysis.id},
|
||||
'capability': {'structure_analysis_id': analysis.id},
|
||||
}
|
||||
stale.payload_json = stale_payload
|
||||
stale.payload_checksum, stale.payload_size_bytes = canonical_layout_payload(stale_payload)
|
||||
db.session.flush()
|
||||
repaired = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(marker='xfa-pre-fix-stale'),
|
||||
'xfa_capability': {'structure_analysis_id': analysis.id},
|
||||
'capability': {'structure_analysis_id': analysis.id},
|
||||
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
|
||||
repaired_analysis = db.session.get(
|
||||
ShippingXfaStructureAnalysis,
|
||||
repaired.payload_json['xfa_capability']['structure_analysis_id'],
|
||||
)
|
||||
assert repaired.id == stale.id
|
||||
assert repaired_analysis.id != analysis.id
|
||||
assert repaired_analysis.layout_version_id == repaired.id
|
||||
|
||||
|
||||
def test_failed_or_oversized_layout_does_not_replace_last_good_version(app):
|
||||
"""失败/超限版本必须可审计,但绝不能覆盖 Document 上一次成功布局。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 500
|
||||
@@ -198,8 +267,8 @@ def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
|
||||
assert scheduled.id != incomplete.id
|
||||
|
||||
|
||||
def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(app, monkeypatch):
|
||||
"""相同 XFA 文件复用时,目标 Document 必须获得独立 Analysis 并重写快照身份。"""
|
||||
def test_shared_visual_layout_reuse_localizes_xfa_structure_analysis(app, monkeypatch):
|
||||
"""共享视觉 Layout 带 datasets capability 时,复用必须本地化其结构分析身份。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
audit_events: list[str] = []
|
||||
|
||||
@@ -232,11 +301,13 @@ def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(ap
|
||||
db.session.flush()
|
||||
source_layout = record_inline_layout_snapshot(original, {
|
||||
'status': 'ready',
|
||||
'provider': 'xfa',
|
||||
'provider_version': 'xfa-parser.v1',
|
||||
'backend': 'pypdf',
|
||||
'provider': 'mineru',
|
||||
'provider_version': 'mineru-v1',
|
||||
'backend': 'pipeline',
|
||||
'snapshot_version': 'shipping_document_layout.v1',
|
||||
'tables': [],
|
||||
# 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁;datasets 仅为末端值源。
|
||||
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': []}},
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': source_analysis.id,
|
||||
@@ -281,8 +352,8 @@ def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(ap
|
||||
assert 'xfa_structure_analysis_reused' in audit_events
|
||||
|
||||
|
||||
def test_xfa_layout_without_source_analysis_is_not_reused(app, monkeypatch):
|
||||
"""XFA 快照声明 ready 但源 Analysis 缺失时必须重新排队,禁止复制伪 ready 状态。"""
|
||||
def test_legacy_xfa_only_layout_without_shared_visual_evidence_is_reparsed(app, monkeypatch):
|
||||
"""旧 XFA-only 快照缺共同视觉证据时一律重解析,不能保留格式专用复用分支。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
audit_events: list[str] = []
|
||||
|
||||
@@ -332,8 +403,7 @@ def test_xfa_layout_without_source_analysis_is_not_reused(app, monkeypatch):
|
||||
assert scheduled.status == 'queued'
|
||||
assert duplicate.current_layout_version_id is None
|
||||
assert ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).count() == 0
|
||||
assert 'xfa_structure_analysis_reuse_rejected' in audit_events
|
||||
assert 'xfa_structure_analysis_reparse_queued' in audit_events
|
||||
assert not audit_events
|
||||
|
||||
|
||||
def test_layout_parser_fingerprint_change_creates_new_version_without_force(app, monkeypatch):
|
||||
|
||||
@@ -368,3 +368,23 @@ def test_runtime_attachment_budget_preserves_order_and_marks_overflow(app):
|
||||
assert rows[0]['layout_snapshot']['marker'] == 'first.pdf'
|
||||
assert rows[1]['layout_snapshot']['marker'] == 'second.pdf'
|
||||
assert rows[2]['layout_snapshot']['status'] == 'skipped_budget'
|
||||
def test_runtime_builds_xfa_visual_layout_without_creating_unfrozen_value_source_capability(app) -> None:
|
||||
"""关键断言:runtime 只构建共享视觉 Layout;datasets 身份只能由正式 Layout Job 冻结。"""
|
||||
candidate = _candidate()
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient',
|
||||
) as mineru, patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
|
||||
return_value=candidate,
|
||||
):
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL'] = 'http://mineru.test'
|
||||
mineru.return_value.parse_file_async.return_value = {'ok': True}
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename='order.pdf', content=b'%PDF-xfa', document_id=9, content_hash='c' * 64,
|
||||
)
|
||||
|
||||
assert snapshot['status'] == 'ready'
|
||||
assert 'xfa_capability' not in snapshot
|
||||
assert snapshot['tables']
|
||||
mineru.return_value.parse_file_async.assert_called_once()
|
||||
@@ -181,6 +181,19 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
|
||||
return profile, user, documents
|
||||
|
||||
|
||||
def _independent_approver() -> User:
|
||||
"""创建与盲测编辑者不同的审批人,验证双人复核门禁。"""
|
||||
suffix = User.query.count() + 1
|
||||
approver = User(
|
||||
username=f'profile-quality-approver-{suffix}',
|
||||
email=f'profile-quality-approver-{suffix}@example.com',
|
||||
role='admin',
|
||||
)
|
||||
db.session.add(approver)
|
||||
db.session.flush()
|
||||
return approver
|
||||
|
||||
|
||||
def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
||||
"""将质量夹具改为最小 v2 草稿,使发布测试只覆盖阶段 4 边界。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
@@ -231,7 +244,10 @@ def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(a
|
||||
)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']
|
||||
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
with pytest.raises(Exception) as self_approval:
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert getattr(self_approval.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
|
||||
approved = quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
||||
assert approved['status'] == 'approved'
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
qualification = quality.qualification_summary(profile)
|
||||
@@ -675,7 +691,7 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
||||
)
|
||||
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
||||
profile.checksum = 'c' * 64
|
||||
db.session.commit()
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
@@ -799,7 +815,7 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap
|
||||
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
||||
)
|
||||
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
||||
immutable_sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
|
||||
with pytest.raises(Exception) as caught:
|
||||
quality.remove_sample(suite_id=suite['id'], sample_id=immutable_sample_id, actor_id=user.id)
|
||||
@@ -920,7 +936,7 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'customer_po_line_no': '00010', 'part_number': 'PN-3', 'qty': '5'}], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
||||
|
||||
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert published['status'] == 'published'
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
@@ -28,10 +29,8 @@ from app.services.shipping_notice import document_profile_quality_service as qua
|
||||
from app.services.shipping_notice.document_profile_quality_service import (
|
||||
MINIMUM_BLIND_SAMPLES,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_DOCUMENT_TABLE_ID,
|
||||
XFA_PARSER_IDENTITY,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_PARSER_IDENTITY
|
||||
from tests.test_shipping_xfa_helpers import FIXTURE_ROOT
|
||||
|
||||
|
||||
@@ -45,7 +44,43 @@ def test_xfa_blind_fixture_requires_independent_identity_and_full_accuracy():
|
||||
assert blind['required_accuracy']['line_count'] == 1.0
|
||||
assert blind['required_accuracy']['quantity_amount_date_normalization'] == 1.0
|
||||
assert MINIMUM_BLIND_SAMPLES >= 1
|
||||
assert XFA_DOCUMENT_TABLE_ID == 'xfa-authoritative-lines'
|
||||
|
||||
|
||||
def test_blind_candidate_comparison_is_shared_by_coordinate_and_xfa_adapters():
|
||||
"""关键断言:两类 adapter 统一按 order_fields 和 rows 与冻结真值比对。"""
|
||||
failures, total, matched = quality._compare_blind_candidate(
|
||||
candidate={
|
||||
'order_fields': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'value': 'PO-1', 'status': 'confirmed',
|
||||
}],
|
||||
'rows': [{'material_no': 'MAT-1', 'quantity': '2'}],
|
||||
},
|
||||
sample=SimpleNamespace(
|
||||
expected_order_fields_json={'header:customer_po_no': 'PO-1'},
|
||||
expected_rows_json=[{'material_no': 'MAT-1', 'quantity': '2'}],
|
||||
),
|
||||
schema_fields={'f-po': {}},
|
||||
)
|
||||
|
||||
assert failures == []
|
||||
assert (total, matched) == (3, 3)
|
||||
|
||||
|
||||
def test_cross_page_blind_gate_uses_shared_visual_table_rule_for_xfa():
|
||||
"""关键断言:XFA datasets 不得绕过共同视觉表区的跨页盲测门禁。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={
|
||||
'template_mode': 'xfa_dataset',
|
||||
'table_regions': [{
|
||||
'region_id': 'lines',
|
||||
'continuation_rule': {'allow_cross_page': True},
|
||||
}],
|
||||
},
|
||||
)
|
||||
|
||||
assert quality._requires_cross_page_sample(profile) is True
|
||||
|
||||
|
||||
def test_serialize_suite_does_not_leak_blind_truths():
|
||||
@@ -59,7 +94,7 @@ def test_serialize_suite_does_not_leak_blind_truths():
|
||||
'samples': [{
|
||||
'id': 3,
|
||||
'document_id': 88,
|
||||
'table_id': XFA_DOCUMENT_TABLE_ID,
|
||||
'table_id': 'visual-main-table',
|
||||
'filename': '',
|
||||
'page_no': 1,
|
||||
}],
|
||||
@@ -121,8 +156,8 @@ def _make_sample_document(*, user: User, suffix: str) -> ShippingOrderDocument:
|
||||
return document
|
||||
|
||||
|
||||
def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app):
|
||||
"""关键断言:XFA 草稿列出文档级结构分析候选,confirmable=True 且不走坐标表。"""
|
||||
def test_xfa_list_independent_samples_returns_confirmable_visual_table_candidate(app):
|
||||
"""关键断言:XFA 盲测冻结视觉主表,datasets 仅保留为末端值源身份。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-quality', email='xfa-p4-quality@example.com', role='admin')
|
||||
schema = ShippingOrderSchema(schema_code='XFA_P4Q', display_name='XFA P4Q')
|
||||
@@ -151,6 +186,7 @@ def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'main_table_id': 'visual-main-table',
|
||||
'cross_checks': {
|
||||
'acroform_enabled': False, 'mirror_collection_policy': 'ignore',
|
||||
'line_amount_formula': 'disabled', 'total_amount_policy': 'disabled',
|
||||
@@ -161,10 +197,23 @@ def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=annotation_doc.id,
|
||||
table_id=XFA_DOCUMENT_TABLE_ID, sample_role='annotation', created_by_id=user.id,
|
||||
table_id='visual-main-table', sample_role='annotation', created_by_id=user.id,
|
||||
))
|
||||
db.session.add(ShippingXfaStructureAnalysis(
|
||||
blind_layout_version = record_inline_layout_snapshot(blind_doc, {
|
||||
'status': 'ready',
|
||||
'tables': [{
|
||||
'table_id': 'visual-main-table', 'page_no': 1,
|
||||
'html': '<table><tr><th>Material</th></tr></table>',
|
||||
}],
|
||||
'coordinate_evidence': {
|
||||
'tables': {'visual-main-table': [{'text': 'Material'}]},
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
},
|
||||
'xfa_capability': {'structure_analysis_ready': True},
|
||||
})
|
||||
blind_analysis = ShippingXfaStructureAnalysis(
|
||||
document_id=blind_doc.id,
|
||||
layout_version_id=blind_layout_version.id,
|
||||
source_content_hash=str(blind_doc.content_hash),
|
||||
document_kind='xfa_hybrid',
|
||||
analysis_status='ready',
|
||||
@@ -177,20 +226,37 @@ def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app
|
||||
tree_summary_json={},
|
||||
parser_identity=XFA_PARSER_IDENTITY,
|
||||
contract_version='xfa-structure-analysis.v1',
|
||||
))
|
||||
)
|
||||
db.session.add(blind_analysis)
|
||||
db.session.flush()
|
||||
blind_layout_version.payload_json = {
|
||||
**blind_layout_version.payload_json,
|
||||
'xfa_capability': {
|
||||
**blind_layout_version.payload_json['xfa_capability'],
|
||||
'structure_analysis_id': blind_analysis.id,
|
||||
},
|
||||
}
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=profile.structure_fingerprint, created_by_id=user.id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:XFA 与普通 PDF 都从共同视觉 Layout 生成盲测候选;
|
||||
# adapter 不再拥有列举、预览身份或样本冻结等生命周期步骤。
|
||||
adapter_samples = quality._common_blind_sample_descriptors(
|
||||
profile=profile, document=blind_doc,
|
||||
)
|
||||
assert adapter_samples[0]['table_id'] == 'visual-main-table'
|
||||
assert adapter_samples[0]['confirmable'] is True
|
||||
|
||||
listed = quality.list_independent_samples(suite_id=suite.id, actor_id=user.id)
|
||||
samples = listed['samples']
|
||||
assert samples, 'XFA blind candidate list must not be empty'
|
||||
assert all(item['table_id'] == XFA_DOCUMENT_TABLE_ID for item in samples)
|
||||
assert all(item['table_id'] == 'visual-main-table' for item in samples)
|
||||
match = next(item for item in samples if int(item['document_id']) == int(blind_doc.id))
|
||||
assert match['confirmable'] is True
|
||||
assert match['review_mode'] == 'formal_review'
|
||||
assert match['layout_version_id']
|
||||
assert match['layout_payload_checksum'] == 'sha256:ds'
|
||||
assert match['layout_payload_checksum'] == blind_layout_version.payload_checksum
|
||||
assert annotation_doc.id not in {int(item['document_id']) for item in samples}
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
tests/test_shipping_eml_preview_service.py
|
||||
|
||||
用途:锁定 EML 安全预览清洗与快照复用契约。
|
||||
依赖:eml_preview_service。
|
||||
逻辑:预览仅保留安全正文布局;图片、脚本和外部资源不得进入浏览器。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.eml_preview_service import (
|
||||
EML_PREVIEW_MAX_BYTES,
|
||||
consume_eml_preview_grant,
|
||||
issue_eml_preview_grant,
|
||||
sanitize_eml_preview_html,
|
||||
highlight_eml_preview_html,
|
||||
)
|
||||
from app.services.shipping_notice.eml_parse import extract_eml_preview_html
|
||||
|
||||
|
||||
def test_sanitize_eml_preview_keeps_table_and_safe_inline_style():
|
||||
"""安全预览保留表格和有限样式,但剥离主动内容及图片。"""
|
||||
html = '<div style="color:red;position:fixed" onclick="bad()"><table><tr><td>PO</td></tr></table><img src="cid:logo"><a href="https://x">link</a><script>bad()</script></div>'
|
||||
|
||||
preview = sanitize_eml_preview_html(html)
|
||||
|
||||
# 关键断言:视觉结构可读,执行、追踪和定位样式均不可进入预览。
|
||||
assert '<table>' in preview
|
||||
assert 'color: red' in preview
|
||||
assert 'position' not in preview
|
||||
assert 'onclick' not in preview
|
||||
assert '<img' not in preview
|
||||
assert 'href' not in preview
|
||||
assert '<script' not in preview
|
||||
|
||||
|
||||
def test_sanitize_eml_preview_keeps_safe_background_shorthand_for_light_text():
|
||||
"""Outlook 表头常以 background 简写搭配白字;清洗后必须同时保留,避免文字不可见。"""
|
||||
html = '<table><tr><td style="background:#ED7D31;color:white">PO</td></tr></table>'
|
||||
|
||||
preview = sanitize_eml_preview_html(html)
|
||||
|
||||
# 关键断言:纯色背景可保留,url 等外部背景资源仍由样式解析器拒绝。
|
||||
assert 'background: #ED7D31' in preview
|
||||
assert 'color: white' in preview
|
||||
|
||||
|
||||
def test_eml_preview_html_size_limit_is_finite():
|
||||
"""安全预览快照必须有固定尺寸上限,超限邮件回退文本而非撑大工作台。"""
|
||||
assert EML_PREVIEW_MAX_BYTES == 500_000
|
||||
|
||||
|
||||
def test_extract_eml_preview_html_preserves_the_raw_html_table_and_head_style():
|
||||
"""视觉预览必须读取原始 HTML MIME,而不是复用已扁平化的文本抽取路径。"""
|
||||
eml = b"""MIME-Version: 1.0\r
|
||||
Content-Type: multipart/alternative; boundary=preview\r
|
||||
\r
|
||||
--preview\r
|
||||
Content-Type: text/plain; charset=utf-8\r
|
||||
\r
|
||||
PO\tQty\r
|
||||
--preview\r
|
||||
Content-Type: text/html; charset=utf-8\r
|
||||
\r
|
||||
<html><head><style>.order { border-collapse: collapse; } .order td { border: 1px solid #000; width: 120px; }</style></head><body><table class=\"order\"><tr><td>PO</td><td>Qty</td></tr></table><img src=\"cid:logo\"><script>alert(1)</script></body></html>\r
|
||||
--preview--\r
|
||||
"""
|
||||
|
||||
preview = extract_eml_preview_html(eml)
|
||||
|
||||
# 关键断言:保留供浏览器排版的 table/head/style/class,主动内容和 CID 图片必须剥离。
|
||||
assert '<table class="order">' in preview
|
||||
assert 'border-collapse' in preview
|
||||
assert '<head>' in preview
|
||||
assert '<img' not in preview
|
||||
assert '<script' not in preview
|
||||
|
||||
|
||||
def test_eml_preview_grant_is_single_use_and_bound_to_the_case(monkeypatch):
|
||||
"""iframe 无法带 Bearer Header 时,预览 URL 必须使用短时且不可重放的 Case 绑定令牌。"""
|
||||
class Store:
|
||||
def __init__(self):
|
||||
self.items = {}
|
||||
|
||||
def setex(self, key, _ttl, value):
|
||||
self.items[key] = value
|
||||
|
||||
def getdel(self, key):
|
||||
return self.items.pop(key, None)
|
||||
|
||||
monkeypatch.setattr('app.services.shipping_notice.eml_preview_service._eml_preview_grant_store', lambda: Store())
|
||||
# 同一个 Store 必须跨签发/消费调用复用。
|
||||
store = Store()
|
||||
monkeypatch.setattr('app.services.shipping_notice.eml_preview_service._eml_preview_grant_store', lambda: store)
|
||||
|
||||
token = issue_eml_preview_grant(user_id=7, case_no='CASE-1', document_id=9, html='<table><tr><td>PO</td></tr></table>')
|
||||
|
||||
assert consume_eml_preview_grant(token=token, user_id=7, case_no='CASE-1') == '<table><tr><td>PO</td></tr></table>'
|
||||
assert consume_eml_preview_grant(token=token, user_id=7, case_no='CASE-1') == ''
|
||||
|
||||
|
||||
def test_highlight_eml_preview_html_marks_one_unique_evidence_quote_only():
|
||||
"""字段证据只在安全 HTML 中唯一命中引文时加标记,避免全文值猜测。"""
|
||||
html = '<html><body><p>PO: 33894</p><p>Qty: 10</p></body></html>'
|
||||
|
||||
highlighted = highlight_eml_preview_html(html, '33894')
|
||||
|
||||
assert highlighted.count('<mark') == 1
|
||||
assert '33894' in highlighted
|
||||
assert highlight_eml_preview_html(html, 'missing') == html
|
||||
@@ -110,7 +110,7 @@ def test_inventory_preparation_reason_code_from_pending():
|
||||
assert inventory_preparation_reason_code(missing) == 'inventory_file_missing'
|
||||
|
||||
upload_failed = SimpleNamespace(
|
||||
id=None, pending_human_reason='upload_rpa_failed', process_status='upload_failed',
|
||||
id=None, pending_human_reason='upload_rpa_failed',
|
||||
)
|
||||
assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed'
|
||||
|
||||
@@ -155,7 +155,7 @@ def test_build_explainability_reason_unknown_requires_request_id():
|
||||
|
||||
def test_technical_failure_alias_and_gate_request_id_fallback():
|
||||
"""
|
||||
technical_failure 须归一为 technical_retry_exhausted;Gate 投影无 HTTP 上下文时回退 execution_no。
|
||||
技术失败须归一为中性失败码;Gate 投影无 HTTP 上下文时回退 execution_no。
|
||||
|
||||
核心逻辑:别名对齐契约;_resolve_explainability_request_id 保证未知失败可追溯。
|
||||
"""
|
||||
@@ -166,8 +166,9 @@ def test_technical_failure_alias_and_gate_request_id_fallback():
|
||||
)
|
||||
|
||||
# [STEP 1] 历史写入码归一到契约稳定码
|
||||
assert canonicalize_reason_code('technical_failure') == 'technical_retry_exhausted'
|
||||
assert message_zh_for_reason('technical_retry_exhausted')
|
||||
assert canonicalize_reason_code('technical_failure') == 'technical_failure_present'
|
||||
assert canonicalize_reason_code('technical_retry_exhausted') == 'technical_failure_present'
|
||||
assert message_zh_for_reason('technical_failure_present')
|
||||
|
||||
# [STEP 2] Worker 无 HTTP request_id 时不得用 execution_no 冒充
|
||||
execution = SimpleNamespace(execution_no='PEX-TEST-001')
|
||||
@@ -194,7 +195,7 @@ def test_technical_failure_alias_and_gate_request_id_fallback():
|
||||
# [STEP 4] 抽取失败/取消别名不得再降级为 unknown
|
||||
assert canonicalize_reason_code('SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED') == 'order_extraction_failed'
|
||||
assert canonicalize_reason_code('SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED') == 'order_extraction_cancelled'
|
||||
assert message_zh_for_reason('technical_retry_exhausted')
|
||||
assert message_zh_for_reason('technical_failure_present')
|
||||
failed = build_explainability_reason(reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED')
|
||||
assert failed['reason_code'] == 'order_extraction_failed'
|
||||
assert failed['next_action'] == 'retry_order_extraction'
|
||||
@@ -202,6 +203,7 @@ def test_technical_failure_alias_and_gate_request_id_fallback():
|
||||
assert cancelled['reason_code'] == 'order_extraction_cancelled'
|
||||
assert cancelled['next_action'] == 'open_order_review'
|
||||
retry_meta = build_explainability_reason(reason_code='technical_retry_exhausted')
|
||||
assert retry_meta['reason_code'] == 'technical_failure_present'
|
||||
assert retry_meta['next_action'] == 'open_order_review'
|
||||
|
||||
|
||||
@@ -327,6 +329,9 @@ def test_audit_reason_code_mapping_for_rpa_and_notice_replace():
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'login timeout'},
|
||||
) == 'inventory_rpa_timeout'
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'Crane scheduled report not ready for download within 300000ms'},
|
||||
) == 'inventory_rpa_timeout'
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'auth rejected'},
|
||||
) == 'inventory_rpa_login_failed'
|
||||
|
||||
@@ -23,7 +23,14 @@ from app.models import (
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice.export import _excel_business_no, _filename, _mapping_value, _system_fact, generate_shipment_excel
|
||||
from app.services.shipping_notice.export import (
|
||||
_excel_business_no,
|
||||
_filename,
|
||||
_mapping_value,
|
||||
_system_fact,
|
||||
_template_requires_system_warehouse_id,
|
||||
generate_shipment_excel,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_lines_for_task,
|
||||
@@ -47,6 +54,28 @@ def _inventory_field_id(field_code: str) -> str:
|
||||
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
|
||||
|
||||
|
||||
def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fact():
|
||||
"""模板将库位作为 inventory_field 消费时,不得被任务级 Warehouse ID 门禁误拦。"""
|
||||
assert _template_requires_system_warehouse_id([
|
||||
{
|
||||
'sheet': 'PVMI Pull Request Header',
|
||||
'row_mode': 'header',
|
||||
'target_column': 1,
|
||||
'source_kind': 'inventory_field',
|
||||
'source_key': '7',
|
||||
},
|
||||
]) is False
|
||||
assert _template_requires_system_warehouse_id([
|
||||
{
|
||||
'sheet': 'Header',
|
||||
'row_mode': 'header',
|
||||
'target_column': 2,
|
||||
'source_kind': 'system_fact',
|
||||
'source_key': 'warehouse_id',
|
||||
},
|
||||
]) is True
|
||||
|
||||
|
||||
def _freeze_export_snapshot(
|
||||
task: ShippingNotice, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
|
||||
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
|
||||
@@ -259,8 +288,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
'filename_pattern': 'shipment_{task_no}_{date}.xlsx',
|
||||
'mappings': [
|
||||
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'order_field', 'source_key': customer.id, 'formatter': 'upper'},
|
||||
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 2, 'source_kind': 'system_fact', 'source_key': 'warehouse_id', 'formatter': 'text'},
|
||||
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 3, 'source_kind': 'system_fact', 'source_key': 'export_date', 'formatter': 'date_mmddyyyy'},
|
||||
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 2, 'source_kind': 'system_fact', 'source_key': 'export_date', 'formatter': 'date_mmddyyyy'},
|
||||
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 1, 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text'},
|
||||
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 2, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
|
||||
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 3, 'source_kind': 'order_field', 'source_key': po_number.id, 'formatter': 'text'},
|
||||
@@ -307,7 +335,8 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
])
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB',
|
||||
inventory_warehouse_id='DUB', inventory_lines_json=[{
|
||||
# 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。
|
||||
inventory_warehouse_id=None, inventory_lines_json=[{
|
||||
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
|
||||
}], inventory_snapshot_id=None,
|
||||
)
|
||||
@@ -324,8 +353,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
|
||||
wb = load_workbook(path, read_only=True)
|
||||
assert wb['Header'].cell(2, 1).value == 'ACME' # Header 动态字段及 formatter 生效。
|
||||
assert wb['Header'].cell(2, 2).value == 'DUB' # 受控系统事实写入目标列。
|
||||
assert wb['Header'].cell(2, 3).value == _system_fact(task, 'export_date').strftime('%m/%d/%Y')
|
||||
assert wb['Header'].cell(2, 2).value == _system_fact(task, 'export_date').strftime('%m/%d/%Y')
|
||||
assert wb['Detail'].cell(3, 1).value == 'PN-1' # Line 字段按订单行写入。
|
||||
assert wb['Detail'].cell(3, 2).value == 'ODM-9' # 标准库存字段无需 LLM 判断。
|
||||
assert wb['Detail'].cell(3, 3).value == '16754796' # Header 字段按业务要求重复到每条明细。
|
||||
@@ -336,9 +364,8 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
assert artifact.inventory_parsing_profile_id == parsing.id
|
||||
assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0
|
||||
|
||||
# Dynamic inventory sources must resolve Warehouse before any export can be created.
|
||||
task.inventory_warehouse_id = None
|
||||
with pytest.raises(ValueError, match='缺少已解析的 Warehouse ID'):
|
||||
# 已存在待上传 Artifact 时仍保持原有幂等保护,和 Warehouse ID 无关。
|
||||
with pytest.raises(ValueError, match='当前任务存在待上传的发货 Excel'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
|
||||
@@ -89,18 +89,17 @@ def test_all_execution_statuses_have_user_mapping():
|
||||
|
||||
def test_blocking_reason_classification_coverage():
|
||||
"""
|
||||
除豁免 1 个(technical_retry_exhausted)外,108 个阻断原因码必须一一分类。
|
||||
每个阻断原因码必须一一分类。
|
||||
|
||||
断言意图:禁止新增 reason_code 而漏掉用户处置模式,否则前端无法决定按钮渲染。
|
||||
"""
|
||||
total = len(PROCESS_GATE_BLOCKING_REASON_CODES)
|
||||
classified = set(BLOCKING_REASON_TO_USER_MODE.keys())
|
||||
exempt = {'technical_retry_exhausted'}
|
||||
missing = PROCESS_GATE_BLOCKING_REASON_CODES - classified - exempt
|
||||
missing = PROCESS_GATE_BLOCKING_REASON_CODES - classified
|
||||
assert not missing, f'unclassified blocking reasons: {sorted(missing)}'
|
||||
# 规模冻结:当前全集(含豁免)共 108+1=109;此断言随新增原因码需显式更新
|
||||
# 规模冻结:新增原因码时需同步补充用户处置模式。
|
||||
assert total >= 100, f'expected >= 100 blocking codes, got {total}'
|
||||
assert len(classified) + len(exempt) >= total
|
||||
assert len(classified) >= total
|
||||
|
||||
|
||||
def test_user_mode_values_are_allowed():
|
||||
|
||||
@@ -43,3 +43,23 @@ def test_build_field_observation_prefers_bbox_text_quote():
|
||||
assert observation['quote'] == 'EA'
|
||||
assert observation['layout_evidence']['bbox_text'] == 'EA'
|
||||
assert observation['layout_evidence']['quote_source'] == 'bbox_tokens'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('source', 'expected'), [
|
||||
('native_glyph', 'native_pdf'),
|
||||
('ocr', 'ocr'),
|
||||
('acroform_widget', 'acroform_widget'),
|
||||
])
|
||||
def test_build_field_observation_exposes_runtime_value_source(source: str, expected: str):
|
||||
"""关键断言:通用 PDF 证据必须把原生/OCR/Widget 的来源带到 observation 顶层。"""
|
||||
observation = build_field_observation(
|
||||
field={
|
||||
'value': '4500001234',
|
||||
'source': source,
|
||||
'page_no': 1,
|
||||
'table_id': 'header',
|
||||
'cell_id': 'po',
|
||||
},
|
||||
document_id=9,
|
||||
)
|
||||
assert observation['value_source'] == expected
|
||||
@@ -243,8 +243,8 @@ def test_should_attempt_generic_extraction_allows_no_match_for_coordinate_path()
|
||||
) is False
|
||||
|
||||
|
||||
def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monkeypatch):
|
||||
"""关键断言:XFA capability 文档正式提取失败后不回退 generic/coordinate。"""
|
||||
def test_route_deterministic_unit_unmatched_xfa_uses_generic_evidence_only_for_review(monkeypatch):
|
||||
"""关键断言:未命中 XFA Profile 只走共同视觉 Review,不能伪装成 datasets 正式值。"""
|
||||
document = {
|
||||
'document_id': 90,
|
||||
'layout_snapshot': {
|
||||
@@ -276,10 +276,6 @@ def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monke
|
||||
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
|
||||
lambda *_args, **_kwargs: ({'intake_no': 'SNI-XFA'}, document),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow.xfa_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._load_unit_pdf_bytes',
|
||||
lambda *_args, **_kwargs: None,
|
||||
@@ -301,7 +297,7 @@ def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monke
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
|
||||
'app.services.shipping_notice.order_extraction_workflow._extract_generic_evidence_result',
|
||||
_fake_generic,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -315,15 +311,11 @@ def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monke
|
||||
lambda: True,
|
||||
)
|
||||
route = route_deterministic_unit(run, unit=unit)
|
||||
assert generic_called['value'] is False
|
||||
assert generic_called['value'] is True
|
||||
assert route.execution_mode == 'review_required'
|
||||
assert route.decision.get('capability_kind') == 'xfa_dataset'
|
||||
assert route.decision.get('capability_kind') != 'xfa_fallback_coordinate'
|
||||
assert 'xfa_dataset_missing' in (
|
||||
route.decision.get('fallback_reason_codes')
|
||||
or route.decision.get('reason_codes')
|
||||
or []
|
||||
)
|
||||
assert route.decision.get('route_decision') == 'needs_review'
|
||||
assert route.decision.get('capability_kind') == 'coordinate'
|
||||
assert route.decision.get('capability_kind') != 'xfa_dataset'
|
||||
|
||||
|
||||
def test_should_attempt_generic_extraction_allows_no_special_profile_feature():
|
||||
@@ -682,7 +674,7 @@ def test_route_deterministic_unit_layout_drift_does_not_fallback_to_generic(monk
|
||||
lambda *_args, **_kwargs: ({'intake_no': 'SNI-001'}, {'document_id': 1, 'layout_schema_candidates': []}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
|
||||
'app.services.shipping_notice.order_extraction_workflow._extract_generic_evidence_result',
|
||||
lambda **_kwargs: (_ for _ in ()).throw(AssertionError('layout_drift must not enter generic')),
|
||||
)
|
||||
|
||||
|
||||
@@ -42,9 +42,11 @@ def test_manual_upload_records_receipt_asset(app):
|
||||
)
|
||||
attempt = record_manual_upload(
|
||||
task, artifact_id=artifact.id, evidence_asset_no=payload['asset_no'], operator_id=user.id,
|
||||
freight_ref_no='FREIGHT-RECEIPT-1',
|
||||
)
|
||||
assert attempt.mode == 'manual'
|
||||
assert attempt.status == 'succeeded'
|
||||
assert attempt.evidence_asset_id is not None
|
||||
assert attempt.freight_ref_no == 'FREIGHT-RECEIPT-1'
|
||||
assert db.session.get(type(reservation), reservation.id).status == 'uploaded'
|
||||
assert ShippingUploadAttempt.query.count() == 1
|
||||
@@ -22,7 +22,6 @@ def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int |
|
||||
shipping_case_id=case_id,
|
||||
supersedes_task_id=supersedes_task_id,
|
||||
source_type='manual',
|
||||
process_status='created',
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -189,7 +189,6 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
|
||||
task_no='SN-PENDING-1',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
@@ -225,7 +224,6 @@ def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
|
||||
intake.duplicate_matches_json = [
|
||||
{
|
||||
'task_no': 'SN-OLD',
|
||||
'process_status': 'waiting_inventory',
|
||||
'document_version': 1,
|
||||
'match_type': 'weak_fingerprint',
|
||||
'matched_fields': ['line_digest'],
|
||||
@@ -256,7 +254,6 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
|
||||
task_no='SN-EXISTING-PO-A',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-other-file',
|
||||
@@ -379,7 +376,6 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
|
||||
task_no='SN-REFRESH-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-refresh-other',
|
||||
@@ -487,7 +483,6 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
|
||||
task_no='SN-CONTENT-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=identity['fingerprint'],
|
||||
fingerprint_version=identity['version'],
|
||||
content_fingerprint=content['fingerprint'],
|
||||
|
||||
@@ -1493,6 +1493,102 @@ def test_normalize_notice_line_aliases():
|
||||
}
|
||||
|
||||
|
||||
def test_normalize_notice_line_uses_frozen_schema_aliases_for_inventory_source_hint():
|
||||
"""邮件列名只有在本次冻结 Schema 配置后才可映射库存源线索,禁止代码内置业务别名。"""
|
||||
schema_definition = {
|
||||
'fields': [
|
||||
{
|
||||
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '内部料号', 'aliases': ['Custom MPN'],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '数量', 'aliases': ['Custom Qty'],
|
||||
},
|
||||
{
|
||||
'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '库存源线索', 'aliases': ['VMI HUB'],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
line = normalize_notice_line(
|
||||
{'Custom MPN': 'A-001', 'Custom Qty': '3', 'VMI HUB': 'CMH01'},
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
|
||||
assert line == {
|
||||
'part_number': 'A-001',
|
||||
'qty': 3.0,
|
||||
'inventory_source_hint': 'CMH01',
|
||||
}
|
||||
|
||||
|
||||
def test_normalize_notice_line_uses_schema_alias_for_line_remark():
|
||||
"""行备注只能通过冻结 Schema 的正式字段和别名进入订单行。"""
|
||||
schema_definition = {
|
||||
'fields': [
|
||||
{
|
||||
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '内部料号', 'aliases': ['Custom MPN'],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '数量', 'aliases': ['Custom Qty'],
|
||||
},
|
||||
{
|
||||
'field_id': 'remark', 'field_code': 'line_remark', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '行备注', 'aliases': ['Customer Note'],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
line = normalize_notice_line(
|
||||
{'Custom MPN': 'A-001', 'Custom Qty': '3', 'Customer Note': 'Ship together'},
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
|
||||
assert line == {
|
||||
'part_number': 'A-001',
|
||||
'qty': 3.0,
|
||||
'line_remark': 'Ship together',
|
||||
}
|
||||
|
||||
|
||||
def test_parse_notice_table_keeps_configured_line_remark():
|
||||
"""表格中的行备注仅在冻结 Schema 声明其别名后进入解析结果。"""
|
||||
schema_definition = _table_schema_definition()
|
||||
schema_definition['fields'].append({
|
||||
'field_id': 'line-remark', 'field_code': 'line_remark', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'display_name': '行备注',
|
||||
'aliases': ['Customer Note'], 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
})
|
||||
|
||||
lines = parse_notice_table_rows(
|
||||
['MPN', 'Allocated QTY', 'Customer Note'],
|
||||
[['D4-A08AR12000002', 10, 'Ship together']],
|
||||
contract=compile_table_header_contract(schema_definition),
|
||||
)
|
||||
|
||||
assert lines == [{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'qty': 10.0,
|
||||
'line_remark': 'Ship together',
|
||||
}]
|
||||
|
||||
|
||||
def test_schema_disables_free_text_field_guessing_after_table_parse_miss():
|
||||
"""存在冻结 Schema 时,表格未命中不得用固定 SKU x Qty 正则生成订单行。"""
|
||||
parsed, confidence, warnings = extract_notice_fields(
|
||||
raw_text='D4-A08AR12000002 x 10',
|
||||
schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
assert parsed['lines'] == []
|
||||
assert confidence == 0.0
|
||||
assert 'schema_table_no_lines' in warnings
|
||||
|
||||
|
||||
def test_normalize_notice_line_splits_frozen_temp_composite():
|
||||
"""TEMP 二段复合文本应拆为客户料号和内部料号,禁止把组合值持久化。"""
|
||||
line = normalize_notice_line({
|
||||
|
||||
@@ -149,7 +149,6 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
task_no='SN-CANDIDATE-EXISTING-001',
|
||||
user_id=owner.id,
|
||||
source_content_hash=asset.content_hash,
|
||||
process_status='created',
|
||||
)
|
||||
db.session.add_all([document, existing])
|
||||
db.session.flush()
|
||||
@@ -224,7 +223,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
with app.app_context():
|
||||
db.session.add(ShippingNotice(
|
||||
task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id,
|
||||
source_content_hash='candidate-api-content-hash', process_status='created',
|
||||
source_content_hash='candidate-api-content-hash',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -582,7 +581,7 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
|
||||
task_no='SN-REV-LOCK-BASE',
|
||||
user_id=shipping_user.id,
|
||||
source_type='manual',
|
||||
process_status='uploaded',
|
||||
upload_status='uploaded',
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(base)
|
||||
@@ -591,7 +590,6 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
|
||||
task_no='SN-REV-LOCK-V2',
|
||||
user_id=shipping_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
document_version=2,
|
||||
supersedes_task_id=base.id,
|
||||
duplicate_resolution_type='revision',
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -452,6 +452,103 @@ def test_recompute_supersedes_referenced_stale_candidate_without_deleting_histor
|
||||
assert order_task.candidate_id == stale_candidate.id
|
||||
|
||||
|
||||
def test_document_reparse_does_not_expire_sibling_document_candidate(app):
|
||||
"""单附件增量重解析只收口目标 Document,不能撤销同一 Intake 的兄弟候选。"""
|
||||
with app.app_context():
|
||||
_user, session, intake, document, _runtime = _seed_extraction_input()
|
||||
sibling = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
asset_id=int(document.asset_id),
|
||||
document_type='attachment',
|
||||
attachment_key='sibling.pdf',
|
||||
filename='sibling.pdf',
|
||||
content_hash='order-extraction-sibling-document-hash',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 4510000002 SKU SKU-B QTY 20',
|
||||
)
|
||||
db.session.add(sibling)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
agent = Agent.query.filter_by(agent_code='shipping_notice').one()
|
||||
first_run = ShippingOrderProcessingRun(
|
||||
run_no='SNER-SIBLING-REPARSE-1',
|
||||
user_id=int(session.user_id),
|
||||
owner_agent_id=int(agent.id),
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=int(schema.id),
|
||||
input_snapshot_hash='sibling-reparse-1',
|
||||
input_snapshot_json={},
|
||||
idempotency_key='sibling-reparse-1',
|
||||
)
|
||||
db.session.add(first_run)
|
||||
db.session.flush()
|
||||
|
||||
first = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510000001',
|
||||
part_number='SKU-A',
|
||||
qty=10,
|
||||
include_process_fields=False,
|
||||
)
|
||||
persist_order_extraction_result(
|
||||
session=session,
|
||||
intakes=[intake],
|
||||
documents=[document],
|
||||
current_snapshot='sibling-reparse-1',
|
||||
request_id='sibling-reparse-1',
|
||||
orders=[first],
|
||||
run_id=int(first_run.id),
|
||||
schema_version_id=int(schema.id),
|
||||
extraction_source='test_workflow',
|
||||
auto_create_enabled=True,
|
||||
)
|
||||
sibling_order = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(sibling.id),
|
||||
po_number='4510000002',
|
||||
part_number='SKU-B',
|
||||
qty=20,
|
||||
include_process_fields=False,
|
||||
)
|
||||
sibling_reparse_run = ShippingOrderProcessingRun(
|
||||
run_no='SNER-SIBLING-REPARSE-2',
|
||||
user_id=int(session.user_id),
|
||||
owner_agent_id=int(agent.id),
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=int(schema.id),
|
||||
input_snapshot_hash='sibling-reparse-2',
|
||||
input_snapshot_json={'review_reparse': {'document_id': int(sibling.id)}},
|
||||
idempotency_key='sibling-reparse-2',
|
||||
reparse_of_run_id=int(first_run.id),
|
||||
)
|
||||
db.session.add(sibling_reparse_run)
|
||||
db.session.flush()
|
||||
persist_order_extraction_result(
|
||||
session=session,
|
||||
intakes=[intake],
|
||||
documents=[sibling],
|
||||
current_snapshot='sibling-reparse-2',
|
||||
request_id='sibling-reparse-2',
|
||||
orders=[sibling_order],
|
||||
run_id=int(sibling_reparse_run.id),
|
||||
schema_version_id=int(schema.id),
|
||||
extraction_source='test_workflow',
|
||||
auto_create_enabled=True,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
first_candidate = ShippingOrderCandidate.query.filter_by(
|
||||
intake_id=int(intake.id), primary_document_id=int(document.id),
|
||||
).one()
|
||||
sibling_candidate = ShippingOrderCandidate.query.filter_by(
|
||||
intake_id=int(intake.id), primary_document_id=int(sibling.id),
|
||||
).one()
|
||||
assert first_candidate.is_current_version is True
|
||||
assert sibling_candidate.is_current_version is True
|
||||
|
||||
|
||||
def test_plain_text_table_issue_reaches_candidate_as_machine_readable_conflict(app):
|
||||
"""无 cell 证据的纯文本表格必须在 Candidate 保留原因码,供现有任务 UI 解释。"""
|
||||
with app.app_context():
|
||||
@@ -630,7 +727,7 @@ def test_order_field_display_uses_current_catalog_sequence(app):
|
||||
).all():
|
||||
field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
|
||||
task = ShippingNotice(
|
||||
task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual',
|
||||
task_no='SN-ORDER-DISPLAY-SEQUENCE', source_type='manual',
|
||||
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}],
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -908,7 +1005,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
|
||||
task_no='SN-ORDER-EXISTING-001',
|
||||
user_id=int(user.id),
|
||||
source_type='manual',
|
||||
process_status='waiting_inventory',
|
||||
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
@@ -926,7 +1023,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
|
||||
'content_fingerprint_version': 'shipping-content-v4',
|
||||
'matches': [{
|
||||
'task_no': existing.task_no,
|
||||
'process_status': existing.process_status,
|
||||
'match_status': existing.match_status,
|
||||
'match_type': 'business_fingerprint',
|
||||
}],
|
||||
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
|
||||
@@ -1046,7 +1143,6 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
error_message='解析失败:未识别到 Reservation ID',
|
||||
@@ -1099,7 +1195,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
assert values['part_number'] == 'P123456'
|
||||
assert values['qty'] == 24
|
||||
assert values['reservation_id'] == '1000140351'
|
||||
assert existing.process_status == 'pending_review'
|
||||
assert existing.review_status == 'rsv_req'
|
||||
assert existing.pending_human_reason == 'low_confidence'
|
||||
assert 'process_field_gate' not in (existing.step_payload_json or {})
|
||||
assert existing.error_message is None
|
||||
@@ -1198,7 +1294,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
|
||||
@pytest.mark.parametrize(
|
||||
'task_overrides',
|
||||
[
|
||||
{'process_status': 'waiting_inventory'},
|
||||
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]},
|
||||
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]},
|
||||
{'match_status': 'matched'},
|
||||
{'export_file_path': '/tmp/shipment.xlsx'},
|
||||
@@ -1211,7 +1307,6 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
|
||||
'task_no': f"SN-RSV-BACKFILL-NEG-{next(iter(task_overrides))}",
|
||||
'po_number': '4510038672',
|
||||
'source_type': 'manual',
|
||||
'process_status': 'pending_review',
|
||||
'review_status': 'rsv_req',
|
||||
'pending_human_reason': 'rsv_req',
|
||||
'lines_json': [{'part_number': 'P123456', 'qty': 24}],
|
||||
@@ -1256,7 +1351,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
task_no='SN-RSV-BACKFILL-CONFLICT',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
|
||||
@@ -1265,7 +1359,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[
|
||||
@@ -1277,7 +1370,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
@@ -1327,7 +1419,6 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
|
||||
task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
|
||||
@@ -1369,7 +1460,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
process_status='waiting_inventory',
|
||||
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.add(existing)
|
||||
@@ -1400,7 +1491,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
|
||||
assert result['pending_count'] == 0
|
||||
assert candidate.consumed_task_id == int(existing.id)
|
||||
assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}]
|
||||
assert existing.process_status == 'waiting_inventory'
|
||||
assert existing.inventory_lines_json == [{'part_number': 'P123456', 'qty': 24}]
|
||||
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
|
||||
|
||||
|
||||
@@ -1444,7 +1535,6 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
|
||||
@@ -24,12 +24,37 @@ from app.services.shipping_notice.query_service import (
|
||||
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
|
||||
|
||||
|
||||
def test_chat_match_result_payload_uses_unified_actions_only():
|
||||
"""Chat 匹配结果不得再把旧 action_buttons 作为按钮来源。"""
|
||||
from app.services.shipping_notice.chat_action_handlers import _match_result_payload
|
||||
|
||||
payload = _match_result_payload(
|
||||
"SN-ACTIONS-ONLY",
|
||||
{
|
||||
"data": {
|
||||
"match_status": "shortage",
|
||||
"line_results": [],
|
||||
"shortage": {"lines": []},
|
||||
},
|
||||
"action_buttons": [{"id": "legacy_retry"}],
|
||||
"ui_state": {
|
||||
"actions": {
|
||||
"primary": {"code": "open_shortage_review", "enabled": True},
|
||||
"secondary": [],
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert payload["actions"]["primary"]["code"] == "open_shortage_review"
|
||||
assert "action_buttons" not in payload
|
||||
|
||||
|
||||
def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
|
||||
"""task_no 与数字主键均应能解析到同一任务。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-TEST-QUERY-001",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
)
|
||||
from app import db
|
||||
@@ -47,28 +72,28 @@ def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
|
||||
|
||||
|
||||
def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
|
||||
"""库存缺口筛选应读取复核状态,而不是要求不存在的 process_status。"""
|
||||
"""库存缺口筛选应读取领域事实和复核状态。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
shortage = ShippingNotice(
|
||||
task_no="SN-FILTER-SHORTAGE",
|
||||
process_status="pending_review",
|
||||
review_status="shortage_review",
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
user_id=999999,
|
||||
)
|
||||
ordinary = ShippingNotice(
|
||||
task_no="SN-FILTER-PARSE",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=2,
|
||||
)
|
||||
db.session.add_all([shortage, ordinary])
|
||||
db.session.commit()
|
||||
|
||||
rows = list_tasks_for_user(999999, process_status="shortage_review")
|
||||
rows = list_tasks_for_user(999999)
|
||||
|
||||
assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"]
|
||||
|
||||
@@ -79,7 +104,7 @@ def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", process_status="created", source_type="manual")
|
||||
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", source_type="manual")
|
||||
for index in range(1, 6)
|
||||
])
|
||||
db.session.commit()
|
||||
@@ -105,13 +130,13 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-1", process_status="created", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-2", process_status="created", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-3", process_status="uploaded", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-3", upload_status="uploaded", source_type="manual"),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
result = list_tasks_page_for_user(999999, process_status="created", page=1, page_size=10)
|
||||
result = list_tasks_page_for_user(999999, lifecycle_status="active", page=1, page_size=10)
|
||||
|
||||
# 关键断言:uploaded 任务既不在 items 中,也不计入总数。
|
||||
assert result["total"] == 2
|
||||
@@ -123,12 +148,11 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
|
||||
def test_task_export_error_message_distinct_for_missing_path(app):
|
||||
"""无导出路径与磁盘缺失应返回不同错误文案。"""
|
||||
with app.app_context():
|
||||
empty = ShippingNotice(task_no="SN-NO-EXPORT", process_status="created", source_type="manual")
|
||||
empty = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual")
|
||||
assert task_export_error_message(empty) == "export file not found"
|
||||
|
||||
missing = ShippingNotice(
|
||||
task_no="SN-MISSING-FILE",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/not-a-real-shipping-export.xlsx",
|
||||
)
|
||||
@@ -140,7 +164,6 @@ def test_task_projection_tool_strips_internal_fields(app):
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-PROJ-TOOL",
|
||||
process_status="waiting_inventory",
|
||||
review_status="align_review",
|
||||
match_status="pending",
|
||||
pending_human_reason="rpa_pending",
|
||||
@@ -161,12 +184,11 @@ def test_task_projection_internal_keeps_status_fields(app):
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-PROJ-INT",
|
||||
process_status="parsed",
|
||||
review_status="parse_review",
|
||||
source_type="manual",
|
||||
)
|
||||
data = serialize_task(task, TaskProjection.TOOL_INTERNAL)
|
||||
assert data["process_status"] == "parsed"
|
||||
assert "review_status" in data
|
||||
assert data["review_status"] == "parse_review"
|
||||
|
||||
|
||||
@@ -177,7 +199,6 @@ def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CONV-1",
|
||||
conversation_id="conv-abc",
|
||||
process_status="parsed",
|
||||
source_type="manual",
|
||||
)
|
||||
from app import db
|
||||
@@ -202,13 +223,11 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
|
||||
ShippingNotice(
|
||||
task_no="SN-CONV-MULTI-1",
|
||||
conversation_id="conv-multi",
|
||||
process_status="parsed",
|
||||
source_type="manual",
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-CONV-MULTI-2",
|
||||
conversation_id="conv-multi",
|
||||
process_status="pending_review",
|
||||
source_type="manual",
|
||||
),
|
||||
]
|
||||
@@ -232,13 +251,11 @@ def test_task_can_handle_only_creator(app):
|
||||
|
||||
owned = ShippingNotice(
|
||||
task_no="SN-HANDLE-OWN",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=42,
|
||||
)
|
||||
orphan = ShippingNotice(
|
||||
task_no="SN-HANDLE-ORPHAN",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=None,
|
||||
)
|
||||
@@ -263,13 +280,11 @@ def test_get_task_for_user_rejects_null_owner(app):
|
||||
|
||||
orphan = ShippingNotice(
|
||||
task_no="SN-NULL-OWNER",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=None,
|
||||
)
|
||||
owned = ShippingNotice(
|
||||
task_no="SN-OWNED",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=7,
|
||||
)
|
||||
@@ -291,7 +306,6 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-ENRICH-1",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -306,7 +320,7 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
assert data["todo_category"] == "review"
|
||||
assert data["created_by"] == 11
|
||||
assert data["can_handle"] is True
|
||||
assert data["ui_state"]["checkpoint"] == "parse_review"
|
||||
assert data["ui_state"]["checkpoint"]["code"] == "parse_review"
|
||||
assert data["artifact_summary"]["export_file_name"] == "a.xlsx"
|
||||
|
||||
no_viewer = serialize_task_summary(task)
|
||||
@@ -322,7 +336,6 @@ def test_list_my_todos_and_count_buckets(app):
|
||||
owner = 55
|
||||
review = ShippingNotice(
|
||||
task_no="SN-TODO-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -330,7 +343,6 @@ def test_list_my_todos_and_count_buckets(app):
|
||||
)
|
||||
upload = ShippingNotice(
|
||||
task_no="SN-TODO-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
export_file_path="/tmp/u.xlsx",
|
||||
@@ -338,13 +350,12 @@ def test_list_my_todos_and_count_buckets(app):
|
||||
)
|
||||
done = ShippingNotice(
|
||||
task_no="SN-TODO-DONE",
|
||||
process_status="uploaded",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
upload_status="uploaded",
|
||||
)
|
||||
other = ShippingNotice(
|
||||
task_no="SN-TODO-OTHER",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -387,7 +398,7 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-REV-DL')
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='TODO-REV-DL')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
@@ -397,6 +408,15 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
|
||||
'conflicts': [],
|
||||
}],
|
||||
}
|
||||
from app.models import ShippingOrderCandidate
|
||||
|
||||
db.session.add(ShippingOrderCandidate(
|
||||
candidate_no='CAND-TODO-REV-DL',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='todo-review-deep-link',
|
||||
order_extraction_run_id=run.id,
|
||||
))
|
||||
db.session.commit()
|
||||
cases = ensure_run_review_cases(run=run)
|
||||
assert cases
|
||||
@@ -412,17 +432,86 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
|
||||
assert hit['conversation_id'] == session.session_id
|
||||
assert hit['can_handle'] is True
|
||||
assert hit['ui_state']['summary']['entry_surface'] == 'review_workbench'
|
||||
assert hit['ui_state']['lifecycle_stage'] == 'order_review'
|
||||
assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [
|
||||
'available', 'current', 'unavailable', 'unavailable',
|
||||
]
|
||||
|
||||
counts = count_my_todos(user.id)
|
||||
assert counts['pending'] >= 1
|
||||
assert counts['total_pending_badge'] == counts['pending']
|
||||
|
||||
|
||||
def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_still_open(app):
|
||||
"""待办只能指向文件 Stream 当前 Case,不能因旧 Case 状态残留而重复展示。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_disposition_service import reparse_case_document
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
from app.services.shipping_notice.review_stream_service import activate_review_case
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-STREAM-CURRENT')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
original = ensure_run_review_cases(run=source)[0]
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
|
||||
replacement_run, _ = reparse_case_document(
|
||||
user_id=user.id, case_no=original.case_no, reason='rule_updated',
|
||||
)
|
||||
ensure_order_extraction_plan(replacement_run)
|
||||
for unit in replacement_run.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
replacement = ensure_run_review_cases(run=replacement_run)[0]
|
||||
activate_review_case(case=replacement, trigger='document_reparse_succeeded')
|
||||
|
||||
# 模拟旧数据未正确标成 superseded:当前态仍必须由 Stream 指针裁决。
|
||||
original.status = 'draft'
|
||||
original.confirmed_task_id = None
|
||||
db.session.commit()
|
||||
|
||||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||||
review_case_nos = {
|
||||
item['review_case_no']
|
||||
for item in pending['items']
|
||||
if item.get('item_kind') == 'review_case'
|
||||
}
|
||||
assert replacement.case_no in review_case_nos
|
||||
assert original.case_no not in review_case_nos
|
||||
|
||||
|
||||
def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app):
|
||||
"""历史空 Review Case 可以处置,但不能被待办页默认授权进入订单生命周期。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-EMPTY-CASE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': []}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||||
hit = next(item for item in pending['items'] if item.get('review_case_no') == case.case_no)
|
||||
assert hit['ui_state']['lifecycle_stage'] is None
|
||||
assert hit['ui_state']['lifecycle_entries'] == []
|
||||
|
||||
|
||||
def test_list_my_todos_includes_orphan_parse_failed_intake(app):
|
||||
"""
|
||||
未建 OT 且解析失败的 Intake 须进入 pending,并暴露 conversation 深链字段。
|
||||
|
||||
断言:item_kind=order_intake;todo_category=intake_parse;count.pending 计入。
|
||||
断言:item_kind=order_intake;todo_category=intake_parse;count.pending 计入。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
@@ -472,6 +561,8 @@ def test_list_my_todos_includes_orphan_parse_failed_intake(app):
|
||||
assert hit['source_file_name'] == 'orphan-fail.pdf'
|
||||
assert hit['can_handle'] is True
|
||||
assert hit['ui_state']['summary']['entry_surface'] == 'conversation_processing'
|
||||
assert hit['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||||
assert hit['ui_state']['lifecycle_entries'] == []
|
||||
|
||||
filtered = list_my_todos(
|
||||
user.id, bucket='pending', page=1, page_size=50, todo_category='intake_parse',
|
||||
@@ -527,7 +618,6 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app):
|
||||
tasks = [
|
||||
ShippingNotice(
|
||||
task_no=f"SN-TODO-PAGE-{index:04d}",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -578,7 +668,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
fixtures = [
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -586,7 +675,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
export_file_path="/tmp/lw.xlsx",
|
||||
@@ -595,7 +683,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-SHORTAGE",
|
||||
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
|
||||
process_status="parsed",
|
||||
review_status="shortage_review",
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
@@ -603,13 +690,12 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-DONE",
|
||||
process_status="uploaded",
|
||||
upload_status="uploaded",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-PROGRESS",
|
||||
process_status="parsed",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
@@ -620,7 +706,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
category_expr = _task_todo_category_sql_expr()
|
||||
for task in fixtures:
|
||||
row = SimpleNamespace(
|
||||
process_status=task.process_status,
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
shipping_case_id=task.shipping_case_id,
|
||||
@@ -630,6 +715,7 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
inventory_lines_json=task.inventory_lines_json,
|
||||
match_status=task.match_status,
|
||||
export_file_path=task.export_file_path,
|
||||
upload_status=task.upload_status,
|
||||
)
|
||||
expected = task_todo_category(task)
|
||||
# 轻量路径与 ORM 路径同分类。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_notice_state_machine.py
|
||||
|
||||
用途:校验发货通知状态机注册表完整性与 STP checkpoint_kind 映射。
|
||||
用途:校验发货通知 checkpoint 内部流程映射与 STP checkpoint_kind。
|
||||
依赖:pytest、state_machine、constants、ShippingNotice。
|
||||
逻辑:validate_registry 无错误;关键检查点 kind 正确;resolve_task_ui_state 对简单任务属性可解析。
|
||||
"""
|
||||
@@ -16,16 +16,11 @@ from app.services.shipping_notice.constants import (
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
checkpoint_kind_for,
|
||||
resolve_task_ui_state,
|
||||
validate_registry,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for, resolve_task_ui_state, validate_registry
|
||||
|
||||
|
||||
def test_validate_registry_has_no_errors() -> None:
|
||||
"""CHECKPOINT_REGISTRY 与 KIND / ACTION_SPECS 应完全对齐。"""
|
||||
"""checkpoint 仅维护内部流程分类。"""
|
||||
assert validate_registry() == []
|
||||
|
||||
|
||||
@@ -41,7 +36,6 @@ def test_resolve_task_ui_state_parse_review(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-PARSE",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
@@ -56,7 +50,6 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-EXPORT",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
@@ -64,15 +57,15 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.checkpoint == CP_EXPORT_READY
|
||||
assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert "mark_manual_uploaded" in (ui.human_options or [])
|
||||
assert not hasattr(ui, 'human_options')
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_uploaded_complete(app) -> None:
|
||||
"""process_status=uploaded 应为 complete。"""
|
||||
"""upload_status=uploaded 应为 complete。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-UPLOADED",
|
||||
process_status="uploaded",
|
||||
upload_status="uploaded",
|
||||
source_type="manual",
|
||||
)
|
||||
ui = resolve_task_ui_state(task)
|
||||
@@ -83,7 +76,7 @@ def test_resolve_task_ui_state_uploaded_complete(app) -> None:
|
||||
def test_resolve_with_mocked_simple_namespace_attributes() -> None:
|
||||
"""无 DB 会话时可用简易命名空间验证 uploaded 终态分支。"""
|
||||
task = SimpleNamespace(
|
||||
process_status="uploaded",
|
||||
upload_status="uploaded",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
shipping_case_id=None,
|
||||
|
||||
@@ -38,7 +38,6 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app)
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-WAIT-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/stp-export.xlsx",
|
||||
export_file_name="stp-export.xlsx",
|
||||
@@ -62,7 +61,6 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-MUST-HUMAN",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
@@ -85,7 +83,6 @@ def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-RPA-ON",
|
||||
process_status="matched",
|
||||
match_status="fulfillable",
|
||||
source_type="manual",
|
||||
line_results_json=[{"line_status": "ok"}],
|
||||
@@ -127,7 +124,6 @@ def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-NO-RPA",
|
||||
process_status="matched",
|
||||
match_status="fulfillable",
|
||||
source_type="manual",
|
||||
line_results_json=[{"line_status": "ok"}],
|
||||
@@ -166,7 +162,6 @@ def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-MANUAL-CFM",
|
||||
process_status="waiting_upload",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
@@ -235,7 +230,6 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-CLOSE-FAIL",
|
||||
process_status="waiting_upload",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
@@ -301,17 +295,21 @@ def test_export_ready_ui_state_entry_is_task_workbench(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-ENTRY",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/x.xlsx",
|
||||
export_file_name="x.xlsx",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["checkpoint"]["kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
button_ids = [b.get("id") for b in (state.get("action_buttons") or [])]
|
||||
button_ids = [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
assert "mark_manual_uploaded" in button_ids
|
||||
assert "download_excel" in button_ids
|
||||
assert "action_buttons" not in state
|
||||
|
||||
|
||||
def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
@@ -339,7 +337,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
mine = ShippingNotice(
|
||||
task_no="SN-STP-OWN",
|
||||
user_id=owner.id,
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
@@ -347,7 +344,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
waiting_upload = ShippingNotice(
|
||||
task_no="SN-STP-UPLOAD",
|
||||
user_id=owner.id,
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/own.xlsx",
|
||||
export_file_name="own.xlsx",
|
||||
@@ -355,7 +351,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
other = ShippingNotice(
|
||||
task_no="SN-STP-OTHER",
|
||||
user_id=admin.id,
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
|
||||
@@ -297,14 +297,13 @@ def test_openapi_spec_public(app, client):
|
||||
assert "submit_decision" not in spec_text
|
||||
|
||||
|
||||
def test_confirm_inventory_source_route_returns_json(app, client):
|
||||
"""confirm_inventory_source HTTP 路由必须存在且可调用。"""
|
||||
def test_confirm_inventory_source_route_is_removed(app, client):
|
||||
"""库存源人工确认已下线,任何旧 Tool 写入口均不得可达。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-HTTP-CONFIRM-SRC",
|
||||
source_type="manual",
|
||||
process_status="pending_review",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
ship_to="Dublin",
|
||||
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
|
||||
@@ -317,8 +316,7 @@ def test_confirm_inventory_source_route_returns_json(app, client):
|
||||
headers=headers,
|
||||
json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.get_json()["status"] in {"ok", "needs_human", "running"}
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
def test_static_openapi_snapshot_contains_shipping_contract_keywords():
|
||||
@@ -339,7 +337,7 @@ def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision):
|
||||
"""已启用库存站点不得通过任务决策重开旧列映射路径。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual", process_status="waiting_inventory")
|
||||
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual")
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -363,7 +361,6 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REUPLOAD-INVENTORY",
|
||||
source_type="manual",
|
||||
process_status="matched",
|
||||
inventory_lines_json=[{"part_number": "A001", "available_qty": 10}],
|
||||
match_status="fulfillable",
|
||||
line_results_json=[{"part_number": "A001"}],
|
||||
@@ -398,12 +395,12 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
|
||||
body = response.get_json()
|
||||
assert body["status"] == "needs_human"
|
||||
assert body["checkpoint"] == "upload_req"
|
||||
assert body["human_options"] == ["upload_inventory_file", "retry_rpa"]
|
||||
assert "human_options" not in body
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
|
||||
assert link.is_active is False
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.match_status is None
|
||||
@@ -519,7 +516,6 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "inventory_ready"
|
||||
task.review_status = None
|
||||
task.pending_human_reason = "inv_unavail"
|
||||
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}]
|
||||
@@ -542,7 +538,6 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
|
||||
}
|
||||
}
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
task.process_status = "parsed"
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice import decision_workflow
|
||||
@@ -555,7 +550,7 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.review_status is None
|
||||
assert task.inventory_lines_json is None
|
||||
@@ -601,7 +596,6 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_PENDING
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
@@ -628,7 +622,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert result["status"] == "needs_human"
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
|
||||
@@ -665,7 +659,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_EXHAUSTED
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
@@ -677,7 +670,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
}
|
||||
}
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
task.process_status = "parsed"
|
||||
base_time = datetime.utcnow() - timedelta(minutes=5)
|
||||
for idx in range(3):
|
||||
db.session.add(
|
||||
@@ -700,7 +692,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.error_message is None
|
||||
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
|
||||
@@ -749,7 +741,6 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_PENDING
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
@@ -777,7 +768,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
|
||||
assert task is not None
|
||||
assert result["started"] == 1
|
||||
assert result["skipped"] == 0
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
|
||||
@@ -791,7 +782,6 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
|
||||
first = ShippingNotice(
|
||||
task_no="SN-MULTI-CONV-001",
|
||||
conversation_id="conv-test-multi",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -800,7 +790,6 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
|
||||
second = ShippingNotice(
|
||||
task_no="SN-MULTI-CONV-002",
|
||||
conversation_id="conv-test-multi",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -835,8 +824,8 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
|
||||
.order_by(ShippingNotice.task_no)
|
||||
.all()
|
||||
}
|
||||
assert rows["SN-MULTI-CONV-001"].process_status == "pending_review"
|
||||
assert rows["SN-MULTI-CONV-002"].process_status == "pending_review"
|
||||
assert rows["SN-MULTI-CONV-001"].review_status == "parse_review"
|
||||
assert rows["SN-MULTI-CONV-002"].review_status == "parse_review"
|
||||
|
||||
|
||||
def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch):
|
||||
@@ -885,17 +874,15 @@ def test_parse_inventory_oversized_text_route_is_removed(app, client):
|
||||
|
||||
|
||||
def test_chat_actions_empty_when_task_rejected(app):
|
||||
from app.services.shipping_notice.chat_actions import human_options_for_task
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-20260101-TEST0001",
|
||||
source_type="manual",
|
||||
process_status="rejected",
|
||||
review_status="rejected",
|
||||
)
|
||||
assert human_options_for_task(task) == []
|
||||
ui_state = build_task_ui_state(task)
|
||||
assert ui_state["checkpoint"] == "rejected"
|
||||
assert ui_state["action_buttons"] == []
|
||||
assert ui_state["checkpoint"]["code"] == "rejected"
|
||||
assert ui_state["actions"] == {"primary": None, "secondary": []}
|
||||
assert "action_buttons" not in ui_state
|
||||
@@ -6,7 +6,9 @@ tests/test_shipping_notice_ui_state.py
|
||||
逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。
|
||||
"""
|
||||
|
||||
from app.models import ShippingNotice
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, User
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
@@ -14,6 +16,7 @@ from app.services.shipping_notice.constants import (
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
from app.services.shipping_notice.ui_state import _unified_actions
|
||||
|
||||
|
||||
_REQUIRED_SUMMARY_KEYS = {
|
||||
@@ -31,29 +34,241 @@ _REQUIRED_SUMMARY_KEYS = {
|
||||
}
|
||||
|
||||
|
||||
def test_unified_actions_deduplicates_gate_primary_action():
|
||||
"""Gate 主动作同时出现在展示列表时,只能渲染一次。"""
|
||||
state = _unified_actions(
|
||||
process_gate={
|
||||
"primary_action": {"code": "open_order_review", "label": "进入订单复核"},
|
||||
"action_presentation": [
|
||||
{"code": "open_order_review", "label": "进入订单复核"},
|
||||
{"code": "view_audit", "label": "查看审计", "kind": "view"},
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
assert state["primary"]["code"] == "open_order_review"
|
||||
assert [item["code"] for item in state["secondary"]] == ["view_audit"]
|
||||
|
||||
|
||||
def test_unified_action_shape_contains_gate_version_fields():
|
||||
"""统一动作 DTO 必须包含前端提交所需的版本、分派与禁用字段。"""
|
||||
state = _unified_actions(
|
||||
process_gate={
|
||||
"lock_version": 7,
|
||||
"current_gate": {"evaluation_version": 3},
|
||||
"primary_action": {
|
||||
"code": "retry_inventory_matching",
|
||||
"label": "重新匹配",
|
||||
"dispatch": "mutation",
|
||||
},
|
||||
"action_presentation": [],
|
||||
},
|
||||
)
|
||||
assert state["primary"]["expected_gate_version"] == 3
|
||||
# 关键断言:前端必须按 Gate 声明的执行方式分派,不能按动作码硬编码。
|
||||
assert state["primary"]["dispatch"] == "mutation"
|
||||
assert "disabled_reason" in state["primary"]
|
||||
|
||||
|
||||
def test_unified_actions_preserve_backend_surface_without_action_code_fallback():
|
||||
"""UI State 只透传动作来源声明的位置,不再按下载动作码补默认工作面。"""
|
||||
state = _unified_actions(
|
||||
process_gate={
|
||||
"primary_action": {
|
||||
"code": "mark_manual_uploaded",
|
||||
"label": "登记人工上传",
|
||||
"target_surface": "upload_complete",
|
||||
},
|
||||
"action_presentation": [{
|
||||
"code": "download_excel",
|
||||
"label": "下载发货 Excel",
|
||||
"target_surface": "upload_complete",
|
||||
"target_anchor": "excel_artifact",
|
||||
}],
|
||||
},
|
||||
)
|
||||
assert state["primary"]["target_surface"] == "upload_complete"
|
||||
assert state["secondary"][0]["target_surface"] == "upload_complete"
|
||||
assert state["secondary"][0]["target_anchor"] == "excel_artifact"
|
||||
|
||||
|
||||
def test_build_task_ui_state_summary_has_required_keys(app) -> None:
|
||||
"""summary 必须包含 STP 可解释字段全集。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-SUMMARY",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
|
||||
assert state["checkpoint"] == CP_PARSE_REVIEW
|
||||
assert state["checkpoint"]["code"] == CP_PARSE_REVIEW
|
||||
assert state["checkpoint_kind"] == "must_human"
|
||||
assert "stp_facts" not in state["summary"]
|
||||
|
||||
|
||||
def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||||
"""列表等轻量调用默认不得加载阶段工作面详情。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no="SN-UI-LIGHTWEIGHT", source_type="manual")
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
detailed_state = build_task_ui_state(task, include_stage_context=True)
|
||||
|
||||
# 关键断言:只有详情接口显式请求时才查询行、Artifact 和上传 Attempt。
|
||||
assert "stage_context" not in state
|
||||
assert "stage_context" in detailed_state
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None:
|
||||
"""没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STAGE-ACTIONS",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["stage"]["code"] == "order_review"
|
||||
assert state["stage"]["index"] == 2
|
||||
assert state["stage"]["total"] == 4
|
||||
assert state["actions"]["primary"] is None
|
||||
assert state["actions"]["secondary"] == []
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None:
|
||||
"""正式工作台的四个入口必须由后端下发,页面不能按阶段顺序自行生成。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-LIFECYCLE-ENTRIES",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["lifecycle_stage"] == "order_review"
|
||||
assert state["lifecycle_entries"] == [
|
||||
{"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
|
||||
]
|
||||
|
||||
|
||||
def test_task_ui_state_ignores_superseded_process_execution(app) -> None:
|
||||
"""被替代的 Execution 不能继续给正式工作台下发历史 Gate 或按钮。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
)
|
||||
|
||||
user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(task_no='SN-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
execution.status = 'superseded'
|
||||
db.session.flush()
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['process_gate'] is None
|
||||
|
||||
|
||||
def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
|
||||
"""正式 Gate 与旧任务字段冲突时,任务详情必须与批次中心同样以 Gate 裁决阶段。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-UI-GATE-AUTHORITY',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
# 模拟历史字段尚未同步:旧字段仍像解析复核。
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
execution.current_gate_code = 'inventory_matching'
|
||||
db.session.flush()
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert state['lifecycle_authority'] == 'process_gate'
|
||||
assert state['stage']['code'] == 'fulfillment_prep'
|
||||
assert state['current_step']['code'] == 'fulfillment_prep'
|
||||
assert [entry['state'] for entry in state['lifecycle_entries']] == [
|
||||
'available', 'available', 'current', 'unavailable',
|
||||
]
|
||||
|
||||
|
||||
def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None:
|
||||
"""正式人工上传 Gate 必须裁决为通知完成,不受旧复核字段影响。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-UI-UPLOAD-GATE-AUTHORITY',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
execution.current_gate_code = 'manual_upload_handoff'
|
||||
db.session.flush()
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['lifecycle_stage'] == 'upload_complete'
|
||||
assert state['lifecycle_authority'] == 'process_gate'
|
||||
assert state['stage']['code'] == 'upload_complete'
|
||||
assert [entry['state'] for entry in state['lifecycle_entries']] == [
|
||||
'available', 'available', 'available', 'current',
|
||||
]
|
||||
|
||||
|
||||
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
|
||||
"""库存匹配/上传结果只映射四个业务阶段。"""
|
||||
with app.app_context():
|
||||
fulfillment = ShippingNotice(
|
||||
task_no="SN-UI-FULFILLMENT",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_lines_json=[{"part_number": "P-1"}],
|
||||
)
|
||||
upload = ShippingNotice(
|
||||
task_no="SN-UI-UPLOAD",
|
||||
source_type="manual",
|
||||
upload_status="uploaded",
|
||||
)
|
||||
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
|
||||
upload_state = build_task_ui_state(upload, include_stage_context=True)
|
||||
assert upload_state["stage"]["code"] == "upload_complete"
|
||||
# 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。
|
||||
assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual"
|
||||
|
||||
|
||||
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
"""解析复核应进入人工复核工作台。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
@@ -63,24 +278,76 @@ def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
|
||||
|
||||
def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
"""Excel 待人工上传登记应进入任务处理工作台(下载 + 登记)。"""
|
||||
"""Excel 待人工上传登记仍进入工作台,但历史文件名不能擅自授权下载。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-EXPORT",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint"] == CP_EXPORT_READY
|
||||
assert state["checkpoint"]["code"] == CP_EXPORT_READY
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
assert state["summary"].get("pause_reason_code") == "wait_manual_upload"
|
||||
assert "登记凭据" in str(state["summary"].get("pause_reason") or "")
|
||||
button_ids = [b.get("id") for b in (state.get("action_buttons") or [])]
|
||||
button_ids = [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
# 关键断言:没有可验证 Artifact 时,遗留 export_file_name 不得生成下载按钮。
|
||||
assert "download_excel" not in button_ids
|
||||
assert "mark_manual_uploaded" not in button_ids
|
||||
|
||||
|
||||
def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypatch) -> None:
|
||||
"""下载入口必须由后端 Artifact 解析结果裁决,而不是由遗留文件名裁决。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-RESOLVED-EXPORT",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
lambda _task: (object(), 'shipping-export.xlsx'),
|
||||
)
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
button_ids = [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
assert "download_excel" in button_ids
|
||||
assert "mark_manual_uploaded" in button_ids
|
||||
|
||||
|
||||
def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None:
|
||||
"""当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no="SN-UI-GATE-EXPORT", source_type="manual")
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
lambda _task: (None, 'shipping-export.xlsx'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda _task: {
|
||||
'current_gate': {'gate_code': 'freight_upload_rpa', 'evaluation_version': 3},
|
||||
'current_blocking_gate': {'gate_code': 'freight_upload_rpa', 'evaluation_version': 3},
|
||||
'primary_action': {'code': 'retry_freight_upload_rpa', 'label': '重新上传'},
|
||||
'action_presentation': [],
|
||||
},
|
||||
)
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['actions']['primary']['code'] == 'retry_freight_upload_rpa'
|
||||
assert [item['code'] for item in state['actions']['secondary']] == ['download_excel']
|
||||
|
||||
|
||||
def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||||
@@ -88,7 +355,6 @@ def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-FROZEN",
|
||||
process_status="waiting_inventory",
|
||||
source_type="manual",
|
||||
inventory_source_status="candidates_frozen",
|
||||
inventory_source_method="stp_build_freeze",
|
||||
@@ -111,7 +377,6 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-LINES",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="resolved",
|
||||
@@ -135,12 +400,309 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
],
|
||||
},
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
state = build_task_ui_state(task, include_stage_context=True)
|
||||
rows = state["summary"]["stp_facts"]["line_resolutions"]
|
||||
assert rows[0]["effective_reservation_id"] == "3000092917"
|
||||
assert rows[0]["part_number"] == "PN-1"
|
||||
assert rows[0]["resolved_inventory_source_code"] == "DBS_DUB"
|
||||
assert rows[0]["inventory_file_no"] == "INV-1"
|
||||
stage_context = state["stage_context"]
|
||||
assert stage_context["preparation"]["status"] == "ready"
|
||||
assert stage_context["preparation"]["lines"] == [{
|
||||
"line_key": None,
|
||||
"reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"required_qty": None,
|
||||
"available_qty": None,
|
||||
"shortage_qty": None,
|
||||
"source_code": "DBS_DUB",
|
||||
"status": "ok",
|
||||
}]
|
||||
# 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。
|
||||
assert stage_context["upload"]["outcome"] == "not_started"
|
||||
|
||||
|
||||
def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
"""通知准备摘要必须从当前行级匹配事实投影数量,不能只依赖旧 JSON。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STRUCTURED-MATCH",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_source_code="DBS_DUB",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
line_results_json=[],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
required_qty="10",
|
||||
available_qty="7",
|
||||
matched_qty="7",
|
||||
shortage_qty="3",
|
||||
reservation_id="RSV-1",
|
||||
part_number="PN-1",
|
||||
inventory_source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
assert preparation["has_match_result"] is True
|
||||
assert preparation["lines"] == [{
|
||||
"line_key": "line-1",
|
||||
"reservation_id": "RSV-1",
|
||||
"part_number": "PN-1",
|
||||
"required_qty": "10",
|
||||
"available_qty": "7",
|
||||
"shortage_qty": "3",
|
||||
"source_code": "DBS_DUB",
|
||||
"status": "matched",
|
||||
}]
|
||||
|
||||
|
||||
def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None:
|
||||
"""库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no="SN-UI-FROZEN-ORDER", source_type="manual")
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLine(
|
||||
notice_id=task.id,
|
||||
position=0,
|
||||
line_key="line-frozen-1",
|
||||
reservation_id="RSV-FROZEN",
|
||||
part_number="PN-FROZEN",
|
||||
required_qty="6",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
|
||||
# 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。
|
||||
assert preparation["frozen_order_lines"] == [{
|
||||
"line_key": "line-frozen-1",
|
||||
"reservation_id": "RSV-FROZEN",
|
||||
"part_number": "PN-FROZEN",
|
||||
"required_qty": "6.00000000",
|
||||
}]
|
||||
assert preparation["lines"] == []
|
||||
assert preparation["has_match_result"] is False
|
||||
|
||||
|
||||
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
|
||||
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
|
||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
|
||||
with app.app_context():
|
||||
inventory_path = tmp_path / "task-inventory.xlsx"
|
||||
inventory_path.write_bytes(b"inventory-content")
|
||||
task = ShippingNotice(task_no="SN-UI-INVENTORY-DOWNLOAD", source_type="manual")
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no="SIF-UI-DOWNLOAD",
|
||||
storage_path=str(inventory_path),
|
||||
source_file_name="task-inventory.xlsx",
|
||||
snapshot_status="ready",
|
||||
)
|
||||
db.session.add_all([task, inventory_file])
|
||||
db.session.flush()
|
||||
|
||||
# 未建立 task link 时不得因为文件存在而放行下载。
|
||||
assert resolve_task_inventory_download(task) is None
|
||||
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inventory_file.id,
|
||||
is_active=True,
|
||||
access_mode="readonly",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
resolved = resolve_task_inventory_download(task)
|
||||
assert resolved is not None
|
||||
assert resolved[0] == inventory_path.resolve()
|
||||
assert resolved[1] == "task-inventory.xlsx"
|
||||
|
||||
|
||||
def test_workspace_inventory_download_requires_owned_active_file(app, client, tmp_path) -> None:
|
||||
"""库存下载路由只能返回当前用户任务的 active link 文件,不能泄漏其他任务或无关联文件。"""
|
||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username='inventory-download-owner', email='inventory-download-owner@example.com')
|
||||
other = User(username='inventory-download-other', email='inventory-download-other@example.com')
|
||||
db.session.add_all([owner, other])
|
||||
db.session.flush()
|
||||
inventory_path = tmp_path / 'inventory-download.xlsx'
|
||||
inventory_path.write_bytes(b'inventory-download-content')
|
||||
task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='manual')
|
||||
no_file_task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='manual')
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-DOWNLOAD-API',
|
||||
storage_path=str(inventory_path),
|
||||
source_file_name='inventory-download.xlsx',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, no_file_task, inventory_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inventory_file.id,
|
||||
is_active=True,
|
||||
access_mode='readonly',
|
||||
))
|
||||
db.session.commit()
|
||||
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
|
||||
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
|
||||
|
||||
# 关键断言:活动 link 文件可下载,并以服务端原始内容响应。
|
||||
success = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers)
|
||||
assert success.status_code == 200
|
||||
assert success.data == b'inventory-download-content'
|
||||
assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '')
|
||||
|
||||
# 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。
|
||||
missing = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers)
|
||||
assert missing.status_code == 404
|
||||
assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND'
|
||||
forbidden = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers)
|
||||
assert forbidden.status_code == 404
|
||||
|
||||
|
||||
def test_workspace_line_inventory_download_requires_current_line_reference(app, client, tmp_path) -> None:
|
||||
"""行内下载只能读取当前匹配事实引用的库存文件,不能按文件号探测同任务其他来源。"""
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username='line-inventory-download-owner', email='line-inventory-download-owner@example.com')
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
allowed_path = tmp_path / 'crane.xlsx'
|
||||
denied_path = tmp_path / 'dbs.xlsx'
|
||||
allowed_path.write_bytes(b'crane-content')
|
||||
denied_path.write_bytes(b'dbs-content')
|
||||
task = ShippingNotice(task_no='SN-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, source_type='manual')
|
||||
allowed_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path),
|
||||
source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready',
|
||||
)
|
||||
denied_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-LINE-DBS', storage_path=str(denied_path),
|
||||
source_file_name='dbs.xlsx', source_code='DBS', snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, allowed_file, denied_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, line_key='line-crane', line_index=0,
|
||||
inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no,
|
||||
inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
|
||||
|
||||
allowed = client.get(
|
||||
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE',
|
||||
headers=headers,
|
||||
)
|
||||
assert allowed.status_code == 200
|
||||
assert allowed.data == b'crane-content'
|
||||
assert 'crane.xlsx' in str(allowed.headers.get('Content-Disposition') or '')
|
||||
|
||||
denied = client.get(
|
||||
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS',
|
||||
headers=headers,
|
||||
)
|
||||
assert denied.status_code == 404
|
||||
|
||||
|
||||
def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None:
|
||||
"""结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STRUCTURED-PARTIAL",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
step_payload_json={"line_inventory_resolutions": [{
|
||||
"line_index": 0,
|
||||
"line_key": "line-1",
|
||||
"effective_reservation_id": "RSV-LEGACY",
|
||||
"part_number": "PN-LEGACY",
|
||||
"inventory_file_no": "INV-1",
|
||||
"disposition": "ok",
|
||||
}]},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
required_qty="10",
|
||||
available_qty="8",
|
||||
shortage_qty="2",
|
||||
inventory_source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
line = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]["lines"][0]
|
||||
assert line["reservation_id"] == "RSV-LEGACY"
|
||||
assert line["part_number"] == "PN-LEGACY"
|
||||
assert line["available_qty"] == "8"
|
||||
|
||||
|
||||
def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch) -> None:
|
||||
"""正式详情接口必须原样携带通知准备摘要,供工作台首屏消费。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.api.workspace import shipping_notice as api
|
||||
from app.services.shipping_notice import query_service
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-DETAIL-CONTEXT",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
required_qty="2",
|
||||
available_qty="2",
|
||||
shortage_qty="0",
|
||||
reservation_id="RSV-DETAIL",
|
||||
part_number="PN-DETAIL",
|
||||
inventory_source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=1, role='user'))
|
||||
monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task)
|
||||
monkeypatch.setattr(api, '_ok', lambda data: data)
|
||||
|
||||
payload = api.workspace_shipping_task_detail(task.task_no)
|
||||
preparation = payload['ui_state']['stage_context']['preparation']
|
||||
assert preparation['has_match_result'] is True
|
||||
assert preparation['lines'][0]['reservation_id'] == 'RSV-DETAIL'
|
||||
|
||||
|
||||
def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
|
||||
@@ -150,7 +712,6 @@ def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-MULTI",
|
||||
process_status="matched",
|
||||
review_status=RS_SHORTAGE_REVIEW,
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
|
||||
@@ -19,7 +19,6 @@ def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None:
|
||||
"""
|
||||
task = ShippingNotice(
|
||||
task_no="SN-TEST-RPA-PENDING",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason=PH_RPA_PENDING,
|
||||
)
|
||||
|
||||
|
||||
@@ -122,6 +122,386 @@ def _coordinate_definition() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def test_visual_sample_preview_reads_common_ocr_value_before_xfa_path_is_selected(app, monkeypatch):
|
||||
"""XFA 草稿未选 datasets path 时,仍从共同 PDF 坐标证据显示 PO 样本值。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'line-field', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'customer_po', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
# 正式 datasets binding 尚未完成:它必须不参与共同视觉样本值的输入校验。
|
||||
definition.update({
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {'template_packet_checksum': 'sha256:placeholder'},
|
||||
'bindings': [{
|
||||
'binding_id': 'value-source-customer_po', 'field_layout_id': 'customer_po',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': None},
|
||||
}],
|
||||
})
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:视觉/OCR 值正常显示;正式 datasets path 仍由独立 value-preview 决定。
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
assert result['fields'][0]['source'] == 'pdf_coordinate'
|
||||
|
||||
|
||||
def test_visual_sample_preview_retries_only_missing_hybrid_xfa_field_with_ocr(app, monkeypatch):
|
||||
"""Hybrid XFA 有标签 glyph 但值仅在外观层时,当前字段须以 OCR 样本值回退。"""
|
||||
native_label_glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('ORDER NO:')
|
||||
]
|
||||
ocr_value_glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 100 + index * 8, 'y0': 10, 'x1': 106 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=102)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': native_label_glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 102 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(
|
||||
service, '_read_page_ocr_coordinate_evidence',
|
||||
lambda **_kwargs: {'width': 200, 'height': 100, 'glyphs': ocr_value_glyphs},
|
||||
raising=False,
|
||||
)
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'customer_po', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .45, 'y0': .05, 'x1': .95, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [{
|
||||
'binding_id': 'value-source-customer_po', 'field_layout_id': 'customer_po',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': None},
|
||||
}],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 102, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:页面仍有原生标签时,字段值缺失必须继续读取同页 OCR,而非将整页误判为可用。
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
assert result['fields'][0]['source'] == 'ocr_coordinate'
|
||||
assert result['fields'][0]['status'] == 'needs_review'
|
||||
assert 'order_field_ocr_coordinate_needs_review' in result['fields'][0]['issues']
|
||||
|
||||
|
||||
def test_visual_sample_preview_uses_unique_xfa_widget_when_native_and_ocr_are_missing(app, monkeypatch):
|
||||
"""Hybrid XFA 的唯一带值 Widget 只能作为画框后的复核样本值。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=103, asset_id=501, filename='hybrid.pdf')
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 103 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .45, 'y0': .05, 'x1': .75, 'y1': .25}, value='4510039227'),
|
||||
], raising=False)
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [], 'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'customer_po', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .40, 'y0': .04, 'x1': .80, 'y1': .30},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 103, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# Widget 值不进入正式取值;仅供当前视觉框展示,且必须要求人工复核。
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
assert result['fields'][0]['source'] == 'acroform_widget'
|
||||
assert result['fields'][0]['status'] == 'needs_review'
|
||||
assert 'order_field_acroform_widget_needs_review' in result['fields'][0]['issues']
|
||||
|
||||
|
||||
def test_visual_sample_preview_rejects_ambiguous_xfa_widget_values(app, monkeypatch):
|
||||
"""同一画框命中多个 XFA Widget 时,预览不得静默任选一个值。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=104, asset_id=501, filename='hybrid.pdf')
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 104 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .45, 'y0': .05, 'x1': .60, 'y1': .25}, value='4510039227'),
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .61, 'y0': .05, 'x1': .75, 'y1': .25}, value='4510039228'),
|
||||
], raising=False)
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [], 'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'customer_po', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .40, 'y0': .04, 'x1': .80, 'y1': .30},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 104, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
assert result['fields'][0]['value'] is None
|
||||
assert result['fields'][0]['status'] == 'unavailable'
|
||||
assert 'order_field_acroform_widget_ambiguous' in result['fields'][0]['issues']
|
||||
|
||||
|
||||
def test_preview_page_region_text_uses_unique_xfa_widget_when_coordinate_text_is_missing(app, monkeypatch):
|
||||
"""任意已画视觉框在 native/OCR 无文本时,可展示唯一 XFA Widget 样本值。"""
|
||||
document = SimpleNamespace(id=109, asset_id=501, filename='hybrid.pdf')
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout)
|
||||
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .45, 'y0': .20, 'x1': .70, 'y1': .30}, value='AMTEMP-S000218922'),
|
||||
], raising=False)
|
||||
with app.app_context():
|
||||
result = service.read_preview_page_region_text(
|
||||
1, data={'document_id': 109, 'region': {'x0': .40, 'y0': .15, 'x1': .75, 'y1': .35}}, page_no=1, actor_id=1,
|
||||
)
|
||||
|
||||
assert result['text'] == 'AMTEMP-S000218922'
|
||||
assert result['source'] == 'acroform_widget'
|
||||
assert result['status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch):
|
||||
"""任意视觉框命中多个带值 Widget 时不得将其中之一冒充样本值。"""
|
||||
document = SimpleNamespace(id=110, asset_id=501, filename='hybrid.pdf')
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout)
|
||||
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .45, 'y0': .20, 'x1': .55, 'y1': .30}, value='A'),
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .56, 'y0': .20, 'x1': .70, 'y1': .30}, value='B'),
|
||||
], raising=False)
|
||||
with app.app_context():
|
||||
result = service.read_preview_page_region_text(
|
||||
1, data={'document_id': 110, 'region': {'x0': .40, 'y0': .15, 'x1': .75, 'y1': .35}}, page_no=1, actor_id=1,
|
||||
)
|
||||
|
||||
assert result['text'] == ''
|
||||
assert result['source'] == 'acroform_widget_ambiguous'
|
||||
|
||||
|
||||
def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field(app, monkeypatch):
|
||||
"""共同视觉预览忽略旧浏览器重复提交的已绑定未绑定布局,仍返回 PO 样本值。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'line-field', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'order_field_1_1', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
definition['draft_unbound_order_field_layouts'] = [{
|
||||
'layout_id': 'order_field_1_1', 'label': '客户 PO 号',
|
||||
'page_scope': 'exact_page', 'page_no': 1, 'anchor': None,
|
||||
'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'minimum_evidence_level': 'coordinate',
|
||||
}] * 6
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:同一 layout 一旦有 Schema 绑定,不能再作为未绑定草稿传给坐标校验器。
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def test_visual_sample_preview_reads_order_field_before_table_region_is_drawn(app, monkeypatch):
|
||||
"""共同视觉预览在明细表尚未标注时,仍可读取已标注的订单级 PO 字段。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'order_field_1_2', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:预览仅展示现有视觉证据,不把“尚未绘制明细表”伪装为可保存模板。
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def _bind_ready_profile_sample(
|
||||
profile_id: int,
|
||||
*,
|
||||
@@ -342,7 +722,11 @@ def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
definition = _coordinate_definition()
|
||||
schema.definition_json['fields'][1].pop('allowed_sources', None)
|
||||
part_field = next(
|
||||
field for field in schema.definition_json['fields']
|
||||
if field['field_code'] == 'part_number'
|
||||
)
|
||||
part_field.pop('allowed_sources', None)
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft({
|
||||
'profile_code': 'COORD_V2', 'display_name': 'Coordinate V2',
|
||||
@@ -350,13 +734,13 @@ def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_
|
||||
}, actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
|
||||
schema.definition_json['fields'][1]['allowed_sources'] = ['pdf_coordinate']
|
||||
part_field['allowed_sources'] = ['pdf_coordinate']
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'COORD_V2', 'display_name': 'Coordinate V2',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
field_region = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field_region = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
assert field_region['field_id'] == 'part-field'
|
||||
assert 'contract_version' not in saved['definition']
|
||||
|
||||
@@ -373,6 +757,7 @@ def test_order_field_layout_is_independent_from_line_layout_and_freezes_header_f
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': 'forged', 'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page',
|
||||
'anchor': {'anchor_id': 'po_label', 'text': 'PO NO', 'aliases': ['PO NUMBER']},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
@@ -405,6 +790,7 @@ def test_order_field_layout_duplicate_returns_bound_schema_code(app):
|
||||
definition['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': f'ship_to_{index}', 'field_id': '', 'field_code': 'ship_to_customer',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': {'anchor_id': f'ship_to_label_{index}', 'text': f'SHIP TO {index}'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
@@ -448,6 +834,7 @@ def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app):
|
||||
definition['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': 'bill_to_customer_layout', 'field_id': '', 'field_code': 'bill_to_customer',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor,
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 3, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
@@ -455,6 +842,7 @@ def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app):
|
||||
},
|
||||
{
|
||||
'layout_id': 'bill_to_address_layout', 'field_id': '', 'field_code': 'bill_to_address',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor,
|
||||
'value_region': {'x0': 3, 'y0': 0, 'x1': 10, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
@@ -505,6 +893,7 @@ def test_order_field_layout_freezes_schema_normalizer_and_rejects_a_mismatch(app
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page', 'page_no': 1,
|
||||
'fallback_value_region': {'x0': .4, 'y0': .1, 'x1': .8, 'y1': .16},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'required': False,
|
||||
@@ -537,6 +926,7 @@ def test_order_field_ocr_minimum_level_keeps_native_pdf_as_stronger_allowed_sour
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page', 'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
'stop_anchors': [], 'required': False, 'minimum_evidence_level': 'ocr_coordinate',
|
||||
@@ -565,7 +955,7 @@ def test_composite_coordinate_binding_freezes_all_registered_output_fields(app):
|
||||
'profile_code': 'COMPOSITE_QTY', 'display_name': 'Composite qty',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['target_fields']
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]['target_fields']
|
||||
assert targets == [
|
||||
{'field_id': 'qty-field', 'field_code': 'qty', 'scope': 'line'},
|
||||
{'field_id': 'uom-field', 'field_code': 'uom', 'scope': 'line'},
|
||||
@@ -600,14 +990,17 @@ def test_amount_currency_binding_freezes_header_target_and_checks_each_output_so
|
||||
])
|
||||
definition = _coordinate_definition()
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
field.update({'field_code': 'line_amount_before_tax', 'extractor_key': 'amount_currency'})
|
||||
field.update({
|
||||
'field_code': 'line_amount_before_tax',
|
||||
'extractor_key': 'amount_currency',
|
||||
})
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'COMPOSITE_AMOUNT', 'display_name': 'Composite amount',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['target_fields']
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]['target_fields']
|
||||
assert targets == [
|
||||
{'field_id': 'currency-field', 'field_code': 'currency', 'scope': 'line'},
|
||||
{'field_id': 'currency-field', 'field_code': 'currency', 'scope': 'header'},
|
||||
{'field_id': 'amount-field', 'field_code': 'line_amount_before_tax', 'scope': 'line'},
|
||||
]
|
||||
|
||||
@@ -631,12 +1024,12 @@ def test_coordinate_binding_allows_enabled_header_value_from_a_detail_physical_r
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
field['field_code'] = 'incoterm'
|
||||
field.update({'field_code': 'incoterm', 'scope': 'header'})
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'HEADER_FROM_LINE', 'display_name': 'Header from detail line',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
bound = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
bound = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
assert bound['field_id'] == 'incoterm-field'
|
||||
assert bound['target_fields'] == [{'field_id': 'incoterm-field', 'field_code': 'incoterm', 'scope': 'header'}]
|
||||
|
||||
@@ -675,7 +1068,18 @@ def test_profile_samples_are_governed_and_audited(app, monkeypatch):
|
||||
db.session.flush()
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'sample-table', 'html': '<table><tr><td>ok</td></tr></table>'}],
|
||||
'pages': [{'page_no': 1}],
|
||||
'tables': [{'table_id': 'sample-table', 'page_no': 1, 'html': '<table><tr><td>ok</td></tr></table>'}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': [{
|
||||
'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
|
||||
}]},
|
||||
'tables': {'sample-table': [{
|
||||
'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
|
||||
}]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}, 'tables': {'sample-table': 'pdf_coordinate'}},
|
||||
},
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
@@ -738,7 +1142,7 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon
|
||||
first['id'], actor_id=None, expected_lock_version=first['lock_version'],
|
||||
)
|
||||
|
||||
field_region = published['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field_region = published['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
assert field_region['field_id'] == 'part-field'
|
||||
assert field_region['field_code'] == 'part_number'
|
||||
assert len(published['checksum']) == 64
|
||||
@@ -1006,6 +1410,9 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st
|
||||
checksum='c' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json={'fields': [
|
||||
dict(field) for field in source_schema.definition_json['fields']
|
||||
if field['field_id'] != 'part-field'
|
||||
] + [
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number',
|
||||
'scope': 'line', 'value_type': 'decimal', 'enabled': True,
|
||||
@@ -1030,7 +1437,7 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
assert field['field_id'] == 'replacement-field'
|
||||
assert field['field_code'] == 'supplier_part_number'
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
@@ -1059,6 +1466,7 @@ def test_schema_migration_preserves_unbound_order_field_region_and_blocks_publis
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page',
|
||||
'anchor': {'anchor_id': 'po_label', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
@@ -1380,7 +1788,9 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
user = User(username='preview-admin', email='preview-admin@example.com', role='admin', status='active')
|
||||
other_user = User(username='other-admin', email='other-admin@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.add(other_user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-PREVIEW-SAMPLE', owner_user_id=user.id, original_filename='preview.pdf',
|
||||
@@ -1410,7 +1820,6 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
'profile_code': 'PREVIEW_V2', 'display_name': 'Preview', 'schema_version_id': schema.id,
|
||||
'document_id': document.id, 'definition': _coordinate_definition(),
|
||||
}, actor_id=user.id)
|
||||
db.session.commit()
|
||||
document_id = document.id
|
||||
profile_id = draft['id']
|
||||
|
||||
@@ -1460,6 +1869,63 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
assert candidates.status_code == 200
|
||||
assert 'html' not in str(parse_api_data(candidates.get_json()))
|
||||
|
||||
# 坐标模板与 XFA 必须共用原 PDF + PDF.js 的受控画布入口;模板类型不得扩大样本读取范围。
|
||||
raw_coordinate_authorized = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
json={'document_id': document_id}, headers=headers,
|
||||
)
|
||||
assert raw_coordinate_authorized.status_code == 200
|
||||
raw_coordinate_grant = parse_api_data(raw_coordinate_authorized.get_json())
|
||||
assert 'storage_bucket' not in str(raw_coordinate_grant) and 'storage_key' not in str(raw_coordinate_grant)
|
||||
raw_coordinate_pdf = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
query_string={'preview_token': raw_coordinate_grant['preview_token']}, headers=headers,
|
||||
)
|
||||
assert raw_coordinate_pdf.status_code == 200
|
||||
assert raw_coordinate_pdf.mimetype == 'application/pdf'
|
||||
assert raw_coordinate_pdf.data == b'%PDF-preview'
|
||||
assert raw_coordinate_pdf.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
profile.template_mode = 'xfa_dataset'
|
||||
db.session.commit()
|
||||
|
||||
# XFA 编辑画布也必须复用同一受控入口,不得恢复格式专属预览路由。
|
||||
raw_authorized = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
json={'document_id': document_id}, headers=headers,
|
||||
)
|
||||
assert raw_authorized.status_code == 200
|
||||
assert raw_authorized.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
raw_grant = parse_api_data(raw_authorized.get_json())
|
||||
assert 'storage_bucket' not in str(raw_grant) and 'storage_key' not in str(raw_grant)
|
||||
foreign = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']},
|
||||
headers={'X-Username': 'other-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert foreign.status_code == 404
|
||||
raw_authorized = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
json={'document_id': document_id}, headers=headers,
|
||||
)
|
||||
raw_grant = parse_api_data(raw_authorized.get_json())
|
||||
raw_pdf = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']}, headers=headers,
|
||||
)
|
||||
assert raw_pdf.status_code == 200
|
||||
assert raw_pdf.mimetype == 'application/pdf'
|
||||
assert raw_pdf.data == b'%PDF-preview'
|
||||
assert raw_pdf.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
assert b'private-bucket' not in raw_pdf.data and b'internal/preview.pdf' not in raw_pdf.data
|
||||
raw_replay = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']}, headers=headers,
|
||||
)
|
||||
assert raw_replay.status_code == 404
|
||||
|
||||
|
||||
def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, monkeypatch):
|
||||
"""预览授权依赖 Redis 且只能读取 Profile 已绑定样本,不能降级为进程内或任意文档读取。"""
|
||||
@@ -1534,6 +2000,7 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke
|
||||
definition = _coordinate_definition()
|
||||
definition['table_regions'][0]['line_layouts'][0]['field_regions'] = [{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}]
|
||||
@@ -1606,6 +2073,7 @@ def test_coordinate_profile_exact_pages_allow_same_geometry_and_preview_only_cur
|
||||
table_region['line_layouts'][0]['layout_id'] = f'line_{page_no}_1'
|
||||
table_region['line_layouts'][0]['field_regions'] = [{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0 if page_no == 1 else .5, 'y0': 0, 'x1': .5 if page_no == 1 else 1, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}]
|
||||
@@ -2016,12 +2484,14 @@ def test_workbench_minimum_v2_definition_can_be_saved(app):
|
||||
'line_layouts': [{'layout_id': 'main_line', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': .16, 'y0': .30, 'x1': .72, 'y1': .50},
|
||||
'field_regions': [
|
||||
{'field_id': '', 'field_code': 'customer_po_line_no',
|
||||
'region': {'x0': .16, 'y0': .36, 'x1': .28, 'y1': .42},
|
||||
{'field_id': '', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': .16, 'y0': .36, 'x1': .28, 'y1': .42},
|
||||
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate'},
|
||||
{'field_id': '', 'field_code': 'part_number',
|
||||
'region': {'x0': .30, 'y0': .36, 'x1': .44, 'y1': .42},
|
||||
{'field_id': '', 'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'region': {'x0': .30, 'y0': .36, 'x1': .44, 'y1': .42},
|
||||
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate'},
|
||||
],
|
||||
|
||||
@@ -98,3 +98,61 @@ def test_shipping_order_extraction_run_migration_round_trip():
|
||||
}
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def test_parallel_pdf_reparse_migration_replaces_active_intake_uniqueness():
|
||||
"""同一 EML 的不同 PDF 子 Run 必须能共用活动 Intake,回滚后恢复旧唯一约束。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
members = sa.Table(
|
||||
'shipping_order_processing_run_intakes',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('run_id', sa.Integer(), nullable=False),
|
||||
sa.Column('intake_id', sa.Integer(), nullable=False),
|
||||
sa.Column('position', sa.Integer(), nullable=False),
|
||||
sa.Column('released_at', sa.DateTime(), nullable=True),
|
||||
)
|
||||
sa.Index(
|
||||
'uq_shipping_order_processing_run_intakes_active_intake',
|
||||
members.c.intake_id,
|
||||
unique=True,
|
||||
sqlite_where=members.c.released_at.is_(None),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.hj4k5l6m7n8o_allow_parallel_pdf_reparse_runs'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
indexes = {
|
||||
index['name']: index
|
||||
for index in sa.inspect(connection).get_indexes('shipping_order_processing_run_intakes')
|
||||
}
|
||||
assert indexes['ix_shipping_order_processing_run_intakes_active_intake']['unique'] == 0
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_order_processing_run_intakes "
|
||||
"(id, run_id, intake_id, position) VALUES "
|
||||
"(1, 1, 9, 0), (2, 2, 9, 0)"
|
||||
))
|
||||
|
||||
try:
|
||||
migration.downgrade()
|
||||
raise AssertionError('downgrade must reject active parallel PDF reparses')
|
||||
except RuntimeError as exc:
|
||||
assert 'parallel PDF reparses' in str(exc)
|
||||
connection.execute(sa.text(
|
||||
"UPDATE shipping_order_processing_run_intakes "
|
||||
"SET released_at = CURRENT_TIMESTAMP WHERE id = 2"
|
||||
))
|
||||
migration.downgrade()
|
||||
indexes = {
|
||||
index['name']: index
|
||||
for index in sa.inspect(connection).get_indexes('shipping_order_processing_run_intakes')
|
||||
}
|
||||
assert indexes['uq_shipping_order_processing_run_intakes_active_intake']['unique'] == 1
|
||||
finally:
|
||||
migration.op = original_op
|
||||
@@ -8,7 +8,9 @@ backend/tests/test_shipping_order_extraction_runs.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
@@ -52,8 +54,10 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
resume_runs_waiting_for_layout,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
order_extraction_layouts_failed,
|
||||
materialize_order_extraction_run_inputs,
|
||||
serialize_order_extraction_message_state,
|
||||
serialize_order_extraction_run,
|
||||
synchronize_order_extraction_expansion_snapshot,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.jobs.queue import fail_job
|
||||
@@ -70,6 +74,7 @@ from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_apply_reparse_profile_affinity,
|
||||
route_deterministic_unit,
|
||||
)
|
||||
from app.services.shipping_notice.document_candidate_persist import _json_safe_value
|
||||
from tests.test_shipping_notice_order_extraction import _ensure_order_schema, _order
|
||||
|
||||
|
||||
@@ -92,6 +97,24 @@ def _seed_run_with_plan(*, suffix: str = 'A', agent_code: str = 'shipping_notice
|
||||
return user, agent, session, intake, document, run, reused
|
||||
|
||||
|
||||
def test_document_json_payload_normalizes_dynamic_date_and_decimal_values(app):
|
||||
"""Document JSON 写回前,动态 Schema 结果必须只含 JSON 原生值。"""
|
||||
with app.app_context():
|
||||
payload = _json_safe_value({
|
||||
'email_supplement': {
|
||||
'rows': [{
|
||||
'order_date': date(2026, 8, 14),
|
||||
'allocated_qty': Decimal('12.5000'),
|
||||
'evidence': [{'raw_value': '2026-08-14'}],
|
||||
}],
|
||||
},
|
||||
})
|
||||
|
||||
assert payload['email_supplement']['rows'][0]['order_date'] == '2026-08-14'
|
||||
assert payload['email_supplement']['rows'][0]['allocated_qty'] == '12.5000'
|
||||
assert json.loads(json.dumps(payload)) == payload
|
||||
|
||||
|
||||
def test_route_decision_is_immutable_per_unit_job_attempt_and_cascades_with_run(app):
|
||||
"""路由审计按尝试追加;同一尝试不可覆盖,删除 Run 时随其级联删除。"""
|
||||
with app.app_context():
|
||||
@@ -311,10 +334,84 @@ def test_create_run_reparses_empty_email_supplement_from_frozen_html_tables(app)
|
||||
)
|
||||
|
||||
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
|
||||
assert body['email_supplement']['rows'][0]['po_number'] == '4518838154'
|
||||
assert body['email_supplement']['rows'][0]['customer_po_number'] == '4518838154'
|
||||
assert body['email_supplement']['rows'][0]['reservation_id'] == '4000111701'
|
||||
|
||||
|
||||
def test_create_run_serializes_date_values_in_frozen_email_supplement(app):
|
||||
"""邮件补充日期必须以 JSON 原生字符串冻结,避免重解析 Run 在首次 flush 时失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='EMAIL-DATE')
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
schema.definition_json = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#']},
|
||||
{'field_id': 'date', 'field_code': 'order_date', 'scope': 'header', 'value_type': 'date', 'aliases': ['Order Date']},
|
||||
]}
|
||||
intake.structured_result_json = {
|
||||
'email': {'body_html_tables': ['''<table><tr><th>PO#</th><th>Order Date</th></tr><tr><td>4518838154</td><td>2026-08-13</td></tr></table>''']},
|
||||
}
|
||||
db.session.add(ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='__email_body__',
|
||||
filename='email-body.html',
|
||||
content_hash='f' * 64,
|
||||
classification='email_context',
|
||||
parse_status='parsed',
|
||||
extracted_text='Order Date 2026-08-13',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
|
||||
assert body['email_supplement']['rows'][0]['order_date'] == '2026-08-13'
|
||||
assert json.loads(json.dumps(run.input_snapshot_json)) == run.input_snapshot_json
|
||||
assert reused is False
|
||||
|
||||
|
||||
def test_materialize_run_serializes_date_values_from_email_supplement(app):
|
||||
"""Worker 物化正文日期时必须先转为 JSON 原生字符串,避免更新 Run 快照失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='EMAIL-DATE-MATERIALIZE')
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
schema.definition_json = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#']},
|
||||
{'field_id': 'date', 'field_code': 'order_date', 'scope': 'header', 'value_type': 'date', 'aliases': ['Order Date']},
|
||||
]}
|
||||
db.session.commit()
|
||||
|
||||
# 创建时没有正文补充表;真实 Worker 随后物化附件时才会重新解析该表。
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
intake.structured_result_json = {
|
||||
'email': {'body_html_tables': ['''<table><tr><th>PO#</th><th>Order Date</th></tr><tr><td>4518838154</td><td>2026-08-13</td></tr></table>''']},
|
||||
}
|
||||
db.session.add(ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='__email_body__',
|
||||
filename='email-body.html',
|
||||
content_hash='d' * 64,
|
||||
classification='email_context',
|
||||
parse_status='parsed',
|
||||
extracted_text='Order Date 2026-08-13',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
# 物化 I/O 已由其他用例覆盖;此处仅验证 Worker 重建快照后的 JSON 写入边界。
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents'):
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
|
||||
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
|
||||
assert body['email_supplement']['rows'][0]['order_date'] == '2026-08-13'
|
||||
assert json.loads(json.dumps(run.input_snapshot_json)) == run.input_snapshot_json
|
||||
|
||||
|
||||
def test_create_run_reparses_partial_email_supplement_from_frozen_html_tables(app):
|
||||
"""历史正文已有部分行时,Run 仍须按冻结 Schema 重建新增的预约号列。"""
|
||||
with app.app_context():
|
||||
@@ -408,6 +505,30 @@ def test_worker_rematerializes_a_legacy_empty_plan(app):
|
||||
assert ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).count() == 1
|
||||
|
||||
|
||||
def test_rematerialization_syncs_existing_plan_snapshot_hash_after_layout_refresh(app):
|
||||
"""重试刷新布局证据后,既有 Plan 必须跟随同一 Run 快照哈希更新。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='PLAN-HASH-SYNC')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
plan = ensure_order_extraction_plan(run)
|
||||
original_hash = plan.input_snapshot_hash
|
||||
snapshot = dict(run.input_snapshot_json or {})
|
||||
snapshot['layout_refresh_marker'] = 'retry-1'
|
||||
run.input_snapshot_json = snapshot
|
||||
run.input_snapshot_hash = 'b' * 64
|
||||
db.session.commit()
|
||||
|
||||
refreshed = materialize_order_extraction_run_inputs(run)
|
||||
|
||||
assert refreshed is not None
|
||||
assert refreshed.id == plan.id
|
||||
assert refreshed.input_snapshot_hash == run.input_snapshot_hash
|
||||
assert refreshed.input_snapshot_hash != original_hash
|
||||
|
||||
|
||||
def test_create_run_rejects_an_intake_from_another_upload_batch(app):
|
||||
"""服务端必须拒绝伪造的跨批次 Intake 清单,不能依赖前端筛选。"""
|
||||
with app.app_context():
|
||||
@@ -1185,6 +1306,76 @@ def test_plan_can_append_future_selection_batch_units_idempotently(app):
|
||||
assert ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).count() == 2
|
||||
|
||||
|
||||
def test_expansion_batch_syncs_materialized_document_into_frozen_run_before_creating_unit(app):
|
||||
"""扩批附件必须先进入 Run 快照并同步 Plan 哈希,Worker 才能定位新增 Unit。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first_document = _seed_run_input(suffix='BATCH-SNAPSHOT')
|
||||
first_document.attachment_key = 'att-1'
|
||||
second_document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='att-2',
|
||||
filename='orders-batch-snapshot.pdf',
|
||||
content_hash='e' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 451883817 BATCH SNAPSHOT',
|
||||
)
|
||||
db.session.add(second_document)
|
||||
db.session.flush()
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
run = ShippingOrderProcessingRun(
|
||||
run_no='SNER-BATCH-SNAPSHOT',
|
||||
user_id=user.id,
|
||||
owner_agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=schema_version.id,
|
||||
input_snapshot_hash='f' * 64,
|
||||
idempotency_key='batch-snapshot-idempotency',
|
||||
input_snapshot_json={
|
||||
'snapshot_version': 3,
|
||||
'schema': {'definition': schema_version.definition_json, 'checksum': schema_version.checksum},
|
||||
'intakes': [{
|
||||
'intake_id': intake.id,
|
||||
'intake_no': intake.intake_no,
|
||||
'documents': [{
|
||||
'document_id': first_document.id,
|
||||
'document_type': first_document.document_type,
|
||||
'attachment_key': 'att-1',
|
||||
'content_hash': first_document.content_hash,
|
||||
}],
|
||||
}],
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{'intake_no': intake.intake_no, 'attachment_key': 'att-1', 'selected': True, 'selection_batch': 1},
|
||||
{'intake_no': intake.intake_no, 'attachment_key': 'att-2', 'selected': False, 'planned_selection_batch': 2},
|
||||
],
|
||||
},
|
||||
},
|
||||
status='queued',
|
||||
phase='queued',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderProcessingRunIntake(run_id=run.id, intake_id=intake.id, position=0))
|
||||
plan = ensure_order_extraction_plan(run)
|
||||
old_hash = str(run.input_snapshot_hash)
|
||||
|
||||
synchronize_order_extraction_expansion_snapshot(run, selection_batch=2)
|
||||
created = ensure_order_extraction_plan_batch(run, selection_batch=2)
|
||||
db.session.commit()
|
||||
|
||||
snapshot_document_ids = {
|
||||
int(document['document_id'])
|
||||
for snapshot_intake in run.input_snapshot_json['intakes']
|
||||
for document in snapshot_intake['documents']
|
||||
}
|
||||
assert int(second_document.id) in snapshot_document_ids
|
||||
assert run.input_snapshot_hash != old_hash
|
||||
assert plan.input_snapshot_hash == run.input_snapshot_hash
|
||||
assert [unit.document_id for unit in created] == [second_document.id]
|
||||
|
||||
|
||||
def test_run_submission_rejects_changed_frozen_mail_context(app):
|
||||
"""Run 创建后 EML From 变化必须触发来源漂移,不能以当前 Intake 覆盖冻结审计事实。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.jobs.handlers.shipping_order_extraction import (
|
||||
_pending_snapshot_batches,
|
||||
_process_unit_with_retries,
|
||||
_result_requires_review,
|
||||
_should_activate_planned_batches,
|
||||
_should_expand_after_wave,
|
||||
_units_for_batch,
|
||||
)
|
||||
@@ -474,6 +475,12 @@ def test_should_expand_after_wave_when_current_wave_needs_more_evidence():
|
||||
) is False
|
||||
|
||||
|
||||
def test_planned_attachment_batch_activates_without_sibling_field_gate():
|
||||
"""计划内附件必须独立消费,首轮字段完整与否不得阻止下一批激活。"""
|
||||
assert _should_activate_planned_batches(pending_batches=[2]) is True
|
||||
assert _should_activate_planned_batches(pending_batches=[]) is False
|
||||
|
||||
|
||||
def test_auto_freeze_blocked_task_requires_run_review():
|
||||
"""自动冻结的 Task 级门禁拒绝必须把 Run 收口为需人工处理,而非 completed。"""
|
||||
assert _result_requires_review(
|
||||
|
||||
@@ -37,7 +37,10 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
cancellation_actor_id=None,
|
||||
cancellation_reason=None,
|
||||
cancellation_reason_code=None,
|
||||
id=None,
|
||||
run_no='OER-TEST',
|
||||
reparse_source=None,
|
||||
superseding_run=None,
|
||||
auto_freeze_policy_json=None,
|
||||
review_cases=[],
|
||||
)
|
||||
@@ -81,6 +84,8 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
assert result['currentActivity']['reasonCodes'] == ['budget_initial_limit', 'required_field_missing']
|
||||
assert result['currentActivity']['userVisibleStage'] == 'extracting'
|
||||
assert result['status'] == 'processing'
|
||||
# 聊天状态投影在 Worker 开始处理时必须可序列化,且不能误标记为终态。
|
||||
assert result['terminal'] is False
|
||||
assert result['handlingItems'] == []
|
||||
assert result['primaryNotice'] is None
|
||||
|
||||
@@ -149,7 +154,9 @@ def test_build_handling_items_splits_pending_freeze_review_and_failure():
|
||||
assert 'candidate_missing_info' in categories
|
||||
assert 'candidate_conflict' in categories
|
||||
assert 'auto_freeze_blocked' in categories
|
||||
assert 'budget_stopped' in categories
|
||||
# 未提供受限文件引用时,预算停扩只能作为 Run 历史上下文,不能伪造一个
|
||||
# 文件级处理事项参与统计;否则同一 PDF 会被多类事项重复相加。
|
||||
assert 'budget_stopped' not in categories
|
||||
assert items[0]['primary_action'] == 'retry_failed_attachments'
|
||||
missing = next(item for item in items if item['category'] == 'candidate_missing_info')
|
||||
assert missing['primary_action'] == 'review_candidate'
|
||||
@@ -189,6 +196,233 @@ def test_build_handling_items_budget_stopped_includes_attachment_refs():
|
||||
assert budget['affected_refs'][0]['document_id'] == 42
|
||||
|
||||
|
||||
def test_build_handling_items_counts_one_document_in_only_one_primary_category():
|
||||
"""同一 PDF 同时存在解析复核、候选待补和预算原因时,只能计入最高优先级事项。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
result_json={
|
||||
'pending_count': 1,
|
||||
'pending_orders': [{
|
||||
'candidate_no': 'C-9',
|
||||
'po_number': 'PO-9',
|
||||
'document_id': 99,
|
||||
'reasons': ['required_field_missing'],
|
||||
'missing_fields': ['qty'],
|
||||
}],
|
||||
'budget_stopped': True,
|
||||
},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [{
|
||||
'selected': False,
|
||||
'filename': 'same.pdf',
|
||||
'document_id': 99,
|
||||
'skip_reason_codes': ['budget_initial_limit'],
|
||||
}],
|
||||
},
|
||||
},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
units = [SimpleNamespace(
|
||||
id=9,
|
||||
document_id=99,
|
||||
status='review_required',
|
||||
reason_code='row_needs_review',
|
||||
technical_failure_reason_code=None,
|
||||
)]
|
||||
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['document_review']
|
||||
assert items[0]['count'] == 1
|
||||
|
||||
|
||||
def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id():
|
||||
"""预算快照仅保留哈希时,仍不得把同一 PDF 与复核事项重复统计。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
result_json={'budget_stopped': True, 'pending_count': 0},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [{
|
||||
'selected': False,
|
||||
'filename': 'same.pdf',
|
||||
# 历史预算计划可能没有 document_id,但保留了冻结时的内容哈希。
|
||||
'content_hash': 'same-content-hash',
|
||||
'skip_reason_codes': ['budget_initial_limit'],
|
||||
}],
|
||||
},
|
||||
},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
units = [SimpleNamespace(
|
||||
id=10,
|
||||
document_id=100,
|
||||
content_hash='same-content-hash',
|
||||
status='review_required',
|
||||
reason_code='row_needs_review',
|
||||
technical_failure_reason_code=None,
|
||||
)]
|
||||
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
|
||||
# 文档复核优先级更高;预算原因可作为解释存在,但不能再增加第二个文件计数。
|
||||
assert [item['category'] for item in items] == ['document_review']
|
||||
assert items[0]['count'] == 1
|
||||
|
||||
|
||||
def test_build_handling_items_keeps_unclaimed_candidate_ready_unit_as_confirmation():
|
||||
"""没有 pending_orders 时,候选就绪文件仍应稳定生成唯一待确认事项。"""
|
||||
run = SimpleNamespace(
|
||||
status='review_required',
|
||||
result_json={'pending_count': 1},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
units = [SimpleNamespace(
|
||||
id=12,
|
||||
document_id=120,
|
||||
content_hash='candidate-ready-hash',
|
||||
status='candidate_ready',
|
||||
reason_code=None,
|
||||
technical_failure_reason_code=None,
|
||||
)]
|
||||
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['candidate_confirmation']
|
||||
assert items[0]['count'] == 1
|
||||
assert items[0]['affected_refs'][0]['document_id'] == 120
|
||||
|
||||
|
||||
def test_build_handling_items_deduplicates_confirmation_candidates_by_document():
|
||||
"""同一 PDF 的多个仅待确认 Candidate 只能统计为一个文件待办。"""
|
||||
run = SimpleNamespace(
|
||||
status='review_required',
|
||||
result_json={
|
||||
'pending_count': 2,
|
||||
'pending_orders': [
|
||||
{
|
||||
'candidate_no': 'C-SAME-1',
|
||||
'po_number': 'PO-SAME-1',
|
||||
'document_id': 101,
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
},
|
||||
{
|
||||
'candidate_no': 'C-SAME-2',
|
||||
'po_number': 'PO-SAME-2',
|
||||
'document_id': 101,
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
},
|
||||
],
|
||||
},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
|
||||
items = build_handling_items(run, [], open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['candidate_confirmation']
|
||||
assert items[0]['count'] == 1
|
||||
assert items[0]['affected_refs'] == [{
|
||||
'type': 'candidate',
|
||||
'candidate_no': 'C-SAME-1',
|
||||
'po_number': 'PO-SAME-1',
|
||||
'document_id': 101,
|
||||
}]
|
||||
|
||||
|
||||
def test_build_handling_items_keeps_confirmation_for_other_document_after_conflict():
|
||||
"""某 PDF 冲突时,其他 PDF 的待确认事项仍须保留且互不重复计数。"""
|
||||
run = SimpleNamespace(
|
||||
status='review_required',
|
||||
result_json={
|
||||
'pending_count': 2,
|
||||
'pending_orders': [
|
||||
{
|
||||
'candidate_no': 'C-CONFLICT',
|
||||
'po_number': 'PO-CONFLICT',
|
||||
'document_id': 201,
|
||||
'reasons': ['email_supplement_conflict'],
|
||||
'missing_fields': [],
|
||||
},
|
||||
{
|
||||
'candidate_no': 'C-CONFIRM',
|
||||
'po_number': 'PO-CONFIRM',
|
||||
'document_id': 202,
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
},
|
||||
],
|
||||
},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
|
||||
items = build_handling_items(run, [], open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == [
|
||||
'candidate_conflict', 'candidate_confirmation',
|
||||
]
|
||||
assert [item['count'] for item in items] == [1, 1]
|
||||
assert items[1]['affected_refs'][0]['document_id'] == 202
|
||||
|
||||
|
||||
def test_build_handling_items_claims_all_documents_before_limiting_refs():
|
||||
"""超过展示上限时,同一 PDF 仍只能归入一个最高优先级处理事项。"""
|
||||
pending_orders = [
|
||||
{
|
||||
'candidate_no': f'C-CONFLICT-{document_id}',
|
||||
'po_number': f'PO-{document_id}',
|
||||
'document_id': document_id,
|
||||
'reasons': ['email_supplement_conflict'],
|
||||
'missing_fields': [],
|
||||
}
|
||||
for document_id in range(1, 12)
|
||||
]
|
||||
# 第 11 份 PDF 同时带有低优先级的待确认记录;截断前认领才能防止重复。
|
||||
pending_orders.append({
|
||||
'candidate_no': 'C-DUPLICATE-11',
|
||||
'po_number': 'PO-11',
|
||||
'document_id': 11,
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
})
|
||||
run = SimpleNamespace(
|
||||
status='review_required',
|
||||
result_json={'pending_count': len(pending_orders), 'pending_orders': pending_orders},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
|
||||
items = build_handling_items(run, [], open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['candidate_conflict']
|
||||
# 统计使用全量互斥文件集合,affected_refs 仅为最多 20 条的展示样本。
|
||||
assert items[0]['count'] == 11
|
||||
assert len(items[0]['affected_refs']) == 11
|
||||
|
||||
|
||||
def test_planned_documents_inherit_failed_run_status_before_units_exist():
|
||||
"""Job 在 Unit 物化前失败时,右侧每份 PDF 必须显示失败而非处理中。"""
|
||||
run = SimpleNamespace(
|
||||
|
||||
@@ -335,6 +335,38 @@ def test_profile_matcher_compares_header_inside_table_not_page_header():
|
||||
assert candidate.dimension_scores.header_semantic_position >= 0.75
|
||||
|
||||
|
||||
def test_profile_matcher_selects_signature_main_table_when_metadata_table_precedes_it():
|
||||
"""运行时须按签名表区选择明细表,不能将前置抬头表误作主表。"""
|
||||
layout = _layout('PLANT NAME: FACTORY A')
|
||||
main_header = 'ITEM NO MATERIAL NO REV MATERIAL DESCRIPTION UNIT PRICE ORDER QUANTITY ORDER AMOUNT'
|
||||
main_glyphs = [
|
||||
{
|
||||
'text': char,
|
||||
'bbox': {'x0': 10 + index * 4, 'y0': 145, 'x1': 13 + index * 4, 'y1': 157},
|
||||
'boundary_before': 'space' if index and main_header[index - 1] == ' ' else 'none',
|
||||
}
|
||||
for index, char in enumerate(main_header)
|
||||
if char != ' '
|
||||
]
|
||||
layout['tables'] = [
|
||||
{'table_id': 'metadata', 'page_no': 1, 'bbox': {'x0': 0.05, 'y0': 0.10, 'x1': 0.95, 'y1': 0.35}},
|
||||
{'table_id': 'line-items', 'page_no': 1, 'bbox': {'x0': 0.05, 'y0': 0.50, 'x1': 0.95, 'y1': 0.95}},
|
||||
]
|
||||
layout['coordinate_evidence']['tables'] = {'metadata': [], 'line-items': main_glyphs}
|
||||
layout['coordinate_evidence']['page_glyphs']['1'].extend(main_glyphs)
|
||||
profile = _profile('PO_A')
|
||||
main_region = {'x0': 0.05, 'y0': 0.50, 'x1': 0.95, 'y1': 0.95}
|
||||
profile['definition']['table_regions'][0]['region'] = main_region
|
||||
profile['definition']['table_regions'][0]['line_layouts'][0]['region'] = main_region
|
||||
profile = _with_signature(profile, layout)
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
|
||||
|
||||
assert result.status == 'unique_match'
|
||||
assert result.candidates[0].dimension_scores.header_semantic_position >= 0.75
|
||||
assert result.candidates[0].dimension_scores.column_topology >= 0.75
|
||||
|
||||
|
||||
def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness():
|
||||
"""硬门禁通过但得分或证据覆盖不合格的候选,不得阻塞唯一合格模板。"""
|
||||
layout = _layout('PLANT NAME: FACTORY A')
|
||||
@@ -348,3 +380,35 @@ def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness
|
||||
|
||||
assert result.status == 'unique_match'
|
||||
assert result.profile_code == 'PO_QUALIFIED'
|
||||
|
||||
|
||||
def test_parse_validation_does_not_upgrade_ineligible_profile_to_unique_match(monkeypatch):
|
||||
"""解析可用性只能验证已通过匹配资格门禁的模板,不能绕过评分和证据覆盖。"""
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
ProfileMatchCandidate,
|
||||
ProfileMatchResult,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workflow import _apply_parse_validation_gate
|
||||
|
||||
profile = _with_signature(_profile('PO_INELIGIBLE', score=.95), _layout())
|
||||
profile['definition']['document_match']['scoring_thresholds']['evidence_coverage_minimum'] = 0.95
|
||||
match = ProfileMatchResult(
|
||||
status='no_match',
|
||||
candidates=[ProfileMatchCandidate(
|
||||
profile_code='PO_INELIGIBLE', version=1, score=.96,
|
||||
evidence_coverage=.60, hard_match=True,
|
||||
)],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow.validate_profile_parse_candidate',
|
||||
lambda **_: {'passed': True, 'reason_codes': [], 'metrics': {}},
|
||||
)
|
||||
|
||||
result = _apply_parse_validation_gate(
|
||||
match=match,
|
||||
coordinate_profiles=[profile],
|
||||
layout=_layout(),
|
||||
definition={},
|
||||
)
|
||||
|
||||
assert result.status == 'no_match'
|
||||
@@ -9,10 +9,14 @@ tests/test_shipping_order_review_field_conflict.py
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.order_review_field_conflict_service import (
|
||||
project_review_case_evidence_issues,
|
||||
project_review_case_field_conflicts,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import _sync_review_gates_safe
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
|
||||
def test_project_review_case_field_conflicts_builds_stable_keys():
|
||||
@@ -88,3 +92,117 @@ def test_project_review_case_field_conflicts_empty_without_candidate():
|
||||
"""无 Candidate 时投影为空列表。"""
|
||||
case = SimpleNamespace(candidate_id=None, current_draft=None)
|
||||
assert project_review_case_field_conflicts(case) == []
|
||||
|
||||
|
||||
def test_project_review_findings_deduplicate_evidence_gaps_and_keep_them_out_of_value_conflicts():
|
||||
"""同键证据缺失只能保留一项,并与多值字段冲突分区展示。"""
|
||||
candidate = SimpleNamespace(
|
||||
conflicts_json=[
|
||||
{
|
||||
'field': 'reservation_id',
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
},
|
||||
{
|
||||
'field': 'reservation_id',
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
},
|
||||
{
|
||||
'field': 'part_number',
|
||||
'line_index': 0,
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
},
|
||||
{
|
||||
'field': 'qty',
|
||||
'line_index': 0,
|
||||
'severity': 'blocking',
|
||||
'reason': 'field_conflict',
|
||||
'values': ['10', '12'],
|
||||
},
|
||||
],
|
||||
structured_result_json={},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
candidate_id=1,
|
||||
current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]),
|
||||
)
|
||||
|
||||
from app.services.shipping_notice import order_review_field_conflict_service as svc
|
||||
|
||||
original = svc._candidate_for_case
|
||||
svc._candidate_for_case = lambda _case: candidate
|
||||
try:
|
||||
items = project_review_case_field_conflicts(case)
|
||||
finally:
|
||||
svc._candidate_for_case = original
|
||||
|
||||
assert [item['conflict_key'] for item in items] == ['0:qty']
|
||||
|
||||
original = svc._candidate_for_case
|
||||
svc._candidate_for_case = lambda _case: candidate
|
||||
try:
|
||||
evidence_issues = project_review_case_evidence_issues(case)
|
||||
finally:
|
||||
svc._candidate_for_case = original
|
||||
|
||||
# 关键断言:同一预约单号证据缺失合并为一项,且不再伪装为待选值冲突。
|
||||
assert [(item['conflict_key'], item['reason']) for item in evidence_issues] == [
|
||||
('-1:reservation_id', 'evidence_missing'),
|
||||
('0:part_number', 'evidence_missing'),
|
||||
]
|
||||
assert [item['scope'] for item in evidence_issues] == ['unscoped', 'line']
|
||||
|
||||
|
||||
def test_sync_review_gates_replaces_stale_missing_field_gate_with_field_conflict():
|
||||
"""草稿字段已齐全时,Gate 必须通过完整性并把最新证据冲突归属到字段冲突门禁。"""
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-TEST',
|
||||
current_draft=SimpleNamespace(draft_version=9),
|
||||
)
|
||||
validation = {
|
||||
'assessment': {'missing_required_fields': [], 'invalid_lines': []},
|
||||
'failed_gates': ['field_conflicts_resolved'],
|
||||
'issues': [{
|
||||
'code': 'candidate_qualification_blocked',
|
||||
'reason_code': 'field_conflict',
|
||||
'owning_gate_code': 'field_conflict_resolution',
|
||||
'severity': 'auto_create_blocking',
|
||||
'field_code': None,
|
||||
'line_index': None,
|
||||
}],
|
||||
'line_projections': [],
|
||||
}
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_review_gate_for_case',
|
||||
) as sync_gate, patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_inventory_routing_gate_for_case',
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._candidate_conflict_locator',
|
||||
return_value={'field_code': 'part_number', 'line_index': 0},
|
||||
):
|
||||
_sync_review_gates_safe(case=case, user_id=7, validation=validation)
|
||||
|
||||
calls = {call.kwargs['gate_code']: call.kwargs for call in sync_gate.call_args_list}
|
||||
# 关键断言:旧 required_field_missing 不得滞留为当前阻断。
|
||||
assert calls['field_completeness']['passed'] is True
|
||||
# 关键断言:自动建单证据冲突必须带字段/行号成为用户可见的正式 Gate。
|
||||
assert calls['field_conflict_resolution']['passed'] is False
|
||||
assert calls['field_conflict_resolution']['blocking_reason_code'] == 'field_conflict'
|
||||
assert calls['field_conflict_resolution']['details']['field_code'] == 'part_number'
|
||||
assert calls['field_conflict_resolution']['details']['line_index'] == 0
|
||||
|
||||
|
||||
def test_not_found_error_preserves_stale_conflict_key_details():
|
||||
"""过期冲突操作必须返回可处理的 404 业务错误,不能因错误构造器再次抛出 TypeError。"""
|
||||
error = NotFoundError(
|
||||
'Field conflict not found',
|
||||
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
|
||||
details={'conflict_key': '-1:part_number'},
|
||||
)
|
||||
|
||||
# 关键断言:前端可据此识别“页面数据过期”并刷新,而非收到 500。
|
||||
assert error.http_status == 404
|
||||
assert error.details == {'conflict_key': '-1:part_number'}
|
||||
@@ -80,3 +80,10 @@ def test_project_review_case_profile_match_missing_route():
|
||||
payload = svc.project_review_case_profile_match(case)
|
||||
assert payload['available'] is False
|
||||
assert payload['status'] == 'unknown'
|
||||
|
||||
|
||||
def test_profile_display_name_never_falls_back_to_internal_code():
|
||||
"""冻结快照只有技术编号时,投影不得把编号伪装成用户模板名称。"""
|
||||
assert svc._resolve_profile_display_name(
|
||||
code='ODP-INTERNAL', version=0, display_map={('ODP-INTERNAL', 0): 'ODP-INTERNAL'},
|
||||
) is None
|
||||
File diff suppressed because it is too large.
Load diff
@@ -86,6 +86,18 @@ def test_text_normalizers_preserve_source_case_for_user_visible_values(normalize
|
||||
) == 'Inventec D4-A08AR12000002 USD'
|
||||
|
||||
|
||||
def test_date_normalizer_accepts_explicit_english_month_abbreviation():
|
||||
"""XFA datasets 与视觉样本均可将 07-Jul-2026 收敛为无歧义 ISO 日期。"""
|
||||
value = normalize_order_field_value(
|
||||
'07-Jul-2026',
|
||||
{'field_code': 'requested_receipt_date', 'value_type': 'date', 'normalizer_key': 'iso_date'},
|
||||
)
|
||||
|
||||
# 关键断言:英文月份缩写不是展示特例,正式 Schema date 值必须可供后续校验和比对。
|
||||
assert value.isoformat() == '2026-07-07'
|
||||
assert validate_order_field_value(value, {'value_type': 'date', 'validator_keys': ['iso_date']})
|
||||
|
||||
|
||||
def test_field_rules_accept_line_number_and_compute_effective_reservation():
|
||||
"""用户配置的项次可从原文写入;有效 Reservation 按行优先回退头,二者均可空。"""
|
||||
assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'}) == '00010'
|
||||
|
||||
@@ -15,6 +15,7 @@ from unittest.mock import patch
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
resolve_pre_confirm_stage,
|
||||
resolve_processing_stage_for_progress_event,
|
||||
sync_order_task_stage_for_notice,
|
||||
write_run_unified_processing_stage,
|
||||
)
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
@@ -183,3 +184,38 @@ def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage():
|
||||
assert result is order_task
|
||||
assert order_task.stage == 'inventory_matching'
|
||||
sync_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task_stage():
|
||||
"""正式 Execution 已进入库存准备时,同步不得把 OT 保留在 waiting_review。"""
|
||||
notice = SimpleNamespace(
|
||||
id=14,
|
||||
order_task_id=81,
|
||||
active_process_execution_id=92,
|
||||
current_step=None,
|
||||
upload_status=None,
|
||||
export_file_path=None,
|
||||
pending_human_reason=None,
|
||||
review_status=None,
|
||||
match_status=None,
|
||||
lifecycle_status='active',
|
||||
inventory_lines_json=None,
|
||||
)
|
||||
order_task = SimpleNamespace(stage='waiting_review', status='waiting_review')
|
||||
execution = SimpleNamespace(
|
||||
current_gate_code='inventory_preparation',
|
||||
status='waiting_external',
|
||||
)
|
||||
with patch('app.services.shipping_notice.order_task_stage_machine.db') as mock_db, patch(
|
||||
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state',
|
||||
) as sync_mock:
|
||||
mock_db.session.get.side_effect = [order_task, execution]
|
||||
sync_order_task_stage_for_notice(notice)
|
||||
|
||||
sync_mock.assert_called_once_with(
|
||||
order_task,
|
||||
stage='inventory_fetching',
|
||||
status='automating',
|
||||
reason_code='notice_fulfillment_sync',
|
||||
source='order_task_stage_machine',
|
||||
)
|
||||
@@ -0,0 +1,809 @@
|
||||
"""
|
||||
tests/test_shipping_pdf_automark.py
|
||||
|
||||
用途:验证统一 PDF 自动标记 Job 对不同 PDF 能力输出同一候选契约。
|
||||
依赖:order_document_profile_pdf_automark_service、pytest mock。
|
||||
逻辑:普通 PDF 复用坐标重建与 OCR 回退;XFA 复用多源融合执行器,但调用方不传类型。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.order_document_profile_pdf_automark_service import (
|
||||
_acroform_widget_candidates,
|
||||
_fuse_header_regions_with_column_geometry,
|
||||
enqueue_pdf_automark,
|
||||
execute_pdf_automark_job,
|
||||
)
|
||||
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_header_text_is_projected_onto_widget_column_geometry():
|
||||
"""表头文字与 Widget 列框融合后,画布必须得到可确认的每列表头框。"""
|
||||
geometry = {
|
||||
'table_region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .8},
|
||||
'subrow_layouts': [{'column_boundaries': [0, .2, .7, 1]}],
|
||||
'header_regions': [],
|
||||
}
|
||||
text = {
|
||||
'header_regions': [{
|
||||
'text': 'ITEM PARTS & DESCRIPTION QTY',
|
||||
'region': {'x0': .1, 'y0': .22, 'x1': .9, 'y1': .28},
|
||||
'fields': [
|
||||
{'text': 'ITEM', 'field_code': 'line_no', 'region': {'x0': .11, 'y0': .22, 'x1': .18, 'y1': .28}},
|
||||
{'text': 'PARTS & DESCRIPTION', 'field_code': 'part_number', 'region': {'x0': .29, 'y0': .22, 'x1': .63, 'y1': .28}},
|
||||
{'text': 'QTY', 'field_code': 'quantity', 'region': {'x0': .76, 'y0': .22, 'x1': .82, 'y1': .28}},
|
||||
],
|
||||
}],
|
||||
}
|
||||
|
||||
fused = _fuse_header_regions_with_column_geometry(
|
||||
geometry, geometry_source='acroform_widget_geometry',
|
||||
text_reconstructions=[('pdf_coordinate', text)],
|
||||
)
|
||||
|
||||
fields = fused['header_regions'][0]['fields']
|
||||
assert [(item['text'], item['field_code'], item['region']) for item in fields] == [
|
||||
('ITEM', 'line_no', {'x0': .1, 'y0': .22, 'x1': .26, 'y1': .28}),
|
||||
('PARTS & DESCRIPTION', 'part_number', {'x0': .26, 'y0': .22, 'x1': .66, 'y1': .28}),
|
||||
('QTY', 'quantity', {'x0': .66, 'y0': .22, 'x1': .9, 'y1': .28}),
|
||||
]
|
||||
assert all(item['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate'] for item in fields)
|
||||
assert fields[0]['observations'] == [{
|
||||
'source': 'pdf_coordinate', 'text': 'ITEM', 'field_code': 'line_no',
|
||||
'region': {'x0': .11, 'y0': .22, 'x1': .18, 'y1': .28},
|
||||
}]
|
||||
|
||||
|
||||
def test_header_geometry_keeps_unmapped_text_unbound():
|
||||
"""视觉文字没有唯一 Schema 映射时只补框,禁止按列位置猜字段编码。"""
|
||||
geometry = {
|
||||
'table_region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .8},
|
||||
'subrow_layouts': [{'column_boundaries': [0, .5, 1]}],
|
||||
'header_regions': [],
|
||||
}
|
||||
text = {'header_regions': [{
|
||||
'region': {'x0': 0, 'y0': .22, 'x1': 1, 'y1': .28},
|
||||
'fields': [{'text': 'UNRECOGNIZED', 'field_code': None, 'region': {'x0': .1, 'y0': .22, 'x1': .4, 'y1': .28}}],
|
||||
}]}
|
||||
|
||||
fused = _fuse_header_regions_with_column_geometry(
|
||||
geometry, geometry_source='opencv_geometry', text_reconstructions=[('ocr_coordinate', text)],
|
||||
)
|
||||
|
||||
assert fused['header_regions'][0]['fields'][0]['field_code'] is None
|
||||
|
||||
|
||||
def test_enqueue_automark_requires_frozen_annotation_layout(monkeypatch):
|
||||
"""关键断言:自动标注不能在无冻结 Layout 的样本上生成可接受候选。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
|
||||
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
|
||||
monkeypatch.setattr(service.db.session, 'get', lambda model, ident: None)
|
||||
monkeypatch.setattr(
|
||||
service, 'ShippingOrderDocumentProfileSample',
|
||||
SimpleNamespace(id=SimpleNamespace(asc=lambda: None), query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(first=lambda: None),
|
||||
),
|
||||
)),
|
||||
)
|
||||
with pytest.raises(Exception) as caught:
|
||||
enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND'
|
||||
|
||||
|
||||
def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_changed(monkeypatch):
|
||||
"""关键断言:Layout 版本未变但内容快照已替换时,不能继续生成旧候选 Job。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
|
||||
annotation = SimpleNamespace(table_id='table-1', layout_version_id=88, layout_payload_checksum='a' * 64)
|
||||
document = SimpleNamespace(
|
||||
id=77,
|
||||
current_layout_version_id=88,
|
||||
current_layout_version=SimpleNamespace(payload_checksum='b' * 64),
|
||||
)
|
||||
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
|
||||
monkeypatch.setattr(
|
||||
service, 'ShippingOrderDocumentProfileSample',
|
||||
SimpleNamespace(id=SimpleNamespace(asc=lambda: None), query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(first=lambda: annotation),
|
||||
),
|
||||
)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
service.db.session,
|
||||
'get',
|
||||
lambda model, _ident: document if model is service.ShippingOrderDocument else None,
|
||||
)
|
||||
monkeypatch.setattr(service, 'enqueue', lambda *_args, **_kwargs: 9001)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1)
|
||||
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_execute_automark_rejects_job_after_document_layout_reparse(monkeypatch):
|
||||
"""关键断言:排队期间 Layout 重解析后,旧 Job 不得生成可被确认的视觉候选。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
|
||||
current_document = SimpleNamespace(id=77, current_layout_version_id=99)
|
||||
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
|
||||
monkeypatch.setattr(
|
||||
service.db.session,
|
||||
'get',
|
||||
lambda model, _ident: current_document if model is service.ShippingOrderDocument else None,
|
||||
)
|
||||
|
||||
with pytest.raises(service.PdfAutomarkError) as caught:
|
||||
execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
|
||||
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
|
||||
})
|
||||
|
||||
assert caught.value.error_code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE'
|
||||
|
||||
|
||||
def test_execute_automark_rejects_job_with_layout_checksum_mismatch(monkeypatch):
|
||||
"""关键断言:同一 Layout 版本但冻结快照 checksum 不一致时也必须失败关闭。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
|
||||
current_document = SimpleNamespace(
|
||||
id=77,
|
||||
current_layout_version_id=88,
|
||||
current_layout_version=SimpleNamespace(payload_checksum='b' * 64),
|
||||
)
|
||||
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
|
||||
monkeypatch.setattr(
|
||||
service.db.session,
|
||||
'get',
|
||||
lambda model, _ident: current_document if model is service.ShippingOrderDocument else None,
|
||||
)
|
||||
|
||||
with pytest.raises(service.PdfAutomarkError) as caught:
|
||||
execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
|
||||
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
|
||||
})
|
||||
|
||||
assert caught.value.error_code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE'
|
||||
|
||||
|
||||
def test_automark_handler_persists_layout_stale_code_for_workbench_recovery(monkeypatch):
|
||||
"""关键断言:Worker 必须原样持久化 Layout 失效码,供统一画布提示重新标记。"""
|
||||
from app.jobs.handlers import shipping_pdf_automark as handler
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
job = SimpleNamespace(id=9001, attempts=1, payload_json={
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
|
||||
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
|
||||
})
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _job_id: job)
|
||||
monkeypatch.setattr(
|
||||
service,
|
||||
'execute_pdf_automark_job',
|
||||
lambda _payload: (_ for _ in ()).throw(service.PdfAutomarkError(
|
||||
'layout changed',
|
||||
error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE',
|
||||
)),
|
||||
)
|
||||
failed: dict[str, object] = {}
|
||||
monkeypatch.setattr(handler, 'fail_job', lambda *_args, **kwargs: failed.update(kwargs))
|
||||
|
||||
handler.run_shipping_pdf_automark(SimpleNamespace(), {'job_id': 9001})
|
||||
|
||||
assert failed['retryable'] is False
|
||||
assert failed['result'] == {
|
||||
'status': 'failed',
|
||||
'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_opencv_reconstruction_projects_only_data_rows(monkeypatch):
|
||||
"""关键断言:冻结 Layout 的 header/summary 只能作证据,不能伪造成明细行。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
layout = {
|
||||
'layout_candidate': {
|
||||
'quality': {'issues': [{'code': 'native_pdf_cells_from_opencv_candidate'}]},
|
||||
'pages': [{
|
||||
'page_no': 1,
|
||||
'tables': [{
|
||||
'table_id': 'table-1',
|
||||
'normalized_bbox': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'rows': [
|
||||
{'row_index': 0, 'role': 'header', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .1}}]},
|
||||
{'row_index': 1, 'role': 'data', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .2}, 'text': 'A'}]},
|
||||
{'row_index': 2, 'role': 'summary', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'text': 'TOTAL'}]},
|
||||
],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._document_layout',
|
||||
lambda _document: layout,
|
||||
)
|
||||
monkeypatch.setattr(service.db.session, 'get', lambda model, ident: object())
|
||||
result = service._layout_opencv_reconstruction(document_id=77, table_id='table-1')
|
||||
assert result is not None
|
||||
assert [item['row_offset'] for item in result['subrow_layouts']] == [0]
|
||||
assert result['subrow_layouts'][0]['source_row_index'] == 1
|
||||
|
||||
|
||||
def test_coordinate_pdf_automark_retries_with_ocr_and_returns_candidates():
|
||||
"""关键断言:普通 PDF 在坐标不足时由统一 Job 触发 OCR 后仍返回 candidates[]。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
reconstruction = {'subrow_layouts': [{'row_offset': 0}], 'header_regions': []}
|
||||
fields = {'order_field_candidates': [], 'page_no': 1}
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [
|
||||
ValidationError('missing', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
|
||||
reconstruction,
|
||||
]
|
||||
coordinate.suggest_order_field_layouts.return_value = fields
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service',
|
||||
coordinate,
|
||||
create=True,
|
||||
):
|
||||
# execute 函数内部延迟导入,直接替换模块缓存中的服务对象。
|
||||
with patch.dict('sys.modules', {
|
||||
'app.services.shipping_notice.order_document_profile_service': coordinate,
|
||||
}):
|
||||
result = execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1', 'schema_version_id': 3, 'page_no': 1,
|
||||
})
|
||||
|
||||
assert result['kind'] == 'field_binding_candidates'
|
||||
assert [item['candidate_kind'] for item in result['candidates']] == ['table_reconstruction']
|
||||
assert result['diagnostics']['coordinate_reconstruction'] == reconstruction
|
||||
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
|
||||
document_id=77, table_id='table-1', actor_id=None, force_ocr=True,
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_reuses_the_shared_visual_executor():
|
||||
"""关键断言:XFA 只在确认后的正式值映射不同,自动标记仍走共享视觉执行器。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
|
||||
status='draft',
|
||||
)
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
|
||||
coordinate.suggest_order_field_layouts.return_value = {
|
||||
'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}],
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table'})
|
||||
|
||||
assert result['kind'] == 'field_binding_candidates'
|
||||
candidate = next(item for item in result['candidates'] if item['candidate_kind'] == 'field_binding')
|
||||
assert candidate['candidate_kind'] == 'field_binding'
|
||||
assert 'value_binding' not in candidate['binding']
|
||||
assert result['diagnostics']['coordinate_reconstruction'] == {'subrow_layouts': []}
|
||||
assert coordinate.suggest_coordinate_reconstruction.call_count == 2
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_keeps_header_candidates_when_visual_rows_need_review():
|
||||
"""关键断言:视觉行重建为空不能丢弃已识别的抬头框,结果必须留在 needs_review。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
|
||||
status='draft',
|
||||
)
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [
|
||||
ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID'),
|
||||
ValidationError('OCR rows unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
|
||||
]
|
||||
coordinate.suggest_order_field_layouts.return_value = {
|
||||
'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}],
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table', 'page_no': 1,
|
||||
})
|
||||
|
||||
assert result['status'] == 'needs_review'
|
||||
assert result['candidates'][0]['binding']['field_code'] == 'customer_po_no'
|
||||
assert result['candidates'][0]['needs_review'] is True
|
||||
assert result['diagnostics']['row_reconstruction']['error_code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_retries_invalid_native_rows_with_forced_ocr():
|
||||
"""关键断言:部分 native glyph 无法成行时,Job 必须强制 OCR 后再重建一次。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
|
||||
status='draft',
|
||||
)
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [
|
||||
ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID'),
|
||||
{'subrow_layouts': [{'row_offset': 0}], 'header_regions': []},
|
||||
]
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'page_no': 1, 'source': 'ocr_coordinate',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}]}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table', 'page_no': 1,
|
||||
})
|
||||
|
||||
# 自动标注只产生待确认的视觉候选;即使 OCR 已补全行框,也不能把 Job 结果标为可发布成功。
|
||||
assert result['status'] == 'needs_review'
|
||||
assert result['diagnostics']['coordinate_reconstruction']['subrow_layouts'] == [{'row_offset': 0}]
|
||||
# OCR 重建后的候选不能声称已有 native 佐证;来源必须忠实反映本次实际证据。
|
||||
assert result['candidates'][0]['evidence_sources'] == ['ocr_coordinate']
|
||||
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
|
||||
document_id=77, table_id='xfa-main-table', actor_id=None, force_ocr=True,
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_requires_the_frozen_visual_main_table():
|
||||
"""关键断言:XFA 也不能绕过统一视觉主表契约执行自动标注。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
|
||||
status='draft',
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
):
|
||||
with pytest.raises(Exception) as caught:
|
||||
execute_pdf_automark_job({'profile_id': 12, 'document_id': 77})
|
||||
|
||||
assert getattr(caught.value, 'error_code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_coordinate_pdf_automark_returns_the_same_field_binding_candidate_contract():
|
||||
"""关键断言:普通 PDF 也以 field_binding_candidates 返回,前端不按 PDF 类型分支保存。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
|
||||
coordinate.suggest_order_field_layouts.return_value = {
|
||||
'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}],
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1', 'page_no': 1})
|
||||
|
||||
assert result['kind'] == 'field_binding_candidates'
|
||||
candidate = next(item for item in result['candidates'] if item['candidate_kind'] == 'field_binding')
|
||||
assert candidate['candidate_kind'] == 'field_binding'
|
||||
assert candidate['binding']['field_id'] == 'f-po'
|
||||
# 自动标记只提出视觉框,最终值源由字段映射确认阶段选择。
|
||||
assert 'value_binding' not in candidate['binding']
|
||||
|
||||
|
||||
def test_automark_does_not_project_ambiguous_or_unavailable_fields_as_empty_boxes():
|
||||
"""关键断言:未得到唯一值框的字段只能留在诊断,不能成为画布可确认候选。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
candidates = service._visual_binding_candidates({
|
||||
'order_field_candidates': [
|
||||
{'field_id': 'ambiguous', 'field_code': 'customer_po_no', 'status': 'ambiguous'},
|
||||
{'field_id': 'unavailable', 'field_code': 'order_date', 'status': 'unavailable'},
|
||||
{
|
||||
'field_id': 'suggested', 'field_code': 'currency', 'status': 'suggested',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
},
|
||||
],
|
||||
}, page_no=1)
|
||||
|
||||
assert [item['binding']['field_code'] for item in candidates] == ['currency']
|
||||
assert candidates[0]['binding']['visual_binding']['normalized_bbox'] == {
|
||||
'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4,
|
||||
}
|
||||
|
||||
|
||||
def test_automark_diagnostics_do_not_claim_unobserved_ocr_or_native_evidence():
|
||||
"""关键断言:诊断只能列出实际候选来源,不能把可用的回退能力写成已取到的证据。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
|
||||
coordinate.suggest_order_field_layouts.return_value = {
|
||||
'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'source': 'pdf_coordinate',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}],
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
assert result['candidates'][0]['evidence_sources'] == ['pdf_coordinate']
|
||||
assert result['diagnostics']['evidence_sources'] == ['pdf_coordinate']
|
||||
|
||||
|
||||
def test_automark_keeps_native_and_ocr_table_reconstruction_candidates_in_parallel():
|
||||
"""关键断言:原生行重建成功也必须保留同页 OCR 的独立候选,不以先成功者屏蔽另一证据。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
native = {'subrow_layouts': [{'row_offset': 0}], 'header_regions': []}
|
||||
ocr = {'subrow_layouts': [{'row_offset': 0}, {'row_offset': 1}], 'header_regions': []}
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [native, ocr]
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
table_candidates = [item for item in result['candidates'] if item['candidate_kind'] == 'table_reconstruction']
|
||||
assert [item['evidence_sources'] for item in table_candidates] == [['pdf_coordinate'], ['ocr_coordinate']]
|
||||
assert result['diagnostics']['coordinate_reconstruction'] == native
|
||||
assert result['diagnostics']['conflicts'] == [{
|
||||
'code': 'table_reconstruction_source_conflict',
|
||||
'sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
}]
|
||||
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
|
||||
document_id=77, table_id='table-1', actor_id=None, force_ocr=True,
|
||||
)
|
||||
|
||||
|
||||
def test_automark_marks_consistent_multi_evidence_candidates_as_needing_review():
|
||||
"""关键断言:多路视觉证据结构一致也只代表可复核候选,不能绕过人工确认。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
reconstruction = {'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}]}
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [reconstruction, reconstruction]
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}]}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
assert result['status'] == 'needs_review'
|
||||
assert result['diagnostics']['conflicts'] == []
|
||||
assert all(item['needs_review'] is True for item in result['candidates'])
|
||||
|
||||
|
||||
def test_automark_exposes_only_the_unified_pdf_job_type():
|
||||
"""关键断言:XFA 不保留独立自动标记 Job 类型。"""
|
||||
from app.jobs.types import JobType
|
||||
|
||||
assert JobType.SHIPPING_PDF_AUTOMARK.value == 'shipping_pdf_automark'
|
||||
assert not hasattr(JobType, 'SHIPPING_XFA_OCR_AUTOMARK')
|
||||
|
||||
|
||||
def test_automark_exposes_acroform_widget_as_independent_visual_candidate():
|
||||
"""关键断言:Widget 只补充定位证据,不能替代 datasets 正式值绑定。"""
|
||||
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}]}
|
||||
widget = SimpleNamespace(widget_id='wgt-1', short_name='customer_po_number', page_no=1,
|
||||
normalized_bbox={'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3})
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._acroform_widget_candidates',
|
||||
return_value=[{
|
||||
'candidate_id': 'widget-wgt-1', 'candidate_kind': 'field_binding',
|
||||
'binding': {'field_code': 'customer_po_number', 'visual_binding': {'source': 'acroform_widget'}},
|
||||
'evidence_sources': ['acroform_widget'], 'needs_review': True,
|
||||
}],
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget'])
|
||||
assert widget_candidate['needs_review'] is True
|
||||
assert 'value_binding' not in widget_candidate['binding']
|
||||
|
||||
|
||||
def test_automark_keeps_unmatched_acroform_widget_as_unbound_visual_candidate(monkeypatch):
|
||||
"""Widget 技术名未匹配 Schema 时仍可供人工框选,禁止自动猜业务字段。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
document = SimpleNamespace(asset_id=11)
|
||||
asset = SimpleNamespace(id=11)
|
||||
widget = SimpleNamespace(
|
||||
widget_id='wgt-ebeln', short_name='EBELN', page_no=1,
|
||||
normalized_bbox={'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3},
|
||||
)
|
||||
monkeypatch.setattr(service.db.session, 'get', lambda _model, ident: document if ident == 77 else asset)
|
||||
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_acroform.read_acroform_widgets',
|
||||
lambda _bytes: [widget],
|
||||
)
|
||||
|
||||
candidates = _acroform_widget_candidates(
|
||||
document_id=77,
|
||||
fields={'order_field_candidates': []},
|
||||
actor_id=1,
|
||||
)
|
||||
|
||||
# 关键断言:只携带 Widget 几何和技术名,field_code 为空且不存在正式 value_binding。
|
||||
assert candidates == [
|
||||
{
|
||||
'candidate_id': 'widget-unbound-wgt-ebeln',
|
||||
'candidate_kind': 'field_binding',
|
||||
'binding': {
|
||||
'binding_id': 'widget-unbound-wgt-ebeln',
|
||||
'field_id': '',
|
||||
'field_code': '',
|
||||
'display_name': 'EBELN',
|
||||
'scope': 'header',
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3},
|
||||
'source': 'acroform_widget',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
'region_kind': 'field',
|
||||
'widget_id': 'wgt-ebeln',
|
||||
'widget_short_name': 'EBELN',
|
||||
},
|
||||
},
|
||||
'evidence_sources': ['acroform_widget'],
|
||||
'needs_review': True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_automark_keeps_existing_opencv_layout_geometry_as_parallel_table_candidate():
|
||||
"""关键断言:Layout 阶段已验收的 OpenCV 几何进入统一候选,但仍需人工确认。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {
|
||||
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
|
||||
}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
opencv = {'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .5, 1]}], 'header_regions': []}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._layout_opencv_reconstruction',
|
||||
return_value=opencv,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
opencv_candidates = [item for item in result['candidates'] if item['evidence_sources'] == ['opencv_geometry']]
|
||||
assert len(opencv_candidates) == 1
|
||||
assert opencv_candidates[0]['needs_review'] is True
|
||||
assert result['diagnostics']['evidence_sources'] == ['opencv_geometry', 'pdf_coordinate']
|
||||
|
||||
|
||||
def test_automark_keeps_xfa_widget_geometry_as_parallel_table_candidate():
|
||||
"""关键断言:动态 XFA 未绘制明细值时,Widget 几何可形成待确认行框但不能自动采值。"""
|
||||
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {
|
||||
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
|
||||
}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
widget_geometry = {
|
||||
'subrow_layouts': [{
|
||||
'row_offset': 0, 'column_boundaries': [0, .2, .5, 1],
|
||||
'column_samples': [],
|
||||
}],
|
||||
'header_regions': [], 'status': 'needs_review',
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._xfa_widget_geometry_reconstruction',
|
||||
return_value=widget_geometry,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget_geometry'])
|
||||
assert widget_candidate['needs_review'] is True
|
||||
assert widget_candidate['payload']['subrow_layouts'][0]['column_samples'] == []
|
||||
|
||||
|
||||
def test_automark_enriches_widget_table_candidate_with_coordinate_header_text():
|
||||
"""XFA 行框来自 Widget 时仍须把独立坐标表头补入同一候选,供画布生成 header_field。"""
|
||||
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {
|
||||
'subrow_layouts': [], 'header_regions': [],
|
||||
}
|
||||
coordinate.suggest_coordinate_header_reconstruction.return_value = {
|
||||
'header_regions': [{
|
||||
'region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .2},
|
||||
'fields': [{'text': 'ITEM', 'field_code': 'line_no', 'region': {'x0': .11, 'y0': .15, 'x1': .18, 'y1': .2}}],
|
||||
}],
|
||||
}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
widget_geometry = {
|
||||
'table_region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .8},
|
||||
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .25, 1]}],
|
||||
'header_regions': [], 'status': 'needs_review',
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_header_reconstruction',
|
||||
coordinate.suggest_coordinate_header_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._xfa_widget_geometry_reconstruction',
|
||||
return_value=widget_geometry,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget_geometry'])
|
||||
field = widget_candidate['payload']['header_regions'][0]['fields'][0]
|
||||
assert field['text'] == 'ITEM'
|
||||
assert field['field_code'] == 'line_no'
|
||||
assert field['region'] == {'x0': .1, 'y0': .15, 'x1': .3, 'y1': .2}
|
||||
assert field['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate']
|
||||
|
||||
|
||||
def test_automark_marks_opencv_and_native_structure_conflict_for_review():
|
||||
"""关键断言:OpenCV 与 native 几何不一致时保留双方并记录冲突。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {
|
||||
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
|
||||
}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._layout_opencv_reconstruction',
|
||||
return_value={'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .5, 1]}], 'header_regions': []},
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
assert result['status'] == 'needs_review'
|
||||
assert result['diagnostics']['conflicts'] == [{
|
||||
'code': 'table_reconstruction_source_conflict',
|
||||
'sources': ['pdf_coordinate', 'opencv_geometry'],
|
||||
}]
|
||||
|
||||
|
||||
def test_automark_keeps_native_and_ocr_field_candidates_in_parallel():
|
||||
"""关键断言:字段框与表格行一样保留 native/OCR 两路,不以 native 候选屏蔽 OCR。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': [], 'header_regions': []}
|
||||
native_fields = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
'source': 'pdf_coordinate',
|
||||
}]}
|
||||
ocr_fields = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'absolute_value_region': {'x0': .12, 'y0': .2, 'x1': .32, 'y1': .4},
|
||||
'source': 'ocr_coordinate',
|
||||
}]}
|
||||
coordinate.suggest_order_field_layouts.side_effect = [native_fields, ocr_fields]
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
fields = [item for item in result['candidates'] if item['candidate_kind'] == 'field_binding']
|
||||
assert [item['evidence_sources'] for item in fields] == [['pdf_coordinate'], ['ocr_coordinate']]
|
||||
assert result['diagnostics']['field_conflicts'] == [{
|
||||
'code': 'field_binding_source_conflict',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
}]
|
||||
@@ -15,6 +15,7 @@ from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_CODE_SET,
|
||||
PROCESS_GATE_DEFINITIONS,
|
||||
PROCESS_GATE_REASON_OWNING_GATE,
|
||||
action_belongs_to_gate,
|
||||
assert_process_gate_contract_integrity,
|
||||
action_presentation,
|
||||
field_quality_may_block,
|
||||
@@ -58,6 +59,27 @@ def test_inventory_source_routing_primary_retry_action():
|
||||
status='blocked_retryable',
|
||||
)
|
||||
assert action == 'retry_with_latest_rules'
|
||||
assert primary_next_action_for_gate(
|
||||
gate_code='inventory_source_routing', status='blocked_manual',
|
||||
) == 'retry_with_latest_rules'
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_source_routing', action_code='open_inventory_source_review',
|
||||
) is False
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_field_mapping', action_code='confirm_inventory_field_mapping',
|
||||
) is False
|
||||
|
||||
|
||||
def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate():
|
||||
"""库存源重路由动作绝不能被 Excel Gate 自动入队。"""
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='excel_readiness',
|
||||
action_code='retry_with_latest_rules',
|
||||
) is False
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='excel_readiness',
|
||||
action_code='recheck_excel_readiness',
|
||||
) is True
|
||||
|
||||
|
||||
def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
@@ -67,6 +89,7 @@ def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.open_shortage_review',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'navigation',
|
||||
'ui_handler': 'shortage_review',
|
||||
}
|
||||
assert action_presentation('retry_inventory_from_matching') == {
|
||||
'code': 'retry_inventory_from_matching',
|
||||
@@ -76,6 +99,70 @@ def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
}
|
||||
|
||||
|
||||
def test_fulfillment_action_presentation_declares_lifecycle_surface():
|
||||
"""动作位置必须继承当前 Gate,而非维护 action_code 到位置的映射。"""
|
||||
assert action_presentation(
|
||||
'regenerate_excel_artifact', gate_code='artifact_generation',
|
||||
)['target_surface'] == 'fulfillment_prep'
|
||||
assert action_presentation(
|
||||
'retry_freight_upload_rpa', gate_code='freight_upload_rpa',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
assert action_presentation(
|
||||
'regenerate_manual_upload_todo', gate_code='manual_upload_handoff',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
assert action_presentation(
|
||||
'mark_manual_uploaded', gate_code='manual_upload_handoff',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
|
||||
|
||||
def test_manual_upload_handoff_authorizes_excel_regeneration_at_artifact_anchor():
|
||||
"""已到人工上传交接时,Excel 重生仍须由当前 Gate 合法授权并回到产物位置。"""
|
||||
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
|
||||
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='manual_upload_handoff',
|
||||
action_code='regenerate_excel_artifact',
|
||||
) is True
|
||||
plan = recovery_plan_for_action(
|
||||
current_gate='manual_upload_handoff',
|
||||
action_code='regenerate_excel_artifact',
|
||||
)
|
||||
assert plan['ui_placement'] == {
|
||||
'target_surface': 'fulfillment_prep',
|
||||
'target_anchor': 'excel_artifact',
|
||||
}
|
||||
|
||||
|
||||
def test_gate_action_presentation_declares_ui_dispatch_without_frontend_action_code_inference():
|
||||
"""非 mutation 动作必须由合同明确其页面宿主能力。"""
|
||||
assert action_presentation('mark_manual_uploaded') == {
|
||||
'code': 'mark_manual_uploaded',
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'dialog',
|
||||
'ui_handler': 'manual_upload_evidence',
|
||||
}
|
||||
assert action_presentation('confirm_customer') == {
|
||||
'code': 'confirm_customer',
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.confirm_customer',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'navigation',
|
||||
'ui_handler': 'customer_resolution',
|
||||
}
|
||||
|
||||
|
||||
def test_every_gate_declares_a_surface_and_anchor_for_its_actions():
|
||||
"""所有 Gate 的动作位置必须在 Gate 定义处声明,避免前端或动作码映射猜测。"""
|
||||
for gate in PROCESS_GATE_DEFINITIONS:
|
||||
placement = gate['ui_placement']
|
||||
for action in (gate.get('default_next_actions') or {}).values():
|
||||
if action:
|
||||
presentation = action_presentation(action, gate_code=gate['gate_code'])
|
||||
assert presentation is not None
|
||||
assert presentation['target_surface'] == placement['target_surface']
|
||||
assert presentation['target_anchor'] == placement['target_anchor']
|
||||
|
||||
|
||||
def test_process_gate_reason_ownership_is_unique():
|
||||
"""
|
||||
每个阻断原因码恰好映射一个 owning_gate,覆盖率 100%。
|
||||
@@ -240,6 +327,63 @@ def test_formal_inventory_matching_uses_only_executable_retries(app, monkeypatch
|
||||
]
|
||||
|
||||
|
||||
def test_inventory_shortage_with_active_snapshot_projects_rematch_and_rpa_refresh(app, tmp_path):
|
||||
"""库存不足时,已确认的活动 Excel 必须可重匹配;重新获取库存才是第二入口。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
inventory_path = tmp_path / 'active-inventory.xlsx'
|
||||
inventory_path.write_bytes(b'confirmed inventory')
|
||||
task = ShippingNotice(
|
||||
task_no='SN-SUFFICIENCY-ACTIVE-SNAPSHOT',
|
||||
inventory_lines_json=[{'part_number': 'P-1', 'available_qty': 2}],
|
||||
)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-SUFFICIENCY-ACTIVE-SNAPSHOT',
|
||||
storage_path=str(inventory_path),
|
||||
snapshot_status='ready',
|
||||
mapping_confirmed=True,
|
||||
inventory_lines_json=[{'part_number': 'P-1', 'available_qty': 2}],
|
||||
line_count=1,
|
||||
)
|
||||
db.session.add_all([task, inventory_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=int(task.id), inventory_file_id=int(inventory_file.id), is_active=True,
|
||||
))
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='EXE-SUFFICIENCY-ACTIVE-SNAPSHOT', task_id=int(task.id), status='blocked',
|
||||
current_gate_code='inventory_sufficiency', lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id), gate_code='inventory_sufficiency', sequence_no=16,
|
||||
status='blocked_manual', evaluation_version=1,
|
||||
blocking_reason_code='inventory_insufficient', next_action_code='open_shortage_review',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
summary = project_user_gate_summary(execution)
|
||||
|
||||
# 有效 Excel 是匹配的输入事实;缺口只阻断履约决定,不能迫使用户再次抓取文件。
|
||||
assert summary['next_action_code'] == 'retry_inventory_matching'
|
||||
assert summary['allowed_actions'] == [
|
||||
'retry_inventory_matching',
|
||||
'retry_inventory_preparation',
|
||||
]
|
||||
assert [item['action_code'] for item in summary['recovery_targets']] == [
|
||||
'retry_inventory_preparation',
|
||||
]
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch):
|
||||
"""所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -310,8 +454,42 @@ def test_user_gate_summary_repairs_stale_rpa_action_for_gate19(app, monkeypatch)
|
||||
assert summary['owner_type'] == 'human'
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch):
|
||||
"""Gate 20 人工交接也可显式重试 RPA,且不依赖 AUTO_UPLOAD 配置。"""
|
||||
def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch):
|
||||
"""库存准备不再提供库存文件上传旁路,仅允许重试 RPA。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-INVENTORY-1', status='blocked',
|
||||
current_gate_code='inventory_preparation',
|
||||
primary_next_action_code='retry_inventory_preparation',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-INVENTORY-1', 'status': 'blocked',
|
||||
'primary_next_action_code': 'retry_inventory_preparation',
|
||||
'responsible_party': 'worker', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['next_action_code'] == 'retry_inventory_preparation'
|
||||
assert summary['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
assert summary['allowed_actions'] == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_manual_gate_evidence_and_rpa_retry(app, monkeypatch):
|
||||
"""Gate 20 保持凭据登记主动作,并显式下发可选 RPA 重试。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
@@ -338,10 +516,121 @@ def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch):
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
assert summary['next_action_code'] == 'retry_freight_upload_rpa'
|
||||
assert summary['next_action_code'] == 'mark_manual_uploaded'
|
||||
assert summary['allowed_actions'] == [
|
||||
'mark_manual_uploaded',
|
||||
'retry_freight_upload_rpa',
|
||||
]
|
||||
assert summary['owner_type'] == 'human'
|
||||
|
||||
|
||||
def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action(app, monkeypatch):
|
||||
"""Gate 20 必须引导受控凭据登记,不得再重生待办或直接声称上传完成。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-MANUAL-CONFIRM', status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
primary_next_action_code='regenerate_manual_upload_todo',
|
||||
responsible_party='owner', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-MANUAL-CONFIRM', 'status': 'blocked',
|
||||
'primary_next_action_code': 'regenerate_manual_upload_todo',
|
||||
'responsible_party': 'owner', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'manual_upload_pending',
|
||||
'next_action_code': 'regenerate_manual_upload_todo', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['next_action_code'] == 'mark_manual_uploaded'
|
||||
assert summary['allowed_actions'] == [
|
||||
'mark_manual_uploaded',
|
||||
'retry_freight_upload_rpa',
|
||||
]
|
||||
assert summary['primary_action']['target_surface'] == 'upload_complete'
|
||||
assert summary['primary_action']['target_anchor'] == 'manual_upload'
|
||||
|
||||
|
||||
def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, monkeypatch):
|
||||
"""跨 Gate Excel 恢复必须采用 RecoveryPlan 的位置,不能继承 Gate 20 的上传位置。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-MANUAL-EXCEL', status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
primary_next_action_code='regenerate_manual_upload_todo',
|
||||
responsible_party='owner', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-MANUAL-EXCEL', 'status': 'blocked',
|
||||
'primary_next_action_code': 'regenerate_manual_upload_todo',
|
||||
'responsible_party': 'owner', 'active_recovery_plans': [], 'gates': [],
|
||||
'recovery_targets': [{'action_code': 'regenerate_excel_artifact'}],
|
||||
'current_gate': {
|
||||
'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'manual_upload_pending',
|
||||
'next_action_code': 'regenerate_manual_upload_todo', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(projection, '_excel_regeneration_allowed', lambda **_: True)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
regeneration = next(
|
||||
item for item in summary['action_presentation']
|
||||
if item['code'] == 'regenerate_excel_artifact'
|
||||
)
|
||||
assert regeneration['target_surface'] == 'fulfillment_prep'
|
||||
assert regeneration['target_anchor'] == 'excel_artifact'
|
||||
|
||||
|
||||
def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, monkeypatch):
|
||||
"""库存源路由只允许自动重算,Gate 卡不得暴露人工选源或确认。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-ROUTING', status='blocked',
|
||||
current_gate_code='inventory_source_routing', primary_next_action_code='retry_with_latest_rules',
|
||||
responsible_party='system', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-ROUTING', 'status': 'blocked',
|
||||
'primary_next_action_code': 'retry_with_latest_rules',
|
||||
'responsible_party': 'system', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_source_routing', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'no_inventory_source_candidates',
|
||||
'next_action_code': 'retry_with_latest_rules', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['allowed_actions'] == []
|
||||
|
||||
|
||||
def test_process_gate_dependency_integrity_and_excel_only_scope():
|
||||
"""
|
||||
校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。
|
||||
|
||||
@@ -168,6 +168,41 @@ def test_inventory_matching_retryable_exposes_retry_action():
|
||||
assert technical_auto_only is False
|
||||
|
||||
|
||||
def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_sufficiency(app, monkeypatch):
|
||||
"""匹配已完成但存在缺口时,当前匹配 Gate 必须通过并交给满足性 Gate。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
from app.models import ShippingNotice
|
||||
|
||||
task = SimpleNamespace(
|
||||
task_no='SN-SHORTAGE-1',
|
||||
match_status='partial',
|
||||
shortage_json=[{'line_key': 'L1', 'shortage_qty': '2'}],
|
||||
)
|
||||
execution = SimpleNamespace(task_id=7)
|
||||
gate = SimpleNamespace(gate_code='inventory_matching')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
|
||||
lambda _payload: {'status': 'needs_human'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
|
||||
with app.app_context():
|
||||
outcome = executor._handle_retry_inventory_matching(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
payload={},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'passed'
|
||||
assert outcome['output_snapshot']['business_result'] == 'inventory_shortage'
|
||||
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_inventory_preparation_retryable_without_reason_uses_contract_action():
|
||||
"""无特定原因码、仅 blocked_retryable 时沿用 Gate 合同默认动作(retry_inventory_preparation)。"""
|
||||
|
||||
@@ -14,10 +14,11 @@ from unittest.mock import MagicMock, patch
|
||||
from app import db
|
||||
from app.jobs.handlers.shipping_process_gate import run_shipping_process_gate
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.models import Job, ShippingNotice, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_job_service import (
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
enqueue_gate_attempt_job,
|
||||
schedule_waiting_external_poll,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
@@ -114,3 +115,155 @@ def test_gate_failure_does_not_auto_retry(app):
|
||||
)
|
||||
assert queued_jobs == 0
|
||||
assert int(first_job_id) > 0
|
||||
|
||||
|
||||
def test_gate_waiting_external_schedules_next_poll(app):
|
||||
"""外部等待的 Gate Job 成功后必须创建下一次延迟轮询,不能永久停在处理中。"""
|
||||
with app.app_context():
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-poll')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='wait-poll',
|
||||
idempotency_key='wait-poll-1',
|
||||
input_snapshot={'action_code': 'retry_layout_parsing', 'payload': {}},
|
||||
)
|
||||
job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id))
|
||||
job = db.session.get(Job, int(job_id))
|
||||
assert job is not None
|
||||
job.status = 'running'
|
||||
job.attempts = 1
|
||||
db.session.commit()
|
||||
|
||||
ctx = MagicMock()
|
||||
ctx.extras = {'worker_label': 'wait-poll-worker'}
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_process_gate.claim_and_run_gate_attempt',
|
||||
return_value={
|
||||
'attempt_id': int(attempt.id),
|
||||
'gate_code': 'inventory_preparation',
|
||||
'gate_status': 'waiting_external',
|
||||
},
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_process_gate.schedule_waiting_external_poll',
|
||||
return_value=999,
|
||||
) as schedule_poll:
|
||||
run_shipping_process_gate(ctx, {'attempt_id': int(attempt.id), 'job_id': int(job_id)})
|
||||
|
||||
schedule_poll.assert_called_once_with(attempt_id=int(attempt.id))
|
||||
completed_job = db.session.get(Job, int(job_id))
|
||||
assert completed_job is not None
|
||||
assert completed_job.status == 'success'
|
||||
|
||||
|
||||
def test_waiting_inventory_gate_timeout_uses_timeout_reason(app):
|
||||
"""库存 RPA 外部等待超时时须改为 timeout 原因,不可遗留 queued 文案。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-timeout')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
assert execution.task_id == task_id
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='wait-timeout',
|
||||
idempotency_key='wait-timeout-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
assert gate is not None
|
||||
gate.status = 'waiting_external'
|
||||
gate.blocking_reason_code = 'inventory_rpa_queued'
|
||||
gate.effective_result_json = {
|
||||
'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(),
|
||||
}
|
||||
# schedule_waiting_external_poll 只会在上一轮 Attempt 已正常收口后执行;
|
||||
# 保持该前置条件,避免 queued Attempt 触发并发保护而掩盖超时分支。
|
||||
attempt.status = 'succeeded'
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
with app.app_context():
|
||||
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
|
||||
db.session.commit()
|
||||
|
||||
# 前面的 nested app context 使用了独立 scoped session;清掉外层 identity map,
|
||||
# 才能断言内层同步实际提交的 Gate 事实,而不是旧会话中的 waiting_external 缓存。
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(ShippingProcessGate, int(gate.id))
|
||||
assert refreshed is not None
|
||||
assert refreshed.status == 'blocked_manual'
|
||||
assert refreshed.blocking_reason_code == 'inventory_rpa_timeout'
|
||||
|
||||
|
||||
def test_waiting_inventory_gate_timeout_rechecks_callback_facts_before_blocking(app, monkeypatch):
|
||||
"""迟到的超时轮询不得覆盖已经成功落库的库存回调事实。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-timeout-callback-won')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
assert execution.task_id == task_id
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='wait-timeout-callback-won',
|
||||
idempotency_key='wait-timeout-callback-won-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
assert gate is not None
|
||||
gate.status = 'waiting_external'
|
||||
gate.blocking_reason_code = 'inventory_rpa_queued'
|
||||
gate.effective_result_json = {
|
||||
'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(),
|
||||
}
|
||||
task = db.session.get(ShippingNotice, task_id)
|
||||
assert task is not None
|
||||
task.inventory_lines_json = [{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}]
|
||||
assert task.inventory_lines_json
|
||||
attempt.status = 'succeeded'
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
sync_calls = []
|
||||
|
||||
def _sync_callback_success(*, execution, **_kwargs):
|
||||
sync_calls.append(int(execution.id))
|
||||
refreshed_gate = db.session.get(ShippingProcessGate, int(gate.id))
|
||||
assert refreshed_gate is not None
|
||||
refreshed_gate.status = 'passed'
|
||||
refreshed_gate.blocking_reason_code = None
|
||||
db.session.flush()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
_sync_callback_success,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
|
||||
db.session.commit()
|
||||
|
||||
# nested app context 已提交同步结果;外层会话须失效旧 Gate 缓存后再读取。
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(ShippingProcessGate, int(gate.id))
|
||||
assert sync_calls == [int(execution.id)]
|
||||
assert refreshed is not None
|
||||
assert refreshed.status == 'passed'
|
||||
assert refreshed.blocking_reason_code is None
|
||||
@@ -20,6 +20,7 @@ from __future__ import annotations
|
||||
|
||||
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -116,7 +117,6 @@ def _seed_workflow_version(
|
||||
|
||||
source_type='manual',
|
||||
|
||||
process_status='waiting_inventory',
|
||||
|
||||
)
|
||||
|
||||
@@ -174,6 +174,141 @@ def test_ensure_execution_creates_all_contract_gates(gate_execution):
|
||||
|
||||
|
||||
|
||||
def test_ensure_execution_for_task_ignores_superseded_execution(app):
|
||||
|
||||
"""Task 指针指向已替代 Execution 时必须创建新正式链,不能复用历史 Gate。"""
|
||||
|
||||
with app.app_context():
|
||||
|
||||
_user, _review_case_id, task_id = _seed_workflow_version(suffix='superseded-task')
|
||||
|
||||
old = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
|
||||
|
||||
old.status = 'superseded'
|
||||
|
||||
db.session.flush()
|
||||
|
||||
current = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
|
||||
|
||||
assert current.id != old.id
|
||||
|
||||
assert current.status == 'active'
|
||||
|
||||
|
||||
|
||||
def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeypatch):
|
||||
|
||||
"""首次进入库存准备没有任何 RPA Attempt 时,自动推进必须投递一次 trigger。"""
|
||||
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
for prior_gate in (
|
||||
ShippingProcessGate.query
|
||||
.filter(
|
||||
ShippingProcessGate.execution_id == int(gate_execution.id),
|
||||
ShippingProcessGate.sequence_no < 13,
|
||||
)
|
||||
.all()
|
||||
):
|
||||
prior_gate.status = 'passed'
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
queued: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(
|
||||
process_gate_service,
|
||||
'queue_gate_attempt',
|
||||
lambda **kwargs: (queued.append(kwargs), SimpleNamespace(id=1))[1],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
process_gate_service._enqueue_auto_progress_after_gate_pass(
|
||||
execution=gate_execution,
|
||||
gate=gate,
|
||||
)
|
||||
|
||||
assert len(queued) == 1
|
||||
assert queued[0]['gate_code'] == 'inventory_preparation'
|
||||
|
||||
|
||||
def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch):
|
||||
"""已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。"""
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
|
||||
for prior_gate in ShippingProcessGate.query.filter(
|
||||
ShippingProcessGate.execution_id == int(gate_execution.id),
|
||||
ShippingProcessGate.sequence_no < 13,
|
||||
).all():
|
||||
prior_gate.status = 'passed'
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
task = db.session.get(ShippingNotice, int(gate_execution.task_id))
|
||||
db.session.add(ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no, source_code='TEST', attempt_no=1, source_run_no='PSR-FAILED',
|
||||
status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written',
|
||||
))
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
queued: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(process_gate_service, 'queue_gate_attempt', lambda **kwargs: queued.append(kwargs))
|
||||
|
||||
process_gate_service._enqueue_auto_progress_after_gate_pass(execution=gate_execution, gate=gate)
|
||||
|
||||
assert queued == []
|
||||
|
||||
|
||||
def test_auto_progress_does_not_queue_manual_inventory_navigation(gate_execution, monkeypatch):
|
||||
"""库存已入库后的 upload_inventory_file 是导航动作,不能被自动续跑执行。"""
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
for prior_gate in (
|
||||
ShippingProcessGate.query
|
||||
.filter(
|
||||
ShippingProcessGate.execution_id == int(gate_execution.id),
|
||||
ShippingProcessGate.sequence_no < 13,
|
||||
)
|
||||
.all()
|
||||
):
|
||||
prior_gate.status = 'passed'
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'inventory_rpa_timeout'
|
||||
gate.next_action_code = 'upload_inventory_file'
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
queued: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(
|
||||
process_gate_service,
|
||||
'queue_gate_attempt',
|
||||
lambda **kwargs: queued.append(kwargs),
|
||||
)
|
||||
|
||||
process_gate_service._enqueue_auto_progress_after_gate_pass(
|
||||
execution=gate_execution,
|
||||
gate=gate,
|
||||
)
|
||||
|
||||
assert queued == []
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_fingerprint_skip_does_not_rerun_passed_gate(gate_execution):
|
||||
@@ -287,6 +422,41 @@ def test_upstream_invalidation_only_targets_dependents(gate_execution):
|
||||
assert doc.status == 'passed'
|
||||
|
||||
|
||||
def test_invalidation_uses_target_gate_retry_action_not_inventory_reroute_fallback(gate_execution):
|
||||
"""下游 Excel Gate 失效后只能保留自身的重检动作,不能落入库存源重路由兜底。"""
|
||||
excel = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='excel_readiness',
|
||||
).one()
|
||||
excel.status = 'passed'
|
||||
db.session.flush()
|
||||
|
||||
invalidate_downstream_gates(
|
||||
execution=gate_execution,
|
||||
change_type='inventory_file_changed',
|
||||
)
|
||||
|
||||
assert excel.status == 'invalidated'
|
||||
assert excel.next_action_code == 'recheck_excel_readiness'
|
||||
|
||||
|
||||
def test_queue_gate_attempt_rejects_action_owned_by_another_gate(gate_execution):
|
||||
"""任何调用方都不能把库存源路由动作创建到 Excel Gate Attempt。"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
queue_gate_attempt(
|
||||
execution_no=gate_execution.execution_no,
|
||||
gate_code='excel_readiness',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
idempotency_key='wrong-action-excel-gate',
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
)
|
||||
|
||||
assert getattr(exc.value, 'code', None) == 'SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED'
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -488,7 +658,7 @@ def test_idempotent_queue_replays_same_attempt(gate_execution):
|
||||
|
||||
idempotency_key='same-key-ten-times',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -508,7 +678,7 @@ def test_idempotent_queue_replays_same_attempt(gate_execution):
|
||||
|
||||
idempotency_key='same-key-ten-times',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -544,7 +714,7 @@ def test_idempotent_key_conflicts_across_gate_and_action(gate_execution, app):
|
||||
|
||||
idempotency_key='cross-context-key',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -564,7 +734,7 @@ def test_idempotent_key_conflicts_across_gate_and_action(gate_execution, app):
|
||||
|
||||
idempotency_key='cross-context-key',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -660,7 +830,7 @@ def test_idempotent_key_conflicts_across_execution(app):
|
||||
|
||||
idempotency_key='cross-execution-key',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -680,8 +850,34 @@ def test_idempotent_key_conflicts_across_execution(app):
|
||||
|
||||
idempotency_key='cross-execution-key',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
|
||||
|
||||
|
||||
def test_superseded_execution_rejects_late_business_gate_result(app):
|
||||
"""候选版本已替换后,迟到结果不得重新写回旧 Gate。"""
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
with app.app_context():
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='superseded-sync')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
execution.status = 'superseded'
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
sync_gate_from_business_result(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
passed=False,
|
||||
blocking_reason_code='inventory_preparation_failed',
|
||||
effective_result_json={'findings': []},
|
||||
idempotency_key='late-result-must-not-write-superseded-execution',
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.PROCESS_EXECUTION_SUPERSEDED'
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import UniqueConstraint
|
||||
|
||||
from app.models import (
|
||||
@@ -33,6 +34,104 @@ def test_recovery_plan_has_idempotent_business_identity():
|
||||
assert 'invalidation_plan_json' in ShippingProcessRecoveryPlan.__table__.c
|
||||
|
||||
|
||||
def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
"""仅重生 Excel 只替代旧产物和未完成上传,不能重算库存或抹掉短缺放行事实。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryVerification,
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingProcessExecution,
|
||||
ShippingReservation,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only
|
||||
|
||||
task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', export_file_path='old.xlsx', export_file_name='old.xlsx')
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='REGEN-ONLY', display_name='Regen only', version=1, status='published',
|
||||
storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='REGEN-ONLY', display_name='Regen only', version=1,
|
||||
status='published', file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='REGEN-ONLY', display_name='Regen only')
|
||||
db.session.add_all([task, template, profile, schema])
|
||||
db.session.flush()
|
||||
schema_version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(schema_version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=schema_version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-EXCEL-REGEN-ONLY', task_id=task.id, status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
)
|
||||
db.session.add_all([extraction, execution])
|
||||
db.session.flush()
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no='EXP-EXCEL-REGEN-ONLY', task_id=task.id, template_id=template.id,
|
||||
order_schema_version_id=schema_version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path='old.xlsx', file_name='old.xlsx', file_checksum='d' * 64, file_size=1,
|
||||
status='ready',
|
||||
)
|
||||
reservation = ShippingReservation(
|
||||
task_id=task.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY',
|
||||
part_number='PN-1', po_number_normalized='PO-1', required_qty=1,
|
||||
status='artifact_reserved', current_artifact_id=None,
|
||||
)
|
||||
verification = ShippingInventoryVerification(task_id=task.id, status='completed', result_json={})
|
||||
match = ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, line_key='line-1', reservation_id='RSV-EXCEL-REGEN-ONLY',
|
||||
part_number='PN-1', match_result='matched', inventory_status='ready', is_current=True,
|
||||
)
|
||||
db.session.add_all([artifact, reservation, verification, match])
|
||||
db.session.flush()
|
||||
reservation.current_artifact_id = artifact.id
|
||||
upload = ShippingUploadAttempt(
|
||||
artifact_id=artifact.id, attempt_no=1, mode='manual',
|
||||
idempotency_key='excel-regen-only', status='pending',
|
||||
)
|
||||
db.session.add(upload)
|
||||
db.session.flush()
|
||||
|
||||
result = invalidate_excel_regeneration_only(
|
||||
execution=execution,
|
||||
attempt_id=17,
|
||||
actor_id=9,
|
||||
)
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(artifact)
|
||||
db.session.refresh(upload)
|
||||
db.session.refresh(reservation)
|
||||
db.session.refresh(verification)
|
||||
db.session.refresh(match)
|
||||
assert result['artifacts'] == [artifact.id]
|
||||
assert result['uploads'] == [upload.id]
|
||||
assert artifact.status == 'superseded'
|
||||
assert upload.status == 'failed'
|
||||
assert upload.invalidated_at is not None
|
||||
assert reservation.status == 'available'
|
||||
assert reservation.current_artifact_id is None
|
||||
assert task.export_file_path is None
|
||||
assert task.export_file_name is None
|
||||
assert verification.status == 'completed'
|
||||
assert match.is_current is True
|
||||
|
||||
|
||||
def test_inventory_preparation_is_task_round_with_per_source_uniqueness():
|
||||
"""准备轮次和逐源 Attempt 均必须保留不可混淆的唯一范围。"""
|
||||
assert 'uq_shipping_inventory_preparation_task_attempt' in _unique_names(ShippingInventoryPreparationAttempt)
|
||||
@@ -52,7 +151,7 @@ def test_rpa_attempt_status_updates_its_bound_preparation_source(app):
|
||||
sync_preparation_source_from_rpa_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-LINEAGE-1', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-PREP-LINEAGE-1')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
preparation = create_inventory_preparation_round(
|
||||
@@ -80,6 +179,83 @@ def test_rpa_attempt_status_updates_its_bound_preparation_source(app):
|
||||
assert preparation.status == 'succeeded'
|
||||
|
||||
|
||||
def test_rpa_callback_completes_waiting_preparation_recovery_plan(app):
|
||||
"""RPA 成功回调完成准备轮次后,关联恢复计划不得继续占用 waiting_external。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingProcessExecution,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_recovery_service import (
|
||||
create_inventory_preparation_round,
|
||||
sync_inventory_preparation_round,
|
||||
sync_preparation_source_from_rpa_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-PLAN-COMPLETE')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-PREP-PLAN-COMPLETE', task_id=int(task.id), status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
plan = ShippingProcessRecoveryPlan(
|
||||
plan_no='RCP-PREP-PLAN-COMPLETE', execution_id=int(execution.id),
|
||||
current_gate='inventory_matching', action_code='retry_inventory_from_preparation',
|
||||
target_gate='inventory_preparation', resume_after_gate='inventory_matching',
|
||||
status='waiting_external', invalidation_plan_json={},
|
||||
idempotency_key='prep-plan-complete', actor_type='user',
|
||||
)
|
||||
db.session.add(plan)
|
||||
db.session.flush()
|
||||
preparation = create_inventory_preparation_round(
|
||||
task=task, execution_id=int(execution.id), recovery_plan_id=int(plan.id),
|
||||
action_code='retry_inventory_from_preparation', source_codes=['DBS'], gate_attempt_id=None,
|
||||
)
|
||||
rpa = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no, source_code='DBS', attempt_no=1, source_run_no='PSR-PREP-PLAN-COMPLETE',
|
||||
status='queued', lease_token='lease-prep-plan', extra_json={}, callback_payload_json={},
|
||||
)
|
||||
db.session.add(rpa)
|
||||
db.session.flush()
|
||||
sync_inventory_preparation_round(
|
||||
preparation_attempt=preparation,
|
||||
result={'pending_source_codes': ['DBS'], 'source_attempts': {'DBS': {'attempt_id': rpa.id}}},
|
||||
)
|
||||
|
||||
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(rpa.id), rpa_status='succeeded')
|
||||
|
||||
db.session.refresh(plan)
|
||||
assert preparation.status == 'succeeded'
|
||||
assert plan.status == 'succeeded'
|
||||
assert plan.completed_at is not None
|
||||
|
||||
|
||||
def test_per_source_summary_exposes_attempt_id_for_preparation_lineage(app):
|
||||
"""新建 RPA Attempt 的汇总必须返回主键,准备轮次才能被回调准确收口。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
from app.services.shipping_notice.per_source_rpa_service import _attempts_summary
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-SUMMARY-ID')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
attempt = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no, source_code='DBS', attempt_no=1,
|
||||
source_run_no='PSR-PREP-SUMMARY-ID', status='queued',
|
||||
lease_token='lease-prep-summary', extra_json={}, callback_payload_json={},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
|
||||
summary = _attempts_summary(task.task_no, source_codes=['DBS'])
|
||||
|
||||
assert summary['DBS']['attempt_id'] == int(attempt.id)
|
||||
|
||||
|
||||
def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, app):
|
||||
"""库存准备 Trigger 必须把 GateAttempt 身份原样带到 RPA。"""
|
||||
from app import db
|
||||
@@ -87,7 +263,7 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-IDENTITY', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-IDENTITY')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id), actor_type='system')
|
||||
@@ -120,7 +296,7 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-MISSING', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-MISSING')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS'])
|
||||
@@ -134,7 +310,11 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa')
|
||||
assert result.pending_source_codes == []
|
||||
assert result.failed_source_codes == ['DBS']
|
||||
attempt = per_source_rpa_service._latest_attempt(task.task_no, 'DBS')
|
||||
# 读取真实数据库记录,避免被用于构造场景的 monkeypatch 查询函数遮蔽。
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
attempt = ShippingTaskInventoryRpaAttempt.query.filter_by(
|
||||
task_no=task.task_no, source_code='DBS', attempt_no=1,
|
||||
).one()
|
||||
assert attempt.status == 'failed'
|
||||
assert attempt.error_code == 'trigger_not_written'
|
||||
|
||||
@@ -146,7 +326,7 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey
|
||||
from app.services.shipping_notice import process_gate_executor
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-PREP-FREEZE-OPERATOR', process_status='waiting_inventory',
|
||||
task_no='SN-PREP-FREEZE-OPERATOR',
|
||||
order_snapshot_id=None, order_data_version=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -182,7 +362,7 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey
|
||||
payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77},
|
||||
)
|
||||
assert seen['actor_id'] == 77
|
||||
assert result['outcome'] in {'blocked_retryable', 'blocked_manual'}
|
||||
assert result['outcome'] == 'waiting_external'
|
||||
|
||||
|
||||
def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
@@ -195,7 +375,7 @@ def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
)
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
current = ShippingInventoryCandidateSet(
|
||||
@@ -254,7 +434,7 @@ def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app,
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -305,7 +485,7 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SN-2026-001', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-2026-001')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
captured = {}
|
||||
@@ -336,12 +516,12 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
|
||||
|
||||
|
||||
def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch):
|
||||
"""批量成功项也必须先通过逐源身份校验,不能先入库再拒绝。"""
|
||||
"""异步批量处理体必须先通过逐源身份校验,不能先入库再拒绝。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -356,7 +536,8 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
|
||||
lambda task: legacy_called.__setitem__('value', True) or task,
|
||||
)
|
||||
|
||||
response = inventory_rpa_workflow.rpa_report_inventory_batch({
|
||||
# HTTP 入口只负责受控收件和入队;身份围栏属于 Worker 正式处理体。
|
||||
response = inventory_rpa_workflow.process_rpa_report_inventory_batch({
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'callback_id': 'batch-callback-identity',
|
||||
'batch_run_no': 'BATCH-CALLBACK-IDENTITY',
|
||||
@@ -400,15 +581,15 @@ def test_batch_callback_inherits_authenticated_top_level_schema_version():
|
||||
assert merged['task_no'] == 'SN-1'
|
||||
|
||||
|
||||
def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
"""RPA 已耗尽时自动轮询必须终态化,Gate 才能退出系统处理中。"""
|
||||
def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app):
|
||||
"""历史 RPA 耗尽必须退出系统处理中,且不得封锁用户重试入口。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RPA-FAILED-GATE', process_status='waiting_inventory',
|
||||
task_no='SN-RPA-FAILED-GATE',
|
||||
pending_human_reason='rpa_exhausted', error_message='RPA export failed',
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -430,6 +611,7 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
idempotency_key='shipping-auto-progress:rpa-failed-poll',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation'},
|
||||
)
|
||||
@@ -445,9 +627,162 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
ShippingProcessGateAttempt.gate_id == gate.id,
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
).count() == 0
|
||||
assert gate.status == 'blocked_manual'
|
||||
assert gate.status == 'blocked_retryable'
|
||||
assert gate.blocking_reason_code == 'inventory_rpa_exhausted'
|
||||
db.session.refresh(execution)
|
||||
# Gate 已进入可人工恢复的 blocked_manual;Execution 仍保持 active,
|
||||
# 由当前业务阶段/Gate 投影表达阻断,不再回写旧的 execution blocked 状态。
|
||||
assert execution.status == 'active'
|
||||
|
||||
|
||||
def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
"""迟到成功回调已落库存行时,历史 RPA 耗尽不得把准备 Gate 回退为人工上传。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RPA-LATE-SUCCESS',
|
||||
pending_human_reason='rpa_exhausted',
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'available_qty': 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
|
||||
preparation = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_preparation',
|
||||
).one()
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_matching',
|
||||
).one()
|
||||
assert preparation.status == 'passed'
|
||||
assert preparation.blocking_reason_code is None
|
||||
# 断言自动推进确实进入后续匹配,而不是伪造“整条链路成功”。
|
||||
assert matching.status == 'blocked_retryable'
|
||||
assert matching.blocking_reason_code == 'inventory_match_failed'
|
||||
|
||||
|
||||
def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
"""跨 Gate 恢复后,旧准备轮询不得在库存匹配 Gate 产生技术失败。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(task_no='SN-STALE-PREP-POLL')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-STALE-PREP-POLL', task_id=task.id, status='active',
|
||||
current_gate_code='inventory_matching',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_matching',
|
||||
).one()
|
||||
gate.status = 'waiting_external'
|
||||
gate.next_action_code = 'poll_inventory_preparation'
|
||||
gate.effective_result_json = {'waiting_since': datetime.utcnow().isoformat()}
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code=gate.gate_code,
|
||||
trigger_type='user_retry', actor_type='system', actor_id='test',
|
||||
idempotency_key='stale-preparation-poll',
|
||||
input_snapshot={'action_code': 'retry_inventory_from_preparation', 'payload': {}},
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
|
||||
assert attempt.job_id is None
|
||||
|
||||
|
||||
def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rpa(app, monkeypatch):
|
||||
"""已失败的准备轮次被旧 poll 领取时,必须保留超时并禁止再次调 RPA。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingNotice,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_job_service import claim_and_run_gate_attempt
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(task_no='SN-POLL-KEEPS-RPA-TIMEOUT', pending_human_reason='inv_unavail')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=task.id,
|
||||
start_gate_code='inventory_preparation',
|
||||
)
|
||||
task.active_process_execution_id = execution.id
|
||||
preparation = ShippingInventoryPreparationAttempt(
|
||||
task_id=task.id,
|
||||
execution_id=execution.id,
|
||||
attempt_no=1,
|
||||
status='failed',
|
||||
input_snapshot_json={},
|
||||
output_snapshot_json={},
|
||||
)
|
||||
db.session.add_all([
|
||||
preparation,
|
||||
ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type='inventory_rpa_failed',
|
||||
detail_json={'error': 'Crane scheduled report not ready for download within 300000ms'},
|
||||
),
|
||||
])
|
||||
db.session.flush()
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id,
|
||||
gate_code='inventory_preparation',
|
||||
).one()
|
||||
assert gate.status == 'blocked_retryable'
|
||||
assert gate.blocking_reason_code == 'inventory_rpa_timeout'
|
||||
|
||||
rpa_calls = {'count': 0}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda _payload: rpa_calls.__setitem__('count', rpa_calls['count'] + 1),
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='external-wait-poll',
|
||||
idempotency_key='poll-keeps-rpa-timeout-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {'poll': True}},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = claim_and_run_gate_attempt(attempt_id=attempt.id, worker_id='timeout-poll-worker')
|
||||
|
||||
db.session.refresh(gate)
|
||||
db.session.refresh(execution)
|
||||
assert result['skipped'] is False
|
||||
assert rpa_calls['count'] == 0
|
||||
assert gate.status == 'blocked_retryable'
|
||||
assert gate.blocking_reason_code == 'inventory_rpa_timeout'
|
||||
assert gate.next_action_code == 'retry_inventory_preparation'
|
||||
assert execution.status == 'blocked'
|
||||
|
||||
|
||||
@@ -469,8 +804,9 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNFORMALPREPLINEAGE',
|
||||
process_status='waiting_inventory',
|
||||
inventory_source_code='DBS',
|
||||
# 该用例从 inventory_preparation Gate 开始,前置订单复核/冻结事实必须显式存在。
|
||||
order_snapshot_id=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -544,7 +880,6 @@ def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app):
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNSTARTCUSTOMERPENDING',
|
||||
process_status='created',
|
||||
current_order_extraction_id=101,
|
||||
order_snapshot_id=201,
|
||||
customer_resolution_status='pending',
|
||||
@@ -568,7 +903,6 @@ def test_formal_start_gate_stops_at_field_conflict_before_inventory(app):
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNSTARTFIELDCONFLICT',
|
||||
process_status='created',
|
||||
current_order_extraction_id=101,
|
||||
order_snapshot_id=201,
|
||||
customer_resolution_status='confirmed',
|
||||
@@ -594,7 +928,7 @@ def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app):
|
||||
from app.services.shipping_notice.auto_progress_controller import supersede_auto_progress_for_candidate_refreeze
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version, queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
old_candidate = ShippingInventoryCandidateSet(
|
||||
@@ -641,7 +975,7 @@ def test_legacy_workspace_forwarding_audit_is_structured(app):
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint
|
||||
|
||||
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
@@ -670,7 +1004,7 @@ def test_apx_runtime_audit_is_read_only_and_counts_active_states(app):
|
||||
from app.models import Job, ShippingNotice, ShippingProcessExecution
|
||||
from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state
|
||||
|
||||
task = ShippingNotice(task_no='SN-APX-AUDIT', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-APX-AUDIT')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
active = ShippingProcessExecution(
|
||||
@@ -783,6 +1117,146 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan():
|
||||
assert plan.completed_at is not None
|
||||
|
||||
|
||||
def test_excel_regeneration_completion_preserves_manual_upload_gate():
|
||||
"""跨 Gate Excel 重生完成后,当前 Gate 20 必须继续等待人工上传且计划可关闭。"""
|
||||
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
|
||||
|
||||
class Plan:
|
||||
status = 'queued'
|
||||
action_code = 'regenerate_excel_artifact'
|
||||
resume_after_gate = 'manual_upload_handoff'
|
||||
started_at = None
|
||||
completed_at = None
|
||||
failure_code = None
|
||||
failure_detail_json = None
|
||||
|
||||
plan = Plan()
|
||||
complete_recovery_plan_for_attempt(
|
||||
plan=plan,
|
||||
outcome='blocked_manual',
|
||||
business_result_code='manual_upload_pending',
|
||||
)
|
||||
|
||||
assert plan.status == 'succeeded'
|
||||
assert plan.completed_at is not None
|
||||
|
||||
|
||||
def test_manual_upload_excel_regeneration_returns_to_manual_handoff(monkeypatch):
|
||||
"""Gate 20 触发 Excel 重生后,执行器必须作废旧产物并保持人工上传阻断。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
invalidated = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_excel_regeneration_only',
|
||||
lambda **kwargs: invalidated.update(kwargs) or {'artifacts': [10], 'uploads': [11]},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda _payload: {'status': 'ok'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
|
||||
)
|
||||
|
||||
outcome = _handle_regenerate_excel(
|
||||
execution=SimpleNamespace(execution_no='SPE-EXCEL-HANDOFF', task_id=1),
|
||||
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
|
||||
payload={'attempt_id': 3, 'actor_user_id': 9},
|
||||
)
|
||||
|
||||
assert invalidated['attempt_id'] == 3
|
||||
assert outcome['outcome'] == 'blocked_manual'
|
||||
assert outcome['blocking_reason_code'] == 'manual_upload_pending'
|
||||
assert outcome['output_snapshot']['invalidation']['artifacts'] == [10]
|
||||
|
||||
|
||||
def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch):
|
||||
"""Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
synced = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda _payload: {'status': 'failed', 'message': 'template unavailable'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **kwargs: synced.append(kwargs),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
|
||||
)
|
||||
|
||||
execution = SimpleNamespace(execution_no='SPE-EXCEL-FAILED', task_id=1)
|
||||
outcome = _handle_regenerate_excel(
|
||||
execution=execution,
|
||||
gate=SimpleNamespace(gate_code='artifact_generation'),
|
||||
payload={'actor_user_id': 9},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'blocked_retryable'
|
||||
assert outcome['blocking_reason_code'] == 'artifact_generation_failed'
|
||||
assert synced == [{
|
||||
'execution': execution,
|
||||
'actor_type': 'system',
|
||||
'actor_id': 9,
|
||||
}]
|
||||
|
||||
|
||||
def test_executor_accepts_bound_cross_gate_excel_recovery_plan(monkeypatch):
|
||||
"""已绑定的 Gate 20 Excel RecoveryPlan 必须能通过 Worker 归属复核。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._handle_regenerate_excel',
|
||||
lambda **_: {'outcome': 'blocked_manual'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
executor.db.session,
|
||||
'get',
|
||||
lambda _model, _id: SimpleNamespace(
|
||||
id=81,
|
||||
execution_id=1,
|
||||
current_gate='manual_upload_handoff',
|
||||
action_code='regenerate_excel_artifact',
|
||||
target_gate='artifact_generation',
|
||||
resume_after_gate='manual_upload_handoff',
|
||||
),
|
||||
)
|
||||
result = executor._dispatch_action(
|
||||
execution=SimpleNamespace(id=1),
|
||||
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
|
||||
action_code='regenerate_excel_artifact',
|
||||
payload={'recovery_plan_id': 81},
|
||||
)
|
||||
|
||||
assert result['outcome'] == 'blocked_manual'
|
||||
|
||||
|
||||
def test_executor_rejects_unbound_cross_gate_excel_recovery_plan():
|
||||
"""Gate 20 的跨阶段 Excel 动作没有已绑定计划时必须 fail-closed。"""
|
||||
from types import SimpleNamespace
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.process_gate_executor import _dispatch_action
|
||||
|
||||
with pytest.raises(ValidationError, match='Recovery plan is required'):
|
||||
_dispatch_action(
|
||||
execution=SimpleNamespace(id=1),
|
||||
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
|
||||
action_code='regenerate_excel_artifact',
|
||||
payload={},
|
||||
)
|
||||
|
||||
|
||||
def test_inventory_rematch_shortage_is_business_result_not_technical_failure(monkeypatch):
|
||||
"""库存 14、缺口 16 时,匹配 Attempt 成功收口到缺口复核。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -815,8 +1289,10 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
payload={'actor_user_id': 1},
|
||||
)
|
||||
|
||||
assert result['outcome'] == 'blocked_manual'
|
||||
assert result['blocking_reason_code'] == 'inventory_shortage_review_required'
|
||||
# 匹配动作已成功完成;库存缺口由 inventory_sufficiency Gate 单独阻断,
|
||||
# 不能把业务缺口回写成 inventory_matching 的技术失败。
|
||||
assert result['outcome'] == 'passed'
|
||||
assert 'blocking_reason_code' not in result
|
||||
assert result['effective_result_json']['shortage']['lines'][0] == {
|
||||
'available_qty': 14,
|
||||
'shortage_qty': 16,
|
||||
@@ -826,7 +1302,7 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch):
|
||||
"""字段映射恢复必须停留在 mapping handler,不得误建库存准备轮次。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _dispatch_action
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
called = {'preparation': 0, 'matching': 0}
|
||||
monkeypatch.setattr(
|
||||
@@ -837,9 +1313,20 @@ def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_from_field_mapping',
|
||||
lambda **_: {'outcome': 'blocked_manual'},
|
||||
)
|
||||
result = _dispatch_action(
|
||||
execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'),
|
||||
action_code='retry_inventory_from_field_mapping', payload={},
|
||||
monkeypatch.setattr(
|
||||
executor.db.session,
|
||||
'get',
|
||||
lambda _model, _id: SimpleNamespace(
|
||||
execution_id=1,
|
||||
current_gate='inventory_matching',
|
||||
action_code='retry_inventory_from_field_mapping',
|
||||
target_gate='inventory_field_mapping',
|
||||
resume_after_gate='inventory_matching',
|
||||
),
|
||||
)
|
||||
result = executor._dispatch_action(
|
||||
execution=SimpleNamespace(id=1), gate=SimpleNamespace(gate_code='inventory_matching'),
|
||||
action_code='retry_inventory_from_field_mapping', payload={'recovery_plan_id': 7},
|
||||
)
|
||||
assert result['outcome'] == 'blocked_manual'
|
||||
assert called['preparation'] == 0
|
||||
|
||||
@@ -14,7 +14,10 @@ from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
|
||||
from app.services.shipping_notice.processing_ownership import (
|
||||
assert_notice_task_ownership,
|
||||
record_projection_inconsistency_audit,
|
||||
)
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
PROJECTION_INCONSISTENT_ERROR_CODE,
|
||||
TASK_OWNERSHIP_MISMATCH_ERROR_CODE,
|
||||
@@ -65,6 +68,24 @@ def test_reconcile_marks_inconsistency_and_strips_fulfillment():
|
||||
assert len(payload['stage_nodes']) == 15
|
||||
|
||||
|
||||
def test_projection_inconsistency_audit_uses_allowed_failure_result(app):
|
||||
"""不一致审计必须以 audit_service 接受的 failure 落库,不能在 GET 路径反复报参数非法。"""
|
||||
with app.app_context():
|
||||
with patch(
|
||||
'app.services.shipping_notice.processing_ownership.append_shipping_audit_event',
|
||||
) as append_mock, patch(
|
||||
'app.services.shipping_notice.processing_ownership.db.session.flush',
|
||||
):
|
||||
record_projection_inconsistency_audit({
|
||||
'projection_inconsistency_code': PROJECTION_INCONSISTENT_ERROR_CODE,
|
||||
'work_item_no': 'OT-9',
|
||||
'shipping_notice_no': 'SN-9',
|
||||
'stage': 'waiting_review',
|
||||
})
|
||||
|
||||
assert append_mock.call_args.kwargs['result'] == 'failure'
|
||||
|
||||
|
||||
def test_assert_ownership_noop_without_expected_context():
|
||||
"""未传期望 OT/Case/Run 时不拦截(兼容旧客户端)。"""
|
||||
task = SimpleNamespace(id=1, task_no='SN-1', order_task_id=None)
|
||||
|
||||
@@ -77,12 +77,35 @@ def test_projection_fact_read_failure_is_fail_closed():
|
||||
'available_actions': ['retry_inventory_preparation'],
|
||||
})
|
||||
assert payload['status'] == 'waiting_human'
|
||||
assert payload['retryable'] is False
|
||||
assert 'retryable' not in payload
|
||||
assert payload['primary_action'] is None
|
||||
assert payload['available_actions'] == []
|
||||
assert payload['blocking_reason']['code'] == 'projection_data_inconsistent'
|
||||
|
||||
|
||||
def test_inventory_shortage_gate_projects_a_user_visible_blocking_reason():
|
||||
"""库存缺口 Gate 不能只保留内部码而遗漏批次/工作台的统一阻塞原因。"""
|
||||
payload = apply_user_projection_fields(reconcile_processing_projection_facts({
|
||||
'status': 'blocked',
|
||||
'stage': 'inventory_matching',
|
||||
'source_type': 'eml',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
'status': 'blocked_manual',
|
||||
'next_action_code': 'open_shortage_review',
|
||||
'blocking_reason_code': 'inventory_shortage_review_required',
|
||||
},
|
||||
'available_actions': ['open_shortage_review'],
|
||||
}))
|
||||
|
||||
assert payload['user_status'] == 'waiting_human'
|
||||
assert payload['blocking_reason'] == {
|
||||
'code': 'inventory_shortage_review_required',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.reasons.inventory_shortage_review_required',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_normalize_unknown_action_codes():
|
||||
"""未知 / 别名动作码映射到契约或丢弃。"""
|
||||
assert normalize_action_code('retry_failed_documents') == 'retry'
|
||||
@@ -200,17 +223,17 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
)
|
||||
|
||||
uploaded = SimpleNamespace(
|
||||
process_status='uploaded', current_step='', upload_status='', export_file_path=None,
|
||||
current_step='', upload_status='uploaded', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
process_status='waiting_upload', current_step='', upload_status='', export_file_path='/x.xlsx',
|
||||
current_step='', upload_status='pending', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
matching = SimpleNamespace(
|
||||
process_status='matching', current_step='step5_match', upload_status='', export_file_path=None,
|
||||
current_step='step5_match', upload_status='', match_status='matching', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
|
||||
|
||||
@@ -224,7 +247,6 @@ def test_map_notice_unknown_status_fail_closed():
|
||||
)
|
||||
|
||||
unknown = SimpleNamespace(
|
||||
process_status='totally_unknown_xyz',
|
||||
current_step='',
|
||||
upload_status='',
|
||||
export_file_path=None,
|
||||
@@ -267,6 +289,29 @@ def test_derive_available_actions_failed_adds_retry():
|
||||
assert 'retry' in actions
|
||||
|
||||
|
||||
def test_retryable_projection_uses_technical_failure_reason_mapping():
|
||||
"""重试兜底原因必须生成可展示的技术失败 i18n 键,而不能抛 KeyError。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'processing',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_retryable',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'blocking_reason_code': 'technical_failure_present',
|
||||
},
|
||||
'available_actions': ['retry'],
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['blocking_reason'] == {
|
||||
'code': 'technical_failure_present',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.reasons.technical_failure_present',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_inventory_snapshot_missing_projects_retryable_inventory_action():
|
||||
"""库存快照缺失属于可恢复技术阻断,用户态必须保留重试动作。"""
|
||||
payload = apply_user_projection_fields({
|
||||
@@ -287,8 +332,147 @@ def test_inventory_snapshot_missing_projects_retryable_inventory_action():
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['retryable'] is True
|
||||
assert payload['primary_action']['code'] == 'retry'
|
||||
assert 'retryable' not in payload
|
||||
# 主动作必须保留 Gate 原始码,前端才能提交到正确的库存准备执行器。
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_preparation',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
'parameters': {},
|
||||
}
|
||||
|
||||
|
||||
def test_formal_blocked_gate_overrides_stale_preparation_running_state():
|
||||
"""正式 Gate 已阻断时,旧库存准备 waiting 不能把用户态降回系统处理中。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'processing',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_retryable',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'blocking_reason_code': 'technical_failure_present',
|
||||
},
|
||||
'available_actions': ['retry_inventory_preparation'],
|
||||
})
|
||||
|
||||
# 关键断言:Gate 是业务裁决真相;Preparation Attempt 只能作为过程明细。
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
|
||||
|
||||
def test_retryable_projection_exposes_technical_failure_reason_without_retry_decision():
|
||||
"""AutoProgress 超时未生成 Retry Decision 时,工作项读取仍必须返回可翻译原因。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'blocked',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'technical_failure_present',
|
||||
},
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['blocking_reason'] == {
|
||||
'code': 'technical_failure_present',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.reasons.technical_failure_present',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_formal_inventory_matching_retry_projects_business_i18n_key():
|
||||
"""正式 OT 的库存重试不得让页面回退展示内部 action code。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'blocked',
|
||||
'stage': 'inventory_matching',
|
||||
'source_type': 'order_task',
|
||||
'shipping_notice_no': 'SN-RETRY-MATCH',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_matching',
|
||||
'status': 'blocked_retryable',
|
||||
'next_action_code': 'retry_inventory_matching',
|
||||
'blocking_reason_code': 'inventory_match_failed',
|
||||
},
|
||||
'available_actions': ['retry_inventory_matching'],
|
||||
})
|
||||
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_matching',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
|
||||
'parameters': {},
|
||||
}
|
||||
|
||||
|
||||
def test_formal_inventory_gate_overrides_stale_waiting_review_compatibility_fields():
|
||||
"""正式库存 Gate 必须覆盖历史 OT 的 waiting_review,防止阶段回退。"""
|
||||
payload = reconcile_processing_projection_facts({
|
||||
'work_item_no': 'OT-GATE-OVERRIDE',
|
||||
'shipping_notice_no': 'SN-GATE-OVERRIDE',
|
||||
'status': 'waiting_review',
|
||||
'stage': 'waiting_review',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_manual',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'blocking_reason_code': 'inventory_rpa_timeout',
|
||||
},
|
||||
'available_actions': ['open_order_review'],
|
||||
})
|
||||
|
||||
assert payload['status'] == 'waiting_review'
|
||||
assert payload['stage'] == 'inventory_fetching'
|
||||
assert 'projection_inconsistency_code' not in payload
|
||||
assert payload['available_actions'] == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_inventory_file_missing_exposes_a_user_facing_reason_i18n_key():
|
||||
"""库存文件缺失需携带可翻译原因,批次中心不得回显内部原因码。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'blocked',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_file_missing',
|
||||
},
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
assert payload['blocking_reason'] == {
|
||||
'code': 'inventory_file_missing',
|
||||
'i18n_key': 'chat.shippingProcessing.reasonCode.inventory_file_missing',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action():
|
||||
"""库存文件缺失必须保留 Gate 重试,不得降级为线外上传或空按钮。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'processing',
|
||||
'stage': 'inventory_fetching',
|
||||
'source_type': 'order_task',
|
||||
'shipping_notice_no': 'SN-1',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_manual',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
},
|
||||
'available_actions': ['retry_inventory_preparation'],
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'waiting_human'
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_preparation',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
'parameters': {},
|
||||
}
|
||||
assert payload['available_actions'] == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_waiting_human_reconcile_action_uses_projected_available_actions():
|
||||
@@ -338,7 +522,7 @@ def test_apply_user_projection_fields_fail_closes_inconsistent_projection():
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'waiting_human'
|
||||
assert payload['retryable'] is False
|
||||
assert 'retryable' not in payload
|
||||
assert payload['primary_action'] is None
|
||||
assert payload['available_actions'] == []
|
||||
assert payload['blocking_reason']['code'] == 'projection_data_inconsistent'
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -35,7 +35,6 @@ def test_sync_order_task_stage_must_be_processing_stage(app):
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-CROSS-SURFACE-001',
|
||||
source_type='manual',
|
||||
process_status='matched',
|
||||
po_number='PO-CROSS-001',
|
||||
order_lines_migration_status='pending',
|
||||
)
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
收料 RPA 持久化模型契约测试。
|
||||
|
||||
用途:锁定收料配置、单元运行、归档文件和企微投递的独立存储边界。
|
||||
依赖:测试应用数据库、货代库存站点和排程模型。
|
||||
逻辑:验证数据库唯一约束;收料文件只能从收料单元运行派生,不能混入库存文件表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
|
||||
def _receipt_config(source_id: int):
|
||||
"""构造一条 DBS 收料配置,供一对一约束测试复用。"""
|
||||
from app.models import ShippingReceiptReportConfig
|
||||
|
||||
return ShippingReceiptReportConfig(
|
||||
inventory_source_id=source_id,
|
||||
enabled=True,
|
||||
report_path_json={
|
||||
'program_group': 'Bison',
|
||||
'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound',
|
||||
'report_name': 'Receipt Detail',
|
||||
},
|
||||
query_parameters_json=[],
|
||||
warehouse_ids_json=['AWSDU'],
|
||||
)
|
||||
|
||||
|
||||
def test_receipt_config_is_unique_per_inventory_source(app):
|
||||
"""同一库存站点至多维护一条独立收料配置。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add_all([_receipt_config(source.id), _receipt_config(source.id)])
|
||||
|
||||
# 关键断言:站点与收料配置是一对一,避免排程重复导出。
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_receipt_unit_callback_and_file_sha_are_idempotent(app):
|
||||
"""回调、站点仓库单元及归档文件 SHA 均由独立表去重。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun,
|
||||
ScheduleTask,
|
||||
ShippingInventorySource,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-MODEL-001', name='Receipt model test',
|
||||
schedule_type='platform_job', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
job_params={},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-MODEL-001', schedule_task_id=task.id, status='awaiting_callback')
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-001',
|
||||
status='awaiting_rpa', config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
|
||||
duplicate_callback = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU-2', callback_id='receipt-callback-001',
|
||||
status='awaiting_rpa', config_snapshot_json={},
|
||||
)
|
||||
db.session.add(duplicate_callback)
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
retry_unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-002',
|
||||
status='awaiting_rpa', config_snapshot_json={}, retry_of_id=unit.id,
|
||||
)
|
||||
# Retry must retain the old failed unit instead of overwriting it; thus the
|
||||
# same schedule/source/Warehouse identity is valid when linked by retry_of_id.
|
||||
db.session.add(retry_unit)
|
||||
db.session.commit()
|
||||
assert retry_unit.retry_of_id == unit.id
|
||||
|
||||
digest = hashlib.sha256(b'receipt workbook').hexdigest()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=unit.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/test.xlsx', original_filename='test.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
))
|
||||
db.session.commit()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=unit.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/test-copy.xlsx', original_filename='test-copy.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
))
|
||||
# 关键断言:同一 RPA 单元不可归档同 SHA 文件两次。
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_receipt_models_do_not_reference_inventory_files(app):
|
||||
"""收料归档表只关联收料单元运行,避免触发库存快照或匹配链路。"""
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
foreign_keys = {foreign_key.target_fullname for foreign_key in ShippingReceiptReportFile.__table__.foreign_keys}
|
||||
|
||||
# 关键断言:收料归档不能写入或关联库存快照事实表。
|
||||
assert 'shipping_inventory_files.id' not in foreign_keys
|
||||
assert foreign_keys == {'shipping_receipt_rpa_unit_runs.id'}
|
||||
@@ -43,7 +43,7 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk
|
||||
from app.services.shipping_notice import order_review_workbench_projection as workbench
|
||||
|
||||
case = MagicMock(status='confirmed', confirmed_task_id=9)
|
||||
stuck = MagicMock(task_no='SN-STUCK-1', process_status='created', current_order_extraction_id=3)
|
||||
stuck = MagicMock(task_no='SN-STUCK-1', current_order_extraction_id=3)
|
||||
finished = NS(
|
||||
id=55,
|
||||
status='success',
|
||||
@@ -83,19 +83,16 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk
|
||||
def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction():
|
||||
"""created/parsed 且已挂 Extraction 的任务需要确认后补推。"""
|
||||
stuck = MagicMock(
|
||||
process_status='created',
|
||||
current_order_extraction_id=12,
|
||||
)
|
||||
parsed = MagicMock(
|
||||
process_status='parsed',
|
||||
current_order_extraction_id=12,
|
||||
)
|
||||
progressed = MagicMock(
|
||||
process_status='waiting_upload',
|
||||
upload_status='pending',
|
||||
current_order_extraction_id=12,
|
||||
)
|
||||
shell = MagicMock(
|
||||
process_status='created',
|
||||
current_order_extraction_id=None,
|
||||
)
|
||||
assert _task_needs_post_confirm_auto_progress(stuck) is True
|
||||
@@ -111,7 +108,6 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-1',
|
||||
user_id=1,
|
||||
process_status='created',
|
||||
current_order_extraction_id=99,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -144,12 +140,11 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
|
||||
|
||||
|
||||
def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypatch):
|
||||
"""确认后 process_status=parsed 仍须入队(CONFIRM_PARSE 后常见态)。"""
|
||||
"""确认后已有解析结果仍须入队(CONFIRM_PARSE 后常见态)。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-PARSED',
|
||||
user_id=1,
|
||||
process_status='parsed',
|
||||
current_order_extraction_id=99,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -185,7 +180,6 @@ def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkey
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-2',
|
||||
user_id=1,
|
||||
process_status='created',
|
||||
current_order_extraction_id=88,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -229,7 +223,7 @@ def test_schedule_auto_progress_skips_when_already_progressed(app, monkeypatch):
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-3',
|
||||
user_id=1,
|
||||
process_status='waiting_upload',
|
||||
upload_status='pending',
|
||||
current_order_extraction_id=77,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -295,7 +289,6 @@ def test_run_single_task_auto_progresses_created_task_with_extraction(app, monke
|
||||
task_no='SN-CONFIRM-AP-4',
|
||||
user_id=1,
|
||||
source_type='review_confirmation',
|
||||
process_status='created',
|
||||
current_order_extraction_id=66,
|
||||
)
|
||||
db.session.add(task)
|
||||
|
||||
@@ -154,7 +154,6 @@ def _task(**kwargs) -> ShippingNotice:
|
||||
task = ShippingNotice(
|
||||
task_no=kwargs.pop('task_no', 'SN-FORMAL-EDIT-001'),
|
||||
source_type='manual',
|
||||
process_status=kwargs.pop('process_status', 'matched'),
|
||||
po_number=kwargs.pop('po_number', 'PO-FORMAL-001'),
|
||||
match_status=kwargs.pop('match_status', 'matched'),
|
||||
line_results_json=kwargs.pop('line_results_json', [{'part_number': 'A001'}]),
|
||||
|
||||
@@ -16,12 +16,22 @@ from app.services.shipping_notice.order_review_fulfillment_decision_service impo
|
||||
ALLOWED_DECISIONS,
|
||||
DECISION_CLOSE,
|
||||
DECISION_FULFILL,
|
||||
DECISION_RELEASE_SHORTAGE,
|
||||
DECISION_REOPEN,
|
||||
DECISION_WAIT,
|
||||
_STATUS_BY_DECISION,
|
||||
_assess_line_fulfill_complete,
|
||||
_assert_line_can_fulfill_complete,
|
||||
_manual_release_fields_from_inventory_candidates,
|
||||
_parse_qty,
|
||||
_release_template_inventory_fields,
|
||||
_release_template_system_fields,
|
||||
_release_fact_identity,
|
||||
_resolve_shortage_release_inventory_source,
|
||||
_sync_confirmed_task_fulfillment_gates,
|
||||
_is_shortage_match_fact,
|
||||
_has_terminal_inventory_rpa_failure,
|
||||
_validate_inventory_shortage_release_fields,
|
||||
)
|
||||
|
||||
|
||||
@@ -30,8 +40,10 @@ def test_allowed_decisions_cover_contract():
|
||||
assert DECISION_WAIT in ALLOWED_DECISIONS
|
||||
assert DECISION_FULFILL in ALLOWED_DECISIONS
|
||||
assert DECISION_CLOSE in ALLOWED_DECISIONS
|
||||
assert DECISION_RELEASE_SHORTAGE in ALLOWED_DECISIONS
|
||||
assert _STATUS_BY_DECISION[DECISION_FULFILL] == 'ready_to_fulfill'
|
||||
assert _STATUS_BY_DECISION[DECISION_CLOSE] == 'closed_unfulfillable'
|
||||
assert _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE] == 'released_shortage'
|
||||
|
||||
|
||||
def test_parse_qty_rejects_non_positive():
|
||||
@@ -43,6 +55,264 @@ def test_parse_qty_rejects_non_positive():
|
||||
assert _parse_qty('abc') is None
|
||||
|
||||
|
||||
def test_shortage_release_requires_template_inventory_field_when_snapshot_value_is_ambiguous():
|
||||
"""短缺放行不能任取多条库存记录中的 ODM ID,必须要求人工明确填写。"""
|
||||
required = _manual_release_fields_from_inventory_candidates(
|
||||
mappings=[
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': '101'},
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': '102'},
|
||||
],
|
||||
candidates=[
|
||||
{'101': 'ODM-A', '102': 'R1'},
|
||||
{'101': 'ODM-B', '102': 'R1'},
|
||||
],
|
||||
field_labels={'101': 'ODM ID', '102': 'Reservation ID'},
|
||||
)
|
||||
|
||||
assert required == [{'field_id': '101', 'display_name': 'ODM ID'}]
|
||||
|
||||
|
||||
def test_shortage_release_exposes_unique_template_inventory_value_as_read_only_evidence():
|
||||
"""模板字段在当前快照唯一时只读展示来源,不应要求用户重复填写。"""
|
||||
fields = _release_template_inventory_fields(
|
||||
mappings=[
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': '101'},
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': '102'},
|
||||
],
|
||||
candidates=[
|
||||
{'101': 'ODM-A', '102': 'A-01'},
|
||||
{'101': 'ODM-A', '102': 'A-02'},
|
||||
],
|
||||
field_labels={'101': 'ODM ID', '102': '库位'},
|
||||
)
|
||||
|
||||
assert fields == [
|
||||
{
|
||||
'field_id': '101',
|
||||
'display_name': 'ODM ID',
|
||||
'value': 'ODM-A',
|
||||
'value_source': 'inventory_snapshot',
|
||||
'requires_manual': False,
|
||||
},
|
||||
{
|
||||
'field_id': '102',
|
||||
'display_name': '库位',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_shortage_release_requires_header_inventory_field_when_snapshot_has_no_controlled_candidate():
|
||||
"""模板 Header 消费 ODM ID 时,短缺行没有受控候选记录必须要求人工补录。"""
|
||||
fields = _release_template_inventory_fields(
|
||||
mappings=[
|
||||
{'row_mode': 'header', 'source_kind': 'inventory_field', 'source_key': '6'},
|
||||
],
|
||||
candidates=[],
|
||||
field_labels={'6': 'ODM ID'},
|
||||
)
|
||||
|
||||
assert fields == [
|
||||
{
|
||||
'field_id': '6',
|
||||
'display_name': 'ODM ID',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_shortage_release_requires_missing_header_warehouse_system_fact():
|
||||
"""模板实际消费 Warehouse ID 而任务未解析时,放行前必须人工填写。"""
|
||||
assert _release_template_system_fields(
|
||||
mappings=[
|
||||
{'row_mode': 'header', 'source_kind': 'system_fact', 'source_key': 'warehouse_id'},
|
||||
],
|
||||
warehouse_id=None,
|
||||
) == [
|
||||
{
|
||||
'field_id': 'system_fact:warehouse_id',
|
||||
'display_name': 'Warehouse ID',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_shortage_release_export_uses_audited_header_override_when_no_snapshot_candidate_exists():
|
||||
"""短缺行无库存候选时,导出只能使用该行已审计补录的模板字段。"""
|
||||
from app.services.shipping_notice.export import _match_inventory_lines
|
||||
|
||||
assert _match_inventory_lines(
|
||||
order_lines=[{'part': 'PN-1', 'reservation': 'R-1'}],
|
||||
inventory_lines=[],
|
||||
match_keys=[
|
||||
{'order_field_id': 'part', 'inventory_field_id': '1'},
|
||||
{'order_field_id': 'reservation', 'inventory_field_id': '2'},
|
||||
],
|
||||
required_fields={'6'},
|
||||
release_overrides_by_line={0: {'6': 'ODM-001'}},
|
||||
released_export_line_indexes={0},
|
||||
) == [{'6': 'ODM-001'}]
|
||||
|
||||
|
||||
def test_shortage_release_export_allows_reservation_miss_when_template_uses_no_inventory_field():
|
||||
"""已审计短缺放行时,库存预约单未命中不能阻断只消费订单字段的 Excel。"""
|
||||
from app.services.shipping_notice.export import _match_inventory_lines
|
||||
|
||||
assert _match_inventory_lines(
|
||||
order_lines=[{'part': 'PN-1', 'reservation': 'R-1'}],
|
||||
inventory_lines=[{'1': 'PN-1', '2': 'R-2'}],
|
||||
match_keys=[
|
||||
{'order_field_id': 'part', 'inventory_field_id': '1'},
|
||||
{'order_field_id': 'reservation', 'inventory_field_id': '2'},
|
||||
],
|
||||
required_fields=set(),
|
||||
released_export_line_indexes={0},
|
||||
) == [{}]
|
||||
|
||||
|
||||
def test_unreleased_export_keeps_reservation_miss_blocked_when_template_uses_no_inventory_field():
|
||||
"""未放行行仍必须严格按料号和预约单匹配,不能因模板未引用库存字段而放宽。"""
|
||||
from app.services.shipping_notice.export import _match_inventory_lines
|
||||
|
||||
with pytest.raises(ValueError, match='第 1 条订单行没有匹配的库存记录'):
|
||||
_match_inventory_lines(
|
||||
order_lines=[{'part': 'PN-1', 'reservation': 'R-1'}],
|
||||
inventory_lines=[{'1': 'PN-1', '2': 'R-2'}],
|
||||
match_keys=[
|
||||
{'order_field_id': 'part', 'inventory_field_id': '1'},
|
||||
{'order_field_id': 'reservation', 'inventory_field_id': '2'},
|
||||
],
|
||||
required_fields=set(),
|
||||
)
|
||||
|
||||
|
||||
def test_shortage_release_keeps_first_export_line_override():
|
||||
"""首行原始索引为 0 时,导出仍须将已审计补录字段传入模板匹配。"""
|
||||
from app.services.shipping_notice.export import _release_overrides_for_export_lines
|
||||
|
||||
assert _release_overrides_for_export_lines(
|
||||
line_values=[{'__order_line_index': 0}],
|
||||
release_overrides_by_source_line={0: {'6': 'ODM-001'}},
|
||||
) == {0: {'6': 'ODM-001'}}
|
||||
|
||||
|
||||
def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_inventory_fact(app, monkeypatch):
|
||||
"""短缺放行重投影后必须入队 Excel 产物 Gate,且不得改写库存缺口事实。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
|
||||
|
||||
task = SimpleNamespace(id=12, active_process_execution_id=34)
|
||||
case = SimpleNamespace(confirmed_task_id=12)
|
||||
execution = SimpleNamespace(id=34, task_id=12)
|
||||
synced = []
|
||||
queued = []
|
||||
monkeypatch.setattr(svc.db.session, 'get', lambda model, key: task if key == 12 else execution)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **kwargs: synced.append(kwargs),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.auto_progress_controller.submit_auto_progress',
|
||||
lambda **kwargs: queued.append(kwargs),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=7)
|
||||
|
||||
assert synced == [{'execution': execution, 'actor_type': 'user', 'actor_id': 7}]
|
||||
assert queued == [{
|
||||
'task': task,
|
||||
'trigger': 'inventory_shortage_released',
|
||||
'operator_id': 7,
|
||||
'commit': False,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_rejects_missing_template_inventory_override():
|
||||
"""短缺放行漏填模板要求的库存字段时必须在服务端拒绝,不能只靠前端禁用按钮。"""
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
_validate_inventory_shortage_release_fields(
|
||||
required_fields=[{'field_id': '101', 'display_name': 'ODM ID'}],
|
||||
supplied_values={},
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.REVIEW_LINE_RELEASE_FIELDS_REQUIRED'
|
||||
|
||||
|
||||
def test_shortage_release_override_supplies_template_field_when_no_snapshot_value_exists():
|
||||
"""短缺放行后导出必须消费已审计补录值,不能因库存行缺失继续报字段不唯一。"""
|
||||
from app.services.shipping_notice.export import _collapse_inventory_matches
|
||||
|
||||
resolved = _collapse_inventory_matches(
|
||||
[{'101': ''}],
|
||||
{'101'},
|
||||
release_overrides={'101': 'ODM-001'},
|
||||
)
|
||||
|
||||
assert resolved['101'] == 'ODM-001'
|
||||
|
||||
|
||||
def test_shortage_release_reads_inventory_identity_from_projected_dict_fact():
|
||||
"""行库存事实已被序列化为 dict 时,放行字段判定仍必须拿到行/快照/库存源。"""
|
||||
assert _release_fact_identity({
|
||||
'line_index': 0,
|
||||
'inventory_snapshot_id': 24,
|
||||
'inventory_source_code': 'CRANE',
|
||||
}) == (0, 24, 'CRANE')
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_shortage_release_recognizes_current_match_fact_when_draft_projection_is_stale():
|
||||
"""放行资格必须由当前 OT 行事实决定,不能回退到过期草稿投影。"""
|
||||
assert _is_shortage_match_fact({
|
||||
'match_result': 'matched',
|
||||
'inventory_status': 'ready',
|
||||
'required_qty': '1.0',
|
||||
'available_qty': '0.0',
|
||||
'shortage_qty': '1.0',
|
||||
}) is True
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_shortage_release_inventory_source_falls_back_from_line_fact_to_task_then_snapshot():
|
||||
"""历史行事实漏源时,仍须从当前 OT 或快照恢复受控库存源。"""
|
||||
assert _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=None,
|
||||
task_source_code='CRANE',
|
||||
snapshot_source_code='DBS',
|
||||
) == 'CRANE'
|
||||
assert _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=None,
|
||||
task_source_code=None,
|
||||
snapshot_source_code='DBS',
|
||||
) == 'DBS'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_rpa_failure_release_requires_a_terminal_attempt_and_no_active_attempt():
|
||||
"""无库存快照的放行只允许在 RPA 已终态失败后,排队/运行中绝不能放行。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
task = SimpleNamespace(task_no='SN-RPA-FAILED', inventory_source_code='CRANE')
|
||||
assert _has_terminal_inventory_rpa_failure(
|
||||
task,
|
||||
attempts=[SimpleNamespace(source_code='CRANE', attempt_no=1, status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written')],
|
||||
) is True
|
||||
assert _has_terminal_inventory_rpa_failure(
|
||||
task,
|
||||
attempts=[SimpleNamespace(source_code='CRANE', attempt_no=1, status='queued', trigger_file_path='C:/trigger.json', execution_phase='trigger_written')],
|
||||
) is False
|
||||
|
||||
|
||||
|
||||
|
||||
def test_assess_rejects_shortage_and_missing_reservation():
|
||||
"""库存不足或缺 Reservation 时不可完整行先行。"""
|
||||
ok, code, _, _ = _assess_line_fulfill_complete(
|
||||
@@ -205,6 +475,85 @@ def test_decide_reopen_requires_admin_for_closed(app, monkeypatch):
|
||||
assert exc.value.code == 'SHIPPING.REVIEW_LINE_REOPEN_FORBIDDEN'
|
||||
|
||||
|
||||
def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
|
||||
"""新决定写审计前必须生成主键,避免审计序列化触发 500。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
|
||||
|
||||
draft = SimpleNamespace(
|
||||
draft_version=1,
|
||||
lines_json=[{'line_key': 'L1', 'qty': '1', 'reservation_id': 'R1', 'part_number': 'PN1'}],
|
||||
validation_result_json={'line_projections': [{'line_key': 'L1', 'available_qty': '1'}]},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
id=1,
|
||||
case_no='CASE-1',
|
||||
status='ready',
|
||||
current_draft=draft,
|
||||
run=SimpleNamespace(run_no='RUN-1'),
|
||||
)
|
||||
row = SimpleNamespace(
|
||||
id=None,
|
||||
line_key='L1',
|
||||
line_index=0,
|
||||
decision_version=1,
|
||||
decision_code=DECISION_FULFILL,
|
||||
decision_source='user',
|
||||
line_status='ready_to_fulfill',
|
||||
is_active=True,
|
||||
reason=None,
|
||||
required_qty='1',
|
||||
available_qty='1',
|
||||
reservation_id='R1',
|
||||
part_number='PN1',
|
||||
task_id=None,
|
||||
wave_no=None,
|
||||
actor_user_id=1,
|
||||
snapshot_json={},
|
||||
created_at=None,
|
||||
updated_at=None,
|
||||
)
|
||||
monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_active_decision', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(svc, '_next_version', lambda *args, **kwargs: 1)
|
||||
monkeypatch.setattr(svc, 'ShippingOrderReviewLineDecision', lambda **kwargs: row)
|
||||
monkeypatch.setattr(svc.db.session, 'add', lambda value: None)
|
||||
monkeypatch.setattr(svc.db.session, 'flush', lambda: setattr(row, 'id', 42))
|
||||
monkeypatch.setattr(svc, 'record_fulfillment_audit', lambda **kwargs: None, raising=False)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **kwargs: (_ for _ in ()).throw(AssertionError('audit should receive generated id'))
|
||||
if kwargs['after']['id'] is None else None,
|
||||
)
|
||||
monkeypatch.setattr(svc, 'resume_after_review_change', lambda **kwargs: {}, raising=False)
|
||||
monkeypatch.setattr(svc, '_get_soft_loader', lambda: lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, 'project_review_case_line_decisions', lambda value: {})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_resume_service.resume_after_review_change',
|
||||
lambda **kwargs: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_resume_service.attach_resume_outcome',
|
||||
lambda payload, resume: payload,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_projection.serialize_review_case',
|
||||
lambda value: {},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
result = svc.decide_review_line_fulfillment(
|
||||
user_id=1,
|
||||
case_no='CASE-1',
|
||||
line_key='L1',
|
||||
decision_code=DECISION_FULFILL,
|
||||
expected_draft_version=1,
|
||||
)
|
||||
|
||||
assert result['decision']['id'] == 42
|
||||
|
||||
|
||||
def test_create_wave_revalidates_inventory(app, monkeypatch):
|
||||
"""建波次前 validate_draft 后仍库存不足则拒绝。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -242,7 +591,7 @@ def test_create_wave_revalidates_inventory(app, monkeypatch):
|
||||
)
|
||||
|
||||
monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, 'soft_load_review_case_for_audit', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_get_soft_loader', lambda: lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_active_decision', lambda *a, **k: decision)
|
||||
|
||||
called = {'validate': False}
|
||||
|
||||
@@ -54,12 +54,12 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
|
||||
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id))
|
||||
task1 = ShippingNotice(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
|
||||
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
)
|
||||
task2 = ShippingNotice(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
|
||||
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
)
|
||||
db.session.add_all([task1, task2])
|
||||
@@ -114,7 +114,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
for _ in range(2):
|
||||
task = ShippingNotice(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
|
||||
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
)
|
||||
db.session.add(task)
|
||||
|
||||
@@ -25,8 +25,6 @@ def test_review_workbench_write_and_sensitive_events_are_frozen() -> None:
|
||||
'review_marked_non_order',
|
||||
'review_marked_quality_issue',
|
||||
'inventory_routing_rerouted',
|
||||
'inventory_routing_suggestion_adopted',
|
||||
'inventory_routing_manual_kept',
|
||||
'llm_review_requested',
|
||||
'llm_suggestion_accepted',
|
||||
'llm_suggestion_modified',
|
||||
@@ -46,8 +44,6 @@ def test_inventory_routing_events_are_in_workflow_audit_dictionary() -> None:
|
||||
"""库存路由恢复三类写事件不得再游离于冻结字典之外。"""
|
||||
for event_type in (
|
||||
'inventory_routing_rerouted',
|
||||
'inventory_routing_suggestion_adopted',
|
||||
'inventory_routing_manual_kept',
|
||||
):
|
||||
assert event_type in WORKFLOW_ITEM_AUDIT_EVENT_TYPES
|
||||
|
||||
|
||||
@@ -36,6 +36,13 @@ def test_profile_match_unknown_not_collapsed_to_unmatched():
|
||||
assert map_profile_match_user_status('not_matched') == 'unmatched'
|
||||
|
||||
|
||||
def test_profile_match_route_unique_statuses_are_matched():
|
||||
"""路由已唯一选定模板时,用户态不得误显示为未知。"""
|
||||
# 关键断言:真实路由契约 unique_match / selected_by_score 必须收敛为用户可读的已匹配。
|
||||
assert map_profile_match_user_status('unique_match') == 'matched'
|
||||
assert map_profile_match_user_status('selected_by_score') == 'matched'
|
||||
|
||||
|
||||
def test_user_profile_match_strips_admin_fields():
|
||||
"""普通用户不得看到候选分 / Profile code。"""
|
||||
payload = project_user_profile_match({
|
||||
@@ -220,12 +227,11 @@ def test_task_missing_does_not_reopen_confirm():
|
||||
assert result['reason_code'] == 'task_missing'
|
||||
|
||||
|
||||
def test_project_stage_for_task_created_is_order_creating():
|
||||
"""正式 OT 仍为 created 时阶段统一为 order_creating,label_key=waiting_system_start。"""
|
||||
def test_project_stage_for_task_without_domain_facts_is_order_creating():
|
||||
"""没有履约领域事实时,内部 OT 阶段投影保持 order_creating。"""
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
order_task_id=None,
|
||||
process_status='created',
|
||||
current_step=None,
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
@@ -233,7 +239,7 @@ def test_project_stage_for_task_created_is_order_creating():
|
||||
stage = project_stage_for_task(task)
|
||||
assert stage['code'] == 'order_creating'
|
||||
assert stage['label_key'] == 'waiting_system_start'
|
||||
assert stage['source'] == 'process_status'
|
||||
assert stage['source'] == 'domain_facts'
|
||||
|
||||
|
||||
def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
|
||||
@@ -241,7 +247,7 @@ def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
order_task_id=9,
|
||||
process_status='uploaded',
|
||||
upload_status='uploaded',
|
||||
current_step='step6_generate_file',
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
@@ -261,7 +267,6 @@ def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeyp
|
||||
|
||||
task = NS(
|
||||
task_no='SN-HANG-1',
|
||||
process_status='created',
|
||||
current_order_extraction_id=9,
|
||||
)
|
||||
finished = NS(
|
||||
|
||||
@@ -103,8 +103,8 @@ def test_stp_failure_stays_on_order_creation_node_and_hides_review_entry():
|
||||
assert 'open_order_review' not in actions
|
||||
|
||||
|
||||
def test_stale_running_stp_job_becomes_retryable_failure():
|
||||
"""超时的 running Job 不能永久遮蔽失败,必须投影为可恢复失败。"""
|
||||
def test_stale_running_stp_job_becomes_user_actionable_failure():
|
||||
"""超时的 running Job 必须停止,并投影当前 Gate 的明确用户动作。"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
case = SimpleNamespace(
|
||||
@@ -137,7 +137,7 @@ def test_stale_running_stp_job_becomes_retryable_failure():
|
||||
)
|
||||
|
||||
assert result['status'] == 'failed'
|
||||
assert result['retryable'] is True
|
||||
assert result['retryable'] is False
|
||||
assert result['reason_code'] == 'stp_job_stale'
|
||||
|
||||
|
||||
@@ -151,14 +151,14 @@ def test_unexpected_stp_error_has_stable_user_message():
|
||||
category_hint='temporary_storage_error',
|
||||
)
|
||||
|
||||
assert retryable is True
|
||||
assert result['message'] == '自动建单失败,系统将自动重试'
|
||||
assert retryable is False
|
||||
assert result['message'] == '自动建单失败,已停止,等待用户选择下一步动作'
|
||||
assert 'psycopg2' not in result['message']
|
||||
assert 'invalid input syntax' not in result['message']
|
||||
|
||||
|
||||
def test_automation_failed_retryable_when_post_confirm_needs_retry():
|
||||
"""确认后推进失败必须可重试,不能只显示已确认。"""
|
||||
def test_automation_failed_stops_when_post_confirm_needs_user_action():
|
||||
"""确认后推进失败必须停止,等待用户在当前 Gate 选择动作。"""
|
||||
case = SimpleNamespace(status='confirmed', confirmed_task_id=12)
|
||||
result = _project_case_automation_status(
|
||||
case,
|
||||
@@ -167,11 +167,11 @@ def test_automation_failed_retryable_when_post_confirm_needs_retry():
|
||||
'task_no': 'SN-1',
|
||||
'needs_retry': True,
|
||||
'status': 'needs_retry',
|
||||
'task_process_status': 'created',
|
||||
'task_stage': 'order_review',
|
||||
},
|
||||
)
|
||||
assert result['status'] == 'failed'
|
||||
assert result['retryable'] is True
|
||||
assert result['retryable'] is False
|
||||
assert result['task_no'] == 'SN-1'
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,13 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingOrderExtraction, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingReservation, ShippingNotice
|
||||
from app.models import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingReservation,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
current_available_snapshot_line_ids,
|
||||
ensure_task_reservations,
|
||||
@@ -48,6 +54,29 @@ def test_rolling_verification_keeps_shortage_pending_and_later_releases_it(app):
|
||||
assert second.result_json['available_count'] == 1
|
||||
|
||||
|
||||
def test_shortage_release_makes_only_its_snapshot_line_exportable(app):
|
||||
"""已审计短缺放行可导出该行,其他 shortage Reservation 仍不能被捎带导出。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order(suffix='released-shortage-export')
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
released_line = snapshot.lines[0]
|
||||
blocked_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
|
||||
qty=Decimal('3'), field_values_json={},
|
||||
)
|
||||
snapshot.lines.append(blocked_line)
|
||||
db.session.flush()
|
||||
verification = record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[
|
||||
{'reservation_id': released_line.reservation_id, 'part_number': released_line.part_number, 'required_qty': released_line.qty, 'available_qty': '0', 'line_status': 'shortage'},
|
||||
{'reservation_id': blocked_line.reservation_id, 'part_number': blocked_line.part_number, 'required_qty': blocked_line.qty, 'available_qty': '0', 'line_status': 'shortage'},
|
||||
])
|
||||
_verification, line_ids = current_available_snapshot_line_ids(
|
||||
task, released_snapshot_line_ids={released_line.id},
|
||||
)
|
||||
|
||||
assert line_ids == {released_line.id}
|
||||
|
||||
|
||||
def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app):
|
||||
"""关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -79,7 +79,6 @@ def test_excel_ready_requires_ready_artifact(app) -> None:
|
||||
task = ShippingNotice(
|
||||
task_no='SN-EXCEL-READY-BE09',
|
||||
source_type='manual',
|
||||
process_status='matched',
|
||||
export_file_path='/tmp/be09.xlsx',
|
||||
export_file_name='be09.xlsx',
|
||||
order_data_version=1,
|
||||
|
||||
@@ -31,7 +31,6 @@ def test_log_task_event_dual_write_keeps_match_detail(monkeypatch):
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
task_no='T-STP-1',
|
||||
process_status='pending_review',
|
||||
)
|
||||
tool_common_mod.log_task_event(
|
||||
task,
|
||||
|
||||
@@ -89,7 +89,6 @@ def stp_eligibility_stubs(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(svc, '_validation', lambda _case: _eligible_validation())
|
||||
monkeypatch.setattr(svc, '_persist_case_candidate_qualification', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(svc, '_is_xfa_case', lambda **_kwargs: False)
|
||||
monkeypatch.setattr(svc, '_draft_has_manual_edits', lambda _case: False)
|
||||
monkeypatch.setattr(svc, 'record_fulfillment_audit', lambda **_kwargs: None)
|
||||
|
||||
|
||||
@@ -38,8 +38,7 @@ def test_ensure_stp_reuses_active_job_without_duplicate(app):
|
||||
active = SimpleNamespace(id=77, status='queued', retry_of_job_id=None)
|
||||
|
||||
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
|
||||
svc, '_is_xfa_case', return_value=False,
|
||||
), patch.object(svc, '_draft_has_manual_edits', return_value=False), patch.object(
|
||||
svc, '_draft_has_manual_edits', return_value=False), patch.object(
|
||||
svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-1:doc-10:v2',
|
||||
), patch.object(svc, 'find_active_stp_job', return_value=active), patch.object(
|
||||
svc, 'find_latest_stp_job', return_value=active,
|
||||
@@ -82,8 +81,7 @@ def test_ensure_stp_force_retry_keeps_failed_and_sets_retry_of(app):
|
||||
return 51
|
||||
|
||||
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
|
||||
svc, '_is_xfa_case', return_value=False,
|
||||
), patch.object(svc, '_draft_has_manual_edits', return_value=False), patch.object(
|
||||
svc, '_draft_has_manual_edits', return_value=False), patch.object(
|
||||
svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-2:doc-11:v1',
|
||||
), patch.object(svc, 'find_active_stp_job', return_value=None), patch.object(
|
||||
svc, 'find_latest_stp_job', return_value=failed,
|
||||
@@ -100,6 +98,55 @@ def test_ensure_stp_force_retry_keeps_failed_and_sets_retry_of(app):
|
||||
assert new_job.retry_of_job_id == 50
|
||||
|
||||
|
||||
def test_worker_revalidation_preserves_current_manual_validation_confirmation(app):
|
||||
"""手动保存校验后的同版本 STP 重验不得丢失确认身份并误判 needs_review。"""
|
||||
from app.services.shipping_notice import order_stp_auto_create_service as svc
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=3,
|
||||
case_no='SORC-STP-MANUAL-CONFIRMED',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
document_id=12,
|
||||
candidate_id=None,
|
||||
disposition=None,
|
||||
run_id=3,
|
||||
run=SimpleNamespace(run_no='SNER-TEST-MANUAL-CONFIRMED', id=3),
|
||||
owner_user_id=1,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=4,
|
||||
validation_result_json={
|
||||
'status': 'ready', 'can_build': True, 'can_auto_create': True,
|
||||
'validation_version': 4,
|
||||
},
|
||||
issue_summary_json=[],
|
||||
header_values_json={},
|
||||
lines_json=[{
|
||||
'line_key': 'machine-1',
|
||||
'values': {'part-id': {'value': 'D4-A08AR12000001', 'source': 'manual'}},
|
||||
}],
|
||||
),
|
||||
)
|
||||
new_job = SimpleNamespace(id=52, status='queued', retry_of_job_id=None)
|
||||
refreshed = {'status': 'ready', 'can_build': True, 'can_auto_create': True, 'issues': []}
|
||||
|
||||
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
|
||||
svc, '_validation', return_value=refreshed), patch.object(
|
||||
svc, 'find_active_stp_job', return_value=None,
|
||||
), patch.object(svc, 'find_latest_stp_job', return_value=None), patch.object(
|
||||
svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-MANUAL-CONFIRMED:doc-12:v4',
|
||||
), patch.object(svc, 'enqueue', return_value=52), patch.object(
|
||||
svc, 'record_fulfillment_audit',
|
||||
), patch.object(svc, 'db') as mock_db:
|
||||
mock_db.session.get.return_value = new_job
|
||||
mock_db.session.flush = MagicMock()
|
||||
result = svc.ensure_stp_auto_create_for_case(case=case, commit=False, refresh_validation=True)
|
||||
|
||||
# 关键断言:重新计算资格事实不等于撤销同一 Draft 版本已完成的人工保存校验。
|
||||
assert result['status'] == 'queued'
|
||||
assert case.current_draft.validation_result_json['validation_version'] == 4
|
||||
|
||||
|
||||
def test_retry_stp_auto_create_for_case_rejects_confirmed(app):
|
||||
"""已 confirmed Case 不得走 STP retry,须走确认后推进重试。"""
|
||||
from app.core.errors import ConflictError
|
||||
@@ -240,3 +287,32 @@ def test_stp_handler_uses_fail_job_contract_for_business_failure(app):
|
||||
owned_attempt=1,
|
||||
)
|
||||
finish_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_stp_handler_flattens_business_error_details(app):
|
||||
"""Schema 拒绝必须在 Job 结果保留具体字段,供人工精确处理。"""
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import shipping_stp_auto_create as handler
|
||||
|
||||
job = SimpleNamespace(
|
||||
id=908,
|
||||
attempts=1,
|
||||
payload_json={'case_no': 'SORC-STP-HANDLER-DETAIL'},
|
||||
)
|
||||
ctx = JobContext(config={}, logger=MagicMock(), extras={})
|
||||
result = {
|
||||
'ok': False,
|
||||
'error_code': 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
'message': '订单明细包含未在当前 Schema 中定义的字段',
|
||||
'details': {'fields': ['unexpected_field'], 'schema_version_id': 31},
|
||||
}
|
||||
with patch.object(handler.db.session, 'get', return_value=job), patch.object(
|
||||
handler, 'execute_stp_auto_create_job', return_value=result,
|
||||
), patch.object(handler, '_emit_blocked_manual_audit_if_needed'), patch.object(
|
||||
handler, 'fail_job',
|
||||
) as fail_mock:
|
||||
handler.handle_shipping_stp_auto_create(ctx, {'job_id': 908})
|
||||
|
||||
persisted = fail_mock.call_args.kwargs['result']['blocking_reason_details']
|
||||
assert persisted['fields'] == ['unexpected_field']
|
||||
assert persisted['schema_version_id'] == 31
|
||||
@@ -21,7 +21,6 @@ def test_progress_nodes_follow_fixed_order_and_manual_freight():
|
||||
"""Excel 就绪后货代节点为 manual_takeover,不得投影为 running(首期无货代 RPA)。"""
|
||||
task = SimpleNamespace(
|
||||
customer_resolution_status='confirmed',
|
||||
process_status='waiting_upload',
|
||||
pending_human_reason=None,
|
||||
match_status='matched',
|
||||
review_status=None,
|
||||
@@ -44,7 +43,6 @@ def test_progress_nodes_mark_inventory_rpa_retrying():
|
||||
"""库存 RPA 等待中投影为 retrying/running,匹配节点保持 pending。"""
|
||||
task = SimpleNamespace(
|
||||
customer_resolution_status='confirmed',
|
||||
process_status='waiting_inventory',
|
||||
pending_human_reason='rpa_pending',
|
||||
match_status=None,
|
||||
review_status=None,
|
||||
@@ -61,7 +59,6 @@ def test_progress_nodes_customer_pending_blocks_downstream():
|
||||
"""客户未确认时下游库存节点保持 pending。"""
|
||||
task = SimpleNamespace(
|
||||
customer_resolution_status='pending',
|
||||
process_status='created',
|
||||
pending_human_reason=None,
|
||||
match_status=None,
|
||||
review_status=None,
|
||||
|
||||
@@ -26,7 +26,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
process_status='waiting_upload',
|
||||
current_step='step7_upload_freight',
|
||||
)
|
||||
db.session.add(notice)
|
||||
|
||||
@@ -24,8 +24,8 @@ from app.services.shipping_notice.batch_orchestrator import _should_orchestrate_
|
||||
|
||||
|
||||
def _task(task_no: str, **kwargs) -> ShippingNotice:
|
||||
"""构造最小发货任务,便于隔离验证处置状态与原流程状态。"""
|
||||
return ShippingNotice(task_no=task_no, process_status='created', source_type='manual', **kwargs)
|
||||
"""构造最小发货任务,便于隔离验证生命周期处置。"""
|
||||
return ShippingNotice(task_no=task_no, source_type='manual', **kwargs)
|
||||
|
||||
|
||||
def test_plain_created_task_can_be_deleted_and_restored(app):
|
||||
@@ -38,9 +38,8 @@ def test_plain_created_task_can_be_deleted_and_restored(app):
|
||||
outcome = move_task_to_recycle_bin(task, actor_id=1, reason='误建任务', request_id='req-delete')
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:删除不篡改 process_status,异步门禁仅因回收站状态停止任务。
|
||||
# 关键断言:删除仅改变生命周期,异步门禁据此停止任务。
|
||||
assert outcome == 'deleted'
|
||||
assert task.process_status == 'created'
|
||||
assert task.lifecycle_status == 'active'
|
||||
assert task.deleted_at is not None
|
||||
assert task_is_active(task) is False
|
||||
@@ -135,8 +134,8 @@ def test_void_requires_reason_and_rejects_successor(app):
|
||||
assert task_disposition_capability(task, 'delete').code == 'SHIPPING.TASK_SUCCESSOR_VOID_BLOCKED'
|
||||
|
||||
|
||||
def test_disposition_stops_backend_orchestration_without_changing_process_status(app):
|
||||
"""后台编排必须读取独立生命周期,不能依赖 process_status 被伪造为 rejected。"""
|
||||
def test_disposition_stops_backend_orchestration_from_lifecycle(app):
|
||||
"""后台编排必须读取独立生命周期。"""
|
||||
with app.app_context():
|
||||
task = _task('SN-DISPOSITION-ORCHESTRATOR-001')
|
||||
db.session.add(task)
|
||||
@@ -145,8 +144,7 @@ def test_disposition_stops_backend_orchestration_without_changing_process_status
|
||||
assert _should_orchestrate_task(task) is True
|
||||
move_task_to_recycle_bin(task, actor_id=1, reason='取消处理')
|
||||
|
||||
# 关键断言:任务仍为 created,但回收站状态已让编排器停止执行。
|
||||
assert task.process_status == 'created'
|
||||
# 关键断言:回收站状态已让编排器停止执行。
|
||||
assert _should_orchestrate_task(task) is False
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 606 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user