feat(shipping_notice): 添加重新上传发货通知功能

- 新增接口支持覆盖当前任务的发货通知
- 重新解析时重置任务状态,避免重复任务
- 增加库存 RPA 等待时间的复查逻辑
- 更新状态机以处理文本抽取失败的情况
- 增强测试用例以覆盖新功能
This commit is contained in:
hugo committed 2026-06-29 17:52:17 +08:00
1 parent f434402530
commit 7f1d5dfbcd
20 files changed
+691 -26

No files matched your search

+237 -2
View File
@@ -7,15 +7,17 @@
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。
"""
from datetime import datetime, timedelta
from io import BytesIO
from app import db
from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, User
from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, ShippingTaskEvent, 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
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs, tools as shipping_tools
from app.services.shipping_notice.progress_workflow import auto_progress
def _tool_headers(app):
@@ -205,6 +207,184 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap
assert started == [data["batch_no"]]
def test_parse_notice_empty_result_requires_reupload_instead_of_review(app):
"""无订单行且无单头字段时,不应生成空审核卡片,应停在重新上传/清洗节点。"""
with app.app_context():
user = User(username="shipping_empty_parse_user", email="shipping_empty_parse_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-EMPTY-PARSE-001",
user_id=user.id,
source_type="pdf",
process_status="created",
raw_content="This PDF extraction contains no order table.",
)
db.session.add(task)
db.session.commit()
result = shipping_tools.parse_notice({"task_id": task.task_no})
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "notice_text_extraction_failed"
assert [button["id"] for button in result["action_buttons"]] == [
"replace_notice_file",
"reparse",
"reject",
]
assert task.pending_human_reason == "notice_text_extraction_failed"
assert task.review_status is None
assert task.lines_json == []
assert "重新上传" in result["message"]
def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app, client):
"""重新上传当前任务通知应保留 task_no/batch_no,只覆盖正文并清理旧解析结果。"""
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 = ShippingBatch(
batch_no="SB-REPLACE-NOTICE-001",
user_id=user.id,
conversation_id="conv-replace-notice",
current_focus_task_no="SN-REPLACE-NOTICE-001",
file_count=1,
)
db.session.add(batch)
db.session.flush()
task = ShippingTask(
task_no="SN-REPLACE-NOTICE-001",
batch_id=batch.id,
user_id=user.id,
conversation_id="conv-replace-notice",
source_type="pdf",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
raw_content="old text",
source_file_name="old.pdf",
lines_json=[{"sku": "OLD", "qty": 1}],
match_status="shortage",
shortage_json={"OLD": 1},
export_file_name="old.xlsx",
)
db.session.add(task)
db.session.commit()
original_batch_count = ShippingBatch.query.count()
original_task_count = ShippingTask.query.count()
res = client.post(
"/api/workspace/shipping-tasks/SN-REPLACE-NOTICE-001/replace-notice",
headers=headers,
data={"file": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "new-notice.txt")},
content_type="multipart/form-data",
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] in {"ok", "running"}
assert data["data"]["task_no"] == "SN-REPLACE-NOTICE-001"
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-REPLACE-NOTICE-001").one()
assert ShippingBatch.query.count() == original_batch_count
assert ShippingTask.query.count() == original_task_count
assert task.batch.batch_no == "SB-REPLACE-NOTICE-001"
assert task.raw_content == "客户:ACME\nA001 x 10"
assert task.source_file_name == "new-notice.txt"
assert task.lines_json == []
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.export_file_name is None
def test_auto_progress_inventory_trigger_failure_marks_step3(app):
"""库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = ""
with app.app_context():
user = User(username="shipping_inventory_step_user", email="shipping_inventory_step_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-STEP-001",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="客户:ACME\nA001 x 10",
lines_json=[{"sku": "A001", "qty": 10}],
current_step="step2_parse_confirm",
)
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "upload_req"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "inv_unavail"
assert task.current_step == "step3_inventory_prepare"
assert task.step_payload_json["current_step_progress"]["status"] == "needs_human"
def test_workspace_task_detail_rechecks_timed_out_inventory_rpa(app, client, tmp_path):
"""工作台查询遇到已超时 RPA 等待态时,应兜底复查并自动触发下一次库存导出。"""
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 5
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
task = ShippingTask(
task_no="SN-RPA-RECHECK-001",
user_id=user.id,
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
parse_confidence=0.95,
raw_content="客户:ACME\nA001 x 10",
lines_json=[{"sku": "A001", "qty": 10}],
)
db.session.add(task)
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": 1},
created_at=datetime.utcnow() - timedelta(seconds=10),
)
)
db.session.commit()
res = client.get("/api/workspace/shipping-tasks/SN-RPA-RECHECK-001", headers=headers)
assert res.status_code == 200
data = res.get_json()
assert data["process_status"] == "waiting_inventory"
assert data["pending_human_reason"] == "rpa_pending"
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-RPA-RECHECK-001").one()
events = ShippingTaskEvent.query.filter_by(task_id=task.id).order_by(ShippingTaskEvent.id.asc()).all()
triggered = [event for event in events if event.event_type == "inventory_rpa_triggered"]
failed = [event for event in events if event.event_type == "inventory_rpa_failed"]
rechecked = [event for event in events if event.event_type == "inventory_rpa_wait_rechecked"]
assert len(triggered) == 2
assert len(failed) == 1
assert len(rechecked) == 1
assert triggered[-1].detail_json["attempt"] == 2
assert task.step_payload_json["current_step_progress"]["current"] == 2
def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client):
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
headers = _workspace_headers(app)
@@ -469,6 +649,61 @@ def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
assert called.get("dify") == task_no
def test_submit_reparse_resets_task_and_starts_dify_orchestrator(app, monkeypatch):
"""重新解析必须回退到 created 并交给后台 Dify,不允许同步启发式解析。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-REPARSE-DIFY", file_count=1)
task = ShippingTask(
task_no="SN-20260629-REPARSE1",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
lines_json=[{"sku": "OLD", "qty": 1}],
parse_confidence=0.42,
match_status="shortage",
shortage_json={"OLD": 1},
line_results_json=[{"sku": "OLD", "status": "shortage"}],
inventory_lines_json=[{"sku": "OLD", "available_qty": 0}],
error_message="old error",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
started: list[str] = []
def fake_start(task_ref: str | None) -> bool:
if task_ref:
started.append(task_ref)
return True
monkeypatch.setattr(
"app.services.shipping_notice.decision_workflow.start_task_orchestrator",
fake_start,
)
result = shipping_tools.submit_decision({"task_id": task_no, "decision": "reparse"})
db.session.refresh(task)
assert result["status"] == "running"
assert started == [task_no]
assert task.process_status == "created"
assert task.review_status is None
assert task.pending_human_reason is None
assert task.lines_json == []
assert task.parse_confidence is None
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
assert task.inventory_lines_json is None
assert task.error_message is None
assert "Dify" in result["message"]
assert "【发货通知解析确认】" not in result["message"]
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