feat(shipping-notice): 添加识别定义和规则集管理功能,支持客户和站点的可配置识别规则
This commit is contained in:
1 parent
88408490d7
commit
34d489a2d1
167 files changed
+10365
-7978
No files matched your search
+109
-15
@@ -2,6 +2,38 @@ import pytest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _capture_legacy_order_rows_for_tests(monkeypatch):
|
||||
"""将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。"""
|
||||
from app.models import ShippingTask
|
||||
|
||||
original_init = ShippingTask.__init__
|
||||
legacy_headers = ('customer_name', 'customer_code', 'ship_to', 'po_number', 'required_date')
|
||||
|
||||
def _init(self, **kwargs):
|
||||
rows = kwargs.pop('lines_json', None)
|
||||
kwargs.pop('order_lines_migration_status', None)
|
||||
header_values = {key: kwargs.pop(key) for key in legacy_headers if key in kwargs}
|
||||
original_init(self, **kwargs)
|
||||
if rows is not None:
|
||||
self._test_order_rows = [dict(item) for item in rows if isinstance(item, dict)]
|
||||
for key, value in header_values.items():
|
||||
setattr(self, f'_test_{key}', value)
|
||||
|
||||
monkeypatch.setattr(ShippingTask, '__init__', _init)
|
||||
for key in (*legacy_headers, 'lines_json'):
|
||||
storage = f'_test_{key}' if key != 'lines_json' else '_test_order_rows'
|
||||
monkeypatch.setattr(
|
||||
ShippingTask,
|
||||
key,
|
||||
property(
|
||||
lambda task, name=storage: getattr(task, name, None),
|
||||
lambda task, value, name=storage: setattr(task, name, value),
|
||||
),
|
||||
raising=False,
|
||||
)
|
||||
|
||||
|
||||
def parse_api_error(body: dict) -> dict:
|
||||
"""
|
||||
从标准 API 错误 envelope 中提取 error 子对象,供测试断言 error.code / details。
|
||||
@@ -93,7 +125,6 @@ def _shipping_test_default_destination(monkeypatch, request):
|
||||
return
|
||||
|
||||
from app.services.shipping_notice import extract as extract_mod
|
||||
import app.services.shipping_notice.task_workflow as task_workflow_mod
|
||||
|
||||
original = extract_mod.extract_notice_fields
|
||||
|
||||
@@ -119,7 +150,6 @@ def _shipping_test_default_destination(monkeypatch, request):
|
||||
return original(*args, structured=patched, **kwargs)
|
||||
|
||||
monkeypatch.setattr(extract_mod, "extract_notice_fields", _extract_with_default_destination)
|
||||
monkeypatch.setattr(task_workflow_mod, "extract_notice_fields", _extract_with_default_destination)
|
||||
|
||||
|
||||
def seed_task_inventory_source(
|
||||
@@ -128,6 +158,7 @@ def seed_task_inventory_source(
|
||||
source_code: str = "DSV360_AWSDU",
|
||||
) -> None:
|
||||
"""测试辅助:为直接构造的 ShippingTask 写入稳定库存源独立字段。"""
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
@@ -158,6 +189,79 @@ def seed_task_inventory_source(
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
|
||||
|
||||
def _ensure_test_task_dynamic_order(task: "ShippingTask") -> None:
|
||||
"""将 RPA 测试显式构造的旧行样例转换为当前测试所需的动态 FieldValue。"""
|
||||
from decimal import Decimal
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
if task.current_order_extraction_id is not None:
|
||||
return
|
||||
rows = list(getattr(task, '_test_order_rows', []) or [])
|
||||
if not rows:
|
||||
return
|
||||
if task.id is None:
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
order_schema_service.initialize_schema({'display_name': 'RPA 测试动态订单'}, actor_id=None)
|
||||
fields = {
|
||||
code: order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
|
||||
)
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
|
||||
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
|
||||
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
|
||||
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
} for code, field in fields.items()],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
field_ids = {str(item['field_code']): str(item['field_id']) for item in (version.definition_json or {}).get('fields') or []}
|
||||
required = {'part_number', 'reservation_id', 'qty'}
|
||||
if not required.issubset(field_ids):
|
||||
raise ValueError('RPA test schema lacks required order business purposes')
|
||||
extraction = ShippingOrderExtraction(task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
for position, row in enumerate(rows):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code in required:
|
||||
value = row.get(code)
|
||||
if code == 'qty' and value not in (None, ''):
|
||||
value = Decimal(str(value))
|
||||
json_value = str(value) if code == 'qty' and value is not None else value
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json=json_value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
|
||||
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
|
||||
value_json=json_value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def seed_rpa_inventory_trigger(
|
||||
task: "ShippingTask",
|
||||
*,
|
||||
@@ -288,8 +392,8 @@ def _seed_test_inventory_configuration() -> None:
|
||||
"""为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition, ShippingInventorySource, ShippingRpaProfile,
|
||||
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
|
||||
ShippingRpaProfile,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import (
|
||||
FINGERPRINT_VERSION,
|
||||
@@ -386,19 +490,9 @@ def _seed_test_inventory_configuration() -> None:
|
||||
query_parameters_json=[
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': True, 'select_all': False},
|
||||
],
|
||||
match_aliases_json=['AWSDU', 'DUB'],
|
||||
enabled=True,
|
||||
)
|
||||
rule = ShippingInventoryRoutingRule(
|
||||
rule_code='TEST_DUB', rule_name='Test DUB route', scope='task', priority=100,
|
||||
match_mode='all', status='published', action_type='add_source_candidates',
|
||||
action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=1,
|
||||
)
|
||||
rule.conditions.append(ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=1, source_kind='system_fact', system_fact_key='task.destination_port', operator='equals',
|
||||
expected_value_json='DUB', sequence=1,
|
||||
))
|
||||
db.session.add_all([profile, parsing_profile, excel_template, source, rule])
|
||||
db.session.add_all([profile, parsing_profile, excel_template, source])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerImportBatch,
|
||||
ShippingCustomerImportRow,
|
||||
@@ -154,6 +156,34 @@ def test_delete_unused_customer_cascades_identifiers_and_keeps_snapshot_audit(ap
|
||||
assert event.reason == '误建客户'
|
||||
|
||||
|
||||
def test_delete_unused_customer_cascades_configurable_identity_evidence(app):
|
||||
"""关键断言:新模型证据也是可级联配置,不能成为永久删除阻断或遗留外键。"""
|
||||
with app.app_context():
|
||||
customer = _customer('IDE')
|
||||
definition = ShippingIdentityDefinition(
|
||||
definition_code='delete_sender_email', target_type='customer', source_adapter_key='email_metadata',
|
||||
source_selector_json={'attribute': 'email.from', 'projection': 'email'},
|
||||
attribute_key='email', normalizer_key='email', comparator_key='normalized_exact',
|
||||
max_automation='conditional', status='active',
|
||||
)
|
||||
db.session.add(definition)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingIdentityEvidence(
|
||||
definition_id=definition.id, customer_id=customer.id, raw_value='delete@example.com',
|
||||
normalized_value='delete@example.com', status='approved',
|
||||
))
|
||||
db.session.commit()
|
||||
customer_id = customer.id
|
||||
|
||||
impact = get_customer_lifecycle_impact(customer_id)
|
||||
assert impact['can_delete'] is True
|
||||
assert impact['cascade']['identity_evidences'] == 1
|
||||
result = delete_customer(customer_id, confirmation_short_code='IDE', reason='误建', actor_id=1)
|
||||
|
||||
assert result['cascade']['identity_evidences'] == 1
|
||||
assert db.session.query(ShippingIdentityEvidence).filter_by(customer_id=customer_id).count() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference_kind', [
|
||||
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
])
|
||||
|
||||
@@ -20,6 +20,8 @@ from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerMerge,
|
||||
ShippingCustomerShadowResolution,
|
||||
@@ -71,8 +73,10 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
|
||||
preview = get_customer_merge_impact(source_id, target_id)
|
||||
assert preview['historical_references']['business_cases'] == 1
|
||||
# 合并预检同时展示旧识别证据与阶段一可配置证据的迁移统计。
|
||||
assert preview['migrate'] == {
|
||||
'identifiers': 1, 'duplicate_identifiers': 1, 'external_references': 1, 'sites': 0,
|
||||
'identifiers': 1, 'duplicate_identifiers': 1, 'identity_evidences': 0,
|
||||
'duplicate_identity_evidences': 0, 'external_references': 1, 'sites': 0,
|
||||
}
|
||||
|
||||
result = merge_customer(
|
||||
@@ -80,7 +84,8 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
)
|
||||
|
||||
assert result['migrate'] == {
|
||||
'identifiers': 1, 'duplicate_identifiers': 1, 'external_references': 1, 'sites': 0,
|
||||
'identifiers': 1, 'duplicate_identifiers': 1, 'identity_evidences': 0,
|
||||
'duplicate_identity_evidences': 0, 'external_references': 1, 'sites': 0,
|
||||
}
|
||||
source_after = db.session.get(ShippingCustomer, source_id)
|
||||
target_after = db.session.get(ShippingCustomer, target_id)
|
||||
@@ -102,6 +107,37 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
assert {item['id'] for item in list_customer_options()} == {target_id}
|
||||
|
||||
|
||||
def test_merge_moves_and_deduplicates_configurable_identity_evidences(app):
|
||||
"""关键断言:阶段一新证据随未来配置归并,重复标准值先删除再迁移。"""
|
||||
with app.app_context():
|
||||
source = _customer('新证据源客户', 'IES')
|
||||
target = _customer('新证据目标客户', 'IET')
|
||||
definition = ShippingIdentityDefinition(
|
||||
definition_code='merge_sender_email', target_type='customer', source_adapter_key='email_metadata',
|
||||
source_selector_json={'attribute': 'email.from', 'projection': 'email'},
|
||||
attribute_key='email', normalizer_key='email', comparator_key='normalized_exact',
|
||||
max_automation='conditional', status='active',
|
||||
)
|
||||
db.session.add(definition)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingIdentityEvidence(definition_id=definition.id, customer_id=source.id,
|
||||
raw_value='move@example.com', normalized_value='move@example.com', status='approved'),
|
||||
ShippingIdentityEvidence(definition_id=definition.id, customer_id=source.id,
|
||||
raw_value='same@example.com', normalized_value='same@example.com', status='approved'),
|
||||
ShippingIdentityEvidence(definition_id=definition.id, customer_id=target.id,
|
||||
raw_value='same@example.com', normalized_value='same@example.com', status='approved'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
result = merge_customer(source.id, target_customer_id=target.id, confirmation_short_code='IES', reason='重复', actor_id=1)
|
||||
|
||||
assert result['migrate']['identity_evidences'] == 1
|
||||
assert result['migrate']['duplicate_identity_evidences'] == 1
|
||||
assert db.session.query(ShippingIdentityEvidence).filter_by(customer_id=source.id).count() == 0
|
||||
assert db.session.query(ShippingIdentityEvidence).filter_by(customer_id=target.id).count() == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode', ['same', 'inactive_target', 'wrong_confirmation', 'missing_reason'])
|
||||
def test_merge_rejects_invalid_request(app, mode: str):
|
||||
"""归并请求必须选择不同的启用目标客户,并由服务端校验简码和原因。"""
|
||||
|
||||
@@ -16,7 +16,13 @@ from app.services.admin import shipping_inventory_service
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app import db
|
||||
from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryStructureAnalysis
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
)
|
||||
|
||||
|
||||
def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
|
||||
@@ -131,10 +137,18 @@ def _source_data(profile_id: int, *, parsing_profile_id: int | None = None, code
|
||||
'query_parameters_json': [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
|
||||
],
|
||||
'match_aliases_json': ['DUB'],
|
||||
}
|
||||
|
||||
|
||||
def _published_route_field_id() -> str:
|
||||
"""返回当前发布 Schema 的行级预定单号字段,避免测试再构造固定系统事实条件。"""
|
||||
_parsing_profile()
|
||||
return next(
|
||||
item['field_id'] for item in order_schema_service.get_published_contract()['fields']
|
||||
if item['scope'] == 'line' and item['field_code'] == 'reservation_id'
|
||||
)
|
||||
|
||||
|
||||
def test_profile_credentials_are_not_returned(app):
|
||||
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
@@ -240,7 +254,7 @@ def test_activation_status_exposes_structured_checks_without_duplicate_test_bloc
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inventory', 'report_name': 'On Hand',
|
||||
},
|
||||
'query_parameters_json': [], 'match_aliases_json': [], 'enabled': False,
|
||||
'query_parameters_json': [], 'enabled': False,
|
||||
}
|
||||
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
|
||||
@@ -278,7 +292,6 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app):
|
||||
assert source['query_parameters_json'] == [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
|
||||
]
|
||||
assert source['match_aliases_json'] == ['DUB']
|
||||
|
||||
|
||||
def test_source_rejects_driver_selector_in_business_parameters(app):
|
||||
@@ -306,24 +319,104 @@ def test_crane_source_rejects_dbs_report_path(app):
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app):
|
||||
"""停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
|
||||
payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE')
|
||||
payload.update({'enabled': False, 'parsing_profile_id': None})
|
||||
source = shipping_inventory_service.save_source(payload, actor_id=7, allow_enable_transition=False)
|
||||
profile = _parsing_profile()
|
||||
|
||||
bound = shipping_inventory_service.bind_source_parsing_profile(
|
||||
[source['id']], profile['id'], actor_id=7, operation='direct',
|
||||
)
|
||||
|
||||
# 关键断言:直接绑定只配置解析定义,绝不绕过独立启用门禁。
|
||||
assert bound[0]['enabled'] is False
|
||||
assert bound[0]['parsing_profile_id'] == profile['id']
|
||||
assert bound[0]['config_version'] == source['config_version'] + 1
|
||||
audit = ShippingInventorySourceParsingBindingAudit.query.one()
|
||||
assert audit.operation == 'direct'
|
||||
# 关键断言:审计保留系统动作说明,不要求管理员额外填写“绑定原因”。
|
||||
assert audit.reason == '管理员直接绑定已发布解析方案'
|
||||
assert audit.before_snapshot_json['parsing_profile_id'] is None
|
||||
assert audit.after_snapshot_json['parsing_profile_id'] == profile['id']
|
||||
history = shipping_inventory_service.get_source_parsing_binding_audits(source['id'])
|
||||
assert history[0]['actor_id'] == 7
|
||||
assert history[0]['source_config_version_after'] == bound[0]['config_version']
|
||||
|
||||
|
||||
def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
|
||||
"""批量绑定必须先全量预检;已启用站点阻断时其余站点不能部分写入。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
|
||||
disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED')
|
||||
disabled_payload.update({'enabled': False, 'parsing_profile_id': None})
|
||||
disabled = shipping_inventory_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False)
|
||||
enabled = shipping_inventory_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
|
||||
profile = _parsing_profile()
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.bind_source_parsing_profile(
|
||||
[disabled['id'], enabled['id']], profile['id'], actor_id=None,
|
||||
reason='批量迁移同类报表', operation='bulk',
|
||||
)
|
||||
|
||||
# 关键断言:任一站点不可变更时,停用站点也不得留下部分绑定或审计。
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_BLOCKED'
|
||||
assert db.session.get(ShippingInventorySource, disabled['id']).parsing_profile_id is None
|
||||
assert ShippingInventorySourceParsingBindingAudit.query.count() == 0
|
||||
|
||||
|
||||
def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app):
|
||||
"""直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
|
||||
payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE')
|
||||
payload.update({'enabled': False, 'parsing_profile_id': None})
|
||||
source = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
template = db.session.get(ShippingExcelTemplate, source['excel_template_id'])
|
||||
template.definition_json = {
|
||||
'filename_pattern': '{business_no}.xlsx',
|
||||
'mappings': [{'source_kind': 'inventory_field', 'source_key': '999999'}],
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.bind_source_parsing_profile(
|
||||
[source['id']], _parsing_profile()['id'], actor_id=None,
|
||||
reason='模板字段契约预检', operation='direct',
|
||||
)
|
||||
|
||||
# 关键断言:模板依赖缺失必须在绑定时拒绝,不能产生半成品站点绑定。
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID'
|
||||
assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None
|
||||
assert ShippingInventorySourceParsingBindingAudit.query.count() == 0
|
||||
|
||||
|
||||
def test_published_rule_cannot_be_mutated_in_place(app):
|
||||
"""发布规则必须依靠新版本演进,避免改写历史任务依据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
|
||||
reservation_field_id = _published_route_field_id()
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line',
|
||||
'priority': 100, 'match_mode': 'all', 'action_type': 'add_source_candidates',
|
||||
'action_payload_json': {'source_codes': [source['source_code']]}, 'version': 1,
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
}, actor_id=None)
|
||||
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.save_rule({
|
||||
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Changed', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
}, actor_id=None, rule_id=rule['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_IMMUTABLE'
|
||||
|
||||
@@ -331,15 +424,16 @@ def test_published_rule_cannot_be_mutated_in_place(app):
|
||||
def test_draft_rule_update_keeps_the_same_draft(app):
|
||||
"""草稿更新应原地替换条件,不能偷偷新增同版本规则记录。"""
|
||||
with app.app_context():
|
||||
reservation_field_id = _published_route_field_id()
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'task',
|
||||
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'task.destination_port', 'operator': 'equals', 'expected_value_json': 'DUB'}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'DUB'}],
|
||||
}, actor_id=None)
|
||||
updated = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'task',
|
||||
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'task.destination_port', 'operator': 'equals', 'expected_value_json': 'FRA'}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'FRA'}],
|
||||
}, actor_id=None, rule_id=rule['id'])
|
||||
assert updated['id'] == rule['id']
|
||||
assert updated['rule_name'] == 'After'
|
||||
@@ -349,10 +443,11 @@ def test_draft_rule_update_keeps_the_same_draft(app):
|
||||
def test_rule_condition_value_type_follows_the_selected_operator(app):
|
||||
"""列表、长度和空值操作符必须保存受控值类型,不能把配置错误拖到运行期。"""
|
||||
with app.app_context():
|
||||
reservation_field_id = _published_route_field_id()
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'RSV_IN', 'rule_name': 'Reservation list', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'in', 'expected_value_json': ['1001', '1002']}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': ['1001', '1002']}],
|
||||
}, actor_id=None)
|
||||
assert rule['conditions'][0]['expected_value_json'] == ['1001', '1002']
|
||||
|
||||
@@ -360,7 +455,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
|
||||
shipping_inventory_service.save_rule({
|
||||
'rule_code': 'RSV_BAD_IN', 'rule_name': 'Invalid list', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'in', 'expected_value_json': '1001'}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': '1001'}],
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_CONDITION_INVALID'
|
||||
|
||||
@@ -382,10 +477,11 @@ def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
|
||||
shipping_inventory_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLE_BLOCKED'
|
||||
|
||||
reservation_field_id = _published_route_field_id()
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'RETIRE_ME', 'rule_name': 'Retire me', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
}, actor_id=None)
|
||||
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
|
||||
retired = shipping_inventory_service.retire_rule(rule['id'], actor_id=None)
|
||||
@@ -405,11 +501,12 @@ def test_publish_rule_rejects_missing_or_disabled_source(app):
|
||||
disabled_payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
|
||||
shipping_inventory_service.save_source(disabled_payload, actor_id=None)
|
||||
|
||||
reservation_field_id = _published_route_field_id()
|
||||
for index, code in enumerate(('MISSING_SOURCE', 'DISABLED_ROUTE_SOURCE'), start=1):
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': f'INVALID_SOURCE_{index}', 'rule_name': 'Invalid source rule', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [code]},
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': str(index)}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': str(index)}],
|
||||
}, actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
|
||||
@@ -418,7 +515,7 @@ def test_publish_rule_rejects_missing_or_disabled_source(app):
|
||||
valid_rule = shipping_inventory_service.save_rule({
|
||||
'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
|
||||
'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '9'}],
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '9'}],
|
||||
}, actor_id=None)
|
||||
assert shipping_inventory_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published'
|
||||
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
backend/tests/services/shipping_notice/test_identity_rules_service.py
|
||||
|
||||
用途:验证可配置客户识别定义、规则集版本和订单字段依赖门禁。
|
||||
依赖:内存数据库、订单 Schema 模型、identity_rules.service。
|
||||
逻辑:只覆盖阶段一配置模型,不提前验证阶段二运行时客户候选解析。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingCustomer, ShippingIdentityDefinition, ShippingOrderField, ShippingOrderSchema, ShippingOrderSchemaVersion
|
||||
from app.services.shipping_notice.identity_rules import service
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _published_header_field() -> ShippingOrderField:
|
||||
"""建立已发布 Header 文本字段,模拟业务识别定义的唯一合法来源。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(schema_id=schema.id, field_code='ship_to_address', scope='header', value_type='string')
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': [{
|
||||
'field_id': field.id, 'field_code': field.field_code, 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True,
|
||||
}]}, lock_version=1,
|
||||
))
|
||||
db.session.commit()
|
||||
return field
|
||||
|
||||
|
||||
def test_order_field_definition_requires_published_header_text_field_and_never_auto_confirms(app):
|
||||
"""订单字段定义只能引用当前发布 Header 文本字段,且首期不能提升自动确认等级。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field()
|
||||
created = service.save_definition({
|
||||
'definition_code': 'ship_to_address', 'target_type': 'site', 'attribute_key': 'ship_to_address',
|
||||
'order_field_id': field.id, 'normalizer_key': 'text_upper',
|
||||
'comparator_key': 'normalized_exact', 'default_weight': 50, 'max_automation': 'none',
|
||||
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
|
||||
}, actor_id=1)
|
||||
assert created['order_field_id'] == field.id
|
||||
assert created['source_adapter_key'] == 'order_field'
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
service.save_definition({
|
||||
'definition_code': 'unsafe', 'target_type': 'site', 'attribute_key': 'ship_to_address',
|
||||
'order_field_id': field.id, 'normalizer_key': 'text_upper',
|
||||
'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
|
||||
}, actor_id=1)
|
||||
assert exc_info.value.code == 'SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN'
|
||||
|
||||
|
||||
def test_definition_reference_blocks_order_field_retirement(app):
|
||||
"""关键断言:被启用识别定义引用的 field_id 不能退役,避免字段改名/退役静默失效。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field()
|
||||
service.save_definition({
|
||||
'definition_code': 'site_contact', 'target_type': 'site', 'attribute_key': 'contact',
|
||||
'order_field_id': field.id, 'normalizer_key': 'name',
|
||||
'comparator_key': 'normalized_exact', 'max_automation': 'none',
|
||||
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
|
||||
}, actor_id=1)
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
order_schema_service.retire_field(field.id, actor_id=1)
|
||||
assert exc_info.value.code == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
|
||||
|
||||
|
||||
def test_published_rule_snapshot_also_blocks_order_field_retirement_after_definition_is_retired(app):
|
||||
"""关键断言:历史发布规则快照仍引用字段时,退役字段必须被阻断。"""
|
||||
with app.app_context():
|
||||
field = _published_header_field()
|
||||
definition = service.save_definition({
|
||||
'definition_code': 'site_address_history', 'target_type': 'site', 'attribute_key': 'ship_to_address',
|
||||
'order_field_id': field.id, 'normalizer_key': 'text_upper',
|
||||
'comparator_key': 'normalized_exact', 'max_automation': 'none',
|
||||
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
|
||||
}, actor_id=1)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
service.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
|
||||
service.retire_definition(definition['id'], actor_id=1)
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
order_schema_service.retire_field(field.id, actor_id=1)
|
||||
assert exc_info.value.code == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
|
||||
|
||||
|
||||
def test_rule_set_is_optimistically_locked_and_published_snapshot_is_immutable(app):
|
||||
"""草稿以锁版本防覆盖,发布后冻结定义快照并自动退役上一版本。"""
|
||||
with app.app_context():
|
||||
definition = service.save_definition({
|
||||
'definition_code': 'sender_email', 'target_type': 'customer', 'attribute_key': 'email',
|
||||
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'default_weight': 100,
|
||||
'max_automation': 'conditional', 'source_adapter_key': 'email_metadata',
|
||||
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
|
||||
}, actor_id=1)
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
published = service.publish_rule_set(
|
||||
draft['id'], expected_lock_version=saved['lock_version'], actor_id=1,
|
||||
)
|
||||
assert published['status'] == 'published'
|
||||
assert published['checksum']
|
||||
with pytest.raises(ConflictError):
|
||||
service.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': saved['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
|
||||
|
||||
def test_customer_evidence_is_unique_per_definition_and_normalized_value(app):
|
||||
"""关键断言:同一客户相同定义的标准值只能保存一次,NULL 目标列不得绕过唯一性。"""
|
||||
with app.app_context():
|
||||
customer = ShippingCustomer(standard_name='Evidence Customer', short_code='EVC', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.commit()
|
||||
definition = service.save_definition({
|
||||
'definition_code': 'customer_sender_email', 'target_type': 'customer', 'attribute_key': 'email',
|
||||
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'email_metadata',
|
||||
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
|
||||
}, actor_id=1)
|
||||
# 阶段三后证据维护只能选择当前已发布规则集中的定义,避免录入运行期不消费的值。
|
||||
draft = service.create_rule_set({}, actor_id=1)
|
||||
saved = service.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
service.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
|
||||
service.create_evidence(
|
||||
target_type='customer', target_id=customer.id,
|
||||
data={'definition_id': definition['id'], 'raw_value': 'buyer@example.com', 'status': 'approved'}, actor_id=1,
|
||||
)
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
service.create_evidence(
|
||||
target_type='customer', target_id=customer.id,
|
||||
data={'definition_id': definition['id'], 'raw_value': 'BUYER@example.com', 'status': 'approved'}, actor_id=1,
|
||||
)
|
||||
assert exc_info.value.code == 'SHIPPING.IDENTITY_EVIDENCE_CONFLICT'
|
||||
|
||||
|
||||
def test_identity_rule_admin_routes_are_registered(app):
|
||||
"""关键断言:阶段一规则目录、规则集和新证据值均通过管理员受保护 API 暴露。"""
|
||||
with app.app_context():
|
||||
rules = {rule.rule for rule in app.url_map.iter_rules()}
|
||||
assert '/api/admin/shipping-identity-rules/definitions' in rules
|
||||
assert '/api/admin/shipping-identity-rules/rule-sets' in rules
|
||||
assert '/api/admin/shipping-customers/<int:customer_id>/identity-evidences' in rules
|
||||
|
||||
|
||||
def test_business_definition_owns_display_copy_and_service_derives_execution_settings(app):
|
||||
"""管理员维护业务名称和说明;来源适配器而非前端白名单决定内部标准化与自动化上限。"""
|
||||
with app.app_context():
|
||||
definition = service.save_definition({
|
||||
'display_name': '北美客户业务邮箱',
|
||||
'description': '仅用于北美区域客户的发件人邮箱识别。',
|
||||
'evidence_label': '北美客户业务邮箱',
|
||||
'target_type': 'customer',
|
||||
'source_adapter_key': 'email_metadata',
|
||||
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
|
||||
# 客户端传入的运行参数不能覆盖平台受控来源的安全边界。
|
||||
'attribute_key': 'customer_name', 'normalizer_key': 'text_upper',
|
||||
'max_automation': 'conditional',
|
||||
}, actor_id=1)
|
||||
|
||||
# 关键断言:业务名称进入 API 返回和后续规则快照,实际匹配策略由来源能力决定。
|
||||
assert definition['display_name'] == '北美客户业务邮箱'
|
||||
assert definition['description'] == '仅用于北美区域客户的发件人邮箱识别。'
|
||||
assert definition['evidence_label'] == '北美客户业务邮箱'
|
||||
assert definition['attribute_key'] == 'email'
|
||||
assert definition['normalizer_key'] == 'email'
|
||||
assert definition['max_automation'] == 'conditional'
|
||||
|
||||
|
||||
def test_definition_catalog_serializes_source_adapter_sets_as_stable_json_arrays(app):
|
||||
"""来源目录中的内部集合必须转换为有序 JSON 数组,规则列表接口不能因目录加载而返回 500。"""
|
||||
with app.app_context():
|
||||
catalog = service.list_definitions()['catalog']
|
||||
email_adapter = next(item for item in catalog['source_adapters'] if item['key'] == 'email_metadata')
|
||||
|
||||
# 关键断言:内部 set 不可泄漏到 API;固定排序也保证前端目录结果可预测。
|
||||
assert email_adapter['selectors']['projections'] == ['domain', 'email']
|
||||
assert json.loads(json.dumps(catalog)) == catalog
|
||||
|
||||
|
||||
def test_email_and_template_definitions_are_explicit_business_configuration(app):
|
||||
"""空库不自动补齐定义;管理员可按受控适配器创建邮箱和模板业务规则。"""
|
||||
with app.app_context():
|
||||
assert ShippingIdentityDefinition.query.count() == 0
|
||||
email = service.save_definition({
|
||||
'definition_code': 'apac_sender_email', 'target_type': 'customer', 'attribute_key': 'email',
|
||||
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'email_metadata',
|
||||
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
|
||||
}, actor_id=1)
|
||||
template = service.save_definition({
|
||||
'definition_code': 'apac_notice_template', 'target_type': 'customer', 'attribute_key': 'template_fingerprint',
|
||||
'normalizer_key': 'text_upper', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'document_template', 'source_selector': {'document': 'primary'},
|
||||
}, actor_id=1)
|
||||
|
||||
assert email['source_adapter_key'] == 'email_metadata'
|
||||
assert email['source_selector']['projection'] == 'email'
|
||||
assert template['source_adapter_key'] == 'document_template'
|
||||
assert ShippingIdentityDefinition.query.count() == 2
|
||||
|
||||
|
||||
def test_source_adapter_rejects_arbitrary_paths_and_unsafe_automation(app):
|
||||
"""来源选择器只能使用平台目录,订单字段和站点定义均不能借 API 绕过自动化红线。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as invalid_source:
|
||||
service.save_definition({
|
||||
'definition_code': 'unsafe_path', 'target_type': 'customer', 'attribute_key': 'email',
|
||||
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'email_metadata',
|
||||
'source_selector': {'attribute': 'raw_llm_output_json', 'projection': 'email'},
|
||||
}, actor_id=1)
|
||||
assert invalid_source.value.code == 'SHIPPING.IDENTITY_DEFINITION_INVALID'
|
||||
|
||||
with pytest.raises(ValidationError) as site_automation:
|
||||
service.save_definition({
|
||||
'definition_code': 'site_template', 'target_type': 'site', 'attribute_key': 'ship_to_name',
|
||||
'normalizer_key': 'name', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'document_template', 'source_selector': {'document': 'primary'},
|
||||
}, actor_id=1)
|
||||
assert site_automation.value.code == 'SHIPPING.IDENTITY_DEFINITION_INVALID'
|
||||
@@ -14,6 +14,8 @@ from app.models import (
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
@@ -81,6 +83,72 @@ def test_shipping_customer_admin_routes_reject_non_admin(app, client):
|
||||
assert parse_api_error(response.get_json())['code'] == 'AUTH.FORBIDDEN'
|
||||
|
||||
|
||||
def test_configured_identity_evidence_api_requires_published_definition_and_disables_legacy_writes(app, client):
|
||||
"""后台只能维护已发布定义的证据;旧固定类型写入口必须明确拒绝,避免写入运行期不消费的数据。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
customer = ShippingCustomer(standard_name='配置客户', short_code='CFG', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.commit()
|
||||
customer_id = customer.id
|
||||
|
||||
headers = _headers('shipping-admin', 'admin')
|
||||
catalog = client.get('/api/admin/shipping-identity-rules/published-evidence-definitions?target_type=customer', headers=headers)
|
||||
assert catalog.status_code == 200
|
||||
assert parse_api_data(catalog.get_json())['disabled_reason'] == 'published_rule_set_required'
|
||||
|
||||
blocked = client.post(
|
||||
f'/api/admin/shipping-customers/{customer_id}/identifiers',
|
||||
json={'identifier_type': 'email', 'identifier_value': 'legacy@example.com'}, headers=headers,
|
||||
)
|
||||
assert blocked.status_code == 400
|
||||
assert parse_api_error(blocked.get_json())['code'] == 'SHIPPING.CUSTOMER_LEGACY_IDENTIFIER_WRITE_DISABLED'
|
||||
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.identity_rules import service as identity_rules
|
||||
|
||||
definition = identity_rules.save_definition({
|
||||
'definition_code': 'api_sender_email', 'target_type': 'customer', 'attribute_key': 'email',
|
||||
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'email_metadata',
|
||||
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
|
||||
}, actor_id=1)
|
||||
draft = identity_rules.create_rule_set({}, actor_id=1)
|
||||
saved = identity_rules.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': [definition['id']],
|
||||
}, actor_id=1)
|
||||
identity_rules.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
|
||||
|
||||
enabled = client.get('/api/admin/shipping-identity-rules/published-evidence-definitions?target_type=customer', headers=headers)
|
||||
definition_payload = parse_api_data(enabled.get_json())['definitions'][0]
|
||||
assert definition_payload['definition_code'] == 'api_sender_email'
|
||||
|
||||
created = client.post(
|
||||
f'/api/admin/shipping-customers/{customer_id}/identity-evidences',
|
||||
json={'definition_id': definition_payload['id'], 'raw_value': 'buyer@cfg.example.com', 'status': 'pending'},
|
||||
headers=headers,
|
||||
)
|
||||
assert created.status_code == 201
|
||||
evidence = parse_api_data(created.get_json())
|
||||
assert evidence['definition']['definition_code'] == 'api_sender_email'
|
||||
|
||||
missing_reason = client.put(
|
||||
f'/api/admin/shipping-identity-evidences/{evidence["id"]}', json={'status': 'approved'}, headers=headers,
|
||||
)
|
||||
assert missing_reason.status_code == 400
|
||||
assert parse_api_error(missing_reason.get_json())['code'] == 'SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED'
|
||||
|
||||
approved = client.put(
|
||||
f'/api/admin/shipping-identity-evidences/{evidence["id"]}',
|
||||
json={'status': 'approved', 'reason': '已核验邮箱归属'}, headers=headers,
|
||||
)
|
||||
assert approved.status_code == 200
|
||||
assert parse_api_data(approved.get_json())['status'] == 'approved'
|
||||
with app.app_context():
|
||||
assert ShippingIdentityEvidence.query.count() == 1
|
||||
|
||||
|
||||
def test_shipping_customer_lifecycle_impact_api_is_admin_only(app, client):
|
||||
"""生命周期影响预览返回统一结构,普通用户不能读取删除资格。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
|
||||
@@ -160,7 +160,7 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inventory', 'report_name': 'On Hand',
|
||||
},
|
||||
'query_parameters_json': [], 'match_aliases_json': [],
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
created = client.post('/api/admin/shipping-notice/sources', json=payload, headers=_headers('inventory-admin', 'admin'))
|
||||
assert created.status_code == 201
|
||||
@@ -192,7 +192,7 @@ def test_latest_inventory_configuration_test_is_admin_only(app, client):
|
||||
source_code='API_LATEST_TEST_SOURCE', display_name='Latest Test Source', connector_type='dbs',
|
||||
rpa_profile=profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
query_parameters_json=[], match_aliases_json=[], enabled=False,
|
||||
query_parameters_json=[], enabled=False,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
|
||||
@@ -30,3 +30,29 @@ def test_shipping_handler_builds_ui_state_event(app):
|
||||
)
|
||||
event = handler.build_ui_state_event(ctx)
|
||||
assert event is None or event.get('event') == 'shipping_ui_state'
|
||||
|
||||
|
||||
def test_shipping_handler_recovers_only_persisted_extraction_terminal(monkeypatch):
|
||||
"""已持久化的部分完成订单应覆盖 SSE 断流,进行态仍须保留失败语义。"""
|
||||
load_handlers()
|
||||
handler = get_handler('shipping_notice')
|
||||
assert handler is not None
|
||||
ctx = ChatStreamContext(
|
||||
query='extract orders',
|
||||
display_query='extract orders',
|
||||
user=SimpleNamespace(id=1),
|
||||
agent=SimpleNamespace(agent_code='shipping_notice'),
|
||||
session=SimpleNamespace(session_id='conv-1'),
|
||||
external_conversation_id=None,
|
||||
request_id='req-1',
|
||||
)
|
||||
|
||||
monkeypatch.setattr(handler, 'build_order_extraction_state_event', lambda _ctx: {
|
||||
'status': 'partially_completed', 'terminal': True,
|
||||
})
|
||||
assert handler.should_recover_upstream_error(ctx, {'event': 'error'}) is True
|
||||
|
||||
monkeypatch.setattr(handler, 'build_order_extraction_state_event', lambda _ctx: {
|
||||
'status': 'extracting', 'terminal': False,
|
||||
})
|
||||
assert handler.should_recover_upstream_error(ctx, {'event': 'error'}) is False
|
||||
@@ -14,6 +14,7 @@ from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventoryValidationBatch,
|
||||
ShippingInventoryExternalMapping,
|
||||
ShippingExcelTemplate,
|
||||
ShippingExcelTemplate,
|
||||
@@ -45,20 +46,20 @@ def _workbook(path: Path) -> None:
|
||||
workbook.save(path)
|
||||
|
||||
|
||||
def _source() -> dict:
|
||||
def _source(code: str = 'TEST_EXPORT_SOURCE', profile_code: str = 'TEST_EXPORT_LOGIN') -> dict:
|
||||
"""创建一个保持停用的 DBS 库存站点。"""
|
||||
login = shipping_inventory_service.save_profile({
|
||||
'profile_code': 'TEST_EXPORT_LOGIN', 'display_name': 'Test Login', 'connector_type': 'dbs',
|
||||
'profile_code': profile_code, 'display_name': 'Test Login', 'connector_type': 'dbs',
|
||||
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
|
||||
'username': 'user', 'password': 'password', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
return shipping_inventory_service.save_source({
|
||||
'source_code': 'TEST_EXPORT_SOURCE', 'display_name': 'Test Export Source', 'connector_type': 'dbs',
|
||||
'source_code': code, 'display_name': 'Test Export Source', 'connector_type': 'dbs',
|
||||
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
|
||||
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
|
||||
'enabled': False,
|
||||
'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
'query_parameters_json': [], 'match_aliases_json': [],
|
||||
'query_parameters_json': [],
|
||||
}, actor_id=None)
|
||||
|
||||
|
||||
@@ -105,6 +106,23 @@ def _complete_test_run(source: dict, tmp_path: Path) -> dict:
|
||||
})
|
||||
|
||||
|
||||
def _published_template(*, code: str) -> ShippingExcelTemplate:
|
||||
"""创建引用库存料号字段的最小已发布发货模板,满足自动启用门禁。"""
|
||||
template = ShippingExcelTemplate(
|
||||
template_code=code, display_name=code, version=1, status='published',
|
||||
storage_bucket='test', storage_key=f'{code}.xlsx', original_filename=f'{code}.xlsx',
|
||||
file_checksum='0' * 64,
|
||||
definition_json={'filename_pattern': '{business_no}.xlsx', 'mappings': [{
|
||||
'sheet': 'Sheet', 'row_mode': 'line', 'start_row': 2, 'target_column': 1,
|
||||
'source_kind': 'inventory_field', 'source_key': _inventory_field_id('part_number'), 'formatter': 'text',
|
||||
}]},
|
||||
definition_checksum='1' * 64,
|
||||
)
|
||||
db.session.add(template)
|
||||
db.session.flush()
|
||||
return template
|
||||
|
||||
|
||||
def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path):
|
||||
"""测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
@@ -127,6 +145,296 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
|
||||
assert ShippingInventoryConfigurationTestRun.query.count() == 1
|
||||
|
||||
|
||||
def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
|
||||
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
field_id = _published_order_field()
|
||||
analysis_path = tmp_path / 'profile-evidence.xlsx'
|
||||
_workbook(analysis_path)
|
||||
seed_run = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seeded = inventory_configuration_test.report_test_export({
|
||||
'run_no': seed_run['run_no'], 'status': 'success', 'file_path': str(analysis_path),
|
||||
})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], field_id, code='EMPTY_RESULT_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile(
|
||||
[source['id']], profile['id'], actor_id=None, reason='空结果前已确认同类报表结构', operation='direct',
|
||||
)
|
||||
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result = inventory_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'empty', 'message': 'no inventory rows',
|
||||
})
|
||||
|
||||
# 关键断言:空结果保留数据质量待验证,而不是伪造失败或生成生产快照。
|
||||
assert result['status'] == 'completed_empty'
|
||||
assert result['stage'] == 'empty_data_pending_validation'
|
||||
assert result['result']['data_validation'] == 'pending_first_non_empty_export'
|
||||
assert not ShippingInventoryFile.query.count()
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
checks = {item['code']: item for item in current['activation']['checks']}
|
||||
# 关键断言:连接测试已通过;数量与匹配字段仅待首次非空文件验证,不能伪装成失败。
|
||||
assert checks['configuration_test']['status'] == 'empty'
|
||||
assert checks['configuration_test']['blocking'] is False
|
||||
assert checks['parsing_validation']['status'] == 'pending'
|
||||
assert checks['parsing_validation']['blocking'] is False
|
||||
assert checks['warehouse_mapping']['blocking'] is False
|
||||
# 关键断言:无库存不会被行级解析或调拨映射阻断;本例仍缺发货模板,因此尚不可启用。
|
||||
assert current['activation']['missing_requirements'] == ['excel_template']
|
||||
|
||||
|
||||
def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
||||
"""没有受控解析定义时,空结果不能被用作站点可用性的替代证据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result = inventory_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'empty',
|
||||
})
|
||||
|
||||
# 关键断言:没有已发布方案就无法验证空报表的格式,仍必须阻断。
|
||||
assert result['status'] == 'failed'
|
||||
assert '尚未绑定已发布库存解析方案' in result['error_message']
|
||||
|
||||
|
||||
def test_configuration_test_automatically_verifies_compatible_bound_profile(app, tmp_path):
|
||||
"""当前绑定方案的核心栏位仍在时,历史无关列缺失也必须直接成为验证证据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'bound-profile-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BOUND_PROFILE_VERIFY')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
|
||||
|
||||
verified = _complete_test_run(source, tmp_path)
|
||||
# 关键断言:当前绑定方案无需再出现在候选确认列表,测试直接写入启用所需的确认事实。
|
||||
assert verified['stage'] == 'current_profile_verified'
|
||||
assert verified['result']['current_profile_verified'] is True
|
||||
assert verified['result']['confirmed_profile_id'] == profile['id']
|
||||
|
||||
|
||||
def test_verified_current_profile_automatically_enables_ready_source(app, tmp_path):
|
||||
"""当前解析验证通过且必要条件齐全时,站点无需人工确认即可自动启用。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_PROFILE')
|
||||
template = _published_template(code='AUTO_ENABLE_TEMPLATE')
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_inventory_service.save_source({
|
||||
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': template.id,
|
||||
}, actor_id=None, source_id=source['id'])
|
||||
|
||||
verified = _complete_test_run(source, tmp_path)
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
# 关键断言:测试证据与完整门禁在同一事务提交,避免页面看到已验证但仍需手动启用。
|
||||
assert verified['stage'] == 'current_profile_verified'
|
||||
assert source_model.enabled is True
|
||||
|
||||
|
||||
def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path):
|
||||
"""解析测试通过不绕过发货模板门禁,条件不完整的站点必须保持停用。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_BLOCKED')
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_inventory_service.save_source({
|
||||
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': None,
|
||||
}, actor_id=None, source_id=source['id'])
|
||||
|
||||
_complete_test_run(source, tmp_path)
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
# 关键断言:自动启用始终复用正式门禁,缺少模板不会被测试成功放行。
|
||||
assert source_model.enabled is False
|
||||
assert shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
|
||||
|
||||
|
||||
def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path):
|
||||
"""固定仓查询成功但无库存时,也能在完整门禁下自动启用站点。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_EMPTY')
|
||||
template = _published_template(code='AUTO_ENABLE_EMPTY_TEMPLATE')
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_inventory_service.save_source({
|
||||
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': template.id,
|
||||
}, actor_id=None, source_id=source['id'])
|
||||
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
completed = inventory_configuration_test.report_test_export({'run_no': started['run_no'], 'status': 'empty'})
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
# 关键断言:无库存是成功查询事实,完整门禁下不再要求人工启用。
|
||||
assert completed['status'] == 'completed_empty'
|
||||
assert source_model.enabled is True
|
||||
|
||||
|
||||
def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path):
|
||||
"""同连接站点一次投递,混合成功、空库存及失败后仍独立汇总为部分失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
) as write_trigger:
|
||||
first = _source('BATCH_SOURCE_A', 'BATCH_LOGIN_A')
|
||||
second = _source('BATCH_SOURCE_B', 'BATCH_LOGIN_B')
|
||||
third = _source('BATCH_SOURCE_C', 'BATCH_LOGIN_C')
|
||||
second_model = db.session.get(ShippingInventorySource, second['id'])
|
||||
second_model.rpa_profile_id = first['rpa_profile_id']
|
||||
second_model.config_version += 1
|
||||
db.session.commit()
|
||||
# 用首站既有测试证据创建发布方案,再作为三站批量验证的受控解析定义。
|
||||
seed = inventory_configuration_test.start_test_export(first['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'batch-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BATCH_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile(
|
||||
[first['id'], second['id'], third['id']], profile['id'], actor_id=None, reason='批量验证测试', operation='bulk',
|
||||
)
|
||||
|
||||
write_trigger.reset_mock()
|
||||
batch = inventory_configuration_test.start_batch_test_export([first['id'], second['id'], third['id']], actor_id=None)
|
||||
# 关键断言:两个相同 Profile 的站点合并为一个 trigger,第三站独立触发。
|
||||
assert write_trigger.call_count == 2
|
||||
assert batch['total_count'] == 3
|
||||
runs = {run['inventory_source_id']: run for run in batch['runs']}
|
||||
result_file = tmp_path / 'batch-success.xlsx'; _workbook(result_file)
|
||||
reported = inventory_configuration_test.report_batch_test_exports({
|
||||
'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': runs[first['id']]['run_no'], 'status': 'success', 'file_path': str(result_file)},
|
||||
{'validation_run_no': runs[second['id']]['run_no'], 'status': 'skipped', 'skip_reason': 'no_inventory_data'},
|
||||
{'validation_run_no': runs[third['id']]['run_no'], 'status': 'failed', 'error_message': 'login failed'},
|
||||
],
|
||||
})
|
||||
# 关键断言:失败站点不影响其他站点,批次仅汇总为部分失败。
|
||||
assert reported['status'] == 'partial_failed'
|
||||
assert (reported['success_count'], reported['empty_count'], reported['failed_count']) == (1, 1, 1)
|
||||
assert ShippingInventoryValidationBatch.query.get(batch['id']).status == 'partial_failed'
|
||||
|
||||
|
||||
def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
"""批次重试只新建失败站点运行,成功和空库存结果不会被重复导出。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('RETRY_SOURCE', 'RETRY_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'retry-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RETRY_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='重试测试', operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
run = batch['runs'][0]
|
||||
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': run['run_no'], 'status': 'failed', 'error_message': 'temporary failure'},
|
||||
]})
|
||||
retried = inventory_configuration_test.retry_failed_validation_batch(batch['id'], actor_id=None)
|
||||
assert retried['retry_of_batch_id'] == batch['id']
|
||||
assert retried['total_count'] == 1
|
||||
|
||||
|
||||
def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app, tmp_path):
|
||||
"""配置变更后的旧批次回调必须失效,未知运行号不能污染同批次状态。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('STALE_BATCH_SOURCE', 'STALE_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'stale-batch-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='STALE_BATCH_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='过期回调测试', operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
run = batch['runs'][0]
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
source_model.config_version += 1
|
||||
db.session.commit()
|
||||
result_file = tmp_path / 'stale-batch-result.xlsx'; _workbook(result_file)
|
||||
reported = inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': 'UNKNOWN-RUN', 'status': 'success', 'file_path': str(result_file)},
|
||||
{'validation_run_no': run['run_no'], 'status': 'success', 'file_path': str(result_file)},
|
||||
]})
|
||||
# 关键断言:旧配置只标记自身 stale,未知运行号不会写入或影响批次统计。
|
||||
assert reported['ignored_count'] == 1
|
||||
assert reported['stale_count'] == 1
|
||||
assert reported['runs'][0]['result']['stale_configuration'] is True
|
||||
|
||||
|
||||
def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
||||
"""页面刷新只能恢复仍在执行的批次,已结束批次不会反复占用进度面板。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('RESTORE_BATCH_SOURCE', 'RESTORE_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'restore-batch-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RESTORE_BATCH_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
# 关键断言:刷新期间读取服务端 active batch,会返回待 Worker 处理的真实运行。
|
||||
assert inventory_configuration_test.get_latest_active_validation_batch()['id'] == batch['id']
|
||||
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': batch['runs'][0]['run_no'], 'status': 'empty'},
|
||||
]})
|
||||
# 关键断言:结束后不再恢复,避免管理端反复弹出旧批次。
|
||||
assert inventory_configuration_test.get_latest_active_validation_batch() is None
|
||||
|
||||
|
||||
def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path):
|
||||
"""Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('PROGRESS_BATCH_SOURCE', 'PROGRESS_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'progress-batch-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='PROGRESS_BATCH_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
run = batch['runs'][0]
|
||||
|
||||
progressed = inventory_configuration_test.report_batch_test_progress({
|
||||
'validation_batch_id': batch['id'], 'validation_run_no': run['run_no'], 'stage': 'rpa_exporting',
|
||||
})
|
||||
# 关键断言:页面可区分尚未领取与 Worker 已实际执行,批次仍等待最终结果。
|
||||
assert (progressed['status'], progressed['stage']) == ('processing', 'rpa_exporting')
|
||||
assert inventory_configuration_test.get_validation_batch(batch['id'])['status'] == 'running'
|
||||
|
||||
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': run['run_no'], 'status': 'empty'},
|
||||
]})
|
||||
unchanged = inventory_configuration_test.report_batch_test_progress({
|
||||
'validation_batch_id': batch['id'], 'validation_run_no': run['run_no'], 'stage': 'rpa_exporting',
|
||||
})
|
||||
# 关键断言:迟到的 progress 不得覆盖已经确认的空库存终态。
|
||||
assert (unchanged['status'], unchanged['stage']) == ('completed_empty', 'empty_data_pending_validation')
|
||||
|
||||
|
||||
def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_path):
|
||||
"""重开配置抽屉只能恢复当前版本测试;站点改动后可发起独立新测试而不复用旧运行。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
@@ -197,12 +505,9 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
assert source_model.parsing_profile_id == profile['id']
|
||||
assert 'configuration_test' not in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements']
|
||||
assert 'warehouse_mapping' in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements']
|
||||
# 关键断言:外部仓库映射只在调拨前校验,不应出现在站点启用阻断清单。
|
||||
assert shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
|
||||
|
||||
db.session.add(ShippingInventoryExternalMapping(
|
||||
inventory_source_id=source['id'], freight_warehouse_id='DUB', external_system_code='TOPGP',
|
||||
external_warehouse_code='DUB-01', external_warehouse_name='Dublin', enabled=True,
|
||||
))
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='TEST_ACTIVATION', display_name='Activation Template', version=1, status='published',
|
||||
storage_bucket='test', storage_key='activation.xlsx', original_filename='activation.xlsx',
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
tests/test_inventory_empty_snapshot.py
|
||||
|
||||
用途:验证 RPA 零库存结果仅形成审计快照,绝不作为可匹配库存复用。
|
||||
依赖:inventory_snapshot_store、ShippingInventoryFile、Flask 测试应用。
|
||||
逻辑:二期空结果由 Worker/回调写入 empty 快照;查询 ready 快照的运行链路必须忽略它。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
create_empty_rpa_inventory_snapshot,
|
||||
find_latest_ready_snapshot,
|
||||
)
|
||||
|
||||
|
||||
def test_empty_rpa_snapshot_is_auditable_but_never_available_for_matching(app):
|
||||
"""空快照应保留导出事实和幂等身份,但 ready 查询必须返回空。"""
|
||||
with app.app_context():
|
||||
source = {'source_code': 'EMPTY_DUB', 'warehouse_id': 'DUB', 'connector_type': 'dbs'}
|
||||
first = create_empty_rpa_inventory_snapshot(
|
||||
source=source, rpa_run_no='EMPTY-RUN-1', schedule_run_id=None,
|
||||
trigger_type='scheduled', message='no inventory data',
|
||||
)
|
||||
repeated = create_empty_rpa_inventory_snapshot(
|
||||
source=source, rpa_run_no='EMPTY-RUN-1', schedule_run_id=None,
|
||||
trigger_type='scheduled', message='no inventory data',
|
||||
)
|
||||
|
||||
# 关键断言:重放同一空结果不重复写审计;空快照不能污染匹配可用库存池。
|
||||
assert repeated.id == first.id
|
||||
assert first.snapshot_status == 'empty'
|
||||
assert first.line_count == 0
|
||||
assert find_latest_ready_snapshot('EMPTY_DUB', 'DUB') is None
|
||||
@@ -91,7 +91,7 @@ def _source(profile_id: int, parsing_id: int, code: str) -> dict:
|
||||
'excel_template_id': _excel_template_id(),
|
||||
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': code,
|
||||
'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
'query_parameters_json': [], 'match_aliases_json': [], 'snapshot_ttl_seconds': 3600, 'enabled': True,
|
||||
'query_parameters_json': [], 'snapshot_ttl_seconds': 3600, 'enabled': True,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ def _source_with_profile(path: Path) -> ShippingInventorySource:
|
||||
source_code='DRIFT_SOURCE', display_name='Drift Source', connector_type='dbs', rpa_profile=rpa,
|
||||
parsing_profile=profile, excel_template=template, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
query_parameters_json=[], match_aliases_json=[], enabled=True,
|
||||
query_parameters_json=[], enabled=True,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
|
||||
@@ -14,8 +14,10 @@ from app.models import (
|
||||
FileAsset,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
@@ -27,12 +29,39 @@ from app.services.shipping_notice.customer_auto_resolution import (
|
||||
AUTO_RESOLUTION_VERSION,
|
||||
correct_numbered_task_customer,
|
||||
get_auto_resolution_metrics,
|
||||
resolve_auto_customer_from_shadow,
|
||||
try_auto_confirm_task_customer,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
|
||||
def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]:
|
||||
"""创建管理员配置的邮箱定义及冻结发布规则集快照。"""
|
||||
definition = ShippingIdentityDefinition.query.filter_by(definition_code='test_mail_sender_email').one_or_none()
|
||||
if definition is None:
|
||||
definition = ShippingIdentityDefinition(
|
||||
definition_code='test_mail_sender_email', target_type='customer', source_adapter_key='email_metadata',
|
||||
source_selector_json={'attribute': 'email.from', 'projection': 'email'},
|
||||
attribute_key='email', normalizer_key='email', comparator_key='normalized_exact',
|
||||
default_weight=100, max_automation='conditional', status='active',
|
||||
)
|
||||
db.session.add(definition)
|
||||
db.session.flush()
|
||||
rule_set = ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
if rule_set is None:
|
||||
rule_set = ShippingIdentityRuleSet(
|
||||
version=1, status='published', checksum='a' * 64,
|
||||
definition_json={'definitions': [{
|
||||
'id': definition.id, 'definition_code': definition.definition_code,
|
||||
'target_type': 'customer', 'attribute_key': 'email', 'max_automation': 'conditional',
|
||||
}]},
|
||||
)
|
||||
db.session.add(rule_set)
|
||||
db.session.flush()
|
||||
return definition, rule_set
|
||||
|
||||
|
||||
def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
"""创建带邮件证据的 Candidate、影子记录和待确认任务。"""
|
||||
user = User(username=f"auto-user-{db.session.query(User).count()}", email="auto@example.com", role="user")
|
||||
@@ -72,14 +101,24 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
definition, rule_set = _auto_definition()
|
||||
shadow = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=intake.id, resolution_version="shadow-v1",
|
||||
identity_rule_set_id=rule_set.id, identity_rule_set_version=rule_set.version,
|
||||
identity_rule_set_checksum=rule_set.checksum,
|
||||
status="unique_candidate",
|
||||
evidence_json=[
|
||||
{"type": "email", "raw_value": sender, "normalized_value": sender},
|
||||
{"type": "domain", "raw_value": sender.split("@")[-1], "normalized_value": sender.split("@")[-1]},
|
||||
{"definition_id": definition.id, "definition_code": definition.definition_code,
|
||||
"raw_value": sender, "normalized_value": sender, "source": {"kind": "mail_metadata"}},
|
||||
],
|
||||
candidate_matches_json=[],
|
||||
candidate_matches_json=[], resolution_context_json={'rule_set': {
|
||||
'id': rule_set.id, 'version': rule_set.version, 'checksum': rule_set.checksum,
|
||||
'definitions': [{
|
||||
'id': definition.id, 'definition_code': definition.definition_code,
|
||||
'target_type': 'customer', 'attribute_key': 'email', 'max_automation': 'conditional',
|
||||
'source_adapter_key': 'email_metadata',
|
||||
}],
|
||||
}},
|
||||
)
|
||||
db.session.add(shadow)
|
||||
db.session.commit()
|
||||
@@ -87,13 +126,14 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
|
||||
|
||||
def _customer_with_identifier(*, code: str, value: str, allowed: bool = True, status: str = "approved"):
|
||||
"""创建客户及邮箱强证据。"""
|
||||
"""创建客户及冻结邮箱定义对应的可审核证据。"""
|
||||
customer = ShippingCustomer(standard_name=f"客户 {code}", short_code=code, status="active")
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer.id, identifier_type="email", raw_value=value, normalized_value=value,
|
||||
status=status, source="manual", auto_match_allowed=allowed,
|
||||
definition, _ = _auto_definition()
|
||||
db.session.add(ShippingIdentityEvidence(
|
||||
definition_id=definition.id, customer_id=customer.id, raw_value=value, normalized_value=value,
|
||||
status=status, auto_match_allowed=allowed,
|
||||
))
|
||||
db.session.flush()
|
||||
return customer
|
||||
@@ -122,6 +162,10 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
assert task.shipping_case.customer_id == customer.id
|
||||
assert task.shipping_case.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']
|
||||
assert event.detail_json['evidence'][0]['definition_id']
|
||||
assert event.detail_json['evidence'][0]['evidence_id']
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert metrics["auto_confirmed_count"] == 1
|
||||
assert metrics["recent_events"][0]["event_type"] == "customer_auto_confirmed"
|
||||
@@ -199,6 +243,56 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic
|
||||
assert task.shipping_case.business_no is None
|
||||
|
||||
|
||||
def test_business_evidence_never_auto_confirms(app):
|
||||
"""订单业务字段即使被人为授权,也受定义上限约束而不能自动绑定客户。"""
|
||||
with app.app_context():
|
||||
_allow_auto_confirmation(app)
|
||||
customer = ShippingCustomer(standard_name='业务字段客户', short_code='BIZ', status='active')
|
||||
definition = ShippingIdentityDefinition(
|
||||
definition_code='test_business_contact', target_type='customer', source_adapter_key='order_field',
|
||||
source_selector_json={'order_field_id': 'test-field'},
|
||||
attribute_key='customer_code', normalizer_key='text_upper', comparator_key='normalized_exact',
|
||||
default_weight=100, max_automation='none', status='active',
|
||||
)
|
||||
db.session.add_all([customer, definition])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingIdentityEvidence(
|
||||
definition_id=definition.id, customer_id=customer.id, raw_value='ACME', normalized_value='ACME',
|
||||
status='approved', auto_match_allowed=True,
|
||||
))
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow.evidence_json = [{'definition_id': definition.id, 'normalized_value': 'ACME'}]
|
||||
shadow.resolution_context_json = {'rule_set': {
|
||||
'id': shadow.identity_rule_set_id, 'version': shadow.identity_rule_set_version,
|
||||
'checksum': shadow.identity_rule_set_checksum,
|
||||
'definitions': [{'id': definition.id, 'target_type': 'customer', 'attribute_key': 'customer_code',
|
||||
'max_automation': 'none', 'source_adapter_key': 'order_field'}],
|
||||
}}
|
||||
db.session.commit()
|
||||
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
|
||||
assert result['status'] == 'unmatched'
|
||||
assert task.customer_resolution_status == 'pending'
|
||||
|
||||
|
||||
def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
|
||||
"""公共域名和无法验证的冻结规则快照均不可触发自动绑定。"""
|
||||
with app.app_context():
|
||||
_allow_auto_confirmation(app)
|
||||
_customer_with_identifier(code='PUB', value='buyer@gmail.com')
|
||||
task = _seed_candidate_task(sender='buyer@gmail.com')
|
||||
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
|
||||
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow.resolution_context_json = {}
|
||||
db.session.commit()
|
||||
missing = resolve_auto_customer_from_shadow(task)
|
||||
assert missing['status'] == 'rule_snapshot_missing'
|
||||
assert missing['customer_id'] is None
|
||||
|
||||
|
||||
def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app):
|
||||
"""有足够样本但强规则与人工真值不一致时,自动确认必须安全降级。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1,38 +1,43 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_shadow_resolution.py
|
||||
|
||||
用途:验证客户影子识别的确定性候选、幂等、质量标签和零副作用边界。
|
||||
依赖:内存数据库、客户主数据、Candidate/Intake、customer_shadow_resolution。
|
||||
逻辑:构造真实 ORM 样本后刷新影子结果,断言业务单客户与业务编号始终不被写入。
|
||||
用途:验证规则集驱动的客户影子识别、订单字段裁决门禁和客户/站点隔离。
|
||||
依赖:身份规则服务、受控订单 FieldValue、Candidate/Intake 与客户主数据。
|
||||
逻辑:仅已发布定义和 accepted/corroborated Header 值可进入候选;影子结果只记录审计,绝不绑定业务单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingCustomerShadowMatch,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingCustomerSite,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.document_candidate_persist import persist_documents_and_candidates
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
from app.services.shipping_notice.customer_shadow_resolution import (
|
||||
get_shadow_quality_report,
|
||||
label_shadow_resolution,
|
||||
refresh_candidate_shadow_resolution,
|
||||
)
|
||||
from app.services.shipping_notice.identity_rules import service as identity_rules
|
||||
|
||||
|
||||
def _seed_candidate(*, customer_name: str, sender: str = '') -> ShippingNoticeCandidate:
|
||||
"""创建影子识别所需的最小 Intake、Document 与 Candidate。"""
|
||||
user = User(username=f'user-{customer_name}-{sender}', email=f'{db.session.query(User).count()}@example.com', role='user')
|
||||
def _seed_candidate(*, sender: str = '', document_text: str = 'Order template for supplied goods'):
|
||||
"""创建带邮件元数据、主文档和 Candidate 的最小影子识别上下文。"""
|
||||
user = User(username=f'shadow-{db.session.query(User).count()}', email=f'{db.session.query(User).count()}@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
@@ -50,18 +55,76 @@ def _seed_candidate(*, customer_name: str, sender: str = '') -> ShippingNoticeCa
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
|
||||
filename='notice.pdf', classification='order_notice', parse_status='parsed',
|
||||
filename='notice.pdf', classification='order_notice', parse_status='parsed', extracted_text=document_text,
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no=f'SNC-{user.id}', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='document:1', validation_status='ready',
|
||||
structured_result_json={'business_summary': {'customer_name': customer_name, 'lines': [{'sku': 'A', 'quantity': 1}]}},
|
||||
structured_result_json={'business_summary': {'customer_name': 'RAW LLM VALUE MUST NOT BE USED'}},
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
return candidate
|
||||
return intake, candidate
|
||||
|
||||
|
||||
def _published_header_field(*, field_code: str, value_type: str = 'string'):
|
||||
"""建立当前已发布 Header 字段,作为业务识别定义唯一合法来源。"""
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
field = ShippingOrderField(schema_id=schema.id, field_code=field_code, scope='header', value_type=value_type)
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
current = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='published').one_or_none()
|
||||
if current is not None:
|
||||
current.status = 'retired'
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=(db.session.query(ShippingOrderSchemaVersion).filter_by(schema_id=schema.id).count() + 1),
|
||||
status='published', lock_version=1,
|
||||
definition_json={'fields': [{
|
||||
'field_id': field.id, 'field_code': field.field_code, 'scope': 'header',
|
||||
'value_type': value_type, 'enabled': True,
|
||||
}]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
return field, version
|
||||
|
||||
|
||||
def _publish_rule_set(*, definition_ids: list[str] | None = None):
|
||||
"""发布测试规则集;运行时只读取该不可变快照而非当前定义表。"""
|
||||
draft = identity_rules.create_rule_set({}, actor_id=1)
|
||||
ids = definition_ids or [item['id'] for item in identity_rules.list_definitions(active_only=True)['definitions']]
|
||||
saved = identity_rules.save_rule_set(draft['id'], {
|
||||
'expected_lock_version': draft['lock_version'], 'definition_ids': ids,
|
||||
}, actor_id=1)
|
||||
return identity_rules.publish_rule_set(draft['id'], expected_lock_version=saved['lock_version'], actor_id=1)
|
||||
|
||||
|
||||
def _attach_header_value(candidate, version, field, value: str, status: str = 'accepted'):
|
||||
"""写入受控订单抽取、裁决和 Header FieldValue,模拟运行期唯一允许的业务证据来源。"""
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=candidate.intake_id, schema_version_id=version.id, input_snapshot_hash='a' * 64,
|
||||
status='accepted', raw_llm_output_json={'header_fields': [{'value': 'ATTACKER CONTROLLED'}]},
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, field_id=field.id, decision_status=status, resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, field_id=field.id, decision_id=decision.id, value_text=value,
|
||||
))
|
||||
candidate.order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
return extraction
|
||||
|
||||
|
||||
def _create_customer(name: str, code: str) -> ShippingCustomer:
|
||||
@@ -72,109 +135,169 @@ def _create_customer(name: str, code: str) -> ShippingCustomer:
|
||||
return customer
|
||||
|
||||
|
||||
def test_shadow_resolution_uses_strong_evidence_without_binding_case(app):
|
||||
"""完整邮箱可形成唯一候选,但业务单客户和业务编号保持为空。"""
|
||||
def _email_definition(code: str = 'sender_email') -> dict:
|
||||
"""创建管理员配置的 EML 发件人邮箱定义。"""
|
||||
return identity_rules.save_definition({
|
||||
'definition_code': code, 'target_type': 'customer', 'attribute_key': 'email',
|
||||
'normalizer_key': 'email', 'comparator_key': 'normalized_exact', 'default_weight': 100,
|
||||
'max_automation': 'conditional', 'source_adapter_key': 'email_metadata',
|
||||
'source_selector': {'attribute': 'email.from', 'projection': 'email'},
|
||||
}, actor_id=1)
|
||||
|
||||
|
||||
def _template_definition(code: str = 'notice_template') -> dict:
|
||||
"""创建管理员配置的主文档模板指纹定义。"""
|
||||
return identity_rules.save_definition({
|
||||
'definition_code': code, 'target_type': 'customer', 'attribute_key': 'template_fingerprint',
|
||||
'normalizer_key': 'text_upper', 'comparator_key': 'normalized_exact', 'default_weight': 90,
|
||||
'max_automation': 'conditional', 'source_adapter_key': 'document_template',
|
||||
'source_selector': {'document': 'primary'},
|
||||
}, actor_id=1)
|
||||
|
||||
|
||||
def test_shadow_resolution_uses_published_email_definition_without_binding_case(app):
|
||||
"""管理员配置的邮箱定义按规则集命中唯一客户,业务单客户和业务编号仍保持为空。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer('无锡宇辰有限公司', 'WYC')
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer.id, identifier_type='email', raw_value='buyer@wyc.example.com',
|
||||
normalized_value='buyer@wyc.example.com', status='approved', source='manual', auto_match_allowed=True,
|
||||
))
|
||||
candidate = _seed_candidate(customer_name='不稳定解析名称', sender='Buyer <buyer@wyc.example.com>')
|
||||
definition = _email_definition()
|
||||
rule_set = _publish_rule_set(definition_ids=[definition['id']])
|
||||
identity_rules.create_evidence(
|
||||
target_type='customer', target_id=customer.id,
|
||||
data={'definition_id': definition['id'], 'raw_value': 'buyer@wyc.example.com', 'status': 'approved'}, actor_id=1,
|
||||
)
|
||||
_intake, candidate = _seed_candidate(sender='Buyer <buyer@wyc.example.com>')
|
||||
case = ShippingCase(case_no='CASE-SHADOW-1')
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
|
||||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||||
db.session.commit()
|
||||
|
||||
assert resolution.status == 'unique_candidate'
|
||||
assert resolution.top_customer_id == customer.id
|
||||
assert resolution.identity_rule_set_id == rule_set['id']
|
||||
assert resolution.identity_rule_set_checksum == rule_set['checksum']
|
||||
assert resolution.top_score == 100.0
|
||||
assert any(item['definition_code'] == definition['definition_code'] for item in resolution.evidence_json)
|
||||
assert resolution.evidence_json[0]['source_adapter_key'] == 'email_metadata'
|
||||
assert db.session.query(ShippingCustomerShadowMatch).filter_by(customer_id=customer.id).count() == 1
|
||||
assert case.customer_id is None
|
||||
assert case.business_no is None
|
||||
assert get_shadow_quality_report()['auto_bound_count'] == 0
|
||||
|
||||
|
||||
def test_shadow_resolution_reports_ambiguous_and_unmatched(app):
|
||||
"""同名客户必须保留歧义,无证据样本必须标记未匹配。"""
|
||||
@pytest.mark.parametrize('decision_status', ['needs_review', 'blocked', 'missing'])
|
||||
def test_unaccepted_header_values_never_become_identity_evidence(app, decision_status):
|
||||
"""关键断言:needs_review、blocked、missing 的 Header 值和原始 LLM JSON 都不能参与识别。"""
|
||||
with app.app_context():
|
||||
_create_customer('ACME', 'ACA')
|
||||
_create_customer('ACME', 'ACB')
|
||||
ambiguous = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='ACME'))
|
||||
unmatched = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='UNKNOWN'))
|
||||
db.session.commit()
|
||||
field, version = _published_header_field(field_code=f'bill_to_{decision_status}')
|
||||
definition = identity_rules.save_definition({
|
||||
'definition_code': f'bill_to_{decision_status}', 'target_type': 'customer', 'attribute_key': 'customer_name',
|
||||
'order_field_id': field.id, 'normalizer_key': 'name', 'comparator_key': 'normalized_exact',
|
||||
'default_weight': 60, 'max_automation': 'none',
|
||||
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
|
||||
}, actor_id=1)
|
||||
customer = _create_customer('受控客户', 'CTL')
|
||||
_publish_rule_set(definition_ids=[definition['id']])
|
||||
_intake, candidate = _seed_candidate()
|
||||
_attach_header_value(candidate, version, field, '受控客户', decision_status)
|
||||
|
||||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
assert resolution.status == 'unmatched'
|
||||
assert resolution.evidence_json == []
|
||||
assert resolution.candidate_matches_json == []
|
||||
|
||||
|
||||
def test_address_field_resolves_site_only_and_freezes_rule_schema_field_snapshots(app):
|
||||
"""地址业务字段只产出站点候选,并冻结规则集、Schema、字段 ID 和命中证据的解释链。"""
|
||||
with app.app_context():
|
||||
field, version = _published_header_field(field_code='ship_to_address')
|
||||
definition = identity_rules.save_definition({
|
||||
'definition_code': 'ship_to_address', 'target_type': 'site', 'attribute_key': 'ship_to_address',
|
||||
'order_field_id': field.id, 'normalizer_key': 'text_upper', 'comparator_key': 'normalized_exact',
|
||||
'default_weight': 50, 'max_automation': 'none',
|
||||
'source_adapter_key': 'order_field', 'source_selector': {'order_field_id': field.id},
|
||||
}, actor_id=1)
|
||||
rule_set = _publish_rule_set(definition_ids=[definition['id']])
|
||||
customer = _create_customer('账款客户', 'BIL')
|
||||
site = ShippingCustomerSite(customer_id=customer.id, site_name='上海仓', site_code='SHA', address='上海市浦东新区', status='active')
|
||||
db.session.add(site)
|
||||
db.session.flush()
|
||||
identity_rules.create_evidence(
|
||||
target_type='site', target_id=site.id,
|
||||
data={'definition_id': definition['id'], 'raw_value': '上海市浦东新区', 'status': 'approved'}, actor_id=1,
|
||||
)
|
||||
_intake, candidate = _seed_candidate()
|
||||
extraction = _attach_header_value(candidate, version, field, '上海市浦东新区', 'corroborated')
|
||||
|
||||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
assert resolution.status == 'unmatched'
|
||||
assert resolution.top_customer_id is None
|
||||
assert resolution.order_schema_version_id == version.id
|
||||
assert resolution.identity_rule_set_version == rule_set['version']
|
||||
assert resolution.resolution_context_json['order_extraction_id'] == extraction.id
|
||||
assert resolution.resolution_context_json['site_matches'][0]['site_id'] == site.id
|
||||
reason = resolution.resolution_context_json['site_matches'][0]['reasons'][0]
|
||||
assert reason['source']['order_field_id'] == field.id
|
||||
assert reason['evidence_id'] is not None
|
||||
assert resolution.resolution_context_json['rule_set']['definitions'][0]['order_field_id'] == field.id
|
||||
|
||||
|
||||
def test_equal_scores_remain_ambiguous_and_template_fingerprint_is_supported(app):
|
||||
"""同分邮箱命中保留歧义;后端模板指纹也能经已审核证据产生可解释候选。"""
|
||||
with app.app_context():
|
||||
first = _create_customer('客户甲', 'AAA')
|
||||
second = _create_customer('客户乙', 'BBB')
|
||||
email_definition = _email_definition('shared_sender_email')
|
||||
template_definition = _template_definition()
|
||||
_publish_rule_set(definition_ids=[email_definition['id']])
|
||||
for customer in (first, second):
|
||||
identity_rules.create_evidence(
|
||||
target_type='customer', target_id=customer.id,
|
||||
data={'definition_id': email_definition['id'], 'raw_value': 'shared@example.com', 'status': 'approved'}, actor_id=1,
|
||||
)
|
||||
_intake, candidate = _seed_candidate(sender='shared@example.com')
|
||||
ambiguous = refresh_candidate_shadow_resolution(candidate)
|
||||
assert ambiguous.status == 'ambiguous'
|
||||
assert ambiguous.top_customer_id is None
|
||||
assert len(ambiguous.candidate_matches_json) == 2
|
||||
assert len(ambiguous.matches) == 2
|
||||
assert unmatched.status == 'unmatched'
|
||||
assert unmatched.candidate_matches_json == []
|
||||
|
||||
fingerprint_customer = _create_customer('模板客户', 'TMP')
|
||||
_publish_rule_set(definition_ids=[template_definition['id']])
|
||||
_intake, fingerprint_candidate = _seed_candidate(document_text='SHIPMENT NOTICE\nCustomer: example\nPO: 10001')
|
||||
first_pass = refresh_candidate_shadow_resolution(fingerprint_candidate)
|
||||
fingerprint = first_pass.evidence_json[0]['raw_value']
|
||||
identity_rules.create_evidence(
|
||||
target_type='customer', target_id=fingerprint_customer.id,
|
||||
data={'definition_id': template_definition['id'], 'raw_value': fingerprint, 'status': 'approved'}, actor_id=1,
|
||||
)
|
||||
matched = refresh_candidate_shadow_resolution(fingerprint_candidate)
|
||||
assert matched.status == 'unique_candidate'
|
||||
assert matched.top_customer_id == fingerprint_customer.id
|
||||
assert matched.evidence_json[0]['source']['kind'] == 'document_template_fingerprint'
|
||||
|
||||
|
||||
def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
|
||||
"""重算复用同一记录;准确率只统计人工标签且不会反向绑定业务。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer('ACME', 'ACM')
|
||||
candidate = _seed_candidate(customer_name='ACME')
|
||||
definition = _email_definition('accuracy_sender_email')
|
||||
_publish_rule_set(definition_ids=[definition['id']])
|
||||
identity_rules.create_evidence(
|
||||
target_type='customer', target_id=customer.id,
|
||||
data={'definition_id': definition['id'], 'raw_value': 'buyer@acme.example', 'status': 'approved'}, actor_id=1,
|
||||
)
|
||||
_intake, candidate = _seed_candidate(sender='buyer@acme.example')
|
||||
first = refresh_candidate_shadow_resolution(candidate)
|
||||
first_id = first.id
|
||||
second = refresh_candidate_shadow_resolution(candidate)
|
||||
db.session.commit()
|
||||
assert second.id == first_id
|
||||
assert second.id == first.id
|
||||
assert db.session.query(ShippingCustomerShadowResolution).count() == 1
|
||||
|
||||
labeled = label_shadow_resolution(first_id, customer_id=customer.id, actor_id=None)
|
||||
labeled = label_shadow_resolution(first.id, customer_id=customer.id, actor_id=None)
|
||||
report = get_shadow_quality_report()
|
||||
assert labeled['is_correct'] is True
|
||||
assert report['labeled_count'] == 1
|
||||
assert report['correct_count'] == 1
|
||||
assert report['accuracy'] == 1.0
|
||||
assert report['auto_bound_count'] == 0
|
||||
|
||||
|
||||
def test_shadow_failure_does_not_block_candidate_persistence(app, monkeypatch):
|
||||
"""影子规则异常时 Candidate 主流程仍须创建并可提交。"""
|
||||
with app.app_context():
|
||||
user = User(username='shadow-safe-user', email='shadow-safe@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-SHADOW-SAFE', owner_user_id=user.id, original_filename='notice.txt',
|
||||
storage_provider='minio', storage_bucket='test', storage_key='shadow-safe',
|
||||
content_hash='a' * 64, file_size=10, upload_status='uploaded', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-SHADOW-SAFE', asset_id=asset.id, user_id=user.id,
|
||||
parser_version='v6', parse_status='parsed', structured_result_json={},
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.customer_shadow_resolution.refresh_candidate_shadow_resolution',
|
||||
lambda _candidate: (_ for _ in ()).throw(RuntimeError('shadow failure')),
|
||||
)
|
||||
result = NoticeIntakeResult(
|
||||
filename='notice.txt', source_type='manual', source_file_type='text/plain',
|
||||
text='Customer: ACME\nPO: PO-1\nSKU: A001 Qty: 1', content_hash='a' * 64,
|
||||
file_size=10, status='accepted',
|
||||
)
|
||||
|
||||
persisted = persist_documents_and_candidates(
|
||||
intake=intake,
|
||||
parent_asset=asset,
|
||||
result=result,
|
||||
run_duplicate_detection=False,
|
||||
create_candidates=True,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert persisted['candidate_count'] == 1
|
||||
candidate = db.session.query(ShippingNoticeCandidate).one()
|
||||
assert candidate.validation_status == 'ready'
|
||||
shadow = db.session.query(ShippingCustomerShadowResolution).one()
|
||||
assert shadow.status == 'failed'
|
||||
@@ -23,7 +23,7 @@ from app.models import (
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
|
||||
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
|
||||
|
||||
def _inventory_field_id(field_code: str) -> str:
|
||||
@@ -132,7 +132,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
source = ShippingInventorySource(
|
||||
source_code='DUB', display_name='Dublin', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[],
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
||||
db.session.add_all([source, extraction])
|
||||
@@ -242,7 +242,7 @@ def test_two_sources_can_share_one_published_excel_template(app, tmp_path):
|
||||
source_code=code, display_name=code, connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'],
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id=code,
|
||||
report_path_json={}, query_parameters_json=[], match_aliases_json=[],
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -272,7 +272,7 @@ def test_disabled_source_still_blocks_template_retirement(app):
|
||||
source_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs', enabled=False,
|
||||
rpa_profile_id=login.id, excel_template_id=published['id'],
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
||||
report_path_json={}, query_parameters_json=[], match_aliases_json=[],
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -313,7 +313,7 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
|
||||
db.session.add(ShippingInventorySource(
|
||||
source_code='KEYED', display_name='Keyed', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[],
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
||||
db.session.add(extraction); db.session.flush()
|
||||
@@ -377,6 +377,35 @@ def test_existing_template_can_create_new_draft_version_without_reupload(app):
|
||||
assert set(layout['sheets']) == {'Header', 'Detail'}
|
||||
|
||||
|
||||
def test_existing_template_can_clone_as_independent_v1_without_reupload(app):
|
||||
"""复制为新模板必须复用文件和定义,但采用新编码且不加入原模板版本链。"""
|
||||
with app.app_context():
|
||||
draft = excel_template.create_draft(_workbook_upload(), {
|
||||
'template_code': 'SOURCE_TEMPLATE', 'display_name': 'Source Template',
|
||||
'definition': {'filename_pattern': '{business_no}.xlsx', 'mappings': [{
|
||||
'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
|
||||
'source_kind': 'constant', 'source_key': 'copy', 'formatter': 'text',
|
||||
}]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
copied = excel_template.clone_as_new_template(published['id'], {
|
||||
'template_code': 'COPIED_TEMPLATE', 'display_name': 'Copied Template',
|
||||
}, actor_id=None)
|
||||
|
||||
assert copied['template_code'] == 'COPIED_TEMPLATE'
|
||||
assert copied['display_name'] == 'Copied Template'
|
||||
assert copied['version'] == 1
|
||||
assert copied['status'] == 'draft'
|
||||
assert copied['definition'] == draft['definition']
|
||||
assert copied['file_checksum'] == draft['file_checksum']
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
excel_template.clone_as_new_template(published['id'], {
|
||||
'template_code': 'COPIED_TEMPLATE', 'display_name': 'Another Copy',
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_CODE_EXISTS'
|
||||
|
||||
|
||||
def test_template_publish_rejects_order_field_removed_from_current_schema(app):
|
||||
"""模板草稿不得在订单字段移出当前 published Schema 后继续发布。"""
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
@@ -449,7 +478,7 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app,
|
||||
db.session.add(ShippingInventorySource(
|
||||
source_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[],
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
||||
db.session.add(extraction); db.session.flush()
|
||||
|
||||
@@ -144,7 +144,6 @@ def test_database_source_snapshot_uses_source_business_report_configuration(app)
|
||||
source.query_parameters_json = [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
|
||||
]
|
||||
source.match_aliases_json = ['DUB', 'Dublin']
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
|
||||
@@ -152,7 +151,6 @@ def test_database_source_snapshot_uses_source_business_report_configuration(app)
|
||||
assert payload is not None
|
||||
assert payload['navigation']['report_name'] == 'Source Report'
|
||||
assert payload['parameters'][0]['name'] == 'Warehouse'
|
||||
assert payload['match_aliases_json'] == ['DUB', 'Dublin']
|
||||
assert 'operation_config' not in payload
|
||||
assert payload['login_config'] == {'auth_mode': 'password'}
|
||||
|
||||
|
||||
@@ -1,136 +1,177 @@
|
||||
"""
|
||||
tests/test_shipping_inventory_routing_engine.py
|
||||
|
||||
用途:验证通用库存源路由规则的候选、优先级和冲突裁决。
|
||||
依赖:库存路由模型、inventory_routing_engine、Flask 测试数据库。
|
||||
逻辑:锁定 Reservation ID 兜底规则只是受控事实字段之一,规则引擎不会执行 RPA 或猜测 Warehouse。
|
||||
用途:验证库存源路由只消费已发布订单 Schema 的已裁决字段值。
|
||||
依赖:订单 Schema service、库存路由模型、inventory_routing_engine。
|
||||
逻辑:测试以稳定 field_id 创建 FieldValue,确认库存源线索优先于预定单号兜底且不会读取固定任务行字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _rule(*, code: str, priority: int, action: str, sources: list[str], value: object, operator: str = 'prefix'):
|
||||
"""构造一个已发布的行级 Reservation ID 路由规则。"""
|
||||
return ShippingInventoryRoutingRule(
|
||||
rule_code=code,
|
||||
rule_name=code,
|
||||
scope='line',
|
||||
priority=priority,
|
||||
match_mode='all',
|
||||
status='published',
|
||||
action_type=action,
|
||||
action_payload_json={'source_codes': sources},
|
||||
version=1,
|
||||
conditions=[
|
||||
ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=1,
|
||||
source_kind='system_fact',
|
||||
system_fact_key='line.reservation_id',
|
||||
operator=operator,
|
||||
expected_value_json=value,
|
||||
sequence=1,
|
||||
)
|
||||
],
|
||||
def _field_config(field_id: str, *, name: str) -> dict:
|
||||
"""构造最小可发布行字段配置;路由只依赖其稳定 field_id。"""
|
||||
return {
|
||||
'field_id': field_id, 'display_name': name, 'required': False, 'aliases': [],
|
||||
'normalizer_key': 'uppercase_trim', 'validator_keys': [], 'enum_options': [],
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_table'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None, 'comparator_key': 'normalized_text',
|
||||
}
|
||||
|
||||
|
||||
def _published_line_fields() -> dict[str, str]:
|
||||
"""创建当前测试所需的预定单号和库存源线索字段,并发布其稳定契约。"""
|
||||
order_schema_service.initialize_schema({'display_name': '路由字段'}, actor_id=None)
|
||||
reservation = order_schema_service.save_field(
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
|
||||
|
||||
def _task() -> SimpleNamespace:
|
||||
"""提供最小任务事实,确保路由测试只依赖显式输入。"""
|
||||
return SimpleNamespace(
|
||||
customer_code=None, destination_country=None, destination_city=None,
|
||||
destination_port=None, warehouse_hint=None, order_type=None, sender_email=None,
|
||||
current_order_extraction_id=None,
|
||||
source_hint = order_schema_service.save_field(
|
||||
{'field_code': 'inventory_source_hint', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
reservation_config = _field_config(reservation['id'], name='预定单号')
|
||||
reservation_config['business_purpose'] = 'reservation_id'
|
||||
source_hint_config = _field_config(source_hint['id'], name='库存源线索')
|
||||
source_hint_config['business_purpose'] = 'inventory_source_hint'
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [reservation_config, source_hint_config], 'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
return {'reservation_id': reservation['id'], 'inventory_source_hint': source_hint['id']}
|
||||
|
||||
|
||||
def test_prefix_rule_returns_ambiguous_source_candidates(app):
|
||||
"""前缀 1 规则只产生 DUB/RTM 候选,不在路由阶段擅自选择 Source。"""
|
||||
with app.app_context():
|
||||
db.session.add(_rule(code='RSV_PREFIX_1', priority=100, action='add_source_candidates', sources=['DBS_DUB', 'DBS_RTM'], value='1'))
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '1000123456'})
|
||||
assert result.status == 'ambiguous'
|
||||
assert result.source_codes == ('DBS_DUB', 'DBS_RTM')
|
||||
|
||||
|
||||
def test_higher_priority_document_rule_wins_over_reservation_fallback(app):
|
||||
"""高优先级规则覆盖兜底规则,体现明确业务事实优先于通用前缀。"""
|
||||
with app.app_context():
|
||||
db.session.add_all([
|
||||
_rule(code='RSV_PREFIX_1', priority=100, action='add_source_candidates', sources=['DBS_DUB', 'DBS_RTM'], value='1'),
|
||||
_rule(code='RSV_FIXED_DUB', priority=200, action='add_source_candidates', sources=['DBS_DUB'], value='1000123456', operator='equals'),
|
||||
])
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '1000123456'})
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('DBS_DUB',)
|
||||
|
||||
|
||||
def test_five_digit_reservation_rule_can_route_to_crane(app):
|
||||
"""五位纯数字经 numeric_length 规则产生 Crane Source,最终 Warehouse 仍留给库存行匹配。"""
|
||||
with app.app_context():
|
||||
db.session.add(_rule(code='RSV_LENGTH_5', priority=100, action='add_source_candidates', sources=['CRANE'], value=5, operator='numeric_length'))
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '12345'})
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('CRANE',)
|
||||
|
||||
|
||||
def test_dynamic_order_field_value_routes_inventory_source(app):
|
||||
"""路由条件引用稳定订单 field_id,并从 Task 当前 Extraction 读取行值。"""
|
||||
with app.app_context():
|
||||
order_schema_service.initialize_schema({'display_name': '路由字段'}, actor_id=None)
|
||||
field = order_schema_service.save_field(
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
saved_schema = order_schema_service.save_draft(draft['id'], {'fields': [{
|
||||
'field_id': field['id'], 'display_name': 'Reservation', 'required': True, 'aliases': [],
|
||||
'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id'], 'enum_options': [],
|
||||
'evidence_policy': {'required': True, 'source_precedence': ['attachment_text'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'reservation_id',
|
||||
}], 'expected_lock_version': draft['lock_version']})
|
||||
order_schema_service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
|
||||
)
|
||||
task = ShippingTask(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(schema_version_id=draft['id'], input_snapshot_hash='d' * 64, status='accepted', task_id=task.id)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
def _task_with_line_values(values: dict[str, tuple[str, str]]) -> tuple[ShippingTask, dict[str, int]]:
|
||||
"""保存当前解析的 FieldValue;测试断言路由只通过该审计投影读取值。"""
|
||||
task = ShippingTask(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=order_schema_service.get_published_contract()['schema_version_id'],
|
||||
input_snapshot_hash='d' * 64, status='accepted', task_id=task.id,
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for field_id, (value, _purpose) in values.items():
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field['id'], decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json='1000123456',
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field['id'], decision_id=decision.id,
|
||||
value_text='1000123456', value_json='1000123456',
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_id=decision.id,
|
||||
value_text=value, value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
rule = _rule(code='DYNAMIC_RSV', priority=200, action='add_source_candidates', sources=['DBS_DUB'], value='1')
|
||||
condition = rule.conditions[0]
|
||||
condition.source_kind = 'order_field'
|
||||
condition.system_fact_key = None
|
||||
condition.order_field_id = field['id']
|
||||
db.session.add(rule)
|
||||
db.session.commit()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
return task, {'_position': 0}
|
||||
|
||||
result = evaluate_inventory_source_rules(task=task, line={'_position': 0})
|
||||
|
||||
def _rule(*, code: str, priority: int, sources: list[str], conditions: list[tuple[str, str, object]]):
|
||||
"""构造已发布的行级订单字段规则;禁止使用 system_fact 路径。"""
|
||||
return ShippingInventoryRoutingRule(
|
||||
rule_code=code, rule_name=code, scope='line', priority=priority, match_mode='all',
|
||||
status='published', action_type='add_source_candidates', action_payload_json={'source_codes': sources}, version=1,
|
||||
conditions=[
|
||||
ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=1, source_kind='order_field', order_field_id=field_id,
|
||||
operator=operator, expected_value_json=expected, sequence=index,
|
||||
)
|
||||
for index, (field_id, operator, expected) in enumerate(conditions, start=1)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_reservation_prefix_rule_returns_ambiguous_source_candidates(app):
|
||||
"""十位预定单号兜底只产生 DUB/RTM 候选,不在路由阶段擅自选择 Source。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values({fields['reservation_id']: ('1000123456', 'reservation_id')})
|
||||
db.session.add(_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
))
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'ambiguous'
|
||||
assert result.source_codes == ('DBS_DUB', 'DBS_RTM')
|
||||
|
||||
|
||||
def test_inventory_source_hint_wins_over_reservation_fallback(app):
|
||||
"""高优先级库存源线索必须覆盖预定单号兜底,体现明确订单事实优先。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values({
|
||||
fields['reservation_id']: ('1000123456', 'reservation_id'),
|
||||
fields['inventory_source_hint']: ('VMI-FRA01', 'inventory_source_hint'),
|
||||
})
|
||||
db.session.add_all([
|
||||
_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
),
|
||||
_rule(
|
||||
code='HINT_FRA', priority=300, sources=['DBS_FRA'],
|
||||
conditions=[(fields['inventory_source_hint'], 'in', ['VMI-FRA01', 'FRA01'])],
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('DBS_DUB',)
|
||||
assert result.source_codes == ('DBS_FRA',)
|
||||
|
||||
|
||||
def test_crane_inventory_source_hint_wins_over_reservation_fallback(app):
|
||||
"""Crane 邮件线索必须按高优先级规则命中,不依赖五位预定单号兜底。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values({
|
||||
fields['reservation_id']: ('1000123456', 'reservation_id'),
|
||||
fields['inventory_source_hint']: ('LUK', 'inventory_source_hint'),
|
||||
})
|
||||
db.session.add_all([
|
||||
_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
),
|
||||
_rule(
|
||||
code='HINT_CRANE', priority=300, sources=['CRANE'],
|
||||
conditions=[(
|
||||
fields['inventory_source_hint'], 'in',
|
||||
['DBS TZR02', 'TZR02', 'VMI-RBD02', 'RBD2', 'LUK'],
|
||||
)],
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('CRANE',)
|
||||
|
||||
|
||||
def test_five_digit_reservation_rule_can_route_to_crane(app):
|
||||
"""五位纯数字预定单号通过订单 FieldValue 路由 Crane,Warehouse 仍留给库存行匹配。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
task, line = _task_with_line_values({fields['reservation_id']: ('12345', 'reservation_id')})
|
||||
db.session.add(_rule(
|
||||
code='RSV_LENGTH_5', priority=200, sources=['CRANE'],
|
||||
conditions=[(fields['reservation_id'], 'numeric_length', 5)],
|
||||
))
|
||||
db.session.commit()
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'resolved'
|
||||
assert result.source_codes == ('CRANE',)
|
||||
@@ -559,38 +559,6 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr
|
||||
assert not (tmp_path / "notice_uploads" / "_tmp").exists()
|
||||
|
||||
|
||||
def test_parse_notice_empty_result_requires_reupload_instead_of_review(app):
|
||||
"""无订单行且无单头字段时,不应生成空审核卡片,应停在重新上传/清洗节点。"""
|
||||
with app.app_context():
|
||||
user = User(username="shipping_empty_parse_user", email="shipping_empty_parse_user@example.com")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingTask(
|
||||
task_no="SN-EMPTY-PARSE-001",
|
||||
user_id=user.id,
|
||||
source_type="pdf",
|
||||
process_status="created",
|
||||
raw_content="This PDF extraction contains no order table.",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = shipping_tools.parse_notice({"task_id": task.task_no})
|
||||
|
||||
db.session.refresh(task)
|
||||
assert result["status"] == "needs_human"
|
||||
assert result["checkpoint"] == "notice_text_extraction_failed"
|
||||
assert [button["id"] for button in result["action_buttons"]] == [
|
||||
"replace_notice_file",
|
||||
"reparse",
|
||||
"reject",
|
||||
]
|
||||
assert task.pending_human_reason == "notice_text_extraction_failed"
|
||||
assert task.review_status is None
|
||||
assert task.lines_json == []
|
||||
assert "重新上传" in result["message"]
|
||||
|
||||
|
||||
def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app, client):
|
||||
"""重新上传当前任务通知应保留 task_no/batch_no,只覆盖正文并清理旧解析结果。"""
|
||||
headers = _workspace_headers(app)
|
||||
|
||||
@@ -13,8 +13,10 @@ import pytest
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
|
||||
ShippingRpaProfile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink,
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
|
||||
|
||||
@@ -22,6 +24,59 @@ def _tool_headers():
|
||||
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
|
||||
|
||||
|
||||
def _attach_dynamic_order(task: ShippingTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
"""为库存/RPA 测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。"""
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
order_schema_service.initialize_schema({'display_name': 'RPA 动态订单'}, actor_id=None)
|
||||
fields = {
|
||||
code: order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
|
||||
)
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
|
||||
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
|
||||
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
|
||||
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
} for code, field in fields.items()],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
field_ids = {
|
||||
str(item['field_code']): str(item['field_id'])
|
||||
for item in (version.definition_json or {}).get('fields') or []
|
||||
}
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code, value in {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}.items():
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
|
||||
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
|
||||
value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _confirm_direct_rpa_task_customer(task: ShippingTask) -> None:
|
||||
"""为直接构造的 RPA 回调任务补齐已确认客户。
|
||||
|
||||
@@ -96,115 +151,6 @@ def test_inventory_rpa_single_attempt_messages_hide_fraction():
|
||||
) == "已触发库存获取。若长时间无结果,可手动重试,或上传库存 Excel。"
|
||||
|
||||
|
||||
def test_ensure_inventory_auto_does_not_trigger_rpa_when_snapshot_is_missing(app, client, tmp_path, monkeypatch):
|
||||
"""正常 auto 未命中库存快照时应转缺库存,且不得写入 RPA trigger。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
trigger = tmp_path / "triggers"
|
||||
trigger.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
|
||||
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
|
||||
|
||||
headers = _tool_headers()
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"destination": {"port_code": "DUB", "city": "Dublin"},
|
||||
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
inv_res = client.post(
|
||||
"/api/shipping-notice/tools/ensure_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "mode": "auto"},
|
||||
)
|
||||
body = inv_res.get_json()
|
||||
assert body["status"] == "needs_human"
|
||||
assert "暂无可用库存数据" in body.get("message", "")
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
events = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered")
|
||||
.all()
|
||||
)
|
||||
assert len(events) == 0
|
||||
assert not list(trigger.glob("inventory_export_*.json"))
|
||||
|
||||
|
||||
def test_ensure_inventory_auto_reuses_snapshot_without_rpa(app, client, monkeypatch):
|
||||
"""正常 auto 命中已有快照时应直接返回复用结果,不得进入 RPA 编排。"""
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def _reuse(task, source, *, mode):
|
||||
captured.update({"task_no": task.task_no, "source": source, "mode": mode})
|
||||
return {"status": "ok", "message": "已复用库存快照", "data": {"reused": True}}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
_reuse,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa",
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("auto must not invoke RPA")),
|
||||
)
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
|
||||
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
|
||||
|
||||
headers = _tool_headers()
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"destination": {"port_code": "DUB", "city": "Dublin"},
|
||||
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
result = client.post(
|
||||
"/api/shipping-notice/tools/ensure_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "mode": "auto"},
|
||||
).get_json()
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["data"]["reused"] is True
|
||||
assert captured["task_no"] == task_id
|
||||
assert captured["mode"] == "auto"
|
||||
|
||||
|
||||
def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantity_selection(app, tmp_path):
|
||||
"""多个 Source 候选仅按 Reservation + PN 的唯一快照命中确定,数量为零也不改选其他 Source。"""
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
@@ -255,6 +201,8 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit
|
||||
}], schema_preview_json={},
|
||||
)
|
||||
db.session.add_all([profile, rtm_source, task, source_snapshot, other_snapshot])
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='1000123456', quantity=1)
|
||||
db.session.commit()
|
||||
|
||||
result = resolve_ambiguous_source_from_ready_snapshots(
|
||||
@@ -279,94 +227,6 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit
|
||||
}
|
||||
|
||||
|
||||
def test_rpa_report_inventory_callback_uses_published_profile(app, client, tmp_path, monkeypatch):
|
||||
"""RPA 回调必须按库存站点已发布方案解析,不再进入任务级字段映射确认。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
drop = tmp_path / "drop"
|
||||
drop.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
|
||||
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
|
||||
|
||||
headers = _tool_headers()
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"destination": {"port_code": "DUB", "city": "Dublin"},
|
||||
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
inv_file = drop / "stock.xlsx"
|
||||
inv_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU", qty=20).getvalue())
|
||||
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from tests.conftest import seed_rpa_inventory_trigger
|
||||
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-MAP-REVIEW")
|
||||
db.session.commit()
|
||||
run_no = "RUN-MAP-REVIEW"
|
||||
|
||||
cb_res = client.post(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_no": task_id,
|
||||
"success": True,
|
||||
"file_path": str(inv_file),
|
||||
"run_no": run_no,
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"warehouse_id": "AWSDU",
|
||||
"rpa_mode": "browser",
|
||||
},
|
||||
)
|
||||
data = cb_res.get_json()
|
||||
assert data["status"] == "ok"
|
||||
assert data.get("checkpoint") == "ready_to_match"
|
||||
assert "confirm_inventory_mapping" not in (data.get("human_options") or [])
|
||||
assert data.get("data", {}).get("rpa_runtime", {}).get("mode") == "browser"
|
||||
assert data.get("data", {}).get("rpa_runtime", {}).get("label") == "真实 RPA"
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert (task.step_payload_json or {})["last_inventory_rpa_runtime"]["mode"] == "browser"
|
||||
assert task.process_status == "inventory_ready"
|
||||
from app.services.shipping_notice.inventory_upload import resolve_task_inventory_upload_path
|
||||
|
||||
stored = resolve_task_inventory_upload_path(task_id)
|
||||
assert stored is not None and stored.is_file()
|
||||
inv_file = ShippingInventoryFile.query.order_by(ShippingInventoryFile.id.desc()).first()
|
||||
assert inv_file is not None
|
||||
assert inv_file.share_mode == "task_only"
|
||||
assert Path(inv_file.storage_path).is_file()
|
||||
assert inv_file.source_file_name == "stock.xlsx"
|
||||
active_link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).first()
|
||||
assert active_link is not None
|
||||
assert active_link.inventory_file_id == inv_file.id
|
||||
assert task.inventory_snapshot_id == inv_file.id
|
||||
|
||||
|
||||
def test_manual_task_inventory_upload_uses_published_profile_without_mapping_review(app, tmp_path):
|
||||
"""任务级人工上传必须复用库存站点发布方案,并直接进入待匹配状态。"""
|
||||
from io import BytesIO
|
||||
@@ -452,155 +312,6 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
|
||||
assert not list((tmp_path / 'storage' / 'inventory_uploads').glob('**/inventory.*'))
|
||||
|
||||
|
||||
def test_rpa_callback_gate_rechecks_order_drift_after_trigger(app, client):
|
||||
"""RPA 触发后新增 Reservation 异常或字段冲突时,旧回调必须停止入库。"""
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
|
||||
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
|
||||
headers = _tool_headers()
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
create_data = create_res.get_json()
|
||||
assert create_res.status_code == 200 and create_data.get("task_id"), create_data
|
||||
task_id = create_data["task_id"]
|
||||
client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"destination": {"port_code": "DUB", "city": "Dublin"},
|
||||
"lines": [
|
||||
{
|
||||
"part_number": "D4-A08AR12000002",
|
||||
"reservation_id": "R-1",
|
||||
"qty": 1,
|
||||
"uom": "EA",
|
||||
}
|
||||
],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _validate_rpa_callback_gate
|
||||
from app.services.shipping_notice.task_field_conflict_service import upsert_open_field_conflict
|
||||
from app.services.shipping_notice.task_line_store import replace_task_order_lines
|
||||
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).one()
|
||||
replace_task_order_lines(
|
||||
task,
|
||||
[{"part_number": "D4-A08AR12000002", "reservation_id": "", "qty": 1, "uom": "EA"}],
|
||||
)
|
||||
db.session.flush()
|
||||
reservation_block = _validate_rpa_callback_gate(task)
|
||||
assert reservation_block is not None
|
||||
assert reservation_block["checkpoint"] == "rsv_req"
|
||||
|
||||
replace_task_order_lines(
|
||||
task,
|
||||
[{"part_number": "D4-A08AR12000002", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
|
||||
)
|
||||
upsert_open_field_conflict(
|
||||
task=task,
|
||||
position=0,
|
||||
field_name="part_number",
|
||||
existing_value="D4-A08AR12000002",
|
||||
incoming_value="D4-A08AR12000003",
|
||||
existing_source="backend",
|
||||
incoming_source="dify",
|
||||
)
|
||||
db.session.flush()
|
||||
conflict_block = _validate_rpa_callback_gate(task)
|
||||
assert conflict_block is not None
|
||||
assert conflict_block["checkpoint"] == "parse_review"
|
||||
|
||||
|
||||
def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, tmp_path):
|
||||
"""无库存 skipped 回调应提示人工上传,且不计入 inventory_rpa_failed。"""
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "drop")
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
|
||||
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
|
||||
|
||||
headers = _tool_headers()
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"destination": {"port_code": "DUB", "city": "Dublin"},
|
||||
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
from app import db
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
from tests.conftest import seed_rpa_inventory_trigger
|
||||
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-SKIPPED")
|
||||
db.session.commit()
|
||||
|
||||
cb_res = client.post(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_no": task_id,
|
||||
"status": "skipped",
|
||||
"success": False,
|
||||
"skipped": True,
|
||||
"skip_reason": "no_inventory_data",
|
||||
"message": "DSV report has no inventory data",
|
||||
"run_no": "RUN-SKIPPED",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"warehouse_id": "AWSDU",
|
||||
"rpa_mode": "browser",
|
||||
},
|
||||
)
|
||||
data = cb_res.get_json()
|
||||
assert data["status"] == "needs_human"
|
||||
assert data.get("checkpoint") == "upload_req"
|
||||
assert "无可用库存" in (data.get("message") or "")
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.process_status == "waiting_inventory"
|
||||
failed_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_failed",
|
||||
).all()
|
||||
skipped_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_skipped",
|
||||
).all()
|
||||
assert not failed_events
|
||||
assert len(skipped_events) == 1
|
||||
assert skipped_events[0].detail_json.get("skip_reason") == "no_inventory_data"
|
||||
assert task.error_message is None
|
||||
skipped_meta = (task.step_payload_json or {}).get("inventory_rpa_skipped") or {}
|
||||
assert skipped_meta.get("skip_reason") == "no_inventory_data"
|
||||
assert skipped_meta.get("message")
|
||||
|
||||
|
||||
def test_normalize_rpa_inventory_result_status():
|
||||
"""单任务与 batch item 归一化:单任务宽松、batch 严格。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import (
|
||||
|
||||
@@ -27,6 +27,10 @@ from app.models import (
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
@@ -57,6 +61,7 @@ from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.query_service import resolve_order_extraction_ui_target
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.task_order_field_editor import current_line_field_values
|
||||
|
||||
|
||||
def _ensure_order_schema() -> dict[str, str]:
|
||||
@@ -77,6 +82,12 @@ def _ensure_order_schema() -> dict[str, str]:
|
||||
]
|
||||
fields = {}
|
||||
configs = []
|
||||
business_purposes = {
|
||||
'part_number': 'part_number',
|
||||
'qty': 'quantity',
|
||||
'reservation_id': 'reservation_id',
|
||||
'inventory_source_hint': 'inventory_source_hint',
|
||||
}
|
||||
for code, scope, value_type, required, normalizer, validators, comparator in definitions:
|
||||
field = order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': scope, 'value_type': value_type}, actor_id=None,
|
||||
@@ -84,6 +95,7 @@ def _ensure_order_schema() -> dict[str, str]:
|
||||
fields[code] = field['id']
|
||||
configs.append({
|
||||
'field_id': field['id'], 'display_name': code, 'required': required, 'aliases': [],
|
||||
'business_purpose': business_purposes.get(code, 'general'),
|
||||
'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [],
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_text', 'backend_table', 'dify_llm'],
|
||||
@@ -294,6 +306,65 @@ def _invalidate_dynamic_line_evidence(order: dict, code: str) -> None:
|
||||
field['observations'][0]['quote'] = 'NOT-IN-SOURCE'
|
||||
|
||||
|
||||
def _attach_existing_task_dynamic_order(task: ShippingTask) -> None:
|
||||
"""为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。"""
|
||||
fields = _ensure_order_schema()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id,
|
||||
schema_version_id=version.id,
|
||||
input_snapshot_hash='e' * 64,
|
||||
status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
configs = list((version.definition_json or {}).get('fields') or [])
|
||||
header_values = {'po_number': task.po_number}
|
||||
for config in configs:
|
||||
if config.get('scope') != 'header':
|
||||
continue
|
||||
code = str(config['field_code'])
|
||||
value = header_values.get(code)
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']),
|
||||
decision_status='accepted' if value not in (None, '') else 'missing',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value not in (None, ''):
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']),
|
||||
decision_id=decision.id, value_text=str(value), value_json=value,
|
||||
))
|
||||
for position, row in enumerate(task.lines_json or []):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for config in configs:
|
||||
if config.get('scope') != 'line':
|
||||
continue
|
||||
code = str(config['field_code'])
|
||||
value = row.get(code)
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=str(config['field_id']),
|
||||
decision_status='accepted' if value not in (None, '') else 'missing',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value not in (None, ''):
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=str(config['field_id']),
|
||||
decision_id=decision.id,
|
||||
value_text=str(value) if config.get('value_type') != 'decimal' else None,
|
||||
value_decimal=value if config.get('value_type') == 'decimal' else None,
|
||||
value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _add_extraction_intake(
|
||||
*,
|
||||
user: User,
|
||||
@@ -909,7 +980,7 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re
|
||||
assert edit_result['status'] == 'ok'
|
||||
assert task.pending_human_reason == 'low_confidence'
|
||||
assert 'process_field_gate' not in (task.step_payload_json or {})
|
||||
assert task.lines_json[0]['reservation_id'] == 'R-100'
|
||||
assert task.current_order_extraction_id is not None
|
||||
assert session.user_id == user.id
|
||||
|
||||
|
||||
@@ -975,6 +1046,8 @@ def test_submit_order_extraction_reports_opened_existing_without_claiming_creati
|
||||
process_status='waiting_inventory',
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(existing)
|
||||
db.session.commit()
|
||||
|
||||
duplicate_result = {
|
||||
@@ -1242,6 +1315,8 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor
|
||||
process_status='waiting_inventory',
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(existing)
|
||||
db.session.commit()
|
||||
|
||||
duplicate_result = {
|
||||
@@ -1369,6 +1444,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
},
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(existing)
|
||||
db.session.commit()
|
||||
|
||||
document.extracted_text = (
|
||||
@@ -1401,12 +1478,11 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
|
||||
candidate_line = candidate.structured_result_json['business_summary']['lines'][0]
|
||||
assert candidate_line['inventory_source_hint'] == 'DBS DUB'
|
||||
# 通用字段对账会同时补空的 Source Type 等可选字段;Reservation 必须落库。
|
||||
assert existing.lines_json[0]['part_number'] == 'P123456'
|
||||
assert existing.lines_json[0]['qty'] == 24
|
||||
assert existing.lines_json[0]['uom'] == 'EA'
|
||||
assert existing.lines_json[0]['reservation_id'] == '1000140351'
|
||||
assert existing.lines_json[0].get('inventory_source_hint') == 'DBS DUB'
|
||||
# 通用字段对账只写当前 Extraction 的 FieldValue;固定订单行投影不得变化。
|
||||
values = current_line_field_values(existing)[0]
|
||||
assert values['part_number'] == 'P123456'
|
||||
assert values['qty'] == 24
|
||||
assert values['reservation_id'] == '1000140351'
|
||||
assert existing.process_status == 'pending_review'
|
||||
assert existing.pending_human_reason == 'low_confidence'
|
||||
assert 'process_field_gate' not in (existing.step_payload_json or {})
|
||||
@@ -1511,6 +1587,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
|
||||
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-NEG')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(task)
|
||||
|
||||
outcome = backfill_exact_file_open_existing_reservations(
|
||||
task=task,
|
||||
@@ -1574,6 +1651,8 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
]
|
||||
db.session.add_all(tasks)
|
||||
db.session.flush()
|
||||
for task in tasks:
|
||||
_attach_existing_task_dynamic_order(task)
|
||||
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS')
|
||||
summary = {
|
||||
'po_number': '4510038672',
|
||||
@@ -1622,6 +1701,7 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
|
||||
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(task)
|
||||
|
||||
outcome = backfill_exact_file_open_existing_reservations(
|
||||
task=task,
|
||||
@@ -1750,6 +1830,8 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
_attach_existing_task_dynamic_order(existing)
|
||||
db.session.commit()
|
||||
|
||||
document.extracted_text = (
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.services.shipping_notice.query_service import (
|
||||
get_task_by_ref,
|
||||
get_task_in_batch,
|
||||
list_tasks_for_user,
|
||||
list_tasks_page_for_user,
|
||||
list_batch_task_summaries,
|
||||
resolve_task_from_payload,
|
||||
serialize_batch,
|
||||
@@ -108,6 +109,53 @@ def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
|
||||
assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"]
|
||||
|
||||
|
||||
def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
|
||||
"""分页必须由数据库排序、计数后切片,不能把固定上限结果伪装成分页。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
ShippingTask(task_no=f"SN-PAGE-{index:02d}", process_status="created", source_type="manual")
|
||||
for index in range(1, 6)
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
first_page = list_tasks_page_for_user(999999, page=1, page_size=2)
|
||||
second_page = list_tasks_page_for_user(999999, page=2, page_size=2)
|
||||
|
||||
# 关键断言:总数独立于每页大小,页面之间不重叠且均不超过 page_size。
|
||||
assert first_page["total"] == 5
|
||||
assert first_page["page"] == 1
|
||||
assert len(first_page["items"]) == 2
|
||||
assert second_page["total"] == 5
|
||||
assert second_page["page"] == 2
|
||||
assert len(second_page["items"]) == 2
|
||||
assert {item["task_no"] for item in first_page["items"]}.isdisjoint(
|
||||
{item["task_no"] for item in second_page["items"]}
|
||||
)
|
||||
|
||||
|
||||
def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
|
||||
"""分页总数必须只统计当前状态筛选命中的任务。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
ShippingTask(task_no="SN-PAGE-FILTER-1", process_status="created", source_type="manual"),
|
||||
ShippingTask(task_no="SN-PAGE-FILTER-2", process_status="created", source_type="manual"),
|
||||
ShippingTask(task_no="SN-PAGE-FILTER-3", process_status="uploaded", source_type="manual"),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
result = list_tasks_page_for_user(999999, process_status="created", page=1, page_size=10)
|
||||
|
||||
# 关键断言:uploaded 任务既不在 items 中,也不计入总数。
|
||||
assert result["total"] == 2
|
||||
assert {item["task_no"] for item in result["items"]} == {
|
||||
"SN-PAGE-FILTER-1", "SN-PAGE-FILTER-2",
|
||||
}
|
||||
|
||||
|
||||
def test_task_export_error_message_distinct_for_missing_path(app):
|
||||
"""无导出路径与磁盘缺失应返回不同错误文案。"""
|
||||
with app.app_context():
|
||||
@@ -139,8 +187,8 @@ def test_task_projection_tool_strips_internal_fields(app):
|
||||
)
|
||||
data = serialize_task(task, TaskProjection.TOOL)
|
||||
assert data["task_no"] == "SN-PROJ-TOOL"
|
||||
assert data["customer_name"] == "ACME"
|
||||
assert data["lines"] == [{"sku": "A001"}]
|
||||
assert data["customer_name"] is None
|
||||
assert data["lines"] == []
|
||||
assert not TOOL_TASK_DATA_OMIT.intersection(data.keys())
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
tests/test_shipping_order_field_purposes.py
|
||||
|
||||
用途:验证履约门禁从任务锁定的订单 Schema 快照和 FieldValue 读取业务字段。
|
||||
依赖:订单 Schema service/runtime 模型、reservation_gate。
|
||||
逻辑:当前任务不读取固定任务行投影;缺少用途或 Extraction 时必须明确阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
|
||||
|
||||
def _config(field_id: str) -> dict:
|
||||
"""构造包含预定单号用途的最小行字段配置。"""
|
||||
return {
|
||||
'field_id': field_id, 'display_name': '预定单号', 'business_purpose': 'reservation_id',
|
||||
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim',
|
||||
'validator_keys': ['reservation_id'], 'enum_options': [],
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_table'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None, 'comparator_key': 'normalized_text',
|
||||
}
|
||||
|
||||
|
||||
def _task_with_reservation(value: str) -> ShippingTask:
|
||||
"""发布 Schema 并持久化当前 Extraction 的行级 FieldValue。"""
|
||||
service.initialize_schema({'display_name': '用途测试'}, actor_id=None)
|
||||
field = service.save_field({'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
saved = service.save_draft(draft['id'], {'fields': [_config(field['id'])], 'expected_lock_version': draft['lock_version']}, actor_id=None)
|
||||
published = service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
task = ShippingTask(
|
||||
task_no='SN-PURPOSE-1', source_type='manual', lines_json=[{'reservation_id': 'WRONG'}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=published['id'], input_snapshot_hash='p' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field['id'], decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field['id'], decision_id=decision.id,
|
||||
value_text=value, value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def test_task_reservation_gate_uses_current_field_value_not_task_line_projection(app):
|
||||
"""门禁以 FieldValue 的合法号码为准,即使旧任务行投影保存错误值也不得阻断。"""
|
||||
with app.app_context():
|
||||
task = _task_with_reservation('3000000001')
|
||||
assert task_reservation_gate_issues(task) == []
|
||||
|
||||
|
||||
def test_task_reservation_gate_blocks_extraction_without_purpose(app):
|
||||
"""历史 Schema 未声明业务用途时不得猜测 field_code,必须阻断履约。"""
|
||||
with app.app_context():
|
||||
task = _task_with_reservation('3000000001')
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
definition = dict(extraction.schema_version.definition_json)
|
||||
definition['fields'] = [dict(item, business_purpose='general') for item in definition['fields']]
|
||||
extraction.schema_version.definition_json = definition
|
||||
db.session.commit()
|
||||
issues = task_reservation_gate_issues(task)
|
||||
assert issues[0]['reason'] == 'order_schema_unavailable'
|
||||
@@ -113,6 +113,70 @@ def test_order_schema_publish_keeps_history_when_field_code_changes(app):
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_IMMUTABLE'
|
||||
|
||||
|
||||
def test_order_schema_business_purposes_bind_stable_line_field_ids(app):
|
||||
"""业务用途只存在于不可变版本快照,字段改名后仍由原 field_id 供下游定位。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
reservation = service.save_field({
|
||||
'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
source_hint = service.save_field({
|
||||
'field_code': 'inventory_source_hint', 'scope': 'line', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
reservation_config = _field_config(reservation['id'], name='预定单号')
|
||||
reservation_config.update({
|
||||
'normalizer_key': 'uppercase_trim', 'validator_keys': ['reservation_id'],
|
||||
'comparator_key': 'normalized_text', 'business_purpose': 'reservation_id',
|
||||
})
|
||||
source_hint_config = _field_config(source_hint['id'], name='库存源线索')
|
||||
source_hint_config.update({
|
||||
'normalizer_key': 'uppercase_trim', 'validator_keys': [],
|
||||
'comparator_key': 'normalized_text', 'business_purpose': 'inventory_source_hint',
|
||||
})
|
||||
|
||||
_save_draft(draft['id'], [reservation_config, source_hint_config])
|
||||
published = _publish_draft(draft['id'])
|
||||
purposes = {
|
||||
item['business_purpose']: item['field_id']
|
||||
for item in service.get_published_contract()['fields']
|
||||
}
|
||||
assert purposes == {
|
||||
'reservation_id': reservation['id'],
|
||||
'inventory_source_hint': source_hint['id'],
|
||||
}
|
||||
|
||||
service.save_field({
|
||||
'field_code': 'reservation_number', 'scope': 'line', 'value_type': 'string',
|
||||
}, actor_id=None, field_id=reservation['id'])
|
||||
assert next(
|
||||
item for item in published['definition']['fields'] if item['field_id'] == reservation['id']
|
||||
)['business_purpose'] == 'reservation_id'
|
||||
|
||||
|
||||
def test_order_schema_rejects_duplicate_or_incompatible_business_purposes(app):
|
||||
"""用途必须唯一且符合行级类型约束,防止路由与门禁在运行期读取错误字段。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
first = service.save_field({'field_code': 'first_hint', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
second = service.save_field({'field_code': 'second_hint', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
header = service.save_field({'field_code': 'header_hint', 'scope': 'header', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
first_config = _field_config(first['id'], name='线索一')
|
||||
first_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text', 'business_purpose': 'inventory_source_hint'})
|
||||
second_config = _field_config(second['id'], name='线索二')
|
||||
second_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text', 'business_purpose': 'inventory_source_hint'})
|
||||
with pytest.raises(Exception) as duplicate_exc:
|
||||
_save_draft(draft['id'], [first_config, second_config])
|
||||
assert getattr(duplicate_exc.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
|
||||
header_config = _field_config(header['id'], name='订单头线索')
|
||||
header_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text', 'business_purpose': 'reservation_id'})
|
||||
with pytest.raises(Exception) as scope_exc:
|
||||
_save_draft(draft['id'], [header_config])
|
||||
assert getattr(scope_exc.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
|
||||
|
||||
def test_order_schema_excluded_field_config_is_saved_but_not_published(app):
|
||||
"""未纳入字段仍保存版本显示名称和规则,但发布契约不得包含该字段。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
"""发货任务回收站、作废和归档基础服务测试。"""
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingCase, ShippingTask, ShippingTaskEvent, ShippingTaskPurgeAudit
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import User
|
||||
from app.services.shipping_notice.task_disposition_service import (
|
||||
archive_task,
|
||||
move_task_to_recycle_bin,
|
||||
restore_task_from_recycle_bin,
|
||||
purge_task_permanently,
|
||||
task_disposition_capability,
|
||||
task_is_active,
|
||||
void_task,
|
||||
)
|
||||
from app.services.shipping_notice.batch_orchestrator import _should_orchestrate_task
|
||||
|
||||
|
||||
def _task(task_no: str, **kwargs) -> ShippingTask:
|
||||
"""构造最小发货任务,便于隔离验证处置状态与原流程状态。"""
|
||||
return ShippingTask(task_no=task_no, process_status='created', source_type='manual', **kwargs)
|
||||
|
||||
|
||||
def test_plain_created_task_can_be_deleted_and_restored(app):
|
||||
"""纯误建任务进入回收站后保持 active,恢复后可继续作为普通任务处理。"""
|
||||
with app.app_context():
|
||||
task = _task('SN-DISPOSITION-DELETE-001')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
outcome = move_task_to_recycle_bin(task, actor_id=1, reason='误建任务', request_id='req-delete')
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:删除不篡改 process_status,异步门禁仅因回收站状态停止任务。
|
||||
assert outcome == 'deleted'
|
||||
assert task.process_status == 'created'
|
||||
assert task.lifecycle_status == 'active'
|
||||
assert task.deleted_at is not None
|
||||
assert task_is_active(task) is False
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type='task_deleted').count() == 1
|
||||
|
||||
restore_task_from_recycle_bin(task, actor_id=1, request_id='req-restore')
|
||||
db.session.commit()
|
||||
assert task.deleted_at is None
|
||||
assert task_is_active(task) is True
|
||||
|
||||
|
||||
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
|
||||
db.session.commit()
|
||||
|
||||
outcome = move_task_to_recycle_bin(task, actor_id=1, reason='重复建单')
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:业务引用存在时,回收站任务必须同时标记为 voided 且不可恢复。
|
||||
assert outcome == 'voided_and_deleted'
|
||||
assert task.lifecycle_status == 'voided'
|
||||
assert task.void_reason == '重复建单'
|
||||
assert task_disposition_capability(task, 'restore').allowed is False
|
||||
|
||||
|
||||
def test_external_fulfillment_can_only_be_archived(app):
|
||||
"""上传中或已有外部回执时,平台禁止单方删除/作废以避免双系统不一致。"""
|
||||
with app.app_context():
|
||||
task = _task('SN-DISPOSITION-EXTERNAL-001', upload_status='running')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
assert task_disposition_capability(task, 'delete').code == 'SHIPPING.TASK_EXTERNAL_VOID_BLOCKED'
|
||||
assert task_disposition_capability(task, 'void').code == 'SHIPPING.TASK_EXTERNAL_VOID_BLOCKED'
|
||||
archive_task(task, actor_id=1)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:归档不改写上传状态,仅隐藏默认列表所需的生命周期状态。
|
||||
assert task.lifecycle_status == 'archived'
|
||||
assert task.upload_status == 'running'
|
||||
assert task_is_active(task) is False
|
||||
|
||||
|
||||
def test_void_requires_reason_and_rejects_successor(app):
|
||||
"""作废必须有原因,且不可破坏存在后继版本的修订链。"""
|
||||
with app.app_context():
|
||||
task = _task('SN-DISPOSITION-SOURCE-001')
|
||||
successor = _task('SN-DISPOSITION-SUCCESSOR-001')
|
||||
db.session.add_all([task, successor])
|
||||
db.session.flush()
|
||||
successor.supersedes_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
void_task(task, actor_id=1, reason='')
|
||||
except Exception as exc:
|
||||
assert getattr(exc, 'code', None) == 'SHIPPING.TASK_VOID_REASON_REQUIRED'
|
||||
else:
|
||||
raise AssertionError('empty void reason must be rejected')
|
||||
try:
|
||||
void_task(task, actor_id=1, reason='需要作废')
|
||||
except ConflictError as exc:
|
||||
assert exc.code == 'SHIPPING.TASK_SUCCESSOR_VOID_BLOCKED'
|
||||
else:
|
||||
raise AssertionError('task with successor must not be voided')
|
||||
assert task_disposition_capability(task, 'delete').code == 'SHIPPING.TASK_SUCCESSOR_VOID_BLOCKED'
|
||||
|
||||
|
||||
def test_disposition_stops_backend_orchestration_without_changing_process_status(app):
|
||||
"""后台编排必须读取独立生命周期,不能依赖 process_status 被伪造为 rejected。"""
|
||||
with app.app_context():
|
||||
task = _task('SN-DISPOSITION-ORCHESTRATOR-001')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
assert _should_orchestrate_task(task) is True
|
||||
move_task_to_recycle_bin(task, actor_id=1, reason='取消处理')
|
||||
|
||||
# 关键断言:任务仍为 created,但回收站状态已让编排器停止执行。
|
||||
assert task.process_status == 'created'
|
||||
assert _should_orchestrate_task(task) is False
|
||||
|
||||
|
||||
def _headers_for_user(app, username: str, role: str = 'user') -> tuple[dict[str, str], int]:
|
||||
"""创建工作台 API 测试用户并生成 Bearer token,验证服务端而非前端的权限判定。"""
|
||||
with app.app_context():
|
||||
user = User(username=username, email=f'{username}@example.com', role=role, status='active')
|
||||
user.set_password('password')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return {'Authorization': f'Bearer {issue_local_access_token(user)}'}, int(user.id)
|
||||
|
||||
|
||||
def test_batch_delete_returns_partial_results_and_enforces_ownership(app, client):
|
||||
"""批量删除必须逐票鉴权:自己的任务可处理,他人任务返回 blocked 而不影响前者。"""
|
||||
headers, user_id = _headers_for_user(app, 'disposition-owner')
|
||||
_other_headers, other_user_id = _headers_for_user(app, 'disposition-other')
|
||||
with app.app_context():
|
||||
own = _task('SN-DISPOSITION-API-OWN', user_id=user_id)
|
||||
foreign = _task('SN-DISPOSITION-API-FOREIGN', user_id=other_user_id)
|
||||
db.session.add_all([own, foreign])
|
||||
db.session.commit()
|
||||
|
||||
response = client.post(
|
||||
'/api/workspace/shipping-tasks/batch-delete',
|
||||
headers=headers,
|
||||
json={'task_nos': ['SN-DISPOSITION-API-OWN', 'SN-DISPOSITION-API-FOREIGN'], 'reason': '批量清理'},
|
||||
)
|
||||
|
||||
# 关键断言:部分成功不整体回滚,越权任务在服务端明确标记为 blocked。
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()
|
||||
assert payload['success'] is True
|
||||
statuses = {item['task_no']: item['status'] for item in payload['data']['results']}
|
||||
assert statuses == {'SN-DISPOSITION-API-OWN': 'deleted', 'SN-DISPOSITION-API-FOREIGN': 'blocked'}
|
||||
with app.app_context():
|
||||
assert ShippingTask.query.filter_by(task_no='SN-DISPOSITION-API-OWN').one().deleted_at is not None
|
||||
assert ShippingTask.query.filter_by(task_no='SN-DISPOSITION-API-FOREIGN').one().deleted_at is None
|
||||
|
||||
|
||||
def test_workspace_list_hides_deleted_tasks_and_exposes_recycle_bin(app, client):
|
||||
"""默认列表不能泄漏回收站任务;指定 lifecycle_status=deleted 时才返回该任务。"""
|
||||
headers, user_id = _headers_for_user(app, 'disposition-list')
|
||||
with app.app_context():
|
||||
active = _task('SN-DISPOSITION-LIST-ACTIVE', user_id=user_id)
|
||||
deleted = _task('SN-DISPOSITION-LIST-DELETED', user_id=user_id)
|
||||
db.session.add_all([active, deleted])
|
||||
db.session.flush()
|
||||
move_task_to_recycle_bin(deleted, actor_id=user_id, reason='测试回收站')
|
||||
db.session.commit()
|
||||
|
||||
normal = client.get('/api/workspace/shipping-tasks', headers=headers).get_json()
|
||||
recycle_bin = client.get('/api/workspace/shipping-tasks?lifecycle_status=deleted', headers=headers).get_json()
|
||||
|
||||
# 关键断言:默认查询仅活动任务,回收站查询仅已删除任务。
|
||||
assert [item['task_no'] for item in normal['items']] == ['SN-DISPOSITION-LIST-ACTIVE']
|
||||
assert [item['task_no'] for item in recycle_bin['items']] == ['SN-DISPOSITION-LIST-DELETED']
|
||||
|
||||
|
||||
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])
|
||||
db.session.flush()
|
||||
task.shipping_case_id = case.id
|
||||
move_task_to_recycle_bin(task, actor_id=user_id, reason='测试作废')
|
||||
db.session.commit()
|
||||
|
||||
response = client.get('/api/workspace/shipping-tasks?lifecycle_status=voided', headers=headers)
|
||||
|
||||
# 关键断言:作废任务即使同时在回收站,仍可通过已作废筛选追溯。
|
||||
assert [item['task_no'] for item in response.get_json()['items']] == ['SN-DISPOSITION-LIST-VOIDED']
|
||||
|
||||
|
||||
def test_admin_can_purge_only_pure_deleted_task_and_audit_is_retained(app, client):
|
||||
"""永久删除只能清除纯误建回收站任务,且删除后仍须保留无 task 外键的审计快照。"""
|
||||
admin_headers, admin_id = _headers_for_user(app, 'disposition-admin', role='admin')
|
||||
with app.app_context():
|
||||
task = _task('SN-DISPOSITION-PURGE-001', user_id=admin_id)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
move_task_to_recycle_bin(task, actor_id=admin_id, reason='误建')
|
||||
db.session.commit()
|
||||
|
||||
response = client.post(
|
||||
'/api/workspace/shipping-tasks/batch-purge',
|
||||
headers=admin_headers,
|
||||
json={'task_nos': ['SN-DISPOSITION-PURGE-001'], 'reason': '管理员清除误建任务'},
|
||||
)
|
||||
|
||||
# 关键断言:任务物理删除,但审计快照不依赖 task FK,仍可供后续追溯。
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()['data']['results'][0]['status'] == 'purged'
|
||||
with app.app_context():
|
||||
assert ShippingTask.query.filter_by(task_no='SN-DISPOSITION-PURGE-001').first() is None
|
||||
audit = ShippingTaskPurgeAudit.query.filter_by(task_no_snapshot='SN-DISPOSITION-PURGE-001').one()
|
||||
assert audit.reason == '管理员清除误建任务'
|
||||
|
||||
|
||||
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.deleted_at = __import__('datetime').datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
purge_task_permanently(task, actor_id=1, reason='尝试清除')
|
||||
except ConflictError as exc:
|
||||
assert exc.code == 'SHIPPING.TASK_PURGE_BLOCKED'
|
||||
else:
|
||||
raise AssertionError('business-linked task must not be purged')
|
||||
@@ -11,7 +11,11 @@ from __future__ import annotations
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskFieldConflict
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingTask, ShippingTaskFieldConflict,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.task_candidate_reconciliation import (
|
||||
apply_candidate_reconciliation_plan,
|
||||
build_candidate_reconciliation_plan,
|
||||
@@ -19,8 +23,7 @@ from app.services.shipping_notice.task_candidate_reconciliation import (
|
||||
)
|
||||
from app.services.shipping_notice.task_field_conflict_service import resolve_field_conflict
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.task_line_store import replace_task_order_lines
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
from app.services.shipping_notice.task_workflow import add_notice_line, update_notice_line
|
||||
|
||||
|
||||
def _task(**kwargs) -> ShippingTask:
|
||||
@@ -37,6 +40,7 @@ def _task(**kwargs) -> ShippingTask:
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_extraction(task, list(task.lines_json or []))
|
||||
return task
|
||||
|
||||
|
||||
@@ -48,6 +52,75 @@ def _candidate(summary_lines: list[dict], *, po_number: str = 'PO-100') -> Simpl
|
||||
)
|
||||
|
||||
|
||||
def _attach_dynamic_extraction(task: ShippingTask, rows: list[dict]) -> dict[str, str]:
|
||||
"""建立候选对账所需的动态 FieldValue,测试不得依赖固定订单行投影。"""
|
||||
order_schema_service.initialize_schema({'display_name': '对账字段'}, actor_id=None)
|
||||
fields = {
|
||||
code: order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': scope, 'value_type': value_type}, actor_id=None,
|
||||
)
|
||||
for code, scope, value_type in (
|
||||
('po_number', 'header', 'string'),
|
||||
('part_number', 'line', 'string'), ('qty', 'line', 'decimal'), ('reservation_id', 'line', 'string'),
|
||||
)
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'qty': 'quantity', 'reservation_id': 'reservation_id'}
|
||||
saved = order_schema_service.save_draft(draft['id'], {'fields': [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes.get(code, 'general'),
|
||||
'required': code != 'reservation_id',
|
||||
'aliases': [], 'normalizer_key': 'decimal' if code == 'qty' else 'uppercase_trim',
|
||||
'validator_keys': ['positive_decimal'] if code == 'qty' else ['reservation_id'] if code == 'reservation_id' else ['non_empty'],
|
||||
'enum_options': [],
|
||||
'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
} for code, field in fields.items()], 'expected_lock_version': draft['lock_version']}, actor_id=None)
|
||||
published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=published['id'], input_snapshot_hash='r' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
header_field = fields['po_number']
|
||||
header_value = task.po_number
|
||||
header_decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=None, field_id=header_field['id'],
|
||||
decision_status='accepted' if header_value else 'missing',
|
||||
supporting_observation_ids_json=[], resolved_value_json=header_value,
|
||||
)
|
||||
db.session.add(header_decision)
|
||||
db.session.flush()
|
||||
if header_value:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None, field_id=header_field['id'], decision_id=header_decision.id,
|
||||
value_text=str(header_value), value_json=header_value,
|
||||
))
|
||||
for position, row in enumerate(rows):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code, field in fields.items():
|
||||
if code == 'po_number':
|
||||
continue
|
||||
value = row.get(code)
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field['id'],
|
||||
decision_status='accepted' if value not in (None, '') else 'missing',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value not in (None, ''):
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field['id'], decision_id=decision.id,
|
||||
value_text=str(value) if code != 'qty' else None,
|
||||
value_decimal=value if code == 'qty' else None,
|
||||
value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
return {code: field['id'] for code, field in fields.items()}
|
||||
|
||||
|
||||
def test_build_plan_fills_empty_and_conflicts_on_diff(app):
|
||||
"""空字段自动进入 fills;双方非空不同进入 conflicts。"""
|
||||
with app.app_context():
|
||||
@@ -77,7 +150,6 @@ def test_apply_conflict_persists_field_conflict_and_blocks_gate(app):
|
||||
"""冲突落库后库存门禁应阻断。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
|
||||
plan = build_candidate_reconciliation_plan(
|
||||
task=task,
|
||||
@@ -93,11 +165,16 @@ def test_apply_conflict_persists_field_conflict_and_blocks_gate(app):
|
||||
assert gate['status'] == 'needs_human'
|
||||
|
||||
|
||||
def test_resolve_conflict_writes_line_and_is_idempotent(app):
|
||||
"""解决冲突回写订单行;同幂等键可重放。"""
|
||||
def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app):
|
||||
"""解决冲突只回写当前 FieldValue;旧订单行投影保持不变且同幂等键可重放。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
field_id = next(
|
||||
item['field_id']
|
||||
for item in extraction.schema_version.definition_json['fields']
|
||||
if item['field_code'] == 'reservation_id'
|
||||
)
|
||||
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
|
||||
plan = build_candidate_reconciliation_plan(
|
||||
task=task,
|
||||
@@ -119,7 +196,10 @@ def test_resolve_conflict_writes_line_and_is_idempotent(app):
|
||||
)
|
||||
assert first['idempotent_replay'] is False
|
||||
task = db.session.get(ShippingTask, task.id)
|
||||
assert task.lines_json[0]['reservation_id'] == '3000092917'
|
||||
value = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=task.current_order_extraction_id, field_id=field_id,
|
||||
).one()
|
||||
assert value.value_json == '3000092917'
|
||||
assert ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').count() == 0
|
||||
|
||||
replay = resolve_field_conflict(
|
||||
@@ -139,7 +219,6 @@ def test_update_notice_line_version_mismatch(app):
|
||||
pending_human_reason=None,
|
||||
lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
)
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
db.session.commit()
|
||||
resp = update_notice_line({
|
||||
'task_id': task.task_no,
|
||||
@@ -160,15 +239,43 @@ def test_update_notice_line_version_mismatch(app):
|
||||
assert resp['data']['error_code'] == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
|
||||
|
||||
|
||||
def test_add_notice_line_creates_new_extraction_and_preserves_header_values(app):
|
||||
"""新增行必须生成新 Extraction,且复制已有单头值,避免行编辑破坏锁定订单真相。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[{'reservation_id': '3000000001'}])
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
header_decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=None, field_id='header-po', decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json='PO-100',
|
||||
)
|
||||
db.session.add(header_decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None, field_id='header-po', decision_id=header_decision.id,
|
||||
value_text='PO-100', value_json='PO-100',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = add_notice_line({
|
||||
'task_id': task.task_no,
|
||||
'line': {'reservation_id': '3000000002'},
|
||||
})
|
||||
assert result['status'] == 'ok'
|
||||
current = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
assert current.id != extraction.id
|
||||
assert extraction.status == 'superseded'
|
||||
assert ShippingOrderLine.query.filter_by(extraction_id=current.id).count() == 2
|
||||
header = ShippingOrderFieldValue.query.filter_by(extraction_id=current.id, line_id=None, field_id='header-po').one()
|
||||
assert header.value_json == 'PO-100'
|
||||
|
||||
|
||||
def test_multiline_conflicts_persist_and_survive_line_replace(app):
|
||||
"""多行同字段冲突应分别落库,且双写重建订单行后不得被抹掉。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _task(lines_json=[
|
||||
{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'},
|
||||
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000000002'},
|
||||
])
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
candidate = _candidate([
|
||||
{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'},
|
||||
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000092918'},
|
||||
@@ -189,19 +296,13 @@ def test_multiline_conflicts_persist_and_survive_line_replace(app):
|
||||
assert len(open_rows) == 2
|
||||
assert {row.position for row in open_rows} == {0, 1}
|
||||
|
||||
# 再次双写重建行主键后,冲突审计仍在。
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
db.session.commit()
|
||||
open_rows = ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').all()
|
||||
assert len(open_rows) == 2
|
||||
assert all(row.line_id is not None for row in open_rows)
|
||||
assert all(row.position is not None for row in open_rows)
|
||||
|
||||
|
||||
def test_reconcile_exact_file_open_existing_auto_fill(app):
|
||||
"""安全态 exact_file 可自动补空 Reservation。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10}])
|
||||
replace_task_order_lines(task, task.lines_json, normalize=False)
|
||||
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
|
||||
result = reconcile_exact_file_open_existing(
|
||||
task=task,
|
||||
@@ -213,4 +314,9 @@ def test_reconcile_exact_file_open_existing_auto_fill(app):
|
||||
)
|
||||
db.session.commit()
|
||||
assert result['status'] == 'applied'
|
||||
assert task.lines_json[0]['reservation_id'] == '3000092917'
|
||||
assert any(
|
||||
item.value_json == '3000092917'
|
||||
for item in ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=task.current_order_extraction_id,
|
||||
).all()
|
||||
)
|
||||
@@ -1,323 +0,0 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_line_store.py
|
||||
|
||||
用途:验证订单行双写、历史回填、影子/表读与故障回滚。
|
||||
依赖:Flask testing app、ShippingTask/ShippingTaskLine、task_line_store、backfill 脚本函数。
|
||||
逻辑:覆盖双写原子性、未知字段 round-trip、dry-run/幂等回填、shadow 差异日志、table 读投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskLine
|
||||
from app.services.shipping_notice.task_line_store import (
|
||||
clear_task_order_lines,
|
||||
compare_task_order_line_projections,
|
||||
lines_checksum,
|
||||
read_task_order_lines,
|
||||
replace_task_order_lines,
|
||||
sync_task_order_lines_from_json,
|
||||
)
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
_BACKFILL_PATH = Path(__file__).resolve().parents[1] / 'scripts' / 'backfill_shipping_task_lines.py'
|
||||
_BACKFILL_SPEC = importlib.util.spec_from_file_location(
|
||||
'backfill_shipping_task_lines',
|
||||
_BACKFILL_PATH,
|
||||
)
|
||||
assert _BACKFILL_SPEC and _BACKFILL_SPEC.loader
|
||||
_BACKFILL_MODULE = importlib.util.module_from_spec(_BACKFILL_SPEC)
|
||||
_BACKFILL_SPEC.loader.exec_module(_BACKFILL_MODULE)
|
||||
backfill_shipping_task_lines = _BACKFILL_MODULE.backfill_shipping_task_lines
|
||||
|
||||
|
||||
def _make_task(*, task_no: str = 'SN-LINE-STORE-001', lines: list | None = None) -> ShippingTask:
|
||||
"""创建最小可落库任务,供双写测试复用。"""
|
||||
task = ShippingTask(
|
||||
task_no=task_no,
|
||||
source_type='manual',
|
||||
process_status='parsed',
|
||||
lines_json=lines if lines is not None else [],
|
||||
order_data_version=1,
|
||||
order_lines_migration_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def test_dual_write_replace_persists_json_and_table(app):
|
||||
"""dual 写模式应在同一事务内更新 lines_json 与规范表,并保留未知字段。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'json'
|
||||
task = _make_task()
|
||||
version_before = int(task.order_data_version)
|
||||
|
||||
written = replace_task_order_lines(
|
||||
task,
|
||||
[
|
||||
{
|
||||
'part_number': 'A001',
|
||||
'qty': 10,
|
||||
'reservation_id': '3000092917',
|
||||
'customer_part_number': 'C-A001',
|
||||
'aws_part_number': 'AWS-A001',
|
||||
'inventory_source_hint': 'H1',
|
||||
'custom_note': 'keep-me',
|
||||
}
|
||||
],
|
||||
normalize=False,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert written[0]['part_number'] == 'A001'
|
||||
assert task.lines_json[0]['custom_note'] == 'keep-me'
|
||||
assert int(task.order_data_version) == version_before + 1
|
||||
assert task.order_lines_migration_status == 'synced'
|
||||
|
||||
rows = ShippingTaskLine.query.filter_by(task_id=task.id).order_by(ShippingTaskLine.position).all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].part_number == 'A001'
|
||||
assert rows[0].qty == Decimal('10')
|
||||
assert rows[0].reservation_id == '3000092917'
|
||||
assert rows[0].customer_part_number == 'C-A001'
|
||||
assert rows[0].aws_part_number == 'AWS-A001'
|
||||
assert rows[0].inventory_source_hint == 'H1'
|
||||
assert rows[0].extra_json == {'custom_note': 'keep-me'}
|
||||
assert compare_task_order_line_projections(task)['equal'] is True
|
||||
|
||||
|
||||
def test_dual_write_failure_rolls_back_both_sides(app):
|
||||
"""构造行失败时不得留下半写规范行或 JSON。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _make_task(lines=[{'part_number': 'OLD', 'qty': 1}])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValueError, match='invalid qty'):
|
||||
replace_task_order_lines(
|
||||
task,
|
||||
[{'part_number': 'BAD', 'qty': 0, 'reservation_id': 'R-1'}],
|
||||
normalize=False,
|
||||
)
|
||||
db.session.rollback()
|
||||
|
||||
task = db.session.get(ShippingTask, task.id)
|
||||
assert task.lines_json == [{'part_number': 'OLD', 'qty': 1}]
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
|
||||
|
||||
def test_clear_and_shadow_read(app, caplog):
|
||||
"""清空走 store;shadow 模式对外仍读 JSON,并在不一致时打 warning。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _make_task()
|
||||
replace_task_order_lines(task, [{'part_number': 'A001', 'qty': 2}], normalize=False)
|
||||
db.session.commit()
|
||||
|
||||
clear_task_order_lines(task)
|
||||
db.session.commit()
|
||||
assert task.lines_json == []
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
|
||||
# 人为制造影子差异:只改 JSON,不改表。
|
||||
task.lines_json = [{'part_number': 'SHADOW', 'qty': 9}]
|
||||
task.order_lines_migration_status = 'pending'
|
||||
db.session.commit()
|
||||
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'shadow'
|
||||
with caplog.at_level('WARNING'):
|
||||
lines = read_task_order_lines(task)
|
||||
assert lines == [{'part_number': 'SHADOW', 'qty': 9}]
|
||||
assert any('shadow mismatch' in message for message in caplog.messages)
|
||||
|
||||
|
||||
def test_sync_from_json_backfill_idempotent_and_dry_run(app):
|
||||
"""历史回填 dry-run 不落库;apply 幂等且不 bump order_data_version。"""
|
||||
with app.app_context():
|
||||
task = _make_task(
|
||||
task_no='SN-LINE-BACKFILL-001',
|
||||
lines=[
|
||||
{
|
||||
'part_number': 'B002',
|
||||
'qty': '3.50',
|
||||
'inventory_source_hint': 'HUB',
|
||||
'legacy_flag': True,
|
||||
}
|
||||
],
|
||||
)
|
||||
db.session.commit()
|
||||
version_before = int(task.order_data_version)
|
||||
|
||||
dry = sync_task_order_lines_from_json(task, dry_run=True)
|
||||
assert dry['status'] == 'synced'
|
||||
assert dry['reason'] == 'dry_run'
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
|
||||
applied = sync_task_order_lines_from_json(task, dry_run=False)
|
||||
db.session.commit()
|
||||
assert applied['status'] == 'synced'
|
||||
assert int(task.order_data_version) == version_before
|
||||
assert task.order_lines_migration_status == 'synced'
|
||||
row = ShippingTaskLine.query.filter_by(task_id=task.id).one()
|
||||
assert row.qty == Decimal('3.50')
|
||||
assert row.extra_json == {'legacy_flag': True}
|
||||
|
||||
again = sync_task_order_lines_from_json(task, dry_run=False)
|
||||
assert again['status'] == 'skipped'
|
||||
assert again['reason'] == 'already_synced'
|
||||
|
||||
|
||||
def test_sync_rejects_invalid_historical_line(app):
|
||||
"""非法历史行应返回 failed,并保留原 JSON / 空规范表。"""
|
||||
with app.app_context():
|
||||
task = _make_task(
|
||||
task_no='SN-LINE-BAD-001',
|
||||
lines=[{'part_number': 'Z', 'qty': -1}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = sync_task_order_lines_from_json(task, dry_run=False)
|
||||
assert result['status'] == 'failed'
|
||||
assert 'invalid qty' in str(result.get('reason') or '')
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
assert task.lines_json == [{'part_number': 'Z', 'qty': -1}]
|
||||
|
||||
|
||||
def test_backfill_script_page_and_resume(app):
|
||||
"""回填脚本支持 dry-run、apply、按 after_id 续跑,失败任务隔离。"""
|
||||
with app.app_context():
|
||||
good = _make_task(task_no='SN-BF-GOOD', lines=[{'part_number': 'G1', 'qty': 1}])
|
||||
bad = _make_task(task_no='SN-BF-BAD', lines=[{'part_number': 'B1', 'qty': 0}])
|
||||
db.session.commit()
|
||||
|
||||
dry_summary = backfill_shipping_task_lines(dry_run=True, after_id=0, limit=50)
|
||||
assert dry_summary['scanned'] >= 2
|
||||
assert ShippingTaskLine.query.count() == 0
|
||||
|
||||
apply_summary = backfill_shipping_task_lines(dry_run=False, after_id=0, limit=50)
|
||||
assert apply_summary['synced'] >= 1
|
||||
assert apply_summary['failed'] >= 1
|
||||
assert any(item['task_no'] == 'SN-BF-BAD' for item in apply_summary['failures'])
|
||||
|
||||
good = db.session.get(ShippingTask, good.id)
|
||||
bad = db.session.get(ShippingTask, bad.id)
|
||||
assert good.order_lines_migration_status == 'synced'
|
||||
assert ShippingTaskLine.query.filter_by(task_id=good.id).count() == 1
|
||||
assert ShippingTaskLine.query.filter_by(task_id=bad.id).count() == 0
|
||||
|
||||
resume = backfill_shipping_task_lines(dry_run=False, after_id=int(good.id), limit=50)
|
||||
assert all(item['task_id'] > good.id for item in resume['results'])
|
||||
|
||||
|
||||
def test_json_write_mode_skips_table(app):
|
||||
"""write=json 时只更新快照,不写规范表。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'json'
|
||||
task = _make_task(task_no='SN-JSON-ONLY')
|
||||
replace_task_order_lines(task, [{'part_number': 'J1', 'qty': 4}], normalize=False)
|
||||
db.session.commit()
|
||||
assert task.lines_json[0]['part_number'] == 'J1'
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
assert task.order_lines_migration_status == 'pending'
|
||||
|
||||
|
||||
def test_table_read_mode_returns_canonical_projection(app):
|
||||
"""read=table 时以规范表投影为准,忽略仅存在于 JSON 的漂移。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'table'
|
||||
task = _make_task(task_no='SN-TABLE-READ')
|
||||
replace_task_order_lines(
|
||||
task,
|
||||
[{'part_number': 'T1', 'qty': 5, 'reservation_id': '3000092917'}],
|
||||
normalize=False,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 人为制造 JSON 漂移:table 读路径不得返回漂移值。
|
||||
task.lines_json = [{'part_number': 'DRIFT', 'qty': 99}]
|
||||
db.session.commit()
|
||||
|
||||
lines = read_task_order_lines(task)
|
||||
assert lines == [{'part_number': 'T1', 'qty': 5, 'reservation_id': '3000092917'}]
|
||||
comparison = compare_task_order_line_projections(task)
|
||||
assert comparison['equal'] is False
|
||||
assert comparison['table_count'] == 1
|
||||
|
||||
|
||||
def test_lines_checksum_stable_for_key_order(app):
|
||||
"""checksum 对 dict key 顺序稳定,供影子对账。"""
|
||||
left = [{'qty': 1, 'part_number': 'A'}]
|
||||
right = [{'part_number': 'A', 'qty': 1}]
|
||||
assert lines_checksum(left) == lines_checksum(right)
|
||||
|
||||
|
||||
def test_lines_checksum_normalizes_id_and_qty_types(app):
|
||||
"""checksum 忽略 reservation_id int/str 与 qty 1/1.0 的类型差异。"""
|
||||
left = [{'part_number': 'A', 'qty': 1, 'reservation_id': 3000092917, 'inventory_source_hint': 12}]
|
||||
right = [{'part_number': 'A', 'qty': 1.0, 'reservation_id': '3000092917', 'inventory_source_hint': '12'}]
|
||||
assert lines_checksum(left) == lines_checksum(right)
|
||||
|
||||
|
||||
def test_shadow_read_tolerates_unsaved_task(app):
|
||||
"""未落库任务(id=None)在 shadow/table 读路径不得抛 TypeError。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'shadow'
|
||||
task = ShippingTask(
|
||||
task_no='SN-UNSAVED',
|
||||
source_type='manual',
|
||||
process_status='parsed',
|
||||
lines_json=[{'part_number': 'A001', 'qty': 1}],
|
||||
)
|
||||
assert read_task_order_lines(task) == [{'part_number': 'A001', 'qty': 1}]
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'table'
|
||||
assert read_task_order_lines(task) == []
|
||||
|
||||
|
||||
def test_replace_rolls_back_when_commit_fails_after_dual_write(app):
|
||||
"""提交阶段失败时,两侧变更应随事务回滚(故障注入)。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _make_task(task_no='SN-FAULT-001', lines=[{'part_number': 'OLD', 'qty': 1}])
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
|
||||
replace_task_order_lines(task, [{'part_number': 'NEW', 'qty': 2}], normalize=False)
|
||||
with patch.object(db.session, 'commit', side_effect=RuntimeError('boom')):
|
||||
with pytest.raises(RuntimeError, match='boom'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
task = db.session.get(ShippingTask, task_id)
|
||||
assert task.lines_json == [{'part_number': 'OLD', 'qty': 1}]
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task_id).count() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('line', 'error'),
|
||||
[
|
||||
({'qty': 1}, 'missing part_number'),
|
||||
({'part_number': 'TEMP/D4', 'qty': 1}, 'non-atomic part_number'),
|
||||
({'part_number': 'D4', 'customer_part_number': 'C/1', 'qty': 1}, 'non-atomic customer_part_number'),
|
||||
({'part_number': 'D4', 'aws_part_number': 'AWS/1', 'qty': 1}, 'non-atomic aws_part_number'),
|
||||
],
|
||||
)
|
||||
def test_v2_store_rejects_missing_or_composite_part_numbers(app, line, error):
|
||||
"""v2 双写入口必须拒绝缺失或含 `/` 的任一料号,避免复合值进入规范投影。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
|
||||
task = _make_task(task_no=f"SN-V2-INVALID-{error[:8].upper()}")
|
||||
|
||||
with pytest.raises(ValueError, match=error):
|
||||
replace_task_order_lines(task, [line], normalize=False)
|
||||
db.session.rollback()
|
||||
|
||||
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
|
||||
@@ -1,240 +0,0 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_lines_migration.py
|
||||
|
||||
用途:验证规范订单行与冲突表迁移可升级/降级,以及模型级唯一与 qty 约束。
|
||||
依赖:Alembic Operations、SQLAlchemy、ShippingTaskLine 模型。
|
||||
逻辑:在最小 shipping_tasks/users 历史上执行 d5e6f7a8b9c0;再在 Flask app 内断言 ORM 约束。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskFieldConflict, ShippingTaskLine
|
||||
|
||||
|
||||
def _task_lines_pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建订单行迁移所需的最小历史表(含 connector 改名后的 shipping_tasks)。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_tasks',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('task_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('source_type', sa.String(length=32), nullable=False),
|
||||
sa.Column('process_status', sa.String(length=32), nullable=False),
|
||||
sa.Column('lines_json', sa.JSON(), nullable=True),
|
||||
sa.Column('inventory_connector_type', sa.String(length=32), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_shipping_task_lines_migration_upgrade_and_downgrade():
|
||||
"""d5e6f7a8b9c0 应建立规范行/冲突表与任务版本字段,并能完整回滚且不改 lines_json。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_task_lines_pre_migration_schema(engine)
|
||||
module = importlib.import_module(
|
||||
'migrations.versions.d5e6f7a8b9c0_shipping_task_lines_and_conflicts'
|
||||
)
|
||||
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
|
||||
original_op = module.op
|
||||
module.op = operations
|
||||
try:
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"INSERT INTO shipping_tasks "
|
||||
"(id, task_no, source_type, process_status, lines_json, created_at, updated_at) "
|
||||
"VALUES (1, 'SN-LINE-MIG-001', 'manual', 'parsed', :lines_json, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
),
|
||||
{'lines_json': '[{"sku":"A001","qty":1}]'},
|
||||
)
|
||||
module.upgrade()
|
||||
|
||||
inspector = sa.inspect(connection)
|
||||
assert {'shipping_task_lines', 'shipping_task_field_conflicts'} <= set(inspector.get_table_names())
|
||||
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
|
||||
assert {'order_data_version', 'order_lines_migration_status', 'lines_json'} <= task_columns
|
||||
|
||||
row = connection.execute(sa.text(
|
||||
"SELECT order_data_version, order_lines_migration_status, lines_json "
|
||||
"FROM shipping_tasks WHERE id = 1"
|
||||
)).one()
|
||||
assert row[0] == 1
|
||||
assert row[1] == 'pending'
|
||||
assert 'A001' in str(row[2])
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
with connection.begin_nested():
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_lines "
|
||||
"(id, task_id, position, sku, qty, schema_version, line_version, created_at, updated_at) "
|
||||
"VALUES (1, 1, 0, 'A001', 0, 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_lines "
|
||||
"(id, task_id, position, sku, qty, reservation_id, source_type, hub_code, "
|
||||
"extra_json, schema_version, line_version, created_at, updated_at) "
|
||||
"VALUES (1, 1, 0, 'A001', 1.5, '1000140351', 'DBS DUB', 'DUB1', "
|
||||
"'{\"legacy_note\":\"kept\"}', 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
with connection.begin_nested():
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_lines "
|
||||
"(id, task_id, position, sku, qty, schema_version, line_version, created_at, updated_at) "
|
||||
"VALUES (2, 1, 0, 'B001', 2, 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_field_conflicts "
|
||||
"(id, task_id, line_id, field_name, status, conflict_version, created_at, updated_at) "
|
||||
"VALUES (1, 1, NULL, 'customer_name', 'open', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
with connection.begin_nested():
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_field_conflicts "
|
||||
"(id, task_id, line_id, field_name, status, conflict_version, created_at, updated_at) "
|
||||
"VALUES (2, 1, NULL, 'customer_name', 'open', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
module.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_task_lines' not in inspector.get_table_names()
|
||||
assert 'shipping_task_field_conflicts' not in inspector.get_table_names()
|
||||
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
|
||||
assert 'order_data_version' not in task_columns
|
||||
assert 'order_lines_migration_status' not in task_columns
|
||||
assert 'lines_json' in task_columns
|
||||
preserved = connection.execute(sa.text(
|
||||
"SELECT lines_json FROM shipping_tasks WHERE id = 1"
|
||||
)).scalar()
|
||||
assert 'A001' in str(preserved)
|
||||
finally:
|
||||
module.op = original_op
|
||||
|
||||
|
||||
def test_shipping_task_line_orm_constraints_and_cascade(app):
|
||||
"""ORM 层应强制 qty>0、(task_id,position) 唯一,并在删除 Task 时级联清理行与冲突。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no='SN-LINE-ORM-001',
|
||||
source_type='manual',
|
||||
process_status='parsed',
|
||||
lines_json=[{'part_number': 'A001', 'qty': 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
line = ShippingTaskLine(
|
||||
task_id=int(task.id),
|
||||
position=0,
|
||||
part_number='A001',
|
||||
qty=Decimal('1'),
|
||||
reservation_id='1000140351',
|
||||
inventory_source_hint='DUB1',
|
||||
extra_json={'legacy_note': 'kept'},
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
conflict = ShippingTaskFieldConflict(
|
||||
task_id=int(task.id),
|
||||
line_id=int(line.id),
|
||||
position=0,
|
||||
field_name='reservation_id',
|
||||
existing_value='1000140351',
|
||||
incoming_value='3000092917',
|
||||
status='open',
|
||||
)
|
||||
db.session.add(conflict)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.add(ShippingTaskLine(
|
||||
task_id=int(task.id),
|
||||
position=0,
|
||||
part_number='B001',
|
||||
qty=Decimal('2'),
|
||||
))
|
||||
db.session.flush()
|
||||
db.session.rollback()
|
||||
|
||||
task = ShippingTask.query.filter_by(task_no='SN-LINE-ORM-001').one()
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
assert ShippingTaskLine.query.count() == 0
|
||||
assert ShippingTaskFieldConflict.query.count() == 0
|
||||
|
||||
|
||||
def test_shipping_task_line_v2_migration_is_destructive_and_reversible():
|
||||
"""v2 迁移应清空旧数据、切换新列和约束,并可恢复空的 v1 表结构。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_task_lines_pre_migration_schema(engine)
|
||||
v1 = importlib.import_module(
|
||||
'migrations.versions.d5e6f7a8b9c0_shipping_task_lines_and_conflicts'
|
||||
)
|
||||
v2 = importlib.import_module(
|
||||
'migrations.versions.0f7a8b9c0d1e_shipping_task_line_v2'
|
||||
)
|
||||
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
|
||||
original_v1_op = v1.op
|
||||
original_v2_op = v2.op
|
||||
v1.op = operations
|
||||
v2.op = operations
|
||||
try:
|
||||
v1.upgrade()
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_tasks "
|
||||
"(id, task_no, source_type, process_status, lines_json, order_data_version, "
|
||||
"order_lines_migration_status, created_at, updated_at) "
|
||||
"VALUES (1, 'SN-V2-MIG', 'manual', 'parsed', :lines_json, 1, 'synced', "
|
||||
"CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
), {'lines_json': '[{"sku":"OLD","qty":1}]'})
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_lines "
|
||||
"(id, task_id, position, sku, qty, schema_version, line_version, created_at, updated_at) "
|
||||
"VALUES (1, 1, 0, 'OLD', 1, 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
v2.upgrade()
|
||||
columns = {column['name'] for column in sa.inspect(connection).get_columns('shipping_task_lines')}
|
||||
assert {'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint'} <= columns
|
||||
assert not {'sku', 'vendor_part_number', 'customer_sku', 'source_type', 'hub_code'} & columns
|
||||
assert connection.execute(sa.text('SELECT COUNT(*) FROM shipping_task_lines')).scalar() == 0
|
||||
task_row = connection.execute(sa.text(
|
||||
'SELECT lines_json, order_lines_migration_status FROM shipping_tasks WHERE id = 1'
|
||||
)).one()
|
||||
assert str(task_row[0]) == '[]'
|
||||
assert task_row[1] == 'pending'
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
with connection.begin_nested():
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_lines "
|
||||
"(id, task_id, position, part_number, qty, schema_version, line_version, created_at, updated_at) "
|
||||
"VALUES (2, 1, 0, 'TEMP/D4', 1, 'shipping-task-line-v2', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
|
||||
))
|
||||
|
||||
v2.downgrade()
|
||||
downgraded = {column['name'] for column in sa.inspect(connection).get_columns('shipping_task_lines')}
|
||||
assert {'sku', 'vendor_part_number', 'customer_sku', 'source_type', 'hub_code'} <= downgraded
|
||||
assert not {'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint'} & downgraded
|
||||
finally:
|
||||
v1.op = original_v1_op
|
||||
v2.op = original_v2_op
|
||||
Reference in new issue
Block a user