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

+6 -3
View File
@@ -1495,7 +1495,8 @@ def workspace_list_shipping_order_extraction_progress_events(run_no: str):
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no, batch_id=batch_id)
record_access_audit(
action='view_order_extraction_timeline',
aggregate_type='order_extraction_run',
@@ -1514,7 +1515,8 @@ def workspace_list_shipping_order_extraction_documents(run_no: str):
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_documents
items = list_user_order_extraction_documents(user_id=user.id, run_no=run_no)
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
items = list_user_order_extraction_documents(user_id=user.id, run_no=run_no, batch_id=batch_id)
record_access_audit(
action='view_order_extraction_documents',
aggregate_type='order_extraction_run',
@@ -2959,7 +2961,8 @@ def workspace_shipping_order_extraction_timeline(run_no: str):
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)
batch_id = str(request.args.get('upload_batch_id') or '').strip() or None
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no, batch_id=batch_id)
record_access_audit(
action='view_order_extraction_timeline',
aggregate_type='order_extraction_run',
@@ -201,6 +201,9 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
extra['task_no'] = str(result.get('task_no') or '')
if result.get('idempotent_replay'):
extra['idempotent_replay'] = True
if result.get('superseded'):
extra['superseded'] = True
extra['superseded_draft_version'] = result.get('superseded_draft_version')
if result.get('auto_progress_status'):
extra['auto_progress_status'] = str(result.get('auto_progress_status') or '')
finish_job(
@@ -238,6 +241,9 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
'details',
}
}
nested_details = details.pop('details', None)
if isinstance(nested_details, dict):
details.update(nested_details)
details.setdefault('payload_case_no', str(frozen.get('case_no') or ''))
details.setdefault('payload_run_no', str(frozen.get('run_no') or ''))
retryable, normalized, next_action = _classify_stp_job_result(
@@ -346,6 +346,25 @@ def append_shipping_audit_event(
resolved_reason_code = str(reason_code)[:128] if reason_code else None
resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None
# #region debug-point A/B/C/D:submission-audit-flush
try:
import os
import urllib.request
debug_env = Path(__file__).resolve().parents[5] / '.dbg' / 'order-submission-deadlock.env'
debug_values = {
line.split('=', 1)[0]: line.split('=', 1)[1].strip()
for line in debug_env.read_text(encoding='utf-8').splitlines()
if '=' in line
}
urllib.request.urlopen(urllib.request.Request(
debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'),
data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'order-submission-deadlock'), 'runId': 'pre-fix', 'hypothesisId': 'A/B/C/D', 'location': 'audit_service.py:349', 'msg': '[DEBUG] audit flush lock state', 'data': {'pid': os.getpid(), 'aggregate_type': str(aggregate_type)[:64], 'aggregate_id': str(aggregate_id)[:128], 'event_type': str(event_type)[:64], 'in_transaction': db.session.in_transaction()}}).encode(),
headers={'Content-Type': 'application/json'},
), timeout=1).read()
except Exception:
pass
# #endregion
# [STEP 2] flush 同事务先前事件,保证哈希链前驱可查。
db.session.flush()
previous_event_hash = resolve_previous_event_hash(
@@ -3194,13 +3194,20 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str,
else {}
)
workspace_projection = serialize_workspace_run(run)
effective_status = str(workspace_projection.get('effective_status') or run.status or 'queued')
return {
'run_no': run.run_no,
'agent_id': run.owner_agent_id,
'conversation_id': run.conversation_id,
'status': run.status,
'phase': run.phase,
'status': effective_status,
'phase': effective_status if effective_status == 'failed' else run.phase,
'intake_nos': [item.get('intake_no') for item in intake_snapshot if item.get('intake_no')],
# 同一文件选择批次可拆为多个独立 Run;仅供聊天层聚合展示,绝不作为 OT 主键。
'upload_batch_id': (
str(run.input_snapshot_json.get('upload_batch_id') or '').strip() or None
if isinstance(run.input_snapshot_json, dict)
else None
),
'schema_version_id': run.schema_version_id,
'schema_version': schema_snapshot.get('version'),
'schema_checksum': schema_snapshot.get('checksum'),
@@ -3216,6 +3223,7 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str,
'selection_plan': _selection_plan_summary(selection_snapshot),
'unit_summary': _unit_fact_summary(run),
'current_activity': workspace_projection['current_activity'],
'documents': workspace_projection.get('documents') or [],
'available_actions': workspace_projection['available_actions'],
'handling_items': workspace_projection.get('handling_items') or [],
'primary_notice': workspace_projection.get('primary_notice'),
@@ -3295,20 +3303,39 @@ def cleanup_expired_order_extraction_progress_events(*, limit: int = 1000, now:
return {'deleted_count': count}
def list_user_order_extraction_progress_events(*, user_id: int, run_no: str) -> list[dict[str, Any]]:
def _detail_scope_runs(run: ShippingOrderProcessingRun) -> list[ShippingOrderProcessingRun]:
"""返回同一用户、会话、上传批次的 Run;无批次时仅返回当前 Run。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
batch_id = str(snapshot.get('upload_batch_id') or '').strip()
if not batch_id:
return [run]
rows = ShippingOrderProcessingRun.query.filter_by(
user_id=run.user_id,
conversation_id=run.conversation_id,
).order_by(ShippingOrderProcessingRun.created_at.asc()).all()
return [row for row in rows if str((row.input_snapshot_json or {}).get('upload_batch_id') or '').strip() == batch_id]
def list_user_order_extraction_progress_events(*, user_id: int, run_no: str, batch_id: str | None = None) -> list[dict[str, Any]]:
"""返回当前执行周期的用户进度,避免历史重试技术事件干扰最终业务结论。"""
from app.models import ShippingOrderExtractionProgressEvent
run = get_order_extraction_run(user_id=user_id, run_no=run_no)
query = (
ShippingOrderExtractionProgressEvent.query
.filter_by(run_id=run.id, visibility='workspace')
scoped_runs = _detail_scope_runs(run)
requested_batch = str(batch_id or '').strip()
if requested_batch and requested_batch != str((run.input_snapshot_json or {}).get('upload_batch_id') or '').strip():
raise NotFoundError('Order extraction batch not found')
run_ids = [int(item.id) for item in scoped_runs]
query = ShippingOrderExtractionProgressEvent.query.filter(
ShippingOrderExtractionProgressEvent.run_id.in_(run_ids),
ShippingOrderExtractionProgressEvent.visibility == 'workspace',
)
# 手工重试会创建新 Job;保留本次 Run 在入队前产生的计划事件,过滤旧 Job 的执行事件。
if run.current_job_id is not None:
current_job_ids = [int(item.current_job_id) for item in scoped_runs if item.current_job_id is not None]
if current_job_ids:
query = query.filter(or_(
ShippingOrderExtractionProgressEvent.job_id.is_(None),
ShippingOrderExtractionProgressEvent.job_id == int(run.current_job_id),
ShippingOrderExtractionProgressEvent.job_id.in_(current_job_ids),
))
rows = query.order_by(
ShippingOrderExtractionProgressEvent.sequence_no.asc(),
@@ -3334,15 +3361,29 @@ def list_user_order_extraction_progress_events(*, user_id: int, run_no: str) ->
'summary': row.summary_json,
'occurred_at': (row.occurred_at or row.received_at or row.created_at).isoformat() + 'Z',
})
return items
return sorted(items, key=lambda item: str(item.get('occurred_at') or ''))
def list_user_order_extraction_documents(*, user_id: int, run_no: str) -> list[dict[str, Any]]:
def list_user_order_extraction_documents(*, user_id: int, run_no: str, batch_id: str | None = None) -> list[dict[str, Any]]:
"""返回按 PDF 归并的工作台详情结果;前端不得再从事件流自行推断文档结论。"""
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_documents
run = get_order_extraction_run(user_id=user_id, run_no=run_no)
return serialize_workspace_run_documents(run)
requested_batch = str(batch_id or '').strip()
actual_batch = str((run.input_snapshot_json or {}).get('upload_batch_id') or '').strip()
if requested_batch and requested_batch != actual_batch:
raise NotFoundError('Order extraction batch not found')
items: list[dict[str, Any]] = []
seen: set[int] = set()
for scoped_run in _detail_scope_runs(run):
for item in serialize_workspace_run_documents(scoped_run):
document_id = int(item.get('document_id') or 0)
if document_id and document_id in seen:
continue
if document_id:
seen.add(document_id)
items.append(item)
return items
def mark_order_extraction_run_seen(*, user_id: int, run_no: str) -> bool:
@@ -317,6 +317,93 @@ def _snapshot_documents(run: ShippingOrderProcessingRun) -> dict[int, dict[str,
return items
def _snapshot_intake_parse_statuses(run: ShippingOrderProcessingRun) -> dict[int, str]:
"""读取冻结 Intake 解析状态,供 EML 父项和失败态展示使用。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
return {
int(item.get('intake_id') or 0): str(item.get('parse_status') or '').strip().lower()
for item in snapshot.get('intakes') or []
if isinstance(item, dict) and int(item.get('intake_id') or 0) > 0
}
def _effective_run_status(
run: ShippingOrderProcessingRun,
*,
units: list[ShippingOrderProcessingUnit],
) -> str:
"""把已冻结的 Intake.parse_failed 反映到用户态 Run 状态,避免继续显示处理中。"""
current = str(run.status or 'queued').strip().lower()
if current not in {'queued', 'processing'}:
return current
parse_statuses = _snapshot_intake_parse_statuses(run)
if parse_statuses and any(status == 'parse_failed' for status in parse_statuses.values()):
if not units or all(str(unit.status or '') in {'pending', 'failed', 'cancelled'} for unit in units):
return 'failed'
return current
def _email_parent_rows(
run: ShippingOrderProcessingRun,
*,
documents: dict[int, dict[str, Any]],
existing_document_ids: set[int],
) -> list[dict[str, Any]]:
"""为每个 EML Intake 补出父项,确保附件按 EML 聚合而非平铺。"""
parse_statuses = _snapshot_intake_parse_statuses(run)
rows: list[dict[str, Any]] = []
for document in documents.values():
if str(document.get('document_type') or '').strip().lower() != 'email_body':
continue
document_id = int(document.get('document_id') or 0)
intake_id = int(document.get('intake_id') or 0)
if document_id <= 0 or document_id in existing_document_ids:
continue
parse_status = parse_statuses.get(intake_id, '')
parent_status = 'failed' if parse_status == 'parse_failed' else 'processing'
rows.append({
'unit_id': -document_id,
'document_id': document_id,
'intake_id': intake_id,
'document_type': 'email_body',
'file_name': document.get('file_name'),
'status': parent_status,
'user_visible_stage': 'failed' if parent_status == 'failed' else 'email_parsing',
'queue_position': None,
'elapsed_seconds': None,
'health_tips': [],
'cancellation': None,
'activity_version': 1,
'selection_batch': None,
'group_key': None,
'retry_status': None,
'technical_failure_reason_code': 'intake_parse_failed' if parent_status == 'failed' else None,
'budget_cost': None,
'po_number': None,
'line_count': 0,
'profile': None,
'route_type': None,
'match_status': None,
'freeze_source': None,
'email_supplement': {'status': 'none', 'relation_codes': [], 'conflict_count': 0},
'reason_code': 'intake_parse_failed' if parent_status == 'failed' else None,
'explainability': build_explainability_reason(
reason_code='intake_parse_failed',
details={'document_id': document_id, 'file_name': document.get('file_name')},
) if parent_status == 'failed' else None,
'review_details': [],
'duplicate_resolution': None,
'existing_task_no': None,
'duplicate_status': None,
'available_actions': ['view_details', 'retry_parse'] if parent_status == 'failed' else ['view_details'],
'activity_event_code': 'parse_failed' if parent_status == 'failed' else 'email_parsing',
'started_at': None,
'last_activity_at': None,
'finished_at': run.finished_at.isoformat() + 'Z' if parent_status == 'failed' and run.finished_at else None,
})
return rows
def _snapshot_profiles(run: ShippingOrderProcessingRun) -> dict[tuple[str, int], dict[str, Any]]:
"""从冻结快照中读取模板展示信息,避免文档详情受后续模板修改影响。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -1057,7 +1144,7 @@ def _planned_layout_documents(
if str(item.get('content_hash') or '').strip()
}
items: list[dict[str, Any]] = []
run_failed = str(run.status or '') == 'failed'
run_failed = _effective_run_status(run, units=[] ) == 'failed'
run_failure_code = str(run.error_code or '').strip() or 'technical_failure'
run_cancelled = str(run.status or '') == 'cancelled'
now = datetime.utcnow()
@@ -1083,6 +1170,8 @@ def _planned_layout_documents(
# Unit 尚不存在时没有稳定 unit_id;使用负序号仅作 UI 列表 key,不可用于写接口。
'unit_id': -index,
'document_id': document_id,
'intake_id': int(document.get('intake_id') or 0) or None,
'document_type': str(document.get('document_type') or '').strip() or 'attachment',
'file_name': _safe_file_name(selected_item.get('filename')) or document.get('file_name'),
# Job 可在 Unit 物化前最终失败;此时每份计划 PDF 都不能继续显示为 pending。
'status': status,
@@ -1273,7 +1362,12 @@ def serialize_workspace_run_documents(run: ShippingOrderProcessingRun) -> list[d
documents = _snapshot_documents(run)
event_map, _ = _latest_progress_events(run)
if not units:
return _planned_layout_documents(run, documents, _latest_layout_document_events(run))
planned = _planned_layout_documents(run, documents, _latest_layout_document_events(run))
return _email_parent_rows(
run,
documents=documents,
existing_document_ids={int(item.get('document_id') or 0) for item in planned},
) + planned
profiles_by_key = _snapshot_profiles(run)
field_codes = _schema_field_codes(run)
route_by_unit = _latest_route_decisions(run)
@@ -1300,6 +1394,8 @@ def serialize_workspace_run_documents(run: ShippingOrderProcessingRun) -> list[d
items.append({
'unit_id': int(unit.id),
'document_id': int(unit.document_id),
'intake_id': int(document.get('intake_id') or 0) or None,
'document_type': str(document.get('document_type') or '').strip() or 'attachment',
'file_name': document.get('file_name'),
'status': unit.status,
'user_visible_stage': _unit_user_visible_stage(unit, run=run),
@@ -1336,7 +1432,11 @@ def serialize_workspace_run_documents(run: ShippingOrderProcessingRun) -> list[d
'last_activity_at': getattr(unit, 'last_activity_at', None).isoformat() + 'Z' if getattr(unit, 'last_activity_at', None) else None,
'finished_at': getattr(unit, 'finished_at', None).isoformat() + 'Z' if getattr(unit, 'finished_at', None) else None,
})
return items
return _email_parent_rows(
run,
documents=documents,
existing_document_ids={int(item.get('document_id') or 0) for item in items},
) + items
def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
@@ -1349,9 +1449,15 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
documents = _snapshot_documents(run)
_, current_event = _latest_progress_events(run)
status_counter = Counter(str(unit.status or '') for unit in units)
effective_status = _effective_run_status(run, units=units)
email_parent_count = len(_email_parent_rows(
run,
documents=documents,
existing_document_ids={int(unit.document_id) for unit in units},
))
open_existing_doc_ids = _open_existing_document_ids(run)
current_activity = None
if run.status in {'queued', 'processing'}:
if effective_status in {'queued', 'processing'}:
if str(run.phase or '') == 'waiting_layout':
current_activity = {
'unit_id': None,
@@ -1419,18 +1525,23 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
),
}
return {
'effective_status': effective_status,
'summary': {
'total_documents': _planned_document_count(run, units),
# EML 父项只是聚合容器,不重复计入文件总数;无附件时至少展示父项本身。
'total_documents': max(_planned_document_count(run, units), email_parent_count),
'pending_documents': sum(status_counter.get(status, 0) for status in {'pending'}),
'processing_documents': sum(status_counter.get(status, 0) for status in {'routing', 'matching_profile', 'extracting', 'merging_supplement'}),
'completed_documents': status_counter.get('candidate_ready', 0),
'review_required_documents': review_document_count,
'failed_documents': status_counter.get('failed', 0),
'failed_documents': status_counter.get('failed', 0) + sum(
1 for status in _snapshot_intake_parse_statuses(run).values() if status == 'parse_failed'
),
'cancelled_documents': status_counter.get('cancelled', 0),
'candidate_count': sum(_candidate_count(unit) for unit in units),
'opened_existing_documents': opened_existing_count,
},
'current_activity': current_activity,
'documents': serialize_workspace_run_documents(run),
'handling_items': handling_items,
'primary_notice': _primary_notice_from_handling_items(handling_items),
'available_actions': _run_available_actions(
@@ -1439,7 +1550,7 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
open_existing_doc_ids=open_existing_doc_ids,
handling_items=handling_items,
),
'user_visible_stage': _run_user_visible_stage(run, units),
'user_visible_stage': 'failed' if effective_status == 'failed' else _run_user_visible_stage(run, units),
# 回滚进度 UI v3 时不下发健康提示,避免前端展示灰度未启用的细化提醒。
'health_tips': _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else [],
'cancellation': _cancellation_projection(run),
@@ -1477,10 +1588,11 @@ def serialize_workspace_run_chat_state(run: ShippingOrderProcessingRun) -> dict[
不能继续把 Workflow/health 等旧展示语义塞回消息 payload。
"""
projection = serialize_workspace_run(run)
effective_status = str(projection.get('effective_status') or run.status or 'queued')
summary = projection['summary'] if isinstance(projection.get('summary'), dict) else {}
current_activity = projection['current_activity'] if isinstance(projection.get('current_activity'), dict) else None
return {
'status': str(run.status or 'queued'),
'status': effective_status,
# 版本谱系是聊天历史只读隔离的事实源;前端不得按时间或消息位置猜测当前 Run。
'runNo': run.run_no,
'sourceRunNo': run.reparse_source.run_no if run.reparse_source is not None else None,
@@ -1513,6 +1625,22 @@ def serialize_workspace_run_chat_state(run: ShippingOrderProcessingRun) -> dict[
}
if current_activity else None
),
'documents': [
{
'unitId': int(item.get('unit_id') or 0),
'documentId': int(item.get('document_id') or 0),
'intakeId': int(item.get('intake_id') or 0) or None,
'documentType': item.get('document_type'),
'fileName': item.get('file_name'),
'status': str(item.get('status') or ''),
'userVisibleStage': item.get('user_visible_stage'),
'reasonCode': item.get('reason_code'),
'explainability': item.get('explainability'),
'emailSupplement': item.get('email_supplement'),
}
for item in (projection.get('documents') or [])
if isinstance(item, dict)
],
'availableActions': [str(action) for action in projection.get('available_actions') or []],
'handlingItems': [
{
@@ -1530,7 +1658,7 @@ def serialize_workspace_run_chat_state(run: ShippingOrderProcessingRun) -> dict[
'healthTips': projection.get('health_tips') or [],
'cancellation': projection.get('cancellation'),
'progressVersion': projection.get('progress_version'),
'terminal': str(run.status or '') not in {'queued', 'processing'},
'terminal': effective_status not in {'queued', 'processing'},
'errorCode': str(run.error_code or '') or None,
# [STEP] Run 失败可解释性;与 serialize_order_extraction_run.error.explainability 语义对齐。
'errorExplainability': _chat_run_error_explainability(run),
@@ -364,12 +364,19 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
for item in configs
if str(item.get('scope') or '') == 'line' and item.get('field_code')
}
# `line_key` is Draft-only identity used by wave selection and lineage remapping.
# It is not a Schema business field and must never be materialized as one.
internal_line_fields = {'line_key'}
unknown_line_fields = sorted({
str(key)
for line in summary.get('lines') or []
if isinstance(line, dict)
for key in line
if str(key) not in formal_line_codes and not str(key).startswith('_')
if (
str(key) not in formal_line_codes
and str(key) not in internal_line_fields
and not str(key).startswith('_')
)
})
if unknown_line_fields:
raise ValidationError(
@@ -1239,8 +1246,11 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
'Customer is not confirmed',
code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED',
)
# Candidate normalization adds fulfillment-only derived fields such as
# effective_reservation_id. Extraction is the frozen Schema record and
# must receive the unmodified reviewed summary for strict field checks.
normalized = normalize_candidate_business_summary(summary)
extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=normalized, actor_id=int(user_id))
extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=summary, actor_id=int(user_id))
candidate = _create_review_candidate(
case=case,
intake=intake,
@@ -816,8 +816,8 @@ def execute_stp_auto_create_job(*, payload: dict[str, Any], job_id: int) -> dict
"""
Worker 执行 STP 自动建单:confirm_review_case + 确认后推进。
核心逻辑:按 payload.case_no 加载 Case;已 confirmed 则幂等成功;否则用
同一 STP 幂等键调用 confirm;成功后 schedule_auto_progress。
核心逻辑:按 payload.case_no 加载 Case;已 confirmed 或已被新版草稿替代时幂等成功;
否则用同一 STP 幂等键调用 confirm;成功后 schedule_auto_progress。
Args:
payload: Job payload(case_no / draft_version / idempotency_key)。
@@ -850,9 +850,13 @@ def execute_stp_auto_create_job(*, payload: dict[str, Any], job_id: int) -> dict
draft_version = int(payload.get('draft_version') or case.current_draft.draft_version)
if int(case.current_draft.draft_version) != draft_version:
return {
'ok': False,
'error_code': 'SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT',
'message': 'Draft version changed; re-enqueue required',
# A newer Draft has its own idempotency key and enqueue path. This
# stale Job must close successfully so it is not surfaced as a
# business failure or manually retried against outdated content.
'ok': True,
'message': 'STP 自动建单 Job 已被新版草稿替代',
'superseded': True,
'superseded_draft_version': int(case.current_draft.draft_version),
}
run = case.run or (
@@ -968,6 +972,7 @@ def execute_stp_auto_create_job(*, payload: dict[str, Any], job_id: int) -> dict
'ok': False,
'error_code': str(getattr(exc, 'code', None) or 'SHIPPING.STP_AUTO_CREATE_FAILED'),
'message': str(getattr(exc, 'message', None) or exc)[:500],
'details': dict(getattr(exc, 'details', None) or {}),
}
@@ -528,20 +528,23 @@ def project_case_current_gate(
next_action_code = next(iter([a for a in next_action if a]), None)
else:
next_action_code = str(next_action or '').strip() or None
# Schema 字段阻断发生在 STP 物化阶段;Case 已经处于当前复核工作台,
# 用户下一步应修订草稿字段,不应再导航到同一个“打开订单复核”页面。
if reason_code == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED' and 'edit_draft' in available_actions:
next_action_code = 'edit_draft'
br_code: str | None = reason_code or None
gate_code: str | None = None
if auto_status in {'queued', 'running'}:
gate_code = 'stp_auto_progress'
elif auto_status in {'failed', 'manual_fallback'}:
# STP 尚未创建正式 OT 时的失败属于 task_creation。Case 仍为 ready 只说明
# 草稿可建单,不能把后续建单失败回退投影为 customer/order-review 门禁。
gate_code = 'task_creation'
elif case.status in {'unreviewed', 'draft', 'ready'} and not case.confirmed_task_id:
gate_code = 'order_review_build'
elif str(case.status or '') == 'confirmed':
gate_code = 'post_ot_progress'
elif auto_status in {'failed', 'manual_fallback'}:
if reason_code:
gate_code = f'blocked:{reason_code}'
else:
gate_code = 'blocked:generic'
next_action_code = next_action_code or (
available_actions[1] if len(available_actions) > 1 else available_actions[0] if available_actions else None
)
@@ -1065,9 +1068,18 @@ def project_review_case_projection_bundle(
# [STEP 5] user_status
user_status = project_case_user_status(case, automation)
# [STEP 6] primary_action
# 建单前 STP 已失败时,主操作的阶段必须随失败事实停在 pre_ot_stp;
# 不能因 Case 仍为 ready 回退到 customer_resolution/order_review 的展示语义。
user_stage = (
'pre_ot_stp'
if str((automation or {}).get('status') or '').strip().lower() in {
'queued', 'running', 'failed', 'manual_fallback',
}
else 'order_review'
)
primary_action = project_case_primary_action(
user_status, blocking_reason, available_actions,
user_stage='order_review',
user_stage=user_stage,
)
# [STEP 7] 返回 bundle(TypedDict 按字段 key 聚合)
return ReviewCaseProjectionBundle(
@@ -1077,4 +1089,11 @@ def project_review_case_projection_bundle(
blocking_reason=blocking_reason,
primary_action=primary_action,
user_status=user_status,
user_stage=user_stage,
user_current_gate_code=(
'task_creation'
if user_stage == 'pre_ot_stp'
else str((current_gate or {}).get('gate_code') or '') or None
),
retryable=bool((automation or {}).get('retryable')),
)
@@ -271,6 +271,13 @@ def _intake_processing_status(intake: ShippingOrderIntake) -> str:
parsed 且已消费→completed,否则仍 processing。
"""
parse_status = str(intake.parse_status or '').strip().lower()
extraction_status = str(
getattr(intake, 'order_extraction_status', None) or ''
).strip().lower()
if extraction_status in {'failed', 'error', 'fatal'}:
return 'failed'
if extraction_status in {'cancelled', 'canceled'}:
return 'cancelled'
if parse_status == 'parse_failed':
return 'failed'
if parse_status in {'cancelled', 'expired'}:
@@ -483,7 +490,32 @@ def project_intake_work_item(
or getattr(intake, 'created_at', None)
)
legacy_actions = _intake_available_actions(intake)
return reconcile_processing_projection_facts(
intake_status = _intake_processing_status(intake)
intake_stage = _intake_processing_stage(intake)
extraction_status = str(
getattr(intake, 'order_extraction_status', None) or ''
).strip().lower()
if extraction_status in {'partially_completed', 'partial', 'interrupted'}:
intake_status = 'waiting_human'
intake_stage = _clamp_processing_stage(
'waiting_review', source_type=source_type,
)
# EML 已消费仅表示已交给后续订单流程。当前响应尚无同 Intake 的 order_task
# 聚合卡时,仍须以“系统处理中”过渡卡稳定展示,不能误报用户流程已完成。
if (
source_type == 'eml'
and intake.consumed_at is not None
and extraction_status not in {'partially_completed', 'partial', 'interrupted'}
):
intake_status = 'processing'
intake_stage = _clamp_processing_stage(
'candidate_creating', source_type=source_type,
)
if extraction_status in {'failed', 'error', 'fatal'}:
intake_status = 'failed'
elif extraction_status in {'partially_completed', 'partial', 'interrupted'}:
intake_status = 'waiting_human'
payload = reconcile_processing_projection_facts(
{
'work_item_type': 'order_intake',
'work_item_no': str(intake.intake_no),
@@ -494,8 +526,8 @@ def project_intake_work_item(
'conversation_id': str(intake.conversation_id or '').strip() or None,
'submission_no': str(submission.submission_no) if submission is not None else '',
'intake_no': str(intake.intake_no),
'status': _intake_processing_status(intake),
'stage': _intake_processing_stage(intake),
'status': intake_status,
'stage': intake_stage,
'progress_version': progress_version,
'last_activity_at': _iso(last_activity) or '',
'current_gate': _intake_current_gate(intake, asset=asset),
@@ -505,6 +537,19 @@ def project_intake_work_item(
},
legacy_actions=legacy_actions,
)
# 尚未建 OT 的 EML 也必须进入统一聚合状态区,不能走「待处理材料」旁路。
status = str(payload.get('status') or '').strip().lower()
if extraction_status in {'partially_completed', 'partial', 'interrupted'}:
payload['status'] = 'waiting_human'
payload['user_status'] = 'waiting_human'
payload['user_stage'] = 'waiting_review'
status = 'waiting_human'
payload['user_group'] = (
'failed' if status in {'failed', 'blocked'}
else 'waiting_human' if status == 'waiting_human'
else 'processing'
)
return payload
def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None:
@@ -1202,6 +1247,18 @@ def _project_order_task_work_item(
post_confirm=post_confirm_snapshot,
is_admin=False,
)
# 建单前 Case 的 STP 事实优先于旧 OT/Run checkpoint。旧 stage 可能仍是
# document_parsing/customer_resolving,但不可重试 STP 失败实际已经停在 task_creation。
pre_ot_stp = str(bundle.get('user_stage') or '').strip().lower() == 'pre_ot_stp'
if pre_ot_stp:
payload['stage'] = 'order_creating'
payload['stage_label_key'] = 'order_creating'
payload['legacy_stage'] = 'order_creating'
for child in payload.get('aggregate_children') or []:
if isinstance(child, dict):
child['stage'] = 'order_creating'
child['stage_label_key'] = 'order_creating'
child['legacy_stage'] = 'order_creating'
formal_gate_projection = isinstance(payload.get('current_gate'), dict) and bool(
str((payload.get('current_gate') or {}).get('gate_code') or '').strip()
)
@@ -1210,9 +1267,9 @@ def _project_order_task_work_item(
payload['user_status'] = bundle['user_status']
if isinstance(bundle.get('blocking_reason'), dict):
payload['blocking_reason'] = dict(bundle['blocking_reason'])
if isinstance(bundle.get('primary_action'), dict) and not formal_gate_projection:
if isinstance(bundle.get('primary_action'), dict) and (pre_ot_stp or not formal_gate_projection):
payload['primary_action'] = dict(bundle['primary_action'])
if isinstance(bundle.get('current_gate'), dict) and not formal_gate_projection:
if isinstance(bundle.get('current_gate'), dict) and (pre_ot_stp or not formal_gate_projection):
current_gate = dict(payload.get('current_gate') or {})
current_gate.update(bundle['current_gate'])
payload['current_gate'] = current_gate
@@ -1229,6 +1286,19 @@ def _project_order_task_work_item(
retry_flag = bool((bundle.get('automation') or {}).get('retryable'))
if retry_flag or str(payload.get('user_status') or '') == 'retryable':
payload['retryable'] = True
if pre_ot_stp:
payload['user_stage'] = 'pre_ot_stp'
payload['user_current_gate_code'] = 'task_creation'
payload['legacy_status'] = payload.get('status')
payload['status'] = 'failed'
for child in payload.get('aggregate_children') or []:
if isinstance(child, dict):
child['user_stage'] = 'pre_ot_stp'
child['user_current_gate_code'] = 'task_creation'
child['stage'] = 'order_creating'
child['stage_label_key'] = 'order_creating'
child['legacy_stage'] = 'order_creating'
child['current_gate'] = dict(payload.get('current_gate') or {})
except Exception: # noqa: BLE001
# Review bundle 是当前用户动作的权威来源;读取失败时不得静默回退到
# 旧 checkpoint/notice 字段,避免前端展示可继续执行的过时动作。
@@ -1313,6 +1383,17 @@ def _project_order_task_work_item(
elif has_fail and payload.get('retryable') is not False:
payload['retryable'] = True
# pre_ot_stp 是内部责任阶段,不是会话时间线展示枚举;最终输出统一为正式建单节点。
if str(payload.get('user_stage') or '').strip().lower() == 'pre_ot_stp':
payload['stage'] = 'order_creating'
payload['stage_label_key'] = 'order_creating'
payload['legacy_stage'] = 'order_creating'
for child in payload.get('aggregate_children') or []:
if isinstance(child, dict) and str(child.get('user_stage') or '').strip().lower() == 'pre_ot_stp':
child['stage'] = 'order_creating'
child['stage_label_key'] = 'order_creating'
child['legacy_stage'] = 'order_creating'
return payload
@@ -1363,16 +1444,22 @@ def _should_emit_intake_work_item(
intake: ShippingOrderIntake,
*,
linked_intake_ids: set[int],
represented_eml_intake_nos: set[str],
) -> bool:
"""
判断 Intake 是否应以 order_intake 出现在统一投影中。
核心逻辑:仍在解析链路(created/queued/parsing/parse_failed)必出;
已挂 OT 且已解析完成的 Intake 不再单独出卡(由 order_task 代表)。
EML 只有在当前响应已有同 Intake 的聚合 order_task 卡时才隐藏。
consumed_at 仅表示内部消费,不代表用户已看到可替代的任务卡。
"""
parse_status = str(intake.parse_status or '').strip().lower()
if parse_status in _INTAKE_ORDER_INTAKE_PARSE_STATUSES:
return True
source_type = str(intake.source_type or '').strip().lower()
intake_no = str(intake.intake_no or '').strip()
if source_type == 'eml':
return intake_no not in represented_eml_intake_nos
if int(intake.id) in linked_intake_ids:
return False
# 已解析但尚未进入任何 OT:仍作为材料工作项展示。
@@ -1391,6 +1478,15 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str:
Returns:
needs_action | processing | completed 之一。
"""
user_group = str(item.get('user_group') or '').strip().lower()
if user_group in {'failed', 'waiting_human'}:
return 'needs_action'
if user_group == 'completed':
return 'completed'
if user_group in {'cancelled', 'archived'}:
return 'history'
if user_group == 'processing':
return 'processing'
user_status = str(item.get('user_status') or '').strip().lower()
status = str(item.get('status') or '').strip().lower()
stage = str(item.get('stage') or '').strip().lower()
@@ -1439,6 +1535,173 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) ->
return 'processing'
def _eml_aggregate_user_group(
*,
states: list[str],
upload_states: list[str],
children: list[dict[str, Any]],
) -> str:
"""按用户关注优先级确定一张 EML Intake 卡的唯一分组。"""
if any(state in {'failed', 'retryable'} for state in states):
return 'failed'
if any(state == 'waiting_human' for state in states):
return 'waiting_human'
if any(state not in {'completed', 'cancelled'} for state in states):
return 'processing'
if any(state == 'cancelled' for state in states):
return 'cancelled'
if states and all(state == 'completed' for state in states) and all(
state == 'succeeded' for state in upload_states
):
return 'completed'
if children and all(bool(item.get('is_archived')) for item in children):
return 'archived'
# 已完成但尚未上传、或取消与其它终态混合,均不能被误认为完成。
return 'processing'
def _aggregate_eml_order_task_work_items(
work_items: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""
按 Intake 聚合同一 EML 的多个 order_task 工作项。
核心逻辑:同一 EML 只返回一张用户卡,但保留子任务真实状态;候选生成只是处理中,
只有所有子任务均 user_status=completed 且 upload_state=succeeded 才聚合为完成。
Args:
work_items: 已完成用户态投影的工作项列表。
Returns:
EML order_task 聚合后的工作项列表;非 EML 与 order_intake 原样保留。
"""
grouped: dict[str, list[dict[str, Any]]] = {}
passthrough: list[dict[str, Any]] = []
for item in work_items:
if (
str(item.get('work_item_type') or '').strip() != 'order_task'
or str(item.get('source_type') or '').strip().lower() != 'eml'
or not str(item.get('intake_no') or '').strip()
):
passthrough.append(item)
continue
grouped.setdefault(str(item['intake_no']).strip(), []).append(item)
def _state(item: dict[str, Any]) -> str:
return str(item.get('user_status') or item.get('status') or '').strip().lower()
def _upload_state(item: dict[str, Any]) -> str:
facts = item.get('facts') if isinstance(item.get('facts'), dict) else {}
return str(facts.get('upload_state') or '').strip().lower()
result = list(passthrough)
for intake_no, children in grouped.items():
states = [_state(item) for item in children]
upload_states = [_upload_state(item) for item in children]
failed_count = sum(state in {'failed', 'retryable'} for state in states)
waiting_count = sum(state == 'waiting_human' for state in states)
# 用户视角的完成必须同时满足任务完成和货代上传成功;候选已生成等中间态仍在处理中。
completed_count = sum(
state == 'completed' and upload_state == 'succeeded'
for state, upload_state in zip(states, upload_states)
)
processing_count = len(children) - failed_count - waiting_count - completed_count
all_uploaded = bool(upload_states) and all(state == 'succeeded' for state in upload_states)
aggregate_group = _eml_aggregate_user_group(
states=states,
upload_states=upload_states,
children=children,
)
aggregate_status = (
'failed' if aggregate_group == 'failed' else
'waiting_human' if aggregate_group == 'waiting_human' else
'cancelled' if aggregate_group == 'cancelled' else
'completed' if aggregate_group == 'completed' else
'running'
)
aggregate_stage = next(
(
'order_creating'
if str(item.get('user_stage') or '').strip().lower() == 'pre_ot_stp'
else str(item.get('user_stage') or item.get('stage') or '').strip()
for item in children
if _state(item) != 'completed' or _upload_state(item) != 'succeeded'
),
'completed',
)
aggregate_upload_state = (
'failed' if any(state == 'failed' for state in upload_states) else
'succeeded' if all_uploaded else
'uploading' if any(state in {'uploading', 'callback_received'} for state in upload_states) else
'manual_upload_pending' if any(state == 'manual_upload_pending' for state in upload_states) else
'not_created'
)
representative = max(
children,
key=lambda item: str(item.get('last_activity_at') or ''),
)
source_summary = dict(representative.get('source_summary') or {})
source_summary['document_count'] = sum(
int((item.get('source_summary') or {}).get('document_count') or 0)
for item in children
)
aggregate = dict(representative)
aggregate['work_item_no'] = f'INTAKE:{intake_no}'
aggregate['root_order_task_no'] = representative.get('root_order_task_no') or representative.get('work_item_no')
aggregate['status'] = aggregate_status
aggregate['stage'] = aggregate_stage
aggregate['user_status'] = aggregate_status
aggregate['user_stage'] = aggregate_stage
aggregate['user_group'] = aggregate_group
aggregate['source_summary'] = source_summary
aggregate['facts'] = dict(representative.get('facts') or {})
aggregate['facts']['upload_state'] = aggregate_upload_state
blocking_child = next(
(
item for item in children
if _state(item) in {'failed', 'retryable', 'waiting_human'}
and isinstance(item.get('blocking_reason'), dict)
),
None,
)
if blocking_child is not None:
aggregate['blocking_reason'] = dict(blocking_child['blocking_reason'])
aggregate['primary_action'] = blocking_child.get('primary_action')
aggregate['aggregate_children'] = children
summary_stages = {
(
'order_creating'
if str(item.get('user_stage') or '').strip().lower() == 'pre_ot_stp'
else str(item.get('user_stage') or item.get('stage') or '').strip()
)
for item in children
if str(item.get('user_stage') or item.get('stage') or '').strip()
}
aggregate['aggregate_summary'] = {
'intake_no': intake_no,
'total': len(children),
'completed': completed_count,
'processing': processing_count,
'needs_action': waiting_count,
'failed': failed_count,
'stages': sorted(summary_stages),
'reason_codes': sorted({
str(code).strip()
for item in children
for code in (
(item.get('blocking_reason') or {}).get('code')
if isinstance(item.get('blocking_reason'), dict) else None,
(item.get('source_summary') or {}).get('failure_reason_code')
if isinstance(item.get('source_summary'), dict) else None,
)
if str(code or '').strip()
}),
'upload_states': sorted(set(upload_states)),
}
result.append(aggregate)
return result
def _conversation_task_row_from_work_item(
item: dict[str, Any],
*,
@@ -1463,7 +1726,8 @@ def _conversation_task_row_from_work_item(
title = filename if document_count == 1 and filename else None
display_kind = 'single_document_task' if document_count == 1 else 'multi_document_task'
group = _conversation_processing_group_for_work_item(item)
run_no = None
# 聚合 Intake 卡仍必须透传真实 Run/Case/文档上下文;前端不能用 INTAKE 编号反查写操作目标。
run_no = str(item.get('run_no') or '').strip() or None
workflow_no = None
resolved_primary: str | None = None
order_task = (
@@ -1490,7 +1754,7 @@ def _conversation_task_row_from_work_item(
if run_candidate is not None:
run = run_candidate
if run is not None:
run_no = str(run.run_no or '').strip() or None
run_no = run_no or str(run.run_no or '').strip() or None
from app.services.shipping_notice.conversation_processing_projection import (
_resolve_workflow_no,
)
@@ -1509,6 +1773,43 @@ def _conversation_task_row_from_work_item(
primary_action = available_actions[0]
else:
primary_action = 'focus_task'
source_document_id = int(source_summary.get('document_id') or 0) or None
item_case_no = str(item.get('case_no') or '').strip() or None
item_task_no = str(item.get('root_order_task_no') or '').strip() or None
objects = []
for child in item.get('aggregate_children') or []:
if not isinstance(child, dict):
continue
child_summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {}
child_document_id = int(child_summary.get('document_id') or 0) or None
if not child_document_id and not child.get('case_no') and not child.get('run_no'):
continue
objects.append({
'kind': 'document',
'object_key': f"DOC-{child_document_id}" if child_document_id else str(child.get('work_item_no') or user_task_no),
'label': str(child_summary.get('filename') or '').strip() or user_task_no,
'status_label': child.get('status'),
'run_no': child.get('run_no'),
'current_run_no': child.get('run_no'),
'case_no': child.get('case_no'),
'task_no': child.get('root_order_task_no'),
'document_id': child_document_id,
'filename': child_summary.get('filename'),
'workflow_item_no': child.get('work_item_no'),
})
if not objects and (source_document_id or item_case_no or run_no):
objects.append({
'kind': 'document',
'object_key': f'DOC-{source_document_id}' if source_document_id else user_task_no,
'label': filename or user_task_no,
'status_label': item.get('status'),
'run_no': run_no,
'current_run_no': run_no,
'case_no': item_case_no,
'task_no': item_task_no,
'document_id': source_document_id,
'filename': filename,
})
return {
'user_task_no': user_task_no,
'submission_ordinal': None,
@@ -1533,7 +1834,15 @@ def _conversation_task_row_from_work_item(
'recently_created': False,
'primary_action': primary_action,
'available_actions': available_actions or ['view_details'],
'objects': [],
'objects': objects,
# EML Intake 聚合卡必须透传统一用户态与子附件汇总;前端禁止再从旧 status 猜测。
'user_status': item.get('user_status'),
'user_stage': item.get('user_stage'),
'blocking_reason': item.get('blocking_reason'),
'primary_action': item.get('primary_action'),
'facts': item.get('facts'),
'aggregate_summary': item.get('aggregate_summary'),
'user_group': item.get('user_group'),
}
@@ -1567,7 +1876,7 @@ def _conversation_processing_from_work_items(
for item in work_items:
if not isinstance(item, dict):
continue
if str(item.get('work_item_type') or '') != 'order_task':
if str(item.get('work_item_type') or '') not in {'order_task', 'order_intake'}:
continue
row = _conversation_task_row_from_work_item(item, focused_task_no=focused)
if recent and row['user_task_no'] == recent:
@@ -1884,6 +2193,17 @@ def project_conversation_processing_items(
user_id=int(user_id),
conversation_id=normalized,
)
# 仅已有可见 EML 聚合卡才能替代 Intake。消费标记先于 OT 投影落库时,
# 不能让该邮件在下一次轮询中消失。
represented_eml_intake_nos = {
str(item.get('intake_no') or '').strip()
for item in work_items
if (
item.get('work_item_type') == 'order_task'
and str(item.get('source_type') or '').strip().lower() == 'eml'
and str(item.get('intake_no') or '').strip()
)
}
intakes = (
ShippingOrderIntake.query.filter(
ShippingOrderIntake.user_id == int(user_id),
@@ -1899,7 +2219,11 @@ def project_conversation_processing_items(
submission_cache: dict[int, ShippingOrderSubmission | None] = {}
asset_cache: dict[int, FileAsset | None] = {}
for intake in intakes:
if not _should_emit_intake_work_item(intake, linked_intake_ids=linked_intake_ids):
if not _should_emit_intake_work_item(
intake,
linked_intake_ids=linked_intake_ids,
represented_eml_intake_nos=represented_eml_intake_nos,
):
continue
submission = None
if intake.order_submission_id:
@@ -1917,6 +2241,10 @@ def project_conversation_processing_items(
project_intake_work_item(intake, submission=submission, asset=asset)
)
# 同一 EML Intake 只作为一个用户工作项返回。聚合必须发生在 work_items 返回前,
# 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。
work_items = _aggregate_eml_order_task_work_items(work_items)
recent_override = str(recent_task_no or '').strip() or None
rebuilt = _conversation_processing_from_work_items(
work_items,
@@ -52,12 +52,6 @@ _STP_ACTIVE_STATUSES = ('queued', 'running')
_STP_FAILED_STATUS = 'failed'
_STP_PREFIX_SEGMENT_SEP = ':'
_STP_PREFIX_HEAD = 'stp-auto'
_NON_RETRYABLE_BLOCKING_REASONS = (
'duplicate_decision_required',
'SHIPPING.NOTICE_EXACT_DUPLICATE',
)
def _recover_auto_progress_jobs() -> int:
"""
补偿无活动 Job 的 P0-3 Task Execution。
@@ -135,8 +129,9 @@ def _fetch_sweeper_case_candidates(*, max_age_hours: int = 72) -> list[int]:
4. Draft.validation_result_json.status = 'ready'(草稿校验已通过)
5. Draft.validation_result_json.can_auto_create = true(具备自动建单资格)
6. 不存在同 (run_no, document_id) 的 queued/running STP Job(避免重复入队)
7. 不存在同 (run_no, document_id) 的 retryable=false 业务阻断失败 Job
(duplicate/SHIPPING.NOTICE_EXACT_DUPLICATE)→ 尊重人工对账边界。
7. 不存在同 (run_no, document_id) 的 retryable=false 业务阻断失败 Job。
recovery contract 已裁决为不可重试的失败必须等待人工处理或显式恢复,
Sweeper 不得通过刷新 Draft 版本绕过该裁决并创建新 Job。
单批上限 LIMIT 50,按 updated_at + id 倒序优先处理最近更新。
@@ -171,15 +166,15 @@ def _fetch_sweeper_case_candidates(*, max_age_hours: int = 72) -> list[int]:
j.c.business_ref.like(stp_prefix_like),
))
# j2:retryable=false 的业务阻断失败 → 要求不存在
blocking_code_expr = _json_text_expr(j2.c.result_json, 'blocking_reason')
# j2:任何 retryable=false 的业务阻断失败 → 要求不存在。
# 不能只匹配个别错误码:STP 幂等键包含 draft_version,漏掉一个不可重试原因
# 就会让每轮 Sweeper 重新校验并递增版本,实际变成每分钟创建一个新 Job。
retryable_expr = _json_text_expr(j2.c.result_json, 'retryable')
blocking_stp_exists = exists().where(and_(
j2.c.domain == _STP_JOB_DOMAIN,
j2.c.job_type.in_(_STP_JOB_TYPES),
j2.c.status == _STP_FAILED_STATUS,
retryable_expr == 'false',
blocking_code_expr.in_(_NON_RETRYABLE_BLOCKING_REASONS),
j2.c.business_ref.like(stp_prefix_like),
))
@@ -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