feat(chat): 更新发货任务处理逻辑和界面文本

- 移除不必要的状态引用
- 更新上传处理提示文本,使用国际化支持
- 扩展发货任务摘要接口,增加错误信息和短缺信息
- 更新多语言支持的文本,改善用户体验
- 增加批次工作区的汇总信息和操作提示
This commit is contained in:
hugo committed 2026-06-29 14:43:27 +08:00
1 parent 0b083cfdbd
commit 1fc9976ca3
60 files changed
+3876 -639

No files matched your search

+6
View File
@@ -20,6 +20,11 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
@pytest.fixture(autouse=True)
def _shipping_notice_stable_auto_config(app, request):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
tmp_path = request.getfixturevalue("tmp_path")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
)
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
@@ -27,6 +32,7 @@ def _shipping_notice_stable_auto_config(app, request):
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
+1 -1
View File
@@ -17,6 +17,6 @@ def test_resolve_backend_relative_path_data_prefix():
def test_resolve_backend_relative_path_default():
root = backend_dir()
default = root / "data" / "freight_rpa" / "inventory_drop"
default = root / "data" / "shipping_notice" / "freight_rpa" / "inventory_drop"
resolved = Path(resolve_backend_relative_path(None, default))
assert resolved == default.resolve()
@@ -205,6 +205,169 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap
assert started == [data["batch_no"]]
def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client):
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch_a = ShippingBatch(
batch_no="SB-CONV-WS-A",
user_id=user.id,
conversation_id="conv-workspace-multi",
current_focus_task_no="SN-20260626-CONVA001",
file_count=2,
)
batch_b = ShippingBatch(
batch_no="SB-CONV-WS-B",
user_id=user.id,
conversation_id="conv-workspace-multi",
current_focus_task_no="SN-20260626-CONVB001",
file_count=2,
)
other_batch = ShippingBatch(
batch_no="SB-CONV-WS-OTHER",
user_id=user.id,
conversation_id="conv-workspace-other",
file_count=1,
)
db.session.add_all([batch_a, batch_b, other_batch])
db.session.flush()
db.session.add_all([
ShippingTask(
task_no="SN-20260626-CONVA001",
batch_id=batch_a.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="uploaded",
batch_index=1,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVA002",
batch_id=batch_a.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="matched",
batch_index=2,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVB001",
batch_id=batch_b.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="waiting_inventory",
review_status="align_review",
batch_index=1,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVB002",
batch_id=batch_b.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="matched",
upload_status="failed",
batch_index=2,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-OTHER001",
batch_id=other_batch.id,
user_id=user.id,
conversation_id="conv-workspace-other",
source_type="manual",
process_status="uploaded",
batch_index=1,
batch_total=1,
),
])
db.session.commit()
res = client.get(
"/api/workspace/shipping-conversations/conv-workspace-multi/batch-workspace",
headers=headers,
)
assert res.status_code == 200
data = res.get_json()
assert data["conversation_id"] == "conv-workspace-multi"
assert data["summary"] == {
"batch_count": 2,
"total": 4,
"completed": 1,
"running": 1,
"failed": 1,
"needs_human": 1,
"pending": 0,
}
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-WS-A", "SB-CONV-WS-B"]
assert data["batches"][0]["focus_task"]["task_no"] == "SN-20260626-CONVA001"
assert len(data["batches"][1]["tasks"]) == 2
def test_workspace_conversation_batch_workspace_filters_by_user(app, client):
"""会话级工作台只能返回当前用户可访问的批次。"""
headers = _workspace_headers(app)
with app.app_context():
current = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
other = User(
username="shipping_workspace_other",
email="shipping_workspace_other@example.com",
role="user",
status="active",
)
other.set_password("password")
db.session.add(other)
db.session.flush()
own_batch = ShippingBatch(
batch_no="SB-CONV-OWN",
user_id=current.id,
conversation_id="conv-workspace-secure",
file_count=1,
)
foreign_batch = ShippingBatch(
batch_no="SB-CONV-FOREIGN",
user_id=other.id,
conversation_id="conv-workspace-secure",
file_count=1,
)
db.session.add_all([own_batch, foreign_batch])
db.session.flush()
db.session.add_all([
ShippingTask(
task_no="SN-20260626-OWN00001",
batch_id=own_batch.id,
user_id=current.id,
conversation_id="conv-workspace-secure",
source_type="manual",
process_status="created",
),
ShippingTask(
task_no="SN-20260626-FGN00001",
batch_id=foreign_batch.id,
user_id=other.id,
conversation_id="conv-workspace-secure",
source_type="manual",
process_status="uploaded",
),
])
db.session.commit()
res = client.get(
"/api/workspace/shipping-conversations/conv-workspace-secure/batch-workspace",
headers=headers,
)
assert res.status_code == 200
data = res.get_json()
assert data["summary"]["batch_count"] == 1
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-OWN"]
def test_shipping_orchestrator_enqueues_generic_job_not_kb_job(app):
"""发货通知后台编排应写入通用 jobs,不能污染 kb_jobs。"""
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
@@ -306,6 +469,53 @@ def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
assert called.get("dify") == task_no
def test_run_single_task_refreshes_after_dify_parse_before_auto_progress(app, monkeypatch):
"""Dify Tool 提交解析结果后,编排器应刷新 session 并继续触发自动推进。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-PARSE-FOLLOW", file_count=1)
task = ShippingTask(
task_no="SN-20260629-FOLLOW01",
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):
stmt = (
ShippingTask.__table__.update()
.where(ShippingTask.__table__.c.task_no == task_ref)
.values(
process_status="parsed",
review_status=None,
pending_human_reason=None,
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
)
)
with db.engine.begin() as conn:
conn.execute(stmt)
return {"status": "ok", "message": "parsed-by-dify"}
def fake_auto_progress(payload):
called["auto_progress"] = payload
return {"status": "running", "message": "rpa triggered"}
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_no)
assert result["status"] == "running"
assert isinstance(called.get("auto_progress"), dict)
assert called["auto_progress"]["task_id"] == task_no
def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypatch):
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
with app.app_context():
@@ -146,12 +146,13 @@ def test_batch_process_summary_shared_formula(app):
db.session.commit()
tasks = [done, running]
assert compute_batch_process_summary(tasks) == {
"total": 2,
"completed": 1,
"failed": 0,
"running": 1,
}
summary = compute_batch_process_summary(tasks)
assert summary["total"] == 2
assert summary["completed"] == 1
assert summary["failed"] == 0
assert summary["running"] == 1
assert summary["pending"] == 2
assert summary["current_task_no"] == "SN-RUN"
tool_batch = serialize_batch(batch, BatchProjection.TOOL)
assert tool_batch["process_summary"]["completed"] == 1
assert tool_batch["batch_no"] == "SB-SUMMARY"
+307 -1
View File
@@ -83,10 +83,16 @@ def test_shipping_notice_tool_flow(app, client):
)
assert match_res.status_code == 200
match_data = match_res.get_json()
assert match_data["status"] == "ok"
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",
@@ -160,6 +166,67 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
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")
@@ -683,6 +750,82 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
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")
@@ -1016,6 +1159,169 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
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)