feat(shipping): 实现订单批处理聊天聚合展示与优化后端逻辑

This commit is contained in:
hugo committed 2026-08-13 17:40:43 +08:00
1 parent 11cef575b4
commit 523b791c92
38 files changed
+2868 -414

No files matched your search

@@ -217,6 +217,54 @@ def test_contract_05_recovery_tick_scans_stale_inventory_attempts(app):
assert count == 2
def test_contract_05a_sweeper_respects_every_non_retryable_stp_failure(app):
"""不可重试的 Schema 阻断不能被 Sweeper 通过新 Draft 版本绕过。"""
from sqlalchemy.dialects import postgresql
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
captured = []
with patch.object(sw.db.session, 'execute', side_effect=lambda stmt: captured.append(stmt) or MagicMock(fetchall=lambda: [])):
assert sw._fetch_sweeper_case_candidates() == []
compiled = captured[0].compile(dialect=postgresql.dialect())
sql = str(compiled)
# 唯一裁决条件是 result_json.retryable=false,不能再按 blocking_reason 白名单漏拦。
assert "result_json ->> %(result_json_1)s" in sql
assert compiled.params['result_json_1'] == 'retryable'
assert 'blocking_reason' not in compiled.params.values()
def test_contract_05b_stp_schema_failure_stays_at_task_creation(app):
"""后续 STP Schema 阻断不应把当前节点投影回客户识别。"""
from app.services.shipping_notice.reconciliation_projector import (
project_review_case_projection_bundle,
)
case = SimpleNamespace(
id=505, case_no='SORC-P1-05B', status='ready', confirmed_task_id=None,
document_id=505, run=SimpleNamespace(run_no='SNER-P1-05B'),
candidate_id=None, current_draft=SimpleNamespace(draft_version=1),
)
with patch(
'app.services.shipping_notice.reconciliation_projector.project_case_automation_status',
return_value={
'status': 'failed', 'retryable': False, 'can_auto_create': True,
'can_build': True, 'job_id': 505,
'reason_code': 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
'blocking_reason': 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
'next_action': 'open_order_review',
},
):
bundle = project_review_case_projection_bundle(
case, validation={'status': 'ready', 'can_auto_create': True}, post_confirm=None,
)
assert bundle['user_stage'] == 'pre_ot_stp'
assert bundle['user_current_gate_code'] == 'task_creation'
assert bundle['current_gate']['gate_code'] == 'task_creation'
assert bundle['current_gate']['next_action_code'] == 'edit_draft'
def test_contract_06_concurrent_sweep_produces_single_active_job_via_idempotency(app):
"""合同 5:并发 Sweeper 扫描 + 部分唯一索引约束 → 只产生一个活动 STP Job。"""
from app.jobs.queue import enqueue
@@ -81,6 +81,8 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
assert result['currentActivity']['reasonCodes'] == ['budget_initial_limit', 'required_field_missing']
assert result['currentActivity']['userVisibleStage'] == 'extracting'
assert result['status'] == 'processing'
# 聊天状态投影在 Worker 开始处理时必须可序列化,且不能误标记为终态。
assert result['terminal'] is False
assert result['handlingItems'] == []
assert result['primaryNotice'] is None
@@ -988,6 +988,16 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
assert review_candidate is not None
assert review_candidate.evidence_json
assert all(item.get('field') for item in review_candidate.evidence_json)
# 冻结 Extraction 只保存 Schema 字段;Candidate 才可持有履约派生 Reservation。
confirmed_extraction = db.session.get(
ShippingOrderExtraction,
int(task.current_order_extraction_id),
)
extraction_line = confirmed_extraction.normalized_result_json['lines'][0]
candidate_line = review_candidate.structured_result_json['business_summary']['lines'][0]
assert 'effective_reservation_id' not in extraction_line
assert 'line_amount_with_tax' not in extraction_line
assert candidate_line['effective_reservation_id'] == '3000092917'
assert revision.task_id == task.id
assert revision.header_values_json['values']['po-id']['value'] == 'PO-CONFIRMED'
assert db.session.get(ShippingOrderCandidate, machine.id).structured_result_json == {
@@ -25,6 +25,7 @@ from app.services.shipping_notice.progress_audit_contract import (
DIRECT_PDF_ALLOWED_STAGES,
)
from app.services.shipping_notice.shipping_processing_projection import (
_aggregate_eml_order_task_work_items,
_conversation_processing_from_work_items,
_project_order_task_work_item,
map_run_status_to_processing_status,
@@ -77,6 +78,117 @@ def test_map_run_status_to_processing_status() -> None:
assert map_run_status_to_processing_status('unknown') == 'processing'
def test_aggregate_eml_work_items_uses_upload_completion_not_candidate_completion() -> None:
"""同一 EML 聚合卡仅在所有附件上传成功后完成,候选生成仍属于处理中。"""
base = {
'work_item_type': 'order_task', 'source_type': 'eml', 'intake_no': 'SNI-EML-1',
'root_order_task_no': 'OT-1', 'last_activity_at': '2026-08-13T00:00:00Z',
'source_summary': {'document_count': 1}, 'available_actions': [],
}
items = [
{
**base, 'work_item_no': 'OT-1', 'status': 'processing', 'stage': 'candidate_creating',
'user_status': 'running', 'user_stage': 'candidate_creating',
'facts': {'upload_state': 'not_created'},
},
{
**base, 'work_item_no': 'OT-2', 'status': 'completed', 'stage': 'completed',
'user_status': 'completed', 'user_stage': 'completed',
'facts': {'upload_state': 'succeeded'},
},
{
**base, 'work_item_no': 'OT-3', 'status': 'failed', 'stage': 'freight_uploading',
'user_status': 'failed', 'user_stage': 'freight_uploading',
'facts': {'upload_state': 'failed'},
'blocking_reason': {'code': 'upload_rpa_failed'},
},
]
result = _aggregate_eml_order_task_work_items(items)
assert len(result) == 1
aggregate = result[0]
assert aggregate['user_status'] == 'failed'
assert aggregate['facts']['upload_state'] == 'failed'
assert aggregate['aggregate_summary'] == {
'intake_no': 'SNI-EML-1', 'total': 3, 'completed': 1, 'processing': 1,
'needs_action': 0, 'failed': 1,
'stages': ['candidate_creating', 'completed', 'freight_uploading'],
'reason_codes': ['upload_rpa_failed'],
'upload_states': ['failed', 'not_created', 'succeeded'],
}
def test_aggregate_single_eml_attachment_is_still_an_intake_card() -> None:
"""单附件 EML 也必须走 Intake 聚合,且未上传的 completed 不得显示为完成。"""
item = {
'work_item_type': 'order_task', 'work_item_no': 'OT-ONLY',
'source_type': 'eml', 'intake_no': 'SNI-EML-ONLY',
'root_order_task_no': 'OT-ONLY', 'last_activity_at': '2026-08-13T00:00:00Z',
'source_summary': {'document_count': 1}, 'available_actions': [],
'status': 'completed', 'stage': 'candidate_ready',
'user_status': 'completed', 'user_stage': 'candidate_ready',
'facts': {'upload_state': 'not_created'},
}
result = _aggregate_eml_order_task_work_items([item])
assert len(result) == 1
assert result[0]['work_item_no'] == 'INTAKE:SNI-EML-ONLY'
assert result[0]['user_status'] == 'running'
assert result[0]['user_stage'] == 'candidate_ready'
assert result[0]['facts']['upload_state'] == 'not_created'
assert result[0]['aggregate_summary']['total'] == 1
assert result[0]['aggregate_summary']['completed'] == 0
assert result[0]['aggregate_summary']['processing'] == 1
def test_aggregate_maps_internal_pre_ot_stp_stage_for_user_summary() -> None:
"""建单前 STP 失败的内部阶段码不得泄漏到会话聚合摘要。"""
item = {
'work_item_type': 'order_task', 'work_item_no': 'OT-STP-FAIL',
'source_type': 'direct_pdf', 'intake_no': 'SNI-STP-FAIL',
'root_order_task_no': 'OT-STP-FAIL',
'last_activity_at': '2026-08-13T00:00:00Z',
'source_summary': {'document_count': 1}, 'available_actions': [],
'status': 'failed', 'stage': 'order_creating',
'user_status': 'failed', 'user_stage': 'pre_ot_stp',
'user_current_gate_code': 'task_creation',
'facts': {'upload_state': 'not_created'},
}
aggregate = _aggregate_eml_order_task_work_items([item])[0]
assert aggregate['stage'] == 'order_creating'
assert aggregate['user_stage'] == 'order_creating'
assert aggregate['aggregate_summary']['stages'] == ['order_creating']
assert 'pre_ot_stp' not in aggregate['aggregate_summary']['stages']
def test_eml_aggregate_prefers_cancelled_over_completed_child() -> None:
"""同一 EML 的取消附件优先于已上传完成附件,整卡不得回退为处理中。"""
base = {
'work_item_type': 'order_task', 'source_type': 'eml', 'intake_no': 'SNI-EML-CANCEL',
'root_order_task_no': 'OT-CANCEL', 'last_activity_at': '2026-08-13T00:00:00Z',
'source_summary': {'document_count': 1}, 'available_actions': [],
}
result = _aggregate_eml_order_task_work_items([
{
**base, 'work_item_no': 'OT-DONE', 'status': 'completed', 'stage': 'completed',
'user_status': 'completed', 'user_stage': 'completed',
'facts': {'upload_state': 'succeeded'},
},
{
**base, 'work_item_no': 'OT-CANCEL', 'status': 'cancelled', 'stage': 'cancelled',
'user_status': 'cancelled', 'user_stage': 'cancelled',
'facts': {'upload_state': 'not_created'},
},
])
assert result[0]['user_group'] == 'cancelled'
assert result[0]['user_status'] == 'cancelled'
def test_map_run_to_processing_stage_direct_pdf_never_email_adjudicating() -> None:
"""
direct_pdf 不得进入 email_parsing / email_adjudicating。
@@ -277,6 +389,42 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping
assert solo['status'] == 'processing'
def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, shipping_user):
"""已消费 EML 不能在 OT 聚合卡尚未可见的轮询窗口中从右侧消失。"""
with app.app_context():
conversation_id = f'conv-stage4-consumed-eml-{uuid.uuid4().hex[:8]}'
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=9403):
created = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=_upload_ready_asset(
shipping_user.id,
filename='mail.eml',
content=b'From: a@b.c\nSubject: PO-1\n\nbody',
),
upload_batch_id=str(uuid.uuid4()),
conversation_id=conversation_id,
)
intake = ShippingOrderIntake.query.filter_by(intake_no=created['intake_no']).one()
intake.parse_status = 'consumed'
intake.consumed_at = intake.created_at
db.session.commit()
payload = project_conversation_processing_items(
user_id=shipping_user.id,
conversation_id=conversation_id,
)
# 关键断言:无可替代 EML order_task 时,邮件仍以一张统一 Intake 卡返回。
assert any(
row.get('work_item_type') == 'order_intake'
and row.get('source_type') == 'eml'
and row.get('intake_no') == intake.intake_no
and row.get('status') == 'processing'
and row.get('stage') == 'candidate_creating'
for row in payload['work_items']
)
def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, shipping_user):
"""
order_task 投影须填充 current_gate / candidate_count / po_number,禁止全空摘要。
@@ -240,3 +240,32 @@ def test_stp_handler_uses_fail_job_contract_for_business_failure(app):
owned_attempt=1,
)
finish_mock.assert_not_called()
def test_stp_handler_flattens_business_error_details(app):
"""Schema 拒绝必须在 Job 结果保留具体字段,供人工精确处理。"""
from app.jobs.context import JobContext
from app.jobs.handlers import shipping_stp_auto_create as handler
job = SimpleNamespace(
id=908,
attempts=1,
payload_json={'case_no': 'SORC-STP-HANDLER-DETAIL'},
)
ctx = JobContext(config={}, logger=MagicMock(), extras={})
result = {
'ok': False,
'error_code': 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
'message': '订单明细包含未在当前 Schema 中定义的字段',
'details': {'fields': ['unexpected_field'], 'schema_version_id': 31},
}
with patch.object(handler.db.session, 'get', return_value=job), patch.object(
handler, 'execute_stp_auto_create_job', return_value=result,
), patch.object(handler, '_emit_blocked_manual_audit_if_needed'), patch.object(
handler, 'fail_job',
) as fail_mock:
handler.handle_shipping_stp_auto_create(ctx, {'job_id': 908})
persisted = fail_mock.call_args.kwargs['result']['blocking_reason_details']
assert persisted['fields'] == ['unexpected_field']
assert persisted['schema_version_id'] == 31