Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/jobs/queue.py
This commit is contained in:
hugo committed 2026-06-29 20:39:06 +08:00
commit ce80867d09
89 files changed
+10328 -4126

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
@@ -23,6 +23,6 @@ def test_resolve_backend_relative_path_kb_storage_legacy_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()
+769 -20
View File
@@ -7,12 +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, 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.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs
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, tools as shipping_tools
from app.services.shipping_notice.progress_workflow import auto_progress
def _tool_headers(app):
@@ -202,6 +207,598 @@ 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",
step_payload_json={
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
}
},
)
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}],
step_payload_json={
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
}
},
)
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_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_path):
"""目的地 DUB 应解析到 DSV360_AWSDU,并写入 RPA 库存导出 trigger。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
with app.app_context():
user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-DUB",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="Ship to Dublin DUB\nA001 x 10",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 10}],
step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}},
)
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "running"
source = task.step_payload_json["rpa_inventory_source"]
assert source["source_code"] == "DSV360_AWSDU"
trigger_path = tmp_path / "inventory_triggers" / f"inventory_export_{task.task_no}.json"
assert trigger_path.exists()
trigger_text = trigger_path.read_text(encoding="utf-8")
assert '"source_code": "DSV360_AWSDU"' in trigger_text
assert '"source_type": "dsv360"' in trigger_text
def test_inventory_source_rules_cover_dsv360_programs(app):
"""截图中的 DSV 360 Program 均应能通过别名解析到对应库存源。"""
from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source
cases = [
("Bison", "DSV360_AWSBI"),
("Cincinnati", "DSV360_AWSCV"),
("Moerdijk", "DSV360_AWSAMS"),
]
with app.app_context():
for ship_to, expected_code in cases:
task = ShippingTask(
task_no=f"SN-INVENTORY-SOURCE-{expected_code}",
source_type="pdf",
process_status="parsed",
ship_to=ship_to,
lines_json=[{"sku": "A001", "qty": 10}],
)
resolution = resolve_inventory_source(task)
assert resolution.status == "resolved"
assert resolution.source is not None
assert resolution.source["source_code"] == expected_code
def test_auto_progress_unknown_destination_requires_inventory_source_review(app):
"""无法根据目的地唯一判断库存源时,应停在库存源人工确认检查点。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
with app.app_context():
user = User(username="shipping_inventory_source_unknown", email="shipping_inventory_source_unknown@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-UNKNOWN",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="Ship to Mystery Port\nA001 x 10",
ship_to="Mystery Port",
lines_json=[{"sku": "A001", "qty": 10}],
)
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"] == "inventory_source_review"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "inventory_source_unresolved"
assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved"
assert len(result["data"]["inventory_source_candidates"]) >= 4
def test_inventory_source_review_chat_actions_return_source_buttons(app):
"""库存源待确认且只有一个候选时,聊天按钮才携带具体 source_code。"""
from app.services.shipping_notice.state_machine import build_chat_actions_payload
with app.app_context():
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-ACTIONS",
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="inventory_source_unresolved",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSDU",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
}
],
}
},
)
payload = build_chat_actions_payload(task)
assert payload["checkpoint"] == "inventory_source_review"
first = payload["action_buttons"][0]
assert first["id"] == "confirm_inventory_source"
assert first["source_code"] == "DSV360_AWSDU"
assert first["label"] == "确认:DSV 360 / Dublin / AWSDU - Prod (JDA)"
def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
"""库存源候选很多时,不应把全部数据源铺成按钮。"""
from app.services.shipping_notice.state_machine import build_chat_actions_payload
with app.app_context():
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-MANY-ACTIONS",
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="inventory_source_unresolved",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSBI",
"display_name": "DSV 360 / Bison / AWSBI",
},
{
"source_code": "DSV360_AWSDU",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
},
],
}
},
)
payload = build_chat_actions_payload(task)
source_buttons = [
item for item in payload["action_buttons"]
if item["id"] == "confirm_inventory_source" and item.get("source_code")
]
assert source_buttons == []
assert [item["id"] for item in payload["action_buttons"]] == [
"confirm_inventory_source",
"retry_resolve_inventory_source",
"upload_inventory_file",
]
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
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():
@@ -234,6 +831,108 @@ 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
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():
@@ -266,8 +965,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 +992,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 +1021,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 +1069,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):
@@ -13,6 +13,24 @@ from app.services.shipping_notice.reservation_id import (
)
def test_extract_notice_text_reads_xfa_pdf_datasets():
"""XFA 表单型 PO 的订单字段应进入 raw_text,避免只抽页面文本漏明细。"""
from pathlib import Path
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf_path = Path(__file__).resolve().parents[2] / "docs" / "prototype" / "4510038672.pdf"
text, meta = extract_notice_text(pdf_path)
assert meta["file_type"] == "pdf"
assert "pdf xfa datasets extracted" in meta["warnings"]
assert "HEADER/EBELN: 4510038672" in text
assert "HEADER/SHIPMENT_TEXT: 1000144510" in text
assert "TEMP-S000218922" in text
assert "MPN:D4-A08AR12000001" in text
assert "EINDT=2026-06-23" in text
def test_extract_reservation_id_from_pr_number():
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
@@ -9,7 +9,7 @@ from app.models import ShippingTask, ShippingTaskEvent
def _tool_headers():
return {"Content-Type": "application/json"}
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
@@ -19,6 +19,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
headers = _tool_headers()
create_res = client.post(
@@ -35,6 +36,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
@@ -66,6 +68,7 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
drop = tmp_path / "drop"
drop.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
headers = _tool_headers()
create_res = client.post(
@@ -99,3 +102,47 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "inventory_ready"
def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
"""确认库存源后应立即进入 RPA pending,并写出库存导出 trigger。"""
from app import db
from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source
trigger = tmp_path / "triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
with app.app_context():
task = ShippingTask(
task_no="SN-CONFIRM-SOURCE-RPA",
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="inventory_source_unresolved",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSDU",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
}
],
}
},
lines_json=[{"sku": "A001", "qty": 1}],
)
db.session.add(task)
db.session.commit()
result = confirm_inventory_source({"task_id": task.task_no, "source_code": "DSV360_AWSDU"})
db.session.refresh(task)
assert result["status"] == "running"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.step_payload_json["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU"
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
assert len(events) == 1
assert list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json"))
@@ -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"
+461 -9
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
@@ -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,19 +166,87 @@ 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")
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):
@@ -676,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")
@@ -841,8 +991,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 +1023,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 +1076,250 @@ 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
@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):
@@ -950,6 +1365,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