feat(shipping-notice): 实现货代发货通知的库存全流程与对话交互

This commit is contained in:
hugo committed 2026-06-03 11:09:46 +08:00
1 parent a5cc48b6aa
commit 2607f4a9f6
26 files changed
+5013 -256

No files matched your search

@@ -0,0 +1,111 @@
from app.services.shipping_notice.extract import extract_notice_fields
from app.services.shipping_notice.notice_lines import (
normalize_notice_line,
parse_notice_table_rows,
parse_notice_table_text,
validate_notice_lines,
)
from app.services.shipping_notice.reservation_id import (
looks_like_reservation_id,
normalize_reservation_id,
)
def test_normalize_reservation_id_from_excel_float():
assert normalize_reservation_id(1000140351.0) == "1000140351"
assert normalize_reservation_id("1000140351.0") == "1000140351"
assert looks_like_reservation_id("1000140351")
def test_parse_notice_table_numeric_reservation_id():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\t1000140351\t2\t15.5\t31.0
"""
lines = parse_notice_table_text(text)
assert lines[0]["reservation_id"] == "1000140351"
def test_infer_reservation_id_without_header():
headers = ["AWS Sku", "Ref", "Qty"]
rows = [["10-40594-001", 1000140351, 2]]
lines = parse_notice_table_rows(headers, rows)
assert lines[0]["reservation_id"] == "1000140351"
def test_parse_notice_table_with_all_fields():
text = """
AWS Sku\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]["reservation_id"] == "AWS-311"
assert lines[0]["qty"] == 2
assert lines[0]["unit_price"] == 15.5
assert lines[0]["amount"] == 31.0
def test_normalize_notice_line_aliases():
line = normalize_notice_line(
{
"part_number": "A-001",
"quantity": "3",
"com_id": "COM-99",
"price": "12.5",
}
)
assert line == {
"sku": "A-001",
"qty": 3.0,
"uom": "EA",
"reservation_id": "COM-99",
"unit_price": 12.5,
"amount": 37.5,
}
def test_extract_notice_fields_structured():
structured = {
"customer_name": "ACME",
"lines": [
{
"sku": "10-40594-001",
"qty": 2,
"reservation_id": "AWS-311",
"unit_price": 10,
"amount": 20,
}
],
"confidence": 0.9,
}
parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured)
assert parsed["lines"][0]["reservation_id"] == "AWS-311"
assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.8
assert not any("未解析到有效订单行" in w for w in warnings)
def test_validate_notice_lines_missing_reservation():
warnings = validate_notice_lines([{"sku": "A001", "qty": 1, "uom": "EA"}])
assert any("Reservation ID" in w for w in warnings)
def test_heuristic_table_skips_title_row():
from app.services.shipping_notice.extract import _heuristic_extract
text = """
Shipping Notice
AWS Sku\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]["reservation_id"] == "ORD-3002"
assert parsed["lines"][0]["qty"] == 4
assert parsed["lines"][0]["unit_price"] == 5
assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.5
@@ -0,0 +1,73 @@
"""Tests for AWS inventory template parsing."""
from pathlib import Path
from openpyxl import Workbook
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_rows,
parse_inventory_text,
read_inventory_schema_preview,
)
from app.services.shipping_notice.match import match_notice_lines
def _write_title_row_inventory_xlsx(path: Path) -> None:
wb = Workbook()
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])
wb.save(str(path))
wb.close()
def test_read_inventory_schema_preview_skips_title_row(app, tmp_path):
path = tmp_path / "aws_title.xlsx"
_write_title_row_inventory_xlsx(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["suggested_mapping"]["available_qty"] == "Qty Available"
assert preview["sample_rows"][0][0] == "10-40594-001"
def test_parse_aws_inventory_headers(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "Qty"]
data = [
["10-40594-001", "AWS-311", 2, 1],
["10-40594-002", "ORD-3002", 0, 5],
]
lines = parse_inventory_rows(headers, data)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["available_qty"] == 2.0
assert lines[1]["reservation_id"] == "ORD-3002"
assert lines[1]["available_qty"] == 0.0
def test_match_aggregates_same_sku_reservation():
notice = [{"sku": "10-40594-001", "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},
]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["available_qty"] == 3.0
def test_parse_inventory_text_aws_table(app):
with app.app_context():
text = "AWS Sku\tReservation Order\tQty\n10-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]["reservation_id"] == "ORD-3002"
assert lines[0]["available_qty"] == 4.0
assert column_meta["mapping"]["reservation_id"]["source_column"] == "Reservation Order"
@@ -0,0 +1,15 @@
from app.services.shipping_notice.match import match_notice_lines
from app.services.shipping_notice.reservation_id import normalize_reservation_id
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}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["reservation_id"] == "1000140351"
assert results[0]["available_qty"] == 3
def test_normalize_reservation_id_string():
assert normalize_reservation_id("1000140351") == "1000140351"
+484 -6
View File
@@ -3,12 +3,8 @@ from app.models import ShippingCase
def _tool_headers(app):
key = app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or app.config.get("INTEGRATION_API_KEY") or "test-tool-key"
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = key
app.config["INTEGRATION_API_KEY"] = key
return {
"Content-Type": "application/json",
"X-Shipping-Tool-Key": key,
}
@@ -127,8 +123,221 @@ def test_openapi_spec_public(app, client):
assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice"
props = spec["paths"]["/tools/create_case"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
assert "raw_content" in props
assert "ShippingToolKey" in spec["components"]["securitySchemes"]
assert "/rpa/" not in str(spec["paths"])
assert "/tools/parse_inventory" in spec["paths"]
assert "/tools/get_inventory_schema_preview" in spec["paths"]
assert "/tools/apply_inventory_mapping" in spec["paths"]
def test_parse_inventory_from_chat_text(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
inv_text = "料号\t可用数量\nA001\t10\nB002\t5"
parse_inv = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": inv_text},
)
assert parse_inv.status_code == 200
data = parse_inv.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "inventory_field_mapping_review"
assert data.get("stop_agent_turn") is True
assert "match_inventory" in (data.get("forbidden_next_tools") or [])
assert "field_alignment" in data["data"]
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm_inventory_mapping"},
)
assert confirm_res.get_json()["status"] == "ok"
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
)
assert match_res.get_json()["status"] == "ok"
def test_parse_inventory_empty_needs_human(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": " "},
)
assert res.get_json()["status"] == "needs_human"
assert "reparse_inventory" in (res.get_json().get("human_options") or [])
def test_match_by_aws_sku_and_reservation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"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"},
],
"confidence": 0.95,
},
},
)
inv_text = (
"AWS Sku\tCOM ID\tQty Available\n"
"10-40594-001\tAWS-311\t2\n"
"10-40594-001\tORD-3002\t0\n"
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": inv_text},
)
client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm_inventory_mapping"},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
results = {r["reservation_id"]: r for r in data["data"]["line_results"]}
assert results["AWS-311"]["line_status"] == "ok"
assert results["ORD-3002"]["line_status"] == "shortage"
def test_match_inventory_blocked_before_mapping_confirm(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"case_id": case_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
)
blocked = match_res.get_json()
assert blocked["status"] == "needs_human"
assert blocked.get("checkpoint") == "inventory_field_mapping_review"
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"]["reservation_id"]["source_column"] == "COM ID"
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"case_id": case_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
correct_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "correct_inventory_mapping"},
)
data = correct_res.get_json()
assert data["status"] == "ok"
assert data.get("checkpoint") == "inventory_mapping_inference"
assert "schema_preview" in data["data"]
assert data["data"]["schema_preview"]["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
@@ -164,8 +373,9 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
)
assert cb_res.status_code == 200
data = cb_res.get_json()
assert data["status"] == "ok"
assert data["status"] == "needs_human"
assert data["data"]["process_status"] == "inventory_ready"
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
def test_rpa_upload_callback(app, client, tmp_path):
@@ -220,3 +430,271 @@ def test_rpa_upload_callback(app, client, tmp_path):
assert cb_res.status_code == 200
assert cb_res.get_json()["status"] == "ok"
assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001"
def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 1000
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
from io import BytesIO
from openpyxl import Workbook
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["10-40594-001", "AWS-311", 5])
wb.save(buf)
wb.close()
buf.seek(0)
upload_res = client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={
"case_id": case_id,
"file": (buf, "inventory.xlsx"),
},
)
assert upload_res.status_code == 200
upload_data = upload_res.get_json()
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "inventory_mapping_inference"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"case_id": case_id,
"column_mapping_json": preview["suggested_mapping"],
},
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data.get("checkpoint") == "inventory_field_mapping_review"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
def test_get_inventory_schema_preview(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
missing = client.post(
"/api/shipping-notice/tools/get_inventory_schema_preview",
headers=headers,
json={"case_id": case_id},
)
assert missing.get_json()["checkpoint"] == "inventory_upload_required"
def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
from io import BytesIO
from openpyxl import Workbook
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Part No", "Resv", "On Hand"])
ws.append(["SKU-99", "R-1", 12])
wb.save(buf)
wb.close()
buf.seek(0)
client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"case_id": case_id, "file": (buf, "inv.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"case_id": case_id,
"column_mapping_json": {
"sku": "Part No",
"reservation_id": "Resv",
"available_qty": "On Hand",
},
},
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data["data"]["inventory_row_count"] == 1
sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0]
assert sample["sku"] == "SKU-99"
assert sample["available_qty"] == 12
def test_confirm_parse_does_not_skip_inventory_match(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
)
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "ok"
assert confirm_data.get("checkpoint") == "parse_confirmed"
assert "generate_shipment_excel" in (confirm_data.get("forbidden_next_tools") or [])
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"case_id": case_id},
)
excel_data = excel_res.get_json()
assert excel_data["status"] == "failed"
assert "匹配" in excel_data["message"]
with app.app_context():
case = ShippingCase.query.filter_by(case_no=case_id).first()
assert case is not None
assert case.process_status == "parsed"
assert case.match_status is None
def test_submit_decision_by_conversation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
case_id = create_res.get_json()["case_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"conversation_id": "conv-test-001",
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
)
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"conversation_id": "conv-test-001", "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "ok"
assert confirm_data["case_id"] == case_id
assert confirm_data.get("checkpoint") == "parse_confirmed"
dup_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
dup_data = dup_res.get_json()
assert dup_data["case_id"] == case_id
assert dup_data.get("checkpoint") == "case_already_exists"
def test_parse_inventory_rejects_oversized_text(app, client):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100
create_res = client.post(
"/api/shipping-notice/tools/create_case",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": "x" * 200},
)
data = res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "inventory_upload_required"
assert "过大" in data["message"]
def test_chat_actions_empty_when_case_rejected(app):
from app.services.shipping_notice.chat_actions import build_chat_actions_payload, human_options_for_case
with app.app_context():
case = ShippingCase(
case_no="SN-20260101-TEST0001",
source_type="manual",
process_status="rejected",
review_status="rejected",
)
assert human_options_for_case(case) == []
payload = build_chat_actions_payload(case)
assert payload["checkpoint"] == "rejected"
assert payload["action_buttons"] == []