65 lines
2.7 KiB
Python
65 lines
2.7 KiB
Python
"""
|
|
services/shipping_notice/routing_facts.py
|
|
|
|
用途:构造库存源路由规则可读取的受控业务事实。
|
|
依赖:无 ORM 写入依赖;调用方传入已完成解析和标准化的任务/订单行数据。
|
|
逻辑:规则引擎只能通过本模块的白名单读取事实,避免管理端规则访问任意模型字段。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
|
|
ALLOWED_SYSTEM_FACT_KEYS = frozenset({
|
|
'task.customer_code', 'task.destination_country', 'task.destination_city', 'task.destination_port',
|
|
'task.warehouse_hint', 'task.order_type', 'task.sender_email', 'task.sender_domain',
|
|
'line.reservation_id', 'line.part_number', 'line.customer_part_number', 'line.aws_part_number',
|
|
'line.inventory_source_hint',
|
|
})
|
|
|
|
|
|
def build_routing_facts(*, task: Any, line: dict[str, Any] | None = None) -> dict[str, dict[str, Any]]:
|
|
"""
|
|
将任务和订单行投影为路由规则可读取的稳定事实。
|
|
|
|
Args:
|
|
task: ShippingTask 或提供同名属性的对象。
|
|
line: 单条规范订单行;任务级规则传 None。
|
|
|
|
Returns:
|
|
dict: 使用 task/line 两层命名空间的只读事实字典。
|
|
"""
|
|
line_data = dict(line or {})
|
|
sender_email = str(getattr(task, 'sender_email', '') or '').strip().lower()
|
|
sender_domain = sender_email.rsplit('@', 1)[-1] if '@' in sender_email else ''
|
|
return {
|
|
'task': {
|
|
'customer_code': str(getattr(task, 'customer_code', '') or '').strip().upper(),
|
|
'destination_country': str(getattr(task, 'destination_country', '') or '').strip().upper(),
|
|
'destination_city': str(getattr(task, 'destination_city', '') or '').strip().upper(),
|
|
'destination_port': str(getattr(task, 'destination_code', '') or '').strip().upper(),
|
|
'warehouse_hint': str(getattr(task, 'warehouse_hint', '') or '').strip().upper(),
|
|
'order_type': str(getattr(task, 'order_type', '') or '').strip().upper(),
|
|
'sender_email': sender_email,
|
|
'sender_domain': sender_domain,
|
|
},
|
|
'line': {
|
|
key: str(line_data.get(key) or '').strip().upper()
|
|
for key in ('reservation_id', 'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint')
|
|
},
|
|
}
|
|
|
|
|
|
def read_system_fact(facts: dict[str, dict[str, Any]], fact_path: str) -> Any:
|
|
"""
|
|
读取白名单路由事实。
|
|
|
|
Raises:
|
|
KeyError: 规则引用未注册字段时抛出,调用方应拒绝发布或执行该规则。
|
|
"""
|
|
if fact_path not in ALLOWED_SYSTEM_FACT_KEYS:
|
|
raise KeyError(f'Unsupported routing fact: {fact_path}')
|
|
namespace, field = fact_path.split('.', 1)
|
|
return facts.get(namespace, {}).get(field)
|