feat(shipping-notice): 添加订单抽取功能,支持异步运行和管理,优化相关数据模型和处理逻辑

This commit is contained in:
hugo committed 2026-07-21 09:02:42 +08:00
1 parent 34d489a2d1
commit ce26d6d0c4
144 files changed
+12241 -4233

No files matched your search

+126 -457
View File
@@ -25,6 +25,11 @@ from app.models import (
ShippingCustomer,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingTask,
ShippingTaskEvent,
ShippingTemporaryInventorySession,
@@ -34,8 +39,9 @@ from app.core.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, tools as shipping_tools
from app.services.shipping_notice import batch_orchestrator, dify_inputs, tools as shipping_tools
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import seed_task_inventory_source
@@ -350,7 +356,7 @@ def test_contract_batch_status_keeps_single_focus_without_advancing_other_tasks(
def test_create_batch_defers_parse_without_structured(app, client):
"""默认将 parse_notice 延后到 Dify,仅保存 raw_text。"""
"""旧建批入口只登记待订单抽取状态,不触发普通 Chatflow。"""
headers = _tool_headers(app)
res = client.post(
"/api/shipping-notice/tools/create_batch",
@@ -366,7 +372,7 @@ def test_create_batch_defers_parse_without_structured(app, client):
)
assert res.status_code == 200
data = res.get_json()
assert data["data"]["tasks"][0]["parse_status"] == "deferred"
assert data["data"]["tasks"][0]["parse_status"] == "awaiting_order_extraction"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=data["data"]["tasks"][0]["task_id"]).first()
assert task is not None
@@ -392,7 +398,7 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
assert result["status"] == "ok"
assert result["batch_no"].startswith("SB-")
assert result["data"]["batch"]["batch_no"] == result["batch_no"]
assert result["data"]["tasks"][0]["parse_status"] == "deferred"
assert result["data"]["tasks"][0]["parse_status"] == "awaiting_order_extraction"
assert result["data"]["focus_task"]["task_no"] == result["data"]["tasks"][0]["task_id"]
file_summary = result["file_summary"]
assert file_summary["total_files"] == 1
@@ -613,7 +619,7 @@ def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app,
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.lines_json is None
assert task.review_status is None
assert task.pending_human_reason is None
assert task.match_status is None
@@ -755,6 +761,8 @@ def test_auto_progress_resolves_dub_source_without_implicitly_triggering_rpa(app
)
_confirm_direct_task_customer(task)
db.session.add(task)
task._test_order_rows = [{"part_number": "A001", "reservation_id": "R-1", "qty": 10}]
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
@@ -768,10 +776,39 @@ def test_auto_progress_resolves_dub_source_without_implicitly_triggering_rpa(app
def test_inventory_source_rules_resolve_configured_dublin_source(app):
"""数据库中已发布的 Dublin 规则应解析到已启用库存站点。"""
"""数据库中显式发布的 Dublin 规则应解析到已启用库存站点。"""
from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source
with app.app_context():
order_schema_service.initialize_schema({'display_name': '批次库存路由测试'}, actor_id=None)
destination_field = order_schema_service.save_field(
{'field_code': 'routing_destination_code', 'scope': 'header', 'value_type': 'string'},
actor_id=None,
)
draft = order_schema_service.create_draft({}, actor_id=None)
saved = order_schema_service.save_draft(draft['id'], {
'fields': [{
'field_id': destination_field['id'],
'display_name': '路由目的地代码',
'required': False,
'aliases': [],
'normalizer_key': 'uppercase_trim',
'validator_keys': [],
'enum_options': [],
'evidence_policy': {
'required': True,
'source_precedence': ['attachment_table'],
'conflict_policy': 'block',
'allow_single_source': True,
},
'relation_role': None,
'comparator_key': 'normalized_text',
}],
'expected_lock_version': draft['lock_version'],
}, actor_id=None)
published = order_schema_service.publish(
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
)
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-DSV360-AWSDU",
source_type="pdf",
@@ -779,12 +816,61 @@ def test_inventory_source_rules_resolve_configured_dublin_source(app):
destination_code="DUB",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 10}],
)
db.session.add(task)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=task.id,
schema_version_id=published['id'],
input_snapshot_hash='b' * 64,
status='accepted',
)
db.session.add(extraction)
db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id,
line_id=None,
field_id=destination_field['id'],
decision_status='accepted',
supporting_observation_ids_json=[],
resolved_value_json='DUB',
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id,
line_id=None,
field_id=destination_field['id'],
decision_id=decision.id,
value_text='DUB',
value_json='DUB',
))
task.current_order_extraction_id = extraction.id
db.session.add(ShippingInventoryRoutingRule(
rule_code='BATCH_TEST_DUB',
rule_name='批次测试 Dublin 路由',
scope='task',
priority=100,
match_mode='all',
status='published',
action_type='add_source_candidates',
action_payload_json={'source_codes': ['DSV360_AWSDU']},
version=1,
conditions=[ShippingInventoryRoutingRuleCondition(
condition_group=1,
source_kind='order_field',
order_field_id=destination_field['id'],
operator='equals',
expected_value_json='DUB',
sequence=1,
)],
))
db.session.commit()
resolution = resolve_inventory_source(task)
assert resolution.status == "resolved"
assert resolution.source_code == "DSV360_AWSDU"
def test_auto_progress_unknown_destination_requires_inventory_source_review(app):
"""无法根据目的地唯一判断库存源时,应停在库存源人工确认检查点。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
@@ -1070,257 +1156,6 @@ def test_chat_completions_streams_shipping_ui_state(app, client, monkeypatch):
assert '"action_buttons"' in body
def test_chat_completions_streams_order_extraction_terminal_ui_state(app, client, monkeypatch):
"""事务提交并解绑 ORM 后仍须调用 Dify,并按本轮 Intake 补发权威 Batch UI State。"""
from app.services import dify as dify_module
from app.services.shipping_notice import order_extraction as order_extraction_module
with app.app_context():
user = User(
username="shipping_extraction_stream_user",
email="shipping_extraction_stream_user@example.com",
role="user",
status="active",
)
user.set_password("password")
agent = Agent(
name="货代发货通知 Agent",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
dify_api_key="test-dify-key",
api_base_url="http://dify.example/v1",
type="api",
is_active=True,
)
user.agents.append(agent)
db.session.add_all([user, agent])
db.session.flush()
session = ChatSession(
session_id="conv-extraction-terminal-ui-state",
user_id=user.id,
agent_id=agent.id,
title="Order extraction",
)
asset = FileAsset(
asset_no="FA-EXTRACTION-STREAM",
owner_user_id=user.id,
original_filename="orders.eml",
storage_provider="minio",
storage_bucket="test",
storage_key="test/orders.eml",
content_hash="extraction-stream-hash",
file_size=128,
mime_type="message/rfc822",
upload_status="ready",
lifecycle_status="referenced",
)
batch = ShippingBatch(
batch_no="SB-EXTRACTION-STREAM",
user_id=user.id,
conversation_id=session.session_id,
current_focus_task_no="SN-EXTRACTION-STREAM",
file_count=1,
)
task = ShippingTask(
task_no="SN-EXTRACTION-STREAM",
batch=batch,
user_id=user.id,
conversation_id=session.session_id,
source_type="email",
process_status="pending_review",
pending_human_reason="rsv_req",
)
db.session.add_all([session, asset, batch, task])
db.session.flush()
intake = ShippingNoticeIntake(
intake_no="SNI-EXTRACTION-STREAM",
asset_id=asset.id,
user_id=user.id,
conversation_id=session.session_id,
purpose="shipping_notice",
parse_status="parsed",
parser_version="v6",
order_extraction_status="not_started",
)
db.session.add(intake)
db.session.commit()
user_id = user.id
agent_id = agent.id
dify_called = False
original_start_order_extraction = order_extraction_module.start_order_extraction
def detaching_start_order_extraction(**kwargs):
"""模拟生产流开始前原请求 scoped session 已清理,强制暴露 ORM 跨流引用。"""
result = original_start_order_extraction(**kwargs)
db.session.expunge_all()
return result
def fake_stream_chat(*args, **kwargs):
nonlocal dify_called
dify_called = True
# 模拟 Dify submit_order_extraction Tool 在 terminal 前提交消费关系。
with app.app_context():
intake = ShippingNoticeIntake.query.filter_by(intake_no="SNI-EXTRACTION-STREAM").one()
batch = ShippingBatch.query.filter_by(batch_no="SB-EXTRACTION-STREAM").one()
intake.parse_status = "consumed"
intake.order_extraction_status = "completed"
intake.consumed_at = datetime.utcnow()
intake.consumed_batch_id = batch.id
db.session.commit()
yield 'data: {"event":"message","answer":"已创建发货任务。"}\n\n'
yield 'data: {"event":"workflow_finished","answer":"","conversation_id":"dify-extraction-conv"}\n\n'
monkeypatch.setattr(order_extraction_module, "start_order_extraction", detaching_start_order_extraction)
monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat))
res = client.post(
"/api/chat/completions",
headers={
"X-User-Id": str(user_id),
"X-Username": "shipping_extraction_stream_user",
"X-Role": "user",
"Content-Type": "application/json",
},
json={
"agent_id": agent_id,
"query": "请解析邮件并自动建单",
"conversation_id": "conv-extraction-terminal-ui-state",
"shipping_intake_nos": ["SNI-EXTRACTION-STREAM"],
},
)
body = res.get_data(as_text=True)
assert res.status_code == 200
# 关键断言:prepare_stream 提交事务并解绑 ORM 后,relay 首帧仍可发送且 Dify generator 必须被迭代。
assert dify_called is True
assert '"event": "session_created"' in body
assert '"event": "message", "answer": "已创建发货任务。"' in body
assert '"event": "shipping_ui_state"' in body
assert '"source": "order_extraction"' in body
assert '"batch_no": "SB-EXTRACTION-STREAM"' in body
assert '"task_no": "SN-EXTRACTION-STREAM"' in body
assert body.index('"event": "workflow_finished"') < body.rindex('"event": "shipping_ui_state"')
@pytest.mark.parametrize('failure_mode', ['sse_error', 'relay_exception'])
def test_chat_completions_closes_order_extraction_on_upstream_error(
app,
client,
monkeypatch,
failure_mode,
):
"""Dify SSE error 或 relay 异常都必须即时收口,不能等待五分钟超时。"""
from app.services import dify as dify_module
with app.app_context():
user = User(
username="shipping_extraction_error_user",
email="shipping_extraction_error_user@example.com",
role="user",
status="active",
)
user.set_password("password")
agent = Agent(
name="货代发货通知 Agent",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
dify_api_key="test-dify-key",
api_base_url="http://dify.example/v1",
type="api",
is_active=True,
)
user.agents.append(agent)
db.session.add_all([user, agent])
db.session.flush()
session = ChatSession(
session_id="conv-extraction-upstream-error",
user_id=user.id,
agent_id=agent.id,
title="Order extraction error",
)
asset = FileAsset(
asset_no="FA-EXTRACTION-ERROR",
owner_user_id=user.id,
original_filename="orders-error.eml",
storage_provider="minio",
storage_bucket="test",
storage_key="test/orders-error.eml",
content_hash="extraction-error-hash",
file_size=128,
mime_type="message/rfc822",
upload_status="ready",
lifecycle_status="referenced",
)
db.session.add_all([session, asset])
db.session.flush()
intake = ShippingNoticeIntake(
intake_no="SNI-EXTRACTION-ERROR",
asset_id=asset.id,
user_id=user.id,
conversation_id=session.session_id,
purpose="shipping_notice",
parse_status="parsed",
parser_version="v6",
order_extraction_status="not_started",
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type="attachment",
attachment_key="orders-error.pdf",
filename="orders-error.pdf",
content_hash="extraction-error-document-hash",
classification="order_notice",
parse_status="parsed",
extracted_text="SKU ERROR-SKU QTY 1",
)
db.session.add(document)
db.session.commit()
user_id = user.id
agent_id = agent.id
def fake_stream_chat(*args, **kwargs):
"""模拟 Dify 主动返回 error,或流迭代期间直接抛出异常。"""
if failure_mode == 'relay_exception':
raise RuntimeError('Dify connection reset')
yield 'data: {"event":"error","message":"Dify unavailable"}\n\n'
monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat))
res = client.post(
"/api/chat/completions",
headers={
"X-User-Id": str(user_id),
"X-Username": "shipping_extraction_error_user",
"X-Role": "user",
"Content-Type": "application/json",
},
json={
"agent_id": agent_id,
"query": "请解析邮件并自动建单",
"conversation_id": "conv-extraction-upstream-error",
"shipping_intake_nos": ["SNI-EXTRACTION-ERROR"],
},
)
body = res.get_data(as_text=True)
assert res.status_code == 200
assert '"event": "error"' in body
with app.app_context():
intake = ShippingNoticeIntake.query.filter_by(intake_no="SNI-EXTRACTION-ERROR").one()
document = ShippingNoticeDocument.query.filter_by(intake_id=intake.id).one()
assert intake.order_extraction_status == "failed"
assert intake.order_extraction_error_code == "SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED"
assert intake.order_extraction_error_message == (
"Dify connection reset" if failure_mode == 'relay_exception' else "Dify unavailable"
)
assert document.order_extraction_status == "failed"
def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client):
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
headers = _workspace_headers(app)
@@ -1521,6 +1356,13 @@ 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():
batch = ShippingBatch(batch_no="SB-JOB-DETACHED", file_count=1)
task = ShippingTask(
task_no="SN-20260626-DETACHED1",
batch=batch,
source_type="manual",
process_status="parsed",
)
job = Job(
domain="shipping_notice",
job_type=JobType.SHIPPING_NOTICE_RUN.value,
@@ -1529,7 +1371,7 @@ def test_process_shipping_job_survives_session_remove(app, monkeypatch):
payload_json={"task_no": "SN-20260626-DETACHED1"},
message="等待后台处理发货任务",
)
db.session.add(job)
db.session.add_all([batch, task, job])
db.session.commit()
job_id = job.id
@@ -1555,139 +1397,62 @@ def test_process_shipping_job_survives_session_remove(app, monkeypatch):
assert refreshed.result_json["status"] == "ok"
def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
"""编排器遇到 created 任务时应调用后台 Dify 执行器。"""
def test_run_single_task_stops_created_legacy_task_without_calling_chatflow(app, monkeypatch):
"""created 旧壳任务必须停下并要求重新上传,不能再次调用普通 Dify Chatflow。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-PARSE", file_count=1)
batch = ShippingBatch(batch_no="SB-ORCH-LEGACY", file_count=1)
task = ShippingTask(
task_no="SN-20260622-AAAA0001",
task_no="SN-20260622-LEGACY01",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
raw_content="customer 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)
monkeypatch.setattr(
batch_orchestrator,
"auto_progress",
lambda _payload: (_ for _ in ()).throw(AssertionError("legacy created task must not auto progress")),
)
result = batch_orchestrator._run_single_task(task.task_no)
assert result["status"] == "ok"
assert called.get("dify") == task_no
assert result["status"] == "needs_human"
assert "重新上传" in str(result["message"])
def test_submit_reparse_resets_task_and_starts_dify_orchestrator(app, monkeypatch):
"""重新解析必须回退到 created 并交给后台 Dify,不允许同步启发式解析。"""
def test_submit_reparse_requires_new_intake_run_without_mutating_task(app, monkeypatch):
"""Task 重新识别必须要求重新上传创建 Intake Run,不能回退 created 或启动旧编排器。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-REPARSE-DIFY", file_count=1)
batch = ShippingBatch(batch_no="SB-REPARSE-RUN", file_count=1)
task = ShippingTask(
task_no="SN-20260629-REPARSE1",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
raw_content="customer 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,
lambda _task_no: (_ for _ in ()).throw(AssertionError("must not start legacy orchestrator")),
)
result = shipping_tools.submit_decision({"task_id": task_no, "decision": "reparse"})
result = shipping_tools.submit_decision({"task_id": task.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
assert result["status"] == "needs_human"
assert task.process_status == "pending_review"
assert task.review_status == "parse_review"
assert task.lines_json == [{"sku": "OLD", "qty": 1}]
assert "重新上传" in result["message"]
def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypatch):
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
@@ -1705,14 +1470,9 @@ def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypat
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)
@@ -1721,97 +1481,6 @@ 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_without_persisting_chat(app, monkeypatch):
"""后台 Dify 执行器应带当前任务上下文,但不复用/污染前端聊天记录。"""
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",
agent_code="shipping_notice",
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",
external_conversation_id="22222222-2222-2222-2222-222222222222",
)
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")
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)
runtime_context = json.loads(captured["inputs"]["agent_runtime_context"])
assert runtime_context["schema_version"] == "1"
assert runtime_context["agent_code"] == "shipping_notice"
assert runtime_context["scope"] == "task_run"
assert runtime_context["platform"]["session_id"] == session.session_id
assert runtime_context["platform"]["request_id"] == f"shipping-orch-{task.task_no}"
assert runtime_context["platform"]["trigger_source"] == "backend_orchestrator"
assert runtime_context["refs"]["task_no"] == task.task_no
assert runtime_context["refs"]["batch_no"] == batch.batch_no
assert runtime_context["refs"]["run_purpose"] == "parse_notice"
assert runtime_context["domain"]["type"] == "shipping_notice"
assert runtime_context["domain"]["state_hint"]["focus_task_no"] == task.task_no
assert runtime_context["domain"]["state_hint"]["status"] == task.process_status
assert runtime_context["reference_context"]["focus_object"]["id"] == task.task_no
assert set(captured["inputs"].keys()) == {"agent_runtime_context"}
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
assert refreshed_session is not None
assert refreshed_session.external_conversation_id == "22222222-2222-2222-2222-222222222222"
def test_build_dify_chat_inputs_returns_agent_runtime_context_only(app):
"""货代发货 Agent 仅应向 Dify 注入 agent_runtime_context。"""
with app.app_context():
@@ -2025,7 +1694,7 @@ def test_build_dify_chat_inputs_does_not_restore_temporary_session_for_backend_o
runtime_context = json.loads(inputs['agent_runtime_context'])
assert 'temporary_inventory_session_no' not in runtime_context['refs']
assert runtime_context['refs']['run_purpose'] == 'parse_notice'
assert runtime_context['refs']['run_purpose'] == 'chat_turn'
def test_shipping_notice_agent_code_from_resolver():