docs(tec): 更新货代发货通知批次库存能力文档

- 添加单票与多票发货需求的处理方式
- 说明库存 Excel 上传后的保存与关联机制
- 解释库存匹配与 Excel 生成的独立执行方式
- 明确批次库存的真相来源

feat(chat): 优化发货库存上传提示语
- 根据上传结果生成更详细的提示信息
- 增加批次号的提示逻辑
- 使用国际化支持替换硬编码字符串

refactor(chat): 重构发货库存上传处理逻辑
- 移除多余的任务选择逻辑
- 简化上传处理流程
- 增强代码可读性与维护性

feat(locales): 更新多语言支持的提示信息
- 添加库存上传与任务处理的多语言提示
- 更新库存缺口与任务状态的描述
This commit is contained in:
hugo committed 2026-06-26 16:27:49 +08:00
1 parent 1bd9f278fe
commit 1cf8ff40bd
34 files changed
+4367 -3553

No files matched your search

+141 -19
View File
@@ -10,8 +10,11 @@
from io import BytesIO
from app import db
from app.models import Agent, ChatSession, ShippingBatch, ShippingTask, User
from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, User
from app.auth_jwt import issue_local_access_token
from app.jobs.context import JobContext
from app.jobs.queue import process_next_job
from app.jobs.types import JobType
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs
@@ -202,6 +205,75 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap
assert started == [data["batch_no"]]
def test_shipping_orchestrator_enqueues_generic_job_not_kb_job(app):
"""发货通知后台编排应写入通用 jobs,不能污染 kb_jobs。"""
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
app.config["SHIPPING_NOTICE_TASK_EXECUTION_MODE"] = "worker"
with app.app_context():
batch = ShippingBatch(batch_no="SB-JOBS-QUEUE", file_count=1, user_id=123)
task = ShippingTask(
task_no="SN-20260626-JOBS0001",
batch=batch,
user_id=123,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
started = batch_orchestrator.start_task_orchestrator(task.task_no)
assert started is True
job = Job.query.filter_by(
domain="shipping_notice",
job_type="shipping_notice_run",
business_ref=task.task_no,
).first()
assert job is not None
assert job.status == "queued"
assert job.payload_json["task_no"] == task.task_no
assert KbJob.query.filter_by(job_type="shipping_notice_run").count() == 0
def test_process_shipping_job_survives_session_remove(app, monkeypatch):
"""Job Runner 应能处理业务编排内部 db.session.remove 后的状态回写。"""
app.config["SHIPPING_NOTICE_TASK_EXECUTION_MODE"] = "worker"
with app.app_context():
job = Job(
domain="shipping_notice",
job_type=JobType.SHIPPING_NOTICE_RUN.value,
status="queued",
business_ref="SN-20260626-DETACHED1",
payload_json={"task_no": "SN-20260626-DETACHED1"},
message="等待后台处理发货任务",
)
db.session.add(job)
db.session.commit()
job_id = job.id
def fake_run_single_task(task_no: str):
db.session.remove()
return {"status": "ok", "message": f"done {task_no}"}
monkeypatch.setattr(batch_orchestrator, "_run_single_task", fake_run_single_task)
ctx = JobContext(config=dict(app.config), logger=app.logger, extras={"queues": ["shipping"]})
processed, message = process_next_job(
ctx=ctx,
domain="shipping_notice",
job_types=[JobType.SHIPPING_NOTICE_RUN],
timeout_config_key="SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS",
)
assert processed is True
assert message == JobType.SHIPPING_NOTICE_RUN.value
refreshed = db.session.get(Job, job_id)
assert refreshed is not None
assert refreshed.status == "success"
assert refreshed.result_json["status"] == "ok"
def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
"""编排器遇到 created 任务时应调用后台 Dify 执行器。"""
with app.app_context():
@@ -266,8 +338,8 @@ def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypat
assert called["auto_progress"]["task_id"] == task_no
def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app, monkeypatch):
"""后台 Dify 执行器应带上当前任务上下文,并回写 provider conversation id。"""
def test_run_shipping_parse_via_dify_passes_task_context_without_persisting_chat(app, monkeypatch):
"""后台 Dify 执行器应带当前任务上下文,但不复用/污染前端聊天记录。"""
with app.app_context():
user = User(
username="shipping_dify_user",
@@ -293,6 +365,7 @@ def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app
agent_id=agent.id,
title="shipping parse",
status="running",
external_conversation_id="22222222-2222-2222-2222-222222222222",
)
batch = ShippingBatch(
batch_no="SB-DIFY-EXEC",
@@ -321,28 +394,35 @@ def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app
captured["conversation_id"] = conversation_id
captured["session_id"] = kwargs.get("session_id")
captured["inputs"] = kwargs.get("inputs")
captured["persist_chat_log"] = kwargs.get("persist_chat_log")
yield 'data: {"event":"message_end","conversation_id":"11111111-1111-1111-1111-111111111111","answer":"parsed"}\n\n'
monkeypatch.setattr(dify_executor.DifyService, "stream_chat", staticmethod(fake_stream_chat))
result = dify_executor.run_shipping_parse_via_dify(task.task_no)
assert result["status"] == "ok"
assert captured["query"] == "解析当前发货通知任务"
assert captured["user_id"] == user.id
assert captured["agent_id"] == agent.id
assert captured["conversation_id"] is None
assert captured["session_id"] == session.session_id
assert captured["persist_chat_log"] is False
assert isinstance(captured["inputs"], dict)
assert captured["inputs"]["entry_mode"] == "orchestrator_parse"
assert captured["inputs"]["trigger_source"] == "backend_orchestrator"
assert captured["inputs"]["user_message"] == ""
assert captured["inputs"]["current_task_no"] == task.task_no
assert captured["inputs"]["current_batch_no"] == batch.batch_no
assert captured["inputs"]["hxops_context"]["schema_version"] == "1"
assert captured["inputs"]["hxops_context"]["session"]["id"] == session.session_id
assert captured["inputs"]["hxops_context"]["request"]["id"] == f"shipping-orch-{task.task_no}"
assert captured["inputs"]["hxops_context"]["request"]["trigger_source"] == "backend_orchestrator"
assert captured["inputs"]["hxops_context"]["refs"] == [
{"field": "task", "value": task.task_no},
{"field": "batch", "value": batch.batch_no},
]
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
assert refreshed_session is not None
assert refreshed_session.external_conversation_id == "11111111-1111-1111-1111-111111111111"
assert refreshed_session.external_conversation_id == "22222222-2222-2222-2222-222222222222"
def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
"""统一版 Dify inputs 应同时包含 entry_mode/user_message/trigger_source。"""
def test_build_dify_chat_inputs_returns_hxops_context_only(app):
"""货代发货 Agent 应只注入平台统一的 hxops_context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-DIFY-INPUTS",
@@ -362,17 +442,59 @@ def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
inputs = dify_inputs.build_dify_chat_inputs(
"conv-shipping-inputs-001",
entry_mode="user_chat",
user_message="这票现在什么状态?",
trigger_source="frontend_chat",
request_id="req-frontend-001",
)
assert inputs["entry_mode"] == "user_chat"
assert inputs["conversation_id"] == "conv-shipping-inputs-001"
assert inputs["current_batch_no"] == "SB-DIFY-INPUTS"
assert inputs["current_task_no"] == "SN-20260622-DDDD0004"
assert inputs["user_message"] == "这票现在什么状态?"
assert inputs["trigger_source"] == "frontend_chat"
assert set(inputs.keys()) == {"hxops_context"}
assert inputs["hxops_context"]["schema_version"] == "1"
assert inputs["hxops_context"]["session"]["id"] == "conv-shipping-inputs-001"
assert inputs["hxops_context"]["request"]["id"] == "req-frontend-001"
assert inputs["hxops_context"]["request"]["trigger_source"] == "frontend_chat"
assert inputs["hxops_context"]["refs"] == [
{"field": "task", "value": "SN-20260622-DDDD0004"},
{"field": "batch", "value": "SB-DIFY-INPUTS"},
]
def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation(app):
"""已有 Dify provider 会话号时,HXOPS 上下文仍应按本地 session 解析。"""
with app.app_context():
local_session_id = "conv-shipping-local-session-001"
provider_conversation_id = "f3b371e7-4d8b-40b6-80be-76fd98459c65"
batch = ShippingBatch(
batch_no="SB-DIFY-LOCAL",
conversation_id=local_session_id,
current_focus_task_no="SN-20260626-LOCAL001",
file_count=1,
)
task = ShippingTask(
task_no="SN-20260626-LOCAL001",
batch=batch,
conversation_id=local_session_id,
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
provider_inputs = dify_inputs.build_dify_chat_inputs(provider_conversation_id)
local_inputs = dify_inputs.build_dify_chat_inputs(local_session_id)
assert provider_inputs["hxops_context"]["refs"] == []
assert local_inputs["hxops_context"]["session"]["id"] == local_session_id
assert local_inputs["hxops_context"]["refs"] == [
{"field": "task", "value": "SN-20260626-LOCAL001"},
{"field": "batch", "value": "SB-DIFY-LOCAL"},
]
def test_is_shipping_notice_chat_agent_accepts_current_dify_app_name():
"""兼容 Dify 侧当前使用的智能发货通知Agent命名。"""
class AgentLike:
name = "智能发货通知Agent"
assert dify_inputs.is_shipping_notice_chat_agent(AgentLike()) is True
def test_create_empty_batch_returns_batch_shell(app, client):
+154 -8
View File
@@ -1,7 +1,7 @@
import pytest
from app import db
from app.models import ShippingInventoryMapping, ShippingTask
from app.models import ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.match import match_notice_lines
@@ -165,14 +165,21 @@ 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_task" in str(spec)
assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice"
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"]
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):
@@ -841,8 +848,17 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
@pytest.mark.auto_rpa
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
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",
@@ -864,17 +880,30 @@ def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
},
)
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):
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",
@@ -904,7 +933,87 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "running"
assert "RPA 库存导出" in confirm_data["message"]
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
def test_submit_decision_by_conversation_id(app, client):
@@ -950,6 +1059,43 @@ def test_submit_decision_by_conversation_id(app, client):
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