feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
1 parent
7cfd5d167e
commit
1e5aedb9ed
235 files changed
+11394
-9613
No files matched your search
@@ -251,7 +251,7 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||||
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
|
||||
db.session.flush()
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
customer = getattr(getattr(task, 'shipping_case', None), 'customer', None)
|
||||
customer = getattr(task, 'customer', None)
|
||||
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
|
||||
extraction_id=extraction.id, role='bill_to',
|
||||
).one_or_none() is None:
|
||||
|
||||
@@ -16,7 +16,7 @@ from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingCase,
|
||||
ShippingNotice,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
@@ -74,14 +74,14 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference_kind', [
|
||||
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
])
|
||||
def test_business_and_audit_references_block_delete(app, reference_kind: str):
|
||||
"""每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。"""
|
||||
with app.app_context():
|
||||
customer = _customer()
|
||||
if reference_kind == 'case':
|
||||
db.session.add(ShippingCase(case_no='CASE-LIFECYCLE', customer_id=customer.id))
|
||||
if reference_kind == 'notice':
|
||||
db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id))
|
||||
elif reference_kind == 'sequence':
|
||||
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
|
||||
elif reference_kind == 'external_ref':
|
||||
@@ -194,14 +194,14 @@ def test_delete_unused_customer_cascades_configurable_identity_evidence(app):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference_kind', [
|
||||
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
])
|
||||
def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str):
|
||||
"""永久删除必须复用完整生命周期统计,任一业务或审计引用均返回冲突。"""
|
||||
with app.app_context():
|
||||
customer = _customer('BLK')
|
||||
if reference_kind == 'case':
|
||||
db.session.add(ShippingCase(case_no='CASE-DELETE-BLOCK', customer_id=customer.id))
|
||||
if reference_kind == 'notice':
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id))
|
||||
elif reference_kind == 'sequence':
|
||||
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
|
||||
elif reference_kind == 'external_ref':
|
||||
@@ -267,13 +267,13 @@ def test_delete_blocks_reference_created_after_preview(app):
|
||||
preview = get_customer_lifecycle_impact(customer.id)
|
||||
assert preview['can_delete'] is True
|
||||
|
||||
db.session.add(ShippingCase(case_no='CASE-DELETE-RACE', customer_id=customer.id))
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id))
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
|
||||
assert exc_info.value.details['blockers']['business_cases'] == 1
|
||||
assert exc_info.value.details['blockers']['shipping_notices'] == 1
|
||||
assert db.session.get(ShippingCustomer, customer.id) is not None
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingCase,
|
||||
ShippingNotice,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
@@ -71,8 +71,8 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
normalized_value='same@example.com', status='approved', source='manual',
|
||||
),
|
||||
ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'),
|
||||
ShippingCase(
|
||||
case_no='CASE-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
|
||||
ShippingNotice(
|
||||
task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
|
||||
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
|
||||
),
|
||||
ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1),
|
||||
@@ -82,7 +82,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
target_id = target.id
|
||||
|
||||
preview = get_customer_merge_impact(source_id, target_id)
|
||||
assert preview['historical_references']['business_cases'] == 1
|
||||
assert preview['historical_references']['shipping_notices'] == 1
|
||||
# 合并预检同时展示旧识别证据与阶段一可配置证据的迁移统计。
|
||||
assert preview['migrate'] == {
|
||||
'identifiers': 1, 'duplicate_identifiers': 1, 'identity_evidences': 0,
|
||||
@@ -105,10 +105,10 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source_id).count() == 0
|
||||
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2
|
||||
assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1
|
||||
historical_case = db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-HISTORY').one()
|
||||
assert historical_case.customer_id == source_id
|
||||
assert historical_case.business_no == 'SRC26071601'
|
||||
assert historical_case.customer_short_code_snapshot == 'SRC'
|
||||
historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one()
|
||||
assert historical_notice.customer_id == source_id
|
||||
assert historical_notice.business_no == 'SRC26071601'
|
||||
assert historical_notice.customer_short_code_snapshot == 'SRC'
|
||||
assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1
|
||||
merge = db.session.get(ShippingCustomerMerge, result['merge_id'])
|
||||
assert merge is not None and merge.source_customer_id_snapshot == source_id
|
||||
|
||||
@@ -13,7 +13,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent
|
||||
from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice
|
||||
from app.services.admin.shipping_customer_service import (
|
||||
create_customer,
|
||||
create_identifier,
|
||||
@@ -219,7 +219,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
|
||||
"""列表返回业务单和识别证据数量,避免管理端逐客户补查。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer()
|
||||
db.session.add(ShippingCase(case_no='CASE-COUNT-1', customer_id=customer['id']))
|
||||
db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id']))
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer['id'],
|
||||
identifier_type='name_alias',
|
||||
@@ -231,5 +231,5 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
|
||||
db.session.commit()
|
||||
|
||||
result = list_customers({'page': 1, 'page_size': 20})
|
||||
assert result['items'][0]['case_count'] == 1
|
||||
assert result['items'][0]['notice_count'] == 1
|
||||
assert result['items'][0]['identifier_count'] == 1
|
||||
@@ -11,7 +11,6 @@ from __future__ import annotations
|
||||
from app import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingIdentityDefinition,
|
||||
@@ -328,7 +327,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
|
||||
customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCase(case_no='CASE-DELETE-API', customer_id=customer.id))
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id))
|
||||
db.session.commit()
|
||||
customer_id = customer.id
|
||||
|
||||
@@ -364,7 +363,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
|
||||
customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias',
|
||||
normalized_value='SOURCEALIAS', status='approved', source='manual',
|
||||
),
|
||||
ShippingCase(case_no='CASE-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
|
||||
ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
|
||||
])
|
||||
db.session.commit()
|
||||
source_id = source.id
|
||||
@@ -397,7 +396,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
|
||||
with app.app_context():
|
||||
assert db.session.get(ShippingCustomer, source_id).status == 'merged'
|
||||
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1
|
||||
assert db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-API').one().customer_id == source_id
|
||||
assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id
|
||||
|
||||
|
||||
def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client):
|
||||
@@ -517,11 +516,10 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
|
||||
_create_users()
|
||||
wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active')
|
||||
correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active')
|
||||
case = ShippingCase(case_no='CASE-CORRECTION-API', numbering_status='pending')
|
||||
db.session.add_all([wrong, correct, case])
|
||||
db.session.add_all([wrong, correct])
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CORRECTION-API', shipping_case_id=case.id,
|
||||
task_no='SN-CORRECTION-API',
|
||||
source_type='manual', customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -529,7 +527,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
|
||||
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
|
||||
old_business_no = task.shipping_case.business_no
|
||||
old_business_no = task.business_no
|
||||
correct_id = correct.id
|
||||
|
||||
forbidden = client.post(
|
||||
@@ -549,7 +547,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
|
||||
assert payload['old_business_no'] == old_business_no
|
||||
assert payload['new_business_no'].startswith('NEW')
|
||||
with app.app_context():
|
||||
old_case = ShippingCase.query.filter_by(business_no=old_business_no).one()
|
||||
replacement = ShippingCase.query.filter_by(replaces_case_id=old_case.id).one()
|
||||
assert old_case.status == 'voided'
|
||||
old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one()
|
||||
replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one()
|
||||
assert old_notice.lifecycle_status == 'voided'
|
||||
assert replacement.business_no == payload['new_business_no']
|
||||
@@ -55,6 +55,8 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
|
||||
assert created['profile_code'] != 'CLIENT_SUPPLIED_CODE'
|
||||
assert created['draft_revision']['revision_no'] == 1
|
||||
assert created['edit_lease']['browser_session_id'] == 'wizard-tab-a'
|
||||
# 主表身份必须同时冻结在 Profile 定义和两类共同视觉样本上。
|
||||
assert created['definition']['main_table_id'] == 'sample-table'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1
|
||||
@@ -115,6 +117,27 @@ def test_public_identity_signature_owns_coordinate_run_lifecycle(app, monkeypatc
|
||||
assert signature['run_type'] == 'layout_signature'
|
||||
|
||||
|
||||
def test_runtime_adapter_does_not_route_plain_pdf_by_stale_xfa_capability(monkeypatch):
|
||||
"""关键断言:普通 PDF 的残留 XFA capability 不得改变正式值源路由。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
|
||||
monkeypatch.setattr(xfa_dataset, 'xfa_enabled', lambda: True)
|
||||
stale_plain_pdf_layout = {
|
||||
'document_kind': 'plain_pdf',
|
||||
'xfa_capability': {'structure_analysis_ready': True},
|
||||
}
|
||||
assert xfa_dataset.owns_layout(stale_plain_pdf_layout) is False
|
||||
|
||||
supported_xfa_layout = {
|
||||
'document_kind': 'xfa_hybrid',
|
||||
'xfa_capability': {
|
||||
'document_kind': 'xfa_hybrid',
|
||||
'structure_analysis_ready': True,
|
||||
},
|
||||
}
|
||||
assert xfa_dataset.owns_layout(supported_xfa_layout) is True
|
||||
|
||||
|
||||
def test_wizard_xfa_mode_creates_visual_main_table_draft_before_dataset_mapping(app, monkeypatch):
|
||||
"""关键断言:XFA 向导只冻结视觉主表;datasets 选择留给编辑映射,发布仍 fail-closed。"""
|
||||
from hashlib import sha256
|
||||
|
||||
@@ -46,7 +46,11 @@ def _signature_run(profile: dict) -> ShippingOrderDocumentProfileValidationRun:
|
||||
profile_id=profile['id'], revision_no=profile['draft_revision']['revision_no'],
|
||||
definition_checksum=profile['draft_revision']['definition_checksum'], schema_version_id=profile['schema_version_id'],
|
||||
run_type='layout_signature', status='passed',
|
||||
summary_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'},
|
||||
summary_json={
|
||||
'signature_checksum': 'sig-checksum',
|
||||
'matcher_policy_version': 'profile-layout-matcher',
|
||||
'evidence_contract_version': validation_service.LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION,
|
||||
},
|
||||
result_snapshot_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'},
|
||||
operation_id='signature-validation',
|
||||
)
|
||||
@@ -160,6 +164,37 @@ def test_report_blocks_when_signature_missing(app, monkeypatch):
|
||||
assert 'signature_required' in keys or 'overlap_validation_required' in keys
|
||||
|
||||
|
||||
def test_report_ignores_submitted_pre_hydration_signature(app, monkeypatch):
|
||||
"""页面提交旧签名 ID 时,发布检查必须忽略它并通过统一入口重建当前签名。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
|
||||
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-legacy-signature-create')
|
||||
lease = _lease(draft['id']); run = _passing_run(draft)
|
||||
legacy = _signature_run(draft)
|
||||
legacy.summary_json = {
|
||||
key: value for key, value in legacy.summary_json.items()
|
||||
if key != 'evidence_contract_version'
|
||||
}
|
||||
db.session.commit()
|
||||
fresh = _signature_run(draft)
|
||||
overlap = _overlap_run(draft)
|
||||
calls: list[int] = []
|
||||
|
||||
def _resolve(profile, _revision, **_kwargs):
|
||||
calls.append(profile.id)
|
||||
return fresh
|
||||
|
||||
monkeypatch.setattr(validation_service, 'resolve_profile_identity_signature', _resolve)
|
||||
monkeypatch.setattr(validation_service, 'run_cross_template_overlap', lambda *args, **kwargs: {'id': overlap.id, 'status': 'passed', 'stored_status': 'passed'})
|
||||
report = checks.create_report(
|
||||
draft['id'], data={'validation_run_id': run.id, 'matching_signature_run_id': legacy.id, 'overlap_validation_run_id': overlap.id},
|
||||
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-legacy-signature-report',
|
||||
)
|
||||
|
||||
assert calls == [draft['id']]
|
||||
assert report['matching_signature_run_id'] == fresh.id
|
||||
|
||||
|
||||
def test_report_blocks_when_overlap_failed(app, monkeypatch):
|
||||
"""关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。"""
|
||||
with app.app_context():
|
||||
@@ -202,8 +237,8 @@ def test_report_invalidates_when_signature_cleared(app, monkeypatch):
|
||||
assert refreshed['status'] == 'invalidated'
|
||||
|
||||
|
||||
def test_consume_report_blocks_editor_self_approval(app, monkeypatch):
|
||||
"""职责分离:最近映射编辑者不得消费自己的发布检查报告。"""
|
||||
def test_consume_report_allows_editor_self_approval(app, monkeypatch):
|
||||
"""业务规则:管理员可确认发布自己编辑的订单模板草稿。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
|
||||
monkeypatch.setattr(
|
||||
@@ -244,15 +279,9 @@ def test_consume_report_blocks_editor_self_approval(app, monkeypatch):
|
||||
operation_id='pc-sod-report',
|
||||
)
|
||||
keys = [str(item['key']) for item in report['warning_items']]
|
||||
with pytest.raises(ValidationError) as error:
|
||||
checks.consume_report(
|
||||
draft['id'],
|
||||
report['report_no'],
|
||||
data={'confirmed_warning_keys': keys},
|
||||
actor_id=editor.id,
|
||||
browser_session_id='publish-check-tab',
|
||||
lease_token=lease['lease_token'],
|
||||
operation_id='pc-sod-consume',
|
||||
)
|
||||
assert error.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID'
|
||||
assert (error.value.details or {}).get('key') == 'editor_cannot_approve_own_version'
|
||||
published = checks.consume_report(
|
||||
draft['id'], report['report_no'], data={'confirmed_warning_keys': keys},
|
||||
actor_id=editor.id, browser_session_id='publish-check-tab',
|
||||
lease_token=lease['lease_token'], operation_id='pc-sod-consume',
|
||||
)
|
||||
assert published['status'] == 'published'
|
||||
@@ -85,6 +85,71 @@ def test_frozen_sample_layout_survives_source_document_retention_cleanup(monkeyp
|
||||
assert validation_service._load_sample_layout(sample) == frozen_layout
|
||||
|
||||
|
||||
def test_frozen_sample_layout_hydrates_coordinate_evidence_reference(monkeypatch):
|
||||
"""压缩 Layout 仍须通过其 FileAsset 引用恢复坐标证据,供签名和发布校验使用。"""
|
||||
sample = SimpleNamespace(document_id=992, layout_version_id=772)
|
||||
frozen_layout = {'status': 'ready', 'coordinate_evidence_ref': {'asset_no': 'evidence-asset'}}
|
||||
document = SimpleNamespace(id=992)
|
||||
hydrated_layout = {
|
||||
**frozen_layout,
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 100}}},
|
||||
}
|
||||
|
||||
def _get(model, identity):
|
||||
if model.__name__ == 'ShippingDocumentLayoutVersion' and identity == 772:
|
||||
return SimpleNamespace(payload_json=frozen_layout)
|
||||
if model.__name__ == 'ShippingOrderDocument' and identity == 992:
|
||||
return document
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(validation_service.db.session, 'get', _get)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.lifecycle._hydrate_coordinate_evidence',
|
||||
lambda *, payload, document: hydrated_layout,
|
||||
)
|
||||
|
||||
assert validation_service._load_sample_layout(sample) == hydrated_layout
|
||||
|
||||
|
||||
def test_profile_identity_signature_rejects_pre_hydration_signature(monkeypatch):
|
||||
"""旧证据契约生成的签名不能在修复后继续参与发布唯一性校验。"""
|
||||
profile = SimpleNamespace(
|
||||
id=93,
|
||||
matching_signature_run_id=94,
|
||||
matching_signature_checksum='old-signature',
|
||||
matching_signature_version='order-profile-layout-signature',
|
||||
)
|
||||
revision = SimpleNamespace(definition_checksum='definition-checksum')
|
||||
legacy_run = SimpleNamespace(
|
||||
profile_id=93,
|
||||
run_type='layout_signature',
|
||||
status='passed',
|
||||
definition_checksum='definition-checksum',
|
||||
summary_json={},
|
||||
result_snapshot_json={'signature_checksum': 'old-signature'},
|
||||
)
|
||||
monkeypatch.setattr(validation_service.db.session, 'get', lambda *_args: legacy_run)
|
||||
|
||||
with pytest.raises(Exception) as error:
|
||||
validation_service.resolve_profile_identity_signature(profile, revision, auto_run=False)
|
||||
|
||||
assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE'
|
||||
|
||||
|
||||
def test_match_thresholds_preserve_explicit_zero_score_and_margin():
|
||||
"""模板允许唯一命中不设分数/间距下限时,发布校验不得把 0 覆盖为默认门槛。"""
|
||||
thresholds = validation_service._match_thresholds({
|
||||
'document_match': {
|
||||
'minimum_score': 0.0,
|
||||
'minimum_margin': 0.0,
|
||||
'scoring_thresholds': {'evidence_coverage_minimum': 0.7},
|
||||
},
|
||||
})
|
||||
|
||||
assert thresholds['minimum_score'] == 0.0
|
||||
assert thresholds['minimum_margin'] == 0.0
|
||||
|
||||
|
||||
def test_failed_current_sample_run_remains_queryable(app):
|
||||
"""关键断言:运行时样本证据不可用也必须保存 failed 摘要,方便后续审计而非吞掉失败。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -8,7 +8,10 @@ from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_extraction_workflow import _build_approved_profile_order_result
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_build_approved_profile_order_result,
|
||||
_reservation_region_candidates,
|
||||
)
|
||||
|
||||
|
||||
SCHEMA = {'schema_version_id': 1, 'checksum': 'schema'}
|
||||
@@ -18,6 +21,14 @@ DEFINITION = {'fields': [
|
||||
{'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'required': True},
|
||||
]}
|
||||
|
||||
RESERVATION_DEFINITION = {
|
||||
'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1},
|
||||
'fields': DEFINITION['fields'] + [
|
||||
{'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header'},
|
||||
{'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _row(po: str, part: str) -> dict:
|
||||
return {'status': 'parsed', 'issues': [], 'fields': [
|
||||
@@ -27,6 +38,32 @@ def _row(po: str, part: str) -> dict:
|
||||
]}
|
||||
|
||||
|
||||
def _page_glyphs(*lines: str) -> list[dict]:
|
||||
"""构造跨页 Reservation 路由回归所需的最小坐标文字。"""
|
||||
glyphs = []
|
||||
for row_index, line in enumerate(lines):
|
||||
for column_index, char in enumerate(line):
|
||||
glyphs.append({
|
||||
'text': char,
|
||||
'bbox': {'x0': column_index * 8, 'x1': column_index * 8 + 6, 'y0': row_index * 16, 'y1': row_index * 16 + 12},
|
||||
'source_index': len(glyphs),
|
||||
'boundary_before': 'space' if char == ' ' else 'none',
|
||||
})
|
||||
return glyphs
|
||||
|
||||
|
||||
def _two_page_layout() -> dict:
|
||||
return {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 800, 'height': 600}, '2': {'width': 800, 'height': 600}},
|
||||
'page_glyphs': {
|
||||
'1': _page_glyphs('Vendor Comments:', 'Reservation#33008'),
|
||||
'2': _page_glyphs('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999'),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_approved_pdf_rejects_multiple_pos_in_one_pdf():
|
||||
"""同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
@@ -47,3 +84,75 @@ def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven():
|
||||
)
|
||||
assert reason is None
|
||||
assert len(orders or []) == 1
|
||||
|
||||
|
||||
def test_approved_pdf_writes_unnumbered_reservation_to_header_and_line_value_to_its_row():
|
||||
"""同一证据区可同时提供整单默认 Reservation 与指定行覆盖值。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=RESERVATION_DEFINITION,
|
||||
table={'rows': [_row('PO-1', 'P-1'), _row('PO-1', 'P-2')]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '33008', 'scope': 'header', 'line_no': None, 'raw_text': 'Reservation#33008'},
|
||||
{'value': '3000098851', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098851 for line#1'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert any(
|
||||
item['field_id'] == 'header-reservation' and item['observations'][0]['value'] == '33008'
|
||||
for item in order['header_fields']
|
||||
)
|
||||
assert any(
|
||||
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == '3000098851'
|
||||
for item in order['lines'][0]['fields']
|
||||
)
|
||||
assert not any(item['field_id'] == 'line-reservation' for item in order['lines'][1]['fields'])
|
||||
|
||||
|
||||
def test_approved_pdf_marks_conflicting_reservation_region_for_review():
|
||||
"""同一逻辑行的不同 Reservation 不得被任意选择。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '3000098851', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098851 for line#1'},
|
||||
{'value': '3000098852', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098852 for line#1'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
|
||||
"""已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。"""
|
||||
result = _reservation_region_candidates(
|
||||
raw_profile={'definition': RESERVATION_DEFINITION}, layout=_two_page_layout(),
|
||||
)
|
||||
|
||||
assert result['reason'] is None
|
||||
assert [item['value'] for item in result['candidates']] == ['33008', '3000098851']
|
||||
|
||||
|
||||
def test_profile_without_reservation_region_does_not_scan_vendor_comments():
|
||||
"""未标注专区的模板必须保持既有行为,不得扫描正文中的 Reservation。"""
|
||||
result = _reservation_region_candidates(
|
||||
raw_profile={'definition': DEFINITION}, layout=_two_page_layout(),
|
||||
)
|
||||
|
||||
assert result == {'candidates': [], 'reason': None}
|
||||
|
||||
|
||||
def test_enabled_reservation_region_requires_review_when_terms_heading_is_missing():
|
||||
"""专区缺少结束锚点时,不得把未封闭文本区的值当成可自动建单证据。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]},
|
||||
reservation_region_reason='terms_and_conditions_anchor_missing',
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
|
||||
assert (orders or [])[0]['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing']
|
||||
@@ -8,6 +8,8 @@ tests/test_post_ot_fulfillment_wave_p0.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -16,6 +18,99 @@ import pytest
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
|
||||
def test_create_post_ot_wave_uses_standard_fulfillment_audit_snapshot_keywords():
|
||||
"""履约波次审计必须使用统一的 before/after 状态摘要参数。"""
|
||||
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
|
||||
|
||||
function_node = ast.parse(inspect.getsource(svc.create_post_ot_fulfillment_wave)).body[0]
|
||||
audit_calls = [
|
||||
node
|
||||
for node in ast.walk(function_node)
|
||||
if isinstance(node, ast.Call)
|
||||
and isinstance(node.func, ast.Name)
|
||||
and node.func.id == 'record_fulfillment_audit'
|
||||
]
|
||||
|
||||
assert len(audit_calls) == 1
|
||||
keyword_names = {keyword.arg for keyword in audit_calls[0].keywords}
|
||||
assert {'before', 'after'} <= keyword_names
|
||||
assert not {'before_json', 'after_json'} & keyword_names
|
||||
|
||||
|
||||
def test_released_shortage_line_is_eligible_for_post_ot_wave():
|
||||
"""短缺放行仅完成审批,后续必须允许该行进入独立发货通知波次。"""
|
||||
from app.services.shipping_notice.post_ot_fulfillment_wave_service import _assert_fact_allows_fulfill
|
||||
|
||||
required, available = _assert_fact_allows_fulfill({
|
||||
'line_key': 'L-RELEASED',
|
||||
'inventory_status': 'ready',
|
||||
'match_result': 'matched',
|
||||
'is_shortage': True,
|
||||
'required_qty': '3',
|
||||
'available_qty': '0',
|
||||
'decision': {'decision_code': 'release_inventory_shortage'},
|
||||
})
|
||||
|
||||
assert str(required) == '3'
|
||||
assert str(available) == '0'
|
||||
|
||||
|
||||
def test_list_eligible_post_ot_lines_keeps_released_shortage_only():
|
||||
"""库存不足明细必须先有放行审计决定,才能成为 wave 候选。"""
|
||||
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
|
||||
|
||||
case = SimpleNamespace(id=1)
|
||||
with patch.object(svc, 'project_review_case_line_decisions', return_value={'lines': [
|
||||
{
|
||||
'line_key': 'released', 'line_status': 'released_shortage',
|
||||
'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True,
|
||||
'required_qty': '3', 'available_qty': '0',
|
||||
'decision': {'decision_code': 'release_inventory_shortage'},
|
||||
},
|
||||
{
|
||||
'line_key': 'unreleased', 'line_status': 'pending_decision',
|
||||
'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True,
|
||||
'required_qty': '3', 'available_qty': '0',
|
||||
'decision': None,
|
||||
},
|
||||
]}):
|
||||
assert svc.list_eligible_post_ot_line_keys(case) == ['released']
|
||||
|
||||
|
||||
def test_post_ot_wave_creates_a_distinct_notice_with_only_selected_lines(app):
|
||||
"""波次必须产生独立 Notice,且其 NoticeLine 只能包含本次勾选项次。"""
|
||||
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
|
||||
|
||||
selected = [SimpleNamespace(
|
||||
id=101, position=0, line_no='10', part_number='PN-10',
|
||||
reservation_id='RES-10', qty='2', field_values_json={},
|
||||
)]
|
||||
snapshot = SimpleNamespace(lines=[
|
||||
*selected,
|
||||
SimpleNamespace(
|
||||
id=102, position=1, line_no='20', part_number='PN-20',
|
||||
reservation_id='RES-20', qty='3', field_values_json={},
|
||||
),
|
||||
])
|
||||
added: list = []
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch('app.services.shipping_notice.notice_line_service.db.session.query') as query,
|
||||
patch('app.services.shipping_notice.notice_line_service.db.session.add_all', side_effect=added.extend),
|
||||
patch('app.services.shipping_notice.notice_line_service.db.session.flush'),
|
||||
):
|
||||
query.return_value.filter_by.return_value.delete.return_value = 0
|
||||
count = replace_notice_lines_from_snapshot(
|
||||
notice_id=9,
|
||||
snapshot=snapshot,
|
||||
snapshot_line_ids={101},
|
||||
)
|
||||
|
||||
assert count == 1
|
||||
assert [(row.notice_id, row.snapshot_line_id, row.line_key) for row in added] == [(9, 101, '10')]
|
||||
|
||||
|
||||
def test_create_post_ot_wave_idempotent_replay_returns_original(app):
|
||||
"""同 key 且参数一致必须返回原 wave,不二次建波。"""
|
||||
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
|
||||
@@ -143,7 +238,12 @@ def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app):
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(coord, 'line_auto_fulfill_enabled', return_value=True),
|
||||
patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']),
|
||||
patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']),
|
||||
patch.object(
|
||||
coord,
|
||||
'project_review_case_line_decisions',
|
||||
return_value={'lines': [{'line_key': 'L1', 'line_status': 'ready_to_fulfill'}]},
|
||||
),
|
||||
patch.object(coord, 'create_post_ot_fulfillment_wave', side_effect=_boom),
|
||||
patch.object(coord.db.session, 'rollback', side_effect=lambda: calls.append('rollback')),
|
||||
patch.object(coord.db.session, 'flush', side_effect=lambda: calls.append('flush')),
|
||||
@@ -159,6 +259,32 @@ def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app):
|
||||
schedule_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_coordinate_auto_fulfill_requires_manual_selection_for_multiple_lines(app):
|
||||
"""多条开放明细不得由系统自动合并为同一张发货通知单。"""
|
||||
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(id=3, case_no='RC-MULTI', confirmed_task_id=8)
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(coord, 'line_auto_fulfill_enabled', return_value=True),
|
||||
patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1', 'L2']),
|
||||
patch.object(
|
||||
coord,
|
||||
'project_review_case_line_decisions',
|
||||
return_value={'lines': [
|
||||
{'line_key': 'L1', 'line_status': 'released_shortage'},
|
||||
{'line_key': 'L2', 'line_status': 'ready_to_fulfill'},
|
||||
]},
|
||||
),
|
||||
patch.object(coord, 'create_post_ot_fulfillment_wave') as create_mock,
|
||||
):
|
||||
out = coord.coordinate_post_ot_auto_fulfill(case=case, trigger='inventory_shortage_released')
|
||||
|
||||
assert out['status'] == 'idle'
|
||||
assert out['reason'] == 'manual_wave_selection_required'
|
||||
create_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_mark_auto_fulfill_failed_does_not_create_wait_inventory(app):
|
||||
"""无活动决定时只写匹配事实 detail,不新建 wait_inventory 决定。"""
|
||||
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_business_numbering.py
|
||||
|
||||
用途:验证货代业务编号格式、上海日期、两位流水上限及业务单版本继承。
|
||||
依赖:ShippingCase/Customer/Sequence、business_numbering_service、customer_identity_gate。
|
||||
逻辑:直接调用领域服务,覆盖幂等、01-99、修订共享与强制新建独立编号。
|
||||
用途:验证货代业务编号格式、上海日期、两位流水上限及 Notice 独立编号。
|
||||
依赖:ShippingNotice/Customer/Sequence、business_numbering_service、customer_identity_gate。
|
||||
逻辑:直接调用领域服务,覆盖幂等、01-99 与替代 Notice 独立编号。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
@@ -12,9 +12,9 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.business_numbering_service import (
|
||||
assign_business_number,
|
||||
assign_notice_business_number,
|
||||
format_business_no,
|
||||
shanghai_business_date,
|
||||
)
|
||||
@@ -22,25 +22,23 @@ from app.services.shipping_notice.customer_identity_gate import confirm_task_cus
|
||||
from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref
|
||||
|
||||
|
||||
def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
|
||||
"""创建待客户确认的业务单、任务和启用客户。"""
|
||||
def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
|
||||
"""创建待客户确认的 Notice 和启用客户。"""
|
||||
customer = ShippingCustomer(
|
||||
standard_name=f"编号测试客户 {short_code}",
|
||||
short_code=short_code,
|
||||
status="active",
|
||||
)
|
||||
case = ShippingCase(case_no=f"CASE-{task_no}", numbering_status="pending")
|
||||
db.session.add_all([customer, case])
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=task_no,
|
||||
shipping_case_id=case.id,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return task, case, customer
|
||||
return task, customer
|
||||
|
||||
|
||||
def test_number_format_and_shanghai_date_boundary(app):
|
||||
@@ -55,53 +53,89 @@ def test_number_format_and_shanghai_date_boundary(app):
|
||||
def test_confirmation_assigns_idempotent_business_number(app):
|
||||
"""重复确认同一客户不得重复占用流水,正式编号保持不变。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
task, customer = _seed_notice()
|
||||
first = confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
first_no = first.shipping_case.business_no
|
||||
first_no = first.business_no
|
||||
second = confirm_task_customer(first, customer_id=customer.id, actor_id=None)
|
||||
|
||||
assert first_no
|
||||
assert second.shipping_case.business_no == first_no
|
||||
assert second.business_no == first_no
|
||||
assert ShippingBusinessSequence.query.one().current_value == 1
|
||||
assert second.shipping_case.customer_short_code_snapshot == "WYC"
|
||||
assert second.customer_short_code_snapshot == "WYC"
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1
|
||||
|
||||
|
||||
def test_revision_inherits_and_force_case_uses_next_sequence(app):
|
||||
"""同一业务单修订继承编号,独立业务单确认同客户时占用下一流水。"""
|
||||
def test_each_notice_gets_a_distinct_business_number_for_same_customer(app):
|
||||
"""同一客户 PO 的不同发货通知必须各自占用独立业务流水。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
customer = ShippingCustomer(
|
||||
standard_name='通知单波次客户', short_code='WVC', status='active',
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
first = ShippingNotice(task_no='SN-NOTICE-NO-1', customer_resolution_status='confirmed')
|
||||
second = ShippingNotice(task_no='SN-NOTICE-NO-2', customer_resolution_status='confirmed')
|
||||
db.session.add_all([first, second])
|
||||
db.session.flush()
|
||||
first.customer_id = customer.id
|
||||
second.customer_id = customer.id
|
||||
db.session.flush()
|
||||
|
||||
first_no = assign_notice_business_number(first)
|
||||
second_no = assign_notice_business_number(second)
|
||||
|
||||
assert first_no != second_no
|
||||
assert first.business_no == first_no
|
||||
assert second.business_no == second_no
|
||||
|
||||
|
||||
def test_notice_confirms_customer_and_assigns_number_without_shipping_case(app):
|
||||
"""新 Notice 必须自持客户快照与编号,不能要求 ShippingCase 作为前置容器。"""
|
||||
with app.app_context():
|
||||
customer = ShippingCustomer(
|
||||
standard_name='Notice 自持客户', short_code='NHC', status='active',
|
||||
)
|
||||
task = ShippingNotice(
|
||||
task_no='SN-NOTICE-SELF-CUSTOMER',
|
||||
customer_resolution_status='pending',
|
||||
source_type='manual',
|
||||
)
|
||||
db.session.add_all([customer, task])
|
||||
db.session.commit()
|
||||
|
||||
confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=7)
|
||||
|
||||
assert confirmed.customer_id == customer.id
|
||||
assert confirmed.customer_name_snapshot == 'Notice 自持客户'
|
||||
assert confirmed.customer_short_code_snapshot == 'NHC'
|
||||
assert confirmed.business_no
|
||||
assert confirmed.customer_resolution_status == 'confirmed'
|
||||
|
||||
|
||||
def test_replacement_notice_uses_next_sequence(app):
|
||||
"""替代 Notice 保留原号审计并为新 Notice 分配下一业务号。"""
|
||||
with app.app_context():
|
||||
task, customer = _seed_notice()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
revision = ShippingNotice(
|
||||
task_no="SN-NUMBER-REV",
|
||||
shipping_case_id=case.id,
|
||||
supersedes_task_id=task.id,
|
||||
customer_resolution_status="confirmed",
|
||||
source_type="manual",
|
||||
)
|
||||
forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending")
|
||||
db.session.add_all([revision, forced_case])
|
||||
db.session.flush()
|
||||
forced_task = ShippingNotice(
|
||||
task_no="SN-NUMBER-FORCED",
|
||||
shipping_case_id=forced_case.id,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add(forced_task)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
confirm_task_customer(forced_task, customer_id=customer.id, actor_id=None)
|
||||
assert revision.shipping_case.business_no == case.business_no
|
||||
assert forced_task.shipping_case.business_no[:-2] == case.business_no[:-2]
|
||||
assert case.business_no.endswith("01")
|
||||
assert forced_task.shipping_case.business_no.endswith("02")
|
||||
confirm_task_customer(revision, customer_id=customer.id, actor_id=None)
|
||||
assert revision.business_no[:-2] == task.business_no[:-2]
|
||||
assert task.business_no.endswith("01")
|
||||
assert revision.business_no.endswith("02")
|
||||
|
||||
|
||||
def test_daily_sequence_blocks_one_hundredth_case(app):
|
||||
"""客户当日已有 99 笔时,第 100 笔必须阻断且不写业务号。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
task, customer = _seed_notice()
|
||||
business_date = shanghai_business_date()
|
||||
db.session.add(ShippingBusinessSequence(
|
||||
business_type="shipping_notice",
|
||||
@@ -110,19 +144,19 @@ def test_daily_sequence_blocks_one_hundredth_case(app):
|
||||
current_value=99,
|
||||
))
|
||||
db.session.commit()
|
||||
case.customer_id = customer.id
|
||||
task.customer_id = customer.id
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
assign_business_number(case)
|
||||
assign_notice_business_number(task)
|
||||
assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED"
|
||||
assert case.business_no is None
|
||||
assert task.business_no is None
|
||||
assert ShippingBusinessSequence.query.one().current_value == 99
|
||||
|
||||
|
||||
def test_numbering_failure_rolls_back_customer_confirmation(app):
|
||||
"""流水耗尽导致确认失败时,业务单客户和任务确认状态不得半落库。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
task, customer = _seed_notice()
|
||||
db.session.add(ShippingBusinessSequence(
|
||||
business_type="shipping_notice",
|
||||
customer_id=customer.id,
|
||||
@@ -135,43 +169,41 @@ def test_numbering_failure_rolls_back_customer_confirmation(app):
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
persisted_case = db.session.get(ShippingCase, case.id)
|
||||
persisted_task = db.session.get(ShippingNotice, task.id)
|
||||
assert persisted_case.customer_id is None
|
||||
assert persisted_case.business_no is None
|
||||
assert persisted_task.customer_id is None
|
||||
assert persisted_task.business_no is None
|
||||
assert persisted_task.customer_resolution_status == "pending"
|
||||
|
||||
|
||||
def test_business_number_query_returns_latest_revision(app):
|
||||
"""使用正式业务号查询时应返回同业务单最新修订任务。"""
|
||||
def test_business_number_query_returns_exact_notice(app):
|
||||
"""使用正式业务号查询时必须返回该 Notice,不能跳到替代版本。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
task, customer = _seed_notice()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
revision = ShippingNotice(
|
||||
task_no="SN-NUMBER-QUERY-REV",
|
||||
shipping_case_id=case.id,
|
||||
supersedes_task_id=task.id,
|
||||
document_version=2,
|
||||
customer_resolution_status="confirmed",
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
resolved = get_task_by_ref(case.business_no)
|
||||
assert resolved.id == revision.id
|
||||
assert extract_task_no_from_text(f"请继续处理 {case.business_no}") == case.business_no
|
||||
resolved = get_task_by_ref(task.business_no)
|
||||
assert resolved.id == task.id
|
||||
assert extract_task_no_from_text(f"请继续处理 {task.business_no}") == task.business_no
|
||||
|
||||
|
||||
def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app):
|
||||
"""客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。"""
|
||||
with app.app_context():
|
||||
task, case, customer = _seed_case()
|
||||
case.customer_id = customer.id
|
||||
task, customer = _seed_notice()
|
||||
task.customer_id = customer.id
|
||||
customer.short_code = "W1"
|
||||
# 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。
|
||||
with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info:
|
||||
assign_business_number(case)
|
||||
assign_notice_business_number(task)
|
||||
assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID"
|
||||
assert case.business_no is None
|
||||
assert task.business_no is None
|
||||
db.session.rollback()
|
||||
@@ -12,8 +12,12 @@ from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
coordinate_profile_character_candidates,
|
||||
_text_in_region,
|
||||
_text_in_horizontal_region,
|
||||
reconstruction_exclusion_regions,
|
||||
reconstruct_coordinate_profile_rows,
|
||||
reconstruct_coordinate_profile_rows_with_strategy,
|
||||
reconstruct_table_from_positioned_text,
|
||||
resolve_line_start_field_code,
|
||||
suggest_header_layouts,
|
||||
@@ -65,6 +69,87 @@ def _adaptive_layouts() -> list[dict]:
|
||||
]
|
||||
|
||||
|
||||
def test_coordinate_profile_character_candidates_share_page_first_union_contract():
|
||||
"""三条解析链路应得到同一套整页优先、纵向并集字符候选。"""
|
||||
page_characters = [
|
||||
{'text': 'H', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}},
|
||||
{'text': 'D', 'bbox': {'x0': 10, 'y0': 160, 'x1': 20, 'y1': 170}},
|
||||
{'text': 'X', 'bbox': {'x0': 300, 'y0': 160, 'x1': 310, 'y1': 170}},
|
||||
]
|
||||
table_characters = [{'text': 'legacy', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]
|
||||
characters, page_bbox = coordinate_profile_character_candidates(
|
||||
table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5},
|
||||
page_size={'width': 400, 'height': 400}, page_characters=page_characters,
|
||||
table_characters=table_characters,
|
||||
raw_table_bbox={'x0': 0, 'y0': 120, 'x1': 200, 'y1': 180},
|
||||
table_id='table-1', page_no=1,
|
||||
)
|
||||
assert page_bbox == {'x0': 0.0, 'y0': 0.0, 'x1': 400.0, 'y1': 400.0}
|
||||
assert [item['text'] for item in characters or []] == ['H', 'D']
|
||||
|
||||
|
||||
def test_coordinate_profile_character_candidates_use_annotation_page_frame_on_taller_runtime_page():
|
||||
"""分页训练表区在未分页长页中必须保持原始 PDF 点坐标,不能按新页高拉伸。"""
|
||||
characters, page_bbox = coordinate_profile_character_candidates(
|
||||
table_region={'x0': .0, 'y0': .2, 'x1': 1.0, 'y1': .3},
|
||||
reference_page_frame={'width': 200, 'height': 100},
|
||||
page_size={'width': 200, 'height': 200},
|
||||
page_characters=[
|
||||
{'text': 'line', 'bbox': {'x0': 10, 'y0': 21, 'x1': 30, 'y1': 29}},
|
||||
{'text': 'wrong', 'bbox': {'x0': 10, 'y0': 41, 'x1': 35, 'y1': 49}},
|
||||
],
|
||||
table_characters=None, table_id='page-1', page_no=1,
|
||||
)
|
||||
|
||||
# 关键断言:训练页 .2-.3 对应 y=20..30,而不是长页 y=40..60。
|
||||
assert page_bbox == {'x0': 0.0, 'y0': 0.0, 'x1': 200.0, 'y1': 200.0}
|
||||
assert [item['text'] for item in characters or []] == ['line']
|
||||
|
||||
|
||||
def test_coordinate_profile_character_candidates_fallback_when_page_crop_is_empty():
|
||||
"""空的页级裁剪不能覆盖仍可用的当前表字符证据。"""
|
||||
characters, _ = coordinate_profile_character_candidates(
|
||||
table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5},
|
||||
page_size={'width': 100, 'height': 100},
|
||||
page_characters=[{'text': 'header', 'bbox': {'x0': 80, 'y0': 80, 'x1': 90, 'y1': 90}}],
|
||||
table_characters=[{'text': '10', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}],
|
||||
table_id='table-1', page_no=1,
|
||||
)
|
||||
assert [item['text'] for item in characters or []] == ['10']
|
||||
|
||||
|
||||
def test_coordinate_profile_character_candidates_do_not_reuse_table_on_other_page():
|
||||
"""续页没有自己的页级候选时,不能重复消费首页表字符。"""
|
||||
characters, _ = coordinate_profile_character_candidates(
|
||||
table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5},
|
||||
page_size={'width': 100, 'height': 100},
|
||||
page_characters=[],
|
||||
table_characters=[{'text': '10', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}],
|
||||
table_id='table-1', page_no=2, allow_table_fallback=False,
|
||||
)
|
||||
assert characters is None
|
||||
|
||||
|
||||
def test_reconstruction_exclusions_do_not_treat_header_layouts_as_deleted_text():
|
||||
"""表头框是语义/预览证据,默认不得在明细起行前删除相交字符。"""
|
||||
exclusions = reconstruction_exclusion_regions({
|
||||
'exclusion_regions': [{'x0': .1, 'y0': .1, 'x1': .2, 'y1': .2}],
|
||||
'header_layouts': [{'region': {'x0': .0, 'y0': .2, 'x1': 1, 'y1': .4}}],
|
||||
})
|
||||
|
||||
assert exclusions == [{'x0': .1, 'y0': .1, 'x1': .2, 'y1': .2}]
|
||||
|
||||
|
||||
def test_horizontal_region_keeps_a_character_that_intersects_its_right_edge():
|
||||
"""字段边界切过字形时必须保留该字,避免料号末尾标点被静默截断。"""
|
||||
glyphs = [
|
||||
(0, PositionedCharacter(text='A', bbox=LayoutBBox(x0=80, y0=20, x1=84, y1=30))),
|
||||
(1, PositionedCharacter(text='-', bbox=LayoutBBox(x0=99.9, y0=20, x1=103, y1=30))),
|
||||
]
|
||||
|
||||
assert _text_in_horizontal_region(glyphs, LayoutBBox(x0=80, y0=10, x1=100, y1=40)) == 'A -'
|
||||
|
||||
|
||||
def test_table_region_text_prefers_explicit_pdf_space_boundary():
|
||||
"""明细自由文本列应恢复 PDF 原始词边界,同时不依赖降低全局几何阈值。"""
|
||||
glyphs = [
|
||||
@@ -308,6 +393,114 @@ def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
|
||||
assert rows[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'}
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_require_multi_field_signature_for_new_records():
|
||||
"""孤立数字不能启动明细;同一视觉行的业务字段组合才可启动。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('0', 10)],
|
||||
[('20', 10), ('PART-A', 65), ('5', 160)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer', 'validator_keys': ['positive_integer']},
|
||||
],
|
||||
)
|
||||
|
||||
# 关键断言:表头/噪声中的孤立 0 不得成为第 1 条明细,真实组合只产生 1 条。
|
||||
assert [row.fields for row in rows] == [{
|
||||
'customer_po_line_no': '20', 'part_number': 'PART-A', 'qty': '5',
|
||||
}]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_can_start_without_line_number_when_business_fields_agree():
|
||||
"""客户行号缺失时,料号与数量等独立业务字段可在任意列位置联合起行。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('PART-A', 10), ('5', 160)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer', 'validator_keys': ['positive_integer']},
|
||||
],
|
||||
)
|
||||
|
||||
# 关键断言:起行不依赖列序或必须存在的行号字段。
|
||||
assert [row.fields for row in rows] == [{'part_number': 'PART-A', 'qty': '5'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_ignore_non_line_schema_fields_for_record_start():
|
||||
"""明细起行只消费 Schema scope=line,header 字段不能提供联合起行证据。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('Vendor', 10), ('PART-A', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'vendor', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'vendor', 'scope': 'header', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
# 只有一个 line 字段有效;header 字段不能把该视觉行提升为明细。
|
||||
assert rows == []
|
||||
|
||||
|
||||
def test_adaptive_record_start_uses_only_schema_line_fields_without_business_name_whitelist():
|
||||
"""自适应模式同样按 Schema line 字段联合起行,不能把表头文本当行号。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('0rd', 10), ('Shipping In', 65)], [('20', 10), ('PART-A', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
row_reconstruction_mode='adaptive_record_columns',
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{
|
||||
'customer_po_line_no': '20', 'customer_part_number': 'PART-A',
|
||||
}]
|
||||
|
||||
|
||||
def test_schema_string_line_anchor_rejects_header_text():
|
||||
"""string 类型起行字段仍须满足通用行号形态,不能接受表头文本。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('0rd', 10), ('PART-A', 65)], [('B', 10), ('PART-B', 65)], [('20', 10), ('PART-C', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{
|
||||
'customer_po_line_no': '20', 'part_number': 'PART-C',
|
||||
}]
|
||||
|
||||
|
||||
def test_line_number_can_be_used_as_a_configured_coordinate_anchor():
|
||||
"""用户选择项次字段时,坐标模板可用 line_no 启动明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
@@ -719,6 +912,133 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_dynamic_x_columns_recovers_a_shifted_record_hidden_by_static_header_exclusion():
|
||||
"""表头随单头高度移动时,动态候选须以起行/列校验恢复被旧表头框遮住的首条明细。"""
|
||||
rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
|
||||
characters=_glyphs(
|
||||
[('LN', 10), ('Quantity', 50), ('Part Number', 120)],
|
||||
[('1', 10), ('113', 50), ('PART-A', 120)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 60},
|
||||
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': .9},
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .5, 'x1': .15, 'y1': .7}},
|
||||
{'field_code': 'qty', 'region': {'x0': .15, 'y0': .5, 'x1': .4, 'y1': .7}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .4, 'y0': .5, 'x1': 1, 'y1': .7}},
|
||||
],
|
||||
}],
|
||||
exclusion_regions=[{'x0': 0, 'y0': .2, 'x1': 1, 'y1': .75}],
|
||||
dynamic_exclusion_regions=[],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
)
|
||||
|
||||
assert strategy.status == 'selected'
|
||||
assert strategy.row_mode == 'dynamic_x_columns'
|
||||
assert [row.fields for row in rows] == [
|
||||
{'customer_po_line_no': '1', 'qty': '113', 'part_number': 'PART-A'},
|
||||
]
|
||||
|
||||
|
||||
def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor():
|
||||
"""动态行整体上移时,跨视觉行字段须随同一锚点平移而非复用首行前缀。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('1', 10), ('113', 50), ('WTP-D4-', 120)],
|
||||
[('A08AR12000001', 120)],
|
||||
[('D4-A08AR12000001', 120)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 120},
|
||||
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .50, 'x1': 1, 'y1': .95},
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .15, 'y1': .80}},
|
||||
{'field_code': 'qty', 'region': {'x0': .15, 'y0': .70, 'x1': .4, 'y1': .80}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .4, 'y0': .70, 'x1': 1, 'y1': .90}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .4, 'y0': .92, 'x1': 1, 'y1': 1}},
|
||||
],
|
||||
}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
row_reconstruction_mode='dynamic_x_columns',
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{
|
||||
'customer_po_line_no': '1', 'qty': '113',
|
||||
'customer_part_number': 'WTP-D4-A08AR12000001',
|
||||
'part_number': 'D4-A08AR12000001',
|
||||
}]
|
||||
|
||||
|
||||
def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor():
|
||||
"""固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('1', 10), ('CUSTOMER-1', 60)], [('VENDOR-1', 60)],
|
||||
[('2', 10), ('CUSTOMER-2', 60)], [('VENDOR-2', 60)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 140},
|
||||
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .50, 'x1': 1, 'y1': .95},
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .60, 'x1': .2, 'y1': .70}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .60, 'x1': 1, 'y1': .68}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': .70, 'x1': 1, 'y1': .78}},
|
||||
],
|
||||
}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [
|
||||
{'customer_po_line_no': '1', 'customer_part_number': 'CUSTOMER-1', 'part_number': 'VENDOR-1'},
|
||||
{'customer_po_line_no': '2', 'customer_part_number': 'CUSTOMER-2', 'part_number': 'VENDOR-2'},
|
||||
]
|
||||
|
||||
|
||||
def test_coordinate_profile_strategy_prefers_fixed_for_wrapped_part_fields():
|
||||
"""跨视觉行字段必须使用字段框完整值,不能被 adaptive 前缀覆盖。"""
|
||||
schema = [
|
||||
{'field_code': code, 'scope': 'line', 'enabled': True, 'data_type': 'string'}
|
||||
for code in ('customer_po_line_no', 'customer_part_number', 'part_number')
|
||||
]
|
||||
rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
|
||||
characters=_glyphs(
|
||||
[('1', 10), ('WTP-B3-', 55)],
|
||||
[('A08AR11000001', 55)],
|
||||
[('B3-A08AR11000001', 55)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 70},
|
||||
table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .95},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .95},
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .4}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .7, 'y1': .65}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .65, 'x1': .7, 'y1': .9}},
|
||||
],
|
||||
}],
|
||||
schema_field_metadata=schema,
|
||||
line_start_field_code='customer_po_line_no',
|
||||
)
|
||||
|
||||
assert strategy.status == 'selected'
|
||||
assert strategy.row_mode == 'fixed_subrows'
|
||||
assert rows[0].fields['customer_part_number'] == 'WTP-B3-A08AR11000001'
|
||||
assert rows[0].fields['part_number'] == 'B3-A08AR11000001'
|
||||
assert rows[0].issues == []
|
||||
|
||||
deleted = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('B3-A08AR10000018-A7', 120)],
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_customer_auto_resolution.py
|
||||
|
||||
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice/Case、customer_auto_resolution。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
|
||||
"""
|
||||
|
||||
@@ -14,7 +14,6 @@ from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingIdentityDefinition,
|
||||
@@ -122,11 +121,10 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
candidate_key="document:1", validation_status="ready", selected=True,
|
||||
structured_result_json={"business_summary": {"customer_name": "unstable name"}},
|
||||
)
|
||||
case = ShippingCase(case_no=f"AUTO-CASE-{user.id}", numbering_status="pending")
|
||||
db.session.add_all([candidate, case])
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id,
|
||||
task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id,
|
||||
user_id=user.id, source_type="email_attachment",
|
||||
customer_resolution_status="pending",
|
||||
)
|
||||
@@ -216,8 +214,8 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
assert result["rule_version"] == AUTO_RESOLUTION_VERSION
|
||||
assert task.customer_resolution_status == "confirmed"
|
||||
assert task.customer_resolution_method == "auto_rule"
|
||||
assert task.shipping_case.customer_id == customer.id
|
||||
assert task.shipping_case.business_no.startswith("WYC")
|
||||
assert task.customer_id == customer.id
|
||||
assert task.business_no.startswith("WYC")
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1
|
||||
event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one()
|
||||
assert event.detail_json['rule_set']['checksum']
|
||||
@@ -240,13 +238,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False
|
||||
disabled = try_auto_confirm_task_customer(task)
|
||||
assert disabled["status"] == "disabled"
|
||||
assert task.shipping_case.business_no is None
|
||||
assert task.business_no is None
|
||||
|
||||
_allow_auto_confirmation(app)
|
||||
unmatched = try_auto_confirm_task_customer(task)
|
||||
assert unmatched["status"] == "unmatched"
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.shipping_case.business_no is None
|
||||
assert task.business_no is None
|
||||
|
||||
|
||||
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
@@ -261,7 +259,7 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
assert result["status"] == "ambiguous"
|
||||
assert len(result["candidate_customer_ids"]) == 2
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.shipping_case.business_no is None
|
||||
assert task.business_no is None
|
||||
|
||||
|
||||
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
@@ -271,7 +269,6 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
task = _seed_candidate_task()
|
||||
task_id = task.id
|
||||
case_id = task.shipping_case_id
|
||||
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
assert result["status"] == "auto_confirmed"
|
||||
@@ -279,10 +276,9 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
db.session.expire_all()
|
||||
|
||||
persisted_task = db.session.get(ShippingNotice, task_id)
|
||||
persisted_case = db.session.get(ShippingCase, case_id)
|
||||
assert persisted_task.customer_resolution_status == "pending"
|
||||
assert persisted_case.customer_id is None
|
||||
assert persisted_case.business_no is None
|
||||
assert persisted_task.customer_id is None
|
||||
assert persisted_task.business_no is None
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
|
||||
|
||||
|
||||
@@ -300,7 +296,7 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic
|
||||
assert result["status"] == "insufficient_labeled_samples"
|
||||
assert result["quality_gate"]["labeled_sample_count"] == 0
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.shipping_case.business_no is None
|
||||
assert task.business_no is None
|
||||
|
||||
|
||||
def test_business_evidence_never_auto_confirms(app):
|
||||
@@ -405,61 +401,48 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
|
||||
assert result["quality_gate"]["labeled_sample_count"] == 1
|
||||
assert result["quality_gate"]["accuracy"] == 0
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.shipping_case.business_no is None
|
||||
assert task.business_no is None
|
||||
|
||||
|
||||
def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
|
||||
"""客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。"""
|
||||
def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app):
|
||||
"""客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。"""
|
||||
with app.app_context():
|
||||
wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active")
|
||||
correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active")
|
||||
case = ShippingCase(case_no="CASE-CORRECTION", numbering_status="pending")
|
||||
db.session.add_all([wrong, correct, case])
|
||||
db.session.add_all([wrong, correct])
|
||||
db.session.flush()
|
||||
first = ShippingNotice(
|
||||
task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1,
|
||||
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", upload_status="pending",
|
||||
customer_resolution_status="pending", inventory_source_code="DSV",
|
||||
task_no="SN-CORRECTION-V1", document_version=1,
|
||||
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"}],
|
||||
export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx",
|
||||
)
|
||||
db.session.add(latest)
|
||||
db.session.add(first)
|
||||
db.session.commit()
|
||||
confirm_task_customer(first, customer_id=wrong.id, actor_id=None)
|
||||
old_case_id = case.id
|
||||
old_business_no = case.business_no
|
||||
old_business_no = first.business_no
|
||||
|
||||
result = correct_numbered_task_customer(
|
||||
latest,
|
||||
first,
|
||||
customer_id=correct.id,
|
||||
reason="自动识别客户错误",
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
old_case = db.session.get(ShippingCase, old_case_id)
|
||||
replacement = db.session.get(ShippingCase, result["new_case_id"])
|
||||
assert old_case.business_no == old_business_no
|
||||
assert old_case.status == "voided"
|
||||
assert old_case.numbering_status == "voided"
|
||||
assert replacement.replaces_case_id == old_case.id
|
||||
replacement = db.session.get(ShippingNotice, result["new_notice_id"])
|
||||
assert first.business_no == old_business_no
|
||||
assert first.lifecycle_status == "voided"
|
||||
assert replacement.supersedes_task_id == first.id
|
||||
assert replacement.business_no.startswith("NEW")
|
||||
assert replacement.business_no != old_business_no
|
||||
assert latest.shipping_case_id == replacement.id
|
||||
assert first.shipping_case_id == replacement.id
|
||||
assert latest.customer_resolution_method == "admin_correction"
|
||||
assert latest.inventory_source_status is None
|
||||
assert latest.inventory_lines_json is None
|
||||
assert latest.export_file_path is None
|
||||
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 replacement.customer_resolution_method == "admin_correction"
|
||||
assert replacement.inventory_source_status is None
|
||||
assert replacement.inventory_lines_json is None
|
||||
assert replacement.export_file_path is None
|
||||
assert replacement.source_type == "manual"
|
||||
assert get_task_by_ref(old_business_no).id == first.id
|
||||
assert get_task_by_ref(replacement.business_no).id == replacement.id
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert metrics["corrected_task_count"] == 2
|
||||
@@ -471,11 +454,10 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
|
||||
with app.app_context():
|
||||
wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active")
|
||||
correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active")
|
||||
case = ShippingCase(case_no="CASE-CORRECTION-BLOCK", numbering_status="pending")
|
||||
db.session.add_all([wrong, correct, case])
|
||||
db.session.add_all([wrong, correct])
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id,
|
||||
task_no="SN-CORRECTION-BLOCK",
|
||||
source_type="manual", customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -493,4 +475,4 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
|
||||
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
|
||||
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED"
|
||||
db.session.rollback()
|
||||
assert db.session.query(ShippingCase).count() == 1
|
||||
assert db.session.query(ShippingNotice).count() == 1
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_shipping_customer_identity_gate.py
|
||||
|
||||
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。
|
||||
依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。
|
||||
逻辑:构造 pending 或缺失业务单的任务逐入口断言无副作用;确认后验证业务单/修订同步。
|
||||
逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +15,7 @@ from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent, User
|
||||
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
assert_customer_identity_gate,
|
||||
confirm_task_customer,
|
||||
@@ -31,7 +31,7 @@ from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.task_workflow import retry_task
|
||||
|
||||
|
||||
def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]:
|
||||
def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]:
|
||||
"""创建待确认任务、启用客户和任务用户。"""
|
||||
sequence = db.session.query(User).count()
|
||||
user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user')
|
||||
@@ -39,14 +39,9 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCusto
|
||||
customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active')
|
||||
db.session.add_all([user, customer])
|
||||
db.session.flush()
|
||||
case = ShippingCase(case_no=f'CASE-GATE-{user.id}') if with_case else None
|
||||
if case:
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
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,
|
||||
customer_resolution_status='pending' if customer_pending else None,
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
|
||||
inventory_source_status='user_confirmed', inventory_source_code='DSV',
|
||||
)
|
||||
@@ -111,12 +106,12 @@ def test_pending_customer_blocks_retry_before_clearing_review_state(app):
|
||||
assert task.error_message == '标准客户尚未确认'
|
||||
|
||||
|
||||
def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
|
||||
"""客户确认同步同业务单全部任务,并在同事务生成正式业务号。"""
|
||||
def test_confirm_customer_does_not_assign_notice_number_before_excel(app):
|
||||
"""客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
revision = ShippingNotice(
|
||||
task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id,
|
||||
task_no='SN-GATE-REV', user_id=user.id,
|
||||
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(revision)
|
||||
@@ -124,24 +119,60 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
|
||||
|
||||
updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
db.session.refresh(revision)
|
||||
case = db.session.get(ShippingCase, task.shipping_case_id)
|
||||
assert updated.customer_resolution_status == 'confirmed'
|
||||
assert revision.customer_resolution_status == 'confirmed'
|
||||
assert revision.customer_resolution_status == 'pending'
|
||||
assert updated.customer_resolution_method == 'manual'
|
||||
assert case.customer_id == customer.id
|
||||
assert case.customer_name_snapshot == customer.standard_name
|
||||
assert case.customer_short_code_snapshot == customer.short_code
|
||||
assert case.business_no.startswith(customer.short_code)
|
||||
assert len(case.business_no) == len(customer.short_code) + 8
|
||||
assert case.sequence_value == 1
|
||||
assert case.numbering_status == 'assigned'
|
||||
assert updated.customer_id == customer.id
|
||||
assert updated.customer_name_snapshot == customer.standard_name
|
||||
assert updated.customer_short_code_snapshot == customer.short_code
|
||||
assert updated.business_no is None
|
||||
assert updated.business_date is None
|
||||
assert updated.business_sequence_value is None
|
||||
assert customer_identity_is_confirmed(updated) is True
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 2
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 2
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0
|
||||
|
||||
|
||||
def test_inactive_customer_reblocks_and_missing_case_is_blocked(app):
|
||||
"""已确认客户停用后重新阻断;缺少业务单的任务也必须阻断。"""
|
||||
def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch):
|
||||
"""PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
original_query = db.session.query
|
||||
lock_arguments: list[dict] = []
|
||||
|
||||
class NoticeQuerySpy:
|
||||
"""保留真实 Query 行为,仅记录客户确认路径的行锁参数。"""
|
||||
|
||||
def __init__(self, query):
|
||||
self._query = query
|
||||
|
||||
def filter(self, *criteria):
|
||||
self._query = self._query.filter(*criteria)
|
||||
return self
|
||||
|
||||
def with_for_update(self, **kwargs):
|
||||
lock_arguments.append(kwargs)
|
||||
self._query = self._query.with_for_update(**kwargs)
|
||||
return self
|
||||
|
||||
def one(self):
|
||||
return self._query.one()
|
||||
|
||||
def traced_query(*entities, **kwargs):
|
||||
query = original_query(*entities, **kwargs)
|
||||
if len(entities) == 1 and entities[0] is ShippingNotice:
|
||||
return NoticeQuerySpy(query)
|
||||
return query
|
||||
|
||||
monkeypatch.setattr(db.session, 'query', traced_query)
|
||||
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
|
||||
assert lock_arguments == [{'of': ShippingNotice}]
|
||||
|
||||
|
||||
def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
|
||||
"""已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
@@ -151,11 +182,11 @@ def test_inactive_customer_reblocks_and_missing_case_is_blocked(app):
|
||||
assert_customer_identity_gate(task, operation='match_inventory')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
missing_case, _other_customer, _other_user = _seed_task(with_case=False)
|
||||
with pytest.raises(AppError) as missing_case_error:
|
||||
assert_customer_identity_gate(missing_case, operation='match_inventory')
|
||||
assert missing_case_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
assert customer_identity_is_confirmed(missing_case) is False
|
||||
unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False)
|
||||
with pytest.raises(AppError) as unconfirmed_error:
|
||||
assert_customer_identity_gate(unconfirmed, operation='match_inventory')
|
||||
assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
assert customer_identity_is_confirmed(unconfirmed) is False
|
||||
|
||||
|
||||
def test_workspace_customer_search_and_confirmation_api(app, client):
|
||||
|
||||
@@ -95,3 +95,113 @@ def test_shipping_customer_migrations_upgrade_and_downgrade():
|
||||
finally:
|
||||
for module, original_op in zip(modules, original_ops, strict=True):
|
||||
module.op = original_op
|
||||
|
||||
|
||||
def _shipping_case_removal_schema(engine: sa.Engine, *, migrated: bool) -> None:
|
||||
"""构造最终删表迁移所需的最小 Notice/Case 历史结构。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_cases', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('customer_id', sa.Integer(), nullable=True),
|
||||
sa.Column('business_no', sa.String(32), nullable=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notices', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('task_no', sa.String(64), nullable=False),
|
||||
sa.Column('shipping_case_id', sa.Integer(), sa.ForeignKey('shipping_cases.id'), nullable=True),
|
||||
sa.Column('customer_id', sa.Integer(), nullable=True),
|
||||
sa.Column('business_no', sa.String(32), nullable=True),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(sa.text("INSERT INTO shipping_cases (id, customer_id, business_no) VALUES (1, 7, 'CUS26082301')"))
|
||||
if migrated:
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notices (id, task_no, shipping_case_id, customer_id, business_no) "
|
||||
"VALUES (1, 'SN-MIGRATED', 1, 7, 'CUS26082301')"
|
||||
))
|
||||
else:
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notices (id, task_no, shipping_case_id, customer_id, business_no) "
|
||||
"VALUES (1, 'SN-UNMIGRATED', 1, NULL, NULL)"
|
||||
))
|
||||
|
||||
|
||||
def test_shipping_case_removal_migration_requires_notice_facts_and_drops_legacy_table():
|
||||
"""最终迁移只能删除已回填 Notice 的 Case;未回填事实必须显式失败。"""
|
||||
module = importlib.import_module('migrations.versions.hp9q0r1s2t3u_remove_shipping_case')
|
||||
for migrated in (True, False):
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_shipping_case_removal_schema(engine, migrated=migrated)
|
||||
with engine.begin() as connection:
|
||||
original_op = module.op
|
||||
module.op = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
|
||||
try:
|
||||
if migrated:
|
||||
module.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_cases' not in inspector.get_table_names()
|
||||
assert 'shipping_case_id' not in {item['name'] for item in inspector.get_columns('shipping_notices')}
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match='migration incomplete'):
|
||||
module.upgrade()
|
||||
finally:
|
||||
module.op = original_op
|
||||
|
||||
|
||||
def test_shipping_case_removal_repairs_fact_columns_skipped_by_inconsistent_revision():
|
||||
"""版本表已越过前置迁移但 Notice 仍为旧结构时,最终迁移应先恢复事实列再删 Case。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_cases', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('customer_id', sa.Integer(), nullable=True),
|
||||
sa.Column('business_no', sa.String(32), nullable=True),
|
||||
sa.Column('business_date', sa.Date(), nullable=True),
|
||||
sa.Column('sequence_value', sa.Integer(), nullable=True),
|
||||
sa.Column('numbering_rule_version', sa.String(32), nullable=True),
|
||||
sa.Column('customer_name_snapshot', sa.String(200), nullable=True),
|
||||
sa.Column('customer_short_code_snapshot', sa.String(6), nullable=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notices', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('task_no', sa.String(64), nullable=False),
|
||||
sa.Column('shipping_case_id', sa.Integer(), sa.ForeignKey('shipping_cases.id'), nullable=True),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(sa.text("INSERT INTO shipping_customers (id) VALUES (7)"))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_cases "
|
||||
"(id, customer_id, business_no, business_date, sequence_value, numbering_rule_version, "
|
||||
"customer_name_snapshot, customer_short_code_snapshot) "
|
||||
"VALUES (1, 7, 'CUS26082301', '2026-08-23', 1, 'V1', 'Customer', 'CUS')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notices (id, task_no, shipping_case_id) "
|
||||
"VALUES (1, 'SN-LEGACY', 1)"
|
||||
))
|
||||
|
||||
module = importlib.import_module('migrations.versions.hp9q0r1s2t3u_remove_shipping_case')
|
||||
with engine.begin() as connection:
|
||||
original_op = module.op
|
||||
module.op = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
|
||||
try:
|
||||
module.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
columns = {item['name'] for item in inspector.get_columns('shipping_notices')}
|
||||
assert {'business_no', 'customer_id', 'business_date', 'business_sequence_value'} <= columns
|
||||
row = connection.execute(sa.text(
|
||||
"SELECT business_no, customer_id, business_sequence_value "
|
||||
"FROM shipping_notices WHERE id = 1"
|
||||
)).one()
|
||||
assert row == ('CUS26082301', 7, 1)
|
||||
assert 'shipping_cases' not in inspector.get_table_names()
|
||||
finally:
|
||||
module.op = original_op
|
||||
@@ -14,7 +14,7 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
FileAsset, ShippingCase, ShippingCustomer, ShippingCustomerShadowMatch,
|
||||
FileAsset, ShippingCustomer, ShippingCustomerShadowMatch,
|
||||
ShippingCustomerShadowResolution, ShippingCustomerSite, ShippingOrderCandidate,
|
||||
ShippingOrderDocument, ShippingOrderIntake, ShippingOrderExtraction, ShippingOrderField,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderSchema,
|
||||
@@ -154,9 +154,6 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app):
|
||||
)
|
||||
_intake, candidate = _seed_candidate(sender='spoof@example.net')
|
||||
_attach_value(candidate, version, field, 'buyer@wyc.example.com')
|
||||
case = ShippingCase(case_no='CASE-SHADOW')
|
||||
db.session.add(case)
|
||||
|
||||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
assert resolution.status == 'unique_candidate'
|
||||
@@ -164,7 +161,6 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app):
|
||||
assert resolution.identity_rule_set_id == rule_set['id']
|
||||
assert resolution.evidence_json[0]['context_field_id'] == field.id
|
||||
assert resolution.evidence_json[0]['source']['kind'] == 'field_value'
|
||||
assert case.customer_id is None and case.business_no is None
|
||||
|
||||
|
||||
def test_schema_uuid_drift_keeps_stable_customer_identity_rule_matching(app):
|
||||
|
||||
@@ -93,6 +93,25 @@ def test_layout_snapshot_checksum_and_idempotent_current_version(app):
|
||||
assert current_layout_snapshot(document)['marker'] == 'v1'
|
||||
|
||||
|
||||
def test_ready_pdf_layout_requires_coordinate_evidence_asset(app, monkeypatch):
|
||||
"""关键断言:PDF 坐标证据资产保存失败时,布局不得伪装为 ready。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
monkeypatch.setattr(layout_lifecycle, '_persist_coordinate_evidence_asset', lambda **_: None)
|
||||
snapshot = {
|
||||
**_snapshot(),
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><td>x</td></tr></table>'}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': [{'text': 'x'}]},
|
||||
'tables': {'table-1': [{'text': 'x'}]},
|
||||
},
|
||||
}
|
||||
version = record_inline_layout_snapshot(document, snapshot)
|
||||
assert version.status == 'failed'
|
||||
assert 'shipping_document_layout_coordinate_evidence_persist_failed' in version.issues_json
|
||||
|
||||
|
||||
def test_inline_derived_xfa_layout_localizes_structure_analysis_identity(app):
|
||||
"""坐标补证派生 Layout 必须克隆 XFA Analysis,样本可安全冻结到新版本。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -115,6 +115,53 @@ def test_attach_native_pdf_page_images_renders_only_missing_pages():
|
||||
assert attached[1].characters is chars_b
|
||||
|
||||
|
||||
def test_extract_native_pdf_pages_closes_pdfium_handles_before_returning():
|
||||
"""PDFium 句柄必须在数据复制后显式关闭,不能留给 weakref finalizer 在进程退出时回收。"""
|
||||
closed: list[str] = []
|
||||
|
||||
class FakeTextPage:
|
||||
def count_chars(self):
|
||||
return 0
|
||||
|
||||
def close(self):
|
||||
closed.append('text')
|
||||
|
||||
class FakePage:
|
||||
def get_size(self):
|
||||
return 200, 100
|
||||
|
||||
def get_textpage(self):
|
||||
return FakeTextPage()
|
||||
|
||||
def get_rotation(self):
|
||||
return 0
|
||||
|
||||
def close(self):
|
||||
closed.append('page')
|
||||
|
||||
class FakeDocument:
|
||||
def __init__(self, _content):
|
||||
self.page = FakePage()
|
||||
|
||||
def __len__(self):
|
||||
return 1
|
||||
|
||||
def __getitem__(self, _index):
|
||||
return self.page
|
||||
|
||||
def close(self):
|
||||
closed.append('document')
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument',
|
||||
FakeDocument,
|
||||
):
|
||||
pages = extract_native_pdf_pages(b'%PDF', render_images=False)
|
||||
|
||||
assert len(pages) == 1
|
||||
assert closed == ['text', 'page', 'document']
|
||||
|
||||
|
||||
def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
|
||||
"""PDFium 空格即使没有 bbox,也必须成为下一可见字符的可靠边界并保留原始序号。"""
|
||||
class FakeTextPage:
|
||||
@@ -135,6 +182,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
|
||||
assert loose is True
|
||||
return (10 + index * 4, 80, 13 + index * 4, 88)
|
||||
|
||||
def close(self):
|
||||
"""模拟 PDFium text page 的显式释放接口。"""
|
||||
|
||||
class FakePage:
|
||||
"""模拟无需渲染的单页 PDF。"""
|
||||
|
||||
@@ -150,6 +200,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
|
||||
"""样本不旋转。"""
|
||||
return 0
|
||||
|
||||
def close(self):
|
||||
"""模拟 PDFium page 的显式释放接口。"""
|
||||
|
||||
class FakeDocument:
|
||||
"""模拟 PDFium 文档的页数和索引访问。"""
|
||||
|
||||
@@ -164,6 +217,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
|
||||
"""返回唯一页面。"""
|
||||
return FakePage()
|
||||
|
||||
def close(self):
|
||||
"""模拟 PDFium document 的显式释放接口。"""
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument',
|
||||
FakeDocument,
|
||||
@@ -242,6 +298,35 @@ def test_native_pdf_text_fallback_accepts_po_header_synonyms_without_false_page_
|
||||
assert 'PURCHASE' not in tables[0]['html']
|
||||
|
||||
|
||||
def test_native_pdf_text_fallback_skips_separator_between_header_and_first_data_row():
|
||||
"""表头下的起始横线不能截断无框采购订单的首条明细。"""
|
||||
characters = []
|
||||
for y, entries in [
|
||||
(10, [('Item', 10), ('Material', 55), ('Qty', 135)]),
|
||||
(22, [('________________________________________', 10)]),
|
||||
(34, [('00010', 10), ('PART-A', 55), ('2', 135)]),
|
||||
(46, [('________________________________________', 10)]),
|
||||
(58, [('Total:', 90), ('2', 135)]),
|
||||
]:
|
||||
for value, x0 in entries:
|
||||
for index, char in enumerate(value):
|
||||
characters.append(PositionedCharacter(
|
||||
text=char, source_index=len(characters),
|
||||
bbox=LayoutBBox(x0=x0 + index * 4, y0=y, x1=x0 + index * 4 + 3, y1=y + 8),
|
||||
))
|
||||
page = NativePdfPage(
|
||||
page_no=1, width=180, height=100, rotation=0, characters=characters,
|
||||
image=np.full((200, 360), 255, dtype=np.uint8),
|
||||
)
|
||||
|
||||
tables = build_native_pdf_text_table_fallbacks(b'%PDF', native_pages=[page])
|
||||
|
||||
# 起始横线后仍须保留首条业务数据;合计行和表尾横线不属于候选表。
|
||||
assert len(tables) == 1
|
||||
assert '00010' in tables[0]['html']
|
||||
assert 'Total:' not in tables[0]['html']
|
||||
|
||||
|
||||
def test_native_pdf_unique_text_builds_traceable_needs_review_layout():
|
||||
"""唯一文本可形成 cell/token 引用,但人工真值延期时整体仍必须 needs_review。"""
|
||||
mineru = _candidate('<table><tr><th>Part</th><th>Qty</th></tr></table>')
|
||||
|
||||
@@ -65,6 +65,7 @@ def test_runtime_persists_compact_text_and_table_snapshot_without_raw_response(a
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False,
|
||||
)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
|
||||
@@ -107,6 +108,7 @@ def test_runtime_reuses_native_pdf_pages_across_fallback_layout_and_evidence(app
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False,
|
||||
)
|
||||
native_pages = [object()]
|
||||
timings: dict[str, int] = {}
|
||||
@@ -157,6 +159,7 @@ def test_runtime_empty_mineru_tables_use_pdfium_provider_fallback(app):
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False,
|
||||
)
|
||||
empty_candidate = _candidate().model_copy(update={'pages': [
|
||||
_candidate().pages[0].model_copy(update={'tables': []}),
|
||||
|
||||
@@ -30,6 +30,16 @@ from app.models import (
|
||||
)
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.file_assets import storage as file_asset_storage_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _memory_file_asset_storage(monkeypatch):
|
||||
"""测试外置坐标证据使用内存对象,保持 FileAsset/MinIO 契约而不依赖服务。"""
|
||||
objects: dict[str, bytes] = {}
|
||||
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'upload_bytes', lambda *, storage_key, data, content_type: objects.__setitem__(storage_key, bytes(data)))
|
||||
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'get_bytes', lambda storage_key: objects[storage_key])
|
||||
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -52,8 +62,8 @@ def test_blind_test_order_field_comparison_rejects_different_values():
|
||||
)
|
||||
|
||||
|
||||
def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_source():
|
||||
"""盲测仅在模板显式启用自适应模式时改用整页字符,默认表格模式必须保持不变。"""
|
||||
def test_quality_region_uses_page_glyphs_for_every_reconstruction_mode():
|
||||
"""盲测与预览/正式解析必须从当前页同一字符事实开始重建。"""
|
||||
evidence = {
|
||||
'tables': {'table-1': [{'text': 'TABLE'}]},
|
||||
'page_glyphs': {'1': [{'text': 'PAGE'}]},
|
||||
@@ -62,13 +72,36 @@ def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_sourc
|
||||
assert quality._region_characters_for_quality(
|
||||
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
|
||||
evidence=evidence, raw_table=raw_table, table_id='table-1',
|
||||
) == [{'text': 'TABLE'}]
|
||||
) == [{'text': 'PAGE'}]
|
||||
assert quality._region_characters_for_quality(
|
||||
region=SimpleNamespace(row_reconstruction_mode='adaptive_record_columns'),
|
||||
evidence=evidence, raw_table=raw_table, table_id='table-1',
|
||||
) == [{'text': 'PAGE'}]
|
||||
|
||||
|
||||
def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages():
|
||||
"""关键断言:第二页只有合同正文时,不能重复重建第一页的订单明细。"""
|
||||
evidence = {
|
||||
'tables': {'table-1': [{'text': 'TABLE'}]},
|
||||
'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'TERMS'}]},
|
||||
}
|
||||
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False))
|
||||
raw_table = {'table_id': 'table-1', 'page_no': 1}
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}]
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None
|
||||
|
||||
|
||||
def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region():
|
||||
"""关键断言:显式跨页区域只能使用后续页自己的 page glyphs。"""
|
||||
evidence = {
|
||||
'tables': {'table-1': [{'text': 'PAGE-1'}]},
|
||||
'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'PAGE-2'}]},
|
||||
}
|
||||
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=True))
|
||||
raw_table = {'table_id': 'table-1', 'page_no': 1}
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) == [{'text': 'PAGE-2'}]
|
||||
|
||||
|
||||
def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingOrderDocument]]:
|
||||
"""创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。"""
|
||||
user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin')
|
||||
@@ -244,10 +277,8 @@ 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']
|
||||
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)
|
||||
# 业务规则:具备管理员权限即可批准,不再要求必须由其他管理员批准。
|
||||
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert approved['status'] == 'approved'
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
qualification = quality.qualification_summary(profile)
|
||||
@@ -334,6 +365,7 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app):
|
||||
|
||||
layout_version = documents[1].current_layout_version
|
||||
payload = dict(layout_version.payload_json)
|
||||
payload.pop('coordinate_evidence_ref', None)
|
||||
payload['coordinate_evidence'] = {'tables': {}, 'pages': {}, 'page_glyphs': {}}
|
||||
layout_version.payload_json = payload
|
||||
db.session.commit()
|
||||
@@ -344,7 +376,6 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app):
|
||||
if item['document_id'] == documents[1].id
|
||||
)
|
||||
assert candidate['review_mode'] == 'preparing'
|
||||
assert candidate['confirmable'] is False
|
||||
assert candidate['layout_issue_codes'] == ['coordinate_evidence_missing']
|
||||
|
||||
|
||||
@@ -365,27 +396,6 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
|
||||
db.session.commit()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
|
||||
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
|
||||
"""模拟从原始 PDF 恢复整页字符,验证盲测不依赖 MinerU table_id。"""
|
||||
assert page_nos is None
|
||||
recovered = dict(layout)
|
||||
recovered['coordinate_evidence'] = {
|
||||
'pages': {'1': {'width': 200, 'height': 60}},
|
||||
'page_glyphs': {'1': [
|
||||
{'text': char, 'bbox': {
|
||||
'x0': x0 + char_index * 5, 'y0': 20,
|
||||
'x1': x0 + char_index * 5 + 4, 'y1': 30,
|
||||
}}
|
||||
for text, x0 in [('PN-1', 30), ('3', 150)]
|
||||
for char_index, char in enumerate(text)
|
||||
]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
'tables': {},
|
||||
}
|
||||
return recovered
|
||||
|
||||
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
|
||||
|
||||
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
candidate_option = next(item for item in available if item['document_id'] == document.id)
|
||||
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
|
||||
@@ -393,11 +403,13 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
|
||||
assert candidate_option['confirmable'] is False
|
||||
assert candidate_option['layout_issue_codes'] == ['mineru_cell_coordinates_missing']
|
||||
|
||||
candidate = quality.preview_independent_sample(
|
||||
suite_id=suite['id'], document_id=document.id,
|
||||
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
|
||||
)
|
||||
assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': '3'}]
|
||||
with pytest.raises(Exception) as diagnostic_preview:
|
||||
quality.preview_independent_sample(
|
||||
suite_id=suite['id'], document_id=document.id,
|
||||
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
|
||||
)
|
||||
assert getattr(diagnostic_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
candidate = {'rows': []}
|
||||
with pytest.raises(Exception) as bypassed_review:
|
||||
quality.add_sample(
|
||||
suite_id=suite['id'], document_id=document.id,
|
||||
@@ -405,7 +417,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
|
||||
expected_rows=candidate['rows'], actor_id=user.id,
|
||||
)
|
||||
assert getattr(bypassed_review.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
|
||||
assert candidate['confirmable'] is False
|
||||
assert diagnostic_preview.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
with pytest.raises(Exception) as diagnostic_confirmation:
|
||||
quality.confirm_sample_reviews(
|
||||
suite_id=suite['id'], document_id=document.id,
|
||||
@@ -414,7 +426,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
|
||||
layout_version_id=current_version.id,
|
||||
layout_payload_checksum=current_version.payload_checksum, actor_id=user.id,
|
||||
)
|
||||
assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE'
|
||||
assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
|
||||
|
||||
def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch):
|
||||
@@ -431,29 +443,6 @@ def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch):
|
||||
db.session.commit()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
|
||||
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
|
||||
"""模拟正在预热时直接从原 PDF 恢复整页坐标,空布局不得阻断复核。"""
|
||||
assert layout == {'status': 'pending', 'tables': [], 'issues': []}
|
||||
assert page_nos is None
|
||||
return {
|
||||
**layout,
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 60}},
|
||||
'page_glyphs': {'1': [
|
||||
{'text': char, 'bbox': {
|
||||
'x0': x0 + char_index * 5, 'y0': 20,
|
||||
'x1': x0 + char_index * 5 + 4, 'y1': 30,
|
||||
}}
|
||||
for text, x0 in [('PN-1', 30), ('3', 150)]
|
||||
for char_index, char in enumerate(text)
|
||||
]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
'tables': {},
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
|
||||
|
||||
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
candidate_option = next(item for item in available if item['document_id'] == document.id)
|
||||
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
|
||||
@@ -484,26 +473,6 @@ def test_document_candidate_identity_expires_after_background_layout_completion(
|
||||
for item in available
|
||||
)
|
||||
|
||||
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
|
||||
"""文档级复核使用整页证据,不依赖后台刚生成的表格身份。"""
|
||||
assert page_nos is None
|
||||
recovered = dict(layout)
|
||||
recovered['coordinate_evidence'] = {
|
||||
'pages': {'1': {'width': 200, 'height': 60}},
|
||||
'page_glyphs': {'1': [
|
||||
{'text': char, 'bbox': {
|
||||
'x0': x0 + char_index * 5, 'y0': 20,
|
||||
'x1': x0 + char_index * 5 + 4, 'y1': 30,
|
||||
}}
|
||||
for text, x0 in [('PN-1', 30), ('3', 150)]
|
||||
for char_index, char in enumerate(text)
|
||||
]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
'tables': {},
|
||||
}
|
||||
return recovered
|
||||
|
||||
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
|
||||
with pytest.raises(Exception) as stale_preview:
|
||||
quality.preview_independent_sample(
|
||||
suite_id=suite['id'], document_id=document.id,
|
||||
@@ -600,8 +569,9 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
||||
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}},
|
||||
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
||||
})
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
for document in documents:
|
||||
@@ -671,7 +641,7 @@ def test_coordinate_blind_preview_skips_header_only_regions(app):
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
||||
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}},
|
||||
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
||||
})
|
||||
db.session.commit()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
@@ -680,6 +650,56 @@ def test_coordinate_blind_preview_skips_header_only_regions(app):
|
||||
assert candidate['rows'] == []
|
||||
|
||||
|
||||
def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app):
|
||||
"""盲测候选必须和编辑器预览一样排除表头视觉区域。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
profile.definition_json = {
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [{
|
||||
'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [{
|
||||
'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25},
|
||||
'field_regions': [],
|
||||
}],
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
}],
|
||||
}], 'order_field_layouts': [],
|
||||
}
|
||||
glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 10, 'x1': 23 + index * 4, 'y1': 20}}
|
||||
for index, char in enumerate('Item')
|
||||
] + [
|
||||
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}}
|
||||
for index, char in enumerate('20')
|
||||
] + [
|
||||
{'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}}
|
||||
for index, char in enumerate('PART-A')
|
||||
]
|
||||
record_inline_layout_snapshot(documents[1], {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
||||
'coordinate_evidence': {
|
||||
'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
})
|
||||
db.session.commit()
|
||||
candidate = quality._candidate_for_sample(
|
||||
profile=profile, document_id=documents[1].id, table_id='table-1',
|
||||
)
|
||||
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -19,7 +19,7 @@ from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
|
||||
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingCase, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice import excel_template
|
||||
@@ -152,12 +152,10 @@ def _workbook_upload() -> FileStorage:
|
||||
|
||||
def test_filename_pattern_supports_business_number_and_split_business_variables():
|
||||
"""业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。"""
|
||||
shipping_case = ShippingCase(
|
||||
case_no='CASE-FILENAME', business_no='WYC26060201', customer_short_code_snapshot='WYC',
|
||||
business_date=date(2026, 6, 2), sequence_value=1,
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-FILENAME', inventory_source_code='DBS', business_no='WYC26060201',
|
||||
customer_short_code_snapshot='WYC', business_date=date(2026, 6, 2), business_sequence_value=1,
|
||||
)
|
||||
task = ShippingNotice(task_no='TASK-FILENAME', inventory_source_code='DBS')
|
||||
task.shipping_case = shipping_case
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='FILENAME', display_name='Filename',
|
||||
definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'},
|
||||
@@ -333,8 +331,15 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
ShippingOrderFieldValue(extraction_id=extraction.id, field_id=po_number.id, value_text='16754796', decision_id=po_decision.id),
|
||||
ShippingOrderFieldValue(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, value_text='PN-1', decision_id=line_decision.id),
|
||||
])
|
||||
confirmed_customer = ShippingCustomer(
|
||||
standard_name='Export ACME', short_code='EAC', status='active',
|
||||
)
|
||||
db.session.add(confirmed_customer)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB',
|
||||
customer_id=confirmed_customer.id,
|
||||
customer_resolution_status='confirmed',
|
||||
# 此模板只消费 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',
|
||||
@@ -348,6 +353,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
lines=[(1, part.id, 'PN-1', 1, '1000000001')],
|
||||
)
|
||||
|
||||
assert task.business_no is None
|
||||
path, filename, artifact = generate_shipment_excel(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -363,10 +369,13 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
assert artifact.order_schema_version_id == version.id
|
||||
assert artifact.inventory_parsing_profile_id == parsing.id
|
||||
assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0
|
||||
assert task.business_no is not None
|
||||
assert task.business_no.startswith('EAC')
|
||||
|
||||
# 已存在待上传 Artifact 时仍保持原有幂等保护,和 Warehouse ID 无关。
|
||||
with pytest.raises(ValueError, match='当前任务存在待上传的发货 Excel'):
|
||||
# 一个 Notice 已有 Excel 后必须创建新 Notice,禁止同号追加第二个 Artifact。
|
||||
with pytest.raises(ConflictError) as second_export:
|
||||
generate_shipment_excel(task)
|
||||
assert second_export.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED'
|
||||
|
||||
|
||||
def test_header_mapping_rejects_line_order_field(app):
|
||||
@@ -401,17 +410,13 @@ def test_export_date_system_fact_uses_business_timezone(app):
|
||||
assert isinstance(value, date)
|
||||
|
||||
|
||||
def test_excel_pull_request_number_uses_export_date_without_changing_case_number(app):
|
||||
"""Excel Pull Request Number 必须采用导出日期,且业务单主编号保持原值。"""
|
||||
def test_excel_pull_request_number_uses_notice_business_number(app):
|
||||
"""Excel Pull Request Number 直接使用 Notice business_no,不因导出日期重编号。"""
|
||||
with app.app_context():
|
||||
shipping_case = ShippingCase(
|
||||
case_no='CASE-EXCEL-NO', business_no='IVMX26080801', sequence_value=1,
|
||||
)
|
||||
task = ShippingNotice(task_no='TASK-EXCEL-NO')
|
||||
task.shipping_case = shipping_case
|
||||
task = ShippingNotice(task_no='TASK-EXCEL-NO', business_no='IVMX26080801', business_sequence_value=1)
|
||||
|
||||
assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26081101'
|
||||
assert shipping_case.business_no == 'IVMX26080801'
|
||||
assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26080801'
|
||||
assert task.business_no == 'IVMX26080801'
|
||||
|
||||
|
||||
def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app):
|
||||
|
||||
@@ -16,8 +16,11 @@ from app.services.shipping_notice.generic_parse_plan import compile_generic_pars
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_apply_stp_route_adjudication,
|
||||
_coordinate_profile_rows,
|
||||
_physical_table_targets_profile_region,
|
||||
_profile_table_candidates,
|
||||
_route_reason_for_issue,
|
||||
_selected_coordinate_transform,
|
||||
_virtual_page_without_rows_is_nonblocking,
|
||||
_should_attempt_generic_extraction,
|
||||
route_deterministic_unit,
|
||||
)
|
||||
@@ -38,6 +41,37 @@ def _field(code: str, *, scope: str = 'line', required: bool = False, collection
|
||||
}
|
||||
|
||||
|
||||
def test_physical_table_outside_profile_region_is_not_a_parse_target():
|
||||
"""页脚等非目标物理表不得进入模板明细重建并污染已成功的订单表。"""
|
||||
regions = [{
|
||||
'region_id': 'order-lines', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'region': {'x0': .02, 'y0': .40, 'x1': .94, 'y1': .46},
|
||||
'line_layouts': [{}],
|
||||
}]
|
||||
page = {'width': 612, 'height': 792}
|
||||
|
||||
assert _physical_table_targets_profile_region(
|
||||
raw_table={'table_id': 'order-lines', 'page_no': 1, 'bbox': {'x0': 15, 'y0': 235, 'x1': 570, 'y1': 345}},
|
||||
table_regions=regions, page_size=page,
|
||||
) is True
|
||||
assert _physical_table_targets_profile_region(
|
||||
raw_table={'table_id': 'footer-summary', 'page_no': 1, 'bbox': {'x0': 16, 'y0': 659, 'x1': 569, 'y1': 721}},
|
||||
table_regions=regions, page_size=page,
|
||||
) is False
|
||||
|
||||
|
||||
def test_empty_virtual_page_does_not_block_a_successful_target_table():
|
||||
"""无物理表的续页仅用于补漏;没有行时不得覆盖已成功的目标表。"""
|
||||
assert _virtual_page_without_rows_is_nonblocking(
|
||||
raw_table={'table_id': 'page-2', 'page_no': 2},
|
||||
fixed_rows=[], adaptive_rows=[],
|
||||
) is True
|
||||
assert _virtual_page_without_rows_is_nonblocking(
|
||||
raw_table={'table_id': 'page-2', 'page_no': 2},
|
||||
fixed_rows=[{'status': 'needs_review', 'issues': ['field_invalid']}], adaptive_rows=[],
|
||||
) is False
|
||||
|
||||
|
||||
def _good_candidate() -> dict:
|
||||
return {
|
||||
'page_no': 1,
|
||||
@@ -340,6 +374,43 @@ def test_should_attempt_generic_extraction_allows_no_special_profile_feature():
|
||||
) is True
|
||||
|
||||
|
||||
def test_legacy_profile_does_not_apply_matcher_inferred_coordinate_transform():
|
||||
"""已发布 legacy 模板的正式字段解析必须沿用盲测验证过的绝对坐标。"""
|
||||
inferred = {
|
||||
'status': 'applied', 'translate_x': 0.0, 'translate_y': .03,
|
||||
'anchor_ids': ['title'], 'reason_codes': [],
|
||||
}
|
||||
transform = _selected_coordinate_transform(
|
||||
raw_profile={
|
||||
'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
|
||||
'definition': {'coordinate_model': {'type': 'legacy'}},
|
||||
},
|
||||
profile_match={
|
||||
'status': 'unique_match', 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
|
||||
'candidates': [{
|
||||
'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
|
||||
'coordinate_transform': inferred,
|
||||
}],
|
||||
},
|
||||
)
|
||||
|
||||
# 关键断言:自动推断的位移只服务于匹配,不得改变 legacy 模板的正式字段坐标。
|
||||
assert transform is None
|
||||
assert _selected_coordinate_transform(
|
||||
raw_profile={
|
||||
'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
|
||||
'definition': {'coordinate_model': {'type': 'anchor_frame'}},
|
||||
},
|
||||
profile_match={
|
||||
'status': 'unique_match', 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
|
||||
'candidates': [{
|
||||
'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
|
||||
'coordinate_transform': inferred,
|
||||
}],
|
||||
},
|
||||
) == inferred
|
||||
|
||||
|
||||
def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkeypatch):
|
||||
"""自适应模板的完整业务行不得按子布局数量误判跨页,成功匹配必须上送路由审计。"""
|
||||
profile = {
|
||||
@@ -419,7 +490,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey
|
||||
assert result['match']['status'] == 'unique_match'
|
||||
assert result['match']['profile_code'] == 'ODP-PRODUCTION'
|
||||
# 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。
|
||||
assert seen_table_ids == ['native-text-table-p1-1']
|
||||
assert seen_table_ids == ['native-text-table-p1-1', 'native-text-table-p1-1']
|
||||
|
||||
|
||||
def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
|
||||
@@ -429,6 +500,7 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
|
||||
region=SimpleNamespace(model_dump=lambda: {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}),
|
||||
termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False),
|
||||
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
|
||||
model_dump=lambda: {'region_id': 'lines', 'page_scope': 'all_pages', 'line_layouts': [{}]},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
|
||||
@@ -463,6 +535,7 @@ def test_coordinate_profile_rows_forward_selected_match_transform_without_recomp
|
||||
region=SimpleNamespace(model_dump=lambda: {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.5}),
|
||||
termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False),
|
||||
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
|
||||
model_dump=lambda: {'region_id': 'lines', 'page_scope': 'all_pages'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_business_case.py
|
||||
|
||||
用途:验证货代业务单聚合在普通建单、修订和强制新建场景下的归属规则。
|
||||
依赖:app fixture、ShippingNotice/ShippingCase、business_case_service。
|
||||
逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。
|
||||
用途:验证 Notice 建单和替代关系不依赖 ShippingCase。
|
||||
依赖:app fixture、ShippingNotice、task_workflow。
|
||||
逻辑:直接调用领域服务并断言 Notice 独立事实,不触发解析和库存副作用。
|
||||
"""
|
||||
|
||||
from app import db
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingNotice
|
||||
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
|
||||
from app.models import ShippingCustomer, ShippingNotice
|
||||
from app.services.shipping_notice.task_workflow import create_task
|
||||
|
||||
|
||||
def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int | None = None) -> ShippingNotice:
|
||||
"""构造最小货代任务,供业务单关系断言使用。"""
|
||||
def _task(task_no: str, *, supersedes_task_id: int | None = None) -> ShippingNotice:
|
||||
"""构造最小 Notice,供替代关系断言使用。"""
|
||||
return ShippingNotice(
|
||||
task_no=task_no,
|
||||
shipping_case_id=case_id,
|
||||
supersedes_task_id=supersedes_task_id,
|
||||
source_type='manual',
|
||||
)
|
||||
@@ -33,76 +31,32 @@ def _active_customer(*, short_code: str = 'CASE') -> ShippingCustomer:
|
||||
return customer
|
||||
|
||||
|
||||
def test_normal_and_force_create_use_different_cases(app):
|
||||
"""普通建单和强制新建必须各自创建独立业务单。"""
|
||||
def test_notices_are_independent_without_business_case(app):
|
||||
"""不同 Notice 无需中间聚合实体,业务事实由自身保存。"""
|
||||
with app.app_context():
|
||||
normal = resolve_shipping_case_for_new_task(created_by_id=None)
|
||||
forced = resolve_shipping_case_for_new_task(
|
||||
duplicate_resolution_type='force_create',
|
||||
created_by_id=None,
|
||||
)
|
||||
assert normal.id != forced.id
|
||||
assert normal.business_no is None
|
||||
assert forced.business_no is None
|
||||
first = _task('SN-NOTICE-INDEPENDENT-1')
|
||||
second = _task('SN-NOTICE-INDEPENDENT-2')
|
||||
db.session.add_all([first, second])
|
||||
db.session.commit()
|
||||
assert first.id != second.id
|
||||
assert first.business_no is None
|
||||
assert second.business_no is None
|
||||
|
||||
|
||||
def test_revision_inherits_existing_parent_case(app):
|
||||
"""修订任务必须继承父任务已有业务单,不能创建新业务单。"""
|
||||
def test_replacement_links_to_parent_notice(app):
|
||||
"""替代 Notice 仅链接原 Notice,不继承或依赖 Case。"""
|
||||
with app.app_context():
|
||||
case = resolve_shipping_case_for_new_task(created_by_id=None)
|
||||
parent = _task('SN-CASE-PARENT-1', case_id=case.id)
|
||||
parent = _task('SN-NOTICE-PARENT-1')
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
|
||||
resolved = resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=parent.id,
|
||||
duplicate_resolution_type='revision',
|
||||
)
|
||||
assert resolved.id == case.id
|
||||
assert ShippingCase.query.count() == 1
|
||||
replacement = _task('SN-NOTICE-REPLACEMENT-1', supersedes_task_id=parent.id)
|
||||
db.session.add(replacement)
|
||||
db.session.commit()
|
||||
assert replacement.supersedes_task_id == parent.id
|
||||
|
||||
|
||||
def test_revision_rejects_parent_without_business_case(app):
|
||||
"""修订父任务缺少业务单时必须阻断,禁止隐式补建。"""
|
||||
with app.app_context():
|
||||
parent = _task('SN-CASE-LEGACY-1')
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=parent.id,
|
||||
duplicate_resolution_type='revision',
|
||||
)
|
||||
assert exc_info.value.code == 'SHIPPING_NOTICE.REVISION_CASE_MISSING'
|
||||
assert ShippingCase.query.count() == 0
|
||||
|
||||
|
||||
def test_revision_chain_reuses_root_case(app):
|
||||
"""连续修订版本必须沿用同一业务单聚合。"""
|
||||
with app.app_context():
|
||||
case = resolve_shipping_case_for_new_task(created_by_id=None)
|
||||
parent = _task('SN-CASE-CHAIN-1', case_id=case.id)
|
||||
db.session.add(parent)
|
||||
db.session.flush()
|
||||
revision_case = resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=parent.id,
|
||||
duplicate_resolution_type='revision',
|
||||
)
|
||||
revision = _task('SN-CASE-CHAIN-2', case_id=revision_case.id, supersedes_task_id=parent.id)
|
||||
db.session.add(revision)
|
||||
db.session.flush()
|
||||
|
||||
next_case = resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=revision.id,
|
||||
duplicate_resolution_type='revision',
|
||||
)
|
||||
assert next_case.id == case.id
|
||||
assert ShippingCase.query.count() == 1
|
||||
|
||||
|
||||
def test_create_task_assigns_case_and_serializes_it(app):
|
||||
"""真实单票建单路径必须创建业务单并在 Tool 投影中返回关联信息。"""
|
||||
def test_create_task_assigns_notice_customer_and_serializes_it(app):
|
||||
"""真实单票建单路径直接写 Notice 客户事实,不创建 ShippingCase。"""
|
||||
with app.app_context():
|
||||
customer = _active_customer(short_code='CRT')
|
||||
result = create_task({
|
||||
@@ -111,11 +65,9 @@ def test_create_task_assigns_case_and_serializes_it(app):
|
||||
'customer_id': customer.id,
|
||||
})
|
||||
task = ShippingNotice.query.filter_by(task_no=result['task_id']).one()
|
||||
assert task.shipping_case_id is not None
|
||||
assert task.customer_resolution_status == 'confirmed'
|
||||
assert result['data']['shipping_case_id'] == task.shipping_case_id
|
||||
assert result['data']['case_no'] == task.shipping_case.case_no
|
||||
assert task.shipping_case.customer_id == customer.id
|
||||
assert task.customer_id == customer.id
|
||||
assert result['data']['customer_id'] == customer.id
|
||||
|
||||
|
||||
def test_create_task_rejects_without_customer(app):
|
||||
|
||||
@@ -13,7 +13,7 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
|
||||
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink,
|
||||
ShippingOrderCustomerMatch,
|
||||
@@ -101,7 +101,7 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
|
||||
def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
|
||||
"""为直接构造的 RPA 回调任务补齐已确认客户。
|
||||
|
||||
核心逻辑:测试不经建单工作流时,显式创建 business case 与激活客户,
|
||||
核心逻辑:测试不经建单工作流时,显式绑定激活客户,
|
||||
使回调测试只验证 RPA 契约,而不绕过客户身份门禁。
|
||||
"""
|
||||
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
|
||||
@@ -111,47 +111,17 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
case = ShippingCase(
|
||||
case_no=f'CASE-{task.task_no}', customer=customer,
|
||||
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
|
||||
)
|
||||
task.shipping_case = case
|
||||
task.customer = customer
|
||||
task.customer_name_snapshot = customer.standard_name
|
||||
task.customer_short_code_snapshot = customer.short_code
|
||||
task.customer_resolution_status = 'confirmed'
|
||||
task.customer_resolution_method = 'test_fixture'
|
||||
db.session.add_all([case, task])
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
# 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。
|
||||
task._test_customer_confirmed = True
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _confirmed_customer_for_rpa_flows(app, monkeypatch):
|
||||
"""为本模块新建的业务单绑定测试客户,使用例聚焦客户门禁之后的 RPA 行为。"""
|
||||
from app.services.shipping_notice import task_workflow
|
||||
|
||||
original = task_workflow.resolve_shipping_case_for_new_task
|
||||
|
||||
def _resolve_confirmed_case(**kwargs):
|
||||
case = original(**kwargs)
|
||||
if case.customer_id is not None:
|
||||
return case
|
||||
customer = db.session.query(ShippingCustomer).filter_by(short_code="RPA").one_or_none()
|
||||
if customer is None:
|
||||
customer = ShippingCustomer(
|
||||
standard_name="RPA 流程测试客户",
|
||||
short_code="RPA",
|
||||
status="active",
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
case.customer_id = customer.id
|
||||
case.customer_name_snapshot = customer.standard_name
|
||||
case.customer_short_code_snapshot = customer.short_code
|
||||
return case
|
||||
|
||||
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _freeze_test_rpa_batch_callback_contract(monkeypatch):
|
||||
"""兼容旧测试调用:仅在测试边界补齐 v2 envelope,不改变生产回调校验。"""
|
||||
|
||||
@@ -19,6 +19,7 @@ from app.services.shipping_notice.query_service import (
|
||||
resolve_task_from_payload,
|
||||
serialize_task,
|
||||
task_export_error_message,
|
||||
list_freight_notice_groups_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
|
||||
|
||||
@@ -300,6 +301,116 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
assert "can_handle" not in no_viewer
|
||||
|
||||
|
||||
def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
|
||||
"""同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch
|
||||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||||
|
||||
first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11)
|
||||
second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11)
|
||||
db.session.add_all([first, second]); db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingNoticeLine(
|
||||
notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST',
|
||||
reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'},
|
||||
),
|
||||
ShippingNoticeLine(
|
||||
notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND',
|
||||
reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'},
|
||||
),
|
||||
ShippingNoticeLineInventoryMatch(
|
||||
task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready',
|
||||
available_qty='20', shortage_qty='0', is_current=True,
|
||||
),
|
||||
ShippingNoticeLineInventoryMatch(
|
||||
task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready',
|
||||
available_qty='9', shortage_qty='0', is_current=True,
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
data = serialize_task_summary(first, viewer_user_id=11)
|
||||
|
||||
assert data['business_no'] == 'WVC26082301'
|
||||
assert data['notice_line_summary'] == [{
|
||||
'line_no': '00010', 'part_number': 'PART-FIRST', 'customer_part_number': None,
|
||||
'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20',
|
||||
'shortage_qty': '0', 'inventory_status': 'ready',
|
||||
}]
|
||||
|
||||
|
||||
def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app):
|
||||
"""货代上传聚合必须按同 PO 的 business_no 拆组,并排除无业务号及他人 Notice。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingNoticeLine
|
||||
from app.services.shipping_notice import query_service
|
||||
|
||||
def with_po(task_no, business_no, user_id):
|
||||
return ShippingNotice(task_no=task_no, business_no=business_no, source_type='manual', user_id=user_id)
|
||||
|
||||
first = with_po('SN-GROUP-1', 'WYC26082401', 11)
|
||||
second = with_po('SN-GROUP-2', 'WYC26082402', 11)
|
||||
no_business = with_po('SN-GROUP-3', None, 11)
|
||||
other = with_po('SN-GROUP-4', 'WYC26082499', 99)
|
||||
db.session.add_all([first, second, no_business, other]); db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}),
|
||||
ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
original_header_reader = query_service.current_header_field_values_or_empty
|
||||
# customer_po_number 是当前动态 Schema 的正式 PO 字段;聚合必须不依赖旧兼容投影。
|
||||
query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-GROUP'}
|
||||
try:
|
||||
result = list_freight_notice_groups_for_task(first, user_id=11)
|
||||
finally:
|
||||
query_service.current_header_field_values_or_empty = original_header_reader
|
||||
assert result['po_number'] == 'PO-GROUP'
|
||||
assert [item['business_no'] for item in result['items']] == ['WYC26082401', 'WYC26082402']
|
||||
# 单条菜单必须消费服务端授权投影,前端不得按上传状态自行猜测可执行动作。
|
||||
assert 'available_actions' in result['items'][0]
|
||||
assert result['items'][0]['lines'][0]['part_number'] == 'PART-A'
|
||||
assert result['items'][1]['lines'][0]['part_number'] == 'PART-B'
|
||||
|
||||
|
||||
def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app):
|
||||
"""当前 Extraction 不可读时,货代上传聚合仍必须以冻结快照中的客户 PO 对齐同一发货批次。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot
|
||||
from app.services.shipping_notice import query_service
|
||||
|
||||
first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11)
|
||||
second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11)
|
||||
db.session.add_all([first, second]); db.session.flush()
|
||||
for task in (first, second):
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=task.id,
|
||||
schema_version_id=1,
|
||||
order_data_version=1,
|
||||
header_values_json={},
|
||||
customer_po_number='ZNB-16754796',
|
||||
)
|
||||
db.session.add(snapshot); db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.commit()
|
||||
|
||||
original_header_reader = query_service.current_header_field_values_or_empty
|
||||
query_service.current_header_field_values_or_empty = lambda _task: {}
|
||||
try:
|
||||
result = list_freight_notice_groups_for_task(first, user_id=11)
|
||||
finally:
|
||||
query_service.current_header_field_values_or_empty = original_header_reader
|
||||
|
||||
assert result['po_number'] == '16754796'
|
||||
assert [item['business_no'] for item in result['items']] == ['WYC26082411', 'WYC26082412']
|
||||
|
||||
|
||||
def test_list_my_todos_and_count_buckets(app):
|
||||
"""list_my_todos 按 bucket 分类;count 徽标与 pending 一致。"""
|
||||
with app.app_context():
|
||||
@@ -458,8 +569,8 @@ def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_stil
|
||||
assert original.case_no not in review_case_nos
|
||||
|
||||
|
||||
def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app):
|
||||
"""历史空 Review Case 可以处置,但不能被待办页默认授权进入订单生命周期。"""
|
||||
def test_open_review_case_without_current_candidate_enters_intake_parse(app):
|
||||
"""无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
@@ -476,7 +587,8 @@ def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app):
|
||||
|
||||
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_stage'] == 'intake_parse'
|
||||
assert hit['ui_state']['intake_parse_authorized'] is True
|
||||
assert hit['ui_state']['lifecycle_entries'] == []
|
||||
|
||||
|
||||
@@ -681,7 +793,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
row = SimpleNamespace(
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
shipping_case_id=task.shipping_case_id,
|
||||
customer_resolution_status=task.customer_resolution_status,
|
||||
order_snapshot_id=task.order_snapshot_id,
|
||||
current_order_extraction_id=task.current_order_extraction_id,
|
||||
|
||||
@@ -4,6 +4,25 @@ from app.services.shipping_notice.reservation_id import (
|
||||
normalize_reservation_id,
|
||||
validated_reservation_id,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_region import (
|
||||
apply_reservation_region_candidates,
|
||||
extract_reservation_from_region_text,
|
||||
extract_reservation_from_vendor_comments_pages,
|
||||
)
|
||||
|
||||
|
||||
def _glyph_lines(*lines: str) -> list[dict]:
|
||||
"""构造按视觉阅读顺序排列的最小页面文字证据。"""
|
||||
glyphs = []
|
||||
for row_index, line in enumerate(lines):
|
||||
for column_index, char in enumerate(line):
|
||||
glyphs.append({
|
||||
'text': char,
|
||||
'bbox': {'x0': column_index * 8, 'x1': column_index * 8 + 6, 'y0': row_index * 16, 'y1': row_index * 16 + 12},
|
||||
'source_index': len(glyphs),
|
||||
'boundary_before': 'space' if char == ' ' else 'none',
|
||||
})
|
||||
return glyphs
|
||||
|
||||
|
||||
def test_match_numeric_reservation_id():
|
||||
@@ -37,6 +56,91 @@ def test_reservation_contract_only_accepts_five_or_ten_digits():
|
||||
assert not is_valid_reservation_id("12345678901", numeric_only=True)
|
||||
|
||||
|
||||
def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present():
|
||||
"""专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。"""
|
||||
assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{
|
||||
'value': '3000098851', 'line_no': 1, 'scope': 'line',
|
||||
'raw_text': 'Reservation#3000098851 for line#1', 'status': 'mapped',
|
||||
}]
|
||||
|
||||
|
||||
def test_reservation_region_assigns_reservation_without_line_to_header():
|
||||
"""无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。"""
|
||||
assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{
|
||||
'value': '33008', 'line_no': None, 'scope': 'header',
|
||||
'raw_text': 'MDW hub order.Reservation#33008', 'status': 'header',
|
||||
}]
|
||||
|
||||
|
||||
def test_reservation_region_ignores_unrelated_numeric_noise():
|
||||
"""备注区的普通客户号、数量等数字没有 Reservation 标签时不得被误写入订单。"""
|
||||
assert extract_reservation_from_region_text("End Customer: D1\nQuantity: 1000143920") == []
|
||||
|
||||
|
||||
def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading():
|
||||
"""专区启用后跨页累计 Vendor Comments,首次 Terms 标题后的值必须被排除。"""
|
||||
candidates, reason = extract_reservation_from_vendor_comments_pages([
|
||||
(1, _glyph_lines('Vendor Comments:', 'Reservation#33008')),
|
||||
(2, _glyph_lines('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999')),
|
||||
])
|
||||
|
||||
assert reason is None
|
||||
assert [item['value'] for item in candidates] == ['33008', '3000098851']
|
||||
|
||||
|
||||
def test_vendor_comments_window_requires_start_and_end_headings():
|
||||
"""缺少任一边界时不能把全文中的 Reservation 当作专区证据。"""
|
||||
candidates, reason = extract_reservation_from_vendor_comments_pages([
|
||||
(1, _glyph_lines('Reservation#33008')),
|
||||
])
|
||||
|
||||
assert candidates == []
|
||||
assert reason == 'vendor_comments_anchor_missing'
|
||||
|
||||
|
||||
def test_reservation_region_applies_header_and_line_override_together():
|
||||
"""整单值是默认值,指定行的 Reservation 仅覆盖对应明细。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text(
|
||||
"MDW hub order.Reservation#33008\nReservation#3000098851 for line#1"
|
||||
),
|
||||
header_field_id='header-reservation',
|
||||
line_field_id='line-reservation',
|
||||
line_count=2,
|
||||
)
|
||||
|
||||
assert applied.header_value == '33008'
|
||||
assert applied.line_values == {1: '3000098851'}
|
||||
assert applied.needs_review is False
|
||||
|
||||
|
||||
def test_reservation_region_marks_only_conflicts_and_invalid_line_references_for_review():
|
||||
"""重复同一值可去重;同一行冲突或越界才阻断自动建单。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text(
|
||||
"Reservation#3000098851 for line#1\nReservation#3000098852 for line#1\n"
|
||||
"Reservation#3000098853 for line#3"
|
||||
),
|
||||
header_field_id='header-reservation',
|
||||
line_field_id='line-reservation',
|
||||
line_count=2,
|
||||
)
|
||||
|
||||
assert applied.needs_review is True
|
||||
assert set(applied.review_reasons) == {'conflicting_line_value', 'line_out_of_range'}
|
||||
|
||||
|
||||
def test_reservation_region_requires_review_when_numbered_value_has_no_line_target():
|
||||
"""Schema 未启用行级字段时,不能静默丢弃带行号的覆盖值。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text("Reservation#3000098851 for line#1"),
|
||||
header_field_id='header-reservation', line_field_id=None, line_count=1,
|
||||
)
|
||||
|
||||
assert applied.needs_review is True
|
||||
assert applied.review_reasons == ('line_field_unavailable',)
|
||||
|
||||
|
||||
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
|
||||
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
|
||||
@@ -79,7 +79,6 @@ def test_resolve_with_mocked_simple_namespace_attributes() -> None:
|
||||
upload_status="uploaded",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
shipping_case_id=None,
|
||||
customer_resolution_status=None,
|
||||
order_snapshot_id=None,
|
||||
inventory_lines_json=None,
|
||||
|
||||
@@ -14,7 +14,7 @@ import pytest
|
||||
from app import db
|
||||
from app.models import (
|
||||
ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule,
|
||||
ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice,
|
||||
ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice,
|
||||
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine,
|
||||
@@ -107,34 +107,6 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
|
||||
db.session.flush()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _confirmed_customer_for_legacy_tool_flows(app, monkeypatch):
|
||||
"""为本模块创建的业务单绑定测试客户,使既有用例继续聚焦客户 Gate 之后的流程。"""
|
||||
from app.services.shipping_notice import task_workflow
|
||||
|
||||
original = task_workflow.resolve_shipping_case_for_new_task
|
||||
|
||||
def _resolve_confirmed_case(**kwargs):
|
||||
case = original(**kwargs)
|
||||
if case.customer_id is not None:
|
||||
return case
|
||||
customer = db.session.query(ShippingCustomer).filter_by(short_code="TST").one_or_none()
|
||||
if customer is None:
|
||||
customer = ShippingCustomer(
|
||||
standard_name="Tool 流程测试客户",
|
||||
short_code="TST",
|
||||
status="active",
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
case.customer_id = customer.id
|
||||
case.customer_name_snapshot = customer.standard_name
|
||||
case.customer_short_code_snapshot = customer.short_code
|
||||
return case
|
||||
|
||||
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
|
||||
|
||||
|
||||
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
|
||||
|
||||
@@ -122,6 +122,85 @@ def _coordinate_definition() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def test_reservation_region_requires_header_and_allows_optional_line_scope_schema():
|
||||
"""无行号值必须有 Header 落点;启用 Line 后同一区域还可承载行级 Reservation。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'],
|
||||
}, {
|
||||
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'],
|
||||
}, {
|
||||
'field_id': 'line-start', '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'],
|
||||
}]})
|
||||
definition = _coordinate_definition()
|
||||
definition['reservation_id_region'] = {
|
||||
'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .3},
|
||||
'page_scope': 'exact_page', 'page_no': 1,
|
||||
}
|
||||
|
||||
normalized = service._normalize_definition(definition, schema_version=schema)
|
||||
|
||||
assert normalized['reservation_id_region']['page_no'] == 1
|
||||
|
||||
|
||||
def test_reference_page_frames_are_preserved_by_coordinate_definition_normalization():
|
||||
"""模板规范化必须保留标注页物理尺寸,不能只保存浏览器百分比坐标。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'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'],
|
||||
},
|
||||
]})
|
||||
definition = _coordinate_definition()
|
||||
definition['reference_page_frames'] = {
|
||||
'1': {'width': 609, 'height': 791, 'origin': 'pdf_top_left', 'box': 'cropbox'},
|
||||
}
|
||||
|
||||
normalized = service._normalize_definition(definition, schema_version=schema)
|
||||
|
||||
assert normalized['reference_page_frames']['1']['width'] == 609.0
|
||||
assert normalized['reference_page_frames']['1']['height'] == 791.0
|
||||
assert normalized['coordinate_model']['type'] == 'legacy'
|
||||
|
||||
|
||||
def test_reference_page_frames_read_annotation_coordinate_evidence():
|
||||
"""参考页框必须来自冻结 Layout 的 PDF 坐标证据,而不是前端提交。"""
|
||||
frames = service._reference_page_frames({
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 609, 'height': 791}}},
|
||||
})
|
||||
|
||||
assert frames == {
|
||||
'1': {'width': 609.0, 'height': 791.0, 'origin': 'pdf_top_left', 'box': 'cropbox'},
|
||||
}
|
||||
|
||||
|
||||
def test_reservation_region_rejects_schema_without_header_scope():
|
||||
"""无行号 Reservation 需要稳定 Header 落点,只有 Line 字段时不得保存。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
definition = _coordinate_definition()
|
||||
definition['reservation_id_region'] = {
|
||||
'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .3},
|
||||
'page_scope': 'exact_page', 'page_no': 1,
|
||||
}
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
service._normalize_definition(definition, schema_version=schema)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID'
|
||||
|
||||
|
||||
def test_visual_sample_preview_reads_common_ocr_value_before_xfa_path_is_selected(app, monkeypatch):
|
||||
"""XFA 草稿未选 datasets path 时,仍从共同 PDF 坐标证据显示 PO 样本值。"""
|
||||
glyphs = [
|
||||
@@ -365,6 +444,45 @@ def test_preview_page_region_text_uses_unique_xfa_widget_when_coordinate_text_is
|
||||
assert result['status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_preview_page_region_text_does_not_use_partial_xfa_widget_value(app, monkeypatch):
|
||||
"""局部框与大 Widget 仅相交时,不能把整段 /V 当作框内视觉样本。"""
|
||||
document = SimpleNamespace(id=112, 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': .40, 'y0': .10, 'x1': .80, 'y1': .60},
|
||||
value='TEMP-S000218922 FRAME MPN:D4-A08AR12000001 Customer',
|
||||
),
|
||||
], raising=False)
|
||||
monkeypatch.setattr(service, '_read_rendered_preview_crop_text', lambda _image: 'D4-A08AR12000001', raising=False)
|
||||
|
||||
with app.app_context():
|
||||
result = service.read_preview_page_region_text(
|
||||
1,
|
||||
data={
|
||||
'document_id': 112,
|
||||
'region': {'x0': .50, 'y0': .30, 'x1': .70, 'y1': .40},
|
||||
'rendered_image_base64': 'data:image/png;base64,iVBORw0KGgo=',
|
||||
},
|
||||
page_no=1,
|
||||
actor_id=1,
|
||||
)
|
||||
|
||||
assert result['text'] == 'D4-A08AR12000001'
|
||||
assert result['source'] == 'xfa_rendered_ocr'
|
||||
|
||||
|
||||
def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch):
|
||||
"""任意视觉框命中多个带值 Widget 时不得将其中之一冒充样本值。"""
|
||||
document = SimpleNamespace(id=110, asset_id=501, filename='hybrid.pdf')
|
||||
@@ -392,6 +510,39 @@ def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch
|
||||
assert result['source'] == 'acroform_widget_ambiguous'
|
||||
|
||||
|
||||
def test_preview_page_region_text_reads_xfa_canvas_crop_when_server_rendering_has_no_value(app, monkeypatch):
|
||||
"""XFA 可见值必须从管理员当前 PDF.js 画布裁剪图回读,不能以服务端 PDFium 空结果丢弃标注。"""
|
||||
document = SimpleNamespace(id=111, 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)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [])
|
||||
monkeypatch.setattr(service, '_read_rendered_preview_crop_text', lambda _image: 'HC07', raising=False)
|
||||
|
||||
with app.app_context():
|
||||
result = service.read_preview_page_region_text(
|
||||
1,
|
||||
data={
|
||||
'document_id': 111,
|
||||
'region': {'x0': .40, 'y0': .15, 'x1': .75, 'y1': .35},
|
||||
'rendered_image_base64': 'data:image/png;base64,iVBORw0KGgo=',
|
||||
},
|
||||
page_no=1,
|
||||
actor_id=1,
|
||||
)
|
||||
|
||||
assert result['text'] == 'HC07'
|
||||
assert result['source'] == 'xfa_rendered_ocr'
|
||||
|
||||
|
||||
def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field(app, monkeypatch):
|
||||
"""共同视觉预览忽略旧浏览器重复提交的已绑定未绑定布局,仍返回 PO 样本值。"""
|
||||
glyphs = [
|
||||
@@ -952,6 +1103,36 @@ def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app):
|
||||
]
|
||||
|
||||
|
||||
def test_order_field_layout_rejects_address_bound_to_number_anchor(app):
|
||||
"""关键断言:地址字段不能保存为订单编号的 Number 标签,避免错误锚点进入运行时。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].append({
|
||||
'field_id': 'ship-to-address', 'field_code': 'ship_to_address', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'ship_to_address_layout', 'field_id': '', 'field_code': 'ship_to_address',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': {'anchor_id': 'order_field_1_1_anchor', 'text': 'Number'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft({
|
||||
'profile_code': 'SHIP_TO_NUMBER', 'display_name': 'Ship to number mismatch',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
assert getattr(caught.value, 'details', {}).get('reason') == 'order_field_anchor_semantic_mismatch'
|
||||
assert getattr(caught.value, 'details', {}).get('field_code') == 'ship_to_address'
|
||||
|
||||
|
||||
def test_order_field_layout_rejects_line_field_and_unbounded_value_only_mode(app):
|
||||
"""订单字段不得借用明细字段;无锚点坐标回退必须限制在单页。"""
|
||||
with app.app_context():
|
||||
@@ -2119,6 +2300,86 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke
|
||||
assert preview['source_row_indices'] == [[], [0]]
|
||||
|
||||
|
||||
def test_profile_region_preview_does_not_promote_unanchored_header_to_data(app, monkeypatch):
|
||||
"""页级证据没有有效起行锚点时,预览必须保持无明细并进入 Review 语义。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
profile = SimpleNamespace(profile_code='STRICT_PREVIEW', version=1, schema_version=schema)
|
||||
document = SimpleNamespace(id=308)
|
||||
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'],
|
||||
}]
|
||||
layout = {
|
||||
'tables': [{'table_id': 'header-only', 'page_no': 1}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'tables': {'header-only': [
|
||||
{'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}},
|
||||
]},
|
||||
'page_glyphs': {'1': [
|
||||
{'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}},
|
||||
]},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(
|
||||
db.session, 'get',
|
||||
lambda model, _identity: profile if model is ShippingOrderDocumentProfile else None,
|
||||
)
|
||||
preview = service.preview_profile_region(
|
||||
22, data={'document_id': 308, 'table_id': 'header-only', 'definition': definition}, actor_id=1,
|
||||
)
|
||||
|
||||
assert preview['rows'] == [['customer_po_line_no']]
|
||||
assert preview['row_roles'] == ['header']
|
||||
assert preview['status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_profile_region_preview_excludes_configured_header_regions_from_line_rows(app, monkeypatch):
|
||||
"""已配置的表头区域不得作为坐标明细行;真实起行值仍必须保留。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
profile = SimpleNamespace(profile_code='HEADER_BOUNDARY', version=1, schema_version=schema)
|
||||
document = SimpleNamespace(id=309)
|
||||
definition = _coordinate_definition()
|
||||
table = definition['table_regions'][0]
|
||||
table['header_layouts'] = [{
|
||||
'layout_id': 'header_1',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .2},
|
||||
'field_regions': [],
|
||||
}]
|
||||
table['line_layouts'][0]['field_regions'] = [{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': .21, 'x1': .3, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}]
|
||||
table['line_layouts'][0]['region'] = {'x0': 0, 'y0': .2, 'x1': 1, 'y1': 1}
|
||||
layout = {
|
||||
'tables': [{'table_id': 'header-and-data', 'page_no': 1}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'tables': {'header-and-data': [
|
||||
{'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}},
|
||||
{'text': 'Vendor', 'source_index': 1, 'bbox': {'x0': 30, 'y0': 5, 'x1': 45, 'y1': 10}},
|
||||
{'text': '10', 'source_index': 2, 'bbox': {'x0': 5, 'y0': 30, 'x1': 15, 'y1': 40}},
|
||||
]},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, _identity: profile if model is ShippingOrderDocumentProfile else None)
|
||||
preview = service.preview_profile_region(
|
||||
23, data={'document_id': 309, 'table_id': 'header-and-data', 'definition': definition}, actor_id=1,
|
||||
)
|
||||
|
||||
assert preview['rows'] == [['customer_po_line_no'], ['10']]
|
||||
assert preview['source_row_indices'] == [[], [0]]
|
||||
|
||||
|
||||
def test_profile_region_preview_uses_schema_field_order(app, monkeypatch):
|
||||
"""局部候选字段必须按绑定 Schema 顺序返回,不受字段标注先后影响。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -2420,6 +2420,89 @@ def test_run_summary_omits_legacy_progress_projection(app):
|
||||
assert 'progress' not in payload
|
||||
|
||||
|
||||
def test_run_summary_exposes_user_lifecycle_progress_from_current_activity(app):
|
||||
"""Run 摘要必须提供五阶段用户态进度与当前步骤,供复核台首屏直接展示。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LIFECYCLE-PROGRESS')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
run.status = 'processing'
|
||||
run.phase = 'deterministic_parsing'
|
||||
run.progress_version = 4
|
||||
run.last_activity_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
payload = serialize_order_extraction_run(run)
|
||||
progress = payload['lifecycle_progress']
|
||||
|
||||
assert progress['lifecycle_stage'] == 'intake_parse'
|
||||
assert progress['lifecycle_status'] == 'running'
|
||||
assert progress['current_step_code'] == 'document_queued'
|
||||
assert progress['current_step_i18n_key'] == 'chat.shippingProcessing.progress.step.document_queued'
|
||||
assert isinstance(progress['completed_step_codes'], list)
|
||||
assert progress['last_activity_at']
|
||||
assert progress['health_status'] == 'normal'
|
||||
assert 'input_snapshot' not in str(progress)
|
||||
assert 'provider' not in str(progress).lower()
|
||||
|
||||
|
||||
def test_run_summary_lifecycle_progress_maps_completed_events_and_current_step(app):
|
||||
"""事件事实映射为稳定用户步骤,并保留已完成步骤顺序。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='LIFECYCLE-EVENTS')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
ensure_order_extraction_plan(run)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.status = 'extracting'
|
||||
unit.started_at = datetime.utcnow()
|
||||
unit.last_activity_at = datetime.utcnow()
|
||||
latest_sequence = (
|
||||
db.session.query(ShippingOrderExtractionProgressEvent.sequence_no)
|
||||
.filter_by(run_id=run.id)
|
||||
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc())
|
||||
.first()
|
||||
)
|
||||
sequence_base = int(latest_sequence[0]) if latest_sequence else 0
|
||||
for sequence, code in enumerate(('layout_parsing_completed', 'profile_matching'), start=1):
|
||||
db.session.add(ShippingOrderExtractionProgressEvent(
|
||||
run_id=run.id,
|
||||
unit_id=unit.id,
|
||||
document_id=document.id,
|
||||
sequence_no=sequence_base + sequence,
|
||||
event_code=code,
|
||||
# 真实写入契约把该完成事实保留为 running,投影仍必须识别为已完成。
|
||||
status='running',
|
||||
visibility='workspace',
|
||||
summary_json={},
|
||||
idempotency_key=f'lifecycle-events-{sequence}',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
progress = serialize_order_extraction_run(run)['lifecycle_progress']
|
||||
assert progress['current_step_code'] == 'profile_matching'
|
||||
assert progress['completed_step_codes'] == ['layout_parsing_completed']
|
||||
|
||||
|
||||
def test_run_summary_lifecycle_progress_marks_failed_without_worker_details(app):
|
||||
"""失败 Run 只显示稳定失败态和脱敏字段,不泄漏内部错误正文。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LIFECYCLE-FAILED')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='failed', error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED', error_message='secret worker trace')
|
||||
payload = serialize_order_extraction_run(run)
|
||||
progress = payload['lifecycle_progress']
|
||||
assert progress['lifecycle_status'] == 'failed'
|
||||
assert progress['health_status'] == 'failed'
|
||||
assert 'secret worker trace' not in str(progress)
|
||||
|
||||
|
||||
def test_user_run_summary_never_exposes_worker_error_text(app):
|
||||
"""Workspace status cards expose a stable error code, never Provider or Worker details."""
|
||||
with app.app_context():
|
||||
|
||||
@@ -37,7 +37,9 @@ def _glyphs(*lines: tuple[str, float, float]) -> list[dict]:
|
||||
return result
|
||||
|
||||
|
||||
def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfile:
|
||||
def _profile(
|
||||
*, layout: dict, page_scope: str = 'first_page', reference_page_frames: dict[str, dict] | None = None,
|
||||
) -> OrderCoordinateProfile:
|
||||
"""构造包含一个独立 header 字段的最小合法 v2 Profile。"""
|
||||
return OrderCoordinateProfile.model_validate({
|
||||
'profile_code': 'ORDER-FIELD-TEST', 'version': 1,
|
||||
@@ -48,6 +50,7 @@ def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinate
|
||||
'scope': 'header',
|
||||
'page_scope': page_scope, **layout,
|
||||
}],
|
||||
'reference_page_frames': reference_page_frames or {},
|
||||
})
|
||||
|
||||
|
||||
@@ -60,15 +63,38 @@ def _schema(**overrides: object) -> dict[str, dict]:
|
||||
}}
|
||||
|
||||
|
||||
def _evidence(*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate') -> dict:
|
||||
def _evidence(
|
||||
*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate', page_size: tuple[float, float] = (200, 200),
|
||||
) -> dict:
|
||||
"""构造冻结页级证据;故意不提供 tables,证明订单字段不依赖明细区。"""
|
||||
return {
|
||||
'pages': {page: {'width': 200, 'height': 200} for page in pages},
|
||||
'pages': {page: {'width': page_size[0], 'height': page_size[1]} for page in pages},
|
||||
'page_glyphs': pages,
|
||||
'sources': {'pages': {page: source for page in pages}},
|
||||
}
|
||||
|
||||
|
||||
def test_fixed_order_field_uses_annotation_page_frame_when_runtime_page_is_taller():
|
||||
"""同内容由分页页变为长页时,固定字段仍须读取标注页的 PDF 点坐标。"""
|
||||
profile = _profile(
|
||||
layout={'fallback_value_region': {'x0': .10, 'y0': .20, 'x1': .90, 'y1': .30}},
|
||||
reference_page_frames={'1': {'width': 200, 'height': 100}},
|
||||
)
|
||||
|
||||
result = extract_order_fields(
|
||||
profile=profile,
|
||||
schema_fields=_schema(),
|
||||
coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('45001', 40, 21))}, page_size=(200, 200),
|
||||
),
|
||||
allow_fixed_region_confirmation=True,
|
||||
)[0]
|
||||
|
||||
# 关键断言:不能把训练页 y=20..30 重投影到长页 y=40..60。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == '45001'
|
||||
|
||||
|
||||
def test_visual_row_prefers_explicit_pdf_space_boundary_over_geometry_threshold():
|
||||
"""真实词间距低于旧阈值时,PDF 文本流的明确空格仍应恢复,不能输出粘连地址。"""
|
||||
row = [
|
||||
@@ -350,6 +376,25 @@ def test_anchor_reference_region_and_exact_mode_reject_unrelated_label_occurrenc
|
||||
assert result.value == '45001'
|
||||
|
||||
|
||||
def test_unique_anchor_outside_saved_reference_region_is_still_readable():
|
||||
"""同版式样本唯一命中标签时,旧参考框不得阻断盲测/正式读取。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'ship_to', 'text': 'Ship to', 'match_mode': 'exact',
|
||||
'region': {'x0': .55, 'y0': .10, 'x1': .63, 'y1': .12},
|
||||
'position_locked': True,
|
||||
},
|
||||
'value_region': {'x0': .8, 'y0': 0, 'x1': 4.0, 'y1': 1.0},
|
||||
'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('Ship to:ACME', 20, 20))},
|
||||
))[0]
|
||||
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == 'ACME'
|
||||
|
||||
|
||||
def test_legacy_placeholder_anchor_uses_its_reference_region_as_review_only_evidence():
|
||||
"""历史手工默认标签不能丢值,但只能按原标注框降级为人工复核。"""
|
||||
profile = _profile(layout={
|
||||
@@ -439,6 +484,24 @@ def test_fallback_and_ocr_never_become_confirmed():
|
||||
assert ocr_result.status == 'needs_review'
|
||||
|
||||
|
||||
def test_profile_confirmed_fixed_region_is_confirmed_with_native_coordinates():
|
||||
"""唯一确认模板中的无标签固定区域可作为原生 PDF 正式字段证据。"""
|
||||
profile = _profile(layout={
|
||||
'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2},
|
||||
})
|
||||
|
||||
result = extract_order_fields(
|
||||
profile=profile,
|
||||
schema_fields=_schema(),
|
||||
coordinate_evidence=_evidence(pages={'1': _glyphs(('45001', 30, 20))}),
|
||||
allow_fixed_region_confirmation=True,
|
||||
)[0]
|
||||
|
||||
# 关键断言:此放宽仅由已确认的模板调用方显式开启,原生坐标和字段校验仍是必要条件。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.issues == []
|
||||
|
||||
|
||||
def test_multiline_stops_at_next_label_and_type_failure_requires_review():
|
||||
"""地址值在下一个标签前截断;日期格式无效不能绕过 Schema validator。"""
|
||||
address = _profile(layout={
|
||||
@@ -478,6 +541,21 @@ def test_common_purchase_order_slash_date_is_normalized():
|
||||
assert result.value.isoformat() == '2026-06-20'
|
||||
|
||||
|
||||
def test_common_purchase_order_short_slash_date_is_normalized():
|
||||
"""采购单常见两位年份日期应按冻结 date Schema 归一化。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(
|
||||
field_code='order_date', value_type='date', validator_keys=['iso_date'],
|
||||
), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/16/26', 20, 20))}))[0]
|
||||
|
||||
# 关键断言:视觉样本的两位年份转换为统一 ISO 日期,而不是未读取。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value.isoformat() == '2026-06-16'
|
||||
|
||||
|
||||
def test_date_does_not_extend_beyond_value_frame():
|
||||
"""值框边界是标注预览的唯一证据,日期也不得跨框补全。"""
|
||||
profile = _profile(layout={
|
||||
@@ -547,6 +625,27 @@ def test_absolute_value_region_uses_canvas_boundary_instead_of_anchor_projection
|
||||
assert result.value == '66 Hou-Kang Street'
|
||||
|
||||
|
||||
def test_absolute_single_line_value_region_moves_with_its_unique_anchor():
|
||||
"""单头整体上移时,绝对客户值框必须跟随已唯一命中的自身标签。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'bill_to', 'text': 'BILL TO',
|
||||
'region': {'x0': .10, 'y0': .30, 'x1': .30, 'y1': .35},
|
||||
},
|
||||
'absolute_value_region': {'x0': .10, 'y0': .38, 'x1': .90, 'y1': .44},
|
||||
'value_mode': 'single_line',
|
||||
})
|
||||
result = extract_order_fields(
|
||||
profile=profile, schema_fields=_schema(field_code='bill_to_customer'),
|
||||
coordinate_evidence=_evidence(pages={'1': _glyphs(
|
||||
('BILL TO', 20, 40), ('Hyve Solutions Corporation', 20, 56), ('44201 Nobel Drive', 20, 72),
|
||||
)}),
|
||||
)[0]
|
||||
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == 'Hyve Solutions Corporation'
|
||||
|
||||
|
||||
def test_tight_value_region_keeps_edge_glyphs_without_reading_adjacent_text():
|
||||
"""紧贴 USD 字符盒的右侧值框应容忍渲染误差,但不能吞入相邻字段。"""
|
||||
profile = _profile(layout={
|
||||
|
||||
@@ -155,6 +155,29 @@ def test_anchor_frame_matches_bounded_vertical_translation_without_changing_lega
|
||||
assert legacy_result.candidates[0].coordinate_transform is None
|
||||
|
||||
|
||||
def test_legacy_profile_automatically_uses_unique_document_match_label_for_bounded_translation():
|
||||
"""新管理台不配置坐标模型时,唯一的模板身份标签仍可自动校正小幅整体平移。"""
|
||||
definition = _profile('PO_AUTO_FRAME')['definition']
|
||||
definition['document_match']['required_anchors'][0].update({
|
||||
'label_region': {'x0': .05, 'y0': .02, 'x1': .265, 'y1': .10},
|
||||
'value_region': {'x0': .42, 'y0': .02, 'x1': .85, 'y1': .10},
|
||||
})
|
||||
profile = OrderCoordinateProfile.model_validate(definition)
|
||||
pages = {'1': {'width': 200, 'height': 280}}
|
||||
glyphs = {'1': [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 25.8, 'x1': 13 + index * 4, 'y1': 35.8}}
|
||||
for index, char in enumerate('PLANT NAME:')
|
||||
]}
|
||||
|
||||
transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs)
|
||||
|
||||
assert reasons == []
|
||||
assert transform == {
|
||||
'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.05,
|
||||
'anchor_ids': ['plant_name'], 'reason_codes': [],
|
||||
}
|
||||
|
||||
|
||||
def test_affine_anchor_frame_requires_explicit_opt_in_and_three_stable_anchors():
|
||||
"""仿射只允许显式治理的多锚点 Profile 使用,默认平移模板不改变行为。"""
|
||||
definition = _anchor_frame_profile()['definition']
|
||||
|
||||
@@ -96,6 +96,35 @@ def test_project_review_case_field_conflicts_empty_without_candidate():
|
||||
assert project_review_case_field_conflicts(case) == []
|
||||
|
||||
|
||||
def test_project_review_case_keeps_open_legacy_single_value_conflict_visible(monkeypatch):
|
||||
"""资格层仍阻断的遗留单值 Finding 不得被投影静默丢弃。"""
|
||||
candidate = SimpleNamespace(
|
||||
conflicts_json=[{
|
||||
'conflict_key': '0:unit_price',
|
||||
'field': 'unit_price',
|
||||
'line_index': 0,
|
||||
'severity': 'blocking',
|
||||
'reason': 'field_conflict',
|
||||
'values': ['1731.60'],
|
||||
}],
|
||||
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
|
||||
|
||||
monkeypatch.setattr(svc, '_candidate_for_case', lambda _case: candidate)
|
||||
monkeypatch.setattr(svc, 'current_open_candidate_conflicts', lambda _candidate: list(candidate.conflicts_json))
|
||||
|
||||
items = project_review_case_field_conflicts(case)
|
||||
|
||||
assert len(items) == 1
|
||||
assert items[0]['field_code'] == 'unit_price'
|
||||
assert items[0]['conflict_key'] == '0:unit_price'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_project_review_case_field_conflicts_uses_complete_finding_source_evidence():
|
||||
"""正文补充真冲突必须直接展示 PDF/邮件值与来源,不能因缺 Observation 而消失。"""
|
||||
|
||||
@@ -591,6 +591,42 @@ def test_reservation_summary_reads_machine_value_before_async_validation():
|
||||
assert result['lines'][0]['effective_reservation_id'] == '33874'
|
||||
|
||||
|
||||
def test_reservation_summary_does_not_leak_inventory_block_reason():
|
||||
"""Reservation 面板不得展示同一明细的库存路由阻断原因。"""
|
||||
case = SimpleNamespace(
|
||||
run=SimpleNamespace(input_snapshot_json={
|
||||
'schema': {'definition': {'fields': [{
|
||||
'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
}]}}},
|
||||
),
|
||||
current_draft=SimpleNamespace(
|
||||
validation_result_json={
|
||||
'status': 'needs_review',
|
||||
'line_projections': [{
|
||||
'line_key': 'line-1',
|
||||
'effective_reservation_id': None,
|
||||
'can_build': False,
|
||||
'block_reason': 'no_inventory_source_candidates',
|
||||
}],
|
||||
'issues': [{
|
||||
'code': 'effective_reservation_missing',
|
||||
'line_index': 0,
|
||||
'owning_gate_code': 'reservation_validation',
|
||||
'severity': 'blocking',
|
||||
}],
|
||||
},
|
||||
lines_json=[],
|
||||
),
|
||||
)
|
||||
|
||||
result = project_review_case_reservation(case)
|
||||
|
||||
# 关键断言:库存路由码只能留在库存 Gate,Reservation 行应显示自身缺失原因。
|
||||
assert result['lines'][0]['block_reason'] == 'effective_reservation_missing'
|
||||
assert result['lines'][0]['block_reason'] != 'no_inventory_source_candidates'
|
||||
assert result['lines'][0]['needs_attention'] is True
|
||||
|
||||
|
||||
def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candidate_readonly(app):
|
||||
"""同一 PDF 重入只保留一个 Case/Draft,草稿复制机器快照但不改写 Candidate。"""
|
||||
with app.app_context():
|
||||
@@ -1026,11 +1062,20 @@ def test_review_read_api_returns_safe_owner_scoped_projection(app):
|
||||
token = issue_local_access_token(user)
|
||||
headers = {'Authorization': f'Bearer {token}'}
|
||||
run_response = client.get(f'/api/workspace/shipping-notice/order-extraction-runs/{run.run_no}/review', headers=headers)
|
||||
queue_response = client.get(f'/api/workspace/shipping-notice/order-review-queue/{run.run_no}', headers=headers)
|
||||
case_response = client.get(f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}', headers=headers)
|
||||
|
||||
# 关键断言:列表和详情仅给 owner 返回 Case/Draft 安全投影,不输出原始文本或对象存储信息。
|
||||
assert run_response.status_code == 200
|
||||
assert queue_response.status_code == 200
|
||||
assert case_response.status_code == 200
|
||||
# 关键断言:慢切换读取必须返回查找/投影边界,供浏览器 HAR 精确定位,不泄露业务内容。
|
||||
assert 'review_lookup' in run_response.headers.get('Server-Timing', '')
|
||||
assert 'review_projection' in run_response.headers.get('Server-Timing', '')
|
||||
assert 'queue_lookup' in queue_response.headers.get('Server-Timing', '')
|
||||
assert 'queue_projection' in queue_response.headers.get('Server-Timing', '')
|
||||
assert 'case_lookup' in case_response.headers.get('Server-Timing', '')
|
||||
assert 'case_projection' in case_response.headers.get('Server-Timing', '')
|
||||
assert case.case_no in str(run_response.get_json())
|
||||
body = case_response.get_json()
|
||||
assert 'extracted_text' not in str(body)
|
||||
|
||||
@@ -19,11 +19,13 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
|
||||
|
||||
def test_order_task_progress_audit_event_types_frozen():
|
||||
"""契约冻结:OT 进度三类事件码齐全。"""
|
||||
"""契约冻结:OT 进度及投影一致性事件码齐全。"""
|
||||
assert ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES == frozenset({
|
||||
'order_task_created',
|
||||
'order_task_updated',
|
||||
'order_task_progress_changed',
|
||||
'shipping_processing_projection_inconsistent',
|
||||
'shipping_processing_task_ownership_mismatch',
|
||||
})
|
||||
|
||||
|
||||
@@ -114,3 +116,29 @@ def test_sync_order_task_processing_state_noop_skips_audit(app):
|
||||
).count()
|
||||
assert after_count == before_count
|
||||
assert int(ot.progress_version or 1) == version
|
||||
|
||||
|
||||
def test_sync_order_task_processing_state_can_bump_for_review_projection(app):
|
||||
"""Review Gate 变化即使不改 stage/status,也必须推进 Projection 版本。"""
|
||||
with app.app_context():
|
||||
ot = _seed_user_and_task('OT-PROGRESS-AUDIT-3')
|
||||
version = int(ot.progress_version or 1)
|
||||
sync_order_task_processing_state(
|
||||
ot,
|
||||
force_progress_bump=True,
|
||||
reason_code='review_gate_changed',
|
||||
source='test_review_projection',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert int(ot.progress_version or 1) == version + 1
|
||||
event = (
|
||||
ShippingAuditEvent.query.filter_by(
|
||||
event_type='order_task_progress_changed',
|
||||
aggregate_id=ot.task_no,
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert event is not None
|
||||
assert event.reason_code == 'review_gate_changed'
|
||||
@@ -186,7 +186,7 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app):
|
||||
notice_before = ShippingNotice.query.count()
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_confirmation_service.resolve_shipping_case_for_new_task',
|
||||
'app.services.shipping_notice.order_task_service.link_notice_to_order_task',
|
||||
side_effect=ConflictError('simulated notice create failure', code='SHIPPING.SIMULATED_NOTICE_FAIL'),
|
||||
):
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
|
||||
@@ -601,6 +601,33 @@ def test_automark_exposes_acroform_widget_as_independent_visual_candidate():
|
||||
assert 'value_binding' not in widget_candidate['binding']
|
||||
|
||||
|
||||
def test_automark_merges_same_field_same_geometry_sources():
|
||||
"""关键断言:同字段同页同坐标的 PDF 与 Widget 候选只生成一个画布框。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
candidates = [
|
||||
{
|
||||
'candidate_id': 'pdf-1', 'candidate_kind': 'field_binding',
|
||||
'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': {
|
||||
'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}},
|
||||
'evidence_sources': ['pdf_coordinate'], 'needs_review': True,
|
||||
},
|
||||
{
|
||||
'candidate_id': 'widget-1', 'candidate_kind': 'field_binding',
|
||||
'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': {
|
||||
'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}},
|
||||
'evidence_sources': ['acroform_widget'], 'needs_review': True,
|
||||
},
|
||||
]
|
||||
|
||||
merged = service._merge_duplicate_field_binding_candidates(candidates)
|
||||
|
||||
assert len(merged) == 1
|
||||
assert merged[0]['evidence_sources'] == ['pdf_coordinate', 'acroform_widget']
|
||||
|
||||
|
||||
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
|
||||
@@ -727,7 +754,11 @@ def test_automark_enriches_widget_table_candidate_with_coordinate_header_text():
|
||||
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]}],
|
||||
# 动态 XFA 的表头控件有展示值时,Widget 聚类会把表头带误判为候选行。
|
||||
'subrow_layouts': [{
|
||||
'row_offset': 0, 'column_boundaries': [0, .25, 1],
|
||||
'region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .2},
|
||||
}],
|
||||
'header_regions': [], 'status': 'needs_review',
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
@@ -751,6 +782,8 @@ def test_automark_enriches_widget_table_candidate_with_coordinate_header_text():
|
||||
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']
|
||||
# 已确认的表头带不得同时作为可保存的 Widget 明细行。
|
||||
assert widget_candidate['payload']['subrow_layouts'] == []
|
||||
|
||||
|
||||
def test_automark_marks_opencv_and_native_structure_conflict_for_review():
|
||||
|
||||
@@ -82,6 +82,16 @@ def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate():
|
||||
) is True
|
||||
|
||||
|
||||
def test_inventory_preparation_allows_reload_existing_result_without_rpa():
|
||||
"""RPA 超时后可重读已有库存结果;该动作仅属于库存准备 Gate。"""
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_preparation', action_code='reload_inventory_result',
|
||||
) is True
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_matching', action_code='reload_inventory_result',
|
||||
) is False
|
||||
|
||||
|
||||
def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
"""库存缺口恢复必须保留精确业务动作,禁止客户端降级为统一“重试”。"""
|
||||
assert action_presentation('open_shortage_review') == {
|
||||
@@ -140,7 +150,7 @@ def test_gate_action_presentation_declares_ui_dispatch_without_frontend_action_c
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'dialog',
|
||||
'ui_handler': 'manual_upload_evidence',
|
||||
'ui_handler': 'manual_upload_confirmation',
|
||||
}
|
||||
assert action_presentation('confirm_customer') == {
|
||||
'code': 'confirm_customer',
|
||||
@@ -433,6 +443,43 @@ def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch):
|
||||
assert summary['allowed_actions'] == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch):
|
||||
"""RPA 超时先重读已落盘结果,不能把主按钮直接指向新的 RPA 请求。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-INVENTORY-TIMEOUT', 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-TIMEOUT', '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_retryable',
|
||||
'blocking_reason_code': 'inventory_rpa_timeout',
|
||||
'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['next_action_code'] == 'reload_inventory_result'
|
||||
assert summary['primary_action']['code'] == 'reload_inventory_result'
|
||||
assert summary['allowed_actions'] == [
|
||||
'reload_inventory_result',
|
||||
'retry_inventory_preparation',
|
||||
]
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_manual_gate_evidence_and_rpa_retry(app, monkeypatch):
|
||||
"""Gate 20 保持凭据登记主动作,并显式下发可选 RPA 重试。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -507,8 +554,8 @@ def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action(
|
||||
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 的上传位置。"""
|
||||
def test_manual_upload_handoff_hides_excel_regeneration_for_single_notice(app, monkeypatch):
|
||||
"""同一 Notice 只能有一个 Excel,上传阶段不得投影重生入口。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
@@ -533,16 +580,10 @@ def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, m
|
||||
},
|
||||
},
|
||||
)
|
||||
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'
|
||||
assert 'regenerate_excel_artifact' not in summary['allowed_actions']
|
||||
assert all(item['code'] != 'regenerate_excel_artifact' for item in summary['action_presentation'])
|
||||
|
||||
|
||||
def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, monkeypatch):
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_recovery_action_contract.py
|
||||
|
||||
用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 失败统一下发
|
||||
「重新获取库存」(retry_inventory_preparation),不再因 inventory_preparation
|
||||
Gate 的 responsible_party='worker' 被历史「worker/retry_ 技术动作屏蔽」规则
|
||||
降级为人工上传入口 (upload_inventory_file)。
|
||||
用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 超时/耗尽优先下发
|
||||
「重新读取库存结果」(reload_inventory_result),其他失败下发「重新获取库存」
|
||||
(retry_inventory_preparation),不再被历史 worker 技术动作屏蔽规则降级为人工上传入口。
|
||||
|
||||
依赖:process_gate_projection._resolve_recovery_next_action。
|
||||
逻辑:pure_unit 纯单测(不建 Flask/DB);以阻断原因码 / Gate 状态为输入,
|
||||
@@ -59,12 +58,10 @@ def test_inventory_file_empty_blocked_manual_resolves_to_retry():
|
||||
@pytest.mark.parametrize('reason', [
|
||||
'inventory_file_empty',
|
||||
'inventory_preparation_failed',
|
||||
'inventory_rpa_timeout',
|
||||
'inventory_rpa_login_failed',
|
||||
'inventory_rpa_export_failed',
|
||||
'inventory_file_identity_mismatch',
|
||||
'inventory_file_missing',
|
||||
'inventory_rpa_exhausted',
|
||||
])
|
||||
def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason):
|
||||
"""全部库存 RPA 失败原因(无论 blocked_manual / blocked_retryable)均下发「重新获取库存」。"""
|
||||
@@ -79,14 +76,15 @@ def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason):
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_inventory_rpa_exhausted_falls_back_to_manual_upload():
|
||||
"""历史耗尽码仍允许用户手动重新获取库存。"""
|
||||
@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted'])
|
||||
def test_inventory_rpa_timeout_or_exhausted_prefers_reload_existing_result(reason):
|
||||
"""超时或耗尽先重读已有结果,不能直接新开 RPA Attempt。"""
|
||||
full, blocking = _mk(
|
||||
{'gate_code': 'inventory_preparation', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_rpa_exhausted'},
|
||||
'blocking_reason_code': reason},
|
||||
)
|
||||
action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None)
|
||||
assert action == 'retry_inventory_preparation'
|
||||
assert action == 'reload_inventory_result'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -225,6 +223,84 @@ def test_inventory_preparation_waiting_keeps_refresh_action():
|
||||
assert action == 'poll_inventory_preparation'
|
||||
|
||||
|
||||
def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, monkeypatch):
|
||||
"""重新读取库存结果只复用快照,不能触发新的库存 RPA。"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = SimpleNamespace(task_no='SN-RELOAD-1')
|
||||
execution = SimpleNamespace(task_id=7)
|
||||
calls: list[tuple[str, object]] = []
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
|
||||
lambda _task: {'source_code': 'DSV360_AWSDU'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot',
|
||||
lambda received_task, source, *, mode: calls.append((mode, (received_task, source))) or {'status': 'ok'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
|
||||
lambda *_args, **_kwargs: pytest.fail('reload must not trigger RPA'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_rpa_timeout',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_kwargs: calls.append(('sync', _kwargs)),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
outcome = executor._handle_reload_inventory_result(
|
||||
execution=execution,
|
||||
gate=SimpleNamespace(gate_code='inventory_preparation'),
|
||||
payload={'actor_user_id': 3},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'passed'
|
||||
assert calls[0][0] == 'reload_result'
|
||||
assert calls[1][0] == 'sync'
|
||||
|
||||
|
||||
def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app, monkeypatch):
|
||||
"""无可复用快照时保持超时阻断,不能隐式改为重新触发 RPA。"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = SimpleNamespace(task_no='SN-RELOAD-MISSING')
|
||||
execution = SimpleNamespace(task_id=7)
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
|
||||
lambda _task: {'source_code': 'DSV360_AWSDU'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
|
||||
lambda *_args, **_kwargs: pytest.fail('reload must not trigger RPA'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_rpa_timeout',
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
outcome = executor._handle_reload_inventory_result(
|
||||
execution=execution,
|
||||
gate=SimpleNamespace(gate_code='inventory_preparation'),
|
||||
payload={},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'blocked_retryable'
|
||||
assert outcome['blocking_reason_code'] == 'inventory_rpa_timeout'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_no_blocking_returns_no_action():
|
||||
"""无当前阻断时不下发给任何主恢复动作。"""
|
||||
|
||||
@@ -1082,71 +1082,48 @@ 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 重生后,执行器必须作废旧产物并保持人工上传阻断。"""
|
||||
def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch):
|
||||
"""已有 Excel 时不能在同一 Notice 重生,必须创建新的 Notice。"""
|
||||
from types import SimpleNamespace
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
invalidated = {}
|
||||
task = SimpleNamespace(id=1, task_no='SN-ONE-EXCEL')
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_excel_regeneration_only',
|
||||
lambda **kwargs: invalidated.update(kwargs) or {'artifacts': [10], 'uploads': [11]},
|
||||
ShippingExportArtifact,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=10))),
|
||||
)
|
||||
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},
|
||||
lambda _payload: pytest.fail('existing Artifact must not be regenerated'),
|
||||
)
|
||||
|
||||
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},
|
||||
payload={'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]
|
||||
assert outcome['blocking_reason_code'] == 'notice_excel_already_generated'
|
||||
|
||||
|
||||
def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch):
|
||||
"""Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。"""
|
||||
from types import SimpleNamespace
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
synced = []
|
||||
task = SimpleNamespace(id=1, task_no='SN-FIRST-EXCEL')
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
ShippingExportArtifact,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: None)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda _payload: {'status': 'failed', 'message': 'template unavailable'},
|
||||
|
||||
@@ -202,17 +202,18 @@ def test_shortage_release_keeps_first_export_line_override():
|
||||
) == {0: {'6': 'ODM-001'}}
|
||||
|
||||
|
||||
def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_inventory_fact(app, monkeypatch):
|
||||
"""短缺放行重投影后必须入队 Excel 产物 Gate,且不得改写库存缺口事实。"""
|
||||
def test_shortage_release_syncs_gate_and_enqueues_auto_fulfill_without_mutating_inventory_fact(app, monkeypatch):
|
||||
"""短缺放行只同步 Gate,并由 Worker 决定是否创建单条 Notice/Excel。"""
|
||||
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)
|
||||
task = SimpleNamespace(id=12, task_no='SN-12', active_process_execution_id=34)
|
||||
case = SimpleNamespace(confirmed_task_id=12)
|
||||
execution = SimpleNamespace(id=34, task_id=12)
|
||||
synced = []
|
||||
queued = []
|
||||
auto_fulfill_jobs = []
|
||||
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',
|
||||
@@ -222,6 +223,10 @@ def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_
|
||||
'app.services.shipping_notice.auto_progress_controller.submit_auto_progress',
|
||||
lambda **kwargs: queued.append(kwargs),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
|
||||
lambda **kwargs: auto_fulfill_jobs.append(kwargs),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=7)
|
||||
@@ -233,6 +238,11 @@ def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_
|
||||
'operator_id': 7,
|
||||
'commit': False,
|
||||
}]
|
||||
assert auto_fulfill_jobs == [{
|
||||
'task_no': 'SN-12',
|
||||
'trigger': 'inventory_shortage_released',
|
||||
'commit': False,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_rejects_missing_template_inventory_override():
|
||||
|
||||
@@ -36,7 +36,6 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
|
||||
from app.services.shipping_notice.tool_common import generate_task_no
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-UQ')
|
||||
@@ -46,19 +45,19 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
|
||||
ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
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),
|
||||
task_no=generate_task_no(),
|
||||
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),
|
||||
task_no=generate_task_no(),
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
)
|
||||
@@ -93,7 +92,6 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
|
||||
from app.services.shipping_notice.tool_common import generate_task_no
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-RACE')
|
||||
@@ -103,17 +101,17 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
case_id = int(case.id)
|
||||
|
||||
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id))
|
||||
tasks = []
|
||||
for _ in range(2):
|
||||
task = ShippingNotice(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
|
||||
task_no=generate_task_no(),
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
)
|
||||
|
||||
@@ -106,6 +106,30 @@ def test_completed_checks_include_formal_ot_milestone():
|
||||
assert 'order_review_completed' in codes
|
||||
|
||||
|
||||
def test_completed_checks_do_not_mark_open_legacy_conflict_as_resolved():
|
||||
"""遗留阻断 Finding 已投影为开放冲突时,不得再显示冲突已解决。"""
|
||||
checks = project_completed_checks(
|
||||
case=SimpleNamespace(updated_at=None),
|
||||
process_gate={
|
||||
'gates_track': [
|
||||
{'gate_code': 'field_conflict_resolution', 'status': 'passed'},
|
||||
],
|
||||
},
|
||||
customer_resolution=None,
|
||||
duplicate=None,
|
||||
field_conflicts=[{
|
||||
'conflict_key': '0:unit_price',
|
||||
'field_code': 'unit_price',
|
||||
'status': 'open',
|
||||
}],
|
||||
field_completeness=None,
|
||||
profile_match=None,
|
||||
formal_ot={'has_formal_ot': False},
|
||||
)
|
||||
|
||||
assert 'field_conflicts_resolved' not in {item['code'] for item in checks}
|
||||
|
||||
|
||||
def test_post_ot_clears_pre_ot_blocking_gate():
|
||||
"""正式 OT 后建单前 Gate 不得成为当前阻断。"""
|
||||
summary = apply_post_ot_gate_rules(
|
||||
@@ -235,6 +259,7 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating():
|
||||
current_step=None,
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
upload_status=None,
|
||||
)
|
||||
stage = project_stage_for_task(task)
|
||||
assert stage['code'] == 'order_creating'
|
||||
|
||||
@@ -26,6 +26,7 @@ from app.services.shipping_notice.reservation_service import (
|
||||
ensure_task_reservations,
|
||||
record_inventory_verification,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error
|
||||
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
@@ -77,6 +78,53 @@ def test_shortage_release_makes_only_its_snapshot_line_exportable(app):
|
||||
assert line_ids == {released_line.id}
|
||||
|
||||
|
||||
def test_partial_inventory_allows_excel_for_the_available_lines(app):
|
||||
"""关键断言:部分短缺不阻断已完整满足行的滚动 Excel 导出资格。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order(suffix='partial-excel-gate')
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
available_line = snapshot.lines[0]
|
||||
shortage_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
|
||||
qty=Decimal('3'), field_values_json={},
|
||||
)
|
||||
snapshot.lines.append(shortage_line)
|
||||
db.session.flush()
|
||||
record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[
|
||||
{'reservation_id': available_line.reservation_id, 'part_number': available_line.part_number, 'required_qty': available_line.qty, 'available_qty': available_line.qty, 'line_status': 'ok'},
|
||||
{'reservation_id': shortage_line.reservation_id, 'part_number': shortage_line.part_number, 'required_qty': shortage_line.qty, 'available_qty': '0', 'line_status': 'shortage'},
|
||||
])
|
||||
|
||||
assert excel_gate_error(task) is None
|
||||
|
||||
|
||||
def test_selected_notice_only_returns_its_frozen_lines(app):
|
||||
"""独立发货通知只能取得用户选择的满足行,不能捎带同 PO 其他可用行。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order(suffix='selected-notice-lines')
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
first_line = snapshot.lines[0]
|
||||
second_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
|
||||
qty=Decimal('3'), field_values_json={},
|
||||
)
|
||||
snapshot.lines.append(second_line)
|
||||
db.session.flush()
|
||||
record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[
|
||||
{'reservation_id': first_line.reservation_id, 'part_number': first_line.part_number, 'required_qty': first_line.qty, 'available_qty': first_line.qty, 'line_status': 'ok'},
|
||||
{'reservation_id': second_line.reservation_id, 'part_number': second_line.part_number, 'required_qty': second_line.qty, 'available_qty': second_line.qty, 'line_status': 'ok'},
|
||||
])
|
||||
|
||||
_verification, line_ids = current_available_snapshot_line_ids(
|
||||
task,
|
||||
selected_snapshot_line_ids={first_line.id},
|
||||
)
|
||||
|
||||
assert line_ids == {first_line.id}
|
||||
|
||||
|
||||
|
||||
|
||||
def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app):
|
||||
"""关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""验证订单模板运行时策略仅基于当前文档证据作出可审计的受控选择。"""
|
||||
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import (
|
||||
resolve_runtime_parse_strategy,
|
||||
select_runtime_region_ids,
|
||||
)
|
||||
|
||||
|
||||
def _row(*, line_no: str, part_no: str, issues: list[str] | None = None) -> dict:
|
||||
"""构造最小重建行,关键料号与项次用于验证策略不得静默改写业务结果。"""
|
||||
return {
|
||||
'status': 'parsed' if not issues else 'needs_review',
|
||||
'issues': issues or [],
|
||||
'fields': [
|
||||
{'field_code': 'customer_po_line_no', 'value': line_no},
|
||||
{'field_code': 'part_number', 'value': part_no},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_runtime_strategy_uses_every_page_with_coordinate_evidence():
|
||||
"""模板画在首页时,运行时仍须计划检查所有有页级坐标的页面以避免静默漏续页。"""
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}], '2': [{}], '3': []},
|
||||
fixed_rows=[], adaptive_rows=[],
|
||||
)
|
||||
|
||||
# 页面计划仍完整保留;没有任何可用明细行时整体必须 Review,不能伪造成功。
|
||||
assert result.status == 'needs_review'
|
||||
assert result.page_nos == (1, 2)
|
||||
|
||||
|
||||
def test_runtime_strategy_selects_adaptive_only_when_fixed_has_no_valid_rows():
|
||||
"""固定子行无有效行而自适应能完整重建时,系统才自动切换而非要求人工猜策略。"""
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[_row(line_no='10', part_no='PART-A', issues=['row_incomplete'])],
|
||||
adaptive_rows=[_row(line_no='10', part_no='PART-A')],
|
||||
)
|
||||
|
||||
assert result.status == 'selected'
|
||||
assert result.row_mode == 'adaptive_record_columns'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',)
|
||||
|
||||
|
||||
def test_runtime_strategy_selects_dynamic_x_columns_when_existing_modes_have_no_valid_rows():
|
||||
"""固定与自适应均无行时,才允许使用同一 Schema 校验过的动态 Y 候选。"""
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[], adaptive_rows=[],
|
||||
dynamic_rows=[_row(line_no='10', part_no='PART-A')],
|
||||
)
|
||||
|
||||
assert result.status == 'selected'
|
||||
assert result.row_mode == 'dynamic_x_columns'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_requires_review_when_dynamic_conflicts_with_existing_valid_row():
|
||||
"""动态结果与既有有效行冲突时不得静默保留旧模式,必须进入 Review。"""
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[_row(line_no='10', part_no='PART-A')], adaptive_rows=[],
|
||||
dynamic_rows=[_row(line_no='10', part_no='PART-B')],
|
||||
)
|
||||
|
||||
assert result.status == 'needs_review'
|
||||
assert result.row_mode is None
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_selects_dynamic_when_it_safely_covers_more_valid_records():
|
||||
"""动态候选完整覆盖旧模式且额外恢复有效起行记录时,才能取代不完整结果。"""
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[_row(line_no='20', part_no='PART-B')], adaptive_rows=[],
|
||||
dynamic_rows=[
|
||||
_row(line_no='10', part_no='PART-A'),
|
||||
_row(line_no='20', part_no='PART-B'),
|
||||
],
|
||||
)
|
||||
|
||||
assert result.status == 'selected'
|
||||
assert result.row_mode == 'dynamic_x_columns'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_requires_review_when_two_valid_modes_disagree_on_business_rows():
|
||||
"""两种有效重建结果的关键项次或料号不一致时不得按分数强选,必须转既有 Review。"""
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[_row(line_no='10', part_no='PART-A')],
|
||||
adaptive_rows=[_row(line_no='10', part_no='PART-B')],
|
||||
)
|
||||
|
||||
assert result.status == 'needs_review'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value():
|
||||
"""同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。"""
|
||||
fixed = _row(line_no='10', part_no='PART-A')
|
||||
fixed['fields'].append({'field_code': 'quantity', 'value': '12'})
|
||||
adaptive = _row(line_no='10', part_no='PART-A')
|
||||
adaptive['fields'].append({'field_code': 'quantity', 'value': '10'})
|
||||
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive],
|
||||
)
|
||||
|
||||
assert result.status == 'needs_review'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_prefers_complete_fixed_rows_when_overlap_matches():
|
||||
"""固定模式多识别一个字段时不得把同一条明细误判为策略冲突。"""
|
||||
fixed = _row(line_no='10', part_no='PART-A')
|
||||
fixed['fields'].append({'field_code': 'uom', 'value': 'EA'})
|
||||
adaptive = _row(line_no='10', part_no='PART-A')
|
||||
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive],
|
||||
)
|
||||
|
||||
assert result.status == 'selected'
|
||||
assert result.row_mode == 'fixed_subrows'
|
||||
|
||||
|
||||
def test_runtime_strategy_still_reviews_when_field_values_conflict():
|
||||
"""字段值冲突仍必须进入 Review,不能用字段数量掩盖识别差异。"""
|
||||
fixed = _row(line_no='10', part_no='PART-A')
|
||||
fixed['fields'].append({'field_code': 'uom', 'value': 'EA'})
|
||||
adaptive = _row(line_no='10', part_no='PART-A')
|
||||
adaptive['fields'].append({'field_code': 'uom', 'value': 'PCS'})
|
||||
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive],
|
||||
)
|
||||
|
||||
assert result.status == 'needs_review'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_reuses_base_region_on_continuation_page_without_duplicate_page_regions():
|
||||
"""标注页只用于定位同页表区;没有专属标注的续页复用基础表区,不能重复消费其他页布局。"""
|
||||
regions = [
|
||||
{'region_id': 'page_one', 'page_scope': 'exact_page', 'page_no': 1},
|
||||
{'region_id': 'page_two', 'page_scope': 'exact_page', 'page_no': 2},
|
||||
]
|
||||
|
||||
assert select_runtime_region_ids(table_regions=regions, page_no=1) == ('page_one',)
|
||||
assert select_runtime_region_ids(table_regions=regions, page_no=2) == ('page_two',)
|
||||
assert select_runtime_region_ids(table_regions=regions, page_no=3) == ('page_one',)
|
||||
|
||||
|
||||
def test_runtime_region_selection_prefers_legacy_continuation_region_before_base_region():
|
||||
"""已发布模板的续页专属框仍优先于首页基准框,避免升级后错用另一种行布局。"""
|
||||
regions = [
|
||||
{'region_id': 'page_one', 'page_scope': 'first_page'},
|
||||
{'region_id': 'continuation', 'page_scope': 'continuation_pages'},
|
||||
{'region_id': 'all_pages', 'page_scope': 'all_pages'},
|
||||
]
|
||||
|
||||
assert select_runtime_region_ids(table_regions=regions, page_no=1) == ('page_one',)
|
||||
assert select_runtime_region_ids(table_regions=regions, page_no=2) == ('continuation',)
|
||||
@@ -4,7 +4,6 @@ from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingCase,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskPurgeAudit,
|
||||
@@ -62,11 +61,8 @@ def test_plain_created_task_can_be_deleted_and_restored(app):
|
||||
def test_internal_business_task_is_voided_before_recycle_bin(app):
|
||||
"""已有业务单的任务不能伪装为纯删除,必须留下作废事实和原因。"""
|
||||
with app.app_context():
|
||||
case = ShippingCase(case_no='SC-DISPOSITION-001')
|
||||
task = _task('SN-DISPOSITION-VOID-001')
|
||||
db.session.add_all([case, task])
|
||||
db.session.flush()
|
||||
task.shipping_case_id = case.id
|
||||
task = _task('SN-DISPOSITION-VOID-001', business_no='SN260823001')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
outcome = move_task_to_recycle_bin(task, actor_id=1, reason='重复建单')
|
||||
@@ -210,11 +206,9 @@ def test_workspace_voided_filter_includes_voided_recycle_bin_task(app, client):
|
||||
"""已作废视图必须可审计“作废并删除”的任务,不能被 deleted_at 条件意外排除。"""
|
||||
headers, user_id = _headers_for_user(app, 'disposition-voided-list')
|
||||
with app.app_context():
|
||||
case = ShippingCase(case_no='SC-DISPOSITION-LIST-VOIDED')
|
||||
task = _task('SN-DISPOSITION-LIST-VOIDED', user_id=user_id)
|
||||
db.session.add_all([case, task])
|
||||
task = _task('SN-DISPOSITION-LIST-VOIDED', user_id=user_id, business_no='SN260823002')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
task.shipping_case_id = case.id
|
||||
move_task_to_recycle_bin(task, actor_id=user_id, reason='测试作废')
|
||||
db.session.commit()
|
||||
|
||||
@@ -254,11 +248,8 @@ def test_admin_can_purge_only_pure_deleted_task_and_audit_is_retained(app, clien
|
||||
def test_purge_blocks_task_with_business_reference(app):
|
||||
"""已有业务单的回收站任务即使被手工篡改为 active,也必须阻断永久删除。"""
|
||||
with app.app_context():
|
||||
case = ShippingCase(case_no='SC-DISPOSITION-PURGE-BLOCK')
|
||||
task = _task('SN-DISPOSITION-PURGE-BLOCK')
|
||||
db.session.add_all([case, task])
|
||||
db.session.flush()
|
||||
task.shipping_case_id = case.id
|
||||
task = _task('SN-DISPOSITION-PURGE-BLOCK', business_no='SN260823003')
|
||||
db.session.add(task)
|
||||
task.deleted_at = __import__('datetime').datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ def test_unuploaded_resend_voids_old_task_and_keeps_new_active(app):
|
||||
assert new.lifecycle_status == 'active'
|
||||
|
||||
|
||||
def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(app):
|
||||
"""关键断言:已上传旧版必须先有撤销回执,后继版才恢复活动状态。"""
|
||||
def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app):
|
||||
"""关键断言:已上传旧版须登记外部撤销确认;不要求回执号或文件。"""
|
||||
with app.app_context():
|
||||
old, new, user = _tasks(uploaded=True)
|
||||
establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend')
|
||||
@@ -39,7 +39,11 @@ def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(a
|
||||
assert new.lifecycle_status == 'blocked'
|
||||
with pytest.raises(ConflictError):
|
||||
assert_task_not_supersession_blocked(new)
|
||||
complete_freight_cancellation(cancellation_id=row.id, actor_id=user.id, freight_receipt_no='CANCEL-1', receipt_asset_id=1)
|
||||
complete_freight_cancellation(
|
||||
cancellation_id=row.id,
|
||||
actor_id=user.id,
|
||||
note='已在货代平台确认撤销',
|
||||
)
|
||||
assert row.status == 'cancelled'
|
||||
assert old.lifecycle_status == 'voided'
|
||||
assert new.lifecycle_status == 'active'
|
||||
@@ -18,9 +18,10 @@ from app.models import (
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success
|
||||
from app.services.shipping_notice.export import assert_notice_has_no_export_artifact
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
complete_attempt, has_verified_upload_success, mark_attempt_result_unknown,
|
||||
start_rpa_attempt, void_rejected_artifact,
|
||||
record_manual_upload, start_rpa_attempt, void_rejected_artifact,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
|
||||
@@ -73,6 +74,108 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app):
|
||||
start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
|
||||
|
||||
def test_notice_with_existing_excel_cannot_generate_another_artifact(app):
|
||||
"""一个发货通知单已有 Excel 后必须创建新 Notice,不能追加第二个 Artifact。"""
|
||||
with app.app_context():
|
||||
task, _artifact, _reservation = _ready_artifact()
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
assert_notice_has_no_export_artifact(task)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED'
|
||||
|
||||
|
||||
def test_batch_notice_confirmation_isolates_each_business_number(app, monkeypatch):
|
||||
"""批量通知单确认中一张被阻断时,其他通知单仍独立提交成功。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.api.workspace import shipping_notice as api
|
||||
|
||||
with app.app_context(), app.test_request_context(
|
||||
'/api/workspace/shipping-notices/batch/confirm-uploaded',
|
||||
method='POST',
|
||||
json={'business_nos': ['WVC26082301', 'WVC26082302']},
|
||||
):
|
||||
commits: list[str] = []
|
||||
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=7))
|
||||
monkeypatch.setattr(
|
||||
api,
|
||||
'_confirm_notice_uploaded',
|
||||
lambda *, business_no, user_id: (
|
||||
{'status': 'ok'} if business_no.endswith('01')
|
||||
else (_ for _ in ()).throw(ConflictError('already uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED'))
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(api.db.session, 'commit', lambda: commits.append('commit'))
|
||||
monkeypatch.setattr(api.db.session, 'rollback', lambda: commits.append('rollback'))
|
||||
|
||||
response = api.workspace_batch_confirm_shipping_notices_uploaded()
|
||||
body = response[0].get_json()['data']
|
||||
|
||||
assert [item['status'] for item in body['results']] == ['confirmed', 'blocked']
|
||||
assert commits == ['commit', 'rollback']
|
||||
|
||||
|
||||
def test_business_no_rpa_batch_isolates_each_notice(app, monkeypatch):
|
||||
"""批量 RPA 必须只接受 business_no,并让已受理通知独立提交。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.api.workspace import shipping_notice as api
|
||||
|
||||
with app.app_context(), app.test_request_context(
|
||||
'/api/workspace/shipping-notices/batch/rpa-upload',
|
||||
method='POST',
|
||||
json={'business_nos': ['WVC26082301', 'WVC26082302']},
|
||||
):
|
||||
commits: list[str] = []
|
||||
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=7))
|
||||
monkeypatch.setattr(
|
||||
api,
|
||||
'_start_notice_rpa_upload',
|
||||
lambda *, business_no, user_id: (
|
||||
{'status': 'running'} if business_no.endswith('01')
|
||||
else (_ for _ in ()).throw(ConflictError('unknown result', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN'))
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(api.db.session, 'commit', lambda: commits.append('commit'))
|
||||
monkeypatch.setattr(api.db.session, 'rollback', lambda: commits.append('rollback'))
|
||||
|
||||
response = api.workspace_batch_start_shipping_notice_rpa_upload()
|
||||
body = response[0].get_json()['data']
|
||||
|
||||
assert [item['status'] for item in body['results']] == ['accepted', 'blocked']
|
||||
assert [item['business_no'] for item in body['results']] == ['WVC26082301', 'WVC26082302']
|
||||
assert commits == ['commit', 'rollback']
|
||||
|
||||
|
||||
def test_business_no_loader_rejects_task_no_alias(app, monkeypatch):
|
||||
"""新货代入口不得把内部 task_no 或旧 Case 编号当作 business_no 接收。"""
|
||||
from app.api.workspace import shipping_notice as api
|
||||
|
||||
with app.app_context(), app.test_request_context('/api/workspace/shipping-notices/SN-1/export'):
|
||||
task = ShippingNotice(task_no='SN-1', business_no='WVC26082301', user_id=7)
|
||||
monkeypatch.setattr(api, 'get_task_for_user', lambda reference, user_id: task)
|
||||
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
api._load_business_notice_for_user(business_no='SN-1', user_id=7)
|
||||
|
||||
assert getattr(exc_info.value, 'code', None) == 'RESOURCE.NOT_FOUND'
|
||||
|
||||
|
||||
def test_upload_success_updates_only_its_notice(app):
|
||||
"""一张独立 Notice 上传成功只终态化其自身,不影响同 PO 的其他 Notice。"""
|
||||
with app.app_context():
|
||||
task, artifact, _reservation = _ready_artifact()
|
||||
other = ShippingNotice(task_no='TASK-UPLOAD-OTHER', order_task_id=task.order_task_id)
|
||||
db.session.add(other); db.session.flush()
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
|
||||
complete_attempt(attempt, success=True, callback_id='callback-notice', freight_ref_no='F-2')
|
||||
|
||||
assert db.session.get(ShippingNotice, task.id).upload_status == 'uploaded'
|
||||
assert db.session.get(ShippingNotice, other.id).upload_status is None
|
||||
|
||||
|
||||
def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app):
|
||||
"""历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。"""
|
||||
with app.app_context():
|
||||
@@ -105,6 +208,24 @@ def test_failed_attempt_does_not_complete_reservation(app):
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready'
|
||||
|
||||
|
||||
def test_manual_upload_confirmation_requires_no_receipt_or_file_evidence(app):
|
||||
"""人工确认只记录操作者和目标 Excel,不要求货代回执或截图/PDF。"""
|
||||
with app.app_context():
|
||||
task, artifact, reservation = _ready_artifact()
|
||||
|
||||
attempt = record_manual_upload(
|
||||
task,
|
||||
artifact_id=artifact.id,
|
||||
operator_id=7,
|
||||
)
|
||||
|
||||
assert attempt.mode == 'manual'
|
||||
assert attempt.evidence_asset_id is None
|
||||
assert attempt.freight_ref_no is None
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
|
||||
|
||||
|
||||
def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app):
|
||||
"""共享目录投递失败要落为失败 Attempt,不能遗留 uploading Artifact 阻断下一轮。"""
|
||||
with app.app_context():
|
||||
@@ -200,7 +321,7 @@ def test_upload_callback_success_parsing_does_not_treat_false_text_as_success():
|
||||
|
||||
|
||||
def test_rpa_report_upload_success_without_evidence_rejected(app):
|
||||
"""success=True 但缺少 success_evidence 时必须 fail-closed 拒绝。"""
|
||||
"""RPA success=True 但缺少受信 Worker 证据时必须 fail-closed 拒绝。"""
|
||||
with app.app_context():
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -224,7 +345,7 @@ def test_rpa_report_upload_success_without_evidence_rejected(app):
|
||||
|
||||
|
||||
def test_rpa_report_upload_success_without_reference_allowed(app):
|
||||
"""DSV 绿 DOM 成功时 reference 可为空;须带 success_evidence.kind 且证据资产落库。"""
|
||||
"""DSV 受信成功证据可不带 reference,并持久化内部审计资产。"""
|
||||
with app.app_context():
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -259,13 +380,9 @@ def test_rpa_report_upload_success_without_reference_allowed(app):
|
||||
'observed_at': '2026-08-05T03:00:00Z',
|
||||
'page_url': 'https://dsv.example/history',
|
||||
'dom_snippet': '<em class="fa fa-circle success-color status-icon"></em>',
|
||||
'dom_sha256': (
|
||||
__import__('hashlib')
|
||||
.sha256(
|
||||
b'<em class="fa fa-circle success-color status-icon"></em>'
|
||||
)
|
||||
.hexdigest()
|
||||
),
|
||||
'dom_sha256': __import__('hashlib').sha256(
|
||||
b'<em class="fa fa-circle success-color status-icon"></em>'
|
||||
).hexdigest(),
|
||||
},
|
||||
})
|
||||
assert result['status'] == 'ok'
|
||||
@@ -273,13 +390,12 @@ def test_rpa_report_upload_success_without_reference_allowed(app):
|
||||
refreshed = db.session.get(ShippingUploadAttempt, attempt.id)
|
||||
assert refreshed is not None
|
||||
evidence = refreshed.success_evidence_json or {}
|
||||
assert evidence.get('dom_sha256')
|
||||
assert evidence.get('page_url')
|
||||
assert refreshed.evidence_asset_id == 4242
|
||||
|
||||
|
||||
def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app):
|
||||
"""DOM 校验通过但证据资产落库失败时,不得标记上传成功。"""
|
||||
def test_rpa_report_upload_success_requires_internal_audit_asset(app):
|
||||
"""自动 RPA 成功仍保存内部审计资产;人工确认路径不受此规则影响。"""
|
||||
with app.app_context():
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -288,12 +404,16 @@ def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app):
|
||||
task, artifact, reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
db.session.commit()
|
||||
def _persist(*, task, attempt, success_evidence):
|
||||
attempt.evidence_asset_id = 4242
|
||||
return 4242
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.fulfillment_workflow.customer_gate_tool_response',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.fulfillment_workflow._persist_rpa_success_evidence_asset',
|
||||
return_value=None,
|
||||
side_effect=_persist,
|
||||
):
|
||||
result = rpa_report_upload({
|
||||
'task_id': task.task_no,
|
||||
@@ -310,60 +430,43 @@ def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app):
|
||||
'dom_sha256': __import__('hashlib').sha256(b'<div id="ok"/>').hexdigest(),
|
||||
},
|
||||
})
|
||||
assert result['status'] == 'failed'
|
||||
assert result.get('data', {}).get('upload_evidence_persist_failed') is True
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
|
||||
assert db.session.get(ShippingUploadAttempt, attempt.id).status != 'succeeded'
|
||||
assert result['status'] == 'ok'
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
|
||||
assert db.session.get(ShippingUploadAttempt, attempt.id).evidence_asset_id == 4242
|
||||
|
||||
|
||||
def test_normalize_rpa_success_evidence_rejects_missing_dom_or_bad_hash():
|
||||
"""缺少 page_url/dom 或哈希不匹配时必须拒绝。"""
|
||||
def test_normalize_rpa_success_evidence_requires_minimal_status_summary():
|
||||
"""受信 RPA 成功证据必须具备可核验的站点、时间、文件和页面定位。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import _normalize_rpa_success_evidence
|
||||
import hashlib
|
||||
|
||||
snippet = '<div id="ok"/>'
|
||||
digest = hashlib.sha256(snippet.encode('utf-8')).hexdigest()
|
||||
base = {
|
||||
'kind': 'green_success_dom',
|
||||
'selector': '#ok',
|
||||
'filename': 'test.xlsx',
|
||||
'observed_at': '2026-08-05T03:00:00Z',
|
||||
'page_url': 'https://example.test/upload',
|
||||
'dom_snippet': snippet,
|
||||
'dom_sha256': digest,
|
||||
}
|
||||
base.update({'dom_snippet': '<div id="ok"/>', 'dom_sha256': __import__('hashlib').sha256(b'<div id="ok"/>').hexdigest()})
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': base}) is not None
|
||||
# 关键断言:缺 page_url / 缺 snippet / 哈希错误一律 None。
|
||||
# 关键断言:缺页面定位、选择器、时间或文件名一律拒绝。
|
||||
bad_url = dict(base, page_url='')
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': bad_url}) is None
|
||||
bad_snip = dict(base, dom_snippet='')
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': bad_snip}) is None
|
||||
bad_hash = dict(base, dom_sha256='0' * 64)
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': bad_hash}) is None
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': dict(base, selector='')}) is None
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': dict(base, observed_at='')}) is None
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': dict(base, filename='')}) is None
|
||||
|
||||
|
||||
def test_normalize_rpa_success_evidence_requires_dom_contract():
|
||||
"""缺 page_url / dom_snippet / 哈希不一致时必须拒绝成功证据。"""
|
||||
import hashlib
|
||||
|
||||
def test_normalize_rpa_success_evidence_rejects_bad_dom_contract():
|
||||
"""RPA 内部回调仍需 DOM 哈希自洽;这不适用于人工上传确认。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import _normalize_rpa_success_evidence
|
||||
|
||||
snippet = '<em class="ok"></em>'
|
||||
digest = hashlib.sha256(snippet.encode('utf-8')).hexdigest()
|
||||
base = {
|
||||
'kind': 'dsv_history_green_dom',
|
||||
'selector': 'em.ok',
|
||||
'filename': 'test.xlsx',
|
||||
'observed_at': '2026-08-05T03:00:00Z',
|
||||
'page_url': 'https://dsv.example/history',
|
||||
'dom_snippet': snippet,
|
||||
'dom_sha256': digest,
|
||||
'dom_snippet': '<em class="ok"></em>',
|
||||
'dom_sha256': '0' * 64,
|
||||
'screenshot_base64': 'legacy-only',
|
||||
}
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': base}) is not None
|
||||
# 关键断言:缺 page_url / 缺 snippet / 哈希不匹配均 fail-closed。
|
||||
missing_url = dict(base, page_url='')
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': missing_url}) is None
|
||||
missing_dom = dict(base, dom_snippet='')
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': missing_dom}) is None
|
||||
bad_hash = dict(base, dom_sha256='0' * 64)
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': bad_hash}) is None
|
||||
assert _normalize_rpa_success_evidence({'success_evidence': base}) is None
|
||||
@@ -1,444 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_vendor_comments_phase2.py
|
||||
|
||||
用途:阶段 2 集成回归——契约、关系投影、三来源裁决(Header/Table/Vendor Comments)、
|
||||
回 Draft 门禁、格式策略服务 5 大主题全量覆盖。
|
||||
依赖:6 个新服务(profile_vendor_comments_contract、coordinate_region_source_adapter、
|
||||
reservation_relation_projection、profile_field_source_mapping_service、
|
||||
source_merge_service、reservation_format_policy_service)。
|
||||
逻辑:纯内存单测——读真实 PDF/数据库的用例放在阶段 4;
|
||||
覆盖 Q13/Q14/Q15/Q16/Q18 全部冻结决策矩阵。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import (
|
||||
CoordinateRegionSourceAdapter,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
BaseSplitMatcher,
|
||||
BaseSplitNormalization,
|
||||
BaseSplitRule,
|
||||
BaseSplitRuleSet,
|
||||
BaseSplitSegment,
|
||||
RelationCaptureDef,
|
||||
new_segment_id,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import (
|
||||
FieldSourceCandidate,
|
||||
ProfileFieldSourceMappingService,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
|
||||
NamedRegion,
|
||||
ProfileFieldSourceMapping,
|
||||
ReservationFormatPolicy,
|
||||
field_source_mappings_checksum,
|
||||
field_source_mappings_require_draft,
|
||||
named_regions_checksum,
|
||||
parse_field_source_mappings,
|
||||
parse_named_regions,
|
||||
profile_regions_require_draft,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.reservation_format_policy_service import (
|
||||
ReservationFormatPolicyService,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.reservation_relation_projection import (
|
||||
ReservationRelationProjection,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.source_merge_service import (
|
||||
SourceMergeService,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile import RelativeRegion
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# [TEST GROUP 1] profile_vendor_comments_contract(Q14/Q15)
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_parse_named_regions_empty_is_allowed():
|
||||
"""当前客户没配 Vendor Comments 区域 → 返回空,不报错。"""
|
||||
assert parse_named_regions(None) == {}
|
||||
assert parse_named_regions({}) == {}
|
||||
|
||||
|
||||
def test_named_region_last_page_vendor_comments_parses():
|
||||
"""Q14 冻结结构:region_id/label/region/page_scope/selection_mode 全齐。"""
|
||||
raw = {
|
||||
'vendor_comments': {
|
||||
'region_id': 'vendor-comments-v1',
|
||||
'label': 'Vendor Comments',
|
||||
'region': {'x0': 0.03, 'y0': 0.62, 'x1': 0.42, 'y1': 0.78},
|
||||
'page_scope': 'last_page',
|
||||
'selection_mode': 'fixed_region',
|
||||
},
|
||||
}
|
||||
regions = parse_named_regions(raw)
|
||||
assert 'vendor_comments' in regions
|
||||
r = regions['vendor_comments']
|
||||
assert r.page_scope == 'last_page'
|
||||
assert r.region.y1 > r.region.y0
|
||||
|
||||
|
||||
def test_named_region_rejects_key_region_id_mismatch():
|
||||
"""外键 key 与 region_id 不一致:拒绝。"""
|
||||
raw = {'vc': {'region_id': 'other-name',
|
||||
'label': 'L', 'region': {'x0':0,'y0':0,'x1':1,'y1':1},
|
||||
'page_scope': 'last_page', 'selection_mode': 'fixed_region'}}
|
||||
from app.core.errors import ValidationError
|
||||
with pytest.raises(ValidationError):
|
||||
parse_named_regions(raw)
|
||||
|
||||
|
||||
def test_profile_regions_require_draft_matrix():
|
||||
"""Q14:增删改 region/坐标/page_scope/selection_mode → 回 Draft;仅 label 不回。"""
|
||||
old = {
|
||||
'vc': {
|
||||
'region_id': 'vc', 'label': 'Old Label',
|
||||
'region': {'x0':0,'y0':0,'x1':1,'y1':1},
|
||||
'page_scope': 'last_page', 'selection_mode': 'fixed_region',
|
||||
},
|
||||
}
|
||||
# 仅改 label → 不回 Draft
|
||||
new_same_label_only = {k: {**v, 'label': 'New Label'} for k, v in old.items()}
|
||||
assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_same_label_only) is False
|
||||
|
||||
# 改 x0 → 回 Draft
|
||||
new_coord = {k: {**v} for k, v in old.items()}
|
||||
new_coord['vc']['region'] = {'x0':0.01,'y0':0,'x1':1,'y1':1}
|
||||
assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_coord) is True
|
||||
|
||||
# 新增 region → 回 Draft
|
||||
new_extra = {
|
||||
**old,
|
||||
'other': {
|
||||
'region_id': 'other', 'label': 'O',
|
||||
'region': {'x0':0,'y0':0,'x1':0.1,'y1':0.1},
|
||||
'page_scope': 'first_page', 'selection_mode': 'fixed_region',
|
||||
},
|
||||
}
|
||||
assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_extra) is True
|
||||
|
||||
|
||||
def test_field_source_mappings_require_draft_any_change_triggers():
|
||||
"""Q9:field_source_mappings 任何改 → 回 Draft(首期全量 fail-close)。"""
|
||||
old = [{
|
||||
'mapping_id': 'm1', 'target_scope': 'line', 'target_field_code': 'reservation_id',
|
||||
'target_field_id': 'f-r1', 'vendor_comments_enabled': False,
|
||||
}]
|
||||
new = [{
|
||||
'mapping_id': 'm1', 'target_scope': 'line', 'target_field_code': 'reservation_id',
|
||||
'target_field_id': 'f-r1', 'vendor_comments_enabled': True,
|
||||
'vendor_comments_region_ref': 'vc',
|
||||
'vendor_comments_split_rule_set': {
|
||||
'rule_set_id': 'rs1', 'rule_version': 1,
|
||||
'normalization': {}, 'rules': [],
|
||||
'unmatched_line_policy': 'evidence_only', 'source': 'user',
|
||||
'status': 'confirmed', 'requires_confirmation': False,
|
||||
},
|
||||
}]
|
||||
assert field_source_mappings_require_draft(old_mappings=old, new_mappings=new) is True
|
||||
|
||||
|
||||
def test_reservation_format_policy_rejects_dangerous_regex():
|
||||
"""Q15:(a+)+$ 被 Pydantic validator 拦截在构造阶段。"""
|
||||
from pydantic import ValidationError as PydanticValErr
|
||||
with pytest.raises(PydanticValErr):
|
||||
ReservationFormatPolicy(
|
||||
mode='custom_safe_regex',
|
||||
pattern=r'(a+)+$',
|
||||
)
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# [TEST GROUP 2] reservation_relation_projection(Q2/Q7/Q12)
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_relation_projection_bind_target_line_via_profile_business_line_no():
|
||||
"""Q2:captured_relation.line_no=2 命中 profile_business_line_no{2:1} → 逻辑行号1。"""
|
||||
from app.services.shipping_notice.document_layout.field_split_core import CoreCapturedRelation
|
||||
proj = ReservationRelationProjection(
|
||||
relation_policy='bind_target_line',
|
||||
line_reference_basis='profile_business_line_no',
|
||||
)
|
||||
result = proj.project(
|
||||
captured_relation=CoreCapturedRelation(type='line_reference', line_no=2, raw_text='for line#2'),
|
||||
profile_business_line_numbers={1: '1', 2: '2', 3: '3'},
|
||||
)
|
||||
assert result.resolution == 'bound_to_line'
|
||||
assert result.resolved_logical_line_no == 2 # 逻辑行号=1-based mapping key
|
||||
|
||||
|
||||
def test_relation_projection_invalid_line_reference_emits_independent_reason():
|
||||
"""Q12:引用不存在的行 99 → invalid_line_reference 独立原因码。"""
|
||||
from app.services.shipping_notice.document_layout.field_split_core import CoreCapturedRelation
|
||||
proj = ReservationRelationProjection(relation_policy='bind_target_line')
|
||||
result = proj.project(
|
||||
captured_relation=CoreCapturedRelation(type='line_reference', line_no=99, raw_text='line#99'),
|
||||
profile_business_line_numbers={1: '1', 2: '2'},
|
||||
)
|
||||
assert result.resolution == 'invalid_line_reference'
|
||||
assert result.invalid_reference_line_no == 99
|
||||
assert result.audit_chain is not None
|
||||
assert result.should_generate_header_observation is True # invalid 保留为头证据
|
||||
|
||||
|
||||
def test_relation_projection_annotation_only_writes_metadata():
|
||||
"""annotation_only:不绑定行,不生成行 Observation,生成头元数据。"""
|
||||
proj = ReservationRelationProjection(relation_policy='annotation_only')
|
||||
result = proj.project(
|
||||
captured_relation=None,
|
||||
annotation_reason_override='customer_commentary_reservation',
|
||||
)
|
||||
assert result.resolution == 'annotation_only'
|
||||
assert result.annotation_reason == 'customer_commentary_reservation'
|
||||
assert result.should_generate_line_observation is False
|
||||
assert result.should_generate_header_observation is True
|
||||
|
||||
|
||||
def test_relation_missing_policy_default_all_lines_flags_every_line():
|
||||
"""missing_relation_policy=default_all_lines:每行都生成 Observation。"""
|
||||
proj = ReservationRelationProjection(
|
||||
relation_policy='bind_target_line',
|
||||
missing_relation_policy='default_all_lines',
|
||||
)
|
||||
result = proj.project(captured_relation=None)
|
||||
assert result.resolution == 'default_all_lines'
|
||||
assert result.should_generate_line_observation is True
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# [TEST GROUP 3] SourceMergeService(Q18 三来源裁决)
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def _make_cand(source, scope, code, line_no, value, *,
|
||||
fv=True, frc=None, mapping_id='m1', target_field_id='f-r1',
|
||||
hint='provisional') -> FieldSourceCandidate:
|
||||
c = FieldSourceCandidate(
|
||||
source=source, target_scope=scope, target_field_code=code,
|
||||
target_field_id=target_field_id, value=value, normalized_value=value,
|
||||
format_valid=fv, format_reason_code=frc, effective_line_no=line_no,
|
||||
resolution_hint=hint,
|
||||
evidence_quote=value, evidence_ref=f'{source}-ref',
|
||||
evidence_metadata={'mapping_id': mapping_id},
|
||||
)
|
||||
c.conflict_group_key = (scope, code, line_no)
|
||||
return c
|
||||
|
||||
|
||||
def test_source_merge_same_value_merged_marks_metadata():
|
||||
"""Q18 same_value_merge:三来源同值 3000098851 → resolution=same_value_merged。"""
|
||||
candidates = [
|
||||
_make_cand('header_region', 'line', 'reservation_id', 1, '3000098851'),
|
||||
_make_cand('table_column', 'line', 'reservation_id', 1, '3000098851'),
|
||||
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851'),
|
||||
]
|
||||
svc = SourceMergeService(candidates)
|
||||
merged = svc.merge_and_decide()
|
||||
assert len(merged) == 1
|
||||
m = merged[0]
|
||||
assert m.accepted_value == '3000098851'
|
||||
assert m.resolution == 'same_value_merged'
|
||||
assert m.decision_status == 'accepted'
|
||||
assert m.should_persist_observation is True
|
||||
md = m.evidence_metadata
|
||||
assert md['resolution'] == 'same_value_merged'
|
||||
assert len(md['source_observations']) == 3
|
||||
assert 'vendor_comments' in md['resolution_meta'].get('merged_from_sources', [])
|
||||
|
||||
|
||||
def test_source_merge_conflict_triggers_needs_review_no_accepted_value():
|
||||
"""Q18 冲突:Header=3000098851, VC=3000098899 → accepted_value=None, needs_review。"""
|
||||
candidates = [
|
||||
_make_cand('header_region', 'line', 'reservation_id', 1, '3000098851'),
|
||||
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098899'),
|
||||
]
|
||||
svc = SourceMergeService(candidates)
|
||||
merged = svc.merge_and_decide()
|
||||
assert len(merged) == 1
|
||||
m = merged[0]
|
||||
assert m.accepted_value is None
|
||||
assert m.resolution == 'needs_review'
|
||||
assert m.decision_status == 'needs_review'
|
||||
assert m.should_persist_observation is False
|
||||
assert len(m.evidence_metadata['source_observations']) == 2
|
||||
assert len(m.conflicts) == 2 # 双冲突
|
||||
|
||||
|
||||
def test_source_merge_fill_missing_table_empty_filled_from_vc():
|
||||
"""Q4 fill_missing:表列空,VC 提供值 → fill_missing 自动填补。"""
|
||||
candidates = [
|
||||
_make_cand('table_column', 'line', 'reservation_id', 1, ''),
|
||||
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851'),
|
||||
]
|
||||
svc = SourceMergeService(candidates)
|
||||
merged = svc.merge_and_decide()
|
||||
m = merged[0]
|
||||
assert m.accepted_value == '3000098851'
|
||||
assert m.resolution == 'fill_missing'
|
||||
md = m.evidence_metadata
|
||||
assert md['resolution_meta']['accepted_source'] == 'vendor_comments'
|
||||
|
||||
|
||||
def test_source_merge_annotation_only_never_becomes_accepted():
|
||||
"""annotation_only / invalid_line_reference:永不升 accepted,永不生成有效 Observation。"""
|
||||
candidates = [
|
||||
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851', hint='annotation_only'),
|
||||
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '123', hint='invalid_line_reference'),
|
||||
]
|
||||
svc = SourceMergeService(candidates)
|
||||
merged = svc.merge_and_decide()
|
||||
assert len(merged) == 1
|
||||
m = merged[0]
|
||||
assert m.should_persist_observation is False
|
||||
assert m.decision_status == 'blocked'
|
||||
assert len(m.evidence_metadata['source_observations']) == 2
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# [TEST GROUP 4] 三来源候选收集(ProfileFieldSourceMappingService)
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_collect_candidates_table_and_header_scopes_are_independent():
|
||||
"""Q4:不同 scope 独立保留,互不冲突。Header=300001, Line=300002 都被收集。"""
|
||||
definition_json = {
|
||||
'field_source_mappings': [
|
||||
{'mapping_id': 'mh', 'target_scope': 'header',
|
||||
'target_field_code': 'reservation_id', 'target_field_id': 'f-hr',
|
||||
'header_source_enabled': True, 'header_source_ref': 'header-rid'},
|
||||
{'mapping_id': 'ml', 'target_scope': 'line',
|
||||
'target_field_code': 'reservation_id', 'target_field_id': 'f-lr',
|
||||
'table_source_enabled': True, 'table_column_code': 'reservation_id'},
|
||||
],
|
||||
}
|
||||
svc = ProfileFieldSourceMappingService(
|
||||
definition_json=definition_json,
|
||||
header_observations_by_source_ref={
|
||||
'header-rid': [{'value': '300001', 'evidence_ref': 'h-ref-1'}],
|
||||
},
|
||||
table_column_values={
|
||||
'reservation_id': [
|
||||
{'line_index': 0, 'value': '300002', 'evidence_ref': 'l1'},
|
||||
{'line_index': 1, 'value': '300003', 'evidence_ref': 'l2'},
|
||||
],
|
||||
},
|
||||
)
|
||||
cands = svc.collect_candidates()
|
||||
header_cands = [c for c in cands if c.target_scope == 'header']
|
||||
line_cands = [c for c in cands if c.target_scope == 'line']
|
||||
assert len(header_cands) == 1
|
||||
assert header_cands[0].value == '300001'
|
||||
assert len(line_cands) == 2
|
||||
line_values = sorted([c.value for c in line_cands])
|
||||
assert line_values == ['300002', '300003']
|
||||
# Header 与 Line 不同冲突组
|
||||
groups = {c.conflict_group_key for c in cands}
|
||||
assert len(groups) == 3 # header+None / line+1 / line+2
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# [TEST GROUP 5] FormatPolicyService(Q15)
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_format_policy_inherit_global_accepts_5_and_10_numeric():
|
||||
svc = ReservationFormatPolicyService()
|
||||
r5 = svc.check(ReservationFormatPolicy(mode='inherit_global'), '12345')
|
||||
r10 = svc.check(ReservationFormatPolicy(mode='inherit_global'), '1234567890')
|
||||
r_alpha = svc.check(ReservationFormatPolicy(mode='inherit_global'), 'ABC12')
|
||||
assert r5.valid is True and r5.normalized_value == '12345'
|
||||
assert r10.valid is True and r10.normalized_value == '1234567890'
|
||||
assert r_alpha.valid is False and r_alpha.reason_code == 'reservation_format_invalid'
|
||||
assert r_alpha.should_block_auto_create is True
|
||||
|
||||
|
||||
def test_format_policy_custom_safe_regex_uses_first_capture_group():
|
||||
"""字母型 Reservation 预留(例如 R-12345)通过第 1 捕获组提取。"""
|
||||
svc = ReservationFormatPolicyService()
|
||||
policy = ReservationFormatPolicy(
|
||||
mode='custom_safe_regex',
|
||||
pattern=r'R[ -](\d{5,10})\b',
|
||||
case_sensitive=False,
|
||||
)
|
||||
r = svc.check(policy, 'please use R-3000098851 thanks')
|
||||
assert r.valid is True
|
||||
assert r.normalized_value == '3000098851'
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# [TEST GROUP 6] CoordinateRegionSourceAdapter smoke(小字典 bbox)
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_coordinate_region_adapter_last_page_reads_text():
|
||||
"""last_page → page_no=2,返回可用原文 + bbox 证据。"""
|
||||
def glyph(ch, x, y, page_w=800, page_h=1100, *,
|
||||
prev_space=False, src_idx=0):
|
||||
w = 10
|
||||
b = 'space' if prev_space else 'none'
|
||||
return {
|
||||
'text': ch,
|
||||
'bbox': {'x0': x*page_w, 'y0': y*page_h,
|
||||
'x1': (x+0.01)*page_w, 'y1': (y+0.02)*page_h},
|
||||
'boundary_before': b,
|
||||
'source_index': src_idx,
|
||||
}
|
||||
page1_glyphs = [glyph('A', 0.05, 0.1, src_idx=i) for i, A in enumerate('PageOne')]
|
||||
page2_glyphs = [
|
||||
*(glyph(ch, 0.04 + i*0.015, 0.65, src_idx=100+i, prev_space=(ch == ' '))
|
||||
for i, ch in enumerate('Reservation 3000098851 for line#2')),
|
||||
]
|
||||
page_bundle = {
|
||||
1: {'glyphs': page1_glyphs, 'page': {'width': 800, 'height': 1100}},
|
||||
2: {'glyphs': page2_glyphs, 'page': {'width': 800, 'height': 1100}},
|
||||
}
|
||||
region = NamedRegion(
|
||||
region_id='vc', label='VC',
|
||||
region=RelativeRegion(x0=0.01, y0=0.60, x1=0.80, y1=0.80),
|
||||
page_scope='last_page',
|
||||
selection_mode='fixed_region',
|
||||
)
|
||||
adapter = CoordinateRegionSourceAdapter(region, page_bundle)
|
||||
result = adapter.extract()
|
||||
assert result.status == 'available'
|
||||
assert result.page_no == 2
|
||||
assert '3000098851' in result.raw_text
|
||||
assert 'line' in result.raw_text.lower()
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# [TEST GROUP 7] checksums 稳定性(防篡改)
|
||||
# =========================================================================
|
||||
|
||||
|
||||
def test_checksums_deterministic_and_sensitive_to_content():
|
||||
regions = {'vc': NamedRegion(
|
||||
region_id='vc', label='L', selection_mode='fixed_region',
|
||||
region=RelativeRegion(x0=0, y0=0, x1=1, y1=1),
|
||||
page_scope='last_page',
|
||||
)}
|
||||
h1 = named_regions_checksum(regions)
|
||||
assert len(h1) == 64
|
||||
regions2 = dict(regions)
|
||||
regions2['vc'].model_copy() # 内容相同 → hash 相同(copy 保持引用,直接 mutate 不行,因此换 label)
|
||||
regions_diff = {'vc': NamedRegion(
|
||||
region_id='vc', label='Changed Label But Still Same Content?',
|
||||
selection_mode='fixed_region',
|
||||
region=RelativeRegion(x0=0, y0=0, x1=1, y1=1),
|
||||
page_scope='last_page',
|
||||
)}
|
||||
# Label 变化 → 不同 hash(label 进入 checksum,因为管理员 label 变更不触发回 Draft,但需要留痕)
|
||||
h_diff = named_regions_checksum(regions_diff)
|
||||
assert h1 != h_diff
|
||||
|
||||
mappings = [ProfileFieldSourceMapping(
|
||||
mapping_id='m1', target_scope='line', target_field_code='reservation_id',
|
||||
target_field_id='f-r1', vendor_comments_enabled=False,
|
||||
)]
|
||||
mh1 = field_source_mappings_checksum(mappings)
|
||||
assert len(mh1) == 64
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_publish_separation_of_duties.py
|
||||
|
||||
用途:阶段 6 发布职责分离契约——编辑人不得批准自己的 Revision。
|
||||
用途:验证发布确认不再额外限制草稿创建人。
|
||||
依赖:publish_check_service 已有 consume 阻断键;本文件固化原因码与审计事件集合。
|
||||
逻辑:纯单元断言职责分离键与编辑审计事件白名单稳定。
|
||||
"""
|
||||
@@ -17,19 +17,13 @@ from app.services.shipping_notice import order_document_profile_publish_check_se
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_editor_self_approval_reason_key_is_stable():
|
||||
"""关键断言:职责分离失败键稳定为 editor_cannot_approve_own_version。"""
|
||||
def test_editor_self_approval_gate_is_removed():
|
||||
"""关键断言:消费流程不再包含自己编辑不得发布的门禁。"""
|
||||
source = inspect.getsource(checks.consume_report)
|
||||
assert 'editor_cannot_approve_own_version' in source
|
||||
assert '_find_last_profile_editor_id' in source
|
||||
assert 'editor_cannot_approve_own_version' not in source
|
||||
assert '_find_last_profile_editor_id' not in source
|
||||
|
||||
|
||||
def test_editor_audit_events_cover_mapping_and_split():
|
||||
"""关键断言:查找最近编辑者覆盖末端映射与拆分编辑审计事件。"""
|
||||
source = inspect.getsource(checks._find_last_profile_editor_id)
|
||||
for event in (
|
||||
'xfa_mapping_saved',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_segment_mapping_updated',
|
||||
):
|
||||
assert event in source
|
||||
def test_publish_check_service_has_no_editor_separation_helper():
|
||||
"""关键断言:发布检查服务不再保留历史编辑者查询辅助函数。"""
|
||||
assert not hasattr(checks, '_find_last_profile_editor_id')
|
||||
@@ -97,6 +97,18 @@ def test_matcher_whitelist_and_regex_limits():
|
||||
XfaSplitMatcher(type='regex', pattern=r'(a+)+$')
|
||||
|
||||
|
||||
def test_position_matcher_accepts_restricted_prefix_post_processor():
|
||||
"""位置选行后可正式执行标签后取值,不能依赖 UI stages[]。"""
|
||||
matcher = XfaSplitMatcher(
|
||||
type='position',
|
||||
line_index=3,
|
||||
post_processors=[{'type': 'prefix', 'value': 'MPN', 'separators': [':', ':']}],
|
||||
)
|
||||
|
||||
assert matcher.post_processors[0].type == 'prefix'
|
||||
assert matcher.post_processors[0].value == 'MPN'
|
||||
|
||||
|
||||
def test_rule_set_accepts_rule_id_alias():
|
||||
"""历史 rule_id 字段可解析为 rule_set_id。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
|
||||
@@ -254,3 +254,32 @@ def test_line_breaks_config_is_honored():
|
||||
assert 'A' in claimeds
|
||||
unmatched = {item.normalized_text for item in result.evidence_only_segments if item.rule_id == 'unmatched'}
|
||||
assert unmatched == {'B', 'C'}
|
||||
|
||||
|
||||
def test_position_rule_applies_prefix_post_processor_to_selected_line():
|
||||
"""先按行定位,再取标签后内容,保证 XFA 正式规则与预览一致。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_set_id='mpn-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-x',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r-mpn',
|
||||
matcher=XfaSplitMatcher(
|
||||
type='position', line_index=3,
|
||||
post_processors=[{'type': 'prefix', 'value': 'MPN', 'separators': [':', ':']}],
|
||||
),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='part_number', display_name='MPN',
|
||||
handling='mapped', target_field_id='f-part', target_field_code='part_number',
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
result = execute_split_rule_set(raw_value='TEMP-S000218922\nFRAME\nMPN:D4-A08AR12000001', rule_set=rule_set)
|
||||
|
||||
assert result.mapped_fields == {'part_number': 'D4-A08AR12000001'}
|
||||
assert result.segments[0].raw_text == 'MPN:D4-A08AR12000001'
|
||||
assert result.segments[0].normalized_text == 'D4-A08AR12000001'
|
||||
@@ -1,6 +1,7 @@
|
||||
import pytest
|
||||
from flask import g
|
||||
from app import create_app, db
|
||||
from app.models import Agent, User
|
||||
from app.models import Agent, ChatSession, User
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
@@ -97,3 +98,60 @@ def test_chat_url_logic(client):
|
||||
res = client.get('/api/chat/sessions', headers=headers, json={'agent_id': agent_id})
|
||||
assert res.status_code == 403
|
||||
assert res.get_json()['error'] == 'Permission denied for this agent'
|
||||
|
||||
|
||||
def test_chat_completions_stream_reads_session_snapshot_after_commit(client, monkeypatch):
|
||||
"""
|
||||
提交会话后消费 SSE 时使用标量快照,避免已脱离 Session 的 ORM 实例被延迟刷新。
|
||||
|
||||
关键断言:生成器在请求返回后仍能产出 session_created 事件,而不会抛出
|
||||
DetachedInstanceError。
|
||||
"""
|
||||
with client.application.app_context():
|
||||
user = User(username='stream-user', role='admin', email='stream-user@example.com')
|
||||
agent = Agent(name='Stream Agent', dify_api_key='test-key', api_base_url='http://dify.invalid')
|
||||
db.session.add_all([user, agent])
|
||||
db.session.commit()
|
||||
user_id = user.id
|
||||
agent_id = agent.id
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.chat.executors.stream_chat_via_executor',
|
||||
lambda _context: iter(['data: {"event": "message_end"}\n\n']),
|
||||
)
|
||||
from app.api.chat import completions
|
||||
|
||||
captured_session = None
|
||||
original_ensure_chat_session = completions._ensure_chat_session
|
||||
|
||||
def capture_ensured_session(*args, **kwargs):
|
||||
nonlocal captured_session
|
||||
captured_session = original_ensure_chat_session(*args, **kwargs)
|
||||
return captured_session
|
||||
|
||||
monkeypatch.setattr(completions, '_ensure_chat_session', capture_ensured_session)
|
||||
|
||||
def get_current_user():
|
||||
current_user = db.session.get(User, user_id)
|
||||
g.current_user = current_user
|
||||
return current_user
|
||||
|
||||
monkeypatch.setattr('app.core.decorators._get_current_user', get_current_user)
|
||||
|
||||
with client.application.test_request_context(
|
||||
'/api/chat/completions',
|
||||
method='POST',
|
||||
json={'agent_id': agent_id, 'query': '测试流式会话'},
|
||||
):
|
||||
response = client.application.view_functions['chat.chat_completions']()
|
||||
# 模拟生产环境:流式处理中的事务令 ORM 属性过期,随后请求 scoped Session 被清理。
|
||||
assert captured_session is not None
|
||||
db.session.expire(captured_session)
|
||||
db.session.remove()
|
||||
body = ''.join(response.response).encode()
|
||||
|
||||
assert response.status_code == 200
|
||||
assert b'"event": "session_created"' in body
|
||||
assert b'DetachedInstanceError' not in body
|
||||
with client.application.app_context():
|
||||
assert ChatSession.query.filter_by(user_id=user_id, agent_id=agent_id).count() == 1
|
||||
@@ -53,6 +53,22 @@ def test_shipping_worker_claims_unified_pdf_automark_jobs(monkeypatch):
|
||||
assert JobType.SHIPPING_PDF_AUTOMARK in received['job_types']
|
||||
|
||||
|
||||
def test_shipping_worker_claims_review_revalidate_jobs(monkeypatch):
|
||||
"""Review Revalidate Job 必须进入 shipping worker 领取白名单,不能永久 queued。"""
|
||||
received: dict[str, object] = {}
|
||||
|
||||
def claim_next_job(**kwargs):
|
||||
received.update(kwargs)
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.jobs.queue.claim_next_job', claim_next_job)
|
||||
|
||||
queue_service.claim_next_shipping_notice_job()
|
||||
|
||||
# 关键断言:字段变更后的异步校验任务必须由 shipping worker 领取。
|
||||
assert JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS in received['job_types']
|
||||
|
||||
|
||||
def test_route_runtime_diagnostic_identifies_loaded_workflow_without_document_content():
|
||||
"""路由审计必须可定位 Worker 代码身份,且不得采集文档或字段内容。"""
|
||||
from app.jobs.handlers import shipping_order_extraction as handler
|
||||
|
||||
Reference in new issue
Block a user