refactor(shipping-notice): 统一料号字段,移除过时的 SKU 相关字段,更新相关逻辑以支持新字段命名

This commit is contained in:
hugo committed 2026-07-16 20:02:33 +08:00
1 parent dde25344ca
commit 46eb63f5bb
111 files changed
+3116 -1250

No files matched your search

@@ -28,6 +28,7 @@ from app.services.shipping_notice.inventory_rpa_workflow import (
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory, parse_inventory, upload_inventory_file
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.task_workflow import retry_task
def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, ShippingCustomer, User]:
@@ -46,7 +47,8 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, ShippingCustome
task_no=f'SN-GATE-{user.id}', user_id=user.id,
shipping_case_id=case.id if case else None,
customer_resolution_status='pending' if case else None,
process_status='parsed', lines_json=[{'sku': 'A001', 'quantity': 1}],
process_status='parsed',
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
inventory_source_status='user_confirmed', inventory_source_code='DSV',
)
db.session.add(task)
@@ -92,6 +94,22 @@ def test_pending_customer_blocks_every_downstream_entry(app):
assert task.upload_status is None
def test_pending_customer_blocks_retry_before_clearing_review_state(app):
"""重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。"""
with app.app_context():
task, _customer, _user = _seed_task()
task.pending_human_reason = 'customer_unconfirmed'
task.error_message = '标准客户尚未确认'
db.session.commit()
result = retry_task({'task_id': task.task_no})
_assert_customer_gate_response(result)
db.session.refresh(task)
assert task.pending_human_reason == 'customer_unconfirmed'
assert task.error_message == '标准客户尚未确认'
def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
"""客户确认同步同业务单全部任务,并在同事务生成正式业务号。"""
with app.app_context():
@@ -649,7 +649,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
process_status="parsed",
parse_confidence=0.95,
raw_content="客户:ACME\nA001 x 10",
lines_json=[{"sku": "A001", "qty": 10}],
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
current_step="step2_parse_confirm",
step_payload_json={
"rpa_inventory_source": {
@@ -759,7 +759,7 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p
parse_confidence=0.95,
raw_content="Ship to Dublin DUB\nA001 x 10",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 10}],
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}},
)
db.session.add(task)
@@ -928,7 +928,7 @@ def test_parse_stage_ui_state_lists_all_issues(app):
"issues": [
{
"line_index": 0,
"sku": "A001",
"part_number": "A001",
"field": "reservation_id",
"reason": "invalid_format",
"severity": "blocking",
@@ -954,7 +954,7 @@ def test_parse_stage_ui_state_lists_all_issues(app):
assert issues[0] == "无法根据发货通知唯一确定库存查询来源"
assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
assert "第 1 行 SKU A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
assert "第 1 行料号 A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
assert len(issues) == 5
@@ -97,7 +97,7 @@ def test_business_fingerprint_ignores_internal_hex_reservation_id():
'reservation_ids': ['1f1a682dfdc446a393415dee93eb36ce'],
'lines': [
{
'sku': 'A001',
'part_number': 'A001',
'qty': 1,
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
}
@@ -116,15 +116,15 @@ def test_fingerprint_stable_across_line_order():
'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
'required_date': '2026-01-01',
'lines': [
{'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
{'part_number': 'B', 'qty': 2, 'reservation_id': '1000000001'},
{'part_number': 'A', 'qty': 1, 'reservation_id': '1000000002'},
],
}
swapped = {
**base,
'lines': [
{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
{'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
{'part_number': 'A', 'qty': 1, 'reservation_id': '1000000002'},
{'part_number': 'B', 'qty': 2, 'reservation_id': '1000000001'},
],
}
a = build_business_fingerprint(base)
@@ -138,9 +138,9 @@ def test_fingerprint_changes_with_qty():
'customer_code': 'C1',
'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
'required_date': '2026-01-01',
'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'}],
'lines': [{'part_number': 'A', 'qty': 1, 'reservation_id': '1000000002'}],
}
changed = {**base, 'lines': [{'sku': 'A', 'qty': 9, 'reservation_id': '1000000002'}]}
changed = {**base, 'lines': [{'part_number': 'A', 'qty': 9, 'reservation_id': '1000000002'}]}
assert build_business_fingerprint(base)['fingerprint'] != build_business_fingerprint(changed)['fingerprint']
@@ -264,7 +264,7 @@ def test_create_revision_sets_supersedes_and_version(app, dedup_user, monkeypatc
'customer_code': 'C1',
'po_number': 'PO-REV-1',
'reservation_ids': ['12345678'],
'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '12345678'}],
'lines': [{'part_number': 'A', 'qty': 1, 'reservation_id': '12345678'}],
}
fp = build_business_fingerprint(summary)
asset, intake = _seed_parsed_intake(
@@ -384,7 +384,7 @@ def test_fingerprint_strong_with_customer_name_po_reservation():
'customer_code': None,
'po_number': 'PO-20260714',
'reservation_ids': ['1000140351'],
'lines': [{'sku': 'SKU001', 'qty': 10, 'reservation_id': '1000140351'}],
'lines': [{'part_number': 'SKU001', 'qty': 10, 'reservation_id': '1000140351'}],
}
fp = build_business_fingerprint(summary)
assert fp['strength'] == 'strong'
@@ -488,7 +488,7 @@ def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
dedup_user.id,
intake_no='SNI-POSSIBLE-1',
hash_value='hash-possible-1',
business_summary={'customer_name': 'X', 'lines': [{'sku': 'A', 'qty': 1}]},
business_summary={'customer_name': 'X', 'lines': [{'part_number': 'A', 'qty': 1}]},
fingerprint={'fingerprint': 'weakfp', 'version': 'shipping-v1', 'strength': 'weak'},
)
intake.duplicate_status = 'possible_duplicate'
@@ -786,7 +786,7 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
'lines': [
{
'reservation_id': '2000485916',
'sku': '504-006043-001',
'part_number': '504-006043-001',
'qty': 30,
'uom': 'EA',
}
@@ -855,11 +855,11 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
assert candidate.content_fingerprint == revision['content_fingerprint']
assert candidate.content_fingerprint != content['fingerprint']
source_type_changed = {
inventory_source_changed = {
**base,
'lines': [{**base['lines'][0], 'source_type': 'DBS DUB'}],
'lines': [{**base['lines'][0], 'inventory_source_hint': 'DBS DUB'}],
}
assert build_content_fingerprint(source_type_changed)['fingerprint'] != content['fingerprint']
assert build_content_fingerprint(inventory_source_changed)['fingerprint'] != content['fingerprint']
header_date_changed = {**base, 'required_date': '2026-07-20'}
assert build_content_fingerprint(header_date_changed)['fingerprint'] != content['fingerprint']
@@ -108,27 +108,34 @@ def _order_extraction_pre_migration_schema(engine: sa.Engine) -> None:
def test_order_extraction_state_migration_upgrade_and_downgrade():
"""e0f1 迁移应增加抽取状态、多订单键并可在单候选场景完整降级。"""
"""订单状态迁移后应移除废弃发布标记,并可在单候选场景完整降级。"""
engine = sa.create_engine('sqlite:///:memory:')
_order_extraction_pre_migration_schema(engine)
migration = importlib.import_module(
state_migration = importlib.import_module(
'migrations.versions.e0f1a2b3c4d5_shipping_order_extraction_state'
)
removal_migration = importlib.import_module(
'migrations.versions.1a2b3c4d5e6f_remove_shipping_order_extraction_contract_version'
)
with engine.begin() as connection:
connection.execute(sa.text(
"INSERT INTO shipping_notice_candidates "
"(id, candidate_no, intake_id, primary_document_id) VALUES (1, 'SNC-1', 10, 20)"
))
operations = Operations(MigrationContext.configure(connection))
original_op = migration.op
migration.op = operations
original_state_op = state_migration.op
original_removal_op = removal_migration.op
state_migration.op = operations
removal_migration.op = operations
try:
migration.upgrade()
state_migration.upgrade()
removal_migration.upgrade()
inspector = sa.inspect(connection)
intake_columns = {column['name'] for column in inspector.get_columns('shipping_notice_intakes')}
document_columns = {column['name'] for column in inspector.get_columns('shipping_notice_documents')}
candidate_columns = {column['name'] for column in inspector.get_columns('shipping_notice_candidates')}
assert {'order_extraction_status', 'order_extraction_version'} <= intake_columns
assert 'order_extraction_status' in intake_columns
assert 'order_extraction_version' not in intake_columns
assert {'order_extraction_status', 'order_extraction_result_json'} <= document_columns
assert {'candidate_key', 'source_order_index', 'evidence_json'} <= candidate_columns
row = connection.execute(sa.text(
@@ -139,7 +146,8 @@ def test_order_extraction_state_migration_upgrade_and_downgrade():
item['name'] for item in inspector.get_unique_constraints('shipping_notice_candidates')
}
migration.downgrade()
removal_migration.downgrade()
state_migration.downgrade()
inspector = sa.inspect(connection)
assert 'order_extraction_status' not in {
column['name'] for column in inspector.get_columns('shipping_notice_intakes')
@@ -148,7 +156,8 @@ def test_order_extraction_state_migration_upgrade_and_downgrade():
column['name'] for column in inspector.get_columns('shipping_notice_candidates')
}
finally:
migration.op = original_op
state_migration.op = original_state_op
removal_migration.op = original_removal_op
def test_order_extraction_state_migration_rejects_unsafe_multi_candidate_downgrade():
+90 -40
View File
@@ -1,6 +1,8 @@
from email.message import EmailMessage
from pathlib import Path
import pytest
from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract
from app.services.shipping_notice.order_candidate_builder import (
build_email_order_index,
@@ -123,6 +125,8 @@ def test_extract_notice_text_reads_xfa_pdf_datasets():
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf_path = Path(__file__).resolve().parents[2] / "docs" / "prototype" / "4510038672.pdf"
if not pdf_path.exists():
pytest.skip("XFA PDF fixture docs/prototype/4510038672.pdf is not present")
text, meta = extract_notice_text(pdf_path)
assert meta["file_type"] == "pdf"
@@ -146,19 +150,18 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
assert len(rows) == 3
assert rows[0]['po_number'] == '4510039227'
assert rows[0]['reservation_id'] == '2000485916'
assert rows[0]['sku'] == '504-006043-001'
assert rows[0]['part_number'] == 'D4-A08AR12000001'
assert rows[0]['qty'] == 30
assert rows[0]['source_type'] == 'VMI-FRA01'
assert rows[0]['customer_sku'] == 'TEMP-S000218922'
assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001'
assert rows[0]['hub_code'] == 'FRA01'
assert rows[2]['hub_code'] == 'DUB'
assert rows[0]['inventory_source_hint'] == 'VMI-FRA01'
assert rows[0]['customer_part_number'] == 'TEMP-S000218922'
assert rows[0]['aws_part_number'] == '504-006043-001'
assert rows[2]['inventory_source_hint'] == 'DBS DUB'
fused = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30, 'uom': 'EA'}],
'lines': [{'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', 'qty': 30, 'uom': 'EA'}],
},
filename='4510039227.pdf',
body_rows=rows,
@@ -166,15 +169,15 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
line = fused['business_summary']['lines'][0]
assert fused['validation_status'] == 'ready'
assert not fused['conflicts']
assert line['source_type'] == 'VMI-FRA01'
assert line['customer_sku'] == 'TEMP-S000218922'
assert line['hub_code'] == 'FRA01'
assert line['inventory_source_hint'] == 'VMI-FRA01'
assert line['customer_part_number'] == 'TEMP-S000218922'
assert line['aws_part_number'] == '504-006043-001'
conflict = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 20, 'uom': 'EA'}],
'lines': [{'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', 'qty': 20, 'uom': 'EA'}],
},
filename='4510039227.pdf',
body_rows=rows,
@@ -187,16 +190,16 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
'po_number': '4510039227',
'reservation_ids': ['OTHER', '2000485916'],
'lines': [
{'reservation_id': 'OTHER', 'sku': 'OTHER-SKU', 'qty': 5},
{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30},
{'reservation_id': 'OTHER', 'part_number': 'OTHER-SKU', 'qty': 5},
{'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', 'qty': 30},
],
},
filename='4510039227.pdf',
body_rows=rows,
)
assert multi_line['validation_status'] == 'ready'
assert 'source_type' not in multi_line['business_summary']['lines'][0]
assert multi_line['business_summary']['lines'][1]['source_type'] == 'VMI-FRA01'
assert 'inventory_source_hint' not in multi_line['business_summary']['lines'][0]
assert multi_line['business_summary']['lines'][1]['inventory_source_hint'] == 'VMI-FRA01'
def test_extract_eml_with_three_pdf_attachments(tmp_path):
@@ -1236,8 +1239,8 @@ def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evid
)
lines = [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"vendor_part_number": "D4-A08AR12000002",
"part_number": "D4-A08AR12000002",
"customer_part_number": "TEMP-S000218929",
"qty": 10,
"uom": "EA",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
@@ -1251,7 +1254,7 @@ def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evid
assert issues == [
{
"line_index": 0,
"sku": "TEMP-S000218929/D4-A08AR12000002",
"part_number": "D4-A08AR12000002",
"field": "reservation_id",
"reason": "value_corrected",
"severity": "info",
@@ -1270,7 +1273,7 @@ def test_flattened_text_does_not_guess_external_reservation_id():
)
lines = [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"part_number": "D4-A08AR12000002",
"qty": 10,
"uom": "EA",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
@@ -1287,8 +1290,8 @@ def test_flattened_text_does_not_guess_external_reservation_id():
def test_adjudication_supports_non_numeric_reservation_templates():
"""不同来源模板可使用字母型 Reservation ID,后端只排除内部 ID,不绑定单一数字模板。"""
raw_text = "AWS Sku\tReservation Order\tQty\nA001\tAWS-311\t2"
lines = [{"sku": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
raw_text = "Part Number\tReservation Order\tQty\nA001\tAWS-311\t2"
lines = [{"part_number": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
@@ -1306,14 +1309,14 @@ Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tA
"""
lines = parse_notice_table_text(text)
assert len(lines) == 1
assert lines[0]["sku"] == "504-010213-001"
assert lines[0]["part_number"] == "B3-A08AR11000001"
assert lines[0]["line_no"] == "10"
assert lines[0]["qty"] == 9.0
assert lines[0]["unit_price"] == 1607.72
assert lines[0]["amount"] == 14469.48
assert lines[0]["reservation_id"] == "1000140351"
assert lines[0]["required_date"] == "2026-06-15"
assert lines[0]["vendor_part_number"] == "B3-A08AR11000001"
assert lines[0]["aws_part_number"] == "504-010213-001"
assert lines[0]["currency"] == "USD"
@@ -1325,7 +1328,7 @@ def test_normalize_reservation_id_from_excel_float():
def test_parse_notice_table_numeric_reservation_id():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
Part Number\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\t1000140351\t2\t15.5\t31.0
"""
lines = parse_notice_table_text(text)
@@ -1333,7 +1336,7 @@ AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
def test_infer_reservation_id_without_header():
headers = ["AWS Sku", "Ref", "Qty"]
headers = ["Part Number", "Ref", "Qty"]
rows = [["10-40594-001", 1000140351, 2]]
lines = parse_notice_table_rows(headers, rows)
assert lines[0]["reservation_id"] == "1000140351"
@@ -1341,13 +1344,13 @@ def test_infer_reservation_id_without_header():
def test_parse_notice_table_with_all_fields():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
Part Number\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\tAWS-311\t2\t15.5\t31.0
10-40594-002\tORD-3002\t1\t20\t20
"""
lines = parse_notice_table_text(text)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["part_number"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["qty"] == 2
assert lines[0]["unit_price"] == 15.5
@@ -1362,14 +1365,15 @@ def test_normalize_notice_line_aliases():
"com_id": "COM-99",
"price": "12.5",
"delivery_date": "2026/06/15",
"vendorPartNumber": "VND-001",
"customer_part_number": "CUST-001",
"aws_part_number": "AWS-001",
"currency": "USD",
"line_no": "10",
}
)
assert line == {
"line_no": "10",
"sku": "A-001",
"part_number": "A-001",
"qty": 3.0,
"uom": "EA",
"reservation_id": "COM-99",
@@ -1377,17 +1381,63 @@ def test_normalize_notice_line_aliases():
"amount": 37.5,
"currency": "USD",
"required_date": "2026-06-15",
"vendor_part_number": "VND-001",
"customer_part_number": "CUST-001",
"aws_part_number": "AWS-001",
}
def test_normalize_notice_line_splits_frozen_temp_composite():
"""TEMP 二段复合文本应拆为客户料号和内部料号,禁止把组合值持久化。"""
line = normalize_notice_line({
"part_number": "TEMP-S000218929/D4-A08AR12000002",
"qty": 10,
})
assert line is not None
assert line["part_number"] == "D4-A08AR12000002"
assert line["customer_part_number"] == "TEMP-S000218929"
@pytest.mark.parametrize(
"value",
["LEFT/RIGHT", "TEMP-A/D4-B/THIRD", "TEMP-A/TEMP-B"],
)
def test_normalize_notice_line_rejects_ambiguous_composite(value):
"""未命中冻结规则的复合料号不得猜测角色或生成有效订单行。"""
assert normalize_notice_line({"part_number": value, "qty": 1}) is None
def test_parse_notice_table_maps_three_part_number_roles():
"""MPN、Allocated HHPN 与 Allocated APN 必须分别进入内部、客户和 AWS 料号。"""
lines = parse_notice_table_rows(
["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"],
[["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]],
)
assert lines == [{
"part_number": "D4-A08AR12000002",
"customer_part_number": "TEMP-S000218929",
"aws_part_number": "504-006055-001",
"qty": 10.0,
"uom": "EA",
}]
def test_parse_notice_table_rejects_aws_only_as_internal_part_number():
"""只有 AWS Sku 的表格缺少内部料号,不能生成可建单订单行。"""
assert parse_notice_table_rows(
["AWS Sku", "Reservation ID", "Qty"],
[["504-006055-001", "3000092917", 10]],
) == []
def test_enrich_notice_with_document_currency():
from app.services.shipping_notice.notice_lines import enrich_notice_with_document_currency
parsed = enrich_notice_with_document_currency(
{
"currency": "USD",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "currency": "EUR", "uom": "EA"}],
"lines": [{"part_number": "A-001", "qty": 1, "uom": "EA"}, {"part_number": "B-002", "qty": 2, "currency": "EUR", "uom": "EA"}],
}
)
assert parsed["lines"][0]["currency"] == "USD"
@@ -1408,7 +1458,7 @@ def test_enrich_notice_with_document_required_date():
parsed = enrich_notice_with_document_required_date(
{
"required_date": "2026-06-20",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "required_date": "2026-06-18", "uom": "EA"}],
"lines": [{"part_number": "A-001", "qty": 1, "uom": "EA"}, {"part_number": "B-002", "qty": 2, "required_date": "2026-06-18", "uom": "EA"}],
}
)
assert parsed["lines"][0]["required_date"] == "2026-06-20"
@@ -1420,7 +1470,7 @@ def test_extract_notice_fields_structured():
"customer_name": "ACME",
"lines": [
{
"sku": "10-40594-001",
"part_number": "10-40594-001",
"qty": 2,
"reservation_id": "AWS-311",
"unit_price": 10,
@@ -1437,7 +1487,7 @@ def test_extract_notice_fields_structured():
def test_validate_notice_lines_missing_reservation():
warnings = validate_notice_lines([{"sku": "A001", "qty": 1, "uom": "EA"}])
warnings = validate_notice_lines([{"part_number": "A001", "qty": 1, "uom": "EA"}])
assert any("Reservation ID" in w for w in warnings)
assert any("阻断后续库存匹配" in w for w in warnings)
@@ -1447,12 +1497,12 @@ def test_heuristic_table_skips_title_row():
text = """
Shipping Notice
AWS Sku\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
10-40594-001\tORD-3002\t4\t5\t20
"""
parsed, confidence, _ = _heuristic_extract(text)
assert len(parsed["lines"]) == 1
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert parsed["lines"][0]["part_number"] == "10-40594-001"
assert parsed["lines"][0]["reservation_id"] == "ORD-3002"
assert parsed["lines"][0]["qty"] == 4
assert parsed["lines"][0]["unit_price"] == 5
@@ -1464,7 +1514,7 @@ def test_extract_notice_fields_structured_over_heuristic():
"""Dify 传入 structured 时应直接使用,不走启发式。"""
structured = {
"customer_name": "ACME",
"lines": [{"sku": "SKU-DIFY", "qty": 3, "uom": "EA"}],
"lines": [{"part_number": "SKU-DIFY", "qty": 3, "uom": "EA"}],
"confidence": 0.95,
}
parsed, confidence, warnings = extract_notice_fields(
@@ -1472,15 +1522,15 @@ def test_extract_notice_fields_structured_over_heuristic():
structured=structured,
)
assert parsed["parse_source"] == "dify"
assert parsed["lines"][0]["sku"] == "SKU-DIFY"
assert parsed["lines"][0]["part_number"] == "SKU-DIFY"
assert confidence > 0.8
assert "parse_fallback_heuristic" not in warnings
def test_extract_notice_fields_heuristic_fallback():
"""无 structured 时走后端启发式兜底。"""
text = "AWS Sku\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
parsed, _, warnings = extract_notice_fields(raw_text=text)
assert parsed["parse_source"] == "heuristic"
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert parsed["lines"][0]["part_number"] == "10-40594-001"
assert "parse_fallback_heuristic" in warnings
@@ -0,0 +1,168 @@
"""
tests/test_shipping_notice_field_adjudication.py
用途:锁定后端规则解析与 Dify LLM Observation 的字段级交叉裁决规则。
依赖:field_adjudication、ShippingNoticeDocument 测试替身。
逻辑:覆盖单侧采用、共识、可信冲突、分差决策及不可变 Observation 审计。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.field_adjudication import (
adjudicate_order_fields,
merge_observation_history,
trusted_required_fields,
)
def _document(document_id: int, text: str):
"""构造裁决服务所需的最小 Document 测试替身。"""
return SimpleNamespace(id=document_id, extracted_text=text)
def _raw_order(*, line: dict, document_id: int, evidence: bool = True) -> dict:
"""构造一条 Dify Observation 输入,可选择是否提供逐字可信证据。"""
items = []
if evidence:
items = [
{
"field": "lines[0].part_number",
"quote": str(line.get("part_number") or ""),
"document_id": document_id,
},
{
"field": "lines[0].qty",
"quote": f"Qty {line.get('qty')}",
"document_id": document_id,
},
]
return {
"lines": [line],
"evidence": items,
"field_confidence": {"part_number": 0.99, "qty": 0.99},
}
def test_adjudication_uses_verified_dify_when_backend_has_no_table():
"""只有 Dify 有可信字段时应采用,并保留 Dify Observation。"""
document = _document(1, "Email D4-A08AR12000002 Qty 10")
line = {"part_number": "D4-A08AR12000002", "qty": 10}
raw_order = _raw_order(line=line, document_id=1)
result = adjudicate_order_fields(
{"lines": [line]},
raw_order=raw_order,
documents=[document],
field_confidence=raw_order["field_confidence"],
)
assert result["summary"]["lines"][0]["part_number"] == "D4-A08AR12000002"
assert trusted_required_fields(result) is True
assert {item["source"] for item in result["observations"]} == {"dify_llm"}
def test_adjudication_uses_backend_when_dify_field_is_missing():
"""Dify 缺内部料号但后端表格列关系明确时,应采用后端 Observation。"""
document = _document(1, "MPN\tQty\nD4-A08AR12000002\t10")
raw_order = {"lines": [{"qty": 10}], "evidence": [], "field_confidence": {}}
result = adjudicate_order_fields(
{"lines": [{"qty": 10}]},
raw_order=raw_order,
documents=[document],
)
assert result["summary"]["lines"][0]["part_number"] == "D4-A08AR12000002"
assert trusted_required_fields(result) is True
assert any(item["source"] == "backend_table" for item in result["observations"])
def test_adjudication_marks_consensus_without_overwriting_observations():
"""双方一致时规范值标记 consensus,并同时保留两侧 Observation。"""
document = _document(1, "MPN\tQty\nD4-A08AR12000002\t10")
line = {"part_number": "D4-A08AR12000002", "qty": 10}
raw_order = _raw_order(line=line, document_id=1)
result = adjudicate_order_fields(
{"lines": [line]},
raw_order=raw_order,
documents=[document],
field_confidence=raw_order["field_confidence"],
)
decision = next(item for item in result["decisions"] if item["field"] == "part_number")
assert decision["status"] == "consensus"
assert {item["source"] for item in result["observations"] if item["field"] == "part_number"} == {
"backend_table",
"dify_llm",
}
def test_adjudication_blocks_two_trusted_different_values():
"""双方证据都可信但字段不同必须生成 blocking 冲突,禁止静默覆盖。"""
document = _document(
1,
"MPN\tQty\nD4-BACKEND\t10\nLLM evidence D4-DIFY Qty 10",
)
line = {"part_number": "D4-DIFY", "qty": 10}
raw_order = _raw_order(line=line, document_id=1)
result = adjudicate_order_fields(
{"lines": [line]},
raw_order=raw_order,
documents=[document],
field_confidence=raw_order["field_confidence"],
)
conflict = next(item for item in result["conflicts"] if item["field"] == "part_number")
assert conflict["severity"] == "blocking"
assert conflict["reason"] == "cross_source_conflict"
assert trusted_required_fields(result) is False
def test_adjudication_prefers_backend_when_dify_quote_is_unverified():
"""Dify 无可信 quote 且与后端不同,分差足够时应采用后端值而不产生冲突。"""
document = _document(1, "MPN\tQty\nD4-BACKEND\t10")
line = {"part_number": "D4-DIFY", "qty": 10}
raw_order = _raw_order(line=line, document_id=1, evidence=False)
result = adjudicate_order_fields(
{"lines": [line]},
raw_order=raw_order,
documents=[document],
field_confidence=raw_order["field_confidence"],
)
assert result["summary"]["lines"][0]["part_number"] == "D4-BACKEND"
assert not [item for item in result["conflicts"] if item["field"] == "part_number"]
assert len([item for item in result["observations"] if item["field"] == "part_number"]) == 2
def test_adjudication_builds_multiple_lines_from_backend_only():
"""Dify 未产出行但后端有多行表格时,应逐行生成规范投影而非丢弃。"""
document = _document(
1,
"MPN\tQty\tReservation ID\nD4-A\t10\tR-1\nD4-B\t20\tR-2",
)
result = adjudicate_order_fields(
{"lines": []},
raw_order={"lines": [], "evidence": []},
documents=[document],
)
assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"]
assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["R-1", "R-2"]
assert trusted_required_fields(result) is True
def test_observation_history_is_append_only_and_deduplicated():
"""重裁决必须保留旧 Observation,并按稳定 ID 去重当前重复项。"""
old = {"observation_id": "old", "value": "D4-OLD"}
current = {"observation_id": "current", "value": "D4-NEW"}
merged = merge_observation_history([old], [old, current])
assert merged == [old, current]
@@ -16,16 +16,17 @@ def test_format_field_alignment_summary_single_block():
"match_rule_source": "llm",
"inventory_columns": {
"mapping": {
"sku": {"source_column": "AWS Sku"},
"part_number": {"source_column": "Supplier Sku"},
"aws_part_number": {"source_column": "AWS Sku"},
"reservation_id": {"source_column": "Reservation Order"},
"available_qty": {"source_column": "Qty Available"},
}
},
"sample_notice_lines": [
{"sku": "504-010213-001", "reservation_id": "1000140351", "qty": 9},
{"part_number": "D4-A", "aws_part_number": "504-010213-001", "reservation_id": "1000140351", "qty": 9},
],
"sample_inventory_lines": [
{"sku": "504-010213-001", "reservation_id": "1000140351", "available_qty": 12},
{"part_number": "D4-A", "aws_part_number": "504-010213-001", "reservation_id": "1000140351", "available_qty": 12},
],
"inventory_row_count": 120,
"notice_line_count": 1,
@@ -40,14 +41,14 @@ def test_format_field_alignment_summary_single_block():
assert "【库存字段对齐确认" in text
assert "SN-20260602-AB12CD34" in text
assert "| 预订单号 | `Reservation Order` | 预订单号 |" in text
assert "| 料号 | `AWS Sku` | 料号 |" in text
assert "| 内部料号 | `Supplier Sku` | 内部料号 |" in text
rid_idx = text.index("| 预订单号 |")
sku_idx = text.index("| 料号 | `AWS Sku`")
sku_idx = text.index("| 内部料号 | `Supplier Sku`")
assert rid_idx < sku_idx
assert "(LLM 推断)" in text
assert "订单样例:" in text
assert "预订单号 1000140351" in text
assert "料号 504-010213-001" in text
assert "内部料号 D4-A" in text
assert "请核对字段对齐后使用下方按钮继续" in text
assert "回复「确认」进入匹配" not in text
@@ -109,7 +109,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
structured_result_json={
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': 'R-1', 'sku': 'SKU-1', 'qty': 1}],
'lines': [{'reservation_id': 'R-1', 'part_number': 'SKU-1', 'qty': 1}],
},
},
validation_status='needs_review',
@@ -131,7 +131,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
'selected': False,
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': 'R-1', 'sku': 'SKU-1', 'qty': 2}],
'lines': [{'reservation_id': 'R-1', 'part_number': 'SKU-1', 'qty': 2}],
},
},
headers=owner_headers,
@@ -186,7 +186,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
"""人工修订不得以空摘要或无效 SKU/Qty 绕过 Candidate 审核门禁。"""
"""人工修订不得以空摘要或无效 part_number/Qty 绕过 Candidate 审核门禁。"""
from app.core.auth.jwt import issue_local_access_token
with app.app_context():
@@ -235,7 +235,7 @@ def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='test:SNC-CANDIDATE-VALIDATION',
structured_result_json={'business_summary': {'lines': [{'sku': 'SKU-1', 'qty': 1}]}},
structured_result_json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 1}]}},
validation_status='needs_review',
selected=True,
)
@@ -253,7 +253,7 @@ def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
invalid_qty = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': {'lines': [{'sku': 'SKU-1', 'qty': 0}]}},
json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 0}]}},
headers=headers,
)
assert invalid_qty.status_code == 400
@@ -264,7 +264,7 @@ def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
'business_summary': {
'lines': [
{
'sku': 'SKU-1',
'part_number': 'SKU-1',
'qty': 1,
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
}
@@ -336,7 +336,7 @@ def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app
)
db.session.add(document)
db.session.flush()
summary = {'po_number': f'PO-{index}', 'lines': [{'sku': f'SKU-{index}', 'qty': index}]}
summary = {'po_number': f'PO-{index}', 'lines': [{'part_number': f'SKU-{index}', 'qty': index}]}
candidate = ShippingNoticeCandidate(
candidate_no=f'SNC-CANDIDATE-GATE-{index}',
intake_id=intake.id,
@@ -520,7 +520,7 @@ def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping
'lines': [
{
'reservation_id': f'20004859{index:02d}',
'sku': f'SKU-{index}',
'part_number': f'SKU-{index}',
'qty': index,
'uom': 'EA',
}
@@ -18,8 +18,8 @@ def _write_title_row_inventory_xlsx(path: Path) -> None:
ws = wb.active
ws.append(["AWS DUB On Hand Inventory by Location"])
ws.append([])
ws.append(["AWS Sku", "COM ID", "Qty Available", "Qty"])
ws.append(["10-40594-001", "AWS-311", 2, 1])
ws.append(["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "Qty"])
ws.append(["D4-A08AR12000002", "10-40594-001", "AWS-311", 2, 1])
wb.save(str(path))
wb.close()
@@ -28,10 +28,10 @@ def _write_header_index_mismatch_xlsx(path: Path) -> None:
wb = Workbook()
ws = wb.active
ws.append(["Inventory Report"])
ws.append(["AWS Sku", "Qty"])
ws.append(["Supplier Sku", "Qty"])
ws.append(["EARLY-001", 7])
ws.append([])
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["Supplier Sku", "COM ID", "Qty Available"])
ws.append(["LATE-001", "ORD-1", 5])
wb.save(str(path))
wb.close()
@@ -43,22 +43,26 @@ def test_read_inventory_schema_preview_skips_title_row(app, tmp_path):
with app.app_context():
preview = read_inventory_schema_preview(path)
assert preview["header_row_index"] == 3
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available", "Qty"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
assert preview["headers"] == ["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "Qty"]
assert preview["suggested_mapping"]["part_number"] == "Supplier Sku"
assert preview["suggested_mapping"]["aws_part_number"] == "AWS Sku"
assert preview["suggested_mapping"]["available_qty"] == "Qty Available"
assert preview["sample_rows"][0][0] == "10-40594-001"
assert preview["mapping_targets"]["reservation_id"] == "Reservation ID / COM ID(必填)"
assert preview["sample_rows"][0][0] == "D4-A08AR12000002"
assert preview["sample_rows"][0][1] == "10-40594-001"
def test_parse_aws_inventory_headers(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "Qty", "ODM ID"]
headers = ["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "Qty", "ODM ID"]
data = [
["10-40594-001", "AWS-311", 2, 1, "16754796"],
["10-40594-002", "ORD-3002", 0, 5, "16754797"],
["D4-A", "10-40594-001", "AWS-311", 2, 1, "16754796"],
["D4-B", "10-40594-002", "ORD-3002", 0, 5, "16754797"],
]
lines = parse_inventory_rows(headers, data)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["part_number"] == "D4-A"
assert lines[0]["aws_part_number"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["available_qty"] == 2.0
assert lines[0]["odm_id"] == "16754796"
@@ -71,22 +75,33 @@ def test_parse_inventory_drops_internal_hex_reservation_id(app):
"""库存快照可保留 SKU/数量,但内部 hex 不得写入 Reservation ID 字段。"""
with app.app_context():
lines = parse_inventory_rows(
["AWS Sku", "COM ID", "Qty Available"],
[["A001", "1f1a682dfdc446a393415dee93eb36ce", 2]],
["Supplier Sku", "AWS Sku", "COM ID", "Qty Available"],
[["A001", "AWS-A001", "1f1a682dfdc446a393415dee93eb36ce", 2]],
)
assert lines == [{"sku": "A001", "available_qty": 2.0}]
assert lines == [{"part_number": "A001", "aws_part_number": "AWS-A001", "available_qty": 2.0}]
def test_parse_inventory_rejects_aws_only_as_internal_part_number(app):
"""只有 AWS Sku 的库存表不能生成可匹配库存行。"""
with app.app_context():
lines = parse_inventory_rows(
["AWS Sku", "COM ID", "Qty Available"],
[["AWS-A001", "R-1", 2]],
)
assert lines == []
def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "ODM ID"]
data = [["10-40594-001", "AWS-311", 2, "16754796"]]
headers = ["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "ODM ID"]
data = [["D4-A", "10-40594-001", "AWS-311", 2, "16754796"]]
lines = parse_inventory_rows(
headers,
data,
field_mapping={
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"aws_part_number": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
@@ -94,11 +109,11 @@ def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
assert lines[0]["odm_id"] == "16754796"
def test_match_aggregates_same_sku_reservation():
notice = [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 3}]
def test_match_aggregates_same_part_number_reservation():
notice = [{"part_number": "D4-A", "reservation_id": "AWS-311", "qty": 3}]
inventory = [
{"sku": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 1},
{"sku": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 2},
{"part_number": "D4-A", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 1},
{"part_number": "D4-A", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 2},
]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
@@ -107,10 +122,11 @@ def test_match_aggregates_same_sku_reservation():
def test_parse_inventory_text_aws_table(app):
with app.app_context():
text = "AWS Sku\tReservation Order\tQty\n10-40594-001\tORD-3002\t4"
text = "Supplier Sku\tAWS Sku\tReservation Order\tQty\nD4-A\t10-40594-001\tORD-3002\t4"
lines, warnings, column_meta = parse_inventory_text(text)
assert not warnings or "no inventory" not in warnings[0]
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["part_number"] == "D4-A"
assert lines[0]["aws_part_number"] == "10-40594-001"
assert lines[0]["reservation_id"] == "ORD-3002"
assert lines[0]["available_qty"] == 4.0
assert column_meta["mapping"]["reservation_id"]["source_column"] == "Reservation Order"
@@ -120,13 +136,13 @@ def test_read_inventory_schema_preview_suggests_misspelled_reservation_order(app
path = tmp_path / "aws_misspelled_reservation.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "Resevation Order", "Qty"])
ws.append(["10-40594-001", "ORD-3002", 4])
ws.append(["Supplier Sku", "AWS Sku", "Resevation Order", "Qty"])
ws.append(["D4-A", "10-40594-001", "ORD-3002", 4])
wb.save(str(path))
wb.close()
with app.app_context():
preview = read_inventory_schema_preview(path)
assert preview["headers"] == ["AWS Sku", "Resevation Order", "Qty"]
assert preview["headers"] == ["Supplier Sku", "AWS Sku", "Resevation Order", "Qty"]
assert preview["suggested_mapping"]["reservation_id"] == "Resevation Order"
@@ -134,7 +150,7 @@ def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path):
path = tmp_path / "header_mismatch.xlsx"
_write_header_index_mismatch_xlsx(path)
with app.app_context():
mapping = {"sku": "AWS Sku", "available_qty": "Qty"}
mapping = {"part_number": "Supplier Sku", "available_qty": "Qty"}
lines_auto, meta_auto = parse_inventory_excel_with_meta(path, field_mapping=mapping, mapping_source="manual")
lines_fixed, meta_fixed = parse_inventory_excel_with_meta(
path,
@@ -144,12 +160,12 @@ def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path):
)
assert meta_auto["header_row_index"] == 5
assert meta_fixed["header_row_index"] == 2
assert any(line["sku"] == "EARLY-001" and line["available_qty"] == 7.0 for line in lines_fixed)
assert any(line["part_number"] == "EARLY-001" and line["available_qty"] == 7.0 for line in lines_fixed)
def test_match_extracts_reservation_id_suffix():
notice = [{"sku": "A001", "reservation_id": "1000140351", "qty": 1}]
inventory = [{"sku": "A001", "reservation_id": "ADU_S-ENCWIW260528126265@1000140351", "available_qty": 1}]
notice = [{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}]
inventory = [{"part_number": "A001", "reservation_id": "ADU_S-ENCWIW260528126265@1000140351", "available_qty": 1}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["available_qty"] == 1.0
@@ -8,7 +8,10 @@
from datetime import datetime
from pathlib import Path
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
import pytest
from app import db
from app.models import ShippingCustomer, ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source
@@ -16,6 +19,34 @@ def _tool_headers():
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
@pytest.fixture(autouse=True)
def _confirmed_customer_for_rpa_flows(app, monkeypatch):
"""为本模块新建的业务单绑定测试客户,使用例聚焦客户门禁之后的 RPA 行为。"""
from app.services.shipping_notice import task_workflow
original = task_workflow.resolve_shipping_case_for_new_task
def _resolve_confirmed_case(**kwargs):
case = original(**kwargs)
if case.customer_id is not None:
return case
customer = db.session.query(ShippingCustomer).filter_by(short_code="RPA").one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name="RPA 流程测试客户",
short_code="RPA",
status="active",
)
db.session.add(customer)
db.session.flush()
case.customer_id = customer.id
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = customer.short_code
return case
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
def test_inventory_rpa_single_attempt_messages_hide_fraction():
"""单次自动尝试模式不应再产出 1/1 计数,避免 Dify 误判仍会继续自动重试。"""
from app.services.shipping_notice.inventory_rpa_workflow import (
@@ -69,7 +100,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path, monke
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -129,7 +160,7 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -196,6 +227,74 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
assert task.inventory_snapshot_id == inv_file.id
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["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "drop")
@@ -211,13 +310,25 @@ def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client,
)
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
from tests.conftest import seed_task_inventory_source
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
seed_rpa_inventory_trigger(task, run_no="RUN-SKIPPED")
@@ -428,7 +539,7 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch
],
}
},
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -473,7 +584,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
@@ -515,7 +626,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
@@ -558,7 +669,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT")
@@ -637,7 +748,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT")
@@ -705,7 +816,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no=run_no)
@@ -820,14 +931,14 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
task_b = ShippingTask(
task_no="SN-BATCH-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "B001", "qty": 1}],
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
)
seed_task_inventory_source(task_a, source_code="DSV360_AWSDU")
seed_task_inventory_source(task_b, source_code="DSV360_AWSDU")
@@ -883,14 +994,14 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
task_fail = ShippingTask(
task_no="SN-SHARED-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "B001", "qty": 1}],
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
)
seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU")
seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU")
@@ -970,7 +1081,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT")
@@ -1014,7 +1125,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL")
@@ -1050,7 +1161,7 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
task_no="SN-REPAIR-ATTACH",
source_type="manual",
process_status="inventory_ready",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1209,7 +1320,7 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
task_no="SN-REPAIR-REJECT",
source_type="manual",
process_status="inventory_ready",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -61,7 +61,7 @@ def test_confirm_parse_blocked_when_inventory_source_unstable(app):
process_status="pending_review",
review_status="parse_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -89,7 +89,7 @@ def test_rpa_callback_rejected_when_inventory_source_unstable(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -121,7 +121,7 @@ def test_rpa_callback_rejects_mismatched_source_code(app, tmp_path):
task_no="SN-GATE-RPA-MISMATCH",
source_type="pdf",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
ship_to="Dublin",
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -148,7 +148,7 @@ def test_confirm_inventory_source_tool_route_exists(app, client):
process_status="pending_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -177,7 +177,7 @@ def test_crane_task_rpa_source_includes_dynamic_warehouse(app):
source_type="pdf",
process_status="parsed",
ship_to="TZR2",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="CRANE")
db.session.add(task)
@@ -209,7 +209,7 @@ def test_confirm_inventory_source_records_user_id(app, tmp_path, monkeypatch):
process_status="pending_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
@@ -243,7 +243,7 @@ def test_config_version_change_invalidates_stable_source(app):
source_type="pdf",
process_status="parsed",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
task.inventory_source_config_version = "stale-version"
@@ -264,7 +264,7 @@ def test_inventory_tools_blocked_without_stable_source(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -280,7 +280,7 @@ def test_inventory_tools_blocked_without_stable_source(app, tmp_path):
mapping_result = apply_inventory_mapping({
"task_id": task.task_no,
"map_json": {"sku": "SKU", "qty": "Qty"},
"map_json": {"part_number": "SKU", "qty": "Qty"},
})
assert mapping_result["status"] == "needs_human"
assert ShippingInventoryFile.query.count() == 0
@@ -296,7 +296,7 @@ def test_user_can_confirm_candidate_not_in_auto_top_match(app):
process_status="pending_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
ship_to="UnknownCity",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
@@ -321,7 +321,7 @@ def test_site_level_source_requires_explicit_warehouse_id(app):
source_type="pdf",
process_status="parsed",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
assert task.inventory_warehouse_id == "AWSDU"
@@ -344,7 +344,7 @@ def test_legacy_without_routing_fingerprint_is_not_stable(app):
source_type="pdf",
process_status="parsed",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
task.inventory_routing_fingerprint = None
@@ -363,7 +363,7 @@ def test_missing_warehouse_when_config_requires_it_is_not_stable(app):
source_type="pdf",
process_status="parsed",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSBI_BYAWSATL01")
task.inventory_warehouse_id = None
@@ -387,7 +387,7 @@ def test_rpa_callback_leaves_no_snapshot_when_identity_rejected(app, tmp_path):
task_no="SN-GATE-RPA-ORPHAN",
source_type="pdf",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
ship_to="Dublin",
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -419,7 +419,7 @@ def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
batch_index=1,
batch_total=2,
)
@@ -428,7 +428,7 @@ def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "B001", "qty": 1, "reservation_id": "R-200"}],
lines_json=[{"part_number": "B001", "qty": 1, "reservation_id": "R-200"}],
batch_index=2,
batch_total=2,
)
@@ -455,7 +455,7 @@ def test_crane_auto_adjudication_resolves_warehouse_from_alias(app):
source_type="pdf",
process_status="parsed",
ship_to="TZR2 footprint",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -468,8 +468,8 @@ def test_crane_auto_adjudication_resolves_warehouse_from_alias(app):
@pytest.mark.inventory_source_gate
def test_line_source_type_matches_alias_without_using_task_source_type(app):
"""orders[].lines[].source_type 应命中 match_aliases,Task.source_type 接入来源不得参与裁决。"""
def test_line_inventory_source_hint_matches_alias_without_using_task_source_type(app):
"""订单行 inventory_source_hint 应命中别名,Task.source_type 接入来源不得参与裁决。"""
with app.app_context():
task = ShippingTask(
task_no="SN-GATE-LINE-SOURCE-TYPE",
@@ -477,10 +477,10 @@ def test_line_source_type_matches_alias_without_using_task_source_type(app):
process_status="parsed",
lines_json=[
{
"sku": "A001",
"part_number": "A001",
"qty": 1,
"reservation_id": "R-100",
"source_type": "DBS DUB",
"inventory_source_hint": "DBS DUB",
},
],
)
@@ -506,7 +506,7 @@ def test_crane_user_confirm_and_gate_stable(app):
process_status="pending_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
ship_to="TZR3",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -548,7 +548,7 @@ def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch):
review_status="parse_review",
parse_confidence=0.4,
ship_to="UnknownCity",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
inventory_source_status="unresolved",
)
db.session.add(task)
@@ -603,7 +603,7 @@ def test_legacy_pending_parse_review_after_source_compat(app, monkeypatch):
review_status="parse_review",
parse_confidence=0.4,
ship_to="UnknownCity",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
step_payload_json={"pending_parse_review_after_source": True},
)
db.session.add(task)
@@ -651,7 +651,7 @@ def test_parse_notice_high_confidence_unresolved_source_goes_to_source_review(ap
"structured": {
"customer_name": "ACME",
"ship_to": "Mystery Port",
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -692,7 +692,7 @@ def test_parse_notice_low_confidence_unresolved_source_goes_to_parse_review(app,
"structured": {
"customer_name": "ACME",
"ship_to": "Mystery Port",
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"confidence": 0.4,
},
},
@@ -730,7 +730,7 @@ def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
batch_index=1,
batch_total=2,
)
@@ -739,7 +739,7 @@ def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "B001", "qty": 1, "reservation_id": "R-200"}],
lines_json=[{"part_number": "B001", "qty": 1, "reservation_id": "R-200"}],
batch_index=2,
batch_total=2,
)
@@ -851,7 +851,7 @@ def test_rpa_callback_rejects_excel_warehouse_mismatch(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="TZR2 footprint",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="CRANE")
seed_rpa_inventory_trigger(task, run_no="RUN-EXCEL-WH")
@@ -877,7 +877,7 @@ def test_manual_upload_rejects_wrong_excel_warehouse(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -908,7 +908,7 @@ def test_rpa_callback_rejects_mismatched_warehouse_id(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-WH-MISMATCH")
@@ -939,7 +939,7 @@ def test_rpa_callback_rejects_stale_run_no(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT")
@@ -1000,7 +1000,7 @@ def test_manual_upload_csv_preserves_suffix_and_passes_identity(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1026,7 +1026,7 @@ def test_manual_upload_rejects_xls_extension(app, tmp_path):
task_no="SN-GATE-UPLOAD-XLS",
source_type="pdf",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1056,7 +1056,7 @@ def test_rpa_success_rejected_without_active_trigger(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1080,7 +1080,7 @@ def test_rpa_failed_rejected_stale_run_no(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT-FAIL")
@@ -7,7 +7,8 @@ from app.services.shipping_notice.match_rule_desc import (
def test_extract_mapping_payload_extras():
payload = {
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"aws_part_number": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
"match_rule": "以 Reservation Order 对齐订单 reservation_id,汇总 Qty Available 与订单 qty 比对。",
@@ -19,25 +20,25 @@ def test_extract_mapping_payload_extras():
def test_resolve_match_rule_prefers_llm():
mapping = {
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
llm_rule = "LLM 自定义匹配说明。"
rule, keys, source = resolve_match_rule(mapping, llm_match_rule=llm_rule)
assert rule == llm_rule
assert keys == ["sku", "reservation_id"]
assert keys == ["part_number", "reservation_id"]
assert source == "llm"
def test_build_match_rule_fallback_uses_column_names():
mapping = {
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
rule = build_match_rule_fallback(mapping)
assert "AWS Sku" in rule
assert "Supplier Sku" in rule
assert "Reservation Order" in rule
assert "Qty Available" in rule
assert "按 SKU + Reservation ID" not in rule
@@ -6,7 +6,7 @@ def test_format_match_summary_fulfillable():
"fulfillable",
[
{
"sku": "10-40594-001",
"part_number": "D4-A08AR12000002",
"reservation_id": "AWS-311",
"required_qty": 2,
"available_qty": 5,
@@ -16,8 +16,8 @@ def test_format_match_summary_fulfillable():
],
)
assert "【库存匹配结果】" in msg or "匹配明细" in msg
assert "| # | 预订单号 | 料号 |" in msg
assert "| 1 | AWS-311 | 10-40594-001 | 2 | 5 | - |" in msg
assert "| # | 预订单号 | 内部料号 |" in msg
assert "| 1 | AWS-311 | D4-A08AR12000002 | 2 | 5 | - |" in msg
assert "✅ 充足" in msg
assert "可生成发货 Excel" in msg
@@ -27,7 +27,7 @@ def test_format_match_summary_shortage():
"partial",
[
{
"sku": "A001",
"part_number": "A001",
"reservation_id": "R-1",
"required_qty": 100,
"available_qty": 5,
@@ -1,7 +1,7 @@
"""
tests/test_shipping_notice_openapi_contract.py
用途:锁定发货通知订单行路由线索与库存连接器 OpenAPI 命名契约。
用途:锁定发货通知 v2 订单行、单一路由线索与库存连接器 OpenAPI 命名契约。
依赖:Flask 测试 client、静态 Dify OpenAPI JSON。
逻辑:分别校验动态 builder 输出与脚本生成的静态快照,防止两者发生漂移。
"""
@@ -17,8 +17,8 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
"""
校验订单行与库存连接器的字段边界。
核心逻辑:订单行保留可选 source_type 与独立 hub_code;任务状态说明使用
inventory_connector_type,并拒绝旧 inventory_source_type 命名。
核心逻辑:订单行只接受 part_number 与可选外部料号/inventory_source_hint;
任务状态说明使用 inventory_connector_type,并拒绝旧 inventory_source_type 命名。
Args:
spec: 动态接口或静态快照读取出的 OpenAPI 对象。
@@ -30,9 +30,23 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
"application/json"
]["schema"]["properties"]["orders"]["items"]
line_properties = order_schema["properties"]["lines"]["items"]["properties"]
assert set(line_properties) == {"sku", "qty", "reservation_id", "source_type", "hub_code"}
assert "可选订单路由线索" in line_properties["source_type"]["description"]
assert "Hub" in line_properties["hub_code"]["description"] or "hub" in line_properties["hub_code"]["description"].lower()
assert order_schema["properties"]["lines"]["items"]["additionalProperties"] is False
assert set(line_properties) == {
"part_number",
"customer_part_number",
"aws_part_number",
"qty",
"reservation_id",
"inventory_source_hint",
}
assert "库存来源提示" in line_properties["inventory_source_hint"]["description"]
assert not {"sku", "vendor_part_number", "source_type", "hub_code"} & set(line_properties)
request_schema = spec["paths"]["/tools/submit_order_extraction"]["post"]["requestBody"]["content"][
"application/json"
]["schema"]
assert "schema_version" not in request_schema["properties"]
assert request_schema["required"] == ["agent_runtime_context", "input_snapshot_hash", "orders"]
status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"]
assert "inventory_connector_type" in status_description
@@ -38,7 +38,6 @@ from app.services.chat.log_service import merge_chat_log_payload
from app.services.chat.stream_relay import iter_handler_preface_sse
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.order_extraction import (
EXTRACTION_CONTRACT_VERSION,
ORDER_EXTRACTION_FAILED_CODE,
ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
ORDER_EXTRACTION_TIMEOUT_MESSAGE,
@@ -63,8 +62,8 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
assessment = assess_candidate_business_summary({
'po_number': '4510038672',
'lines': [
{'sku': 'SKU-A', 'qty': 1, 'reservation_id': 'R-100'},
{'sku': 'SKU-B', 'qty': 2},
{'part_number': 'SKU-A', 'qty': 1, 'reservation_id': 'R-100'},
{'part_number': 'SKU-B', 'qty': 2},
],
})
@@ -72,6 +71,32 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
assert assessment['missing_process_fields'] == ['reservation_id']
@pytest.mark.parametrize('field', ['customer_part_number', 'aws_part_number'])
def test_candidate_validation_blocks_non_atomic_optional_part_numbers(field):
"""可选料号包含分隔符时必须在 Candidate 门禁阻断,不能延迟到规范表写入失败。"""
assessment = assess_candidate_business_summary({
'lines': [{'part_number': 'D4-A08AR12000002', field: 'LEFT/RIGHT', 'qty': 10}],
})
assert assessment['can_create_task'] is False
assert assessment['invalid_lines'] == [{
'line_index': 0,
'reason': 'non_atomic_part_number',
'field': field,
}]
def test_candidate_validation_accepts_frozen_temp_composite_rule():
"""已冻结 TEMP 二段规则应在门禁前拆成客户料号与内部料号。"""
assessment = assess_candidate_business_summary({
'lines': [{'part_number': 'TEMP-S000218929/D4-A08AR12000002', 'qty': 10}],
})
assert assessment['can_create_task'] is True
assert assessment['normalized_summary']['lines'][0]['part_number'] == 'D4-A08AR12000002'
assert assessment['normalized_summary']['lines'][0]['customer_part_number'] == 'TEMP-S000218929'
def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, ShippingNoticeDocument, str]:
"""
创建一封已完成上传预处理的邮件、单个附件和对应统一运行态上下文。
@@ -132,7 +157,9 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S
parse_status='parsed',
extracted_text=(
'PO 4510000001 SKU SKU-A QTY 10 RSV R-100 SOURCE AWS Dublin HUB DUB\n'
'PO 4510000002 SKU SKU-B QTY 20'
'PO 4510000002 SKU SKU-B QTY 20\n'
'SKU SKU-STATE SKU SKU-STALE SKU SKU-UI-STATE SKU SKU-OPEN-EXISTING\n'
'SKU P123456 SKU IGNORED-SKU QTY 1 QTY 2 QTY 3 QTY 5 QTY 24'
),
)
db.session.add(document)
@@ -143,7 +170,6 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S
request_id='req-order-extraction-001',
refs={
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
'intake_nos': json.dumps([intake.intake_no], separators=(',', ':')),
'run_purpose': 'order_extraction',
},
@@ -156,17 +182,17 @@ def _order(
intake_no: str,
document_id: int,
po_number: str,
sku: str,
part_number: str,
qty: int,
confidence: float = 0.99,
include_process_fields: bool,
) -> dict:
"""构造符合 Chatflow v1 契约的单个订单结果。"""
line = {'sku': sku, 'qty': qty}
"""构造符合 Chatflow V2 契约的单个订单结果。"""
line = {'part_number': part_number, 'qty': qty}
if include_process_fields:
line.update({'reservation_id': 'R-100', 'source_type': 'AWS Dublin'})
line.update({'reservation_id': 'R-100', 'inventory_source_hint': 'AWS Dublin'})
evidence = [
{'field': 'lines[0].sku', 'quote': f'SKU {sku}', 'document_id': document_id},
{'field': 'lines[0].part_number', 'quote': f'SKU {part_number}', 'document_id': document_id},
{'field': 'lines[0].qty', 'quote': f'QTY {qty}', 'document_id': document_id},
]
if include_process_fields:
@@ -181,7 +207,7 @@ def _order(
'candidate_key_hint': po_number,
'classification': 'shipping_request',
'classification_confidence': confidence,
'field_confidence': {'sku': confidence, 'qty': confidence},
'field_confidence': {'part_number': confidence, 'qty': confidence},
'po_number': po_number,
'lines': [line],
'evidence': evidence,
@@ -267,7 +293,6 @@ def _shipping_handler_context(
'shipping_notice': {
'intake_nos': [intake_no],
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
},
},
)
@@ -479,13 +504,12 @@ def test_order_extraction_state_is_request_fenced_and_reads_submission_facts(app
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000011',
sku='SKU-STATE',
part_number='SKU-STATE',
qty=2,
include_process_fields=False,
),
@@ -668,13 +692,12 @@ def test_superseded_order_extraction_request_cannot_read_or_submit(app):
submit_order_extraction({
'agent_runtime_context': old_runtime_context,
'input_snapshot_hash': old_context['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000999',
sku='SKU-STALE',
part_number='SKU-STALE',
qty=1,
include_process_fields=True,
),
@@ -702,13 +725,12 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re
payload = {
'agent_runtime_context': runtime_context,
'input_snapshot_hash': snapshot,
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=False,
),
@@ -716,7 +738,7 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000002',
sku='SKU-B',
part_number='SKU-B',
qty=20,
confidence=0.60,
include_process_fields=True,
@@ -794,7 +816,7 @@ def test_submit_order_extraction_consumes_empty_and_confident_non_shipping_resul
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='NOTICE-ONLY',
sku='IGNORED-SKU',
part_number='IGNORED-SKU',
qty=1,
include_process_fields=True,
)
@@ -803,7 +825,6 @@ def test_submit_order_extraction_consumes_empty_and_confident_non_shipping_resul
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [non_shipping_order],
})
@@ -858,7 +879,7 @@ def test_submit_order_extraction_reports_opened_existing_without_claiming_creati
'fingerprint_version': 'shipping-v1',
'components': {},
'content_fingerprint': 'existing-order-content',
'content_fingerprint_version': 'shipping-content-v3',
'content_fingerprint_version': 'shipping-content-v4',
'matches': [{
'task_no': existing.task_no,
'process_status': existing.process_status,
@@ -879,12 +900,11 @@ def test_submit_order_extraction_reports_opened_existing_without_claiming_creati
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=True,
)],
@@ -911,7 +931,6 @@ def test_submit_order_extraction_empty_orders_reports_no_task_created(app):
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [],
})
@@ -934,12 +953,11 @@ def test_submit_order_extraction_pending_only_message_does_not_start_with_additi
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000002',
sku='SKU-B',
part_number='SKU-B',
qty=20,
confidence=0.60,
include_process_fields=True,
@@ -963,7 +981,6 @@ def test_submit_order_extraction_unassigned_pending_keeps_documents_partial(app)
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [None],
})
@@ -984,13 +1001,12 @@ def test_order_extraction_terminal_ui_state_resolves_only_the_current_intakes(ap
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000099',
sku='SKU-UI-STATE',
part_number='SKU-UI-STATE',
qty=3,
include_process_fields=False,
),
@@ -1037,7 +1053,6 @@ def test_order_extraction_terminal_ui_state_resolves_only_the_current_intakes(ap
'shipping_notice': {
'intake_nos': [intake.intake_no],
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
},
},
)
@@ -1131,7 +1146,7 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor
'fingerprint_version': 'shipping-v1',
'components': {},
'content_fingerprint': 'existing-order-content',
'content_fingerprint_version': 'shipping-content-v3',
'content_fingerprint_version': 'shipping-content-v4',
'matches': [{
'task_no': existing.task_no,
'process_status': existing.process_status,
@@ -1152,12 +1167,11 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000100',
sku='SKU-OPEN-EXISTING',
part_number='SKU-OPEN-EXISTING',
qty=5,
include_process_fields=True,
)],
@@ -1180,7 +1194,6 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor
'shipping_notice': {
'intake_nos': [intake.intake_no],
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
},
},
)
@@ -1240,13 +1253,12 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
review_status='rsv_req',
pending_human_reason='rsv_req',
error_message='解析失败:未识别到 Reservation ID',
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
step_payload_json={
'process_field_gate': {
'status': 'needs_enrichment',
'missing_fields': ['reservation_id'],
'issues': [],
'contract_version': EXTRACTION_CONTRACT_VERSION,
},
},
)
@@ -1260,17 +1272,16 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510038672',
sku='P123456',
part_number='P123456',
qty=24,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['lines'][0]['source_type'] = 'DBS DUB'
order['lines'][0]['inventory_source_hint'] = 'DBS DUB'
order['evidence'][-1]['quote'] = '1000140351'
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1280,13 +1291,13 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1
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['source_type'] == 'DBS DUB'
assert candidate_line['inventory_source_hint'] == 'DBS DUB'
# 通用字段对账会同时补空的 Source Type 等可选字段;Reservation 必须落库。
assert existing.lines_json[0]['sku'] == 'P123456'
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('source_type') == 'DBS DUB'
assert existing.lines_json[0].get('inventory_source_hint') == 'DBS DUB'
assert existing.process_status == 'pending_review'
assert existing.pending_human_reason == 'low_confidence'
assert 'process_field_gate' not in (existing.step_payload_json or {})
@@ -1307,7 +1318,7 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=True,
)
@@ -1320,7 +1331,6 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1335,7 +1345,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
with app.app_context():
user, _session, intake, document, runtime_context = _seed_extraction_input()
document.extracted_text = (
"SKU\tReservation ID\tQty\n"
"Part Number\tReservation ID\tQty\n"
"SKU-A\tR-200\t10\n"
"LLM candidate quote R-100"
)
@@ -1345,7 +1355,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=True,
)
@@ -1353,7 +1363,6 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1361,7 +1370,13 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
assert result['pending_count'] == 1
assert 'blocking_conflict' in result['pending_orders'][0]['reasons']
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.conflicts_json[0]['reason'] == 'source_conflict'
assert candidate.conflicts_json[0]['reason'] == 'cross_source_conflict'
adjudication = candidate.structured_result_json['extraction']['field_adjudication']
reservation_observations = [
item for item in adjudication['observations']
if item['field'] == 'reservation_id'
]
assert {item['source'] for item in reservation_observations} == {'backend_table', 'dify_llm'}
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
@@ -1384,7 +1399,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
'process_status': 'pending_review',
'review_status': 'rsv_req',
'pending_human_reason': 'rsv_req',
'lines_json': [{'sku': 'P123456', 'qty': 24}],
'lines_json': [{'part_number': 'P123456', 'qty': 24}],
}
task_values.update(task_overrides)
task = ShippingTask(**task_values)
@@ -1397,7 +1412,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
candidate=candidate,
candidate_summary={
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
'lines': [{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
},
duplicate_status='exact_file',
duplicate_matches=[{'task_no': task.task_no}],
@@ -1428,7 +1443,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
),
ShippingTask(
task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES',
@@ -1438,8 +1453,8 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[
{'sku': 'P123456', 'qty': 24},
{'sku': 'P123456', 'qty': 24},
{'part_number': 'P123456', 'qty': 24},
{'part_number': 'P123456', 'qty': 24},
],
),
ShippingTask(
@@ -1449,7 +1464,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24}],
lines_json=[{'part_number': 'P123456', 'qty': 24}],
),
]
db.session.add_all(tasks)
@@ -1457,7 +1472,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS')
summary = {
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
'lines': [{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
}
results = [
@@ -1497,7 +1512,7 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
)
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
db.session.add(task)
@@ -1508,7 +1523,7 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
candidate=candidate,
candidate_summary={
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
'lines': [{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
},
duplicate_status='exact_file',
duplicate_matches=[{'task_no': task.task_no}],
@@ -1543,7 +1558,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
source_content_hash=document.content_hash,
po_number='4510038672',
process_status='waiting_inventory',
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.add(existing)
db.session.commit()
@@ -1555,7 +1570,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510038672',
sku='P123456',
part_number='P123456',
qty=24,
include_process_fields=True,
)
@@ -1565,7 +1580,6 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1574,7 +1588,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
assert result['opened_existing_count'] == 1
assert result['pending_count'] == 0
assert candidate.consumed_task_id == int(existing.id)
assert existing.lines_json == [{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}]
assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}]
assert existing.process_status == 'waiting_inventory'
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
@@ -1588,7 +1602,7 @@ def test_order_extraction_requires_verified_pair_after_reservation_adjudication(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=True,
)
@@ -1611,7 +1625,6 @@ def test_order_extraction_requires_verified_pair_after_reservation_adjudication(
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1644,7 +1657,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.add(existing)
db.session.commit()
@@ -1654,7 +1667,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510038672',
sku='P123456',
part_number='P123456',
qty=24,
include_process_fields=True,
)
@@ -1666,7 +1679,6 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1693,7 +1705,6 @@ def test_submit_order_extraction_rejects_changed_document_snapshot(app):
submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [],
})
@@ -8,7 +8,7 @@ def test_format_parse_summary_single_line():
ship_to="Wistron Corporation, Czech Republic",
lines=[
{
"sku": "504-010213-001",
"part_number": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "PCS",
@@ -22,11 +22,11 @@ def test_format_parse_summary_single_line():
assert "【发货通知解析确认】任务编号:SN-20260604-7249E4D7" in msg
assert "| 采购单号 | 16754796 |" in msg
assert "| 预订单号 | 1000140351 |" in msg
assert "| 料号 | 504-010213-001 |" in msg
assert "| 内部料号 | 504-010213-001 |" in msg
po_idx = msg.index("| 采购单号 |")
rid_idx = msg.index("| 预订单号 |")
sku_idx = msg.index("| 料号 |")
assert po_idx < rid_idx < sku_idx
part_idx = msg.index("| 内部料号 |")
assert po_idx < rid_idx < part_idx
assert "| 数量 | 9 PCS |" in msg
assert "| 单价 | $1,607.72 |" in msg
assert "| 金额 | $14,469.48 |" in msg
@@ -41,8 +41,8 @@ def test_format_parse_summary_multiple_lines():
task_no="SN-1",
po_number="PO-1",
lines=[
{"sku": "A", "qty": 1, "reservation_id": "R1"},
{"sku": "B", "qty": 2, "reservation_id": "R2"},
{"part_number": "A", "qty": 1, "reservation_id": "R1"},
{"part_number": "B", "qty": 2, "reservation_id": "R2"},
],
)
assert "【明细 1】" in msg
@@ -53,7 +53,7 @@ def test_format_parse_summary_multiple_lines():
def test_format_parse_summary_includes_warnings():
msg = format_parse_summary(
task_no="SN-1",
lines=[{"sku": "A", "qty": 1}],
lines=[{"part_number": "A", "qty": 1}],
warnings=["订单行未解析到 Reservation ID"],
low_confidence=True,
)
@@ -7,8 +7,8 @@ from app.services.shipping_notice.reservation_id import (
def test_match_numeric_reservation_id():
notice = [{"sku": "10-40594-001", "reservation_id": "1000140351", "qty": 2}]
inventory = [{"sku": "10-40594-001", "reservation_id": 1000140351.0, "available_qty": 3}]
notice = [{"part_number": "D4-A08AR12000002", "reservation_id": "1000140351", "qty": 2}]
inventory = [{"part_number": "D4-A08AR12000002", "reservation_id": 1000140351.0, "available_qty": 3}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["reservation_id"] == "1000140351"
@@ -27,3 +27,11 @@ def test_reservation_contract_rejects_internal_hex_but_keeps_business_ids():
assert is_valid_reservation_id("AWS-311")
assert is_valid_reservation_id("R-1")
assert not is_valid_reservation_id("AWS-311", numeric_only=True)
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
assert reservation_gate_issues([])[0]["reason"] == "missing_order_lines"
assert reservation_gate_issues(["invalid-line"])[0]["reason"] == "invalid_order_line"
+114 -74
View File
@@ -64,7 +64,7 @@ def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) ->
"structured": {
"customer_name": "AWS",
"ship_to": "Dublin",
"lines": [{"sku": "A001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -121,12 +121,12 @@ def test_match_notice_lines_reports_progress():
status, line_results, shortage = match_notice_lines(
[
{"sku": "A001", "reservation_id": "R-1", "qty": 1},
{"sku": "A002", "reservation_id": "R-2", "qty": 2},
{"part_number": "A001", "reservation_id": "R-1", "qty": 1},
{"part_number": "A002", "reservation_id": "R-2", "qty": 2},
],
[
{"sku": "A001", "reservation_id": "R-1", "available_qty": 1},
{"sku": "A002", "reservation_id": "R-2", "available_qty": 2},
{"part_number": "A001", "reservation_id": "R-1", "available_qty": 1},
{"part_number": "A002", "reservation_id": "R-2", "available_qty": 2},
],
progress_callback=lambda current, total: seen.append((current, total)),
)
@@ -158,11 +158,11 @@ def test_shipping_notice_tool_flow(app, client):
"structured": {
"customer_name": "ACME",
"lines": [{
"sku": "A001",
"part_number": "A001",
"reservation_id": "R-1",
"qty": 10,
"uom": "EA",
"source_type": "AWS Dublin",
"inventory_source_hint": "AWS Dublin",
}],
"confidence": 0.95,
},
@@ -172,14 +172,14 @@ def test_shipping_notice_tool_flow(app, client):
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human", "running"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| 料号 | A001 |" in parse_body["message"]
assert "| 内部料号 | A001 |" in parse_body["message"]
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
"inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
assert inv_res.status_code == 200
@@ -267,7 +267,7 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -275,7 +275,7 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 5}]},
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
@@ -329,7 +329,7 @@ def test_submit_decision_rematch_reruns_match_and_returns_shortage(app, client,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -337,7 +337,7 @@ def test_submit_decision_rematch_reruns_match_and_returns_shortage(app, client,
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 5}]},
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
@@ -394,7 +394,7 @@ def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 20, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 20, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -402,7 +402,7 @@ def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client,
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 1}]},
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 1}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
@@ -481,7 +481,7 @@ def test_confirm_inventory_source_route_returns_json(app, client):
process_status="pending_review",
pending_human_reason="inventory_source_unresolved",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
)
db.session.add(task)
db.session.commit()
@@ -533,7 +533,7 @@ def test_parse_inventory_from_chat_text(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -592,7 +592,7 @@ def test_parse_inventory_empty_needs_human(app, client):
assert body.get("human_options") is not None or body.get("action_buttons")
def test_match_by_aws_sku_and_reservation_id(app, client):
def test_match_by_supplier_sku_and_reservation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
@@ -609,8 +609,8 @@ def test_match_by_aws_sku_and_reservation_id(app, client):
"structured": {
"customer_name": "AWS",
"lines": [
{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 2, "uom": "EA"},
{"sku": "10-40594-001", "reservation_id": "ORD-3002", "qty": 1, "uom": "EA"},
{"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 2, "uom": "EA"},
{"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "ORD-3002", "qty": 1, "uom": "EA"},
],
"confidence": 0.95,
},
@@ -618,9 +618,9 @@ def test_match_by_aws_sku_and_reservation_id(app, client):
)
inv_text = (
"AWS Sku\tCOM ID\tQty Available\n"
"10-40594-001\tAWS-311\t2\n"
"10-40594-001\tORD-3002\t0\n"
"Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n"
"D4-A08AR12000002\t10-40594-001\tAWS-311\t2\n"
"D4-A08AR12000002\t10-40594-001\tORD-3002\t0\n"
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
@@ -661,7 +661,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -671,7 +671,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
headers=headers,
json={
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
"raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n",
},
)
@@ -686,7 +686,8 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
assert blocked.get("stop_agent_turn") is True
assert "field_alignment" in blocked["data"]
mapping = blocked["data"]["field_alignment"]
assert mapping["inventory_columns"]["mapping"]["sku"]["source_column"] == "AWS Sku"
assert mapping["inventory_columns"]["mapping"]["part_number"]["source_column"] == "Supplier Sku"
assert mapping["inventory_columns"]["mapping"]["aws_part_number"]["source_column"] == "AWS Sku"
assert mapping["inventory_columns"]["mapping"]["reservation_id"]["source_column"] == "COM ID"
@@ -706,7 +707,7 @@ def test_match_inventory_requires_reservation_id(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -714,7 +715,7 @@ def test_match_inventory_requires_reservation_id(app, client):
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"sku": "A001", "qty": 1, "uom": "EA"}]
task.lines_json = [{"part_number": "A001", "qty": 1, "uom": "EA"}]
db.session.commit()
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory as ensure_inventory_service,
@@ -726,7 +727,7 @@ def test_match_inventory_requires_reservation_id(app, client):
direct_data = ensure_inventory_service({
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
"inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}],
})
assert direct_data["status"] == "needs_human", direct_data
assert direct_data.get("checkpoint") == "rsv_req"
@@ -734,7 +735,7 @@ def test_match_inventory_requires_reservation_id(app, client):
parse_data = parse_inventory_service({
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
"inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}],
})
assert parse_data["status"] == "needs_human"
assert parse_data.get("checkpoint") == "rsv_req"
@@ -771,7 +772,15 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"lines": [
{
"part_number": "D4-A08AR12000002",
"aws_part_number": "10-40594-001",
"reservation_id": "AWS-311",
"qty": 1,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
@@ -781,7 +790,10 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
headers=headers,
json={
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
"raw_inventory_text": (
"Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n"
"D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n"
),
},
)
@@ -795,7 +807,12 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
assert data.get("checkpoint") == "map_infer"
assert data.get("stop_agent_turn") is True
assert "schema_preview" in data["data"]
assert data["data"]["schema_preview"]["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
assert data["data"]["schema_preview"]["headers"] == [
"Supplier Sku",
"AWS Sku",
"COM ID",
"Qty Available",
]
def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
@@ -813,6 +830,25 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
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",
"lines": [
{
"part_number": "A001",
"reservation_id": "R-1",
"qty": 1,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
from app import db
from tests.conftest import seed_task_inventory_source
@@ -829,8 +865,8 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "料号", "可用数量"])
ws.append(["AWSDU", "A001", 20])
ws.append(["Warehouse ID", "Supplier Sku", "Reservation ID", "可用数量"])
ws.append(["AWSDU", "A001", "R-1", 20])
wb.save(inv_file)
wb.close()
@@ -842,8 +878,8 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
"task_no": task_id,
"success": True,
"file_path": str(inv_file),
"run_no": "RUN-TOOLS-CB",
"source_code": "DSV360_AWSDU",
"run_no": "RUN-TOOLS-CB",
"source_code": "DSV360_AWSDU",
"site_id": "AWSDU",
"warehouse_id": "AWSDU",
}
@@ -880,7 +916,7 @@ def test_rpa_upload_callback(app, client, tmp_path):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 5, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -888,7 +924,7 @@ def test_rpa_upload_callback(app, client, tmp_path):
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]},
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
@@ -911,7 +947,7 @@ def test_rpa_upload_callback(app, client, tmp_path):
assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001"
def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client):
def test_generate_shipment_excel_writes_part_number_and_odm_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
@@ -931,8 +967,7 @@ def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client):
"po_number": "SN-20260608-7FCBFA4B",
"lines": [
{
"sku": "504-010213-001",
"vendor_part_number": "504-010213-001",
"part_number": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "EA",
@@ -949,7 +984,7 @@ def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client):
"task_id": task_id,
"inventory_lines": [
{
"sku": "504-010213-001",
"part_number": "504-010213-001",
"reservation_id": "1000140351",
"available_qty": 9,
"odm_id": "16754796",
@@ -1004,7 +1039,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1017,8 +1052,8 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "10-40594-001", "AWS-311", 5])
ws.append(["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "D4-A08AR12000002", "10-40594-001", "AWS-311", 5])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -1036,8 +1071,9 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "map_infer"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
assert preview["headers"] == ["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["part_number"] == "Supplier Sku"
assert preview["suggested_mapping"]["aws_part_number"] == "AWS Sku"
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
@@ -1091,7 +1127,7 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
source_type="manual",
process_status="uploaded",
pending_human_reason=None,
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
batch_index=1,
batch_total=2,
)
@@ -1100,7 +1136,7 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A002", "reservation_id": "R-2", "qty": 1, "uom": "EA"}],
lines_json=[{"part_number": "A002", "reservation_id": "R-2", "qty": 1, "uom": "EA"}],
batch_index=2,
batch_total=2,
)
@@ -1156,8 +1192,8 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "504-010213-001", "1000140351", 5])
ws.append(["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "D4-A08AR12000002", "504-010213-001", "1000140351", 5])
buf = BytesIO()
wb.save(buf)
buf.seek(0)
@@ -1174,7 +1210,7 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
@@ -1182,7 +1218,7 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
)
apply_data = apply_res.get_json()
match_rule = apply_data["data"]["field_alignment"]["match_rule"]
assert "AWS Sku" in match_rule
assert "Supplier Sku" in match_rule
assert "COM ID" in match_rule
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "fallback"
@@ -1244,7 +1280,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "Part No",
"part_number": "Part No",
"reservation_id": "Resv",
"available_qty": "On Hand",
},
@@ -1254,7 +1290,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
assert apply_data["status"] == "needs_human"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0]
assert sample["sku"] == "SKU-99"
assert sample["part_number"] == "SKU-99"
assert sample["available_qty"] == 12
@@ -1276,7 +1312,7 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
"structured": {
"customer_name": "Wistron",
"ship_to": "Dublin",
"lines": [{"sku": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}],
"lines": [{"part_number": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1333,7 +1369,7 @@ def test_parse_notice_blocks_when_reservation_id_missing(app, client, monkeypatc
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1380,7 +1416,8 @@ def test_parse_notice_blocks_invalid_nonempty_reservation_id(app, client, monkey
"structured": {
"lines": [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"part_number": "D4-A08AR12000002",
"customer_part_number": "TEMP-S000218929",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
"qty": 10,
"uom": "EA",
@@ -1421,7 +1458,7 @@ def test_human_edit_revalidates_reservation_and_blocks_stale_confirm(app, client
json={
"task_id": task_id,
"structured": {
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 2, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 2, "uom": "EA"}],
"confidence": 0.4,
},
},
@@ -1463,7 +1500,7 @@ def test_parse_notice_blocks_valid_reservation_when_column_evidence_conflicts(ap
headers=headers,
json={"source_type": "manual"},
).get_json()["task_id"]
raw_text = "AWS Sku\tReservation ID\tQty\nA001\t3000092917\t2"
raw_text = "Part Number\tReservation ID\tQty\nA001\t3000092917\t2"
result = client.post(
"/api/shipping-notice/tools/parse_notice",
@@ -1472,7 +1509,7 @@ def test_parse_notice_blocks_valid_reservation_when_column_evidence_conflicts(ap
"task_id": task_id,
"raw_text": raw_text,
"structured": {
"lines": [{"sku": "A001", "reservation_id": "3000092918", "qty": 2, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "3000092918", "qty": 2, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1510,7 +1547,7 @@ def test_parse_notice_low_confidence_does_not_write_parse_review_chat_card(app,
"conversation_id": "conv-no-parse-card",
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"confidence": 0.4,
},
},
@@ -1553,7 +1590,7 @@ def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, m
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1598,7 +1635,7 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1646,7 +1683,7 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1656,7 +1693,7 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task_db_id = task.id
task.inventory_lines_json = [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]
task.inventory_lines_json = [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}]
task.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
@@ -1672,7 +1709,7 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
"headers": ["Reservation ID", "SKU", "Qty Available"],
"field_mapping": {
"reservation_id": "Reservation ID",
"sku": "SKU",
"part_number": "SKU",
"available_qty": "Qty Available",
},
"mapping": {
@@ -1720,13 +1757,14 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}]
task.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
task.inventory_lines_json = [{"sku": "OLD", "reservation_id": "R-1", "available_qty": 3}]
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "R-1", "available_qty": 3}]
task.match_status = "fulfillable"
task.shortage_json = {"lines": []}
task.line_results_json = [{"sku": "OLD", "status": "ok"}]
task.line_results_json = [{"part_number": "OLD", "status": "ok"}]
task.export_file_path = str(tmp_path / "old.xlsx")
task.export_file_name = "old.xlsx"
task.upload_status = "failed"
@@ -1797,6 +1835,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}]
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
@@ -1860,6 +1899,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}]
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_EXHAUSTED
task.step_payload_json = {
@@ -1939,6 +1979,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}]
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
@@ -1993,7 +2034,7 @@ def test_submit_decision_by_conversation_id(app, client):
"conversation_id": "conv-test-001",
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "reservation_id": "1000140351", "qty": 9, "uom": "EA"}],
"lines": [{"part_number": "504-010213-001", "reservation_id": "1000140351", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -2028,7 +2069,7 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"sku": "A001", "reservation_id": "1000140351", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}],
)
second = ShippingTask(
task_no="SN-MULTI-CONV-002",
@@ -2037,7 +2078,7 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"sku": "A002", "reservation_id": "1000140352", "qty": 1}],
lines_json=[{"part_number": "A002", "reservation_id": "1000140352", "qty": 1}],
)
with app.app_context():
db.session.add_all([first, second])
@@ -2147,4 +2188,3 @@ def test_chat_actions_empty_when_task_rejected(app):
ui_state = build_task_ui_state(task)
assert ui_state["checkpoint"] == "rejected"
assert ui_state["action_buttons"] == []
@@ -30,7 +30,7 @@ def _task(**kwargs) -> ShippingTask:
process_status=kwargs.pop('process_status', 'pending_review'),
pending_human_reason=kwargs.pop('pending_human_reason', 'rsv_req'),
po_number=kwargs.pop('po_number', 'PO-100'),
lines_json=kwargs.pop('lines_json', [{'sku': 'A001', 'qty': 10}]),
lines_json=kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}]),
order_data_version=1,
order_lines_migration_status='pending',
**kwargs,
@@ -52,15 +52,15 @@ def test_build_plan_fills_empty_and_conflicts_on_diff(app):
"""空字段自动进入 fills;双方非空不同进入 conflicts。"""
with app.app_context():
task = _task(lines_json=[
{'sku': 'A001', 'qty': 10, 'reservation_id': ''},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000001'},
{'part_number': 'A001', 'qty': 10, 'reservation_id': ''},
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000000001'},
])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary={
'lines': [
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917', 'hub_code': 'H1'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000099'},
{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917', 'inventory_source_hint': 'H1'},
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000000099'},
]
},
verified_reservation_evidence=[
@@ -76,9 +76,9 @@ def test_build_plan_fills_empty_and_conflicts_on_diff(app):
def test_apply_conflict_persists_field_conflict_and_blocks_gate(app):
"""冲突落库后库存门禁应阻断。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary=candidate.summary_json,
@@ -96,9 +96,9 @@ def test_apply_conflict_persists_field_conflict_and_blocks_gate(app):
def test_resolve_conflict_writes_line_and_is_idempotent(app):
"""解决冲突回写订单行;同幂等键可重放。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary=candidate.summary_json,
@@ -137,14 +137,14 @@ def test_update_notice_line_version_mismatch(app):
task = _task(
process_status='parsed',
pending_human_reason=None,
lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
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,
'line_index': 0,
'patch': {'hub_code': 'H9'},
'patch': {'inventory_source_hint': 'H9'},
'expected_order_data_version': 1,
})
# replace 已 bump version,再带 1 应失败;先读当前版本再测过期。
@@ -153,7 +153,7 @@ def test_update_notice_line_version_mismatch(app):
resp = update_notice_line({
'task_id': task.task_no,
'line_index': 0,
'patch': {'hub_code': 'H8'},
'patch': {'inventory_source_hint': 'H8'},
'expected_order_data_version': stale,
})
assert resp['status'] == 'failed'
@@ -165,13 +165,13 @@ 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=[
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000002'},
{'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([
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000092918'},
{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'},
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000092918'},
])
plan = build_candidate_reconciliation_plan(
task=task,
@@ -200,9 +200,9 @@ def test_multiline_conflicts_persist_and_survive_line_replace(app):
def test_reconcile_exact_file_open_existing_auto_fill(app):
"""安全态 exact_file 可自动补空 Reservation。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10}])
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
result = reconcile_exact_file_open_existing(
task=task,
candidate=candidate,
+57 -31
View File
@@ -64,10 +64,12 @@ def test_dual_write_replace_persists_json_and_table(app):
task,
[
{
'sku': 'A001',
'part_number': 'A001',
'qty': 10,
'reservation_id': '3000092917',
'hub_code': 'H1',
'customer_part_number': 'C-A001',
'aws_part_number': 'AWS-A001',
'inventory_source_hint': 'H1',
'custom_note': 'keep-me',
}
],
@@ -75,17 +77,19 @@ def test_dual_write_replace_persists_json_and_table(app):
)
db.session.commit()
assert written[0]['sku'] == 'A001'
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].sku == 'A001'
assert rows[0].part_number == 'A001'
assert rows[0].qty == Decimal('10')
assert rows[0].reservation_id == '3000092917'
assert rows[0].hub_code == 'H1'
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
@@ -94,19 +98,19 @@ 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=[{'sku': 'OLD', 'qty': 1}])
task = _make_task(lines=[{'part_number': 'OLD', 'qty': 1}])
db.session.commit()
with pytest.raises(ValueError, match='invalid qty'):
replace_task_order_lines(
task,
[{'sku': 'BAD', 'qty': 0, 'reservation_id': 'R-1'}],
[{'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 == [{'sku': 'OLD', 'qty': 1}]
assert task.lines_json == [{'part_number': 'OLD', 'qty': 1}]
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
@@ -115,7 +119,7 @@ def test_clear_and_shadow_read(app, caplog):
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _make_task()
replace_task_order_lines(task, [{'sku': 'A001', 'qty': 2}], normalize=False)
replace_task_order_lines(task, [{'part_number': 'A001', 'qty': 2}], normalize=False)
db.session.commit()
clear_task_order_lines(task)
@@ -124,14 +128,14 @@ def test_clear_and_shadow_read(app, caplog):
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
# 人为制造影子差异:只改 JSON,不改表。
task.lines_json = [{'sku': 'SHADOW', 'qty': 9}]
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 == [{'sku': 'SHADOW', 'qty': 9}]
assert lines == [{'part_number': 'SHADOW', 'qty': 9}]
assert any('shadow mismatch' in message for message in caplog.messages)
@@ -142,9 +146,9 @@ def test_sync_from_json_backfill_idempotent_and_dry_run(app):
task_no='SN-LINE-BACKFILL-001',
lines=[
{
'sku': 'B002',
'part_number': 'B002',
'qty': '3.50',
'source_type': 'HUB',
'inventory_source_hint': 'HUB',
'legacy_flag': True,
}
],
@@ -176,7 +180,7 @@ def test_sync_rejects_invalid_historical_line(app):
with app.app_context():
task = _make_task(
task_no='SN-LINE-BAD-001',
lines=[{'sku': 'Z', 'qty': -1}],
lines=[{'part_number': 'Z', 'qty': -1}],
)
db.session.commit()
@@ -184,14 +188,14 @@ def test_sync_rejects_invalid_historical_line(app):
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 == [{'sku': 'Z', 'qty': -1}]
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=[{'sku': 'G1', 'qty': 1}])
bad = _make_task(task_no='SN-BF-BAD', lines=[{'sku': 'B1', 'qty': 0}])
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)
@@ -218,9 +222,9 @@ def test_json_write_mode_skips_table(app):
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, [{'sku': 'J1', 'qty': 4}], normalize=False)
replace_task_order_lines(task, [{'part_number': 'J1', 'qty': 4}], normalize=False)
db.session.commit()
assert task.lines_json[0]['sku'] == 'J1'
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'
@@ -233,17 +237,17 @@ def test_table_read_mode_returns_canonical_projection(app):
task = _make_task(task_no='SN-TABLE-READ')
replace_task_order_lines(
task,
[{'sku': 'T1', 'qty': 5, 'reservation_id': '3000092917'}],
[{'part_number': 'T1', 'qty': 5, 'reservation_id': '3000092917'}],
normalize=False,
)
db.session.commit()
# 人为制造 JSON 漂移:table 读路径不得返回漂移值。
task.lines_json = [{'sku': 'DRIFT', 'qty': 99}]
task.lines_json = [{'part_number': 'DRIFT', 'qty': 99}]
db.session.commit()
lines = read_task_order_lines(task)
assert lines == [{'sku': 'T1', 'qty': 5, 'reservation_id': '3000092917'}]
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
@@ -251,15 +255,15 @@ def test_table_read_mode_returns_canonical_projection(app):
def test_lines_checksum_stable_for_key_order(app):
"""checksum 对 dict key 顺序稳定,供影子对账。"""
left = [{'qty': 1, 'sku': 'A'}]
right = [{'sku': 'A', 'qty': 1}]
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 = [{'sku': 'A', 'qty': 1, 'reservation_id': 3000092917, 'hub_code': 12}]
right = [{'sku': 'A', 'qty': 1.0, 'reservation_id': '3000092917', 'hub_code': '12'}]
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)
@@ -271,9 +275,9 @@ def test_shadow_read_tolerates_unsaved_task(app):
task_no='SN-UNSAVED',
source_type='manual',
process_status='parsed',
lines_json=[{'sku': 'A001', 'qty': 1}],
lines_json=[{'part_number': 'A001', 'qty': 1}],
)
assert read_task_order_lines(task) == [{'sku': '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) == []
@@ -282,16 +286,38 @@ 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=[{'sku': 'OLD', 'qty': 1}])
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, [{'sku': 'NEW', 'qty': 2}], normalize=False)
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 == [{'sku': 'OLD', 'qty': 1}]
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
@@ -135,7 +135,7 @@ def test_shipping_task_line_orm_constraints_and_cascade(app):
task_no='SN-LINE-ORM-001',
source_type='manual',
process_status='parsed',
lines_json=[{'sku': 'A001', 'qty': 1}],
lines_json=[{'part_number': 'A001', 'qty': 1}],
)
db.session.add(task)
db.session.flush()
@@ -143,11 +143,10 @@ def test_shipping_task_line_orm_constraints_and_cascade(app):
line = ShippingTaskLine(
task_id=int(task.id),
position=0,
sku='A001',
part_number='A001',
qty=Decimal('1'),
reservation_id='1000140351',
source_type='DBS DUB',
hub_code='DUB1',
inventory_source_hint='DUB1',
extra_json={'legacy_note': 'kept'},
)
db.session.add(line)
@@ -168,7 +167,7 @@ def test_shipping_task_line_orm_constraints_and_cascade(app):
db.session.add(ShippingTaskLine(
task_id=int(task.id),
position=0,
sku='B001',
part_number='B001',
qty=Decimal('2'),
))
db.session.flush()
@@ -179,3 +178,63 @@ def test_shipping_task_line_orm_constraints_and_cascade(app):
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
@@ -22,8 +22,8 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
intake_id=1,
primary_document_id=1,
candidate_key='parsed-projection-1',
missing_fields_json=['hub_code'],
field_confidence_json={'sku': 0.95, 'qty': 0.9},
missing_fields_json=['inventory_source_hint'],
field_confidence_json={'part_number': 0.95, 'qty': 0.9},
evidence_json=[{
'field': 'lines[0].reservation_id',
'line_index': 0,
@@ -43,17 +43,15 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
po_number='4510038672',
source_candidate_id=int(candidate.id),
lines_json=[{
'sku': 'P123456',
'part_number': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
'inventory_source_hint': 'DBS DUB',
}],
step_payload_json={
'parse_validation': {
'status': 'ready',
'issues': [],
'contract_version': 'shipping-line-v1',
},
'process_field_gate': {
'status': 'ready',
@@ -67,11 +65,11 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
detail = serialize_task_detail(task)
assert detail['lines'][0]['reservation_id'] == '1000140351'
assert detail['lines'][0]['hub_code'] == 'DUB1'
assert detail['lines'][0]['inventory_source_hint'] == 'DBS DUB'
assert detail['parse_validation']['status'] == 'ready'
assert detail['process_field_gate']['status'] == 'ready'
assert detail['source_candidate']['candidate_no'] == 'SNC-PARSED-PROJECTION-001'
assert detail['source_candidate']['missing_fields'] == ['hub_code']
assert detail['source_candidate']['missing_fields'] == ['inventory_source_hint']
assert detail['source_candidate']['evidence'][0]['reservation_id'] == '1000140351'
@@ -84,51 +82,66 @@ def test_serialize_candidate_brief_exposes_evidence_and_missing_fields(app):
primary_document_id=1,
candidate_key='brief-evidence-1',
missing_fields_json=['reservation_id'],
field_confidence_json={'sku': 0.88},
evidence_json=[{'field': 'lines[0].sku', 'quote': 'SKU-A', 'document_id': 1}],
field_confidence_json={'part_number': 0.88},
evidence_json=[{'field': 'lines[0].part_number', 'quote': 'SKU-A', 'document_id': 1}],
conflicts_json=[{'field': 'reservation_id', 'reason': 'source_conflict'}],
structured_result_json={'business_summary': {'po_number': 'PO-1', 'lines': []}},
structured_result_json={
'business_summary': {'po_number': 'PO-1', 'lines': []},
'extraction': {
'field_adjudication': {
'schema_version': 'shipping-field-adjudication-v1',
'decisions': [{'field': 'part_number', 'status': 'consensus'}],
'observations': [{'observation_id': 'obs-current'}],
'observation_history': [
{'observation_id': 'obs-old'},
{'observation_id': 'obs-current'},
],
'conflicts': [],
},
},
},
)
brief = _serialize_candidate_brief(candidate)
assert brief['missing_fields'] == ['reservation_id']
assert brief['field_confidence']['sku'] == 0.88
assert brief['field_confidence']['part_number'] == 0.88
assert brief['evidence'][0]['quote'] == 'SKU-A'
assert brief['conflicts'][0]['reason'] == 'source_conflict'
assert brief['field_adjudication']['decisions'][0]['status'] == 'consensus'
assert [
item['observation_id']
for item in brief['field_adjudication']['observation_history']
] == ['obs-old', 'obs-current']
def test_normalize_notice_line_keeps_hub_code_independent_of_source_type():
"""Hub Code 不得折叠进 source_type;两者应同时保留。"""
def test_normalize_notice_line_keeps_inventory_source_hint():
"""V2 订单行应保留唯一的 inventory_source_hint 路由线索。"""
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
from app.services.shipping_notice.notice_lines import normalize_notice_line
line = normalize_notice_line({
'sku': 'P123456',
'part_number': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
'inventory_source_hint': 'DBS DUB',
'Hub Code': 'SHOULD_NOT_OVERRIDE_EXPLICIT',
})
assert line is not None
assert line['source_type'] == 'DBS DUB'
assert line['hub_code'] == 'DUB1'
assert line['inventory_source_hint'] == 'DBS DUB'
summary = normalize_candidate_business_summary({
'po_number': '4510038672',
'lines': [{
'sku': 'P123456',
'part_number': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'VMI-FRA01',
'hub_code': 'FRA01',
'inventory_source_hint': 'VMI-FRA01',
}],
})
assert summary['lines'][0]['source_type'] == 'VMI-FRA01'
assert summary['lines'][0]['hub_code'] == 'FRA01'
assert summary['lines'][0]['inventory_source_hint'] == 'VMI-FRA01'
def test_candidate_update_persists_hub_code_round_trip(app):
"""Candidate 人工修订保存后,hub_code 必须仍在 business_summary 中。"""
def test_candidate_update_persists_inventory_source_hint_round_trip(app):
"""Candidate 人工修订保存后,inventory_source_hint 必须仍在 business_summary 中。"""
from app.models import Agent, ChatSession, FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, User
from app.services.shipping_notice.candidate_service import update_candidate
@@ -197,7 +210,7 @@ def test_candidate_update_persists_hub_code_round_trip(app):
structured_result_json={
'business_summary': {
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
'lines': [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
},
},
)
@@ -210,19 +223,16 @@ def test_candidate_update_persists_hub_code_round_trip(app):
business_summary={
'po_number': '4510038672',
'lines': [{
'sku': 'P123456',
'part_number': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
'inventory_source_hint': 'DBS DUB',
'uom': 'EA',
}],
},
)
line = updated['business_summary']['lines'][0]
assert line['source_type'] == 'DBS DUB'
assert line['hub_code'] == 'DUB1'
assert line['inventory_source_hint'] == 'DBS DUB'
db.session.refresh(candidate)
persisted = candidate.structured_result_json['business_summary']['lines'][0]
assert persisted['hub_code'] == 'DUB1'
assert persisted['source_type'] == 'DBS DUB'
assert persisted['inventory_source_hint'] == 'DBS DUB'