diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 9d2d1eca..23e659fc 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -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', diff --git a/backend/app/jobs/handlers/shipping_stp_auto_create.py b/backend/app/jobs/handlers/shipping_stp_auto_create.py index 154ebcf6..40ba3426 100644 --- a/backend/app/jobs/handlers/shipping_stp_auto_create.py +++ b/backend/app/jobs/handlers/shipping_stp_auto_create.py @@ -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( diff --git a/backend/app/services/shipping_notice/audit_service.py b/backend/app/services/shipping_notice/audit_service.py index b1fb73d2..ba415883 100644 --- a/backend/app/services/shipping_notice/audit_service.py +++ b/backend/app/services/shipping_notice/audit_service.py @@ -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( diff --git a/backend/app/services/shipping_notice/order_extraction_run_service.py b/backend/app/services/shipping_notice/order_extraction_run_service.py index 4a3af567..a065db67 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -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: diff --git a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py index 95473f34..87a7aa2d 100644 --- a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -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), diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index e8cdf9d9..8d538c76 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -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, diff --git a/backend/app/services/shipping_notice/order_stp_auto_create_service.py b/backend/app/services/shipping_notice/order_stp_auto_create_service.py index 9275adef..f3eacc3c 100644 --- a/backend/app/services/shipping_notice/order_stp_auto_create_service.py +++ b/backend/app/services/shipping_notice/order_stp_auto_create_service.py @@ -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 {}), } diff --git a/backend/app/services/shipping_notice/reconciliation_projector.py b/backend/app/services/shipping_notice/reconciliation_projector.py index 0d0ccdd9..71a692a8 100644 --- a/backend/app/services/shipping_notice/reconciliation_projector.py +++ b/backend/app/services/shipping_notice/reconciliation_projector.py @@ -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')), ) diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 79ad66dc..1fdb458c 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -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, diff --git a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py index 3bd338e0..00f314df 100644 --- a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py +++ b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py @@ -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), )) diff --git a/backend/tests/test_shipping_auto_progress_controller_phase1.py b/backend/tests/test_shipping_auto_progress_controller_phase1.py index b2163776..c1b8a6fa 100644 --- a/backend/tests/test_shipping_auto_progress_controller_phase1.py +++ b/backend/tests/test_shipping_auto_progress_controller_phase1.py @@ -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 diff --git a/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py b/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py index 28958d86..898e17af 100644 --- a/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py +++ b/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py @@ -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 diff --git a/backend/tests/test_shipping_order_review_service.py b/backend/tests/test_shipping_order_review_service.py index edf3dd28..3ea690ee 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -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 == { diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 009d2104..52e31ac4 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -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,禁止全空摘要。 diff --git a/backend/tests/test_shipping_stp_auto_create_enqueue.py b/backend/tests/test_shipping_stp_auto_create_enqueue.py index e548cce4..6c432974 100644 --- a/backend/tests/test_shipping_stp_auto_create_enqueue.py +++ b/backend/tests/test_shipping_stp_auto_create_enqueue.py @@ -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 diff --git a/docs/features/document-check/frontend-prd.md b/docs/features/document-check/frontend-prd.md index 708fa252..c87e010e 100644 --- a/docs/features/document-check/frontend-prd.md +++ b/docs/features/document-check/frontend-prd.md @@ -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` 通过,四语言文案齐全。 diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 59239d34..8641d5a2 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -371,9 +371,9 @@ export const reparseWorkspaceShippingOrderExtractionRun = ( ); /** 获取当前订单抽取 Run 的按 PDF 归并详情。 */ -export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) => +export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string, uploadBatchId?: string | null) => requestJson( - `/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)}` : ''}`, ); /** 在终态状态卡已投影到当前会话后确认已查看,避免只因预加载会话列表而消除提醒。 */ diff --git a/frontend/src/features/chat/components/ChatMessageList.vue b/frontend/src/features/chat/components/ChatMessageList.vue index 66a4be1a..28434a3c 100644 --- a/frontend/src/features/chat/components/ChatMessageList.vue +++ b/frontend/src/features/chat/components/ChatMessageList.vue @@ -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 : {}; - 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 : {}; - 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), + ); }); }; diff --git a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts index e39289ab..852c2aa3 100644 --- a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts +++ b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts @@ -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 () => { diff --git a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue index ac1868c9..a71a37b8 100644 --- a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue +++ b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue @@ -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 = { + '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 }); -}