feat(shipping-notice): 完成货代发货通知全流程开发与代码重构

- 新增PO号提取、预约ID解析(支持`PR@xxx`格式)工具,完善库存匹配逻辑
- 新增库存映射缓存、匹配/解析结果格式化摘要,优化用户提示
- 修复数据库迁移脚本未检查表存在的问题,避免全新部署失败
- 新增路径工具类统一管理相对路径,优化配置文件处理逻辑
- 归档旧文档,将部署、Dify配置合并到`shipping_notice.md`
- 新增完整单元测试与集成测试覆盖核心流程
- 更新前端国际化与会话管理逻辑,优化界面交互
This commit is contained in:
hugo committed 2026-06-04 15:26:34 +08:00
1 parent b62082758b
commit 8deae3146b
65 files changed
+6477 -1937

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
from pathlib import Path
from app.path_utils import backend_dir, resolve_backend_relative_path
def test_resolve_backend_relative_path_legacy_prefix():
root = backend_dir()
resolved = Path(resolve_backend_relative_path("backend/data/shipping_notice"))
assert resolved == (root / "data" / "shipping_notice").resolve()
def test_resolve_backend_relative_path_data_prefix():
root = backend_dir()
resolved = Path(resolve_backend_relative_path("data/shipping_notice"))
assert resolved == (root / "data" / "shipping_notice").resolve()
def test_resolve_backend_relative_path_default():
root = backend_dir()
default = root / "data" / "freight_rpa" / "inventory_drop"
resolved = Path(resolve_backend_relative_path(None, default))
assert resolved == default.resolve()
@@ -6,11 +6,38 @@ from app.services.shipping_notice.notice_lines import (
validate_notice_lines,
)
from app.services.shipping_notice.reservation_id import (
extract_reservation_id,
find_reservation_id_in_document,
looks_like_reservation_id,
normalize_reservation_id,
)
def test_extract_reservation_id_from_pr_number():
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
def test_wistron_po_table_with_pr_number_in_document():
text = """
Vendor: HOXIN
PR Number: ADU_S-ENCWIW260528126265@1000140351
Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tAmount
10\t504-010213-001\tB3-A08AR11000001\tENCLOSURE\t9.000 PCS\t2026/06/15\t1,607.72 USD\t14,469.48 USD
"""
lines = parse_notice_table_text(text)
assert len(lines) == 1
assert lines[0]["sku"] == "504-010213-001"
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]["currency"] == "USD"
def test_normalize_reservation_id_from_excel_float():
assert normalize_reservation_id(1000140351.0) == "1000140351"
assert normalize_reservation_id("1000140351.0") == "1000140351"
@@ -55,18 +82,60 @@ def test_normalize_notice_line_aliases():
"quantity": "3",
"com_id": "COM-99",
"price": "12.5",
"delivery_date": "2026/06/15",
"vendorPartNumber": "VND-001",
"currency": "USD",
"line_no": "10",
}
)
assert line == {
"line_no": "10",
"sku": "A-001",
"qty": 3.0,
"uom": "EA",
"reservation_id": "COM-99",
"unit_price": 12.5,
"amount": 37.5,
"currency": "USD",
"required_date": "2026-06-15",
"vendor_part_number": "VND-001",
}
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"}],
}
)
assert parsed["lines"][0]["currency"] == "USD"
assert parsed["lines"][1]["currency"] == "EUR"
def test_extract_currency_from_price_string():
from app.services.shipping_notice.notice_lines import _extract_currency
assert _extract_currency("1,607.72 USD") == "USD"
assert _extract_currency("$15.5") == "USD"
assert _extract_currency("¥100") == "CNY"
def test_enrich_notice_with_document_required_date():
from app.services.shipping_notice.notice_lines import 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"}],
}
)
assert parsed["lines"][0]["required_date"] == "2026-06-20"
assert parsed["lines"][1]["required_date"] == "2026-06-18"
def test_extract_notice_fields_structured():
structured = {
"customer_name": "ACME",
@@ -5,6 +5,7 @@ from pathlib import Path
from openpyxl import Workbook
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
parse_inventory_rows,
parse_inventory_text,
read_inventory_schema_preview,
@@ -23,6 +24,19 @@ def _write_title_row_inventory_xlsx(path: Path) -> None:
wb.close()
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(["EARLY-001", 7])
ws.append([])
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["LATE-001", "ORD-1", 5])
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)
@@ -71,3 +85,42 @@ def test_parse_inventory_text_aws_table(app):
assert lines[0]["reservation_id"] == "ORD-3002"
assert lines[0]["available_qty"] == 4.0
assert column_meta["mapping"]["reservation_id"]["source_column"] == "Reservation Order"
def test_read_inventory_schema_preview_suggests_misspelled_reservation_order(app, tmp_path):
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])
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["suggested_mapping"]["reservation_id"] == "Resevation Order"
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"}
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,
field_mapping=mapping,
mapping_source="manual",
header_row_index=2,
)
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)
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}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["available_qty"] == 1.0
@@ -0,0 +1,43 @@
from app.services.shipping_notice.match_rule_desc import (
build_match_rule_fallback,
extract_mapping_payload_extras,
resolve_match_rule,
)
def test_extract_mapping_payload_extras():
payload = {
"sku": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
"match_rule": "以 Reservation Order 对齐订单 reservation_id,汇总 Qty Available 与订单 qty 比对。",
}
extras = extract_mapping_payload_extras(payload)
assert extras["match_rule"].startswith("以 Reservation Order")
assert "match_key" not in extras
def test_resolve_match_rule_prefers_llm():
mapping = {
"sku": "AWS 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 source == "llm"
def test_build_match_rule_fallback_uses_column_names():
mapping = {
"sku": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
rule = build_match_rule_fallback(mapping)
assert "AWS Sku" in rule
assert "Reservation Order" in rule
assert "Qty Available" in rule
assert "按 SKU + Reservation ID" not in rule
@@ -0,0 +1,40 @@
from app.services.shipping_notice.match import format_match_summary
def test_format_match_summary_fulfillable():
msg = format_match_summary(
"fulfillable",
[
{
"sku": "10-40594-001",
"reservation_id": "AWS-311",
"required_qty": 2,
"available_qty": 5,
"shortage_qty": 0,
"line_status": "ok",
}
],
)
assert "匹配明细" in msg
assert "订单 2 / 库存 5" in msg
assert "充足" in msg
assert "可生成发货 Excel" in msg
def test_format_match_summary_shortage():
msg = format_match_summary(
"partial",
[
{
"sku": "A001",
"reservation_id": "R-1",
"required_qty": 100,
"available_qty": 5,
"shortage_qty": 95,
"line_status": "partial",
}
],
)
assert "订单 100 / 库存 5" in msg
assert "缺口 95" in msg
assert "部分行库存不足" in msg
@@ -0,0 +1,57 @@
from app.services.shipping_notice.parse_summary import format_parse_summary
def test_format_parse_summary_single_line():
msg = format_parse_summary(
task_no="SN-20260604-7249E4D7",
po_number="16754796",
ship_to="Wistron Corporation, Czech Republic",
lines=[
{
"sku": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "PCS",
"unit_price": 1607.72,
"amount": 14469.48,
"currency": "USD",
"required_date": "2026-06-15",
}
],
)
assert "【发货通知解析确认】任务编号:SN-20260604-7249E4D7" in msg
assert "| PO | 16754796 |" in msg
assert "| SKU | 504-010213-001 |" in msg
assert "| Reservation ID | 1000140351 |" in msg
assert "| 数量 | 9 PCS |" in msg
assert "| 单价 | $1,607.72 |" in msg
assert "| 金额 | $14,469.48 |" in msg
assert "| 需求日期 | 2026-06-15 |" in msg
assert "Wistron Corporation, Czech Republic" in msg
assert "请确认以上信息是否正确?" in msg
assert "待从任务中获取" not in msg
def test_format_parse_summary_multiple_lines():
msg = format_parse_summary(
task_no="SN-1",
po_number="PO-1",
lines=[
{"sku": "A", "qty": 1, "reservation_id": "R1"},
{"sku": "B", "qty": 2, "reservation_id": "R2"},
],
)
assert "【明细 1】" in msg
assert "【明细 2】" in msg
assert "PO:PO-1" in msg
def test_format_parse_summary_includes_warnings():
msg = format_parse_summary(
task_no="SN-1",
lines=[{"sku": "A", "qty": 1}],
warnings=["订单行未解析到 Reservation ID"],
low_confidence=True,
)
assert "订单行未解析到 Reservation ID" in msg
assert "解析置信度较低" in msg
@@ -0,0 +1,30 @@
from app.services.shipping_notice.po_number import find_po_number_in_document, normalize_po_number
from app.services.shipping_notice.extract import extract_notice_fields
def test_find_po_number_in_document():
text = """
PO Number: PO-2026-001
PR Number: ADU_S-PO260528126265@1000140351
"""
assert find_po_number_in_document(text) == "PO-2026-001"
def test_po_number_not_from_pr_number():
text = "PR Number: ADU_S-PO260528126265@1000140351"
assert find_po_number_in_document(text) == ""
def test_normalize_po_number():
assert normalize_po_number(" PO-99 ") == "PO-99"
assert normalize_po_number("") == ""
def test_extract_notice_fields_includes_po_number():
structured = {
"po_number": "PO-2026-001",
"lines": [{"sku": "A-001", "qty": 1}],
"confidence": 0.9,
}
parsed, _, _ = extract_notice_fields(raw_text="", structured=structured)
assert parsed["po_number"] == "PO-2026-001"
+220 -109
View File
@@ -1,5 +1,5 @@
from app import db
from app.models import ShippingCase
from app.models import ShippingInventoryMapping, ShippingTask
def _tool_headers(app):
@@ -12,29 +12,39 @@ def test_shipping_notice_tool_flow(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"},
)
assert create_res.status_code == 200
create_data = create_res.get_json()
assert create_data["status"] == "ok"
case_id = create_data["case_id"]
task_id = create_data["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={"case_id": case_id, "raw_text": "客户:ACME 料号A001 x 10"},
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
assert parse_res.status_code == 200
assert parse_res.get_json()["status"] in {"ok", "needs_human"}
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| SKU | A001 |" in parse_body["message"]
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"case_id": case_id,
"inventory_lines": [{"sku": "A001", "available_qty": 10}],
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
assert inv_res.status_code == 200
@@ -43,28 +53,32 @@ def test_shipping_notice_tool_flow(app, client):
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert match_res.status_code == 200
assert match_res.get_json()["status"] == "ok"
match_data = match_res.get_json()
assert match_data["status"] == "ok"
assert "订单" in match_data["message"]
assert "库存" in match_data["message"]
assert "A001" in match_data["message"]
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert excel_res.status_code == 200
assert excel_res.get_json()["status"] == "ok"
with app.app_context():
case = ShippingCase.query.filter_by(case_no=case_id).first()
assert case is not None
assert case.export_file_path
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.export_file_path
status_res = client.post(
"/api/shipping-notice/tools/get_case_status",
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert status_res.status_code == 200
assert status_res.get_json()["status"] == "ok"
@@ -74,20 +88,20 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 100, "uom": "EA"}],
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -95,21 +109,24 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"case_id": case_id, "inventory_lines": [{"sku": "A001", "available_qty": 5}]},
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert "订单" in data["message"]
assert "库存" in data["message"]
assert "缺口" in data["message"]
assert "confirm" in (data.get("human_options") or [])
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm"},
json={"task_id": task_id, "decision": "confirm"},
)
assert confirm_res.get_json()["status"] == "ok"
@@ -119,9 +136,9 @@ def test_openapi_spec_public(app, client):
res = client.get("/api/shipping-notice/tools/openapi.json")
assert res.status_code == 200
spec = res.get_json()
assert "create_case" in str(spec)
assert "create_task" in str(spec)
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"]
props = spec["paths"]["/tools/create_task"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
assert "raw_content" in props
assert "/rpa/" not in str(spec["paths"])
assert "/tools/parse_inventory" in spec["paths"]
@@ -133,20 +150,20 @@ def test_parse_inventory_from_chat_text(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 10, "uom": "EA"}],
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -156,7 +173,7 @@ def test_parse_inventory_from_chat_text(app, client):
parse_inv = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": inv_text},
json={"task_id": task_id, "raw_inventory_text": inv_text},
)
assert parse_inv.status_code == 200
data = parse_inv.get_json()
@@ -169,30 +186,33 @@ def test_parse_inventory_from_chat_text(app, client):
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm_inventory_mapping"},
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
assert confirm_res.get_json()["status"] == "ok"
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "needs_human"
assert confirm_data.get("checkpoint") == "inventory_field_mapping_review"
assert "Reservation ID" in (confirm_data.get("message") or "")
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert match_res.get_json()["status"] == "ok"
assert match_res.get_json()["status"] in {"failed", "needs_human"}
def test_parse_inventory_empty_needs_human(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": " "},
json={"task_id": task_id, "raw_inventory_text": " "},
)
assert res.get_json()["status"] == "needs_human"
assert "reparse_inventory" in (res.get_json().get("human_options") or [])
@@ -201,17 +221,17 @@ def test_parse_inventory_empty_needs_human(app, client):
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",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [
@@ -231,18 +251,18 @@ def test_match_by_aws_sku_and_reservation_id(app, client):
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": inv_text},
json={"task_id": task_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"},
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
@@ -254,17 +274,17 @@ def test_match_by_aws_sku_and_reservation_id(app, client):
def test_match_inventory_blocked_before_mapping_confirm(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
@@ -276,7 +296,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
@@ -284,7 +304,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
blocked = match_res.get_json()
assert blocked["status"] == "needs_human"
@@ -296,22 +316,61 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
assert mapping["inventory_columns"]["mapping"]["reservation_id"]["source_column"] == "COM ID"
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
def test_match_inventory_requires_reservation_id(app, client):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
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}],
},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "reservation_id_required"
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_task",
headers=headers,
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": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
@@ -323,7 +382,7 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
@@ -331,7 +390,7 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
correct_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "correct_inventory_mapping"},
json={"task_id": task_id, "decision": "correct_inventory_mapping"},
)
data = correct_res.get_json()
assert data["status"] == "ok"
@@ -350,11 +409,11 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
from openpyxl import Workbook
@@ -369,7 +428,7 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
json={"case_no": case_id, "success": True, "file_path": str(inv_file)},
json={"task_no": task_id, "success": True, "file_path": str(inv_file)},
)
assert cb_res.status_code == 200
data = cb_res.get_json()
@@ -388,20 +447,20 @@ def test_rpa_upload_callback(app, client, tmp_path):
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 5, "uom": "EA"}],
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -409,23 +468,23 @@ def test_rpa_upload_callback(app, client, tmp_path):
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"case_id": case_id, "inventory_lines": [{"sku": "A001", "available_qty": 10}]},
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
cb_res = client.post(
"/api/shipping-notice/rpa/upload-complete",
headers=headers,
json={"case_no": case_id, "success": True, "freight_ref_no": "FR-001"},
json={"task_no": task_id, "success": True, "freight_ref_no": "FR-001"},
)
assert cb_res.status_code == 200
assert cb_res.get_json()["status"] == "ok"
@@ -438,17 +497,17 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 1000
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
@@ -474,7 +533,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
"/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,
"task_id": task_id,
"file": (buf, "inventory.xlsx"),
},
)
@@ -490,14 +549,69 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"case_id": case_id,
"column_mapping_json": preview["suggested_mapping"],
"task_id": task_id,
"column_mapping_json": {
**preview["suggested_mapping"],
"match_rule": "LLM:Reservation Order 对齐订单 reservation_id,汇总 Qty Available。",
},
},
)
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
assert apply_data["data"]["field_alignment"]["match_rule"].startswith("LLM:")
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "llm"
with app.app_context():
assert ShippingInventoryMapping.query.filter_by(customer_code="GLOBAL").count() >= 1
def test_apply_inventory_mapping_fallback_match_rule(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_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
from io import BytesIO
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["504-010213-001", "1000140351", 5])
buf = BytesIO()
wb.save(buf)
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={"task_id": task_id, "file": (buf, "inventory.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
},
)
apply_data = apply_res.get_json()
match_rule = apply_data["data"]["field_alignment"]["match_rule"]
assert "AWS Sku" in match_rule
assert "COM ID" in match_rule
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "fallback"
def test_get_inventory_schema_preview(app, client, tmp_path):
@@ -505,16 +619,16 @@ def test_get_inventory_schema_preview(app, client, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
missing = client.post(
"/api/shipping-notice/tools/get_inventory_schema_preview",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert missing.get_json()["checkpoint"] == "inventory_upload_required"
@@ -524,11 +638,11 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
from io import BytesIO
@@ -546,14 +660,14 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
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")},
data={"task_id": task_id, "file": (buf, "inv.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"column_mapping_json": {
"sku": "Part No",
"reservation_id": "Resv",
@@ -573,17 +687,17 @@ 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",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
@@ -595,44 +709,42 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm"},
json={"task_id": task_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 [])
assert confirm_data["status"] in {"ok", "running", "needs_human"}
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_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
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status in {"parsed", "waiting_inventory"}
assert task.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",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"conversation_id": "conv-test-001",
"structured": {
"customer_name": "Wistron",
@@ -648,18 +760,17 @@ def test_submit_decision_by_conversation_id(app, client):
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"
assert confirm_data["status"] in {"ok", "running", "needs_human"}
assert confirm_data["task_id"] == task_id
dup_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
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"
assert dup_data["task_id"] == task_id
assert dup_data.get("checkpoint") == "task_already_exists"
def test_parse_inventory_rejects_oversized_text(app, client):
@@ -667,16 +778,16 @@ def test_parse_inventory_rejects_oversized_text(app, client):
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": "x" * 200},
json={"task_id": task_id, "raw_inventory_text": "x" * 200},
)
data = res.get_json()
assert data["status"] == "needs_human"
@@ -684,17 +795,17 @@ def test_parse_inventory_rejects_oversized_text(app, client):
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
def test_chat_actions_empty_when_task_rejected(app):
from app.services.shipping_notice.chat_actions import build_chat_actions_payload, human_options_for_task
with app.app_context():
case = ShippingCase(
case_no="SN-20260101-TEST0001",
task = ShippingTask(
task_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 human_options_for_task(task) == []
payload = build_chat_actions_payload(task)
assert payload["checkpoint"] == "rejected"
assert payload["action_buttons"] == []