import pytest from app import db from app.models import ShippingInventoryMapping, ShippingTask, ShippingTaskEvent from app.services.shipping_notice.match import match_notice_lines def _tool_headers(app): app.config["INTEGRATION_API_KEY"] = "test-integration-key" return { "Content-Type": "application/json", "X-Integration-Key": "test-integration-key", } def test_match_notice_lines_reports_progress(): seen: list[tuple[int, int]] = [] status, line_results, shortage = match_notice_lines( [ {"sku": "A001", "reservation_id": "R-1", "qty": 1}, {"sku": "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}, ], progress_callback=lambda current, total: seen.append((current, total)), ) assert status == "fulfillable" assert len(line_results) == 2 assert shortage["lines"] == [] assert seen == [(1, 2), (2, 2)] def test_shipping_notice_tool_flow(app, client): headers = _tool_headers(app) create_res = client.post( "/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" task_id = create_data["task_id"] parse_res = client.post( "/api/shipping-notice/tools/parse_notice", headers=headers, 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 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"] 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}], }, ) assert inv_res.status_code == 200 assert inv_res.get_json()["status"] == "ok" match_res = client.post( "/api/shipping-notice/tools/match_inventory", headers=headers, json={"task_id": task_id}, ) assert match_res.status_code == 200 match_data = match_res.get_json() assert match_data["status"] == "running" assert "订单" in match_data["message"] assert "库存" in match_data["message"] assert "A001" in match_data["message"] with app.app_context(): auto_exported = ShippingTask.query.filter_by(task_no=task_id).first() assert auto_exported is not None assert auto_exported.export_file_path assert auto_exported.process_status == "waiting_upload" assert auto_exported.pending_human_reason == "upload_rpa_pending" excel_res = client.post( "/api/shipping-notice/tools/generate_shipment_excel", headers=headers, json={"task_id": task_id}, ) assert excel_res.status_code == 200 assert excel_res.get_json()["status"] == "ok" with app.app_context(): 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_task_status", headers=headers, json={"task_id": task_id}, ) assert status_res.status_code == 200 assert status_res.get_json()["status"] == "ok" def test_shipping_notice_match_shortage_needs_human(app, client): headers = _tool_headers(app) 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": "ACME", "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "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": 5}]}, ) 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 "订单" in data["message"] assert "库存" in data["message"] assert "缺口" in data["message"] options = data.get("human_options") or [] assert "confirm" not in options assert "reparse_inventory" in options assert "rematch" in options confirm_res = client.post( "/api/shipping-notice/tools/submit_decision", headers=headers, json={"task_id": task_id, "decision": "confirm"}, ) assert confirm_res.get_json()["status"] == "failed" def test_submit_decision_rematch_reopens_shortage_for_worker(app, client, monkeypatch): headers = _tool_headers(app) started: list[str] = [] from app.services.shipping_notice import decision_workflow monkeypatch.setattr( decision_workflow, "start_task_orchestrator", lambda task_no: started.append(str(task_no)) or True, ) 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": "ACME", "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "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": 5}]}, ) client.post( "/api/shipping-notice/tools/match_inventory", headers=headers, json={"task_id": task_id}, ) rematch_res = client.post( "/api/shipping-notice/tools/submit_decision", headers=headers, json={"task_id": task_id, "decision": "rematch"}, ) assert rematch_res.status_code == 200 assert rematch_res.get_json()["status"] == "running" assert started == [task_id] with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).one() assert task.process_status == "inventory_ready" assert task.review_status is None assert task.pending_human_reason is None assert task.match_status is None assert task.shortage_json is None assert task.line_results_json is None def test_openapi_spec_public(app, client): app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com" res = client.get("/api/shipping-notice/tools/openapi.json") assert res.status_code == 200 spec = res.get_json() assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice" assert "/rpa/" not in str(spec["paths"]) assert "/tools/create_task" not in spec["paths"] assert "/tools/create_batch" not in spec["paths"] assert "/tools/parse_inventory" not in spec["paths"] assert "/tools/ensure_inventory" not in spec["paths"] assert "/tools/auto_progress" not in spec["paths"] assert "/tools/match_inventory" not in spec["paths"] assert "/tools/generate_shipment_excel" not in spec["paths"] assert "/tools/upload_to_freight" not in spec["paths"] assert "/tools/switch_focus_task" not in spec["paths"] assert "/tools/get_inventory_schema_preview" in spec["paths"] assert "/tools/apply_inventory_mapping" in spec["paths"] submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"] assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"] def test_parse_inventory_from_chat_text(app, client): headers = _tool_headers(app) 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": "ACME", "lines": [{"sku": "A001", "reservation_id": "R-1", "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={"task_id": task_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") == "align_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={"task_id": task_id, "decision": "confirm_inventory_mapping"}, ) confirm_data = confirm_res.get_json() assert confirm_data["status"] == "needs_human" assert confirm_data.get("checkpoint") == "align_review" assert "Reservation ID" in (confirm_data.get("message") or "") match_res = client.post( "/api/shipping-notice/tools/match_inventory", headers=headers, json={"task_id": task_id}, ) 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_task", headers=headers, json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, json={"task_id": task_id, "raw_inventory_text": " "}, ) assert res.get_json()["status"] == "needs_human" body = res.get_json() assert body.get("checkpoint") in {"map_infer", "upload_req"} assert body.get("human_options") is not None or body.get("action_buttons") def test_match_by_aws_sku_and_reservation_id(app, client): headers = _tool_headers(app) 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": 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={"task_id": task_id, "raw_inventory_text": inv_text}, ) client.post( "/api/shipping-notice/tools/submit_decision", headers=headers, json={"task_id": task_id, "decision": "confirm_inventory_mapping"}, ) 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" 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_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"}], "confidence": 0.95, }, }, ) client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ "task_id": task_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={"task_id": task_id}, ) blocked = match_res.get_json() assert blocked["status"] == "needs_human" assert blocked.get("checkpoint") == "align_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_match_inventory_requires_reservation_id(app, client): headers = _tool_headers(app) 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": "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") == "rsv_req" 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"}], "confidence": 0.95, }, }, ) client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ "task_id": task_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={"task_id": task_id, "decision": "correct_inventory_mapping"}, ) data = correct_res.get_json() assert data["status"] == "needs_human" 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"] def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): headers = _tool_headers(app) drop = tmp_path / "drop" trigger = tmp_path / "triggers" drop.mkdir() trigger.mkdir() app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop) app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) 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 openpyxl import Workbook inv_file = drop / "stock.xlsx" wb = Workbook() ws = wb.active ws.append(["料号", "可用数量"]) ws.append(["A001", 20]) wb.save(inv_file) wb.close() cb_res = client.post( "/api/shipping-notice/rpa/inventory-ready", headers=headers, json={"task_no": task_id, "success": True, "file_path": str(inv_file)}, ) assert cb_res.status_code == 200 data = cb_res.get_json() assert data["status"] == "needs_human" assert data.get("checkpoint") in {"map_infer", "align_review"} assert "confirm_inventory_mapping" in (data.get("human_options") or []) with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None assert task.process_status == "inventory_ready" def test_rpa_upload_callback(app, client, tmp_path): headers = _tool_headers(app) queue = tmp_path / "queue" trigger = tmp_path / "upload_triggers" queue.mkdir() trigger.mkdir() app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(queue) app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(trigger) 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": "ACME", "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 5, "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}]}, ) client.post( "/api/shipping-notice/tools/match_inventory", headers=headers, json={"task_id": task_id}, ) client.post( "/api/shipping-notice/tools/generate_shipment_excel", headers=headers, json={"task_id": task_id}, ) cb_res = client.post( "/api/shipping-notice/rpa/upload-complete", headers=headers, 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" assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001" def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client): headers = _tool_headers(app) 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": "Wistron", "po_number": "SN-20260608-7FCBFA4B", "lines": [ { "sku": "504-010213-001", "vendor_part_number": "504-010213-001", "reservation_id": "1000140351", "qty": 9, "uom": "EA", } ], "confidence": 0.95, }, }, ) client.post( "/api/shipping-notice/tools/ensure_inventory", headers=headers, json={ "task_id": task_id, "inventory_lines": [ { "sku": "504-010213-001", "reservation_id": "1000140351", "available_qty": 9, "odm_id": "16754796", } ], }, ) client.post( "/api/shipping-notice/tools/match_inventory", headers=headers, json={"task_id": task_id}, ) excel_res = client.post( "/api/shipping-notice/tools/generate_shipment_excel", headers=headers, json={"task_id": task_id}, ) assert excel_res.status_code == 200 assert excel_res.get_json()["status"] == "ok" from openpyxl import load_workbook with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None assert task.export_file_path wb = load_workbook(task.export_file_path, read_only=True) header_ws = wb["PVMI Pull Request Header"] detail_ws = wb["PVMI Pull Request Detail"] assert header_ws.cell(4, 6).value == "16754796" assert detail_ws.cell(4, 4).value == "504-010213-001" wb.close() 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_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"}], "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={ "task_id": task_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") == "map_infer" 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={ "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") == "align_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_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_path, monkeypatch): """已手工上传完成的票不能被后续批次库存快照重新带回 RPA 上传链路。""" from io import BytesIO from openpyxl import Workbook from app.models import ShippingBatch, ShippingTaskInventoryLink from app.services.shipping_notice import inventory_file_store headers = _tool_headers(app) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "freight" / "upload_queue") app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(tmp_path / "freight" / "upload_triggers") started_task_nos: list[str] = [] def fake_start_task_orchestrator(task_no: str) -> bool: started_task_nos.append(task_no) return True monkeypatch.setattr(inventory_file_store, "start_task_orchestrator", fake_start_task_orchestrator, raising=False) with app.app_context(): batch = ShippingBatch(batch_no="SB-COMPLETED-LOCK", file_count=2) completed = ShippingTask( task_no="SN-20260629-DONE0001", batch=batch, source_type="manual", process_status="uploaded", pending_human_reason=None, lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}], batch_index=1, batch_total=2, ) pending = ShippingTask( task_no="SN-20260629-PEND0002", batch=batch, source_type="manual", process_status="waiting_inventory", lines_json=[{"sku": "A002", "reservation_id": "R-2", "qty": 1, "uom": "EA"}], batch_index=2, batch_total=2, ) db.session.add_all([batch, completed, pending]) db.session.commit() buf = BytesIO() wb = Workbook() ws = wb.active ws.append(["SKU", "Reservation ID", "Available Qty"]) ws.append(["A001", "R-1", 10]) ws.append(["A002", "R-2", 10]) 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={"task_id": "SN-20260629-PEND0002", "file": (buf, "inventory.xlsx")}, ) assert upload_res.status_code == 200 with app.app_context(): completed = ShippingTask.query.filter_by(task_no="SN-20260629-DONE0001").one() pending = ShippingTask.query.filter_by(task_no="SN-20260629-PEND0002").one() completed_links = ShippingTaskInventoryLink.query.filter_by(task_id=completed.id, is_active=True).count() pending_links = ShippingTaskInventoryLink.query.filter_by(task_id=pending.id, is_active=True).count() assert completed.process_status == "uploaded" assert completed.pending_human_reason is None assert completed_links == 0 assert pending_links == 1 assert "SN-20260629-DONE0001" not in started_task_nos 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): 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"] missing = client.post( "/api/shipping-notice/tools/get_inventory_schema_preview", headers=headers, json={"task_id": task_id}, ) assert missing.get_json()["checkpoint"] == "upload_req" 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_task", headers=headers, json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_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={"task_id": task_id, "file": (buf, "inv.xlsx")}, ) apply_res = client.post( "/api/shipping-notice/tools/apply_inventory_mapping", headers=headers, json={ "task_id": task_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"]["field_alignment"]["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_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": "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={"task_id": task_id, "decision": "confirm"}, ) confirm_data = confirm_res.get_json() assert confirm_data["status"] in {"ok", "running", "needs_human"} excel_res = client.post( "/api/shipping-notice/tools/generate_shipment_excel", headers=headers, 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(): 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 @pytest.mark.auto_rpa def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, monkeypatch): import app.services.shipping_notice.task_workflow as task_workflow headers = _tool_headers(app) called: dict[str, str] = {} def fake_start_task_orchestrator(task_no: str | None) -> bool: called["task_no"] = str(task_no or "") return True monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator) create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] parse_res = client.post( "/api/shipping-notice/tools/parse_notice", headers=headers, json={ "task_id": task_id, "structured": { "customer_name": "ACME", "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}], "confidence": 0.95, }, }, ) parse_data = parse_res.get_json() assert parse_data["status"] == "running" assert "【发货通知解析确认】" in parse_data["message"] assert "回复「确认」进入库存检查" not in parse_data["message"] assert parse_data.get("checkpoint") != "parse_review" assert called.get("task_no") == task_id @pytest.mark.auto_rpa def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path, monkeypatch): import app.services.shipping_notice.task_workflow as task_workflow import app.services.shipping_notice.decision_workflow as decision_workflow headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" trigger.mkdir() app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) called: dict[str, str] = {} def fake_start_task_orchestrator(task_no: str | None) -> bool: called["task_no"] = str(task_no or "") return True monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator) monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator) create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] parse_res = client.post( "/api/shipping-notice/tools/parse_notice", headers=headers, 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.get_json()["status"] == "running" confirm_res = client.post( "/api/shipping-notice/tools/submit_decision", headers=headers, json={"task_id": task_id, "decision": "confirm"}, ) confirm_data = confirm_res.get_json() assert confirm_data["status"] == "running" assert "后台" in confirm_data["message"] assert "ensure_inventory" not in confirm_data["message"] assert "match_inventory" not in confirm_data["message"] assert called.get("task_no") == task_id def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, monkeypatch): import app.services.shipping_notice.decision_workflow as decision_workflow headers = _tool_headers(app) called: dict[str, str] = {} def fake_start_task_orchestrator(task_no: str | None) -> bool: called["task_no"] = str(task_no or "") return True monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator) 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": "ACME", "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}], "confidence": 0.95, }, }, ) with app.app_context(): 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.process_status = "inventory_ready" task.review_status = "align_review" task.pending_human_reason = "align_review" db.session.commit() with app.app_context(): db.session.add( ShippingTaskEvent( task_id=task_db_id, event_type="inventory_mapping_inferred", detail_json={ "column_meta": { "headers": ["Reservation ID", "SKU", "Qty Available"], "field_mapping": { "reservation_id": "Reservation ID", "sku": "SKU", "available_qty": "Qty Available", }, "mapping": { "reservation_id": {"source_column": "Reservation ID"}, "sku": {"source_column": "SKU"}, "available_qty": {"source_column": "Qty Available"}, }, } }, ) ) db.session.commit() confirm_res = client.post( "/api/shipping-notice/tools/submit_decision", headers=headers, json={"task_id": task_id, "decision": "confirm_inventory_mapping"}, ) confirm_data = confirm_res.get_json() assert confirm_data["status"] == "running" assert "后台继续处理匹配与后续步骤" in confirm_data["message"] assert called.get("task_no") == task_id @pytest.mark.auto_rpa def test_rpa_pending_timeout_recheck_triggers_next_inventory_export(app, client, tmp_path): from datetime import datetime, timedelta from app.services.shipping_notice.batch_orchestrator import _run_single_task from app.services.shipping_notice.constants import PH_RPA_PENDING headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" trigger.mkdir() app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None task.process_status = "waiting_inventory" task.pending_human_reason = PH_RPA_PENDING db.session.add( ShippingTaskEvent( task_id=task.id, event_type="inventory_rpa_triggered", detail_json={"attempt": 1}, created_at=datetime.utcnow() - timedelta(seconds=5), ) ) db.session.commit() with app.app_context(): result = _run_single_task(task_id) task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None assert result["status"] == "running" assert task.process_status == "waiting_inventory" assert task.pending_human_reason == PH_RPA_PENDING assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1 assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 2 assert len(list(trigger.glob("inventory_export_*.json"))) == 1 @pytest.mark.auto_rpa def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path): from datetime import datetime, timedelta from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" trigger.mkdir() app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None task.process_status = "waiting_inventory" task.pending_human_reason = PH_RPA_EXHAUSTED base_time = datetime.utcnow() - timedelta(minutes=5) for idx in range(3): db.session.add( ShippingTaskEvent( task_id=task.id, event_type="inventory_rpa_triggered", detail_json={"attempt": idx + 1}, created_at=base_time + timedelta(seconds=idx), ) ) db.session.commit() retry_res = client.post( "/api/shipping-notice/tools/submit_decision", headers=headers, json={"task_id": task_id, "decision": "retry_rpa"}, ) retry_data = retry_res.get_json() assert retry_data["status"] == "running" assert "新一轮第 1/3 次" in retry_data["message"] with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None assert task.process_status == "waiting_inventory" assert task.pending_human_reason == "rpa_pending" assert task.error_message is None progress = (task.step_payload_json or {}).get("current_step_progress") or {} assert progress.get("message") == "已手动重新触发 RPA 库存导出,等待结果" assert progress.get("detail") == "新一轮第 1/3 次尝试" assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").count() == 1 assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 4 assert len(list(trigger.glob("inventory_export_*.json"))) == 1 @pytest.mark.auto_rpa def test_batch_retry_rechecks_timed_out_rpa_pending_immediately(app, client, tmp_path): from datetime import datetime, timedelta from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks from app.services.shipping_notice.constants import PH_RPA_PENDING headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" trigger.mkdir() app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 create_res = client.post( "/api/shipping-notice/tools/create_batch", headers=headers, json={"conversation_id": "conv-rpa-batch-retry"}, ) batch_no = create_res.get_json()["batch_no"] task_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, json={ "batch_no": batch_no, "conversation_id": "conv-rpa-batch-retry", "source_type": "manual", }, ) task_id = task_res.get_json()["task_id"] with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None task.process_status = "waiting_inventory" task.pending_human_reason = PH_RPA_PENDING db.session.add( ShippingTaskEvent( task_id=task.id, event_type="inventory_rpa_triggered", detail_json={"attempt": 1}, created_at=datetime.utcnow() - timedelta(seconds=5), ) ) db.session.commit() with app.app_context(): result = retry_batch_pending_tasks(batch_no) task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None assert result["started"] == 1 assert result["skipped"] == 0 assert task.process_status == "waiting_inventory" assert task.pending_human_reason == PH_RPA_PENDING assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1 assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 2 assert len(list(trigger.glob("inventory_export_*.json"))) == 1 def test_submit_decision_by_conversation_id(app, client): headers = _tool_headers(app) create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, json={"source_type": "manual", "conversation_id": "conv-test-001"}, ) task_id = create_res.get_json()["task_id"] client.post( "/api/shipping-notice/tools/parse_notice", headers=headers, json={ "task_id": task_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"] in {"ok", "running", "needs_human"} assert confirm_data["task_id"] == task_id dup_res = client.post( "/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["task_id"] == task_id assert dup_data.get("checkpoint") == "task_exists" def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, monkeypatch): headers = _tool_headers(app) create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] import app.services.shipping_notice.decision_workflow as decision_workflow captured: dict[str, object] = {} def fake_ensure_inventory(payload): captured.update(payload) return { "status": "running", "task_id": payload["task_id"], "message": "已触发 RPA 库存导出(测试桩)", } monkeypatch.setattr(decision_workflow, "ensure_inventory", fake_ensure_inventory) res = client.post( "/api/shipping-notice/tools/submit_decision", headers=headers, json={"task_id": task_id, "decision": "retry_rpa", "comment": "retry now"}, ) data = res.get_json() assert data["status"] == "running" assert data["task_id"] == task_id assert data["message"] == "已触发 RPA 库存导出(测试桩)" assert captured["task_id"] == task_id assert captured["mode"] == "retry_rpa" 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_task", headers=headers, json={"source_type": "manual"}, ) task_id = create_res.get_json()["task_id"] res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, json={"task_id": task_id, "raw_inventory_text": "x" * 200}, ) data = res.get_json() assert data["status"] == "needs_human" assert data.get("checkpoint") == "upload_req" assert "过大" in data["message"] 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(): task = ShippingTask( task_no="SN-20260101-TEST0001", source_type="manual", process_status="rejected", review_status="rejected", ) assert human_options_for_task(task) == [] payload = build_chat_actions_payload(task) assert payload["checkpoint"] == "rejected" assert payload["action_buttons"] == []