feat(shipping): 新增货代发货批量自动处理与任务重试功能

本次提交完整实现货代发货通知的自动化批量处理能力:
1.  新增发货单票后台任务类型与专用worker队列,实现任务持久化调度
2.  实现发货批次后台编排器,支持上传后自动逐票推进解析、匹配、导出全流程
3.  新增单票重试、批次待处理重试的API与前端操作界面
4.  补充全量多语言翻译,新增重试、任务列表、状态展示相关文案
5.  优化上传交互逻辑,改为后台自动处理任务,无需手动触发解析指令
6.  修复文件检核工具无数据预检逻辑,避免创建空检核批次
7.  调整发货工作流细节,优化Excel生成幂等性与任务状态同步
8.  更新环境配置与API文档,修正货代工具接口地址端口
This commit is contained in:
hugo committed 2026-06-23 11:22:09 +08:00
1 parent 70e8f700ff
commit 08360a4142
40 files changed
+2515 -371

No files matched your search

+2
View File
@@ -23,9 +23,11 @@ def _shipping_notice_stable_auto_config(app, request):
if request.node.get_closest_marker("auto_rpa"):
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
def pytest_configure(config):
+75
View File
@@ -389,6 +389,81 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
assert resolve_run_id_for_chat_log(session_id='bind-on-start', query='执行 RoHS 检核') == run_id
def test_file_check_tool_no_data_does_not_create_run_or_bind_context(app, client, monkeypatch):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
before_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
monkeypatch.setattr('app.api.file_check_tools._precheck_no_data', lambda _task: {
'ok': False,
'error_code': 'no_data_to_check',
'message': '目前没有资料需要检核',
'task': {'task_id': _task.id, 'task_name': _task.name},
})
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'no-data-session',
'hxops_turn_id': 'no-data-turn',
'user_message': '立即执行检核',
},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'no_data_to_check'
assert 'run' not in data
with app.app_context():
after_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
assert after_count == before_count
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
assert resolve_run_id_for_chat_log(turn_id='no-data-turn') is None
assert resolve_run_id_for_chat_log(session_id='no-data-session', query='立即执行检核') is None
def test_file_check_tool_no_data_keeps_existing_running_conflict_priority(app, client, monkeypatch):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-NO-DATA-CONFLICT',
schedule_task_id=task.id,
status='running',
trigger_type='manual',
)
db.session.add(run)
db.session.commit()
task_id = task.id
monkeypatch.setattr('app.api.file_check_tools._precheck_no_data', lambda _task: {
'ok': False,
'error_code': 'no_data_to_check',
'message': '目前没有资料需要检核',
'task': {'task_id': _task.id, 'task_name': _task.name},
})
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
assert res.status_code == 200
data = res.get_json()
assert data['error_code'] == 'check_running'
assert data.get('run', {}).get('run_id')
def test_file_check_tool_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
+208 -2
View File
@@ -7,9 +7,12 @@
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。
"""
from io import BytesIO
from app import db
from app.models import ShippingBatch, ShippingTask, User
from app.models import Agent, ChatSession, ShippingBatch, ShippingTask, User
from app.auth_jwt import issue_local_access_token
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs
def _tool_headers(app):
@@ -148,7 +151,7 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (__import__("io").BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"conversation_id": "conv-workspace-batch-001",
},
content_type="multipart/form-data",
@@ -169,6 +172,209 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
assert len(task.lines_json or []) == 0
def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(app, client, monkeypatch):
"""开启编排器时,工作台上传接口应返回 orchestrator_started。"""
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
app.config["SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY"] = True
started: list[str] = []
def fake_start(batch_no: str | None) -> bool:
if batch_no:
started.append(batch_no)
return True
monkeypatch.setattr(batch_orchestrator, "start_batch_orchestrator", fake_start)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"conversation_id": "conv-workspace-batch-002",
},
content_type="multipart/form-data",
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] == "ok"
assert data["data"]["orchestrator_started"] is True
assert started == [data["batch_no"]]
def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
"""编排器遇到 created 任务时应调用后台 Dify 执行器。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-PARSE", file_count=1)
task = ShippingTask(
task_no="SN-20260622-AAAA0001",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_dify(task_ref: str):
called["dify"] = task_ref
return {"status": "ok", "message": "parsed-by-dify"}
def fake_auto_progress(payload):
raise AssertionError("created task should not call auto_progress when auto_progress is disabled")
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
result = batch_orchestrator._run_single_task(task.task_no)
assert result["status"] == "ok"
assert called.get("dify") == task_no
def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypatch):
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-AUTO", file_count=1)
task = ShippingTask(
task_no="SN-20260622-BBBB0002",
batch=batch,
source_type="manual",
process_status="parsed",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_dify(task_ref: str):
raise AssertionError(f"parsed task should not call dify parse executor: {task_ref}")
def fake_auto_progress(payload):
called["auto_progress"] = payload
return {"status": "ok", "message": "advanced"}
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
result = batch_orchestrator._run_single_task(task.task_no)
assert result["status"] == "ok"
assert isinstance(called.get("auto_progress"), dict)
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。"""
with app.app_context():
user = User(
username="shipping_dify_user",
email="shipping_dify_user@example.com",
role="user",
status="active",
)
user.set_password("password")
db.session.add(user)
db.session.flush()
agent = Agent(
name="货代发货通知 Agent",
dify_api_key="test-dify-key",
is_active=True,
)
db.session.add(agent)
db.session.flush()
session = ChatSession(
session_id="conv-shipping-dify-001",
user_id=user.id,
agent_id=agent.id,
title="shipping parse",
status="running",
)
batch = ShippingBatch(
batch_no="SB-DIFY-EXEC",
user_id=user.id,
conversation_id=session.session_id,
file_count=1,
)
task = ShippingTask(
task_no="SN-20260622-CCCC0003",
batch=batch,
user_id=user.id,
conversation_id=session.session_id,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([session, batch, task])
db.session.commit()
captured: dict[str, object] = {}
def fake_stream_chat(query, user_id, agent_obj, conversation_id=None, **kwargs):
captured["query"] = query
captured["user_id"] = user_id
captured["agent_id"] = agent_obj.id
captured["conversation_id"] = conversation_id
captured["session_id"] = kwargs.get("session_id")
captured["inputs"] = kwargs.get("inputs")
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["user_id"] == user.id
assert captured["agent_id"] == agent.id
assert captured["session_id"] == session.session_id
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
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"
def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
"""统一版 Dify inputs 应同时包含 entry_mode/user_message/trigger_source。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-DIFY-INPUTS",
conversation_id="conv-shipping-inputs-001",
current_focus_task_no="SN-20260622-DDDD0004",
file_count=1,
)
task = ShippingTask(
task_no="SN-20260622-DDDD0004",
batch=batch,
conversation_id="conv-shipping-inputs-001",
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
inputs = dify_inputs.build_dify_chat_inputs(
"conv-shipping-inputs-001",
entry_mode="user_chat",
user_message="这票现在什么状态?",
trigger_source="frontend_chat",
)
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"
def test_create_empty_batch_returns_batch_shell(app, client):
"""验证无 notice_items 时仍可创建批次壳,供后续续办。"""
headers = _tool_headers(app)