feat(shipping): 实现订单批处理聊天聚合展示与优化后端逻辑
This commit is contained in:
1 parent
11cef575b4
commit
523b791c92
38 files changed
+2868
-414
No files matched your search
@@ -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
|
||||
@@ -1,114 +1,459 @@
|
||||
# 通用文档检核前端页面/模块 PRD
|
||||
|
||||
## 1. 产品结构
|
||||
> 版本:v1.0 · 状态:开发设计基线 · 更新时间:2026-08-13
|
||||
>
|
||||
> 本文面向产品、前端、后端、测试和 Dify 编排人员。它定义页面职责、字段、交互、权限、API 映射、状态和验收边界;不规定后端内部实现。
|
||||
|
||||
## 1. 产品定位与边界
|
||||
|
||||
HXOPS 注册三个独立 Agent:RoHS、SDS/MSDS、材质证明。用户看到三个名称和编号不同的入口;三个入口共用通用文档检核前端和后端能力,当前 Agent 上下文决定 `application_code`,用户不在运行时选择 Schema 或规则。
|
||||
|
||||
```text
|
||||
RoHS Agent / SDS-MSDS Agent / 材质证明 Agent
|
||||
↓(同一页面组件,Agent 配置注入检核类型)
|
||||
通用文档检核工作区
|
||||
↓
|
||||
通用文档检核工作区组件
|
||||
↓
|
||||
Flask Tool + Job/Worker + PostgreSQL/MinIO
|
||||
```
|
||||
|
||||
普通用户只通过 Dify 对话上传文件、查询结果和触发有权限排程;管理端负责配置、试运行、复核、学习和审计。
|
||||
用户侧只做:上传文件、查看进度、查看结果、下载 Excel、查询历史、补充 SRM 查询信息、确认候选 SRM 记录。管理员侧做:配置、试运行、Run 查询、复核、审计和学习任务审核。
|
||||
|
||||
## 2. 页面清单
|
||||
不在本 PRD 范围内:供应商版式模板维护、字段级人工改值、普通用户 SQL/规则/模型配置、前端直接写 SRM、PDF 正式报告。
|
||||
|
||||
| 页面 | 角色 | 目的 |
|
||||
## 2. 角色、权限与数据范围
|
||||
|
||||
| 角色 | 可做操作 | 数据范围 |
|
||||
|---|---|---|
|
||||
| 文档检核工作区 | 普通用户 | 对话、上传、进度、结果、Excel |
|
||||
| Run 列表 | 业务负责人/管理员 | 查询、筛选、重检、下载 |
|
||||
| Run 详情 | 负责人/管理员 | 查看项目、证据、规则、SRM、写回 |
|
||||
| 项目/Run 复核 | 负责人/管理员 | 项目级和 Run 级结论 |
|
||||
| Schema 配置 | 管理员 | 表单维护字段与提取约束 |
|
||||
| 规则配置 | 管理员 | 表单维护规则并启停 |
|
||||
| 材质术语库 | 管理员 | 标准概念、别名、正则、角色 |
|
||||
| 模型路由 | 管理员 | 选择已注册本地模型 |
|
||||
| 规则试运行 | 管理员 | 用测试文件验证配置,不写 SRM |
|
||||
| 学习任务 | 管理员 | 审核低置信/冲突/新术语样本 |
|
||||
| 审计中心 | 管理员/审计员 | 查询、详情、脱敏导出 |
|
||||
| 普通用户 | 通过 Dify 发起单文件检核;查询自己有权限的 Run;下载 Excel;补充 SRM 条件并确认候选 | Agent/RBAC 授权范围 |
|
||||
| 应用责任人 | 普通用户能力;复核对应应用项目和 Run | 负责的应用 |
|
||||
| 排程责任人 | 查看、复核对应排程产生的项目和 Run;触发授权排程 | 负责的排程 |
|
||||
| 管理员 | 配置 Schema、规则、术语;试运行;查看和复核全部 Run;审计、学习任务 | 全量 |
|
||||
| 审计员 | 查看和脱敏导出审计;敏感快照需额外权限 | 授权审计范围 |
|
||||
|
||||
## 3. 工作区线框
|
||||
后端权限是最终门禁;前端按钮隐藏只改善体验,不能替代接口授权。所有写操作和敏感读取写入审计。
|
||||
|
||||
## 3. 路由与信息架构
|
||||
|
||||
### 3.1 用户侧路由
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 当前 Agent:RoHS 文件检核 能力:单文件|资料包|排程 │
|
||||
├──────────────────────────────┬──────────────────────────────┤
|
||||
│ 对话区 │ 本轮检核 │
|
||||
│ 用户消息/助手回复 │ Run 号、状态、进度 │
|
||||
│ [上传文件] [发送] │ 通过/不合格/复核/技术失败 │
|
||||
│ │ [查看详情] [下载 Excel] │
|
||||
└──────────────────────────────┴──────────────────────────────┘
|
||||
/chat/:agentId 既有 Dify 对话页,挂载检核能力
|
||||
/workspace/document-check/runs 授权 Run 列表(可选工作台入口)
|
||||
/workspace/document-check/runs/:id Run 详情(只读/按权限显示复核)
|
||||
```
|
||||
|
||||
交互:进入 Agent 即固定类型;上传前选择“独立文件/资料包”;资料包允许增删,Run 启动后冻结;运行中可查询,不重复创建相同参数 Run。Dify 消息中的下载链接必须是 HXOPS 鉴权短链。
|
||||
普通用户的主要入口仍是 `/chat/:agentId`;工作台 Run 页面用于从进度卡、历史消息或通知跳转,不新增第二个业务入口。
|
||||
|
||||
## 4. Run 详情/复核线框
|
||||
### 3.2 管理侧路由
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ RUN-20260812-001 RoHS 状态:needs_review [下载 Excel] │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ 统计:总30 通过22 失败3 复核5 技术失败0 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ 项目列表:记录号 | 文件 | 文件结论 | SRM结论 | 原因 | 查看证据 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ 复核结论 [通过] [不合格] [退回重检] │
|
||||
│ 理由* ____________________________________ [提交] │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
/admin/document-check/runs
|
||||
/admin/document-check/runs/:id
|
||||
/admin/document-check/runs/:id/review
|
||||
/admin/document-check/schemas
|
||||
/admin/document-check/rules
|
||||
/admin/document-check/terminology
|
||||
/admin/document-check/rule-trials
|
||||
/admin/document-check/learning-tasks
|
||||
/admin/document-check/audits
|
||||
```
|
||||
|
||||
仅应用责任人、排程责任人和管理员可提交复核;不允许字段级改值,不删除 AI 原始结果。
|
||||
路由在 `features/admin` 的文档检核子模块注册,配置页面按 Agent/检核类型筛选;不新增独立 Admin Layout。
|
||||
|
||||
## 5. 管理配置线框
|
||||
## 4. 统一交互与视觉规则
|
||||
|
||||
### 4.1 信息层级
|
||||
|
||||
1. 顶部显示当前 Agent 名称、检核类型和权限范围。
|
||||
2. 状态使用统一徽标:运行中蓝色、通过绿色、不合格红色、待复核橙色、技术失败深红/灰色。
|
||||
3. 业务结论和技术状态分列,不把 `technical_failed` 显示成业务不合格。
|
||||
4. 所有危险操作使用明确动词:`重新检核`、`提交复核`、`启用写回`,不使用“确定”作为唯一按钮文案。
|
||||
5. 重要结果旁必须提供证据入口或“无证据原因”。
|
||||
|
||||
### 4.2 响应式
|
||||
|
||||
- 桌面:列表/详情采用双栏或三栏布局;证据抽屉最大宽度 560px。
|
||||
- 移动端:详情改为纵向卡片;表格转为字段卡;不在移动端提供 SQL 编辑、规则试运行和审计大批量导出。
|
||||
- 键盘:所有按钮、Tab、抽屉和表格行可聚焦;弹窗关闭后焦点回到触发控件。
|
||||
- 动效:只用于进度和抽屉过渡;尊重 `prefers-reduced-motion`。
|
||||
|
||||
## 5. 用户工作区 PRD
|
||||
|
||||
### 5.1 页面职责
|
||||
|
||||
`DocumentCheckWorkspaceView` 不替换现有 ChatView,而是由检核 Agent 的运行时能力在聊天页展示:上传文件由既有 Chat composer 处理,检核进度和结果由本域组件渲染。
|
||||
|
||||
### 5.2 页面线框
|
||||
|
||||
```text
|
||||
┌──────────────┬────────────────────────────────────────────────┐
|
||||
│ Schema │ 应用/Agent:RoHS │
|
||||
│ 规则 │ 字段:报告编号、型号、日期、有效期、材质... │
|
||||
│ 材质术语 │ 提取方式:文本/表格/VLM │
|
||||
│ 模型路由 │ SRM SQL:已绑定排程 SQL │
|
||||
│ 试运行 │ [保存立即生效] [测试] [停用] │
|
||||
└──────────────┴────────────────────────────────────────────────┘
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ RoHS 文件检核 Agent [新建对话] │
|
||||
├───────────────────────────────┬────────────────────────────────┤
|
||||
│ 对话区 │ 本轮检核 │
|
||||
│ 用户:检核这个文件 │ Run:RUN-20260813-0001 │
|
||||
│ [report.pdf] │ 状态:执行中 · 解析文档 │
|
||||
│ 助手:已受理,请查看右侧进度 │ ━━━━━━━━━━━░░ 62% │
|
||||
│ │ 总数 1 通过 0 失败 0 复核 0 │
|
||||
│ │ [查看详情] [下载 Excel(禁用)] │
|
||||
├───────────────────────────────┴────────────────────────────────┤
|
||||
│ 输入消息…… [附件] [发送] │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
规则全部表单化:类型、字段、运算符、阈值、单位、失败原因、是否强制、是否允许自动写回。复杂 JSON/DSL 不作为普通配置入口。
|
||||
|
||||
## 6. 审计中心线框
|
||||
### 5.3 组件拆分
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 时间 [ ] 操作人 [ ] 对象 [ ] 动作 [查询] [导出脱敏 CSV] │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ 时间 | 操作人 | 动作 | 对象 | 结果 | before/after hash | 详情 │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
DocumentCheckRuntimeCard
|
||||
├─ DocumentCheckRunSummary
|
||||
├─ DocumentCheckProgressBar
|
||||
├─ DocumentCheckStats
|
||||
├─ DocumentCheckRunActions
|
||||
└─ DocumentCheckErrorNotice
|
||||
```
|
||||
|
||||
敏感快照需单独授权,读取本身再次审计;导出不包含凭据和未经脱敏原文。
|
||||
组件只接收 props/emits,不直接调用 API;轮询、状态合并和下载由 `useDocumentCheckRuntime` 负责。
|
||||
|
||||
## 7. 状态与提示
|
||||
### 5.4 上传与资料包交互
|
||||
|
||||
`passed`、`failed`、`needs_review`、`technical_failed`、`running`、`cancelled`。业务失败与技术失败分开展示;SRM 写回超时显示“结果未知,已反查/待复核”,禁止提示为成功。
|
||||
| 步骤 | 控件 | 规则 |
|
||||
|---|---|---|
|
||||
| 1 | 附件选择 | 仅 PDF/DOC/DOCX/XLS/XLSX/PNG/JPG/ZIP;单文件 ≤100MB |
|
||||
| 2 | 组织方式 | `独立文件` 或 `资料包`;默认不自动猜测 |
|
||||
| 3 | 资料包清单 | 显示文件名、大小、类型、移除按钮;总解压量 ≤300MB |
|
||||
| 4 | 启动确认 | 展示 Agent 类型、文件数、文件 hash、是否请求 SRM |
|
||||
| 5 | 启动 | 禁止重复提交;返回 `run_id` 后绑定当前消息 |
|
||||
|
||||
## 8. 前端模块与文件规划
|
||||
资料包不指定主文件,所有文件同等作为证据;字段冲突进入 `needs_review`。
|
||||
|
||||
### 5.5 运行状态
|
||||
|
||||
```text
|
||||
queued → validating → parsing → extracting → rule_checking
|
||||
→ srm_checking → writing_back → report_generating
|
||||
→ knowledge_sync → completed
|
||||
```
|
||||
|
||||
终态映射:`passed`、`failed`、`needs_review`、`technical_failed`、`cancelled`。轮询在终态停止;刷新页面后凭 `run_id` 恢复。
|
||||
|
||||
### 5.6 用户错误与空态
|
||||
|
||||
| 情况 | 页面行为 |
|
||||
|---|---|
|
||||
| 文件类型不匹配 | 显示当前 Agent 支持类型,阻止启动 |
|
||||
| 超过 100MB/300MB | 显示具体文件和限制,阻止启动 |
|
||||
| 无权限排程 | 不展示触发按钮;接口 403 时显示权限提示 |
|
||||
| SRM 信息不足 | Dify 继续追问,不创建 Run |
|
||||
| 多条 SRM 候选 | 显示候选卡,要求用户点击确认 |
|
||||
| SRM 写回未知 | 显示“已反查/待复核”,不显示成功 |
|
||||
| Excel 未生成 | 下载按钮禁用并显示当前阶段 |
|
||||
| 知识库同步失败 | 不改变 Run 结论,显示重试状态 |
|
||||
|
||||
### 5.7 用户工作区 API 映射
|
||||
|
||||
| 前端行为 | API |
|
||||
|---|---|
|
||||
| 创建 Run | `POST /api/document-check/tools/runs` |
|
||||
| 查询状态 | `GET /api/document-check/tools/runs/{id}` |
|
||||
| 查询项目 | `GET /api/document-check/tools/runs/{id}/items` |
|
||||
| 下载 Excel | `GET /api/document-check/tools/runs/{id}/excel` |
|
||||
| SRM 候选 | `POST /api/document-check/tools/srm/candidates` |
|
||||
| 确认候选 | `POST /api/document-check/tools/srm/confirm` |
|
||||
|
||||
## 6. Run 列表页 PRD
|
||||
|
||||
### 6.1 线框
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ 文档检核 Run [导出列表] │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ Agent[全部] 类型[全部] 状态[全部] 时间[起止] 关键词[查询] │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ Run号 | 应用 | 模式 | 触发 | 总数 | 结论 | 写回 | 开始时间 | 操作 │
|
||||
│ ... | RoHS | SRM | 排程 | 30 | 复核 | 未启用 | ... | 查看 │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ 共 30 条 [< 1 2 3 >] │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 6.2 筛选字段
|
||||
|
||||
`agent_id`、`application_code`、`mode`、`status`、`writeback_status`、`trigger_type`、`created_by`、时间范围、Run 编号、SRM 报告编号、供应商、型号/样品名称。
|
||||
|
||||
### 6.3 行操作与权限
|
||||
|
||||
- `查看`:有结果读取权限。
|
||||
- `下载 Excel`:Run 终态且有下载权限。
|
||||
- `重新检核`:负责人/管理员;默认最新配置+最新 SRM 数据;需二次确认。
|
||||
- `复核`:应用责任人、排程责任人、管理员。
|
||||
- `重试`:技术失败或知识库同步失败且后端判定允许。
|
||||
|
||||
### 6.4 API 与验收
|
||||
|
||||
API:`GET /api/admin/document-check/runs`、`POST /api/document-check/tools/runs/{id}/retry`。
|
||||
|
||||
验收:筛选条件可组合;分页稳定;越权 Run 不出现在列表;重复点击重检不会产生两个相同幂等 Run;所有操作写审计。
|
||||
|
||||
## 7. Run 详情页 PRD
|
||||
|
||||
### 7.1 线框
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ ← Run 列表 RUN-... [状态徽标] [下载 Excel] [重新检核] │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ 摘要:应用|模式|触发人|开始/结束|配置快照|SRM 快照 │
|
||||
├───────────────┬─────────────────────────────────────────────────┤
|
||||
│ 项目导航 │ 项目详情 │
|
||||
│ 001 通过 │ 文件:report.pdf 文件结论:通过 │
|
||||
│ 002 待复核 │ SRM:匹配 / 写回:未启用 │
|
||||
│ 003 不合格 │ [文件证据] [规则结果] [SRM核验] [审计] │
|
||||
├───────────────┴─────────────────────────────────────────────────┤
|
||||
│ 项目操作:[通过] [不合格] [退回重检](有权限时显示) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 7.2 Tab 内容
|
||||
|
||||
| Tab | 内容 | 只读/可写 |
|
||||
|---|---|---|
|
||||
| 文件证据 | 文件、页码、bbox、OCR/VLM 来源、置信度、证据预览 | 只读 |
|
||||
| 规则结果 | 规则名、输入值、期望、实际、原因码、结果 | 只读 |
|
||||
| SRM 核验 | 文件值/SRM 值/比较方式/快照/状态 | 只读 |
|
||||
| 写回 | 模式、拟写文本、前后状态、影响行数、反查 | 只读;写回由受控后台流程触发 |
|
||||
| 审计 | 当前对象操作时间线和快照 hash | 只读 |
|
||||
|
||||
字段事实不能在此页面编辑;复核通过/不合格/退回重检是独立结论。
|
||||
|
||||
### 7.3 证据抽屉
|
||||
|
||||
```text
|
||||
┌──────────────────────────────┐
|
||||
│ 证据:报告编号 │
|
||||
│ 值:R-2026-001 │
|
||||
│ 来源:VLM + OCR │
|
||||
│ 文件:report.pdf · 第 2 页 │
|
||||
│ 区域:[x,y,w,h] │
|
||||
│ 置信度:0.96 │
|
||||
│ [打开原文件] [查看原始 JSON] │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
敏感原文和原始 JSON 需要额外权限,打开动作写 `audit_access`。
|
||||
|
||||
## 8. 复核页 PRD
|
||||
|
||||
### 8.1 线框
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ 项目复核:SRM-123 / report.pdf 当前:needs_review │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ 复核摘要:缺少文件报告编号;SRM 记录存在 │
|
||||
│ [查看文件证据] [查看 SRM 快照] [查看命中规则] │
|
||||
├──────────────────────────────────────────────────────────────┤
|
||||
│ 结论* ( ) 确认通过 ( ) 确认不合格 ( ) 退回重新检核 │
|
||||
│ 理由* [_______________________________________________] │
|
||||
│ 附加说明 [_____________________________________________] │
|
||||
│ [取消] [提交复核] │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
提交规则:结论必选、理由必填;提交前显示当前状态和“原始 AI 结论不会删除”;若状态版本变化返回冲突并要求刷新。
|
||||
|
||||
Run 级复核仅在项目状态已明确或全部项目已处理时显示;提交 Run 结论不自动覆盖项目事实。
|
||||
|
||||
## 9. Schema 配置页 PRD
|
||||
|
||||
### 9.1 线框
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ Schema 配置 Agent[RoHS] 状态:启用 [保存配置] │
|
||||
├──────────────┬─────────────────────────────────────────────────┤
|
||||
│ 字段目录 │ 字段编辑 │
|
||||
│ 报告编号 │ 显示名* 报告编号 字段键* report_number │
|
||||
│ 型号/样品名 │ 类型 [文本] 必填 [是] 多值 [否] │
|
||||
│ 报告日期 │ 提取来源 [文本/表格/VLM] 允许别名 [编辑] │
|
||||
│ 有效期 │ 证据要求 [页码+区域] 排序 10 │
|
||||
│ 材质 │ [保存字段] [删除字段] │
|
||||
│ [+ 新增字段] │ │
|
||||
└──────────────┴─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 9.2 字段表单
|
||||
|
||||
字段键、显示名、数据类型(文本/数字/日期/枚举/列表)、必填、允许多值、单位、提取优先级、证据要求、SRM 映射、冲突策略、启用状态。字段删除仅允许停用;已被 Run 快照引用的字段不能物理删除。
|
||||
|
||||
### 9.3 验收
|
||||
|
||||
- 表单保存立即影响新 Run;
|
||||
- 缺字段键、重复键、非法单位不能保存;
|
||||
- 试运行可展示提取值和证据;
|
||||
- 历史 Run 显示原 Schema 快照。
|
||||
|
||||
## 10. 规则配置页 PRD
|
||||
|
||||
### 10.1 线框
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ 规则配置 Agent[RoHS] [新增规则] [保存] │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ 规则名 | 作用域 | 类型 | 强制 | 自动写回 | 状态 | 操作 │
|
||||
│ 编号匹配 | SRM | 比较 | 是 | 是 | 启用 | 编辑 │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ 规则编辑:字段 [报告编号] 比较 [精确等于] 目标 [SRM报告编号] │
|
||||
│ 失败原因码 [report_number_mismatch] 失败文案 [文本] │
|
||||
│ [启用] [保存] │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 10.2 支持规则表单
|
||||
|
||||
必填、格式正则、枚举、日期/有效期、数值阈值/单位换算、字段一致性、文件-SRM 比较、材质匹配、文件类型。每条规则包含作用域、输入字段、运算符、目标、强制标记、失败原因码、解释文本、是否允许写回、启用状态。
|
||||
|
||||
### 10.3 试运行入口
|
||||
|
||||
规则列表提供“试运行”按钮,进入 Rule Trial 页面并带入 `app_id`;保存试运行不生成正式 Run、不写回 SRM、不改变生产统计。
|
||||
|
||||
## 11. 材质术语库页 PRD
|
||||
|
||||
### 11.1 线框
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ 材质术语库 Agent[材质证明] [新增标准材质] │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ 标准概念 | 角色 | 别名数 | 正则数 | 来源 | 状态 | 操作 │
|
||||
│ ABS | 基材 | 4 | 1 | SRM | 启用 | 查看 │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ 原始说法 [____] 标准概念 [____] 角色 [基材/涂层/...] │
|
||||
│ 别名 [添加] 正则 [添加] 适用字段 [多选] [保存] │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
禁止把产品、组件、基材、包装、油墨、涂层、胶黏剂默认当作同义词;角色必须明确。模糊候选只能进入学习任务。
|
||||
|
||||
## 12. 规则试运行页 PRD
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ 规则试运行 Agent[RoHS] │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ 文件 [选择历史文件/上传测试文件] Schema [当前] 规则集 [当前] │
|
||||
│ SRM 模式 [不查询/读取测试快照] [开始试运行] │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ 结果:字段提取 | 规则命中 | 证据 | 预期/实际 | 建议 │
|
||||
│ 通过 8 失败 1 复核 2 技术失败 0 │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
试运行结果有独立 `trial_id`,不出现在正式 Run 列表,不写 SRM,不同步知识库;可导出脱敏结果给管理员评审。
|
||||
|
||||
## 13. 学习任务页 PRD
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ 学习任务 状态[待审核] 来源[低置信/复核/新术语] │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ 来源 Run | 字段/术语 | 候选值 | 证据 | 审核状态 | 操作 │
|
||||
│ RUN-001 | material | ABS... | p2 | 待审核 | 查看 │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ [接受为样本] [拒绝] [创建术语草稿] [加入评估集] │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
接受不会直接改生产规则或模型;只生成可追踪样本,记录审核人、时间和理由。
|
||||
|
||||
## 14. 审计页 PRD
|
||||
|
||||
### 15.1 字段与筛选
|
||||
|
||||
时间、操作人、角色、来源(Dify/后台/排程/系统)、动作、对象类型、对象 ID、结果、Run ID、请求 ID、原因码。支持分页、详情抽屉、脱敏 CSV/JSON 导出。
|
||||
|
||||
### 15.2 详情抽屉
|
||||
|
||||
展示事件元数据、changed paths、before/after hash、快照对象引用、关联 Run/Item/Evidence。敏感快照需二次授权,授权理由必填,读取再写审计。
|
||||
|
||||
## 15. 前端实现文件清单
|
||||
|
||||
```text
|
||||
frontend/src/features/document-check/
|
||||
api/document-check.api.ts
|
||||
types/document-check.types.ts
|
||||
composables/useDocumentCheckWorkspace.ts
|
||||
stores/document-check.store.ts
|
||||
composables/useDocumentCheckRuntime.ts
|
||||
composables/useDocumentCheckRuns.ts
|
||||
composables/useDocumentCheckReview.ts
|
||||
components/DocumentCheckProgressCard.vue
|
||||
components/DocumentCheckEvidenceDrawer.vue
|
||||
views/DocumentCheckWorkspaceView.vue
|
||||
components/DocumentCheckSrmCandidateCard.vue
|
||||
views/DocumentCheckRunView.vue
|
||||
|
||||
frontend/src/features/admin/modules/document-check/
|
||||
DocumentCheckRunListPage.vue
|
||||
DocumentCheckRunsPage.vue
|
||||
DocumentCheckRunDetailPage.vue
|
||||
DocumentCheckReviewPage.vue
|
||||
DocumentCheckSchemaPage.vue
|
||||
DocumentCheckRulesPage.vue
|
||||
MaterialTerminologyPage.vue
|
||||
DocumentCheckModelRoutePage.vue
|
||||
DocumentCheckRuleTrialPage.vue
|
||||
DocumentCheckLearningTaskPage.vue
|
||||
DocumentCheckLearningTasksPage.vue
|
||||
DocumentCheckAuditPage.vue
|
||||
composables/useDocumentCheckAdmin.ts
|
||||
composables/useDocumentCheckConfig.ts
|
||||
components/DocumentCheckFieldForm.vue
|
||||
components/DocumentCheckRuleForm.vue
|
||||
components/DocumentCheckTermForm.vue
|
||||
components/DocumentCheckReviewDialog.vue
|
||||
components/DocumentCheckAuditDrawer.vue
|
||||
|
||||
frontend/src/app/router/routes/document-check.routes.ts
|
||||
frontend/src/features/admin/constants/modules.ts
|
||||
frontend/src/locales/{zh-CN,zh-TW,en,th}/document-check.json
|
||||
frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json
|
||||
frontend/tests/document-check/*.spec.ts
|
||||
```
|
||||
|
||||
全部 HTTP 使用 `requestJson`;新增文案同步四语言。
|
||||
实现约束:Page <300 行;复杂状态放 composable/store;组件不直接调 API;所有请求经 `requestJson`;新增错误码和页面文案四语言同步;不在 `shared/` 放文档检核业务组件。
|
||||
|
||||
## 16. 前端类型契约
|
||||
|
||||
```ts
|
||||
type CheckResult = 'passed' | 'failed' | 'needs_review' | 'technical_failed';
|
||||
type RunStatus = 'queued' | 'running' | 'completed' | 'cancelled';
|
||||
type CheckMode = 'single_file' | 'package' | 'file_plus_srm';
|
||||
|
||||
interface CheckRunSummary {
|
||||
id: number;
|
||||
run_no: string;
|
||||
agent_id: number;
|
||||
application_code: string;
|
||||
mode: CheckMode;
|
||||
status: RunStatus;
|
||||
result: CheckResult | null;
|
||||
total_count: number;
|
||||
passed_count: number;
|
||||
failed_count: number;
|
||||
needs_review_count: number;
|
||||
technical_failed_count: number;
|
||||
progress_percent: number;
|
||||
excel_download_url: string | null;
|
||||
writeback_status: 'off' | 'shadow' | 'pending' | 'success' | 'failed' | 'conflict';
|
||||
knowledge_sync_status: 'pending' | 'success' | 'failed' | 'not_requested';
|
||||
}
|
||||
```
|
||||
|
||||
## 17. 前端验收标准
|
||||
|
||||
1. 三个 Agent 进入后显示正确名称、编号和检核类型,组件不复制三套实现。
|
||||
2. 单文件、资料包上传均可校验格式/大小,并在启动前显示确认摘要。
|
||||
3. 运行中进度可刷新恢复;终态停止轮询;重复请求不产生重复 Run。
|
||||
4. Run 列表支持组合筛选、分页、权限过滤和 Excel 下载。
|
||||
5. 详情页能从项目进入文件证据、规则结果、SRM 比较、写回和审计。
|
||||
6. 复核页只允许项目级/Run 级结论,理由必填,越权操作不可见且后端拒绝。
|
||||
7. Schema、规则、术语和试运行页面均为表单;模型路由由环境变量固定,不提供管理页面;不要求管理员编辑 JSON/DSL。
|
||||
8. 试运行不污染正式 Run、统计、SRM 和知识库。
|
||||
9. 审计详情支持 before/after hash、敏感访问授权和脱敏导出。
|
||||
10. `npm run test:unit`、`npm run build` 通过,四语言文案齐全。
|
||||
@@ -371,9 +371,9 @@ export const reparseWorkspaceShippingOrderExtractionRun = (
|
||||
);
|
||||
|
||||
/** 获取当前订单抽取 Run 的按 PDF 归并详情。 */
|
||||
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) =>
|
||||
export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string, uploadBatchId?: string | null) =>
|
||||
requestJson<ShippingOrderExtractionDocumentsResponse>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents`,
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents${uploadBatchId ? `?upload_batch_id=${encodeURIComponent(uploadBatchId)}` : ''}`,
|
||||
);
|
||||
|
||||
/** 获取 Run 下每份 PDF 的建单前复核摘要,服务端负责 owner 隔离。 */
|
||||
@@ -935,9 +935,9 @@ export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Pr
|
||||
}
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string, uploadBatchId?: string | null) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events`,
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/progress-events${uploadBatchId ? `?upload_batch_id=${encodeURIComponent(uploadBatchId)}` : ''}`,
|
||||
);
|
||||
|
||||
/** 在终态状态卡已投影到当前会话后确认已查看,避免只因预加载会话列表而消除提醒。 */
|
||||
|
||||
@@ -77,32 +77,45 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
|
||||
);
|
||||
|
||||
/** 同一 Run 只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
|
||||
/** 同一 Run 或同一次上传批次只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
|
||||
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
|
||||
const current = items[index];
|
||||
if (!current?.shipping_order_extraction_state) return false;
|
||||
const payload = current.payload && typeof current.payload === 'object'
|
||||
? current.payload as Record<string, unknown>
|
||||
: {};
|
||||
const identity = String(
|
||||
const runIdentity = String(
|
||||
payload.order_extraction_run_no
|
||||
|| payload.formId
|
||||
|| current.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
if (!identity) return false;
|
||||
const batchIdentity = String(
|
||||
payload.shipping_order_extraction_upload_batch_id
|
||||
|| current.shipping_order_extraction_state.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
if (!runIdentity && !batchIdentity) return false;
|
||||
return items.slice(index + 1).some((candidate) => {
|
||||
if (!candidate?.shipping_order_extraction_state) return false;
|
||||
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
|
||||
? candidate.payload as Record<string, unknown>
|
||||
: {};
|
||||
const candidateIdentity = String(
|
||||
const candidateRunIdentity = String(
|
||||
candidatePayload.order_extraction_run_no
|
||||
|| candidatePayload.formId
|
||||
|| candidate.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
return candidateIdentity === identity;
|
||||
const candidateBatchIdentity = String(
|
||||
candidatePayload.shipping_order_extraction_upload_batch_id
|
||||
|| candidate.shipping_order_extraction_state.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
return Boolean(
|
||||
(batchIdentity && candidateBatchIdentity === batchIdentity)
|
||||
|| (runIdentity && candidateRunIdentity === runIdentity),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
+25
-15
@@ -125,9 +125,9 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-needs_action"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('需要你处理 · 1 个任务');
|
||||
expect(wrapper.text()).toContain('异常 / 失败 · 1 个任务');
|
||||
expect(wrapper.text()).toContain('系统处理中 · 1 个任务');
|
||||
expect(wrapper.text()).toContain('刚刚创建');
|
||||
|
||||
@@ -441,20 +441,36 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(wrapper.findAll('[data-testid="shipping-conversation-processing-card"]')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders pending order_intake work items above task groups', async () => {
|
||||
it('renders an EML order_intake in the unified failed group rather than the removed intake side path', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: null,
|
||||
projection: {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
user_task_no: 'SNI-1',
|
||||
group: 'needs_action',
|
||||
userGroup: 'failed',
|
||||
status_label: 'failed',
|
||||
title: 'mail.eml',
|
||||
file_count: 1,
|
||||
run_no: null,
|
||||
can_append: false,
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
workItems: [{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'failed',
|
||||
userGroup: 'failed',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-04T12:00:00Z',
|
||||
@@ -484,16 +500,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-intake-SNI-1"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('po.pdf');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-intake-recovery"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('SHIPPING_NOTICE.INTAKE_PARSE_FAILED');
|
||||
await wrapper.find('[data-testid="shipping-processing-intake-action-retry_parse"]').trigger('click');
|
||||
expect(wrapper.emitted('intakeAction')?.[0]?.[0]).toMatchObject({
|
||||
action: 'retry_parse',
|
||||
item: { workItemNo: 'SNI-1' },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-SNI-1"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain('重试解析');
|
||||
});
|
||||
|
||||
it('keeps a human Gate action visible before and after selecting its task', async () => {
|
||||
|
||||
+105
-160
@@ -31,7 +31,6 @@ import {
|
||||
import {
|
||||
resolveShippingProcessingMessage,
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingSourceTypeKey,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveConversationTaskActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
@@ -71,22 +70,21 @@ const activeProjection = computed((): ConversationProcessingProjection | null =>
|
||||
props.projection || null
|
||||
));
|
||||
|
||||
/** 尚未建 OT、仍应展示在「待处理材料」的 Intake 工作项。 */
|
||||
const pendingIntakeItems = computed((): ShippingProcessingProjection[] => {
|
||||
const items = Array.isArray(props.workItems) ? props.workItems : [];
|
||||
return items.filter((item) => {
|
||||
if (item.workItemType !== 'order_intake') return false;
|
||||
return !['completed', 'cancelled'].includes(String(item.status || ''));
|
||||
});
|
||||
});
|
||||
|
||||
const hasContent = computed(() => Boolean(
|
||||
activeProjection.value
|
||||
|| pendingIntakeItems.value.length,
|
||||
activeProjection.value,
|
||||
));
|
||||
|
||||
const completedTasks = computed(() => activeProjection.value?.completed || []);
|
||||
const historyTasks = computed(() => activeProjection.value?.history || []);
|
||||
const statusGroups = computed(() => activeProjection.value?.status_groups || null);
|
||||
const completedTasks = computed(() => statusGroups.value?.completed || activeProjection.value?.completed || []);
|
||||
const historyTasks = computed(() => statusGroups.value
|
||||
? [...statusGroups.value.cancelled, ...statusGroups.value.archived]
|
||||
: (activeProjection.value?.history || []));
|
||||
/** EML 卡必须由后端 userGroup 分入独立用户区;旧任务保留 needs_action 兼容归属。 */
|
||||
const failedTasks = computed(() => statusGroups.value?.failed
|
||||
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'failed' || !task.userGroup));
|
||||
const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human
|
||||
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'waiting_human'));
|
||||
const processingTasks = computed(() => statusGroups.value?.processing || activeProjection.value?.processing || []);
|
||||
|
||||
/** history 中非取消 →「历史版本」。 */
|
||||
const historyVersionTasks = computed(() => historyTasks.value.filter(
|
||||
@@ -123,7 +121,7 @@ function projectionForTask(task: ConversationProcessingUserTask): ShippingProces
|
||||
if (!taskNo) return null;
|
||||
const items = Array.isArray(props.workItems) ? props.workItems : [];
|
||||
return items.find((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
(item.workItemType === 'order_task' || item.workItemType === 'order_intake')
|
||||
&& String(item.workItemNo || '').trim() === taskNo
|
||||
)) || null;
|
||||
}
|
||||
@@ -232,6 +230,38 @@ function statusLabel(task: ConversationProcessingUserTask): string {
|
||||
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
|
||||
}
|
||||
|
||||
/** 展示统一投影的真实履约阶段;识别候选不再冒充最终完成。 */
|
||||
function stageLabel(task: ConversationProcessingUserTask): string {
|
||||
const projection = projectionForTask(task);
|
||||
if (!projection) return '';
|
||||
return intakeStageLabel(projection);
|
||||
}
|
||||
|
||||
/** 展示后端统一投影的阻断/失败原因,不从状态码自行猜测。 */
|
||||
function taskReasonLabel(task: ConversationProcessingUserTask): string {
|
||||
const code = String(task.blockingReason?.code || task.aggregateSummary?.reasonCodes[0] || '').trim();
|
||||
if (!code) return '';
|
||||
const messages: Record<string, string> = {
|
||||
'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED': '识别结果需要人工确认,请进入订单处理继续。',
|
||||
'generic_extraction_disabled': '当前文件暂不支持自动解析,请人工处理或更换文件。',
|
||||
'SHIPPING_NOTICE.INTAKE_PARSE_FAILED': '邮件或附件解析失败,请检查文件后重试。',
|
||||
'upload_rpa_failed': '上传货代系统失败,请稍后重试。',
|
||||
};
|
||||
return messages[code] || '文件处理需要人工确认,请进入订单处理查看。';
|
||||
}
|
||||
|
||||
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
|
||||
function aggregateStatusLabel(task: ConversationProcessingUserTask): string {
|
||||
const summary = task.aggregateSummary;
|
||||
if (!summary) return '';
|
||||
const parts: string[] = [];
|
||||
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
|
||||
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
|
||||
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
|
||||
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否高亮 needs_action 任务。
|
||||
*/
|
||||
@@ -391,25 +421,6 @@ function toggleHistorySection() {
|
||||
historySectionExpanded.value = !historySectionExpanded.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 材料标题:文件名 / 邮件主题 / Intake 编号。
|
||||
*/
|
||||
function intakeTitle(item: ShippingProcessingProjection): string {
|
||||
return String(
|
||||
item.sourceSummary?.filename
|
||||
|| item.sourceSummary?.emailSubject
|
||||
|| item.workItemNo
|
||||
|| '',
|
||||
).trim() || item.workItemNo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 状态文案。
|
||||
*/
|
||||
function intakeStatusLabel(item: ShippingProcessingProjection): string {
|
||||
return resolveShippingProcessingStatusLabel(item.status, te, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 阶段文案。
|
||||
*/
|
||||
@@ -417,68 +428,6 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
|
||||
const key = shippingProcessingStageKey(item.stage);
|
||||
return te(key) ? t(key) : String(item.stage || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 来源类型文案。
|
||||
*/
|
||||
function intakeSourceLabel(item: ShippingProcessingProjection): string {
|
||||
const key = shippingProcessingSourceTypeKey(item.sourceType);
|
||||
return te(key) ? t(key) : String(item.sourceType || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake / OT 门禁与失败恢复元信息(Gate / Attempt / 资产状态)。
|
||||
*/
|
||||
function intakeRecoveryMeta(item: ShippingProcessingProjection): string[] {
|
||||
const parts: string[] = [];
|
||||
const gate = item.currentGate;
|
||||
const reason = String(
|
||||
gate?.blockingReasonCode
|
||||
|| item.sourceSummary?.failureReasonCode
|
||||
|| '',
|
||||
).trim();
|
||||
if (reason) {
|
||||
parts.push(t('chat.shippingProcessing.failureReason', { code: reason }));
|
||||
}
|
||||
const attempt = gate?.attemptNo ?? item.sourceSummary?.parseAttemptCount;
|
||||
if (attempt != null && Number(attempt) > 0) {
|
||||
parts.push(t('chat.shippingProcessing.parseAttempt', { count: Number(attempt) }));
|
||||
}
|
||||
const assetStatus = String(item.sourceSummary?.assetStatus || '').trim();
|
||||
if (assetStatus) {
|
||||
const key = `chat.shippingProcessing.assetStatus.${assetStatus}`;
|
||||
parts.push(te(key) ? t(key) : t('chat.shippingProcessing.assetStatusLabel', { status: assetStatus }));
|
||||
}
|
||||
if (gate?.gateCode) {
|
||||
parts.push(t('chat.shippingProcessing.gateCode', { code: gate.gateCode }));
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 可见动作(仅展示 retry_parse)。
|
||||
*/
|
||||
function visibleIntakeActions(item: ShippingProcessingProjection): string[] {
|
||||
const actions = Array.isArray(item.availableActions) ? item.availableActions : [];
|
||||
return actions.filter((code) => code === 'retry_parse');
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 动作文案。
|
||||
*/
|
||||
function intakeActionLabel(action: string): string {
|
||||
if (action === 'retry_parse') return t('chat.shippingProcessing.retryFromFailure');
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发 Intake 级动作。
|
||||
*/
|
||||
function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
const code = String(action || '').trim();
|
||||
if (!code) return;
|
||||
emit('intakeAction', { item, action: code });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -488,70 +437,15 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
data-testid="shipping-conversation-processing-card"
|
||||
>
|
||||
<section
|
||||
v-if="pendingIntakeItems.length"
|
||||
data-testid="shipping-processing-group-order-intake"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300">
|
||||
{{ t('chat.shippingProcessing.pendingMaterials') }}
|
||||
· {{ pendingIntakeItems.length }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="item in pendingIntakeItems"
|
||||
:key="item.workItemNo"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2"
|
||||
:data-testid="`shipping-processing-intake-${item.workItemNo}`"
|
||||
:data-source-type="item.sourceType"
|
||||
:data-status="item.status"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ intakeTitle(item) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span>{{ intakeSourceLabel(item) }}</span>
|
||||
<span>{{ intakeStatusLabel(item) }}</span>
|
||||
<span v-if="intakeStageLabel(item)">{{ intakeStageLabel(item) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="intakeRecoveryMeta(item).length"
|
||||
class="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-rose-700 dark:text-rose-300"
|
||||
data-testid="shipping-processing-intake-recovery"
|
||||
>
|
||||
<span
|
||||
v-for="(meta, idx) in intakeRecoveryMeta(item)"
|
||||
:key="`${item.workItemNo}-meta-${idx}`"
|
||||
>{{ meta }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="visibleIntakeActions(item).length"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-intake-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleIntakeActions(item)"
|
||||
:key="`${item.workItemNo}-${action}`"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-intake-action-${action}`"
|
||||
@click="onIntakeAction(item, action)"
|
||||
>
|
||||
{{ intakeActionLabel(action) }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="activeProjection?.needs_action.length"
|
||||
data-testid="shipping-processing-group-needs_action"
|
||||
v-if="failedTasks.length"
|
||||
data-testid="shipping-processing-group-failed"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
{{ resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: activeProjection.needs_action.length }) }}
|
||||
{{ t('chat.shippingProcessing.groupFailed', { count: failedTasks.length }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in activeProjection.needs_action"
|
||||
v-for="task in failedTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border px-2.5 py-2 transition"
|
||||
:class="[
|
||||
@@ -574,6 +468,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
@@ -582,6 +477,12 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
{{ taskReasonLabel(task) }}
|
||||
</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
|
||||
{{ aggregateStatusLabel(task) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="task.recent_append_count"
|
||||
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
|
||||
@@ -630,15 +531,52 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="activeProjection?.processing.length"
|
||||
data-testid="shipping-processing-group-processing"
|
||||
v-if="waitingHumanTasks.length"
|
||||
data-testid="shipping-processing-group-waiting_human"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
|
||||
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: activeProjection.processing.length }) }}
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
|
||||
{{ t('chat.shippingProcessing.groupWaitingHuman', { count: waitingHumanTasks.length }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in activeProjection.processing"
|
||||
v-for="task in waitingHumanTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-amber-400 bg-amber-50/80 px-2.5 py-2 transition dark:border-amber-700 dark:bg-amber-950/30"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
|
||||
>
|
||||
<button type="button" class="w-full text-left" @click="onSelectTask(task)">
|
||||
<div class="text-sm font-semibold text-primary">{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
|
||||
</button>
|
||||
<div v-if="currentNeedLabel(task)" class="mt-1 text-[11px] text-secondary">{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}</div>
|
||||
<SidebarProgressInline
|
||||
v-if="projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="false"
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="processingTasks.length"
|
||||
data-testid="shipping-processing-group-processing"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
|
||||
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: processingTasks.length }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in processingTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2"
|
||||
:class="focusedTaskNo === task.user_task_no
|
||||
@@ -666,6 +604,9 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">
|
||||
{{ aggregateStatusLabel(task) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="task.recent_append_count"
|
||||
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
|
||||
@@ -805,6 +746,7 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="stageLabel(task)">· {{ stageLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
@@ -813,6 +755,9 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
|
||||
{{ taskReasonLabel(task) }}
|
||||
</div>
|
||||
<button
|
||||
v-if="recordViewDetailsItem(task)"
|
||||
type="button"
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
* 逻辑:断言不再渲染进度列表/刷新取消/完整 handling 卡片;失败重试与需处理继续处理互斥。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { ref } from 'vue';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -51,6 +53,288 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
it('uses unified EML aggregation and keeps candidate creation out of completed', async () => {
|
||||
const aggregate = {
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1',
|
||||
shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1',
|
||||
status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'forwarder.eml', documentCount: 3, parsedDocumentCount: 3, candidateCount: 2, customerName: null, poNumber: null }, childOrderTasks: [],
|
||||
userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' },
|
||||
aggregateSummary: { intakeNo: 'SNI-1', total: 3, completed: 1, processing: 1, needsAction: 0, failed: 1, stages: ['completed', 'candidate_creating'], reasonCodes: ['upload_rpa_failed'] },
|
||||
aggregateChildren: [
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1', shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'completed', stage: 'completed', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'done.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null }, childOrderTasks: [], userStatus: 'completed', userStage: 'completed', facts: { uploadState: 'succeeded' } },
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: 'OT-1', shippingNoticeNo: null, runNo: 'SNER-EML', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'candidate.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null }, childOrderTasks: [], userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' } },
|
||||
],
|
||||
} as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-EML' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([aggregate]) } } },
|
||||
});
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('已上传完成 1 · 处理中 1 · 异常 1');
|
||||
expect(wrapper.text()).not.toContain('已生成候选 3 个文件');
|
||||
await wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"] button').trigger('click');
|
||||
expect(wrapper.text()).toContain('candidate.pdf');
|
||||
expect(wrapper.text()).toContain('处理中 1');
|
||||
});
|
||||
|
||||
it('keeps its matched EML card when the side-panel poll temporarily omits the intake', async () => {
|
||||
const workItems = ref<any[]>([{
|
||||
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-STABLE', sourceType: 'eml', rootOrderTaskNo: 'OT-STABLE',
|
||||
shippingNoticeNo: null, runNo: 'SNER-STABLE', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
|
||||
status: 'processing', stage: 'candidate_creating', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'stable.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
|
||||
childOrderTasks: [], userStatus: 'running', userStage: 'candidate_creating', facts: { uploadState: 'not_created' },
|
||||
aggregateSummary: { intakeNo: 'SNI-STABLE', total: 2, completed: 0, processing: 2, needsAction: 0, failed: 0, stages: ['candidate_creating'], reasonCodes: [] },
|
||||
aggregateChildren: [],
|
||||
}]);
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-STABLE' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: workItems } } },
|
||||
});
|
||||
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
|
||||
// 关键断言:右侧轮询暂时省略本 Intake 时,中间消息卡仍保留其自身的 EML 形态。
|
||||
workItems.value = [];
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
|
||||
});
|
||||
|
||||
it('expands an EML inside its status group and shows every child attachment state', async () => {
|
||||
const child = {
|
||||
workItemType: 'order_task', workItemNo: 'OT-CHILD-1', sourceType: 'eml', rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null, runNo: 'SNER-DETAIL', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-DETAIL',
|
||||
status: 'failed', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'failed.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null },
|
||||
childOrderTasks: [], userStatus: 'failed', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
|
||||
blockingReason: { code: 'PARSE_FAILED' },
|
||||
} as any;
|
||||
const task = { user_task_no: 'INTAKE:SNI-DETAIL', title: 'mail.eml', file_count: 1, userGroup: 'failed', group: 'needs_action', aggregateChildren: [child], aggregateSummary: { intakeNo: 'SNI-DETAIL', total: 1, completed: 0, processing: 0, needsAction: 0, failed: 1, stages: ['document_parsing'], reasonCodes: ['PARSE_FAILED'] } } as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-DETAIL' },
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
provide: {
|
||||
[SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({ status_groups: { failed: [task], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [] } }),
|
||||
processingWorkItems: ref([]),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
await wrapper.get('[data-testid="shipping-order-extraction-eml-failed-INTAKE:SNI-DETAIL"] button').trigger('click');
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('failed.pdf');
|
||||
expect(wrapper.text()).toContain('异常 1');
|
||||
expect(wrapper.text()).toContain('文件处理需要人工确认');
|
||||
expect(wrapper.text()).not.toContain('PARSE_FAILED');
|
||||
});
|
||||
|
||||
it('falls back to the matched work item children when the status task only has a summary', async () => {
|
||||
const child = {
|
||||
workItemType: 'order_task', workItemNo: 'OT-FALLBACK-1', sourceType: 'eml', rootOrderTaskNo: 'OT-FALLBACK',
|
||||
shippingNoticeNo: null, runNo: 'SNER-FALLBACK', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-FALLBACK',
|
||||
status: 'processing', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'inside.eml.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
|
||||
childOrderTasks: [], userStatus: 'running', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
|
||||
} as any;
|
||||
const task = { user_task_no: 'INTAKE:SNI-FALLBACK', title: 'inside.eml', file_count: 1, userGroup: 'processing', group: 'processing', aggregateChildren: [], aggregateSummary: { intakeNo: 'SNI-FALLBACK', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: ['document_parsing'], reasonCodes: [] } } as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-FALLBACK' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }),
|
||||
processingWorkItems: ref([{ workItemType: 'order_intake', workItemNo: 'INTAKE:SNI-FALLBACK', sourceType: 'eml', intakeNo: 'SNI-FALLBACK', aggregateChildren: [child] } as any]),
|
||||
} } },
|
||||
});
|
||||
await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-FALLBACK"] button').trigger('click');
|
||||
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('inside.eml.pdf');
|
||||
});
|
||||
|
||||
it('counts unique EML attachment children instead of task rows', async () => {
|
||||
const childA = { workItemType: 'order_task', workItemNo: 'OT-A', sourceType: 'eml', intakeNo: 'SNI-COUNT', sourceSummary: { filename: 'a.pdf', documentId: 101, documentCount: 1 }, status: 'processing', stage: 'document_parsing', userStatus: 'running', facts: { uploadState: 'not_created' } } as any;
|
||||
const childB = { ...childA, workItemNo: 'OT-B', sourceSummary: { filename: 'b.pdf', documentId: 102, documentCount: 1 } } as any;
|
||||
const task = { user_task_no: 'INTAKE:SNI-COUNT', title: 'count.eml', file_count: 2, userGroup: 'processing', group: 'processing', aggregateChildren: [childA, childB], aggregateSummary: { intakeNo: 'SNI-COUNT', total: 2, completed: 0, processing: 2, needsAction: 0, failed: 0, stages: [], reasonCodes: [] } } as any;
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-COUNT' },
|
||||
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }), processingWorkItems: ref([]) } } },
|
||||
});
|
||||
expect(wrapper.text()).toContain('2 个文件');
|
||||
});
|
||||
|
||||
it('renders every projected file when the batch has two documents', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 0,
|
||||
reviewRequiredDocuments: 2,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 0,
|
||||
},
|
||||
documents: [
|
||||
{ unitId: 1, documentId: 11, fileName: '4518838154.pdf', status: 'review_required' },
|
||||
{ unitId: 2, documentId: 12, fileName: '4518838152.pdf', status: 'review_required' },
|
||||
],
|
||||
availableActions: ['enter_manual_review'],
|
||||
healthTips: [],
|
||||
}),
|
||||
runNo: 'SNER-2',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('4518838154.pdf');
|
||||
expect(wrapper.text()).toContain('4518838152.pdf');
|
||||
});
|
||||
|
||||
it('groups completed attachments under their EML intake instead of mixing unrelated files', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
documents: [
|
||||
{ unitId: 1, documentId: 11, intakeId: 7, documentType: 'email_body', fileName: 'Forwarder_A.eml', status: 'processing' },
|
||||
{ unitId: 2, documentId: 12, intakeId: 7, documentType: 'attachment', fileName: 'Packing_List.pdf', status: 'candidate_ready' },
|
||||
{ unitId: 3, documentId: 13, intakeId: 8, documentType: 'attachment', fileName: 'Customs_Form.pdf', status: 'processing' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('button').trigger('click');
|
||||
const text = wrapper.text();
|
||||
expect(text.indexOf('Forwarder_A.eml')).toBeLessThan(text.indexOf('Packing_List.pdf'));
|
||||
expect(text).toContain('Customs_Form.pdf');
|
||||
expect(text.match(/Packing_List\.pdf/g)?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('groups by email_body document type and renders parse failure as failed', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'failed',
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 0,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 0,
|
||||
},
|
||||
documents: [
|
||||
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder-message', status: 'failed', reasonCode: 'intake_parse_failed' },
|
||||
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'po.pdf', status: 'failed', reasonCode: 'intake_parse_failed' },
|
||||
],
|
||||
healthTips: [],
|
||||
currentActivity: null,
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const text = wrapper.text();
|
||||
expect(text).toContain('forwarder-message');
|
||||
expect(text).toContain('po.pdf');
|
||||
expect(text).toContain('异常');
|
||||
expect(wrapper.findAll('.animate-spin').length).toBe(0);
|
||||
});
|
||||
|
||||
it('does not render completed files again as standalone cards', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
documents: [
|
||||
{ unitId: 1, documentId: 11, fileName: '4518838152.pdf', status: 'candidate_ready' },
|
||||
{ unitId: 2, documentId: 12, fileName: '4518838154.pdf', status: 'candidate_ready' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const accordion = wrapper.find('button');
|
||||
await accordion.trigger('click');
|
||||
expect(wrapper.text().match(/4518838152\.pdf/g)?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('aggregates a fully completed EML intake only inside the completed section', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 2,
|
||||
},
|
||||
documents: [
|
||||
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
|
||||
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'candidate_ready' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).not.toContain('forwarder.eml');
|
||||
expect(wrapper.text()).not.toContain('packing.pdf');
|
||||
await wrapper.find('button').trigger('click');
|
||||
expect(wrapper.text()).toContain('forwarder.eml');
|
||||
expect(wrapper.text()).toContain('packing.pdf');
|
||||
expect(wrapper.text().match(/forwarder\.eml/g)?.length).toBe(1);
|
||||
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
|
||||
expect(wrapper.text()).toContain('已提取');
|
||||
});
|
||||
|
||||
it('keeps a partially completed EML intake outside the completed section', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
documents: [
|
||||
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
|
||||
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'candidate_ready' },
|
||||
{ unitId: 9, documentId: 9, intakeId: 7, documentType: 'attachment', fileName: 'invoice.pdf', status: 'processing' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await wrapper.find('button').trigger('click');
|
||||
expect(wrapper.text()).toContain('forwarder.eml');
|
||||
expect(wrapper.text()).toContain('invoice.pdf');
|
||||
expect(wrapper.text().match(/packing\.pdf/g)?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('shows an EML as exception when a child failed even if the parent status is processing', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
documents: [
|
||||
{ unitId: -7, documentId: 7, intakeId: 7, documentType: 'email_body', fileName: 'forwarder.eml', status: 'processing' },
|
||||
{ unitId: 8, documentId: 8, intakeId: 7, documentType: 'attachment', fileName: 'packing.pdf', status: 'failed', reasonCode: 'intake_parse_failed' },
|
||||
],
|
||||
healthTips: [],
|
||||
}),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('异常');
|
||||
expect(wrapper.text()).not.toContain('解析附件中');
|
||||
});
|
||||
|
||||
it('renders summary title, file count, system processing and no progress/refresh/cancel', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-1' },
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
* 逻辑:对话区只做任务摘要;长进度/Gate/刷新取消由右侧栏承接;详情抽屉仅由次要「查看详情」打开。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import { AlertCircle, ArrowRight, CheckCircle2, ChevronDown, CircleX, FileText, LoaderCircle, Mail, RefreshCw, TriangleAlert } from 'lucide-vue-next';
|
||||
import type {
|
||||
ShippingOrderExtractionHandlingItemState,
|
||||
ShippingOrderExtractionFileState,
|
||||
ShippingOrderExtractionState,
|
||||
} from '../../types/chat.types';
|
||||
import type {
|
||||
@@ -18,6 +19,8 @@ import type {
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
|
||||
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
|
||||
import { shippingProcessingStageKey } from '../../shipping/shippingProcessingLabels';
|
||||
import {
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents,
|
||||
@@ -46,6 +49,211 @@ const emit = defineEmits<{
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const shippingWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
|
||||
|
||||
type ConversationStatusGroups = NonNullable<import('../../types/shipping.api.types').ConversationProcessingProjection['status_groups']>;
|
||||
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => ((shippingWorkflow as { processing?: { value?: { status_groups?: ConversationStatusGroups | null } | null } } | null)?.processing?.value?.status_groups || null));
|
||||
const hasConversationStatusGroups = computed(() => Boolean(conversationStatusGroups.value));
|
||||
const statusGroupDefs = [
|
||||
{ key: 'failed', label: 'chat.shippingProcessing.groupFailed' },
|
||||
{ key: 'waiting_human', label: 'chat.shippingProcessing.groupWaitingHuman' },
|
||||
{ key: 'processing', label: 'chat.shippingProcessing.groupProcessing' },
|
||||
{ key: 'completed', label: 'chat.shippingProcessing.groupCompleted' },
|
||||
{ key: 'cancelled', label: 'chat.shippingProcessing.groupCancelled' },
|
||||
{ key: 'archived', label: 'chat.shippingProcessing.groupHistoryRecords' },
|
||||
] as const;
|
||||
const expandedStatusGroups = ref(new Set<string>(['failed', 'waiting_human', 'processing']));
|
||||
const expandedEmlTasks = ref(new Set<string>());
|
||||
function statusGroupTasks(key: typeof statusGroupDefs[number]['key']) {
|
||||
return conversationStatusGroups.value?.[key] || [];
|
||||
}
|
||||
function statusGroupLabel(key: typeof statusGroupDefs[number]['key']) {
|
||||
const count = statusGroupTasks(key).length;
|
||||
return t(statusGroupDefs.find((item) => item.key === key)!.label, { count });
|
||||
}
|
||||
function toggleStatusGroup(key: string) {
|
||||
const next = new Set(expandedStatusGroups.value);
|
||||
if (next.has(key)) next.delete(key); else next.add(key);
|
||||
expandedStatusGroups.value = next;
|
||||
}
|
||||
function toggleEmlTask(taskNo: string) {
|
||||
const next = new Set(expandedEmlTasks.value);
|
||||
if (next.has(taskNo)) next.delete(taskNo); else next.add(taskNo);
|
||||
expandedEmlTasks.value = next;
|
||||
}
|
||||
function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]; user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
|
||||
if (task.aggregateChildren?.length) return task.aggregateChildren;
|
||||
const projection = statusTaskProjection(task);
|
||||
if (!projection) return [];
|
||||
if (projection?.aggregateChildren?.length) return projection.aggregateChildren;
|
||||
const projectionChildren = (projection?.childOrderTasks || []).map((child) => ({
|
||||
...projection,
|
||||
workItemNo: child.orderTaskNo,
|
||||
status: child.status,
|
||||
stage: child.stage,
|
||||
userStatus: child.status === 'completed' ? 'completed' : child.status === 'failed' ? 'failed' : 'running',
|
||||
userStage: child.stage,
|
||||
sourceSummary: {
|
||||
...projection.sourceSummary,
|
||||
filename: child.orderTaskNo,
|
||||
documentCount: 1,
|
||||
},
|
||||
} as ShippingProcessingProjection));
|
||||
if (projectionChildren.length) return projectionChildren;
|
||||
|
||||
// 系统处理中 work_item 可能只有 EML 摘要;附件真实状态仍由当前 Run 文档列表承载。
|
||||
const emailName = String(projection.sourceSummary?.filename || task.aggregateSummary?.intakeNo || '').trim().toLowerCase();
|
||||
const emailRow = emailRows.value.find((row) => (
|
||||
String(row.fileName || '').trim().toLowerCase() === emailName
|
||||
|| String(row.intakeId || '').trim() === String(task.aggregateSummary?.intakeNo || '').trim()
|
||||
));
|
||||
if (!emailRow) return [];
|
||||
return childRows(emailRow).map((row) => ({
|
||||
workItemType: 'order_task',
|
||||
workItemNo: `DOCUMENT:${row.documentId || row.unitId}`,
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
runNo: props.runNo || props.state.runNo || null,
|
||||
caseNo: null,
|
||||
conversationId: null,
|
||||
submissionNo: '',
|
||||
intakeNo: String(emailRow.intakeId || task.aggregateSummary?.intakeNo || ''),
|
||||
status: row.status === 'failed' ? 'failed' : row.status === 'review_required' ? 'waiting_review' : row.status === 'candidate_ready' ? 'completed' : 'processing',
|
||||
stage: String(row.userVisibleStage || row.status || 'processing'),
|
||||
progressVersion: 0,
|
||||
lastActivityAt: '',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: row.fileName,
|
||||
documentId: row.documentId || null,
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: row.status === 'failed' ? 0 : 1,
|
||||
candidateCount: row.status === 'candidate_ready' ? 1 : 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
failureReasonCode: row.reasonCode || null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
userStatus: row.status === 'failed' ? 'failed' : row.status === 'review_required' ? 'waiting_human' : row.status === 'candidate_ready' ? 'completed' : 'running',
|
||||
userStage: row.userVisibleStage || row.status,
|
||||
blockingReason: row.explainability?.message ? { code: row.reasonCode || 'DOCUMENT_PROCESSING_FAILED', details: { message: row.explainability.message } } : null,
|
||||
retryable: false,
|
||||
primaryAction: null,
|
||||
facts: { uploadState: row.status === 'candidate_ready' ? 'succeeded' : 'not_created' },
|
||||
userGroup: null,
|
||||
} as ShippingProcessingProjection));
|
||||
}
|
||||
function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[]; file_count?: number | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
|
||||
const children = taskChildren(task);
|
||||
if (children.length) {
|
||||
const ids = new Set(children.map((child) => String(child.sourceSummary?.documentId || child.workItemNo || '').trim()).filter(Boolean));
|
||||
return ids.size || children.length;
|
||||
}
|
||||
const projection = statusTaskProjection(task);
|
||||
const sourceCount = Number(projection?.sourceSummary?.documentCount || 0);
|
||||
return sourceCount > 0 ? sourceCount : Math.max(0, Number(task.file_count || 0));
|
||||
}
|
||||
function childStatusLabel(child: ShippingProcessingProjection) {
|
||||
const status = String(child.userStatus || child.status || '').toLowerCase();
|
||||
if (status === 'completed' && child.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
|
||||
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
|
||||
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
|
||||
}
|
||||
function userReasonLabel(code?: string | null) {
|
||||
const key = String(code || '').trim();
|
||||
const messages: Record<string, string> = {
|
||||
'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED': '识别结果需要人工确认,请进入订单处理继续。',
|
||||
'generic_extraction_disabled': '当前文件暂不支持自动解析,请人工处理或更换文件。',
|
||||
'SHIPPING_NOTICE.INTAKE_PARSE_FAILED': '邮件或附件解析失败,请检查文件后重试。',
|
||||
'upload_rpa_failed': '上传货代系统失败,请稍后重试。',
|
||||
};
|
||||
return messages[key] || (key ? '文件处理需要人工确认,请进入订单处理查看。' : '');
|
||||
}
|
||||
function childStageLabel(child: ShippingProcessingProjection) {
|
||||
const stage = String(child.userStage || child.stage || '').trim();
|
||||
if (stage === 'review_required' || stage === 'waiting_review') return '等待人工复核';
|
||||
if (stage === 'failed' || stage === 'parse_failed') return '处理失败';
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
}
|
||||
function statusTaskProjection(task: { user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
|
||||
const items = shippingWorkflow?.processingWorkItems.value || [];
|
||||
const intakeNo = String(task.aggregateSummary?.intakeNo || '').trim();
|
||||
if (intakeNo) {
|
||||
const intakeMatch = items.find((item) => (
|
||||
item.sourceType === 'eml'
|
||||
&& String(item.intakeNo || '').trim() === intakeNo
|
||||
));
|
||||
if (intakeMatch) return intakeMatch;
|
||||
}
|
||||
return items.find((item) => (
|
||||
(item.workItemType === 'order_task' || item.workItemType === 'order_intake')
|
||||
&& String(item.workItemNo || '').trim() === String((task as any).user_task_no || '').trim()
|
||||
)) || null;
|
||||
}
|
||||
function aggregateStatusLabelFromSummary(summary: NonNullable<import('../../types/shipping.api.types').ConversationProcessingUserTask['aggregateSummary']>) {
|
||||
const parts: string[] = [];
|
||||
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
|
||||
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
|
||||
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
|
||||
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前 Run 对应的 EML Intake 聚合项。
|
||||
*
|
||||
* 右侧投影轮询是增量可见的:一次响应暂未带回该 Intake 不能让聊天消息卡
|
||||
* 降级为旧 Run 卡。消息卡保留最后一次同 Run/用户任务命中的聚合快照,只有
|
||||
* 同一绑定再次命中时才更新;右侧面板仍直接消费实时投影。
|
||||
*/
|
||||
const matchedEmlAggregate = computed(() => {
|
||||
const runNo = String(props.runNo || props.state.runNo || '').trim();
|
||||
const userTaskNo = String(props.state.userTaskNo || '').trim();
|
||||
const items = shippingWorkflow?.processingWorkItems.value || [];
|
||||
return items.find((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
&& item.sourceType === 'eml'
|
||||
&& Boolean(item.aggregateSummary)
|
||||
&& (
|
||||
String(item.runNo || '').trim() === runNo
|
||||
|| (Boolean(userTaskNo) && String(item.rootOrderTaskNo || '').trim() === userTaskNo)
|
||||
)
|
||||
)) || null;
|
||||
});
|
||||
const lastMatchedEmlAggregate = ref<ShippingProcessingProjection | null>(null);
|
||||
watch(matchedEmlAggregate, (item) => {
|
||||
if (item) lastMatchedEmlAggregate.value = item;
|
||||
}, { immediate: true });
|
||||
const emlAggregate = computed(() => matchedEmlAggregate.value || lastMatchedEmlAggregate.value);
|
||||
const emlAggregateChildren = computed(() => emlAggregate.value?.aggregateChildren || []);
|
||||
const emlAggregateExpanded = ref(false);
|
||||
function aggregateStageLabel(item: ShippingProcessingProjection): string {
|
||||
const stage = String(item.userStage || item.stage || '').trim();
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
}
|
||||
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
|
||||
const status = String(item.userStatus || item.status || '').trim().toLowerCase();
|
||||
if (status === 'completed' && item.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
|
||||
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
|
||||
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
|
||||
}
|
||||
function aggregateSummaryLabel(item: ShippingProcessingProjection): string {
|
||||
const summary = item.aggregateSummary;
|
||||
if (!summary) return '';
|
||||
const parts: string[] = [];
|
||||
if (summary.completed) parts.push(t('chat.shippingProcessing.aggregate.completed', { count: summary.completed }));
|
||||
if (summary.processing) parts.push(t('chat.shippingProcessing.aggregate.processing', { count: summary.processing }));
|
||||
if (summary.needsAction) parts.push(t('chat.shippingProcessing.aggregate.needsAction', { count: summary.needsAction }));
|
||||
if (summary.failed) parts.push(t('chat.shippingProcessing.aggregate.failed', { count: summary.failed }));
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
const detailsOpen = ref(false);
|
||||
const detailsLoading = ref(false);
|
||||
@@ -58,6 +266,62 @@ const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
const displaySummary = computed(() => props.state.summary);
|
||||
|
||||
const handlingItems = computed(() => props.state.handlingItems || []);
|
||||
const fileRows = computed(() => props.state.documents || []);
|
||||
const isEmailRow = (row: ShippingOrderExtractionFileState) => (
|
||||
row.documentType === 'email_body' || row.fileName?.toLowerCase().endsWith('.eml')
|
||||
);
|
||||
const emailRows = computed(() => fileRows.value.filter(isEmailRow));
|
||||
const isFailedParseRow = (row: ShippingOrderExtractionFileState) => (
|
||||
row.status === 'failed'
|
||||
|| row.reasonCode === 'intake_parse_failed'
|
||||
|| row.userVisibleStage === 'parse_failed'
|
||||
);
|
||||
const childRows = (email: ShippingOrderExtractionFileState) => fileRows.value.filter((row) => (
|
||||
row.unitId !== email.unitId
|
||||
&& row.intakeId != null
|
||||
&& row.intakeId === email.intakeId
|
||||
&& !isEmailRow(row)
|
||||
));
|
||||
const candidateEmailGroups = computed(() => emailRows.value
|
||||
.map((parent) => ({ parent, children: childRows(parent) }))
|
||||
.filter((group) => group.children.length > 0 && group.children.every((child) => child.status === 'candidate_ready')));
|
||||
const emailHasFailedChild = (email: ShippingOrderExtractionFileState) => childRows(email).some(isFailedParseRow);
|
||||
const emailIsCompleted = (email: ShippingOrderExtractionFileState) => {
|
||||
const children = childRows(email);
|
||||
return children.length > 0 && children.every((child) => child.status === 'candidate_ready');
|
||||
};
|
||||
const candidateEmailUnitIds = computed(() => new Set(
|
||||
candidateEmailGroups.value.flatMap((group) => [group.parent.unitId, ...group.children.map((child) => child.unitId)]),
|
||||
));
|
||||
const candidateStandaloneRows = computed(() => fileRows.value.filter((row) => (
|
||||
!isEmailRow(row)
|
||||
&& row.status === 'candidate_ready'
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const candidateFileCount = computed(() => (
|
||||
candidateEmailGroups.value.reduce((count, group) => count + group.children.length, 0)
|
||||
+ candidateStandaloneRows.value.length
|
||||
));
|
||||
const activeEmailRows = computed(() => emailRows.value.filter((row) => !candidateEmailUnitIds.value.has(row.unitId)));
|
||||
const standaloneRows = computed(() => fileRows.value.filter((row) => (
|
||||
!isEmailRow(row)
|
||||
&& row.status !== 'candidate_ready'
|
||||
&& !isFailedParseRow(row)
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const failedRows = computed(() => fileRows.value.filter((row) => (
|
||||
isFailedParseRow(row)
|
||||
&& !candidateEmailUnitIds.value.has(row.unitId)
|
||||
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
|
||||
)));
|
||||
const processedCount = computed(() => emlAggregate.value?.aggregateSummary?.completed
|
||||
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments));
|
||||
const progressPercent = computed(() => {
|
||||
const total = Math.max(0, props.state.summary.totalDocuments);
|
||||
return total > 0 ? Math.min(100, Math.round((processedCount.value / total) * 100)) : 0;
|
||||
});
|
||||
const completedExpanded = ref(false);
|
||||
|
||||
/**
|
||||
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
|
||||
@@ -83,26 +347,20 @@ const isCandidateConfirmationNotice = computed(() => (
|
||||
)
|
||||
));
|
||||
|
||||
const toneClass = computed(() => {
|
||||
if (isDuplicateOnlyNotice.value) {
|
||||
return 'border-violet-200 bg-violet-50/80 text-violet-950 dark:border-violet-800 dark:bg-violet-950/35 dark:text-violet-100';
|
||||
}
|
||||
if (isCandidateConfirmationNotice.value) {
|
||||
return 'border-teal-200 bg-teal-50/80 text-teal-950 dark:border-teal-800 dark:bg-teal-950/35 dark:text-teal-100';
|
||||
}
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return 'border-emerald-200 bg-emerald-50/80 text-emerald-950 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100';
|
||||
case 'partially_completed':
|
||||
case 'review_required':
|
||||
return 'border-amber-200 bg-amber-50/80 text-amber-950 dark:border-amber-800 dark:bg-amber-950/35 dark:text-amber-100';
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
return 'border-rose-200 bg-rose-50/80 text-rose-900 dark:border-rose-800 dark:bg-rose-950/35 dark:text-rose-100';
|
||||
default:
|
||||
return 'border-sky-200 bg-sky-50/80 text-sky-900 dark:border-sky-800 dark:bg-sky-950/35 dark:text-sky-100';
|
||||
}
|
||||
});
|
||||
function rowStatusLabel(row: ShippingOrderExtractionFileState): string {
|
||||
if (row.status === 'candidate_ready') return t('chat.shippingProcessing.candidateReady');
|
||||
if (isFailedParseRow(row)) return t('chat.shippingProcessing.batchException');
|
||||
if (row.status === 'review_required') return t('chat.shippingProcessing.waitingReview');
|
||||
const stageKey = `chat.shippingOrderExtractionUserStage.${String(row.userVisibleStage || '').trim()}`;
|
||||
if (row.userVisibleStage && te(stageKey)) return t(stageKey);
|
||||
return t('chat.shippingProcessing.batchProcessing');
|
||||
}
|
||||
|
||||
function rowStatusClass(row: ShippingOrderExtractionFileState): string {
|
||||
if (row.status === 'candidate_ready') return 'text-emerald-500';
|
||||
if (isFailedParseRow(row)) return 'text-rose-500';
|
||||
return 'text-blue-500';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将处理事项类别映射为一句过程通知文案。
|
||||
@@ -126,6 +384,13 @@ function handlingTitle(item: ShippingOrderExtractionHandlingItemState): string {
|
||||
* 状态短句:排队/处理中仅「系统处理中」;其余用过程通知,不含文件阶段耗时。
|
||||
*/
|
||||
const statusNotice = computed(() => {
|
||||
if (emlAggregate.value) {
|
||||
const status = String(emlAggregate.value.userStatus || '').trim().toLowerCase();
|
||||
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
|
||||
if (status === 'failed' || status === 'retryable') return t('chat.shippingSessionSummary.processNoticeFailed');
|
||||
if (status === 'waiting_human') return t('chat.shippingSessionSummary.processNoticeNeedsAction');
|
||||
return t('chat.shippingProcessing.systemProcessing');
|
||||
}
|
||||
if (props.state.cancellation?.requested && !props.state.cancellation?.completedAt && !props.state.terminal) {
|
||||
return t('chat.shippingOrderExtractionUserStage.cancellation_requested');
|
||||
}
|
||||
@@ -261,7 +526,7 @@ async function loadDetailsDocuments() {
|
||||
detailsLoading.value = true;
|
||||
detailsLoadFailed.value = false;
|
||||
try {
|
||||
const docsRes = await listWorkspaceShippingOrderExtractionDocuments(runNo).catch(() => null);
|
||||
const docsRes = await listWorkspaceShippingOrderExtractionDocuments(runNo, props.state.uploadBatchId).catch(() => null);
|
||||
if (docsRes) {
|
||||
detailsDocuments.value = Array.isArray(docsRes.items) ? docsRes.items : [];
|
||||
} else {
|
||||
@@ -286,7 +551,7 @@ async function loadDetailsProgress() {
|
||||
progressLoading.value = true;
|
||||
progressLoadFailed.value = false;
|
||||
try {
|
||||
const eventsRes = await listWorkspaceShippingOrderExtractionProgressEvents(runNo).catch(() => null);
|
||||
const eventsRes = await listWorkspaceShippingOrderExtractionProgressEvents(runNo, props.state.uploadBatchId).catch(() => null);
|
||||
if (eventsRes) {
|
||||
progressEvents.value = Array.isArray(eventsRes.items) ? eventsRes.items : [];
|
||||
} else {
|
||||
@@ -347,25 +612,126 @@ async function onPrimaryChatAction() {
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="mb-3 rounded-lg border px-3.5 py-2.5"
|
||||
:class="toneClass"
|
||||
class="mb-3 overflow-hidden rounded-xl border border-slate-200 bg-white/90 text-slate-900 shadow-md backdrop-blur-sm dark:border-slate-700 dark:bg-slate-900/90 dark:text-slate-100"
|
||||
data-testid="shipping-order-extraction-card"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<LoaderCircle
|
||||
v-if="state.status === 'queued' || state.status === 'processing'"
|
||||
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck
|
||||
v-else-if="state.status === 'completed' || isDuplicateOnlyNotice || isCandidateConfirmationNotice"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<TriangleAlert
|
||||
v-else-if="state.status === 'partially_completed' || state.status === 'review_required'"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 text-lg font-semibold">
|
||||
<LoaderCircle v-if="emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
|
||||
<CheckCircle2 v-else-if="emlAggregate ? emlAggregate.userStatus === 'completed' && emlAggregate.facts?.uploadState === 'succeeded' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
|
||||
<TriangleAlert v-else class="h-5 w-5 text-amber-500" />
|
||||
<span>{{ t('chat.shippingProcessing.multiPdfTaskTitle') }}</span>
|
||||
</div>
|
||||
<span class="rounded-full bg-slate-200 px-3 py-1 text-xs font-medium text-slate-600 dark:bg-slate-700 dark:text-slate-200">
|
||||
{{ t('chat.shippingProcessing.batchFilesTotal', { count: emlAggregate?.sourceSummary.documentCount ?? state.summary.totalDocuments }) }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.batchStatusTitle') }} · {{ statusNotice }}</p>
|
||||
<div v-for="tip in healthTips" :key="tip.code" class="mt-1 text-sm font-medium text-amber-600">{{ t(`chat.shippingOrderExtractionHealthTip.${tip.code}`) }}</div>
|
||||
<div v-if="handlingSummaryLine" class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ handlingSummaryLine }}</div>
|
||||
<div class="mt-4 flex items-end justify-between">
|
||||
<span class="text-lg font-medium text-blue-600">{{ progressPercent }}% {{ t('chat.shippingProcessing.batchComplete') }}</span>
|
||||
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ emlAggregate?.sourceSummary.documentCount ?? state.summary.totalDocuments }} {{ t('chat.shippingProcessing.batchProcessed') }}</span>
|
||||
</div>
|
||||
<div class="mt-3 h-2 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700">
|
||||
<div class="h-full rounded-full bg-blue-600 transition-all" :style="{ width: `${progressPercent}%` }" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasConversationStatusGroups" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
|
||||
<template v-for="group in statusGroupDefs" :key="group.key">
|
||||
<section v-if="statusGroupTasks(group.key).length" class="overflow-hidden rounded-lg border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
|
||||
<button type="button" class="flex w-full items-center justify-between px-3 py-3 text-left" @click="toggleStatusGroup(group.key)">
|
||||
<span class="text-sm font-semibold" :class="group.key === 'failed' ? 'text-rose-600' : group.key === 'waiting_human' ? 'text-amber-700' : group.key === 'completed' ? 'text-emerald-600' : 'text-slate-700 dark:text-slate-200'">{{ statusGroupLabel(group.key) }}</span>
|
||||
<ChevronDown class="h-4 w-4 transition-transform" :class="expandedStatusGroups.has(group.key) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="expandedStatusGroups.has(group.key)" class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-700">
|
||||
<article v-for="task in statusGroupTasks(group.key)" :key="task.user_task_no" class="rounded-lg border border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-950/30" :data-testid="`shipping-order-extraction-eml-${group.key}-${task.user_task_no}`">
|
||||
<div class="flex items-start gap-2">
|
||||
<Mail class="mt-0.5 h-4 w-4 text-blue-600" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<button type="button" class="flex w-full items-center justify-between gap-2 text-left" @click="toggleEmlTask(task.user_task_no)">
|
||||
<span class="truncate text-sm font-medium">{{ statusTaskProjection(task)?.sourceSummary?.filename || task.title || task.user_task_no }}</span>
|
||||
<ChevronDown class="h-4 w-4 shrink-0 transition-transform" :class="expandedEmlTasks.has(task.user_task_no) ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div class="mt-1 text-xs text-slate-500">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
|
||||
<div v-if="task.blockingReason?.code" class="mt-1 text-xs text-rose-600">{{ userReasonLabel(task.blockingReason.code) }}</div>
|
||||
<div v-if="expandedEmlTasks.has(task.user_task_no)" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
|
||||
<div v-for="child in taskChildren(task)" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-medium">{{ child.sourceSummary.filename || child.workItemNo }}</div>
|
||||
<div class="text-[11px] text-slate-500">{{ childStageLabel(child) }}</div>
|
||||
<div v-if="child.blockingReason?.code || child.sourceSummary?.failureReasonCode" class="text-[11px] text-rose-600">{{ userReasonLabel(child.blockingReason?.code || child.sourceSummary?.failureReasonCode) }}</div>
|
||||
</div>
|
||||
<span class="shrink-0" :class="child.userStatus === 'failed' || child.userStatus === 'retryable' ? 'text-rose-600' : child.userStatus === 'waiting_human' ? 'text-amber-700' : child.userStatus === 'completed' && child.facts?.uploadState === 'succeeded' ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
<div v-else-if="emlAggregate" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
|
||||
<article class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
|
||||
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<span class="truncate font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ emlAggregate.sourceSummary.filename || emlAggregate.intakeNo }}</span>
|
||||
<span class="rounded border px-2 py-0.5 text-xs" :class="emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emlAggregate.userStatus === 'waiting_human' ? 'border-amber-200 bg-amber-100/70 text-amber-700' : emlAggregate.userStatus === 'completed' ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">
|
||||
{{ emlAggregate.userStatus === 'completed' ? t('chat.shippingProcessing.aggregate.completed', { count: emlAggregate.aggregateSummary?.completed || 0 }) : emlAggregate.userStatus === 'failed' || emlAggregate.userStatus === 'retryable' ? t('chat.shippingProcessing.batchException') : emlAggregate.userStatus === 'waiting_human' ? t('chat.shippingProcessing.waitingReview') : t('chat.shippingProcessing.systemProcessing') }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ aggregateSummaryLabel(emlAggregate) }}</div>
|
||||
<div v-if="emlAggregate.blockingReason?.code" class="mt-1 text-xs text-rose-600">{{ userReasonLabel(emlAggregate.blockingReason.code) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="flex w-full items-center justify-between px-3 py-2 text-left text-sm" @click="emlAggregateExpanded = !emlAggregateExpanded">
|
||||
<span>{{ t('chat.shippingProcessing.taskFiles', { count: emlAggregate.sourceSummary.documentCount || 0 }) }}</span>
|
||||
<ChevronDown class="h-4 w-4 transition-transform" :class="emlAggregateExpanded ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="emlAggregateExpanded" class="space-y-1 border-t border-slate-200 px-3 py-2 dark:border-slate-700">
|
||||
<div v-for="child in emlAggregateChildren" :key="child.workItemNo" class="flex items-center justify-between gap-3 py-1 text-sm">
|
||||
<span class="min-w-0 truncate">{{ child.sourceSummary.filename || child.workItemNo }}</span>
|
||||
<span class="shrink-0 text-xs" :class="child.userStatus === 'failed' || child.userStatus === 'retryable' ? 'text-rose-600' : child.userStatus === 'waiting_human' ? 'text-amber-700' : child.userStatus === 'completed' && child.facts?.uploadState === 'succeeded' ? 'text-emerald-600' : 'text-blue-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div v-else class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
|
||||
<button type="button" class="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-3 text-left dark:border-slate-700 dark:bg-slate-900" @click="completedExpanded = !completedExpanded">
|
||||
<span class="flex items-center gap-3 text-base font-medium"><span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-100 text-blue-600"><CheckCircle2 class="h-4 w-4" /></span>{{ t('chat.shippingProcessing.candidateFiles', { count: candidateFileCount }) }}</span>
|
||||
<ChevronDown class="h-5 w-5 transition-transform" :class="completedExpanded ? 'rotate-180' : ''" />
|
||||
</button>
|
||||
<div v-if="completedExpanded && candidateFileCount" class="space-y-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div v-for="group in candidateEmailGroups" :key="`candidate-email-${group.parent.unitId}`" class="rounded-md border border-blue-100 bg-blue-50/50 px-3 py-2 dark:border-blue-900 dark:bg-blue-950/20">
|
||||
<div class="flex items-center gap-2 font-medium text-slate-700 dark:text-slate-200"><Mail class="h-4 w-4 text-blue-600" />{{ t('chat.shippingProcessing.emailPrefix') }}{{ group.parent.fileName }}<span class="ml-auto text-emerald-500">{{ t('chat.shippingProcessing.batchExtracted') }}</span></div>
|
||||
<div class="mt-1 space-y-1 border-l-2 border-blue-200 pl-3 dark:border-blue-800">
|
||||
<div v-for="row in group.children" :key="`candidate-child-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-for="row in candidateStandaloneRows" :key="`candidate-${row.unitId}`" class="flex items-center gap-2 py-1 text-slate-600 dark:text-slate-300"><CheckCircle2 class="h-4 w-4 text-blue-500" />{{ row.fileName }}<span class="ml-auto text-blue-500">{{ rowStatusLabel(row) }}</span></div>
|
||||
</div>
|
||||
<div v-for="row in activeEmailRows" :key="row.unitId" class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20"><Mail class="mt-0.5 h-5 w-5 text-blue-600" /><div class="min-w-0 flex-1"><div class="flex items-center justify-between gap-3"><span class="font-medium">{{ t('chat.shippingProcessing.emailPrefix') }}{{ row.fileName }}</span><span class="rounded border px-2 py-0.5 text-xs" :class="isFailedParseRow(row) || emailHasFailedChild(row) ? 'border-rose-200 bg-rose-100/70 text-rose-600' : emailIsCompleted(row) ? 'border-emerald-200 bg-emerald-100/70 text-emerald-600' : 'border-blue-200 bg-blue-100/70 text-blue-600'">{{ isFailedParseRow(row) || emailHasFailedChild(row) ? t('chat.shippingProcessing.batchException') : emailIsCompleted(row) ? t('chat.shippingProcessing.batchExtracted') : t('chat.shippingProcessing.parsingAttachments') }}</span></div><span class="mt-1 block font-mono text-xs text-slate-500">{{ t('chat.shippingProcessing.emailMeta') }}</span></div></div>
|
||||
<div class="mx-4 my-2 flex flex-col gap-2 border-l-2 border-blue-200 bg-slate-50 p-3 pl-4 dark:border-blue-800 dark:bg-blue-950/30"><div v-for="child in childRows(row)" :key="`child-${child.unitId}`" class="flex items-center justify-between gap-3 text-sm"><span class="flex min-w-0 items-center gap-2"><CheckCircle2 v-if="child.status === 'candidate_ready'" class="h-4 w-4 text-emerald-500" /><LoaderCircle v-else-if="!isFailedParseRow(child)" class="h-4 w-4 animate-spin text-blue-500" /><AlertCircle v-else class="h-4 w-4 text-rose-500" /><span class="truncate">{{ child.fileName }}</span></span><span :class="rowStatusClass(child)">{{ rowStatusLabel(child) }}</span></div></div>
|
||||
</div>
|
||||
<div v-for="row in standaloneRows" :key="row.unitId" class="flex items-center justify-between gap-3 rounded-lg border border-slate-200 bg-white p-3 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900"><span class="flex min-w-0 items-center gap-3"><FileText class="h-5 w-5 text-slate-500" /><span class="truncate">{{ row.fileName }}</span></span><span class="flex items-center gap-2" :class="rowStatusClass(row)">{{ rowStatusLabel(row) }}<RefreshCw v-if="!isFailedParseRow(row)" class="h-4 w-4 animate-spin" /></span></div>
|
||||
<div v-if="!fileRows.length" class="rounded-lg border border-slate-200 bg-white p-3 text-sm text-slate-500 dark:border-slate-700 dark:bg-slate-900">{{ t('chat.shippingProcessing.batchFilesUnavailable') }}</div>
|
||||
<div v-for="row in failedRows" :key="`failed-${row.unitId}`" class="rounded-lg border border-rose-200 bg-rose-50 p-3 dark:border-rose-800 dark:bg-rose-950/30"><div class="flex items-center justify-between text-rose-600"><span class="flex items-center gap-2 font-medium"><AlertCircle class="h-5 w-5" />{{ row.fileName }}</span><span class="rounded bg-rose-100 px-2 py-0.5 text-xs">{{ t('chat.shippingProcessing.batchException') }}</span></div><p class="mt-2 pl-7 text-sm">{{ row.explainability?.message || t('chat.shippingProcessing.batchManualVerify') }}</p></div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end border-t border-slate-200 bg-indigo-50/60 p-3 dark:border-slate-700 dark:bg-indigo-950/20">
|
||||
<div class="flex items-center gap-3">
|
||||
<button v-if="primaryChatAction" type="button" class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 disabled:opacity-50" data-testid="shipping-order-extraction-primary-action" :disabled="primaryChatAction.kind === 'retry' && retrying" @click="onPrimaryChatAction">{{ primaryChatAction.kind === 'retry' && retrying ? t('chat.shippingOrderExtractionRetrying') : primaryChatAction.label }}<ArrowRight class="h-4 w-4" /></button>
|
||||
<button v-if="String(props.runNo || '').trim()" type="button" class="text-sm font-medium text-blue-600 underline-offset-2 hover:underline" data-testid="shipping-order-extraction-view-details" @click="openDetailsDrawer">{{ t('chat.shippingProcessing.viewTaskDetails') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="false" class="flex items-start gap-3">
|
||||
<CircleX class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div
|
||||
v-if="readonly"
|
||||
@@ -394,7 +760,7 @@ async function onPrimaryChatAction() {
|
||||
class="mt-1 text-[11px] opacity-80"
|
||||
data-testid="shipping-order-extraction-error-request-id"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability.request_id }) }}
|
||||
{{ t('chat.shippingOrderExtractionErrorRequestId', { id: state.errorExplainability?.request_id }) }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
@@ -424,12 +790,12 @@ async function onPrimaryChatAction() {
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
data-testid="shipping-order-extraction-primary-action"
|
||||
:disabled="primaryChatAction.kind === 'retry' && retrying"
|
||||
:disabled="primaryChatAction?.kind === 'retry' && retrying"
|
||||
@click="onPrimaryChatAction"
|
||||
>
|
||||
{{ primaryChatAction.kind === 'retry' && retrying
|
||||
{{ primaryChatAction?.kind === 'retry' && retrying
|
||||
? t('chat.shippingOrderExtractionRetrying')
|
||||
: primaryChatAction.label }}
|
||||
: primaryChatAction?.label }}
|
||||
</button>
|
||||
<button
|
||||
v-if="String(props.runNo || '').trim()"
|
||||
|
||||
+26
-23
@@ -7,7 +7,7 @@
|
||||
* 以模态对话框语义呈现(初始焦点、Tab 陷阱、Escape/关闭后焦点恢复);
|
||||
* 文档与时间线加载失败分别提供就地重试;内部错误码不向普通用户展示。
|
||||
*/
|
||||
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { X } from 'lucide-vue-next';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
@@ -42,6 +42,19 @@ const closeButtonRef = ref<HTMLButtonElement | null>(null);
|
||||
let previouslyFocused: HTMLElement | null = null;
|
||||
const timelineOpen = ref(false);
|
||||
|
||||
const timelineGroups = computed(() => {
|
||||
const groups = new Map<string, { documentId: number | null; fileName: string; events: ShippingOrderExtractionProgressEvent[] }>();
|
||||
for (const event of props.progressEvents) {
|
||||
const documentId = event.document_id != null ? Number(event.document_id) : null;
|
||||
const document = documentId == null ? null : props.documents.find((item) => Number(item.document_id) === documentId);
|
||||
const key = documentId == null ? 'run' : `document-${documentId}`;
|
||||
const group = groups.get(key) || { documentId, fileName: document?.file_name || (documentId == null ? t('chat.shippingOrderExtractionTimelineRunScope') : `Document ${documentId}`), events: [] };
|
||||
group.events.push(event);
|
||||
groups.set(key, group);
|
||||
}
|
||||
return [...groups.values()];
|
||||
});
|
||||
|
||||
const FOCUSABLE_SELECTOR = [
|
||||
'a[href]',
|
||||
'button:not([disabled])',
|
||||
@@ -314,28 +327,18 @@ onBeforeUnmount(() => {
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionTimelineEmpty') }}
|
||||
</div>
|
||||
<ol v-else class="mt-3 space-y-3">
|
||||
<li
|
||||
v-for="event in progressEvents"
|
||||
:key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`"
|
||||
class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">
|
||||
{{ t(eventCategoryKey(event)) }}
|
||||
</span>
|
||||
<div class="font-medium text-slate-900 dark:text-slate-100">
|
||||
{{ eventActivityLabel(event) }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">
|
||||
{{ eventContextLabel(event) }}
|
||||
</div>
|
||||
<div class="mt-1 opacity-70">
|
||||
{{ eventOccurredAtLabel(event.occurred_at) }}
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<div v-else class="mt-3 space-y-3">
|
||||
<section v-for="group in timelineGroups" :key="group.documentId == null ? 'run' : group.documentId" class="rounded-md border border-slate-200 px-3 py-2 dark:border-slate-700">
|
||||
<h4 class="text-xs font-semibold text-slate-900 dark:text-slate-100">{{ group.fileName }}</h4>
|
||||
<ol class="mt-2 space-y-3">
|
||||
<li v-for="event in group.events" :key="`${event.event_code}-${event.unit_id || 0}-${event.document_id || 0}-${event.occurred_at}`" class="border-l-2 border-slate-200 pl-3 text-xs text-slate-700 dark:border-slate-700 dark:text-slate-200">
|
||||
<div class="flex flex-wrap items-center gap-2"><span class="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-200">{{ t(eventCategoryKey(event)) }}</span><div class="font-medium text-slate-900 dark:text-slate-100">{{ eventActivityLabel(event) }}</div></div>
|
||||
<div v-if="eventContextLabel(event)" class="mt-1 opacity-85">{{ eventContextLabel(event) }}</div>
|
||||
<div class="mt-1 opacity-70">{{ eventOccurredAtLabel(event.occurred_at) }}</div>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -330,7 +330,9 @@ async function onProcessingIntakeAction(payload: {
|
||||
action: string;
|
||||
}) {
|
||||
const action = String(payload.action || '').trim();
|
||||
const intakeNo = String(payload.item.workItemNo || payload.item.intakeNo || '').trim();
|
||||
// 聚合卡的 workItemNo 可能是 INTAKE:<no>,写接口必须使用规范化 intakeNo。
|
||||
const intakeNo = String(payload.item.intakeNo || '').trim()
|
||||
|| String(payload.item.workItemNo || '').replace(/^INTAKE:/i, '').trim();
|
||||
if (action === 'retry_parse') {
|
||||
if (!intakeNo) {
|
||||
msg.error(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
@@ -382,6 +384,49 @@ async function onProcessingTaskAction(payload: {
|
||||
await openReviewFromTask(task);
|
||||
return;
|
||||
}
|
||||
if (action === 'edit_draft' || action === 'create_draft' || action === 'reconcile_and_progress') {
|
||||
await openReviewFromTask(task);
|
||||
return;
|
||||
}
|
||||
if (action === 'reparse') {
|
||||
if (!runNo) {
|
||||
msg.warning(t('chat.shippingOrderReview.caseRequired'));
|
||||
return;
|
||||
}
|
||||
const target = items.value.find((item) => String(item.current_run_no || '').trim() === runNo);
|
||||
if (target) openReparseDialog(target);
|
||||
else msg.warning(t('chat.shippingOrderReview.caseRequired'));
|
||||
return;
|
||||
}
|
||||
if (action === 'retry_parse' || action === 'retry') {
|
||||
const intakeNo = String(task.user_task_no || '').replace(/^INTAKE:/i, '').trim();
|
||||
if (intakeNo.startsWith('SNI-')) {
|
||||
if (actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = intakeNo;
|
||||
try {
|
||||
await retryShippingNoticeIntake(intakeNo);
|
||||
await ctl.value.refresh();
|
||||
} catch (err) {
|
||||
msg.error(reparseErrorMessage(err));
|
||||
} finally {
|
||||
actionBusyItemNo.value = null;
|
||||
}
|
||||
} else if (runNo) {
|
||||
if (actionBusyItemNo.value) return;
|
||||
actionBusyItemNo.value = runNo;
|
||||
try {
|
||||
await retryWorkspaceShippingOrderExtractionRun(runNo);
|
||||
await ctl.value.refresh();
|
||||
} catch (err) {
|
||||
msg.error(reparseErrorMessage(err));
|
||||
} finally {
|
||||
actionBusyItemNo.value = null;
|
||||
}
|
||||
} else {
|
||||
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action === 'cancel_task' || action === 'cancel_run') {
|
||||
if (!runNo) {
|
||||
msg.error(t('chat.shippingProcessing.cancelTaskMissingRun'));
|
||||
@@ -554,6 +599,14 @@ async function onTaskProjectionAction(payload: {
|
||||
const { projection, item } = payload;
|
||||
const taskNo = String(projection.workItemNo || '').trim();
|
||||
const code = String(item.actionCode || '').trim();
|
||||
if (code === 'reparse') {
|
||||
const task = [
|
||||
...(displayProcessing.value?.needs_action || []),
|
||||
...(displayProcessing.value?.processing || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) void onProcessingTaskAction({ task, action: 'reparse' });
|
||||
return;
|
||||
}
|
||||
if (code === 'retry_parse' || item.intent === 'retry') {
|
||||
void onProcessingIntakeAction({ item: projection, action: code || 'retry_parse' });
|
||||
return;
|
||||
@@ -569,7 +622,7 @@ async function onTaskProjectionAction(payload: {
|
||||
...(displayProcessing.value?.completed || []),
|
||||
].find((row) => String(row.user_task_no || '').trim() === taskNo);
|
||||
if (task) {
|
||||
void onProcessingTaskAction({ task, action: 'open_review' });
|
||||
void onProcessingTaskAction({ task, action: code || 'open_review' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -185,6 +185,7 @@ const normalizeShippingOrderExtractionState = (
|
||||
: null;
|
||||
return {
|
||||
status: status as ShippingOrderExtractionState['status'],
|
||||
uploadBatchId: String(data.uploadBatchId || '').trim() || null,
|
||||
summary: {
|
||||
totalDocuments: Math.max(0, Number(rawSummary.totalDocuments || 0)),
|
||||
pendingDocuments: Math.max(0, Number(rawSummary.pendingDocuments || 0)),
|
||||
@@ -207,6 +208,27 @@ const normalizeShippingOrderExtractionState = (
|
||||
: [],
|
||||
}
|
||||
: null,
|
||||
documents: Array.isArray(data.documents)
|
||||
? data.documents.map((item) => {
|
||||
const row = item && typeof item === 'object' ? item as Record<string, unknown> : {};
|
||||
return {
|
||||
unitId: Math.max(0, Number(row.unitId || 0)),
|
||||
documentId: Math.max(0, Number(row.documentId || 0)),
|
||||
intakeId: row.intakeId != null ? Math.max(0, Number(row.intakeId || 0)) || null : null,
|
||||
documentType: String(row.documentType || '').trim() || null,
|
||||
fileName: String(row.fileName || '').trim() || null,
|
||||
status: String(row.status || '').trim(),
|
||||
userVisibleStage: String(row.userVisibleStage || '').trim() || null,
|
||||
reasonCode: String(row.reasonCode || '').trim() || null,
|
||||
explainability: row.explainability && typeof row.explainability === 'object'
|
||||
? row.explainability as { message?: string | null }
|
||||
: null,
|
||||
emailSupplement: row.emailSupplement && typeof row.emailSupplement === 'object'
|
||||
? row.emailSupplement as { status?: string | null }
|
||||
: null,
|
||||
};
|
||||
})
|
||||
: [],
|
||||
selectionPlan: rawSelectionPlan
|
||||
? {
|
||||
selectionVersion: String(rawSelectionPlan.selectionVersion || '').trim() || null,
|
||||
|
||||
@@ -613,6 +613,94 @@ describe('conversationProcessingProjection', () => {
|
||||
expect(projection?.summary.total_files).toBe(1);
|
||||
});
|
||||
|
||||
it('aggregates mixed order tasks from one EML intake into one card', () => {
|
||||
const base = {
|
||||
sourceType: 'eml' as const,
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-eml',
|
||||
submissionNo: 'SOS-EML',
|
||||
intakeNo: 'INTAKE-EML-1',
|
||||
progressVersion: 1,
|
||||
currentGate: null,
|
||||
childOrderTasks: [],
|
||||
};
|
||||
const items: ShippingProcessingProjection[] = [
|
||||
{
|
||||
...base, workItemType: 'order_task', workItemNo: 'OT-DONE', status: 'completed', stage: 'completed',
|
||||
userStatus: 'completed', userStage: 'completed', lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
|
||||
sourceSummary: { emailSubject: 'Shipment', filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
},
|
||||
{
|
||||
...base, workItemType: 'order_task', workItemNo: 'OT-RUN', status: 'processing', stage: 'inventory_matching',
|
||||
userStatus: 'running', userStage: 'inventory_match', lastActivityAt: '2026-08-06T00:00:01Z', availableActions: [],
|
||||
sourceSummary: { emailSubject: 'Shipment', filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
},
|
||||
{
|
||||
...base, workItemType: 'order_task', workItemNo: 'OT-FAIL', status: 'failed', stage: 'freight_uploading',
|
||||
userStatus: 'failed', userStage: 'freight_upload', lastActivityAt: '2026-08-06T00:00:02Z', availableActions: [],
|
||||
blockingReason: { code: 'upload_rpa_failed' },
|
||||
sourceSummary: { emailSubject: 'Shipment', filename: 'c.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
|
||||
},
|
||||
];
|
||||
const projection = projectConversationProcessingFromWorkItems(items);
|
||||
expect(projection?.needs_action).toHaveLength(1);
|
||||
expect(projection?.processing).toHaveLength(0);
|
||||
expect(projection?.completed).toHaveLength(0);
|
||||
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
|
||||
intakeNo: 'INTAKE-EML-1', total: 3, completed: 1, processing: 1, needsAction: 1, failed: 1,
|
||||
}));
|
||||
expect(projection?.needs_action[0]?.file_count).toBe(3);
|
||||
expect(projection?.needs_action[0]?.aggregateSummary?.reasonCodes).toContain('upload_rpa_failed');
|
||||
});
|
||||
|
||||
it('does not reuse an empty EML task when a later poll returns aggregate children', () => {
|
||||
const base = {
|
||||
workItemType: 'order_task' as const, sourceType: 'eml' as const, rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null, conversationId: 'conv-stable', submissionNo: 'SOS-1', intakeNo: 'SNI-STABLE',
|
||||
progressVersion: 1, currentGate: null, availableActions: [], status: 'processing' as const,
|
||||
stage: 'document_parsing' as const, userStatus: 'running' as const, userStage: 'document_parsing' as const,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
sourceSummary: { emailSubject: 'mail', filename: 'stable.eml', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null },
|
||||
};
|
||||
const first = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [] }]);
|
||||
const child = { ...base, workItemNo: 'OT-CHILD', sourceSummary: { ...base.sourceSummary, filename: 'attachment.pdf' } };
|
||||
const second = projectConversationProcessingFromWorkItems([{ ...base, workItemNo: 'INTAKE:SNI-STABLE', aggregateSummary: { intakeNo: 'SNI-STABLE', total: 1, completed: 0, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, aggregateChildren: [child] }], first);
|
||||
expect(second?.processing[0]?.aggregateChildren?.map((item) => item.sourceSummary.filename)).toEqual(['attachment.pdf']);
|
||||
expect(second?.processing[0]).not.toBe(first?.processing[0]);
|
||||
});
|
||||
|
||||
it('puts an EML with review-required children into needs_action even when parent says processing', () => {
|
||||
const parent = {
|
||||
workItemType: 'order_task' as const, workItemNo: 'INTAKE:SNI-STATUS', sourceType: 'eml' as const,
|
||||
rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS',
|
||||
status: 'processing' as const, stage: 'document_parsing' as const, userStatus: 'running' as const, userGroup: 'processing' as const,
|
||||
userStage: 'document_parsing' as const, progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
|
||||
sourceSummary: { emailSubject: null, filename: 'mail.eml', documentCount: 2, parsedDocumentCount: 2, candidateCount: 0, customerName: null, poNumber: null },
|
||||
aggregateChildren: [
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'review_required', stage: 'review_required', userStatus: 'waiting_human', userStage: 'review_required', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
|
||||
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', rootOrderTaskNo: null, shippingNoticeNo: null, conversationId: 'conv-status', submissionNo: 'SOS-1', intakeNo: 'SNI-STATUS', status: 'processing', stage: 'document_parsing', userStatus: 'running', userStage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [], sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 0, customerName: null, poNumber: null }, childOrderTasks: [], facts: { uploadState: 'not_created' } },
|
||||
],
|
||||
} as any;
|
||||
const projection = projectConversationProcessingFromWorkItems([parent]);
|
||||
expect(projection?.needs_action).toHaveLength(1);
|
||||
expect(projection?.processing).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not aggregate direct PDFs with matching intake numbers', () => {
|
||||
const common = {
|
||||
workItemType: 'order_task' as const, rootOrderTaskNo: null, shippingNoticeNo: null,
|
||||
conversationId: 'conv-pdf', submissionNo: 'SOS-PDF', intakeNo: 'INTAKE-SAME', progressVersion: 1,
|
||||
currentGate: null, childOrderTasks: [], status: 'processing' as const, stage: 'document_parsing' as const,
|
||||
userStatus: 'running' as const, userStage: 'document_parsing' as const, lastActivityAt: '2026-08-06T00:00:00Z', availableActions: [],
|
||||
};
|
||||
const projection = projectConversationProcessingFromWorkItems([
|
||||
{ ...common, workItemNo: 'OT-1', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'a.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
|
||||
{ ...common, workItemNo: 'OT-2', sourceType: 'direct_pdf', sourceSummary: { emailSubject: null, filename: 'b.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null } },
|
||||
]);
|
||||
expect(projection?.processing).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
|
||||
const workItems: ShippingProcessingProjection[] = [
|
||||
{
|
||||
@@ -693,7 +781,10 @@ describe('conversationProcessingProjection', () => {
|
||||
const projection = resolveConversationProcessingFromUnified(workItems, embedded);
|
||||
// 关键断言:兄弟 OT 仅出现在 work_items;embedded 缺 sibling 时不得覆盖任务列表。
|
||||
expect(projection?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
|
||||
expect(projection?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
|
||||
expect(projection?.processing).toEqual([]);
|
||||
expect(projection?.needs_action[0]?.aggregateSummary).toEqual(expect.objectContaining({
|
||||
intakeNo: 'SNI-1', total: 2, completed: 0, processing: 1, needsAction: 1,
|
||||
}));
|
||||
expect(projection?.focused_task_no).toBe('OT-ROOT');
|
||||
expect(projection?.recent_task_no).toBe('OT-SIBLING');
|
||||
});
|
||||
@@ -1006,7 +1097,7 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
expect(result!.needs_action[0]!.title).toBe('b.pdf');
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified: work_items 仅含 order_intake 时,仍走 embedded normalize 路径(过渡窗口不跳状态)', () => {
|
||||
it('resolveConversationProcessingFromUnified: 仅含 EML order_intake 时,派生统一 processing 投影而非回退 embedded', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
focused_task_no: 'OT-LEG3',
|
||||
@@ -1035,7 +1126,7 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
sourceType: 'eml',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
@@ -1061,13 +1152,16 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
];
|
||||
const result = resolveConversationProcessingFromUnified(workItems, embedded);
|
||||
expect(result).not.toBeNull();
|
||||
// 过渡阶段:order_intake 不触发统一投影派生;embedded waiting_human 必须 normalize 成 waiting_review/needs_action
|
||||
// EML 尚未创建 OT 时,也必须作为一张 EML 卡进入统一“系统处理中”区。
|
||||
expect(result!.focused_task_no).toBe('OT-LEG3');
|
||||
expect(result!.processing.length).toBe(0);
|
||||
expect(result!.needs_action.length).toBe(1);
|
||||
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
expect(result!.needs_action[0]!.title).toBe('c.pdf');
|
||||
expect(result!.needs_action[0]!.group).toBe('needs_action');
|
||||
expect(result!.needs_action).toHaveLength(0);
|
||||
expect(result!.processing).toHaveLength(1);
|
||||
expect(result!.processing[0]).toMatchObject({
|
||||
user_task_no: 'SNI-1',
|
||||
title: 'c.pdf',
|
||||
group: 'processing',
|
||||
status_label: 'processing',
|
||||
});
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified + IntakeOtStabilizer: 看到 order_task 后 2s 内暂缺 OT 保持 previousProjection(避免轮询抖动)', () => {
|
||||
|
||||
@@ -50,6 +50,15 @@ export function buildTaskSemanticKey(
|
||||
): string {
|
||||
if (!task) return '';
|
||||
const rawStatus = (task as ConversationProcessingUserTask & { userStatus?: string | null }).userStatus ?? task.status_label;
|
||||
const aggregateChildren = (task.aggregateChildren || []).map((child) => ({
|
||||
workItemNo: child.workItemNo,
|
||||
intakeNo: child.intakeNo,
|
||||
status: child.userStatus ?? child.status,
|
||||
stage: child.userStage ?? child.stage,
|
||||
uploadState: child.facts?.uploadState ?? null,
|
||||
filename: child.sourceSummary?.filename ?? null,
|
||||
reason: child.blockingReason?.code ?? child.sourceSummary?.failureReasonCode ?? null,
|
||||
}));
|
||||
return JSON.stringify({
|
||||
taskNo: task.user_task_no,
|
||||
group: task.group,
|
||||
@@ -83,6 +92,7 @@ export function buildTaskSemanticKey(
|
||||
: null,
|
||||
availableActions: normalizeActionCodes(task.available_actions || []),
|
||||
canAppend: task.can_append ?? null,
|
||||
aggregateChildren,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -791,7 +801,22 @@ export function groupConversationProcessingTasks(
|
||||
export function mapShippingProcessingStatusToTaskGroup(
|
||||
item: ShippingProcessingProjection,
|
||||
): ConversationProcessingTaskGroup {
|
||||
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
|
||||
const userGroup = String(item.userGroup || '').trim().toLowerCase();
|
||||
const status = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim());
|
||||
const childStatuses = (item.aggregateChildren || []).map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
|
||||
const childHasFailure = childStatuses.some((value) => value === 'failed');
|
||||
const childNeedsHuman = childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready');
|
||||
const childAllUploaded = childStatuses.length > 0
|
||||
&& childStatuses.every((value, index) => value === 'completed' && item.aggregateChildren?.[index]?.facts?.uploadState === 'succeeded');
|
||||
if (childHasFailure) return 'needs_action';
|
||||
if (childNeedsHuman) return 'needs_action';
|
||||
if (childAllUploaded) return 'completed';
|
||||
// 子项真实状态优先于父级 userGroup,避免 review_required/failed 被旧 processing 覆盖。
|
||||
if (status === 'failed' || status === 'waiting_review' || status === 'manual_upload_pending') return 'needs_action';
|
||||
if (userGroup === 'failed' || userGroup === 'waiting_human') return 'needs_action';
|
||||
if (userGroup === 'completed') return 'completed';
|
||||
if (userGroup === 'cancelled' || userGroup === 'archived') return 'history';
|
||||
if (userGroup === 'processing') return 'processing';
|
||||
const gateAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase();
|
||||
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
|
||||
.map((value) => String(value || '').trim().toLowerCase())
|
||||
@@ -859,7 +884,10 @@ export function resolveConversationProcessingFromUnified(
|
||||
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
|
||||
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
|
||||
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
|
||||
const hasOrderTask = items.some((item) => item.workItemType === 'order_task');
|
||||
const hasOrderTask = items.some((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
|| (item.workItemType === 'order_intake' && item.sourceType === 'eml')
|
||||
));
|
||||
const convId = stabilizer?.conversationId;
|
||||
if (hasOrderTask) {
|
||||
stabilizer?.markSeen?.(convId);
|
||||
@@ -945,24 +973,27 @@ export function normalizeConversationProcessingProjection(
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(order_task 与 EML order_intake)。
|
||||
*
|
||||
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组;
|
||||
* 核心逻辑:order_task 与 EML order_intake 均进入状态区;非 EML intake 不入组;
|
||||
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
|
||||
*
|
||||
* @param workItems - 统一投影 work_items
|
||||
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
|
||||
* @returns 兼容投影;无 order_task 时返回 null
|
||||
* @returns 兼容投影;无可展示任务时返回 null
|
||||
*/
|
||||
export function projectConversationProcessingFromWorkItems(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
): ConversationProcessingProjection | null {
|
||||
const items = Array.isArray(workItems) ? workItems : [];
|
||||
const orderTasks = items.filter((row) => row.workItemType === 'order_task');
|
||||
const orderTasks = items.filter((row) => (
|
||||
row.workItemType === 'order_task'
|
||||
|| (row.workItemType === 'order_intake' && row.sourceType === 'eml')
|
||||
));
|
||||
if (!orderTasks.length) return null;
|
||||
|
||||
const rawTasks: ConversationProcessingUserTask[] = [];
|
||||
const rawTaskEntries: Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }> = [];
|
||||
|
||||
for (const item of orderTasks) {
|
||||
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
|
||||
@@ -1019,15 +1050,111 @@ export function projectConversationProcessingFromWorkItems(
|
||||
available_actions: normalizedActions,
|
||||
primary_action: gateNextAction || normalizedActions[0] || null,
|
||||
userStatus: item.userStatus ?? null,
|
||||
userStage: item.userStage ?? null,
|
||||
blockingReason: userBlocking,
|
||||
primaryAction: userPrimaryAction,
|
||||
facts: userFacts,
|
||||
userGroup: item.userGroup ?? null,
|
||||
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
|
||||
userCurrentGateCode: item.userCurrentGateCode ?? null,
|
||||
legacyStatus: item.legacyStatus ?? null,
|
||||
legacyStage: item.legacyStage ?? null,
|
||||
aggregateSummary: item.aggregateSummary ?? null,
|
||||
aggregateChildren: item.aggregateChildren ?? [],
|
||||
};
|
||||
rawTasks.push(task);
|
||||
rawTaskEntries.push({ task, item });
|
||||
}
|
||||
|
||||
const rawTasks: ConversationProcessingUserTask[] = [];
|
||||
const emlGroups = new Map<string, Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }>>();
|
||||
for (const entry of rawTaskEntries) {
|
||||
if (entry.item.sourceType !== 'eml' || !entry.item.intakeNo) {
|
||||
rawTasks.push(entry.task);
|
||||
continue;
|
||||
}
|
||||
const key = String(entry.item.intakeNo).trim();
|
||||
const group = emlGroups.get(key) || [];
|
||||
group.push(entry);
|
||||
emlGroups.set(key, group);
|
||||
}
|
||||
for (const [intakeNo, entries] of emlGroups) {
|
||||
if (entries.length === 1) {
|
||||
rawTasks.push({
|
||||
...entries[0]!.task,
|
||||
aggregateChildren: entries[0]!.task.aggregateChildren?.length
|
||||
? entries[0]!.task.aggregateChildren
|
||||
: entries[0]!.item.aggregateChildren || [],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const completed = entries.filter(({ item }) => String(item.userStatus ?? item.status).toLowerCase() === 'completed').length;
|
||||
const failed = entries.filter(({ item }) => ['failed', 'retryable'].includes(String(item.userStatus ?? item.status).toLowerCase())).length;
|
||||
const needsAction = entries.filter(({ task }) => task.group === 'needs_action').length;
|
||||
const processing = entries.filter(({ task }) => task.group === 'processing').length;
|
||||
const stages = [...new Set(entries.flatMap(({ item }) => [item.userStage, item.stage].filter(Boolean).map(String)))];
|
||||
const reasonCodes = [...new Set(entries.flatMap(({ item }) => [
|
||||
item.blockingReason?.code,
|
||||
item.sourceSummary?.failureReasonCode,
|
||||
].filter(Boolean).map(String)))];
|
||||
const entryGroups = entries.map(({ task, item }) => {
|
||||
const children = item.aggregateChildren || [];
|
||||
const childStatuses = children.map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
|
||||
if (childStatuses.some((value) => value === 'failed')) return 'failed';
|
||||
if (childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready')) return 'waiting_human';
|
||||
if (childStatuses.length > 0 && childStatuses.every((value, index) => value === 'completed' && children[index]?.facts?.uploadState === 'succeeded')) return 'completed';
|
||||
const explicit = String(item.userGroup || '').trim().toLowerCase();
|
||||
if (explicit) return explicit;
|
||||
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
|
||||
if (status === 'failed' || status === 'retryable') return 'failed';
|
||||
if (task.group === 'needs_action') return 'waiting_human';
|
||||
if (task.group === 'completed' && status === 'completed') return 'completed';
|
||||
if (task.group === 'history') return status === 'cancelled' ? 'cancelled' : 'archived';
|
||||
return 'processing';
|
||||
});
|
||||
const aggregateUserGroup = entryGroups.includes('failed')
|
||||
? 'failed'
|
||||
: entryGroups.includes('waiting_human')
|
||||
? 'waiting_human'
|
||||
: entryGroups.includes('processing')
|
||||
? 'processing'
|
||||
: entryGroups.includes('completed') && entryGroups.every((value) => value === 'completed')
|
||||
? 'completed'
|
||||
: entryGroups.includes('cancelled')
|
||||
? 'cancelled'
|
||||
: entryGroups.includes('archived')
|
||||
? 'archived'
|
||||
: 'processing';
|
||||
const group = aggregateUserGroup === 'failed' || aggregateUserGroup === 'waiting_human'
|
||||
? 'needs_action'
|
||||
: aggregateUserGroup === 'completed'
|
||||
? 'completed'
|
||||
: aggregateUserGroup === 'cancelled' || aggregateUserGroup === 'archived'
|
||||
? 'history'
|
||||
: 'processing';
|
||||
const representative = entries[0]!.task;
|
||||
const documentNames = [...new Set(entries.flatMap(({ task }) => task.document_names || []).filter(Boolean))];
|
||||
const fileCount = entries.reduce((sum, { task }) => sum + Number(task.file_count || 0), 0);
|
||||
rawTasks.push({
|
||||
...representative,
|
||||
title: representative.title || `EML ${intakeNo}`,
|
||||
display_kind: fileCount > 1 ? 'multi_document_task' : representative.display_kind,
|
||||
document_names: documentNames,
|
||||
file_count: fileCount,
|
||||
group,
|
||||
available_actions: [...new Set(entries.flatMap(({ task }) => task.available_actions || []))].sort(),
|
||||
aggregateSummary: {
|
||||
intakeNo,
|
||||
total: entries.length,
|
||||
completed,
|
||||
processing,
|
||||
needsAction,
|
||||
failed,
|
||||
stages,
|
||||
reasonCodes,
|
||||
},
|
||||
aggregateChildren: entries.flatMap(({ item }) => item.aggregateChildren || [item]),
|
||||
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
|
||||
});
|
||||
}
|
||||
|
||||
if (!rawTasks.length) return null;
|
||||
@@ -1082,6 +1209,15 @@ export function projectConversationProcessingFromWorkItems(
|
||||
stabilizedAll.filter((t) => t.group === 'history'),
|
||||
);
|
||||
|
||||
const status_groups = {
|
||||
failed: stabilizedAll.filter((task) => task.userGroup === 'failed'),
|
||||
waiting_human: stabilizedAll.filter((task) => task.userGroup === 'waiting_human'),
|
||||
processing: stabilizedAll.filter((task) => task.userGroup === 'processing'),
|
||||
completed: stabilizedAll.filter((task) => task.userGroup === 'completed'),
|
||||
cancelled: stabilizedAll.filter((task) => task.userGroup === 'cancelled'),
|
||||
archived: stabilizedAll.filter((task) => task.userGroup === 'archived'),
|
||||
};
|
||||
|
||||
return {
|
||||
summary: {
|
||||
total_tasks: active.length,
|
||||
@@ -1097,5 +1233,6 @@ export function projectConversationProcessingFromWorkItems(
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
status_groups,
|
||||
};
|
||||
}
|
||||
@@ -230,6 +230,29 @@ function normalizeFacts(raw: unknown): ShippingProcessingFacts | undefined {
|
||||
return out;
|
||||
}
|
||||
|
||||
function normalizeAggregateSummary(
|
||||
raw: unknown,
|
||||
): ShippingProcessingProjection['aggregateSummary'] {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const array = (value: unknown): string[] => Array.isArray(value)
|
||||
? value.map((entry) => String(entry || '').trim()).filter(Boolean)
|
||||
: [];
|
||||
const count = (key: string): number => Number(item[key] || 0) || 0;
|
||||
const intakeNo = String(item.intake_no ?? item.intakeNo ?? '').trim();
|
||||
if (!intakeNo) return null;
|
||||
return {
|
||||
intakeNo,
|
||||
total: count('total'),
|
||||
completed: count('completed'),
|
||||
processing: count('processing'),
|
||||
needsAction: count('needs_action') || count('needsAction'),
|
||||
failed: count('failed'),
|
||||
stages: array(item.stages),
|
||||
reasonCodes: array(item.reason_codes ?? item.reasonCodes),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
|
||||
* 注意:failed_sources 会进一步透传到 exhausted_sources 分开(二者互斥;仅 max_attempts 耗尽的源进 exhausted)。
|
||||
@@ -324,6 +347,12 @@ export function normalizeShippingProcessingProjection(
|
||||
const stageNodes = Array.isArray(stageNodesRaw)
|
||||
? stageNodesRaw.map(normalizeStageNode).filter((row): row is ShippingProcessingStageNode => Boolean(row))
|
||||
: undefined;
|
||||
const aggregateChildrenRaw = item.aggregate_children ?? item.aggregateChildren;
|
||||
const aggregateChildren = Array.isArray(aggregateChildrenRaw)
|
||||
? aggregateChildrenRaw
|
||||
.map(normalizeShippingProcessingProjection)
|
||||
.filter((entry): entry is ShippingProcessingProjection => Boolean(entry))
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
|
||||
@@ -368,6 +397,9 @@ export function normalizeShippingProcessingProjection(
|
||||
(item.retryable as boolean | undefined) == null ? false : Boolean(item.retryable),
|
||||
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
|
||||
facts: normalizeFacts(item.facts),
|
||||
userGroup: readNullableString(item, 'user_group', 'userGroup') as ShippingProcessingProjection['userGroup'],
|
||||
aggregateSummary: normalizeAggregateSummary(item.aggregate_summary ?? item.aggregateSummary),
|
||||
aggregateChildren: aggregateChildren?.length ? aggregateChildren : undefined,
|
||||
legacyStatus: readNullableString(item, 'legacy_status', 'legacyStatus'),
|
||||
legacyStage: readNullableString(item, 'legacy_stage', 'legacyStage'),
|
||||
hasFormalOt:
|
||||
|
||||
@@ -311,7 +311,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('derives sibling OT tasks from work_items when embedded conversation_processing omits them', async () => {
|
||||
it('aggregates sibling EML OT work_items into one highest-attention Intake card', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [
|
||||
@@ -397,7 +397,12 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
|
||||
expect(ctl.processing.value?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
|
||||
expect(ctl.processing.value?.processing).toEqual([]);
|
||||
expect(ctl.processing.value?.needs_action[0]?.aggregateSummary).toMatchObject({
|
||||
intakeNo: 'SNI-1',
|
||||
total: 2,
|
||||
processing: 1,
|
||||
});
|
||||
expect(ctl.processing.value?.focused_task_no).toBe('OT-ROOT');
|
||||
expect(ctl.processing.value?.recent_task_no).toBe('OT-SIBLING');
|
||||
ctl.stop();
|
||||
|
||||
@@ -136,6 +136,80 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('merges sibling Runs from one upload batch into one chat status card', async () => {
|
||||
const first = Object.assign(run({
|
||||
run_no: 'SNER-BATCH-1',
|
||||
conversation_id: 'conv-batch',
|
||||
intake_nos: ['SNI-BATCH-1'],
|
||||
summary: {
|
||||
total_documents: 1,
|
||||
pending_documents: 1,
|
||||
processing_documents: 0,
|
||||
completed_documents: 0,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 0,
|
||||
},
|
||||
documents: [{
|
||||
unit_id: 1,
|
||||
document_id: 101,
|
||||
file_name: 'notice-a.pdf',
|
||||
status: 'queued',
|
||||
line_count: 0,
|
||||
email_supplement: { status: 'none', relation_codes: [] },
|
||||
available_actions: [],
|
||||
}],
|
||||
}), { upload_batch_id: 'upload-batch-1' });
|
||||
const second = Object.assign(run({
|
||||
run_no: 'SNER-BATCH-2',
|
||||
conversation_id: 'conv-batch',
|
||||
intake_nos: ['SNI-BATCH-2'],
|
||||
summary: {
|
||||
total_documents: 1,
|
||||
pending_documents: 0,
|
||||
processing_documents: 1,
|
||||
completed_documents: 0,
|
||||
review_required_documents: 0,
|
||||
failed_documents: 0,
|
||||
candidate_count: 0,
|
||||
},
|
||||
documents: [{
|
||||
unit_id: 2,
|
||||
document_id: 102,
|
||||
file_name: 'notice-b.pdf',
|
||||
status: 'processing',
|
||||
line_count: 0,
|
||||
email_supplement: { status: 'none', relation_codes: [] },
|
||||
available_actions: [],
|
||||
}],
|
||||
}), { upload_batch_id: 'upload-batch-1' });
|
||||
api.createSubmission.mockResolvedValue({
|
||||
decision: 'created',
|
||||
user_task_no: null,
|
||||
run_no: first.run_no,
|
||||
created_new: true,
|
||||
operation_id: 'op-batch',
|
||||
});
|
||||
api.getRun.mockResolvedValue(first);
|
||||
api.listRuns.mockResolvedValue({ items: [first, second] });
|
||||
const harness = createHarness();
|
||||
|
||||
await harness.runs.startRun('', ['SNI-BATCH-1', 'SNI-BATCH-2'], [], 'upload-batch-1');
|
||||
|
||||
const cards = harness.messages.value.filter((message) => message.shipping_order_extraction_state);
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.shipping_order_extraction_state?.summary).toMatchObject({
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 1,
|
||||
processingDocuments: 1,
|
||||
});
|
||||
expect(cards[0]?.shipping_order_extraction_state?.documents?.map((item) => item.fileName)).toEqual([
|
||||
'notice-a.pdf',
|
||||
'notice-b.pdf',
|
||||
]);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('keeps an appended submission in the user message and the existing Run state card only', async () => {
|
||||
const queued = run({
|
||||
run_no: 'SNER-APPENDED',
|
||||
|
||||
@@ -54,6 +54,69 @@ const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/**
|
||||
* 将同一上传批次的独立 Run 合成单张聊天状态卡。
|
||||
*
|
||||
* 核心逻辑:Run 仍按 Intake 独立执行、审计和复核;仅把同会话同 upload_batch_id
|
||||
* 的用户态摘要相加,保证一次文件选择在聊天区只出现一个卡片。
|
||||
*/
|
||||
function mergeUploadBatchRuns(primary: ShippingOrderExtractionRun, runs: ShippingOrderExtractionRun[]): ShippingOrderExtractionRun {
|
||||
const batchId = String(primary.upload_batch_id || '').trim();
|
||||
if (!batchId) return primary;
|
||||
const members = runs.filter((item) => (
|
||||
item.conversation_id === primary.conversation_id
|
||||
&& String(item.upload_batch_id || '').trim() === batchId
|
||||
));
|
||||
if (members.length <= 1) return primary;
|
||||
const activeMembers = members.filter((item) => ACTIVE_RUN_STATUSES.has(item.status));
|
||||
const status = activeMembers.some((item) => item.status === 'processing')
|
||||
? 'processing'
|
||||
: activeMembers.length > 0
|
||||
? 'queued'
|
||||
: members.some((item) => item.status === 'failed')
|
||||
? 'failed'
|
||||
: members.some((item) => item.status === 'review_required')
|
||||
? 'review_required'
|
||||
: members.some((item) => item.status === 'partially_completed')
|
||||
? 'partially_completed'
|
||||
: 'completed';
|
||||
const failedParseMembers = members.filter((item) => (
|
||||
item.documents || []
|
||||
).some((document) => document.reason_code === 'intake_parse_failed' || String(document.user_visible_stage || '') === 'parse_failed'));
|
||||
const effectiveStatus = failedParseMembers.length > 0 && activeMembers.length === 0 ? 'failed' : status;
|
||||
const summaryKeys = [
|
||||
'total_documents', 'pending_documents', 'processing_documents', 'completed_documents',
|
||||
'review_required_documents', 'failed_documents', 'cancelled_documents', 'candidate_count',
|
||||
'opened_existing_documents',
|
||||
] as const;
|
||||
const summary = summaryKeys.reduce((result, key) => {
|
||||
result[key] = members.reduce((total, item) => total + Number(item.summary?.[key] || 0), 0);
|
||||
return result;
|
||||
}, {} as ShippingOrderExtractionRun['summary']);
|
||||
const documentIds = new Set<number>();
|
||||
const documents = members.flatMap((item) => item.documents || []).filter((item) => {
|
||||
const id = Number(item.document_id || 0);
|
||||
if (id && documentIds.has(id)) return false;
|
||||
if (id) documentIds.add(id);
|
||||
return true;
|
||||
});
|
||||
const mostRecent = [...members].sort((left, right) => String(right.last_activity_at || '').localeCompare(String(left.last_activity_at || '')))[0] || primary;
|
||||
return {
|
||||
...primary,
|
||||
status: effectiveStatus,
|
||||
phase: effectiveStatus,
|
||||
intake_nos: [...new Set(members.flatMap((item) => item.intake_nos || []))],
|
||||
summary,
|
||||
documents,
|
||||
current_activity: mostRecent.current_activity || primary.current_activity,
|
||||
available_actions: [...new Set(members.flatMap((item) => item.available_actions || []))],
|
||||
handling_items: members.flatMap((item) => item.handling_items || []),
|
||||
health_tips: members.flatMap((item) => item.health_tips || []),
|
||||
progress_version: Math.max(...members.map((item) => Number(item.progress_version || 0))),
|
||||
last_activity_at: mostRecent.last_activity_at || primary.last_activity_at,
|
||||
};
|
||||
}
|
||||
|
||||
/** 按页面可见性选择轮询间隔;后台放慢,失败退避另算。 */
|
||||
function resolvePollIntervalMs(failureCount = 0): number {
|
||||
if (failureCount > 0) {
|
||||
@@ -72,6 +135,7 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
userTaskNo: run.user_task_no || null,
|
||||
submissionOrdinal: run.submission_ordinal ?? null,
|
||||
composerContextId: run.composer_context_id || null,
|
||||
uploadBatchId: run.upload_batch_id || null,
|
||||
runNo: run.run_no,
|
||||
sourceRunNo: run.reparse?.source_run_no || null,
|
||||
supersedingRunNo: run.reparse?.superseding_run_no || null,
|
||||
@@ -110,6 +174,20 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
lastActivityAt: run.current_activity.last_activity_at || null,
|
||||
}
|
||||
: null,
|
||||
documents: Array.isArray(run.documents)
|
||||
? run.documents.map((item) => ({
|
||||
unitId: Number(item.unit_id || 0),
|
||||
documentId: Number(item.document_id || 0),
|
||||
intakeId: item.intake_id != null ? Number(item.intake_id || 0) || null : null,
|
||||
documentType: item.document_type || null,
|
||||
fileName: item.file_name || null,
|
||||
status: String(item.status || ''),
|
||||
userVisibleStage: item.user_visible_stage || null,
|
||||
reasonCode: item.reason_code || null,
|
||||
explainability: item.explainability ? { message: item.explainability.message || null } : null,
|
||||
emailSupplement: item.email_supplement ? { status: item.email_supplement.status || null } : null,
|
||||
}))
|
||||
: [],
|
||||
selectionPlan: run.selection_plan
|
||||
? {
|
||||
selectionVersion: run.selection_plan.selection_version || null,
|
||||
@@ -218,6 +296,22 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return composerContextId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取同批次兄弟 Run 后生成聊天展示快照。
|
||||
*
|
||||
* 仅在服务端已返回 upload_batch_id 时查询;旧 Run 或重识别 Run 保持原有单卡逻辑。
|
||||
*/
|
||||
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => {
|
||||
if (!String(run.upload_batch_id || '').trim()) return run;
|
||||
try {
|
||||
const response = await listWorkspaceShippingOrderExtractionRuns(run.conversation_id, 100);
|
||||
return mergeUploadBatchRuns(run, response.items || []);
|
||||
} catch {
|
||||
// 聚合读失败时宁可显示本 Run 的真实状态,也不阻断轮询或误改业务状态。
|
||||
return run;
|
||||
}
|
||||
};
|
||||
|
||||
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
|
||||
const stopPolling = () => {
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
@@ -260,10 +354,18 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
): Promise<ChatMessage> => {
|
||||
const formId = `shipping-order-extraction-run:${run.run_no}`;
|
||||
const state = mapOrderExtractionRunToMessageState(run);
|
||||
const uploadBatchId = String(run.upload_batch_id || '').trim();
|
||||
const stateCards = options.messages.value.filter((item) => {
|
||||
if (item.role !== 'assistant') return false;
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
return payload.formId === formId || payload.order_extraction_run_no === run.run_no;
|
||||
const cardBatchId = String(
|
||||
payload.shipping_order_extraction_upload_batch_id
|
||||
|| item.shipping_order_extraction_state?.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
return payload.formId === formId
|
||||
|| payload.order_extraction_run_no === run.run_no
|
||||
|| Boolean(uploadBatchId && cardBatchId === uploadBatchId);
|
||||
});
|
||||
let message = stateCards.find((item) => {
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
@@ -287,6 +389,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
message.payload = {
|
||||
formId,
|
||||
order_extraction_run_no: run.run_no,
|
||||
shipping_order_extraction_upload_batch_id: run.upload_batch_id || null,
|
||||
shipping_order_extraction_state: state,
|
||||
order_extraction_reparse: run.reparse || null,
|
||||
shipping_order_extraction_review: reviewAttachments || [],
|
||||
@@ -386,18 +489,20 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const request = createRequestController(generation);
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(runNo, request.signal).finally(request.release);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
const displayRun = await loadDisplayRun(run);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollFailureCount = 0;
|
||||
setRunRefreshFailed(run.run_no, false);
|
||||
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
const reviewAttachments = await refreshTerminalFacts(run);
|
||||
setRunRefreshFailed(displayRun.run_no, false);
|
||||
if (!ACTIVE_RUN_STATUSES.has(displayRun.status)) {
|
||||
const reviewAttachments = await refreshTerminalFacts(displayRun);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
stopPolling();
|
||||
await upsertRunMessage(run, reviewAttachments);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
await upsertRunMessage(displayRun, reviewAttachments);
|
||||
await acknowledgeTerminalRunWhenVisible(displayRun);
|
||||
return;
|
||||
}
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
await upsertRunMessage(displayRun);
|
||||
await acknowledgeTerminalRunWhenVisible(displayRun);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollTimer = setTimeout(() => void pollRun(run.run_no, generation), resolvePollIntervalMs(0));
|
||||
} catch {
|
||||
@@ -456,7 +561,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
focused_user_task_no: focusedUserTaskNo,
|
||||
});
|
||||
// 统一提交只返回决策摘要;再拉 Run 投影供状态卡与轮询。
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
|
||||
const submittedRun = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
|
||||
const run = await loadDisplayRun(submittedRun);
|
||||
if (!options.conversationId.value) {
|
||||
options.conversationId.value = run.conversation_id;
|
||||
composerBoundConversationId = run.conversation_id;
|
||||
@@ -487,7 +593,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
await options.onConversationResolved(run.conversation_id);
|
||||
options.onWorkflowRefresh?.();
|
||||
if (ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
beginPolling(run.run_no, 1000);
|
||||
beginPolling(submittedRun.run_no, 1000);
|
||||
} else {
|
||||
const reviewAttachments = await refreshTerminalFacts(run);
|
||||
await upsertRunMessage(run, reviewAttachments);
|
||||
@@ -524,7 +630,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const normalizedRunNo = String(runNo || '').trim();
|
||||
if (!normalizedRunNo) return false;
|
||||
try {
|
||||
const run = await getWorkspaceShippingOrderExtractionRun(normalizedRunNo);
|
||||
const fetchedRun = await getWorkspaceShippingOrderExtractionRun(normalizedRunNo);
|
||||
const run = await loadDisplayRun(fetchedRun);
|
||||
setRunRefreshFailed(run.run_no, false);
|
||||
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
const reviewAttachments = await refreshTerminalFacts(run);
|
||||
@@ -533,7 +640,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return true;
|
||||
}
|
||||
await upsertRunMessage(run);
|
||||
if (activeRunNo !== run.run_no || !pollTimer) beginPolling(run.run_no, FOREGROUND_POLL_MS);
|
||||
if (activeRunNo !== fetchedRun.run_no || !pollTimer) beginPolling(fetchedRun.run_no, FOREGROUND_POLL_MS);
|
||||
return true;
|
||||
} catch (error) {
|
||||
setRunRefreshFailed(normalizedRunNo, true);
|
||||
@@ -662,15 +769,16 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const latest = items[0];
|
||||
if (!latest) return;
|
||||
activeRunNo = latest.run_no;
|
||||
const reviewAttachments = ACTIVE_RUN_STATUSES.has(latest.status)
|
||||
const displayRun = mergeUploadBatchRuns(latest, items);
|
||||
const reviewAttachments = ACTIVE_RUN_STATUSES.has(displayRun.status)
|
||||
? undefined
|
||||
: await refreshTerminalFacts(latest);
|
||||
: await refreshTerminalFacts(displayRun);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
await upsertRunMessage(latest, reviewAttachments);
|
||||
await acknowledgeTerminalRunWhenVisible(latest);
|
||||
await upsertRunMessage(displayRun, reviewAttachments);
|
||||
await acknowledgeTerminalRunWhenVisible(displayRun);
|
||||
options.onWorkflowRefresh?.();
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
if (ACTIVE_RUN_STATUSES.has(latest.status)) {
|
||||
if (ACTIVE_RUN_STATUSES.has(displayRun.status)) {
|
||||
beginPolling(latest.run_no, 1000);
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -77,6 +77,20 @@ export interface ShippingOrderExtractionCurrentActivityState {
|
||||
lastActivityAt?: string | null;
|
||||
}
|
||||
|
||||
/** 聊天批处理卡按文件展示的只读状态;业务真相仍由 Run/Unit 后端投影提供。 */
|
||||
export interface ShippingOrderExtractionFileState {
|
||||
unitId: number;
|
||||
documentId: number;
|
||||
intakeId?: number | null;
|
||||
documentType?: string | null;
|
||||
fileName?: string | null;
|
||||
status: string;
|
||||
userVisibleStage?: string | null;
|
||||
reasonCode?: string | null;
|
||||
explainability?: { message?: string | null } | null;
|
||||
emailSupplement?: { status?: string | null } | null;
|
||||
}
|
||||
|
||||
export interface ShippingOrderExtractionSelectionPlanState {
|
||||
selectionVersion?: string | null;
|
||||
maxInitialAttachments?: number;
|
||||
@@ -143,6 +157,8 @@ export interface ShippingOrderExtractionState {
|
||||
submissionOrdinal?: number | null;
|
||||
/** 当前输入区短生命周期上下文;发送决策用,非业务主键 */
|
||||
composerContextId?: string | null;
|
||||
/** 同一次文件选择的聊天卡聚合键;绝不参与业务写入或任务路由。 */
|
||||
uploadBatchId?: string | null;
|
||||
/** Run 版本谱系;由后端投影,供历史消息只读隔离。 */
|
||||
runNo?: string | null;
|
||||
sourceRunNo?: string | null;
|
||||
@@ -151,6 +167,7 @@ export interface ShippingOrderExtractionState {
|
||||
readOnlyReason?: string | null;
|
||||
summary: ShippingOrderExtractionStateSummary;
|
||||
currentActivity?: ShippingOrderExtractionCurrentActivityState | null;
|
||||
documents?: ShippingOrderExtractionFileState[];
|
||||
selectionPlan?: ShippingOrderExtractionSelectionPlanState | null;
|
||||
unitSummary?: ShippingOrderExtractionUnitSummaryState | null;
|
||||
availableActions: string[];
|
||||
|
||||
@@ -343,6 +343,12 @@ export interface ShippingProcessingProjection {
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
/** 子状态事实字典(inventorySourceStatus / candidateSourceCodes / preparedSourceCodes / pendingSourceCodes / lineResolutions / exportState / uploadState / switchState)。 */
|
||||
facts?: ShippingProcessingFacts;
|
||||
/** EML Intake 的用户可见全局分组;由后端按子附件最高关注级别裁决。 */
|
||||
userGroup?: 'failed' | 'waiting_human' | 'processing' | 'completed' | 'cancelled' | 'archived' | null;
|
||||
/** 同一 EML Intake 的后端聚合摘要;子附件仍以 aggregate_children 保留在服务端。 */
|
||||
aggregateSummary?: ConversationProcessingUserTask['aggregateSummary'];
|
||||
/** EML Intake 聚合卡的真实子附件工作项;仅展示,不作为写操作目标。 */
|
||||
aggregateChildren?: ShippingProcessingProjection[];
|
||||
/** 旧 status 备份(T8 apply_user_projection_fields.legacy_status);调试用。 */
|
||||
legacyStatus?: string | null;
|
||||
/** 旧 stage 备份(T8 apply_user_projection_fields.legacy_stage);调试用。 */
|
||||
@@ -581,8 +587,23 @@ export interface ConversationProcessingUserTask {
|
||||
retryable?: boolean;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
facts?: ShippingProcessingFacts;
|
||||
/** EML Intake 的用户可见全局分组;前端只消费,不从附件状态自行推导。 */
|
||||
userGroup?: ShippingProcessingProjection['userGroup'];
|
||||
legacyStatus?: string | null;
|
||||
legacyStage?: string | null;
|
||||
/** 同一 EML Intake 聚合后的子任务状态,仅供展示,不作为写操作事实。 */
|
||||
aggregateSummary?: {
|
||||
intakeNo: string;
|
||||
total: number;
|
||||
completed: number;
|
||||
processing: number;
|
||||
needsAction: number;
|
||||
failed: number;
|
||||
stages: string[];
|
||||
reasonCodes: string[];
|
||||
} | null;
|
||||
/** EML 聚合内的真实邮件/附件子项;仅用于展开明细展示。 */
|
||||
aggregateChildren?: ShippingProcessingProjection[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -625,6 +646,15 @@ export interface ConversationProcessingProjection {
|
||||
/** 成功完成待查看;与 needs_action 异常态分离 */
|
||||
completed?: ConversationProcessingUserTask[];
|
||||
history: ConversationProcessingUserTask[];
|
||||
/** 按 EML Intake 唯一归组后的六类用户状态;同一 EML 只允许出现一次。 */
|
||||
status_groups?: {
|
||||
failed: ConversationProcessingUserTask[];
|
||||
waiting_human: ConversationProcessingUserTask[];
|
||||
processing: ConversationProcessingUserTask[];
|
||||
completed: ConversationProcessingUserTask[];
|
||||
cancelled: ConversationProcessingUserTask[];
|
||||
archived: ConversationProcessingUserTask[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1662,6 +1692,8 @@ export interface ShippingOrderExtractionEmailSupplementResult {
|
||||
export interface ShippingOrderExtractionDocumentResult {
|
||||
unit_id: number;
|
||||
document_id: number;
|
||||
intake_id?: number | null;
|
||||
document_type?: string | null;
|
||||
file_name?: string | null;
|
||||
status: ShippingOrderExtractionDocumentStatus;
|
||||
user_visible_stage?: ShippingOrderExtractionUserVisibleStage | null;
|
||||
@@ -1718,6 +1750,8 @@ export interface ShippingOrderExtractionRun {
|
||||
status: ShippingOrderExtractionRunStatus;
|
||||
phase: string;
|
||||
intake_nos: string[];
|
||||
/** 同一次文件选择的展示聚合键;不是 user_task_no,不能用于业务写入。 */
|
||||
upload_batch_id?: string | null;
|
||||
schema_version_id: number;
|
||||
schema_version?: number | null;
|
||||
schema_checksum?: string | null;
|
||||
@@ -1764,6 +1798,7 @@ export interface ShippingOrderExtractionRun {
|
||||
technical_failure_reason_codes?: string[];
|
||||
} | null;
|
||||
current_activity?: ShippingOrderExtractionCurrentActivity | null;
|
||||
documents?: ShippingOrderExtractionDocumentResult[];
|
||||
available_actions: string[];
|
||||
/** Run 级处理事项;聊天卡与右侧「本次处理」按类别展示。 */
|
||||
handling_items?: Array<{
|
||||
|
||||
@@ -47,6 +47,13 @@ const ACTION_CODE_TO_INTENT: Record<string, ShippingProcessingActionIntent> = {
|
||||
retry_failed_attachments: 'retry',
|
||||
retry_upload: 'retry',
|
||||
retry_freight_upload_rpa: 'retry',
|
||||
// 订单识别复核卡后端动作码:统一复用右侧「进入订单处理/重试解析/查看结果」执行器。
|
||||
edit_draft: 'open_order_review',
|
||||
reconcile_and_progress: 'open_order_review',
|
||||
create_draft: 'open_order_review',
|
||||
retry_stp_auto_create: 'retry',
|
||||
reparse: 'retry',
|
||||
view: 'view_result',
|
||||
refresh: 'refresh',
|
||||
regenerate_excel: 'regenerate_excel',
|
||||
generate_excel: 'regenerate_excel',
|
||||
@@ -189,7 +196,10 @@ export function resolveProcessingActionPresentation(
|
||||
if (key === 'regenerate_manual_upload_todo') return;
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
const intent = mapActionCodeToIntent(code);
|
||||
// 识别/建单失败的 view 是进入当前 Case 处理;已完成任务才打开只读结果。
|
||||
const intent = key === 'view' && NEEDS_ACTION_STATUSES.has(status)
|
||||
? 'open_order_review'
|
||||
: mapActionCodeToIntent(code);
|
||||
if (!intent || intent === 'none') {
|
||||
// [fail-closed] 未知动作不渲染原始码,仅告警。
|
||||
warnUnregisteredWorkbenchAction({
|
||||
@@ -290,7 +300,9 @@ export function resolveConversationTaskActionPresentation(
|
||||
if (!code) return;
|
||||
const key = code.toLowerCase();
|
||||
if (seen.has(key)) return;
|
||||
const intent = mapActionCodeToIntent(code);
|
||||
const intent = key === 'view' && isNeedsAction
|
||||
? 'open_order_review'
|
||||
: mapActionCodeToIntent(code);
|
||||
if (!intent || intent === 'none') return;
|
||||
seen.add(key);
|
||||
items.push(toItem(code, intent, surface));
|
||||
|
||||
@@ -281,6 +281,7 @@
|
||||
"shippingOrderExtractionDetailsTitle": "Processing details",
|
||||
"shippingOrderExtractionCloseDetails": "Close processing details",
|
||||
"shippingOrderExtractionTimelineTitle": "Run timeline",
|
||||
"shippingOrderExtractionTimelineRunScope": "Run-level events",
|
||||
"shippingOrderExtractionTimelineLoading": "Loading the processing timeline...",
|
||||
"shippingOrderExtractionTimelineUnavailable": "Unable to load the processing timeline right now. Please try again later.",
|
||||
"shippingOrderExtractionTimelineEmpty": "No processing timeline is available yet.",
|
||||
@@ -2567,11 +2568,37 @@
|
||||
"failed": "Cancellation request failed. Please try again."
|
||||
},
|
||||
"shippingProcessing": {
|
||||
"batchStatusTitle": "Batch Processing Status",
|
||||
"batchFilesTotal": "{count} files total",
|
||||
"batchComplete": "Complete",
|
||||
"batchProcessed": "processed",
|
||||
"batchCompletedFiles": "{count} Files Completed",
|
||||
"batchProcessing": "Processing...",
|
||||
"batchException": "Exception",
|
||||
"batchManualVerify": "Manual verification required.",
|
||||
"batchExtracted": "Extracted",
|
||||
"candidateReady": "Candidate generated (awaiting next steps)",
|
||||
"candidateFiles": "{count} candidate files generated",
|
||||
"waitingReview": "Awaiting manual review",
|
||||
"batchAnalyzing": "Analyzing...",
|
||||
"emailPrefix": "Email: ",
|
||||
"parsingAttachments": "Parsing Attachments",
|
||||
"emailMeta": "Attachments · System processing",
|
||||
"batchFilesUnavailable": "File details are temporarily unavailable. Open the batch workbench to view them.",
|
||||
"openBatchWorkbench": "Open Batch Workbench",
|
||||
"panelTitle": "Processing in this conversation",
|
||||
"pendingMaterials": "Pending materials",
|
||||
"orderTasks": "Order tasks",
|
||||
"groupNeedsAction": "Needs your action · {count} tasks",
|
||||
"groupFailed": "Exceptions / failed · {count} tasks",
|
||||
"groupWaitingHuman": "Needs manual action / interrupted · {count} tasks",
|
||||
"groupProcessing": "System processing · {count} tasks",
|
||||
"aggregate": {
|
||||
"completed": "Uploaded {count}",
|
||||
"processing": "Processing {count}",
|
||||
"needsAction": "Needs action {count}",
|
||||
"failed": "Failed {count}"
|
||||
},
|
||||
"groupCompleted": "Completed · {count}",
|
||||
"groupProcessingRecords": "Processing records · {count}",
|
||||
"groupRecordCompleted": "Completed",
|
||||
|
||||
@@ -281,6 +281,7 @@
|
||||
"shippingOrderExtractionDetailsTitle": "รายละเอียดการประมวลผล",
|
||||
"shippingOrderExtractionCloseDetails": "ปิดรายละเอียดการประมวลผล",
|
||||
"shippingOrderExtractionTimelineTitle": "ไทม์ไลน์การประมวลผล",
|
||||
"shippingOrderExtractionTimelineRunScope": "เหตุการณ์ระดับการทำงาน",
|
||||
"shippingOrderExtractionTimelineLoading": "กำลังโหลดไทม์ไลน์การประมวลผล...",
|
||||
"shippingOrderExtractionTimelineUnavailable": "ยังไม่สามารถโหลดไทม์ไลน์การประมวลผลได้ในขณะนี้ โปรดลองอีกครั้งภายหลัง",
|
||||
"shippingOrderExtractionTimelineEmpty": "ยังไม่มีไทม์ไลน์การประมวลผล",
|
||||
@@ -2567,11 +2568,37 @@
|
||||
"failed": "คำขอยกเลิกล้มเหลว โปรดลองใหม่ภายหลัง"
|
||||
},
|
||||
"shippingProcessing": {
|
||||
"batchStatusTitle": "สถานะการประมวลผลเป็นชุด",
|
||||
"batchFilesTotal": "ทั้งหมด {count} ไฟล์",
|
||||
"batchComplete": "เสร็จสิ้น",
|
||||
"batchProcessed": "ประมวลผลแล้ว",
|
||||
"batchCompletedFiles": "เสร็จสิ้น {count} ไฟล์",
|
||||
"batchProcessing": "กำลังประมวลผล...",
|
||||
"batchException": "ข้อผิดพลาด",
|
||||
"batchManualVerify": "ต้องตรวจสอบด้วยตนเอง",
|
||||
"batchExtracted": "แยกข้อมูลแล้ว",
|
||||
"candidateReady": "สร้างรายการผู้สมัครแล้ว (รอขั้นตอนถัดไป)",
|
||||
"candidateFiles": "สร้างไฟล์ผู้สมัครแล้ว {count} ไฟล์",
|
||||
"waitingReview": "รอการตรวจสอบด้วยตนเอง",
|
||||
"batchAnalyzing": "กำลังวิเคราะห์...",
|
||||
"emailPrefix": "อีเมล: ",
|
||||
"parsingAttachments": "กำลังวิเคราะห์ไฟล์แนบ",
|
||||
"emailMeta": "ไฟล์แนบ · ระบบกำลังประมวลผล",
|
||||
"batchFilesUnavailable": "ยังไม่สามารถโหลดรายละเอียดไฟล์ได้ โปรดเปิดเวิร์กเบนช์",
|
||||
"openBatchWorkbench": "เปิดเวิร์กเบนช์การประมวลผล",
|
||||
"panelTitle": "กำลังประมวลผลในการสนทนานี้",
|
||||
"pendingMaterials": "เอกสารรอดำเนินการ",
|
||||
"orderTasks": "งานคำสั่งซื้อ",
|
||||
"groupNeedsAction": "ต้องดำเนินการ · {count} งาน",
|
||||
"groupFailed": "ข้อผิดพลาด / ล้มเหลว · {count} งาน",
|
||||
"groupWaitingHuman": "ต้องดำเนินการด้วยตนเอง / ถูกขัดจังหวะ · {count} งาน",
|
||||
"groupProcessing": "ระบบกำลังประมวลผล · {count} งาน",
|
||||
"aggregate": {
|
||||
"completed": "อัปโหลดแล้ว {count}",
|
||||
"processing": "กำลังประมวลผล {count}",
|
||||
"needsAction": "รอดำเนินการ {count}",
|
||||
"failed": "ผิดปกติ {count}"
|
||||
},
|
||||
"groupCompleted": "เสร็จสิ้น · {count}",
|
||||
"groupProcessingRecords": "ประวัติการประมวลผล · {count}",
|
||||
"groupRecordCompleted": "เสร็จสิ้น",
|
||||
|
||||
@@ -315,6 +315,7 @@
|
||||
"shippingOrderExtractionDetailsTitle": "处理详情",
|
||||
"shippingOrderExtractionCloseDetails": "关闭处理详情",
|
||||
"shippingOrderExtractionTimelineTitle": "运行时间线",
|
||||
"shippingOrderExtractionTimelineRunScope": "运行级事件",
|
||||
"shippingOrderExtractionTimelineLoading": "正在加载处理时间线...",
|
||||
"shippingOrderExtractionTimelineUnavailable": "暂时无法加载处理时间线,请稍后再试。",
|
||||
"shippingOrderExtractionTimelineEmpty": "暂未返回处理时间线。",
|
||||
@@ -2641,11 +2642,37 @@
|
||||
}
|
||||
},
|
||||
"shippingProcessing": {
|
||||
"batchStatusTitle": "批处理状态",
|
||||
"batchFilesTotal": "共 {count} 个文件",
|
||||
"batchComplete": "完成",
|
||||
"batchProcessed": "已处理",
|
||||
"batchCompletedFiles": "已完成 {count} 个文件",
|
||||
"batchProcessing": "处理中...",
|
||||
"batchException": "异常",
|
||||
"batchManualVerify": "需要人工核验。",
|
||||
"batchExtracted": "已提取",
|
||||
"candidateReady": "已生成候选(待后续处理)",
|
||||
"candidateFiles": "已生成候选 {count} 个文件",
|
||||
"waitingReview": "待人工复核",
|
||||
"batchAnalyzing": "分析中...",
|
||||
"emailPrefix": "邮件:",
|
||||
"parsingAttachments": "正在解析附件",
|
||||
"emailMeta": "附件处理 · 系统处理中",
|
||||
"batchFilesUnavailable": "文件明细暂不可用,请打开批处理工作台查看。",
|
||||
"openBatchWorkbench": "打开批处理工作台",
|
||||
"panelTitle": "本次处理中",
|
||||
"pendingMaterials": "待处理材料",
|
||||
"orderTasks": "订单任务",
|
||||
"groupNeedsAction": "需要你处理 · {count} 个任务",
|
||||
"groupFailed": "异常 / 失败 · {count} 个任务",
|
||||
"groupWaitingHuman": "待人工处理 / 中断 · {count} 个任务",
|
||||
"groupProcessing": "系统处理中 · {count} 个任务",
|
||||
"aggregate": {
|
||||
"completed": "已上传完成 {count}",
|
||||
"processing": "处理中 {count}",
|
||||
"needsAction": "待人工 {count}",
|
||||
"failed": "异常 {count}"
|
||||
},
|
||||
"groupCompleted": "已完成 · {count}",
|
||||
"groupProcessingRecords": "处理记录 · {count}",
|
||||
"groupRecordCompleted": "已完成",
|
||||
|
||||
@@ -281,6 +281,7 @@
|
||||
"shippingOrderExtractionDetailsTitle": "處理詳情",
|
||||
"shippingOrderExtractionCloseDetails": "關閉處理詳情",
|
||||
"shippingOrderExtractionTimelineTitle": "執行時間線",
|
||||
"shippingOrderExtractionTimelineRunScope": "執行層級事件",
|
||||
"shippingOrderExtractionTimelineLoading": "正在載入處理時間線...",
|
||||
"shippingOrderExtractionTimelineUnavailable": "暫時無法載入處理時間線,請稍後再試。",
|
||||
"shippingOrderExtractionTimelineEmpty": "暫未返回處理時間線。",
|
||||
@@ -2567,11 +2568,37 @@
|
||||
"failed": "取消請求失敗,請稍後重試。"
|
||||
},
|
||||
"shippingProcessing": {
|
||||
"batchStatusTitle": "批次處理狀態",
|
||||
"batchFilesTotal": "共 {count} 個檔案",
|
||||
"batchComplete": "完成",
|
||||
"batchProcessed": "已處理",
|
||||
"batchCompletedFiles": "已完成 {count} 個檔案",
|
||||
"batchProcessing": "處理中...",
|
||||
"batchException": "異常",
|
||||
"batchManualVerify": "需要人工核驗。",
|
||||
"batchExtracted": "已擷取",
|
||||
"candidateReady": "已產生候選(待後續處理)",
|
||||
"candidateFiles": "已產生候選 {count} 個檔案",
|
||||
"waitingReview": "待人工複核",
|
||||
"batchAnalyzing": "分析中...",
|
||||
"emailPrefix": "郵件:",
|
||||
"parsingAttachments": "正在解析附件",
|
||||
"emailMeta": "附件處理 · 系統處理中",
|
||||
"batchFilesUnavailable": "檔案明細暫不可用,請開啟批次工作台查看。",
|
||||
"openBatchWorkbench": "開啟批次工作台",
|
||||
"panelTitle": "本次處理中",
|
||||
"pendingMaterials": "待處理材料",
|
||||
"orderTasks": "訂單任務",
|
||||
"groupNeedsAction": "需要你處理 · {count} 個任務",
|
||||
"groupFailed": "異常 / 失敗 · {count} 個任務",
|
||||
"groupWaitingHuman": "待人工處理 / 中斷 · {count} 個任務",
|
||||
"groupProcessing": "系統處理中 · {count} 個任務",
|
||||
"aggregate": {
|
||||
"completed": "已上傳完成 {count}",
|
||||
"processing": "處理中 {count}",
|
||||
"needsAction": "待人工 {count}",
|
||||
"failed": "異常 {count}"
|
||||
},
|
||||
"groupCompleted": "已完成 · {count}",
|
||||
"groupProcessingRecords": "處理記錄 · {count}",
|
||||
"groupRecordCompleted": "已完成",
|
||||
|
||||
Reference in new issue
Block a user