test(shipping): 更新订单复核库存与通知流程测试
This commit is contained in:
1 parent
8ec028e6a3
commit
265a6e179a
168 files changed
+9420
-4613
No files matched your search
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_notice_tools.py
|
||||
|
||||
用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。
|
||||
依赖:Flask 测试客户端、ShippingNotice/Customer、货代 workflow 测试辅助。
|
||||
依赖:Flask 测试客户端、ShippingNotice/ShippingOrderTask/Customer、货代 workflow 测试辅助。
|
||||
逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。
|
||||
"""
|
||||
|
||||
@@ -13,16 +13,32 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule,
|
||||
ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice,
|
||||
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine,
|
||||
ShippingTaskEvent, ShippingTaskInventoryLink,
|
||||
Agent,
|
||||
ChatLog,
|
||||
ChatSession,
|
||||
ShippingCustomer,
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.match import match_notice_lines
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
from tests.conftest import confirm_test_customer_resolution, inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
|
||||
|
||||
def _tool_headers(app):
|
||||
@@ -34,46 +50,63 @@ def _tool_headers(app):
|
||||
}
|
||||
|
||||
|
||||
def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
def _seed_test_user(*, username: str) -> int:
|
||||
"""创建测试用户并返回主键,供 OT 建单与能力强令牌使用。"""
|
||||
user = User(username=username, email=f"{username}@example.test", password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
return int(user.id)
|
||||
|
||||
|
||||
def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
"""为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。"""
|
||||
order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None)
|
||||
fields = {
|
||||
code: order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None)
|
||||
fields = {
|
||||
code: order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
|
||||
)
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
|
||||
configs = [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
|
||||
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
|
||||
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
|
||||
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
} for code, field in fields.items()]
|
||||
saved = order_schema_service.save_draft(
|
||||
draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None,
|
||||
)
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
|
||||
published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
|
||||
field_ids = {
|
||||
str(item['field_code']): str(item['field_id'])
|
||||
for item in (version.definition_json or {}).get('fields') or []
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
|
||||
configs = [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
|
||||
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
|
||||
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
|
||||
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
} for code, field in fields.items()]
|
||||
saved = order_schema_service.save_draft(
|
||||
draft['id'], {'fields': configs, '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'])
|
||||
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=published['id'], input_snapshot_hash='t' * 64, status='accepted',
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
values = {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}
|
||||
for code, value in values.items():
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_status='accepted',
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_id=decision.id,
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
|
||||
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
|
||||
value_json=value,
|
||||
))
|
||||
@@ -81,14 +114,14 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
|
||||
# RPA/库存链路只消费冻结订单快照;此辅助保留动态字段测试证据的同时
|
||||
# 建立最小履约真相,避免旧测试绕过阶段 1 门禁。
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'],
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=task.order_data_version or 1,
|
||||
rule_versions_json={'fulfillment_policy': {
|
||||
'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1,
|
||||
'definition': {'field_bindings': [
|
||||
{'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']['id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']['id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']['id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.part_number', 'field_id': field_ids['part_number'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.reservation_identity', 'field_id': field_ids['reservation_id'], 'scope': 'line'},
|
||||
{'capability_code': 'fulfillment.quantity', 'field_id': field_ids['qty'], 'scope': 'line'},
|
||||
]},
|
||||
}},
|
||||
header_values_json={},
|
||||
@@ -96,26 +129,41 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0, part_number=part_number, reservation_id=reservation_id,
|
||||
snapshot_id=snapshot.id, position=0, line_no=1, part_number=part_number, reservation_id=reservation_id,
|
||||
qty=quantity, field_values_json={
|
||||
str(fields['part_number']['id']): part_number,
|
||||
str(fields['reservation_id']['id']): reservation_id,
|
||||
str(fields['qty']['id']): quantity,
|
||||
str(field_ids['part_number']): part_number,
|
||||
str(field_ids['reservation_id']): reservation_id,
|
||||
str(field_ids['qty']): quantity,
|
||||
},
|
||||
))
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _confirm_test_task_customer(task: ShippingOrderTask) -> None:
|
||||
"""为 RPA 回调/超时链路补齐已确认客户,避免自动推进被客户门禁提前阻断。"""
|
||||
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
|
||||
if customer is None:
|
||||
customer = ShippingCustomer(
|
||||
standard_name='RPA 直接回调测试客户', short_code='RPC', status='active',
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
|
||||
task._test_customer_confirmed = True
|
||||
|
||||
|
||||
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
|
||||
app.config["INTEGRATION_API_KEY"] = ""
|
||||
user_id = _seed_test_user(username='auth-dedicated')
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"},
|
||||
json={"source_type": "manual"},
|
||||
json={"source_type": "direct_pdf", "user_id": user_id},
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
@@ -126,11 +174,12 @@ def test_shipping_notice_tool_auth_falls_back_to_integration_key(app, client):
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
|
||||
app.config["INTEGRATION_API_KEY"] = "integration-secret"
|
||||
user_id = _seed_test_user(username='auth-integration')
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"},
|
||||
json={"source_type": "manual"},
|
||||
json={"source_type": "direct_pdf", "user_id": user_id},
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
@@ -145,7 +194,7 @@ def test_shipping_notice_tool_auth_reports_missing_config(app, client):
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers={"Content-Type": "application/json", "X-Integration-Key": "any"},
|
||||
json={"source_type": "manual"},
|
||||
json={"source_type": "direct_pdf"},
|
||||
)
|
||||
|
||||
assert res.status_code == 503
|
||||
@@ -157,7 +206,7 @@ def test_parse_notice_tool_is_removed(app, client):
|
||||
response = client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=_tool_headers(app),
|
||||
json={"task_id": "SN-REMOVED"},
|
||||
json={"task_id": "OT-REMOVED"},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
@@ -179,14 +228,14 @@ def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch):
|
||||
)
|
||||
|
||||
result = fulfillment_workflow.generate_excel({
|
||||
'task_id': 'SN-FORMAL-EXCEL-ONLY',
|
||||
'task_id': 'OT-FORMAL-EXCEL-ONLY',
|
||||
'operator_id': 7,
|
||||
'idempotency_key': 'formal-excel-only',
|
||||
})
|
||||
|
||||
assert result['status'] == 'running'
|
||||
assert submitted == {
|
||||
'task_no': 'SN-FORMAL-EXCEL-ONLY',
|
||||
'task_no': 'OT-FORMAL-EXCEL-ONLY',
|
||||
'trigger': 'tool_api_generate_excel',
|
||||
'expected_version': None,
|
||||
'idempotency_key': 'formal-excel-only',
|
||||
@@ -222,20 +271,36 @@ def test_match_notice_lines_reports_progress():
|
||||
|
||||
|
||||
def test_contract_get_task_status_accepts_task_no_anchor(app, client):
|
||||
"""契约:用户输入 SN-... 时,Dify 应直连 get_task_status 并锚定对应任务。"""
|
||||
"""契约:用户输入 OT-... 时,Dify 应直连 get_task_status 并锚定对应任务。"""
|
||||
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability
|
||||
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
app.config["SHIPPING_CHAT_CAPABILITY_SECRET"] = "test-capability-secret"
|
||||
user_id = _seed_test_user(username='status-anchor')
|
||||
agent = Agent(name='shipping-agent', agent_code='shipping_notice_status_anchor')
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
session = ChatSession(session_id='status-anchor-session', user_id=user_id, agent_id=agent.id)
|
||||
db.session.add(session)
|
||||
db.session.commit()
|
||||
session_id = session.session_id
|
||||
agent_id = int(agent.id)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"},
|
||||
json={"source_type": "direct_pdf", "user_id": user_id, "conversation_id": session_id,
|
||||
"raw_content": "客户:ACME 料号A001 x 10"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
token = issue_chat_capability(user_id=user_id, session_id=session_id, agent_id=agent_id, task_no=task_id)
|
||||
|
||||
status_res = client.post(
|
||||
"/api/shipping-notice/tools/get_task_status",
|
||||
headers=headers,
|
||||
json={"task_no": task_id},
|
||||
json={"task_no": task_id, "shipping_chat_capability_token": token},
|
||||
)
|
||||
data = status_res.get_json()
|
||||
|
||||
@@ -273,12 +338,11 @@ def test_confirm_inventory_source_route_is_removed(app, client):
|
||||
"""库存源人工确认已下线,任何旧 Tool 写入口均不得可达。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-HTTP-CONFIRM-SRC",
|
||||
source_type="manual",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-HTTP-CONFIRM-SRC",
|
||||
user_id=1,
|
||||
source_type="eml",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
ship_to="Dublin",
|
||||
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -286,7 +350,7 @@ def test_confirm_inventory_source_route_is_removed(app, client):
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/confirm_inventory_source",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
|
||||
json={"task_id": "OT-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
|
||||
)
|
||||
assert res.status_code == 404
|
||||
|
||||
@@ -304,91 +368,13 @@ def test_static_openapi_snapshot_contains_shipping_contract_keywords():
|
||||
assert "match_inventory" not in spec_text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("decision", ["confirm_inventory_mapping", "correct_inventory_mapping"])
|
||||
def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision):
|
||||
"""已启用库存站点不得通过任务决策重开旧列映射路径。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual")
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
response = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": f"SN-LEGACY-MAP-{decision}", "decision": decision},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
# These decisions must never reopen manual mapping or mutate the task.
|
||||
assert body["status"] == "failed"
|
||||
assert "已发布解析方案" in body["message"]
|
||||
|
||||
|
||||
def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app, client, tmp_path):
|
||||
"""重新上传库存只重置正式库存结果,不进入任务级字段映射。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REUPLOAD-INVENTORY",
|
||||
source_type="manual",
|
||||
inventory_lines_json=[{"part_number": "A001", "available_qty": 10}],
|
||||
match_status="fulfillable",
|
||||
line_results_json=[{"part_number": "A001"}],
|
||||
shortage_json={"lines": []},
|
||||
export_file_path=str(tmp_path / "shipment.xlsx"),
|
||||
export_file_name="shipment.xlsx",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no="SIF-REUPLOAD-001",
|
||||
storage_path=str(tmp_path / "inventory.xlsx"),
|
||||
source_file_name="inventory.xlsx",
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
link = ShippingTaskInventoryLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inventory_file.id,
|
||||
link_role="owner",
|
||||
)
|
||||
db.session.add(link)
|
||||
db.session.commit()
|
||||
|
||||
response = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-REUPLOAD-INVENTORY", "decision": "reparse_inventory"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["status"] == "needs_human"
|
||||
assert body["checkpoint"] == "upload_req"
|
||||
assert "human_options" not in body
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
|
||||
assert link.is_active is False
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.match_status is None
|
||||
assert task.line_results_json is None
|
||||
assert task.shortage_json is None
|
||||
assert task.export_file_path is None
|
||||
assert task.export_file_name is None
|
||||
|
||||
|
||||
def test_parse_inventory_from_chat_text_route_is_removed(app, client):
|
||||
"""正式任务不再接受对话文本库存;临时库存由独立会话 Tool 处理。"""
|
||||
headers = _tool_headers(app)
|
||||
parse_inv = client.post(
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"},
|
||||
json={"task_id": "OT-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"},
|
||||
)
|
||||
assert parse_inv.status_code == 404
|
||||
assert parse_inv.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
|
||||
@@ -400,7 +386,7 @@ def test_parse_inventory_empty_text_route_is_removed(app, client):
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-REMOVED", "raw_inventory_text": " "},
|
||||
json={"task_id": "OT-REMOVED", "raw_inventory_text": " "},
|
||||
)
|
||||
assert res.status_code == 404
|
||||
assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
|
||||
@@ -413,7 +399,7 @@ def test_match_by_supplier_sku_and_reservation_id(app, client):
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": "SN-REMOVED",
|
||||
"task_id": "OT-REMOVED",
|
||||
"raw_inventory_text": "Supplier Sku\tCOM ID\tQty Available\nA001\tR-1\t2\n",
|
||||
},
|
||||
)
|
||||
@@ -427,7 +413,7 @@ def test_removed_inventory_text_route_cannot_create_mapping_checkpoint(app, clie
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": "SN-REMOVED",
|
||||
"task_id": "OT-REMOVED",
|
||||
"raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n",
|
||||
},
|
||||
)
|
||||
@@ -441,7 +427,7 @@ def test_removed_inventory_text_route_cannot_reopen_mapping_correction(app, clie
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": "SN-REMOVED",
|
||||
"task_id": "OT-REMOVED",
|
||||
"raw_inventory_text": (
|
||||
"Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n"
|
||||
"D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n"
|
||||
@@ -459,87 +445,10 @@ def test_legacy_task_inventory_mapping_routes_are_removed(app, client):
|
||||
"/api/shipping-notice/tools/get_inventory_schema_preview",
|
||||
"/api/shipping-notice/tools/apply_inventory_mapping",
|
||||
):
|
||||
response = client.post(path, headers=headers, json={"task_id": "SN-LEGACY-REMOVED"})
|
||||
response = client.post(path, headers=headers, json={"task_id": "OT-LEGACY-REMOVED"})
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
headers = _tool_headers(app)
|
||||
trigger = tmp_path / "inventory_triggers"
|
||||
inventory_drop = tmp_path / "inventory_drop"
|
||||
trigger.mkdir()
|
||||
inventory_drop.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop)
|
||||
|
||||
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 = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.review_status = None
|
||||
task.pending_human_reason = "inv_unavail"
|
||||
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}]
|
||||
task.match_status = "fulfillable"
|
||||
task.shortage_json = {"lines": []}
|
||||
task.line_results_json = [{"part_number": "OLD", "status": "ok"}]
|
||||
task.export_file_path = str(tmp_path / "old.xlsx")
|
||||
task.export_file_name = "old.xlsx"
|
||||
task.upload_status = "failed"
|
||||
task.upload_mode = "rpa"
|
||||
task.upload_error_message = "old upload failed"
|
||||
task.freight_ref_no = "OLD-REF"
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"connector_type": "dsv360",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
|
||||
}
|
||||
}
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice import decision_workflow
|
||||
|
||||
with app.app_context():
|
||||
retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"})
|
||||
assert retry_data["status"] == "running"
|
||||
assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"}
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.review_status is None
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.match_status is None
|
||||
assert task.shortage_json is None
|
||||
assert task.line_results_json is None
|
||||
assert task.export_file_path is None
|
||||
assert task.export_file_name is None
|
||||
assert task.upload_status is None
|
||||
assert task.upload_error_message is None
|
||||
assert task.freight_ref_no is None
|
||||
event = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").first()
|
||||
assert event is not None
|
||||
assert event.detail_json.get("force_refresh") is True
|
||||
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path, monkeypatch):
|
||||
from datetime import datetime, timedelta
|
||||
@@ -557,17 +466,21 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
lambda: None,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
user_id = _seed_test_user(username='rpa-timeout-recheck')
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
json={"source_type": "direct_pdf", "user_id": user_id},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
_confirm_test_task_customer(task)
|
||||
task.pending_human_reason = PH_RPA_PENDING
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
@@ -591,7 +504,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
|
||||
with app.app_context():
|
||||
result = _run_single_task(task_id)
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert result["status"] == "needs_human"
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
@@ -602,171 +515,13 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
|
||||
|
||||
|
||||
@pytest.mark.auto_rpa
|
||||
def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
|
||||
|
||||
headers = _tool_headers(app)
|
||||
trigger = tmp_path / "inventory_triggers"
|
||||
inventory_drop = tmp_path / "inventory_drop"
|
||||
trigger.mkdir()
|
||||
inventory_drop.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop)
|
||||
|
||||
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 = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.pending_human_reason = PH_RPA_EXHAUSTED
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"connector_type": "dsv360",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
|
||||
}
|
||||
}
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
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()
|
||||
|
||||
from app.services.shipping_notice import decision_workflow
|
||||
|
||||
with app.app_context():
|
||||
retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"})
|
||||
assert retry_data["status"] == "running"
|
||||
assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
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("current") == 1
|
||||
assert progress.get("extra", {}).get("manual_retry_round") is True
|
||||
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
|
||||
|
||||
|
||||
def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client):
|
||||
headers = _tool_headers(app)
|
||||
|
||||
first = ShippingNotice(
|
||||
task_no="SN-MULTI-CONV-001",
|
||||
conversation_id="conv-test-multi",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}],
|
||||
)
|
||||
second = ShippingNotice(
|
||||
task_no="SN-MULTI-CONV-002",
|
||||
conversation_id="conv-test-multi",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
lines_json=[{"part_number": "A002", "reservation_id": "1000140352", "qty": 1}],
|
||||
)
|
||||
with app.app_context():
|
||||
db.session.add_all([first, second])
|
||||
db.session.commit()
|
||||
|
||||
confirm_res = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"conversation_id": "conv-test-multi", "decision": "confirm"},
|
||||
)
|
||||
confirm_data = confirm_res.get_json()
|
||||
assert confirm_data["status"] == "failed"
|
||||
assert "任务编号" in confirm_data["message"] or "task ID" in confirm_data["message"]
|
||||
|
||||
status_res = client.post(
|
||||
"/api/shipping-notice/tools/get_task_status",
|
||||
headers=headers,
|
||||
json={"conversation_id": "conv-test-multi"},
|
||||
)
|
||||
status_data = status_res.get_json()
|
||||
assert status_data["status"] == "failed"
|
||||
assert "任务编号" in status_data["message"]
|
||||
|
||||
with app.app_context():
|
||||
rows = {
|
||||
task.task_no: task
|
||||
for task in ShippingNotice.query.filter(ShippingNotice.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"]))
|
||||
.order_by(ShippingNotice.task_no)
|
||||
.all()
|
||||
}
|
||||
assert rows["SN-MULTI-CONV-001"].review_status == "parse_review"
|
||||
assert rows["SN-MULTI-CONV-002"].review_status == "parse_review"
|
||||
|
||||
|
||||
def test_submit_decision_retry_rpa_routes_to_formal_gate_action(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_request_formal_gate_action(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {"status": "running", "task_id": task_id, "message": "已提交正式 20-Gate 恢复动作"}
|
||||
|
||||
monkeypatch.setattr(decision_workflow, "_request_formal_gate_action", fake_request_formal_gate_action)
|
||||
|
||||
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"] == "已提交正式 20-Gate 恢复动作"
|
||||
assert captured["task"].task_no == task_id
|
||||
assert captured["action_code"] == "retry_inventory_preparation"
|
||||
|
||||
|
||||
def test_parse_inventory_oversized_text_route_is_removed(app, client):
|
||||
"""旧正式库存文本入口无论内容大小都不可访问。"""
|
||||
headers = _tool_headers(app)
|
||||
res = client.post(
|
||||
"/api/shipping-notice/tools/parse_inventory",
|
||||
headers=headers,
|
||||
json={"task_id": "SN-REMOVED", "raw_inventory_text": "x" * 200},
|
||||
json={"task_id": "OT-REMOVED", "raw_inventory_text": "x" * 200},
|
||||
)
|
||||
assert res.status_code == 404
|
||||
assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
|
||||
@@ -776,12 +531,13 @@ def test_chat_actions_empty_when_task_rejected(app):
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-20260101-TEST0001",
|
||||
source_type="manual",
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-20260101-TEST0001",
|
||||
user_id=1,
|
||||
source_type="eml",
|
||||
review_status="rejected",
|
||||
)
|
||||
ui_state = build_task_ui_state(task)
|
||||
assert ui_state["checkpoint"]["code"] == "rejected"
|
||||
assert ui_state["review_status"] == "rejected"
|
||||
assert ui_state["actions"] == {"primary": None, "secondary": []}
|
||||
assert "action_buttons" not in ui_state
|
||||
Reference in new issue
Block a user