feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议

This commit is contained in:
hugo committed 2026-07-18 11:41:02 +08:00
1 parent 46eb63f5bb
commit e9bdd81f1a
320 files changed
+28361 -10487

No files matched your search

+135 -19
View File
@@ -54,8 +54,8 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
def _shipping_notice_stable_auto_config(app, request, monkeypatch):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
tmp_path = request.getfixturevalue("tmp_path")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
)
if request.node.get_closest_marker("auto_rpa"):
@@ -132,12 +132,12 @@ def seed_task_inventory_source(
compute_routing_fingerprint,
extract_routing_context,
)
from app.services.shipping_notice.inventory_sources import (
get_inventory_source,
get_inventory_sources_config_version,
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
source = get_inventory_source(source_code)
source = get_database_inventory_source(source_code)
if not source:
raise ValueError(f"unknown inventory source for tests: {source_code}")
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
@@ -151,11 +151,10 @@ def seed_task_inventory_source(
identity = resolution.identity
task.inventory_source_code = identity.source_code
task.inventory_connector_type = identity.connector_type
task.inventory_site_id = identity.site_id
task.inventory_warehouse_id = identity.warehouse_id
task.inventory_source_status = "resolved"
task.inventory_source_method = "rule_exact"
task.inventory_source_config_version = get_inventory_sources_config_version()
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
@@ -184,9 +183,10 @@ def inventory_xlsx_with_warehouse(
warehouse_id: str,
*,
sku: str = "A001",
reservation_id: str = "R-1",
qty: int = 1,
) -> "BytesIO":
"""生成带 Warehouse ID 列的库存 Excel,供身份校验测试使用。"""
"""生成符合发布解析方案的库存 Excel,供身份、结构和库存解析测试使用。"""
from io import BytesIO
from openpyxl import Workbook
@@ -194,8 +194,8 @@ def inventory_xlsx_with_warehouse(
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "SKU", "Qty"])
ws.append([warehouse_id, sku, qty])
ws.append(["Warehouse ID", "SKU", "Reservation ID", "Qty"])
ws.append([warehouse_id, sku, reservation_id, qty])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -220,25 +220,23 @@ def inventory_csv_with_warehouse(
def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]:
"""构造 batch 成功回调 item 须携带的 Worker 身份字段。"""
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
return {
"source_code": str(task.inventory_source_code or ""),
"site_id": str(task.inventory_site_id or ""),
"warehouse_id": str(task.inventory_warehouse_id or ""),
}
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
"""构造定时 batch 成功回调 item 的四字段身份(与 YAML 配置一致)。"""
from app.services.shipping_notice.inventory_sources import get_inventory_source
"""构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。"""
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_inventory_source(source_code)
source = get_database_inventory_source(source_code)
if not source:
raise ValueError(f"unknown inventory source for tests: {source_code}")
item = {
"source_code": source_code,
"site_id": str(source.get("site_id") or ""),
"warehouse_id": str(source.get("warehouse_id") or ""),
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
}
item.update(overrides)
return item
@@ -258,7 +256,6 @@ def rpa_callback_payload(
"file_path": str(file_path),
"run_no": run_no,
"source_code": task.inventory_source_code,
"site_id": task.inventory_site_id,
"warehouse_id": task.inventory_warehouse_id,
}
@@ -281,11 +278,130 @@ def app():
app = create_app('testing')
with app.app_context():
db.create_all()
_seed_test_inventory_configuration()
yield app
db.session.remove()
db.drop_all()
def _seed_test_inventory_configuration() -> None:
"""为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。"""
from app import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition, ShippingInventorySource, ShippingRpaProfile,
)
from app.services.shipping_notice.inventory_structure_fingerprint import (
FINGERPRINT_VERSION,
compatibility_fingerprint,
exact_fingerprint,
structure_definition,
)
# 各测试显式创建所需用户字段;生产目录本身保持零预置。
if not ShippingInventoryField.query.filter_by(field_code='part_number').first():
db.session.add_all([
ShippingInventoryField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10),
ShippingInventoryField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20),
ShippingInventoryField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30),
ShippingInventoryField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40),
ShippingInventoryField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100),
ShippingInventoryField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110),
ShippingInventoryField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120),
ShippingInventoryField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130),
ShippingInventoryField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140),
])
db.session.flush()
inventory_fields = {
item.field_code: item
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_([
'part_number', 'reservation_id', 'available_qty', 'warehouse_id',
])
).all()
}
field_mapping = {
str(inventory_fields['part_number'].id): 'SKU',
str(inventory_fields['reservation_id'].id): 'Reservation ID',
str(inventory_fields['available_qty'].id): 'Qty',
str(inventory_fields['warehouse_id'].id): 'Warehouse ID',
}
# 测试专用稳定字段 ID 避免全局创建订单模板,后者会破坏订单模板初始化专项测试。
match_keys = [
{
'order_field_id': 'test-order-part-number',
'inventory_field_id': str(inventory_fields['part_number'].id),
},
{
'order_field_id': 'test-order-reservation-id',
'inventory_field_id': str(inventory_fields['reservation_id'].id),
},
]
definition = {
'sheet_name': 'Sheet',
'header_row_index': 1,
'field_mapping': field_mapping,
'match_keys': match_keys,
}
structure = structure_definition(
file_format='xlsx', sheet_name='Sheet', header_row_index=1,
headers=['Warehouse ID', 'SKU', 'Reservation ID', 'Qty'],
)
import hashlib
import json
checksum = hashlib.sha256(
json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
).hexdigest()
parsing_profile = ShippingInventoryParsingProfile(
profile_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published',
file_format='xlsx', definition_json=definition, checksum=checksum,
structure_definition_json=structure,
exact_structure_fingerprint=exact_fingerprint(structure),
compatibility_fingerprint=compatibility_fingerprint(
definition=structure, field_mapping=field_mapping, match_keys=match_keys,
),
fingerprint_version=FINGERPRINT_VERSION,
)
excel_template = ShippingExcelTemplate(
template_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published',
storage_provider='minio', storage_bucket='test', storage_key='test/runtime/template.xlsx',
original_filename='template.xlsx',
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
)
profile = ShippingRpaProfile(
profile_code='DBS_DUB_TEST', display_name='DBS Dublin', connector_type='dbs',
login_url='https://test.invalid/dbs', login_config_json={'auth_mode': 'password'},
)
source = ShippingInventorySource(
source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs',
rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU',
report_path_json={
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
},
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.commit()
@pytest.fixture
def client(app):
return app.test_client()