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()
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user