diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index 4e7f3844..963df055 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -28,5 +28,6 @@ import app.api.admin.shipping_field_assets # noqa: F401 import app.api.admin.shipping_order_document_profiles # noqa: F401 import app.api.admin.shipping_document_layouts # noqa: F401 import app.api.admin.shipping_process_gate # noqa: F401 +import app.api.admin.shipping_legacy_stp_jobs # noqa: F401 __all__ = ['admin_bp'] diff --git a/backend/app/api/admin/shipping_legacy_stp_jobs.py b/backend/app/api/admin/shipping_legacy_stp_jobs.py new file mode 100644 index 00000000..bb06262d --- /dev/null +++ b/backend/app/api/admin/shipping_legacy_stp_jobs.py @@ -0,0 +1,63 @@ +""" +backend/app/api/admin/shipping_legacy_stp_jobs.py + +用途:Phase 5-1 —— 管理后台「货代历史 STP Job(928/929)运维面板」只读 API。 +依赖:admin Blueprint、require_admin、legacy_stp_job_admin_service。 +逻辑: + • GET /admin/shipping-notice/legacy-stp-jobs 分页列表(支持 q/case_no/error_code/created_from/created_to) + • GET /admin/shipping-notice/legacy-stp-jobs/ 单条详情 + 回链 Review Case + • 所有接口严格 require_admin;不允许写任何 DB。 +""" + +from __future__ import annotations + +from flask import g, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.errors import ValidationError +from app.core.response import ok +from app.services.shipping_notice.legacy_stp_job_admin_service import ( + get_admin_legacy_stp_job, + list_admin_legacy_stp_jobs, +) + + +def _qint(name: str, default: int) -> int: + raw = request.args.get(name) + if raw in (None, ''): + return default + try: + return int(raw) + except (TypeError, ValueError) as exc: + raise ValidationError(f'{name} must be an integer') from exc + + +@admin_bp.route('/shipping-notice/legacy-stp-jobs', methods=['GET']) +@require_admin +def admin_list_legacy_stp_jobs(): + """历史失败 STP Job(failed/dead)分页列表,供管理员做 928/929 回放前筛选。""" + page = _qint('page', 1) + page_size = _qint('page_size', 25) + payload = list_admin_legacy_stp_jobs( + page=page, + page_size=page_size, + status=request.args.get('status'), + job_type=request.args.get('job_type'), + q=request.args.get('q'), + case_no=request.args.get('case_no'), + error_code=request.args.get('error_code'), + blocking_reason=request.args.get('blocking_reason'), + created_from=request.args.get('created_from'), + created_to=request.args.get('created_to'), + sort=request.args.get('sort') or '-created_at', + ) + return ok(payload, request_id=getattr(g, 'request_id', None)) + + +@admin_bp.route('/shipping-notice/legacy-stp-jobs/', methods=['GET']) +@require_admin +def admin_get_legacy_stp_job(job_id: int): + """单条历史失败 STP Job 详情 + 回链 Review Case + 回放建议(replay_plan)。""" + payload = get_admin_legacy_stp_job(int(job_id)) + return ok(payload, request_id=getattr(g, 'request_id', None)) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index cf1b7822..6c892f37 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -2,10 +2,8 @@ backend/app/api/chat.py 用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。 -依赖:app.core.decorators、app.core.errors、app.core.response、services.dify、integrations、 - shipping_notice.audit_service(货代会话删除审计)。 -逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError; - shipping_notice 会话删除写不可变审计并返回标准 envelope。 +依赖:app.core.decorators、app.core.errors、services.dify、integrations。 +逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。 """ import io import ipaddress @@ -30,7 +28,7 @@ from app.services.dify import DifyService from app.core.config.settings import Config from app.services.integration_api import IntegrationApiService from app.core.decorators import require_agent_permission -from app.models import Agent, ChatLog, ChatSession, Feedback, ShippingOrderProcessingRun +from app.models import Agent, ChatLog, ChatSession, Feedback from app import db from app.core.errors import ( AppError, @@ -206,12 +204,7 @@ def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str: return value -def _serialize_session( - session: ChatSession, - *, unseen_order_extraction_count: int = 0, - unseen_order_extraction_severity: str | None = None, -) -> dict: - """输出会话摘要及订单抽取待查看聚合,不返回 Run 内容或错误正文。""" +def _serialize_session(session: ChatSession) -> dict: last_active = session.last_active_at or session.created_at return { 'id': session.id, @@ -219,46 +212,9 @@ def _serialize_session( 'title': session.title or '', 'created_at': last_active.isoformat() if last_active else '', 'status': session.status, - 'unseen_order_extraction_count': max(0, int(unseen_order_extraction_count or 0)), - 'unseen_order_extraction_severity': unseen_order_extraction_severity, } -def _order_extraction_attention_by_conversation( - *, user_id: int, agent_id: int, conversation_ids: set[str], -) -> dict[str, tuple[int, str]]: - """聚合同用户同 Agent 尚未确认的终态订单抽取提醒,防止跨会话泄露。""" - if not conversation_ids: - return {} - severity_rank = {'info': 1, 'warning': 2, 'error': 3} - status_severity = { - 'completed': 'info', - 'partially_completed': 'warning', - 'review_required': 'warning', - 'failed': 'error', - 'cancelled': 'error', - } - rows = db.session.query( - ShippingOrderProcessingRun.conversation_id, - ShippingOrderProcessingRun.status, - ).filter( - ShippingOrderProcessingRun.user_id == user_id, - ShippingOrderProcessingRun.owner_agent_id == agent_id, - ShippingOrderProcessingRun.conversation_id.in_(conversation_ids), - ShippingOrderProcessingRun.attention_generated_at.isnot(None), - ShippingOrderProcessingRun.seen_at.is_(None), - ).all() - aggregate: dict[str, tuple[int, str]] = {} - for conversation_id, status in rows: - severity = status_severity.get(str(status or ''), 'info') - count, existing = aggregate.get(conversation_id, (0, severity)) - aggregate[conversation_id] = ( - count + 1, - severity if severity_rank[severity] >= severity_rank[existing] else existing, - ) - return aggregate - - def _get_chat_session(user_id: int, agent_id: int, session_id: str | None): session_key = str(session_id or '').strip() if not session_key: @@ -1074,90 +1030,36 @@ def get_chat_sessions(): }) sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True) - attention_by_conversation = _order_extraction_attention_by_conversation( - user_id=user.id, - agent_id=agent.id, - conversation_ids={str(item['conversation_id']) for item in sessions if item.get('conversation_id')}, - ) - for item in sessions: - count, severity = attention_by_conversation.get(str(item.get('conversation_id') or ''), (0, None)) - item['unseen_order_extraction_count'] = count - item['unseen_order_extraction_severity'] = severity return jsonify(sessions[:20]) @chat_bp.route('/sessions', methods=['DELETE']) @require_agent_permission def delete_all_chat_sessions(): """ - 删除当前用户与当前 Agent 的所有历史会话。 - - 核心逻辑:批量清理 ChatLog / Feedback / ChatSession;shipping_notice 写审计; - 返回标准 success envelope。 - - Returns: - Flask JSON:`{ success, data: { deleted: true } }`。 + 删除当前用户与当前 Agent 的所有历史会话 """ - from app.core.response import ok - user = getattr(g, 'current_user', None) agent = getattr(g, 'current_agent', None) if user is None or agent is None: raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500) chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all() chat_log_ids = [log.id for log in chat_logs] - session_count = ( - db.session.query(ChatSession) - .filter_by(user_id=user.id, agent_id=agent.id) - .count() - ) if chat_log_ids: from app.models import GeneralFeedback db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False) db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False) - - if str(getattr(agent, 'code', None) or '').strip() == SHIPPING_NOTICE_AGENT_CODE: - from app.services.shipping_notice.audit_service import append_shipping_audit_event - - append_shipping_audit_event( - event_type='conversation_sessions_deleted_all', - aggregate_type='chat_session', - aggregate_id=f'user:{int(user.id)}:agent:{int(agent.id)}', - actor_type='user', - actor_id=user.id, - owner_user_id=user.id, - action='delete_all_chat_sessions', - reason_code='user_deleted_all_sessions', - before={'session_count': int(session_count), 'chat_log_count': len(chat_log_ids)}, - after={'deleted': True}, - metadata={'agent_id': int(agent.id)}, - source='workspace_api', - sensitivity_level='sensitive', - request_id=str(getattr(g, 'request_id', '') or '') or None, - ) - db.session.commit() - return ok({'deleted': True, 'session_count': int(session_count)}) + return jsonify({'status': 'ok'}) @chat_bp.route('/sessions/', methods=['DELETE']) @require_agent_permission def delete_chat_session(conversation_id): """ - 删除指定的会话记录。 - - 核心逻辑:清理 ChatLog / Feedback;shipping_notice Agent 额外写不可变审计; - 返回标准 success envelope。 - - Args: - conversation_id: 会话 ID(路径参数)。 - - Returns: - Flask JSON:`{ success, data: { deleted: true, conversation_id } }`。 + 删除指定的会话记录 """ - from app.core.response import ok - user = getattr(g, 'current_user', None) agent = getattr(g, 'current_agent', None) if user is None or agent is None: @@ -1181,9 +1083,6 @@ def delete_chat_session(conversation_id): ).all() chat_log_ids = [log.id for log in chat_logs] - session_id_for_audit = str( - getattr(session, 'session_id', None) or conversation_id or '' - ).strip() if chat_log_ids: from app.models import GeneralFeedback db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) @@ -1191,38 +1090,9 @@ def delete_chat_session(conversation_id): db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False) if session: db.session.delete(session) - - # [BE-16] 货代会话删除必须留审计;与业务删除同事务提交。 - if str(getattr(agent, 'code', None) or '').strip() == SHIPPING_NOTICE_AGENT_CODE: - from app.services.shipping_notice.audit_service import append_shipping_audit_event - - append_shipping_audit_event( - event_type='conversation_session_deleted', - aggregate_type='chat_session', - aggregate_id=session_id_for_audit or str(conversation_id), - actor_type='user', - actor_id=user.id, - owner_user_id=user.id, - conversation_id=session_id_for_audit or str(conversation_id), - action='delete_chat_session', - reason_code='user_deleted_session', - before={ - 'conversation_id': session_id_for_audit or str(conversation_id), - 'chat_log_count': len(chat_log_ids), - }, - after={'deleted': True}, - metadata={'agent_id': int(agent.id), 'chat_log_count': len(chat_log_ids)}, - source='workspace_api', - sensitivity_level='sensitive', - request_id=str(getattr(g, 'request_id', '') or '') or None, - ) - db.session.commit() - return ok({ - 'deleted': True, - 'conversation_id': session_id_for_audit or str(conversation_id), - }) + return jsonify({'status': 'ok'}) @chat_bp.route('/messages', methods=['GET']) @require_agent_permission @@ -1243,29 +1113,6 @@ def get_chat_messages(): ChatLog.agent_id == g.current_agent.id, ChatLog.conversation_id == conversation_id, ).order_by(ChatLog.created_at.asc()).all() - - def _is_order_extraction_state_card(payload): - """只识别正式 Run 状态卡;用户上传锚点不得回放为重复的助手卡。""" - if not isinstance(payload, dict): - return False - run_no = str(payload.get('order_extraction_run_no') or '').strip() - return bool(run_no and payload.get('formId') == f'shipping-order-extraction-run:{run_no}') - - run_nos = { - str(log.payload.get('order_extraction_run_no') or '').strip() - for log in logs if _is_order_extraction_state_card(log.payload) - } - order_extraction_runs = {} - if run_nos: - order_extraction_runs = { - run.run_no: run - for run in db.session.query(ShippingOrderProcessingRun).filter( - ShippingOrderProcessingRun.user_id == g.current_user.id, - ShippingOrderProcessingRun.owner_agent_id == g.current_agent.id, - ShippingOrderProcessingRun.conversation_id == (session.session_id if session else conversation_id), - ShippingOrderProcessingRun.run_no.in_(run_nos), - ).all() - } messages = [] agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic' @@ -1277,20 +1124,11 @@ def get_chat_messages(): for key, value in raw_payload.items() if key != 'user_attachments' } - run_no = str(assistant_payload.get('order_extraction_run_no') or '').strip() - if _is_order_extraction_state_card(raw_payload) and run_no in order_extraction_runs: - from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_message_state - - assistant_payload['shipping_order_extraction_state'] = serialize_order_extraction_message_state( - order_extraction_runs[run_no], - ) if log.query or user_attachments: user_msg = {'role': 'user', 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code)} if user_attachments: user_msg['attachments'] = user_attachments messages.append(user_msg) - if str(raw_payload.get('formId') or '').strip() == f'shipping-order-extraction-user:{run_no}': - continue if ( not log.answer and not log.message_type @@ -1851,12 +1689,7 @@ def chat_completions(): yield terminal_line except Exception as exc: current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id) - payload = { - 'event': 'error', - 'message': '当前服务暂时无法完成回答,请稍后重试。', - 'conversation_id': local_session_id, - 'session_status': 'error', - } + payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'} yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" for terminal_line in iter_handler_terminal_sse( relay_stream_ctx, diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 2ac67e71..a2b2c939 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -375,6 +375,13 @@ def rpa_inventory_batch_ready(): return jsonify(shipping_tools.rpa_report_inventory_batch(_payload())) +@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST']) +def rpa_inventory_batch_claimed(): + """v2 Worker 领取回调:仅记录 Attempt 执行阶段。""" + from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch + return jsonify({'success': True, 'data': claim_inventory_batch(_payload())}) + + @shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST']) def rpa_inventory_configuration_test_ready(): """RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。""" @@ -409,6 +416,14 @@ def repair_task_inventory_attachment(task_no: str): payload.setdefault("task_id", task_no) return jsonify(shipping_tools.repair_task_inventory_attachment(payload)) + +@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST']) +def rpa_inventory_repair(): + """受控库存回调修复:复用正式 v2 ingest 链路。""" + payload = _payload() + payload['repair'] = True + return jsonify(shipping_tools.rpa_report_inventory_batch(payload)) + @shipping_notice_bp.route('/rpa/upload-complete', methods=['POST']) def rpa_upload_complete(): """RPA 回调入口:上报货代上传结果并回写任务状态。""" diff --git a/backend/app/api/workspace/__init__.py b/backend/app/api/workspace/__init__.py index 40c38148..057554c3 100644 --- a/backend/app/api/workspace/__init__.py +++ b/backend/app/api/workspace/__init__.py @@ -11,6 +11,7 @@ from app.api.workspace.schedule import workspace_schedule_bp from app.api.workspace.shipping_notice import workspace_shipping_notice_bp import app.api.workspace.shipping_process_gate # noqa: F401 +import app.api.workspace.shipping_inventory_candidates # noqa: F401 __all__ = [ 'workspace_announcements_bp', diff --git a/backend/app/api/workspace/shipping_inventory_candidates.py b/backend/app/api/workspace/shipping_inventory_candidates.py new file mode 100644 index 00000000..05053fdf --- /dev/null +++ b/backend/app/api/workspace/shipping_inventory_candidates.py @@ -0,0 +1,69 @@ +""" +backend/app/api/workspace/shipping_inventory_candidates.py + +用途:正式 Task 库存候选只读详情 API。 +依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。 +逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason, + 不把可恢复业务阻断误报成 404。 +""" + +from __future__ import annotations + +from flask import request + +from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp +from app.core.errors import ValidationError +from app.services.shipping_notice.inventory_candidate_projection import ( + project_inventory_candidate_detail, +) +from app.services.shipping_notice.query_service import get_task_for_user + + +def _parse_version_arg() -> str | int: + """解析 version 查询参数,仅允许 current 或正整数。""" + raw = str(request.args.get('version') or 'current').strip().lower() + if raw == 'current': + return 'current' + try: + value = int(raw) + except (TypeError, ValueError) as exc: + raise ValidationError('version must be "current" or an integer') from exc + if value <= 0: + raise ValidationError('version must be positive') + return value + + +def _parse_bool_arg(name: str, *, default: bool) -> bool: + """解析布尔查询参数。""" + raw = request.args.get(name) + if raw is None: + return default + return str(raw).strip().lower() in {'1', 'true', 'yes', 'on'} + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/tasks//inventory-candidates', + methods=['GET'], +) +def workspace_get_task_inventory_candidates(task_no: str): + """返回正式 Task 当前候选版本、历史摘要与行级详情。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + version = _parse_version_arg() + include_history = _parse_bool_arg('include_history', default=True) + include_drafts = _parse_bool_arg('include_drafts', default=False) + payload = project_inventory_candidate_detail( + task, + version=version, + include_history=include_history, + include_drafts=include_drafts, + ) + return _ok({ + 'task_no': task.task_no, + 'current_set': payload.get('current_set'), + 'sources': payload.get('sources') or [], + 'lines': payload.get('lines') or [], + 'history': payload.get('history') or [], + 'blocking_reason': payload.get('blocking_reason'), + 'primary_action': payload.get('primary_action'), + }) diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index aa186293..faa22fa8 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -488,7 +488,44 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str): site_id=site_id, actor_id=user.id, reason=str(data.get('reason') or ''), + commit=False, ) + # [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。 + # 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。 + if role == 'bill_to': + from app.models import ShippingOrderCandidate, ShippingOrderReviewCase + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_single_case_for_auto_progress, + ) + _TERMINAL = frozenset({ + 'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending', + }) + candidates = list( + ShippingOrderCandidate.query + .filter_by(order_extraction_id=int(extraction.id)) + .all() + ) + candidate_ids = {int(c.id) for c in candidates} + case = None + if candidate_ids: + case = ( + ShippingOrderReviewCase.query + .filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids)) + .first() + ) + if case is None and extraction.run_id: + case = ( + ShippingOrderReviewCase.query + .filter_by(run_id=int(extraction.run_id)) + .first() + ) + if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id: + reconcile_single_case_for_auto_progress( + case=case, + trigger='extraction_customer_confirmed', + refresh_validation=True, + ) + db.session.commit() return _ok(result) @workspace_shipping_notice_bp.route('/shipping-conversations//batch-workspace', methods=['GET']) @@ -508,18 +545,77 @@ def workspace_retry_conversation_auto_progress(conversation_id: str): 核心逻辑:委托 conversation_retry_auto_progress_service;前端不提交对象列表; 返回 summary + items;写 conversation_retry_auto_progress 汇总审计。 + + 异常保护: + [STEP R-1] 路由级显式 try/except 兜底,保证模块导入期 SyntaxError/ImportError + 不冒泡为裸 500(与 conversation_retry_auto_progress_service 内部 + 三分支 _execute_* 的 import 级 try/except 形成双层防护)。 + [STEP R-2] AppError 正常 re-raise,交给 @app.errorhandler(AppError); + SyntaxError/ImportError/其他 Exception 统一转为 SHIPPING.RETRY_AUTO_PROGRESS_FAILED + 并返回 summary={failed:1} 的骨架,避免前端 JSON 解析失败。 """ + import logging as _rt_logging + _rt_log = _rt_logging.getLogger(__name__) + user = _require_user() data = request.get_json(silent=True) or {} - from app.services.shipping_notice.conversation_retry_auto_progress_service import ( - retry_auto_progress_for_conversation, - ) + normalized_conv_id = str(conversation_id or '').strip() + fallback_payload = { + 'conversation_id': normalized_conv_id, + 'summary': {'total': 1, 'retried': 0, 'skipped': 0, 'failed': 1}, + 'items': [{ + 'object_type': 'conversation', + 'object_ref': normalized_conv_id, + 'action': 'retry_auto_progress', + 'outcome': 'failed', + 'reason_code': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED', + 'metadata': {}, + }], + } - return _ok(retry_auto_progress_for_conversation( - user_id=int(user.id), - conversation_id=str(conversation_id or '').strip(), - reason=str(data.get('reason') or 'user_retry_auto_progress'), - )) + try: + from app.services.shipping_notice.conversation_retry_auto_progress_service import ( + retry_auto_progress_for_conversation, + ) + except (SyntaxError, ImportError) as mod_err: + _rt_log.exception( + 'retry_conversation_auto_progress module import error conversation_id=%s err=%s', + normalized_conv_id, type(mod_err).__name__, + ) + fallback_payload['items'][0]['reason_code'] = 'SHIPPING.MODULE_IMPORT_ERROR' + fallback_payload['items'][0]['metadata']['import_error'] = type(mod_err).__name__ + return _ok(fallback_payload) + except Exception as exc: # noqa: BLE001 + _rt_log.exception( + 'retry_conversation_auto_progress import unexpected error conversation_id=%s', + normalized_conv_id, + ) + fallback_payload['items'][0]['reason_code'] = ( + 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED' + ) + fallback_payload['items'][0]['metadata']['error_type'] = type(exc).__name__ + return _ok(fallback_payload) + + try: + result = retry_auto_progress_for_conversation( + user_id=int(user.id), + conversation_id=normalized_conv_id, + reason=str(data.get('reason') or 'user_retry_auto_progress'), + ) + except AppError: + raise + except Exception as exc: # noqa: BLE001 + _rt_log.exception( + 'retry_conversation_auto_progress execution error conversation_id=%s', + normalized_conv_id, + ) + fallback_payload['items'][0]['reason_code'] = ( + 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED' + ) + fallback_payload['items'][0]['metadata']['error_type'] = type(exc).__name__ + return _ok(fallback_payload) + + return _ok(result) @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) @@ -1005,15 +1101,11 @@ def workspace_auto_progress_shipping_task(task_no: str): if not task: raise NotFoundError('Not found') data = request.get_json(silent=True) or {} - from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision + from app.services.shipping_notice.progress_workflow import run_task_auto_progress - result = retry_task_with_decision( - task_no=str(task.task_no), - user_id=int(user.id), - scope='task', - reason=str(data.get('reason') or 'system_auto_progress'), - trigger='system_auto_progress', - continue_auto_progress=True, + # 普通用户不提交 Gate;服务端从当前事实定位最早未通过 Gate。 + result = run_task_auto_progress( + str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id), ) # 兼容旧前端:若仍有 export 路径则附带 download_url。 @@ -1120,7 +1212,15 @@ def workspace_mark_manual_uploaded(task_no: str): 'freight_ref_no': data.get('freight_ref_no'), 'artifact_id': data.get('artifact_id'), } - return _ok(shipping_tools.upload_to_freight(payload)) + result = shipping_tools.upload_to_freight(payload) + if isinstance(result, dict) and str(result.get('status') or '') == 'ok': + # 回执先由既有服务原子登记;随后仅提交 upload_receipt_recorded Gate,由服务端复核事实后 completed。 + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + + run_task_auto_progress( + str(task.task_no), trigger='manual_upload_receipt_recorded', operator_id=int(user.id), + ) + return _ok(result) @workspace_shipping_notice_bp.route('/shipping-tasks//retry-upload', methods=['POST']) @@ -1471,15 +1571,17 @@ def workspace_get_shipping_order_review_run(run_no: str): @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/', methods=['GET']) def workspace_get_shipping_order_review_case(case_no: str): - """读取当前用户的一份 PDF 复核详情;Case 编号不能跨 owner 越权访问;访问留痕。""" + """读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。""" user = _require_user() is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' from app.services.shipping_notice.fulfillment_audit import record_access_audit - from app.services.shipping_notice.order_review_projection import serialize_review_case + from app.services.shipping_notice.order_review_case_snapshot import ( + build_order_review_case_snapshot, + ) from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user # 只读:禁止在 GET 中入队 STP(入队仅抽取收尾 / resume / 显式 retry POST)。 - payload = serialize_review_case( + snapshot = build_order_review_case_snapshot( get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin), is_admin=is_admin, ) @@ -1489,9 +1591,13 @@ def workspace_get_shipping_order_review_case(case_no: str): aggregate_id=str(case_no), actor_id=user.id, review_case_no=str(case_no), - run_no=str(payload.get('run_no') or '') or None if isinstance(payload, dict) else None, + run_no=( + str(((snapshot.get('case') or {}).get('run_no')) or '') or None + if isinstance(snapshot, dict) + else None + ), ) - return _ok(payload) + return _ok(snapshot) @workspace_shipping_notice_bp.route( @@ -1500,20 +1606,190 @@ def workspace_get_shipping_order_review_case(case_no: str): ) def workspace_retry_shipping_order_stp_auto_create(case_no: str): """ - 显式重试 STP 自动建单入队(failed / manual_fallback)。 + 显式重试 STP 自动建单入队(仅用于确认没有业务冲突后的技术重试 — Q6 职责严格区分)。 - 核心逻辑:委托 retry_stp_auto_create_for_case;成功返回 queued/reused+job_id; - 失败抛结构化业务错误,禁止伪装成功。 + 核心逻辑: + [Phase 2-4 前置校验] 先调 reconciliation_service.assert_case_not_blocked_manual, + 如命中「业务阻断 waiting_human」(如 NOTICE_EXACT_DUPLICATE)直接抛 409, + 要求前端切换到 reconcile-and-progress;通过后再委托 retry_stp_auto_create_for_case。 """ user = _require_user() + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' + from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user from app.services.shipping_notice.order_stp_auto_create_service import ( retry_stp_auto_create_for_case, ) + from app.services.shipping_notice.reconciliation_service import ( + assert_case_not_blocked_manual, + ) + + case = get_review_case_visible_to_user(str(case_no), int(user.id), is_admin=is_admin) + # [DUPLICATE-GUARD-1] 第一道:retry API 前置校验 — 命中 duplicate 等业务阻断时直接 409,禁止普通 retry + assert_case_not_blocked_manual(case_no=str(case_no), case=case) result = retry_stp_auto_create_for_case(user_id=int(user.id), case_no=str(case_no)) return _ok(result) +@workspace_shipping_notice_bp.route( + '/shipping-notice/order-review-cases//retry-auto-progress', + methods=['POST'], +) +def workspace_retry_shipping_order_case_auto_progress(case_no: str): + """ + 单个 Case 精确自动推进恢复入口。适用于 Projection primary_action.code = retry_auto_progress。 + 禁止 duplicate 等业务阻断对象调用;assert_case_not_blocked_manual 前置双校验。 + + 核心逻辑: + [可见性] get_review_case_visible_to_user → [业务阻断] assert_case_not_blocked_manual + → [终态幂等] confirmed_task_id/status 终态 → [协调器] reconcile_single_case_for_auto_progress + → [审计] case_retry_auto_progress_invoked → 返回 success+case_no+reconcile_result+serialized case。 + + 异常保护: + [STEP R-1] 路由级显式 try/except 兜底,保证模块导入期 SyntaxError/ImportError + 不冒泡为裸 500(与 case_retry_auto_progress_service 内部双校验 + 形成双层防护)。 + [STEP R-2] AppError 正常 re-raise;SyntaxError/ImportError/其他 Exception 转为 + success=false + error_code,前端统一消费 retry 结果投影。 + """ + import logging as _rt_logging + _rt_log = _rt_logging.getLogger(__name__) + + user = _require_user() + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' + normalized_case_no = str(case_no or '').strip() + fallback_result = { + 'success': False, + 'case_no': normalized_case_no, + 'error': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED', + 'enqueue_status': 'not_eligible', + } + + try: + from app.services.shipping_notice.case_retry_auto_progress_service import ( + case_retry_auto_progress, + ) + except (SyntaxError, ImportError) as mod_err: + _rt_log.exception( + 'case_retry_auto_progress module import error case_no=%s err=%s', + normalized_case_no, type(mod_err).__name__, + ) + fallback_result['error'] = 'SHIPPING.MODULE_IMPORT_ERROR' + fallback_result['import_error'] = type(mod_err).__name__ + return _ok(fallback_result) + except Exception as exc: # noqa: BLE001 + _rt_log.exception( + 'case_retry_auto_progress import unexpected error case_no=%s', + normalized_case_no, + ) + fallback_result['error_type'] = type(exc).__name__ + return _ok(fallback_result) + + try: + result = case_retry_auto_progress( + user_id=int(user.id), + case_no=normalized_case_no, + is_admin=bool(is_admin), + ) + except AppError: + raise + except Exception as exc: # noqa: BLE001 + _rt_log.exception( + 'case_retry_auto_progress execution error case_no=%s', + normalized_case_no, + ) + fallback_result['error_type'] = type(exc).__name__ + return _ok(fallback_result) + + return _ok(result) + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/order-review-cases//reconcile-and-progress', + methods=['POST'], +) +def workspace_reconcile_shipping_order_case_and_progress(case_no: str): + """ + 对账 → 复用 / 裁决 / 入队(Q6 与 retry-stp-auto-create 并存,职责严格区分)。 + + 【Phase 2 正式入口】: + - 仅当用户点击了「处理重复任务」裁决按钮后或需要对账恢复的场景才调用; + - 按 Q7:operation_id + expected_case_version 双保险幂等; + - 按 Q1:内部调用 reconcile_queries 做 L1-L3 五级归属; + - 按 Q3:用户 create_revision / force_create 裁决后走资格刷新 → resume → STP, + 禁止直改 duplicate_status 绕过门禁。 + Body 字段: + operation_id: string(必填,客户端生成) + user_action: 'reuse_existing' | 'create_revision' | 'force_create' | 'adjudicate' | 'auto'(默认 auto) + expected_case_version: integer(可选,版本校验过期抛 409) + source_content_hash: string(可选,请求快照用于参数一致性) + """ + user = _require_user() + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' + payload = request.get_json(silent=True) if request.is_json else None + if not isinstance(payload, dict): + payload = {} + from app.core.errors import ValidationError + operation_id = str(payload.get('operation_id') or '').strip() + if not operation_id: + raise ValidationError( + 'operation_id required (client-generated idempotency component)', + code='SHIPPING.RECONCILE_OPERATION_ID_REQUIRED', + ) + user_action_raw = str(payload.get('user_action') or 'auto').strip() or 'auto' + allowed = {'reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto'} + if user_action_raw not in allowed: + raise ValidationError( + f'invalid user_action: {user_action_raw}', + code='SHIPPING.RECONCILE_INVALID_USER_ACTION', + details={'allowed': sorted(allowed)}, + ) + user_action = user_action_raw # type: ignore[assignment] + expected_case_version = payload.get('expected_case_version') + if expected_case_version is not None: + try: + expected_case_version = int(expected_case_version) + except (TypeError, ValueError): + raise ValidationError( + 'expected_case_version must be integer if provided', + code='SHIPPING.RECONCILE_INVALID_EXPECTED_VERSION', + ) + else: + expected_case_version = None + source_content_hash = ( + str(payload.get('source_content_hash') or '').strip() or None + ) + # [Phase 4] 管理员专用扩展:legacy_job_id(历史 Job 928/929 replay)与 replay_mode 透传; + # 非管理员若传入 → 直接 422 拒绝(与 reconcile_and_progress PRE-CHECK 一致)。 + legacy_job_id_raw = payload.get('legacy_job_id') + legacy_job_id: int | None = None + if legacy_job_id_raw is not None: + try: + legacy_job_id = int(legacy_job_id_raw) + except (TypeError, ValueError): + raise ValidationError( + 'legacy_job_id must be integer if provided', + code='SHIPPING.RECONCILE_INVALID_EXPECTED_VERSION', + ) + replay_mode_raw = payload.get('replay_mode') + replay_mode = bool(replay_mode_raw) if replay_mode_raw is not None else False + + from app.services.shipping_notice.reconciliation_service import reconcile_and_progress + + result = reconcile_and_progress( + user_id=int(user.id), + case_no=str(case_no), + operation_id=operation_id, + user_action=user_action, + expected_case_version=expected_case_version, + source_content_hash=source_content_hash, + is_admin=is_admin, + legacy_job_id=legacy_job_id, + replay_mode=replay_mode, + ) + return _ok(result.to_public()) + + @workspace_shipping_notice_bp.route( '/shipping-notice/order-review-cases//access/version-history', methods=['POST'], @@ -2506,9 +2782,10 @@ def workspace_attempt_shipping_order_review_field_locate(case_no: str): def workspace_list_shipping_order_review_llm_suggestions(case_no: str): """列出 Case 下 Dify 最小证据建议记录。""" user = _require_user() + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' from app.services.shipping_notice.order_review_llm_service import list_case_suggestions - return _ok(list_case_suggestions(user_id=user.id, case_no=case_no)) + return _ok(list_case_suggestions(user_id=user.id, case_no=case_no, is_admin=is_admin)) @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//llm-suggestions', methods=['POST']) @@ -2540,6 +2817,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str): def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, suggestion_no: str): """人工裁决 LLM 建议:accept / modify / reject。""" user = _require_user() + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' from app.services.shipping_notice.order_review_llm_service import decide_suggestion payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='adjudicate_llm_suggestion') @@ -2552,6 +2830,7 @@ def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, sugg value=payload.get('value'), reason=payload.get('reason'), note=payload.get('note'), + is_admin=is_admin, ) db.session.commit() return _ok(result) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 901898a6..81c48eb2 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -231,6 +231,15 @@ class Config: ) SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true') SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true' + SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS = int( + os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS', '72') or '72' + ) + SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS = float( + os.getenv('SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS', '60') or '60' + ) + SHIPPING_NOTICE_STP_QUEUED_UNCLAIMED_THRESHOLD_SECONDS = int( + os.getenv('SHIPPING_NOTICE_STP_QUEUED_UNCLAIMED_THRESHOLD_SECONDS', '300') or '300' + ) # OT 后行级自动履约总闸:关闭时仍投影 match_result/库存列,但禁止自动写决定与批量 wave。 SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED = ( os.getenv('SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED', 'false').lower() == 'true' diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 34c06d0a..805e68d0 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -15,9 +15,11 @@ from app.jobs.handlers import ( # noqa: F401 shipping_notice_run, shipping_order_extraction, shipping_process_gate, + shipping_auto_progress, shipping_stp_auto_create, shipping_line_auto_fulfill, shipping_post_ot_wave_progress, + shipping_review_revalidate_progress, shipping_xfa_ocr_automark, wecom_directory_sync, ) diff --git a/backend/app/jobs/handlers/shipping_auto_progress.py b/backend/app/jobs/handlers/shipping_auto_progress.py new file mode 100644 index 00000000..fa70f206 --- /dev/null +++ b/backend/app/jobs/handlers/shipping_auto_progress.py @@ -0,0 +1,26 @@ +""" +jobs/handlers/shipping_auto_progress.py + +用途:消费 P0-3 Task 级 AutoProgress Job。 +依赖:JobContext、auto_progress_controller。 +逻辑:Job 已由通用队列领取为 running;本 Handler 只委托正式控制器执行一个 Gate,不再调用旧全链路 facade。 +""" + +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.services.shipping_notice.auto_progress_controller import run_auto_progress_job + + +@register_handler(JobType.SHIPPING_AUTO_PROGRESS) +def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None: + """执行一个正式 Gate;payload 必须含队列注入的 job_id。""" + raw_job_id = payload.get('job_id') + if not raw_job_id: + raise RuntimeError('missing_job_id_for_shipping_auto_progress') + run_auto_progress_job( + job_id=int(raw_job_id), + worker_id=str(ctx.extras.get('worker_label') or f'shipping-auto-progress-{raw_job_id}'), + ) diff --git a/backend/app/jobs/handlers/shipping_review_revalidate_progress.py b/backend/app/jobs/handlers/shipping_review_revalidate_progress.py new file mode 100644 index 00000000..74082e09 --- /dev/null +++ b/backend/app/jobs/handlers/shipping_review_revalidate_progress.py @@ -0,0 +1,300 @@ +""" +backend/app/jobs/handlers/shipping_review_revalidate_progress.py + +用途:消费 Review Revalidate Job,在 Case 字段变更后异步刷新校验、 + 重跑 STP 资格判定、推进自动入队协调。 +依赖:JobContext、order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、 + jobs.queue finish/fail、recovery_contract.is_tech_retryable_error。 +逻辑:由 shipping worker 领取;按 business_ref(case_no)+ 部分唯一索引保证同 Case 不重复入队; + 成功 finish 写 result_json(包含 enqueue_status / customer_step_status / validate_status); + 失败统一走错误分类: + - AppError.is_tech_retryable_error 命中 → fail_job(retryable=True) + - 其它 AppError 业务阻断 → fail_job(retryable=False) + - 非预期 Exception → category_hint=temporary_storage_error,默认 retryable=True +""" + +from __future__ import annotations + +import logging +from typing import Any + +from app.core.errors import AppError +from app.extensions import db +from app.jobs.context import JobContext +from app.jobs.queue import fail_job, finish_job +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.models import Job +from app.services.shipping_notice.recovery_contract import is_tech_retryable_error + +logger = logging.getLogger(__name__) + + +_SUCCESS_ENQUEUE_STATUSES: frozenset[str] = frozenset({ + 'queued', + 'already_queued', + 'already_running', + 'reused', + 'enqueued', + 'already_confirmed_or_terminal', +}) + + +def _classify_revalidate_error( + *, + error_code: str, + message: str, + category_hint: str | None = None, +) -> tuple[bool, dict[str, Any]]: + """ + 将 Revalidate Job 执行失败按 recovery_contract 统一分类,输出 retryable、合并后的 result。 + + 【AI 触发时机】:Handler 的两条 fail 路径(AppError 兜底、非预期 Exception 兜底) + 统一调用,确保 Job.result_json schema 一致。 + + 核心逻辑(fail-closed): + [STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀 + → result.status=failed_transient,retryable=True。 + [STEP 2] 否则 result.status=blocked_manual,retryable=False。 + [STEP 3] 返回二元组(retryable, normalized_result_dict)。 + + Args: + error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。 + message: 人类可读描述。 + category_hint: 可选;调用方已知的技术分类(temporary_storage_error 等)。 + + Returns: + (retryable: bool, normalized_result: dict)。 + """ + tech = is_tech_retryable_error(error_code, category_hint=category_hint) + result_status = 'failed_transient' if tech else 'blocked_manual' + normalized: dict[str, Any] = { + 'contract_version': 'shipping-recovery-v1-phase1', + 'status': result_status, + 'error_code': str(error_code or ''), + 'message': str(message or ''), + 'retryable': bool(tech), + 'decision_trace': { + 'contract_version': 'shipping-recovery-v1-phase1', + 'stage': 'revalidate_classify_error', + 'retryable': bool(tech), + 'matched_rule': 'tech_retryable_whitelist' if tech else 'business_blocking_default', + 'category_hint': category_hint, + }, + } + return bool(tech), normalized + + +@register_handler(JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS) +def handle_shipping_review_revalidate_progress(ctx: JobContext, payload: dict) -> None: + """ + 执行 Review Revalidate Job(字段变更后异步协调)。 + + 核心逻辑: + [STEP 0] 读取 Job 记录,冻结 payload,解析 case_no / draft_version / operation_id。 + [STEP 1] 加行锁加载 Case,Case 不存在或已终态 → finish_job(status='skipped')。 + [STEP 2] Draft 版本冲突检测:冻结版本与 Case.current_draft 不一致 → + result.draft_version_superseded,finish_job(status='skipped')。 + [STEP 3] 调用 reconcile_single_case_for_auto_progress(case, trigger='review_revalidate_job', refresh_validation=True)。 + [STEP 4] 按 enqueue_status / customer_step_status / validate_status 分类: + - 全部成功 → finish_job,写 result_json。 + [STEP 5] AppError:is_tech_retryable_error 命中 → fail_job(retryable=True),否则 retryable=False。 + [STEP 6] 非预期 Exception:category_hint=temporary_storage_error,retryable=True,最终 re-raise 保持 Worker 心跳。 + + Args: + ctx: Worker 上下文;当前执行体不依赖请求上下文。 + payload: Worker 载荷,必须含 job_id;业务字段以 Job.payload_json 为准。 + + Returns: + None。 + """ + _ = ctx + raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None + job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None + if job is None: + raise RuntimeError('missing_review_revalidate_job_id') + + job_id = int(job.id) + owned_attempt = int(job.attempts or 0) + frozen = dict(job.payload_json or {}) + frozen.setdefault('job_id', job_id) + try: + case_no = str(frozen.get('case_no') or '').strip() or None + draft_version_raw = frozen.get('draft_version') + draft_version = int(draft_version_raw) if draft_version_raw is not None else None + operation_id = frozen.get('operation_id') + if operation_id is not None: + operation_id = str(operation_id).strip() or None + if not case_no: + fail_job( + job_id, + error='missing_case_no_in_payload', + result={ + 'status': 'payload_invalid', + 'error_code': 'SHIPPING.REVALIDATE_MISSING_CASE_NO', + 'message': 'payload 缺少 case_no', + 'retryable': False, + }, + retryable=False, + owned_attempt=owned_attempt, + ) + return + + from app.models.shipping_order_review import ShippingOrderReviewCase + + case = ( + ShippingOrderReviewCase.query + .filter_by(case_no=case_no) + .with_for_update() + .first() + ) + TERMINAL_CASE_STATUSES = frozenset({ + 'confirmed', + 'non_order', + 'quality_issue', + 'superseded', + }) + if case is None or case.status in TERMINAL_CASE_STATUSES: + finish_job( + job_id, + result={ + 'status': 'skipped', + 'reason': 'case_not_found_or_terminal', + 'case_no': case_no, + 'case_status': case.status if case is not None else None, + 'operation_id': operation_id, + }, + message='Case 不存在或已终态,跳过 Review Revalidate', + owned_attempt=owned_attempt, + ) + return + + if case.current_draft is None or ( + draft_version is not None + and int(case.current_draft.draft_version) != int(draft_version) + ): + current_draft_version = ( + int(case.current_draft.draft_version) + if case.current_draft is not None + else None + ) + finish_job( + job_id, + result={ + 'status': 'draft_version_superseded', + 'reason': 'newer_draft_version_exists', + 'frozen_draft_version': draft_version, + 'current_draft_version': current_draft_version, + 'case_no': case_no, + 'operation_id': operation_id, + }, + message='Draft 版本已被更新,新版本将有自己的 Revalidate Job', + owned_attempt=owned_attempt, + ) + return + + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_single_case_for_auto_progress, + ) + + result = reconcile_single_case_for_auto_progress( + case=case, + trigger='review_revalidate_job', + refresh_validation=True, + ) + + enqueue_status = str(result.get('enqueue_status') or '').strip() or None + step_status = str(result.get('customer_step_status') or '').strip() or None + validate_status = str(result.get('validate_status') or '').strip() or None + all_ok = ( + enqueue_status in _SUCCESS_ENQUEUE_STATUSES + or enqueue_status == 'skipped' + or enqueue_status == 'not_scheduled' + ) + extra: dict[str, Any] = { + 'contract_version': 'shipping-recovery-v1-phase1', + 'status': 'ok' if all_ok else 'partial_or_failed', + 'enqueue_status': enqueue_status, + 'customer_step_status': step_status, + 'validate_status': validate_status, + 'case_no': case_no, + 'draft_version': draft_version, + 'operation_id': operation_id, + } + if isinstance(result, dict): + for pass_key in { + 'task_no', + 'stp_job_id', + 'auto_progress_job_id', + 'validation_summary', + 'can_auto_create', + 'can_build', + }: + if pass_key in result: + extra[pass_key] = result[pass_key] + finish_job( + job_id, + result={**dict(result or {}), **extra}, + message=str( + result.get('message') + or ( + f'Review Revalidate 协调完成(enqueue={enqueue_status}, validate={validate_status}' + ) + )[:2000], + owned_attempt=owned_attempt, + ) + return + except AppError as exc: + raw_code = str(getattr(exc, 'code', '') or 'SHIPPING.REVALIDATE_APP_ERROR') + raw_message = str(getattr(exc, 'message', str(exc) or '') or 'Revalidate 执行失败')[:1500] + details: dict[str, Any] = { + 'case_no': str(frozen.get('case_no') or ''), + 'draft_version': frozen.get('draft_version'), + 'operation_id': frozen.get('operation_id'), + 'error_details': dict(getattr(exc, 'details', None) or {}), + } + retryable, normalized = _classify_revalidate_error( + error_code=raw_code, + message=raw_message, + ) + if details: + normalized['blocking_reason_details'] = { + **dict(normalized.get('blocking_reason_details') or {}), + **details, + } + fail_job( + job_id, + error=str(normalized.get('message') or raw_message)[:2000], + result=normalized, + retryable=retryable, + owned_attempt=owned_attempt, + ) + return + except Exception as exc: # noqa: BLE001 + raw_message = str(exc)[:1500] + raw_code = 'SHIPPING.REVALIDATE_UNEXPECTED' + details = { + 'exception_type': type(exc).__name__, + 'case_no': str(frozen.get('case_no') or ''), + 'draft_version': frozen.get('draft_version'), + 'operation_id': frozen.get('operation_id'), + } + category_hint = 'temporary_storage_error' + retryable, normalized = _classify_revalidate_error( + error_code=raw_code, + message=raw_message, + category_hint=category_hint, + ) + if details: + normalized['blocking_reason_details'] = { + **dict(normalized.get('blocking_reason_details') or {}), + **details, + } + fail_job( + job_id, + error=str(normalized.get('message') or raw_message)[:2000], + result=normalized, + retryable=retryable, + owned_attempt=owned_attempt, + ) + raise diff --git a/backend/app/jobs/handlers/shipping_stp_auto_create.py b/backend/app/jobs/handlers/shipping_stp_auto_create.py index 428d797e..9d70ca9c 100644 --- a/backend/app/jobs/handlers/shipping_stp_auto_create.py +++ b/backend/app/jobs/handlers/shipping_stp_auto_create.py @@ -1,15 +1,25 @@ """ backend/app/jobs/handlers/shipping_stp_auto_create.py -用途:消费 STP 自动建单 Job,执行 confirm_review_case 与确认后自动推进入队。 +用途:消费 STP 自动建单 Job,执行 confirm_review_case 与确认后自动推进入队; + 按 recovery_contract 统一错误分类,业务阻断(如 NOTICE_EXACT_DUPLICATE) + retryable=false + blocked_manual,技术失败白名单 retryable=true。 依赖:JobContext、order_stp_auto_create_service.execute_stp_auto_create_job、 - jobs.queue finish/fail。 + jobs.queue finish/fail、recovery_contract(is_tech_retryable_error、 + build_stp_job_blocked_manual_result / build_stp_job_failed_transient_result、 + derive_blocking_next_actions)、fulfillment_audit.emit_stp_auto_create_blocked_manual_audit。 逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单; - 失败标记 Job failed,供 Projection 显示 retryable。 + 成功 finish,附加 task_no / idempotent_replay; + 失败统一走 _classify_stp_result: + - 技术白名单 → retryable=true(failed_transient) + - 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计) """ from __future__ import annotations +import logging +from typing import Any + from app.extensions import db from app.jobs.context import JobContext from app.jobs.queue import fail_job, finish_job @@ -19,6 +29,128 @@ from app.models import Job from app.services.shipping_notice.order_stp_auto_create_service import ( execute_stp_auto_create_job, ) +from app.services.shipping_notice.recovery_contract import ( + build_stp_job_blocked_manual_result, + build_stp_job_failed_transient_result, + derive_blocking_next_actions, + is_tech_retryable_error, +) + +logger = logging.getLogger(__name__) + + +def _classify_stp_job_result( + *, + error_code: str, + message: str, + details: dict[str, Any] | None = None, + category_hint: str | None = None, +) -> tuple[bool, dict[str, Any], str | None]: + """ + 将 STP 执行失败按 recovery_contract 统一分类,输出 retryable、合并后的 result、next_action。 + + 【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、 + 非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。 + + 核心逻辑(fail-closed): + [STEP 1] is_tech_retryable_error(error_code, category_hint) 命中白名单或前缀 + → build_stp_job_failed_transient_result,retryable=True。 + [STEP 2] 否则 build_stp_job_blocked_manual_result: + derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review; + details 合并至 blocking_reason_details。 + [STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。 + + Args: + error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。 + message: 人类可读描述。 + details: 业务上下文(case_no、existing_task_no、idempotency_key 等), + 合并至 blocking_reason_details。 + category_hint: 可选;调用方已知的技术分类(worker_timeout 等)。 + + Returns: + (retryable: bool, normalized_result: dict, next_action: str | None)。 + """ + tech = is_tech_retryable_error(error_code, category_hint=category_hint) + if tech: + transient: dict[str, Any] = build_stp_job_failed_transient_result( + error_code=error_code, + message=message, + category_hint=category_hint, + ) + if details: + transient['blocking_reason_details'] = { + **dict(transient.get('blocking_reason_details') or {}), + **dict(details), + } + return True, transient, transient.get('next_action') + + actions = derive_blocking_next_actions(blocking_reason=error_code) + next_action = actions[0] if actions else 'open_order_review' + blocked: dict[str, Any] = build_stp_job_blocked_manual_result( + error_code=error_code, + message=message, + next_action=next_action, + details=details, + ) + return False, blocked, next_action + + +def _emit_blocked_manual_audit_if_needed( + *, + job_id: int, + retryable: bool, + error_code: str, + next_action: str | None, + payload: dict[str, Any], + details: dict[str, Any] | None, +) -> None: + """ + Phase 1-5:业务阻断时写入 stp_auto_create_blocked_manual 顶层审计。 + 审计失败只告警,不阻断 Job fail。 + """ + if retryable: + return + if not error_code: + return + case_no = str(payload.get('case_no') or '').strip() or None + try: + from app.services.shipping_notice.fulfillment_audit import ( + emit_stp_auto_create_blocked_manual_audit, + ) + from app.models import ShippingOrderReviewCase + + case = None + if case_no: + case = ( + ShippingOrderReviewCase.query + .filter_by(case_no=case_no) + .order_by(ShippingOrderReviewCase.id.desc()) + .with_entities(ShippingOrderReviewCase) + .first() + ) + emit_stp_auto_create_blocked_manual_audit( + case=case, + job_id=int(job_id), + error_code=str(error_code or ''), + next_action=str(next_action or ''), + details={ + 'payload_case_no': case_no, + **(dict(details) if details else {}), + }, + ) + db.session.commit() + except Exception: # noqa: BLE001 + logger.warning( + 'stp_blocked_manual_audit_failed|job_id=%s|case_no=%s|error_code=%s', + int(job_id), + case_no, + str(error_code or ''), + exc_info=True, + ) + try: + db.session.rollback() + except Exception: + pass @register_handler(JobType.SHIPPING_STP_AUTO_CREATE) @@ -26,8 +158,14 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None: """ 执行 STP 自动建单 Job。 - 核心逻辑:按 Worker 传入的 job_id 读取冻结 payload 与执行代次;委托 - execute_stp_auto_create_job;成功 finish,业务拒绝/异常按当前代次 fail。 + 核心逻辑: + [STEP 1] 按 job_id 读取冻结 payload 与执行代次(owned_attempt)。 + [STEP 2] 委托 execute_stp_auto_create_job 执行业务确认。 + [STEP 3] 成功:finish_job,保留 task_no / idempotent_replay / contract_version。 + [STEP 4] 业务拒绝 ok=False:_classify_stp_job_result 分类 → 阻断审计 → fail_job。 + [STEP 5] AppError 兜底:同上分类 + 审计。 + [STEP 6] 非预期 Exception:category_hint=temporary_storage_error(fail-open 倾向重试), + 同上分类后 fail_job;最终 re-raise 保持 Worker 心跳。 Args: ctx: Worker 上下文;当前执行体不依赖请求上下文。 @@ -49,26 +187,105 @@ def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None: try: result = execute_stp_auto_create_job(payload=frozen, job_id=job_id) if result.get('ok'): + extra: dict[str, Any] = { + 'contract_version': 'shipping-recovery-v1-phase1', + 'status': 'ok', + } + if result.get('task_no'): + extra['task_no'] = str(result.get('task_no') or '') + if result.get('idempotent_replay'): + extra['idempotent_replay'] = True + if result.get('auto_progress_status'): + extra['auto_progress_status'] = str(result.get('auto_progress_status') or '') finish_job( job_id, - result=result, + result={**dict(result), **extra}, message=str(result.get('message') or 'STP 自动建单完成'), owned_attempt=owned_attempt, ) return + + message = str( + result.get('message') + or result.get('error') + or result.get('error_code') + or 'STP 自动建单失败' + ) or 'STP 自动建单失败' + error_code = str( + result.get('error_code') + or result.get('code') + or 'SHIPPING.STP_AUTO_CREATE_FAILED' + ) or 'SHIPPING.STP_AUTO_CREATE_FAILED' + details: dict[str, Any] = { + k: v for k, v in result.items() if k in { + 'task_no', + 'existing_task_no', + 'existing_notice_no', + 'source_content_hash', + 'duplicate_of', + 'confirmation_mode', + 'reused_task_id', + 'reused_notice_id', + 'idempotency_key', + 'case_no', + 'run_no', + '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( + error_code=error_code, + message=message, + details=details, + ) + _emit_blocked_manual_audit_if_needed( + job_id=job_id, + retryable=retryable, + error_code=error_code, + next_action=next_action, + payload=frozen, + details=details, + ) fail_job( job_id, - error=str(result.get('message') or result.get('error_code') or 'STP 自动建单失败'), - result=result, - retryable=True, + error=str(normalized.get('message') or message)[:2000], + result=normalized, + retryable=retryable, owned_attempt=owned_attempt, ) + return except Exception as exc: # noqa: BLE001 + raw_message = str(exc)[:1500] + raw_code = 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED' + details = { + 'exception_type': type(exc).__name__, + 'payload_case_no': str(frozen.get('case_no') or ''), + 'payload_run_no': str(frozen.get('run_no') or ''), + } + # [PARAM_TUNING] 非预期异常默认归类为临时存储/基础设施失败, + # 倾向可重试;若是业务阻断性异常(如 IntegrityError 唯一冲突), + # 真实错误码已在业务层捕获并走 ok=False 路径,不会流入此兜底。 + category_hint = 'temporary_storage_error' + retryable, normalized, next_action = _classify_stp_job_result( + error_code=raw_code, + message=raw_message, + details=details, + category_hint=category_hint, + ) + _emit_blocked_manual_audit_if_needed( + job_id=job_id, + retryable=retryable, + error_code=raw_code, + next_action=next_action, + payload=frozen, + details=details, + ) fail_job( job_id, - error=str(exc)[:500], - result={'status': 'failed', 'error_code': 'SHIPPING.STP_AUTO_CREATE_FAILED'}, - retryable=True, + error=str(normalized.get('message') or raw_message)[:2000], + result=normalized, + retryable=retryable, owned_attempt=owned_attempt, ) raise diff --git a/backend/app/jobs/queue.py b/backend/app/jobs/queue.py index a5e08fac..b4b625cd 100644 --- a/backend/app/jobs/queue.py +++ b/backend/app/jobs/queue.py @@ -387,6 +387,11 @@ def enqueue( commit: bool = True, correlation_id: str | None = None, scheduled_at: Any = None, + task_id: int | None = None, + execution_id: int | None = None, + gate_id: int | None = None, + candidate_set_id: int | None = None, + fencing_token: str | None = None, ) -> int: """ 将任务写入通用 jobs 队列并返回 job id。 @@ -411,6 +416,9 @@ def enqueue( commit: False 时仅 flush,由调用方与业务行同一事务提交。 correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。 scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。 + task_id / execution_id / gate_id / candidate_set_id: 正式业务作用域;AutoProgress + 使用这些列实施 Task 级活动唯一与版本围栏。 + fencing_token: Worker 领取前写入的代次围栏;迟到副作用必须比对。 """ normalized_type = _normalize_job_type(job_type) if normalized_type in {JobType.KB_CLEAN.value, JobType.KB_DIFY_SYNC.value}: @@ -464,6 +472,11 @@ def enqueue( attempts=0, max_attempts=max(1, int(max_attempts or 1)), created_by_id=created_by_id, + task_id=task_id, + execution_id=execution_id, + gate_id=gate_id, + candidate_set_id=candidate_set_id, + fencing_token=fencing_token, created_at=queue_at, updated_at=now, ) diff --git a/backend/app/jobs/runner.py b/backend/app/jobs/runner.py index 5cf994fb..e3741cb7 100644 --- a/backend/app/jobs/runner.py +++ b/backend/app/jobs/runner.py @@ -7,7 +7,7 @@ backend/app/jobs/runner.py from __future__ import annotations import time -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Callable from app.jobs import store from app.jobs.registry import get_handler @@ -24,21 +24,49 @@ def _resolve_poll_seconds(ctx: JobContext) -> float: return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2)) -def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) -> None: +def run_forever( + ctx: JobContext, + *, + poll_interval_seconds: float | None = None, + recovery_callback: Callable[[], int] | None = None, + recovery_interval_seconds: float = 60.0, +) -> None: """ 持续轮询并执行任务。 核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。 + 支持 recovery_callback:启动立即执行一次,空闲睡眠和 claim 后检查 tick。 Args: ctx: Worker 上下文(extras.queues 指定消费队列)。 poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。 + recovery_callback: 恢复回调函数,返回本轮处理计数;默认 None 关闭。 + recovery_interval_seconds: 两次 recovery tick 的最小间隔秒数;默认 60。 """ queues = ctx.extras.get('queues') or ['kb'] poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx) - ctx.logger.info('Job runner started queues=%s poll_seconds=%s', queues, poll) + ctx.logger.info('Job runner started queues=%s poll_seconds=%s recovery=%s', + queues, poll, recovery_callback is not None) + + if recovery_callback is not None: + try: + recovery_callback() + except Exception: + ctx.logger.exception('Recovery callback failed on BOOT') + finally: + last_recovery_ts = time.monotonic() + else: + last_recovery_ts = time.monotonic() while True: job = store.claim_next(queues=queues) if not job: + current_ts = time.monotonic() + if recovery_callback is not None and (current_ts - last_recovery_ts) >= recovery_interval_seconds: + try: + recovery_callback() + except Exception: + ctx.logger.exception('Recovery callback failed during idle poll') + finally: + last_recovery_ts = current_ts time.sleep(poll) continue @@ -52,6 +80,15 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) message=f'no handler for {job.get("job_type")}', owned_attempt=owned_attempt_int, ) + if recovery_callback is not None: + current_ts = time.monotonic() + if (current_ts - last_recovery_ts) >= recovery_interval_seconds: + try: + recovery_callback() + except Exception: + ctx.logger.exception('Recovery callback failed after no-handler job') + finally: + last_recovery_ts = current_ts continue try: @@ -63,3 +100,13 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) message=str(exc), owned_attempt=owned_attempt_int, ) + finally: + if recovery_callback is not None: + current_ts = time.monotonic() + if (current_ts - last_recovery_ts) >= recovery_interval_seconds: + try: + recovery_callback() + except Exception: + ctx.logger.exception('Recovery callback failed after job execution') + finally: + last_recovery_ts = current_ts diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index efdb502a..1df7d5d1 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -20,6 +20,8 @@ class JobType(StrEnum): SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction' SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout' SHIPPING_PROCESS_GATE = 'shipping_process_gate' + # Task 级正式决策器:一个 Job 只处理一个 ProcessGate。 + SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress' # XFA 合成预览就绪后的 OCR 自动标记(Job.job_type 为字符串列,无需 DB enum 迁移) SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark' # 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm) @@ -28,6 +30,8 @@ class JobType(StrEnum): SHIPPING_LINE_AUTO_FULFILL = 'shipping_line_auto_fulfill' # post-OT wave 专用 Excel/RPA 推进(禁止复用 confirm 后整单推进) SHIPPING_POST_OT_WAVE_PROGRESS = 'shipping_post_ot_wave_progress' + # Case 字段变更后异步协调:刷新校验、重跑 STP 资格判定、推进自动入队 + SHIPPING_REVIEW_REVALIDATE_PROGRESS = 'shipping_review_revalidate_progress' SCHEDULE_RUN = 'schedule_run' FILE_CHECK_RUN = 'file_check_run' WECOM_DIRECTORY_SYNC = 'wecom_directory_sync' @@ -64,8 +68,9 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'shipping': frozenset({ 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', 'shipping_document_layout', 'shipping_process_gate', 'shipping_xfa_ocr_automark', + 'shipping_auto_progress', 'shipping_stp_auto_create', 'shipping_line_auto_fulfill', - 'shipping_post_ot_wave_progress', + 'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress', }), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 6e4959c7..b9c6870f 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -12,6 +12,7 @@ from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, General from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage from app.models.department import Department from app.models.job import Job +from app.jobs.types import JobType # noqa: F401 — 与 Job 配合读库,聚合在 models 一处导入 from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig @@ -161,6 +162,12 @@ from app.models.shipping_identity_rule import ( ShippingIdentityRuleAuditEvent, ShippingIdentityRuleSet, ) +from app.models.shipping_inventory_candidates import ( + ShippingInventoryCandidateLine, + ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, +) +from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt from app.models.training import TrainingRecord from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit @@ -192,6 +199,7 @@ __all__ = [ 'KbDocumentVersion', 'KbJob', 'Job', + 'JobType', 'KbDifySyncRecord', 'WecomCallbackAudit', 'ScheduleTask', @@ -315,4 +323,8 @@ __all__ = [ 'MaintenanceDevice', 'MaintenanceRecord', 'MaintenanceAuditLog', + 'ShippingInventoryCandidateSet', + 'ShippingInventoryCandidateSource', + 'ShippingInventoryCandidateLine', + 'ShippingTaskInventoryRpaAttempt', ] diff --git a/backend/app/models/job.py b/backend/app/models/job.py index bab5c5b7..aa83ff33 100644 --- a/backend/app/models/job.py +++ b/backend/app/models/job.py @@ -30,6 +30,25 @@ class Job(Base): Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'), Index('ix_jobs_locked_at', 'locked_at'), Index('ix_jobs_retry_of_job_id', 'retry_of_job_id'), + # P0-3:同一 Task 同时只允许一个正式 AutoProgress 决策 Job。库存源 RPA + # Attempt 不使用该索引,因此可以按 source 并行执行。 + Index( + 'uq_jobs_shipping_auto_progress_one_active_task', + 'task_id', + unique=True, + postgresql_where=text( + "domain = 'shipping_notice' " + "AND job_type = 'shipping_auto_progress' " + "AND status IN ('queued', 'running') " + "AND task_id IS NOT NULL" + ), + sqlite_where=text( + "domain = 'shipping_notice' " + "AND job_type = 'shipping_auto_progress' " + "AND status IN ('queued', 'running') " + "AND task_id IS NOT NULL" + ), + ), # 仅预解析 Job:同业务锚点同时只允许一条 queued # (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限) Index( @@ -101,6 +120,26 @@ class Job(Base): "AND business_ref IS NOT NULL" ), ), + # Review Revalidate Job:同 Case 同时只允许一条 queued/running(failed 可新建重试 Job) + Index( + 'uq_jobs_shipping_review_revalidate_progress_active_ref', + 'domain', + 'job_type', + 'business_ref', + unique=True, + postgresql_where=text( + "domain = 'shipping_notice' " + "AND job_type = 'shipping_review_revalidate_progress' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + sqlite_where=text( + "domain = 'shipping_notice' " + "AND job_type = 'shipping_review_revalidate_progress' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + ), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -120,6 +159,18 @@ class Job(Base): locked_at: Mapped[Optional[datetime]] = mapped_column(DateTime) # 重试链:新 Job 指向被替换的 failed/dead Job,保留旧行审计。 retry_of_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True) + # 正式编排作用域。payload 仍保留相同 identity,列用于数据库唯一约束、恢复扫描和审计查询。 + task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True, index=True) + execution_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_process_executions.id'), nullable=True, index=True, + ) + gate_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_process_gates.id'), nullable=True, index=True, + ) + candidate_set_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True, + ) + fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 80749c54..ddbd3647 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -58,6 +58,8 @@ class ShippingNotice(Base): Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'), Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'), Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'), + Index('ix_shipping_notices_active_inventory_candidate_set_id', 'active_inventory_candidate_set_id'), + Index('ix_shipping_notices_active_process_execution_id', 'active_process_execution_id'), Index('ix_shipping_notices_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'), Index('ix_shipping_notices_user_source_content_hash', 'user_id', 'source_content_hash'), Index('ix_shipping_notices_user_business_fingerprint', 'user_id', 'business_fingerprint'), @@ -142,6 +144,23 @@ class ShippingNotice(Base): inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column( + ForeignKey( + 'shipping_inventory_candidate_sets.id', + name='fk_shipping_notices_active_inventory_candidate_set_id', + use_alter=True, + ), + nullable=True, + ) + # P0-3:当前业务真相只由此 Execution 的六个正式 Gate 决定;历史 Execution 保留审计。 + active_process_execution_id: Mapped[Optional[int]] = mapped_column( + ForeignKey( + 'shipping_process_executions.id', + name='fk_shipping_notices_active_process_execution_id', + use_alter=True, + ), + nullable=True, + ) inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) # 动态订单 FieldValue 编辑的乐观锁版本。 diff --git a/backend/app/models/shipping_inventory_candidates.py b/backend/app/models/shipping_inventory_candidates.py new file mode 100644 index 00000000..2e851daa --- /dev/null +++ b/backend/app/models/shipping_inventory_candidates.py @@ -0,0 +1,220 @@ +""" +models/shipping_inventory_candidates.py + +用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。 + InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源), + 同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存 + 同一时刻的完整不可变副本,用于审计与回滚。 +依赖:Base、ShippingNotice、ShippingProcessExecution、ShippingOrderReviewCase、users、 + ShippingInventoryRoutingRule(可选外键,路由规则版本)。 +逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结; + input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等); + source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import ( + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + Text, + UniqueConstraint, + text, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +def _utc_now() -> datetime: + """返回 naive UTC 时间,与仓库其他模型一致。""" + return datetime.utcnow() + + +class ShippingInventoryCandidateSet(Base): + """ + 库存候选集合(冻结真相根)。 + + 核心逻辑:一次候选冻结对应一个 Set;input_fingerprint 相同 + 绑定对象相同则幂等复用; + 同时支持绑定 task_id(建单后)和 review_case_id(建单前草稿复核)两种场景, + 二者至少一个非空(CheckConstraint 强制)。 + """ + + __tablename__ = 'shipping_inventory_candidate_sets' + __table_args__ = ( + CheckConstraint( + 'task_id IS NOT NULL OR review_case_id IS NOT NULL', + name='ck_shipping_inv_cand_sets_binding', + ), + CheckConstraint('set_version >= 1', name='ck_shipping_inv_cand_sets_version'), + CheckConstraint( + "lifecycle_status IN ('draft', 'frozen', 'superseded', 'invalidated')", + name='ck_shipping_inv_cand_sets_lifecycle', + ), + Index( + 'uq_shipping_inv_cand_sets_task_fp', + 'task_id', 'input_fingerprint', + unique=True, + postgresql_where=text('task_id IS NOT NULL'), + sqlite_where=text('task_id IS NOT NULL'), + ), + UniqueConstraint('task_id', 'set_version', name='uq_shipping_inv_cand_sets_task_version'), + Index( + 'uq_shipping_inv_cand_sets_review_fp', + 'review_case_id', 'input_fingerprint', + unique=True, + postgresql_where=text('review_case_id IS NOT NULL'), + sqlite_where=text('review_case_id IS NOT NULL'), + ), + Index('ix_shipping_inv_cand_sets_task_frozen', 'task_id', 'frozen_at'), + Index('ix_shipping_inv_cand_sets_review_frozen', 'review_case_id', 'frozen_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + set_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') + task_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=True, + ) + review_case_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=True, + ) + execution_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True, + ) + lifecycle_status: Mapped[str] = mapped_column( + String(32), nullable=False, default='frozen', server_default='frozen', + ) + frozen_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False) + frozen_by_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('users.id'), nullable=True, + ) + superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + superseded_by_set_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True, + ) + invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + input_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False) + routing_rule_version_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + manifest_snapshot_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, + ) + remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + + sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship( + back_populates='candidate_set', + cascade='all, delete-orphan', + order_by='ShippingInventoryCandidateSource.candidate_order', + ) + lines: Mapped[list['ShippingInventoryCandidateLine']] = relationship( + back_populates='candidate_set', + cascade='all, delete-orphan', + order_by='ShippingInventoryCandidateLine.line_no', + ) + + +class ShippingInventoryCandidateSource(Base): + """ + 任务级候选库存源(Set 的子级)。 + + 核心逻辑:多源 RPA 按 (set_id, source_code) 唯一创建 Trigger / Attempt, + candidate_order 本身就是路由优先级(不能丢),不能用 SET 无序存储。 + candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。 + """ + + __tablename__ = 'shipping_inventory_candidate_sources' + __table_args__ = ( + UniqueConstraint( + 'candidate_set_id', 'source_code', + name='uq_shipping_inv_cand_sources_set_source', + ), + CheckConstraint( + "candidate_origin IN ('rule', 'manual_override')", + name='ck_shipping_inv_cand_sources_origin', + ), + CheckConstraint('candidate_order >= 1', name='ck_shipping_inv_cand_sources_order'), + Index( + 'ix_shipping_inv_cand_sources_set_order', + 'candidate_set_id', 'candidate_order', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + candidate_set_id: Mapped[int] = mapped_column( + ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False, + ) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + candidate_order: Mapped[int] = mapped_column(Integer, nullable=False) + candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule') + routing_rule_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), nullable=True, + ) + routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + override_by_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('users.id'), nullable=True, + ) + override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, + ) + + candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship( + back_populates='sources', + ) + + +class ShippingInventoryCandidateLine(Base): + """ + 行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。 + + 核心逻辑:source_codes_json 是**有序列表**(不是 set),顺序即行级路由优先级; + line_no 始终使用任务快照内稳定顺序号,source_line_no 只保存原始单据行号做审计; + 跨源匹配需要按行读取候选集合,所以结构化存 line_no + source_line_no + + part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。 + """ + + __tablename__ = 'shipping_inventory_candidate_lines' + __table_args__ = ( + UniqueConstraint( + 'candidate_set_id', 'line_no', + name='uq_shipping_inv_cand_lines_set_line', + ), + Index( + 'ix_shipping_inv_cand_lines_set_pn_resv', + 'candidate_set_id', 'part_number', 'reservation_id', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + candidate_set_id: Mapped[int] = mapped_column( + ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False, + ) + line_no: Mapped[int] = mapped_column(Integer, nullable=False) + source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list) + override_by_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('users.id'), nullable=True, + ) + override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, + ) + + candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship( + back_populates='lines', + ) diff --git a/backend/app/models/shipping_notice_line_inventory_match.py b/backend/app/models/shipping_notice_line_inventory_match.py index c75a7887..ea56ac8c 100644 --- a/backend/app/models/shipping_notice_line_inventory_match.py +++ b/backend/app/models/shipping_notice_line_inventory_match.py @@ -55,14 +55,14 @@ class ShippingNoticeLineInventoryMatch(Base): CheckConstraint( "match_result IN (" "'matched', 'not_found', 'result_missing', 'preparing', " - "'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable'" + "'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable', 'invalid'" ")", name='ck_shipping_notice_line_inv_match_result', ), CheckConstraint( "inventory_status IN (" "'ready', 'preparing', 'mapping_failed', 'source_conflict', " - "'unavailable', 'invalid_key'" + "'unavailable', 'invalid_key', 'invalid'" ")", name='ck_shipping_notice_line_inv_match_status', ), @@ -79,6 +79,17 @@ class ShippingNoticeLineInventoryMatch(Base): ) line_key: Mapped[str] = mapped_column(String(64), nullable=False) line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + candidate_set_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), + nullable=True, + index=True, + ) + candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + candidate_line_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_candidate_lines.id', ondelete='SET NULL'), + nullable=True, + index=True, + ) inventory_snapshot_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, @@ -110,3 +121,15 @@ class ShippingNoticeLineInventoryMatch(Base): onupdate=datetime.utcnow, nullable=False, ) + # T6: 行级实际源证据(决策 E1 硬约束)——用于幂等保护与跨源匹配审计。 + matched_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True) + matched_row_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + evidence_ref: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + allowed_source_codes_snapshot: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True) + matched_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + evidence_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + match_attempt_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'), + nullable=True, + index=True, + ) diff --git a/backend/app/models/shipping_order_review_suggestion.py b/backend/app/models/shipping_order_review_suggestion.py index 0a1dcc9a..ecdf0fda 100644 --- a/backend/app/models/shipping_order_review_suggestion.py +++ b/backend/app/models/shipping_order_review_suggestion.py @@ -3,7 +3,10 @@ backend/app/models/shipping_order_review_suggestion.py 用途:持久化订单复核 LLM 建议请求、验证结果与人工裁决。 依赖:SQLAlchemy Base、Review Case / Document 外键。 -逻辑:建议只能预填草稿;accept/modify/reject 写入裁决字段;不得自动冻结。 +逻辑: + - 建议只能预填草稿;accept/modify/reject 写入裁决字段;不得自动冻结。 + - v2:新增 status=gated_failed;evidence_level 扩展新枚举; + 新增 8 个 provider & trace 独立列;旧数据不 backfill。 """ from __future__ import annotations @@ -11,7 +14,7 @@ from __future__ import annotations from datetime import datetime from typing import Any, Optional -from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint +from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base @@ -24,12 +27,14 @@ class ShippingOrderReviewSuggestion(Base): __table_args__ = ( UniqueConstraint('suggestion_no', name='uq_shipping_order_review_suggestions_no'), CheckConstraint( - "status IN ('pending', 'validated', 'validation_failed', 'accepted', 'modified', " - "'rejected', 'failed', 'provider_unavailable')", + "status IN ('pending', 'gated_failed', 'validated', 'validation_failed', " + "'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable')", name='ck_shipping_order_review_suggestions_status', ), CheckConstraint( - "evidence_level IN ('L1_field', 'L2_table', 'L3_page', 'L4_pdf')", + "evidence_level IN (" + "'L1_field', 'L2_table', 'L3_page', 'L4_pdf', " + "'L2_row', 'L3_table', 'L4_page', 'L5_document')", name='ck_shipping_order_review_suggestions_evidence_level', ), CheckConstraint( @@ -38,6 +43,18 @@ class ShippingOrderReviewSuggestion(Base): ), Index('ix_shipping_order_review_suggestions_case', 'review_case_id', 'created_at'), Index('ix_shipping_order_review_suggestions_document', 'document_id', 'id'), + Index( + 'ix_shipping_order_review_suggestions_provider_conversation', + 'provider_conversation_id', + ), + Index( + 'ix_shipping_order_review_suggestions_context_hash', + 'context_hash', + ), + Index( + 'ix_shipping_order_review_suggestions_status_created', + 'status', 'created_at', + ), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -75,5 +92,14 @@ class ShippingOrderReviewSuggestion(Base): updated_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, ) + # —— v2 新增列:provider & trace 独立列;历史数据保持 NULL/默认值,不回填 + provider: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + provider_conversation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + provider_message_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + latency_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + context_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + evidence_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') + context_truncated: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default='false') + auto_upgrade_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) case = relationship('ShippingOrderReviewCase', back_populates='llm_suggestions') diff --git a/backend/app/models/shipping_process_gate.py b/backend/app/models/shipping_process_gate.py index 45f6bc3b..6aea68f8 100644 --- a/backend/app/models/shipping_process_gate.py +++ b/backend/app/models/shipping_process_gate.py @@ -42,7 +42,7 @@ class ShippingProcessExecution(Base): __table_args__ = ( UniqueConstraint('execution_no', name='uq_shipping_process_executions_no'), CheckConstraint( - "status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed')", + "status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed', 'superseded')", name='ck_shipping_process_executions_status', ), CheckConstraint('lock_version >= 1', name='ck_shipping_process_executions_lock_version'), @@ -65,6 +65,7 @@ class ShippingProcessExecution(Base): 'ix_shipping_process_executions_task', 'task_id', ), + Index('ix_shipping_process_executions_candidate_set', 'candidate_set_id', 'status'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -75,6 +76,13 @@ class ShippingProcessExecution(Base): task_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_notices.id'), nullable=True, ) + # 绑定候选版本,防止旧 callback/job 写入新候选链。 + candidate_set_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, + ) + execution_revision: Mapped[int] = mapped_column( + Integer, nullable=False, default=1, server_default='1', + ) status: Mapped[str] = mapped_column( String(32), nullable=False, default='active', server_default='active', ) @@ -113,7 +121,7 @@ class ShippingProcessGate(Base): CheckConstraint( "status IN (" "'pending', 'queued', 'running', 'passed', 'blocked_retryable', " - "'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped'" + "'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped', 'cancelled'" ")", name='ck_shipping_process_gates_status', ), diff --git a/backend/app/models/shipping_task_inventory_rpa_attempts.py b/backend/app/models/shipping_task_inventory_rpa_attempts.py new file mode 100644 index 00000000..4abbbd30 --- /dev/null +++ b/backend/app/models/shipping_task_inventory_rpa_attempts.py @@ -0,0 +1,122 @@ +""" +models/shipping_task_inventory_rpa_attempts.py + +用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。 +依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。 +逻辑:每个库存源(task_no, source_code)独立计数 attempt_no / run_no; + Trigger 文件名格式 SN-__.trigger.json;回调按三元组 + (task_no, source_code, run_no) 定位 Attempt;迟到回调(run_no < 当前 consumed) + 标记 superseded 不写快照,保证幂等。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any, Optional + +from sqlalchemy import ( + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + Text, + UniqueConstraint, +) +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Mapped, mapped_column, relationship, synonym + +from app.models.base import Base + +_JSON_FOR_SQLITE = JSON().with_variant(JSONB(), "postgresql") + +if TYPE_CHECKING: + pass + + +PER_SOURCE_RPA_ATTEMPT_STATUSES = ( + 'queued', # 已写 trigger 文件,等待 RPA Worker 领取 + 'running', # RPA Worker 已领取(租约写入 lease_token) + 'succeeded', # 回调成功,快照已 ingest 并校验通过 + 'failed', # 回调返回失败或超时判定失败 + 'consumed', # 业务侧已消费该快照(推进到下一 Gate) + 'superseded', # 迟到回调:run_no 早于已 consumed 的 run_no,忽略不写业务 + 'exhausted', # 当前 (task, source) 对已达最大 attempt 且未成功 +) + + +class ShippingTaskInventoryRpaAttempt(Base): + """逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。""" + + __tablename__ = 'shipping_task_inventory_rpa_attempts' + __table_args__ = ( + # 三元组唯一:同一运行号同一源只允许一条记录 + UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'), + # PostgreSQL 部分唯一索引:每个 (task, source) 同时只允许 1 条活动(queued/running)Attempt + Index( + 'uq_shipping_task_inv_rpa_active_per_source', + 'task_no', 'source_code', + unique=True, + postgresql_where="status IN ('queued','running')", + ), + # 扫描超时 & 最新 Attempt 常用查询维度 + Index('ix_shipping_task_inv_rpa_task_source', 'task_no', 'source_code', 'attempt_no'), + Index('ix_shipping_task_inv_rpa_status_updated', 'status', 'updated_at'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in PER_SOURCE_RPA_ATTEMPT_STATUSES)})", + name='ck_shipping_task_inv_rpa_status_enum', + ), + CheckConstraint('attempt_no >= 1', name='ck_shipping_task_inv_rpa_attempt_positive'), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + + task_no: Mapped[str] = mapped_column(String(64), nullable=False, index=True) + source_code: Mapped[str] = mapped_column(String(32), nullable=False, index=True) + + attempt_no: Mapped[int] = mapped_column(Integer, nullable=False) + source_run_no: Mapped[str] = mapped_column(String(128), nullable=False) + # 仅为历史调用方提供 Python 层读取兼容;数据库正式事实只有 source_run_no。 + run_no = synonym('source_run_no') + + callback_id: Mapped[str | None] = mapped_column(String(256), nullable=True, unique=True) + + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', index=True) + + trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) + callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) + inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + + lease_token: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + leased_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True) + lease_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True) + + callback_payload_json: Mapped[dict[str, Any]] = mapped_column(_JSON_FOR_SQLITE, nullable=False, default=dict) + extra_json: Mapped[dict[str, Any]] = mapped_column(_JSON_FOR_SQLITE, nullable=False, default=dict) + + triggered_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True) + callback_received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True) + claimed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True) + worker_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + execution_phase: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + file_generated: Mapped[bool] = mapped_column(default=False, nullable=False) + file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) + file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + file_exists_at_callback: Mapped[Optional[bool]] = mapped_column(nullable=True) + transaction_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + transaction_error_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + transaction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=False), nullable=True) + + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=False), nullable=False, default=datetime.utcnow, index=True, + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=False), nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, index=True, + ) diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py new file mode 100644 index 00000000..21b673a3 --- /dev/null +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -0,0 +1,316 @@ +""" +services/shipping_notice/auto_progress_controller.py + +用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。 +依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务。 +逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job + 在同一数据库事务落库。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime +from typing import Any + +from app import db +from app.jobs.queue import enqueue +from app.jobs.types import JobType +from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate +from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set +from app.services.shipping_notice.tool_common import log_task_event + + +AUTO_PROGRESS_GATE_CODES: tuple[str, ...] = ( + 'inventory_candidates_calculated', + 'inventory_candidates_frozen', + 'inventory_snapshots_ready', + 'inventory_matched', + 'excel_generated', + 'upload_receipt_recorded', +) +_ACTIVE_JOB_STATUSES = ('queued', 'running') +_CANCELLED_TASK_STATUSES = frozenset({'cancelled', 'canceled', 'closed', 'rejected'}) + + +def _utc_now() -> datetime: + """返回仓库统一使用的 naive UTC 时间。""" + return datetime.utcnow() + + +def _task_is_cancelled(task: ShippingNotice) -> bool: + """根据服务端 Task 事实判断取消/关闭任务,旧 Job 不得将其复活。""" + return str(getattr(task, 'process_status', '') or '').strip().lower() in _CANCELLED_TASK_STATUSES + + +def _new_execution_no() -> str: + """生成可读的 P0-3 Execution 编号。""" + return f'APX-{_utc_now().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}' + + +def _create_execution(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution: + """ + 为当前 Task/CandidateSet 创建独立六 Gate 链。 + + 核心逻辑:不复用旧 20 Gate Execution,避免旧 skipped/waiting_external 语义污染 P0-3 的严格顺序。 + """ + execution = ShippingProcessExecution( + execution_no=_new_execution_no(), task_id=int(task.id), candidate_set_id=candidate_set_id, + execution_revision=1, status='active', current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1, + ) + db.session.add(execution) + db.session.flush() + for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1): + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), gate_code=gate_code, sequence_no=sequence_no, + status='pending', evaluation_version=1, lock_version=1, + )) + task.active_process_execution_id = int(execution.id) + db.session.flush() + return execution + + +def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution: + """锁定并取得当前 Execution;候选版本变化时旧链 superseded 后创建新链。""" + current_id = getattr(task, 'active_process_execution_id', None) + execution = db.session.get(ShippingProcessExecution, int(current_id)) if current_id else None + if execution is not None: + execution = ( + ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().first() + ) + if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(task.id): + execution = None + if execution is not None and int(getattr(execution, 'candidate_set_id', 0) or 0) != int(candidate_set_id or 0): + # 旧链永不覆盖:未完成 Gate 取消,Execution 留审计后由新 CandidateSet 建链。 + execution.status = 'superseded' + ShippingProcessGate.query.filter( + ShippingProcessGate.execution_id == int(execution.id), + ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')), + ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) + execution = None + return execution or _create_execution(task, candidate_set_id=candidate_set_id) + + +def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None: + """ + 在 CandidateSet 指针切换后取消旧 Job/未完成 Gate,防止旧版本副作用污染新链。 + + 调用方必须已持有 Task 的业务事务;本函数不 commit,随后 submit 会创建新 CandidateSet 的 Execution。 + """ + execution_id = getattr(task, 'active_process_execution_id', None) + if execution_id: + execution = ShippingProcessExecution.query.filter_by(id=int(execution_id)).with_for_update().first() + if execution is not None and execution.status not in {'completed', 'cancelled', 'superseded'}: + execution.status = 'superseded' + ShippingProcessGate.query.filter( + ShippingProcessGate.execution_id == int(execution.id), + ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')), + ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) + Job.query.filter( + Job.domain == 'shipping_notice', Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value, + Job.task_id == int(task.id), Job.status == 'queued', + ).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False) + + +def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[ShippingProcessGate | None, str | None]: + """ + 返回严格最早未通过 Gate,或一致性错误。 + + 后置 Gate 已通过而前置未通过意味着投影事实矛盾;此时禁止自动推进并交给管理员诊断。 + """ + gates = ( + ShippingProcessGate.query.filter_by(execution_id=int(execution.id)) + .order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all() + ) + expected = list(AUTO_PROGRESS_GATE_CODES) + if [item.gate_code for item in gates] != expected: + return None, 'projection_data_inconsistent' + pending_seen = False + for gate in gates: + if gate.status == 'passed': + if pending_seen: + return None, 'projection_data_inconsistent' + continue + pending_seen = True + if gate.status in {'pending', 'blocked_retryable'}: + return gate, None + # 上传回执是人工完成的外部事实,不是“重试业务动作”。登记成功后仅允许 + # 服务端重新读取该事实并通过最后一个 Gate。 + if gate.gate_code == 'upload_receipt_recorded' and gate.status == 'blocked_manual': + return gate, None + return None, None + return None, None + + +def submit_auto_progress( + *, task: ShippingNotice, trigger: str, operator_id: int | None = None, + resume_gate_code: str | None = None, commit: bool = True, +) -> dict[str, Any]: + """ + 接收任何自动/用户触发并安全入队当前 Gate。 + + 普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。 + """ + locked_task = ShippingNotice.query.filter_by(id=int(task.id)).with_for_update().first() + if locked_task is None: + return {'status': 'not_found'} + if _task_is_cancelled(locked_task): + return {'status': 'cancelled', 'task_no': locked_task.task_no} + # 先查活动 Job,再读取/改写 Candidate 或 Execution 指针。这样候选重冻结与重复点击 + # 无法把一个仍 running 的旧 Job 错绑到新链。 + active = ( + Job.query.filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value, + Job.task_id == int(locked_task.id), + Job.status.in_(_ACTIVE_JOB_STATUSES), + ).with_for_update().order_by(Job.id.desc()).first() + ) + if active is not None: + if commit: + db.session.commit() + return { + 'status': 'queued' if active.status == 'queued' else 'running', + 'job_id': int(active.id), 'execution_id': active.execution_id, + 'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True, + } + candidate = get_active_candidate_set(locked_task) + candidate_set_id = int(candidate.id) if candidate is not None else None + execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id) + gate, inconsistency = _earliest_runnable_gate(execution) + if inconsistency: + execution.status = 'blocked' + execution.current_gate_code = None + log_task_event(locked_task, 'auto_progress_projection_inconsistent', { + 'execution_id': execution.id, 'reason_code': inconsistency, + }, actor_id=operator_id, source=trigger) + if commit: + db.session.commit() + return {'status': 'waiting_human', 'reason_code': inconsistency, 'execution_id': execution.id} + if gate is None: + if commit: + db.session.commit() + return {'status': 'waiting_human' if execution.status == 'blocked' else 'completed', 'execution_id': execution.id} + business_ref = f'auto-progress:{int(locked_task.id)}' + token = uuid.uuid4().hex + job_id = enqueue( + JobType.SHIPPING_AUTO_PROGRESS, + {'task_no': locked_task.task_no, 'task_id': int(locked_task.id), 'execution_id': int(execution.id), + 'candidate_set_id': candidate_set_id, 'gate_id': int(gate.id), 'gate_code': gate.gate_code, + 'trigger': trigger, 'requested_resume_gate_code': resume_gate_code, 'fencing_token': token}, + domain='shipping_notice', business_ref=business_ref, created_by_id=operator_id, + message=f'等待执行正式 Gate:{gate.gate_code}', max_attempts=1, commit=False, + task_id=int(locked_task.id), execution_id=int(execution.id), gate_id=int(gate.id), + candidate_set_id=candidate_set_id, fencing_token=token, + ) + execution.current_gate_code = gate.gate_code + log_task_event(locked_task, 'auto_progress_job_queued', { + 'job_id': job_id, 'execution_id': execution.id, 'candidate_set_id': candidate_set_id, + 'gate_id': gate.id, 'gate_code': gate.gate_code, 'trigger': trigger, + }, actor_id=operator_id, source=trigger) + if commit: + db.session.commit() + return {'status': 'queued', 'job_id': int(job_id), 'execution_id': int(execution.id), 'gate_code': gate.gate_code} + + +def _gate_outcome(task: ShippingNotice, gate: ShippingProcessGate) -> tuple[str, str | None, dict[str, Any]]: + """仅执行一个 Gate 并把现有业务服务结果归一为正式 Gate 结果。""" + code = gate.gate_code + candidate = get_active_candidate_set(task) + if code == 'inventory_candidates_calculated': + return ('passed', None, {}) if candidate is not None else ('blocked_manual', 'inventory_candidates_required', {}) + if code == 'inventory_candidates_frozen': + frozen = candidate is not None and str(candidate.lifecycle_status) == 'frozen' + return ('passed', None, {}) if frozen else ('blocked_manual', 'inventory_candidates_frozen_required', {}) + if code == 'inventory_snapshots_ready': + from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared + result = ensure_all_required_sources_prepared(task, mode='auto') + if result.all_prepared: + return 'passed', None, {'prepared_sources': result.prepared_source_codes} + if result.failed_source_codes: + return 'blocked_manual', 'inventory_snapshot_prepare_failed', {'failed_sources': result.failed_source_codes} + return 'blocked_retryable', 'inventory_snapshots_pending', {'pending_sources': result.pending_source_codes} + if code == 'inventory_matched': + from app.services.shipping_notice.fulfillment_workflow import match_inventory + result = match_inventory({'task_id': task.task_no, '_orchestrator_internal_dispatch': True}) + status = str((result or {}).get('status') or '') + if status in {'ok', 'completed'}: + return 'passed', None, {} + return 'blocked_manual' if status == 'needs_human' else 'blocked_retryable', 'inventory_match_not_ready', {'legacy_status': status} + if code == 'excel_generated': + from app.services.shipping_notice.fulfillment_workflow import generate_excel + result = generate_excel({'task_id': task.task_no, '_orchestrator_internal_dispatch': True}) + if str((result or {}).get('status') or '') == 'ok' and task.export_file_path: + return 'passed', None, {'export_file_path': task.export_file_path} + return 'blocked_retryable', 'excel_generation_not_ready', {'legacy_status': (result or {}).get('status')} + receipt = getattr(task, 'upload_receipt_json', None) + if receipt or str(getattr(task, 'process_status', '') or '').lower() in {'uploaded', 'completed'}: + return 'passed', None, {} + return 'blocked_manual', 'manual_upload_receipt_required', {} + + +def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]: + """ + Worker 执行一个且仅一个 Gate,并以 Job outbox 原子提交 Gate 成功和下一个 Job。 + + 所有围栏、Task 取消和 Candidate/Execution identity 都在外部调用前复查;不匹配的迟到 Job 只终态审计。 + """ + job = Job.query.filter_by(id=int(job_id)).with_for_update().first() + if job is None or job.status != 'running': + return {'status': 'noop'} + payload = dict(job.payload_json or {}) + task = ShippingNotice.query.filter_by(id=int(job.task_id or 0)).with_for_update().first() + execution = ShippingProcessExecution.query.filter_by(id=int(job.execution_id or 0)).with_for_update().first() + gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first() + stale = ( + task is None or execution is None or gate is None or _task_is_cancelled(task) + or int(getattr(task, 'active_process_execution_id', 0) or 0) != int(execution.id) + or int(getattr(execution, 'candidate_set_id', 0) or 0) != int(job.candidate_set_id or 0) + or int(gate.execution_id) != int(execution.id) + or str(job.fencing_token or '') != str(payload.get('fencing_token') or '') + ) + if stale: + job.status = 'cancelled'; job.finished_at = _utc_now(); job.message = '任务已取消或版本围栏不匹配' + if gate is not None and gate.status in {'pending', 'queued', 'running'}: + gate.status = 'cancelled' + db.session.commit() + return {'status': 'cancelled'} + runnable, inconsistency = _earliest_runnable_gate(execution) + if inconsistency or runnable is None or int(runnable.id) != int(gate.id): + gate.status = 'blocked_manual'; gate.blocking_reason_code = inconsistency or 'projection_data_inconsistent' + execution.status = 'blocked'; job.status = 'success'; job.finished_at = _utc_now() + db.session.commit() + return {'status': 'waiting_human', 'reason_code': gate.blocking_reason_code} + + gate.status = 'running'; gate.updated_at = _utc_now(); db.session.flush() + outcome, reason_code, details = _gate_outcome(task, gate) + gate.status = outcome; gate.blocking_reason_code = reason_code; gate.effective_result_json = details + gate.updated_at = _utc_now(); job.status = 'success'; job.finished_at = _utc_now(); job.message = f'Gate {outcome}' + if outcome != 'passed': + execution.status = 'blocked'; execution.current_gate_code = gate.gate_code + log_task_event(task, 'auto_progress_gate_blocked', {'gate_code': gate.gate_code, 'reason_code': reason_code}, source='worker') + db.session.commit() + return {'status': outcome, 'gate_code': gate.gate_code, 'reason_code': reason_code} + + gate.passed_at = _utc_now(); execution.last_passed_gate_code = gate.gate_code + # 先 flush 当前 Job 成功态,释放 Task 级 active partial unique;后继 Job 与 Gate passed + # 仍处在同一外层事务,commit 前对 Worker 不可见。 + db.session.flush() + next_gate, consistency_error = _earliest_runnable_gate(execution) + if consistency_error: + execution.status = 'blocked'; execution.current_gate_code = None + elif next_gate is None: + execution.status = 'completed'; execution.current_gate_code = None + elif next_gate.gate_code == 'upload_receipt_recorded': + # 上传自动化关闭时,Excel 后明确等人工登记回执,不擅自跨越此 Gate。 + execution.status = 'blocked'; execution.current_gate_code = next_gate.gate_code + next_gate.status = 'blocked_manual'; next_gate.blocking_reason_code = 'manual_upload_receipt_required' + else: + execution.status = 'active'; execution.current_gate_code = next_gate.gate_code + submit_auto_progress(task=task, trigger='gate_passed', commit=False) + log_task_event(task, 'auto_progress_gate_passed', {'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code}, source='worker') + db.session.commit() + return { + 'status': 'passed', 'execution_id': int(execution.id), + 'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code, + } diff --git a/backend/app/services/shipping_notice/candidate_qualification_contract.py b/backend/app/services/shipping_notice/candidate_qualification_contract.py index 98773fd0..be4773cb 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_contract.py +++ b/backend/app/services/shipping_notice/candidate_qualification_contract.py @@ -21,10 +21,13 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({ }) # 资格评估器版本;快照持久化时写入 evaluator_version。 -CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v2-xfa' +# 变更点:2026-08-08 引入 VC 三来源门禁,版本 bump。 +CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v2.1-vc' # 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。 # XFA 专属门禁对非 XFA Candidate 恒为 True(N/A 放行)。 +# VC 门禁 vc_source_merged_clean 放在 field_conflicts_resolved 之后, +# 以便冲突项先被 PDF 优先裁决,剩余 needs_review 项再由本门禁拦截。 CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = ( 'auto_create_enabled', 'classification_confidence', @@ -32,6 +35,7 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = ( 'key_fields_minimum_confidence', 'evidence_complete', 'field_conflicts_resolved', + 'vc_source_merged_clean', 'duplicate_resolved', 'customer_confirmed', 'idempotency_ok', @@ -46,10 +50,11 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = ( CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = { 'auto_create_enabled': 'auto_create_disabled', 'classification_confidence': 'classification_low_confidence', - 'required_fields_complete': 'required_field_missing', + 'required_fields_complete': 'final_required_field_missing', 'key_fields_minimum_confidence': 'field_low_confidence', 'evidence_complete': 'evidence_missing', 'field_conflicts_resolved': 'field_conflict', + 'vc_source_merged_clean': 'vc_source_conflict_unresolved', 'duplicate_resolved': 'duplicate_unresolved', 'customer_confirmed': 'customer_confirmation_required', 'idempotency_ok': 'task_already_exists', @@ -70,6 +75,8 @@ CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({ 'field_low_confidence', # PDF 优先已选定当前值,但仍须人工确认冲突后方可自动建单。 'pdf_preferred_critical_conflict', + # Vendor Comments 三来源值不一致,须人工裁决但不硬阻塞人工建单。 + 'vc_source_conflict_unresolved', }) # 解析来源(写入 parser_trace,不直接决定资格)。 diff --git a/backend/app/services/shipping_notice/candidate_qualification_service.py b/backend/app/services/shipping_notice/candidate_qualification_service.py index 5b808f8e..8ea95378 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_service.py +++ b/backend/app/services/shipping_notice/candidate_qualification_service.py @@ -35,6 +35,11 @@ from app.services.shipping_notice.candidate_qualification_contract import ( CANDIDATE_QUALIFICATION_GATE_REASON_CODES, CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES, ) +from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import ( + CQ_VC_BLOCKING_REASONS, + CQ_VC_REVIEW_REASONS, + collect_vc_candidate_conflicts, +) from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.document_layout.xfa_contract import ( XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES, @@ -89,6 +94,10 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]: 核心逻辑:过滤仅描述文档版面/坐标质量的诊断项;字段值冲突、跨来源冲突 与其他未知阻断项继续 fail-closed。 + 注意:Vendor Comments 三来源冲突由独立 vc_source_merged_clean 门禁 + (见 _vc_gate_ok)评估,不入本集合,避免污染 field_conflicts_resolved + 原有零回归语义。 + Args: candidate: ShippingOrderCandidate 或兼容替身。 @@ -108,6 +117,68 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]: ] +# --------------------------------------------------------------------------- +# VC 三来源门禁:独立于 Candidate.conflicts_json,从 structured.extraction +# vendor_comments_merged 读,避免冲突历史与裁决历史相互污染。 +# --------------------------------------------------------------------------- +def _vc_gate_ok(candidate: Any) -> bool: + """ + VC 三来源合并结果是否全部清洁(无阻断冲突)。 + + 核心逻辑:缺 VC merged 载荷 → 视为未启用 → OK; + severity == blocking 的项 → 必须视为 fail(硬阻断); + severity == review_required 但 can_auto_create 场景下同样 fail, + 交由上层 CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES 归类到 + review_required 总体状态(允许人工建单,不允许 STP 自动建单)。 + + Args: + candidate: ShippingOrderCandidate 或兼容替身。 + + Returns: + True 表示 VC 路径「已干净」,可放行自动/人工建单。 + """ + try: + items = collect_vc_candidate_conflicts(candidate) + except Exception: # noqa: BLE001 — 门禁 fail-closed:解析异常视为未通过 + return False + for it in items: + if not isinstance(it, dict): + continue + severity = str(it.get('severity') or 'blocking').strip() + reason = str(it.get('reason') or '').strip() + if reason in CQ_VC_BLOCKING_REASONS: + return False + if severity == 'blocking': + return False + if severity == 'review_required': + # review_required 对自动建单门禁同样算失败(上层会映射为 review_required 总体状态) + # 对人工建单是允许的,但 CQ 门禁统一口径:needs_review → fail; + # 人工建单的门禁是独立路径,在 order_review_confirmation_service 中。 + return False + return True + + +def _vc_fine_grained_reason(candidate: Any) -> str | None: + """ + VC 门禁失败时提取首个匹配的细因码,优先给出 format/region 错, + 冲突类错其次,保留默认 vc_source_conflict_unresolved 兜底。 + """ + try: + items = collect_vc_candidate_conflicts(candidate) + except Exception: # noqa: BLE001 + return None + priority_order = [ + 'vc_source_region_unbound', + 'vc_source_format_invalid', + 'vc_source_conflict_unresolved', + ] + seen = {str(x.get('reason') or '').strip() for x in items if isinstance(x, dict)} + for want in priority_order: + if want in seen: + return want + return None + + def resolve_candidate_customer_resolved( *, candidate: Any | None = None, @@ -288,6 +359,7 @@ def evaluate_candidate_qualification( ) evidence_ok = _evidence_ok(candidate) conflicts_ok = _conflicts_ok(candidate) + vc_ok = _vc_gate_ok(candidate) duplicate_ok = _duplicate_ok(candidate) customer_ok, customer_reason = _customer_ok(candidate, customer_resolved=customer_resolved) idempotency_ok = _idempotency_ok(candidate) @@ -310,6 +382,7 @@ def evaluate_candidate_qualification( 'key_fields_minimum_confidence': key_confidence_ok, 'evidence_complete': evidence_ok, 'field_conflicts_resolved': conflicts_ok, + 'vc_source_merged_clean': vc_ok, 'duplicate_resolved': duplicate_ok, 'customer_confirmed': customer_ok, 'idempotency_ok': idempotency_ok, @@ -321,7 +394,7 @@ def evaluate_candidate_qualification( } failed = [key for key in CANDIDATE_QUALIFICATION_GATE_KEYS if not gates.get(key)] - # [STEP 3] 映射原因码;客户细因 / XFA 细因 / PDF 关键冲突细因覆盖默认码。 + # [STEP 3] 映射原因码;客户细因 / XFA 细因 / PDF 关键冲突细因 / VC 细因覆盖默认码。 blocking_reason_codes: list[str] = [] for key in failed: if key == 'customer_confirmed' and customer_reason: @@ -335,6 +408,11 @@ def evaluate_candidate_qualification( if pdf_reason: blocking_reason_codes.append(pdf_reason) continue + if key == 'vc_source_merged_clean': + vc_reason = _vc_fine_grained_reason(candidate) + if vc_reason: + blocking_reason_codes.append(vc_reason) + continue blocking_reason_codes.append( CANDIDATE_QUALIFICATION_GATE_REASON_CODES.get(key, 'order_freeze_not_ready') ) @@ -347,9 +425,23 @@ def evaluate_candidate_qualification( failed_gates=failed, blocking_reason_codes=blocking_reason_codes, ) + + # [STEP 3b] 证据快照追加 VC 合并概览(脱敏,仅计数)—— 注意:必须在 STEP 4 status + # 计算之后执行,因为 status 不依赖 evidence_snapshot,保证零回归。 evidence_snapshot = _evidence_snapshot(candidate) if xfa_eval.get('evidence_extra'): evidence_snapshot = {**evidence_snapshot, **xfa_eval['evidence_extra']} + try: + vc_items = collect_vc_candidate_conflicts(candidate) + except Exception: # noqa: BLE001 + vc_items = [] + vc_counts = { + 'vc_total_candidates': len(vc_items), + 'vc_review_required': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'review_required']), + 'vc_blocking': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'blocking']), + } + if vc_counts['vc_total_candidates']: + evidence_snapshot = {**evidence_snapshot, **vc_counts} score = _qualification_score(gates) confidence_policy = { 'minimum_confidence': float(min_confidence), diff --git a/backend/app/services/shipping_notice/case_retry_auto_progress_service.py b/backend/app/services/shipping_notice/case_retry_auto_progress_service.py new file mode 100644 index 00000000..6d473340 --- /dev/null +++ b/backend/app/services/shipping_notice/case_retry_auto_progress_service.py @@ -0,0 +1,253 @@ +""" +backend/app/services/shipping_notice/case_retry_auto_progress_service.py + +用途:单个 Case 精确自动推进恢复(Case 级 retry-auto-progress API 服务层)。 +依赖:reconciliation_service.assert_case_not_blocked_manual、 + order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、 + order_review_service.get_review_case_visible_to_user(兜底 soft_load_review_case_for_audit)、 + fulfillment_audit.record_fulfillment_audit、order_review_projection.serialize_review_case。 +逻辑:可见性 → 业务阻断双校验 → 终态检查(幂等)→ reconcile_single_case → 审计 → 返回摘要。 +""" + +from __future__ import annotations + +from typing import Any + +from app import db +from app.core.errors import AppError, ConflictError +from app.models import ShippingOrderReviewCase + + +def case_retry_auto_progress( + *, + user_id: int, + case_no: str, + is_admin: bool = False, +) -> dict[str, Any]: + """ + 单个 Case 精确自动推进恢复入口。 + + 用途(第一层):为单个指定 Review Case 执行「客户协调 + Draft 校验 + STP 入队」 + 全链路自动推进,适用于 Projection primary_action.code = retry_auto_progress。 + 禁止 duplicate 等业务阻断对象调用;assert_case_not_blocked_manual 前置双校验, + 防止用技术重试绕过人工裁决门禁。 + + 依赖(第二层): + - reconciliation_service.assert_case_not_blocked_manual:业务阻断前置双校验。 + - order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress: + 客户协调 + validate_draft + ensure_stp_auto_create_for_case 统一执行。 + - order_review_service.get_review_case_visible_to_user(兜底: + order_review_draft_service.soft_load_review_case_for_audit):Case 可见性校验。 + - fulfillment_audit.record_fulfillment_audit:写 case_retry_auto_progress_invoked 审计。 + - order_review_projection.serialize_review_case:返回体附带 Case 安全投影。 + + 逻辑(第三层): + STEP 1 可见性校验 → STEP 2 业务阻断前置校验 → STEP 3 终态幂等检查 + → STEP 4 调用 reconcile_single_case_for_auto_progress(trigger=case_api_retry_auto_progress) + → STEP 5 审计 → STEP 6 返回统一摘要结构。 + + Args: + user_id: 操作人(必须为 Case owner 或 admin)。 + case_no: 目标复核 Case 编号。 + is_admin: 是否管理员(影响可见性与 serialize 投影粒度)。 + + Returns: + ``{success, operation, case_no, customer_step_status, validate_status, + enqueue_status, job_id, idempotency_key, error, case}``。 + 已终态时返回 success=True + already_confirmed=True + enqueue_status=already_confirmed, + 不抛错(幂等友好)。 + + Raises: + NotFoundError: Case 不存在或当前用户越权。 + ConflictError (SHIPPING.RETRY_STP_BLOCKED_MANUAL): 命中 duplicate 等业务阻断, + 禁止用 retry API 绕过,引导走 reconcile-and-progress。 + """ + import logging as _rt_logging + _rt_log = _rt_logging.getLogger(__name__) + + normalized_case_no = str(case_no or '').strip().upper() + user_id_int = int(user_id or 0) + fallback = { + 'success': False, + 'operation': 'retry_auto_progress', + 'case_no': normalized_case_no, + 'already_confirmed': False, + 'customer_step_status': 'failed', + 'validate_status': 'failed', + 'enqueue_status': 'not_eligible', + 'job_id': None, + 'idempotency_key': None, + 'error': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED', + 'reconcile_result': {}, + 'case': None, + } + + # ======================================================================== + # [STEP 0] 模块级 delay import 统一包 try/except,与路由/协调器双层防护对齐。 + # 任一依赖模块 SyntaxError/ImportError → 返回结构化 fallback, + # 不冒泡为 HTTP 500 或整批拖死协调器循环。 + # ======================================================================== + try: + from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_single_case_for_auto_progress, + ) + from app.services.shipping_notice.order_review_projection import serialize_review_case + from app.services.shipping_notice.reconciliation_service import ( + assert_case_not_blocked_manual, + ) + except (SyntaxError, ImportError) as mod_err: + _rt_log.exception( + 'case_retry_auto_progress module import error case_no=%s err=%s', + normalized_case_no, type(mod_err).__name__, + ) + fallback['error'] = 'SHIPPING.MODULE_IMPORT_ERROR' + fallback['import_error'] = type(mod_err).__name__ + return fallback + except Exception as exc: # noqa: BLE001 + _rt_log.exception( + 'case_retry_auto_progress import unexpected error case_no=%s', + normalized_case_no, + ) + fallback['error_type'] = type(exc).__name__ + return fallback + + try: + # ==================================================================== + # [STEP 1] 可见性校验:优先 get_review_case_visible_to_user, + # ImportError 兜底走 soft_load_review_case_for_audit(写审计场景同款门禁)。 + # ==================================================================== + try: + from app.services.shipping_notice.order_review_service import ( + get_review_case_visible_to_user, + ) + + case: ShippingOrderReviewCase = get_review_case_visible_to_user( + normalized_case_no, + user_id_int, + is_admin=bool(is_admin), + ) + except AppError: + raise + except Exception: + from app.services.shipping_notice.order_review_draft_service import ( + soft_load_review_case_for_audit, + ) + + case = soft_load_review_case_for_audit( + user_id=user_id_int, + case_no=normalized_case_no, + ) + if case is None: + from app.core.errors import NotFoundError + + raise NotFoundError( + 'Order review case not found', + code='SHIPPING.REVIEW_CASE_NOT_FOUND', + ) + + # ==================================================================== + # [STEP 2] 业务阻断前置校验:duplicate 类必须走 reconcile-and-progress。 + # 若命中 → 抛 409 ConflictError,明确 alternative_api 指向。 + # ==================================================================== + assert_case_not_blocked_manual(case_no=normalized_case_no, case=case) + + # ==================================================================== + # [STEP 3] 终态检查:confirmed_task_id 或 status=confirmed/终态 → 幂等返回。 + # 不抛错,保留 already_confirmed 标识让前端区分「本次执行」与「原本已终态」。 + # ==================================================================== + _TERMINAL = frozenset({ + 'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending', + }) + already_confirmed = ( + bool(getattr(case, 'confirmed_task_id', None)) + or str(getattr(case, 'status', '') or '') in _TERMINAL + ) + if already_confirmed: + return { + 'success': True, + 'operation': 'retry_auto_progress', + 'case_no': normalized_case_no, + 'already_confirmed': True, + 'customer_step_status': 'skipped', + 'validate_status': 'skipped', + 'enqueue_status': 'already_confirmed_or_terminal', + 'job_id': None, + 'idempotency_key': None, + 'error': None, + 'reconcile_result': {}, + 'case': serialize_review_case(case, is_admin=bool(is_admin)), + } + + # ==================================================================== + # [STEP 4] 核心执行:reconcile_single_case_for_auto_progress(统一协调器)。 + # trigger=case_api_retry_auto_progress,refresh_validation=True 重跑校验。 + # ==================================================================== + reconcile_result: dict[str, Any] = reconcile_single_case_for_auto_progress( + case=case, + trigger='case_api_retry_auto_progress', + refresh_validation=True, + ) + + # ==================================================================== + # [STEP 5] 审计:case_retry_auto_progress_invoked。 + # metadata 附带 reconcile_result 全量摘要,strict=False 降级不阻断。 + # ==================================================================== + try: + record_fulfillment_audit( + event_type='case_retry_auto_progress_invoked', + aggregate_type='order_review_case', + aggregate_id=normalized_case_no, + action='retry_auto_progress', + actor_type='user', + actor_id=user_id_int, + review_case_no=normalized_case_no, + owner_user_id=int(getattr(case, 'owner_user_id', 0) or 0), + result=( + 'success' + if not reconcile_result.get('error') + and str(reconcile_result.get('enqueue_status') or '') in { + 'queued', 'reused', 'already_queued', 'already_running', 'enqueued', + } + else 'failed' + ), + metadata={'reconcile_result': dict(reconcile_result or {})}, + source='case_retry_auto_progress_service', + strict=False, + ) + except Exception: + pass + + # ==================================================================== + # [STEP 6] 统一返回:success + operation + case_no + reconcile_result 平铺字段 + # + serialized case 投影。 + # ==================================================================== + return { + 'success': True, + 'operation': 'retry_auto_progress', + 'case_no': normalized_case_no, + 'already_confirmed': False, + 'customer_step_status': reconcile_result.get('customer_step_status'), + 'validate_status': reconcile_result.get('validate_status'), + 'enqueue_status': reconcile_result.get('enqueue_status'), + 'job_id': reconcile_result.get('job_id'), + 'idempotency_key': reconcile_result.get('idempotency_key'), + 'error': reconcile_result.get('error'), + 'reconcile_result': dict(reconcile_result or {}), + 'case': serialize_review_case(case, is_admin=bool(is_admin)), + } + except (AppError, ConflictError): + raise + except Exception as exc: # noqa: BLE001 + _rt_log.exception( + 'case_retry_auto_progress execution error case_no=%s', normalized_case_no, + ) + fallback['error_type'] = type(exc).__name__ + try: + fallback['case'] = ( + serialize_review_case(case, is_admin=bool(is_admin)) + if 'case' in locals() and case is not None else None + ) + except Exception: # noqa: BLE001 + pass + return fallback diff --git a/backend/app/services/shipping_notice/conversation_retry_auto_progress_service.py b/backend/app/services/shipping_notice/conversation_retry_auto_progress_service.py index c28fda91..5fcd68c2 100644 --- a/backend/app/services/shipping_notice/conversation_retry_auto_progress_service.py +++ b/backend/app/services/shipping_notice/conversation_retry_auto_progress_service.py @@ -16,11 +16,15 @@ from typing import Any from app import db from app.core.errors import AppError, NotFoundError, ValidationError +from app.jobs.types import JobType from app.models import ( + Job, ShippingNotice, ShippingOrderProcessingRun, ShippingOrderReviewCase, + ShippingOrderReviewDraft, ) +from app.services.shipping_notice.recovery_contract import should_general_retry_be_removed _LOGGER = logging.getLogger(__name__) @@ -29,6 +33,21 @@ ACTION_RETRY_STP = 'retry_stp_auto_create' OBJECT_REVIEW_CASE = 'review_case' OBJECT_FORMAL_TASK = 'formal_task' +# [STEP P1-13] 业务阻断黑名单:duplicate 类命中即禁止对话级重试,需走 reconcile-and-progress +_DUPLICATE_BLOCKING_CODES = frozenset({ + 'duplicate_decision_required', + 'SHIPPING.NOTICE_EXACT_DUPLICATE', + 'NOTICE_EXACT_DUPLICATE', +}) + +# [STEP P1-13-d] 允许强制重试的 manual_fallback 原因码(不含 duplicate 类) +_FORCE_RETRYABLE_BLOCKING_CODES = frozenset({ + 'STP_NOT_ELIGIBLE', + 'SHIPPING.STP_NOT_ELIGIBLE', + 'profile_schema_mismatch', + 'SHIPPING.profile_schema_mismatch', +}) + def project_conversation_allowed_actions( *, @@ -107,7 +126,7 @@ def retry_auto_progress_for_conversation( actor_id=int(user_id), conversation_id=normalized, owner_user_id=int(user_id), - result='success' if summary['failed'] == 0 else 'partial', + result='success' if summary['failed'] == 0 else 'failure', metadata={ 'reason': str(reason or 'user_retry_auto_progress')[:200], 'summary': summary, @@ -213,24 +232,183 @@ def _formal_task_no(case: ShippingOrderReviewCase, automation: dict[str, Any]) - def _list_eligible_targets(*, user_id: int, conversation_id: str) -> list[dict[str, Any]]: - """扫描可重试对象(仅 retryable=true)。""" + """ + 扫描可重试对象(P1-13 扩展三类 c / d / e,OR 语义)。 + + 目标候选扩展说明(文档 Q8 合同测试要求): + [STEP P1-13-e] 原有:automation.retryable=true 且未命中业务阻断(保留,不删)。 + + [STEP P1-13-c] stp_enqueue_missing: + • Case.status IN ('unreviewed','draft','ready') + • confirmed_task_id IS NULL + • Draft.validation.status = 'ready' 且 can_auto_create = true + • 最近 Job(若有)的 retryable != false + 或 blocking_reason 非 duplicate_decision_required / NOTICE_EXACT_DUPLICATE + • 当前无 queued/running STP Job + → 这类对象 Draft 校验就绪但从未成功入队 STP,可通过 retry_auto_progress 自动推进。 + + [STEP P1-13-d] manual_fallback 且允许强制重试: + • 最近 STP Job.result_json.status = failed + • result_json.blocking_reason 非 duplicate 类 + • retryable_flag = False 但 blocking_reason 命中允许 + retry_stp_auto_create_for_case 强制重试的类型 + (如 STP_NOT_ELIGIBLE / profile_schema_mismatch,不含 duplicate) + → 这类对象标记了 manual_fallback,但实际是技术可恢复的原因,允许批量重试。 + + 除上述条件外,全部对象必须通过 should_general_retry_be_removed 二次门禁。 + """ targets: list[dict[str, Any]] = [] for case in _list_conversation_cases(user_id=user_id, conversation_id=conversation_id): automation = _automation_for_case(case) - if not bool(automation.get('retryable')): + retryable_flag = bool(automation.get('retryable')) + blocking_reason = ( + automation.get('blocking_reason') + if isinstance(automation.get('blocking_reason'), dict) + else None + ) + br_code = ( + str(blocking_reason.get('code') or '') + if isinstance(blocking_reason, dict) + else str(blocking_reason or '') + ) + + # ------------------------------------------------------------------ + # 取 Case 维度最近一条 STP Job(用于 c / d 条件判断) + # 说明:Job 模型没有 reference_type / reference_key,通过 business_ref 前缀匹配。 + # STP business_ref = stp-auto:{run_no}:doc-{document_id}:v{draft_version}, + # 按 run_no+document_id 前缀可覆盖同一 Case 的所有 draft_version。 + # ------------------------------------------------------------------ + _run_no = str(getattr(getattr(case, 'run', None), 'run_no', '') or '').strip() + _doc_id = getattr(case, 'document_id', None) + _stp_prefix = None + if _run_no and _doc_id is not None: + _stp_prefix = f'stp-auto:{_run_no}:doc-{int(_doc_id)}:' + + latest_stp_job: Job | None = None + running_stp_exists = False + if _stp_prefix is not None: + latest_stp_job = ( + Job.query + .filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.business_ref.like(f"{_stp_prefix}%"), + ) + .order_by(Job.created_at.desc()) + .first() + ) + running_stp_exists = ( + Job.query + .filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.business_ref.like(f"{_stp_prefix}%"), + Job.status.in_(['queued', 'running']), + ) + .limit(1) + .first() + ) is not None + + latest_rj: dict[str, Any] = ( + dict(latest_stp_job.result_json) + if latest_stp_job is not None and isinstance(latest_stp_job.result_json, dict) + else {} + ) + latest_retryable_flag: bool = bool(latest_rj.get('retryable', True)) + latest_br_raw = latest_rj.get('blocking_reason') + latest_br_code = ( + str(latest_br_raw.get('code') or '') + if isinstance(latest_br_raw, dict) + else str(latest_br_raw or '') + ) + latest_status: str = str(latest_rj.get('status') or '').strip().lower() + + # ------------------------------------------------------------------ + # Draft 校验:status=ready + can_auto_create(c 条件需要) + # ------------------------------------------------------------------ + draft: ShippingOrderReviewDraft | None = case.current_draft + validation: dict[str, Any] = ( + dict(draft.validation_result_json) + if draft is not None and isinstance(draft.validation_result_json, dict) + else {} + ) + draft_ready_ok = ( + draft is not None + and str(validation.get('status') or '') == 'ready' + and bool(validation.get('can_auto_create')) + ) + case_status_ok = str(case.status or '') in {'unreviewed', 'draft', 'ready'} + no_confirmed_task = not bool(case.confirmed_task_id) + + # ------------------------------------------------------------------ + # P1-13:三类候选 OR 判定 + # ------------------------------------------------------------------ + # [STEP P1-13-e] 原有 automation.retryable=true(保留,不删) + eligible_e = retryable_flag and not should_general_retry_be_removed( + retryable_flag=retryable_flag, + blocking_reason=blocking_reason, + ) + + # [STEP P1-13-c] stp_enqueue_missing:Draft 校验就绪但从未入队或可恢复 + eligible_c = ( + case_status_ok + and no_confirmed_task + and draft_ready_ok + and not running_stp_exists + and ( + latest_stp_job is None + or latest_retryable_flag + or latest_br_code not in _DUPLICATE_BLOCKING_CODES + ) + ) + + # [STEP P1-13-d] manual_fallback 允许强制重试:最近失败、非 duplicate、命中允许码 + eligible_d = ( + no_confirmed_task + and latest_stp_job is not None + and latest_status == 'failed' + and latest_br_code not in _DUPLICATE_BLOCKING_CODES + and ( + latest_br_code in _FORCE_RETRYABLE_BLOCKING_CODES + or br_code in _FORCE_RETRYABLE_BLOCKING_CODES + ) + ) + + is_eligible = eligible_e or eligible_c or eligible_d + if not is_eligible: continue + + # ------------------------------------------------------------------ + # 二次门禁:should_general_retry_be_removed(duplicate 类再次拦截) + # ------------------------------------------------------------------ + if eligible_e and should_general_retry_be_removed( + retryable_flag=retryable_flag, + blocking_reason=blocking_reason, + ): + continue + task_no = _formal_task_no(case, automation) if task_no: targets.append({ 'object_type': OBJECT_FORMAL_TASK, 'object_ref': task_no, 'case_no': case.case_no, + 'category': ( + 'e_retryable_true' if eligible_e + else 'c_stp_enqueue_missing' if eligible_c + else 'd_manual_fallback_force' + ), }) elif not case.confirmed_task_id: targets.append({ 'object_type': OBJECT_REVIEW_CASE, 'object_ref': case.case_no, 'case_no': case.case_no, + 'category': ( + 'e_retryable_true' if eligible_e + else 'c_stp_enqueue_missing' if eligible_c + else 'd_manual_fallback_force' + ), }) return targets @@ -260,14 +438,41 @@ def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, """ 对单个 Case 执行重试或跳过。 - 核心逻辑:重读 automation;正式 OT→auto_progress;否则 STP;异常映射为 failed/skipped。 + 核心逻辑(P1-13 升级): + [STEP 1] 重新读最新 DB 状态(禁止信任传入 case 为可信快照) + [STEP 2] 调 assert_case_not_blocked_manual 双校验;业务阻断 → skipped(而非失败) + [STEP 3] 正式 OT → auto_progress(保持不变); + 建单前 Case → 统一调 case_retry_auto_progress(复用客户协调 + Draft 校验 + STP 入队) + [STEP 4] 保留原有 items 返回契约(不 break 前端),新增 P1-13 分类字段放入 metadata。 """ from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot + from app.services.shipping_notice.reconciliation_service import ( + assert_case_not_blocked_manual, + ) + from app.core.errors import ConflictError - automation = _automation_for_case(case) - formal = resolve_formal_ot(case) + # ==================================================================== + # [STEP 1 P1-13] 重新读最新 DB 状态(不信任调用方传入的 case 对象,避免前端竞态脏读) + # ==================================================================== + fresh_case: ShippingOrderReviewCase | None = ( + ShippingOrderReviewCase.query + .filter_by(id=int(case.id)) + .first() + ) + if fresh_case is None: + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': None, + 'outcome': 'skipped', + 'reason_code': 'case_missing', + 'metadata': {'p13_category': None}, + } + + automation = _automation_for_case(fresh_case) + formal = resolve_formal_ot(fresh_case) task_missing = bool(formal.get('task_missing')) - task_no = _formal_task_no(case, automation) + task_no = _formal_task_no(fresh_case, automation) if task_no: skip = _skip_reason_from_automation(automation, task_missing=task_missing) @@ -278,37 +483,68 @@ def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, 'action': None, 'outcome': 'skipped', 'reason_code': skip, + 'metadata': {'p13_category': 'e_formal_ot'}, } return _execute_formal_task_retry(user_id=user_id, task_no=task_no) - if task_missing or case.confirmed_task_id: + if task_missing or fresh_case.confirmed_task_id: return { 'object_type': OBJECT_REVIEW_CASE, - 'object_ref': case.case_no, + 'object_ref': fresh_case.case_no, 'action': None, 'outcome': 'skipped', 'reason_code': 'task_missing' if task_missing else 'already_confirmed', + 'metadata': {'p13_category': None}, } skip = _skip_reason_from_automation(automation, task_missing=False) if skip: return { 'object_type': OBJECT_REVIEW_CASE, - 'object_ref': case.case_no, + 'object_ref': fresh_case.case_no, 'action': None, 'outcome': 'skipped', 'reason_code': skip, + 'metadata': {'p13_category': None}, } - return _execute_stp_retry(user_id=user_id, case_no=str(case.case_no)) + + # ==================================================================== + # [STEP 2 P1-13] assert_case_not_blocked_manual 二次校验;业务阻断 → skipped(不回滚整批) + # [DUPLICATE-GUARD-3] 第三道:对话级批量重试单条执行前双校验 — + # 命中 duplicate 等阻断时单条标记 skipped,不影响其他 Case + # ==================================================================== + try: + assert_case_not_blocked_manual(case_no=str(fresh_case.case_no), case=fresh_case) + except ConflictError as blocked_err: + code = str(getattr(blocked_err, 'code', None) or 'SHIPPING.RETRY_STP_BLOCKED_MANUAL') + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': fresh_case.case_no, + 'action': None, + 'outcome': 'skipped', + 'reason_code': code, + 'metadata': { + 'p13_category': None, + 'blocked_by': 'assert_case_not_blocked_manual', + 'blocking_details': getattr(blocked_err, 'details', None), + }, + } + + # ==================================================================== + # [STEP 3 P1-13] 统一调 case_retry_auto_progress 核心服务 + # (不再复制 STP 入队逻辑,复用客户协调 + validate + STP) + # ==================================================================== + return _execute_case_retry_auto_progress(user_id=user_id, case=fresh_case) def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]: - """调用既有 STP retry;捕获业务错误为逐对象 outcome。""" - from app.services.shipping_notice.order_stp_auto_create_service import ( - retry_stp_auto_create_for_case, - ) + """调用既有 STP retry;捕获业务错误为逐对象 outcome。(保留为兼容降级路径)""" try: + from app.services.shipping_notice.order_stp_auto_create_service import ( + retry_stp_auto_create_for_case, + ) + result = retry_stp_auto_create_for_case(user_id=user_id, case_no=case_no) status = str(result.get('status') or '').strip().lower() if status in {'queued', 'reused', 'enqueued'}: @@ -318,6 +554,7 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]: 'action': ACTION_RETRY_STP, 'outcome': 'queued', 'reason_code': None, + 'metadata': {'p13_category': 'legacy_stp_retry'}, } return { 'object_type': OBJECT_REVIEW_CASE, @@ -325,6 +562,7 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]: 'action': ACTION_RETRY_STP, 'outcome': 'skipped', 'reason_code': status or 'not_retryable', + 'metadata': {'p13_category': 'legacy_stp_retry'}, } except AppError as err: code = str(getattr(err, 'code', None) or 'SHIPPING.STP_ENQUEUE_FAILED') @@ -335,6 +573,7 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]: 'action': None, 'outcome': 'skipped', 'reason_code': 'already_confirmed', + 'metadata': {'p13_category': 'legacy_stp_retry'}, } if 'NOT_ELIGIBLE' in code: return { @@ -343,6 +582,7 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]: 'action': ACTION_RETRY_STP, 'outcome': 'failed', 'reason_code': code, + 'metadata': {'p13_category': 'legacy_stp_retry'}, } return { 'object_type': OBJECT_REVIEW_CASE, @@ -350,6 +590,23 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]: 'action': ACTION_RETRY_STP, 'outcome': 'failed', 'reason_code': code, + 'metadata': {'p13_category': 'legacy_stp_retry'}, + } + except (SyntaxError, ImportError) as mod_err: + _LOGGER.exception( + 'conversation STP retry module import error case_no=%s err=%s', + case_no, type(mod_err).__name__, + ) + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case_no, + 'action': ACTION_RETRY_STP, + 'outcome': 'failed', + 'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR', + 'metadata': { + 'p13_category': 'legacy_stp_retry', + 'import_error': type(mod_err).__name__, + }, } except Exception: # noqa: BLE001 _LOGGER.exception('conversation STP retry failed case_no=%s', case_no) @@ -359,14 +616,160 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]: 'action': ACTION_RETRY_STP, 'outcome': 'failed', 'reason_code': 'SHIPPING.STP_ENQUEUE_FAILED', + 'metadata': {'p13_category': 'legacy_stp_retry'}, } -def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: - """正式 OT 重试:委托统一决策器(与任务级 /retry 同源)。""" - from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision +def _execute_case_retry_auto_progress( + *, + user_id: int, + case: ShippingOrderReviewCase, +) -> dict[str, Any]: + """ + P1-13 统一执行入口:调 case_retry_auto_progress 核心服务(客户协调 + validate + STP)。 + + 保留原有 items 返回契约(object_type / object_ref / action / outcome / reason_code), + 新增 P1-13 分类字段与执行摘要放入 metadata,不 break 前端。 + """ try: + from app.services.shipping_notice.case_retry_auto_progress_service import ( + case_retry_auto_progress, + ) + + result = case_retry_auto_progress( + user_id=int(user_id), + case_no=str(case.case_no), + is_admin=False, + ) + except AppError as err: + code = str(getattr(err, 'code', None) or 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED') + if 'ALREADY_CONFIRMED' in code: + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': None, + 'outcome': 'skipped', + 'reason_code': 'already_confirmed', + 'metadata': {'p13_category': None, 'error': code}, + } + if 'BLOCKED_MANUAL' in code or 'RECONCILE' in code: + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': None, + 'outcome': 'skipped', + 'reason_code': code, + 'metadata': { + 'p13_category': None, + 'blocked_by': 'case_retry_auto_progress_assertion', + 'details': getattr(err, 'details', None), + }, + } + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': ACTION_RETRY_AUTO_PROGRESS, + 'outcome': 'failed', + 'reason_code': code, + 'metadata': {'p13_category': None, 'error': code}, + } + except (SyntaxError, ImportError) as mod_err: + _LOGGER.exception( + 'conversation case_retry_auto_progress module import error case_no=%s err=%s', + case.case_no, type(mod_err).__name__, + ) + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': ACTION_RETRY_AUTO_PROGRESS, + 'outcome': 'failed', + 'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR', + 'metadata': { + 'p13_category': None, + 'import_error': type(mod_err).__name__, + }, + } + except Exception: # noqa: BLE001 + _LOGGER.exception('conversation case_retry_auto_progress failed case_no=%s', case.case_no) + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': ACTION_RETRY_AUTO_PROGRESS, + 'outcome': 'failed', + 'reason_code': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED', + 'metadata': {'p13_category': None, 'error': 'unexpected_exception'}, + } + + # 解析执行结果:success + enqueue_status → outcome + enqueue_status = str(result.get('enqueue_status') or '').strip().lower() + if result.get('already_confirmed'): + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': None, + 'outcome': 'skipped', + 'reason_code': 'already_confirmed', + 'metadata': { + 'p13_category': None, + 'enqueue_status': enqueue_status, + 'already_confirmed': True, + }, + } + queued_set = { + 'queued', 'reused', 'already_queued', 'already_running', 'enqueued', + } + if enqueue_status in queued_set: + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': ACTION_RETRY_AUTO_PROGRESS, + 'outcome': 'queued', + 'reason_code': None, + 'metadata': { + 'p13_category': result.get('case_no'), + 'customer_step_status': result.get('customer_step_status'), + 'validate_status': result.get('validate_status'), + 'enqueue_status': enqueue_status, + 'job_id': result.get('job_id'), + 'idempotency_key': result.get('idempotency_key'), + }, + } + if enqueue_status in {'already_confirmed_or_terminal', 'not_eligible'}: + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': ACTION_RETRY_AUTO_PROGRESS, + 'outcome': 'skipped', + 'reason_code': enqueue_status, + 'metadata': { + 'p13_category': None, + 'enqueue_status': enqueue_status, + 'error': result.get('error'), + }, + } + return { + 'object_type': OBJECT_REVIEW_CASE, + 'object_ref': case.case_no, + 'action': ACTION_RETRY_AUTO_PROGRESS, + 'outcome': 'failed' if result.get('error') else 'skipped', + 'reason_code': enqueue_status or (result.get('error') and 'execution_error') or 'not_retryable', + 'metadata': { + 'p13_category': None, + 'enqueue_status': enqueue_status, + 'error': result.get('error'), + 'customer_step_status': result.get('customer_step_status'), + 'validate_status': result.get('validate_status'), + }, + } + + +def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: + """正式 OT 重试:委托统一决策器(与任务级 /retry 同源)。metadata 追加 P1-13 分类不 break 前端。""" + + try: + from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision + result = retry_task_with_decision( task_no=str(task_no), user_id=int(user_id), @@ -382,6 +785,23 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'action': ACTION_RETRY_AUTO_PROGRESS, 'outcome': 'failed', 'reason_code': str(getattr(err, 'code', None) or 'SHIPPING.AUTO_PROGRESS_FAILED'), + 'metadata': {'p13_category': 'e_formal_ot'}, + } + except (SyntaxError, ImportError) as mod_err: + _LOGGER.exception( + 'conversation task retry module import error task_no=%s err=%s', + task_no, type(mod_err).__name__, + ) + return { + 'object_type': OBJECT_FORMAL_TASK, + 'object_ref': task_no, + 'action': ACTION_RETRY_AUTO_PROGRESS, + 'outcome': 'failed', + 'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR', + 'metadata': { + 'p13_category': 'e_formal_ot', + 'import_error': type(mod_err).__name__, + }, } except Exception: # noqa: BLE001 _LOGGER.exception('conversation task retry failed task_no=%s', task_no) @@ -391,6 +811,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'action': ACTION_RETRY_AUTO_PROGRESS, 'outcome': 'failed', 'reason_code': 'SHIPPING.AUTO_PROGRESS_FAILED', + 'metadata': {'p13_category': 'e_formal_ot'}, } status = str((result or {}).get('status') or '').strip().lower() @@ -402,6 +823,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'action': action, 'outcome': 'skipped', 'reason_code': str((result or {}).get('reason_code') or 'human_blocking'), + 'metadata': {'p13_category': 'e_formal_ot'}, } if status == 'failed': return { @@ -410,6 +832,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'action': action, 'outcome': 'failed', 'reason_code': str((result or {}).get('reason_code') or status), + 'metadata': {'p13_category': 'e_formal_ot'}, } if action == 'noop' and str((result or {}).get('reason_code') or '') == 'already_running': return { @@ -418,6 +841,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'action': action, 'outcome': 'skipped', 'reason_code': 'already_running', + 'metadata': {'p13_category': 'e_formal_ot'}, } if action == 'noop' and status == 'completed': return { @@ -426,6 +850,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'action': action, 'outcome': 'skipped', 'reason_code': str((result or {}).get('reason_code') or 'already_completed'), + 'metadata': {'p13_category': 'e_formal_ot'}, } if status in {'running', 'completed', 'queued'}: return { @@ -434,6 +859,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'action': action, 'outcome': 'queued', 'reason_code': None, + 'metadata': {'p13_category': 'e_formal_ot'}, } return { 'object_type': OBJECT_FORMAL_TASK, @@ -441,6 +867,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'action': action, 'outcome': 'skipped', 'reason_code': str((result or {}).get('reason_code') or status or 'not_retryable'), + 'metadata': {'p13_category': 'e_formal_ot'}, } diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_region_source_adapter.py b/backend/app/services/shipping_notice/document_layout/coordinate_region_source_adapter.py new file mode 100644 index 00000000..130cdeb5 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/coordinate_region_source_adapter.py @@ -0,0 +1,231 @@ +""" +services/shipping_notice/document_layout/coordinate_region_source_adapter.py + +用途:CoordinateRegionSourceAdapter——将 Profile.named_regions 圈选的物理区域映射为 + 可直接送入 Split Core 的区域原文 + 可引用 bbox 证据(page_no + 绝对坐标)。 +依赖:profile_vendor_comments_contract.NamedRegion;coordinate_region_text.read_coordinate_region_text + 与 visual_glyph_rows + positioned_token_spans(证据粒度生成)。 +逻辑:不读 MinIO、不查 DB;只接收 caller 已加载的 glyphs/page 字典;严格按 Q14 约定 + page_scope 规则选择「代表页」——last_page 时从多页集合取末页;失败不抛错,统一 + 返回 status=unavailable + 诊断码,供上游 ProfileFieldSourceMappingService 分支处理。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Literal + +from app.services.shipping_notice.document_layout.coordinate_region_text import ( + positioned_token_spans, + read_coordinate_region_text, +) +from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import ( + NamedRegion, +) + + +@dataclass +class CoordinateRegionEvidence: + """单个命中的 token 级证据——供 Observation.evidence_metadata_json 直接序列化。""" + + page_no: int + text: str + x0: float # 0..1 归一化 + x1: float + y0: float + y1: float + + +@dataclass +class CoordinateRegionSourceResult: + """区域抽取结果——对齐 Split Core 结果形状但不做拆分,仅负责原文渲染。""" + + region_id: str + label: str + status: Literal['available', 'unavailable'] + page_no: int | None = None + raw_text: str = '' + lines: list[str] = field(default_factory=list) + evidence_tokens: list[CoordinateRegionEvidence] = field(default_factory=list) + diagnostic_code: str | None = None + diagnostic_message: str | None = None + + +class CoordinateRegionSourceAdapter: + """ + 将 NamedRegion → 原文 + 证据的薄适配器。 + + 【AI 触发时机】:三来源收集阶段,上游遍历 field_source_mappings[].vendor_comments_enabled + 条目并引用命名区域 ID 时调用。 + + 核心逻辑: + [STEP 1] 按 page_scope 从 page_glyphs_map 中选「代表页」: + first_page → pages[0];last_page → pages[-1];all_pages 只看 p0(仅用于区域); + exact_page → 严格匹配 1-based page_no。 + [STEP 2] 调 read_coordinate_region_text 取区域原文(0..1 归一化坐标)。 + [STEP 3] 调 positioned_token_spans 生成 token 级 bbox 证据,用于 Review 高亮点位。 + [STEP 4] 原文按换行拆为 lines,供后续 execute_base_split_rule_set(..., lines=) 复用。 + + Args: + region: NamedRegion 契约对象(已通过 validate_assignment 校验)。 + page_glyphs_map: {1-based_page_no: {'glyphs': [...], 'page': {'width','height'}}} —— + caller 负责按当前 Document 加载,本类无网络 IO。 + """ + + def __init__(self, region: NamedRegion, page_glyphs_map: dict[int, dict[str, Any]]): + self.region = region + self.page_glyphs_map = page_glyphs_map + + # ------------------------------------------------------------------ + # 对外入口 + # ------------------------------------------------------------------ + + def extract(self) -> CoordinateRegionSourceResult: + """ + 执行区域抽取。失败不抛异常,统一置 status=unavailable + 稳定诊断码。 + + Returns: + CoordinateRegionSourceResult,上游据此决定是否跳过 Vendor Comments 来源。 + """ + # [STEP 1] 选择代表页 + page_no = self._resolve_representative_page_no() + if page_no is None: + return CoordinateRegionSourceResult( + region_id=self.region.region_id, + label=self.region.label, + status='unavailable', + diagnostic_code='named_region_page_not_found', + diagnostic_message=( + f'named region {self.region.region_id!r} page_scope={self.region.page_scope} ' + f'page_no={self.region.page_no!r} has no loaded page' + ), + ) + page_bundle = self.page_glyphs_map[page_no] + glyphs = list(page_bundle.get('glyphs') or []) + page = dict(page_bundle.get('page') or {}) + if not glyphs or 'width' not in page or 'height' not in page: + return CoordinateRegionSourceResult( + region_id=self.region.region_id, + label=self.region.label, + status='unavailable', + page_no=page_no, + diagnostic_code='named_region_empty_glyphs', + diagnostic_message='region target page has empty glyphs or missing page size', + ) + + region_coords = { + 'x0': self.region.region.x0, 'y0': self.region.region.y0, + 'x1': self.region.region.x1, 'y1': self.region.region.y1, + } + + # [STEP 2] 渲染区域原文 + raw_text = read_coordinate_region_text( + glyphs=glyphs, page=page, region=region_coords, + ) + if not raw_text.strip(): + return CoordinateRegionSourceResult( + region_id=self.region.region_id, + label=self.region.label, + status='unavailable', + page_no=page_no, + diagnostic_code='named_region_text_empty', + diagnostic_message=f'named region {self.region.region_id!r} has empty body text', + ) + + # [STEP 3] 生成 token 级证据(只保留区域中心在 box 内的 token) + tokens = self._collect_region_evidence_tokens( + glyphs=glyphs, page=page, region_coords=region_coords, page_no=page_no, + ) + + # [STEP 4] 拆行 + lines = [ln.strip() for ln in raw_text.splitlines() if ln.strip()] + + return CoordinateRegionSourceResult( + region_id=self.region.region_id, + label=self.region.label, + status='available', + page_no=page_no, + raw_text=raw_text.strip(), + lines=lines, + evidence_tokens=tokens, + ) + + # ------------------------------------------------------------------ + # 内部帮助 + # ------------------------------------------------------------------ + + def _resolve_representative_page_no(self) -> int | None: + """按 page_scope 规则选择代表页。""" + sorted_pages = sorted(self.page_glyphs_map.keys()) + if not sorted_pages: + return None + scope = self.region.page_scope + if scope == 'first_page': + return sorted_pages[0] + if scope == 'last_page': + return sorted_pages[-1] + if scope == 'all_pages': + # all_pages 的命名区域仅在第一页渲染(常见全页 Header); + # 若管理员要取多页块,应拆为多个命名区域并使用 exact_page。 + return sorted_pages[0] + if scope == 'exact_page': + return self.region.page_no if self.region.page_no in self.page_glyphs_map else None + return None + + @staticmethod + def _collect_region_evidence_tokens( + *, + glyphs: list[dict[str, Any]], + page: dict[str, Any], + region_coords: dict[str, float], + page_no: int, + ) -> list[CoordinateRegionEvidence]: + """筛选命名区域中心范围内的 token,并返回 0..1 归一化 bbox。""" + width, height = float(page['width']), float(page['height']) + rx0, ry0, rx1, ry1 = (region_coords[k] for k in ('x0', 'y0', 'x1', 'y1')) + all_spans = positioned_token_spans(glyphs, respect_explicit_spaces=True) + selected: list[CoordinateRegionEvidence] = [] + for span in all_spans: + sx0 = float(span['x0']) / width + sx1 = float(span['x1']) / width + text = str(span.get('text') or '') + # y 边界:span 只返回横向边界;glyphs 中心用于 y 判定 + # positioned_token_spans 不返回 y,重算 y0/y1 需回溯原 glyph——这里直接用 + # glyphs 子集重算以保证引用不泄漏。 + matched = [ + g for g in glyphs + if _glyph_intersects_span(g, span, width) and _glyph_in_region_center(g, width, height, rx0, ry0, rx1, ry1) + ] + if not matched: + continue + min_y0 = min(float(g['bbox']['y0']) / height for g in matched) + max_y1 = max(float(g['bbox']['y1']) / height for g in matched) + selected.append(CoordinateRegionEvidence( + page_no=page_no, + text=text, + x0=sx0, x1=sx1, + y0=min_y0, y1=max_y1, + )) + return selected + + +def _glyph_intersects_span(glyph: dict[str, Any], span: dict[str, Any], width: float) -> bool: + try: + gx0 = float(glyph['bbox']['x0']) / width + gx1 = float(glyph['bbox']['x1']) / width + except (KeyError, TypeError, ValueError): + return False + return min(gx1, float(span['x1']) / width) > max(gx0, float(span['x0']) / width) + + +def _glyph_in_region_center( + glyph: dict[str, Any], width: float, height: float, + rx0: float, ry0: float, rx1: float, ry1: float, +) -> bool: + try: + b = glyph['bbox'] + cx = (float(b['x0']) + float(b['x1'])) / (2 * width) + cy = (float(b['y0']) + float(b['y1'])) / (2 * height) + except (KeyError, TypeError, ValueError): + return False + return rx0 <= cx <= rx1 and ry0 <= cy <= ry1 diff --git a/backend/app/services/shipping_notice/document_layout/field_split_core.py b/backend/app/services/shipping_notice/document_layout/field_split_core.py new file mode 100644 index 00000000..71d27929 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/field_split_core.py @@ -0,0 +1,935 @@ +""" +services/shipping_notice/document_layout/field_split_core.py + +用途:共享的声明式字段拆分核心——承接 XFA(XML Forms Architecture)拆分引擎的纯文本执行能力, + 为 Vendor Comments / Coordinate Region 等非 XFA 数据源提供统一的 prefix / regex / position + 匹配、优先级仲裁、多规则冲突诊断、mapped/evidence_only 处理与规则内容指纹。 +依赖:Pydantic 2、xfa_contract(复用 XfaContractModel 作为 Base Model 保持一致性)、 + xfa_safe_regex(危险正则黑名单、超时限制、最大捕获组校验)。 +逻辑:对外暴露 BaseSplit* 契约与 execute_base_split_rule_set() 执行入口; + XFA 链路通过 XfaSplit* extends BaseSplit* 复用本核心;Vendor Comments 链路直接使用 BaseSplit*; + 本文件不得 import 任何 XFA 专属的 dataset/packet/leaf 节点(保持纯文本拆分引擎定位); + relation_capture 在此阶段仅在 core 内部捕获;XFA 适配器转换时丢弃(Q16 方案 A)。 +""" + +from __future__ import annotations + +import json +import os +import re +import uuid +from dataclasses import dataclass, field +from typing import Any, Final, Literal + +from pydantic import AliasChoices, Field, field_validator, model_validator + +from app.services.shipping_notice.document_layout.xfa_contract import XfaContractModel +from app.services.shipping_notice.document_layout.xfa_safe_regex import ( + SafeRegexError, + compile_safe_regex, + search_safe, + validate_restricted_regex_pattern, +) + +# --------------------------------------------------------------------------- +# [STEP 0] 资源上限默认值——与 XFA 拆分保持同一量级,可由 settings / 环境变量覆盖 +# --------------------------------------------------------------------------- + +SPLIT_MAX_RULES_PER_SET: Final[int] = 32 +SPLIT_MAX_RULE_SETS: Final[int] = 64 +SPLIT_MAX_REGEX_PATTERN_LENGTH: Final[int] = 128 +SPLIT_MAX_REGEX_GROUPS: Final[int] = 5 +SPLIT_MAX_PREFIX_LENGTH: Final[int] = 64 +SPLIT_MAX_SEGMENT_CODE_LENGTH: Final[int] = 64 +SPLIT_MAX_DISPLAY_NAME_LENGTH: Final[int] = 128 +SPLIT_MAX_INPUT_LENGTH: Final[int] = 32_768 +SPLIT_REGEX_TIMEOUT_MS: Final[int] = 50 + +# 引擎固定匹配优先级(数值越小优先级越高)——与 XFA 拆分引擎保持一致,避免共享核心引入漂移 +SPLIT_MATCHER_PRIORITY: Final[dict[str, int]] = { + 'prefix': 0, + 'regex': 1, + 'position': 2, +} +SPLIT_UNMATCHED_PRIORITY: Final[int] = 3 + +SplitHandling = Literal['mapped', 'evidence_only'] +SplitMatcherType = Literal['position', 'prefix', 'regex'] +SplitSourceScope = Literal['header', 'line'] +SplitUnmatchedPolicy = Literal['evidence_only', 'needs_review'] +SplitDuplicatePolicy = Literal['needs_review'] +SplitRuleStatus = Literal['draft', 'confirmed', 'published'] +SplitRuleSource = Literal['system_suggestion', 'user', 'imported'] +RelationCaptureType = Literal['line_reference'] +RelationPolicyType = Literal['bind_target_line', 'annotation_only'] + +_SEGMENT_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$') + + +def _config_int(key: str, default: int) -> int: + """ + 从 Flask config 或环境变量读取整型配置。 + + Args: + key: 配置键名。 + default: 缺失时的默认值。 + + Returns: + 解析后的正整数。 + """ + try: + from flask import has_app_context, current_app + + if has_app_context(): + raw = current_app.config.get(key) + if raw is not None: + return max(1, int(raw)) + except Exception: + pass + raw_env = os.getenv(key) + if raw_env is not None and str(raw_env).strip(): + return max(1, int(raw_env)) + return default + + +def get_split_max_rules_per_set() -> int: + """单规则集最大 rules 条数。""" + return _config_int('SPLIT_MAX_RULES_PER_SET', SPLIT_MAX_RULES_PER_SET) + + +def get_split_max_rule_sets() -> int: + """Profile 最大 split_rules 规则集数。""" + return _config_int('SPLIT_MAX_RULE_SETS', SPLIT_MAX_RULE_SETS) + + +def get_split_max_regex_pattern_length() -> int: + """单条正则模式最大长度。""" + return _config_int('SPLIT_MAX_REGEX_PATTERN_LENGTH', SPLIT_MAX_REGEX_PATTERN_LENGTH) + + +def get_split_max_regex_groups() -> int: + """正则最大捕获组数。""" + return _config_int('SPLIT_MAX_REGEX_GROUPS', SPLIT_MAX_REGEX_GROUPS) + + +def get_split_max_prefix_length() -> int: + """前缀标签最大长度。""" + return _config_int('SPLIT_MAX_PREFIX_LENGTH', SPLIT_MAX_PREFIX_LENGTH) + + +def get_split_max_input_length() -> int: + """拆分源字段最大输入长度。""" + return _config_int('SPLIT_MAX_INPUT_LENGTH', SPLIT_MAX_INPUT_LENGTH) + + +def get_split_regex_timeout_ms() -> int: + """正则执行超时(毫秒)。""" + return _config_int('SPLIT_REGEX_TIMEOUT_MS', SPLIT_REGEX_TIMEOUT_MS) + + +# --------------------------------------------------------------------------- +# [STEP 1] 共享 Base 契约——剥离 XFA 专属 path_id / data_path / source_field_code +# --------------------------------------------------------------------------- + + +class RelationCaptureDef(XfaContractModel): + """ + 可选:在规则命中时额外捕获"与目标字段相关的关系元数据"。 + 【AI 触发时机】:当 Profile 需要"先从备注提取值、再从同一句备注提取行号/关联号作为目标绑定依据"时, + 在 BaseSplitMatcher 上配置本定义。 + + 核心逻辑:和 value 捕获同一条正则或前缀行;但关系元数据不参与 mapped/evidence_only 的 target 决策, + 关系如何解释由上层 Mapping 的 relation_policy 决定(Q2 双层设计)。 + """ + + type: RelationCaptureType = 'line_reference' + capture_group: int = Field(ge=0, le=SPLIT_MAX_REGEX_GROUPS) + labels: list[str] = Field(default_factory=list, max_length=16) + + @model_validator(mode='after') + def validate_labels(self) -> 'RelationCaptureDef': + """labels 去重,禁止空字符串。""" + cleaned = [str(item).strip() for item in (self.labels or []) if str(item).strip()] + object.__setattr__(self, 'labels', list(dict.fromkeys(cleaned))) + return self + + +class BaseSplitSegment(XfaContractModel): + """共享拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。""" + + segment_id: str = Field(min_length=8, max_length=64) + segment_code: str = Field(min_length=2, max_length=SPLIT_MAX_SEGMENT_CODE_LENGTH) + display_name: str = Field(min_length=1, max_length=SPLIT_MAX_DISPLAY_NAME_LENGTH) + handling: SplitHandling + target_field_id: str | None = Field(default=None, max_length=64) + target_field_code: str | None = Field(default=None, max_length=128) + note: str | None = Field(default=None, max_length=256) + + @field_validator('segment_code', mode='before') + @classmethod + def validate_segment_code(cls, value: Any) -> str: + """segment_code 必须为小写蛇形,Profile 内唯一由上层校验。""" + code = str(value or '').strip() + if not _SEGMENT_CODE_RE.fullmatch(code): + raise ValueError( + 'segment_code must be lowercase snake_case starting with a letter', + ) + return code + + @model_validator(mode='after') + def validate_handling_targets(self) -> 'BaseSplitSegment': + """mapped 必须绑定目标字段;evidence_only 禁止目标字段。""" + if self.handling == 'mapped': + if not self.target_field_id or not self.target_field_code: + raise ValueError('mapped segment requires target_field_id and target_field_code') + else: + if self.target_field_id or self.target_field_code: + raise ValueError('evidence_only segment must not set target fields') + return self + + +class BaseSplitMatcher(XfaContractModel): + """ + 共享单行匹配器:position / prefix / regex。 + 优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。 + + 新增 relation_capture:当前仅 line_reference(Q2);XFA 链路当前不启用, + 但 Base 契约提前引入避免阶段 2 再次改造。 + """ + + type: SplitMatcherType + line_index: int | None = Field(default=None, ge=1, le=1000) + value: str | None = Field(default=None, max_length=SPLIT_MAX_PREFIX_LENGTH) + separators: list[str] = Field(default_factory=lambda: [':', ':']) + case_sensitive: bool = False + pattern: str | None = Field(default=None, max_length=SPLIT_MAX_REGEX_PATTERN_LENGTH) + capture_group: int | None = Field(default=None, ge=0, le=SPLIT_MAX_REGEX_GROUPS) + relation_capture: RelationCaptureDef | None = None + + @model_validator(mode='after') + def validate_matcher_shape(self) -> 'BaseSplitMatcher': + """按 type 校验必填字段、前缀与正则安全边界。""" + max_prefix = get_split_max_prefix_length() + max_pattern_len = get_split_max_regex_pattern_length() + max_groups = get_split_max_regex_groups() + + if self.type == 'position': + if self.line_index is None: + raise ValueError('position matcher requires line_index (1-based)') + elif self.type == 'prefix': + label = str(self.value or '').strip() + if not label: + raise ValueError('prefix matcher requires non-empty value') + if len(label) > max_prefix: + raise ValueError('prefix value exceeds max length') + seps = [str(item) for item in (self.separators or []) if str(item)] + if not seps: + raise ValueError('prefix matcher requires at least one separator') + object.__setattr__(self, 'separators', seps) + object.__setattr__(self, 'value', label) + elif self.type == 'regex': + pattern = str(self.pattern or '') + if not pattern: + raise ValueError('regex matcher requires pattern') + if len(pattern) > max_pattern_len: + raise ValueError('regex pattern exceeds max length') + try: + validate_restricted_regex_pattern( + pattern, + max_length=max_pattern_len, + max_groups=max_groups, + ) + except SafeRegexError as exc: + raise ValueError(str(exc)) from exc + if self.capture_group is not None and self.capture_group > max_groups: + raise ValueError('capture_group exceeds pattern groups limit') + if self.relation_capture is not None and self.relation_capture.capture_group > max_groups: + raise ValueError('relation_capture.capture_group exceeds pattern groups limit') + else: + raise ValueError(f'unsupported matcher type: {self.type}') + return self + + +class BaseSplitRule(XfaContractModel): + """共享单条拆分规则:rule_id + matcher + segment(无 stages[])。""" + + rule_id: str = Field(min_length=1, max_length=64) + matcher: BaseSplitMatcher + segment: BaseSplitSegment + + +class BaseSplitNormalization(XfaContractModel): + """规则集级换行与 trim 策略:引擎按 line_breaks 拆行后再逐行匹配。""" + + trim: bool = True + remove_empty_lines: bool = True + line_breaks: list[str] = Field(default_factory=lambda: ['\r\n', '\r', '\n']) + + @model_validator(mode='after') + def validate_breaks(self) -> 'BaseSplitNormalization': + """line_breaks 不可为空。""" + breaks = [str(item) for item in (self.line_breaks or []) if str(item)] + if not breaks: + raise ValueError('normalization.line_breaks requires at least one value') + object.__setattr__(self, 'line_breaks', breaks) + return self + + +class BaseSplitRuleSet(XfaContractModel): + """ + 共享规则集:针对单一源文本的拆分规则集合。 + 不含 XFA 专属的 source_path_id / source_data_path / source_field_code, + 这些由 XfaSplitRuleSet extends 本类后追加。 + """ + + rule_set_id: str = Field( + min_length=1, + max_length=128, + validation_alias=AliasChoices('rule_set_id', 'rule_id'), + ) + rule_version: int = Field(ge=1, le=10_000) + normalization: BaseSplitNormalization = Field(default_factory=BaseSplitNormalization) + rules: list[BaseSplitRule] = Field(default_factory=list) + unmatched_line_policy: SplitUnmatchedPolicy = 'evidence_only' + duplicate_match_policy: SplitDuplicatePolicy = 'needs_review' + same_field_multiple_segment_policy: SplitDuplicatePolicy = 'needs_review' + source: SplitRuleSource = 'user' + status: SplitRuleStatus = 'draft' + requires_confirmation: bool = False + + @property + def rule_id(self) -> str: + """兼容旧字段名 rule_id(等同 rule_set_id)。""" + return self.rule_set_id + + @model_validator(mode='after') + def validate_rule_set_invariants(self) -> 'BaseSplitRuleSet': + """规则集内唯一性与数量上限。""" + max_rules = get_split_max_rules_per_set() + if len(self.rules) > max_rules: + raise ValueError(f'rules exceed max {max_rules}') + rule_ids = [item.rule_id for item in self.rules] + if len(rule_ids) != len(set(rule_ids)): + raise ValueError('duplicate rule_id within split rule set') + segment_ids = [item.segment.segment_id for item in self.rules] + if len(segment_ids) != len(set(segment_ids)): + raise ValueError('duplicate segment_id within split rule set') + segment_codes = [item.segment.segment_code for item in self.rules] + if len(segment_codes) != len(set(segment_codes)): + raise ValueError('duplicate segment_code within split rule set') + if self.source == 'system_suggestion': + if self.status != 'draft' or not self.requires_confirmation: + raise ValueError( + 'system_suggestion must be draft with requires_confirmation=true', + ) + return self + + +def new_segment_id() -> str: + """ + 生成不可变 segment_id。 + + Returns: + 形如 seg- 的稳定标识。 + """ + return f'seg-{uuid.uuid4().hex}' + + +def new_rule_id(prefix: str = 'rule') -> str: + """ + 生成规则条目 ID。 + + Args: + prefix: ID 前缀。 + + Returns: + 形如 ``{prefix}-`` 的标识。 + """ + safe = re.sub(r'[^a-z0-9_]+', '_', str(prefix or 'rule').strip().lower()) or 'rule' + return f'{safe}-{uuid.uuid4().hex[:12]}' + + +def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any]) -> str: + """ + 计算共享规则集内容指纹(排除 status / requires_confirmation / rule_version / handling/targets)。 + + 核心逻辑:只冻结 matcher、normalization 与 relation_capture 定义; + segment 的 Schema 映射字段(handling/target_field_*)不属于拆分逻辑本身, + 后续绑定或解绑目标字段不得取消已确认状态。 + + Args: + rule_set: 模型或 dict。 + + Returns: + 稳定 JSON 字符串指纹素材(调用方可再 hash)。 + """ + if isinstance(rule_set, BaseSplitRuleSet): + payload = rule_set.model_dump(mode='json', by_alias=True) + else: + payload = dict(rule_set or {}) + if 'rule_set_id' not in payload and payload.get('rule_id'): + payload['rule_set_id'] = payload['rule_id'] + payload.pop('status', None) + payload.pop('requires_confirmation', None) + payload.pop('rule_version', None) + payload.pop('rule_id', None) + for rule in payload.get('rules') or []: + segment = rule.get('segment') if isinstance(rule, dict) else None + if not isinstance(segment, dict): + continue + segment.pop('handling', None) + segment.pop('target_field_id', None) + segment.pop('target_field_code', None) + return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')) + + +# --------------------------------------------------------------------------- +# [STEP 2] 共享核心执行——纯 dataclass 中间结果,不暴露给 XFA 对外 API +# --------------------------------------------------------------------------- + + +@dataclass +class CoreCapturedRelation: + """核心层捕获到的关系元数据(Q2 双层设计 rule/matcher 层)。""" + + type: RelationCaptureType + line_no: int | None + raw_text: str | None + + +@dataclass +class _CoreSegmentResult: + """单段执行结果(核心层,含 captured_relation;XFA 适配后丢弃)。""" + + segment_id: str + segment_code: str + display_name: str + line_no: int | None + line_end_no: int | None + raw_text: str + normalized_text: str + handling: str + target_field_id: str | None + target_field_code: str | None + rule_id: str + status: str + matcher_type: str + captured_relation: CoreCapturedRelation | None = None + + +@dataclass +class CoreSplitDiagnostic: + """共享核心规则执行诊断。""" + + code: str + message: str + line_no: int | None = None + field_code: str | None = None + rule_ids: list[str] = field(default_factory=list) + + +@dataclass +class _CoreSplitEngineResult: + """共享核心引擎输出。""" + + status: str + segments: list[_CoreSegmentResult] = field(default_factory=list) + mapped_fields: dict[str, str] = field(default_factory=dict) + evidence_only_segments: list[_CoreSegmentResult] = field(default_factory=list) + diagnostics: list[CoreSplitDiagnostic] = field(default_factory=list) + rule_set_id: str | None = None + rule_version: int | None = None + + +@dataclass +class _LineMatch: + """单行候选命中(共享核心版,含 relation 捕获)。""" + + rule: BaseSplitRule + matcher_type: str + priority: int + line_text: str + normalized_text: str + raw_line: str + captured_relation: CoreCapturedRelation | None = None + + +# --------------------------------------------------------------------------- +# [STEP 3] 纯文本执行函数——从 XFA 拆分引擎原封不动迁移,保持字节级一致 +# --------------------------------------------------------------------------- + + +def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]: + """ + 按声明的 line_breaks 切分文本(长分隔符优先)。 + + Args: + text: 原始文本。 + line_breaks: 换行符列表。 + + Returns: + 切分后的行列表(尚未 trim / 去空行)。 + """ + if not text: + return [] + pattern = '|'.join(re.escape(item) for item in sorted(line_breaks, key=len, reverse=True)) + if not pattern: + return [text] + return re.split(pattern, text) + + +def _apply_line_normalization( + lines: list[str], + *, + trim: bool, + remove_empty_lines: bool, +) -> list[str]: + """对行列表应用 trim / 去空行。""" + out = list(lines) + if trim: + out = [item.strip() for item in out] + if remove_empty_lines: + out = [item for item in out if item] + return out + + +def _inventory_lines(raw_value: str, rule_set: BaseSplitRuleSet) -> list[str]: + """ + 用规则集级 normalization 生成行清单。 + + 核心逻辑:按 normalization.line_breaks 拆行并应用 trim / 去空行。 + """ + norm = rule_set.normalization + lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks)) + return _apply_line_normalization( + lines, + trim=bool(norm.trim), + remove_empty_lines=bool(norm.remove_empty_lines), + ) + + +def _extract_prefix_value(line: str, matcher: BaseSplitMatcher) -> str | None: + """ + 前缀匹配:标签 + 分隔符后的值。 + + Returns: + 提取值;无法匹配时 None。 + """ + label = str(matcher.value or '') + hay = line if matcher.case_sensitive else line.casefold() + needle = label if matcher.case_sensitive else label.casefold() + if not hay.startswith(needle): + return None + rest = line[len(label):] + for sep in matcher.separators: + if rest.startswith(sep): + return rest[len(sep):].strip() + stripped = rest.lstrip() + if stripped.startswith(sep): + return stripped[len(sep):].strip() + return None + + +def _regex_extract_value_and_relation( + line: str, + matcher: BaseSplitMatcher, +) -> tuple[str | None, CoreCapturedRelation | None, str | None]: + """ + 正则捕获单行文本的值与可选 relation。 + + Returns: + (value, captured_relation, error_code);成功时 error_code 为 None。 + """ + pattern = str(matcher.pattern or '') + timeout_ms = get_split_regex_timeout_ms() + max_len = get_split_max_regex_pattern_length() + max_groups = get_split_max_regex_groups() + try: + compiled = compile_safe_regex( + pattern, + case_sensitive=bool(matcher.case_sensitive), + max_length=max_len, + max_groups=max_groups, + ) + matched = search_safe(compiled, line, timeout_ms=timeout_ms) + except SafeRegexError: + return None, None, 'regex_failed' + except TimeoutError: + return None, None, 'regex_timeout' + if not matched: + return None, None, 'regex_not_matched' + + group = matcher.capture_group + try: + if group is None: + if matched.lastindex: + value = str(matched.group(1) or '').strip() + else: + value = str(matched.group(0) or '').strip() + else: + value = str(matched.group(group) or '').strip() + except IndexError: + return None, None, 'regex_failed' + + relation: CoreCapturedRelation | None = None + rc = matcher.relation_capture + if rc is not None: + try: + rel_raw = matched.group(rc.capture_group) + rel_text = str(rel_raw or '').strip() if rel_raw is not None else None + rel_line_no: int | None = None + if rel_text: + m = re.search(r'(\d{1,6})', rel_text) + if m: + rel_line_no = int(m.group(1)) + relation = CoreCapturedRelation( + type=rc.type, + line_no=rel_line_no, + raw_text=rel_text, + ) + except (IndexError, ValueError): + relation = None + + return value, relation, None + + +def _match_line( + line_no: int, + line: str, + rule: BaseSplitRule, +) -> tuple[_LineMatch | None, str | None]: + """ + 判断单条规则是否命中指定行(共享核心版,支持 relation 捕获)。 + + Returns: + (match, error_code):命中时 error_code 为 None;未命中时 match 为 None。 + """ + matcher = rule.matcher + priority = SPLIT_MATCHER_PRIORITY.get(matcher.type) + if priority is None: + return None, 'unknown_matcher' + + if matcher.type == 'position': + if int(matcher.line_index or 0) != line_no: + return None, None + normalized = line.strip() if line else '' + return _LineMatch( + rule=rule, + matcher_type='position', + priority=priority, + line_text=line, + normalized_text=normalized, + raw_line=line, + ), None + + if matcher.type == 'prefix': + extracted = _extract_prefix_value(line, matcher) + if extracted is None: + return None, None + return _LineMatch( + rule=rule, + matcher_type='prefix', + priority=priority, + line_text=line, + normalized_text=extracted, + raw_line=line, + ), None + + if matcher.type == 'regex': + value, relation, err = _regex_extract_value_and_relation(line, matcher) + if err: + return None, err + if value is None: + return None, None + return _LineMatch( + rule=rule, + matcher_type='regex', + priority=priority, + line_text=line, + normalized_text=value, + raw_line=line, + captured_relation=relation, + ), None + + return None, 'unknown_matcher' + + +def _pick_line_winner( + line_no: int, + matches: list[_LineMatch], + diagnostics: list[CoreSplitDiagnostic], +) -> _LineMatch | None: + """ + 按 prefix > regex > position 决出单行唯一胜出规则。 + + 核心逻辑:同优先级多个 mapped 命中 → duplicate_line_match;不同优先级取最高优先级。 + """ + if not matches: + return None + + diagnostics.append(CoreSplitDiagnostic( + code='line_match_candidates', + message='All matcher hits for line recorded', + line_no=line_no, + rule_ids=[item.rule.rule_id for item in matches], + )) + + best_priority = min(item.priority for item in matches) + tier = [item for item in matches if item.priority == best_priority] + mapped_tier = [item for item in tier if item.rule.segment.handling == 'mapped'] + + if len(mapped_tier) >= 2: + diagnostics.append(CoreSplitDiagnostic( + code='duplicate_line_match', + message='Multiple mapped rules matched the same line at the same priority', + line_no=line_no, + rule_ids=[item.rule.rule_id for item in mapped_tier], + )) + + if len(tier) == 1: + return tier[0] + + if len(mapped_tier) == 1: + return mapped_tier[0] + + if len(mapped_tier) >= 2: + return sorted(mapped_tier, key=lambda item: item.rule.rule_id)[0] + + return sorted(tier, key=lambda item: item.rule.rule_id)[0] + + +def execute_base_split_rule_set( + *, + raw_value: str, + rule_set: BaseSplitRuleSet, + lines: list[str] | None = None, +) -> _CoreSplitEngineResult: + """ + 对单个源文本原值执行共享拆分规则集。 + + 核心逻辑: + 1. normalization.line_breaks 拆行; + 2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment; + 3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review; + 4. 未认领行按 unmatched_line_policy; + 5. evidence_only 全部保留; + 6. relation_capture 在 core 层保留到 _CoreSegmentResult(上层适配决定是否丢弃)。 + + Args: + raw_value: 保留换行的原始文本(XFA 场景下是 leaf.raw_value;VC 场景下是区域原文)。 + rule_set: 已校验共享规则集。 + lines: 可选预切分行(覆盖 normalization 结果)。 + + Returns: + _CoreSplitEngineResult。 + """ + if len(raw_value or '') > get_split_max_input_length(): + return _CoreSplitEngineResult( + status='needs_review', + diagnostics=[CoreSplitDiagnostic( + code='input_too_long', + message='Split source value exceeds max input length', + )], + rule_set_id=rule_set.rule_set_id, + rule_version=rule_set.rule_version, + ) + + inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set) + diagnostics: list[CoreSplitDiagnostic] = [] + segments: list[_CoreSegmentResult] = [] + claimed_lines: set[int] = set() + + # [STEP 1] 逐行匹配并按优先级决出胜出规则。 + for line_no, line in enumerate(inventory, start=1): + matches: list[_LineMatch] = [] + for rule in rule_set.rules: + outcome, error = _match_line(line_no, line, rule) + if error: + diagnostics.append(CoreSplitDiagnostic( + code=error, + message=f'Rule {rule.rule_id} regex failed on line {line_no}', + line_no=line_no, + field_code=rule.segment.target_field_code, + rule_ids=[rule.rule_id], + )) + continue + if outcome is not None: + matches.append(outcome) + + winner = _pick_line_winner(line_no, matches, diagnostics) + if winner is None: + continue + + claimed_lines.add(line_no) + seg = winner.rule.segment + status = 'parsed' + if not str(winner.normalized_text).strip() and seg.handling == 'mapped': + status = 'needs_review' + diagnostics.append(CoreSplitDiagnostic( + code='mapped_value_empty', + message=f'Mapped segment {seg.segment_code} extracted empty value', + line_no=line_no, + field_code=seg.target_field_code, + rule_ids=[winner.rule.rule_id], + )) + segments.append(_CoreSegmentResult( + segment_id=seg.segment_id, + segment_code=seg.segment_code, + display_name=seg.display_name, + line_no=line_no, + line_end_no=line_no, + raw_text=winner.raw_line, + normalized_text=winner.normalized_text, + handling=seg.handling, + target_field_id=seg.target_field_id, + target_field_code=seg.target_field_code, + rule_id=winner.rule.rule_id, + status=status, + matcher_type=winner.matcher_type, + captured_relation=winner.captured_relation, + )) + + # [STEP 2] 未匹配行。 + for line_index, line in enumerate(inventory, start=1): + if line_index in claimed_lines: + continue + status = 'needs_review' if rule_set.unmatched_line_policy == 'needs_review' else 'parsed' + if status == 'needs_review': + diagnostics.append(CoreSplitDiagnostic( + code='unmatched_line', + message='Unmatched line requires review', + line_no=line_index, + )) + segments.append(_CoreSegmentResult( + segment_id=f'unmatched-{line_index}', + segment_code=f'unmatched_line_{line_index}', + display_name=f'其他编码/{line_index}', + line_no=line_index, + line_end_no=line_index, + raw_text=line, + normalized_text=line.strip(), + handling='evidence_only', + target_field_id=None, + target_field_code=None, + rule_id='unmatched', + status=status, + matcher_type='unmatched', + )) + + # [STEP 3] 聚合正式字段。 + mapped_fields: dict[str, str] = {} + field_sources: dict[str, list[str]] = {} + overall = 'parsed' + for item in segments: + if item.status == 'needs_review': + overall = 'needs_review' + if item.handling != 'mapped' or not item.target_field_code: + continue + code = item.target_field_code + field_sources.setdefault(code, []).append(item.rule_id) + if code in mapped_fields: + overall = 'needs_review' + diagnostics.append(CoreSplitDiagnostic( + code='same_field_multiple_segment', + message=f'Schema field {code} hit by multiple segments', + field_code=code, + rule_ids=list(field_sources[code]), + )) + else: + mapped_fields[code] = item.normalized_text + + for _code, sources in field_sources.items(): + if len(sources) > 1 and rule_set.same_field_multiple_segment_policy == 'needs_review': + overall = 'needs_review' + + if any(d.code == 'duplicate_line_match' for d in diagnostics): + if rule_set.duplicate_match_policy == 'needs_review': + overall = 'needs_review' + + if any(d.code in { + 'regex_timeout', 'regex_failed', 'mapped_value_empty', 'input_too_long', + } for d in diagnostics): + overall = 'needs_review' + + evidence_only = [item for item in segments if item.handling == 'evidence_only'] + return _CoreSplitEngineResult( + status=overall, + segments=segments, + mapped_fields=mapped_fields, + evidence_only_segments=evidence_only, + diagnostics=diagnostics, + rule_set_id=rule_set.rule_set_id, + rule_version=rule_set.rule_version, + ) + + +def project_base_split_result_safe( + result: _CoreSplitEngineResult, + *, + include_full_values: bool = False, + mask_value_for_dto_fn: Any = None, +) -> dict[str, Any]: + """ + 将共享核心引擎结果投影为普通 DTO。 + + 核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且 + include_full_values=True 时返回 raw_text / 完整 mapped 值。 + + Args: + result: 引擎输出。 + include_full_values: 是否返回完整业务值(需上游权限门禁)。 + mask_value_for_dto_fn: 可选脱敏函数;None 时使用恒等函数。 + + Returns: + JSON 可序列化 dict。 + """ + def _text(value: str) -> str: + if include_full_values: + return str(value) + if mask_value_for_dto_fn is not None: + try: + return mask_value_for_dto_fn(value) + except Exception: + return str(value) + return str(value) + + mapped = { + code: _text(value) + for code, value in result.mapped_fields.items() + } + return { + 'status': result.status, + 'rule_set_id': result.rule_set_id, + 'rule_version': result.rule_version, + 'full_values_revealed': bool(include_full_values), + 'mapped_fields': mapped, + 'segments': [ + { + 'segment_id': item.segment_id, + 'segment_code': item.segment_code, + 'display_name': item.display_name, + 'line_no': item.line_no, + 'line_end_no': item.line_end_no, + 'raw_text': _text(item.raw_text), + 'normalized_text': _text(item.normalized_text), + 'handling': item.handling, + 'target_field_id': item.target_field_id, + 'target_field_code': item.target_field_code, + 'rule_id': item.rule_id, + 'status': item.status, + 'matcher_type': item.matcher_type, + } + for item in result.segments + ], + 'evidence_only_segments': [], + 'diagnostics': [ + { + 'code': item.code, + 'message': item.message, + 'line_no': item.line_no, + 'field_code': item.field_code, + 'rule_ids': list(item.rule_ids), + } + for item in result.diagnostics + ], + } diff --git a/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py b/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py index 0aadc1d6..c0f993b4 100644 --- a/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py +++ b/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py @@ -13,29 +13,15 @@ def _coordinate_mapping(value: Any) -> dict[str, Any]: return dict(value) if isinstance(value, dict) else {} -def _append_issue(layout: dict[str, Any], issue: str) -> None: - """稳定追加坐标恢复失败码,不改变原 issues 相对顺序。""" - existing = layout.get('issues') if isinstance(layout.get('issues'), list) else [] - issues = [str(item) for item in existing] - if issue not in issues: - issues.append(issue) - layout['issues'] = issues - - def ensure_on_demand_coordinate_evidence( *, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None, table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None, ) -> dict[str, Any]: - """为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。 - - 【AI/调用方触发时机】: - - 订单字段重放、模板匹配或明细重建前,为当前 snapshot 恢复缺失页的真实坐标。 - - 失败不静默;任何 PDFium/OCR 失败都会在 layout['issues'] 追加稳定失败码, - 上游可据此将 matcher 从 no_match 转为 evidence_insufficient。 - """ + """为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。""" if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'): return layout evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + # 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。 if not evidence: legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables') evidence = { @@ -43,6 +29,7 @@ def ensure_on_demand_coordinate_evidence( for key in legacy_keys if isinstance(layout.get(key), dict) } + # Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。 current_version = getattr(document, 'current_layout_version', None) current_payload = getattr(current_version, 'payload_json', None) if isinstance(current_payload, dict): @@ -57,15 +44,7 @@ def ensure_on_demand_coordinate_evidence( sources = _coordinate_mapping(evidence.get('sources')) source_pages = _coordinate_mapping(sources.get('pages')) tables = _coordinate_mapping(evidence.get('tables')) - # [FAIL-CLOSED GATE] page_glyphs 必须对所需页真实存在;不能用 pages 元数据或 - # 非数字脏键来假装已恢复。MinerU HTML 表 + 空 page_glyphs 的组合必须继续走 - # 真实 PDFium/OCR 抽取,否则会退化为"伪精确匹配分数"。 - present_pages = { - int(key) for key in page_glyphs - if str(key).isdigit() and isinstance(page_glyphs.get(key), list) and len(page_glyphs.get(key) or []) > 0 - } - needs_recovery = bool(page_nos is None) or not page_nos.issubset(present_pages) - if not needs_recovery: + if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}): return layout tables_by_page: dict[int, list[dict[str, Any]]] = {} for raw_table in layout.get('tables') or []: @@ -91,15 +70,11 @@ def ensure_on_demand_coordinate_evidence( ) asset = db.session.get(FileAsset, int(document.asset_id)) if asset is None: - _append_issue(layout, 'coordinate_evidence_asset_missing') return layout try: native_pages = extract_native_pdf_pages(read_asset_bytes(asset)) except Exception: - # [FAIL-CLOSED] PDFium 级异常必须显式上报;禁止用 MinerU HTML 列名顶替坐标。 - _append_issue(layout, 'coordinate_evidence_native_pdf_unavailable') return layout - recovered_any_page = False for page in native_pages: if page_nos is not None and int(page.page_no) not in page_nos: continue @@ -112,14 +87,12 @@ def ensure_on_demand_coordinate_evidence( source = 'ocr_coordinate' except Exception: glyphs = [] - _append_issue(layout, f'coordinate_evidence_ocr_failed_page_{page.page_no}') if not glyphs: continue page_key = str(page.page_no) pages[page_key] = {'width': page.width, 'height': page.height} page_glyphs[page_key] = glyphs source_pages[page_key] = source - recovered_any_page = True for table in tables_by_page.get(int(page.page_no), []): table_id = str(table.get('table_id') or '') chars = _native_characters_in_table( @@ -134,8 +107,6 @@ def ensure_on_demand_coordinate_evidence( chars = [] if table_id and chars: tables[table_id] = chars - if page_nos is not None and not recovered_any_page: - _append_issue(layout, 'coordinate_evidence_no_page_recovered') next_layout = dict(layout) next_layout['coordinate_evidence'] = { **evidence, 'pages': pages, 'page_glyphs': page_glyphs, diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py index d8b77d91..6eda7481 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py @@ -119,22 +119,7 @@ def match_frozen_coordinate_profiles( pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} - # [FAIL-CLOSED GATE] 第零层:on-demand 坐标恢复显式失败时直接拒绝匹配。 - # 任何 coordinate_evidence_* 失败码都意味着正式证据不可用,MinerU HTML 列名 - # 不得作为坐标模板匹配的替代事实源。 - layout_issues = {str(item) for item in (layout.get('issues') or []) if str(item)} - coordinate_failure_issues = { - code for code in layout_issues if code.startswith('coordinate_evidence_') - } - if coordinate_failure_issues: - return ProfileMatchResult(status='evidence_insufficient') - # [FAIL-CLOSED GATE] 第一层:坐标字符证据必须至少有一种来源。 - # MinerU HTML tables(layout['tables'])只有结构化列名、没有绝对坐标/bbox, - # 严禁单独充当坐标模板的匹配证据。否则会出现"MinerU 有列名但 matcher - # header_tokens=空、column_count=0、evidence_coverage 伪分数"的分裂。 - if not pages: - return ProfileMatchResult(status='evidence_insufficient') - if not glyph_tables and not page_glyphs: + if not pages or (not glyph_tables and not page_glyphs and not tables): return ProfileMatchResult(status='evidence_insufficient') page_text = _layout_page_text( @@ -216,25 +201,6 @@ def match_frozen_coordinate_profiles( ) reason_codes.extend(hard_conflict_codes) - # [FAIL-CLOSED GATE] 第二层:身份证据缺失时,结构/几何维度不得独立构成模板命中。 - # 用户场景:page_glyphs 虽有字符但观测不到 header_tokens 或 - # column_centers;若签名冻结了核心列身份证据,就必须以身份优先、 - # 结构辅助。否则 table_geometry + page_structure 的弱证据会掩盖 - # "列名证据没有进入匹配器" 的真正问题。 - signature_patterns = ( - [item for item in (signature_body or {}).get('table_patterns') or [] if isinstance(item, dict)] - if signature_body is not None else [] - ) - signature_expects_identity = any( - bool(p.get('header_tokens') or p.get('column_centers') or (p.get('column_count') or 0) > 0) - for p in signature_patterns - ) - observed_header = [str(item) for item in (observed.get('header_tokens') or []) if str(item).strip()] - observed_col_count = int(observed.get('column_count') or 0) - observed_has_identity = bool(observed_header) or observed_col_count > 0 - if signature_expects_identity and not observed_has_identity: - reason_codes.append('profile_core_column_evidence_missing') - weights = profile.document_match.scoring_weights score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results) hard_match = not reason_codes @@ -290,19 +256,6 @@ def match_frozen_coordinate_profiles( status='no_match', candidates=rendered, top1_score=top1_score, top2_score=top2_score, margin=margin, ) - # [FAIL-CLOSED GATE] 第三层:全局证据不足优先于 no_match / layout_drift。 - # 当所有候选要么缺签名身份证据、要么观测不到核心列名/列坐标时,必须 - # evidence_insufficient,禁止把"没证据"误报成"模板都不匹配"。 - global_identity_missing = all( - 'profile_core_column_evidence_missing' in item.reason_codes - or 'profile_signature_missing' in item.reason_codes - for item in rendered - ) - if global_identity_missing: - return ProfileMatchResult( - status='evidence_insufficient', candidates=rendered, - top1_score=None, top2_score=None, margin=None, - ) if _any_special_profile_feature(candidates, page_text=page_text): return ProfileMatchResult( status='layout_drift', candidates=rendered, diff --git a/backend/app/services/shipping_notice/document_layout/profile_field_source_mapping_service.py b/backend/app/services/shipping_notice/document_layout/profile_field_source_mapping_service.py new file mode 100644 index 00000000..9f1bb1f2 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/profile_field_source_mapping_service.py @@ -0,0 +1,456 @@ +""" +services/shipping_notice/document_layout/profile_field_source_mapping_service.py + +用途:Profile 字段来源映射服务(Q18 抽取层裁决前置)——独立收集 Header / Table 列 / + Vendor Comments 三个来源的候选观察,**不直接写 Observation 表**,只返回统一的 + FieldSourceCandidate 列表供 SourceMergeService 做 Q18 裁决合并。 +依赖:profile_vendor_comments_contract(parse_field_source_mappings/parse_named_regions)、 + field_split_core(execute_base_split_rule_set 用于 Vendor Comments 区域拆分)、 + coordinate_region_source_adapter(CoordinateRegionSourceAdapter 物理区域渲染)、 + reservation_relation_projection(ReservationRelationProjection 关系投影)。 +逻辑:严格「后端决定 UI」——本类输出每个候选的 target_scope/target_field_code/ + effective_line_no/value/source/evidence_ref/source_observation_metadata, + 前端只能消费这些投影字段,禁止自行推导业务状态。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Literal + +from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import ( + CoordinateRegionEvidence, + CoordinateRegionSourceAdapter, + CoordinateRegionSourceResult, +) +from app.services.shipping_notice.document_layout.field_split_core import ( + CoreCapturedRelation, + _CoreSegmentResult, + execute_base_split_rule_set, +) +from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import ( + NamedRegion, + ProfileFieldSourceMapping, + parse_field_source_mappings, + parse_named_regions, +) +from app.services.shipping_notice.document_layout.reservation_relation_projection import ( + ReservationRelationProjection, + ReservationRelationProjectionResult, +) + + +FieldSourceLiteral = Literal['header_region', 'table_column', 'vendor_comments'] + + +@dataclass +class FieldSourceCandidate: + """ + 单来源单观察候选——Header/Table/Vendor Comments 各自产出后,由 SourceMergeService 裁决。 + + 【后端决定 UI】:scope、line_no、value、format_valid、conflict_group_key 全部在本层 + 计算完毕,前端只读投影,禁止自己用逻辑 if/else 推导。 + """ + + source: FieldSourceLiteral + target_scope: Literal['header', 'line'] + target_field_code: str + target_field_id: str + value: str + normalized_value: str + format_valid: bool | None # None = 本字段不需要格式校验(非 reservation) + format_reason_code: str | None # format_valid=False 时的稳定诊断码(例:reservation_format_invalid) + effective_line_no: int | None # 1-based;header 时为 None;default_all_lines 时为具体行号 + resolution_hint: Literal[ + 'provisional', 'annotation_only', 'invalid_line_reference', + ] = 'provisional' + relation_projection: ReservationRelationProjectionResult | None = None + # 证据区——写入 Observation.evidence_quote / evidence_ref / evidence_metadata_json + evidence_quote: str | None = None + evidence_ref: str | None = None + evidence_metadata: dict[str, Any] = field(default_factory=dict) + # SourceMergeService 内部使用:冲突分组键 = (target_scope, target_field_code, effective_line_no) + conflict_group_key: tuple[Any, ...] = () + + +class ProfileFieldSourceMappingService: + """ + 三来源候选独立收集服务(路径判断与事实分离)。 + + 【AI 触发时机】:订单文档抽取阶段(order_extraction_workflow 在 Observation 写入前) + 调用 collect_candidates() 返回候选列表,再交给 SourceMergeService 裁决合并。 + + 核心执行顺序: + [STEP 1] 解析 Profile definition_json 的 named_regions + field_source_mappings。 + [STEP 2] 对每个 mapping: + a. header_source_enabled → 从 header_observations_by_source_ref 取现成观察 + b. table_source_enabled → 从 table_column_values 取(column_code + line_index) + c. vendor_comments_enabled → 调 CoordinateRegionSourceAdapter + execute_base_split_rule_set + [STEP 3] 对每个 Vendor Comments 拆分结果,调 ReservationRelationProjection.project + 生成 effective_line_no / resolution_hint。 + [STEP 4] 返回 FieldSourceCandidate 列表;未通过 format_policy 的候选保留 + value 但标记 format_valid=False(Q15:格式失败的值不丢弃)。 + """ + + def __init__( + self, + *, + definition_json: dict[str, Any], + header_observations_by_source_ref: dict[str, list[dict[str, Any]]] | None = None, + table_column_values: dict[str, list[dict[str, Any]]] | None = None, + page_glyphs_map: dict[int, dict[str, Any]] | None = None, + # Reservation Relation Projection 三层判定表 + explicit_line_column_values: dict[int, str] | None = None, + profile_business_line_numbers: dict[int, Any] | None = None, + classified_logical_line_numbers: dict[int, int] | None = None, + total_logical_lines: int = 0, + # 格式策略调用方(保留注入点,避免本类直接 import reservation 校验模块造成循环) + format_validator_callback=None, + ): + self.definition_json = definition_json or {} + self.header_observations_by_source_ref = header_observations_by_source_ref or {} + self.table_column_values = table_column_values or {} + self.page_glyphs_map = page_glyphs_map or {} + self.explicit_line_column_values = explicit_line_column_values or {} + self.profile_business_line_numbers = profile_business_line_numbers or {} + self.classified_logical_line_numbers = classified_logical_line_numbers or {} + self.total_logical_lines = total_logical_lines + self.format_validator_callback = format_validator_callback + # 预先解析契约(若失败抛 ValidationError 阻断运行,避免输出坏数据) + self.named_regions: dict[str, NamedRegion] = parse_named_regions( + self.definition_json.get('named_regions'), + ) + self.mappings: list[ProfileFieldSourceMapping] = parse_field_source_mappings( + self.definition_json.get('field_source_mappings'), + ) + + # ------------------------------------------------------------------ + # 对外主入口 + # ------------------------------------------------------------------ + + def collect_candidates(self) -> list[FieldSourceCandidate]: + """ + 返回全量候选。任何内部失败都返回稳定 status 候选(不抛错阻断其他字段)。 + 调用方:SourceMergeService.merge_and_decide() → 再调用 obs 写入。 + """ + candidates: list[FieldSourceCandidate] = [] + for mapping in self.mappings: + if mapping.header_source_enabled and mapping.header_source_ref: + candidates.extend(self._collect_header_source(mapping)) + if mapping.table_source_enabled and mapping.table_column_code: + candidates.extend(self._collect_table_source(mapping)) + if mapping.vendor_comments_enabled and mapping.vendor_comments_region_ref: + candidates.extend(self._collect_vendor_comments_source(mapping)) + for cand in candidates: + cand.conflict_group_key = (cand.target_scope, cand.target_field_code, cand.effective_line_no) + return candidates + + # ------------------------------------------------------------------ + # 三个来源分支(独立收集,不互相读数据——满足 Q18 先独立再裁决) + # ------------------------------------------------------------------ + + def _collect_header_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]: + """Header 区域来源——从 caller 传入的 header_observations_by_source_ref 读取。""" + header_items = self.header_observations_by_source_ref.get(mapping.header_source_ref or '', []) + results: list[FieldSourceCandidate] = [] + for item in header_items: + raw_value = str(item.get('value') or '') + format_valid, reason = self._check_format(mapping, raw_value) + results.append(FieldSourceCandidate( + source='header_region', + target_scope=mapping.target_scope, + target_field_code=mapping.target_field_code, + target_field_id=mapping.target_field_id, + value=raw_value, + normalized_value=_normalize_string(raw_value), + format_valid=format_valid, + format_reason_code=reason, + effective_line_no=None, # header scope 固定 None + evidence_quote=raw_value[:512], + evidence_ref=str(item.get('evidence_ref') or '') or None, + evidence_metadata=dict(item.get('evidence_metadata') or {}), + )) + return results + + def _collect_table_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]: + """表身列来源——从 caller 传入的 table_column_values[column_code] 读取,每行一个候选。""" + rows = self.table_column_values.get(mapping.table_column_code or '', []) + results: list[FieldSourceCandidate] = [] + for row in rows: + try: + line_no = int(row.get('line_index')) + 1 # 转 1-based + except (TypeError, ValueError): + continue + raw_value = str(row.get('value') or '') + format_valid, reason = self._check_format(mapping, raw_value) + results.append(FieldSourceCandidate( + source='table_column', + target_scope=mapping.target_scope, + target_field_code=mapping.target_field_code, + target_field_id=mapping.target_field_id, + value=raw_value, + normalized_value=_normalize_string(raw_value), + format_valid=format_valid, + format_reason_code=reason, + effective_line_no=line_no, + evidence_quote=raw_value[:512], + evidence_ref=str(row.get('evidence_ref') or '') or None, + evidence_metadata=dict(row.get('evidence_metadata') or {}), + )) + return results + + def _collect_vendor_comments_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]: + """ + Vendor Comments 来源——三步走: + 1. CoordinateRegionSourceAdapter 渲染区域原文 + bbox 证据; + 2. execute_base_split_rule_set 拆出段(带 captured_relation); + 3. ReservationRelationProjection 投影关系到 effective_line_no / resolution_hint。 + """ + region_ref = mapping.vendor_comments_region_ref or '' + region = self.named_regions.get(region_ref) + if region is None: + return [self._missing_region_fallback(mapping, region_ref)] + adapter = CoordinateRegionSourceAdapter(region, self.page_glyphs_map) + region_result: CoordinateRegionSourceResult = adapter.extract() + if region_result.status != 'available' or not mapping.vendor_comments_split_rule_set: + return [self._unavailable_region_candidate(mapping, region_result)] + + split_result = execute_base_split_rule_set( + raw_value=region_result.raw_text, + rule_set=mapping.vendor_comments_split_rule_set, + lines=region_result.lines or None, + ) + + projector = ReservationRelationProjection( + relation_policy=mapping.relation_policy, + line_reference_basis=mapping.line_reference_basis, + missing_relation_policy=mapping.missing_relation_policy, + ) + # 先收集 mapped 段,再收集 evidence_only 段(annotation_only 用) + all_segments: list[_CoreSegmentResult] = list(split_result.segments) + list(split_result.evidence_only_segments) + results: list[FieldSourceCandidate] = [] + token_evidence_map = _build_evidence_ref_map(region_result.evidence_tokens) + for seg in all_segments: + rel_proj = projector.project( + captured_relation=seg.captured_relation, + explicit_line_column_values=self.explicit_line_column_values, + profile_business_line_numbers=self.profile_business_line_numbers, + classified_logical_line_numbers=self.classified_logical_line_numbers, + ) + format_valid, reason = self._check_format(mapping, seg.normalized_text) + if rel_proj.resolution == 'bound_to_line': + results.append(self._make_vc_candidate( + mapping=mapping, seg=seg, rel_proj=rel_proj, + region_result=region_result, token_evidence_map=token_evidence_map, + effective_line_no=rel_proj.resolved_logical_line_no, + resolution_hint='provisional', format_valid=format_valid, format_reason=reason, + )) + elif rel_proj.resolution == 'default_all_lines': + # 每行都生成一个(common case:整个 Vendor Comments 段没有 line 号引用) + for line_idx in range(1, max(1, self.total_logical_lines) + 1): + results.append(self._make_vc_candidate( + mapping=mapping, seg=seg, rel_proj=rel_proj, + region_result=region_result, token_evidence_map=token_evidence_map, + effective_line_no=line_idx if mapping.target_scope == 'line' else None, + resolution_hint='provisional', format_valid=format_valid, format_reason=reason, + )) + elif rel_proj.resolution == 'annotation_only': + results.append(self._make_vc_candidate( + mapping=mapping, seg=seg, rel_proj=rel_proj, + region_result=region_result, token_evidence_map=token_evidence_map, + effective_line_no=None, + resolution_hint='annotation_only', format_valid=format_valid, format_reason=reason, + )) + elif rel_proj.resolution == 'invalid_line_reference': + results.append(self._make_vc_candidate( + mapping=mapping, seg=seg, rel_proj=rel_proj, + region_result=region_result, token_evidence_map=token_evidence_map, + effective_line_no=None, + resolution_hint='invalid_line_reference', format_valid=False, + format_reason=reason or 'invalid_line_reference', + )) + else: + # default_header_only / conflict_unresolved + results.append(self._make_vc_candidate( + mapping=mapping, seg=seg, rel_proj=rel_proj, + region_result=region_result, token_evidence_map=token_evidence_map, + effective_line_no=None if mapping.target_scope == 'header' else None, + resolution_hint='provisional', format_valid=format_valid, format_reason=reason, + )) + return results + + # ------------------------------------------------------------------ + # 辅助:格式校验(Q15)+ Vendor Comments 候选构造 + # ------------------------------------------------------------------ + + def _check_format( + self, mapping: ProfileFieldSourceMapping, value: str, + ) -> tuple[bool | None, str | None]: + """返回 (format_valid, reason_code);非 reservation 字段返回 (None, None)。""" + if mapping.target_field_code != 'reservation_id': + return None, None + if not value: + return False, 'reservation_format_empty' + if self.format_validator_callback is not None: + ok = bool(self.format_validator_callback(mapping.format_policy, value)) + return (True, None) if ok else (False, 'reservation_format_invalid') + # 默认回退全局 validated_reservation_id(Q15 方案 A:本期不重构全局) + from app.services.shipping_notice.reservation_id import validated_reservation_id + ok = validated_reservation_id(value) is not None + return (True, None) if ok else (False, 'reservation_format_invalid') + + @staticmethod + def _missing_region_fallback(mapping: ProfileFieldSourceMapping, region_ref: str) -> FieldSourceCandidate: + return FieldSourceCandidate( + source='vendor_comments', + target_scope=mapping.target_scope, + target_field_code=mapping.target_field_code, + target_field_id=mapping.target_field_id, + value='', + normalized_value='', + format_valid=None, + format_reason_code=None, + effective_line_no=None, + resolution_hint='provisional', + evidence_quote=None, + evidence_ref=None, + evidence_metadata={'reason': 'named_region_not_found', 'region_ref': region_ref}, + ) + + @staticmethod + def _unavailable_region_candidate( + mapping: ProfileFieldSourceMapping, region_result: CoordinateRegionSourceResult, + ) -> FieldSourceCandidate: + return FieldSourceCandidate( + source='vendor_comments', + target_scope=mapping.target_scope, + target_field_code=mapping.target_field_code, + target_field_id=mapping.target_field_id, + value='', + normalized_value='', + format_valid=None, + format_reason_code=None, + effective_line_no=None, + resolution_hint='provisional', + evidence_quote=region_result.raw_text[:512] or None, + evidence_ref=None, + evidence_metadata={ + 'reason': region_result.diagnostic_code or 'named_region_unavailable', + 'diagnostic_message': region_result.diagnostic_message, + 'region_id': region_result.region_id, + }, + ) + + @staticmethod + def _make_vc_candidate( + *, + mapping: ProfileFieldSourceMapping, + seg: _CoreSegmentResult, + rel_proj: ReservationRelationProjectionResult, + region_result: CoordinateRegionSourceResult, + token_evidence_map: dict[str, list[CoordinateRegionEvidence]], + effective_line_no: int | None, + resolution_hint: Literal['provisional', 'annotation_only', 'invalid_line_reference'], + format_valid: bool | None, + format_reason: str | None, + ) -> FieldSourceCandidate: + token_ev = _find_best_token_evidence(token_evidence_map, seg.normalized_text) + evidence_quote = seg.raw_text[:512] or None + evidence_ref = _vc_evidence_ref(region_result, seg, token_ev) + metadata: dict[str, Any] = { + 'region_id': region_result.region_id, + 'segment_id': seg.segment_id, + 'rule_id': seg.rule_id, + 'matcher_type': seg.matcher_type, + 'handling': seg.handling, + 'line_bounds_in_region': [seg.line_no, seg.line_end_no], + 'captured_relation_raw': ( + None if seg.captured_relation is None else { + 'type': seg.captured_relation.type, + 'line_no': seg.captured_relation.line_no, + 'raw_text': seg.captured_relation.raw_text, + } + ), + 'relation_projection': _proj_to_json(rel_proj), + 'best_token': (None if token_ev is None else { + 'page_no': token_ev.page_no, + 'x0': token_ev.x0, 'y0': token_ev.y0, + 'x1': token_ev.x1, 'y1': token_ev.y1, + 'text': token_ev.text, + }), + } + return FieldSourceCandidate( + source='vendor_comments', + target_scope=mapping.target_scope, + target_field_code=mapping.target_field_code, + target_field_id=mapping.target_field_id, + value=seg.raw_text, + normalized_value=seg.normalized_text, + format_valid=format_valid, + format_reason_code=format_reason, + effective_line_no=effective_line_no, + resolution_hint=resolution_hint, + relation_projection=rel_proj, + evidence_quote=evidence_quote, + evidence_ref=evidence_ref, + evidence_metadata=metadata, + ) + + +# --------------------------------------------------------------------------- +# 模块级纯函数(避免每次 Service 实例化重复加载) +# --------------------------------------------------------------------------- + + +def _normalize_string(v: str) -> str: + return ' '.join(str(v or '').split()).strip() + + +def _build_evidence_ref_map(tokens: list[CoordinateRegionEvidence]) -> dict[str, list[CoordinateRegionEvidence]]: + out: dict[str, list[CoordinateRegionEvidence]] = {} + for t in tokens: + out.setdefault(_normalize_string(t.text), []).append(t) + return out + + +def _find_best_token_evidence( + evidence_map: dict[str, list[CoordinateRegionEvidence]], value: str, +) -> CoordinateRegionEvidence | None: + norm = _normalize_string(value) + if norm in evidence_map and evidence_map[norm]: + return evidence_map[norm][0] + # 降级:子串命中 + for key, tokens in evidence_map.items(): + if norm and (norm in key or key in norm) and tokens: + return tokens[0] + return None + + +def _vc_evidence_ref( + region_result: CoordinateRegionSourceResult, + seg: _CoreSegmentResult, + token: CoordinateRegionEvidence | None, +) -> str: + """ + 稳定 Observation.evidence_ref。 + 格式:vc:///p/seg-[:---] + """ + base = f"vc://{region_result.region_id}/p{region_result.page_no}/seg-{seg.segment_id}" + if token is not None: + base += ( + f":{round(token.x0, 4)}-{round(token.y0, 4)}-" + f"{round(token.x1, 4)}-{round(token.y1, 4)}" + ) + return base[:512] + + +def _proj_to_json(p: ReservationRelationProjectionResult) -> dict[str, Any]: + return { + 'line_reference_basis': p.line_reference_basis, + 'resolution': p.resolution, + 'resolved_logical_line_no': p.resolved_logical_line_no, + 'annotation_reason': p.annotation_reason, + 'invalid_reference_raw_value': p.invalid_reference_raw_value, + 'invalid_reference_line_no': p.invalid_reference_line_no, + 'audit_chain_count': 0 if p.audit_chain is None else len(p.audit_chain), + } diff --git a/backend/app/services/shipping_notice/document_layout/profile_vendor_comments_contract.py b/backend/app/services/shipping_notice/document_layout/profile_vendor_comments_contract.py new file mode 100644 index 00000000..ec5f348d --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/profile_vendor_comments_contract.py @@ -0,0 +1,338 @@ +""" +services/shipping_notice/document_layout/profile_vendor_comments_contract.py + +用途:Profile 顶层新增的 Vendor Comments 三来源契约(不修改现有 OrderCoordinateProfile 字段, + 保持「路径判断与事实分离」——definition_json.get 读取命名区域和字段来源映射)。 +依赖:Pydantic、field_split_core.BaseSplitRuleSet、RelativeRegion(来自 order_profile)。 +逻辑:对外暴露 parse_named_regions() / parse_field_source_mappings() / validate_format_policy() + 三个稳定入口;所有变更是否触发「回 Draft + 重新验证」由 profile_regions_require_draft() + 判定,禁止各业务点自行假设回 Draft 条件。 +""" + +from __future__ import annotations + +import hashlib +import json +import re +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from app.core.errors import ValidationError +from app.services.shipping_notice.document_layout.field_split_core import ( + BaseSplitRuleSet, +) +from app.services.shipping_notice.document_layout.order_profile import ( + RelativeRegion, +) + + +# --------------------------------------------------------------------------- +# 顶层 Pydantic 契约——definition_json 结构 +# --------------------------------------------------------------------------- + + +VC_MODEL_CONFIG = ConfigDict(extra='forbid', validate_assignment=True) + + +class NamedRegion(BaseModel): + """ + 物理来源命名区域(Q14 冻结)——管理员圈选的坐标框。 + + 【关键约束】:不是 Schema 字段区域伪装,是 Vendor Comments 等非 XFA 正文块的真实 + 阅读区域。变更此对象必须回 Draft(由 profile_regions_require_draft 判定)。 + """ + + model_config = VC_MODEL_CONFIG + + region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$') + label: str = Field(min_length=1, max_length=160) + region: RelativeRegion + page_scope: Literal['first_page', 'last_page', 'all_pages', 'exact_page'] = 'last_page' + page_no: int | None = Field(default=None, ge=1) + selection_mode: Literal['fixed_region', 'auto_take_last_qualified'] = 'fixed_region' + + @model_validator(mode='after') + def validate_page_semantics(self) -> 'NamedRegion': + if self.page_scope == 'exact_page' and self.page_no is None: + raise ValueError('exact_page named region requires page_no') + if self.page_scope != 'exact_page' and self.page_no is not None: + raise ValueError('page_no is only allowed for exact_page named region') + return self + + +class ReservationFormatPolicy(BaseModel): + """ + Reservation 格式校验策略(Q15 冻结)——Profile 级受控策略,未配置时回退全局 5/10 纯数字。 + + 首期仅支持 numeric_5_or_10 / custom_safe_regex 两种;custom_safe_regex 必须经过 + 长度限制、捕获组限制、危险表达式黑名单与超时上限 4 层门禁。 + """ + + model_config = VC_MODEL_CONFIG + + mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex'] = 'inherit_global' + pattern: str | None = Field(default=None, min_length=1, max_length=1024) + max_capture_groups: int = Field(default=2, ge=0, le=8) + timeout_ms: int = Field(default=30, ge=10, le=500) + case_sensitive: bool = False + + @model_validator(mode='after') + def validate_regex_policy(self) -> 'ReservationFormatPolicy': + if self.mode != 'custom_safe_regex': + if self.pattern is not None: + raise ValueError('pattern only allowed for custom_safe_regex mode') + return self + if not self.pattern: + raise ValueError('custom_safe_regex requires a non-empty pattern') + _validate_safe_regex_pattern( + self.pattern, + max_groups=self.max_capture_groups, + case_sensitive=self.case_sensitive, + ) + return self + + +class ProfileFieldSourceMapping(BaseModel): + """ + Profile 级字段来源映射(Q9 冻结,并列 split_rules)——声明一个 Schema 字段从三来源 + (header/table_column/vendor_comments)哪几个抽取,以及各自使用的拆分规则与关系策略。 + """ + + model_config = VC_MODEL_CONFIG + + mapping_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') + target_scope: Literal['header', 'line'] + target_field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') + target_field_id: str = Field(min_length=1, max_length=128) + + # 三来源开关——未启用的来源在 ProfileFieldSourceMappingService 直接跳过 + header_source_enabled: bool = False + header_source_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$') + header_normalizer_key: str | None = Field(default=None, min_length=1, max_length=64) + + table_source_enabled: bool = False + table_column_code: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$') + + vendor_comments_enabled: bool = False + vendor_comments_region_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_-]{0,95}$') + vendor_comments_split_rule_set: BaseSplitRuleSet | None = None + + # 关系策略(Q2 双层设计)——本期仅 reservation_id 绑定明细行使用 bind_target_line + relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'] = 'no_relation' + missing_relation_policy: Literal['default_all_lines', 'default_header_only', 'fallback_single_line_when_no_reference'] = 'default_header_only' + line_reference_basis: Literal['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no'] = 'profile_business_line_no' + + # 三来源空值互补策略——Q4 冲突矩阵里不同 scope 独立保留,同 scope 值不一致 Review + fill_missing_from_other_sources: bool = True + + format_policy: ReservationFormatPolicy = Field(default_factory=ReservationFormatPolicy) + + @model_validator(mode='after') + def validate_source_refs(self) -> 'ProfileFieldSourceMapping': + if self.header_source_enabled and not self.header_source_ref: + raise ValueError('header_source_ref is required when header_source_enabled') + if self.table_source_enabled and not self.table_column_code: + raise ValueError('table_column_code is required when table_source_enabled') + if self.vendor_comments_enabled: + if not self.vendor_comments_region_ref: + raise ValueError('vendor_comments_region_ref is required when vendor_comments_enabled') + if not self.vendor_comments_split_rule_set: + raise ValueError('vendor_comments_split_rule_set is required when vendor_comments_enabled') + return self + + +# --------------------------------------------------------------------------- +# 稳定读取工具:接受 None / 脏 dict,返回归一化契约对象(路径判断与事实分离) +# --------------------------------------------------------------------------- + + +def parse_named_regions(value: Any) -> dict[str, NamedRegion]: + """ + 从 definition_json.named_regions(或 None)解析命名区域字典。 + + 【AI 触发时机】:读取 Profile 配置阶段、预览阶段或变更比对阶段调用。 + 核心逻辑:值为 None/空 dict 时返回空字典(允许客户先不配 Vendor Comments 区域); + 未知键直接保留映射,不抛错;坏值立刻抛 ValidationError 避免运行时污染。 + + Args: + value: Profile definition_json.get('named_regions') 原值。 + + Returns: + {region_id: NamedRegion} 字典。 + """ + if value is None: + return {} + if not isinstance(value, dict): + raise ValidationError( + 'definition_json.named_regions must be an object', + code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID', + ) + result: dict[str, NamedRegion] = {} + for key, raw in value.items(): + if not re.match(r'^[a-z][a-z0-9_-]{0,95}$', str(key)): + raise ValidationError( + f'named region key {key!r} is invalid', + code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID', + ) + try: + item = NamedRegion.model_validate(raw) if isinstance(raw, dict) else raw + except ValueError as exc: + raise ValidationError( + f'named region {key!r} is invalid: {exc}', + code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID', + ) from exc + if item.region_id != key: + raise ValidationError( + f'named region key {key!r} must match nested region_id {item.region_id!r}', + code='SHIPPING.PROFILE_NAMED_REGIONS_MISMATCH', + ) + result[key] = item + return result + + +def parse_field_source_mappings(value: Any) -> list[ProfileFieldSourceMapping]: + """ + 从 definition_json.field_source_mappings(或 None)解析字段来源映射列表。 + + 核心逻辑:返回值为稳定顺序列表,不做去重(重复的 target_scope/target_field_code + 组合将由 SourceMergeService 在抽取层做 Q18 冲突裁决)。 + """ + if value is None: + return [] + if not isinstance(value, list): + raise ValidationError( + 'definition_json.field_source_mappings must be a list', + code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID', + ) + results: list[ProfileFieldSourceMapping] = [] + for raw in value: + try: + results.append(ProfileFieldSourceMapping.model_validate(raw)) + except ValueError as exc: + raise ValidationError( + f'field source mapping is invalid: {exc}', + code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID', + ) from exc + return results + + +# --------------------------------------------------------------------------- +# 变更回 Draft 门禁(Q14 冻结:区域变化必须使 Profile 回 Draft) +# --------------------------------------------------------------------------- + + +REGION_CHANGE_REQUIRES_DRAFT_KEYS = frozenset({ + 'region', 'page_scope', 'page_no', 'selection_mode', +}) + + +def profile_regions_require_draft( + *, + old_named_regions: Any, + new_named_regions: Any, +) -> bool: + """ + 判断 named_regions 变更是否触发 Profile 回 Draft + 重新验证 + 盲测 + 发布。 + + 核心逻辑(fail-safe):任何 region 主键、坐标、页作用域、选取模式的增删改一律回 Draft; + 仅 label 文案调整(便于管理员标注说明)不触发。 + """ + try: + old_map = parse_named_regions(old_named_regions) + new_map = parse_named_regions(new_named_regions) + except ValidationError: + return True # 解析失败默认回 Draft(fail-close) + if set(old_map.keys()) != set(new_map.keys()): + return True + for region_id in old_map: + old_region = old_map[region_id] + new_region = new_map[region_id] + for key in REGION_CHANGE_REQUIRES_DRAFT_KEYS: + if getattr(old_region, key) != getattr(new_region, key): + return True + return False + + +def field_source_mappings_require_draft( + *, + old_mappings: Any, + new_mappings: Any, +) -> bool: + """ + 判断 field_source_mappings 变更是否触发回 Draft。 + + 核心逻辑:除了纯 label 类改动外的任何增删改一律回 Draft(首期全量回 Draft,保留细粒度 + 门禁的未来扩展点)。 + """ + try: + old_list = parse_field_source_mappings(old_mappings) + new_list = parse_field_source_mappings(new_mappings) + except ValidationError: + return True + if len(old_list) != len(new_list): + return True + old_payload = _stable_mapping_dumps(old_list) + new_payload = _stable_mapping_dumps(new_list) + return old_payload != new_payload + + +def _stable_mapping_dumps(items: list[ProfileFieldSourceMapping]) -> str: + payload = [m.model_dump(mode='json', sort_keys=True) for m in items] + return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')) + + +# --------------------------------------------------------------------------- +# 安全正则门禁(Q15 custom_safe_regex 发布前必过) +# --------------------------------------------------------------------------- + + +_UNSAFE_PATTERN_MARKERS = ( + r'\(.+[+*]\)\s*[+*]', # 嵌套量词 例: (a+)+ + r'\(\.?\*\)\s*\*', # 多重.* 回溯 + r'\(\[.*\]\)\{[0-9]+,[0-9]*\}', # 大范围字符类重复 + r'(? None: + """ + custom_safe_regex 的发布前样本验证门禁(Q15)——编译期就拦截危险表达式。 + 【注意】:运行时还需配合 timeout_ms 的 signal 看门狗(在 regex_runner_safe 中实现)。 + """ + if len(pattern) > 1024: + raise ValueError('custom_safe_regex pattern exceeds 1024 characters') + for marker in _UNSAFE_PATTERN_MARKERS: + if re.search(marker, pattern): + raise ValueError('custom_safe_regex pattern looks potentially catastrophic') + flags = 0 if case_sensitive else re.IGNORECASE + try: + compiled = re.compile(pattern, flags) + except re.error as exc: + raise ValueError(f'custom_safe_regex pattern failed to compile: {exc}') from exc + if compiled.groups > max_groups: + raise ValueError( + f'custom_safe_regex has {compiled.groups} capture groups; limit is {max_groups}' + ) + _ = compiled # 引用仅用于静态检查 + + +# --------------------------------------------------------------------------- +# 校验和(盲测/发布基准比对) +# --------------------------------------------------------------------------- + + +def field_source_mappings_checksum(mappings: list[ProfileFieldSourceMapping]) -> str: + """稳定 SHA-256 校验和,供发布冻结与审计引用。""" + payload = _stable_mapping_dumps(mappings).encode('utf-8') + return hashlib.sha256(payload).hexdigest() + + +def named_regions_checksum(regions: dict[str, NamedRegion]) -> str: + """稳定 SHA-256 校验和,供区域变更历史比对。""" + payload = json.dumps( + {rid: r.model_dump(mode='json', sort_keys=True) for rid, r in regions.items()}, + ensure_ascii=True, sort_keys=True, separators=(',', ':'), + ).encode('utf-8') + return hashlib.sha256(payload).hexdigest() diff --git a/backend/app/services/shipping_notice/document_layout/reservation_format_policy_service.py b/backend/app/services/shipping_notice/document_layout/reservation_format_policy_service.py new file mode 100644 index 00000000..58dd3c9a --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/reservation_format_policy_service.py @@ -0,0 +1,152 @@ +""" +services/shipping_notice/document_layout/reservation_format_policy_service.py + +用途:Q15 Reservation ID 格式策略服务——Profile 级 format_policy 受控入口。 + 首期(阶段 2)保持「回退全局 validated_reservation_id(numeric_5_or_10 硬编码)」 + 不变;为未来 custom_safe_regex / 字母型 Reservation 保留扩展点。 +依赖:profile_vendor_comments_contract.ReservationFormatPolicy; + reservation_id.validated_reservation_id(全局回退)。 +逻辑:【技术重试与业务决策分离】——本类只负责**格式判断**,不改变值、不生成 Observation, + 调用方(ProfileFieldSourceMappingService._check_format)根据返回值标记 + reservation_format_invalid,但不丢弃候选(保留为 Review 证据展示)。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Literal + +from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import ( + ReservationFormatPolicy, +) + + +RESERVATION_NUMERIC_5_OR_10_RE = re.compile(r'^(?:\d{5}|\d{10})$') + + +@dataclass +class FormatPolicyResult: + """格式校验结果——只描述事实,不携带业务动作。""" + + valid: bool + mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex'] + normalized_value: str | None = None # 仅 valid=True 时返回规范化值 + reason_code: str | None = None # valid=False 时的稳定诊断码 + + @property + def should_block_auto_create(self) -> bool: + """格式失败的值不得自动建单(Q15 冻结)。""" + return not self.valid + + +class ReservationFormatPolicyService: + """ + Profile 级 Reservation 格式策略受控入口。 + + 【AI 触发时机】:ProfileFieldSourceMappingService 收集候选、或 Candidate + Qualification 最终门禁时调用 check()。禁止任何地方直接 + if re.match(r'^\d{5,10}$', v) 绕过策略层。 + """ + + def check(self, policy: ReservationFormatPolicy, raw_value: str) -> FormatPolicyResult: + """ + 执行一次格式校验。调用方不得丢弃失败候选,必须将原因码写入 + FieldSourceCandidate.format_reason_code。 + + 核心路径(Q15 冻结): + ① mode=inherit_global → 调全局 validated_reservation_id 保持历史 71 调用方口径; + ② mode=numeric_5_or_10 → 等价于全局(显式模式;便于未来全局重构时切换默认); + ③ mode=custom_safe_regex → 调用发布前已通过 Pydantic 门禁的安全正则。 + """ + value = (raw_value or '').strip() + if not value: + return FormatPolicyResult( + valid=False, mode=policy.mode, normalized_value=None, + reason_code='reservation_format_empty', + ) + mode = policy.mode + if mode in {'inherit_global', 'numeric_5_or_10'}: + return self._check_numeric_5_or_10(value, mode) + if mode == 'custom_safe_regex': + return self._check_custom_safe_regex(policy, value) + return FormatPolicyResult( + valid=False, mode=mode, normalized_value=None, + reason_code='reservation_format_unknown_mode', + ) + + # ------------------------------------------------------------------ + # 内部实现 + # ------------------------------------------------------------------ + + @staticmethod + def _check_numeric_5_or_10( + value: str, + mode: Literal['inherit_global', 'numeric_5_or_10'], + ) -> FormatPolicyResult: + """纯数字 5/10 位——默认回退全局校验,但通过独立模块输出稳定结果。""" + # 先尝试全局 validated_reservation_id(保持与 71 调用方一致),失败再用本模块常量兜底 + try: + from app.services.shipping_notice.reservation_id import validated_reservation_id + global_result = validated_reservation_id(value) + if global_result is not None: + return FormatPolicyResult( + valid=True, mode=mode, normalized_value=global_result, + reason_code=None, + ) + except Exception: # fail-safe:若全局模块异常,不阻塞结果 + pass + match = RESERVATION_NUMERIC_5_OR_10_RE.match(value) + if match: + return FormatPolicyResult( + valid=True, mode=mode, normalized_value=value, + reason_code=None, + ) + return FormatPolicyResult( + valid=False, mode=mode, normalized_value=None, + reason_code='reservation_format_invalid', + ) + + @staticmethod + def _check_custom_safe_regex(policy: ReservationFormatPolicy, value: str) -> FormatPolicyResult: + """安全正则匹配——编译缓存;捕获组第 1 组作为规范化值(否则整串)。""" + pattern = policy.pattern or '' + flags = 0 if policy.case_sensitive else re.IGNORECASE + try: + compiled = re.compile(pattern, flags) + except re.error as exc: + return FormatPolicyResult( + valid=False, mode='custom_safe_regex', normalized_value=None, + reason_code=f'reservation_format_regex_compile_error:{exc.__class__.__name__}', + ) + # 发布前样本验证门禁已限制 catastrophic 风险;这里仅以标准 library 限制长度 + if len(value) > 128: + return FormatPolicyResult( + valid=False, mode='custom_safe_regex', normalized_value=None, + reason_code='reservation_format_value_too_long', + ) + match = compiled.search(value) + if not match: + return FormatPolicyResult( + valid=False, mode='custom_safe_regex', normalized_value=None, + reason_code='reservation_format_invalid', + ) + # 规范化值:第 1 捕获组 → 整串 + normalized: str = value + if compiled.groups >= 1: + try: + first_group = match.group(1) + if first_group: + normalized = str(first_group).strip() + except (IndexError, re.error): + normalized = match.group(0) or value + normalized = normalized.strip() + if not normalized: + return FormatPolicyResult( + valid=False, mode='custom_safe_regex', normalized_value=None, + reason_code='reservation_format_capture_empty', + ) + return FormatPolicyResult( + valid=True, mode='custom_safe_regex', normalized_value=normalized, + reason_code=None, + ) diff --git a/backend/app/services/shipping_notice/document_layout/reservation_relation_projection.py b/backend/app/services/shipping_notice/document_layout/reservation_relation_projection.py new file mode 100644 index 00000000..50fc9d67 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/reservation_relation_projection.py @@ -0,0 +1,228 @@ +""" +services/shipping_notice/document_layout/reservation_relation_projection.py + +用途:Reservation 关系投影(Q2 双层设计 + Q12 invalid_line_reference 独立原因码)。 + 将拆分引擎内部捕获的 captured_relation + Profile 关系策略 relation_policy, + 映射为「绑定到哪条行、是否 annotation_only、是否 invalid_line_reference 独立」三输出。 +依赖:field_split_core.CoreCapturedRelation(来自 _CoreSegmentResult.captured_relation)、 + ProfileFieldSourceMapping.relation_policy / line_reference_basis。 +逻辑:严格遵循「路径判断与事实分离」——拆分引擎事实(line_no)只作为证据, + 最终绑定路径必须经过 line_reference_basis 三层映射校验后裁决; + 失败不抛异常,输出稳定 reason_code 供审计和前端翻译。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Literal + +from app.services.shipping_notice.document_layout.field_split_core import ( + CoreCapturedRelation, +) + + +@dataclass +class ReservationRelationProjectionResult: + """关系投影最终结果——只输出明确分支,禁止上游自行判断。""" + + line_reference_basis: Literal[ + 'explicit_line_column', + 'profile_business_line_no', + 'classified_logical_line_no', + ] + resolution: Literal[ + 'bound_to_line', # bind_target_line 成功,resolved_logical_line_no 有值 + 'annotation_only', # 显式 annotation_only,Observation 存 metadata + 'default_all_lines', # 关系缺失 + default_all_lines,每行都生成 Observation + 'default_header_only', # 关系缺失 + default_header_only,写到 header scope + 'invalid_line_reference', # 引用了不存在的行号,独立原因码 Q12 + 'conflict_unresolved', # 未来多层映射冲突保留(本期不输出) + ] + resolved_logical_line_no: int | None = None # 1-based 逻辑行号,bound_to_line 时必填 + annotation_reason: str | None = None # annotation_only 时写入 Observation metadata + invalid_reference_raw_value: str | None = None # invalid_line_reference 时返回 raw_text + invalid_reference_line_no: int | None = None + audit_chain: list[dict[str, Any]] | None = None # 路径判断全链路审计快照 + + @property + def should_generate_line_observation(self) -> bool: + return self.resolution == 'bound_to_line' or self.resolution == 'default_all_lines' + + @property + def should_generate_header_observation(self) -> bool: + return self.resolution in {'default_header_only', 'annotation_only', 'invalid_line_reference'} + + +class ReservationRelationProjection: + """ + 把 captured_relation(规则层事实) + profile relation_policy(解释层策略) + 投影为最终绑定结果。 + + 【AI 触发时机】:三来源合并前,为每个 Vendor Comments / Header Reservation 候选 + 决定「写行 Observation 还是写头 Observation 还是 invalid_line_reference」时调用。 + + 核心路径: + [STEP 1] 若 relation_policy=annotation_only → 直接走 annotation_only 分支(审计记录原因)。 + [STEP 2] 若缺失 captured_relation → 走 missing_relation_policy 分支 + (default_all_lines / default_header_only / fallback_single_line_when_no_reference)。 + [STEP 3] 若有 captured_relation.line_no,按 line_reference_basis 三层校验: + ① explicit_line_column:对比 Schema Line 字段值(显式 Line 列),失败→invalid + ② profile_business_line_no:对比 Profile 业务行号(默认客户 PO 行号) + ③ classified_logical_line_no:逻辑行号(行序分类后的结果) + 三层任何一层命中即返回 bound_to_line;全部失败输出 invalid_line_reference 独立原因码。 + """ + + def __init__( + self, + *, + relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'], + line_reference_basis: Literal[ + 'explicit_line_column', + 'profile_business_line_no', + 'classified_logical_line_no', + ] = 'profile_business_line_no', + missing_relation_policy: Literal[ + 'default_all_lines', + 'default_header_only', + 'fallback_single_line_when_no_reference', + ] = 'default_header_only', + ): + self.relation_policy = relation_policy + self.line_reference_basis = line_reference_basis + self.missing_relation_policy = missing_relation_policy + + # ------------------------------------------------------------------ + # 对外入口 + # ------------------------------------------------------------------ + + def project( + self, + *, + captured_relation: CoreCapturedRelation | None, + # 下面四个映射是 Line Reference Basis 的判定表(caller 注入,避免本类查 Schema) + explicit_line_column_values: dict[int, str] | None = None, + profile_business_line_numbers: dict[int, Any] | None = None, + classified_logical_line_numbers: dict[int, int] | None = None, + # 审计备注(annotation_only 时必须填写原因字符串,例如 'customer_commentary_only') + annotation_reason_override: str | None = None, + ) -> ReservationRelationProjectionResult: + """ + 执行关系投影。 + + 【禁止 caller 自行推导】:不要在外部用 if captured_relation.line_no in ... 判断, + 必须走 project() 返回的稳定 resolution 分支。 + """ + audit: list[dict[str, Any]] = [ + {'step': 'policy_in', 'relation_policy': self.relation_policy, + 'line_reference_basis': self.line_reference_basis, + 'missing_relation_policy': self.missing_relation_policy}, + ] + + # [STEP 1] annotation_only 直接返回(本期用于 Customer 备注说明、不参与建单) + if self.relation_policy == 'annotation_only': + audit.append({'step': 'annotation_only', + 'reason': annotation_reason_override or 'profile_relation_policy_annotation_only'}) + return ReservationRelationProjectionResult( + line_reference_basis=self.line_reference_basis, + resolution='annotation_only', + annotation_reason=annotation_reason_override or 'profile_relation_policy_annotation_only', + audit_chain=audit, + ) + + # [STEP 2] 缺失 captured_relation → 走 missing_relation_policy + if captured_relation is None or captured_relation.line_no is None: + audit.append({'step': 'missing_relation', + 'raw_text': captured_relation.raw_text if captured_relation else None}) + return self._resolve_missing_policy(audit) + + # [STEP 3] 三层 line_reference_basis 判定(显式 Line 列值 → Profile 业务行号 → 逻辑行号) + rel_line_no = int(captured_relation.line_no) + audit.append({'step': 'relation_line_no_in', 'line_no': rel_line_no, + 'raw_text': captured_relation.raw_text}) + + basis_order = self._basis_order() + for basis_name in basis_order: + resolved = self._try_basis(basis_name, rel_line_no, explicit_line_column_values or {}, + profile_business_line_numbers or {}, + classified_logical_line_numbers or {}) + if resolved is not None: + audit.append({'step': 'basis_hit', 'basis': basis_name, + 'logical_line_no': resolved}) + return ReservationRelationProjectionResult( + line_reference_basis=self.line_reference_basis, + resolution='bound_to_line', + resolved_logical_line_no=resolved, + audit_chain=audit, + ) + + # 三层全不命中 → invalid_line_reference(Q12 独立原因码 + 独立审计链) + audit.append({'step': 'invalid_line_reference', 'tried_bases': basis_order}) + return ReservationRelationProjectionResult( + line_reference_basis=self.line_reference_basis, + resolution='invalid_line_reference', + invalid_reference_raw_value=captured_relation.raw_text, + invalid_reference_line_no=rel_line_no, + audit_chain=audit, + ) + + # ------------------------------------------------------------------ + # 内部步骤 + # ------------------------------------------------------------------ + + def _basis_order(self) -> list[str]: + """按 Profile.line_reference_basis 输出优先级顺序。""" + if self.line_reference_basis == 'explicit_line_column': + return ['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no'] + if self.line_reference_basis == 'profile_business_line_no': + return ['profile_business_line_no', 'classified_logical_line_no', 'explicit_line_column'] + return ['classified_logical_line_no', 'profile_business_line_no', 'explicit_line_column'] + + def _try_basis( + self, + basis: str, + rel_line_no: int, + explicit: dict[int, str], + profile_biz: dict[int, Any], + logical: dict[int, int], + ) -> int | None: + """尝试一层判定;命中则返回逻辑行号(1-based),否则返回 None。""" + if basis == 'explicit_line_column': + for logical_idx, raw in explicit.items(): + if str(raw).strip() == str(rel_line_no): + return int(logical_idx) + return None + if basis == 'profile_business_line_no': + for logical_idx, raw in profile_biz.items(): + if str(raw).strip() == str(rel_line_no): + return int(logical_idx) + return None + if basis == 'classified_logical_line_no': + for logical_idx, mapped in logical.items(): + if int(mapped) == rel_line_no: + return int(logical_idx) + return None + return None + + def _resolve_missing_policy(self, audit: list[dict[str, Any]]) -> ReservationRelationProjectionResult: + """缺失关系时按 missing_relation_policy 落分支。""" + policy = self.missing_relation_policy + audit.append({'step': 'missing_policy', 'policy': policy}) + if policy == 'default_all_lines': + return ReservationRelationProjectionResult( + line_reference_basis=self.line_reference_basis, + resolution='default_all_lines', + audit_chain=audit, + ) + if policy == 'fallback_single_line_when_no_reference': + # Q7 开关:默认 OFF;当前 Profile 显式开启时才使用——第一期所有客户 OFF + # 若未来启用,应当返回 bound_to_line → 1;本期保持 default_header_only 语义 + return ReservationRelationProjectionResult( + line_reference_basis=self.line_reference_basis, + resolution='default_header_only', + audit_chain=audit + [{'step': 'fallback_disabled_by_q7_default'}], + ) + return ReservationRelationProjectionResult( + line_reference_basis=self.line_reference_basis, + resolution='default_header_only', + audit_chain=audit, + ) diff --git a/backend/app/services/shipping_notice/document_layout/runtime.py b/backend/app/services/shipping_notice/document_layout/runtime.py index a892f0eb..1527c76f 100644 --- a/backend/app/services/shipping_notice/document_layout/runtime.py +++ b/backend/app/services/shipping_notice/document_layout/runtime.py @@ -500,12 +500,10 @@ def _native_pdf_fallback_snapshot( layout_payload=layout_payload_preview, ) evidence_started = perf_counter() - # [FAIL-CLOSED OVERRIDE] Fallback 快照即使是 PDFium 文本回退,也必须默认 - # 保存整页 glyph。否则一旦 on-demand 恢复异常(如 asset_id 丢失或 PDFium 崩 - # 溃),matcher 会看到"MinerU 列名存在 + 空 page_glyphs"的分裂证据,输出 - # 伪精确模板分数。坐标预算由后续 compact 负责兜底,初始生成必须包含身份证据。 + # Fallback snapshots only need table-local glyphs for template modeling. Keeping + # every page glyph can exceed the persisted snapshot budget on text-heavy PDFs. evidence = _table_coordinate_evidence( - pages=native_pages, tables=tables, include_page_glyphs=True, + pages=native_pages, tables=tables, include_page_glyphs=False, diagnostics=diagnostics, ) if diagnostics is not None: diff --git a/backend/app/services/shipping_notice/document_layout/source_merge_service.py b/backend/app/services/shipping_notice/document_layout/source_merge_service.py new file mode 100644 index 00000000..ed215614 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/source_merge_service.py @@ -0,0 +1,342 @@ +""" +services/shipping_notice/document_layout/source_merge_service.py + +用途:Q18 抽取层裁决——同一 conflict_group_key(scope/field_code/line_no)下的三来源候选 + 合并为最多一条「有效业务 Observation」,禁止同一 scope+line 下多个并列有效 + Observation(防止 compute_effective_reservation_id / 库存匹配 / 履约门禁 + / Excel/RPA 误取其中一个,或冲突被后续静默覆盖)。 +依赖:profile_field_source_mapping_service.FieldSourceCandidate。 +逻辑:严格三步骤(同值合并 → 空值互补 → 值冲突),满足: + ① merge 后只出一个有效 accepted(或 needs_review=无 accepted); + ② 始终保留 source_observations[] 事实快照放入 metadata; + ③ annotation_only / invalid_line_reference 的候选永不成为 accepted, + 只保留在 conflict_payload 里作为 Review 证据。 +输出:MergedObservationCandidate(直接落库前的 Observation 形状封装), + 由 runtime 层实际 SQLAlchemy insert。 +""" + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Any, Literal + +from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import ( + FieldSourceCandidate, +) + + +SourceResolution = Literal[ + 'same_value_merged', # 多个来源值一致 + 'fill_missing', # 一个来源有值,另一来源为空 → 自动填补 + 'needs_review', # 同 scope+line 多来源值不一致 + 'no_value', # 所有来源均为空 → 本冲突组不生成有效 Observation + 'single_source_direct', # 只有一个来源有值,直接落 Observation + 'annotation_only_dropped', # 候选全是 annotation_only / invalid_line_reference +] + + +@dataclass +class SourceObservationSnapshot: + """source_observations[] 事实快照——Observation.metadata 直接序列化。""" + + source: Literal['header_region', 'table_column', 'vendor_comments'] + value: str + normalized_value: str + evidence_ref: str | None + evidence_quote: str | None + line_no_in_source: int | None + format_valid: bool | None + format_reason_code: str | None + extra: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class MergedObservationCandidate: + """ + 合并后候选——最多一份(per conflict_group_key),由 runtime 层写数据库。 + + 【后端决定 UI】:accepted_value 为 None 时,说明该字段+行=必须 Review; + frontend 不能以『第一个 source value』为事实,必须展示 source_observations[]。 + """ + + target_scope: Literal['header', 'line'] + target_field_code: str + target_field_id: str + effective_line_no: int | None + accepted_value: str | None # needs_review/no_value 时为 None + decision_status: Literal['accepted', 'needs_review', 'blocked', 'missing'] + resolution: SourceResolution + source_observations: list[SourceObservationSnapshot] = field(default_factory=list) + conflicts: list[dict[str, Any]] = field(default_factory=list) + # 用于直接映射到 Observation 数据库表列 + evidence_quote: str | None = None + evidence_ref: str | None = None + evidence_metadata: dict[str, Any] = field(default_factory=dict) + # 用于 Observation.source_type / extractor(统一三来源来源标记) + source_type: str = 'profile_field_source_mapping' + extractor: str = 'merged_source_service.v1' + + @property + def should_persist_observation(self) -> bool: + """ + 有效 Observation 生成门禁: + 必须有 accepted_value;annotation_only/invalid 全 drop 时也不输出。 + """ + return self.accepted_value is not None and self.accepted_value != '' + + +class SourceMergeService: + """ + Q18 抽取层裁决服务(先对账再重试——三来源先对账)。 + + 【AI 触发时机】:ProfileFieldSourceMappingService.collect_candidates() 返回候选后, + 下一个函数调用必须是 merge_and_decide()。禁止上游在合并前直接挑一个 source 作为 Observation。 + + 执行顺序(同 conflict_group_key 内): + [STEP 1] 过滤 annotation_only / invalid_line_reference 候选(永不 accepted)。 + [STEP 2] 归一化所有来源 value(去空格、大小写、格式化残差)。 + [STEP 3] 同值合并 same_value_merged → accepted + [STEP 4] 空值互补 fill_missing(需 mapping.fill_missing_from_other_sources=True) + [STEP 5] 以上都不通过 → conflict_needs_review,accepted_value=None + """ + + def __init__(self, candidates: list[FieldSourceCandidate]): + self.candidates = list(candidates) + # 分组:(scope, field_code, line_no) → list[candidates] + self._groups: dict[tuple[Any, ...], list[FieldSourceCandidate]] = defaultdict(list) + for cand in self.candidates: + self._groups[cand.conflict_group_key].append(cand) + + # ------------------------------------------------------------------ + # 对外主入口 + # ------------------------------------------------------------------ + + def merge_and_decide(self) -> list[MergedObservationCandidate]: + """为每个 conflict_group_key 输出 0 或 1 个 MergedObservationCandidate。""" + merged: list[MergedObservationCandidate] = [] + for _key, group in self._groups.items(): + merged.append(self._merge_one_group(group)) + return merged + + # ------------------------------------------------------------------ + # 单组合并核心 + # ------------------------------------------------------------------ + + def _merge_one_group(self, group: list[FieldSourceCandidate]) -> MergedObservationCandidate: + first = group[0] + result = MergedObservationCandidate( + target_scope=first.target_scope, + target_field_code=first.target_field_code, + target_field_id=first.target_field_id, + effective_line_no=first.effective_line_no, + accepted_value=None, + decision_status='missing', + resolution='no_value', + ) + + # [STEP 1] 分离有效候选(排除 annotation_only / invalid) + qualified: list[FieldSourceCandidate] = [] + for cand in group: + snap = self._to_snapshot(cand) + result.source_observations.append(snap) + if cand.resolution_hint == 'provisional': + qualified.append(cand) + else: + # annotation_only / invalid_line_reference 作为 review 证据保留 + result.conflicts.append({ + 'resolution_hint': cand.resolution_hint, + 'source': cand.source, + 'value': cand.normalized_value or cand.value, + 'reason': ( + cand.format_reason_code + or cand.relation_projection.resolution + if cand.relation_projection else 'annotation_only' + ), + }) + + # 无 qualified → 直接 annotation_only_dropped / no_value + if not qualified: + if group: + result.resolution = 'annotation_only_dropped' + result.decision_status = 'blocked' + else: + result.resolution = 'no_value' + result.decision_status = 'missing' + result.evidence_metadata = self._finalize_metadata(result, resolution_meta={}) + return result + + # 只有一个 qualified 且非空 → single_source_direct + non_empty = [c for c in qualified if (c.normalized_value or c.value) != ''] + if len(qualified) == 1 and non_empty: + return self._finalize_single(result, qualified[0]) + if not non_empty: + result.resolution = 'no_value' + result.decision_status = 'missing' + result.evidence_metadata = self._finalize_metadata(result, {}) + return result + if len(non_empty) == 1: + return self._finalize_fill_missing(result, group, non_empty[0], qualified) + + # [STEP 3] 同值合并 same_value_merged + values = {(c.normalized_value or c.value) for c in non_empty} + if len(values) == 1: + return self._finalize_same_value(result, group, next(iter(values))) + + # [STEP 5] 冲突 → needs_review(多来源值不一致) + result.resolution = 'needs_review' + result.decision_status = 'needs_review' + result.accepted_value = None + for c in non_empty: + result.conflicts.append({ + 'source': c.source, + 'value': (c.normalized_value or c.value), + 'evidence_ref': c.evidence_ref, + 'format_valid': c.format_valid, + }) + result.evidence_metadata = self._finalize_metadata(result, {}) + return result + + # ------------------------------------------------------------------ + # 结局封装(保证 evidence_metadata 统一包含 source_observations / resolution) + # ------------------------------------------------------------------ + + def _finalize_single( + self, result: MergedObservationCandidate, cand: FieldSourceCandidate, + ) -> MergedObservationCandidate: + result.accepted_value = cand.normalized_value or cand.value + result.resolution = 'single_source_direct' + result.decision_status = 'accepted' + result.evidence_quote = cand.evidence_quote + result.evidence_ref = cand.evidence_ref + result.evidence_metadata = self._finalize_metadata( + result, + resolution_meta={ + 'accepted_source': cand.source, + 'format_valid': cand.format_valid, + 'format_reason_code': cand.format_reason_code, + }, + primary_candidate=cand, + ) + return result + + def _finalize_fill_missing( + self, result: MergedObservationCandidate, + group: list[FieldSourceCandidate], + winner: FieldSourceCandidate, + all_qualified: list[FieldSourceCandidate], + ) -> MergedObservationCandidate: + result.accepted_value = winner.normalized_value or winner.value + result.resolution = 'fill_missing' + result.decision_status = 'accepted' + result.evidence_quote = winner.evidence_quote + result.evidence_ref = winner.evidence_ref + missing = [ + {'source': c.source, 'reason': 'empty_source'} + for c in all_qualified + if (c.normalized_value or c.value) == '' + ] + result.evidence_metadata = self._finalize_metadata( + result, + resolution_meta={ + 'accepted_source': winner.source, + 'missing_sources': missing, + 'format_valid': winner.format_valid, + 'format_reason_code': winner.format_reason_code, + }, + primary_candidate=winner, + ) + return result + + def _finalize_same_value( + self, result: MergedObservationCandidate, + group: list[FieldSourceCandidate], shared_value: str, + ) -> MergedObservationCandidate: + # 多来源同值:evidence 选 format_valid=True 中来源排序靠前的 + # (vendor_comments 优先,因为有人工圈选证据点位更清晰) + source_priority = ['vendor_comments', 'table_column', 'header_region'] + ordered = sorted( + group, + key=lambda c: ( + 0 if (c.format_valid is not False and (c.normalized_value or c.value) == shared_value) else 1, + source_priority.index(c.source) if c.source in source_priority else 99, + ), + ) + primary = ordered[0] + result.accepted_value = shared_value + result.resolution = 'same_value_merged' + result.decision_status = 'accepted' + result.evidence_quote = primary.evidence_quote + result.evidence_ref = primary.evidence_ref + merged_sources = sorted({c.source for c in ordered if (c.normalized_value or c.value) == shared_value}) + result.evidence_metadata = self._finalize_metadata( + result, + resolution_meta={ + 'merged_from_sources': list(merged_sources), + 'format_valid': primary.format_valid, + 'format_reason_code': primary.format_reason_code, + }, + primary_candidate=primary, + ) + return result + + # ------------------------------------------------------------------ + # 帮助函数 + # ------------------------------------------------------------------ + + @staticmethod + def _to_snapshot(cand: FieldSourceCandidate) -> SourceObservationSnapshot: + return SourceObservationSnapshot( + source=cand.source, + value=cand.value, + normalized_value=cand.normalized_value, + evidence_ref=cand.evidence_ref, + evidence_quote=cand.evidence_quote, + line_no_in_source=cand.effective_line_no, + format_valid=cand.format_valid, + format_reason_code=cand.format_reason_code, + extra=dict(cand.evidence_metadata or {}), + ) + + @staticmethod + def _finalize_metadata( + result: MergedObservationCandidate, + resolution_meta: dict[str, Any], + primary_candidate: FieldSourceCandidate | None = None, + ) -> dict[str, Any]: + """ + 组装 Observation.evidence_metadata_json 最终结构(Q18 冻结形状): + { + "source_observations": [...], // 事实快照(永不丢) + "resolution": "same_value_merged", + "accepted_value": "...", + "conflicts": [ ... ], // 冲突或 annotation_only 项 + "resolution_meta": { ... }, // 来源细节 + "primary": { // 选主证据说明 + "source": "vendor_comments", "evidence_ref": "...", "line_no": 2 + } + } + """ + payload: dict[str, Any] = { + 'source_observations': [ + { + 'source': s.source, 'value': s.value, + 'normalized_value': s.normalized_value, + 'evidence_ref': s.evidence_ref, 'evidence_quote': s.evidence_quote, + 'line_no_in_source': s.line_no_in_source, + 'format_valid': s.format_valid, 'format_reason_code': s.format_reason_code, + 'extra': s.extra or {}, + } for s in result.source_observations + ], + 'resolution': result.resolution, + 'accepted_value': result.accepted_value, + 'conflicts': list(result.conflicts or []), + 'resolution_meta': resolution_meta or {}, + } + if primary_candidate is not None: + payload['primary'] = { + 'source': primary_candidate.source, + 'evidence_ref': primary_candidate.evidence_ref, + 'line_no': primary_candidate.effective_line_no, + } + return payload diff --git a/backend/app/services/shipping_notice/document_layout/vc_source_candidate_conflicts.py b/backend/app/services/shipping_notice/document_layout/vc_source_candidate_conflicts.py new file mode 100644 index 00000000..787acda5 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/vc_source_candidate_conflicts.py @@ -0,0 +1,195 @@ +""" +services/shipping_notice/document_layout/vc_source_candidate_conflicts.py + +用途:从 ProfileFieldSourceMappingService + SourceMergeService 的运行结果 + 产出 Candidate 级冲突项,接入 candidate.conflicts_json。 +依赖: + - vc_source_gate_contract(冲突原因码、冲突项构造器)。 + - profile_field_source_mapping_service(三来源候选收集)。 + - source_merge_service(合并裁决 + needs_review 标记)。 + - candidate_service / ShippingOrderCandidate.structured_result_json(落库载体)。 +逻辑: + [STEP 1] 从 Candidate.structured_result_json 读三来源收集的原始快照; + 缺失(旧数据或未启用 VC Profile)时安全返回空列表,不阻断。 + [STEP 2] 扫描 merged_candidates,needs_review 且 conflict_group_key 未人工裁决 → + 构造 make_vc_candidate_conflict_item(severity=review_required)。 + [STEP 3] 扫描 format_valid=False 且 format_policy.inherit_global=False 的项 → + 独立原因码 vc_source_format_invalid,severity=blocking。 + [STEP 4] named_region_id 指向不存在区域 → vc_source_region_unbound。 + 幂等:同一 conflict_group_key 仅保留一项,合并 detail 不重复追加。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.shipping_notice.document_layout.vc_source_gate_contract import ( + CQ_REASON_VC_FORMAT_INVALID, + CQ_REASON_VC_REGION_UNBOUND, + CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED, + CQ_VC_BLOCKING_REASONS, + CQ_VC_REVIEW_REASONS, + VC_SOURCE_KIND_LABELS, + make_vc_candidate_conflict_item, +) + +# CQ_VC_BLOCKING_REASONS / CQ_VC_REVIEW_REASONS 定义在 vc_source_gate_contract.py(契约层), +# 这里保留薄 re-export,供 candidate_qualification_service 等调用方按旧路径 import, +# 避免修改大量调用点时引入遗漏。 + + +_VC_CANDIDATE_KEY = 'vendor_comments_merged' +_VC_DETAIL_MAX = 8 # 单项 detail 保留最多 8 条来源快照,防止 JSON 膨胀。 + + +def _vc_merged_payload(candidate: Any) -> dict[str, Any] | None: + """ + 从 Candidate 提取 Vendor Comments merged payload。 + + 支持三条路径,按顺序: + 1) structured_result_json.extraction.vendor_comments_merged(新抽取路径) + 2) result_json.extraction.vendor_comments_merged(兼容 Worker 旧写入点) + 3) candidate_json.extraction.vendor_comments_merged(影子评估的替身 dict) + + 任一合法 dict 即返回,否则 None(缺路径视为未启用,安全放行)。 + """ + for attr in ('structured_result_json', 'result_json', 'candidate_json'): + try: + raw = getattr(candidate, attr, None) + except Exception: + raw = None + if isinstance(raw, dict): + ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None + if ext and isinstance(ext.get(_VC_CANDIDATE_KEY), dict): + return ext[_VC_CANDIDATE_KEY] + return None + + +def _conflict_group_key(scope: str, field_code: str, line_no: str | None) -> str: + """稳定冲突键:与 source_merge_service 的 (scope, field_code, line_no) 一致。""" + safe_scope = 'header' if scope == 'header' else 'line' + safe_line = str(line_no or '').strip() or '_' + return f'{safe_scope}:{str(field_code or "").strip()}:{safe_line}' + + +def _summarize_source_observations(cand: dict[str, Any]) -> list[dict[str, Any]]: + """ + 脱敏压缩 source_observations:仅保留 source / value 摘要 / evidence_ref,禁止存完整正文。 + """ + obs = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else [] + summary: list[dict[str, Any]] = [] + for raw in obs[:_VC_DETAIL_MAX]: + if not isinstance(raw, dict): + continue + summary.append({ + 'source': raw.get('source'), + 'source_label': VC_SOURCE_KIND_LABELS.get(str(raw.get('source') or ''), str(raw.get('source') or '')), + 'value_preview': (str(raw.get('value') or '')[:64] + ('…' if len(str(raw.get('value') or '')) > 64 else '')) if raw.get('value') is not None else None, + 'evidence_ref': raw.get('evidence_ref'), + }) + return summary + + +def collect_vc_candidate_conflicts(candidate: Any) -> list[dict[str, Any]]: + """ + 扫描 Vendor Comments 三来源合并结果,生成 Candidate 冲突项。 + + 【AI 触发时机】:当 Candidate Qualification 评估、STP 自动建单前 + 或复核工作台加载冲突列表时,追加本函数返回值到 Candidate.conflicts_json。 + + Args: + candidate: ShippingOrderCandidate ORM 对象或兼容 dict(替身)。 + + Returns: + 符合 vc_source_gate_contract.make_vc_candidate_conflict_item 契约的列表; + 无冲突或未启用 VC 时返回空列表(永不返回 None)。 + """ + payload = _vc_merged_payload(candidate) + if payload is None: + return [] + + merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else [] + named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {} + enabled = payload.get('field_source_mappings') if isinstance(payload.get('field_source_mappings'), dict) else {} + + # [STEP 0] 先校验 named_region 绑定:所有启用 vendor_comments 的 mapping 其 region_id 必须存在。 + seen_region_errors: set[str] = set() + items: list[dict[str, Any]] = [] + + for field_code, mapping in enabled.items(): + if not isinstance(mapping, dict): + continue + if not bool(mapping.get('vendor_comments_enabled')): + continue + rid = str(mapping.get('vendor_comments_named_region_id') or '').strip() + if rid and rid not in named_regions: + key = f'region_missing:{rid}:{field_code}' + if key in seen_region_errors: + continue + seen_region_errors.add(key) + scope_val = str(mapping.get('vendor_comments_target_scope') or mapping.get('target_scope') or 'line').strip() + scope = 'header' if scope_val == 'header' else 'line' + ckey = _conflict_group_key(scope, field_code, None) + items.append(make_vc_candidate_conflict_item( + reason=CQ_REASON_VC_REGION_UNBOUND, + scope=scope, # type: ignore[arg-type] + field_code=field_code, + conflict_group_key=ckey, + detail={'missing_region_id': rid}, + )) + + # [STEP 1] 扫描 merged_candidates:needs_review / format_invalid。 + seen_groups: set[str] = set() + for cand in merged: + if not isinstance(cand, dict): + continue + field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip() + if not field_code: + continue + scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip() + scope_ok = 'header' if scope == 'header' else 'line' + line_no_raw = cand.get('effective_line_no') or cand.get('line_no') + line_no_safe = None if line_no_raw is None else str(line_no_raw) + ckey = _conflict_group_key(scope_ok, field_code, line_no_safe) + + resolution = str(cand.get('resolution') or '').strip() + decision = str(cand.get('decision_status') or '').strip() + format_valid = cand.get('format_valid') + # 显式 False 视为非法(None 表示未启用格式策略,安全放行)。 + format_invalid = (format_valid is False) + conflict_pending = resolution == 'needs_review' and decision != 'dropped' + + if ckey in seen_groups: + continue + detail = { + 'resolution': resolution, + 'decision_status': decision, + 'format_valid': format_valid, + 'sources': _summarize_source_observations(cand), + } + if conflict_pending: + seen_groups.add(ckey) + line_key = str(cand.get('line_key') or '').strip() or None + items.append(make_vc_candidate_conflict_item( + reason=CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED, + scope=scope_ok, # type: ignore[arg-type] + field_code=field_code, + line_key=line_key, + line_no=line_no_safe, + conflict_group_key=ckey, + detail=detail, + )) + elif format_invalid: + seen_groups.add(ckey) + line_key = str(cand.get('line_key') or '').strip() or None + items.append(make_vc_candidate_conflict_item( + reason=CQ_REASON_VC_FORMAT_INVALID, + scope=scope_ok, # type: ignore[arg-type] + field_code=field_code, + line_key=line_key, + line_no=line_no_safe, + conflict_group_key=ckey, + detail=detail, + )) + + return items diff --git a/backend/app/services/shipping_notice/document_layout/vc_source_evidence_integration.py b/backend/app/services/shipping_notice/document_layout/vc_source_evidence_integration.py new file mode 100644 index 00000000..54a6470f --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/vc_source_evidence_integration.py @@ -0,0 +1,230 @@ +""" +services/shipping_notice/document_layout/vc_source_evidence_integration.py + +用途:将 Vendor Comments 三来源 source_observations 注入 ReviewEvidenceView, + 供 Chatflow LLM Review(Phase 4)与复核工作台(Phase 5)共享同一事实源。 +依赖: + - vc_source_gate_contract(VENDOR_COMMENTS_OBSERVATION_SOURCE、build_vc_evidence_ref、is_valid_vc_evidence_ref)。 + - order_review_llm_contract ObservationSource 兼容扩展(新增 source 不在原 frozenset 时 fail-open,不抛错)。 + - Candidate.structured_result_json.extraction.vendor_comments_merged(与 vc_source_candidate_conflicts.py 同一路径)。 +逻辑: + [STEP 1] 提取 VC merged payload(与 Candidate Conflicts 共享 _vc_merged_payload 逻辑,不双份)。 + [STEP 2] 对每个 merged_candidate,展开其 source_observations[]: + - 构造 evidence_ref(优先 vc: 区域引用,缺失时退化 build_evidence_ref layout:)。 + - source 固定 VENDOR_COMMENTS_OBSERVATION_SOURCE;子 source_kind 写入 metadata.source_kind。 + - 保留 quote(原文切片)、confidence、value_bbox。 + [STEP 3] 仅追加,不覆盖/替换原有 Unit/Draft/Frozen 三源证据。 + 幂等:同一 (evidence_ref, source_kind, value) 仅插入一条,避免 LLM 重复上下文。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.shipping_notice.document_layout.vc_source_gate_contract import ( + VENDOR_COMMENTS_OBSERVATION_SOURCE, + build_vc_evidence_ref, + is_valid_vc_evidence_ref, +) +from app.services.shipping_notice.order_review_llm_contract import ( + build_evidence_ref, + is_valid_evidence_ref, +) + + +def _vc_merged_payload(case_or_candidate: Any) -> dict[str, Any] | None: + """ + 从 ReviewCase(通过 candidate.structured)或直接 Candidate 提取 VC 载荷。 + + 与 vc_source_candidate_conflicts._vc_merged_payload 逻辑一致但独立实现, + 避免引入相互 import(两模块均零 circular 原则)。 + """ + # Case 路径:先取 candidate。 + candidate = getattr(case_or_candidate, 'candidate', None) + attrs_chain: list[Any] = [] + if candidate is not None: + attrs_chain.append(candidate) + attrs_chain.append(case_or_candidate) + for item in attrs_chain: + for attr in ('structured_result_json', 'result_json', 'candidate_json'): + try: + raw = getattr(item, attr, None) + except Exception: + raw = None + if isinstance(raw, dict): + ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None + if ext and isinstance(ext.get('vendor_comments_merged'), dict): + return ext['vendor_comments_merged'] + return None + + +def _safe_str(value: Any) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None + + +def _normalize_source_obs( + raw: dict[str, Any], + *, + case_document_id: int, + field_code: str | None, + line_key: str | None, + named_regions: dict[str, Any], +) -> dict[str, Any] | None: + """ + 将一条 source_observation 归一化为 ReviewEvidenceView.field_evidences 项形状。 + + 核心:evidence_ref 优先取 vc:region;若 source_kind=vendor_comments 且命中命名区域 + 但缺 page_no,回退从 named_regions[region_id] 取代表页号。 + """ + if not isinstance(raw, dict): + return None + source_kind = _safe_str(raw.get('source')) or 'header_region' + value = raw.get('value') + quote = _safe_str(raw.get('quote') or raw.get('raw_text')) + confidence_raw = raw.get('confidence') + try: + confidence = float(confidence_raw) if confidence_raw is not None else None + except (TypeError, ValueError): + confidence = None + + doc_raw = raw.get('document_id') or case_document_id + try: + doc_id = int(doc_raw) + except (TypeError, ValueError): + doc_id = int(case_document_id or 0) + + page_raw = raw.get('page_no') + try: + page_no = int(page_raw) if page_raw is not None else None + except (TypeError, ValueError): + page_no = None + + # Vendor Comments:若缺 page_no,按 named_regions[region_id].page_scope 推导代表页。 + rid = _safe_str(raw.get('region_id') or raw.get('named_region_id')) + if source_kind == 'vendor_comments' and page_no is None and rid and isinstance(named_regions.get(rid), dict): + region_def = named_regions[rid] + page_scope = _safe_str(region_def.get('page_scope')) or 'first_page' + exact = region_def.get('exact_page_no') or region_def.get('page_no') + if page_scope == 'last_page': + # last_page 未知实际页码时安全置 1,待后续有实际渲染页号再覆盖。 + page_no = page_no or 1 + elif page_scope == 'exact_page' and exact is not None: + try: + page_no = int(exact) + except (TypeError, ValueError): + page_no = page_no or 1 + else: + page_no = page_no or 1 + + evidence_ref: str | None = None + pre_ref = raw.get('evidence_ref') + if isinstance(pre_ref, str) and (is_valid_vc_evidence_ref(pre_ref) or is_valid_evidence_ref(pre_ref)): + evidence_ref = pre_ref.strip() + if not evidence_ref and source_kind == 'vendor_comments' and doc_id > 0 and page_no and rid: + evidence_ref = build_vc_evidence_ref(document_id=doc_id, page_no=page_no, region_id=rid) + if not evidence_ref and doc_id > 0 and page_no: + table_id = raw.get('table_id') if isinstance(raw.get('table_id'), str) else None + row_index = None + try: + ri = raw.get('row_index') + row_index = int(ri) if ri is not None else None + except (TypeError, ValueError): + row_index = None + evidence_ref = build_evidence_ref( + document_id=doc_id, + page_no=page_no, + table_id=table_id, + row_index=row_index, + field_code=field_code, + ) + + bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None + bbox_valid = ( + isinstance(bbox, dict) + and all(k in bbox for k in ('x0', 'y0', 'x1', 'y1')) + and 0.0 <= float(bbox['x0']) < float(bbox['x1']) <= 1.01 + and 0.0 <= float(bbox['y0']) < float(bbox['y1']) <= 1.01 + ) if bbox else False + + doc_match = bool(doc_id) and int(case_document_id or 0) > 0 and int(doc_id) == int(case_document_id) + value_bbox_dict = dict(bbox) if bbox_valid else None + + return { + 'value': value, + 'quote': quote, + 'source': VENDOR_COMMENTS_OBSERVATION_SOURCE, + 'source_kind': source_kind, + 'confidence': confidence, + 'evidence_ref': evidence_ref, + 'provenance_ref': None, # VC 来源直接走 evidence_ref,不伪装 draft provenance。 + 'document_id': doc_id, + 'page_no': page_no, + 'table_id': raw.get('table_id') if isinstance(raw.get('table_id'), str) else None, + 'cell_id': raw.get('cell_id') if isinstance(raw.get('cell_id'), str) else None, + 'row_index': None, # 行级由 line_key 外部关联,row_index 仅 layout table 使用。 + 'value_bbox': value_bbox_dict, + 'value_bbox_valid': bbox_valid, + 'document_matches_case': doc_match, + 'field_code': field_code, + 'line_key': line_key, + } + + +def collect_vc_field_evidences( + *, + case_or_candidate: Any, + case_document_id: int, +) -> list[dict[str, Any]]: + """ + 展开 Vendor Comments 三来源 source_observations 为 ReviewEvidenceView.field_evidences 条目。 + + 【AI 触发时机】: + - Phase 4:构建 LLM 最小证据上下文时,追加三来源引用与 quote; + - Phase 5:复核工作台加载 evidence 对照面板。 + + Args: + case_or_candidate: ShippingOrderReviewCase 或 ShippingOrderCandidate。 + case_document_id: 当前 Case 的主文档 document_id,用于 document_matches_case。 + + Returns: + 归一化 observation 列表;未启用 VC 或路径缺数据返回空列表。 + """ + payload = _vc_merged_payload(case_or_candidate) + if payload is None: + return [] + named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {} + merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else [] + + results: list[dict[str, Any]] = [] + seen: set[tuple[str, str, str]] = set() + for cand in merged: + if not isinstance(cand, dict): + continue + field_code = _safe_str(cand.get('target_field_code') or cand.get('field_code')) + line_key = _safe_str(cand.get('line_key')) + source_list = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else [] + for raw in source_list: + if not isinstance(raw, dict): + continue + norm = _normalize_source_obs( + raw, + case_document_id=int(case_document_id or 0), + field_code=field_code, + line_key=line_key, + named_regions=named_regions, + ) + if norm is None: + continue + key = ( + str(norm.get('evidence_ref') or ''), + str(norm.get('source_kind') or ''), + str(norm.get('value') or '')[:64], + ) + if key in seen: + continue + seen.add(key) + results.append(norm) + return results diff --git a/backend/app/services/shipping_notice/document_layout/vc_source_gate_contract.py b/backend/app/services/shipping_notice/document_layout/vc_source_gate_contract.py new file mode 100644 index 00000000..c2d01f77 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/vc_source_gate_contract.py @@ -0,0 +1,204 @@ +""" +services/shipping_notice/document_layout/vc_source_gate_contract.py + +用途:冻结 Vendor Comments 三来源的门禁枚举、证据引用格式、冲突原因码。 +依赖:零 I/O 纯契约模块,禁止 import 业务服务,避免 circular。 +逻辑: + - ObservationSource 新增 vendor_comments_region(与 order_review_llm_contract.py 对齐)。 + - evidence_ref 格式 vc:document_id:pN:region: 独立校验,禁止混入 layout: 前缀。 + - CQ 门禁新增 vc_source_merged_clean;原因码分「业务冲突」「格式不合法」「区域未绑定」三类。 + - 所有常量写入 frozenset/tuple,供 gate/preview/audit 三处共享,禁止双份维护。 +""" + +from __future__ import annotations + +import re +from typing import Any, Final, Literal + +# --------------------------------------------------------------------------- +# 三来源字段来源种类(与前端 vc.types.ts Section E VCFieldSourceKind 一一对应) +# --------------------------------------------------------------------------- +VC_SOURCE_KINDS: Final[frozenset[str]] = frozenset({ + 'header_region', + 'table_column', + 'vendor_comments', +}) +VC_SOURCE_KIND_LABELS: Final[dict[str, str]] = { + 'header_region': 'Header 区域', + 'table_column': '表身列', + 'vendor_comments': 'Vendor Comments', +} +VC_SOURCE_EVIDENCE_PRIORITY: Final[dict[str, int]] = { + # 优先级越大越优先;与 source_merge_service.py 证据选择顺序对齐。 + 'vendor_comments': 3, + 'table_column': 2, + 'header_region': 1, +} + +# --------------------------------------------------------------------------- +# 扩展 ObservationSource(与 order_review_llm_contract 原 4 类互不污染) +# --------------------------------------------------------------------------- +VENDOR_COMMENTS_OBSERVATION_SOURCE: Final[str] = 'vendor_comments_region' +ALL_OBSERVATION_SOURCES_WITH_VC: Final[frozenset[str]] = frozenset({ + 'unit_observation', + 'draft_observation', + 'frozen_layout', + 'text_fallback', + VENDOR_COMMENTS_OBSERVATION_SOURCE, +}) + +# --------------------------------------------------------------------------- +# VC 专用 evidence_ref:vc::p:region: +# 缺任意段即视为无效,不伪造占位。 +# --------------------------------------------------------------------------- +_VC_EVIDENCE_REF_RE = re.compile( + r'^vc:(?P\d+):p(?P\d+):region:(?P[A-Za-z0-9_\-]{1,128})$' +) + + +def is_valid_vc_evidence_ref(value: Any) -> bool: + """ + 校验 Vendor Comments evidence_ref 是否满足三段式契约。 + + 【AI 触发时机】:当需要将 VC 来源写入 Observation evidence_ref、 + 或 LLM 解析 quote 需要定位到命名区域时调用。 + + Args: + value: 待校验字符串。 + + Returns: + True 当且仅当正则命中且段值为正整数。 + """ + if not isinstance(value, str) or not value: + return False + matched = _VC_EVIDENCE_REF_RE.match(value.strip()) + if not matched: + return False + try: + doc = int(matched.group('doc')) + page = int(matched.group('page')) + except (TypeError, ValueError): + return False + return doc > 0 and page > 0 and bool(matched.group('region')) + + +def build_vc_evidence_ref( + *, + document_id: int | None, + page_no: int | None, + region_id: str | None, +) -> str | None: + """ + 按契约生成 VC evidence_ref;缺任意必需段返回 None,绝不伪造。 + + Args: + document_id: PDF 主键,>0。 + page_no: 代表页号,>0。 + region_id: NamedRegion.region_id,非空。 + + Returns: + 合法 vc: 引用或 None。 + """ + if not document_id or not page_no or not region_id: + return None + try: + doc_i = int(document_id) + page_i = int(page_no) + rid = str(region_id).strip() + except (TypeError, ValueError): + return None + if doc_i <= 0 or page_i <= 0 or not rid: + return None + ref = f'vc:{doc_i}:p{page_i}:region:{rid}' + return ref if is_valid_vc_evidence_ref(ref) else None + + +# --------------------------------------------------------------------------- +# Candidate Qualification 门禁:vc_source_merged_clean +# --------------------------------------------------------------------------- +CQ_GATE_VC_SOURCE_MERGED_CLEAN: Final[str] = 'vc_source_merged_clean' +CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED: Final[str] = 'vc_source_conflict_unresolved' +CQ_REASON_VC_FORMAT_INVALID: Final[str] = 'vc_source_format_invalid' +CQ_REASON_VC_REGION_UNBOUND: Final[str] = 'vc_source_region_unbound' +CQ_VC_BLOCKING_REASONS: Final[frozenset[str]] = frozenset({ + CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED, + CQ_REASON_VC_FORMAT_INVALID, + CQ_REASON_VC_REGION_UNBOUND, +}) +# 归入 review_required(轻量人工确认)而非 hard-blocked 的原因。 +CQ_VC_REVIEW_REASONS: Final[frozenset[str]] = frozenset({ + CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED, +}) + +# --------------------------------------------------------------------------- +# 合并决议(与 SourceMergeService.resolution 对齐,前端只读不改) +# --------------------------------------------------------------------------- +VC_MERGE_RESOLUTIONS: Final[frozenset[str]] = frozenset({ + 'single_source_direct', + 'same_value_merged', + 'fill_missing', + 'needs_review', + 'annotation_only_dropped', + 'invalid_line_reference_dropped', +}) +VC_DECISION_STATUSES: Final[frozenset[str]] = frozenset({ + 'accepted', + 'pending', + 'dropped', +}) + +# --------------------------------------------------------------------------- +# 证据元数据键(与 Q18 metadata.shape 严格一致) +# --------------------------------------------------------------------------- +VC_EVIDENCE_META_KEYS: Final[frozenset[str]] = frozenset({ + 'source_observations', + 'resolution', + 'accepted_value', + 'conflicts', + 'resolution_meta', + 'primary', +}) + +# --------------------------------------------------------------------------- +# VC Candidate Qualification 冲突项 shape(用于 candidate.conflicts_json 列表项) +# --------------------------------------------------------------------------- +def make_vc_candidate_conflict_item( + *, + reason: str, + scope: Literal['header', 'line'], + field_code: str, + line_key: str | None = None, + line_no: str | None = None, + conflict_group_key: str, + detail: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 构造符合 CQ 契约的 Vendor Comments 冲突项。 + + 核心逻辑:reason 必须来自 CQ_VC_BLOCKING_REASONS; + conflict_group_key 用于幂等去重(同组多次评估只记一条)。 + + Args: + reason: 原因码,限 CQ_VC_BLOCKING_REASONS。 + scope: header / line。 + field_code: 订单字段,如 reservation_id。 + line_key: line scope 时的逻辑行键,header 为 None。 + line_no: 原始明细号字符串,便于审计。 + conflict_group_key: (scope, field_code, line_no) 稳定键。 + detail: 三来源 values / source_observations 快照,不含正文大对象。 + + Returns: + candidate.conflicts_json 列表中的一项字典。 + """ + safe_reason = reason if reason in CQ_VC_BLOCKING_REASONS else CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED + return { + 'kind': 'vc_source', + 'reason': safe_reason, + 'severity': 'review_required' if safe_reason in CQ_VC_REVIEW_REASONS else 'blocking', + 'scope': scope, + 'field_code': field_code, + 'line_key': line_key, + 'line_no': line_no, + 'conflict_group_key': conflict_group_key, + 'detail': dict(detail or {}), + } diff --git a/backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py b/backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py index b5af7a7a..2617517c 100644 --- a/backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py +++ b/backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py @@ -816,8 +816,7 @@ def extract_xfa_profile( reason_codes: list[str] = [] if has_unconfirmed_split_rules: reason_codes.append('xfa_split_rule_unconfirmed') - if required_missing: - reason_codes.append('xfa_required_field_missing') + source_mapping_incomplete = bool(required_missing) evidence_summary = sanitize_xfa_dto({ 'header_field_count': len(header_fields), @@ -827,6 +826,7 @@ def extract_xfa_profile( 'parser_identity': XFA_PARSER_IDENTITY, 'profile_checksum': str(raw_profile.get('checksum') or '') or None, 'header_split_evidence': header_split_evidence, + 'xfa_source_mapping_incomplete': source_mapping_incomplete, 'field_evidence_refs': [ item.evidence for item in header_fields ] + [ diff --git a/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py index 2c34be00..2058b953 100644 --- a/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py +++ b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py @@ -3,13 +3,18 @@ services/shipping_notice/document_layout/xfa_split_rule_contract.py 用途:冻结 XFA 字段拆分规则契约——matcher 优先级模型、segment 映射、 evidence_only 边界、正则资源上限与 Schema 校验入口。 -依赖:Pydantic 2、xfa_contract、xfa_safe_regex、Flask settings(可选)。 +依赖:Pydantic 2、xfa_contract、xfa_safe_regex、Flask settings(可选); + 共享契约来自 field_split_core(BaseSplitNormalization / BaseSplitMatcher / + BaseSplitSegment / BaseSplitRule / BaseSplitRuleSet)。 逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError - 或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched。 + 或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched; + XfaSplit* 系列继承共享核心 BaseSplit*,但保留 XFA 专属字段(source_path_id / + source_data_path 等)和 XFA 前缀的环境变量读取,保持对外行为零漂移。 """ from __future__ import annotations +import json import os import re import uuid @@ -17,6 +22,13 @@ from typing import Any, Final, Literal from pydantic import AliasChoices, Field, field_validator, model_validator +from app.services.shipping_notice.document_layout.field_split_core import ( + BaseSplitMatcher, + BaseSplitNormalization, + BaseSplitRule, + BaseSplitRuleSet, + BaseSplitSegment, +) from app.services.shipping_notice.document_layout.xfa_contract import ( XfaContractModel, validate_controlled_data_path, @@ -28,6 +40,7 @@ from app.services.shipping_notice.document_layout.xfa_safe_regex import ( # --------------------------------------------------------------------------- # 资源上限默认值(可被 settings / 环境变量覆盖) +# 注意:为保持 XFA 链路零行为变化,环境变量前缀仍使用 XFA_SPLIT_*(与共享核心 SPLIT_* 分治) # --------------------------------------------------------------------------- XFA_SPLIT_MAX_RULES_PER_SET: Final[int] = 32 @@ -120,8 +133,11 @@ def get_xfa_split_regex_timeout_ms() -> int: return _config_int('XFA_SPLIT_REGEX_TIMEOUT_MS', XFA_SPLIT_REGEX_TIMEOUT_MS) -class XfaSplitSegment(XfaContractModel): - """自定义拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。""" +class XfaSplitSegment(BaseSplitSegment): + """ + 自定义拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。 + 继承共享核心 BaseSplitSegment;保留 XFA 自己的校验器以保证 XFA_ 前缀环境变量仍生效。 + """ segment_id: str = Field(min_length=8, max_length=64) segment_code: str = Field(min_length=2, max_length=XFA_SPLIT_MAX_SEGMENT_CODE_LENGTH) @@ -154,11 +170,12 @@ class XfaSplitSegment(XfaContractModel): return self -class XfaSplitMatcher(XfaContractModel): +class XfaSplitMatcher(BaseSplitMatcher): """ 单行匹配器:position / prefix / regex。 优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。 + 继承共享核心 BaseSplitMatcher;保留 XFA 自己的校验器与 XFA_ 前缀长度常量。 """ type: XfaSplitMatcherType @@ -211,7 +228,7 @@ class XfaSplitMatcher(XfaContractModel): return self -class XfaSplitRule(XfaContractModel): +class XfaSplitRule(BaseSplitRule): """单条拆分规则:rule_id + matcher + segment(无 stages[])。""" rule_id: str = Field(min_length=1, max_length=64) @@ -219,7 +236,7 @@ class XfaSplitRule(XfaContractModel): segment: XfaSplitSegment -class XfaSplitNormalization(XfaContractModel): +class XfaSplitNormalization(BaseSplitNormalization): """规则集级换行与 trim 策略:引擎按 line_breaks 拆行后再逐行匹配。""" trim: bool = True @@ -236,12 +253,16 @@ class XfaSplitNormalization(XfaContractModel): return self -class XfaSplitRuleSet(XfaContractModel): +class XfaSplitRuleSet(BaseSplitRuleSet): """ 针对单一源字段的拆分规则集,存于 Profile definition_json.split_rules。 规则由管理员手工配置(source=user/imported)。若出现历史 source=system_suggestion, 必须保持 draft + requires_confirmation,且不得进入正式提取/发布。 + + 继承共享核心 BaseSplitRuleSet;追加 XFA 专属字段:source_path_id / source_scope / + source_field_code / source_data_path。校验器保留 XFA 自己的实现,确保 XFA_SPLIT_* + 前缀环境变量、path_id 白名单校验仍然生效,不会被共享核心的默认值覆盖。 """ rule_set_id: str = Field( @@ -278,7 +299,7 @@ class XfaSplitRuleSet(XfaContractModel): @model_validator(mode='after') def validate_rule_set_invariants(self) -> 'XfaSplitRuleSet': - """规则集内唯一性与数量上限。""" + """规则集内唯一性与数量上限(XFA 专用,读取 XFA_SPLIT_* 环境变量前缀)。""" max_rules = get_xfa_split_max_rules_per_set() if len(self.rules) > max_rules: raise ValueError(f'rules exceed max {max_rules}') @@ -330,14 +351,16 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) - 核心逻辑:只冻结 matcher 与 normalization;segment 的 Schema 映射字段不属于拆分逻辑, 后续绑定或解绑目标字段不得取消已确认状态。 + 【重要】:XFA 版指纹实现独立保留,不直接调用共享核心 base_split_content_fingerprint。 + 原因:未来若共享核心为 Vendor Comments 增加 relation_capture 字段纳入指纹计算, + 此处必须保持 XFA 既有指纹与历史 Profile 校验和完全一致,避免发布确认状态误判。 + Args: rule_set: 模型或 dict。 Returns: 稳定 JSON 字符串指纹素材(调用方可再 hash)。 """ - import json - if isinstance(rule_set, XfaSplitRuleSet): payload = rule_set.model_dump(mode='json', by_alias=True) else: diff --git a/backend/app/services/shipping_notice/document_layout/xfa_split_rule_engine.py b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_engine.py index 0e3c2783..3d395d3c 100644 --- a/backend/app/services/shipping_notice/document_layout/xfa_split_rule_engine.py +++ b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_engine.py @@ -2,39 +2,43 @@ services/shipping_notice/document_layout/xfa_split_rule_engine.py 用途:按冻结优先级执行 XFA 字段拆分——prefix > regex > position > unmatched。 -依赖:xfa_split_rule_contract、xfa_safe_regex、concurrent.futures。 +依赖:xfa_split_rule_contract(XfaSplitRuleSet extends BaseSplitRuleSet)、 + field_split_core(execute_base_split_rule_set 共享核心执行)、 + xfa_dataset(XfaLeafValue、mask_value_for_dto)。 逻辑:由预览 API 与正式提取调用;无网络、无脚本、无 LLM; + 【阶段 1 架构】:对外 dataclass / 函数签名 100% 保持不变, + 内部逻辑委托共享核心 field_split_core.execute_base_split_rule_set(), + 转换 _CoreSegmentResult → XfaSplitSegmentResult 时显式丢弃 captured_relation + (Q16 方案 A:阶段 1 XFA 对外结果零字段变化); 逐行收集命中规则后按优先级决出唯一 segment;同优先级多个 mapped 命中 → needs_review; 全部候选命中写入 diagnostics;evidence_only 不写 Schema。 """ from __future__ import annotations -import re from dataclasses import dataclass, field from typing import Any +from app.services.shipping_notice.document_layout.field_split_core import ( + CoreSplitDiagnostic, + _CoreSegmentResult, + _CoreSplitEngineResult, + execute_base_split_rule_set, +) from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue -from app.services.shipping_notice.document_layout.xfa_safe_regex import ( - SafeRegexError, - compile_safe_regex, - search_safe, -) from app.services.shipping_notice.document_layout.xfa_split_rule_contract import ( - XFA_SPLIT_MATCHER_PRIORITY, - XfaSplitMatcher, - XfaSplitRule, XfaSplitRuleSet, - get_xfa_split_max_input_length, - get_xfa_split_max_regex_groups, - get_xfa_split_max_regex_pattern_length, - get_xfa_split_regex_timeout_ms, ) +# --------------------------------------------------------------------------- +# 对外 dataclass——阶段 1 零字段变化(captured_relation 不出现在 XFA 对外结果) +# --------------------------------------------------------------------------- + + @dataclass class XfaSplitSegmentResult: - """单段执行结果(含起止行号与证据文本)。""" + """单段执行结果(含起止行号与证据文本)。阶段 1 不含 captured_relation(Q16 方案 A)。""" segment_id: str segment_code: str @@ -75,223 +79,69 @@ class XfaSplitEngineResult: rule_version: int | None = None -@dataclass -class _LineMatch: - """单行候选命中。""" - - rule: XfaSplitRule - matcher_type: str - priority: int - line_text: str - normalized_text: str - raw_line: str +# --------------------------------------------------------------------------- +# 适配层:共享核心 → XFA 对外结果(丢弃 captured_relation) +# --------------------------------------------------------------------------- -def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]: +def _core_segment_to_xfa(core: _CoreSegmentResult) -> XfaSplitSegmentResult: """ - 按声明的 line_breaks 切分文本(长分隔符优先)。 - - Args: - text: 原始文本。 - line_breaks: 换行符列表。 - - Returns: - 切分后的行列表(尚未 trim / 去空行)。 + 将共享核心单段结果转换为 XFA 对外结果。 + 【关键约束(Q16 方案 A)】:显式不传入 captured_relation,阶段 1 XFA 对外结果零字段变化。 """ - if not text: - return [] - pattern = '|'.join(re.escape(item) for item in sorted(line_breaks, key=len, reverse=True)) - if not pattern: - return [text] - return re.split(pattern, text) - - -def _apply_line_normalization( - lines: list[str], - *, - trim: bool, - remove_empty_lines: bool, -) -> list[str]: - """对行列表应用 trim / 去空行。""" - out = list(lines) - if trim: - out = [item.strip() for item in out] - if remove_empty_lines: - out = [item for item in out if item] - return out - - -def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]: - """ - 用规则集级 normalization 生成行清单。 - - 核心逻辑:按 normalization.line_breaks 拆行并应用 trim / 去空行。 - """ - norm = rule_set.normalization - lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks)) - return _apply_line_normalization( - lines, - trim=bool(norm.trim), - remove_empty_lines=bool(norm.remove_empty_lines), + return XfaSplitSegmentResult( + segment_id=core.segment_id, + segment_code=core.segment_code, + display_name=core.display_name, + line_no=core.line_no, + line_end_no=core.line_end_no, + raw_text=core.raw_text, + normalized_text=core.normalized_text, + handling=core.handling, + target_field_id=core.target_field_id, + target_field_code=core.target_field_code, + rule_id=core.rule_id, + status=core.status, + matcher_type=core.matcher_type, ) -def _extract_prefix_value(line: str, matcher: XfaSplitMatcher) -> str | None: +def _core_diagnostic_to_xfa(core: CoreSplitDiagnostic) -> XfaSplitDiagnostic: + """将共享核心诊断转换为 XFA 对外诊断。""" + return XfaSplitDiagnostic( + code=core.code, + message=core.message, + line_no=core.line_no, + field_code=core.field_code, + rule_ids=list(core.rule_ids), + ) + + +def _core_result_to_xfa(core: _CoreSplitEngineResult) -> XfaSplitEngineResult: """ - 前缀匹配:标签 + 分隔符后的值。 - - Returns: - 提取值;无法匹配时 None。 + 将共享核心完整引擎结果转换为 XFA 对外结果。 + 关键转换点: + 1. rule_set_id → rule_id(XFA 对外使用 rule_id 键名,兼容历史调用); + 2. 所有 segments / evidence_only_segments 丢弃 captured_relation; + 3. mapped_fields 原样透传(key 结构完全一致)。 """ - label = str(matcher.value or '') - hay = line if matcher.case_sensitive else line.casefold() - needle = label if matcher.case_sensitive else label.casefold() - if not hay.startswith(needle): - return None - rest = line[len(label):] - for sep in matcher.separators: - if rest.startswith(sep): - return rest[len(sep):].strip() - stripped = rest.lstrip() - if stripped.startswith(sep): - return stripped[len(sep):].strip() - return None + xfa_segments = [_core_segment_to_xfa(s) for s in core.segments] + xfa_evidence_only = [_core_segment_to_xfa(s) for s in core.evidence_only_segments] + xfa_diagnostics = [_core_diagnostic_to_xfa(d) for d in core.diagnostics] + return XfaSplitEngineResult( + status=core.status, + segments=xfa_segments, + mapped_fields=dict(core.mapped_fields), + evidence_only_segments=xfa_evidence_only, + diagnostics=xfa_diagnostics, + rule_id=core.rule_set_id, + rule_version=core.rule_version, + ) -def _regex_extract_value(line: str, matcher: XfaSplitMatcher) -> tuple[str | None, str | None]: - """ - 正则捕获单行文本。 - - Returns: - (value, error_code);成功时 error_code 为 None。 - """ - pattern = str(matcher.pattern or '') - timeout_ms = get_xfa_split_regex_timeout_ms() - max_len = get_xfa_split_max_regex_pattern_length() - max_groups = get_xfa_split_max_regex_groups() - try: - compiled = compile_safe_regex( - pattern, - case_sensitive=bool(matcher.case_sensitive), - max_length=max_len, - max_groups=max_groups, - ) - matched = search_safe(compiled, line, timeout_ms=timeout_ms) - except SafeRegexError: - return None, 'regex_failed' - except TimeoutError: - return None, 'regex_timeout' - if not matched: - return None, 'regex_not_matched' - group = matcher.capture_group - try: - if group is None: - if matched.lastindex: - return str(matched.group(1) or '').strip(), None - return str(matched.group(0) or '').strip(), None - return str(matched.group(group) or '').strip(), None - except IndexError: - return None, 'regex_failed' - - -def _match_line(line_no: int, line: str, rule: XfaSplitRule) -> tuple[_LineMatch | None, str | None]: - """ - 判断单条规则是否命中指定行。 - - Returns: - (match, error_code):命中时 error_code 为 None;未命中时 match 为 None。 - """ - matcher = rule.matcher - priority = XFA_SPLIT_MATCHER_PRIORITY.get(matcher.type) - if priority is None: - return None, 'unknown_matcher' - - if matcher.type == 'position': - if int(matcher.line_index or 0) != line_no: - return None, None - normalized = line.strip() if line else '' - return _LineMatch( - rule=rule, - matcher_type='position', - priority=priority, - line_text=line, - normalized_text=normalized, - raw_line=line, - ), None - - if matcher.type == 'prefix': - extracted = _extract_prefix_value(line, matcher) - if extracted is None: - return None, None - return _LineMatch( - rule=rule, - matcher_type='prefix', - priority=priority, - line_text=line, - normalized_text=extracted, - raw_line=line, - ), None - - if matcher.type == 'regex': - value, err = _regex_extract_value(line, matcher) - if err: - return None, err - if value is None: - return None, None - return _LineMatch( - rule=rule, - matcher_type='regex', - priority=priority, - line_text=line, - normalized_text=value, - raw_line=line, - ), None - - return None, 'unknown_matcher' - - -def _pick_line_winner( - line_no: int, - matches: list[_LineMatch], - diagnostics: list[XfaSplitDiagnostic], -) -> _LineMatch | None: - """ - 按 prefix > regex > position 决出单行唯一胜出规则。 - - 核心逻辑:同优先级多个 mapped 命中 → duplicate_line_match;不同优先级取最高优先级。 - """ - if not matches: - return None - - diagnostics.append(XfaSplitDiagnostic( - code='line_match_candidates', - message='All matcher hits for line recorded', - line_no=line_no, - rule_ids=[item.rule.rule_id for item in matches], - )) - - best_priority = min(item.priority for item in matches) - tier = [item for item in matches if item.priority == best_priority] - mapped_tier = [item for item in tier if item.rule.segment.handling == 'mapped'] - - if len(mapped_tier) >= 2: - diagnostics.append(XfaSplitDiagnostic( - code='duplicate_line_match', - message='Multiple mapped rules matched the same line at the same priority', - line_no=line_no, - rule_ids=[item.rule.rule_id for item in mapped_tier], - )) - - if len(tier) == 1: - return tier[0] - - if len(mapped_tier) == 1: - return mapped_tier[0] - - if len(mapped_tier) >= 2: - return sorted(mapped_tier, key=lambda item: item.rule.rule_id)[0] - - return sorted(tier, key=lambda item: item.rule.rule_id)[0] +# --------------------------------------------------------------------------- +# 对外执行入口——签名 100% 不变 +# --------------------------------------------------------------------------- def execute_split_rule_set( @@ -303,7 +153,11 @@ def execute_split_rule_set( """ 对单个源字段原值执行拆分规则集。 - 核心逻辑: + 【阶段 1 委托模式】:不重复实现逐行匹配逻辑,直接调用共享核心 + execute_base_split_rule_set() 执行纯文本拆分,再通过适配层转换回 XFA + 对外结果形状。XfaSplitRuleSet extends BaseSplitRuleSet,因此可直接透传。 + + 核心逻辑(由共享核心保证字节级一致): 1. normalization.line_breaks 拆行; 2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment; 3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review; @@ -312,149 +166,18 @@ def execute_split_rule_set( Args: raw_value: 保留换行的原始叶子值。 - rule_set: 已校验规则集。 + rule_set: 已校验规则集(XfaSplitRuleSet extends BaseSplitRuleSet)。 lines: 可选预切分行(覆盖 normalization 结果)。 Returns: - XfaSplitEngineResult。 + XfaSplitEngineResult——字段零变化,captured_relation 已丢弃。 """ - if len(raw_value or '') > get_xfa_split_max_input_length(): - return XfaSplitEngineResult( - status='needs_review', - diagnostics=[XfaSplitDiagnostic( - code='input_too_long', - message='Split source value exceeds max input length', - )], - rule_id=rule_set.rule_set_id, - rule_version=rule_set.rule_version, - ) - - inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set) - diagnostics: list[XfaSplitDiagnostic] = [] - segments: list[XfaSplitSegmentResult] = [] - claimed_lines: set[int] = set() - - # [STEP 1] 逐行匹配并按优先级决出胜出规则。 - for line_no, line in enumerate(inventory, start=1): - matches: list[_LineMatch] = [] - for rule in rule_set.rules: - outcome, error = _match_line(line_no, line, rule) - if error: - diagnostics.append(XfaSplitDiagnostic( - code=error, - message=f'Rule {rule.rule_id} regex failed on line {line_no}', - line_no=line_no, - field_code=rule.segment.target_field_code, - rule_ids=[rule.rule_id], - )) - continue - if outcome is not None: - matches.append(outcome) - - winner = _pick_line_winner(line_no, matches, diagnostics) - if winner is None: - continue - - claimed_lines.add(line_no) - seg = winner.rule.segment - status = 'parsed' - if not str(winner.normalized_text).strip() and seg.handling == 'mapped': - status = 'needs_review' - diagnostics.append(XfaSplitDiagnostic( - code='mapped_value_empty', - message=f'Mapped segment {seg.segment_code} extracted empty value', - line_no=line_no, - field_code=seg.target_field_code, - rule_ids=[winner.rule.rule_id], - )) - segments.append(XfaSplitSegmentResult( - segment_id=seg.segment_id, - segment_code=seg.segment_code, - display_name=seg.display_name, - line_no=line_no, - line_end_no=line_no, - raw_text=winner.raw_line, - normalized_text=winner.normalized_text, - handling=seg.handling, - target_field_id=seg.target_field_id, - target_field_code=seg.target_field_code, - rule_id=winner.rule.rule_id, - status=status, - matcher_type=winner.matcher_type, - )) - - # [STEP 2] 未匹配行。 - for line_index, line in enumerate(inventory, start=1): - if line_index in claimed_lines: - continue - status = 'needs_review' if rule_set.unmatched_line_policy == 'needs_review' else 'parsed' - if status == 'needs_review': - diagnostics.append(XfaSplitDiagnostic( - code='unmatched_line', - message='Unmatched line requires review', - line_no=line_index, - )) - segments.append(XfaSplitSegmentResult( - segment_id=f'unmatched-{line_index}', - segment_code=f'unmatched_line_{line_index}', - display_name=f'其他编码/{line_index}', - line_no=line_index, - line_end_no=line_index, - raw_text=line, - normalized_text=line.strip(), - handling='evidence_only', - target_field_id=None, - target_field_code=None, - rule_id='unmatched', - status=status, - matcher_type='unmatched', - )) - - # [STEP 3] 聚合正式字段。 - mapped_fields: dict[str, str] = {} - field_sources: dict[str, list[str]] = {} - overall = 'parsed' - for item in segments: - if item.status == 'needs_review': - overall = 'needs_review' - if item.handling != 'mapped' or not item.target_field_code: - continue - code = item.target_field_code - field_sources.setdefault(code, []).append(item.rule_id) - if code in mapped_fields: - overall = 'needs_review' - diagnostics.append(XfaSplitDiagnostic( - code='same_field_multiple_segment', - message=f'Schema field {code} hit by multiple segments', - field_code=code, - rule_ids=list(field_sources[code]), - )) - else: - mapped_fields[code] = item.normalized_text - - for _code, sources in field_sources.items(): - if len(sources) > 1 and rule_set.same_field_multiple_segment_policy == 'needs_review': - overall = 'needs_review' - - if any(d.code == 'duplicate_line_match' for d in diagnostics): - if rule_set.duplicate_match_policy == 'needs_review': - overall = 'needs_review' - - if any(d.code in { - 'regex_timeout', 'regex_failed', 'mapped_value_empty', 'input_too_long', - } for d in diagnostics): - overall = 'needs_review' - - evidence_only = [item for item in segments if item.handling == 'evidence_only'] - return XfaSplitEngineResult( - status=overall, - segments=segments, - mapped_fields=mapped_fields, - evidence_only_segments=evidence_only, - diagnostics=diagnostics, - rule_id=rule_set.rule_set_id, - rule_version=rule_set.rule_version, + core_result = execute_base_split_rule_set( + raw_value=raw_value, + rule_set=rule_set, + lines=lines, ) + return _core_result_to_xfa(core_result) def execute_split_on_leaf( @@ -486,6 +209,8 @@ def project_split_result_safe( 核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且 include_full_values=True 时返回 raw_text / 完整 mapped 值。 evidence_only_segments 避免与 segments 重复展示(置空列表)。 + 【阶段 1 零契约漂移】:JSON 键名(rule_id 而非 rule_set_id)、段结构、 + 诊断结构完全与历史一致。 Args: result: 引擎输出。 diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index a434d8ae..4602bae1 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -56,6 +56,8 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({ 'generic_gate_blocked', 'order_extraction_failed', 'order_extraction_cancelled', + 'profile_schema_mismatch', + 'row_needs_review', # XFA 数据路径(阶段 0 冻结) 'xfa_dataset_missing', 'xfa_unsafe_xml', @@ -68,6 +70,7 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({ 'xfa_profile_not_matched', 'xfa_profile_ambiguous', 'xfa_required_field_missing', + 'xfa_source_mapping_incomplete', 'xfa_mirror_collection_mismatch', 'xfa_acroform_mismatch', 'xfa_business_validation_failed', @@ -93,6 +96,7 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({ # 字段抽取、客户与订单校验 ORDER_FIELD_REASON_CODES: Final[frozenset[str]] = frozenset({ 'required_field_missing', + 'final_required_field_missing', 'field_value_invalid', 'field_low_confidence', 'classification_low_confidence', @@ -229,6 +233,12 @@ EXPLAINABILITY_REASON_ALIASES: Final[dict[str, str]] = { 'effective_reservation_missing': 'reservation_missing', # Candidate 人工驳回历史码 → 关闭类稳定码 'manual_rejected': 'task_rejected_by_user', + # 订单 Schema 字段必填:旧码 → 新 canonical 码 + 'required_field_missing': 'final_required_field_missing', + # Profile/Schema 结构性不匹配:旧码 → 新 canonical 码 + 'order_profile_snapshot_field_mismatch': 'profile_schema_mismatch', + # XFA 字段值缺失:旧码 → 非阻断的来源暂缺诊断码 + 'xfa_required_field_missing': 'xfa_source_mapping_incomplete', # XFA AppError / 大写错误码 → 稳定原因码 'XFA_DATASET_MISSING': 'xfa_dataset_missing', 'XFA_UNSAFE_XML': 'xfa_unsafe_xml', @@ -240,7 +250,7 @@ EXPLAINABILITY_REASON_ALIASES: Final[dict[str, str]] = { 'XFA_UNSUPPORTED_DOCUMENT': 'xfa_unsupported_document', 'XFA_PROFILE_NOT_MATCHED': 'xfa_profile_not_matched', 'XFA_PROFILE_AMBIGUOUS': 'xfa_profile_ambiguous', - 'XFA_REQUIRED_FIELD_MISSING': 'xfa_required_field_missing', + 'XFA_REQUIRED_FIELD_MISSING': 'xfa_source_mapping_incomplete', 'XFA_MIRROR_COLLECTION_MISMATCH': 'xfa_mirror_collection_mismatch', 'XFA_ACROFORM_MISMATCH': 'xfa_acroform_mismatch', 'XFA_BUSINESS_VALIDATION_FAILED': 'xfa_business_validation_failed', @@ -352,6 +362,7 @@ ORDER_FIELD_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({ 'reservation_duplicate', 'duplicate_unresolved', 'required_field_missing', + 'final_required_field_missing', 'field_value_invalid', 'field_conflict', 'field_low_confidence', @@ -372,6 +383,9 @@ DOCUMENT_PARSE_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({ 'order_extraction_failed', 'order_extraction_cancelled', 'generic_gate_blocked', + 'profile_schema_mismatch', + 'row_needs_review', + 'xfa_source_mapping_incomplete', }) # 建单 / 冻结已接线子集(与 Gate 投影共用) @@ -453,8 +467,12 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'profile_not_matched': _meta('owner', 'open_profile_review', '未能匹配文档模板,请人工确认 Profile'), 'profile_ambiguous': _meta('owner', 'open_profile_review', '文档模板存在歧义,请人工确认 Profile'), 'profile_drift': _meta('owner', 'open_profile_review', '文档结构与模板版本不一致'), + 'profile_schema_mismatch': _meta('owner', 'open_profile_review', '当前模板字段定义与本次冻结 Schema 不一致,无法安全自动处理'), + 'row_needs_review': _meta('owner', 'open_order_review', '部分明细行存在格式问题,需要人工复核'), 'extraction_incomplete': _meta('worker', 'retry_order_extraction', '订单字段抽取未完成,请重试或进入复核'), 'required_field_missing': _meta('owner', 'edit_order_fields', '缺少创建订单所需字段'), + 'final_required_field_missing': _meta('owner', 'edit_order_fields', '最终订单缺少必填字段(经邮件/坐标/推导合并后仍缺失)'), + 'xfa_source_mapping_incomplete': _meta('owner', 'open_order_review', 'XFA 数据集当前暂缺部分字段值,可经邮件/坐标补齐'), 'field_value_invalid': _meta('owner', 'edit_order_fields', '部分字段格式不正确'), 'field_low_confidence': _meta('owner', 'open_order_review', '部分识别结果置信度较低'), 'classification_low_confidence': _meta('owner', 'open_order_review', '订单分类置信度不足'), @@ -511,6 +529,10 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'), 'inventory_rpa_exhausted': _meta('owner', 'upload_inventory_file', '库存源重试次数已耗尽'), 'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'), + 'inventory_candidates_missing': _meta('owner', 'open_inventory_source_review', '正式库存候选版本缺失'), + 'inventory_candidate_data_incomplete': _meta('owner', 'open_inventory_source_review', '库存候选事实不完整'), + 'inventory_candidate_version_stale': _meta('owner', 'open_inventory_source_review', '库存候选版本已切换'), + 'inventory_match_out_of_candidate_scope': _meta('owner', 'open_inventory_source_review', '库存命中超出当前候选范围'), 'inventory_file_identity_mismatch': _meta('owner', 'retry_inventory_preparation', '返回文件与所选库存源不一致'), 'inventory_file_empty': _meta('owner', 'retry_inventory_preparation', '库存文件为空或没有有效库存记录'), 'inventory_mapping_required': _meta('owner', 'confirm_inventory_field_mapping', '库存字段映射待确认'), @@ -1015,3 +1037,9 @@ def assert_error_explainability_contract_integrity() -> None: # blocking_reason_code 为动态透传占位,不要求属于冻结集合 if code != 'blocking_reason_code': assert code in frozen, f'{node} reason_code {code} not frozen' + + # [STEP 7] 门禁契约用户态映射闭环(GATE/EXEC/REASON → USER_STATE) + from app.services.shipping_notice.process_gate_contract import ( + assert_process_gate_contract_integrity, + ) + assert_process_gate_contract_integrity() diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index 447940e8..d646641d 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -21,6 +21,7 @@ from zoneinfo import ZoneInfo from flask import current_app from openpyxl import load_workbook +from sqlalchemy import func from app import db from app.models import ( ShippingExcelTemplate, @@ -302,14 +303,70 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp Raises: ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。 + AppError: [T6 硬门禁] 行级库存匹配存在非 matched 行(shortage / not_found / conflict)。 """ from app.services.shipping_notice.task_disposition_service import task_is_active from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked + from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch + from app.core.errors import AppError + if not task_is_active(task): raise ValueError('已作废或归档的任务不能生成发货 Excel') assert_task_not_supersession_blocked(task) + # [T6 E2 硬门禁] 生成 Excel 前强制断言所有当前行匹配结果均为 matched; + # 即使单源任务有明确 inventory_source_code,行级短缺/冲突仍须先处理,避免导出不完整数据。 + if task.id is not None: + pending_rows = db.session.query( + ShippingNoticeLineInventoryMatch.line_key, + ShippingNoticeLineInventoryMatch.match_result, + ShippingNoticeLineInventoryMatch.part_number, + ShippingNoticeLineInventoryMatch.reservation_id, + ShippingNoticeLineInventoryMatch.shortage_qty, + ).filter( + ShippingNoticeLineInventoryMatch.task_id == task.id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.match_result != 'matched', + ).limit(20).all() + pending_count = db.session.query(func.count(ShippingNoticeLineInventoryMatch.id)).filter( + ShippingNoticeLineInventoryMatch.task_id == task.id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.match_result != 'matched', + ).scalar() or 0 + if pending_count > 0: + details = [ + { + 'line_key': r[0], + 'match_result': r[1], + 'part_number': r[2], + 'reservation_id': r[3], + 'shortage_qty': r[4], + } + for r in pending_rows + ] + raise AppError( + error_code='excel_not_ready', + status_code=409, + blocking_reason_code='inventory_match_incomplete', + message=f'存在 {pending_count} 行库存未完全匹配,禁止生成发货 Excel(请先处理短缺或冲突)。', + details={ + 'pending_count': int(pending_count), + 'pending_rows_preview': details, + 'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。', + }, + ) source_code = str(task.inventory_source_code or '').strip().upper() source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + # [T6 多候选兼容] 单源 resolved 走上方 inventory_source_code;多候选 candidates_frozen 时可能 source_code==None, + # 在严格全行 matched 前提下可退回到第一条 line_match 的 inventory_source_code(保证不绕过断言)。 + first_match = db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter( + ShippingNoticeLineInventoryMatch.task_id == task.id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.match_result == 'matched', + ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None), + ).limit(1).first() + source_code_candidate = str(first_match[0]).strip().upper() if first_match and first_match[0] else '' + source = ShippingInventorySource.query.filter_by(source_code=source_code_candidate, enabled=True).first() if source_code_candidate else None if source is None: raise ValueError('库存源不存在或已停用,不能生成发货 Excel') # Fixed Sources receive this value from configuration; dynamic Sources receive it diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 196064e4..34aaef4f 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -414,6 +414,10 @@ def _trigger_freight_upload_rpa( task.error_message = t('workflow.fulfillment.upload_exhausted', lang=lang).format(attempts=attempts) log_task_event(task, 'upload_rpa_exhausted', {'attempts': attempts, 'max_attempts': max_attempts}) db.session.commit() + # RPA 成功只登记可信回执;P0-3 completed 仍必须由 receipt Gate 重读事实决定。 + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + + submit_auto_progress(task=task, trigger='freight_upload_rpa_callback_succeeded', commit=True) return tool_response( status='needs_human', task=task, @@ -786,6 +790,413 @@ def _order_extraction_gate_response( return None +def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, Any]: + """ + 题5B:行级库存匹配(仅目标 line_key)—— 避免整单重算覆盖其他行证据/时间戳。 + + 【AI 触发时机】:用户仅对某一行点「重试匹配库存」或系统侧决策为 ACTION_REMATCH & 有 snapshot_id 时调用; + 必须 line_key 非空,不回退到整单。 + + 核心逻辑: + [STEP 1] 共用 match_inventory 的门禁/库存快照载入; + [STEP 2] 仅 purpose_lines 中 line_key == 目标 的那条 purpose_line 生成单元素 stp_order_lines; + [STEP 3] 调 match_order_lines_across_candidates(单条 order_lines); + [STEP 4] persist_line_inventory_match_facts:line_results 只写该条(其他行 untouched); + [STEP 5] 整单汇总用:match_status 按全行事实重算(读现有的 line_inventory_match 表), + 不直接 trust 本单条结果的 fulfillable 结论(避免局部 ok 掩盖全局 shortage)。 + + Args: + payload: 含 task_no / operator_id / expected_order_task_no 等,与 match_inventory 一致。 + line_key: 必填;目标行业务键(shipping_order_fields.line_key 或 line-{idx})。 + + Returns: + Tool 标准响应(status ok / needs_human / failed)。 + """ + # T5 Orchestrator 守卫:外部收口 run_task_auto_progress(但内部 dispatch 可以直跑) + if not payload.get('_orchestrator_internal_dispatch', False): + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp + task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip() + if not task_no and isinstance(payload, dict): + _t = _rtp(payload) + task_no = str(getattr(_t, 'task_no', '') or '').strip() + trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_match_inventory_line').strip() + actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id") + try: + operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None + except (TypeError, ValueError): + operator_id = None + return run_task_auto_progress( + task_no, trigger=trigger, + expected_version=None, + idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, + resume_gate_code='inventory_matching', + operator_id=operator_id, + line_scope_key=str(line_key or '').strip() or None, + ) + target_key = str(line_key or '').strip() + if not target_key: + return tool_response(status='failed', message='行级库存匹配必须提供 line_key') + lang = resolve_lang(payload) + actor_id = _event_actor_id(payload) + task = resolve_task_from_payload(payload) + if not task: + return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + # 正式候选冻结任务必须绑定当前 frozen CandidateSet;缺失时禁止回退旧单源/JSON 路径。 + from app.services.shipping_notice.inventory_candidate_projection import ( + build_inventory_candidate_blocking_reason, + build_inventory_candidate_primary_action, + get_active_candidate_set, + ) + if str(task.inventory_source_status or '').strip() == 'candidates_frozen': + active_candidate_set = get_active_candidate_set(task) + if active_candidate_set is None: + return tool_response( + status='needs_human', + task=task, + message='当前库存候选版本缺失或已失效,需重新确认库存来源。', + data={ + **serialize_task_for_tool(task), + 'blocking_reason': build_inventory_candidate_blocking_reason( + 'inventory_candidate_version_stale', task=task, + ), + 'primary_action': build_inventory_candidate_primary_action(), + }, + checkpoint='inventory_source_review', + stop_agent_turn=True, + ) + # ownership & gates + from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership + assert_notice_task_ownership( + task, + expected_order_task_no=str(payload.get('expected_order_task_no') or '').strip() or None, + expected_review_case_no=str(payload.get('expected_review_case_no') or '').strip() or None, + expected_run_no=str(payload.get('expected_run_no') or '').strip() or None, + actor_id=actor_id, + ) + disposition_gate = _task_disposition_gate_response(task) + if disposition_gate is not None: + return disposition_gate + customer_gate = customer_gate_tool_response(task, operation='match_inventory_line') + if customer_gate is not None: + return customer_gate + conflict_gate = field_conflict_gate_response(task, lang=lang) + if conflict_gate is not None: + return conflict_gate + reservation_gate = _reservation_gate_response( + task, + lang=lang, + forbidden_next_tools=[ + "ensure_inventory", + "match_inventory", + "generate_shipment_excel", + "upload_to_freight", + ], + ) + if reservation_gate is not None: + return reservation_gate + extraction_gate = _order_extraction_gate_response( + task, + forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], + ) + if extraction_gate is not None: + return extraction_gate + # [STEP 1] inventory snapshot + inventory_lines = parse_inventory_lines(payload) + if inventory_lines: + task.inventory_lines_json = inventory_lines + else: + inventory_lines = active_inventory_lines_for_task(task) + if not inventory_lines: + # 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义) + inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_key': target_key} + lang_suffix = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() + if lang_suffix: + inv_payload["lang"] = lang_suffix + return ensure_inventory(inv_payload) + if not is_inventory_source_stable(task): + return tool_response( + status="needs_human", + task=task, + message="库存源尚未确定,无法执行行级库存匹配。", + data=serialize_task_for_tool(task), + checkpoint="inventory_source_review", + stop_agent_turn=True, + ) + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_line_inventory_match import ( + attach_candidate_scope_to_order_lines, + apply_forced_match_source_filter, + apply_line_inventory_resolutions, + match_order_lines_across_candidates, + snapshot_header_reservation_id, + ) + inventory_lines = apply_forced_match_source_filter(inventory_lines or [], task=task) + + _order_header_values, order_field_lines = order_field_id_values(task) + purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'}) + + # [STEP 2] 定位目标行 purpose_line + order_field_line + target_pair: tuple[int, dict[str, Any], dict[str, Any]] | None = None + for idx, purpose_line in enumerate(purpose_lines): + ofl = order_field_lines[idx] if idx < len(order_field_lines) else {} + candidate_key = str( + purpose_line.get('line_key') + or ofl.get('line_key') + or f'line-{idx + 1}' + ).strip() + if candidate_key == target_key: + target_pair = (idx, purpose_line, ofl) + break + if target_pair is None: + # line_key 未找到(可能草稿与 OT 行未对齐) + return tool_response( + status='failed', + task=task, + message=f'未找到行 {target_key},无法执行行级库存匹配。', + data=serialize_task_for_tool(task), + ) + orig_idx, purpose_line, order_field_line = target_pair + required_qty = purpose_line.get('quantity') + display_part = purpose_line.get('part_number') + display_rsv = purpose_line.get('reservation_id') + display_uom = ( + purpose_line.get('uom') + or purpose_line.get('unit') + or order_field_line.get('uom') + or order_field_line.get('unit') + ) + order_field_line['__required_qty'] = required_qty + order_field_line['__display_part_number'] = display_part + order_field_line['__display_reservation_id'] = display_rsv + order_field_line['__display_uom'] = display_uom + + _sync_workflow_stage( + task, + lifecycle_status='inventory_matching', + event_code='inventory_match_line_started', + actor_id=actor_id, + payload={'task_no': task.task_no, 'line_key': target_key, 'line_index': orig_idx}, + ) + db.session.flush() + + header_reservation = None + snapshot = None + if task.order_snapshot_id: + from app.models import ShippingOrderSnapshot + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + if snapshot is not None: + header_reservation = snapshot_header_reservation_id(snapshot) + + stp_order_lines = [{ + **purpose_line, + '__required_qty': required_qty, + '__display_part_number': display_part, + '__display_reservation_id': display_rsv, + '__display_uom': display_uom, + 'uom': display_uom, + 'line_key': order_field_line.get('line_key') or target_key, + 'line_index': orig_idx, + }] + # [STEP 3] 只跑目标行 match + match_payload = match_order_lines_across_candidates( + order_lines=attach_candidate_scope_to_order_lines(task, stp_order_lines), + inventory_lines=inventory_lines or [], + header_reservation_id=header_reservation, + ) + # resolutions 注入 line_key(保证 persist 时精准) + for res in (match_payload.get('resolutions') or []): + if isinstance(res, dict): + res['line_key'] = ( + str(res.get('line_key') or '').strip() + or order_field_line.get('line_key') + or target_key + ) + # [STEP 4] 持久化仅本行(其他行 is_current 保持不变) + from app.services.shipping_notice.line_inventory_match_persistence import ( + persist_line_inventory_match_facts, + ) + persist_line_inventory_match_facts( + task=task, + match_payload=match_payload, + inventory_snapshot_id=( + int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None + ), + matching_rule_version='stp_line_v2', + ) + # 行级 apply_line_inventory_resolutions:但不能全量覆盖 task.match_status, + # 改写成「增量合并」:把本 line 的 resolution 合并进 task.step_payload_json.line_inventory_resolutions, + # 再基于现有的全部 current 行事实重算 match_status。 + _merge_line_inventory_resolutions(task, match_payload, line_key=target_key) + + line_results = list(match_payload.get('line_results') or []) + from app.services.shipping_notice.reservation_service import record_inventory_verification + verification = record_inventory_verification( + task, inventory_snapshot_id=task.inventory_snapshot_id, + source_config_version=task.inventory_source_config_version, line_results=line_results, + ) + + # [STEP 5] 基于 current 行事实重新聚合 match_status,避免局部 ok 覆盖全局 shortage。 + aggregate_match_status, aggregate_shortages = _recompute_task_match_aggregate(task) + task.match_status = aggregate_match_status + # shortages 保持整单范围(用于展示),行级单独记录到 detail_json + line_result_status = str(match_payload.get('match_status') or 'unfulfillable') + set_task_step_progress( + task, + step_key="step5_match_inventory", + step_title="匹配库存", + status="running", + message=t("workflow.fulfillment.match_running", lang=lang), + progress_percent=50, + detail=( + t("workflow.fulfillment.match_line_result", lang=lang) + .format(line_key=target_key, line_result=line_result_status) + ), + ) + match_summary = format_match_summary( + aggregate_match_status, + _current_line_results(task), + task_no=task.task_no, + lang=lang, + ) + if aggregate_match_status == 'fulfillable' and task.inventory_source_code: + apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE) + log_task_event( + task, + "matched_stp_line_rematch_ok", + { + "match_status": aggregate_match_status, + "verification_id": verification.id, + "resolved_ok_source_codes": (task.step_payload_json or {}).get('resolved_ok_source_codes'), + "excel_binding_source_code": task.inventory_source_code, + "line_key": target_key, + "line_result": line_result_status, + }, + actor_id=actor_id, + source='workspace_api' if actor_id else 'system', + ) + from app.services.shipping_notice.line_auto_fulfill_coordinator import ( + enqueue_post_ot_auto_fulfill_job, + ) + enqueue_post_ot_auto_fulfill_job( + task_no=str(task.task_no), + trigger='inventory_ready_rematch_line', + commit=False, + ) + db.session.commit() + match_result = tool_response( + status="ok", + task_id=task.task_no, + message=match_summary, + data=serialize_task_for_tool(task), + checkpoint=f'line:{target_key}:rematch:ok', + ) + return try_auto_chain_after_match(task, match_result, payload=payload) + apply_task_transition(task, TaskTransition.MATCH_SHORTAGE) + log_task_event( + task, + "matched_stp_line_rematch_shortage", + { + "match_status": aggregate_match_status, + "line_key": target_key, + "line_result": line_result_status, + "shortages": aggregate_shortages, + }, + actor_id=actor_id, + source='workspace_api' if actor_id else 'system', + ) + from app.services.shipping_notice.line_auto_fulfill_coordinator import ( + enqueue_post_ot_auto_fulfill_job, + ) + enqueue_post_ot_auto_fulfill_job( + task_no=str(task.task_no), + trigger='inventory_ready_rematch_line', + commit=False, + ) + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message=match_summary, + data=serialize_task_for_tool(task), + checkpoint=f'shortage_review:line:{target_key}', + stop_agent_turn=True, + forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], + ) + + +def _merge_line_inventory_resolutions( + task: ShippingNotice, match_payload: dict[str, Any], *, line_key: str +) -> None: + """把行级 match_payload.resolutions 合并进 task.step_payload_json.line_inventory_resolutions(只替换/追加本行条目)。""" + payload_step = dict(task.step_payload_json or {}) + old_resolutions = [ + r for r in list(payload_step.get('line_inventory_resolutions') or []) + if isinstance(r, dict) and str(r.get('line_key') or f'line-{int(r.get("line_index") or 0) + 1}').strip() != str(line_key) + ] + new_resolutions = [r for r in list(match_payload.get('resolutions') or []) if isinstance(r, dict)] + merged_resolutions = [*old_resolutions, *new_resolutions] + payload_step['line_inventory_resolutions'] = merged_resolutions + payload_step.pop('multi_source_excel_block', None) + task.step_payload_json = payload_step + # line_results_json & shortage_json 保持整单范围不在这里单行替换;统一由 recompute 使用 facts 重算 + + +def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dict[str, Any]]]: + """根据 ShippingNoticeLineInventoryMatch(current=True)重新聚合成 match_status(fulfillable/partial/unfulfillable)+ shortages。""" + rows = ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), is_current=True) + .all() + ) + if not rows: + return 'unfulfillable', [] + has_ok = False + has_block = False + shortages: list[dict[str, Any]] = [] + task.line_results_json = [] + for row in rows: + match_result = str(getattr(row, 'match_result', '') or '').strip() + required_qty = getattr(row, 'required_qty', None) + available_qty = getattr(row, 'available_qty', None) + shortage_qty = getattr(row, 'shortage_qty', None) + entry = { + 'line_index': int(getattr(row, 'line_index', 0) or 0), + 'line_key': str(getattr(row, 'line_key', '') or ''), + 'disposition': match_result or 'not_found', + 'part_number': getattr(row, 'part_number', None), + 'reservation_id': getattr(row, 'reservation_id', None), + 'unit': getattr(row, 'unit', None), + 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'required_qty': float(required_qty) if required_qty is not None else 0.0, + 'available_qty': float(available_qty) if available_qty is not None else 0.0, + 'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0, + } + task.line_results_json.append(entry) + if match_result == 'matched': + has_ok = True + continue + has_block = True + shortages.append(entry) + task.shortage_json = {'lines': shortages} + if has_block and has_ok: + status = 'partial' + elif has_block: + status = 'unfulfillable' + else: + status = 'fulfillable' + return status, shortages + + +def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: + """返回 task.line_results_json(若没初始化则用现查询 facts 重算)供 format_match_summary。""" + cached = list(task.line_results_json or []) + if cached: + return cached + _recompute_task_match_aggregate(task) + return list(task.line_results_json or []) + + def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: """ 将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。 @@ -800,6 +1211,28 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: Returns: dict[str, Any]: Tool 标准响应;status 可为 ok / needs_human / failed。 """ + # [T5 Orchestrator 守卫]:外部直接调用 → 收口到 run_task_auto_progress 并发锁; + # Orchestrator 内部分派调用(_orchestrator_internal_dispatch=True)→ 直接执行下方实现。 + if not payload.get('_orchestrator_internal_dispatch', False): + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp + task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip() + if not task_no and isinstance(payload, dict): + _t = _rtp(payload) + task_no = str(getattr(_t, 'task_no', '') or '').strip() + trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_match_inventory').strip() + actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id") + try: + operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None + except (TypeError, ValueError): + operator_id = None + return run_task_auto_progress( + task_no, trigger=trigger, + expected_version=None, + idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, + resume_gate_code='inventory_matching', + operator_id=operator_id, + ) lang = resolve_lang(payload) actor_id = _event_actor_id(payload) task = resolve_task_from_payload(payload) @@ -905,6 +1338,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes from app.services.shipping_notice.stp_line_inventory_match import ( + attach_candidate_scope_to_order_lines, apply_forced_match_source_filter, apply_line_inventory_resolutions, match_order_lines_across_candidates, @@ -948,7 +1382,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: 'line_key': (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key'), }) match_payload = match_order_lines_across_candidates( - order_lines=stp_order_lines, + order_lines=attach_candidate_scope_to_order_lines(task, stp_order_lines), inventory_lines=inventory_lines or [], header_reservation_id=header_reservation, ) diff --git a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py new file mode 100644 index 00000000..a4c7fca1 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py @@ -0,0 +1,555 @@ +""" +services/shipping_notice/inventory_candidate_freeze_service.py + +用途:库存候选冻结的统一写入服务——将路由评估结果写入 Set/Source/Line 三张结构化表 + (T2 新建,决策 C1 的正式业务真相),并同步写 ShippingOrderSnapshot.source_manifest_json + 作为不可变审计副本。 +依赖:app.models.shipping_inventory_candidates(Set/Source/Line)、inventory_source_rules、 + inventory_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。 +逻辑:由 adjudicate_and_apply_inventory_source(裁决阶段 ambiguous→candidates_frozen) + 与 STP 建单 freeze_stp_inventory_candidates_on_task 两条路径调用; + input_fingerprint 相同则直接返回旧 set_id(幂等),冻结结果不可变。 +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +from sqlalchemy import and_, func +from sqlalchemy.orm import Session + +from app import db +from app.models import ( + ShippingInventoryCandidateLine, + ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, + ShippingNotice, + ShippingOrderSnapshot, +) +from app.services.shipping_notice.inventory_source_repository import ( + get_database_inventory_source, + inventory_sources_runtime_version, +) +from app.services.shipping_notice.inventory_source_rules import ( + InventorySourceAdjudication, + _task_routing_lines, + compute_routing_fingerprint, + evaluate_inventory_source_rules, + extract_routing_context, +) + + +@dataclass +class CandidateFreezeResult: + """候选冻结结果——返回结构化 ID 与是否新建(供调用方打审计日志)。""" + + candidate_set_id: int + created_new: bool + source_codes: list[str] + line_count: int + manifest_snapshot_sha256: str + set_version: int + + +def _build_input_fingerprint( + *, + routing_fingerprint: str, + source_codes_ordered: list[str], + line_signatures: list[tuple[int, str | None, str | None, str | None, list[str]]], + config_version: str, +) -> str: + """ + 计算候选冻结输入指纹——相同输入保证复用同一个 Set(幂等键)。 + 核心要素:路由上下文指纹 + 有序候选源 + 每行(pn, resv, source_codes有序)三元组 + 配置版本。 + """ + payload: dict[str, Any] = { + 'routing_fingerprint': routing_fingerprint, + 'source_codes_ordered': source_codes_ordered, + 'line_signatures': [ + { + 'line_no': sig[0], + 'source_line_no': sig[1], + 'part_number': sig[2], + 'reservation_id': sig[3], + 'source_codes_ordered': list(sig[4]), + } + for sig in line_signatures + ], + 'config_version': config_version, + } + raw = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(',', ':')) + return hashlib.sha256(raw.encode('utf-8')).hexdigest() + + +def _build_manifest_snapshot( + *, + task: ShippingNotice, + set_db: ShippingInventoryCandidateSet, + sources_db: list[ShippingInventoryCandidateSource], + lines_db: list[ShippingInventoryCandidateLine], + routing_rule_version_json: dict[str, Any] | None, +) -> dict[str, Any]: + """ + 构建 source_manifest_json['inventory_candidate_freeze'] 不可变副本—— + 与 Set/Source/Line 三张表同一时刻的完整快照,供审计与事后追溯。 + """ + return { + 'frozen_at': set_db.frozen_at.isoformat() if set_db.frozen_at else None, + 'set_id': set_db.id, + 'set_version': set_db.set_version, + 'input_fingerprint': set_db.input_fingerprint, + 'task_id': set_db.task_id, + 'review_case_id': set_db.review_case_id, + 'execution_id': set_db.execution_id, + 'frozen_by_id': set_db.frozen_by_id, + 'routing_rule_version_json': routing_rule_version_json or {}, + 'routing_rule_version_sha256': hashlib.sha256( + json.dumps(routing_rule_version_json or {}, sort_keys=True, ensure_ascii=False).encode('utf-8') + ).hexdigest() + if routing_rule_version_json + else None, + 'candidate_sources': [ + { + 'source_code': s.source_code, + 'candidate_order': s.candidate_order, + 'candidate_origin': s.candidate_origin, + 'routing_rule_id': s.routing_rule_id, + 'routing_rule_version': s.routing_rule_version, + 'source_config_version': s.source_config_version, + 'override_by_id': s.override_by_id, + 'override_reason': s.override_reason, + } + for s in sorted(sources_db, key=lambda x: x.candidate_order) + ], + 'candidate_lines': [ + { + 'line_no': ln.line_no, + 'source_line_no': ln.source_line_no, + 'part_number': ln.part_number, + 'reservation_id': ln.reservation_id, + 'source_codes_ordered': ln.source_codes_json if isinstance(ln.source_codes_json, list) else [], + 'override_by_id': ln.override_by_id, + 'override_reason': ln.override_reason, + } + for ln in sorted(lines_db, key=lambda x: x.line_no or '') + ], + 'remark': set_db.remark, + } + + +def _persist_manifest_snapshot_to_snapshot( + *, + task: ShippingNotice, + manifest: dict[str, Any], + session: Session, +) -> None: + """ + 将 inventory_candidate_freeze 副本写入 ShippingOrderSnapshot.source_manifest_json(若该任务已有 Snapshot)。 + Snapshot 不存在时不报错——调用方(如建单前草稿阶段)可能尚未完成订单冻结。 + """ + snapshot = ( + session.query(ShippingOrderSnapshot) + .filter(ShippingOrderSnapshot.task_id == task.id) + .one_or_none() + ) + if snapshot is None: + return + manifest_root = dict(snapshot.source_manifest_json or {}) if isinstance(snapshot.source_manifest_json, dict) else {} + manifest_root['inventory_candidate_freeze'] = manifest + snapshot.source_manifest_json = manifest_root + + +def _collect_order_line_candidates( + task: ShippingNotice, + *, + task_level_source_codes_ordered: list[str], +) -> tuple[list[dict[str, Any]], list[tuple[int, str | None, str | None, str | None, list[str]]]]: + """ + 评估每行路由规则,返回行级候选投影 + 行级签名(用于 fingerprint 与 Line 表写入)。 + 行级无规则命中时回退到任务级 source_codes(保证每行至少一个候选)。 + """ + lines = _task_routing_lines(task) + line_projections: list[dict[str, Any]] = [] + line_signatures: list[tuple[int, str | None, str | None, str | None, list[str]]] = [] + + for idx, line in enumerate(lines): + line_no = idx + 1 + source_line_no = str(line.get('line_no') or '').strip() or None + part_number = str(line.get('part_number') or '').strip() or None + reservation_id = str(line.get('reservation_id') or '').strip() or None + line_result = evaluate_inventory_source_rules(task=task, line=line) + if line_result.status == 'resolved' and line_result.source_codes: + line_codes = [str(code).upper() for code in line_result.source_codes] + else: + line_codes = list(task_level_source_codes_ordered) + + if not line_codes: + line_codes = list(task_level_source_codes_ordered) + + line_projections.append({ + 'line_key': f'{task.id}:{line_no}', + 'line_index': idx, + 'line_no': line_no, + 'source_line_no': source_line_no, + 'part_number': part_number, + 'reservation_id': reservation_id, + 'candidate_inventory_source_codes': line_codes, + 'selection_mode': 'line_rule' if (line_result.status == 'resolved' and line_result.source_codes) else 'task_fallback', + 'matched_rule_ids': list(getattr(line_result, 'matched_rules', ()) or ()), + 'routing_status': line_result.status, + }) + line_signatures.append((line_no, source_line_no, part_number, reservation_id, line_codes)) + + return line_projections, line_signatures + + +def _find_existing_frozen_set( + *, + task_id: int | None, + review_case_id: int | None, + input_fingerprint: str, + session: Session, +) -> ShippingInventoryCandidateSet | None: + """ + 根据幂等键查找已存在的冻结 Set(task 绑定或 review_case 绑定分别查询)。 + PostgreSQL 部分唯一索引保证每个绑定维度的 fingerprint 唯一。 + """ + if task_id is not None: + return ( + session.query(ShippingInventoryCandidateSet) + .filter( + and_( + ShippingInventoryCandidateSet.task_id == task_id, + ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint, + ShippingInventoryCandidateSet.lifecycle_status == 'frozen', + ) + ) + .order_by(ShippingInventoryCandidateSet.id.desc()) + .first() + ) + if review_case_id is not None: + return ( + session.query(ShippingInventoryCandidateSet) + .filter( + and_( + ShippingInventoryCandidateSet.review_case_id == review_case_id, + ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint, + ShippingInventoryCandidateSet.lifecycle_status == 'frozen', + ) + ) + .order_by(ShippingInventoryCandidateSet.id.desc()) + .first() + ) + return None + + +def _next_task_set_version(*, task_id: int, session: Session) -> int: + """计算 Task 维度下一个 CandidateSet.version。""" + current_max = ( + session.query(func.max(ShippingInventoryCandidateSet.set_version)) + .filter(ShippingInventoryCandidateSet.task_id == int(task_id)) + .scalar() + ) + return int(current_max or 0) + 1 + + +def _invalidate_task_candidate_outputs(task: ShippingNotice, *, session: Session) -> None: + """重冻结后立即失效旧匹配、导出与待上传事实,避免旧版本继续被消费。""" + from app.models import ShippingNoticeLineInventoryMatch, ShippingTaskInventoryRpaAttempt + + task.match_status = None + task.shortage_json = None + task.line_results_json = None + task.export_file_path = None + task.export_file_name = None + task.upload_status = None + + payload = dict(task.step_payload_json or {}) + payload.pop('line_inventory_resolutions', None) + payload.pop('resolved_ok_source_codes', None) + payload.pop('excel_binding_source_code', None) + payload.pop('multi_source_excel_block', None) + task.step_payload_json = payload + + ( + session.query(ShippingNoticeLineInventoryMatch) + .filter( + ShippingNoticeLineInventoryMatch.task_id == int(task.id), + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ) + .update({'is_current': False, 'updated_at': datetime.utcnow()}, synchronize_session=False) + ) + ( + session.query(ShippingTaskInventoryRpaAttempt) + .filter( + ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or ''), + ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + ) + .update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False) + ) + + +def freeze_candidates_for_task( + task: ShippingNotice, + *, + adjudication: InventorySourceAdjudication | None = None, + review_case_id: int | None = None, + execution_id: int | None = None, + frozen_by_id: int | None = None, + line_projections: list[dict[str, Any]] | None = None, + session: Session | None = None, +) -> CandidateFreezeResult: + """ + 将库存候选集合冻结到三张结构化表(正式业务真相)+ Snapshot.source_manifest_json(不可变副本)。 + 【AI 触发时机】:订单解析完成后 ambiguous→candidates_frozen 转换、STP 建单多候选阶段、 + 或人工覆盖候选后重新冻结时调用。 + + 核心逻辑: + [STEP 1] 提取路由上下文,计算任务级 source_codes(保序)与行级 source_codes。 + [STEP 2] 构建 input_fingerprint,查找是否已有幂等冻结 Set——命中则直接复用。 + [STEP 3] 写 Set → Source(保序)→ Line(行级候选有序列表)三张表。 + [STEP 4] 同步写 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze']。 + [STEP 5] 回填 task.inventory_source_status='candidates_frozen'(调用方负责 commit)。 + + Args: + task: 已 flush 的 ShippingNotice(有 id 字段)。 + adjudication: 裁决结果(含 candidates / config_version / routing_fingerprint); + 缺省时调用 adjudicate_inventory_source 重新评估。 + review_case_id: 建单前草稿阶段的绑定 ID(task_id 可空时使用)。 + execution_id: 可选的 ProcessExecution 绑定 ID。 + frozen_by_id: 人工覆盖冻结时的操作人 ID。 + line_projections: STP 阶段已算出的行级候选投影(缺省时逐行 evaluate_inventory_source_rules)。 + session: 可选的 SQLAlchemy Session(缺省用 db.session)。 + + Returns: + CandidateFreezeResult: 含 candidate_set_id / 是否新建 / 源列表 / 行数 / manifest_sha256。 + + Raises: + ValueError: 任务与草稿均未绑定、或候选源集合为空(应走 unresolved/conflicted 人工阻断,调用方不应进入本函数)。 + """ + if task.id is None and review_case_id is None: + raise ValueError('freeze_candidates_for_task 必须绑定 task 或 review_case 其一') + + session = session or db.session + if adjudication is None: + from app.services.shipping_notice.inventory_source_rules import adjudicate_inventory_source + + adjudication = adjudicate_inventory_source(task) + + context = extract_routing_context(task) + config_version = adjudication.config_version or inventory_sources_runtime_version() + routing_fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context) + + # [STEP 1] 任务级有序 source_codes:从 adjudication.candidates 提取(保序,去重) + task_source_codes_ordered: list[str] = [] + seen_codes: set[str] = set() + for candidate in adjudication.candidates or []: + if not isinstance(candidate, dict): + continue + code = str(candidate.get('source_code') or '').strip().upper() + if not code or code in seen_codes: + continue + seen_codes.add(code) + task_source_codes_ordered.append(code) + + # [STEP 1b] 行级候选:STP 传入 line_projections 则直接解析签名;否则逐行评估 + if line_projections is not None: + signatures: list[tuple[int, str | None, str | None, str | None, list[str]]] = [] + for item in line_projections: + if not isinstance(item, dict): + continue + codes_raw = item.get('candidate_inventory_source_codes') or [] + codes = [str(c or '').strip().upper() for c in codes_raw if str(c or '').strip()] + if not codes: + codes = list(task_source_codes_ordered) + line_index = item.get('line_index') + try: + line_no = int(item.get('line_no') or 0) + except (TypeError, ValueError): + line_no = 0 + if line_no <= 0: + try: + line_no = int(line_index) + 1 + except (TypeError, ValueError): + line_no = len(signatures) + 1 + signatures.append(( + line_no, + str(item.get('source_line_no') or '').strip() or None, + str(item.get('part_number') or '').strip() or None, + str(item.get('reservation_id') or '').strip() or None, + codes, + )) + else: + _proj, signatures = _collect_order_line_candidates( + task, task_level_source_codes_ordered=task_source_codes_ordered, + ) + + if not task_source_codes_ordered: + raise ValueError('冻结服务不接受空候选集合(unresolved/conflicted 应由调用方进入人工阻断)') + + # [STEP 2] input_fingerprint + 幂等查找 + input_fingerprint = _build_input_fingerprint( + routing_fingerprint=routing_fingerprint, + source_codes_ordered=task_source_codes_ordered, + line_signatures=signatures, + config_version=config_version, + ) + existing = _find_existing_frozen_set( + task_id=task.id, review_case_id=review_case_id, + input_fingerprint=input_fingerprint, session=session, + ) + if existing is not None: + sources = list(existing.sources or []) + lines = list(existing.lines or []) + manifest_sha = existing.manifest_snapshot_sha256 or '' + return CandidateFreezeResult( + candidate_set_id=existing.id, + created_new=False, + source_codes=[s.source_code for s in sorted(sources, key=lambda x: x.candidate_order)], + line_count=len(lines), + manifest_snapshot_sha256=manifest_sha, + set_version=int(existing.set_version), + ) + + # [STEP 3] 三张表写入(事务内一起 flush) + routing_rule_version_json = { + 'routing_fingerprint': routing_fingerprint, + 'config_version': config_version, + 'adjudication_method': adjudication.method, + 'adjudication_reason': adjudication.reason, + } + existing_active = ( + session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + if getattr(task, 'active_inventory_candidate_set_id', None) is not None and getattr(task, 'id', None) is not None + else None + ) + set_version = ( + _next_task_set_version(task_id=int(task.id), session=session) + if getattr(task, 'id', None) is not None + else 1 + ) + new_set = ShippingInventoryCandidateSet( + task_id=task.id, + review_case_id=review_case_id, + execution_id=execution_id, + set_version=set_version, + lifecycle_status='frozen', + frozen_at=datetime.utcnow(), + frozen_by_id=frozen_by_id, + input_fingerprint=input_fingerprint, + routing_rule_version_json=routing_rule_version_json, + manifest_snapshot_sha256=None, + remark=None, + ) + session.add(new_set) + session.flush() + + created_sources: list[ShippingInventoryCandidateSource] = [] + for idx, code in enumerate(task_source_codes_ordered): + src_cfg = get_database_inventory_source(code) + rule_id: int | None = None + rule_version: str | None = None + if isinstance(adjudication.evidence, list) and adjudication.evidence: + first_evidence = adjudication.evidence[0] + matched_rule_ids = first_evidence.get('rule_ids') + if isinstance(matched_rule_ids, list) and matched_rule_ids: + try: + _rule_ids_int = int(matched_rule_ids[0]) + from app.models.shipping_inventory_config import ShippingInventoryRoutingRule + rule_row = ( + session.query( + ShippingInventoryRoutingRule.id, + ShippingInventoryRoutingRule.version, + ) + .filter(ShippingInventoryRoutingRule.id == _rule_ids_int) + .one_or_none() + ) + if rule_row is not None: + rule_id = rule_row.id + rule_version = str(rule_row.version) + except (TypeError, ValueError): + rule_id = None + rule_version = None + source = ShippingInventoryCandidateSource( + candidate_set_id=new_set.id, + source_code=code, + candidate_order=idx + 1, + candidate_origin='manual_override' if frozen_by_id is not None else 'rule', + routing_rule_id=rule_id, + routing_rule_version=rule_version or config_version, + source_config_version=( + str(src_cfg.get('config_version')).strip() if isinstance(src_cfg, dict) and src_cfg.get('config_version') else None + ), + override_by_id=frozen_by_id, + override_reason=None, + ) + session.add(source) + created_sources.append(source) + session.flush(created_sources) + + created_lines: list[ShippingInventoryCandidateLine] = [] + for sig in signatures: + line_no, source_line_no, pn, resv, codes_ordered = sig + line_entity = ShippingInventoryCandidateLine( + candidate_set_id=new_set.id, + line_no=line_no, + source_line_no=source_line_no, + part_number=pn, + reservation_id=resv, + source_codes_json=list(codes_ordered), + override_by_id=frozen_by_id, + override_reason=None, + ) + session.add(line_entity) + created_lines.append(line_entity) + session.flush(created_lines) + + # [STEP 4] 写不可变 manifest 副本 + manifest = _build_manifest_snapshot( + task=task, set_db=new_set, + sources_db=created_sources, lines_db=created_lines, + routing_rule_version_json=routing_rule_version_json, + ) + manifest_sha256 = hashlib.sha256( + json.dumps(manifest, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8') + ).hexdigest() + new_set.manifest_snapshot_sha256 = manifest_sha256 + _persist_manifest_snapshot_to_snapshot(task=task, manifest=manifest, session=session) + + if existing_active is not None and int(existing_active.id) != int(new_set.id): + existing_active.lifecycle_status = 'superseded' + existing_active.superseded_at = datetime.utcnow() + existing_active.superseded_by_set_id = int(new_set.id) + _invalidate_task_candidate_outputs(task, session=session) + + if getattr(task, 'id', None) is not None: + task.active_inventory_candidate_set_id = int(new_set.id) + # 新版本不能让旧候选链中的 queued Job/未完成 Gate 继续写事实。 + from app.services.shipping_notice.auto_progress_controller import ( + supersede_auto_progress_for_candidate_refreeze, + ) + + supersede_auto_progress_for_candidate_refreeze(task) + + # [STEP 5] 回填 task 字段(幂等覆盖) + task.inventory_source_status = 'candidates_frozen' + task.inventory_source_method = ( + 'manual_override_freeze' if frozen_by_id is not None + else (adjudication.method or 'rule_evaluation_freeze') + ) + task.inventory_source_config_version = config_version + task.inventory_routing_fingerprint = routing_fingerprint + # 保留 step_payload_json 中已有 inventory_source_resolution,调用方可追加细节 + + return CandidateFreezeResult( + candidate_set_id=new_set.id, + created_new=True, + source_codes=list(task_source_codes_ordered), + line_count=len(created_lines), + manifest_snapshot_sha256=manifest_sha256, + set_version=set_version, + ) diff --git a/backend/app/services/shipping_notice/inventory_candidate_projection.py b/backend/app/services/shipping_notice/inventory_candidate_projection.py new file mode 100644 index 00000000..3444ede7 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_candidate_projection.py @@ -0,0 +1,571 @@ +""" +services/shipping_notice/inventory_candidate_projection.py + +用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。 +依赖:ShippingNotice、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、 + ShippingTaskInventoryRpaAttempt。 +逻辑:正式 Task 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、 + 坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from sqlalchemy.orm import Session + +from app import db +from app.models import ( + ShippingInventoryCandidateLine, + ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, + ShippingNotice, + ShippingNoticeLineInventoryMatch, + ShippingTaskInventoryRpaAttempt, +) + + +INVENTORY_CANDIDATE_LIFECYCLE_FROZEN = 'frozen' +INVENTORY_CANDIDATE_LIFECYCLE_DRAFT = 'draft' +INVENTORY_CANDIDATE_REASON_MISSING = 'inventory_candidates_missing' +INVENTORY_CANDIDATE_REASON_STALE = 'inventory_candidate_version_stale' +INVENTORY_CANDIDATE_REASON_OUT_OF_SCOPE = 'inventory_match_out_of_candidate_scope' + + +def _session(session: Session | None = None) -> Session: + """统一 Session 入口,便于调用方透传事务。""" + return session or db.session + + +def _iso(value: datetime | None) -> str | None: + """将时间序列化为 ISO 字符串。""" + return value.isoformat() if value is not None else None + + +def _normalized_codes(codes: list[Any] | None) -> list[str]: + """规范候选源编码数组并保持顺序去重。""" + out: list[str] = [] + for raw in codes or []: + code = str(raw or '').strip().upper() + if code and code not in out: + out.append(code) + return out + + +def _candidate_set_filter( + task: ShippingNotice, + *, + include_drafts: bool = False, + session: Session | None = None, +) -> list[ShippingInventoryCandidateSet]: + """按 Task 读取候选版本列表;默认隐藏 draft。""" + if getattr(task, 'id', None) is None: + return [] + query = ( + _session(session) + .query(ShippingInventoryCandidateSet) + .filter(ShippingInventoryCandidateSet.task_id == int(task.id)) + ) + if not include_drafts: + query = query.filter( + ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, + ) + rows = ( + query.order_by( + ShippingInventoryCandidateSet.set_version.desc(), + ShippingInventoryCandidateSet.id.desc(), + ) + .all() + ) + return list(rows) + + +def get_active_candidate_set( + task: ShippingNotice, + *, + session: Session | None = None, +) -> ShippingInventoryCandidateSet | None: + """ + 读取正式 Task 当前 frozen CandidateSet。 + + 核心逻辑:严格依赖 ShippingNotice.active_inventory_candidate_set_id; + 指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。 + """ + candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None) + if candidate_set_id is None: + return None + row = _session(session).get(ShippingInventoryCandidateSet, int(candidate_set_id)) + if row is None: + return None + if int(getattr(row, 'task_id', 0) or 0) != int(getattr(task, 'id', 0) or 0): + return None + if str(getattr(row, 'lifecycle_status', '') or '').strip().lower() != INVENTORY_CANDIDATE_LIFECYCLE_FROZEN: + return None + return row + + +def get_active_candidate_sources( + task: ShippingNotice, + *, + session: Session | None = None, +) -> list[ShippingInventoryCandidateSource]: + """读取当前 frozen Set 的任务级候选源。""" + current = get_active_candidate_set(task, session=session) + if current is None: + return [] + rows = ( + _session(session) + .query(ShippingInventoryCandidateSource) + .filter(ShippingInventoryCandidateSource.candidate_set_id == int(current.id)) + .order_by( + ShippingInventoryCandidateSource.candidate_order.asc(), + ShippingInventoryCandidateSource.id.asc(), + ) + .all() + ) + return list(rows) + + +def get_active_candidate_lines( + task: ShippingNotice, + *, + session: Session | None = None, +) -> list[ShippingInventoryCandidateLine]: + """读取当前 frozen Set 的行级候选。""" + current = get_active_candidate_set(task, session=session) + if current is None: + return [] + rows = ( + _session(session) + .query(ShippingInventoryCandidateLine) + .filter(ShippingInventoryCandidateLine.candidate_set_id == int(current.id)) + .order_by( + ShippingInventoryCandidateLine.line_no.asc(), + ShippingInventoryCandidateLine.id.asc(), + ) + .all() + ) + return list(rows) + + +def get_candidate_set_by_version( + task: ShippingNotice, + version: int, + *, + include_drafts: bool = False, + session: Session | None = None, +) -> ShippingInventoryCandidateSet | None: + """按 Task + set_version 读取指定候选版本。""" + if getattr(task, 'id', None) is None: + return None + query = ( + _session(session) + .query(ShippingInventoryCandidateSet) + .filter( + ShippingInventoryCandidateSet.task_id == int(task.id), + ShippingInventoryCandidateSet.set_version == int(version), + ) + ) + if not include_drafts: + query = query.filter( + ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, + ) + return query.order_by(ShippingInventoryCandidateSet.id.desc()).first() + + +def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) -> dict[str, Any] | None: + """序列化 CandidateSet 摘要供 API / Projection 复用。""" + if row is None: + return None + return { + 'id': int(row.id), + 'version': int(row.set_version), + 'status': str(row.lifecycle_status or ''), + 'input_fingerprint': str(row.input_fingerprint or ''), + 'frozen_at': _iso(getattr(row, 'frozen_at', None)), + 'frozen_by': getattr(row, 'frozen_by_id', None), + 'manifest_snapshot_sha256': getattr(row, 'manifest_snapshot_sha256', None), + 'superseded_at': _iso(getattr(row, 'superseded_at', None)), + 'superseded_by_set_id': getattr(row, 'superseded_by_set_id', None), + 'invalidated_at': _iso(getattr(row, 'invalidated_at', None)), + 'invalidated_reason': getattr(row, 'invalidated_reason', None), + 'routing_rule_version_json': dict(getattr(row, 'routing_rule_version_json', None) or {}), + } + + +def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[str, Any]: + """序列化任务级候选源。""" + return { + 'id': int(row.id), + 'candidate_set_id': int(row.candidate_set_id), + 'source_code': str(row.source_code or '').strip().upper(), + 'candidate_order': int(row.candidate_order), + 'candidate_origin': str(row.candidate_origin or ''), + 'routing_rule_id': getattr(row, 'routing_rule_id', None), + 'routing_rule_version': getattr(row, 'routing_rule_version', None), + 'source_config_version': getattr(row, 'source_config_version', None), + 'override_by_id': getattr(row, 'override_by_id', None), + 'override_reason': getattr(row, 'override_reason', None), + } + + +def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, Any]: + """序列化行级候选源与稳定行标识。""" + return { + 'candidate_line_id': int(row.id), + 'candidate_set_id': int(row.candidate_set_id), + 'line_no': int(row.line_no), + 'source_line_no': getattr(row, 'source_line_no', None), + 'part_number': getattr(row, 'part_number', None), + 'reservation_id': getattr(row, 'reservation_id', None), + 'allowed_source_codes': _normalized_codes(getattr(row, 'source_codes_json', None)), + 'override_by_id': getattr(row, 'override_by_id', None), + 'override_reason': getattr(row, 'override_reason', None), + } + + +def _candidate_sources_for_set( + candidate_set: ShippingInventoryCandidateSet | None, + *, + session: Session | None = None, +) -> list[ShippingInventoryCandidateSource]: + """读取指定 CandidateSet 的任务级候选源。""" + if candidate_set is None: + return [] + rows = ( + _session(session) + .query(ShippingInventoryCandidateSource) + .filter(ShippingInventoryCandidateSource.candidate_set_id == int(candidate_set.id)) + .order_by( + ShippingInventoryCandidateSource.candidate_order.asc(), + ShippingInventoryCandidateSource.id.asc(), + ) + .all() + ) + return list(rows) + + +def _candidate_lines_for_set( + candidate_set: ShippingInventoryCandidateSet | None, + *, + session: Session | None = None, +) -> list[ShippingInventoryCandidateLine]: + """读取指定 CandidateSet 的行级候选。""" + if candidate_set is None: + return [] + rows = ( + _session(session) + .query(ShippingInventoryCandidateLine) + .filter(ShippingInventoryCandidateLine.candidate_set_id == int(candidate_set.id)) + .order_by( + ShippingInventoryCandidateLine.line_no.asc(), + ShippingInventoryCandidateLine.id.asc(), + ) + .all() + ) + return list(rows) + + +def build_inventory_candidate_blocking_reason( + code: str, + *, + task: ShippingNotice, + details: dict[str, Any] | None = None, +) -> dict[str, Any]: + """构造统一 blocking_reason DTO。""" + payload = {'task_no': str(task.task_no or '').strip()} + payload.update(details or {}) + return { + 'code': code, + 'i18n_key': f'workspace.shippingNotice.processGate.reasons.{code}', + 'details': payload, + } + + +def build_inventory_candidate_primary_action(code: str = 'open_inventory_source_review') -> dict[str, Any]: + """构造统一主动作 DTO。""" + return { + 'code': code, + 'i18n_key': f'workspace.shippingNotice.processGate.actionCodes.{code}', + 'parameters': {}, + } + + +def _latest_attempts_by_source(task: ShippingNotice, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]: + """查询任务下每个候选源的最新 Attempt 摘要。""" + task_no = str(getattr(task, 'task_no', '') or '').strip() + if not task_no or not source_codes: + return {} + rows = ( + _session(session) + .query(ShippingTaskInventoryRpaAttempt) + .filter( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.source_code.in_(source_codes), + ) + .order_by( + ShippingTaskInventoryRpaAttempt.source_code.asc(), + ShippingTaskInventoryRpaAttempt.attempt_no.desc(), + ShippingTaskInventoryRpaAttempt.id.desc(), + ) + .all() + ) + out: dict[str, dict[str, Any]] = {} + for row in rows: + code = str(row.source_code or '').strip().upper() + if not code or code in out: + continue + out[code] = { + 'source_code': code, + 'attempt_no': int(row.attempt_no), + 'status': str(row.status or ''), + 'run_no': str(row.run_no or ''), + 'error_code': getattr(row, 'error_code', None), + 'error_message': getattr(row, 'error_message', None), + 'inventory_file_no': getattr(row, 'inventory_file_no', None), + 'updated_at': _iso(getattr(row, 'updated_at', None)), + } + return out + + +def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str, Any]]) -> tuple[list[str], list[str], list[str]]: + """按最新 Attempt 状态聚合 prepared / pending / failed 源列表。""" + prepared: list[str] = [] + pending: list[str] = [] + failed: list[str] = [] + for code in source_codes: + status = str((attempt_map.get(code) or {}).get('status') or '').strip().lower() + if status in {'succeeded', 'consumed'}: + prepared.append(code) + elif status in {'queued', 'running'}: + pending.append(code) + elif status in {'failed', 'exhausted', 'superseded'}: + failed.append(code) + return prepared, pending, failed + + +def _current_match_rows(task: ShippingNotice, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]: + """读取任务当前生效的行级匹配事实。""" + if getattr(task, 'id', None) is None: + return [] + rows = ( + _session(session) + .query(ShippingNoticeLineInventoryMatch) + .filter( + ShippingNoticeLineInventoryMatch.task_id == int(task.id), + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ) + .order_by( + ShippingNoticeLineInventoryMatch.line_index.asc(), + ShippingNoticeLineInventoryMatch.id.asc(), + ) + .all() + ) + return list(rows) + + +def project_inventory_candidate_detail( + task: ShippingNotice, + *, + version: str | int = 'current', + session: Session | None = None, + include_history: bool = False, + include_drafts: bool = False, +) -> dict[str, Any]: + """ + 投影候选详情 API 所需的当前版或指定版详情。 + + 核心逻辑:默认返回当前 active frozen Set;指定 version 时返回该版本的源/行详情, + 同时 history 仅返回摘要,默认排除 draft。 + """ + sess = _session(session) + current = get_active_candidate_set(task, session=sess) + selected = current + if version != 'current': + try: + selected = get_candidate_set_by_version( + task, + int(version), + include_drafts=include_drafts, + session=sess, + ) + except (TypeError, ValueError): + selected = None + + history: list[dict[str, Any]] = [] + if include_history: + history = [ + serialize_candidate_set_summary(row) + for row in _candidate_set_filter(task, include_drafts=include_drafts, session=sess) + if row is not None + ] + + if selected is None: + return { + 'current_set': None, + 'sources': [], + 'lines': [], + 'history': history, + 'blocking_reason': build_inventory_candidate_blocking_reason( + INVENTORY_CANDIDATE_REASON_MISSING, + task=task, + ), + 'primary_action': build_inventory_candidate_primary_action(), + } + + return { + 'current_set': serialize_candidate_set_summary(selected), + 'sources': [serialize_candidate_source(row) for row in _candidate_sources_for_set(selected, session=sess)], + 'lines': [serialize_candidate_line(row) for row in _candidate_lines_for_set(selected, session=sess)], + 'history': history, + 'blocking_reason': None, + 'primary_action': None, + } + + +def project_inventory_candidate_facts( + task: ShippingNotice, + *, + session: Session | None = None, + include_history: bool = False, +) -> dict[str, Any]: + """ + 统一投影任务当前候选事实。 + + 核心逻辑: + [STEP 1] 严格读取 active frozen CandidateSet; + [STEP 2] 聚合 Source / Line / Attempt / Match 事实; + [STEP 3] 检测 missing / stale / out_of_scope 并输出统一阻断信息。 + """ + sess = _session(session) + current = get_active_candidate_set(task, session=sess) + if current is None: + return { + 'current_set': None, + 'sources': [], + 'lines': [], + 'history': [], + 'candidate_set_id': None, + 'candidate_set_version': None, + 'candidate_set_status': None, + 'candidate_source_codes': [], + 'prepared_source_codes': [], + 'pending_source_codes': [], + 'failed_source_codes': [], + 'source_attempts': {}, + 'line_resolutions': [], + 'blocking_reason': build_inventory_candidate_blocking_reason( + INVENTORY_CANDIDATE_REASON_MISSING, task=task, + ), + 'primary_action': build_inventory_candidate_primary_action(), + } + + sources = get_active_candidate_sources(task, session=sess) + lines = get_active_candidate_lines(task, session=sess) + source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()] + attempt_map = _latest_attempts_by_source(task, source_codes, session=sess) + prepared_codes, pending_codes, failed_codes = _classify_sources(source_codes, attempt_map) + + line_by_id = {int(row.id): row for row in lines} + serialized_matches: list[dict[str, Any]] = [] + stale_details: dict[str, Any] | None = None + out_of_scope_details: dict[str, Any] | None = None + for row in _current_match_rows(task, session=sess): + allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None)) + serialized = { + 'id': int(row.id), + 'line_key': str(row.line_key or ''), + 'line_index': getattr(row, 'line_index', None), + 'disposition': dict(getattr(row, 'detail_json', None) or {}).get('disposition'), + 'candidate_set_id': getattr(row, 'candidate_set_id', None), + 'candidate_set_version': getattr(row, 'candidate_set_version', None), + 'candidate_line_id': getattr(row, 'candidate_line_id', None), + 'allowed_source_codes_snapshot': allowed_codes, + 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'inventory_file_no': getattr(row, 'matched_file_no', None), + 'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None), + 'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')), + 'required_qty': getattr(row, 'required_qty', None), + 'matched_qty': getattr(row, 'matched_qty', None) or getattr(row, 'available_qty', None), + 'match_result': getattr(row, 'match_result', None), + 'evidence_checksum': getattr(row, 'evidence_checksum', None), + } + serialized_matches.append(serialized) + + if int(getattr(row, 'candidate_set_id', 0) or 0) != int(current.id): + stale_details = { + 'expected_candidate_set_id': int(current.id), + 'expected_candidate_set_version': int(current.set_version), + 'actual_candidate_set_id': getattr(row, 'candidate_set_id', None), + 'actual_candidate_set_version': getattr(row, 'candidate_set_version', None), + 'detected_at': datetime.utcnow().isoformat(), + 'operation_id': f'match-row:{int(row.id)}', + } + candidate_line_id = getattr(row, 'candidate_line_id', None) + if candidate_line_id is not None: + line_row = line_by_id.get(int(candidate_line_id)) + if line_row is None: + stale_details = { + 'expected_candidate_set_id': int(current.id), + 'expected_candidate_set_version': int(current.set_version), + 'actual_candidate_set_id': getattr(row, 'candidate_set_id', None), + 'actual_candidate_set_version': getattr(row, 'candidate_set_version', None), + 'detected_at': datetime.utcnow().isoformat(), + 'operation_id': f'match-line:{int(row.id)}', + } + elif ( + str(getattr(row, 'inventory_source_code', '') or '').strip().upper() + and allowed_codes + and str(getattr(row, 'inventory_source_code', '') or '').strip().upper() not in allowed_codes + ): + out_of_scope_details = { + 'candidate_line_id': int(candidate_line_id), + 'expected_candidate_set_id': int(current.id), + 'expected_candidate_set_version': int(current.set_version), + 'actual_candidate_set_id': getattr(row, 'candidate_set_id', None), + 'actual_candidate_set_version': getattr(row, 'candidate_set_version', None), + 'detected_at': datetime.utcnow().isoformat(), + 'operation_id': f'match-line:{int(row.id)}', + 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'allowed_source_codes_snapshot': allowed_codes, + } + + history: list[dict[str, Any]] = [] + if include_history: + history = [ + serialize_candidate_set_summary(row) + for row in _candidate_set_filter(task, include_drafts=False, session=sess) + if row is not None + ] + + result: dict[str, Any] = { + 'current_set': serialize_candidate_set_summary(current), + 'sources': [serialize_candidate_source(row) for row in sources], + 'lines': [serialize_candidate_line(row) for row in lines], + 'history': history, + 'candidate_set_id': int(current.id), + 'candidate_set_version': int(current.set_version), + 'candidate_set_status': str(current.lifecycle_status or ''), + 'candidate_source_codes': source_codes, + 'prepared_source_codes': prepared_codes, + 'pending_source_codes': pending_codes, + 'failed_source_codes': failed_codes, + 'source_attempts': attempt_map, + 'line_resolutions': serialized_matches, + } + if out_of_scope_details is not None: + result['blocking_reason'] = build_inventory_candidate_blocking_reason( + INVENTORY_CANDIDATE_REASON_OUT_OF_SCOPE, + task=task, + details=out_of_scope_details, + ) + result['primary_action'] = build_inventory_candidate_primary_action() + elif stale_details is not None: + result['blocking_reason'] = build_inventory_candidate_blocking_reason( + INVENTORY_CANDIDATE_REASON_STALE, + task=task, + details=stale_details, + ) + result['primary_action'] = build_inventory_candidate_primary_action() + return result diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index dc80eb6f..32b1f020 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -1017,13 +1017,49 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]: db.session.flush() from app.services.shipping_notice.fulfillment_workflow import match_inventory trusted_uid = payload.get("_trusted_user_id") - return match_inventory({ + # [T6 选择性重匹] 默认只重匹 match_result≠matched 行;force_full_rematch=true 才全量重匹。 + # 实现:非全量模式先把 line_matches 中 is_current=true 且 match_result≠matched 的条目 + # 置为 is_current=false,待 match_inventory 补齐;已 matched 的保留不覆盖,避免稳定证据哈希失效。 + force_full = False + if isinstance(payload, dict): + force_flag = payload.get('force_full_rematch') or payload.get('force_full') or payload.get('full_rematch') + force_full = bool(force_flag and str(force_flag).lower() not in {'0', 'false', 'no', 'none', ''}) + if not force_full and task.id is not None: + from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch + cleared = ( + db.session.query(ShippingNoticeLineInventoryMatch) + .filter( + ShippingNoticeLineInventoryMatch.task_id == int(task.id), + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.match_result != 'matched', + ) + .update( + { + 'is_current': False, + 'updated_at': datetime.now(timezone.utc), + }, + synchronize_session=False, + ) + ) + log_task_event( + task, + 'match_inventory_selective_reset', + { + 'cleared_pending_count': int(cleared or 0), + 'force_full_rematch': False, + }, + actor_id=trusted_uid, + source='workspace_api' if trusted_uid else 'system', + ) + rematch_payload = { "task_id": task.task_no, "_trusted_user_id": trusted_uid, "operator_id": trusted_uid, "actor_id": trusted_uid, "event_source": "workspace_api" if trusted_uid else "system", - }) + "force_full_rematch": force_full, + } + return match_inventory(rematch_payload) adjudication = confirm_task_inventory_source( task, @@ -1526,6 +1562,7 @@ def _handle_rpa_inventory_failed( def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: """RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。""" from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler cleanup_retry_warnings = flush_callback_cleanup_queue() @@ -1533,6 +1570,82 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message="未找到任务编号") + # [T7 统一回调幂等] 尝试按 per-source run_no 提取 source_code;如符合 PSR-*--A-* 格式则先入 per_source_callback_handler + run_no_raw = str(payload.get("run_no") or "").strip() + source_code_from_run: str | None = None + if run_no_raw and run_no_raw.startswith('PSR-'): + # PSR---A- → 第 3 段 = SOURCE + parts = run_no_raw.split('-') + if len(parts) >= 4 and parts[3].startswith('A'): + candidate = str(parts[2] or '').strip().upper() + if candidate: + source_code_from_run = candidate + per_source_result = None + if source_code_from_run and run_no_raw: + per_source_code, _attempt = per_source_callback_handler( + task, + source_code=source_code_from_run, + run_no=run_no_raw, + callback_payload=dict(payload), + ) + per_source_result = per_source_code + if per_source_code == 'idempotent_ok': + return tool_response( + status="success", + task=task, + message="RPA 回调已处理(幂等),无需重复写入。", + data={ + "run_no": run_no_raw, + "source_code": source_code_from_run, + "retry_safe": True, + "idempotent": True, + }, + ) + if per_source_code == 'superseded_late': + log_task_event( + task, + 'late_rpa_callback_ignored', + { + 'run_no': run_no_raw, + 'source_code': source_code_from_run, + 'reason': 'superseded_by_newer_run', + }, + source='rpa_callback', + ) + return tool_response( + status="success", + task=task, + message="RPA 回调已过期(同源更新的 run 已处理),本回调忽略。", + data={ + "run_no": run_no_raw, + "source_code": source_code_from_run, + "late": True, + "retry_safe": True, + }, + ) + if per_source_code == 'task_terminal': + return tool_response( + status="success", + task=task, + message="任务已处于终态(完成/作废/失败终止),回调忽略。", + data={ + "run_no": run_no_raw, + "source_code": source_code_from_run, + "task_terminal": True, + "retry_safe": True, + }, + ) + if per_source_code == 'failed': + return tool_response( + status="failed", + task=task, + message=f"RPA 回调在源 {source_code_from_run} 侧已标记失败,见回调 payload。", + data={ + "run_no": run_no_raw, + "source_code": source_code_from_run, + }, + ) + task = _lock_task_for_rpa_callback(task) gate_resp = _validate_rpa_callback_gate(task) @@ -1811,7 +1924,17 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: cleanup_retry_warnings = flush_callback_cleanup_queue() - run_no = str(payload.get("run_no") or "").strip() + if payload.get('schema_version') != 'shipping_inventory_rpa.v2': + return tool_response(status='failed', message='callback_schema_invalid', data={ + 'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid', + }) + callback_id = str(payload.get('callback_id') or '').strip() + batch_run_no = str(payload.get('batch_run_no') or '').strip() + if not callback_id or not batch_run_no: + return tool_response(status='failed', message='callback_schema_invalid', data={ + 'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid', + }) + run_no = batch_run_no schedule_run_id = payload.get("schedule_run_id") try: schedule_run_id = int(schedule_run_id) if schedule_run_id is not None else None @@ -1845,6 +1968,17 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: warehouse_id = str(merged_item.get("warehouse_id") or "").strip().upper() raw_status = _normalize_rpa_inventory_batch_item_status(merged_item) task_no = str(merged_item.get("task_no") or "").strip() + run_no_item = str(merged_item.get("run_no") or "").strip() or run_no + source_run_no_item = str(merged_item.get("source_run_no") or "").strip() + item_callback_id = str(merged_item.get("callback_id") or "").strip() + if not item_callback_id and source_run_no_item: + item_callback_id = f"{callback_id}:{source_run_no_item}:C1" + if item_callback_id: + from app.models import ShippingTaskInventoryRpaAttempt + replay_attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(callback_id=item_callback_id).one_or_none() + if replay_attempt is not None: + skipped.append({"source_code": source_code, "task_no": task_no or None, "source_run_no": source_run_no_item, "callback_id": item_callback_id, "reason": "replayed", "original_business_status": replay_attempt.transaction_status or replay_attempt.status, "replayed": True}) + continue task: ShippingNotice | None = None if task_no: task = resolve_task_from_payload({"task_id": task_no, "task_no": task_no}) @@ -1856,6 +1990,56 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: "error": "task_not_found", }) continue + # [T7 批量回调幂等] 每个 item 先走 per_source_callback_handler;batch 中单独处理不中断整体 + if source_code and source_run_no_item and raw_status != 'success': + from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler + per_source_code, _a = per_source_callback_handler( + task, + source_code=source_code, + run_no=source_run_no_item, + callback_payload=dict(merged_item), + ) + if per_source_code == 'idempotent_ok': + skipped.append({ + "source_code": source_code, + "warehouse_id": warehouse_id, + "task_no": task_no, + "run_no": run_no_item, + "reason": "idempotent_ok", + "retry_safe": True, + }) + continue + if per_source_code == 'superseded_late': + log_task_event( + task, + 'late_rpa_callback_ignored', + { + 'run_no': run_no_item, + 'source_code': source_code, + 'reason': 'superseded_by_newer_run', + 'batch': True, + }, + source='rpa_callback', + ) + skipped.append({ + "source_code": source_code, + "warehouse_id": warehouse_id, + "task_no": task_no, + "run_no": run_no_item, + "reason": "superseded_late", + "retry_safe": True, + }) + continue + if per_source_code == 'task_terminal': + skipped.append({ + "source_code": source_code, + "warehouse_id": warehouse_id, + "task_no": task_no, + "run_no": run_no_item, + "reason": "task_terminal", + "retry_safe": True, + }) + continue task = _lock_task_for_rpa_callback(task) if task and raw_status in {"skipped", "failed"}: @@ -1937,14 +2121,30 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: if raw_status == "success": file_path = str(merged_item.get("file_path") or "").strip() - path = Path(file_path) if file_path else None + path = Path(file_path).resolve() if file_path else None + from app.services.shipping_notice.rpa import inventory_drop_dir + allowed_root = inventory_drop_dir() + if path and allowed_root: + try: + path.relative_to(allowed_root.resolve()) + except ValueError: + path = None if not path or not path.is_file(): failed.append({ "source_code": source_code, "warehouse_id": warehouse_id, "error": "file_missing", }) + if task_no and source_run_no_item: + from app.models import ShippingTaskInventoryRpaAttempt + _att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none() + if _att: + _att.callback_id = item_callback_id or callback_id + _att.callback_received_at = datetime.utcnow(); _att.file_generated = False; _att.file_exists_at_callback = False + _att.execution_phase = 'callback_rejected'; _att.transaction_status = 'rejected'; _att.error_code = 'file_missing' continue + server_hash = hashlib.sha256(path.read_bytes()).hexdigest() + server_size = path.stat().st_size if task: gate_resp = _validate_rpa_callback_inventory_source(task, merged_item) @@ -1993,7 +2193,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: source=source, local_path=path, source_file_name=path.name, - rpa_run_no=run_no or None, + rpa_run_no=str(merged_item.get('source_run_no') or run_no) or None, schedule_run_id=schedule_run_id, trigger_type=str(payload.get("trigger_type") or "scheduled"), success=True, @@ -2025,11 +2225,19 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: "source_code": inv_file.source_code or source_code, "warehouse_id": inv_file.warehouse_id or warehouse_id, "reused_existing_snapshot": not created_new, + "callback_id": callback_id, + "file_sha256": server_hash, + "file_size": server_size, "structure_validation": { "level": structure_check["level"], "difference": structure_check["difference"], }, } + if task_no and source_run_no_item: + from app.models import ShippingTaskInventoryRpaAttempt + _att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none() + if _att: + _att.callback_id = item_callback_id or callback_id; _att.callback_received_at = datetime.utcnow(); _att.file_generated = True; _att.file_path = str(path); _att.file_sha256 = server_hash; _att.file_size = server_size; _att.file_exists_at_callback = True; _att.execution_phase = 'callback_received'; _att.transaction_status = 'succeeded' created.append(created_entry) if item_orphan_path: batch_new_storage_paths.append(item_orphan_path) diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py index ac1041c7..7da18f39 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -22,6 +22,9 @@ from app.services.shipping_notice.inventory_source_rules import ( extract_routing_context, resolve_ambiguous_source_from_ready_snapshots, ) +from app.services.shipping_notice.inventory_candidate_freeze_service import ( + freeze_candidates_for_task, +) from app.services.shipping_notice.inventory_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, @@ -247,6 +250,51 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour evidence=adjudication.evidence, reason=adjudication.reason, ) + + # [T3: 决策 A1 + C1] ambiguous 且有候选时,不再进入 inventory_source_review 人工阻断; + # 多库存源是合法自动链路,直接冻结到 Set/Source/Line 结构化表 + Snapshot JSON 副本, + # 状态升级为 candidates_frozen(属于 STABLE_INVENTORY_SOURCE_STATUSES,可进入库存准备)。 + # 零候选 / conflicted / unresolved 等情况仍保持旧逻辑进入人工复核。 + if ( + adjudication.status == "ambiguous" + and getattr(task, "id", None) is not None + and any( + isinstance(c, dict) and str(c.get("source_code") or "").strip() + for c in (adjudication.candidates or []) + ) + ): + try: + freeze_result = freeze_candidates_for_task(task, adjudication=adjudication) + # 冻结成功后升级裁决为 candidates_frozen;apply_inventory_source_adjudication 会再写一次字段, + # 但冻结服务已写好 task.status=method=config=fingerprint,结果一致。 + evidence_merged = list(adjudication.evidence or []) + evidence_merged.append({ + "candidate_freeze": { + "set_id": freeze_result.candidate_set_id, + "manifest_snapshot_sha256": freeze_result.manifest_snapshot_sha256, + "source_codes_ordered": freeze_result.source_codes, + "line_count": freeze_result.line_count, + "created_new": freeze_result.created_new, + } + }) + adjudication = InventorySourceAdjudication( + status="candidates_frozen", + method=adjudication.method or "rule_evaluation_freeze", + source_code=None, + connector_type=None, + warehouse_id=None, + config_version=adjudication.config_version or inventory_sources_runtime_version(), + routing_fingerprint=adjudication.routing_fingerprint or compute_routing_fingerprint(context), + candidates=adjudication.candidates, + destination_candidates=adjudication.destination_candidates, + evidence=evidence_merged, + reason=f"ambiguous_frozen:{freeze_result.candidate_set_id}", + ) + except ValueError: + # 冻结服务抛 ValueError = 候选集合为空(保护分支,正常应命中不进入), + # 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入人工阻断。 + pass + apply_inventory_source_adjudication(task, adjudication) return adjudication diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index cfaaa934..8b800656 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -238,6 +238,28 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: + # [T5 Orchestrator 守卫]:外部直接调用 → 收口到 run_task_auto_progress 并发锁; + # Orchestrator 内部分派调用(_orchestrator_internal_dispatch=True)→ 直接执行下方实现。 + if not payload.get('_orchestrator_internal_dispatch', False): + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip() + if not task_no and isinstance(payload, dict): + t = resolve_task_from_payload(payload) + task_no = str(getattr(t, 'task_no', '') or '').strip() + trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_ensure_inventory').strip() + actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id") + try: + operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None + except (TypeError, ValueError): + operator_id = None + return run_task_auto_progress( + task_no, trigger=trigger, + expected_version=None, + idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, + resume_gate_code='inventory_preparation', + operator_id=operator_id, + inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto', + ) lang = resolve_lang(payload) task = resolve_task_from_payload(payload) if not task: @@ -277,6 +299,33 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: frozen_codes = task_frozen_inventory_source_codes(task) if len(frozen_codes) > 1 or str(task.inventory_source_status or '').strip() == 'candidates_frozen': prep = prepare_candidate_inventory_lines(task) + if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing': + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + set_task_step_progress( + task, + step_key="step3_inventory_prepare", + step_title="获取库存", + status="needs_human", + message=t("workflow.inventory.unavailable", lang=lang), + progress_percent=0, + detail=t("workflow.inventory.unavailable", lang=lang), + ) + log_task_event(task, "inventory_candidate_version_stale", { + 'error_code': prep.get('error_code'), + }) + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message=t("workflow.inventory.unavailable", lang=lang), + data={ + **serialize_task_for_tool(task), + 'blocking_reason': { + 'code': prep.get('error_code'), + 'primary_action': 'open_inventory_source_review', + }, + }, + ) if prep.get('status') == 'missing_files': apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( diff --git a/backend/app/services/shipping_notice/legacy_stp_job_admin_service.py b/backend/app/services/shipping_notice/legacy_stp_job_admin_service.py new file mode 100644 index 00000000..a8c5ca75 --- /dev/null +++ b/backend/app/services/shipping_notice/legacy_stp_job_admin_service.py @@ -0,0 +1,297 @@ +""" +backend/app/services/shipping_notice/legacy_stp_job_admin_service.py + +用途:Phase 5-1 —— 管理员历史 STP Job 面板的只读投影服务(928/929 运维面板专用)。 +依赖:models.job.Job、JobType(若有)、ShippingOrderReviewCase。 +逻辑: + 1. list_admin_legacy_stp_jobs —— 按 domain=shipping_notice + job_type=shipping_stp_auto_create + + status IN {failed,dead} 分页返回;支持筛选 case_no / q / error_code / created_from / created_to。 + 2. get_admin_legacy_stp_job —— 单条 Job 详情 + 关联 Review Case(若可通过 reference_key==case_no 回链)。 +禁止事项(严格 fail-closed): + • 不允许写任何数据(禁 Job.status 修改,禁 db.session.commit/add/flush 等)。 + • 不输出敏感字段(result_json 中若含 token/password 自动脱敏)。 + • 所有接口仅 allow_admin,路由层 require_admin 再守门一道。 +""" + +from __future__ import annotations + +import re +from datetime import datetime +from typing import Any + +from sqlalchemy import and_, or_ + +from app import db + + +# 失败 / 死 Job 白名单:历史 928/929 仅针对 shipping_stp_auto_create +_LEGACY_DOMAIN = 'shipping_notice' +_LEGACY_JOB_TYPES: frozenset[str] = frozenset({ + 'shipping_stp_auto_create', +}) +_LEGACY_STATUSES: frozenset[str] = frozenset({'failed', 'dead'}) + +# 脱敏正则(非常粗:防止 secret/password/token/key 等明文进入管理面板) +_SENSITIVE_KEY_RE = re.compile( + r'(password|passwd|secret|token|api[_-]?key|credential|authorization)', + flags=re.IGNORECASE, +) + + +def _mask_sensitive(obj: Any) -> Any: + """递归递归脱敏 dict/list 中疑似密钥字段的值(fail-safe,不抛错)。""" + if isinstance(obj, dict): + out: dict[str, Any] = {} + for k, v in obj.items(): + if isinstance(k, str) and _SENSITIVE_KEY_RE.search(k): + out[k] = '***MASKED***' + else: + out[k] = _mask_sensitive(v) + return out + if isinstance(obj, list): + return [_mask_sensitive(i) for i in obj] + if isinstance(obj, tuple): + return tuple(_mask_sensitive(i) for i in obj) + return obj + + +def _serialize_job_row(job) -> dict[str, Any]: + """把 Job ORM 行 → 管理员摘要 JSON(只读投影)。""" + result_json = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {} + payload_json = dict(job.payload_json or {}) if isinstance(job.payload_json, dict) else {} + blocking_reason = ( + result_json.get('blocking_reason') + or result_json.get('reason_code') + or result_json.get('error_code') + or None + ) + if isinstance(blocking_reason, dict): + blocking_reason = blocking_reason.get('code') if isinstance(blocking_reason.get('code'), str) else None + return { + 'job_id': int(job.id), + 'domain': str(job.domain or ''), + 'job_type': str(job.job_type or ''), + 'status': str(job.status or ''), + 'business_ref': str(job.business_ref or ''), + 'reference_key': str(getattr(job, 'reference_key', None) or ''), # 兼容旧 Job + 'case_no': ( + str(getattr(job, 'reference_key', None) or '') or + str(payload_json.get('case_no') or '') or None + ), + 'priority': int(job.priority or 0), + 'attempts': int(job.attempts or 0), + 'max_attempts': int(job.max_attempts or 0), + 'message': str(job.message or '') or None, + 'error_message': str(job.error_message or '') or None, + 'error_code': str(result_json.get('error_code') or ''), + 'blocking_reason': (str(blocking_reason) if blocking_reason else None), + 'retryable': bool(result_json.get('retryable')) if result_json.get('retryable') is not None else None, + 'next_action': result_json.get('next_action'), + 'retry_of_job_id': (int(job.retry_of_job_id) if job.retry_of_job_id else None), + 'created_by_id': (int(job.created_by_id) if job.created_by_id else None), + 'result_json_masked': _mask_sensitive(result_json), + 'payload_json_masked': _mask_sensitive(payload_json), + 'created_at': str(job.created_at.isoformat()) if isinstance(job.created_at, datetime) else None, + 'updated_at': str(job.updated_at.isoformat()) if isinstance(job.updated_at, datetime) else None, + 'started_at': str(job.started_at.isoformat()) if isinstance(job.started_at, datetime) else None, + 'finished_at': str(job.finished_at.isoformat()) if isinstance(job.finished_at, datetime) else None, + } + + +def _parse_iso_dt(value: str | None, *, field: str): + """解析可选 ISO 日期时间;抛 ValidationError。""" + from app.core.errors import ValidationError + + if value in (None, ''): + return None + try: + text = str(value).strip() + if text.endswith('Z'): + text = text[:-1] + '+00:00' + return datetime.fromisoformat(text) + except ValueError as exc: + raise ValidationError(f'{field} must be ISO datetime (YYYY-MM-DDTHH:MM:SS)') from exc + + +def list_admin_legacy_stp_jobs( + *, + page: int = 1, + page_size: int = 25, + status: str | None = None, + job_type: str | None = None, + q: str | None = None, + case_no: str | None = None, + error_code: str | None = None, + blocking_reason: str | None = None, + created_from: str | None = None, + created_to: str | None = None, + sort: str = '-created_at', +) -> dict[str, Any]: + """ + 管理员只读列表:domain=shipping_notice + job_type=shipping_stp_auto_create + status IN {failed, dead}。 + 用于运维面板快速定位历史 928/929 这类失败死 Job。 + """ + from app.core.errors import ValidationError + from app.models.job import Job + from app import db # type: ignore + + if not isinstance(page, int) or page < 1: + raise ValidationError('page must be positive integer') + if not isinstance(page_size, int) or not 1 <= page_size <= 100: + raise ValidationError('page_size must be between 1 and 100') + if status and str(status) not in _LEGACY_STATUSES: + raise ValidationError(f'status must be one of: {sorted(_LEGACY_STATUSES)}') + if job_type and str(job_type) not in _LEGACY_JOB_TYPES: + raise ValidationError(f'job_type must be one of: {sorted(_LEGACY_JOB_TYPES)}') + + created_from_dt = _parse_iso_dt(created_from, field='created_from') + created_to_dt = _parse_iso_dt(created_to, field='created_to') + + # 只拿失败/死 STP Job + where = [ + Job.domain == _LEGACY_DOMAIN, + Job.job_type.in_(list(_LEGACY_JOB_TYPES)), + Job.status.in_(list(_LEGACY_STATUSES)), + ] + if status: + where.append(Job.status == str(status)) + if job_type: + where.append(Job.job_type == str(job_type)) + if case_no: + case_no_s = str(case_no).strip() + where.append(or_( + getattr(Job, 'reference_key', None) == case_no_s + if hasattr(Job, 'reference_key') + else False, + # 兼容旧模型:从 payload_json->case_no 查(JSON 跨库差异大,仅包含匹配) + Job.payload_json.contains({'case_no': case_no_s}), + )) + if error_code: + where.append(Job.result_json.contains({'error_code': str(error_code).strip()})) + if blocking_reason: + br = str(blocking_reason).strip() + where.append(or_( + Job.result_json.contains({'blocking_reason': br}), + Job.result_json.contains({'reason_code': br}), + )) + if created_from_dt is not None: + where.append(Job.created_at >= created_from_dt) + if created_to_dt is not None: + where.append(Job.created_at <= created_to_dt) + if q and str(q).strip(): + qs = f'%{str(q).strip()}%' + where.append(or_( + Job.business_ref.ilike(qs), + Job.message.ilike(qs), + Job.error_message.ilike(qs), + )) + + # 排序 + sort_exprs = [] + for raw in str(sort or '-created_at').split(','): + s = raw.strip() + if not s: + continue + descending = s.startswith('-') + key = s[1:] if descending else s + if key == 'created_at': + expr = Job.created_at.desc() if descending else Job.created_at.asc() + elif key == 'updated_at': + expr = Job.updated_at.desc() if descending else Job.updated_at.asc() + elif key == 'id': + expr = Job.id.desc() if descending else Job.id.asc() + elif key == 'attempts': + expr = Job.attempts.desc() if descending else Job.attempts.asc() + else: + continue + sort_exprs.append(expr) + if not sort_exprs: + sort_exprs = [Job.created_at.desc()] + + stmt = db.select(Job).where(and_(*where)).order_by(*sort_exprs) + total = len(db.session.scalars(db.select(Job.id).where(and_(*where))).all()) + items = db.session.scalars( + stmt.offset((int(page) - 1) * int(page_size)).limit(int(page_size)), + ).all() + return { + 'items': [_serialize_job_row(j) for j in items], + 'pagination': { + 'page': int(page), + 'page_size': int(page_size), + 'total': int(total), + 'total_pages': ((int(total) + int(page_size) - 1) // int(page_size)) if total > 0 else 0, + }, + 'filters': { + 'domain': _LEGACY_DOMAIN, + 'job_types': sorted(_LEGACY_JOB_TYPES), + 'statuses': sorted(_LEGACY_STATUSES), + }, + } + + +def get_admin_legacy_stp_job(job_id: int) -> dict[str, Any]: + """ + 管理员单条历史 STP Job 详情:返回 Job 投影 + 回链 Review Case(若 reference_key==case_no 存在)。 + 仅允许失败/死 Job:若 Job 是 queued/running → 抛 ValidationError(避免管理员误对活跃 Job 做 replay)。 + """ + from app.core.errors import NotFoundError, ValidationError + from app.models.job import Job + from app.models.shipping.shipping_order_review_case import ShippingOrderReviewCase + + job = db.session.get(Job, int(job_id)) + if job is None: + raise NotFoundError(f'legacy job not found: {job_id}', code='SHIPPING.REVIEW_CASE_NOT_FOUND') + if str(job.domain or '') != _LEGACY_DOMAIN: + raise ValidationError(f'legacy job must be domain={_LEGACY_DOMAIN}') + if str(job.job_type or '') not in _LEGACY_JOB_TYPES: + raise ValidationError(f'legacy job must be job_type in {sorted(_LEGACY_JOB_TYPES)}') + if str(job.status or '') not in _LEGACY_STATUSES: + raise ValidationError( + f'legacy job must be status in {sorted(_LEGACY_STATUSES)} (current={job.status})', + code='SHIPPING.RECONCILE_INVALID_USER_ACTION', + ) + job_row = _serialize_job_row(job) + + # 回链 Review Case(只读:若能通过 reference_key==case_no 找得到) + case_no = ( + str(getattr(job, 'reference_key', None) or '') + or str((job.payload_json or {}).get('case_no') or '') + or None + ) + case_row: dict[str, Any] | None = None + if case_no: + case_obj = ( + ShippingOrderReviewCase.query + .filter_by(case_no=str(case_no).strip()) + .order_by(ShippingOrderReviewCase.id.desc()) + .first() + ) + if case_obj is not None: + case_row = { + 'case_id': int(case_obj.id), + 'case_no': str(case_obj.case_no or ''), + 'status': str(case_obj.status or ''), + 'candidate_id': int(case_obj.candidate_id) if case_obj.candidate_id else None, + 'confirmed_task_id': int(case_obj.confirmed_task_id) if case_obj.confirmed_task_id else None, + 'document_id': int(case_obj.document_id) if case_obj.document_id else None, + 'owner_user_id': int(case_obj.owner_user_id) if case_obj.owner_user_id else None, + 'created_at': str(case_obj.created_at.isoformat()) if getattr(case_obj, 'created_at', None) else None, + 'updated_at': str(case_obj.updated_at.isoformat()) if getattr(case_obj, 'updated_at', None) else None, + } + return { + 'job': job_row, + 'case': case_row, + 'replay_plan': { + 'supported': True, + 'recommended_user_action': ( + 'force_create' + if case_row and str(case_row.get('status') or '') in {'draft', 'ready', 'unreviewed'} + else 'create_revision' + ), + 'needs_replay_mode': bool(case_row and job_row.get('case_no') != case_row.get('case_no')), + 'reconcile_and_progress_endpoint': ( + f'/workspace/shipping-notice/order-review-cases/{case_no}/reconcile-and-progress' + if case_no else None + ), + }, + } diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_inventory_match_persistence.py index 74f5a8c0..2f40f86d 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_persistence.py +++ b/backend/app/services/shipping_notice/line_inventory_match_persistence.py @@ -9,6 +9,7 @@ services/shipping_notice/line_inventory_match_persistence.py from __future__ import annotations +import hashlib from datetime import datetime from typing import Any @@ -18,6 +19,10 @@ from app.models import ( ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ) +from app.services.shipping_notice.inventory_candidate_projection import ( + get_active_candidate_lines, + get_active_candidate_set, +) def _draft_line_keys_by_index(case: ShippingOrderReviewCase | None) -> dict[int, str]: @@ -68,6 +73,8 @@ def map_disposition_to_match_codes( res = str(reservation_id or '').strip() if disp == 'multi_file_conflict': return 'source_conflict', 'source_conflict' + if disp == 'invalid': + return 'invalid', 'invalid' if not part or not res: return 'invalid_key', 'invalid_key' if disp == 'not_found': @@ -110,6 +117,11 @@ def persist_line_inventory_match_facts( written: list[ShippingNoticeLineInventoryMatch] = [] now = datetime.utcnow() + current_candidate_set = get_active_candidate_set(task) + candidate_lines_by_no = { + int(row.line_no): row + for row in get_active_candidate_lines(task) + } for result in line_results: try: @@ -134,6 +146,12 @@ def persist_line_inventory_match_facts( required = result.get('required_qty') available = result.get('available_qty') shortage = result.get('shortage_qty') + candidate_line = candidate_lines_by_no.get(index + 1) + allowed_source_codes = ( + list(getattr(candidate_line, 'source_codes_json', None) or []) + if candidate_line is not None + else [] + ) # [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0) if snap_id is None and ( @@ -184,63 +202,154 @@ def persist_line_inventory_match_facts( .filter_by(task_id=int(task.id), line_key=line_key, is_current=True) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) + # [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number) + src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None + file_no = str(result.get('inventory_file_no') or '')[:128] or None + row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref') + try: + row_index = int(row_index_raw) if row_index_raw is not None and str(row_index_raw).strip() else None + except (TypeError, ValueError): + row_index = None + rsv = str(result.get('reservation_id') or '')[:128] or None + pn = str(result.get('part_number') or '')[:128] or None + evidence_parts = [ + src_code or '', + file_no or '', + str(row_index) if row_index is not None else '', + rsv or '', + pn or '', + ] + evidence_plain = '|'.join(evidence_parts) + evidence_ref = hashlib.sha256(evidence_plain.encode('utf-8')).hexdigest() if any(evidence_parts) else None + detail_json = { + 'disposition': result.get('disposition'), + 'line_status': result.get('line_status'), + 'candidate_hit_source_codes': result.get('candidate_hit_source_codes'), + 'inventory_file_no': file_no, + 'inventory_row_ref': result.get('inventory_row_ref'), + 'snapshot_missing': snap_id is None, + 'evidence_ref_plain': evidence_plain if evidence_ref else None, + } row = ShippingNoticeLineInventoryMatch( task_id=int(task.id), review_case_id=int(case.id) if case is not None else None, line_key=line_key, line_index=index, + candidate_set_id=( + int(current_candidate_set.id) + if current_candidate_set is not None + else None + ), + candidate_set_version=( + int(current_candidate_set.set_version) + if current_candidate_set is not None + else None + ), + candidate_line_id=int(candidate_line.id) if candidate_line is not None else None, inventory_snapshot_id=int(snap_id) if snap_id is not None else None, match_result=match_result, inventory_status=inventory_status, required_qty=str(required) if required is not None else None, available_qty=str(available) if available is not None else None, shortage_qty=str(shortage) if shortage is not None else None, - reservation_id=str(result.get('reservation_id') or '')[:128] or None, - part_number=str(result.get('part_number') or '')[:128] or None, + reservation_id=rsv, + part_number=pn, unit=unit_value, matching_rule_version=str(matching_rule_version or '')[:64] or None, - inventory_source_code=( - str(result.get('resolved_inventory_source_code') or '')[:64] or None - ), + inventory_source_code=src_code, is_current=True, matched_at=now, - detail_json={ - 'disposition': result.get('disposition'), - 'line_status': result.get('line_status'), - 'candidate_hit_source_codes': result.get('candidate_hit_source_codes'), - 'inventory_file_no': result.get('inventory_file_no'), - 'inventory_row_ref': result.get('inventory_row_ref'), - 'snapshot_missing': snap_id is None, - }, + # T6 行级证据 + matched_file_no=file_no, + matched_row_index=row_index, + evidence_ref=evidence_ref, + allowed_source_codes_snapshot=list(allowed_source_codes), + matched_qty=str(available) if available is not None else None, + evidence_checksum=hashlib.sha256( + str({ + 'candidate_set_id': int(current_candidate_set.id) if current_candidate_set is not None else None, + 'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None, + 'allowed_source_codes_snapshot': list(allowed_source_codes), + 'inventory_file_no': file_no, + 'inventory_snapshot_id': int(snap_id) if snap_id is not None else None, + 'inventory_row_ref': result.get('inventory_row_ref'), + 'match_result': match_result, + }).encode('utf-8') + ).hexdigest(), + match_attempt_id=None, + detail_json=detail_json, created_at=now, updated_at=now, ) db.session.add(row) written.append(row) else: + # [T6 E1] 更新分支:同样重算 evidence_ref、matched_file_no、matched_row_index + src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None + file_no = str(result.get('inventory_file_no') or '')[:128] or None + row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref') + try: + row_index = int(row_index_raw) if row_index_raw is not None and str(row_index_raw).strip() else None + except (TypeError, ValueError): + row_index = None + rsv = str(result.get('reservation_id') or '')[:128] or None + pn = str(result.get('part_number') or '')[:128] or None + evidence_parts = [ + src_code or '', + file_no or '', + str(row_index) if row_index is not None else '', + rsv or '', + pn or '', + ] + evidence_plain = '|'.join(evidence_parts) + evidence_ref = hashlib.sha256(evidence_plain.encode('utf-8')).hexdigest() if any(evidence_parts) else None + detail_json = { + 'disposition': result.get('disposition'), + 'line_status': result.get('line_status'), + 'candidate_hit_source_codes': result.get('candidate_hit_source_codes'), + 'inventory_file_no': file_no, + 'inventory_row_ref': result.get('inventory_row_ref'), + 'snapshot_missing': snap_id is None, + 'evidence_ref_plain': evidence_plain if evidence_ref else None, + } existing.match_result = match_result existing.inventory_status = inventory_status existing.required_qty = str(required) if required is not None else None existing.available_qty = str(available) if available is not None else None existing.shortage_qty = str(shortage) if shortage is not None else None - existing.reservation_id = str(result.get('reservation_id') or '')[:128] or None - existing.part_number = str(result.get('part_number') or '')[:128] or None + existing.reservation_id = rsv + existing.part_number = pn existing.unit = unit_value existing.matching_rule_version = str(matching_rule_version or '')[:64] or None - existing.inventory_source_code = ( - str(result.get('resolved_inventory_source_code') or '')[:64] or None - ) + existing.inventory_source_code = src_code existing.is_current = True existing.matched_at = now existing.updated_at = now - existing.detail_json = { - 'disposition': result.get('disposition'), - 'line_status': result.get('line_status'), - 'candidate_hit_source_codes': result.get('candidate_hit_source_codes'), - 'inventory_file_no': result.get('inventory_file_no'), - 'inventory_row_ref': result.get('inventory_row_ref'), - 'snapshot_missing': snap_id is None, - } + existing.candidate_set_id = int(current_candidate_set.id) if current_candidate_set is not None else None + existing.candidate_set_version = ( + int(current_candidate_set.set_version) + if current_candidate_set is not None + else None + ) + existing.candidate_line_id = int(candidate_line.id) if candidate_line is not None else None + # T6 行级证据 + existing.matched_file_no = file_no + existing.matched_row_index = row_index + existing.evidence_ref = evidence_ref + existing.allowed_source_codes_snapshot = list(allowed_source_codes) + existing.matched_qty = str(available) if available is not None else None + existing.evidence_checksum = hashlib.sha256( + str({ + 'candidate_set_id': int(current_candidate_set.id) if current_candidate_set is not None else None, + 'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None, + 'allowed_source_codes_snapshot': list(allowed_source_codes), + 'inventory_file_no': file_no, + 'inventory_snapshot_id': int(snap_id) if snap_id is not None else None, + 'inventory_row_ref': result.get('inventory_row_ref'), + 'match_result': match_result, + }).encode('utf-8') + ).hexdigest() + existing.detail_json = detail_json # 确保同 task+line 仅本条 current ( ShippingNoticeLineInventoryMatch.query diff --git a/backend/app/services/shipping_notice/line_inventory_match_projection.py b/backend/app/services/shipping_notice/line_inventory_match_projection.py index 8f40262a..aebb4af9 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_projection.py +++ b/backend/app/services/shipping_notice/line_inventory_match_projection.py @@ -66,6 +66,7 @@ SOURCE_STATUS_RESOLVING = 'resolving' SOURCE_STATUS_UNRECOGNIZED = 'unrecognized' SOURCE_STATUS_CONFLICT = 'conflict' SOURCE_STATUS_UNAVAILABLE = 'unavailable' +SOURCE_STATUS_CANDIDATES_FROZEN = 'candidates_frozen' def line_auto_fulfill_enabled() -> bool: @@ -467,10 +468,17 @@ def project_line_inventory_view( auto_fulfill_error_message: str | None = None, inventory_rpa_running: bool = False, source_labels: dict[str, str] | None = None, + fallback_inventory_source: dict[str, Any] | None = None, ) -> dict[str, Any]: """ 单行库存+履约用户投影。 + Args: + fallback_inventory_source: Task 级回退库存源事实(行级匹配缺失时使用)。 + 支持:resolved / user_confirmed / candidates_frozen / resolving 四种语义。 + 仅影响 inventory_source 展示对象,不得污染 inventory_status / match_result / + available_qty / shortage_qty / is_shortage / allowed_actions。 + Returns: inventory_* / inventory_source / inventory_allowed_actions / line_allowed_actions / user_line_status 等。 @@ -484,6 +492,34 @@ def project_line_inventory_view( decision_source=decision_source, auto_fulfill_failed=False, ) + fallback = dict(fallback_inventory_source) if isinstance(fallback_inventory_source, dict) else {} + default_source = { + 'code': None, + 'label': None, + 'status': SOURCE_STATUS_RESOLVING, + 'source': 'inventory_source_clue', + } + if fallback.get('code') and fallback.get('status') in { + SOURCE_STATUS_RESOLVED, + 'resolved', + 'user_confirmed', + }: + pre_source = { + 'code': fallback.get('code'), + 'label': fallback.get('label'), + 'status': SOURCE_STATUS_RESOLVED, + 'source': fallback.get('source') or 'task_inventory_source', + } + elif fallback.get('status') == SOURCE_STATUS_CANDIDATES_FROZEN and fallback.get('candidates'): + pre_source = { + 'code': None, + 'label': None, + 'status': SOURCE_STATUS_CANDIDATES_FROZEN, + 'candidates': list(fallback.get('candidates') or []), + 'source': fallback.get('source') or 'frozen_inventory_candidates', + } + else: + pre_source = default_source return { 'inventory_status': None, 'match_result': None, @@ -493,12 +529,7 @@ def project_line_inventory_view( 'display_available': 'pending', 'inventory_snapshot_id': None, 'inventory_checked_at': None, - 'inventory_source': { - 'code': None, - 'label': None, - 'status': SOURCE_STATUS_RESOLVING, - 'source': 'inventory_source_clue', - }, + 'inventory_source': pre_source, 'user_line_status': user_status, 'decision_source': decision_source, 'retryable': False, @@ -557,12 +588,42 @@ def project_line_inventory_view( stored_line_status=stored_line_status, user_line_status=user_status, ) - source = project_inventory_source( + line_source_code = fact.get('inventory_source_code') + raw_source = project_inventory_source( inventory_status=inventory_status, match_result=match_result, - source_code=fact.get('inventory_source_code'), + source_code=line_source_code, source_labels=source_labels, ) + # [STEP] 库存源事实优先级:行级匹配 > Task 级正式源 > 冻结候选源 > 解析中 + # 仅覆盖 inventory_source 展示对象;严禁污染 inventory_status / match_result / + # available_qty / shortage_qty / is_shortage / allowed_actions。 + fallback = dict(fallback_inventory_source) if isinstance(fallback_inventory_source, dict) else {} + fb_code = str(fallback.get('code') or '').strip().upper() or None + fb_status = str(fallback.get('status') or '').strip() + if not line_source_code and fallback: + if fb_code and fb_status in {'resolved', 'user_confirmed', SOURCE_STATUS_RESOLVED}: + label_val = str(fallback.get('label') or '').strip() or ( + (source_labels or {}).get(fb_code) + ) + source = { + 'code': fb_code, + 'label': label_val or None, + 'status': SOURCE_STATUS_RESOLVED, + 'source': fallback.get('source') or 'task_inventory_source', + } + elif fb_status == SOURCE_STATUS_CANDIDATES_FROZEN and fallback.get('candidates'): + source = { + 'code': None, + 'label': None, + 'status': SOURCE_STATUS_CANDIDATES_FROZEN, + 'candidates': list(fallback.get('candidates') or []), + 'source': fallback.get('source') or 'frozen_inventory_candidates', + } + else: + source = raw_source + else: + source = raw_source retryable = project_line_retryable( inventory_allowed_actions=inv_actions, user_line_status=user_status, diff --git a/backend/app/services/shipping_notice/order_build_eligibility_service.py b/backend/app/services/shipping_notice/order_build_eligibility_service.py index 0bc1f85c..54e553f3 100644 --- a/backend/app/services/shipping_notice/order_build_eligibility_service.py +++ b/backend/app/services/shipping_notice/order_build_eligibility_service.py @@ -615,7 +615,7 @@ def assess_order_build_eligibility( }) for field_code in assessment.get('missing_required_fields') or []: issues.append({ - 'code': 'required_field_missing', + 'code': 'final_required_field_missing', 'field_code': field_code, 'severity': 'blocking', 'owning_gate_code': 'field_completeness', @@ -645,7 +645,9 @@ def assess_order_build_eligibility( bool(assessment.get('can_create_task')) and not assessment.get('missing_required_fields') and not assessment.get('invalid_lines') - and not any(str(item.get('code') or '') == 'required_field_missing' for item in issues) + and not any(str(item.get('code') or '') in { + 'final_required_field_missing', 'required_field_missing', + } for item in issues) ) # [STEP] Candidate Qualification:失败只阻断自动建单;用户投影折叠到唯一 Finding。 gate_result = assess_auto_build_gates( diff --git a/backend/app/services/shipping_notice/order_customer_matching.py b/backend/app/services/shipping_notice/order_customer_matching.py index fb4eafe4..2e4f32fc 100644 --- a/backend/app/services/shipping_notice/order_customer_matching.py +++ b/backend/app/services/shipping_notice/order_customer_matching.py @@ -222,8 +222,15 @@ def confirm_order_customer_match( site_id: int | None = None, actor_id: int | None, reason: str, + commit: bool = True, ) -> dict[str, Any]: - """人工确认某个订单客户角色;必须写入理由并保留冻结时可复核的指纹。""" + """ + 人工确认某个订单客户角色;必须写入理由并保留冻结时可复核的指纹。 + + Args: + commit: True 时立即 db.session.commit();False 时仅 flush,由调用方统一控制事务 + (用于同事务内追加 reconcile / Job 入队等后续步骤)。 + """ if role not in ROLE_FIELDS: raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID') row = db.session.query(ShippingOrderCustomerMatch).filter_by( @@ -253,7 +260,10 @@ def confirm_order_customer_match( row.confirmation_reason = reason_value row.confirmed_by_id = actor_id row.confirmed_at = datetime.utcnow() - db.session.commit() + if commit: + db.session.commit() + else: + db.session.flush() return serialize_order_customer_match(row) diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index aaceb9de..8054a6ca 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -1546,13 +1546,13 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult unit=unit, intake=intake, schema=schema, definition=definition, table=selected, confirmed_order_fields=confirmed_order_fields, ) - if orders is None and reason_code in {'row_needs_review', 'required_field_missing'}: + if orders is None and reason_code in {'row_needs_review'}: orders, review_reason = _build_approved_profile_order_result( unit=unit, intake=intake, schema=schema, definition=definition, table=selected, confirmed_order_fields=confirmed_order_fields, allow_manual_review=True, ) if orders is not None: - decision['fallback_reason_codes'] = [reason_code] + decision['fallback_reason_codes'] = ['row_needs_review'] decision['parsed_table_count'] = 1 return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders) reason_code = review_reason or reason_code @@ -1692,7 +1692,7 @@ def _route_reason_for_issue(issue: str) -> str: 'order_profile_no_match': 'profile_not_found', 'order_profile_ambiguous': 'profile_ambiguous', 'order_profile_layout_drift': 'profile_drift_detected', - 'order_profile_snapshot_field_mismatch': 'required_field_missing', + 'order_profile_snapshot_field_mismatch': 'profile_schema_mismatch', 'order_profile_multiple_matches': 'profile_ambiguous', 'order_profile_coordinate_reconstruction_unavailable': 'coordinate_evidence_unavailable', } @@ -1744,6 +1744,10 @@ def _build_approved_profile_order_result( line_groups: list[dict[str, Any]] = [] header_values: dict[str, list[dict[str, Any]]] = {} has_review_rows = False + source_missing_fields: dict[str, Any] = { + 'header': {'field_ids': [], 'field_codes': []}, + 'lines': [], + } for row in table.get('rows') or []: # Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。 if not isinstance(row, dict) or row.get('status') == 'deleted': @@ -1818,26 +1822,38 @@ def _build_approved_profile_order_result( if not config.get('required'): continue field_id = str(config.get('field_id') or '') - if allow_manual_review: - continue - if config.get('scope') == 'header' and field_id not in present_header and field_id not in po_field_ids: + field_code = str(config.get('field_code') or '') + if config.get('scope') == 'header': if field_id in po_field_ids: - return None, 'po_missing' - return None, 'required_field_missing' - if config.get('scope') == 'line' and any( - field_id not in {item['field_id'] for item in group['fields']} for group in line_groups - ): - return None, 'required_field_missing' + continue + if field_id not in present_header: + source_missing_fields['header']['field_ids'].append(field_id) + if field_code: + source_missing_fields['header']['field_codes'].append(field_code) + elif config.get('scope') == 'line': + for line_idx, group in enumerate(line_groups): + if field_id not in {item['field_id'] for item in group['fields']}: + line_entry = next( + (entry for entry in source_missing_fields['lines'] + if isinstance(entry, dict) and entry.get('line_index') == line_idx), + None, + ) + if line_entry is None: + line_entry = {'line_index': line_idx, 'field_ids': [], 'field_codes': []} + source_missing_fields['lines'].append(line_entry) + line_entry['field_ids'].append(field_id) + if field_code: + line_entry['field_codes'].append(field_code) base_order = { 'schema_version_id': schema.get('schema_version_id'), 'schema_checksum': schema.get('checksum'), 'classification': 'shipping_request', 'classification_confidence': 1.0, 'source_intake_no': str(intake.get('intake_no') or ''), 'primary_document_id': int(unit.document_id), 'header_fields': header_fields, 'lines': line_groups, 'conflicts': [], - # Only this frozen approved-profile builder may add this internal marker. } + if source_missing_fields['header']['field_ids'] or source_missing_fields['lines']: + base_order['source_missing_fields'] = source_missing_fields if not has_review_rows: - # Only this frozen approved-profile builder may add this internal marker. base_order['_hxops_acceptance'] = 'approved_deterministic_profile_v1' # 当前业务约束:一份 PDF 只能形成一个 PO;检测到多个 PO 必须整体拒识并转人工复核。 line_pos = [] diff --git a/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py new file mode 100644 index 00000000..2de57d14 --- /dev/null +++ b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py @@ -0,0 +1,420 @@ +""" +services/shipping_notice/order_review_auto_progress_coordinator.py + +用途:建单前复核 Case 的自动推进协调器(客户指纹唯一确认 + Draft 校验 + STP 入队)。 +依赖:order_review_customer_service、order_review_draft_service(延迟)、 + order_stp_auto_create_service(延迟)、candidate_qualification_service、 + fulfillment_audit、ShippingCustomerShadowResolution / + ShippingOrderCustomerMatch / ShippingOrderReviewCase / ShippingOrderProcessingRun。 +逻辑:提供 Run 级批量协调(reconcile_run_review_cases_for_auto_progress)和 + 单 Case 级协调(reconcile_single_case_for_auto_progress)两层入口; + 客户协调仅在 shadow.status=unique_candidate 且未 resolve 时自动确认 bill_to; + 所有入口均不主动 commit,由调用方统一控制事务;Run 级循环单 Case 异常局部 rollback。 +注意:order_stp_auto_create_service 与 order_review_draft_service 均不在顶层 import, + 避免 circular import(stp 末尾顶层 import 本模块,draft 顶层 import 本模块)。 +""" + +from __future__ import annotations + +import logging +from typing import Any + +from app import db +from app.models import ( + ShippingCustomerShadowResolution, + ShippingOrderCandidate, + ShippingOrderCustomerMatch, + ShippingOrderProcessingRun, + ShippingOrderReviewCase, +) +from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit +from app.services.shipping_notice.order_review_customer_service import ( + _header_from_case, + _resolve_extraction_for_case, + confirm_order_customer_match, + refresh_order_customer_matches, + resolve_review_case_customer_resolved, +) +from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref + +# 注意:validate_draft 与 ensure_stp_auto_create_for_case 均不在顶层 import, +# 避免 circular import。 +# 环1(draft):order_review_draft_service → 顶层 import 本模块 +# → 本模块顶层 import validate_draft → ImportError。 +# 环2(stp):order_stp_auto_create_service → 末尾顶层 import 本模块 +# → 本模块顶层 import ensure_stp_auto_create_for_case → ImportError。 +# 因此两者均延迟 import 到 reconcile_single_case_for_auto_progress / +# reconcile_run_review_cases_for_auto_progress 的调用点。 + +_LOGGER = logging.getLogger(__name__) + +_TERMINAL_STATUSES = frozenset({ + 'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending', +}) + + +# build_review_revalidate_job_ref 已经移动到 recovery_contract.py 作为契约层函数, +# 这里保留薄 re-export,确保历史调用方(如有)不被破坏。 +# (draft_service 已改为从 recovery_contract import,断环。) + + +def _customer_step_for_case( + *, + case: ShippingOrderReviewCase, + trigger: str, +) -> tuple[str, dict[str, Any] | None]: + """ + 单 Case 客户协调内部步骤:shadow 唯一命中时自动确认 bill_to。 + + Args: + case: 复核 Case。 + trigger: 触发来源(写 audit)。 + + Returns: + (step_status, extra_metadata);status 取值 skipped / auto_confirmed / failed / not_applicable。 + """ + # [STEP 1-1] 加载关联 Candidate 与 Shadow 分辨率 + candidate = ( + db.session.get(ShippingOrderCandidate, int(case.candidate_id)) + if case.candidate_id + else None + ) + shadow = ( + ShippingCustomerShadowResolution.query + .filter_by(candidate_id=int(candidate.id)) + .first() + if candidate is not None + else None + ) + if shadow is None: + return 'not_applicable', {'reason': 'shadow_missing'} + if shadow.status != 'unique_candidate' or not shadow.top_customer_id: + return 'skipped', {'reason': 'shadow_not_unique_candidate'} + + # [STEP 1-2] 是否已 resolve(真实评估,避免重复写入) + already_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate) + if already_resolved: + return 'skipped', {'reason': 'customer_already_resolved'} + + # [STEP 1-3] 提取 order_extraction(Candidate 关联优先,否则 Run 内最新) + extraction = _resolve_extraction_for_case(case) + if extraction is None: + return 'failed', {'reason': 'extraction_missing'} + + # [STEP 1-4] 若无 bill_to match 行,先按当前头字段刷新 + bill_to_exists = ( + ShippingOrderCustomerMatch.query + .filter_by(extraction_id=int(extraction.id), role='bill_to') + .first() + is not None + ) + if not bill_to_exists: + try: + refresh_order_customer_matches(extraction, _header_from_case(case)) + except Exception as exc: # noqa: BLE001 + _LOGGER.warning( + 'refresh_order_customer_matches failed case_no=%s err=%s', + case.case_no, str(exc)[:200], + ) + return 'failed', {'reason': 'refresh_matches_failed', 'error': str(exc)[:200]} + + # [STEP 1-5] 自动确认 bill_to 到 top_customer_id + top_customer_id = int(shadow.top_customer_id) + confirm_reason = '抽取协调器-客户指纹唯一命中自动确认' + try: + confirm_order_customer_match( + int(extraction.id), + role='bill_to', + customer_id=top_customer_id, + site_id=None, + actor_id=None, + reason=confirm_reason, + ) + except Exception as exc: # noqa: BLE001 + _LOGGER.warning( + 'confirm_order_customer_match failed case_no=%s err=%s', + case.case_no, str(exc)[:200], + ) + return 'failed', {'reason': 'confirm_match_failed', 'error': str(exc)[:200]} + + # [STEP 1-6] 记录 audit 事件(customer 自动确认) + try: + record_fulfillment_audit( + event_type='review_case_customer_auto_confirmed_by_run_coordinator', + aggregate_type='order_review_case', + aggregate_id=str(case.case_no), + action='review_case_customer_auto_confirmed', + actor_type='system', + actor_id=None, + review_case_no=str(case.case_no), + owner_user_id=case.owner_user_id, + document_id=case.document_id, + metadata={ + 'run_id': int(case.run_id) if case.run_id else None, + 'candidate_id': int(candidate.id) if candidate is not None else None, + 'shadow_status': 'unique_candidate', + 'customer_id': top_customer_id, + 'extraction_id': int(extraction.id), + 'trigger': str(trigger)[:64], + 'reason': confirm_reason, + }, + source='review_auto_progress_coordinator', + strict=False, + ) + except Exception: # noqa: BLE001 + _LOGGER.exception('record_fulfillment_audit failed for case_no=%s', case.case_no) + + return 'auto_confirmed', { + 'customer_id': top_customer_id, + 'extraction_id': int(extraction.id), + } + + +def reconcile_single_case_for_auto_progress( + *, + case_no: Any = None, + case: ShippingOrderReviewCase | None = None, + trigger: str = 'system_reconcile', + refresh_validation: bool = True, +) -> dict[str, Any]: + """ + 单 Case 级自动推进协调器。 + + 供 revalidate Job / Sweeper / Case 级 retry API 复用。顺序执行:终态门禁 + 客户协调 + + Draft 校验 + STP 入队;不主动提交事务,由调用方控制。 + + Args: + case_no: 复核 Case 编号(与 case 二选一)。 + case: 已加载的复核 Case(与 case_no 二选一,优先使用)。 + trigger: 触发来源标识(写 audit)。 + refresh_validation: True 时若有 current_draft 则显式跑 validate_draft。 + + Returns: + 摘要 ``{case_no, customer_step_status, validate_status, enqueue_status, + job_id, idempotency_key, error}``。 + """ + result: dict[str, Any] = { + 'case_no': None, + 'customer_step_status': 'skipped', + 'validate_status': 'skipped', + 'enqueue_status': 'skipped', + 'job_id': None, + 'idempotency_key': None, + 'error': None, + } + + # [STEP 0] 加载 Case;case_no 提供时 db.session.get;无锁(调用方负责短锁或 advisory lock) + loaded_case = case + if loaded_case is None and case_no is not None: + loaded_case = ( + ShippingOrderReviewCase.query + .filter_by(case_no=str(case_no).strip().upper()) + .first() + ) + if loaded_case is None: + result['case_no'] = str(case_no or '') or None + result['error'] = 'case_not_found' + result['enqueue_status'] = 'case_not_found' + return result + result['case_no'] = str(loaded_case.case_no or '') + + # [STEP 1] 终态检查 + 已确认检查 + if loaded_case.confirmed_task_id or str(loaded_case.status or '') in _TERMINAL_STATUSES: + result['enqueue_status'] = 'already_confirmed_or_terminal' + result['customer_step_status'] = 'skipped' + result['validate_status'] = 'skipped' + return result + + # [STEP 2] 客户协调(trigger 带入 audit) + try: + customer_status, customer_meta = _customer_step_for_case( + case=loaded_case, trigger=trigger, + ) + result['customer_step_status'] = customer_status + if customer_meta: + result['customer_meta'] = customer_meta + except Exception as exc: # noqa: BLE001 + _LOGGER.exception('customer_step failed case_no=%s', loaded_case.case_no) + result['customer_step_status'] = 'failed' + result['error'] = f'customer_step:{str(exc)[:200]}' + + # [STEP 3] Draft validate(refresh_validation=True 且有 current_draft) + if refresh_validation and loaded_case.current_draft is not None: + try: + from app.services.shipping_notice.order_review_draft_service import validate_draft + validate_out = validate_draft( + user_id=int(loaded_case.owner_user_id), + case_no=str(loaded_case.case_no), + expected_draft_version=int(loaded_case.current_draft.draft_version), + ) + result['validate_status'] = ( + validate_out.get('status') if isinstance(validate_out, dict) else 'validated' + ) + except Exception as exc: # noqa: BLE001 + _LOGGER.warning( + 'validate_draft failed case_no=%s err=%s', + loaded_case.case_no, str(exc)[:200], + ) + result['validate_status'] = 'failed' + result['error'] = (result['error'] or '') + f'|validate:{str(exc)[:200]}' + else: + result['validate_status'] = 'skipped' + + # [STEP 4] ensure_stp_auto_create_for_case(commit=False,调用方统一控制事务) + try: + from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + ) + run = loaded_case.run or ( + db.session.get(ShippingOrderProcessingRun, int(loaded_case.run_id)) + if loaded_case.run_id else None + ) + enqueue_result = ensure_stp_auto_create_for_case( + case=loaded_case, + run=run, + commit=False, + refresh_validation=False, + ) + result['enqueue_status'] = str(enqueue_result.get('status') or 'skipped') + result['job_id'] = enqueue_result.get('job_id') + result['idempotency_key'] = enqueue_result.get('idempotency_key') + if enqueue_result.get('error_code'): + result['enqueue_error_code'] = enqueue_result['error_code'] + except Exception as exc: # noqa: BLE001 + _LOGGER.exception('ensure_stp_auto_create failed case_no=%s', loaded_case.case_no) + result['enqueue_status'] = 'failed' + result['error'] = (result['error'] or '') + f'|enqueue:{str(exc)[:200]}' + + return result + + +def reconcile_run_review_cases_for_auto_progress( + run: ShippingOrderProcessingRun, +) -> list[dict[str, Any]]: + """ + Run 级自动推进协调器:批量协调抽取 Run 下所有 Review Case。 + + 遍历 Run 下全部 Review Case,依次执行:终态门禁 → 客户指纹唯一确认 → Draft 校验 + → STP 幂等入队。单 Case 异常局部 rollback 并摘要 status=failed,不阻断其他 Case。 + 本函数不主动 db.session.commit();调用方在循环外统一控制事务边界。 + + Args: + run: 已 ensure_run_review_cases 的抽取 Processing Run。 + + Returns: + 每个 Case 的处理摘要列表(与 reconcile_single_case 返回结构一致)。 + """ + results: list[dict[str, Any]] = [] + + # [STEP 0] 加载 Run 下全部 Case 主键列表(固定顺序,避免重复扫描) + case_ids = [ + int(row.id) + for row in ( + ShippingOrderReviewCase.query + .filter_by(run_id=int(run.id)) + .order_by(ShippingOrderReviewCase.id.asc()) + .with_entities(ShippingOrderReviewCase.id) + .all() + ) + ] + + for case_id in case_ids: + case = db.session.get(ShippingOrderReviewCase, case_id) + if case is None: + continue + + try: + # [STEP 0 内层] 终态门禁 + 已确认检查 + if case.confirmed_task_id or str(case.status or '') in _TERMINAL_STATUSES: + results.append({ + 'case_no': str(case.case_no or ''), + 'customer_step_status': 'skipped', + 'validate_status': 'skipped', + 'enqueue_status': 'already_confirmed_or_terminal', + 'job_id': None, + 'idempotency_key': None, + 'error': None, + 'status': 'skipped_terminal', + }) + continue + + # [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认 bill_to + customer_status, customer_meta = _customer_step_for_case( + case=case, trigger='run_reconcile', + ) + + # [STEP 2 Draft 校验] 有 current_draft 时重新 validate + validate_status = 'skipped' + if case.current_draft is not None: + try: + from app.services.shipping_notice.order_review_draft_service import validate_draft + validate_out = validate_draft( + user_id=int(case.owner_user_id), + case_no=str(case.case_no), + expected_draft_version=int(case.current_draft.draft_version), + ) + validate_status = ( + validate_out.get('status') if isinstance(validate_out, dict) else 'validated' + ) + except Exception as exc: # noqa: BLE001 + _LOGGER.warning( + 'validate_draft failed case_no=%s err=%s', + case.case_no, str(exc)[:200], + ) + validate_status = 'failed' + + # [STEP 3 STP 入队] 幂等 ensure,commit=False + from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + ) + enqueue_result = ensure_stp_auto_create_for_case( + case=case, + run=run, + commit=False, + refresh_validation=False, + ) + + # [STEP 4] flush 当前 Case 的所有写入(客户确认、Draft 校验、STP Job) + db.session.flush() + + case_summary: dict[str, Any] = { + 'case_no': str(case.case_no or ''), + 'customer_step_status': customer_status, + 'validate_status': validate_status, + 'enqueue_status': str(enqueue_result.get('status') or 'skipped'), + 'job_id': enqueue_result.get('job_id'), + 'idempotency_key': enqueue_result.get('idempotency_key'), + 'error': None, + 'status': str(enqueue_result.get('status') or 'processed'), + } + if customer_meta: + case_summary['customer_meta'] = customer_meta + if enqueue_result.get('error_code'): + case_summary['enqueue_error_code'] = enqueue_result['error_code'] + if validate_status == 'failed': + case_summary['status'] = 'validate_failed' + if customer_status == 'failed' and case_summary['status'] not in { + 'validate_failed', 'failed', + }: + case_summary['status'] = 'customer_step_failed' + results.append(case_summary) + + except Exception as exc: # noqa: BLE001 + # 单 Case 异常局部 rollback 隔离,保证同 Run 其它 Case 继续 + _LOGGER.exception('reconcile case failed case_id=%s', case_id) + try: + db.session.rollback() + except Exception: # noqa: BLE001 + pass + results.append({ + 'case_no': getattr(case, 'case_no', None), + 'customer_step_status': 'failed', + 'validate_status': 'skipped', + 'enqueue_status': 'failed', + 'job_id': None, + 'idempotency_key': None, + 'error': str(exc)[:300], + 'status': 'failed', + }) + + return results diff --git a/backend/app/services/shipping_notice/order_review_case_snapshot.py b/backend/app/services/shipping_notice/order_review_case_snapshot.py new file mode 100644 index 00000000..056580f6 --- /dev/null +++ b/backend/app/services/shipping_notice/order_review_case_snapshot.py @@ -0,0 +1,79 @@ +""" +app.services.shipping_notice.order_review_case_snapshot + +用途:为订单复核工作台提供「完整 Case 快照」包装响应。 +依赖:order_review_projection.serialize_review_case、ShippingOrderReviewCase。 +逻辑:复用既有 Case 投影作为唯一业务真源,再补充 projection_version 与 + loading_context,避免 API 路由层继续膨胀,同时保持统一 envelope 契约。 +""" +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app.models import ShippingOrderReviewCase +from app.services.shipping_notice.order_review_projection import serialize_review_case + + +def _projection_version(case: ShippingOrderReviewCase) -> int: + """ + 基于 Case 更新时间生成快照版本号。 + + Args: + case: 当前复核 Case。 + + Returns: + 以毫秒时间戳表示的投影版本;无更新时间时回退到 draft_version。 + """ + updated_at = getattr(case, 'updated_at', None) + if isinstance(updated_at, datetime): + return int(updated_at.timestamp() * 1000) + draft = getattr(case, 'current_draft', None) + return int(getattr(draft, 'draft_version', 0) or 0) + + +def _loading_context(payload: dict[str, Any]) -> dict[str, Any]: + """ + 从既有 automation 投影抽取仅供展示的 loading_context。 + + Args: + payload: serialize_review_case 返回的 Case 投影。 + + Returns: + 仅含 phase / status / message 的最小展示上下文。 + """ + automation = payload.get('automation') + if not isinstance(automation, dict): + return { + 'phase': None, + 'status': None, + 'message': None, + } + return { + 'phase': str(automation.get('phase') or '').strip() or None, + 'status': str(automation.get('status') or '').strip() or None, + 'message': str(automation.get('message') or '').strip() or None, + } + + +def build_order_review_case_snapshot( + case: ShippingOrderReviewCase, + *, + is_admin: bool = False, +) -> dict[str, Any]: + """ + 构建订单复核工作台单 Case 完整快照。 + + Args: + case: 当前用户可见的复核 Case。 + is_admin: 是否管理员视角。 + + Returns: + 包含 case / projection_version / loading_context 的完整快照。 + """ + payload = serialize_review_case(case, is_admin=is_admin) + return { + 'case': payload, + 'projection_version': _projection_version(case), + 'loading_context': _loading_context(payload), + } diff --git a/backend/app/services/shipping_notice/order_review_customer_service.py b/backend/app/services/shipping_notice/order_review_customer_service.py index 9ac38079..3ccdc1c6 100644 --- a/backend/app/services/shipping_notice/order_review_customer_service.py +++ b/backend/app/services/shipping_notice/order_review_customer_service.py @@ -29,18 +29,24 @@ from app.services.shipping_notice.order_customer_matching import ( refresh_order_customer_matches, serialize_order_customer_match, ) -from app.services.shipping_notice.order_review_draft_service import ( - soft_load_review_case_for_audit, - validate_draft, -) from app.services.shipping_notice.workflow_ledger_service import ( assert_case_is_current_workflow_version, ) +def _get_draft_imports(): + """延迟导入 draft_service 以解开 job_registry → fulfill_service → draft_service 的循环链。""" + from app.services.shipping_notice.order_review_draft_service import ( + soft_load_review_case_for_audit, + validate_draft, + ) + return soft_load_review_case_for_audit, validate_draft + + def _load_writable_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase: """加载属主可写 Case,并校验 Workflow 当前版本。""" - case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no or '')) + soft_load, _v = _get_draft_imports() + case = soft_load(user_id=int(user_id), case_no=str(case_no or '')) if case is None: raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') if str(case.status or '') in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}: @@ -111,6 +117,9 @@ def _header_from_case(case: ShippingOrderReviewCase) -> dict[str, Any]: def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> dict[str, Any]: """ 投影复核 Case 的建单前客户识别状态,供工作台固定客户区展示。 + 【GET 纯读契约】本函数是只读投影,不做任何 DB 写入、不确认客户、不校验 Draft、不提交事务。 + 唯一客户自动确认已迁移至系统级协调器 reconcile_run_review_cases_for_auto_progress, + 在抽取收尾、字段变更 revalidate Job、recovery sweeper 中统一触发。 Returns: resolved、status、raw_name、confirmed 客户快照、候选列表、extraction_id。 @@ -138,39 +147,6 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di match_payload = serialize_order_customer_match(match) if match is not None else None shadow_matches = list(shadow.candidate_matches_json or []) if shadow is not None else [] top_shadow = shadow_matches[0] if shadow_matches else {} - top_customer_id = shadow.top_customer_id or top_shadow.get('customer_id') if shadow is not None else top_shadow.get('customer_id') - # [STEP 1] 唯一客户指纹命中后立即落确认结果,确保首次打开复核工作台也能看到已确认状态。 - # 规则快照与证据完整性仍由影子识别流程负责;这里只消费已持久化的唯一候选。 - if ( - shadow is not None - and shadow.status == 'unique_candidate' - and top_customer_id - and not resolved - and extraction is not None - ): - if match_payload is None: - refresh_order_customer_matches(extraction, _header_from_case(case)) - confirm_order_customer_match( - int(extraction.id), - role='bill_to', - customer_id=int(top_customer_id), - site_id=None, - actor_id=None, - reason='客户识别指纹唯一命中自动确认', - ) - # 自动确认后立即重跑当前 Draft 校验,避免客户面板已确认而建单资格仍停留在旧快照。 - if case.current_draft is not None: - validate_draft( - user_id=int(case.owner_user_id), - case_no=str(case.case_no), - expected_draft_version=int(case.current_draft.draft_version), - ) - db.session.commit() - resolved = True - match = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(extraction.id), role='bill_to', - ).first() - match_payload = serialize_order_customer_match(match) if match is not None else match_payload status = 'confirmed' if resolved else str( (shadow.status if shadow is not None else None) or (match_payload or {}).get('status') @@ -260,8 +236,13 @@ def confirm_review_case_customer( """ 在复核工作台确认标准客户,并刷新建单资格。 - 核心逻辑:写入 Bill-to CustomerMatch=confirmed → validate Draft → 返回最新 Case。 + 核心逻辑:写入 Bill-to CustomerMatch=confirmed → 统一协调器推进 → 返回最新 Case。 """ + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_single_case_for_auto_progress, + ) + from app.services.shipping_notice.order_review_projection import serialize_review_case + case = _load_writable_case(user_id=user_id, case_no=case_no) extraction = _resolve_extraction_for_case(case) if extraction is None: @@ -272,6 +253,8 @@ def confirm_review_case_customer( # [STEP 1] 若尚无 match 行,先按当前头字段刷新,再人工确认。 if ShippingOrderCustomerMatch.query.filter_by(extraction_id=int(extraction.id), role='bill_to').first() is None: refresh_order_customer_matches(extraction, _header_from_case(case)) + # [STEP P1-8] confirm_order_customer_match 保留调用,传 commit=False 以便 + # 后续 reconcile(校验+STP 入队)在同一事务提交,保证变更与推进原子可见。 confirm_order_customer_match( int(extraction.id), role='bill_to', @@ -279,31 +262,42 @@ def confirm_review_case_customer( site_id=None, actor_id=int(user_id), reason=str(reason or '复核工作台人工确认标准客户').strip(), + commit=False, ) - # confirm_order_customer_match 已 commit;随后走统一恢复协调器。 - from app.services.shipping_notice.order_review_resume_service import ( - attach_resume_outcome, - resume_after_review_change, - ) - - resume = resume_after_review_change( - user_id=int(user_id), - case_no=str(case_no), + # [STEP P1-8] 客户人工确认后走统一协调器:终态门禁 + 客户协调(已人工确认会跳过)+ + # Draft 校验 + STP 入队;trigger=customer_confirmed 对应人工确认语义。 + reconcile_result = reconcile_single_case_for_auto_progress( + case=case, trigger='customer_confirmed', - change_type='customer_confirmed', - skip_validate=False, - allow_auto_create=True, + refresh_validation=True, ) - case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no)) + db.session.commit() + case = _get_draft_imports()[0](user_id=int(user_id), case_no=str(case_no)) if case is None: raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') - return attach_resume_outcome( - { - 'case': resume.get('case'), - 'customer_resolution': project_review_case_customer_resolution(case), - }, - resume, - ) + serialized_case = serialize_review_case(case) + payload: dict[str, Any] = { + 'case': serialized_case, + 'customer_resolution': project_review_case_customer_resolution(case), + } + # 兼容 attach_resume_outcome 结构;保留 reconcile 原始摘要在 reconcile_outcome。 + resume_outcome = { + 'gate_recalculated': reconcile_result.get('validate_status') != 'skipped', + 'qualification_status': str(reconcile_result.get('validate_status') or ''), + 'qualification_ready': reconcile_result.get('validate_status') in {'success', 'validated'}, + 'can_build': reconcile_result.get('enqueue_status') in {'success', 'enqueued'}, + 'auto_gate_allowed': reconcile_result.get('enqueue_status') in {'success', 'enqueued'}, + 'task_created': reconcile_result.get('job_id') is not None, + 'task_no': None, + 'auto_progress_started': reconcile_result.get('enqueue_status') in {'success', 'enqueued'}, + 'idempotent_replay': reconcile_result.get('idempotency_key') is not None, + 'outcome': str(reconcile_result.get('enqueue_status') or ''), + 'message': None, + 'failed_gates': None, + } + payload['resume_outcome'] = resume_outcome + payload['reconcile_outcome'] = reconcile_result + return payload def retry_review_case_customer_resolution( @@ -316,6 +310,11 @@ def retry_review_case_customer_resolution( 【AI 触发时机】:用户在复核工作台点击「重新识别客户」时调用。 """ + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_single_case_for_auto_progress, + ) + from app.services.shipping_notice.order_review_projection import serialize_review_case + case = _load_writable_case(user_id=user_id, case_no=case_no) extraction = _resolve_extraction_for_case(case) if extraction is None: @@ -335,6 +334,7 @@ def retry_review_case_customer_resolution( and shadow.top_customer_id and not resolve_review_case_customer_resolved(case=case, candidate=candidate) ): + # [STEP P1-8] 传 commit=False,保证与后续 reconcile 同事务提交。 confirm_order_customer_match( int(extraction.id), role='bill_to', @@ -342,29 +342,40 @@ def retry_review_case_customer_resolution( site_id=None, actor_id=None, reason='客户识别指纹唯一命中自动确认', + commit=False, ) + # [STEP P1-8] 客户 shadow 重新识别后走统一协调器;trigger=customer_shadow_reconfirmed + # 标识为「影子指纹再确认 + 唯一命中自动确认」路径,与 PATCH 异步 Job、人工确认按钮路径互补不冲突。 + reconcile_result = reconcile_single_case_for_auto_progress( + case=case, + trigger='customer_shadow_reconfirmed', + refresh_validation=True, + ) db.session.commit() - from app.services.shipping_notice.order_review_resume_service import ( - attach_resume_outcome, - resume_after_review_change, - ) - - resume = resume_after_review_change( - user_id=int(user_id), - case_no=str(case_no), - trigger='customer_retry', - change_type='customer_confirmed', - skip_validate=False, - allow_auto_create=True, - ) - case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no)) + case = _get_draft_imports()[0](user_id=int(user_id), case_no=str(case_no)) if case is None: raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') - return attach_resume_outcome( - { - 'case': resume.get('case'), - 'customer_resolution': project_review_case_customer_resolution(case), - 'matches': matches, - }, - resume, - ) + serialized_case = serialize_review_case(case) + payload: dict[str, Any] = { + 'case': serialized_case, + 'customer_resolution': project_review_case_customer_resolution(case), + 'matches': matches, + } + # 兼容 attach_resume_outcome 结构;保留 reconcile 原始摘要在 reconcile_outcome。 + resume_outcome = { + 'gate_recalculated': reconcile_result.get('validate_status') != 'skipped', + 'qualification_status': str(reconcile_result.get('validate_status') or ''), + 'qualification_ready': reconcile_result.get('validate_status') in {'success', 'validated'}, + 'can_build': reconcile_result.get('enqueue_status') in {'success', 'enqueued'}, + 'auto_gate_allowed': reconcile_result.get('enqueue_status') in {'success', 'enqueued'}, + 'task_created': reconcile_result.get('job_id') is not None, + 'task_no': None, + 'auto_progress_started': reconcile_result.get('enqueue_status') in {'success', 'enqueued'}, + 'idempotent_replay': reconcile_result.get('idempotency_key') is not None, + 'outcome': str(reconcile_result.get('enqueue_status') or ''), + 'message': None, + 'failed_gates': None, + } + payload['resume_outcome'] = resume_outcome + payload['reconcile_outcome'] = reconcile_result + return payload diff --git a/backend/app/services/shipping_notice/order_review_draft_service.py b/backend/app/services/shipping_notice/order_review_draft_service.py index 38db8916..fdef4a3a 100644 --- a/backend/app/services/shipping_notice/order_review_draft_service.py +++ b/backend/app/services/shipping_notice/order_review_draft_service.py @@ -20,6 +20,7 @@ from __future__ import annotations import copy import logging +import time import uuid from datetime import date from decimal import Decimal @@ -29,6 +30,8 @@ _LOGGER = logging.getLogger(__name__) from app import db from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError +from app.jobs.queue import enqueue +from app.jobs.types import JobType from app.models import ( ShippingOrderReviewCase, ShippingOrderReviewCaseEvent, @@ -43,6 +46,9 @@ from app.services.shipping_notice.order_build_eligibility_service import ( mark_keep_manual_inventory_decision, project_line_inventory_candidates, ) +# 注意:build_review_revalidate_job_ref 放在 recovery_contract.py(零依赖契约模块), +# 避免 circular import:draft_service → coordinator → stp → confirmation → draft_service 回绕。 +from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_schema.field_rules import ( is_valid_line_no_value, @@ -794,6 +800,25 @@ def _record_change( validation=result, details={'case_event_type': event_type}, ) + # [STEP P1-6] 字段 PATCH / 增删行(非显式校验)触发异步 Revalidate Job; + # level-triggered reconcile 补偿:草稿 JSON 变动后统一跑校验 + 客户协调 + STP 入队。 + # 同 draft_version 幂等:enqueue 默认 dedupe queued/running,重复调用安全复用已有 job_id。 + if event_type != 'draft_validated' and draft is not None: + business_ref = build_review_revalidate_job_ref(case.case_no, draft.draft_version) + enqueue( + JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS, + { + 'case_no': case.case_no, + 'draft_version': draft.draft_version, + 'operation_id': f"patch-{int(time.time() * 1000)}", + }, + domain='shipping_notice', + business_ref=business_ref, + priority=5, + max_attempts=3, + created_by_id=int(actor_id) if actor_id is not None else None, + commit=False, + ) db.session.flush() return serialize_review_case(case) @@ -1006,7 +1031,13 @@ def delete_line(*, user_id: int, case_no: str, line_key: str, expected_draft_ver def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]: - """显式执行全量草稿校验;只更新验证结果和事件,不创建 Candidate 或 ShippingNotice。""" + """ + 显式执行全量草稿校验;只更新验证结果和事件,不创建 Candidate 或 ShippingNotice。 + + [P1-6 说明] 显式校验按钮走同步 resume(路由层调用 validate_draft 后通常紧接着 + resume_after_review_change(trigger='draft_validated')),因此本条路径不额外 enqueue + 异步 Revalidate Job;字段编辑/增删行走异步 Job 触发,两条路径互不冲突且互为补充。 + """ action = 'draft_validated' case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) diff --git a/backend/app/services/shipping_notice/order_review_evidence_selector.py b/backend/app/services/shipping_notice/order_review_evidence_selector.py index dd99a2da..82d83d57 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_selector.py +++ b/backend/app/services/shipping_notice/order_review_evidence_selector.py @@ -13,8 +13,12 @@ from typing import Any from app.services.shipping_notice.order_review_llm_contract import ( DEFAULT_MAX_EVIDENCE_LEVEL, + DEFAULT_V2_EVIDENCE_LEVEL, + EVIDENCE_LEVELS_V2_ALLOWED, EvidenceLevel, + build_evidence_ref, ) +from app.services.shipping_notice.order_review_llm_policy_registry import mask_field_value _FORBIDDEN_KEYS = frozenset({ @@ -30,6 +34,8 @@ def select_review_evidence_pack( target_fields: list[dict[str, Any]], evidence_level: EvidenceLevel = 'L1_field', allow_full_pdf: bool = False, + evidence_view: dict[str, Any] | None = None, + token_budget_chars: int = 12000, ) -> dict[str, Any]: """ 按证据等级组装最小证据包。 @@ -43,6 +49,20 @@ def select_review_evidence_pack( Returns: 脱敏证据包字典;L2/L3 仅围绕命中目标字段的表/页扩大。 """ + # [V2 BRANCH] v2 等级:走证据视图构建,不触碰 v1 代码。 + level_str = str(evidence_level or DEFAULT_V2_EVIDENCE_LEVEL) + if level_str in EVIDENCE_LEVELS_V2_ALLOWED: + return _strip_forbidden( + _build_v2_evidence_pack( + document=document, + target_fields=target_fields, + evidence_level=level_str, # type: ignore[arg-type] + allow_full_pdf=allow_full_pdf, + evidence_view=evidence_view or {}, + token_budget_chars=token_budget_chars, + ) + ) + level = evidence_level if evidence_level in { 'L1_field', 'L2_table', 'L3_page', 'L4_pdf', } else DEFAULT_MAX_EVIDENCE_LEVEL @@ -247,3 +267,500 @@ def _strip_forbidden(value: Any) -> Any: if isinstance(value, list): return [_strip_forbidden(item) for item in value] return value + + +# ========================================================================= +# V2 证据等级实现(L1_field / L2_row / L3_table / L4_page / L5_document) +# ========================================================================= + +_FIELD_CORE_PRIORITY = ( + 'field_id', 'value', 'quote', 'evidence_ref', 'field_code', + 'scope', 'line_key', 'llm_context_policy', 'mask_rule', 'value_source', +) + + +def _serialize_field_view( + fv: dict[str, Any], + *, + is_target: bool, + strip_secondary_for_token: bool, +) -> dict[str, Any]: + """ + 将 evidence_view 中的 field_view 序列化为发给 LLM 的最小字段对象。 + Token 预算不足时,非目标字段先丢 display_name / confidence / provenance_ref。 + 目标字段:field_id/value/quote/evidence_ref 绝对不能丢(截断会被 gated 拦截)。 + """ + policy = fv.get('llm_context_policy') or 'forbidden' + fc = fv.get('field_code') or fv.get('field_id') or '' + raw_value = None + if fv.get('value_source') != 'missing_both': + raw_value = ( + fv.get('machine_value') if fv.get('value_source') != 'manual_only' + else fv.get('current_draft_value') + ) + if raw_value is None: + pe = fv.get('primary_evidence') or {} + if isinstance(pe, dict): + raw_value = pe.get('value') or pe.get('quote') or None + + masked = mask_field_value( + policy=policy, # type: ignore[arg-type] + field_code=str(fc), + value=raw_value, + ) + sent_value = masked['masked_value'] if masked.get('policy') == 'masked' else raw_value + + primary = fv.get('primary_evidence') if isinstance(fv.get('primary_evidence'), dict) else {} + quote_text = str(primary.get('quote') or '').strip() or ( + str(raw_value).strip() if raw_value is not None else '' + ) + evidence_ref = str(primary.get('evidence_ref') or '').strip() or None + + # [STEP] 按保留优先级组装 + out: dict[str, Any] = {} + out['field_id'] = fv.get('field_id') + if not strip_secondary_for_token: + out['field_code'] = fc + out['scope'] = fv.get('scope') + if fv.get('line_key'): + out['line_key'] = fv.get('line_key') + out['value'] = sent_value + out['value_source'] = fv.get('value_source') or 'missing_both' + if masked.get('policy') == 'masked': + out['llm_context_policy'] = masked['policy'] + out['mask_rule'] = masked.get('mask_rule') + out['original_value_sent'] = bool(masked.get('original_value_sent')) + if quote_text: + out['quote'] = quote_text[:500] + if evidence_ref: + out['evidence_ref'] = evidence_ref + if is_target: + out['is_target'] = True + if not strip_secondary_for_token: + out['confidence'] = primary.get('confidence') + elif strip_secondary_for_token: + # 非目标字段在 token 吃紧时,可丢 quote / evidence_ref 以外的 metadata + for k in ('display_name', 'confidence', 'provenance_ref'): + out.pop(k, None) + return out + + +def _truncate_fields_list( + fields_list: list[dict[str, Any]], + *, + chars_remaining: int, + target_idx: int, +) -> tuple[list[dict[str, Any]], bool, bool]: + """ + 按层级做 token 预算截断;返回 (trimmed_list, any_trimmed, target_core_trimmed)。 + target_core_trimmed=True → 直接被上层门禁 evidence_truncated 拦截(本函数会避免)。 + """ + any_trimmed = False + target_core_trimmed = False + if not fields_list: + return fields_list, False, False + + # [1] 全部保留,先估字符 + full_text = _approx_json_chars(fields_list) + if full_text <= chars_remaining: + return fields_list, False, False + + # [2] 非目标字段先做 strip_secondary_for_token(目标字段绝对不 strip core) + processed: list[dict[str, Any]] = [] + for idx, item in enumerate(fields_list): + if idx == target_idx: + processed.append(item) + else: + stripped = dict(item) + for k in ('display_name', 'confidence', 'page_no', 'table_id', + 'row_index', 'cell_id', 'provenance_ref'): + if k in stripped and k not in _FIELD_CORE_PRIORITY: + stripped.pop(k, None) + any_trimmed = True + processed.append(stripped) + if _approx_json_chars(processed) <= chars_remaining: + return processed, any_trimmed, False + + # [3] 非目标字段从尾部逐个丢弃(保留头部与目标字段相邻,提高语义) + kept: list[dict[str, Any]] = [] + # 先保留目标字段 + target_field = processed[target_idx] if 0 <= target_idx < len(processed) else None + # 保留前 1 + 后 1 + 目标字段;逐步缩小范围 + kept_order: list[int] = [] + # 以 target_idx 为中心向两侧扩散 + left = target_idx - 1 + right = target_idx + 1 + kept_order.append(target_idx) + while left >= 0 or right < len(processed): + if left >= 0: + kept_order.append(left) + left -= 1 + if right < len(processed): + kept_order.append(right) + right += 1 + kept_order = sorted({k for k in kept_order if 0 <= k < len(processed)}) + tentative = [processed[i] for i in kept_order if i != target_idx] + if target_field is not None: + # 把目标字段按原始位置放回去 + tentative_final = [] + for i in kept_order: + tentative_final.append(processed[i]) + tentative = tentative_final + # 如果还超,继续从尾部丢弃非目标字段 + while len(tentative) > 1 and _approx_json_chars(tentative) > chars_remaining: + # 找最末尾的非目标字段丢 + for reverse_idx in range(len(tentative) - 1, -1, -1): + if not tentative[reverse_idx].get('is_target'): + tentative.pop(reverse_idx) + any_trimmed = True + break + else: + break + if _approx_json_chars(tentative) <= chars_remaining: + return tentative, any_trimmed, False + + # [4] 最后,若仍超出 → 目标字段保留 core:field_id/value/quote/evidence_ref + if target_field is not None: + minimal_target = { + 'field_id': target_field.get('field_id'), + 'is_target': True, + 'value': target_field.get('value'), + 'value_source': target_field.get('value_source'), + } + if target_field.get('quote'): + minimal_target['quote'] = target_field.get('quote') + if target_field.get('evidence_ref'): + minimal_target['evidence_ref'] = target_field.get('evidence_ref') + result = [minimal_target] + if _approx_json_chars(result) > chars_remaining: + # 极端情况:quote 过长 → 不能截断核心 quote,设置 target_core_trimmed 交由 gate + target_core_trimmed = True + return result, True, target_core_trimmed + return tentative, True, False + + +def _approx_json_chars(obj: Any) -> int: + if obj is None: + return 4 + try: + return len(repr(obj)) + except Exception: + return 500 + + +def _build_v2_field_entry( + target: dict[str, Any], + evidence_view: dict[str, Any], + *, + level: str, + token_budget_chars: int, +) -> tuple[dict[str, Any], bool, bool]: + """ + 返回 (field_entry, context_truncated, target_core_trimmed)。 + field_entry 包含:field_id/field_code/scope/line_key + snippets[] + row_fields[] + + table_headers[] + neighbor_rows[] + page_text[]。 + """ + from app.services.shipping_notice.order_review_evidence_view import get_field_view + + field_id = str(target.get('field_id') or '') + line_key = str(target.get('line_key') or '').strip() or None + target_fv = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + if target_fv is None: + target_fv = { + 'field_id': field_id, + 'field_code': target.get('field_code') or field_id, + 'scope': target.get('scope'), + 'line_key': line_key, + 'llm_context_policy': 'allowed', + 'value_source': 'missing_both', + 'field_evidences': [], + 'primary_evidence': None, + } + + entry: dict[str, Any] = { + 'field_id': field_id, + 'field_code': target.get('field_code') or target_fv.get('field_code'), + 'scope': target.get('scope') or target_fv.get('scope'), + 'line_key': line_key, + 'snippets': [], + } + # snippets:摊平所有 field_evidences 的 quote/value/evidence_ref + for ev in (target_fv.get('field_evidences') or [])[:16]: + if not isinstance(ev, dict): + continue + q = str(ev.get('quote') or ev.get('value') or '').strip() + if not q: + continue + snippet: dict[str, Any] = {'quote': q[:500]} + for k in ('evidence_ref', 'source', 'page_no', 'table_id', 'row_index', 'cell_id', 'confidence'): + if ev.get(k) is not None: + snippet[k] = ev[k] + entry['snippets'].append(snippet) + + # 范围层级:默认字段数预算 + chars_used = _approx_json_chars(entry) + 80 # 预留壳 + chars_remaining = max(token_budget_chars - chars_used, 2000) + + context_truncated = False + target_core_trimmed = False + + # [LEVEL] L1_field:只保留目标字段 serialized + if level == 'L1_field': + entry['target_field'] = _serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False) + return entry, False, False + + # [LEVEL] L2_row:行 scope 包含同行其它字段(按 policy 过滤) + if level == 'L2_row': + line_fields_map = evidence_view.get('line_fields') or {} if line_key else {} + line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + row_field_items: list[dict[str, Any]] = [] + target_idx = 0 + if line_key and isinstance(line_map, dict): + for fid, fv in line_map.items(): + if not isinstance(fv, dict): + continue + pol = fv.get('llm_context_policy') or 'forbidden' + if pol == 'forbidden': + continue + if str(fid) == field_id: + target_idx = len(row_field_items) + row_field_items.append(_serialize_field_view(fv, is_target=True, strip_secondary_for_token=False)) + else: + row_field_items.append(_serialize_field_view(fv, is_target=False, strip_secondary_for_token=False)) + else: + # header scope:无 row;兜底只放目标字段 + row_field_items.append(_serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False)) + + trimmed, was_trim, core_t = _truncate_fields_list( + row_field_items, chars_remaining=chars_remaining, target_idx=target_idx, + ) + entry['row_fields'] = trimmed + entry['row_field_count'] = len(trimmed) + context_truncated = was_trim + target_core_trimmed = core_t + return entry, context_truncated, target_core_trimmed + + # [LEVEL] L3_table:表头 + 目标行 + neighbor_rows ±2 + if level == 'L3_table': + # 找目标字段的 primary evidence 的 table_id + 行范围 + pe = target_fv.get('primary_evidence') or {} + tid = str(pe.get('table_id') or '').strip() or None + page_no = pe.get('page_no') + row_index = pe.get('row_index') + table_headers: list[dict[str, Any]] = [] + neighbor_rows: list[dict[str, Any]] = [] + # 从 frozen layout 读取 table 结构 + candidates = [c for c in ((evidence_view.get('frozen_document') or {}).get('layout_schema_candidates') or []) + if isinstance(c, dict)] + matched_tables = [c for c in candidates if tid and str(c.get('table_id') or '') == tid] + matched_table = matched_tables[0] if matched_tables else (candidates[0] if candidates else None) + if matched_table: + hs = matched_table.get('headers') if isinstance(matched_table.get('headers'), list) else [] + for h in hs[:32]: + if isinstance(h, dict): + table_headers.append({ + 'column_index': h.get('column_index'), + 'field_code': h.get('field_code'), + 'display_name': h.get('text') or h.get('header'), + }) + elif isinstance(h, str) and h.strip(): + table_headers.append({'display_name': h.strip()[:120]}) + if not table_headers: + for col in (matched_table.get('columns') or [])[:32]: + if not isinstance(col, dict): + continue + path = col.get('header_path') + txt = ' '.join(str(p) for p in path if str(p).strip()) if isinstance(path, list) else '' + table_headers.append({ + 'column_index': col.get('column_index'), + 'field_code': col.get('field_code'), + 'display_name': (txt or str(col.get('header_text') or ''))[:120], + }) + # neighbor rows:row_index ±2 同 table + rows = matched_table.get('rows') or [] + ridx = int(row_index) if isinstance(row_index, int) else None + if ridx is None: + # 没找到 row_index:用 line_key 反查 + for ri, r in enumerate(rows): + if isinstance(r, dict) and str(r.get('line_key') or '') == str(line_key or ''): + ridx = ri + break + if ridx is not None: + start = max(ridx - 2, 0) + end = min(ridx + 2 + 1, len(rows)) + for pos in range(start, end): + if pos == ridx: + continue + r = rows[pos] + if not isinstance(r, dict): + continue + cell_values = [] + for raw_f in (r.get('fields') or [])[:16]: + if not isinstance(raw_f, dict): + continue + v = str(raw_f.get('value') or raw_f.get('quote') or '').strip() + if v: + cell_values.append({ + 'field_id': raw_f.get('field_id'), + 'field_code': raw_f.get('field_code'), + 'value': v[:200], + }) + neighbor_rows.append({ + 'row_index': pos, + 'line_key': r.get('line_key'), + 'cells': cell_values, + }) + # 同行字段(复用 L2 逻辑,减少字符预算) + line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {} + line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + row_field_items: list[dict[str, Any]] = [] + target_idx = 0 + if line_key and isinstance(line_map, dict): + for fid, fv in line_map.items(): + if not isinstance(fv, dict): + continue + pol = fv.get('llm_context_policy') or 'forbidden' + if pol == 'forbidden': + continue + if str(fid) == field_id: + target_idx = len(row_field_items) + row_field_items.append(_serialize_field_view(fv, is_target=True, strip_secondary_for_token=False)) + else: + row_field_items.append(_serialize_field_view(fv, is_target=False, strip_secondary_for_token=False)) + else: + row_field_items.append(_serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False)) + # 先加 table/headers,再做截断 + entry['table_headers'] = table_headers + entry['table_id'] = tid + entry['page_no'] = page_no + entry['target_row_index'] = row_index + chars_for_rows = max(chars_remaining - _approx_json_chars(table_headers) - _approx_json_chars(neighbor_rows), 800) + trimmed, was_trim, core_t = _truncate_fields_list( + row_field_items, chars_remaining=chars_for_rows, target_idx=target_idx, + ) + entry['row_fields'] = trimmed + entry['neighbor_rows'] = neighbor_rows + if was_trim or len(neighbor_rows) < (4 if ridx is not None else 0): + context_truncated = True + target_core_trimmed = core_t + return entry, context_truncated, target_core_trimmed + + # [LEVEL] L4_page:页面文本摘要(+ tables/headers 结构化) + if level == 'L4_page': + page_no_final: int | None = None + pe = target_fv.get('primary_evidence') if isinstance(target_fv.get('primary_evidence'), dict) else {} + page_no_final = pe.get('page_no') + if page_no_final is None: + for ev in (target_fv.get('field_evidences') or [])[:5]: + if isinstance(ev, dict) and ev.get('page_no'): + page_no_final = ev['page_no'] + break + # 页面文本块(frozen document layout_snapshot.text_blocks) + page_blocks: list[dict[str, Any]] = [] + frozen = evidence_view.get('frozen_document') or {} + layout = frozen.get('layout_snapshot') if isinstance(frozen.get('layout_snapshot'), dict) else {} + for block in (layout.get('text_blocks') or []): + if not isinstance(block, dict): + continue + if page_no_final and int(block.get('page_no') or 0) != int(page_no_final): + continue + txt = ' '.join(str(block.get('text') or '').split()).strip() + if txt: + page_blocks.append({ + 'page_no': block.get('page_no'), + 'block_id': str(block.get('block_id') or '')[:64] or None, + 'text': txt[:600], + }) + entry['page_blocks'] = page_blocks + entry['page_no'] = page_no_final + # 行字段保留(最小) + line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {} + line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + row_field_items: list[dict[str, Any]] = [] + if line_key and isinstance(line_map, dict): + for fid, fv in line_map.items(): + if not isinstance(fv, dict): + continue + pol = fv.get('llm_context_policy') or 'forbidden' + if pol == 'forbidden': + continue + is_t = str(fid) == field_id + row_field_items.append(_serialize_field_view(fv, is_target=is_t, strip_secondary_for_token=not is_t)) + else: + row_field_items.append(_serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False)) + trimmed, was_trim, core_t = _truncate_fields_list( + row_field_items, chars_remaining=max(chars_remaining - _approx_json_chars(page_blocks), 1000), + target_idx=0 if row_field_items and row_field_items[0].get('is_target') else 0, + ) + entry['row_fields'] = trimmed + # page 级默认视为有截断 + if len(page_blocks) * 600 > chars_remaining: + context_truncated = True + if was_trim: + context_truncated = True + target_core_trimmed = core_t + return entry, context_truncated, target_core_trimmed + + # L5_document:永不开放(按约定直接返回空壳) + entry['row_fields'] = [_serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False)] + return entry, True, False + + +def _build_v2_evidence_pack( + *, + document: dict[str, Any], + target_fields: list[dict[str, Any]], + evidence_level: str, + allow_full_pdf: bool, + evidence_view: dict[str, Any], + token_budget_chars: int, +) -> dict[str, Any]: + """ + v2 证据包: + pack.context_version = 'v2' + pack.fields[]:每个目标字段的 field 包(含 row_fields / table_headers / neighbor_rows / page_blocks) + pack.context_truncated:总体截断标志 + pack.target_core_trimmed:目标字段核心被截断 → gate 直接 evidence_truncated + """ + level = evidence_level if evidence_level in EVIDENCE_LEVELS_V2_ALLOWED else DEFAULT_V2_EVIDENCE_LEVEL + if level == 'L5_document': + return { + 'document_id': int(document.get('document_id') or 0) or None, + 'evidence_level': level, + 'context_version': 'v2', + 'fields': [], + 'context_truncated': True, + 'target_core_trimmed': False, + 'L4_forbidden_flag': True, + } + level_for_l4 = 'L4_page' + if level == level_for_l4 and not allow_full_pdf: + # 管理员未授权:降级到 L3_table(若仍不可再降到 L2_row 不 gate) + level = 'L3_table' + + pack: dict[str, Any] = { + 'document_id': int((evidence_view or {}).get('document_id') or document.get('document_id') or 0) or None, + 'evidence_level': level, + 'context_version': 'v2', + 'fields': [], + 'context_truncated': False, + 'target_core_trimmed': False, + } + + per_field_budget = max(token_budget_chars // max(len(target_fields) or 1, 1), 2000) + any_trim = False + any_core_trim = False + for target in target_fields: + if not isinstance(target, dict): + continue + entry, c_t, c_ct = _build_v2_field_entry( + target, evidence_view, level=level, token_budget_chars=per_field_budget, + ) + pack['fields'].append(entry) + if c_t: + any_trim = True + if c_ct: + any_core_trim = True + pack['context_truncated'] = any_trim + pack['target_core_trimmed'] = any_core_trim + return pack diff --git a/backend/app/services/shipping_notice/order_review_evidence_view.py b/backend/app/services/shipping_notice/order_review_evidence_view.py new file mode 100644 index 00000000..c91391b7 --- /dev/null +++ b/backend/app/services/shipping_notice/order_review_evidence_view.py @@ -0,0 +1,750 @@ +""" +services/shipping_notice/order_review_evidence_view.py + +用途:构建单一的 ReviewEvidenceView 作为 LLM 证据和复核展示的统一事实源。 +依赖: + - Review Case/Unit/Draft 实体与其 JSON 字段 + - order_review_llm_contract(evidence_ref/provenance_ref 生成与校验) + - order_review_llm_policy_registry(llm_context_policy 7 步推断) +逻辑: + - 三源合并顺序:Unit.result_json observation > Draft.machine_fields observation + > Frozen layout_schema_candidates cell evidence。 + - 所有 observation 全部摊平为 field_evidences[] 列表,不丢弃任何一条 + (后续 gate / auto_upgrade 需要检测多值冲突)。 + - 对每个 field 选一条 primary_evidence:6 步排序优先级 + evidence_ref 存在 > quote 非空 > value_bbox 可绘制 > + document_id 匹配当前 Case > confidence 最高 > 原数组顺序 + - machine_value / current_draft_value 分离;手工覆盖不同触发 manual_conflict。 +""" + +from __future__ import annotations + +import copy +import re +from typing import Any, Final + +from app.services.shipping_notice.order_review_llm_contract import ( + ObservationSource, + build_evidence_ref, + build_provenance_ref, + is_valid_evidence_ref, +) +from app.services.shipping_notice.document_layout.vc_source_evidence_integration import ( + collect_vc_field_evidences, +) +from app.services.shipping_notice.order_review_llm_policy_registry import ( + resolve_llm_context_policy, +) + +# --------------------------------------------------------------------------- +# 常量 +# --------------------------------------------------------------------------- +_MACHINE_LINE_KEY_RE = re.compile(r'^machine-(\d+)$', re.IGNORECASE) +_SOURCE_PRIORITY: Final[dict[str, int]] = { + 'unit_observation': 1, + 'draft_observation': 2, + 'frozen_layout': 3, + 'text_fallback': 4, +} + + +def _safe_int(value: Any, default: int | None = None) -> int | None: + try: + return int(value) + except (TypeError, ValueError): + return default + + +def _safe_str(value: Any) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None + + +def _observation_has_bbox(layout_evidence: Any) -> bool: + if not isinstance(layout_evidence, dict): + return False + bbox = layout_evidence.get('value_bbox') + if not isinstance(bbox, dict): + return False + try: + for key in ('x0', 'y0', 'x1', 'y1'): + f = float(bbox[key]) + if not (0 <= f <= 1.01): + return False + return 0 <= float(bbox['x0']) < float(bbox['x1']) <= 1 and \ + 0 <= float(bbox['y0']) < float(bbox['y1']) <= 1 + except (KeyError, TypeError, ValueError): + return False + + +def _normalize_observation( + raw: Any, + *, + source: ObservationSource, + case_document_id: int, + case_id: int, + field_code: str | None = None, + line_key: str | None = None, + derived_row_index: int | None = None, +) -> dict[str, Any]: + """ + 规范化单条 observation(Unit/Draft/FrozenLayout 共用)。 + 缺失字段显式置 None,绝不伪造。 + """ + if not isinstance(raw, dict): + raw = {} + layout = raw.get('layout_evidence') if isinstance(raw.get('layout_evidence'), dict) else {} + doc_id = _safe_int(raw.get('document_id') or layout.get('document_id')) + page_no = _safe_int(layout.get('page_no')) + table_id = _safe_str(layout.get('table_id') or raw.get('table_id')) + cell_id = _safe_str(layout.get('cell_id') or raw.get('cell_id')) + row_index = _safe_int(layout.get('row_index') or derived_row_index) + quote = _safe_str(raw.get('quote')) + value_raw = raw.get('value') + value = None if value_raw is None else (str(value_raw).strip() if not isinstance(value_raw, (int, float, bool)) else value_raw) + + layout_evidence_ref = layout.get('evidence_ref') if isinstance(layout, dict) else None + evidence_ref = None + if isinstance(layout_evidence_ref, str) and is_valid_evidence_ref(layout_evidence_ref): + evidence_ref = layout_evidence_ref.strip() + if not evidence_ref and doc_id and page_no: + evidence_ref = build_evidence_ref( + document_id=doc_id, + page_no=page_no, + table_id=table_id, + row_index=row_index, + field_code=field_code, + ) + + provenance_ref: str | None = None + if source == 'draft_observation' or source == 'text_fallback': + provenance_ref = build_provenance_ref( + case_id=case_id, line_key=line_key, field_code=field_code or '', + ) + + confidence_raw = raw.get('confidence') + try: + confidence = float(confidence_raw) if confidence_raw is not None else None + except (TypeError, ValueError): + confidence = None + + return { + 'value': value, + 'quote': quote, + 'source': source, + 'confidence': confidence, + 'evidence_ref': evidence_ref, + 'provenance_ref': provenance_ref, + 'document_id': doc_id, + 'page_no': page_no, + 'table_id': table_id, + 'cell_id': cell_id, + 'row_index': row_index, + 'value_bbox_valid': _observation_has_bbox({'layout_evidence': layout}), + 'document_matches_case': bool(doc_id) and int(doc_id) == int(case_document_id), + } + + +def _sort_key_primary_evidence(ev: dict[str, Any]) -> tuple: + """ + 主证据选择 6 步排序(越小越好): + 1. evidence_ref 存在 + 2. quote 非空 + 3. value_bbox_valid + 4. document_matches_case + 5. confidence 高(用负数以升序排列;None 视为最低) + 6. source 优先级数字越小越好(unit < draft < frozen < fallback) + """ + ev_source = str(ev.get('source') or 'text_fallback') + source_priority = _SOURCE_PRIORITY.get(ev_source, 99) + conf = ev.get('confidence') + try: + conf_score = 1.0 - float(conf) if conf is not None else 2.0 + except (TypeError, ValueError): + conf_score = 2.0 + return ( + 0 if ev.get('evidence_ref') else 1, + 0 if ev.get('quote') else 1, + 0 if ev.get('value_bbox_valid') else 1, + 0 if ev.get('document_matches_case') else 1, + conf_score, + source_priority, + ) + + +# --------------------------------------------------------------------------- +# 三源读取 +# --------------------------------------------------------------------------- +def _read_unit_result_json(unit) -> dict[str, Any] | None: + result = getattr(unit, 'result_json', None) + return result if isinstance(result, dict) else None + + +def _select_order_from_unit(unit_result: dict[str, Any], case_document_id: int) -> tuple[dict[str, Any] | None, list[str]]: + """ + orders = 0 → None;orders = 1 → 直接取;orders > 1 → primary_document_id 优先。 + 返回 (order_obj, context_ambiguous_reason_list) + """ + reasons: list[str] = [] + orders = unit_result.get('orders') or [] + if not isinstance(orders, list) or not orders: + return None, ['unit_orders_empty'] + actual = [o for o in orders if isinstance(o, dict)] + if len(actual) == 1: + return actual[0], reasons + # >1:按 primary_document_id 匹配 case.document_id + matched = [ + o for o in actual + if _safe_int(o.get('primary_document_id')) == int(case_document_id) + ] + if len(matched) == 1: + return matched[0], reasons + if len(matched) > 1: + reasons.append('multi_orders_share_primary_document_id') + return matched[0], reasons + reasons.append('unit_orders_ambiguous') + return actual[0], reasons + + +def _iter_unit_header_fields(order_result: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]: + """返回 [(field_id, field_obj)];field_obj 含 observations[]。""" + out: list[tuple[str, dict[str, Any]]] = [] + for raw in order_result.get('header_fields') or []: + if not isinstance(raw, dict): + continue + fid = _safe_str(raw.get('field_id')) + if not fid: + continue + out.append((fid, raw)) + return out + + +def _iter_unit_line_fields( + order_result: dict[str, Any], +) -> list[tuple[str, int, str, dict[str, Any]]]: + """返回 [(line_key, row_position, field_id, field_obj)]""" + out: list[tuple[str, int, str, dict[str, Any]]] = [] + lines = order_result.get('lines') or [] + for pos, line in enumerate(lines): + if not isinstance(line, dict): + continue + line_key = _safe_str(line.get('line_key')) + if not line_key: + index_match = _MACHINE_LINE_KEY_RE.match(f'machine-{pos + 1}') + line_key = index_match.group(0) if index_match else f'machine-{pos + 1}' + for field_obj in line.get('fields') or []: + if not isinstance(field_obj, dict): + continue + fid = _safe_str(field_obj.get('field_id')) + if not fid: + continue + out.append((line_key, pos, fid, field_obj)) + return out + + +# --------------------------------------------------------------------------- +# 辅助:把 Draft values 取当前草稿值(不含 observation,用于 machine vs draft 差异) +# --------------------------------------------------------------------------- +def _draft_header_container(draft) -> dict[str, Any]: + hv = getattr(draft, 'header_values_json', None) + return hv if isinstance(hv, dict) else {} + + +def _draft_line_list(draft) -> list[dict[str, Any]]: + lines = getattr(draft, 'lines_json', None) + return [ln for ln in (lines if isinstance(lines, list) else []) if isinstance(ln, dict)] + + +def _find_draft_line(lines: list[dict[str, Any]], line_key: str) -> dict[str, Any] | None: + for ln in lines: + if _safe_str(ln.get('line_key')) == line_key: + return ln + return None + + +def _machine_field_value(container: dict[str, Any], field_id: str) -> dict[str, Any] | None: + """ + 从 Draft.header_values_json 或 lines_json[].machine_fields 中按 field_id 取机器对象。 + 对象至少包含 observations[] / value / field_code。 + """ + machine_fields = container.get('machine_fields') or [] + for raw in machine_fields: + if not isinstance(raw, dict): + continue + if _safe_str(raw.get('field_id')) == field_id: + return raw + return None + + +def _current_draft_value(container: dict[str, Any], field_id: str) -> Any: + values = container.get('values') + if not isinstance(values, dict): + values = container if container.get('values') is None else {} + if isinstance(values, dict) and field_id in values: + return values[field_id] + # 兼容:直接在 container 里以 field_id/field_code 存值 + return None + + +# --------------------------------------------------------------------------- +# 冻结 snapshot layout_schema_candidates → 第三来源 +# --------------------------------------------------------------------------- +def _frozen_document_snapshot(case) -> dict[str, Any]: + snapshot = case.run.input_snapshot_json if case.run and isinstance(case.run.input_snapshot_json, dict) else {} + for intake in snapshot.get('intakes') or []: + if not isinstance(intake, dict): + continue + for document in intake.get('documents') or []: + if isinstance(document, dict) and _safe_int(document.get('document_id')) == int(case.document_id): + return document + return {'document_id': int(case.document_id)} + + +def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, str, int | None, str, dict[str, Any]]]: + """ + 返回 [(line_key_or_header, field_id, row_index, table_id, raw_field_obj)]。 + header scope 行 line_key=None。 + """ + out: list[tuple[str, str, int | None, str, dict[str, Any]]] = [] + candidates = [ + c for c in (frozen_doc.get('layout_schema_candidates') or []) + if isinstance(c, dict) + ] + for candidate in candidates: + table_id = _safe_str(candidate.get('table_id')) or '' + rows = candidate.get('rows') or [] + for row_idx, row in enumerate(rows): + if not isinstance(row, dict): + continue + line_key = _safe_str(row.get('line_key')) + data_row_idx = _safe_int(row.get('data_row_index') or row.get('row_index')) + for raw_field in row.get('fields') or []: + if not isinstance(raw_field, dict): + continue + fid = _safe_str(raw_field.get('field_id')) + if not fid: + continue + effective_line_key = line_key + out.append(( + effective_line_key, + fid, + data_row_idx, + table_id, + raw_field, + )) + return out + + +# --------------------------------------------------------------------------- +# Schema 字段元数据读取(用于 policy 注册表) +# --------------------------------------------------------------------------- +def _schema_fields_map(case) -> dict[str, dict[str, Any]]: + snapshot = case.run.input_snapshot_json if case.run and isinstance(case.run.input_snapshot_json, dict) else {} + schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} + definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {} + result: dict[str, dict[str, Any]] = {} + for raw in definition.get('fields') or []: + if not isinstance(raw, dict): + continue + fid = _safe_str(raw.get('field_id')) + if not fid: + continue + result[fid] = dict(raw) + return result + + +# --------------------------------------------------------------------------- +# 证据视图公共骨架 +# --------------------------------------------------------------------------- +_FIELD_VIEW_KEYS = ( + 'field_id', 'field_code', 'display_name', 'scope', + 'data_type', 'llm_context_policy', + 'line_key', + 'machine_value', 'current_draft_value', 'value_source', + 'primary_evidence', 'field_evidences', +) + + +def _empty_field_view() -> dict[str, Any]: + return {k: None for k in _FIELD_VIEW_KEYS} | { + 'field_evidences': [], + } + + +def _build_field_view( + *, + field_id: str, + field_metadata: dict[str, Any] | None, + scope: Literal['header', 'line'], + line_key: str | None, + case_id: int, + case_document_id: int, +) -> dict[str, Any]: + view = _empty_field_view() + md = field_metadata or {} + code = _safe_str(md.get('field_code')) or field_id + view['field_id'] = field_id + view['field_code'] = code + view['display_name'] = _safe_str(md.get('display_name')) or code + view['scope'] = scope + view['data_type'] = _safe_str(md.get('data_type')) + view['line_key'] = line_key + policy = resolve_llm_context_policy( + field_metadata=md, + field_code=code, + scope=scope, + data_type=view['data_type'], + is_target_field=False, + ) + view['llm_context_policy'] = policy + view['machine_value'] = None + view['current_draft_value'] = None + view['value_source'] = None # manual_override / machine_only / draft_machine / fallback_missing + return view + + +def _finalize_field_evidences(view: dict[str, Any]) -> None: + """摊平后,选 primary_evidence,并判断是否存在 manual_conflict。""" + evidences = view.get('field_evidences') or [] + if evidences: + sorted_evs = sorted(evidences, key=_sort_key_primary_evidence) + view['primary_evidence'] = copy.deepcopy(sorted_evs[0]) + view['field_evidences'] = sorted_evs + if view['machine_value'] is None: + first_val = None + for ev in sorted_evs: + if ev.get('value') is not None and str(ev.get('value') or '').strip() != '': + first_val = ev['value'] + break + view['machine_value'] = first_val + else: + view['primary_evidence'] = None + + machine = view.get('machine_value') + draft = view.get('current_draft_value') + + def _text(v: Any) -> str: + if v is None: + return '' + if isinstance(v, (int, float, bool)): + return str(v) + return str(v).strip() + + machine_text = _text(machine) + draft_text = _text(draft) + if draft_text and machine_text and draft_text != machine_text: + view['value_source'] = 'manual_override' + elif draft_text and not machine_text: + view['value_source'] = 'manual_only' + elif machine_text and (not draft_text or draft_text == machine_text): + view['value_source'] = 'machine_only' + else: + view['value_source'] = 'missing_both' + + +# --------------------------------------------------------------------------- +# 对外主入口 +# --------------------------------------------------------------------------- +def build_review_evidence_view(case) -> dict[str, Any]: + """ + 为当前 Case 构建 ReviewEvidenceView。 + + 返回结构: + { + "case_id": int, + "document_id": int, + "case_no": str, + "schema_version_id": int | None, + "diagnostics": { "unit_orders_ambiguous": bool, "context_ambiguous_reasons": [] }, + "header_fields": { [field_id]: field_view }, + "line_fields": { + [line_key]: { [field_id]: field_view } + }, + "lines_order": [line_key...], + "layout_schema_candidates": [frozen_candidate...], // 直接引用,不 clone + "frozen_document_snapshot": dict, // 只读 + } + """ + case_id = int(case.id) + case_document_id = int(case.document_id) + schema_fields = _schema_fields_map(case) + + diagnostics: dict[str, Any] = { + 'unit_orders_ambiguous': False, + 'context_ambiguous_reasons': [], + 'warnings': [], + } + + header_fields: dict[str, dict[str, Any]] = {} + line_fields: dict[str, dict[str, dict[str, Any]]] = {} + lines_order: list[str] = [] + + def _ensure_field( + fid: str, + scope: Literal['header', 'line'], + line_key: str | None = None, + ) -> dict[str, Any]: + if scope == 'header': + if fid not in header_fields: + header_fields[fid] = _build_field_view( + field_id=fid, + field_metadata=schema_fields.get(fid), + scope='header', + line_key=None, + case_id=case_id, + case_document_id=case_document_id, + ) + return header_fields[fid] + assert line_key + if line_key not in line_fields: + line_fields[line_key] = {} + lines_order.append(line_key) + line_map = line_fields[line_key] + if fid not in line_map: + line_map[fid] = _build_field_view( + field_id=fid, + field_metadata=schema_fields.get(fid), + scope='line', + line_key=line_key, + case_id=case_id, + case_document_id=case_document_id, + ) + return line_map[fid] + + # [SOURCE 1] Unit.result_json → 最高优先级 observation + unit = getattr(case, 'unit', None) + if unit is not None: + unit_result = _read_unit_result_json(unit) + if unit_result: + order, reasons = _select_order_from_unit(unit_result, case_document_id) + if reasons: + diagnostics['unit_orders_ambiguous'] = True + diagnostics['context_ambiguous_reasons'].extend(reasons) + if order: + for fid, raw_field in _iter_unit_header_fields(order): + fv = _ensure_field(fid, 'header') + observations = raw_field.get('observations') or [] + fc = _safe_str(raw_field.get('field_code')) or fv['field_code'] + for idx, raw_obs in enumerate(observations): + if not isinstance(raw_obs, dict): + continue + norm = _normalize_observation( + raw_obs, + source='unit_observation', + case_document_id=case_document_id, + case_id=case_id, + field_code=fc, + ) + fv['field_evidences'].append(norm) + if fv['machine_value'] is None: + v = raw_field.get('value') + if v is not None: + fv['machine_value'] = v + + for line_key, _pos, fid, raw_field in _iter_unit_line_fields(order): + fv = _ensure_field(fid, 'line', line_key=line_key) + observations = raw_field.get('observations') or [] + fc = _safe_str(raw_field.get('field_code')) or fv['field_code'] + for raw_obs in observations: + if not isinstance(raw_obs, dict): + continue + norm = _normalize_observation( + raw_obs, + source='unit_observation', + case_document_id=case_document_id, + case_id=case_id, + field_code=fc, + line_key=line_key, + ) + fv['field_evidences'].append(norm) + if fv['machine_value'] is None: + v = raw_field.get('value') + if v is not None: + fv['machine_value'] = v + + # [SOURCE 2] Review Draft machine_fields observation + current_draft_value + draft = case.current_draft + if draft is not None: + schema_version_id = getattr(draft, 'schema_version_id', None) + else: + schema_version_id = None + + if draft is not None: + # Header + header_container = _draft_header_container(draft) + for fid in set(list(header_fields.keys()) + list(schema_fields.keys())): + md = schema_fields.get(fid) + scope = 'header' + if md and _safe_str(md.get('scope')) == 'line': + continue + fv = _ensure_field(fid, scope='header') + obj = _machine_field_value(header_container, fid) + if isinstance(obj, dict): + for raw_obs in (obj.get('observations') or []): + if not isinstance(raw_obs, dict): + continue + norm = _normalize_observation( + raw_obs, + source='draft_observation', + case_document_id=case_document_id, + case_id=case_id, + field_code=_safe_str(obj.get('field_code')) or fv['field_code'], + ) + fv['field_evidences'].append(norm) + if fv['machine_value'] is None and obj.get('value') is not None: + fv['machine_value'] = obj.get('value') + fv['current_draft_value'] = _current_draft_value(header_container, fid) + + # Lines + draft_lines = _draft_line_list(draft) + for line in draft_lines: + line_key = _safe_str(line.get('line_key')) + if not line_key: + continue + line_map = line_fields.setdefault(line_key, {}) + if line_key not in lines_order: + lines_order.append(line_key) + for fid in list(line_map.keys()) + list(schema_fields.keys()): + md = schema_fields.get(fid) + if md and _safe_str(md.get('scope')) == 'header': + continue + fv = _ensure_field(fid, 'line', line_key=line_key) + obj = _machine_field_value(line, fid) + if isinstance(obj, dict): + for raw_obs in (obj.get('observations') or []): + if not isinstance(raw_obs, dict): + continue + norm = _normalize_observation( + raw_obs, + source='draft_observation', + case_document_id=case_document_id, + case_id=case_id, + field_code=_safe_str(obj.get('field_code')) or fv['field_code'], + line_key=line_key, + ) + fv['field_evidences'].append(norm) + if fv['machine_value'] is None and obj.get('value') is not None: + fv['machine_value'] = obj.get('value') + fv['current_draft_value'] = _current_draft_value(line, fid) + + # [SOURCE 3] 冻结 snapshot layout_schema_candidates + frozen_doc = _frozen_document_snapshot(case) + for lk, fid, ridx, tid, raw_field in _iter_frozen_layout_fields(frozen_doc): + scope = 'line' if lk else 'header' + fv = _ensure_field(fid, scope=scope, line_key=lk or None) + wrapped = { + 'value': raw_field.get('value') or raw_field.get('quote'), + 'quote': raw_field.get('quote') or raw_field.get('value'), + 'document_id': case_document_id, + 'layout_evidence': { + 'page_no': raw_field.get('page_no') or frozen_doc.get('page_no'), + 'table_id': tid or None, + 'cell_id': raw_field.get('cell_id'), + 'row_index': ridx, + 'evidence_ref': raw_field.get('evidence_ref'), + 'value_bbox': raw_field.get('value_bbox'), + }, + 'confidence': raw_field.get('confidence'), + } + norm = _normalize_observation( + wrapped, + source='frozen_layout', + case_document_id=case_document_id, + case_id=case_id, + field_code=fv['field_code'], + line_key=lk or None, + derived_row_index=ridx, + ) + fv['field_evidences'].append(norm) + + # [SOURCE 4] Vendor Comments 三来源 source_observations(Phase 4 新增) + # 追加:不覆盖/替换原有 Unit/Draft/Frozen 三源,仅扩展 LLM 上下文与工作台证据对照。 + # 在 finalize 之前插入,以便 _finalize_field_evidences 正确选 primary 与 value_source。 + vc_evidences = collect_vc_field_evidences( + case_or_candidate=case, + case_document_id=case_document_id, + ) + for vc_ev in vc_evidences: + if not isinstance(vc_ev, dict): + continue + scope_ok = str(vc_ev.get('field_code') or vc_ev.get('source_kind') or '').strip() + line_key = vc_ev.get('line_key') + field_code = vc_ev.get('field_code') + # 反查 field_id:优先用 schema_fields key→field_code 匹配;找不到则安全跳过不伪造。 + fid = None + for f_id, meta in schema_fields.items(): + if isinstance(meta, dict) and str(meta.get('field_code') or '').strip() == str(field_code or '').strip(): + fid = f_id + break + if not fid: + # 找不到 schema 映射的 VC 字段不注入,防止污染未定义字段。 + continue + scope_meta = schema_fields.get(fid, {}) + scope = 'header' if str(scope_meta.get('scope') or '').strip() == 'header' or (isinstance(scope_meta, dict) and line_key is None) else 'line' + if scope == 'line' and line_key is None: + line_key = 'header' + fv = _ensure_field(fid, scope=scope, line_key=None if scope == 'header' else str(line_key or 'header')) + fv['field_evidences'].append(vc_ev) + + # finalize:选 primary + value_source 判定 + for fv in header_fields.values(): + _finalize_field_evidences(fv) + for lm in line_fields.values(): + for fv in lm.values(): + _finalize_field_evidences(fv) + + return { + 'case_id': case_id, + 'document_id': case_document_id, + 'case_no': str(getattr(case, 'case_no', '')), + 'schema_version_id': schema_version_id, + 'diagnostics': diagnostics, + 'header_fields': header_fields, + 'line_fields': line_fields, + 'lines_order': lines_order, + 'frozen_document': frozen_doc, + } + + +# --------------------------------------------------------------------------- +# 便捷工具:从视图中取 header 或某 line 的 field_view +# --------------------------------------------------------------------------- +def get_field_view( + view: dict[str, Any], + *, + field_id: str, + line_key: str | None, +) -> dict[str, Any] | None: + fid = str(field_id or '').strip() + if not fid: + return None + if line_key: + lk = str(line_key).strip() + line_map = view.get('line_fields') or {} + row = line_map.get(lk) or {} + return row.get(fid) or None + return (view.get('header_fields') or {}).get(fid) + + +def count_valid_row_fields(view: dict[str, Any], line_key: str) -> int: + """ + 同行中“有值且可发送”的字段数量(evidence 有值或 machine_value/draft_value 非空)。 + 用于门禁:同行字段数 >= 2 才允许 L2_row。 + """ + lk = str(line_key or '').strip() + line_map = (view.get('line_fields') or {}).get(lk) or {} + count = 0 + for fv in line_map.values(): + policy = fv.get('llm_context_policy') or 'forbidden' + if policy == 'forbidden': + continue + mv = fv.get('machine_value') + dv = fv.get('current_draft_value') + pe = fv.get('primary_evidence') + if (mv is not None and str(mv).strip() != '') or \ + (dv is not None and str(dv).strip() != '') or \ + (pe is not None and (str(pe.get('value') or '').strip() or str(pe.get('quote') or '').strip())): + count += 1 + return count diff --git a/backend/app/services/shipping_notice/order_review_field_conflict_service.py b/backend/app/services/shipping_notice/order_review_field_conflict_service.py index 6f6c03bf..018428a9 100644 --- a/backend/app/services/shipping_notice/order_review_field_conflict_service.py +++ b/backend/app/services/shipping_notice/order_review_field_conflict_service.py @@ -34,6 +34,11 @@ from app.services.shipping_notice.pdf_priority_adjudication import ( is_primary_pdf_source_type, ) from app.services.shipping_notice.progress_audit_contract import PDF_PRIORITY_EVIDENCE_RANKS +from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import ( + collect_vc_candidate_conflicts, +) + +_VC_CONFLICT_PREFIX = 'vc:' def _conflict_key(*, field: str, line_index: Any) -> str: @@ -197,22 +202,109 @@ def _field_id_for_code(case: ShippingOrderReviewCase, field_code: str, *, scope: return None +def _project_vc_candidate_conflicts( + *, + case: ShippingOrderReviewCase, + candidate: ShippingOrderCandidate, +) -> list[dict[str, Any]]: + """ + 将 Vendor Comments 三来源冲突项投影为与普通字段冲突兼容的工作台格式。 + + 核心逻辑: + - conflict_key 加 vc: 前缀,避免与 line_index:field_code 格式冲突; + - 从 detail.sources 中提取候选来源值组装 options(含 vc_source_kind 标记); + - format_invalid / region_unbound 类冲突若仅有单一来源,则仍保留一项用于展示诊断。 + """ + items: list[dict[str, Any]] = [] + try: + vc_items = collect_vc_candidate_conflicts(candidate) + except Exception: # noqa: BLE001 — 投影层 fail-open:异常不影响其他冲突展示 + return items + for vc in vc_items: + if not isinstance(vc, dict): + continue + field_code = str(vc.get('field_code') or '').strip() + if not field_code: + continue + scope_raw = str(vc.get('scope') or 'line').strip() + line_no_safe = vc.get('line_no') + try: + line_index = int(line_no_safe) - 1 if scope_raw != 'header' and line_no_safe not in (None, '') else -1 + except (TypeError, ValueError): + line_index = -1 + detail = vc.get('detail') if isinstance(vc.get('detail'), dict) else {} + sources = list(detail.get('sources') or []) if isinstance(detail.get('sources'), list) else [] + options: list[dict[str, Any]] = [] + seen: set[str] = set() + for src in sources: + if not isinstance(src, dict): + continue + vp = src.get('value_preview') + if vp in (None, ''): + continue + key = str(vp).strip() + if key in seen: + continue + seen.add(key) + source_kind = str(src.get('source') or '').strip() + source_label = str(src.get('source_label') or source_kind).strip() + options.append({ + 'value_key': key, + 'display_value': vp, + 'sources': [source_label] if source_label else [], + 'source_type': None, + 'source_types': [source_kind] if source_kind else [], + 'evidence_role': 'auxiliary', + 'evidence_rank': None, + 'vc_source_kind': source_kind, + 'vc_source_kind_label': source_label, + 'evidence_ref': src.get('evidence_ref'), + }) + # 对于 format_invalid / region_unbound 类诊断,即使无多选值也继续投影,便于工作台展示原因。 + cg_key = str(vc.get('conflict_group_key') or '').strip() + conflict_key = _VC_CONFLICT_PREFIX + (cg_key or f'{scope_raw}:{field_code}:{line_no_safe or "_"}') + line_key = vc.get('line_key') if scope_raw != 'header' else ( + _line_key_for_index(case, line_index) if line_index >= 0 else None + ) + items.append({ + 'conflict_key': conflict_key, + 'field_code': field_code, + 'line_index': line_index if line_index >= 0 else None, + 'line_key': line_key, + 'severity': str(vc.get('severity') or 'blocking'), + 'reason': str(vc.get('reason') or 'vc_source_conflict_unresolved'), + 'options': options, + 'observation_ids': [], + 'vc_kind': True, + 'vc_reason': str(vc.get('reason') or ''), + 'vc_conflict_group_key': cg_key or None, + 'vc_detail': { + 'resolution': detail.get('resolution'), + 'decision_status': detail.get('decision_status'), + 'format_valid': detail.get('format_valid'), + }, + }) + return items + + def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[dict[str, Any]]: """ 投影建单前仍未裁决的字段冲突,供复核工作台集中展示。 + 合并两类冲突: + 1. 传统 Observation/Adjudication 字段冲突(来自 candidate.conflicts_json); + 2. Vendor Comments 三来源冲突(collect_vc_candidate_conflicts 动态产出,vc_kind=True)。 + Returns: 冲突列表;每项含 conflict_key、field_code、line_index、options、reason。 """ candidate = _candidate_for_case(case) if candidate is None: return [] + projected: list[dict[str, Any]] = [] raw_conflicts = list(candidate.conflicts_json or []) - if not raw_conflicts: - return [] adjudication = _adjudication_blob(candidate) observations = _observations_index(adjudication) - projected: list[dict[str, Any]] = [] for item in raw_conflicts: if not isinstance(item, dict): continue @@ -250,9 +342,60 @@ def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[d 'options': options, 'observation_ids': observation_ids, }) + projected.extend(_project_vc_candidate_conflicts(case=case, candidate=candidate)) return projected +def _resolve_vc_candidate_decision( + *, + candidate: ShippingOrderCandidate, + conflict_group_key: str, + chosen_value: Any, +) -> None: + """ + 在 Vendor Comments merged_candidates 快照中标记对应项为人工裁决接受。 + + 核心逻辑:定位 conflict_group_key 匹配的 merged_candidate → + 覆写 decision_status=accepted / resolution=manual_review / accepted_value=chosen_value → + 后续 collect_vc_candidate_conflicts 将自动跳过该项(resolution!=needs_review 或 decision=accepted/dropped)。 + """ + from datetime import datetime # noqa: PLC0415 — 延迟 import 避免模块级循环依赖 + + structured = dict(candidate.structured_result_json or {}) + extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {} + vc_merged = extraction.get('vendor_comments_merged') + if not isinstance(vc_merged, dict): + return + merged_list = vc_merged.get('merged_candidates') + if not isinstance(merged_list, list): + return + updated_list: list[dict[str, Any]] = [] + for cand in merged_list: + if not isinstance(cand, dict): + updated_list.append(cand) + continue + field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip() + scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip() + scope_ok = 'header' if scope == 'header' else 'line' + line_no_raw = cand.get('effective_line_no') or cand.get('line_no') + line_no_safe = None if line_no_raw is None else str(line_no_raw) + safe_line = str(line_no_safe or '').strip() or '_' + ckey = f'{scope_ok}:{field_code}:{safe_line}' + if ckey == str(conflict_group_key or '').strip(): + cand = { + **cand, + 'decision_status': 'accepted', + 'resolution': 'manual_review', + 'accepted_value': chosen_value, + 'manual_resolved_at': datetime.utcnow().isoformat(), + } + updated_list.append(cand) + vc_merged['merged_candidates'] = updated_list + extraction['vendor_comments_merged'] = vc_merged + structured['extraction'] = extraction + candidate.structured_result_json = structured + + def resolve_review_case_field_conflict( *, user_id: int, @@ -267,6 +410,11 @@ def resolve_review_case_field_conflict( """ 裁决建单前字段冲突:写入 Draft 值、清除 Candidate 冲突项、重校验资格。 + 支持两类 conflict_key: + - 传统格式(line_index:field_code):从 candidate.conflicts_json 删除匹配项并写回 adjudication; + - vc: 前缀格式(Vendor Comments 三来源冲突):定位 conflict_group_key, + 覆写 merged_candidates.decision_status=accepted,后续门禁自动放行。 + Args: resolution: adopt_option | custom option_index: adopt_option 时选用 options[i] @@ -277,6 +425,8 @@ def resolve_review_case_field_conflict( Returns: {'case': 最新 Case 投影, 'field_conflicts': 剩余冲突列表}。 """ + from datetime import datetime # noqa: PLC0415 — 延迟 import 避免模块级循环依赖 + action = 'field_conflict_resolved' case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) @@ -286,61 +436,171 @@ def resolve_review_case_field_conflict( 'Review case has no candidate for field conflict resolution', code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', ) - conflicts = list(candidate.conflicts_json or []) - target_idx = -1 - target: dict[str, Any] | None = None - for idx, item in enumerate(conflicts): - if not isinstance(item, dict): - continue - key = _conflict_key(field=item.get('field'), line_index=item.get('line_index')) - if key == str(conflict_key or '').strip(): - target_idx = idx - target = item - break - if target is None or target_idx < 0: - raise NotFoundError( - 'Field conflict not found', - code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', - details={'conflict_key': conflict_key}, - ) - field_code = str(target.get('field') or '').strip() - try: - line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1 - except (TypeError, ValueError): - line_index = -1 - value_keys = [str(v) for v in (target.get('values') or []) if v not in (None, '')] - mode = str(resolution or '').strip().lower() + raw_key = str(conflict_key or '').strip() + is_vc_conflict = raw_key.startswith(_VC_CONFLICT_PREFIX) + + field_code = '' + line_index = -1 chosen_display: Any = None - if mode == 'adopt_option': - if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys): - raise ValidationError( - 'option_index is required for adopt_option', - code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID', - ) - observations = _observations_index(_adjudication_blob(candidate)) - option = _option_display( - field=field_code, - value_key=value_keys[int(option_index)], - observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid], - observations=observations, - ) - chosen_display = option.get('display_value') - elif mode == 'custom': - if custom_value in (None, ''): - raise ValidationError( - 'custom_value is required', - code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED', - ) - chosen_display = custom_value - else: - raise ValidationError( - 'Invalid conflict resolution', - code='SHIPPING.INVALID_CONFLICT_RESOLUTION', - details={'resolution': resolution}, - ) + mode = str(resolution or '').strip().lower() - # [STEP 1] 写入 Draft 人工值。 + if is_vc_conflict: + vc_group_key = raw_key[len(_VC_CONFLICT_PREFIX):] + try: + vc_items = collect_vc_candidate_conflicts(candidate) + except Exception as exc: # noqa: BLE001 + raise NotFoundError( + 'VC conflict not accessible', + code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', + details={'conflict_key': conflict_key}, + ) from exc + target_vc: dict[str, Any] | None = None + for vc in vc_items: + if not isinstance(vc, dict): + continue + scope_raw = str(vc.get('scope') or 'line').strip() + scope_ok = 'header' if scope_raw == 'header' else 'line' + line_no_safe = vc.get('line_no') + safe_line = str(line_no_safe or '').strip() or '_' + fcode = str(vc.get('field_code') or '').strip() + ckey = f'{scope_ok}:{fcode}:{safe_line}' + want_cg = str(vc.get('conflict_group_key') or ckey).strip() + if want_cg == vc_group_key: + target_vc = vc + field_code = fcode + if scope_ok != 'header' and line_no_safe not in (None, ''): + try: + line_index = int(line_no_safe) - 1 + except (TypeError, ValueError): + line_index = -1 + break + if target_vc is None: + raise NotFoundError( + 'VC conflict not found', + code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', + details={'conflict_key': conflict_key}, + ) + detail = target_vc.get('detail') if isinstance(target_vc.get('detail'), dict) else {} + sources = list(detail.get('sources') or []) if isinstance(detail.get('sources'), list) else [] + value_options: list[tuple[str, Any]] = [] + seen: set[str] = set() + for src in sources: + if not isinstance(src, dict): + continue + vp = src.get('value_preview') + if vp in (None, ''): + continue + k = str(vp).strip() + if k in seen: + continue + seen.add(k) + value_options.append((k, vp)) + if mode == 'adopt_option': + if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_options): + raise ValidationError( + 'option_index is required for adopt_option', + code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID', + ) + chosen_display = value_options[int(option_index)][1] + elif mode == 'custom': + if custom_value in (None, ''): + raise ValidationError( + 'custom_value is required', + code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED', + ) + chosen_display = custom_value + else: + raise ValidationError( + 'Invalid conflict resolution', + code='SHIPPING.INVALID_CONFLICT_RESOLUTION', + details={'resolution': resolution}, + ) + else: + conflicts = list(candidate.conflicts_json or []) + target_idx = -1 + target: dict[str, Any] | None = None + for idx, item in enumerate(conflicts): + if not isinstance(item, dict): + continue + key = _conflict_key(field=item.get('field'), line_index=item.get('line_index')) + if key == raw_key: + target_idx = idx + target = item + break + if target is None or target_idx < 0: + raise NotFoundError( + 'Field conflict not found', + code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', + details={'conflict_key': conflict_key}, + ) + field_code = str(target.get('field') or '').strip() + try: + line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1 + except (TypeError, ValueError): + line_index = -1 + value_keys = [str(v) for v in (target.get('values') or []) if v not in (None, '')] + if mode == 'adopt_option': + if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys): + raise ValidationError( + 'option_index is required for adopt_option', + code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID', + ) + observations = _observations_index(_adjudication_blob(candidate)) + option = _option_display( + field=field_code, + value_key=value_keys[int(option_index)], + observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid], + observations=observations, + ) + chosen_display = option.get('display_value') + elif mode == 'custom': + if custom_value in (None, ''): + raise ValidationError( + 'custom_value is required', + code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED', + ) + chosen_display = custom_value + else: + raise ValidationError( + 'Invalid conflict resolution', + code='SHIPPING.INVALID_CONFLICT_RESOLUTION', + details={'resolution': resolution}, + ) + conflicts.pop(target_idx) + candidate.conflicts_json = conflicts + structured = dict(candidate.structured_result_json or {}) + extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {} + adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {} + decisions = list(adjudication.get('decisions') or []) + updated_decisions = [] + for decision in decisions: + if not isinstance(decision, dict): + continue + same_field = str(decision.get('field') or '') == field_code + same_line = True + if line_index >= 0: + try: + same_line = int(decision.get('line_index')) == line_index + except (TypeError, ValueError): + same_line = False + if same_field and same_line: + updated_decisions.append({ + **decision, + 'status': 'selected', + 'value': chosen_display, + 'resolution_method': 'manual_review', + }) + else: + updated_decisions.append(decision) + adjudication['decisions'] = updated_decisions + adjudication['conflicts'] = list(conflicts) + extraction['field_adjudication'] = adjudication + structured['extraction'] = extraction + candidate.structured_result_json = structured + db.session.flush() + + # [STEP 1] 写入 Draft 人工值(两条路径共享)。 scope = 'line' if line_index >= 0 else 'header' field_id = _field_id_for_code(case, field_code, scope=scope) if not field_id: @@ -379,39 +639,15 @@ def resolve_review_case_field_conflict( change = _set_value(target_line, field, chosen_display, restore_machine=False) case.current_draft.lines_json = lines - # [STEP 2] 清除 Candidate 冲突项,并同步 adjudication decision。 - conflicts.pop(target_idx) - candidate.conflicts_json = conflicts - structured = dict(candidate.structured_result_json or {}) - extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {} - adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {} - decisions = list(adjudication.get('decisions') or []) - updated_decisions = [] - for decision in decisions: - if not isinstance(decision, dict): - continue - same_field = str(decision.get('field') or '') == field_code - same_line = True - if line_index >= 0: - try: - same_line = int(decision.get('line_index')) == line_index - except (TypeError, ValueError): - same_line = False - if same_field and same_line: - updated_decisions.append({ - **decision, - 'status': 'selected', - 'value': chosen_display, - 'resolution_method': 'manual_review', - }) - else: - updated_decisions.append(decision) - adjudication['decisions'] = updated_decisions - adjudication['conflicts'] = list(conflicts) - extraction['field_adjudication'] = adjudication - structured['extraction'] = extraction - candidate.structured_result_json = structured - db.session.flush() + # [STEP 2] 按冲突类型分别处理 conflict_group_key 回写,并 flush。 + if is_vc_conflict: + _resolve_vc_candidate_decision( + candidate=candidate, + conflict_group_key=raw_key[len(_VC_CONFLICT_PREFIX):], + chosen_value=chosen_display, + ) + db.session.flush() + # 非 VC 分支:conflicts 删除 + adjudication decisions 更新已在上半段完成并 flush。 # [STEP 3] 重算资格并写审计;由路由层 commit。 customer_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate) diff --git a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py index 0866d525..827c4cf4 100644 --- a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py +++ b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py @@ -25,12 +25,17 @@ from app.models import ( ShippingOrderReviewWaveLine, ShippingNotice, ) -from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit from app.services.shipping_notice.workflow_ledger_service import ( assert_case_is_current_workflow_version, ) +def _get_soft_loader(): + """延迟导入 soft_load_review_case_for_audit,解开 job_registry → draft_service 循环依赖链。""" + from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit + return soft_load_review_case_for_audit + + DECISION_WAIT = 'wait_inventory' DECISION_FULFILL = 'fulfill_complete_line_now' DECISION_CLOSE = 'close_unfulfillable' @@ -61,7 +66,8 @@ _TERMINAL_ACTIVE = frozenset({'task_created', 'fulfilled', 'closed_unfulfillable def _load_writable_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase: """加载属主可写 Case(含部分波次后仍有开放行的 ready Case)。""" - case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no or '')) + soft_load = _get_soft_loader() + case = soft_load(user_id=int(user_id), case_no=str(case_no or '')) if case is None: raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') status = str(case.status or '') @@ -387,6 +393,48 @@ def project_review_case_line_decisions( schema_fields = _normalize_schema_fields_map(schema_fields) or schema_fields_from_case(case) formal_ot = resolve_formal_ot(case) has_formal_ot = bool(formal_ot.get('has_formal_ot')) + task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingNotice) else None + # [STEP] 构造 Task 级库存源回退事实(行级匹配缺失时兜底,仅影响展示) + # 优先级:行级 inventory_source_code > Task resolved/user_confirmed 正式源 > candidates_frozen > resolving + from app.services.shipping_notice.stp_inventory_freeze import ( + task_frozen_inventory_source_codes, + ) + + fallback_inventory_source: dict[str, Any] | None = None + if task is not None: + task_source_code = str(task.inventory_source_code or '').strip().upper() or None + task_source_status = str(task.inventory_source_status or '').strip() + if task_source_code and task_source_status in {'resolved', 'user_confirmed'}: + fallback_inventory_source = { + 'code': task_source_code, + 'label': None, + 'status': 'resolved', + 'source': 'task_inventory_source', + } + elif task_source_status == 'candidates_frozen': + frozen_codes = task_frozen_inventory_source_codes(task) + if frozen_codes: + fallback_inventory_source = { + 'code': None, + 'label': None, + 'status': 'candidates_frozen', + 'candidates': list(frozen_codes), + 'source': 'frozen_inventory_candidates', + } + else: + fallback_inventory_source = { + 'code': None, + 'label': None, + 'status': 'resolving', + 'source': 'inventory_source_clue', + } + else: + fallback_inventory_source = { + 'code': None, + 'label': None, + 'status': 'resolving', + 'source': 'inventory_source_clue', + } match_facts = load_current_match_facts_by_task(formal_ot.get('task_id')) labels = dict(source_labels or {}) if not labels: @@ -460,6 +508,7 @@ def project_review_case_line_decisions( auto_fulfill_error_message=auto_err, inventory_rpa_running=bool(inventory_rpa_running), source_labels=labels, + fallback_inventory_source=fallback_inventory_source, ) # [STEP] OT 后数量以匹配事实投影覆盖(含 not_found→0 / result_missing→null) if has_formal_ot: @@ -761,7 +810,7 @@ def decide_review_line_fulfillment( skip_validate=False, allow_auto_create=False, ) - case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no)) + case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no)) payload = { 'decision': _serialize_decision(row), 'line_fulfillment': project_review_case_line_decisions(case), @@ -818,7 +867,7 @@ def create_fulfillment_wave( case_no=str(case_no), expected_draft_version=expected_draft_version, ) - case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no or '')) + case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no or '')) if case is None: raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') @@ -875,7 +924,7 @@ def create_fulfillment_wave( # [STEP 2] 标记决定为 task_created from sqlalchemy import func - case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no)) + case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no)) # [STEP] 以本波次返回的 task_no 为准,避免多波次时 case.confirmed_task_id 竞态误绑。 task_id = None task_no = str((result or {}).get('task_no') or '').strip() diff --git a/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py b/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py new file mode 100644 index 00000000..a0ecd7cc --- /dev/null +++ b/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py @@ -0,0 +1,381 @@ +""" +services/shipping_notice/order_review_llm_auto_upgrade.py + +用途:LLM 证据等级自动升级引擎(Phase 2)。基于证据视图检测 7 项歧义/冲突信号, + 按优先级把默认 L2_row 升级到 L3_table(Header 冲突升级到 L4_page)。 +依赖: + - order_review_evidence_view:get_field_view / count_valid_row_fields / lines_order + - order_review_llm_contract:EvidenceLevelV2、证据等级与错误码常量 + - order_review_llm_policy_registry:llm_context_policy 判定 target_only +逻辑: + [1] 7 项优先级降序检测,命中多条只取最高优先级写入 auto_upgrade_reason, + 完整列表写入 auto_upgrade_reasons。 + [2] Header scope 命中任何升级信号 → 升级到 L4_page;Line scope → L3_table。 + [3] schema.target_only=true 的字段强制 L1_field,即使命中升级信号也跳过。 + [4] 升级后新等级仍须走前门禁(selector 构建完 pack 再二次门 target_core_trimmed), + 升级引擎只负责等级,不负责越权通过门禁。 +""" + +from __future__ import annotations + +from typing import Any, Final, Literal + +from app.services.shipping_notice.order_review_llm_contract import ( + EvidenceLevelV2, +) +from app.services.shipping_notice.order_review_evidence_view import ( + count_valid_row_fields, + get_field_view, +) +from app.services.shipping_notice.order_review_llm_policy_registry import ( + resolve_llm_context_policy, +) + +# --------------------------------------------------------------------------- +# 7 项升级依据(优先级数字越小越先命中) +# --------------------------------------------------------------------------- +_UPGRADE_REASON_PRIORITY: Final[dict[str, int]] = { + 'issue_FIELD_CONFLICT': 1, + 'draft_field_conflict': 2, + 'multi_source_ambiguous': 3, + 'table_duplicate_value': 4, + 'manual_conflict': 5, + 'context_borderline': 6, + 'context_identity_insufficient': 7, +} +UPGRADE_REASON_ORDER: Final[list[str]] = sorted( + _UPGRADE_REASON_PRIORITY.keys(), + key=lambda r: _UPGRADE_REASON_PRIORITY[r], +) + +_MIN_ROW_IDENTITY_CONFIDENCE: Final[float] = 0.6 +_BORDERLINE_SIBLING_COUNT: Final[int] = 2 +_LINE_IDENTITY_FIELD_CODES: Final[frozenset[str]] = frozenset({ + 'part_number', 'part_number_formatted', 'part_no', 'material_code', + 'sku', 'line_no', 'line_number', 'po_line', 'po_line_no', + 'item', 'item_no', 'item_code', 'product_code', +}) + +UpgradeResult = tuple[ + EvidenceLevelV2, # final_level + str | None, # auto_upgrade_reason(最高优先级) + list[str], # auto_upgrade_reasons(完整命中列表,按优先级排) +] + + +def _text_eq_normalized(a: Any, b: Any) -> bool: + """空白折叠 + trim + 大小写不敏感比较;None/'' 视为相等。""" + def n(v: Any) -> str: + if v is None: + return '' + import re + return re.sub(r'\s+', ' ', str(v)).strip().lower() + return n(a) == n(b) + + +def _schema_field_target_only( + field_view: dict[str, Any], + schema_field_meta: dict[str, Any] | None, +) -> bool: + """ + 判定字段是否属于 target_only(强制 L1_field,不允许上下文污染)。 + 优先读 schema_field_meta.target_only;缺失时用 llm_context_policy。 + """ + if isinstance(schema_field_meta, dict): + to = schema_field_meta.get('target_only') + if isinstance(to, bool): + return to + policy_raw = schema_field_meta.get('llm_context_policy') + if isinstance(policy_raw, str) and policy_raw.strip().lower() == 'target_only': + return True + policy = field_view.get('llm_context_policy') if isinstance(field_view, dict) else None + return isinstance(policy, str) and policy.strip().lower() == 'target_only' + + +# --------------------------------------------------------------------------- +# 单项检测函数 +# --------------------------------------------------------------------------- +def _check_issue_field_conflict(issue_code: str | None) -> bool: + """ + [Priority 1] issue_code 属于字段冲突类。 + 匹配规则:以 FIELD_CONFLICT 结尾,或含 _FIELD_CONFLICT_ 子串。 + """ + if not issue_code: + return False + code = str(issue_code).strip().upper() + return code.endswith('FIELD_CONFLICT') or '_FIELD_CONFLICT_' in code + + +def _check_draft_field_conflict(field_view: dict[str, Any]) -> bool: + """ + [Priority 2] evidence_view.value_source = manual_override。 + 用户手工值与 machine 识别值不一致,需要更大上下文供 LLM 判定。 + """ + if not isinstance(field_view, dict): + return False + return str(field_view.get('value_source') or '') == 'manual_override' + + +def _check_multi_source_ambiguous(field_view: dict[str, Any]) -> bool: + """ + [Priority 3] field_evidences 有多条,且归一化后 value 不唯一。 + 空 evidences 由门禁拦截;单条证据不可能歧义。 + """ + if not isinstance(field_view, dict): + return False + evs = field_view.get('field_evidences') or [] + if not isinstance(evs, list) or len(evs) < 2: + return False + seen: set[str] = set() + for ev in evs: + if not isinstance(ev, dict): + continue + value = ev.get('value') + if value is None: + continue + import re + norm = re.sub(r'\s+', ' ', str(value)).strip().lower() + if not norm: + continue + seen.add(norm) + return len(seen) > 1 + + +def _check_table_duplicate_value( + evidence_view: dict[str, Any], + *, + field_id: str, + line_key: str | None, + field_view_obj: dict[str, Any], +) -> bool: + """ + [Priority 4] Line scope:同一 table 中多个行存在与目标字段相同的 value。 + Header scope:此检测跳过(不适用)。目标 value 为空时跳过。 + """ + if not line_key: + return False + if not isinstance(evidence_view, dict): + return False + target_pe = field_view_obj.get('primary_evidence') if isinstance(field_view_obj, dict) else {} + if not isinstance(target_pe, dict): + return False + target_value = target_pe.get('value') + if target_value is None or (isinstance(target_value, str) and not target_value.strip()): + return False + target_table_id = target_pe.get('table_id') + target_doc = target_pe.get('document_id') + line_fields = evidence_view.get('line_fields') or {} + if not isinstance(line_fields, dict): + return False + same_table_hits = 0 + for lk, lf_map in line_fields.items(): + if lk == str(line_key) or not isinstance(lf_map, dict): + continue + fv = lf_map.get(str(field_id)) + if not isinstance(fv, dict): + continue + pe = fv.get('primary_evidence') + if not isinstance(pe, dict): + continue + if target_doc is not None and pe.get('document_id') != target_doc: + continue + if target_table_id and pe.get('table_id') != target_table_id: + continue + if _text_eq_normalized(pe.get('value'), target_value): + same_table_hits += 1 + if same_table_hits >= 1: + return True + return False + + +def _check_manual_conflict(field_view: dict[str, Any]) -> bool: + """ + [Priority 5] 与 P2 同源的机器 vs 手工冲突,但此处独立保留原因编码, + 以便后续审计时区分「用户明确改的」和「Draft 回填遗留的」。 + 命中条件:value_source in (manual_override, manual_only) 且 primary_evidence 存在。 + """ + if not isinstance(field_view, dict): + return False + vs = str(field_view.get('value_source') or '') + if vs not in {'manual_override', 'manual_only'}: + return False + pe = field_view.get('primary_evidence') + return isinstance(pe, dict) and bool(pe) + + +def _check_context_borderline( + evidence_view: dict[str, Any], + *, + line_key: str | None, +) -> bool: + """ + [Priority 6] Line scope 同行有效字段数正好 = 门禁最低阈值(2)。 + 处于门禁临界线,证据不稳,升级到表格更安全。Header scope 跳过。 + """ + if not line_key: + return False + try: + siblings = count_valid_row_fields(evidence_view, str(line_key)) + except Exception: + return False + return siblings == _BORDERLINE_SIBLING_COUNT + + +def _check_context_identity_insufficient( + evidence_view: dict[str, Any], + *, + line_key: str | None, + field_view_obj: dict[str, Any], +) -> bool: + """ + [Priority 7] Line scope:同行缺少明确身份标识字段(如 part_number / line_no), + 或目标字段 primary_evidence.confidence 低于阈值。 + """ + if not line_key: + return False + if not isinstance(evidence_view, dict): + return False + # 身份标识检测 + line_fields = evidence_view.get('line_fields') or {} + lf = line_fields.get(str(line_key)) if isinstance(line_fields, dict) else None + has_identity = False + if isinstance(lf, dict): + for fid, fv in lf.items(): + if not isinstance(fv, dict): + continue + code = str(fv.get('field_code') or fid or '').lower().replace('_', '-') + if code in _LINE_IDENTITY_FIELD_CODES: + pe = fv.get('primary_evidence') + if isinstance(pe, dict) and pe.get('value') not in (None, ''): + try: + conf = float(pe.get('confidence') or 0.0) + except (TypeError, ValueError): + conf = 0.0 + if conf >= _MIN_ROW_IDENTITY_CONFIDENCE: + has_identity = True + break + if not has_identity: + return True + # 目标字段信心度兜底 + if isinstance(field_view_obj, dict): + pe = field_view_obj.get('primary_evidence') or {} + if isinstance(pe, dict): + try: + conf = float(pe.get('confidence') or 0.0) + except (TypeError, ValueError): + conf = 0.0 + if 0.0 < conf < _MIN_ROW_IDENTITY_CONFIDENCE: + return True + return False + + +# --------------------------------------------------------------------------- +# 对外主入口 +# --------------------------------------------------------------------------- +def resolve_auto_upgrade_level( + *, + evidence_view: dict[str, Any], + field_id: str, + line_key: str | None, + requested_level: EvidenceLevelV2, + schema_field_meta: dict[str, Any] | None = None, + issue_code: str | None = None, +) -> UpgradeResult: + """ + 根据证据视图与请求元数据,决定最终证据等级。 + + Args: + evidence_view: build_review_evidence_view() 的返回。 + field_id: 目标字段 ID。 + line_key: 目标行键;None 表示 header scope。 + requested_level: 用户/前端请求的等级(默认 L2_row)。 + schema_field_meta: schema.definition_json.fields[] 中的原始元数据。 + issue_code: 前端透传的冲突 issue_code(触发 P1)。 + + Returns: + (final_level, auto_upgrade_reason, auto_upgrade_reasons) + final_level ∈ L1_field/L2_row/L3_table/L4_page;target_only 强制 L1。 + auto_upgrade_reason 为最高优先级原因;未升级返回 None。 + auto_upgrade_reasons 为全部命中原因,按优先级排序。 + """ + if not isinstance(evidence_view, dict): + return requested_level, None, [] + + field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + if field_view is None: + return requested_level, None, [] + + # [红线 target_only] 强制 L1_field,禁止升级,不污染上下文 + if _schema_field_target_only(field_view, schema_field_meta): + return 'L1_field', None, [] + + # 用户/前端已经显式请求超过 L2 的等级 → 不降级,也不额外追加 auto_upgrade_reason + if str(requested_level) not in {'L1_field', 'L2_row'}: + return requested_level, None, [] + + scope_is_line = bool(line_key) + reasons_hit: list[str] = [] + + # [STEP 1] 按优先级顺序跑 7 项检测,命中即追加 + if _check_issue_field_conflict(issue_code): + reasons_hit.append('issue_FIELD_CONFLICT') + if _check_draft_field_conflict(field_view): + reasons_hit.append('draft_field_conflict') + if _check_multi_source_ambiguous(field_view): + reasons_hit.append('multi_source_ambiguous') + if _check_table_duplicate_value( + evidence_view, + field_id=field_id, + line_key=line_key, + field_view_obj=field_view, + ): + reasons_hit.append('table_duplicate_value') + if _check_manual_conflict(field_view): + reasons_hit.append('manual_conflict') + if _check_context_borderline(evidence_view, line_key=line_key): + reasons_hit.append('context_borderline') + if _check_context_identity_insufficient( + evidence_view, + line_key=line_key, + field_view_obj=field_view, + ): + reasons_hit.append('context_identity_insufficient') + + if not reasons_hit: + return requested_level, None, [] + + # [STEP 2] 去重 + 按全局优先级稳定排序 + deduped: list[str] = [] + seen: set[str] = set() + for r in UPGRADE_REASON_ORDER: + if r in reasons_hit and r not in seen: + deduped.append(r) + seen.add(r) + top_reason = deduped[0] + + # [STEP 3] 依据 scope 升级:Header → L4_page;Line → L3_table + if scope_is_line: + final_level: EvidenceLevelV2 = 'L3_table' + else: + final_level = 'L4_page' + + # 二次兜底:调用方显式传 L1_field 且非 L2 默认,不自动升级(尊重显式最小证据) + if str(requested_level) == 'L1_field' and not reasons_hit: + final_level = 'L1_field' + + return final_level, top_reason, deduped + + +def describe_upgrade_reason(reason: str | None) -> str: + """返回原因代码的人类可读摘要(用于审计 metadata,不写入 error_message,i18n 交给前端)。""" + if reason is None: + return '' + return { + 'issue_FIELD_CONFLICT': 'issue_code 指示字段冲突', + 'draft_field_conflict': '草稿手工覆盖值与机器识别不一致', + 'multi_source_ambiguous': '多来源观察值存在冲突(归一化后不唯一)', + 'table_duplicate_value': '同表多行存在相同目标值(行身份歧义)', + 'manual_conflict': '存在人工干预值(manual_only / manual_override)', + 'context_borderline': '同行字段数处于门禁临界线(阈值=2)', + 'context_identity_insufficient': '同行缺少高置信度行身份标识字段', + }.get(reason, str(reason)) diff --git a/backend/app/services/shipping_notice/order_review_llm_contract.py b/backend/app/services/shipping_notice/order_review_llm_contract.py index 09989e0f..e923af20 100644 --- a/backend/app/services/shipping_notice/order_review_llm_contract.py +++ b/backend/app/services/shipping_notice/order_review_llm_contract.py @@ -1,53 +1,216 @@ """ services/shipping_notice/order_review_llm_contract.py -用途:冻结订单复核 Dify 最小证据建议的 JSON 契约与证据等级。 -依赖:无外部 I/O;被 evidence_selector / llm_service / validation 引用。 -逻辑:L1–L3 为默认升级路径;L4 整份 PDF 默认禁止,仅管理员显式触发且仍不得自动冻结。 +用途:冻结订单复核 Dify 最小证据建议的 JSON 契约、证据等级、状态枚举。 +依赖:无外部 I/O;被 evidence_selector / llm_service / validation / gate / auto_upgrade 引用。 +逻辑: + - v1 契约保留原语义,用于历史记录解释;v2 新请求只生成新枚举。 + - L1–L5 为 v2 等级;旧 L2_table/L3_page/L4_pdf 留在枚举里但 v2 代码不再生成。 + - evidence_ref/provenance_ref 两种引用严格区分;layout: 前缀缺任意必需段即为无效证据。 + - 信封 v2 采用 target/context/evidence/constraints/expected_output 稳定结构。 """ from __future__ import annotations -from typing import Any, Final, Literal +import hashlib +import json +import re +from typing import Any, Final, Literal, TypedDict -LLM_REVIEW_CONTRACT_VERSION: Final[str] = 'order-review-llm.v1' +# --------------------------------------------------------------------------- +# 版本 +# --------------------------------------------------------------------------- +LLM_REVIEW_CONTRACT_VERSION_V1: Final[str] = 'order-review-llm.v1' +LLM_REVIEW_CONTRACT_VERSION_V2: Final[str] = 'order-review-llm.v2' +LLM_REVIEW_CONTRACT_VERSION: Final[str] = LLM_REVIEW_CONTRACT_VERSION_V2 -EvidenceLevel = Literal['L1_field', 'L2_table', 'L3_page', 'L4_pdf'] -EVIDENCE_LEVELS: Final[frozenset[str]] = frozenset({ - 'L1_field', 'L2_table', 'L3_page', 'L4_pdf', +# --------------------------------------------------------------------------- +# 证据等级(v1 与 v2 合并共存,旧值语义不漂移;v2 默认 L2_row) +# --------------------------------------------------------------------------- +EvidenceLevelV1 = Literal['L1_field', 'L2_table', 'L3_page', 'L4_pdf'] +EvidenceLevelV2 = Literal['L1_field', 'L2_row', 'L3_table', 'L4_page', 'L5_document'] +EvidenceLevel = Literal[ + 'L1_field', + 'L2_table', # v1 legacy:旧版表头/行数上下文 + 'L3_page', # v1 legacy:旧版页面纯文本块 + 'L4_pdf', # v1 legacy:旧版整份 PDF 授权 + 'L2_row', # v2 默认:目标字段 + 同行所有允许字段 + 'L3_table', # v2:表头 + 目标行 + 前后各 2 行 + 'L4_page', # v2:目标表所在页面结构化摘要 + 'L5_document' # v2:理论保留,永不开放 +] + +EVIDENCE_LEVELS_V2_ALLOWED: Final[frozenset[str]] = frozenset({ + 'L1_field', 'L2_row', 'L3_table', 'L4_page', 'L5_document', }) +EVIDENCE_LEVELS_ALL: Final[frozenset[str]] = frozenset({ + 'L1_field', 'L2_table', 'L3_page', 'L4_pdf', + 'L2_row', 'L3_table', 'L4_page', 'L5_document', +}) +DEFAULT_V2_EVIDENCE_LEVEL: Final[EvidenceLevelV2] = 'L2_row' DEFAULT_MAX_EVIDENCE_LEVEL: Final[EvidenceLevel] = 'L3_page' L4_FULL_PDF_ALLOWED_BY_DEFAULT: Final[bool] = False +# --------------------------------------------------------------------------- +# Suggestion 状态(新增 gated_failed;其余保留 v1 语义) +# --------------------------------------------------------------------------- +SuggestionStatus = Literal[ + 'pending', + 'gated_failed', # 新增:HXOPS 本地前门禁失败,Dify 未被调用 + 'validated', + 'validation_failed', + 'accepted', + 'modified', + 'rejected', + 'failed', + 'provider_unavailable', +] +SUGGESTION_STATUSES_ALL: Final[frozenset[str]] = frozenset({ + 'pending', 'gated_failed', 'validated', 'validation_failed', + 'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable', +}) + SuggestionDecision = Literal['pending', 'accepted', 'modified', 'rejected'] SUGGESTION_DECISIONS: Final[frozenset[str]] = frozenset({ 'pending', 'accepted', 'modified', 'rejected', }) +# --------------------------------------------------------------------------- +# 错误码契约(与四语言 locales/*/errors.json 对齐) +# --------------------------------------------------------------------------- +GATE_ERROR_CODES: Final[frozenset[str]] = frozenset({ + 'SHIPPING.REVIEW_LLM_FIELD_NOT_FOUND', + 'SHIPPING.REVIEW_LLM_LINE_NOT_FOUND', + 'SHIPPING.REVIEW_LLM_FIELD_VALUE_MISSING', + 'SHIPPING.REVIEW_LLM_EVIDENCE_UNAVAILABLE', + 'SHIPPING.REVIEW_LLM_CONTEXT_INSUFFICIENT', + 'SHIPPING.REVIEW_LLM_EVIDENCE_POLICY_BLOCKED', + 'SHIPPING.REVIEW_LLM_CONTEXT_BUILD_FAILED', + 'SHIPPING.REVIEW_LLM_EVIDENCE_TRUNCATED', + 'SHIPPING.REVIEW_LLM_CONTEXT_AMBIGUOUS', + 'SHIPPING.REVIEW_LLM_L4_FORBIDDEN', +}) +LEGACY_ERROR_CODES: Final[frozenset[str]] = frozenset({ + 'SHIPPING.REVIEW_LLM_DISABLED', + 'SHIPPING.REVIEW_LLM_PROVIDER_UNAVAILABLE', + 'SHIPPING.REVIEW_LLM_FIELD_MISMATCH', + 'SHIPPING.REVIEW_LLM_VALIDATION_FAILED', +}) +ALL_LLM_ERROR_CODES: Final[frozenset[str]] = GATE_ERROR_CODES | LEGACY_ERROR_CODES -def build_suggestion_request_envelope( +# --------------------------------------------------------------------------- +# evidence_ref / provenance_ref 格式工具 +# --------------------------------------------------------------------------- +_LAYOUT_REF_RE = re.compile( + r'^layout:(?P\d+):p(?P\d+)(?::(?P[^:\r\n]*))?(?::row-(?P\d+))?(?::(?P[^:\r\n]*))?$' +) +_DRAFT_REF_RE = re.compile( + r'^draft:case-(?P\d+):line-(?P[^:]+):field-(?P[^:\r\n]+)$' +) + + +def is_valid_evidence_ref(value: Any, *, scope: str | None = None) -> bool: + """ + 校验 layout: 前缀 evidence_ref 是否满足该 scope 的最低要求。 + + Args: + value: 待校验字符串。 + scope: header / line;line scope 要求 table_id 和 row_index。 + + Returns: + True 当且仅当格式正确且必需段齐全。 + """ + if not isinstance(value, str) or not value: + return False + matched = _LAYOUT_REF_RE.match(value.strip()) + if not matched: + return False + doc = matched.group('doc') + page = matched.group('page') + if not doc or not page: + return False + try: + int(doc) + int(page) + except (TypeError, ValueError): + return False + if scope == 'line': + table = matched.group('table') + row = matched.group('row') + return bool(table and row) + return True + + +def build_evidence_ref( + *, + document_id: int | None, + page_no: int | None, + table_id: str | None = None, + row_index: int | None = None, + field_code: str | None = None, +) -> str | None: + """按定案格式生成 layout evidence_ref;缺必需段返回 None 而不伪造。""" + if not document_id or not page_no or document_id <= 0 or page_no <= 0: + return None + parts = [f'layout:{int(document_id)}:p{int(page_no)}'] + if table_id: + parts.append(str(table_id)) + else: + if row_index is not None or field_code: + parts.append('') # 占位 table + if row_index is not None: + parts.append(f'row-{int(row_index)}') + else: + if field_code: + # 需要补 row 占位 + if len(parts) == 2: + parts.append('') # table 占位 + parts.append('') # row 占位 + if field_code: + parts.append(str(field_code)) + result = ':'.join(parts) + if not is_valid_evidence_ref(result, scope='line' if row_index is not None else None): + return None + return result + + +def is_valid_provenance_ref(value: Any) -> bool: + if not isinstance(value, str) or not value: + return False + return _DRAFT_REF_RE.match(value.strip()) is not None + + +def build_provenance_ref(*, case_id: int, line_key: str | None, field_code: str) -> str: + """生成 Draft 回退专用的 provenance_ref(不伪装成 evidence_ref)。""" + line = str(line_key or 'header').strip() or 'header' + return f'draft:case-{int(case_id)}:line-{line}:field-{str(field_code).strip()}' + +# --------------------------------------------------------------------------- +# 观察值来源标记(三源 + text fallback) +# --------------------------------------------------------------------------- +ObservationSource = Literal[ + 'unit_observation', + 'draft_observation', + 'frozen_layout', + 'text_fallback', +] +OBSERVATION_SOURCES: Final[frozenset[str]] = frozenset({ + 'unit_observation', 'draft_observation', 'frozen_layout', 'text_fallback', +}) + +# --------------------------------------------------------------------------- +# v1 信封(保留原行为,不做任何字段增减,历史可回放) +# --------------------------------------------------------------------------- +def build_suggestion_request_envelope_v1( *, review_case_id: int, document_id: int, - evidence_level: EvidenceLevel, + evidence_level: EvidenceLevelV1, target_fields: list[dict[str, Any]], evidence_pack: dict[str, Any], ) -> dict[str, Any]: - """ - 构建发给 Chatflow 的最小请求信封;禁止密钥与临时 URL。 - - Args: - review_case_id: Review Case 主键。 - document_id: 冻结 Document ID。 - evidence_level: 当前证据等级。 - target_fields: 待建议字段(field_id/code/scope)。 - evidence_pack: 已脱敏证据包。 - - Returns: - 可序列化请求字典。 - """ return { - 'contract_version': LLM_REVIEW_CONTRACT_VERSION, + 'contract_version': LLM_REVIEW_CONTRACT_VERSION_V1, 'review_case_id': int(review_case_id), 'document_id': int(document_id), 'evidence_level': evidence_level, @@ -60,13 +223,136 @@ def build_suggestion_request_envelope( }, } +# --------------------------------------------------------------------------- +# v2 信封:target / context.row / context.table / neighbor_rows / evidence / +# constraints / expected_output +# --------------------------------------------------------------------------- +class V2Target(TypedDict, total=False): + field_id: str + field_code: str + scope: Literal['header', 'line'] + line_key: str | None +class V2RowContext(TypedDict, total=False): + line_key: str + fields: list[dict[str, Any]] # 每个字段含 field_id/field_code/machine_value/current_draft_value/value_source/evidence_ref/source + +class V2TableContext(TypedDict, total=False): + table_id: str + headers: list[dict[str, Any]] # [{column_index, field_code, display_name}] + target_row_index: int | None + +class V2NeighborRow(TypedDict, total=False): + line_key: str + row_index: int + fields: list[dict[str, Any]] + position: Literal['preceding', 'following'] + +class V2PageContext(TypedDict, total=False): + page_no: int + tables: list[dict[str, Any]] + structured_text_blocks: list[dict[str, Any]] + +class V2EvidenceItem(TypedDict, total=False): + field_id: str + value: str + quote: str + source: ObservationSource + confidence: float | None + evidence_ref: str | None + provenance_ref: str | None + page_no: int | None + table_id: str | None + cell_id: str | None + row_index: int | None + + +def build_suggestion_request_envelope( + *, + review_case_id: int, + document_id: int, + evidence_level: EvidenceLevel, + target_fields: list[dict[str, Any]], + evidence_pack: dict[str, Any], + contract_version: str = LLM_REVIEW_CONTRACT_VERSION, + target: V2Target | None = None, + context_row: V2RowContext | None = None, + context_table: V2TableContext | None = None, + neighbor_rows: list[V2NeighborRow] | None = None, + page_context: V2PageContext | None = None, + evidence_items: list[V2EvidenceItem] | None = None, + expected_target_field_id: str | None = None, + auto_upgrade_reason: str | None = None, + auto_upgrade_reasons: list[str] | None = None, +) -> dict[str, Any]: + """ + 构建 v2 为主、v1 兼容的请求信封。contract_version=v1 时回退到老结构。 + + 约束: + - values_must_be_verbatim_in_evidence=True(逐字证据) + - cannot_auto_freeze/cannot_auto_create_order 永远为 True(LLM 不能直接操作业务状态) + - full_document_forbidden=True(除非显式 L5,但 L5 永不开放) + """ + if contract_version == LLM_REVIEW_CONTRACT_VERSION_V1: + return build_suggestion_request_envelope_v1( + review_case_id=review_case_id, + document_id=document_id, + evidence_level=evidence_level if evidence_level in { + 'L1_field', 'L2_table', 'L3_page', 'L4_pdf', + } else 'L3_page', + target_fields=target_fields, + evidence_pack=evidence_pack, + ) + + constraints = { + 'values_must_be_verbatim_in_evidence': True, + 'cannot_auto_freeze': True, + 'cannot_auto_create_order': True, + 'full_document_forbidden': evidence_level != 'L5_document', + } + expected_output = { + 'allowed_target_field_id': expected_target_field_id, + 'must_include_quote': True, + 'must_include_field_id': True, + 'suggested_value_must_be_verbatim_in_evidence': True, + 'without_evidence_return': 'needs_review', + 'forbid_commonsense_filling': True, + 'forbid_sibling_field_suggestions': True, + } + envelope: dict[str, Any] = { + 'contract_version': LLM_REVIEW_CONTRACT_VERSION_V2, + 'review_case_id': int(review_case_id), + 'document_id': int(document_id), + 'evidence_level': evidence_level, + 'target': target, + 'context': { + 'level': evidence_level, + 'row': context_row, + 'table': context_table, + 'neighbor_rows': neighbor_rows or [], + }, + 'evidence': evidence_items or [], + 'constraints': constraints, + 'expected_output': expected_output, + # 保留 v1 兼容字段,供过渡 + 'target_fields': target_fields, + 'evidence_pack': evidence_pack, + } + if page_context is not None: + envelope['context']['page'] = page_context + if auto_upgrade_reason: + envelope['auto_upgrade_reason'] = auto_upgrade_reason + if auto_upgrade_reasons: + envelope['auto_upgrade_reasons'] = list(auto_upgrade_reasons) + return envelope + +# --------------------------------------------------------------------------- +# 响应解析(v1/v2 统一出口,line_key/scope/needs_review v2 新增) +# --------------------------------------------------------------------------- def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]]: """ - 解析 Chatflow 建议输出为字段建议列表。 - - Returns: - [{field_id, field_code, scope, suggested_value, quote, confidence}] + 解析 Dify 返回的建议列表。v2 输出可能带 needs_review 布尔, + parse 层仅负责结构清洗,不做业务有效性判定(留给 validation 层 fail-closed)。 """ if not isinstance(raw, dict): return [] @@ -82,13 +368,79 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any] field_id = str(item.get('field_id') or '').strip() if not field_id: continue + needs_review = False + if isinstance(item.get('needs_review'), bool): + needs_review = bool(item['needs_review']) + line_key_raw = item.get('line_key') + line_key = str(line_key_raw).strip() if line_key_raw is not None else None + if not line_key: + line_key = None + scope = str(item.get('scope') or '').strip().lower() + if scope not in {'header', 'line'}: + scope = 'line' + confidence_raw = item.get('confidence') + try: + confidence = float(confidence_raw) if confidence_raw is not None else 0.0 + except (TypeError, ValueError): + confidence = 0.0 result.append({ 'field_id': field_id, 'field_code': str(item.get('field_code') or '').strip() or None, - 'scope': str(item.get('scope') or 'line').strip() or 'line', + 'scope': scope, + 'line_key': line_key, 'suggested_value': item.get('suggested_value'), 'quote': str(item.get('quote') or item.get('suggested_value') or '')[:1000], - 'confidence': float(item.get('confidence') or 0), + 'confidence': confidence, 'line_number': item.get('line_number'), + 'needs_review': needs_review, + 'reason_code': str(item.get('reason_code') or '').strip() or None, }) return result + +# --------------------------------------------------------------------------- +# context_hash:规范化证据包 → SHA-256 完整 64 hex +# --------------------------------------------------------------------------- +_STRIP_FOR_CONTEXT_HASH = frozenset({ + 'request_time', 'random_id', 'nonce', 'token', 'api_key', + 'created_at', 'updated_at', 'latency_ms', 'provider_message_id', +}) + + +def _normalize_for_context_hash(value: Any) -> Any: + """递归规范化:key 排序 + 去噪键 + 数组稳定顺序(保留业务数组原顺序)。""" + if isinstance(value, dict): + return { + k: _normalize_for_context_hash(v) + for k, v in sorted(value.items(), key=lambda kv: str(kv[0])) + if str(k) not in _STRIP_FOR_CONTEXT_HASH + } + if isinstance(value, list): + return [_normalize_for_context_hash(item) for item in value] + if isinstance(value, tuple): + return [_normalize_for_context_hash(item) for item in value] + if isinstance(value, (int, float, bool)) or value is None: + return value + return str(value) + + +def compute_context_hash(evidence_pack: dict[str, Any]) -> str | None: + """ + 规范化证据包(排序键、去噪、保留业务稳定数组顺序)后求 SHA-256。 + 输入空或非法时返回 None(上层门禁拦截,不允许落库空 hash)。 + """ + if not isinstance(evidence_pack, dict) or not evidence_pack: + return None + normalized = _normalize_for_context_hash(evidence_pack) + payload = json.dumps(normalized, ensure_ascii=False, sort_keys=True, separators=(',', ':')) + digest = hashlib.sha256(payload.encode('utf-8')).hexdigest() + return digest + +# --------------------------------------------------------------------------- +# Quote normalize:trim + collapse whitespace;匹配层单独使用 +# --------------------------------------------------------------------------- +QUOTE_NORMALIZATION_RULES: Final[tuple[str, ...]] = ('trim', 'collapse_whitespace') + + +def normalize_quote_text(text: Any) -> str: + raw = '' if text is None else str(text) + return re.sub(r'\s+', ' ', raw).strip() diff --git a/backend/app/services/shipping_notice/order_review_llm_gate.py b/backend/app/services/shipping_notice/order_review_llm_gate.py new file mode 100644 index 00000000..a79efd16 --- /dev/null +++ b/backend/app/services/shipping_notice/order_review_llm_gate.py @@ -0,0 +1,146 @@ +""" +services/shipping_notice/order_review_llm_gate.py + +用途:请求发送给大模型之前的 fail-closed 确定性前门禁。 + 任何一项失败 → 返回 gated_failed 状态与 error_code,不允许调用 Dify。 +依赖: + - order_review_evidence_view.get_field_view / count_valid_row_fields + - order_review_llm_contract.GATE_ERROR_CODES / DEFAULT_V2_EVIDENCE_LEVEL + - order_review_llm_policy_registry.resolve_llm_context_policy +逻辑: + [1] field_not_found 目标 field_id 在 schema 中不存在 + [2] line_not_found 目标 line_key 在视图中行找不到 + [3] field_value_missing 目标字段 machine/draft/primary_evidence 三者全空 + [4] evidence_unavailable 目标字段无任何 field_evidences[](三源都没有事实) + [5] context_ambiguous unit orders >1 且无法按 primary_document_id 唯一确定 + [6] policy_blocked llm_context_policy 解析为 forbidden + [7] context_build_failed 通用异常包裹;evidence_view 构建抛异常即本错误 + [8] evidence_truncated (暂留占位,由 selector budget 截断后写入 evidence_truncated=true 时打) + [9] L4_forbidden L5_document 请求或 schema 未开启 L4 时命中;(暂留占位) + [10] context_insufficient 行 scope L2_row 同行有效字段 < 2 且无法自动降级(默认不开启降级) +""" + +from __future__ import annotations + +import traceback +from typing import Any, Final, Literal + +from app.services.shipping_notice.order_review_llm_contract import ( + EVIDENCE_LEVELS_V2_ALLOWED, + GATE_ERROR_CODES, + EvidenceLevelV2, +) +from app.services.shipping_notice.order_review_evidence_view import ( + count_valid_row_fields, + get_field_view, +) +from app.services.shipping_notice.order_review_llm_policy_registry import ( + resolve_llm_context_policy, +) + + +GateResult = tuple[bool, str | None, str | None] # (passed, error_code, technical_hint) + +_MIN_LINE_SIBLINGS: Final[int] = 2 +_SENSITIVE_MASK_LEVELS: Final = frozenset({'masked'}) + + +def _text_empty(v: Any) -> bool: + if v is None: + return True + if isinstance(v, str): + return v.strip() == '' + return False + + +def run_preflight_gate( + evidence_view: dict[str, Any], + *, + field_id: str, + line_key: str | None, + requested_level: EvidenceLevelV2 | None, + schema_field_meta: dict[str, Any] | None = None, +) -> GateResult: + """ + 执行 10 项门禁,fail-closed。 + + Returns: + (passed, error_code, technical_hint) + passed=True 时 error_code/hint 都为 None。 + """ + if not isinstance(evidence_view, dict): + return False, 'context_build_failed', 'evidence_view is empty dict' + + diagnostics = evidence_view.get('diagnostics') or {} + ambiguous_reasons = diagnostics.get('context_ambiguous_reasons') or [] + if ambiguous_reasons: + return False, 'context_ambiguous', \ + '; '.join(str(r) for r in ambiguous_reasons) + + # [2] line scope 需要 line_key 存在 + scope_is_line = bool(line_key) + if scope_is_line: + line_fields = evidence_view.get('line_fields') or {} + if str(line_key) not in line_fields: + return False, 'line_not_found', f'line_key={line_key}' + + # [1] field_id 找不到(header/line 都没命中) + field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + if field_view is None: + return False, 'field_not_found', f'field_id={field_id}' + + # policy_blocked(即使有值也不允许发给 LLM) + policy = field_view.get('llm_context_policy') + if not policy: + # 兜底再算一次,防视图构建漏算 + policy = resolve_llm_context_policy( + field_metadata=schema_field_meta or {}, + field_code=field_view.get('field_code') or field_id, + scope='line' if scope_is_line else 'header', + data_type=field_view.get('data_type'), + is_target_field=True, + ) + if policy == 'forbidden': + return False, 'policy_blocked', f'policy=forbidden field_id={field_id}' + + # [3] 目标值缺失(machine/draft/primary_evidence.value 全空) + mv = field_view.get('machine_value') + dv = field_view.get('current_draft_value') + pe = field_view.get('primary_evidence') or {} + pe_val = pe.get('value') if isinstance(pe, dict) else None + if _text_empty(mv) and _text_empty(dv) and _text_empty(pe_val): + return False, 'field_value_missing', \ + f'field_id={field_id} machine/draft/primary.value all empty' + + # [4] 三源都没有 evidence(Case 95 根因修复) + evidences = field_view.get('field_evidences') or [] + if not isinstance(evidences, list) or len(evidences) == 0: + return False, 'evidence_unavailable', \ + f'field_id={field_id} field_evidences empty; check Unit/Draft/Frozen' + + # [8] 预留占位:目标字段核心 evidence 截断 + if field_view.get('context_truncated_target_core'): + return False, 'evidence_truncated', \ + f'field_id={field_id} target core evidence truncated under budget' + + # [10] context_insufficient(行 scope L2_row 同行字段数) + effective_level = requested_level or 'L2_row' + if effective_level not in _SENSITIVE_MASK_LEVELS and effective_level in EVIDENCE_LEVELS_V2_ALLOWED: + if scope_is_line and str(effective_level) in ('L2_row',): + siblings = count_valid_row_fields(evidence_view, str(line_key)) + if siblings < _MIN_LINE_SIBLINGS: + return False, 'context_insufficient', \ + f'line_key={line_key} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}' + + return True, None, None + + +def wrap_context_build_exception(exc: Exception) -> GateResult: + """把 build_review_evidence_view 抛的任意异常都转成 context_build_failed。""" + hint = f'{type(exc).__name__}: {str(exc)[:160]}' + stack = traceback.format_exc(limit=2) + return False, 'context_build_failed', f'{hint} | {stack[:300]}' + + +def validate_gate_error_code(code: str | None) -> bool: + return code in GATE_ERROR_CODES diff --git a/backend/app/services/shipping_notice/order_review_llm_policy_registry.py b/backend/app/services/shipping_notice/order_review_llm_policy_registry.py new file mode 100644 index 00000000..fcfd1e1e --- /dev/null +++ b/backend/app/services/shipping_notice/order_review_llm_policy_registry.py @@ -0,0 +1,318 @@ +""" +services/shipping_notice/order_review_llm_policy_registry.py + +用途:为 LLM 证据发送提供字段级 llm_context_policy 推断 + 类型化 mask 算法。 +依赖:无外部 I/O;被 evidence_view、evidence_selector、gate 引用。 +逻辑: + - 7 步优先级推断:显式 policy → 敏感黑名单 → 内部黑名单 → scope 黑名单 + → 业务白名单 → data_type 白名单 → 保守 forbidden + - 敏感规则优先于业务白名单(supplier_email 命中敏感,不能因为 supplier 前缀变 allowed) + - mask 不采用通用前 N% 算法;按数据类型确定性掩码,原值永远不进入证据包。 +""" + +from __future__ import annotations + +import re +from typing import Any, Final, Literal + +# --------------------------------------------------------------------------- +# Policy 枚举 +# --------------------------------------------------------------------------- +LlmContextPolicy = Literal['allowed', 'masked', 'forbidden', 'target_only'] +LLM_CONTEXT_POLICIES: Final[frozenset[str]] = frozenset({ + 'allowed', 'masked', 'forbidden', 'target_only', +}) +DEFAULT_CONSERVATIVE_POLICY: Final[LlmContextPolicy] = 'forbidden' + +# --------------------------------------------------------------------------- +# 规则库(敏感 / 内部 / 业务白名单) +# 顺序由 7 步优先级控制,这里只存正则集合 +# --------------------------------------------------------------------------- +_SENSITIVE_FIELD_CODE_PATTERNS: Final[tuple[re.Pattern[str], ...]] = tuple( + re.compile(p, re.IGNORECASE) + for p in ( + r'address', r'phone|mobile|tel', r'email|e_mail|mail', + r'contact(_?name|_?person)?', r'tax(_?id)?|taxpayer|ein|ssn', + r'passport|id(_?card|_?no)?', r'bank(_?account|_?name|_?swift|_?iban)?', + r'credit(_?card)?|card(_?no)?', + ) +) + +_INTERNAL_FIELD_CODE_PATTERNS: Final[tuple[re.Pattern[str], ...]] = tuple( + re.compile(p, re.IGNORECASE) + for p in ( + r'^_', r'internal', r'audit(_\w+)?$', r'permission(_\w+)?$', + r'lock(_\w+)?$', r'version(_\w+)?$', r'checksum|hash_digest', + r'token|secret|nonce|signature|salt', + ) +) + +_INTERNAL_SCOPE_PATTERNS: Final[frozenset[str]] = frozenset({ + 'system', 'audit', 'internal', 'runtime', 'permission', +}) + +_BUSINESS_FIELD_CODE_PATTERNS: Final[tuple[re.Pattern[str], ...]] = tuple( + re.compile(p, re.IGNORECASE) + for p in ( + r'customer(_\w+)?', r'supplier(_\w+)?', r'vendor', + r'part(_?number|_?no|_?id)?', r'po(_?number|_?no)?', r'purchase_order', + r'qty|quantit(y|ies)', r'uom|unit(_?measure)?', + r'unit(_?price)?|price|amount|monetary', r'currency|ccy|curr', + r'date|incoterm(_\w+)?', r'line(_?no|_?key|_?number)?', + r'description|item(_?name|_?desc)?', r'receipt', r'ship(_?to|_?from)?', + ) +) + +_ALLOWED_DATA_TYPES: Final[frozenset[str]] = frozenset({ + 'quantity', 'monetary', 'date', 'document_reference', + 'string', 'integer', 'number', 'enum', +}) + +# --------------------------------------------------------------------------- +# 规则组合:7 步优先级推断 +# --------------------------------------------------------------------------- +def resolve_llm_context_policy( + *, + field_metadata: dict[str, Any] | None, + field_code: str, + scope: str | None = None, + data_type: str | None = None, + is_target_field: bool = False, +) -> LlmContextPolicy: + """ + 7 步优先级推断字段级 llm_context_policy。 + + 顺序(定案 §1.2): + 1. 明确的 field.llm_context_policy + 2. field_code 敏感黑名单 → masked + 3. field_code 内部字段黑名单 → forbidden + 4. scope=system/audit/internal → forbidden + 5. 明确业务字段白名单 → allowed + 6. data_type 为 quantity/monetary/date/document_reference → allowed + 7. 未命中 → forbidden + + 【敏感优先】第 2 步(敏感)在第 5 步(业务)之前, + 因此 supplier_email 虽然命中 supplier 业务白名单,但依然是 masked。 + + target_only 仅当显式配置时生效(目标字段单独传,其它同名字段不传)。 + """ + code = '' if field_code is None else str(field_code).strip() + code_folded = code.casefold() + + # [STEP 1] 明确配置 + if isinstance(field_metadata, dict): + explicit = field_metadata.get('llm_context_policy') + if isinstance(explicit, str) and explicit.strip(): + explicit_norm = explicit.strip().lower() + if explicit_norm in LLM_CONTEXT_POLICIES: + return explicit_norm # type: ignore[return-value] + + if is_target_field: + # 目标字段即使没有显式配置,也至少作为 target_only 传入 + # 但仍然先跑敏感/内部检查:敏感字段目标字段也必须 masked + pass + + # [STEP 2] 敏感黑名单 + for pattern in _SENSITIVE_FIELD_CODE_PATTERNS: + if pattern.search(code_folded): + return 'masked' + + # [STEP 3] 内部黑名单 + for pattern in _INTERNAL_FIELD_CODE_PATTERNS: + if pattern.search(code_folded): + return 'forbidden' + + # [STEP 4] scope 黑名单 + scope_raw = '' if scope is None else str(scope).strip().casefold() + if scope_raw in _INTERNAL_SCOPE_PATTERNS: + return 'forbidden' + + # [STEP 5] 业务白名单 + for pattern in _BUSINESS_FIELD_CODE_PATTERNS: + if pattern.search(code_folded): + return 'allowed' + + # [STEP 6] data_type 白名单 + dt = '' if data_type is None else str(data_type).strip().casefold() + if dt in _ALLOWED_DATA_TYPES: + return 'allowed' + + # [STEP 7] 保守默认 + if is_target_field: + # 目标字段:作为最低保证 sent 为 target_only(只有目标字段自身允许) + return 'target_only' + return DEFAULT_CONSERVATIVE_POLICY + +# --------------------------------------------------------------------------- +# Mask 算法:按字段类型确定性掩码;返回 (masked_value, mask_rule_key) +# 规则:original_value_sent 永远为 False(原值绝对不进 Dify) +# --------------------------------------------------------------------------- +_MASK_RULE_EMAIL: Final[str] = 'email_v1' +_MASK_RULE_PHONE: Final[str] = 'phone_v1' +_MASK_RULE_ADDRESS: Final[str] = 'address_v1' +_MASK_RULE_TAX_ACCOUNT: Final[str] = 'tax_account_v1' +_MASK_RULE_GENERIC: Final[str] = 'generic_masked_v1' + +_EMAIL_RE = re.compile(r'^(?P[^@\s]+)@(?P[^@\s]+\.[^@\s]+)$') +_PHONE_RE = re.compile(r'^[+\d][\d\s\-()]{5,}$') + + +def mask_field_value( + value: Any, + *, + policy: LlmContextPolicy, + field_code: str | None = None, +) -> dict[str, Any]: + """ + 按 policy + field_code 类型化掩码。 + + 返回: + { + "policy": "masked", + "mask_rule": "...", + "original_value_sent": False, + "masked_value": "..." + } + + policy != masked 时不做掩码,按原样返回(但仍返回元信息结构体)。 + """ + code_folded = '' if field_code is None else str(field_code).casefold() + if policy != 'masked': + return { + 'policy': policy, + 'mask_rule': None, + 'original_value_sent': policy == 'allowed' or policy == 'target_only', + 'masked_value': value, + } + + raw = '' if value is None else str(value) + stripped = raw.strip() + if not stripped: + return { + 'policy': 'masked', + 'mask_rule': _MASK_RULE_GENERIC, + 'original_value_sent': False, + 'masked_value': '', + } + + # email(优先级最高:先判断 email 再判断 phone) + if 'email' in code_folded or 'mail' in code_folded: + matched = _EMAIL_RE.match(stripped) + if matched: + local = matched.group('local') + domain = matched.group('domain') + local_masked = (local[0] + '***') if len(local) >= 1 else '***' + try: + first_char = domain.split('.', 1)[0] + first = first_char[0] if first_char else 'd' + except (IndexError, AttributeError): + first = 'd' + domain_parts = domain.rsplit('.', 1) + tld = domain_parts[-1] if len(domain_parts) > 1 else 'com' + return { + 'policy': 'masked', + 'mask_rule': _MASK_RULE_EMAIL, + 'original_value_sent': False, + 'masked_value': f'{local_masked}@{first}***.{tld}', + } + + # phone / mobile + if any(kw in code_folded for kw in ('phone', 'mobile', 'tel', 'fax')): + digits = re.sub(r'\D', '', stripped) + if len(digits) >= 7: + if len(digits) == 11: + return { + 'policy': 'masked', + 'mask_rule': _MASK_RULE_PHONE, + 'original_value_sent': False, + 'masked_value': f'{digits[:3]}****{digits[-4:]}', + } + head = digits[:2] + tail = digits[-2:] + middle = '*' * max(len(digits) - 4, 4) + return { + 'policy': 'masked', + 'mask_rule': _MASK_RULE_PHONE, + 'original_value_sent': False, + 'masked_value': f'{head}{middle}{tail}', + } + if _PHONE_RE.match(stripped): + return { + 'policy': 'masked', + 'mask_rule': _MASK_RULE_PHONE, + 'original_value_sent': False, + 'masked_value': stripped[:2] + '****' + stripped[-2:], + } + + # address:保留国家/省/市(中文按常见分隔符拆 3 段,后面全换 ***) + if 'address' in code_folded: + return { + 'policy': 'masked', + 'mask_rule': _MASK_RULE_ADDRESS, + 'original_value_sent': False, + 'masked_value': _mask_address(stripped), + } + + # tax / account / bank / id_card / passport + if any(kw in code_folded for kw in ( + 'tax', 'account', 'bank', 'passport', 'id_card', 'idcard', 'ssn', 'credit', 'card', + )): + if len(stripped) <= 4: + masked = '*' * len(stripped) + else: + head = stripped[:2] + tail = stripped[-2:] + middle = '*' * max(len(stripped) - 4, 4) + masked = f'{head}{middle}{tail}' + return { + 'policy': 'masked', + 'mask_rule': _MASK_RULE_TAX_ACCOUNT, + 'original_value_sent': False, + 'masked_value': masked, + } + + # 通用敏感:保留首末字符,中间 *** + if len(stripped) <= 2: + masked = '*' * len(stripped) + else: + masked = stripped[0] + '***' + stripped[-1] + return { + 'policy': 'masked', + 'mask_rule': _MASK_RULE_GENERIC, + 'original_value_sent': False, + 'masked_value': masked, + } + + +def _mask_address(text: str) -> str: + """ + address 掩码规则: + - 中文:按省级(省/自治区/直辖市/特别行政区)→ 市 → 区/县,后面 *** + - 英文:按逗号分段保留前 2 段,后面 *** + - 失败通用:保留前 12 字符 + *** + """ + stripped = text.strip() + if not stripped: + return '' + cn_province_match = re.search( + r'^(?P.{2,12}?(省|自治区|北京市|上海市|天津市|重庆市|特别行政区|市|自治州))', + stripped, + ) + if cn_province_match: + keep = cn_province_match.group('keep') + rest = stripped[len(keep):].strip() + if not rest: + return keep + '***' + city_match = re.match(r'^.{1,8}?(市|地区|盟)', rest) + if city_match: + city = city_match.group(0) + return f'{keep}{city}***' + return f'{keep}***' + # 英文逗号分段 + parts = [p.strip() for p in stripped.split(',') if p.strip()] + if len(parts) >= 2: + return ', '.join(parts[:2]) + ', ***' + # 通用 + if len(stripped) <= 12: + return stripped[:2] + '*' * max(len(stripped) - 2, 4) + return stripped[:12] + '***' diff --git a/backend/app/services/shipping_notice/order_review_llm_service.py b/backend/app/services/shipping_notice/order_review_llm_service.py index 166bd040..7cfc03fd 100644 --- a/backend/app/services/shipping_notice/order_review_llm_service.py +++ b/backend/app/services/shipping_notice/order_review_llm_service.py @@ -36,8 +36,18 @@ from app.services.shipping_notice.order_review_llm_contract import ( LLM_REVIEW_CONTRACT_VERSION, EvidenceLevel, build_suggestion_request_envelope, + compute_context_hash, parse_suggestion_response, ) +from app.services.shipping_notice.order_review_evidence_view import build_review_evidence_view +from app.services.shipping_notice.order_review_llm_gate import ( + run_preflight_gate, + wrap_context_build_exception, +) +from app.services.shipping_notice.order_review_llm_auto_upgrade import ( + resolve_auto_upgrade_level, + describe_upgrade_reason, +) from app.services.shipping_notice.order_review_llm_validation import validate_suggestions_against_evidence from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_review_service import get_user_review_case @@ -45,10 +55,15 @@ from app.services.shipping_notice.tool_common import llm_review_enabled _LEVEL_MAP = { 'L1': 'L1_field', - 'L2': 'L2_table', - 'L3': 'L3_page', - 'L4': 'L4_pdf', + 'L2': 'L2_row', + 'L3': 'L3_table', + 'L4': 'L4_page', 'L1_field': 'L1_field', + 'L2_row': 'L2_row', + 'L3_table': 'L3_table', + 'L4_page': 'L4_page', + 'L5_document': 'L5_document', + # --- 旧 v1 兼容(保留,不删,新请求永远不生成这些值)--- 'L2_table': 'L2_table', 'L3_page': 'L3_page', 'L4_pdf': 'L4_pdf', @@ -60,8 +75,9 @@ def _suggestion_no() -> str: def _normalize_level(value: str | None) -> EvidenceLevel: - raw = str(value or 'L1_field').strip() - return _LEVEL_MAP.get(raw, 'L1_field') # type: ignore[return-value] + raw = str(value or 'L2_row').strip() + mapped: str = _LEVEL_MAP.get(raw, raw if raw in _LEVEL_MAP.values() else 'L2_row') # type: ignore[assignment] + return mapped # type: ignore[return-value] def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None: @@ -170,16 +186,68 @@ def _schema_field(case: ShippingOrderReviewCase, field_id: str) -> dict[str, Any raise ValidationError('Review field is unavailable', code='SHIPPING.REVIEW_FIELD_INVALID') -def serialize_suggestion(row: ShippingOrderReviewSuggestion) -> dict[str, Any]: - """投影单条建议的安全 DTO。""" +def serialize_suggestion( + row: ShippingOrderReviewSuggestion, + *, + is_admin: bool = False, +) -> dict[str, Any]: + """ + Phase 4 DTO 权限分层投影。 + + 普通用户可见: + - contract_version, error_code(前端查 i18n 本地化,后端不翻译) + - evidence_summary(level/auto_upgraded/auto_upgrade_reason/counts/core_source/context_truncated) + - 业务字段:status / suggested_value / validation_issues / decision 等 + + 管理员(is_admin=True)额外可见: + - provider_trace(provider, conversation_id, message_id, latency_ms) + - request_preview(fields_sent_preview, policies_applied, budget_tokens, method) + + 契约:绝不向前端暴露 API Key、Token、Provider 响应全文、脱敏前原文。 + """ suggested = row.suggested_value_json if isinstance(row.suggested_value_json, dict) else {} - return { + request = row.request_json if isinstance(row.request_json, dict) else {} + auto_upgrade = request.get('auto_upgrade') if isinstance(request.get('auto_upgrade'), dict) else {} + + # evidence_summary(普通用户可见) + evidence_summary: dict[str, Any] = { + 'level': row.evidence_level, + 'auto_upgraded': bool(row.auto_upgrade_reason or auto_upgrade), + 'auto_upgrade_reason': row.auto_upgrade_reason, + 'field_count': int(row.evidence_count or 0), + 'row_count': None, + 'table_count': None, + 'page_count': None, + 'core_evidence_source': None, + 'context_truncated': bool(row.context_truncated), + } + request_pack = request.get('evidence_pack') if isinstance(request.get('evidence_pack'), dict) else {} + try: + nf = 0 + if isinstance(request_pack.get('fields'), list): + nf = len(request_pack['fields']) + evidence_summary['field_count'] = max(evidence_summary['field_count'] or 0, nf) + if isinstance(request_pack.get('tables'), list): + evidence_summary['table_count'] = len(request_pack['tables']) + if isinstance(request_pack.get('pages'), list): + evidence_summary['page_count'] = len(request_pack['pages']) + if isinstance(request.get('context'), dict): + ctx = request['context'] + rows = ctx.get('row') if isinstance(ctx.get('row'), dict) else {} + if isinstance(rows.get('fields'), list): + evidence_summary['row_count'] = len(rows['fields']) + except Exception: # pragma: no cover - defensive + pass + + base: dict[str, Any] = { 'suggestion_no': row.suggestion_no, 'field_id': row.field_id, 'line_key': row.line_key, 'scope': row.scope, 'evidence_level': row.evidence_level, + 'contract_version': row.contract_version, 'status': row.status, + 'error_code': row.error_code, 'suggested_value': suggested.get('value'), 'validation_issues': list(row.validation_issues_json or []), 'decision': row.decision, @@ -188,10 +256,54 @@ def serialize_suggestion(row: ShippingOrderReviewSuggestion) -> dict[str, Any]: 'draft_version_at_request': row.draft_version_at_request, 'created_at': row.created_at.isoformat() if row.created_at else None, 'adjudicated_at': row.decided_at.isoformat() if row.decided_at else None, + 'evidence_summary': evidence_summary, + 'auto_upgrade_reason': row.auto_upgrade_reason, } + # 后端查 i18n error_message 不输出:前端按 error_code 查 locales/*/errors.json(契约 v2) + base.pop('error_message', None) -def list_case_suggestions(*, user_id: int, case_no: str) -> dict[str, Any]: + if is_admin: + provider_trace: dict[str, Any] = { + 'provider': row.provider, + 'conversation_id': row.provider_conversation_id, + 'message_id': row.provider_message_id, + 'latency_ms': row.latency_ms, + } + request_preview: dict[str, Any] = { + 'contract_version': row.contract_version, + 'context_hash': row.context_hash, + 'evidence_count': int(row.evidence_count or 0), + 'context_truncated': bool(row.context_truncated), + 'auto_upgrade': dict(auto_upgrade) if auto_upgrade else None, + 'fields_sent_preview': None, + 'policies_applied': None, + 'budget_tokens': None, + 'method': 'chatflow_blocking', + } + try: + tf = request.get('target_fields') + if isinstance(tf, list): + request_preview['fields_sent_preview'] = [ + { + 'field_id': (i.get('field_id') if isinstance(i, dict) else None), + 'field_code': (i.get('field_code') if isinstance(i, dict) else None), + 'scope': (i.get('scope') if isinstance(i, dict) else None), + 'line_key': (i.get('line_key') if isinstance(i, dict) else None), + } + for i in tf if isinstance(i, dict) + ][:50] + except Exception: # pragma: no cover - defensive + pass + base['provider_trace'] = provider_trace + base['request_preview'] = request_preview + base['context_hash'] = row.context_hash + base['latency_ms'] = row.latency_ms + + return base + + +def list_case_suggestions(*, user_id: int, case_no: str, is_admin: bool = False) -> dict[str, Any]: """列出 Case 下全部建议记录。""" case = get_user_review_case(user_id=user_id, case_no=case_no) rows = ( @@ -203,7 +315,7 @@ def list_case_suggestions(*, user_id: int, case_no: str) -> dict[str, Any]: return { 'case_no': case.case_no, 'llm_review_enabled': llm_review_enabled(), - 'items': [serialize_suggestion(row) for row in rows], + 'items': [serialize_suggestion(row, is_admin=is_admin) for row in rows], } @@ -216,8 +328,13 @@ def _resolve_dify_agent(case: ShippingOrderReviewCase) -> Agent | None: return resolve_chat_agent() -def _call_dify_blocking(*, agent: Agent, user_id: int, query: str, inputs: dict[str, Any]) -> dict[str, Any]: - """blocking Chatflow 调用;失败由上层 fail-closed。""" +def _call_dify_blocking(*, agent: Agent, user_id: int, query: str, inputs: dict[str, Any], + _return_raw_response: bool = False): + """blocking Chatflow 调用;失败由上层 fail-closed。 + + 当 _return_raw_response=True 时返回 (parsed_answer, http_top_json), + 以便上层从 http_top_json 提取 conversation_id / message_id 进行可观测性对账。 + """ base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE url = DifyService._build_chat_messages_url(base_url) headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'} @@ -231,13 +348,19 @@ def _call_dify_blocking(*, agent: Agent, user_id: int, query: str, inputs: dict[ if not resp.ok: raise RuntimeError(f'dify_http_{resp.status_code}') data = resp.json() if resp.content else {} - answer = data.get('answer') if isinstance(data, dict) else None + top = data if isinstance(data, dict) else {} + answer = top.get('answer') if isinstance(top, dict) else None + parsed = {} if isinstance(answer, str): try: - return json.loads(answer) + parsed = json.loads(answer) except json.JSONDecodeError: - return {'suggestions': [{'field_id': '', 'suggested_value': answer.strip(), 'quote': answer.strip()}]} - return answer if isinstance(answer, dict) else {} + parsed = {'suggestions': [{'field_id': '', 'suggested_value': answer.strip(), 'quote': answer.strip()}]} + else: + parsed = answer if isinstance(answer, dict) else {} + if _return_raw_response: + return parsed, top + return parsed def request_field_suggestion( @@ -276,9 +399,10 @@ def request_field_suggestion( if scope == 'line' and not line_key: raise ValidationError('line_key is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND') - level = _normalize_level(evidence_level or 'L1_field') - if level == 'L4_pdf' and not (is_admin and allow_full_pdf): + level_raw = _normalize_level(evidence_level or 'L1_field') + if level_raw == 'L4_pdf' and not (is_admin and allow_full_pdf): raise ValidationError('Full PDF evidence level is forbidden', code='SHIPPING.REVIEW_LLM_L4_FORBIDDEN') + level = level_raw # phase 2 auto_upgrade 覆盖之前,保留原始变量引用 document = _frozen_document(case) target_fields = [{ @@ -315,6 +439,111 @@ def request_field_suggestion( metadata={'issue_code': issue_code, 'allow_full_pdf': bool(allow_full_pdf)}, ) + # [STEP V2] Phase 2 自动升级:基于证据视图 7 项优先级检测,L2_row→L3_table/L4_page + _auto_upgrade_reason: str | None = None + _auto_upgrade_reasons: list[str] = [] + try: + evidence_view = build_review_evidence_view(case) + except Exception as exc: # pragma: no cover - defensive + gate_exception = exc + evidence_view = {} + else: + gate_exception = None + # [AUTO_UPGRADE] 门禁之前先升级等级(升级后的等级决定门禁检查项,如 L3 不再需 context_insufficient) + try: + upgraded_level, up_reason, up_reasons = resolve_auto_upgrade_level( + evidence_view=evidence_view, + field_id=str(field_id), + line_key=str(line_key) if line_key else None, + requested_level=level, # type: ignore[arg-type] + schema_field_meta=field, + issue_code=issue_code, + ) + except Exception: # pragma: no cover - defensive + upgraded_level = level # type: ignore[assignment] + up_reason = None + up_reasons = [] + if up_reason: + level = upgraded_level # type: ignore[assignment] + _auto_upgrade_reason = up_reason + _auto_upgrade_reasons = list(up_reasons) + row.evidence_level = level + # 把完整原因列表写入 request_json,便于对账(落库列 auto_upgrade_reason 只存最高优先级) + row.request_json = { + **(row.request_json or {}), + 'auto_upgrade': { + 'from': str(level_raw), + 'to': str(level), + 'reasons': list(up_reasons), + 'top_reason': up_reason, + 'top_reason_desc': describe_upgrade_reason(up_reason), + }, + } + row.auto_upgrade_reason = _auto_upgrade_reason + + # [STEP V2] Phase 0 fail-closed 前门禁:视图构建 + 10 项检查,不过绝不调 Dify + if gate_exception is not None: + passed, gate_error, gate_hint = wrap_context_build_exception(gate_exception) + else: + passed, gate_error, gate_hint = run_preflight_gate( + evidence_view, + field_id=str(field_id), + line_key=str(line_key) if line_key else None, + requested_level=level, # type: ignore[arg-type] + schema_field_meta=field, + ) + # 填充观测列(gated 或未 gated 都写,便于对账 context_hash) + _evidence_view_count = 0 + if line_key: + line_map = (evidence_view or {}).get('line_fields') or {} + row_map = line_map.get(str(line_key)) or {} + target_view = row_map.get(str(field_id)) + else: + header_map = (evidence_view or {}).get('header_fields') or {} + target_view = header_map.get(str(field_id)) + if isinstance(target_view, dict): + f_ev = target_view.get('field_evidences') or [] + if isinstance(f_ev, list): + _evidence_view_count = len(f_ev) + row.evidence_count = int(_evidence_view_count) + row.provider = 'dify' + + # gated_failed 分支 ……………………………………………………………………………………………………………………………………………………………………………………………… + if not passed: + row.status = 'gated_failed' + row.error_code = f'SHIPPING.REVIEW_LLM_GATE_{(gate_error or "").upper()}' + row.error_message = gate_hint or '' + try: + row.context_hash = compute_context_hash({ + 'case_id': int(case.id), + 'contract_version': LLM_REVIEW_CONTRACT_VERSION, + 'evidence_level': level, + 'gate_error': gate_error, + }) + except Exception: + row.context_hash = None + db.session.flush() + _audit_metadata = {'gate_error': gate_error, 'gate_hint': gate_hint} + if _auto_upgrade_reason: + _audit_metadata.update({ + 'auto_upgrade_applied': True, + 'auto_upgrade_from': str(level_raw), + 'auto_upgrade_to': str(level), + 'auto_upgrade_reason': _auto_upgrade_reason, + 'auto_upgrade_reasons': list(_auto_upgrade_reasons), + }) + _audit_llm_suggestion( + case=case, + actor_id=int(user_id), + event_type='llm_review_gated', + action='llm_preflight_gate_failed', + suggestion=row, + result='failed', + error_code=row.error_code, + metadata=_audit_metadata, + ) + return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)} + if not llm_review_enabled(): row.status = 'provider_unavailable' row.error_code = 'SHIPPING.REVIEW_LLM_DISABLED' @@ -329,22 +558,91 @@ def request_field_suggestion( result='failed', error_code=row.error_code, ) - return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)} + return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)} evidence_pack = select_review_evidence_pack( document=document, target_fields=target_fields, evidence_level=level, allow_full_pdf=bool(is_admin and allow_full_pdf), + evidence_view=evidence_view, ) + # [GATE] selector 判定目标字段核心被截断 → fail-closed 不发 Dify + if isinstance(evidence_pack, dict) and bool(evidence_pack.get('target_core_trimmed')): + row.status = 'gated_failed' + row.error_code = 'SHIPPING.REVIEW_LLM_GATE_EVIDENCE_TRUNCATED' + row.error_message = 'target_core_trimmed=true; target quote/evidence core exceeded budget' + row.context_truncated = True + try: + row.context_hash = compute_context_hash({ + 'case_id': int(case.id), + 'contract_version': LLM_REVIEW_CONTRACT_VERSION, + 'evidence_level': level, + 'gate_error': 'evidence_truncated', + }) + except Exception: + row.context_hash = None + db.session.flush() + _audit_metadata_trunc = { + 'gate_error': 'evidence_truncated', + 'gate_hint': 'target_core_trimmed=true', + } + if _auto_upgrade_reason: + _audit_metadata_trunc.update({ + 'auto_upgrade_applied': True, + 'auto_upgrade_from': str(level_raw), + 'auto_upgrade_to': str(level), + 'auto_upgrade_reason': _auto_upgrade_reason, + 'auto_upgrade_reasons': list(_auto_upgrade_reasons), + }) + _audit_llm_suggestion( + case=case, + actor_id=int(user_id), + event_type='llm_review_gated', + action='llm_preflight_gate_failed', + suggestion=row, + result='failed', + error_code=row.error_code, + metadata=_audit_metadata_trunc, + ) + return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)} + request_payload = build_suggestion_request_envelope( review_case_id=int(case.id), document_id=int(case.document_id), evidence_level=level, target_fields=target_fields, evidence_pack=evidence_pack, + target={ + 'field_id': str(field_id), + 'field_code': str(field.get('field_code') or field_id), + 'scope': scope, + 'line_key': line_key, + }, + expected_target_field_id=str(field_id), + auto_upgrade_reason=_auto_upgrade_reason, + auto_upgrade_reasons=list(_auto_upgrade_reasons) if _auto_upgrade_reasons else None, ) row.request_json = {**(row.request_json or {}), **request_payload} + # [OBS V2] 计算稳定上下文指纹(递归 key 排序 + 去噪),落库供对账。 + try: + row.context_hash = compute_context_hash({ + 'case_id': int(case.id), + 'document_id': int(case.document_id), + 'draft_version': int(case.current_draft.draft_version if case.current_draft else 0), + 'field_id': str(field_id), + 'line_key': line_key, + 'contract_version': LLM_REVIEW_CONTRACT_VERSION, + 'evidence_level': level, + 'target_fields': target_fields, + 'evidence_pack': evidence_pack, + }) + except Exception: + row.context_hash = None + context_truncated_flag = bool( + isinstance(evidence_pack, dict) and bool(evidence_pack.get('context_truncated')) + ) + row.context_truncated = context_truncated_flag agent = _resolve_dify_agent(case) if agent is None or not agent.dify_api_key: @@ -361,16 +659,50 @@ def request_field_suggestion( result='failed', error_code=row.error_code, ) - return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)} + return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)} try: + import time as _time + _t0 = _time.perf_counter() + raw_resp, raw_payload_top = _call_dify_blocking( + agent=agent, + user_id=user_id, + query=json.dumps(request_payload, ensure_ascii=False, separators=(',', ':')), + inputs={'review_llm_contract': LLM_REVIEW_CONTRACT_VERSION}, + _return_raw_response=True, # type: ignore[call-arg] + ) + row.latency_ms = int(round((_time.perf_counter() - _t0) * 1000)) + raw = raw_resp if isinstance(raw_resp, dict) else {'raw': raw_resp} + row.response_json = raw + # [OBS V2] Dify HTTP 返回顶层 conversation_id / message_id + top = raw_payload_top if isinstance(raw_payload_top, dict) else (raw if isinstance(raw, dict) else {}) + cid = top.get('conversation_id') or None + mid = top.get('message_id') or None + if cid is None: + cid = top.get('conversation') if isinstance(top.get('conversation'), str) else None + if isinstance(cid, (int, float)): + cid = str(cid) + if isinstance(mid, (int, float)): + mid = str(mid) + row.provider_conversation_id = (str(cid)[:255] if cid else _conversation_id_for_case(case)) or None + row.provider_message_id = (str(mid)[:255] if mid else None) or None + except TypeError: + # [兼容] _call_dify_blocking 原始签名:返回 dict;无 _return_raw_response + import time as _time + _t0 = _time.perf_counter() raw = _call_dify_blocking( agent=agent, user_id=user_id, query=json.dumps(request_payload, ensure_ascii=False, separators=(',', ':')), inputs={'review_llm_contract': LLM_REVIEW_CONTRACT_VERSION}, ) + row.latency_ms = int(round((_time.perf_counter() - _t0) * 1000)) row.response_json = raw if isinstance(raw, dict) else {'raw': raw} + if isinstance(raw, dict): + cid = raw.get('conversation_id') or raw.get('conversation') + mid = raw.get('message_id') + row.provider_conversation_id = (str(cid)[:255] if cid else _conversation_id_for_case(case)) or None + row.provider_message_id = (str(mid)[:255] if mid else None) or None except Exception as exc: if current_app: current_app.logger.warning('[order-review-llm] provider failed: %s', exc) @@ -388,15 +720,24 @@ def request_field_suggestion( error_code=row.error_code, metadata={'error_message': str(exc)[:256]}, ) - return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)} + return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)} + _audit_received_meta: dict[str, Any] = {'evidence_level': level} + if _auto_upgrade_reason: + _audit_received_meta.update({ + 'auto_upgrade_applied': True, + 'auto_upgrade_from': str(level_raw), + 'auto_upgrade_to': str(level), + 'auto_upgrade_reason': _auto_upgrade_reason, + 'auto_upgrade_reasons': list(_auto_upgrade_reasons), + }) _audit_llm_suggestion( case=case, actor_id=int(user_id), event_type='llm_review_received', action='llm_provider_received', suggestion=row, - metadata={'evidence_level': level}, + metadata=_audit_received_meta, ) suggestions = parse_suggestion_response(raw if isinstance(raw, dict) else {}) @@ -433,29 +774,55 @@ def request_field_suggestion( error_code=row.error_code, after={'valid': False, 'issues': row.validation_issues_json}, ) - return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)} + return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)} - validated = validate_suggestions_against_evidence(suggestions=matched, evidence_pack=evidence_pack) + validated = validate_suggestions_against_evidence( + suggestions=matched, + evidence_pack=evidence_pack, + envelope=request_payload, + expected_target_field_id=str(field_id), + expected_line_key=line_key, + expected_scope=scope, + ) row.validated_suggestions_json = validated primary = next( (item for item in validated if str(item.get('field_id') or '') == str(field_id)), None, ) - issues = [] + issues: list[dict[str, Any]] = [] if primary is None or not primary.get('valid'): - issues.append({ - 'code': str( - (primary or {}).get('rejection_reason') - or ('field_id_mismatch' if primary is None else 'value_not_in_evidence') - ), + reason_code = str( + (primary or {}).get('rejection_reason') + or ('field_id_mismatch' if primary is None else 'value_not_in_evidence') + ) + issue_entry: dict[str, Any] = { + 'code': reason_code, 'severity': 'blocking', - }) + } + if isinstance(primary, dict): + checks_order = primary.get('validation_checks_order') + if isinstance(checks_order, list) and checks_order: + issue_entry['checks_order'] = list(checks_order) + match_meta = primary.get('validation_match') + if isinstance(match_meta, dict) and match_meta: + issue_entry['match'] = dict(match_meta) + detail = primary.get('rejection_detail') + if isinstance(detail, str) and detail: + issue_entry['detail'] = detail[:2000] + issues.append(issue_entry) row.validation_issues_json = issues if primary is not None and primary.get('valid'): row.status = 'validated' value = primary.get('suggested_value') - row.suggested_value_json = {'value': value} + suggested_payload: dict[str, Any] = {'value': value} + vm = primary.get('validation_match') + if isinstance(vm, dict) and vm: + suggested_payload['validation_match'] = dict(vm) + checks_order = primary.get('validation_checks_order') + if isinstance(checks_order, list) and checks_order: + suggested_payload['validation_checks_order'] = list(checks_order) + row.suggested_value_json = suggested_payload apply_llm_suggestion_prefill( user_id=user_id, case_no=case_no, @@ -466,17 +833,26 @@ def request_field_suggestion( expected_draft_version=int(case.current_draft.draft_version), ) case = get_user_review_case(user_id=user_id, case_no=case_no) + _audit_after_valid: dict[str, Any] = {'valid': True} + if isinstance(vm, dict): + _audit_after_valid['validation_match_mode'] = vm.get('mode') _audit_llm_suggestion( case=case, actor_id=int(user_id), event_type='llm_suggestion_validated', action='llm_suggestion_validated', suggestion=row, - after={'valid': True}, + after=_audit_after_valid, ) else: row.status = 'validation_failed' row.error_code = 'SHIPPING.REVIEW_LLM_VALIDATION_FAILED' + _audit_after_invalid: dict[str, Any] = {'valid': False, 'issues': issues} + if _auto_upgrade_reason: + _audit_after_invalid.update({ + 'auto_upgrade_applied': True, + 'auto_upgrade_reason': _auto_upgrade_reason, + }) _audit_llm_suggestion( case=case, actor_id=int(user_id), @@ -485,11 +861,11 @@ def request_field_suggestion( suggestion=row, result='failed', error_code=row.error_code, - after={'valid': False, 'issues': issues}, + after=_audit_after_invalid, ) db.session.flush() - return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)} + return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)} def decide_suggestion( @@ -502,6 +878,7 @@ def decide_suggestion( value: Any = None, reason: str | None = None, note: str | None = None, + is_admin: bool = False, ) -> dict[str, Any]: """人工裁决 LLM 建议:accept / modify / reject。""" decision_norm = str(decision or '').strip().lower() @@ -570,4 +947,4 @@ def decide_suggestion( 'modify_value_present': decision_norm == 'modify' and value is not None, }, ) - return {'suggestion': serialize_suggestion(suggestion), 'case': case_payload} + return {'suggestion': serialize_suggestion(suggestion, is_admin=is_admin), 'case': case_payload} diff --git a/backend/app/services/shipping_notice/order_review_llm_validation.py b/backend/app/services/shipping_notice/order_review_llm_validation.py index 607d6121..88c4cc94 100644 --- a/backend/app/services/shipping_notice/order_review_llm_validation.py +++ b/backend/app/services/shipping_notice/order_review_llm_validation.py @@ -1,109 +1,427 @@ """ services/shipping_notice/order_review_llm_validation.py -用途:验证 LLM 建议值必须逐字存在于冻结证据包;拒绝文档外值。 -依赖:order_review_llm_contract。 -逻辑:人工接受前强制调用;按目标 field_id(及可选 line_key)闭合匹配完整 snippet.quote, - 禁止全文子串(避免 `10` 命中 `100`);验证失败不得预填草稿。 +用途:Phase 3 — LLM 建议后校验 fail-closed(8 项硬规则)。 + 任何一项未通过 → validation_failed,该建议仅能 reject,禁止 accept/modify 写入草稿。 +依赖: + - order_review_llm_contract:QUOTE_NORMALIZATION_RULES / normalize_quote_text + - request_payload.envelope:target / expected_target_field_id / evidence[] / line_key 定位 + - 响应解析层:parse_suggestion_response 输出 [{field_id, line_key, scope, suggested_value, quote}] +逻辑: + 8 项按顺序 fail-closed(优先级从身份→价值→安全性): + 1. json_schema_invalid 响应项非 dict / field_id 为空(结构性非法) + 2. header_scope_has_line_key scope=header 时 line_key 不为 None(头部不能带行键) + 3. non_target_field 响应 field_id 不在请求 expected_target_field_id 内 + 4. field_id_mismatch 响应 field_id 与 expected_target_field_id 不一致 + 5. line_key_mismatch scope=line 时响应 line_key != 请求 line_key(精确相等) + 6. value_not_in_evidence suggested_value 不在 evidence[] 任何 value/quote(normalize 后) + 7. quote_consistency 响应 quote normalize 后与 suggested_value quote 不构成 substring 或 + 完整相等;即使值存在也视为伪造 + 8. guess_without_evidence 响应 quote 为空且 suggested_value 不能 exact 匹配任何 evidence.value + + quote 匹配时:先 normalize(trim+collapse_whitespace),再允许 substring; + 命中后保存 match_mode=exact / exact_substring / normalized / normalized_substring, + normalized=true/false,normalization_rules=[...] 元数据,供审计与 UI 展示。 """ from __future__ import annotations -import re -from typing import Any +from typing import Any, Final + +from app.services.shipping_notice.order_review_llm_contract import ( + QUOTE_NORMALIZATION_RULES, + normalize_quote_text, +) + +# --------------------------------------------------------------------------- +# 硬规则顺序(按严重程度;前序命中立即短路,不做后续检查) +# --------------------------------------------------------------------------- +_VALIDATION_CHECKS_ORDER: Final[tuple[str, ...]] = ( + 'json_schema_invalid', + 'header_scope_has_line_key', + 'non_target_field', + 'field_id_mismatch', + 'line_key_mismatch', + 'value_not_in_evidence', + 'quote_consistency', + 'guess_without_evidence', +) +def _collect_evidence_values( + evidence_pack: dict[str, Any], + envelope: dict[str, Any] | None, +) -> list[dict[str, Any]]: + """ + 从 v2 envelope.evidence 或 v1 evidence_pack.fields[].snippets 提取候选值池。 + v2 优先读 envelope.evidence;缺失时回退 v1 结构(兼容历史 contract)。 + 每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, line_key, evidence_ref} + """ + pool: list[dict[str, Any]] = [] + env = envelope if isinstance(envelope, dict) else {} + ev_list = env.get('evidence') + if isinstance(ev_list, list) and ev_list: + for ev in ev_list: + if not isinstance(ev, dict): + continue + v_raw = ev.get('value') + q_raw = ev.get('quote') + pool.append({ + 'value_norm': normalize_quote_text(v_raw), + 'quote_norm': normalize_quote_text(q_raw), + 'value_raw': None if v_raw is None else str(v_raw), + 'quote_raw': None if q_raw is None else str(q_raw), + 'field_id': str(ev.get('field_id') or ''), + 'line_key': str(ev.get('line_key') or '').strip() or None, + 'evidence_ref': ev.get('evidence_ref'), + }) + return pool + # v1 兼容:evidence_pack.fields[].snippets[] + fields = (evidence_pack or {}).get('fields') or [] + for f in fields: + if not isinstance(f, dict): + continue + fid = str(f.get('field_id') or '') + lk = str(f.get('line_key') or '').strip() or None + for sn in (f.get('snippets') or []): + if not isinstance(sn, dict): + continue + q_raw = sn.get('quote') + v_raw = sn.get('value') if 'value' in sn else q_raw + pool.append({ + 'value_norm': normalize_quote_text(v_raw), + 'quote_norm': normalize_quote_text(q_raw), + 'value_raw': None if v_raw is None else str(v_raw), + 'quote_raw': None if q_raw is None else str(q_raw), + 'field_id': fid, + 'line_key': lk, + 'evidence_ref': sn.get('evidence_ref'), + }) + return pool + + +def _find_value_match( + pool: list[dict[str, Any]], + *, + value_norm: str, + quote_norm_provided: str, + field_id: str, + line_key: str | None, +) -> tuple[str, dict[str, Any] | None]: + """ + 在候选池中按 4 级严格度递减匹配 value;返回 (mode, matched_item)。 + 严格度:exact → exact_substring → normalized → normalized_substring + 同池内优先匹配 field_id + line_key 双重身份的项;其次 field_id;最后全局任意项。 + """ + if not value_norm and not quote_norm_provided: + return '', None + + # 身份过滤:先 field_id + line_key + def _iter_filtered(): + if not pool: + return + same_identity = [ + p for p in pool + if str(p.get('field_id') or '') == field_id + and (str(p.get('line_key') or '') == str(line_key or '') + if line_key else not p.get('line_key')) + ] + same_field = [ + p for p in pool + if str(p.get('field_id') or '') == field_id and p not in same_identity + ] + others = [p for p in pool if p not in same_identity and p not in same_field] + for p in same_identity + same_field + others: + yield p + + # 1. exact:raw 完全相等 + for p in _iter_filtered(): + vr = (p.get('value_raw') or '').strip() + qr = (p.get('quote_raw') or '').strip() + needle = value_norm.strip() + if (vr and vr == needle) or (qr and qr == needle): + return 'exact', p + + # 2. exact_substring:raw 内 substring + for p in _iter_filtered(): + vr = (p.get('value_raw') or '').strip() + qr = (p.get('quote_raw') or '').strip() + needle = value_norm.strip() + if not needle: + continue + if (vr and needle in vr) or (qr and needle in qr): + return 'exact_substring', p + + # 3. normalized:norm 完全相等 + for p in _iter_filtered(): + vn = p.get('value_norm') or '' + qn = p.get('quote_norm') or '' + if (vn and vn == value_norm) or (qn and qn == value_norm): + return 'normalized', p + + # 4. normalized_substring:norm 内 substring + for p in _iter_filtered(): + vn = p.get('value_norm') or '' + qn = p.get('quote_norm') or '' + if not value_norm: + continue + if (vn and value_norm in vn) or (qn and value_norm in qn): + return 'normalized_substring', p + + return '', None + + +def _check_quote_consistency( + *, + suggested_value_norm: str, + provided_quote_norm: str, + matched_item: dict[str, Any] | None, +) -> tuple[bool, str, str]: + """ + [Check 7] 响应提供的 quote 必须能回证: + - provided_quote 非空:normalize 后必须是 suggested_value 的完整相等或 substring(任一方向) + 或者 provided_quote normalize 后等于 matched_item.quote_norm 的完整/substring + - 空 quote:留到 Check 8 guess_without_evidence 再处理,此处不报错 + 返回 (passed, match_mode, rejection_reason_extra) + """ + if not provided_quote_norm: + return True, '', '' + # 方向 A:provided_quote 与 suggested_value 直接构成一致 + if suggested_value_norm and ( + provided_quote_norm == suggested_value_norm + or suggested_value_norm in provided_quote_norm + or provided_quote_norm in suggested_value_norm + ): + mode = 'quote_equals_value' if provided_quote_norm == suggested_value_norm else 'quote_substring_value' + return True, mode, '' + # 方向 B:provided_quote 与命中的证据项 quote_norm 构成一致(优先用精确证据) + if matched_item is not None: + item_qn = matched_item.get('quote_norm') or '' + item_vn = matched_item.get('value_norm') or '' + if item_qn and ( + provided_quote_norm == item_qn + or provided_quote_norm in item_qn + or item_qn in provided_quote_norm + ): + return True, 'quote_matches_evidence_quote', '' + if item_vn and ( + provided_quote_norm == item_vn + or provided_quote_norm in item_vn + or item_vn in provided_quote_norm + ): + return True, 'quote_matches_evidence_value', '' + return False, '', ( + f'provided quote [{provided_quote_norm[:80]}] does not align with ' + f'suggested_value or any matched evidence item quote/value' + ) + + +# --------------------------------------------------------------------------- +# 对外主入口:逐条逐项 8 项 fail-closed +# --------------------------------------------------------------------------- def validate_suggestions_against_evidence( *, suggestions: list[dict[str, Any]], evidence_pack: dict[str, Any], + envelope: dict[str, Any] | None = None, + expected_target_field_id: str | None = None, + expected_line_key: str | None = None, + expected_scope: str | None = None, ) -> list[dict[str, Any]]: """ - 校验建议列表;返回带 validation_status 的副本。 + Phase 3 fail-closed 校验。 Args: suggestions: parse_suggestion_response 输出。 - evidence_pack: select_review_evidence_pack 输出。 + evidence_pack: select_review_evidence_pack 输出(v1/v2 均含 fields 等)。 + envelope: build_suggestion_request_envelope 输出(用于 v2 evidence[] 和 target)。 + expected_target_field_id: 期望的唯一目标 field_id(v2 envelope.target.field_id 兜底)。 + expected_line_key: 期望 line_key(行 scope 用;header scope 传 None)。 + expected_scope: 'header' / 'line'(从 schema_field_meta.scope 兜底)。 Returns: - 每项增加 valid(bool) 与 rejection_reason。 + list,每项增加: + valid(bool)、rejection_reason(str|None)、 + validation_checks_order(list[str] 实际跑了哪些检查)、 + validation_match{ + mode(str), normalized(bool), + normalization_rules(list[str] = QUOTE_NORMALIZATION_RULES), + matched_evidence_ref(str|None), + }(仅 valid=True 时填充) """ result: list[dict[str, Any]] = [] - for item in suggestions: - payload = dict(item) - field_id = str(item.get('field_id') or '').strip() - line_key = str(item.get('line_key') or '').strip() or None - value = item.get('suggested_value') - value_text = str(value).strip() if value is not None else '' - if not value_text: - payload['valid'] = False - payload['rejection_reason'] = 'empty_suggestion' - elif _verbatim_in_field_snippets( - evidence_pack, - field_id=field_id, - line_key=line_key, - needle=value_text, - ): - payload['valid'] = True - payload['rejection_reason'] = None + env = envelope if isinstance(envelope, dict) else {} + target = env.get('target') if isinstance(env.get('target'), dict) else {} + + _exp_fid = ( + expected_target_field_id + or str(target.get('field_id') or '').strip() + or '' + ) + _exp_lk_raw = expected_line_key + if _exp_lk_raw is None: + _exp_lk_from_env = target.get('line_key') + _exp_lk_raw = None if _exp_lk_from_env is None else str(_exp_lk_from_env) + _exp_lk = str(_exp_lk_raw).strip() if _exp_lk_raw is not None else None + if _exp_lk == '' or _exp_lk == 'None': + _exp_lk = None + _exp_scope = ( + expected_scope + or str(target.get('scope') or '').strip().lower() + or '' + ) + if _exp_scope not in {'header', 'line'}: + _exp_scope = 'line' if _exp_lk else 'header' + + pool = _collect_evidence_values(evidence_pack, env) + + for raw_item in suggestions: + payload: dict[str, Any] = dict(raw_item) + checks_ran: list[str] = [] + rejection_reason: str | None = None + match_meta: dict[str, Any] = {} + + # ---- [Check 1] json_schema_invalid ---- + checks_ran.append('json_schema_invalid') + if not isinstance(raw_item, dict): + rejection_reason = 'json_schema_invalid' else: + fid = str(raw_item.get('field_id') or '').strip() + if not fid: + rejection_reason = 'json_schema_invalid' + if rejection_reason: payload['valid'] = False - payload['rejection_reason'] = 'value_not_in_evidence' + payload['rejection_reason'] = rejection_reason + payload['validation_checks_order'] = checks_ran + result.append(payload) + continue + + # ---- [Check 2] header_scope_has_line_key ---- + checks_ran.append('header_scope_has_line_key') + resp_scope = str(raw_item.get('scope') or '').strip().lower() + if not resp_scope: + resp_scope = 'line' if _exp_lk else 'header' + resp_lk_raw = raw_item.get('line_key') + resp_lk = None if resp_lk_raw is None else str(resp_lk_raw).strip() + if resp_lk in ('', 'None'): + resp_lk = None + effective_scope = _exp_scope if resp_scope not in {'header', 'line'} else resp_scope + if effective_scope == 'header' and resp_lk is not None: + rejection_reason = 'header_scope_has_line_key' + if rejection_reason: + payload['valid'] = False + payload['rejection_reason'] = rejection_reason + payload['validation_checks_order'] = checks_ran + result.append(payload) + continue + + # ---- [Check 3] non_target_field ---- + checks_ran.append('non_target_field') + resp_fid = str(raw_item.get('field_id') or '').strip() + if _exp_fid and resp_fid != _exp_fid: + rejection_reason = 'non_target_field' + if rejection_reason: + payload['valid'] = False + payload['rejection_reason'] = rejection_reason + payload['validation_checks_order'] = checks_ran + result.append(payload) + continue + + # ---- [Check 4] field_id_mismatch ---- + checks_ran.append('field_id_mismatch') + if _exp_fid and resp_fid != _exp_fid: + rejection_reason = 'field_id_mismatch' + if rejection_reason: + payload['valid'] = False + payload['rejection_reason'] = rejection_reason + payload['validation_checks_order'] = checks_ran + result.append(payload) + continue + + # ---- [Check 5] line_key_mismatch(行 scope 才校验;header scope line_key 须 None 已在 Check 2)---- + checks_ran.append('line_key_mismatch') + if effective_scope == 'line': + if _exp_lk and resp_lk != _exp_lk: + rejection_reason = 'line_key_mismatch' + if rejection_reason: + payload['valid'] = False + payload['rejection_reason'] = rejection_reason + payload['validation_checks_order'] = checks_ran + result.append(payload) + continue + + # ---- 归一化建议值 / quote(准备 Check 6/7/8)---- + suggested_value = raw_item.get('suggested_value') + sv_norm = normalize_quote_text(suggested_value) + quote_raw = raw_item.get('quote') + quote_norm = normalize_quote_text(quote_raw) + + # ---- [Check 6] value_not_in_evidence ---- + checks_ran.append('value_not_in_evidence') + if not sv_norm: + rejection_reason = 'value_not_in_evidence' + _matched_mode = '' + _matched_item = None + else: + _matched_mode, _matched_item = _find_value_match( + pool, + value_norm=sv_norm, + quote_norm_provided=quote_norm, + field_id=resp_fid, + line_key=resp_lk, + ) + if not _matched_mode: + rejection_reason = 'value_not_in_evidence' + if rejection_reason: + payload['valid'] = False + payload['rejection_reason'] = rejection_reason + payload['validation_checks_order'] = checks_ran + result.append(payload) + continue + + # ---- [Check 7] quote_consistency ---- + checks_ran.append('quote_consistency') + ok_q, q_mode, q_extra = _check_quote_consistency( + suggested_value_norm=sv_norm, + provided_quote_norm=quote_norm, + matched_item=_matched_item, + ) + if not ok_q: + rejection_reason = 'quote_consistency' + if q_extra: + payload['rejection_detail'] = q_extra + if rejection_reason: + payload['valid'] = False + payload['rejection_reason'] = rejection_reason + payload['validation_checks_order'] = checks_ran + result.append(payload) + continue + + # ---- [Check 8] guess_without_evidence ---- + checks_ran.append('guess_without_evidence') + if not quote_norm and _matched_mode not in {'exact', 'normalized'}: + rejection_reason = 'guess_without_evidence' + if rejection_reason: + payload['valid'] = False + payload['rejection_reason'] = rejection_reason + payload['validation_checks_order'] = checks_ran + result.append(payload) + continue + + # ---- 全部通过:记录匹配元数据 ---- + match_meta = { + 'mode': _matched_mode, + 'normalized': _matched_mode in {'normalized', 'normalized_substring', 'quote_consistency'}, + 'normalization_rules': list(QUOTE_NORMALIZATION_RULES), + 'matched_evidence_ref': ( + _matched_item.get('evidence_ref') if isinstance(_matched_item, dict) else None + ), + 'quote_alignment_mode': q_mode if q_mode else None, + } + payload['valid'] = True + payload['rejection_reason'] = None + payload['validation_checks_order'] = checks_ran + payload['validation_match'] = match_meta result.append(payload) + return result - - -def _verbatim_in_field_snippets( - evidence_pack: dict[str, Any], - *, - field_id: str, - line_key: str | None, - needle: str, -) -> bool: - """ - 在目标字段的 snippet.quote 上做完整相等或 token 边界匹配。 - - 核心逻辑:优先匹配同 field_id(及 line_key)的片段;不允许把整份证据拼成语料做子串。 - """ - if not needle or not field_id: - return False - for field in evidence_pack.get('fields') or []: - if not isinstance(field, dict): - continue - if str(field.get('field_id') or '') != field_id: - continue - pack_line = str(field.get('line_key') or '').strip() or None - if line_key and pack_line and pack_line != line_key: - continue - for snippet in field.get('snippets') or []: - if not isinstance(snippet, dict): - continue - snippet_line = str(snippet.get('line_key') or '').strip() or None - if line_key and snippet_line and snippet_line != line_key: - continue - quote = str(snippet.get('quote') or '').strip() - if not quote: - continue - if quote == needle or _token_boundary_match(quote, needle): - return True - return False - - -def _token_boundary_match(haystack: str, needle: str) -> bool: - """ - 在单条 quote 内按 token 边界匹配 needle,避免 `10` 命中 `100`。 - - 数字/字母数字连续串必须整段相等;其它文本使用单词边界。 - """ - if not haystack or not needle: - return False - if haystack == needle: - return True - # 数值建议:只接受完整数字 token,禁止前缀/子串。 - if re.fullmatch(r'[+-]?\d+(?:[.,]\d+)?', needle): - for token in re.findall(r'[+-]?\d+(?:[.,]\d+)?', haystack): - if token == needle: - return True - return False - pattern = r'(? list[str]: else: actions.append('edit_draft') # 普通路径不投影 confirm;自动建单走 STP retry;本轮不提供 manual_create_fallback。 - # STP 失败 / manual_fallback:可重试自动建单。 + # STP 失败:按 recovery_contract 统一判定是否可技术重试,并按 blocking_reason 注入裁决动作。 automation = None try: automation = _project_case_automation_status( @@ -534,10 +564,51 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]: ) except Exception: # noqa: BLE001 automation = None - if isinstance(automation, dict) and automation.get('retryable') and str(automation.get('status') or '') in { + auto_status = str((automation or {}).get('status') or '').strip().lower() + if isinstance(automation, dict) and auto_status in { 'failed', 'manual_fallback', } and not case.confirmed_task_id: - actions.append('retry_stp_auto_create') + retryable_flag = automation.get('retryable') + blocking_reason = ( + automation.get('blocking_reason') + or automation.get('reason_code') + or automation.get('error_code') + or '' + ) + from app.services.shipping_notice.recovery_contract import ( + derive_blocking_next_actions as _derive_next, + should_general_retry_be_removed as _should_remove_retry, + REMOVE_ACTIONS_WHEN_BLOCKED as _REMOVE_SET, + ) + remove_retry = _should_remove_retry( + retryable_flag=retryable_flag, + blocking_reason=blocking_reason, + ) + if not remove_retry and bool(retryable_flag): + actions.append('retry_stp_auto_create') + # [Phase 1-3] 注入裁决动作(如 adjudicate_duplicate、open_order_review),去重。 + # [Phase 2-5] 在业务阻断对象上追加 reconcile_and_progress 作为统一对账恢复入口 + # (与 derive 出的动作共存,前端可按动作码选择打开裁决面板或走自动化对账)。 + _business_blocking = ( + remove_retry or + (isinstance(blocking_reason, dict) and bool(blocking_reason.get('code'))) or + (isinstance(blocking_reason, str) and bool(blocking_reason)) + ) + if _business_blocking: + _bcode = ( + blocking_reason.get('code') if isinstance(blocking_reason, dict) else blocking_reason + ) + if _bcode and str(_bcode) not in { + 'inventory_source_unresolved', 'inventory_shortage', 'inventory_match_incomplete', + 'inventory_multi_file_conflict', 'order_review_required', + }: + if 'reconcile_and_progress' not in actions: + actions.append('reconcile_and_progress') + for _action in _derive_next(blocking_reason=blocking_reason): + if _action and _action not in actions: + actions.append(_action) + if remove_retry: + actions = [a for a in actions if a not in _REMOVE_SET] if llm_review_enabled() and 'edit_draft' in actions: actions.append('request_llm_suggestion') return actions @@ -679,15 +750,50 @@ def serialize_review_case( elif isinstance(post_confirm, dict) and post_confirm.get('task_no'): confirmed_task_no = str(post_confirm.get('task_no') or '') validation_snapshot = dict(draft.validation_result_json or {}) if draft is not None else None + + # [Phase 3] 共享 bundle:保证与 shipping-processing / conversation 卡片 + # 对同一 Case 的 automation / available_actions / current_gate / + # blocking_reason / primary_action / user_status 六事实 100% 同源。 + from app.services.shipping_notice.reconciliation_projector import ( + project_review_case_projection_bundle, + ) + bundle = project_review_case_projection_bundle( + case, + validation=validation_snapshot, + post_confirm=post_confirm if isinstance(post_confirm, dict) else None, + is_admin=is_admin, + ) + # 旧字段 enrichment(owner_type / phase)保留,仅在 bundle.automation 基础上附加 automation = enrich_automation_status( - _project_case_automation_status( - case, - validation=validation_snapshot, - post_confirm=post_confirm if isinstance(post_confirm, dict) else None, - ), + dict(bundle['automation']), formal_ot=formal_ot, is_admin=is_admin, ) + + # process_gate 兜底:当既无 Execution 又无 post_confirm 建单前阶段时, + # 用 bundle.current_gate + user_status 合成 process_gate 占位, + # 保证两端 current_gate 完全一致,不再让前端猜。 + if process_gate is None and execution is None: + cg = bundle.get('current_gate') or {} + if isinstance(cg, dict) and cg.get('gate_code'): + process_gate = { + 'execution_no': None, + 'status': 'running' if bundle.get('user_status') in {'running'} else ( + 'failed' if bundle.get('user_status') in {'failed', 'retryable'} else 'pending' + ), + 'current_blocking_gate': cg.get('blocking_reason_code'), + 'technical_auto_only': True, + 'owner_type': 'system', + 'available_actions': list(cg.get('next_action_code') or bundle['available_actions'][:1]), + 'gates_track': [ + { + 'gate_code': cg.get('gate_code'), + 'status': 'blocked' if cg.get('blocking_reason_code') else 'pending', + 'blocking_reason_code': cg.get('blocking_reason_code'), + 'next_action_code': cg.get('next_action_code'), + }, + ], + } from app.services.shipping_notice.order_review_customer_service import ( project_review_case_customer_resolution, ) @@ -778,7 +884,8 @@ def serialize_review_case( } # task_missing:无恢复 API 时明确 view + contact_admin;防御性剥离残留 confirm。 - available_actions = [a for a in _allowed_actions(case) if a != 'confirm'] + available_actions = list(bundle['available_actions']) if bundle else [a for a in _allowed_actions(case) if a != 'confirm'] + # 兼容兜底:task_missing 仍然优先固定视图动作。 if formal_ot.get('task_missing'): available_actions = ['view', 'contact_admin'] @@ -870,6 +977,10 @@ def serialize_review_case( 'process_gate': process_gate, 'inventory_issue_fallback': inventory_issue_fallback, 'conversation_allowed_actions': conversation_allowed_actions, + # [Phase 3] 新增三字段:与 shipping-processing 列表端完全同源 + 'user_status': bundle.get('user_status') if bundle else None, + 'blocking_reason': dict(bundle['blocking_reason']) if bundle and bundle.get('blocking_reason') else None, + 'primary_action': dict(bundle['primary_action']) if bundle and bundle.get('primary_action') else None, } diff --git a/backend/app/services/shipping_notice/order_schema/field_rules.py b/backend/app/services/shipping_notice/order_schema/field_rules.py index d41e7af2..3c035188 100644 --- a/backend/app/services/shipping_notice/order_schema/field_rules.py +++ b/backend/app/services/shipping_notice/order_schema/field_rules.py @@ -56,17 +56,17 @@ def compute_effective_reservation_id( def default_derivation_rules() -> list[dict[str, Any]]: """ - 返回新草稿默认派生规则(启用状态)。 + 返回新草稿默认派生规则(关闭状态)。 - 核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=True, - 内部项次为空时自动从客户 PO 行号派生;人工已锁定或目标有值时不覆盖。 + 核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False, + 避免未评审规则自动改写内部项次。 Returns: 可写入 definition_json.derivation_rules 的规则列表。 """ return [{ 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': True, + 'enabled': False, 'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no', 'strategy': 'copy_if_empty', 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 cdd9907d..9ee869f1 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 @@ -29,6 +29,9 @@ from app.models import ( from app.services.shipping_notice.candidate_qualification_service import ( recalculate_candidate_qualification, ) +from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import ( + collect_vc_candidate_conflicts, +) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.order_review_confirmation_service import ( confirm_review_case, @@ -348,6 +351,47 @@ def _xfa_stp_precheck(*, validation: dict[str, Any]) -> tuple[bool, str | None]: return True, None +def _vc_stp_precheck(*, candidate: ShippingOrderCandidate | None) -> tuple[bool, str | None]: + """ + Vendor Comments 三来源建单前再次校验 VC 合并结果(防御 CQ 快照与实际抽取结果漂移)。 + + 核心逻辑: + 1. candidate 为空 → 放行(VC 未启用场景); + 2. collect_vc_candidate_conflicts 结果中若存在 severity == blocking 的原因码 → 阻断; + 3. review_required 的原因码 → 阻断自动建单(允许人工,不允许 STP); + 4. 任何解析异常 → fail-closed 阻断自动建单。 + + Args: + candidate: Case 关联的当前 Candidate。 + + Returns: + (允许建单?, 阻断原因码);允许时 reason 为 None。 + """ + if candidate is None: + return True, None + try: + items = collect_vc_candidate_conflicts(candidate) + except Exception as exc: # noqa: BLE001 — 门禁 fail-closed + _LOGGER.warning('vc_stp_precheck collect_vc_candidate_conflicts failed: %s', exc) + return False, 'vc_source_integration_error' + review_seen = False + for item in items: + if not isinstance(item, dict): + continue + reason = str(item.get('reason') or '').strip() + severity = str(item.get('severity') or 'blocking').strip() + if severity == 'blocking' or reason in { + 'vc_source_region_unbound', + 'vc_source_format_invalid', + }: + return False, reason or 'vc_source_blocking_conflict' + if severity == 'review_required' and not review_seen: + review_seen = True + if review_seen: + return False, 'vc_source_conflict_unresolved' + return True, None + + def _traceability_metadata( *, run: ShippingOrderProcessingRun, @@ -556,6 +600,40 @@ def ensure_stp_auto_create_for_case( 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', } + vc_allowed, vc_block_reason = _vc_stp_precheck(candidate=candidate) + if not vc_allowed: + if case.status in {'unreviewed', 'draft', 'ready'}: + case.status = 'draft' + record_fulfillment_audit( + event_type='stp_auto_create_skipped', + aggregate_type='order_review_case', + aggregate_id=str(case.case_no), + action='stp_vc_conflict', + actor_type='system', + actor_id=None, + result='ignored', + metadata={ + 'run_no': str(resolved_run.run_no), + 'reason_code': vc_block_reason, + 'traceability': _traceability_metadata( + run=resolved_run, case=case, candidate=candidate, validation=validation, + ), + }, + source='stp_auto_create', + strict=True, + ) + db.session.flush() + if commit: + db.session.commit() + return { + 'case_no': case.case_no, + 'status': 'skipped_needs_review', + 'job_id': None, + 'can_auto_create': False, + 'blocking_reason_codes': [vc_block_reason] if vc_block_reason else [], + 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', + } + if not ( validation.get('status') == 'ready' and bool(validation.get('can_auto_create')) @@ -890,52 +968,29 @@ def execute_stp_auto_create_job(*, payload: dict[str, Any], job_id: int) -> dict } +# 注意:reconcile_run_review_cases_for_auto_progress 不在顶层 import, +# 避免 circular import。 +# 环:order_review_auto_progress_coordinator 在运行时(延迟)import 本模块 +# → 本模块顶层 import coordinator → coordinator 尚未完成初始化 → ImportError。 +# 因此 reconcile_run_review_cases_for_auto_progress 延迟 import 到 +# maybe_stp_auto_create_for_run 调用点。 + + def maybe_stp_auto_create_for_run(*, run: ShippingOrderProcessingRun) -> list[dict[str, Any]]: """ - 尝试对 Run 下未确认 Case 入队 STP 自动建单。 + Run 级 STP 自动建单薄封装(向后兼容)。 - 核心逻辑:资格 ready 且无人工改脏 → ensure 写入幂等 Job(queued); - Worker 再执行 confirm。失败不阻断同 Run 其他 Case;幂等键保证只保留一条有效入队。 + 原内联逻辑已下沉至 reconcile_run_review_cases_for_auto_progress 统一协调: + 客户指纹唯一确认 → Draft 校验 → STP 幂等入队;单 Case 异常局部 rollback。 + 保留本函数名与签名,防止 order_extraction.py 中 4 处调用点 break。 Args: - run: 已 ensure_run_review_cases 的抽取 Run。 + run: 已 ensure_run_review_cases 的抽取 Processing Run。 Returns: 每个尝试过的 Case 摘要列表。 """ - results: list[dict[str, Any]] = [] - case_ids = [ - int(row.id) - for row in ( - ShippingOrderReviewCase.query - .filter_by(run_id=int(run.id)) - .order_by(ShippingOrderReviewCase.id.asc()) - .with_entities(ShippingOrderReviewCase.id) - .all() - ) - ] - for case_id in case_ids: - case = db.session.get(ShippingOrderReviewCase, case_id) - if case is None: - continue - try: - results.append( - ensure_stp_auto_create_for_case( - case=case, - run=run, - commit=True, - refresh_validation=True, - ) - ) - except Exception as exc: # noqa: BLE001 - _LOGGER.exception('STP enqueue failed for case_id=%s', case_id) - try: - db.session.rollback() - except Exception: # noqa: BLE001 - pass - results.append({ - 'case_no': getattr(case, 'case_no', None), - 'status': 'enqueue_failed', - 'error': str(exc)[:300], - }) - return results + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_run_review_cases_for_auto_progress, + ) + return reconcile_run_review_cases_for_auto_progress(run) diff --git a/backend/app/services/shipping_notice/per_source_rpa_service.py b/backend/app/services/shipping_notice/per_source_rpa_service.py new file mode 100644 index 00000000..229bb500 --- /dev/null +++ b/backend/app/services/shipping_notice/per_source_rpa_service.py @@ -0,0 +1,643 @@ +""" +services/shipping_notice/per_source_rpa_service.py + +用途:逐 (task_no, source_code) 维度的库存 RPA Attempt 结构化管理(决策 D1/D2/D3)。 +依赖:models.ShippingTaskInventoryRpaAttempt、inventory_candidate_freeze_service(取候选源)、 + rpa.write_inventory_export_trigger_for_task(trigger 文件写入)、 + inventory_snapshot_store(快照复用判断)。 +逻辑:T4 新增的结构化表是正式 Attempt 计数真相;旧的 ShippingTaskEvent 统计作为兼容层, + 新的调用方(auto_progress Orchestrator、Gate handler、回调入口)逐步迁移到本模块。 + 三元组 (task_no, source_code, run_no) 幂等定位;迟到回调标记 superseded 不回写业务。 +""" + +from __future__ import annotations + +import hashlib +import json +import os +import uuid +from dataclasses import dataclass +from datetime import datetime, timedelta +from typing import Any + +from sqlalchemy import and_, func, or_ +from sqlalchemy.orm import Session + +from app import db +from app.models import ( + ShippingInventoryFile, + ShippingNotice, + ShippingTaskInventoryRpaAttempt, +) +from app.services.shipping_notice.stp_inventory_freeze import ( + task_frozen_inventory_source_codes, +) +from app.services.shipping_notice.inventory_snapshot_store import ( + find_latest_ready_snapshot, + is_snapshot_fresh, +) +from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task +from app.services.shipping_notice.rpa_attempts import max_rpa_inventory_attempts + + +def _attempt_ref_has_ready_snapshot( + attempt: ShippingTaskInventoryRpaAttempt, + *, + session: Session | None = None, +) -> bool: + """Attempt 状态 succeeded/consumed 时,二次验证 inventory_file_no 对应快照真实存在且 ready。 + + 防止 Attempt 状态与实际快照不同步(TTL 过期、文件被删、异步 ingest 未完成)时 + 被误判为 prepared 而绕过有效库存门禁。 + """ + sess = session or db.session + file_no = str(getattr(attempt, 'inventory_file_no', '') or '').strip() + if not file_no: + return False + inv_file = ( + sess.query(ShippingInventoryFile) + .filter(ShippingInventoryFile.inventory_file_no == file_no) + .one_or_none() + ) + return is_snapshot_fresh(inv_file) + + +PER_SOURCE_RUN_NO_PREFIX = 'PSR' # Per-Source Run,区别于 legacy T-xxx 全局 run_no + + +@dataclass +class PerSourcePrepareResult: + """ensure_all_required_sources_prepared 返回值——聚合所有源的逐源状态 + 总体结论。""" + + task_no: str + all_prepared: bool + prepared_source_codes: list[str] + pending_source_codes: list[str] + failed_source_codes: list[str] + source_attempts: dict[str, dict[str, Any]] # source_code → {attempt_no, status, run_no, error} + + +def _per_source_run_no(attempt: ShippingTaskInventoryRpaAttempt) -> str: + """构造 per-source 三元组唯一 run_no:PSR----。""" + suffix = uuid.uuid4().hex[:8].upper() + return f'{PER_SOURCE_RUN_NO_PREFIX}-{attempt.task_no}-{attempt.source_code}-A{attempt.attempt_no}-{suffix}' + + +def _latest_attempt( + task_no: str, + source_code: str, + *, + session: Session | None = None, +) -> ShippingTaskInventoryRpaAttempt | None: + """查询 (task, source) 维度最新的 Attempt(按 attempt_no desc, id desc)。""" + sess = session or db.session + return ( + sess.query(ShippingTaskInventoryRpaAttempt) + .filter( + and_( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.source_code == source_code, + ) + ) + .order_by( + ShippingTaskInventoryRpaAttempt.attempt_no.desc(), + ShippingTaskInventoryRpaAttempt.id.desc(), + ) + .first() + ) + + +def _consumed_run_nos( + task_no: str, + source_code: str, + *, + session: Session | None = None, +) -> set[str]: + """查询 (task, source) 维度已 consumed/superseded 的 run_no 集合,用于回调幂等/迟到判断。""" + sess = session or db.session + rows = ( + sess.query(ShippingTaskInventoryRpaAttempt.run_no) + .filter( + and_( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.source_code == source_code, + ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded')), + ) + ) + .all() + ) + return {r[0] for r in rows if r and r[0]} + + +def _next_attempt_no( + task_no: str, + source_code: str, + *, + session: Session | None = None, +) -> int: + """ + 计算 (task, source) 维度下一次 attempt_no(自上次 succeeded/consumed 之后的计数)。 + 自成功事件重置逻辑兼容 rpa_attempts.py 的事件统计语义,但基于结构化表计算。 + """ + sess = session or db.session + last_success = ( + sess.query(ShippingTaskInventoryRpaAttempt) + .filter( + and_( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.source_code == source_code, + ShippingTaskInventoryRpaAttempt.status.in_(('succeeded', 'consumed')), + ) + ) + .order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc()) + .first() + ) + base_no = last_success.attempt_no if last_success else 0 + subsequent_count = ( + sess.query(func.count(ShippingTaskInventoryRpaAttempt.id)) + .filter( + and_( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.source_code == source_code, + ShippingTaskInventoryRpaAttempt.attempt_no > base_no, + ) + ) + .scalar() + or 0 + ) + return base_no + int(subsequent_count) + 1 + + +def _trigger_filename(task_no: str, source_code: str, attempt_no: int) -> str: + """ + 新的 per-source trigger 文件名:SN-____A.trigger.json + 与 legacy 文件名(无 __SOURCE 后缀)并行不冲突,RPA Worker 按 __ 分割识别 source_code。 + """ + return f'SN-{task_no}__{source_code.upper()}__A{attempt_no}.trigger.json' + + +def _snapshot_ready_for_source( + source_code: str, + *, + rpa_source: dict[str, Any], + task: ShippingNotice, + session: Session | None = None, +) -> bool: + """判断某源是否已有有效快照(复用路径,命中则不触发 RPA)。""" + try: + warehouse_id = ( + str(rpa_source.get('fixed_warehouse_id')).strip().upper() or None + if isinstance(rpa_source, dict) + and str(rpa_source.get('warehouse_resolution_mode') or '').lower() == 'fixed' + else None + ) + snap = find_latest_ready_snapshot(source_code, warehouse_id) + except Exception: + snap = None + return snap is not None + + +def _attempts_summary( + task_no: str, + *, + source_codes: list[str], + session: Session | None = None, +) -> dict[str, dict[str, Any]]: + """汇总各源的最新 Attempt 状态(供前端 Projection.facts 消费)。""" + result: dict[str, dict[str, Any]] = {} + for code in source_codes: + att = _latest_attempt(task_no, code, session=session) + result[code] = { + 'attempt_no': att.attempt_no if att else 0, + 'status': att.status if att else 'not_started', + 'run_no': att.run_no if att else None, + 'error_code': att.error_code if att else None, + 'error_message': att.error_message if att else None, + } + return result + + +def ensure_all_required_sources_prepared( + task: ShippingNotice, + *, + mode: str = 'auto', + session: Session | None = None, +) -> PerSourcePrepareResult: + """ + 遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。 + 【AI 触发时机】:inventory_preparation Gate handler、AutoProgress Orchestrator 库存准备阶段调用。 + + 核心逻辑: + [STEP 1] 从 T3 冻结表/兼容 step_payload 读取候选 source_codes(保序)。 + [STEP 2] 对每个 source: + a. 先 try reuse snapshot(find_latest_ready_snapshot)→ 命中则 source ∈ prepared + b. 否则检查 (task, source) 当前最新 Attempt 状态: + - queued/running → pending(仍在等待) + - succeeded/consumed → 已 prepared + - failed 且 attempt_no < max_attempts → 触发下一 attempt(queued 新 run) + - failed 且 attempt_no ≥ max_attempts → failed(不自动再触发) + - 从未 attempt → 触发 attempt_no=1 + c. 写 ShippingTaskInventoryRpaAttempt 记录 + trigger 文件 + + Args: + task: 已冻结候选的任务(inventory_source_status ∈ STABLE)。 + mode: 'auto' = Orchestrator 自动推进;'retry_rpa' = 用户显式强制重试(跳过复用快照)。 + session: 可选 Session。 + + Returns: + PerSourcePrepareResult:总体 all_prepared 状态 + 已/待/失败源列表 + 各源 Attempt 摘要。 + """ + task_no = str(task.task_no or '').strip() + sess = session or db.session + source_codes = task_frozen_inventory_source_codes(task) + if not source_codes: + return PerSourcePrepareResult( + task_no=task_no, all_prepared=False, + prepared_source_codes=[], pending_source_codes=[], + failed_source_codes=[], source_attempts={}, + ) + + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + + prepared: list[str] = [] + pending: list[str] = [] + failed: list[str] = [] + + for source_code in source_codes: + rpa_source = get_database_inventory_source(source_code) or {'source_code': source_code} + + # 复用快照(retry_rpa 模式跳过,强制重新触发) + if mode != 'retry_rpa' and _snapshot_ready_for_source(source_code, rpa_source=rpa_source, task=task, session=sess): + prepared.append(source_code) + continue + + att = _latest_attempt(task_no, source_code, session=sess) + current_status = att.status if att else None + + if current_status in ('queued', 'running'): + pending.append(source_code) + continue + # 题2B 服务层并发双保险:_latest_attempt 可能读到缓存/旧事务;此处在创建前重新 SELECT ... FOR UPDATE + # 再次确认 (task_no, source_code) 的最新状态不为 queued/running,避免“双请求同时通过 _latest_attempt, + # 都判成 failed → 都创建新 Attempt”的竞态。仍以 DB 部分唯一索引作为最后兜底。 + if mode == 'retry_rpa' or (current_status == 'failed'): + from app.models.shipping_task_inventory_rpa_attempts import ( + ShippingTaskInventoryRpaAttempt as _Attempt2, + ) + q = ( + sess.query(_Attempt2) + .filter(_Attempt2.task_no == task_no) + .filter(_Attempt2.source_code == source_code) + .order_by(_Attempt2.attempt_no.desc()) + .limit(1) + ) + try: + double_check = q.with_for_update(key_share=True).first() + except Exception: # noqa: BLE001 + double_check = q.first() + if double_check and str(double_check.status or '').strip().lower() in {'queued', 'running'}: + pending.append(source_code) + continue + if double_check is not None and double_check is not att: + current_status = double_check.status + att = double_check + + if current_status in ('succeeded', 'consumed') and att and _attempt_ref_has_ready_snapshot(att, session=sess): + prepared.append(source_code) + continue + + max_attempts = max_rpa_inventory_attempts() + next_att_no = _next_attempt_no(task_no, source_code, session=sess) + if att and current_status == 'failed' and next_att_no - 1 >= max_attempts and mode != 'retry_rpa': + # 自动模式不触发超过 max_attempts 的重试,交由用户手动 + failed.append(source_code) + # 标记 exhausted 方便后续展示(不重复 commit,外层调用方可 flush) + if att and att.status != 'exhausted': + att.status = 'exhausted' + att.error_code = att.error_code or 'attempts_exhausted' + att.updated_at = datetime.utcnow() + sess.flush([att]) + continue + + # [STEP 2c] 新建 Attempt + 写 trigger 文件 + new_att = ShippingTaskInventoryRpaAttempt( + task_no=task_no, + source_code=source_code, + attempt_no=next_att_no, + source_run_no='', # 先写占位,构造 source_run_no 需要 id/attempt_no 稳定 + status='queued', + triggered_at=datetime.utcnow(), + lease_token=uuid.uuid4().hex, + execution_phase='trigger_written', + extra_json={'trigger_mode': mode}, + ) + sess.add(new_att) + sess.flush([new_att]) + new_att.source_run_no = _per_source_run_no(new_att) + sess.flush([new_att]) + + trigger_fname = _trigger_filename(task_no, source_code, next_att_no) + try: + # 复用旧 write_inventory_export_trigger_for_task 内部逻辑,但覆写其生成的文件名 + # (旧函数会按 task 级写 trigger;此处先调旧函数保证 payload 完整,再尝试重命名。) + # + # [T4 兼容策略] 先不修改 rpa.py 避免影响单源任务旧链路;RPA Worker 增加按 source_code 识别 + # trigger 文件的逻辑,文件名同时带 __SOURCE_CODE__A 后缀即可。 + # 这里的 trigger_file_path 仅作为审计字段记录,实际触发由 Worker 按目录扫描识别。 + from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + + legacy_rpa_source = task_rpa_inventory_source(task) or dict(rpa_source) + # 强制注入 source_code 覆盖旧 task 级单源字段,使 RPA Worker 可按 per-source 执行 + per_source_payload = { + 'schema_version': 'shipping_inventory_rpa.v2', + 'mode': mode, + 'attempt': next_att_no, + 'attempt_no': next_att_no, + 'source_code': source_code, + 'source_run_no': new_att.source_run_no, + 'batch_run_no': f'BATCH-{task_no}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}', + 'lease_token': new_att.lease_token, + 'per_source_attempt': True, + } + trigger_result = write_inventory_export_trigger_for_task( + task_no, + dict(legacy_rpa_source, **{'source_code': source_code}), + payload=per_source_payload, + ) + if trigger_result: + new_att.trigger_file_path = str(trigger_result) + else: + new_att.trigger_file_path = trigger_fname + pending.append(source_code) + except Exception as exc: # pragma: no cover - RPA 环境异常 + new_att.status = 'failed' + new_att.error_code = 'trigger_write_error' + new_att.error_message = f'{type(exc).__name__}: {str(exc)[:500]}' + new_att.updated_at = datetime.utcnow() + failed.append(source_code) + finally: + sess.flush([new_att]) + + summary = _attempts_summary(task_no, source_codes=source_codes, session=sess) + all_ok = len(prepared) == len(source_codes) and not pending and not failed + return PerSourcePrepareResult( + task_no=task_no, + all_prepared=all_ok, + prepared_source_codes=list(prepared), + pending_source_codes=list(pending), + failed_source_codes=list(failed), + source_attempts=summary, + ) + + +def per_source_callback_handler( + task: ShippingNotice, + *, + source_code: str, + run_no: str, + callback_payload: dict[str, Any], + session: Session | None = None, +) -> tuple[str, ShippingTaskInventoryRpaAttempt | None]: + """ + 处理 per-source 库存 RPA 回调(三元组幂等 + 迟到保护 + Task 全局状态保护)。 + 【AI 触发时机】:RPA Dropzone 回调入口、手动 ingest API、Worker 补录回调统一调用本函数。 + + 核心逻辑: + [STEP 1] 三元组 (task_no, source_code, run_no) 定位 Attempt;不存在 → return 'not_found' + [STEP 2] 幂等:Attempt.status == succeeded/consumed/superseded → return 'idempotent_ok' + [STEP 3] 迟到保护:若同 (task, source) 已有 run_no > 当前 run_no 已 consumed/superseded → 标记 superseded 不回写快照,return 'superseded_late' + [STEP 4] Task 全局终态保护:Task.status ∈ {completed, cancelled, failed_terminal} → 回调不写任何业务表,标记 late_callback_ignored(audit),return 'task_terminal' + [STEP 5] 校验通过:写 status=succeeded(成功)或 failed(回调含 error_code),回填 callback_payload_json / inventory_file_no / callback_file_path + [STEP 6] 返回处理结果(供调用方决定是否推进 Orchestrator)。 + + Args: + task: 发货任务实例。 + source_code: 库存源编码(大写)。 + run_no: 回调中携带的 PSR-* 三元组 run_no。 + callback_payload: 回调原始 payload(JSONB 存储)。 + session: 可选 Session。 + + Returns: + (result_code: str, attempt: ShippingTaskInventoryRpaAttempt | None) + result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, succeeded, failed} + """ + sess = session or db.session + task_no = str(task.task_no or '').strip() + source_code_up = str(source_code or '').strip().upper() + + # [STEP 1] 三元组定位 + attempt = ( + sess.query(ShippingTaskInventoryRpaAttempt) + .filter( + and_( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.source_code == source_code_up, + ShippingTaskInventoryRpaAttempt.run_no == run_no, + ) + ) + .one_or_none() + ) + if attempt is None: + return 'not_found', None + + # [STEP 2] 幂等 + if attempt.status in ('succeeded', 'consumed', 'superseded'): + return 'idempotent_ok', attempt + + # [STEP 3] 迟到保护:同 (task, source) 有更新 run 已终态 + consumed_runs = _consumed_run_nos(task_no, source_code_up, session=sess) + # Run no format: PSR---A- → 排序按 attempt_no 前缀即可 + try: + current_attempt_no = int(attempt.attempt_no) + except (TypeError, ValueError): + current_attempt_no = 0 + newer_count = ( + sess.query(func.count(ShippingTaskInventoryRpaAttempt.id)) + .filter( + and_( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.source_code == source_code_up, + ShippingTaskInventoryRpaAttempt.attempt_no > current_attempt_no, + ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded', 'succeeded')), + ) + ) + .scalar() + or 0 + ) + if newer_count > 0: + attempt.status = 'superseded' + attempt.callback_payload_json = dict(callback_payload or {}) + attempt.callback_received_at = datetime.utcnow() + attempt.updated_at = datetime.utcnow() + sess.flush([attempt]) + return 'superseded_late', attempt + + # [STEP 4] Task 已终态(兼容旧枚举 active/blocked 等非终态) + terminal_statuses = {'completed', 'cancelled', 'failed_terminal'} + if str(getattr(task, 'process_status', '') or '').strip() in terminal_statuses: + attempt.status = 'superseded' + attempt.extra_json = dict(attempt.extra_json or {}, late_callback_ignored=True, reason='task_terminal') + attempt.callback_payload_json = dict(callback_payload or {}) + attempt.callback_received_at = datetime.utcnow() + attempt.updated_at = datetime.utcnow() + sess.flush([attempt]) + return 'task_terminal', attempt + + # [STEP 5] 写回调结果 + attempt.callback_payload_json = dict(callback_payload or {}) + attempt.callback_received_at = datetime.utcnow() + attempt.callback_id = str(callback_payload.get('callback_id') or '').strip() or attempt.callback_id + attempt.file_generated = bool(callback_payload.get('file_path')) + attempt.file_path = str(callback_payload.get('file_path') or '').strip() or attempt.file_path + attempt.file_exists_at_callback = bool(attempt.file_path and __import__('pathlib').Path(attempt.file_path).is_file()) + attempt.execution_phase = 'callback_received' + attempt.updated_at = datetime.utcnow() + attempt.callback_file_path = str(callback_payload.get('callback_file_path') or '').strip() or None + inventory_file_no = str(callback_payload.get('inventory_file_no') or '').strip() or None + if inventory_file_no: + attempt.inventory_file_no = inventory_file_no + + error_code = str(callback_payload.get('error_code') or '').strip() or None + error_message = str(callback_payload.get('error_message') or '').strip() or None + if error_code: + attempt.status = 'failed' + attempt.transaction_status = 'rejected' + attempt.error_code = error_code + attempt.error_message = error_message[:2000] if error_message else None + sess.flush([attempt]) + return 'failed', attempt + # 回调标称成功,但必须二次验证快照已真实入库且 ready,否则仍然算失败(防止 RPA 伪成功) + if inventory_file_no: + _inv = ( + sess.query(ShippingInventoryFile) + .filter(ShippingInventoryFile.inventory_file_no == inventory_file_no) + .one_or_none() + ) + if _inv is None or not is_snapshot_fresh(_inv): + attempt.status = 'failed' + attempt.execution_phase = 'transaction_failed' + attempt.transaction_status = 'transaction_failed' + attempt.transaction_error_code = 'snapshot_not_ready_after_callback' + attempt.error_code = 'snapshot_not_ready_after_callback' + missing_reason = ( + 'inventory_file record not found' + if _inv is None + else f"snapshot not ready (status={_inv.snapshot_status}, " + f"path_exists={__import__('pathlib').Path(_inv.storage_path).is_file()})" + ) + attempt.error_message = ( + f"回调返回成功但关联库存快照未通过门禁校验:{missing_reason}"[:2000] + ) + sess.flush([attempt]) + return 'failed', attempt + attempt.status = 'succeeded' + attempt.transaction_status = 'succeeded' + sess.flush([attempt]) + # 回调只改变 Attempt/Snapshot 事实;正式 Task Gate 由 AutoProgress Job 重新校验。 + # 调用方在同一事务提交后,Job 才对 Worker 可见。 + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + + submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded', commit=False) + return 'succeeded', attempt + + +def claim_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: + """记录 Worker 领取的逐源 Attempt,不推进 Snapshot、Link 或 Gate。""" + if payload.get('schema_version') != 'shipping_inventory_rpa.v2' or not isinstance(payload.get('items'), list): + return {'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid'} + worker_id = str(payload.get('worker_id') or '').strip() or None + now = datetime.utcnow() + results: list[dict[str, Any]] = [] + for item in payload['items']: + if not isinstance(item, dict): + results.append({'business_status': 'rejected', 'error_code': 'callback_schema_invalid'}) + continue + task_no = str(item.get('task_no') or '').strip() + source_code = str(item.get('source_code') or '').strip().upper() + source_run_no = str(item.get('source_run_no') or '').strip() + lease_token = str(item.get('lease_token') or '').strip() + attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by( + task_no=task_no, source_code=source_code, source_run_no=source_run_no, + ).one_or_none() + if attempt is None or str(attempt.lease_token or '') != lease_token: + results.append({'task_no': task_no, 'source_code': source_code, 'source_run_no': source_run_no, + 'business_status': 'rejected', 'error_code': 'callback_identity_mismatch'}) + continue + if attempt.status in ('succeeded', 'consumed', 'superseded'): + results.append({'task_no': task_no, 'source_code': source_code, 'source_run_no': source_run_no, + 'business_status': 'succeeded', 'replayed': True}) + continue + attempt.status = 'running' + attempt.execution_phase = 'worker_claimed' + attempt.claimed_at = now + attempt.worker_id = worker_id + attempt.updated_at = now + results.append({'task_no': task_no, 'source_code': source_code, 'source_run_no': source_run_no, + 'business_status': 'succeeded'}) + db.session.flush() + return {'transport_status': 'received', 'batch_status': 'partial_failed' if any(r.get('business_status') == 'rejected' for r in results) else 'succeeded', 'items': results} + + +def per_source_timeout_scan( + task: ShippingNotice, + *, + timeout_seconds: int, + session: Session | None = None, +) -> dict[str, Any]: + """ + 扫描 (task, source) 维度的超时 Attempt,对过期 running/queued 标记 failed 并写错误信息。 + 【AI 触发时机】:AutoProgress 轮询间隔、batch_orchestrator 巡检、Worker 启动 stale scan 调用。 + + Args: + task: 发货任务。 + timeout_seconds: 单源 RPA 超时(秒);超过 triggered_at 或 leased_at 阈值未回调即失败。 + session: 可选 Session。 + + Returns: + {'timed_out_count': int, 'details': {source_code: {attempt_no, elapsed, prev_status}}} + """ + sess = session or db.session + task_no = str(task.task_no or '').strip() + threshold = datetime.utcnow() - timedelta(seconds=max(int(timeout_seconds), 1)) + candidates = ( + sess.query(ShippingTaskInventoryRpaAttempt) + .filter( + and_( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + or_( + ShippingTaskInventoryRpaAttempt.triggered_at <= threshold, + ShippingTaskInventoryRpaAttempt.leased_at <= threshold, + ShippingTaskInventoryRpaAttempt.created_at <= threshold, + ), + ) + ) + .all() + ) + details: dict[str, dict[str, Any]] = {} + for att in candidates: + elapsed = int((datetime.utcnow() - (att.triggered_at or att.created_at)).total_seconds()) + prev_status = att.status + trigger_path = str(att.trigger_file_path or '').strip() + trigger_missing = bool( + prev_status == 'queued' + and trigger_path + and not os.path.isfile(trigger_path) + ) + att.status = 'failed' + att.error_code = 'trigger_not_claimed_missing' if trigger_missing else 'per_source_timeout' + att.error_message = ( + f'Attempt 已排队 {elapsed}s,但 Trigger 文件不存在,Worker 未领取' + if trigger_missing + else f'等待 {elapsed}s 超过阈值 {timeout_seconds}s(状态 {prev_status})' + ) + att.updated_at = datetime.utcnow() + sess.flush([att]) + details[att.source_code] = { + 'attempt_no': att.attempt_no, + 'elapsed_seconds': elapsed, + 'prev_status': prev_status, + 'reason_code': att.error_code, + 'trigger_file_path': trigger_path or None, + } + return {'timed_out_count': len(details), 'details': details} diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 296d2670..127e0caf 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -388,6 +388,9 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({ 'order_extraction_cancelled', 'evidence_missing', 'required_field_missing', + 'final_required_field_missing', + 'profile_schema_mismatch', + 'row_needs_review', 'reservation_invalid', 'reservation_missing', 'reservation_duplicate', @@ -484,6 +487,7 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({ 'xfa_visual_not_publishable', 'xfa_visual_bindings_required', 'xfa_visual_binding_incomplete', + 'xfa_source_mapping_incomplete', # 跨门禁技术重试耗尽(不绑定唯一 owning_gate,由当前 Gate 承载) 'technical_retry_exhausted', }) @@ -500,6 +504,10 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = { 'order_extraction_cancelled': 'order_field_extraction', 'evidence_missing': 'order_field_extraction', 'required_field_missing': 'field_completeness', + 'final_required_field_missing': 'field_completeness', + 'profile_schema_mismatch': 'document_profile_routing', + 'row_needs_review': 'order_field_extraction', + 'xfa_source_mapping_incomplete': 'order_field_extraction', 'reservation_invalid': 'reservation_validation', 'reservation_missing': 'reservation_validation', 'reservation_duplicate': 'reservation_validation', @@ -775,4 +783,294 @@ def assert_process_gate_contract_integrity() -> None: assert len(owned_reasons) == len(set(owned_reasons)), 'duplicate reason ownership' for legacy_key, gate in AUTO_BUILD_LEGACY_GATE_OWNING_MAP.items(): - assert gate in PROCESS_GATE_CODE_SET, f'legacy auto-build key {legacy_key} maps to unknown gate' + assert gate in PROCESS_GATE_CODE_SET, f'legacy auto-build key {legacy_key} maps to unknown gate {gate}' + + # [USER_STATE_CONTRACT] 校验 Gate.status / Execution.status / reason_code 与用户态的映射闭环 + for gate_status in PROCESS_GATE_STATUSES: + assert gate_status in GATE_STATUS_TO_USER_STATUS, ( + f'gate status {gate_status} missing in GATE_STATUS_TO_USER_STATUS' + ) + for exec_status in PROCESS_EXECUTION_STATUSES: + assert exec_status in EXECUTION_STATUS_TO_USER_STATUS, ( + f'execution status {exec_status} missing in EXECUTION_STATUS_TO_USER_STATUS' + ) + for reason in PROCESS_GATE_BLOCKING_REASON_CODES: + if reason == 'technical_retry_exhausted': + # 跨门禁技术原因码,可豁免精确分类,默认为 terminal_failed + continue + assert reason in BLOCKING_REASON_TO_USER_MODE, ( + f'blocking reason {reason} missing in BLOCKING_REASON_TO_USER_MODE' + ) + mode = BLOCKING_REASON_TO_USER_MODE[reason] + assert mode in BLOCKING_REASON_USER_MODES, ( + f'reason {reason} invalid user mode {mode}' + ) + + # [INVENTORY_SUB_STAGE_CONTRACT] 校验库存 4 主 Gate 的 sub_stage 命名已在白名单 + for gate_code in INVENTORY_MAIN_GATES: + assert gate_code in PROCESS_GATE_CODE_SET, f'unknown inventory main gate {gate_code}' + for name in INVENTORY_SUB_STAGES: + assert name in INVENTORY_SUB_STAGES, f'inventory sub_stage {name} not in whitelist' + + +# ============================================================ +# 用户态状态契约(v1) +# 决策1 / F2:底层不迁移,仅在 Projection 层统一映射。 +# 所有前端、Chatflow、任务中心只读 USER_FACING_TASK_STATUSES。 +# ============================================================ + +USER_FACING_TASK_STATUSES: Final[frozenset[str]] = frozenset({ + 'running', + 'waiting_human', + 'retryable', + 'failed', + 'completed', + 'cancelled', +}) + +# Gate.status → 用户态主状态。 +# 规则: +# pending/queued/running/passed/skipped/invalidated → running(交给执行驱动) +# blocked_manual → waiting_human(人工门禁) +# blocked_retryable → retryable(技术/外部暂态失败,可重试) +# waiting_external → running(等待回调,用户感知为处理中) +# failed_terminal → failed(不可自动恢复的终态失败) +GATE_STATUS_TO_USER_STATUS: Final[dict[str, str]] = { + 'pending': 'running', + 'queued': 'running', + 'running': 'running', + 'passed': 'running', + 'blocked_retryable': 'retryable', + 'blocked_manual': 'waiting_human', + 'waiting_external': 'running', + 'failed_terminal': 'failed', + 'invalidated': 'running', + 'skipped': 'running', +} + +# Execution.status → 用户态主状态。 +# 当 Gate 信息缺失时,作为 Projection 的回退层。 +# active/waiting_external → running +# blocked → retryable(Proj 再结合 Gate 细分,此处不放大为 waiting_human) +# completed → completed;cancelled → cancelled;failed → failed +EXECUTION_STATUS_TO_USER_STATUS: Final[dict[str, str]] = { + 'active': 'running', + 'blocked': 'retryable', + 'waiting_external': 'running', + 'completed': 'completed', + 'cancelled': 'cancelled', + 'failed': 'failed', +} + +# 阻断原因码 → 用户处置模式。用于 retryable / primary_action 推导。 +# 禁止前端或 Projection 层各写一份 reason→action 的 switch-case。 +BLOCKING_REASON_USER_MODES: Final[frozenset[str]] = frozenset({ + 'retryable_tech', # 技术/外部系统失败,可自动或用户点击重试 + 'needs_human', # 需要人工决策或提供输入 + 'terminal_failed', # 业务或配置终态失败,普通重试无意义 +}) + +BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = { + # --- 文档/抽取/路由/通用 --- + 'document_unavailable': 'retryable_tech', + 'layout_parse_failed': 'retryable_tech', + 'profile_ambiguous': 'needs_human', + 'profile_drift': 'retryable_tech', + 'profile_not_matched': 'needs_human', + 'extraction_incomplete': 'needs_human', + 'order_extraction_failed': 'retryable_tech', + 'order_extraction_cancelled': 'terminal_failed', + 'evidence_missing': 'needs_human', + 'required_field_missing': 'needs_human', + 'final_required_field_missing': 'needs_human', + 'profile_schema_mismatch': 'needs_human', + 'row_needs_review': 'needs_human', + 'xfa_source_mapping_incomplete': 'needs_human', + 'reservation_invalid': 'needs_human', + 'reservation_missing': 'needs_human', + 'reservation_duplicate': 'needs_human', + 'customer_unresolved': 'needs_human', + 'customer_ambiguous': 'needs_human', + 'duplicate_unresolved': 'needs_human', + 'field_conflict': 'needs_human', + 'cross_source_conflict': 'needs_human', + 'pdf_preferred_critical_conflict': 'needs_human', + 'pdf_preferred': 'needs_human', + 'classification_low_confidence': 'needs_human', + 'field_low_confidence': 'needs_human', + 'extraction_emergency_stop': 'terminal_failed', + 'run_failed': 'retryable_tech', + 'run_cancelled': 'terminal_failed', + 'technical_failure_present': 'retryable_tech', + 'gate_invalidated': 'retryable_tech', + 'lease_conflict': 'retryable_tech', + 'version_conflict': 'retryable_tech', + 'not_recoverable': 'terminal_failed', + 'unit_review_required': 'needs_human', + 'budget_stopped': 'terminal_failed', + 'technical_retry_exhausted': 'terminal_failed', + + # --- 库存源路由(多库存源为合法链路,除非以下原因才阻断)--- + 'no_inventory_source_candidates': 'needs_human', # 零候选 + 'require_manual_review': 'needs_human', # 规则明确要求人工 + 'inventory_source_unavailable': 'needs_human', # 候选源配置被禁用(需人工改路由) + 'inventory_source_conflicted': 'needs_human', # 路由规则冲突 + 'inventory_source_changed': 'retryable_tech', # 配置漂移,可重跑规则 + 'inventory_source_identity_mismatch': 'needs_human', # 仓库身份不匹配,需人工确认 + 'retry_with_latest_rules': 'retryable_tech', + + # --- 库存准备 / RPA --- + 'inventory_preparation_failed': 'retryable_tech', + 'inventory_preparation_waiting': 'retryable_tech', + 'inventory_rpa_queued': 'retryable_tech', + 'inventory_rpa_timeout': 'retryable_tech', + 'inventory_rpa_login_failed': 'retryable_tech', + 'inventory_rpa_export_failed': 'retryable_tech', + 'inventory_rpa_exhausted': 'needs_human', # RPA 重试耗尽 → 人工上传 + 'inventory_file_missing': 'retryable_tech', + 'inventory_file_empty': 'retryable_tech', + 'inventory_file_identity_mismatch': 'needs_human', + + # --- 库存字段映射 --- + 'inventory_mapping_required': 'needs_human', + 'inventory_required_column_missing': 'needs_human', + 'inventory_column_ambiguous': 'needs_human', + + # --- 库存匹配(短缺/冲突/未找到都是人工门禁;retryable 仅技术类)--- + 'inventory_match_failed': 'retryable_tech', + 'inventory_multi_file_conflict': 'needs_human', # 跨源冲突 + 'inventory_sku_not_found': 'needs_human', # 料号未命中 → 短缺/未找到 + 'inventory_reservation_not_found': 'needs_human', # 预约单未命中 → 短缺 + 'inventory_warehouse_mismatch': 'needs_human', + 'inventory_insufficient': 'needs_human', # 短缺 → shortage_review + 'inventory_shortage_review_required': 'needs_human', + + # --- 订单冻结 / 建单 / 通用 feature flag --- + 'freeze_not_ready': 'retryable_tech', + 'profile_not_auto_freeze_approved': 'needs_human', + 'profile_manual_confirmation_required': 'needs_human', + 'profile_auto_freeze_qualification_missing': 'needs_human', + 'profile_auto_freeze_suspended': 'needs_human', + 'customer_confirmation_required': 'needs_human', + 'customer_scope_unmatched': 'needs_human', + 'customer_scope_not_configured': 'terminal_failed', + 'customer_scope_out_of_scope': 'terminal_failed', + 'multiple_customers_detected': 'needs_human', + 'multiple_profiles_detected': 'needs_human', + 'business_scenario_unmatched': 'needs_human', + 'business_scenario_not_configured': 'terminal_failed', + 'business_scenario_out_of_scope': 'terminal_failed', + 'generic_auto_freeze_disabled': 'needs_human', + 'llm_path_cannot_auto_freeze': 'needs_human', + 'auto_freeze_not_enabled': 'needs_human', + 'auto_create_disabled': 'needs_human', + 'review_required': 'needs_human', + 'pending_orders_present': 'needs_human', + 'task_creation_failed': 'retryable_tech', + 'xfa_auto_create_disabled': 'needs_human', + 'xfa_shadow_mode': 'needs_human', + 'xfa_profile_not_blind_approved': 'needs_human', + 'xfa_allowlist_unconfigured': 'terminal_failed', + 'xfa_customer_not_allowlisted': 'terminal_failed', + 'xfa_profile_checksum_not_allowlisted': 'terminal_failed', + 'xfa_scenario_not_allowlisted': 'terminal_failed', + 'xfa_evidence_incomplete': 'needs_human', + 'xfa_cross_check_failed': 'needs_human', + 'xfa_visual_coverage_insufficient': 'needs_human', + 'xfa_evidence_retention_insufficient': 'needs_human', + 'xfa_mirror_consistency_insufficient': 'needs_human', + 'xfa_profile_checksum_mismatch': 'retryable_tech', + 'xfa_visual_not_publishable': 'needs_human', + 'xfa_visual_bindings_required': 'needs_human', + 'xfa_visual_binding_incomplete': 'needs_human', + + # --- Excel / 货代上传 --- + 'excel_not_ready': 'retryable_tech', + 'excel_template_missing': 'terminal_failed', + 'excel_input_incomplete': 'needs_human', + 'artifact_validation_failed': 'retryable_tech', + 'artifact_generation_failed': 'retryable_tech', + 'manual_upload_pending': 'needs_human', # Excel 已生成,等待人工上传 + 'upload_rpa_pending': 'retryable_tech', + 'upload_rpa_failed': 'retryable_tech', + 'upload_rpa_login_failed': 'retryable_tech', + 'upload_platform_rejected': 'needs_human', + 'upload_result_unknown': 'retryable_tech', +} + + +# ============================================================ +# 库存 4 主 Gate 的内部子阶段命名(决策 A1:不新增 Gate 实例) +# 短缺/冲突作为 inventory_matching 的 blocking_reason_code 分支,不新增独立 Gate。 +# Projection 层读 Gate.effective_result_json['inventory_sub_stage'] 展示。 +# ============================================================ + +INVENTORY_MAIN_GATES: Final[tuple[str, ...]] = ( + 'inventory_source_routing', # 路由规则计算(sub_stage=calculated) + 'order_freeze_readiness', # 候选冻结(建单瞬间,sub_stage=frozen)——注意:复用现有 Gate,避免 seq 漂移 + 'inventory_preparation', # 多源快照准备(sub_stage=snapshots_ready) + 'inventory_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking) +) + +INVENTORY_SUB_STAGES: Final[frozenset[str]] = frozenset({ + 'not_started', + 'calculated', # 路由规则评估完成 + 'frozen', # 候选集合已写入结构化表 + Snapshot + 'snapshots_ready', # 所有必需源 snapshot ready + 'matched', # 全行 ok,匹配裁决完成 + 'blocked_by_shortage', # 匹配 Gate 下:短缺阻断 + 'blocked_by_conflict', # 匹配 Gate 下:多源冲突阻断 + 'blocked_by_stale_snapshot', # 匹配 Gate 下:快照过期 + 'blocked_by_unknown', # 匹配 Gate 下:未知技术阻断 +}) + +INVENTORY_SUB_STAGE_FIELD: Final[str] = 'inventory_sub_stage' +INVENTORY_SOURCE_STATUS_FIELD: Final[str] = 'inventory_source_status' + +# Projection.facts.inventory_source_status 可取值集合 +PROJECTION_INVENTORY_SOURCE_STATUSES: Final[frozenset[str]] = frozenset({ + 'not_frozen', + 'candidates_calculated', + 'candidates_frozen', + 'snapshots_ready', + 'matched', +}) + +# Projection.facts.export_state / upload_state 可取值集合 +PROJECTION_EXPORT_STATES: Final[frozenset[str]] = frozenset({ + 'not_created', + 'creating', + 'created', + 'failed', +}) +PROJECTION_UPLOAD_STATES: Final[frozenset[str]] = frozenset({ + 'not_created', + 'uploading', + 'callback_received', + 'manual_upload_pending', + 'failed', + 'succeeded', +}) + + +# ============================================================ +# 便捷查询函数(供 Projection 层直接调用,避免各处写 if/else) +# ============================================================ + +def user_status_for_gate_status(gate_status: str | None) -> str: + """按 Gate.status 返回用户态;未知态兜底为 running。""" + key = str(gate_status or '').strip() or 'pending' + return GATE_STATUS_TO_USER_STATUS.get(key, 'running') + + +def user_status_for_execution_status(execution_status: str | None) -> str: + """按 Execution.status 返回用户态;未知态兜底 running。""" + key = str(execution_status or '').strip() or 'active' + return EXECUTION_STATUS_TO_USER_STATUS.get(key, 'running') + + +def user_mode_for_blocking_reason(reason_code: str | None) -> str | None: + """返回 blocking reason 的用户处置模式;未知 reason 返回 None(调用方兜底)。""" + if not reason_code: + return None + return BLOCKING_REASON_TO_USER_MODE.get(str(reason_code).strip()) diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 0f658943..57c2af99 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -39,6 +39,7 @@ _WRITE_ACTION_CODES = frozenset({ 'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate', + 'reconcile_and_progress', 'open_profile_review', 'open_inventory_source_review', 'open_inventory_match_review', @@ -523,3 +524,487 @@ def reconcile_processing_projection_facts( invalidated_from_stage=invalidated_from_stage, ) return payload + + +# [T8 用户态 Projection 新枚举 F2] status 映射:running / waiting_human / retryable / failed / completed / cancelled。 +_USER_PROCESSING_STATUSES = frozenset({ + 'running', + 'waiting_human', + 'retryable', + 'failed', + 'completed', + 'cancelled', +}) + +_USER_STAGE_TO_CODE: dict[str, str] = { + # 建单 → 库存准备 → 匹配 → Excel → 上传 → 完成。 + 'document_parsing': 'document_parsing', + 'order_creating': 'order_creating', + 'waiting_review': 'waiting_human_review', + 'inventory_fetching': 'inventory_fetch', + 'inventory_matching': 'inventory_match', + 'excel_generating': 'excel_generate', + 'freight_uploading': 'freight_upload', + 'completed': 'completed', + 'failed': 'failed_terminal', + 'cancelled': 'cancelled', +} + + +def apply_user_projection_fields( + payload: dict[str, Any], + *, + notice: Any | None = None, + order_task: Any | None = None, +) -> dict[str, Any]: + """ + 在原有 ShippingProcessingProjection 上新增用户态 Projection 7 字段(决策 F3)。 + + 【AI 触发时机】:任何需要向前端返回 OrderTask/Conversation 投影的末端出口, + 在 reconcile_processing_projection_facts 之后、record_projection_inconsistency 之后调用。 + + 核心逻辑(决策 F3:新增字段不替换旧枚举,Retry Decision 优先 + legacy 兜底): + [STEP 1] 保存旧枚举到 legacy_status / legacy_stage / legacy_current_gate,避免旧前端 break。 + [STEP 2] 读取 pending_reason / review_status / inventory_source_status 原始字段。 + [STEP 3] 计算 Retry Decision(仅 notice 存在时,失败/不存在则 legacy 兜底)。 + [STEP 4] 按冻结优先级计算 user_status(completed/cancelled/failed → retryable → waiting_human → running)。 + [STEP 5] 计算 retryable(bool)。 + [STEP 6] 计算 blocking_reason:{code, i18n_key, details} 或 None。 + [STEP 7] 计算 primary_action:对应 blocking_reason/status 的唯一主动作,或 None。 + [不变] user_stage / user_current_gate_code / facts 子事实计算保持不动。 + + Args: + payload: reconcile_processing_projection_facts 输出后的原始 dict。 + notice: 可选 ShippingNotice 实体(用于 Retry Decision 与 facts)。 + order_task: 可选 ShippingOrderTask 实体(用于 facts 与 legacy pending_reason)。 + + Returns: + 就地修改后的 payload(含新增 7 字段与 3 个 legacy_* 备份)。 + """ + from app.services.shipping_notice.constants import ( + RS_SHORTAGE_REVIEW as REVIEW_STATUS_SHORTAGE_REVIEW, + PH_INVENTORY_SOURCE_UNRESOLVED as PROCESS_HUMAN_PENDING_INVENTORY_SOURCE, + PH_SHORTAGE as PROCESS_HUMAN_PENDING_SHORTAGE, + ) + _INVENTORY_SOURCE_STATUS_UNRESOLVED = 'unresolved' + _INVENTORY_SOURCE_STATUS_CANDIDATES_FROZEN = 'candidates_frozen' + _INVENTORY_SOURCE_STATUS_RESOLVED = 'resolved' + _PROCESS_HUMAN_PENDING_MATCH = 'match_review_pending' + + # ===== [STEP 1] 旧枚举备份(保持不变) ===== + payload['legacy_status'] = payload.get('status') + payload['legacy_stage'] = payload.get('stage') + payload['legacy_current_gate'] = payload.get('current_gate') + old_status = str(payload.get('status') or '').strip().lower() + old_stage = str(payload.get('stage') or '').strip().lower() + + # ===== [STEP 2] 读取 notice / order_task 原始字段(保持不变) ===== + pending_reason: str | None = None + review_status_raw: str | None = None + inventory_source_status_raw: str | None = None + if notice is not None: + pending_reason = str(getattr(notice, 'pending_human_reason', None) or '').strip() or None + review_status_raw = str(getattr(notice, 'review_status', None) or '').strip() or None + inventory_source_status_raw = str(getattr(notice, 'inventory_source_status', None) or '').strip() or None + if order_task is not None and not pending_reason: + pending_reason = str(getattr(order_task, 'pending_human_reason', None) or '').strip() or None + + # ===== [STEP 3] 计算 Retry Decision(仅 notice 真实存在时) ===== + retry_decision: dict | None = None + rd_action: str | None = None + rd_status: str | None = None + rd_retryable: bool = False + rd_reason_code: str | None = None + _RD_NEEDS_HUMAN: str | None = None + _RD_NOOP: str | None = None + _RD_STATUS_RUNNING: str | None = None + _RD_STATUS_NEEDS_HUMAN: str | None = None + _RD_STATUS_COMPLETED: str | None = None + _RD_STATUS_FAILED: str | None = None + if notice is not None: + try: + from app.services.shipping_notice.task_retry_decision_service import ( + decide_retry_action_only, + ACTION_NEEDS_HUMAN as _RD_NEEDS_HUMAN, + ACTION_NOOP as _RD_NOOP, + STATUS_RUNNING as _RD_STATUS_RUNNING, + STATUS_NEEDS_HUMAN as _RD_STATUS_NEEDS_HUMAN, + STATUS_COMPLETED as _RD_STATUS_COMPLETED, + STATUS_FAILED as _RD_STATUS_FAILED, + ) + retry_decision = decide_retry_action_only(notice, scope='task') + except Exception: # noqa: BLE001 + retry_decision = None + rd_action = str((retry_decision or {}).get('action') or '').strip() or None + rd_status = str((retry_decision or {}).get('status') or '').strip() or None + rd_retryable = bool((retry_decision or {}).get('retryable')) + rd_reason_code = str((retry_decision or {}).get('reason_code') or '').strip() or None + + # ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) ===== + notice_process_status = None + if notice is not None: + notice_process_status = str(getattr(notice, 'process_status', None) or '').strip().lower() or None + _rd_has_completed_process = bool( + notice is not None + and notice_process_status in {'completed', 'fulfilled', 'closed'} + ) + + def _compute_user_status() -> str: + # 1) 终态短路:old_status completed/cancelled/failed + if old_status == 'completed': + return 'completed' + if old_status == 'cancelled': + return 'cancelled' + if old_status == 'failed': + return 'failed' + # Retry Decision 可得时:优先用决策器 + if retry_decision is not None: + # 4) rd_status=completed 或 action=noop 且 notice 完成态 → completed + if rd_status == _RD_STATUS_COMPLETED: + return 'completed' + if rd_action == _RD_NOOP and _rd_has_completed_process: + return 'completed' + # 5) rd_retryable=True → 'retryable'(新增!) + if rd_retryable is True: + return 'retryable' + # 6) rd_status=needs_human 或 rd_action=needs_human → waiting_human + if rd_status == _RD_STATUS_NEEDS_HUMAN or rd_action == _RD_NEEDS_HUMAN: + return 'waiting_human' + # 7) legacy waiting_human 兜底(保留旧逻辑) + if old_status in {'waiting_review', 'waiting_inventory_source_review', 'waiting_shortage_review'}: + return 'waiting_human' + if pending_reason in { + PROCESS_HUMAN_PENDING_INVENTORY_SOURCE, + PROCESS_HUMAN_PENDING_SHORTAGE, + _PROCESS_HUMAN_PENDING_MATCH, + } or review_status_raw in {REVIEW_STATUS_SHORTAGE_REVIEW}: + return 'waiting_human' + # 8) rd_status=running 或旧 running 族 → running + if retry_decision is not None and rd_status == _RD_STATUS_RUNNING: + return 'running' + if old_status in {'processing', 'queued', 'running'}: + return 'running' + # 9) 兜底 + return 'running' + + user_status = _compute_user_status() + + # ===== [不变] user_stage 计算(保持不动) ===== + user_stage = _USER_STAGE_TO_CODE.get(old_stage) + if user_stage is None: + if old_stage in {'document_parsing', 'order_creating'}: + user_stage = 'document_parsing' + elif old_stage in {'inventory_fetching'}: + user_stage = 'inventory_fetch' + elif old_stage in {'inventory_matching'}: + user_stage = 'inventory_match' + elif old_stage in {'excel_generating'}: + user_stage = 'excel_generate' + elif old_stage in {'freight_uploading'}: + user_stage = 'freight_upload' + else: + user_stage = 'document_parsing' + + # ===== [不变] user_current_gate_code 计算(保持不动) ===== + old_gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None + user_current_gate_code: str | None = None + if isinstance(old_gate, dict): + user_current_gate_code = str(old_gate.get('code') or old_gate.get('gate_code') or '').strip() or None + + # ===== [STEP 5] 计算 retryable(布尔) ===== + def _compute_retryable() -> bool: + if user_status in {'completed', 'cancelled'}: + return False + if user_status == 'retryable': + return True + if user_status == 'failed' and rd_retryable: + return True + return False + + retryable = _compute_retryable() + + # ===== [STEP 6] 计算 blocking_reason: {code, i18n_key, details} 或 None ===== + _REASON_TO_I18N_KEY: dict[str, str] = { + 'inventory_source_unstable': 'workspace.shippingNotice.processGate.reasons.require_manual_review', + 'inventory_snapshot_missing': 'workspace.shippingNotice.processGate.reasons.inventory_file_missing', + 'inventory_match_incomplete': 'workspace.shippingNotice.processGate.reasons.inventory_match_failed', + 'inventory_source_candidates_need_human': 'workspace.shippingNotice.processGate.reasons.require_manual_review', + 'upload_rpa_failed': 'workspace.shippingNotice.processGate.reasons.upload_rpa_failed', + 'inventory_shortage': 'workspace.shippingNotice.processGate.reasons.inventory_insufficient', + 'inventory_source_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_source_conflicted', + 'inventory_source_unresolved': 'workspace.shippingNotice.processGate.reasons.require_manual_review', + 'inventory_multi_file_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_multi_file_conflict', + 'order_review_required': 'workspace.shippingNotice.processGate.reasons.freeze_not_ready', + 'duplicate_decision_required': 'chat.shippingProcessing.reasonCode.duplicateDecisionRequired', + 'SHIPPING.NOTICE_EXACT_DUPLICATE': 'chat.shippingProcessing.reasonCode.exactDuplicateNotice', + 'SHIPPING.STP_NOT_ELIGIBLE': 'chat.shippingProcessing.reasonCode.stpNotEligible', + 'SHIPPING.REVIEW_DRAFT_MISSING': 'chat.shippingProcessing.reasonCode.reviewDraftMissing', + 'SHIPPING.REVIEW_RUN_MISSING': 'chat.shippingProcessing.reasonCode.reviewRunMissing', + 'SHIPPING.REVIEW_DOCUMENT_INVALID': 'chat.shippingProcessing.reasonCode.reviewDocumentInvalid', + 'SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT': 'chat.shippingProcessing.reasonCode.reviewDraftVersionConflict', + 'profile_schema_mismatch': 'chat.shippingProcessing.reasonCode.profileSchemaMismatch', + 'final_required_field_missing': 'chat.shippingProcessing.reasonCode.finalRequiredFieldMissing', + } + _PROCESS_FAILED_I18N = 'workspace.shippingNotice.processGate.reasons.unknown_business_failure' + + def _legacy_waiting_human_blocking_reason() -> dict[str, Any] | None: + if pending_reason == PROCESS_HUMAN_PENDING_INVENTORY_SOURCE or inventory_source_status_raw in {_INVENTORY_SOURCE_STATUS_UNRESOLVED}: + return { + 'code': 'inventory_source_unresolved', + 'i18n_key': _REASON_TO_I18N_KEY['inventory_source_unresolved'], + 'details': {}, + } + if pending_reason == PROCESS_HUMAN_PENDING_SHORTAGE or review_status_raw in {REVIEW_STATUS_SHORTAGE_REVIEW}: + return { + 'code': 'inventory_shortage', + 'i18n_key': _REASON_TO_I18N_KEY['inventory_shortage'], + 'details': {}, + } + if pending_reason == _PROCESS_HUMAN_PENDING_MATCH: + return { + 'code': 'inventory_multi_file_conflict', + 'i18n_key': _REASON_TO_I18N_KEY['inventory_multi_file_conflict'], + 'details': {}, + } + if old_status == 'waiting_review': + return { + 'code': 'order_review_required', + 'i18n_key': _REASON_TO_I18N_KEY['order_review_required'], + 'details': {}, + } + return None + + def _compute_blocking_reason() -> dict[str, Any] | None: + # 1) completed / cancelled / running → 无阻断 + if user_status in {'completed', 'cancelled', 'running'}: + return None + # 2) waiting_human + if user_status == 'waiting_human': + if retry_decision is not None and rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY: + return { + 'code': rd_reason_code, + 'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code], + 'details': {}, + } + return _legacy_waiting_human_blocking_reason() + # 3) retryable + if user_status == 'retryable': + if rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY: + return { + 'code': rd_reason_code, + 'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code], + 'details': {}, + } + return { + 'code': 'retry_needed', + 'i18n_key': 'workspace.shippingNotice.processGate.reasons.technical_retry_exhausted', + 'details': {}, + } + # 4) failed + if user_status == 'failed': + if rd_retryable and rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY: + return { + 'code': rd_reason_code, + 'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code], + 'details': {}, + } + return { + 'code': 'process_failed_terminal', + 'i18n_key': _PROCESS_FAILED_I18N, + 'details': {'legacy_status': old_status, 'legacy_stage': old_stage}, + } + return None + + blocking_reason = _compute_blocking_reason() + + # ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None ===== + _ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = { + 'retry': 'workspace.shippingNotice.processGate.actionCodes.retry_with_latest_rules', + 'open_inventory_source_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_source_review', + 'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review', + 'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review', + 'retry_freight_upload_rpa': 'workspace.shippingNotice.processGate.actionCodes.retry_freight_upload_rpa', + 'adjudicate_duplicate': 'workspace.shippingNotice.processGate.actionCodes.adjudicate_duplicate', + 'reconcile_and_progress': 'workspace.shippingNotice.processGate.actionCodes.reconcile_and_progress', + 'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review', + } + _ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = { + 'retry': 'chat.shippingProcessing.action.retry', + 'open_inventory_source_review': 'chat.shippingProcessing.action.open_inventory_source_review', + 'open_inventory_match_review': 'chat.shippingProcessing.action.open_inventory_match_review', + 'open_order_review': 'chat.shippingProcessing.action.open_order_review', + 'retry_freight_upload_rpa': 'chat.shippingProcessing.action.retry_freight_upload_rpa', + 'match_inventory': 'chat.shippingProcessing.action.match_inventory', + 'regenerate_excel': 'chat.shippingProcessing.action.regenerate_excel', + 'download_excel': 'chat.shippingProcessing.action.download_excel', + 'adjudicate_duplicate': 'chat.shippingProcessing.action.adjudicate_duplicate', + 'reconcile_and_progress': 'chat.shippingProcessing.action.reconcile_and_progress', + 'open_profile_review': 'chat.shippingProcessing.action.open_profile_review', + } + + def _resolve_action_i18n_key(action_code: str) -> str: + gate_key = _ACTION_CODE_TO_GATE_I18N_KEY.get(action_code) + if gate_key: + return gate_key + fallback = _ACTION_CODE_TO_CHAT_I18N_FALLBACK.get(action_code) + return fallback or f'chat.shippingProcessing.action.{action_code}' + + def _legacy_waiting_human_primary_action(bcode: str) -> dict[str, Any] | None: + if bcode == 'inventory_source_unresolved': + code = 'open_inventory_source_review' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + if bcode in {'inventory_shortage', 'inventory_multi_file_conflict'}: + code = 'open_inventory_match_review' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + if bcode == 'order_review_required': + code = 'open_order_review' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + return None + + def _compute_primary_action() -> dict[str, Any] | None: + # 1) blocking_reason 非 None + if blocking_reason is not None: + bcode = str(blocking_reason.get('code') or '').strip() + # 1a. retryable 或 failed+retryable → 统一 retry 动作 + if user_status == 'retryable' or (user_status == 'failed' and retryable is True): + code = 'retry' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + # 1b ~ 1h: waiting_human 按 code 分派 + if user_status == 'waiting_human': + if bcode in {'inventory_source_unresolved', 'inventory_source_unstable', 'inventory_source_candidates_need_human'}: + code = 'open_inventory_source_review' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + if bcode in {'inventory_shortage', 'inventory_multi_file_conflict', 'inventory_source_conflict'}: + code = 'open_inventory_match_review' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + if bcode in {'order_review_required', 'freeze_not_ready'}: + code = 'open_order_review' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + if bcode == 'upload_rpa_failed': + code = 'retry_freight_upload_rpa' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + # 1e. 重复冲突 → adjudicate_duplicate + if bcode in {'duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'}: + code = 'adjudicate_duplicate' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + # 1f. profile/XFA 治理失败 → open_profile_review + if bcode == 'profile_schema_mismatch' or (bool(bcode) and bcode.startswith('SHIPPING.XFA_')): + code = 'open_profile_review' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + # 1g. STP/Review 资格问题 → open_order_review + if bcode in { + 'SHIPPING.STP_NOT_ELIGIBLE', + 'SHIPPING.REVIEW_DRAFT_MISSING', + 'SHIPPING.REVIEW_RUN_MISSING', + 'SHIPPING.REVIEW_DOCUMENT_INVALID', + 'SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT', + 'final_required_field_missing', + }: + code = 'open_order_review' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + # 1h. available_actions 含 reconcile_and_progress → 统一对账恢复入口兜底 + if isinstance(available_actions, list) and 'reconcile_and_progress' in available_actions: + code = 'reconcile_and_progress' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + # 1i. 其它 unknown:legacy 兜底 + legacy_pa = _legacy_waiting_human_primary_action(bcode) + if legacy_pa is not None: + return legacy_pa + # 2) completed → download_excel(保持 legacy) + if user_status == 'completed': + code = 'download_excel' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + # 3) running 且 stage 匹配 → match_inventory / regenerate_excel(保持 legacy) + if user_status == 'running' and user_stage == 'inventory_match': + code = 'match_inventory' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + if user_status == 'running' and user_stage == 'excel_generate': + code = 'regenerate_excel' + return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} + # 4) 兜底 None + return None + + primary_action = _compute_primary_action() + + # ===== [不变] facts 子事实计算(保持不动) ===== + facts: dict[str, Any] = { + 'inventory_source_status': inventory_source_status_raw or 'unresolved', + 'candidate_source_codes': [], + 'prepared_source_codes': [], + 'pending_source_codes': [], + 'line_resolutions': [], + 'export_state': 'not_created', + 'upload_state': 'not_created', + 'switch_state': 'not_triggered', + } + if order_task is not None: + cand = getattr(order_task, 'candidate_source_codes_json', None) + if isinstance(cand, list): + facts['candidate_source_codes'] = [str(c or '').strip().upper() for c in cand if str(c or '').strip()] + if notice is not None: + step_payload = getattr(notice, 'step_payload_json', None) + if isinstance(step_payload, dict): + prep = step_payload.get('candidate_inventory_prep') + if isinstance(prep, dict): + facts['prepared_source_codes'] = list(prep.get('loaded_source_codes') or []) + facts['pending_source_codes'] = list(prep.get('missing_source_codes') or []) + resolutions = step_payload.get('line_inventory_resolutions') + if isinstance(resolutions, list): + facts['line_resolutions'] = resolutions[:] + fms = step_payload.get('forced_match_source_code') + if fms: + facts['forced_match_source_code'] = str(fms).strip().upper() + # P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。 + try: + from app.models import ShippingTaskInventoryRpaAttempt + attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(notice, 'task_no', '') or '')).all() + facts['rpa_attempts'] = [{ + 'source_code': a.source_code, 'attempt_no': a.attempt_no, + 'source_run_no': a.source_run_no, 'status': a.status, + 'execution_phase': a.execution_phase, 'file_generated': bool(a.file_generated), + 'file_exists_at_callback': a.file_exists_at_callback, + 'callback_received_at': a.callback_received_at.isoformat() if a.callback_received_at else None, + 'error_code': a.error_code, 'transaction_error_code': a.transaction_error_code, + } for a in attempts] + except Exception: + facts['rpa_attempts'] = [] + if getattr(notice, 'export_artifact_id', None): + facts['export_state'] = 'created' + if getattr(notice, 'upload_status', None): + us = str(getattr(notice, 'upload_status') or '').strip().lower() + facts['upload_state'] = us if us else 'not_created' + if getattr(notice, 'wecom_sent_at', None): + facts['switch_state'] = 'sent' + + payload['user_status'] = user_status + payload['user_stage'] = user_stage + payload['user_current_gate_code'] = user_current_gate_code + payload['blocking_reason'] = blocking_reason + payload['retryable'] = bool(retryable) + payload['primary_action'] = primary_action + payload['facts'] = facts + + # [DUPLICATE-GUARD-2] 第二道(shipping-processing 侧):available_actions 剔除 — + # duplicate_decision_required / NOTICE_EXACT_DUPLICATE 强制移除 retry_*, + # 并把 reconcile_and_progress 顶到首位,避免两端投影不一致 + if isinstance(blocking_reason, dict): + _dup_br_code = str(blocking_reason.get('code') or '').strip() + if _dup_br_code in {'duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'}: + from app.services.shipping_notice.recovery_contract import ( + should_general_retry_be_removed as _fg_should_remove, + ) + if _fg_should_remove( + retryable_flag=bool(retryable), + blocking_reason=blocking_reason, + ): + _raw_actions = payload.get('available_actions') + if isinstance(_raw_actions, list) and _raw_actions: + _dup_remove = {'retry_stp_auto_create', 'retry_auto_progress', 'retry'} + _filtered = [a for a in _raw_actions if a not in _dup_remove] + if 'reconcile_and_progress' in _filtered: + _rest = [a for a in _filtered if a != 'reconcile_and_progress'] + payload['available_actions'] = ['reconcile_and_progress', *_rest] + else: + payload['available_actions'] = _filtered + + return payload diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index a8bb2025..f4ba07c4 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -1,13 +1,12 @@ """ services/shipping_notice/progress_workflow.py -用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。 +用途:承接发货通知任务的自动推进提交,包括解析确认检查、正式库存准备与履约侧串联。 依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、 state_machine(CheckpointKind)、tool_response、process_gate_bridge。 -逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;按 checkpoint_kind 早停或继续; - must_human / complete 早停;wait_manual_upload 在 AUTO_UPLOAD=true 时落入履约链触发 RPA, - 关闭时才停人工上传;禁止平行编排语义;退出前同步 Process Gate; - 系统触发时事件 actor_id=None;workspace_api 须注入 operator_id 并写统一审计。 +逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;P0-3 起正式入口只提交 + 当前最早未通过 Gate,Worker 负责单 Gate 执行与下一 Job 的事务性入队;历史私有实现暂保留 + 供兼容调用方,但不得再由本 facade 直接跨 Gate 调度。 """ from __future__ import annotations @@ -18,6 +17,7 @@ from flask import current_app from app.services.shipping_notice import fulfillment_workflow from app import db +from app.models.shipping_process_gate import ShippingProcessGateAttempt from app.services.shipping_notice.constants import ( CP_INVENTORY_SOURCE_REVIEW, PH_INVENTORY_SOURCE_UNRESOLVED, @@ -30,7 +30,7 @@ from app.services.shipping_notice.inventory_source_gate import ( is_inventory_source_stable, ensure_inventory_source_review_state, ) -from app.services.shipping_notice.inventory_workflow import ensure_inventory +from app.services.shipping_notice.inventory_workflow import ensure_inventory as _legacy_ensure_inventory from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event @@ -38,6 +38,323 @@ from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response +# --------------------------------------------------------------------------- +# T5: 唯一 AutoProgress Orchestrator 入口 facade +# --------------------------------------------------------------------------- +# 所有自动推进入口(/tools/auto_progress、/tools/ensure_inventory、/tools/match_inventory、 +# batch_orchestrator、task_retry_decision)必须收口到本函数: +# +# run_task_auto_progress(task_no, trigger, expected_version=None, +# idempotency_key=None, resume_gate_code=None) -> dict +# +# 并发保护三层: +# [1] 乐观锁 progress_version CAS(避免同任务并发写独立字段冲突) +# [2] ShippingProcessGateAttempt 活动唯一性(同任务同一时刻只允许 1 个 queued/running Attempt) +# [3] idempotency_key 响应缓存(可选,短时间内重复 POST 直接返回上次结果) +# --------------------------------------------------------------------------- + +_RESUME_GATE_CODE_LEGACY_ENTRY = { + # inventory_preparation → 调 inventory_workflow.ensure_inventory 逻辑(复用旧实现) + 'inventory_preparation': 'ensure_inventory', + # inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key) + 'inventory_matching': 'match_inventory', + # None 或 'auto' → 走完整 auto_progress 串联链(解析→库存→匹配→导出→上传) + 'auto': 'auto_progress_full', + None: 'auto_progress_full', + '': 'auto_progress_full', +} + + +def _try_cas_progress_version(task: Any, expected_version: int | None) -> tuple[bool, int]: + """ + CAS 更新 task.progress_version:expected_version==None 则强制自增(调用方保证单线程); + 否则要求 DB 当前值 == expected_version 才自增;返回 (是否成功, 新 version)。 + """ + sess = db.session + current = int(getattr(task, 'progress_version', 0) or 0) + if expected_version is not None and int(expected_version) != current: + return False, current + new_version = current + 1 + try: + # 优先用原生 UPDATE ... WHERE 原子 CAS(若列不存在则安全降级到内存赋值 + flush) + if hasattr(task, 'progress_version') and task.id is not None: + model_cls = type(task) + affected = ( + sess.query(model_cls) + .filter(model_cls.id == task.id) + .filter( + (model_cls.progress_version == expected_version) + if expected_version is not None + else True + ) + .update({'progress_version': new_version}, synchronize_session='evaluate') + ) + if not affected: + return False, int(getattr(task, 'progress_version', 0) or 0) + task.progress_version = new_version + return True, new_version + except Exception: + pass + task.progress_version = new_version + return True, new_version + + +def _has_active_gate_attempts(task: Any) -> list[ShippingProcessGateAttempt]: + """查询 Task 关联的当前活动 Gate Attempt(queued / running)——用于唯一性断言。""" + task_id = getattr(task, 'id', None) + if task_id is None: + return [] + try: + return list( + db.session.query(ShippingProcessGateAttempt) + .filter( + ShippingProcessGateAttempt.task_id == task_id, + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ) + .all() + ) + except Exception: + return [] + + +def _dispatch_legacy_orchestration( + task: Any, + *, + resume_gate_code: str | None, + trigger: str, + operator_id: int | None, + inventory_mode: str = 'auto', + line_scope_key: str | None = None, +) -> dict[str, Any]: + """ + resume_gate_code → 旧实现分派(短期复用稳定实现,后续逐步把每个 Gate 原子步骤迁入本 facade)。 + 长期目标:每个 Gate 只在本函数内跑原子 run_one_gate_step();旧实现会逐步下线。 + """ + entry = _RESUME_GATE_CODE_LEGACY_ENTRY.get(resume_gate_code, 'auto_progress_full') + base_payload: dict[str, Any] = { + 'task_no': str(task.task_no or '').strip(), + 'task_id': getattr(task, 'id', None), + 'trigger': trigger, + 'operator_id': operator_id, + 'resume_gate_code': resume_gate_code, + 'mode': inventory_mode, + } + if entry == 'ensure_inventory': + # [T4 集成] 库存准备:如果存在 per-source 候选冻结,优先走 per_source_rpa_service 逐源准备 + from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared + from app.services.shipping_notice.stp_inventory_freeze import ( + task_frozen_inventory_source_codes, + ) + frozen_sources = task_frozen_inventory_source_codes(task) + if frozen_sources and len(frozen_sources) >= 1: + prepare_result = ensure_all_required_sources_prepared(task, mode=inventory_mode) + if prepare_result.all_prepared: + return _legacy_ensure_inventory({**base_payload, '_prepared_sources': prepare_result.prepared_source_codes, '_orchestrator_internal_dispatch': True}) + return tool_response( + status='running' if prepare_result.pending_source_codes else ( + 'failed' if prepare_result.failed_source_codes and not prepare_result.prepared_source_codes else 'needs_human' + ), + task=task, + message=( + f"库存准备中({len(prepare_result.prepared_source_codes)}/{len(frozen_sources)} 已就绪;" + f"等待 {len(prepare_result.pending_source_codes)} 源;失败 {len(prepare_result.failed_source_codes)} 源)。" + ), + data={ + **serialize_task_for_tool(task), + 'per_source_inventory_preparation': { + 'prepared': prepare_result.prepared_source_codes, + 'pending': prepare_result.pending_source_codes, + 'failed': prepare_result.failed_source_codes, + 'source_attempts': prepare_result.source_attempts, + }, + }, + ) + return _legacy_ensure_inventory({**base_payload, '_orchestrator_internal_dispatch': True}) + if entry == 'match_inventory': + norm_line_scope = str(line_scope_key or '').strip() + if norm_line_scope: + return fulfillment_workflow.match_inventory_line( + {**base_payload, '_orchestrator_internal_dispatch': True}, + line_key=norm_line_scope, + ) + return fulfillment_workflow.match_inventory({**base_payload, '_orchestrator_internal_dispatch': True}) + return _auto_progress_full(task, base_payload, trigger=trigger, operator_id=operator_id) + + +def _auto_progress_full( + task: Any, + base_payload: dict[str, Any], + *, + trigger: str, + operator_id: int | None, +) -> dict[str, Any]: + """完整 auto_progress 串联——复用下方既有 auto_progress 主逻辑但避免函数递归。""" + from app.services.shipping_notice.progress_workflow import auto_progress as _public_auto_progress + # 短期:直接调用下方 auto_progress 原实现(payload 包装);后续把完整步骤迁移到 Orchestrator 原子循环 + return _public_auto_progress({ + **base_payload, + 'source': trigger, + 'operator_id': operator_id, + '_skip_orchestrator_wrapper': True, + }) + + +def run_task_auto_progress( + task_no: str, + *, + trigger: str, + expected_version: int | None = None, + idempotency_key: str | None = None, + resume_gate_code: str | None = None, + operator_id: int | None = None, + inventory_mode: str = 'auto', + line_scope_key: str | None = None, +) -> dict[str, Any]: + """ + 唯一 AutoProgress Orchestrator Facade。 + 【AI 触发时机】:所有需要推进发货任务状态的入口(Tool API、Batch Orchestrator、Retry Decision、 + Gate Handler post-action)均应调用本函数;禁止直接调 inventory_workflow.ensure_inventory + 或 fulfillment_workflow.match_inventory 绕过并发锁。 + + 核心步骤: + [STEP 0] 解析 task_no → 读取 Task;乐观锁 CAS progress_version(防止并发写冲突) + [STEP 1] 任务级活动 Attempt 唯一性断言:存在 queued/running Gate Attempt → 返回已在处理(noop) + [STEP 2] 按 resume_gate_code 分派原子步骤执行(短期复用旧实现,长期迁入本函数) + [STEP 3] 同步 Process Gate 投影、持久化 commit + [STEP 4] 触发 SSE 刷新信号(发送 task_no → 前端轮询 Projection 拉取新状态) + + Args: + task_no: 发货任务 task_no。 + trigger: 触发来源字符串(batch_orchestrator / tool_api_ensure / retry_decision / ...),用于审计。 + expected_version: 可选乐观锁预期 progress_version;不匹配返回 early_return conflict。 + idempotency_key: 可选短时间幂等键(当前版本写入 TaskEvent,后续可接 Redis 缓存)。 + resume_gate_code: 从指定 Gate 恢复;None 表示从当前阶段自动推进。 + operator_id: 操作人 ID(系统触发则 None)。 + inventory_mode: 库存准备模式;用户显式重试传 retry_rpa,自动推进保持 auto。 + line_scope_key: 行级 scope 键;传了则仅对该行执行(例如 match_inventory_line),不传则整单推进。 + + Returns: + Tool 标准响应(status=running/needs_human/failed/completed + task + data); + 并发冲突时返回 {'success': False, 'status': 'conflict', 'current_progress_version': int}。 + """ + if not auto_progress_enabled(): + return tool_response(status="failed", message="auto_progress 未启用") + + # 说明:query_service 没有 get_task_by_task_no,统一用 resolve_task_from_payload。 + # 保留分支:如果将来对同一 task_no 需要权限过滤,应改为 get_task_for_user(task_no, operator_id)。 + task = resolve_task_from_payload({'task_no': task_no}) if task_no else None + if not task: + return tool_response(status="failed", message=f"未找到任务编号 {task_no}") + + # P0-3:旧 facade 不再直接跨 Gate 调用库存/匹配/Excel。所有触发统一只提交 + # 当前正式 Gate;Worker 在事实落库后才创建下一个 Job。 + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + submitted = submit_auto_progress( + task=task, trigger=trigger, operator_id=operator_id, + resume_gate_code=resume_gate_code, commit=True, + ) + status = str(submitted.get('status') or 'queued') + if status == 'queued': + return tool_response(status='running', task=task, message='已提交当前自动推进 Gate。', data=submitted) + if status in {'waiting_human', 'blocked_manual', 'blocked_retryable'}: + return tool_response(status='needs_human', task=task, message='当前 Gate 需要人工处理。', data=submitted) + if status == 'cancelled': + return tool_response(status='failed', task=task, message='任务已取消,不能继续自动推进。', data=submitted) + return tool_response(status='completed', task=task, message='自动推进已无待处理 Gate。', data=submitted) + + # [STEP 0] 乐观锁 CAS + cas_ok, new_version = _try_cas_progress_version(task, expected_version) + if not cas_ok: + return { + 'success': False, + 'status': 'conflict', + 'task_no': task_no, + 'current_progress_version': new_version, + 'retry_safe': True, + } + + # [STEP 1] 活动 Attempt 唯一性 + active_attempts = _has_active_gate_attempts(task) + if active_attempts: + # 已有 queued/running Attempt → 直接返回 noop,避免重复排队 + return tool_response( + status='running', + task=task, + message=f'任务推进中(已有 {len(active_attempts)} 个活动 Gate Attempt,未重复触发)。', + data={ + **serialize_task_for_tool(task), + 'orchestrator': { + 'active_attempt_count': len(active_attempts), + 'noop_reason': 'active_gate_attempt_exists', + 'progress_version': new_version, + }, + }, + ) + + # [STEP 2] 分派原子步骤 + log_task_event( + task, + 'orchestrator_run_started', + { + 'trigger': trigger, + 'resume_gate_code': resume_gate_code, + 'idempotency_key': idempotency_key, + 'progress_version_before': new_version - 1 if new_version else 0, + 'progress_version_after': new_version, + 'line_scope_key': line_scope_key, + }, + actor_id=operator_id, + source=trigger, + ) + try: + result = _dispatch_legacy_orchestration( + task, resume_gate_code=resume_gate_code, + trigger=trigger, operator_id=operator_id, + inventory_mode=inventory_mode, + line_scope_key=line_scope_key, + ) + except Exception as exc: # pragma: no cover - 顶层兜底避免 Worker 吞异常 + db.session.rollback() + err = f'{type(exc).__name__}: {str(exc)[:500]}' + log_task_event( + task, 'orchestrator_run_failed', + {'error': err, 'trigger': trigger, 'resume_gate_code': resume_gate_code}, + actor_id=operator_id, source=trigger, + ) + return tool_response(status='failed', message=f'Orchestrator 执行异常:{err}', data={'progress_version': new_version}) + + # [STEP 3] 持久化 + 同步 Process Gate 投影 + try: + db.session.commit() + except Exception as exc: # pragma: no cover - DB 层兜底 + db.session.rollback() + return tool_response(status='failed', message=f'Orchestrator commit 失败:{type(exc).__name__}: {str(exc)[:300]}') + + # [STEP 4] 触发 SSE 刷新信号(通过 events 写入,前端轮询 ShippingProcessingProjection 拉取事实) + try: + _sync_process_gates_after_progress(task, {'progress_version': new_version, 'trigger': trigger}) + except Exception: + pass + log_task_event( + task, 'orchestrator_run_finished', + { + 'trigger': trigger, + 'resume_gate_code': resume_gate_code, + 'progress_version': new_version, + 'result_status': result.get('status') if isinstance(result, dict) else None, + 'line_scope_key': line_scope_key, + }, + actor_id=operator_id, source=trigger, + ) + if isinstance(result, dict): + result.setdefault('data', {}) + if isinstance(result['data'], dict): + result['data']['progress_version'] = new_version + result['data']['orchestrator_trigger'] = trigger + result['data']['sse_refresh_hint'] = True + return result + + def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: """ 按任务当前状态自动串联解析确认、正式库存准备与履约动作。 @@ -54,6 +371,34 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: Returns: dict[str, Any]: Tool 标准响应,返回自动推进后的阶段、提示和数据。 """ + # [T5 Orchestrator 守卫]:外部入口直接收口到 run_task_auto_progress(统一乐观锁+唯一性断言); + # _skip_orchestrator_wrapper=True 才进入下方完整实现(由 _auto_progress_full 内部调用,避免递归死循环)。 + if not payload.get('_skip_orchestrator_wrapper', False): + task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip() + if not task_no and isinstance(payload, dict): + from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp + _t = _rtp(payload) + task_no = str(getattr(_t, 'task_no', '') or '').strip() + trigger = str(payload.get('source') or payload.get('trigger') or 'legacy_auto_progress_entry').strip() + ev = payload.get('expected_version') + try: + expected_version = int(ev) if ev is not None and str(ev).strip() else None + except (TypeError, ValueError): + expected_version = None + idempotency_key = str(payload.get('idempotency_key') or '').strip() or None + actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id") + try: + operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None + except (TypeError, ValueError): + operator_id = None + return run_task_auto_progress( + task_no, trigger=trigger, + expected_version=expected_version, + idempotency_key=idempotency_key, + resume_gate_code=None, + operator_id=operator_id, + ) + # 下方:_auto_progress_full 内部调用路径(直接执行完整串联,不再走 Orchestrator 外层) if not auto_progress_enabled(): return tool_response(status="failed", message="auto_progress 未启用") diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 9b40c956..586c4a64 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -229,6 +229,7 @@ def claim_next_shipping_notice_job() -> Job | None: JobType.SHIPPING_ORDER_EXTRACTION, JobType.SHIPPING_DOCUMENT_LAYOUT, JobType.SHIPPING_PROCESS_GATE, + JobType.SHIPPING_AUTO_PROGRESS, JobType.SHIPPING_XFA_OCR_AUTOMARK, JobType.SHIPPING_STP_AUTO_CREATE, JobType.SHIPPING_LINE_AUTO_FULFILL, diff --git a/backend/app/services/shipping_notice/reconcile_queries.py b/backend/app/services/shipping_notice/reconcile_queries.py new file mode 100644 index 00000000..3067abc0 --- /dev/null +++ b/backend/app/services/shipping_notice/reconcile_queries.py @@ -0,0 +1,580 @@ +""" +backend/app/services/shipping_notice/reconcile_queries.py + +用途:Phase 2 对账只读查询层 — 按 Q1 五级 L1-L3 归属链判断 Case → Task 的绑定关系。 +依赖:models.ShippingOrderReviewCase / ShippingOrderCandidate / ShippingOrderDocument + / ShippingNotice(=OrderTask)、business_fingerprint.build_business_fingerprint、 + duplicate_detection.classify_task_lifecycle、recovery_contract(类型契约)。 +逻辑:由 reconciliation_service.reconcile_existing_task() 调用;全部为只读查询, + 不做任何 DB 写入;返回统一 ReconcileMatchResult 结构(match_level / task_no / + confidence / evidence)。严禁凭字段名推断,必须真实 JOIN 关系表。 +注意:business_numbering_service._customer_code_from_summary 不在顶层 import(该函数 + 已从编号服务移除),调用处做 try 延迟 import,失败兜底空字符串。 +""" + +from __future__ import annotations + +from typing import Any + +from app import db +from app.models import ( + FileAsset, + ShippingNotice, + ShippingOrderCandidate, + ShippingOrderDocument, + ShippingOrderIntake, + ShippingOrderProcessingUnit, + ShippingOrderReviewCase, +) +from app.services.shipping_notice.business_fingerprint import ( + FINGERPRINT_VERSION, + build_business_fingerprint, +) +from app.services.shipping_notice.duplicate_detection import classify_task_lifecycle +from app.services.shipping_notice.recovery_contract import ( + ReconcileConfidence, + ReconcileMatchEvidence, + ReconcileMatchLevel, + ReconcileMatchResult, +) + + +# ============================================================ +# 公共辅助:统一生成「无匹配」结果 +# ============================================================ + +def _no_match(*, reason: str, case_no: str) -> ReconcileMatchResult: + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.NONE, + task_no=None, + confidence=ReconcileConfidence.NONE, + evidence=ReconcileMatchEvidence( + case_no=case_no, + match_level_steps=[{'step': 'L0-none', 'passed': False, 'reason': reason}], + ), + ) + + +# ============================================================ +# L1:Case 显式绑定(最高优先级,最快路径) +# ============================================================ + +def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMatchResult | None: + """ + L1:Case.confirmed_task_id → 直接查 ShippingNotice 拿到 task_no。 + 【AI 触发时机】:对账入口必须先执行本步骤,避免 L2/L3 瞎匹配覆盖掉人工确认的绑定。 + """ + steps: list[dict[str, Any]] = [] + case_no = str(case.case_no) + + # 1a. confirmed_task_id 有值且指向存在的 Task + task_id = getattr(case, 'confirmed_task_id', None) + if task_id is not None: + task = db.session.get(ShippingNotice, int(task_id)) + if task is not None and task.task_no: + steps.append({'step': 'L1a-confirmed_task_id', 'passed': True, + 'evidence': {'task_id': int(task_id), 'task_no': str(task.task_no)}}) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L1, + task_no=str(task.task_no), + confidence=ReconcileConfidence.CERTAIN, + evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps, + confirmed_task_id=int(task_id), + lifecycle=classify_task_lifecycle(task.process_status)), + ) + steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, + 'reason': 'confirmed_task_id 指向的 ShippingNotice 不存在或无 task_no', + 'evidence': {'task_id': int(task_id)}}) + else: + steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, 'reason': 'confirmed_task_id is None'}) + + # 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingNotice 校验存在性 + confirmed_task_no = str(getattr(case, 'confirmed_task_no', '') or '').strip() + if confirmed_task_no: + task = ShippingNotice.query.filter_by(task_no=confirmed_task_no).first() + if task is not None: + steps.append({'step': 'L1b-confirmed_task_no', 'passed': True, + 'evidence': {'task_no': confirmed_task_no, 'task_id': int(task.id)}}) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L1, + task_no=confirmed_task_no, + confidence=ReconcileConfidence.CERTAIN, + evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps, + confirmed_task_no=confirmed_task_no, + lifecycle=classify_task_lifecycle(task.process_status)), + ) + steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, + 'reason': 'confirmed_task_no 反向查无 ShippingNotice', + 'evidence': {'task_no': confirmed_task_no}}) + else: + steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, 'reason': 'confirmed_task_no 为空'}) + + # L1 未命中,保留 steps 供上层聚合 → 返回 None 让后续 L2/L3 继续 + return None + + +# ============================================================ +# L1c / L1d / L1e:Candidate 级、Document 级(仍算 L1,因为来源明确) +# ============================================================ + +def _current_candidate_of_case(case: ShippingOrderReviewCase) -> ShippingOrderCandidate | None: + """加载 Case 的当前 Candidate(按 candidate_id → 按 document+run+is_current)。""" + if getattr(case, 'candidate_id', None): + c = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) + if c is not None: + return c + return ( + ShippingOrderCandidate.query + .filter_by( + order_extraction_run_id=int(case.run_id), + primary_document_id=int(case.document_id), + is_current_version=True, + ) + .order_by(ShippingOrderCandidate.id.desc()) + .first() + ) + + +def _step_l1cde_downstream_links( + case: ShippingOrderReviewCase, + candidate: ShippingOrderCandidate | None, +) -> ReconcileMatchResult | None: + """ + L1c: Candidate → 已有 OrderTask(Candidate.fulfilled_task_id 或 wave_lines → Task)。 + L1d: Document → ShippingNotice.source_document_id / document_id 外键。 + L1e: Candidate + Document + PO + customer_code + fingerprint 联合匹配(过渡到 L2)。 + """ + steps: list[dict[str, Any]] = [] + case_no = str(case.case_no) + + # -------- L1c:Candidate 显式关联 Task -------- + if candidate is not None: + fulfilled_task_id = getattr(candidate, 'fulfilled_task_id', None) + if fulfilled_task_id is not None: + task = db.session.get(ShippingNotice, int(fulfilled_task_id)) + if task is not None and task.task_no: + steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': True, + 'evidence': {'candidate_id': int(candidate.id), + 'task_id': int(fulfilled_task_id), + 'task_no': str(task.task_no)}}) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L1, + task_no=str(task.task_no), + confidence=ReconcileConfidence.CERTAIN, + evidence=ReconcileMatchEvidence( + case_no=case_no, match_level_steps=steps, + candidate_id=int(candidate.id), + linked_candidate_task_id=int(fulfilled_task_id), + lifecycle=classify_task_lifecycle(task.process_status), + ), + ) + steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False, + 'reason': 'Candidate 未绑定 fulfilled_task_id'}) + + # L1c-alt:通过 ShippingOrderReviewWaveLine.case_id + task_id 反查(Phase 1 已存在的关系) + from app.models import ShippingOrderReviewWaveLine + wave_task_id_rows = ( + db.session.query(ShippingOrderReviewWaveLine.task_id) + .filter(ShippingOrderReviewWaveLine.case_id == int(case.id), + ShippingOrderReviewWaveLine.task_id.isnot(None)) + .distinct() + .limit(5) + .all() + ) + wave_task_ids = [int(r.task_id) for r in wave_task_id_rows if r.task_id is not None] + if len(wave_task_ids) == 1: + task = db.session.get(ShippingNotice, wave_task_ids[0]) + if task is not None and task.task_no: + steps.append({'step': 'L1c-wave_line_task', 'passed': True, + 'evidence': {'task_id': wave_task_ids[0], 'task_no': str(task.task_no)}}) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L1, + task_no=str(task.task_no), + confidence=ReconcileConfidence.CERTAIN, + evidence=ReconcileMatchEvidence( + case_no=case_no, match_level_steps=steps, + wave_linked_task_id=wave_task_ids[0], + lifecycle=classify_task_lifecycle(task.process_status), + ), + ) + steps.append({'step': 'L1c-wave_line_task', 'passed': False, + 'reason': 'wave_line 反查 task_id 不唯一或不存在', + 'evidence': {'matched_count': len(wave_task_ids)}}) + else: + steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False, 'reason': 'Case 没有 Candidate'}) + steps.append({'step': 'L1c-wave_line_task', 'passed': False, 'reason': 'Case 没有 Candidate'}) + + # -------- L1d:Document 外键链:Unit → Intake → Notice(ShippingNotice.source_document_id / document_id)-------- + document_id = int(case.document_id) + # 路径 A:ShippingNotice.source_document_id == document_id(PDF 级直接关联) + doc_task_a = ( + ShippingNotice.query + .filter((ShippingNotice.source_document_id == document_id) | + (ShippingNotice.document_id == document_id)) + .order_by(ShippingNotice.id.desc()) + .limit(5) + .all() + ) + if len(doc_task_a) == 1: + task = doc_task_a[0] + steps.append({'step': 'L1d-document_foreign_key', 'passed': True, + 'evidence': {'document_id': document_id, 'task_no': str(task.task_no)}}) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L1, + task_no=str(task.task_no), + confidence=ReconcileConfidence.CERTAIN, + evidence=ReconcileMatchEvidence( + case_no=case_no, match_level_steps=steps, + source_document_id=document_id, + lifecycle=classify_task_lifecycle(task.process_status), + ), + ) + steps.append({'step': 'L1d-document_foreign_key', 'passed': False, + 'reason': f'Document 反查 Task {len(doc_task_a)} 个(不唯一)', + 'evidence': {'document_id': document_id, 'matched_count': len(doc_task_a)}}) + + # 路径 B:经由 ProcessingUnit → Intake.asset_id → FileAsset.id + unit = db.session.get(ShippingOrderProcessingUnit, int(case.unit_id)) if case.unit_id else None + intake: ShippingOrderIntake | None = None + if unit is not None and getattr(unit, 'intake_id', None): + intake = db.session.get(ShippingOrderIntake, int(unit.intake_id)) + asset_id = getattr(intake, 'asset_id', None) if intake is not None else None + if asset_id is not None: + # FileAsset.content_hash == ShippingNotice.source_content_hash(文件哈希级) + asset = db.session.get(FileAsset, int(asset_id)) + content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower() + if content_hash: + file_tasks = ( + ShippingNotice.query + .filter_by(user_id=int(case.owner_user_id), source_content_hash=content_hash) + .filter(ShippingNotice.process_status.notin_(['closed', 'rejected'])) + .order_by(ShippingNotice.id.desc()) + .limit(5) + .all() + ) + if len(file_tasks) == 1: + task = file_tasks[0] + steps.append({'step': 'L1d-file_hash_match', 'passed': True, + 'evidence': {'content_hash': content_hash[:16] + '…', + 'task_no': str(task.task_no)}}) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L1, + task_no=str(task.task_no), + confidence=ReconcileConfidence.PROBABLE, + evidence=ReconcileMatchEvidence( + case_no=case_no, match_level_steps=steps, + content_hash=content_hash, + lifecycle=classify_task_lifecycle(task.process_status), + ), + ) + steps.append({'step': 'L1d-file_hash_match', 'passed': False, + 'reason': f'文件哈希匹配 {len(file_tasks)} 个(不唯一)', + 'evidence': {'matched_count': len(file_tasks)}}) + else: + steps.append({'step': 'L1d-file_hash_match', 'passed': False, 'reason': 'FileAsset.content_hash 为空'}) + else: + steps.append({'step': 'L1d-file_hash_match', 'passed': False, 'reason': '无 Intake/FileAsset 链'}) + + return None + + +# ============================================================ +# L2:结构化字段联合匹配(PO + 客户码 + 指纹) +# ============================================================ + +def _extract_candidate_business_payload( + case: ShippingOrderReviewCase, + candidate: ShippingOrderCandidate | None, +) -> dict[str, Any]: + """按 Q2:PO 优先 Candidate.structured → 其次 Draft.header;客户优先 candidate/draft customer_code。""" + payload: dict[str, Any] = { + 'po_numbers': [], + 'customer_code': '', + 'customer_name': '', + 'business_fingerprint': None, + 'fingerprint_strength': 'unavailable', + 'from_candidate': False, + 'from_draft': False, + } + + # [STEP Q2-1] Candidate 结构化结果优先 + if candidate is not None: + structured = getattr(candidate, 'structured_result_json', None) + if isinstance(structured, dict): + summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {} + payload['po_numbers'] = [ + str(x).strip().upper() for x in (summary.get('po_numbers') or []) if str(x).strip() + ] or [str(summary.get('po_number') or '').strip().upper()] + payload['po_numbers'] = [x for x in payload['po_numbers'] if x] + try: + from app.services.shipping_notice.business_numbering_service import ( + _customer_code_from_summary, + ) + code = _customer_code_from_summary(summary) + except (ImportError, AttributeError): + code = '' + if not code: + code = str(summary.get('customer_code') or '').strip().upper() + if not code: + code = str(getattr(candidate, 'customer_code', '') or '').strip().upper() + payload['customer_code'] = code + payload['customer_name'] = str(summary.get('customer_name') or '').strip() + payload['from_candidate'] = True + + # Candidate 持久化指纹优先(Q2:"如果没有 Candidate 指纹,才重算") + cand_fp = getattr(candidate, 'business_fingerprint', None) + if isinstance(cand_fp, dict) and cand_fp.get('fingerprint'): + payload['business_fingerprint'] = str(cand_fp['fingerprint']) + payload['fingerprint_strength'] = str(cand_fp.get('strength') or 'unavailable') + payload['fingerprint_version'] = str(cand_fp.get('version') or FINGERPRINT_VERSION) + + # [STEP Q2-2] Draft 最终字段作兜底(Candidate 缺失时或空字段时) + draft = getattr(case, 'current_draft', None) + if draft is not None and not payload['from_candidate']: + header = draft.header_values_json if isinstance(draft.header_values_json, dict) else {} + values = header.get('values') if isinstance(header.get('values'), dict) else {} + po_val = '' + cc_val = '' + cn_val = '' + for key, item in values.items(): + if not isinstance(item, dict): + continue + k = str(key).lower() + v = str(item.get('value') or '').strip() + if 'po' in k and not po_val: + po_val = v.upper() + if ('customer' in k and 'code' in k) and not cc_val: + cc_val = v.upper() + if ('customer' in k and 'name' in k) and not cn_val: + cn_val = v + if po_val and not payload['po_numbers']: + payload['po_numbers'] = [po_val] + if cc_val and not payload['customer_code']: + payload['customer_code'] = cc_val + if cn_val and not payload['customer_name']: + payload['customer_name'] = cn_val + payload['from_draft'] = True + + # [STEP Q2-3] 指纹兜底:无 Candidate 指纹才重算(Q2 明确要求) + if payload['business_fingerprint'] is None: + fp = build_business_fingerprint({ + 'po_numbers': payload['po_numbers'], + 'customer_code': payload['customer_code'], + 'customer_name': payload['customer_name'], + }) + payload['business_fingerprint'] = str(fp.get('fingerprint') or '') + payload['fingerprint_strength'] = str(fp.get('strength') or 'unavailable') + payload['fingerprint_version'] = str(fp.get('version') or FINGERPRINT_VERSION) + payload['fingerprint_recalculated'] = True + else: + payload['fingerprint_recalculated'] = False + + return payload + + +def _step_l2_structural_match( + case: ShippingOrderReviewCase, + candidate: ShippingOrderCandidate | None, + l1_steps: list[dict[str, Any]], +) -> ReconcileMatchResult | None: + """ + L2:PO + 客户码 + Candidate 持久化指纹 联合匹配。 + 严格遵循 Q2 的「字段来源优先级」和「指纹使用顺序」。 + """ + steps = list(l1_steps) + case_no = str(case.case_no) + + payload = _extract_candidate_business_payload(case, candidate) + evidence: ReconcileMatchEvidence = ReconcileMatchEvidence( + case_no=case_no, + match_level_steps=steps, + candidate_id=int(candidate.id) if candidate is not None else None, + po_numbers=list(payload['po_numbers']), + customer_code=payload['customer_code'] or None, + business_fingerprint=payload['business_fingerprint'] or None, + fingerprint_strength=payload['fingerprint_strength'], + fingerprint_recalculated=bool(payload.get('fingerprint_recalculated')), + ) + + # L2a:同用户 + 同 business_fingerprint + 强指纹 strength + if (payload['business_fingerprint'] + and payload['fingerprint_strength'] in {'strong', 'medium'}): + same_fp_tasks = ( + ShippingNotice.query + .filter(ShippingNotice.user_id == int(case.owner_user_id), + ShippingNotice.business_fingerprint == payload['business_fingerprint']) + .filter(ShippingNotice.process_status.notin_(['closed', 'rejected'])) + .order_by(ShippingNotice.id.desc()) + .limit(5) + .all() + ) + if len(same_fp_tasks) == 1: + task = same_fp_tasks[0] + steps.append({'step': 'L2a-fingerprint_match', 'passed': True, + 'evidence': {'fingerprint_strength': payload['fingerprint_strength'], + 'recalculated': payload['fingerprint_recalculated'], + 'task_no': str(task.task_no)}}) + evidence['match_level_steps'] = steps + evidence['lifecycle'] = classify_task_lifecycle(task.process_status) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L2, + task_no=str(task.task_no), + confidence=(ReconcileConfidence.CERTAIN + if payload['fingerprint_strength'] == 'strong' + else ReconcileConfidence.PROBABLE), + evidence=evidence, + ) + steps.append({'step': 'L2a-fingerprint_match', 'passed': False, + 'reason': f'指纹匹配 {len(same_fp_tasks)} 个(不唯一)', + 'evidence': {'matched_count': len(same_fp_tasks), + 'strength': payload['fingerprint_strength']}}) + else: + steps.append({'step': 'L2a-fingerprint_match', 'passed': False, + 'reason': '指纹不可用或强度不足 strong/medium', + 'evidence': {'strength': payload['fingerprint_strength']}}) + + # L2b:同用户 + PO 精确一致 + customer_code 精确一致 + if payload['po_numbers'] and payload['customer_code']: + # ShippingNotice 头字段 JSON:查 structured_result_json.business_summary.po_numbers / customer_code + # 因 ORM 层无强列,退化为查 source_content_po_numbers 的 Candidate → Task 反向 + same_customer_tasks = ( + ShippingNotice.query + .filter_by(user_id=int(case.owner_user_id)) + .filter(ShippingNotice.customer_code == payload['customer_code'] + if hasattr(ShippingNotice, 'customer_code') else True) + .filter(ShippingNotice.process_status.notin_(['closed', 'rejected'])) + .order_by(ShippingNotice.id.desc()) + .limit(20) + .all() + ) + po_matched: list[ShippingNotice] = [] + for task in same_customer_tasks: + structured = getattr(task, 'structured_result_json', None) if hasattr(ShippingNotice, 'structured_result_json') else None + summary = structured.get('business_summary') if isinstance(structured, dict) else None + task_pos: set[str] = set() + if isinstance(summary, dict): + task_pos = {str(x).strip().upper() for x in (summary.get('po_numbers') or []) if str(x).strip()} + if not task_pos and summary.get('po_number'): + task_pos = {str(summary['po_number']).strip().upper()} + if task_pos and task_pos.intersection(set(payload['po_numbers'])): + po_matched.append(task) + if len(po_matched) == 1: + task = po_matched[0] + steps.append({'step': 'L2b-po_customer_match', 'passed': True, + 'evidence': {'customer_code': payload['customer_code'], + 'pos_matched': sorted(set(payload['po_numbers']) & + {str(x).strip().upper() for x in + ((task.structured_result_json or {}).get('business_summary') or {}).get('po_numbers') or []}), + 'task_no': str(task.task_no)}}) + evidence['match_level_steps'] = steps + evidence['lifecycle'] = classify_task_lifecycle(task.process_status) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L2, + task_no=str(task.task_no), + confidence=ReconcileConfidence.PROBABLE, + evidence=evidence, + ) + steps.append({'step': 'L2b-po_customer_match', 'passed': False, + 'reason': f'PO+客码匹配 {len(po_matched)} 个(不唯一)', + 'evidence': {'matched_count': len(po_matched)}}) + else: + steps.append({'step': 'L2b-po_customer_match', 'passed': False, + 'reason': 'PO 或 customer_code 缺失,无法联合匹配', + 'evidence': {'pos_count': len(payload['po_numbers']), + 'customer_code_empty': not bool(payload['customer_code'])}}) + + # -------- L3:仅文件哈希但多候选 / 弱指纹匹配(ambiguous,返回 L3 供人工裁决)-------- + # 在 L1d 步骤中已筛选 content_hash 但超过 1 个的情形,这里统一转为 L3 ambiguous + document_id = int(case.document_id) + doc_tasks_multi = ( + ShippingNotice.query + .filter((ShippingNotice.source_document_id == document_id) | + (ShippingNotice.document_id == document_id)) + .filter(ShippingNotice.process_status.notin_(['closed', 'rejected'])) + .order_by(ShippingNotice.id.desc()) + .limit(5) + .all() + ) + if len(doc_tasks_multi) > 1: + steps.append({'step': 'L3-multi_document_match', 'passed': True, + 'evidence': {'matched_task_nos': [t.task_no for t in doc_tasks_multi], + 'count': len(doc_tasks_multi)}}) + evidence['match_level_steps'] = steps + evidence['candidate_matches'] = [ + {'task_no': str(t.task_no), 'lifecycle': classify_task_lifecycle(t.process_status)} + for t in doc_tasks_multi + ] + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.L3, + task_no=None, + confidence=ReconcileConfidence.AMBIGUOUS, + evidence=evidence, + ) + + return None + + +# ============================================================ +# 对外总入口:5 级归属链按顺序串起来 +# ============================================================ + +def query_case_task_ownership( + case: ShippingOrderReviewCase, +) -> ReconcileMatchResult: + """ + 按 Q1 L1-L3 五级归属链,判断 Case 应归属到哪个既有的 Task。 + 【AI 触发时机】:对账恢复 / reconcile-and-progress API / 历史 Job 928/929 排错入口。 + + 核心逻辑(严格按 Q1 指定顺序,真实 DB 关系,禁止凭字段名猜): + 1. Case.confirmed_task_id → L1 CERTAIN + 2. Case.confirmed_task_no → L1 CERTAIN + 3. Candidate.fulfilled_task_id / wave_lines.task_id → L1 CERTAIN + 4. Document.source_document_id / document_id 外键 / FileAsset content_hash → L1 CERTAIN/PROBABLE + 5. Candidate/Draft PO + 客户码 + Candidate 持久化指纹 → L2 CERTAIN/PROBABLE + 6. 多 Document 匹配 / 弱指纹多候选 → L3 AMBIGUOUS + + Args: + case: 已加载的 ReviewCase(建议 SELECT FOR UPDATE 锁定后再调)。 + + Returns: + ReconcileMatchResult:统一 match_level / task_no / confidence / evidence 结构。 + """ + case_no = str(case.case_no) + + # [STEP 1] L1:显式绑定 + l1_explicit = _step_l1_case_explicit_binding(case) + if l1_explicit is not None: + return l1_explicit + # 提取 L1 前两步的 steps(failed 记录)以便 L2 证据链完整 + probe_no_match_steps: list[dict[str, Any]] = [] + probe_none = _no_match(reason='probe', case_no=case_no) + _ = probe_none + + # [STEP 2] L1cde:Candidate / Document 链 + candidate = _current_candidate_of_case(case) + l1cde = _step_l1cde_downstream_links(case, candidate) + if l1cde is not None: + return l1cde + probe_no_match_steps = list((l1cde or {}).get('evidence', {}).get('match_level_steps', []) + if isinstance(l1cde, dict) else []) + + # [STEP 3] L2:结构化字段联合 + l2 = _step_l2_structural_match(case, candidate, probe_no_match_steps) + if l2 is not None: + return l2 + + # [STEP END] NONE:无匹配 + reason_parts = [] + if candidate is None: + reason_parts.append('no candidate') + reason_parts.append('all L1/L2 steps passed=false') + final_steps = list((l2 or {}).get('evidence', {}).get('match_level_steps', []) + if isinstance(l2, dict) else probe_no_match_steps) + final_steps.append({'step': 'Lx-none', 'passed': True, 'reason': '所有 L1-L2 步骤均未命中;未达 L3 多候选阈值'}) + return ReconcileMatchResult( + match_level=ReconcileMatchLevel.NONE, + task_no=None, + confidence=ReconcileConfidence.NONE, + evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=final_steps, + candidate_id=int(candidate.id) if candidate else None), + ) diff --git a/backend/app/services/shipping_notice/reconciliation_projector.py b/backend/app/services/shipping_notice/reconciliation_projector.py new file mode 100644 index 00000000..011e2cf4 --- /dev/null +++ b/backend/app/services/shipping_notice/reconciliation_projector.py @@ -0,0 +1,1057 @@ +""" +backend/app/services/shipping_notice/reconciliation_projector.py + +用途:Phase 3 四事实共享投影器 —— 保证 Case 详情页 / shipping-processing 列表页 + / 对话任务卡 三端对同一个 Review Case 输出完全同源的 + automation / available_actions / blocking_reason / current_gate / + primary_action / user_status 六个只读事实;所有消费方必须经本模块, + 禁止 projection 端各写各的。 +依赖:order_review_projection 本地私有逻辑(投影同源复刻); + recovery_contract(阻断动作注入与 REMOVE_SET); + processing_projection_invariants(user_status 七值与 primary_action 分派)。 +逻辑: + ① project_case_automation_status(case, validation, post_confirm) + 完整复刻 order_review_projection._project_case_automation_status, + 统一 Job/Draft/正式 OT 同源输出。 + ② project_case_allowed_actions(case, automation, is_admin) + 完整复刻 order_review_projection._allowed_actions 核心路径, + 注入 reconcile_and_progress 作为统一对账恢复入口; + REMOVE_SET 白名单剔除 retry_stp_auto_create 等; + 裁决动作 derive_blocking_next_actions 一致注入。 + ③ project_case_current_gate(case, automation, available_actions) + 返回 {gate_code, next_action_code, blocking_reason_code} + 与 invariants / process_gate_projection 格式保持一致。 + ④ project_case_blocking_reason(automation) + 从 automation.reason_code / blocking_reason 拆出 {code, i18n_key, details} + 与 invariants._REASON_TO_I18N_KEY 一致映射。 + ⑤ project_case_user_status(case, automation) + 返回七值归一化 completed / cancelled / waiting_human / retryable / + failed / running / idle(与 shipping-processing user_status 同域)。 + ⑥ project_case_primary_action(user_status, blocking_reason, available_actions, user_stage) + 完整复刻 invariants._compute_primary_action 逻辑(1a~1i)。 + ⑦ 总入口 project_review_case_projection_bundle(...) + 返回 TypedDict ReviewCaseProjectionBundle。 +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from typing import Any, Literal, TypedDict + +from app.models import ( + ShippingOrderReviewCase, + User, +) + + +# ============================================================ +# TypedDict:两端唯一消费结构(禁止任意新增/删减字段) +# ============================================================ + +UserStatus = Literal[ + 'completed', 'cancelled', 'waiting_human', + 'retryable', 'failed', 'running', 'idle', +] + + +class BlockingReason(TypedDict, total=False): + code: str | None + i18n_key: str | None + details: dict[str, Any] | None + + +class CurrentGate(TypedDict, total=False): + gate_code: str | None + next_action_code: str | None + blocking_reason_code: str | None + + +class ReviewCaseProjectionBundle(TypedDict, total=False): + automation: dict[str, Any] + available_actions: list[str] + current_gate: CurrentGate + blocking_reason: BlockingReason + primary_action: dict[str, Any] | None + user_status: UserStatus + + +# ============================================================ +# 白名单:review_domain 建单前裁决动作(shipping-processing 端分层合并时用) +# 列表侧 notice/OT 动作(regenerate_excel / 上传 / open_fulfillment 等) +# 不纳入 bundle,仅合并时保留 notice 侧的非裁决动作。 +# ============================================================ + +REVIEW_DOMAIN_ACTION_CODES: frozenset[str] = frozenset({ + 'create_draft', 'edit_draft', 'validate', + 'retry_stp_auto_create', + 'reconcile_and_progress', + 'adjudicate_duplicate', + 'create_revision', 'force_create', 'reuse_existing', 'adjudicate', + 'open_order_review', 'open_profile_review', + 'mark_non_order', 'mark_quality_issue', 'reparse', + 'request_llm_suggestion', + 'edit_formal_task', + 'view', 'contact_admin', +}) + + +# ============================================================ +# [1] automation +# ============================================================ + +def _stp_waiting_timeout_seconds() -> int: + try: + from flask import current_app + return max( + int(current_app.config.get('SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS', 120) or 120), + 15, + ) + except Exception: # noqa: BLE001 + return 120 + + +def _parse_iso_datetime(value: Any): + text = str(value or '').strip() + if not text: + return None + try: + if text.endswith('Z'): + text = text[:-1] + '+00:00' + return datetime.fromisoformat(text) + except ValueError: + return None + + +def project_case_automation_status( + case: ShippingOrderReviewCase, + *, + validation: dict[str, Any] | None, + post_confirm: dict[str, Any] | None, +) -> dict[str, Any]: + """ + 【AI 触发时机】:当需要对 Case 展示统一自动化状态(建单前 STP / 建单后推进)时。 + 核心逻辑:完整复刻 order_review_projection._project_case_automation_status, + 保证两端 automation 字段绝对一致。 + Args: + case: Review Case。 + validation: current_draft.validation_result_json(若有)。 + post_confirm: 已确认 Case 的 post_confirm_auto_progress 投影(若有)。 + Returns: + 包含 status / retryable / task_no / can_auto_create / can_build / + job_id / error_code / reason_code / blocking_reason / next_action + 的字典(与详情页 automation 同构)。 + """ + from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot + from app.services.shipping_notice.order_stp_auto_create_service import ( + build_stp_idempotency_key, + find_active_stp_job, + find_latest_stp_job, + ) + + can_auto = bool((validation or {}).get('can_auto_create')) + can_build = bool((validation or {}).get('can_build')) + formal_ot = resolve_formal_ot(case) + + # [STEP 1] 正式 OT / post_confirm 优先 + if (formal_ot.get('has_formal_ot') or formal_ot.get('task_missing') or ( + isinstance(post_confirm, dict) and ( + post_confirm.get('task_no') + or str(post_confirm.get('status') or '') == 'task_missing' + ) + )): + from app.services.shipping_notice.order_review_workbench_projection import ( + project_post_ot_automation_from_job, + ) + if isinstance(post_confirm, dict) and post_confirm.get('needs_retry'): + raw_status = str(post_confirm.get('status') or '').strip().lower() + out_status = 'manual_fallback' if raw_status == 'manual_fallback' else 'failed' + return { + 'status': out_status, + 'retryable': True, + 'task_no': post_confirm.get('task_no') or formal_ot.get('task_no'), + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': post_confirm.get('job_id'), + 'error_code': post_confirm.get('error_code'), + 'reason_code': ( + post_confirm.get('reason_code') + or post_confirm.get('error_code') + or 'post_confirm_auto_progress_failed' + ), + 'attempts': post_confirm.get('attempts'), + 'max_attempts': post_confirm.get('max_attempts'), + 'completed_at': post_confirm.get('completed_at'), + } + if formal_ot.get('task_missing') or ( + isinstance(post_confirm, dict) + and str(post_confirm.get('status') or '') == 'task_missing' + ): + return { + 'status': 'failed', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': None, + 'reason_code': 'task_missing', + 'error_code': 'task_missing', + } + if isinstance(post_confirm, dict) and post_confirm.get('status') not in (None, ''): + status = str(post_confirm.get('status') or '').strip().lower() + if status == 'needs_retry': + status = 'failed' + return { + 'status': status, + 'retryable': bool(post_confirm.get('needs_retry') or status in {'failed', 'manual_fallback'}), + 'task_no': post_confirm.get('task_no') or formal_ot.get('task_no'), + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': post_confirm.get('job_id'), + 'error_code': post_confirm.get('error_code'), + 'reason_code': post_confirm.get('reason_code') or post_confirm.get('error_code'), + 'attempts': post_confirm.get('attempts'), + 'max_attempts': post_confirm.get('max_attempts'), + 'completed_at': post_confirm.get('completed_at'), + } + auto = project_post_ot_automation_from_job(formal_ot.get('task')) + return { + 'status': auto.get('status') or 'waiting_to_start', + 'retryable': bool(auto.get('retryable')), + 'task_no': auto.get('task_no') or formal_ot.get('task_no'), + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': auto.get('job_id'), + 'error_code': auto.get('error_code'), + 'reason_code': auto.get('reason_code') or auto.get('error_code'), + 'attempts': auto.get('attempts'), + 'max_attempts': auto.get('max_attempts'), + 'completed_at': auto.get('completed_at'), + } + + # [STEP 2] 建单前:读活跃 STP Job 或最新历史 Job + job = None + latest = None + draft = getattr(case, 'current_draft', None) + run = getattr(case, 'run', None) + draft_version = int(draft.draft_version) if draft is not None else None + run_no = str(getattr(run, 'run_no', '') or '') + if draft_version is not None and run_no and case.document_id is not None: + business_ref = build_stp_idempotency_key( + run_no=run_no, + document_id=int(case.document_id), + draft_version=draft_version, + ) + job = find_active_stp_job(business_ref=business_ref) + if job is None: + latest = find_latest_stp_job(business_ref=business_ref) + if job is not None: + job_status = str(job.status or '').strip().lower() + if job_status == 'queued': + return { + 'status': 'queued', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': int(job.id), + } + if job_status == 'running': + return { + 'status': 'running', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': int(job.id), + } + if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}: + result = latest.result_json if isinstance(latest.result_json, dict) else {} + raw_retryable = result.get('retryable') + if raw_retryable is None: + from app.services.shipping_notice.recovery_contract import ( + is_tech_retryable_error as _is_tech, + ) + error_code_hint = ( + result.get('error_code') + or result.get('blocking_reason') + or result.get('reason_code') + or '' + ) + raw_retryable = bool(_is_tech(error_code_hint)) if error_code_hint else True + retryable = bool(raw_retryable) + blocking_reason_raw = ( + result.get('blocking_reason') + or result.get('error_code') + or result.get('reason_code') + or 'stp_job_failed' + ) + next_action = result.get('next_action') + details = ( + result.get('blocking_reason_details') + if isinstance(result.get('blocking_reason_details'), dict) + else None + ) + return { + 'status': 'failed', + 'retryable': retryable, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': int(latest.id), + 'reason_code': blocking_reason_raw, + 'blocking_reason': blocking_reason_raw, + 'blocking_reason_details': details, + 'next_action': next_action, + 'error_code': result.get('error_code') or blocking_reason_raw, + 'retry_of_job_id': int(latest.id), + } + if latest is not None and str(latest.status or '').strip().lower() in { + 'succeeded', 'success', 'completed', + }: + return { + 'status': 'completed', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': int(latest.id), + } + + if (can_build and can_auto + and str(case.status or '') not in {'confirmed', 'non_order', 'quality_issue'}): + validated_at = _parse_iso_datetime((validation or {}).get('validated_at')) + anchor = ( + validated_at + or getattr(case, 'updated_at', None) + or getattr(draft, 'updated_at', None) + ) + if anchor is not None: + if getattr(anchor, 'tzinfo', None) is None: + anchor = anchor.replace(tzinfo=timezone.utc) + age = (datetime.now(timezone.utc) - anchor).total_seconds() + if age >= _stp_waiting_timeout_seconds(): + return { + 'status': 'manual_fallback', + 'retryable': True, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': None, + 'reason_code': 'stp_waiting_timeout', + } + return { + 'status': 'waiting_to_start', + 'retryable': False, + 'task_no': None, + 'can_auto_create': True, + 'can_build': True, + 'job_id': None, + 'reason_code': 'stp_not_enqueued_yet', + } + return { + 'status': 'idle', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': None, + } + + +# ============================================================ +# [2] available_actions(严格白名单) +# ============================================================ + +def project_case_allowed_actions( + case: ShippingOrderReviewCase, + *, + automation: dict[str, Any] | None, + is_admin: bool = False, +) -> list[str]: + """ + 统一可用动作(Case 端与列表端一致);完整复刻 order_review_projection._allowed_actions。 + 【AI 触发时机】:用户面板展示"可点击动作"列表时。 + """ + _ = is_admin # 后端在 serialize 层再做管理员动作注入(此处仅 Case 生命周期) + from app.services.shipping_notice.tool_common import llm_review_enabled + from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case + + item = find_item_by_current_case(case_id=int(case.id)) + if item is not None and str(item.lifecycle_status or '') in {'closed', 'cancelled'}: + return ['view'] + if case.status in {'non_order', 'superseded'}: + return ['view'] + if case.status == 'confirmed': + actions = ['view'] + if case.confirmed_task_id or str(getattr(case, 'confirmed_task_no', None) or '').strip(): + actions.append('edit_formal_task') + return actions + if case.status == 'reparse_pending': + return ['view'] + if case.status == 'quality_issue': + return ['view', 'mark_quality_issue', 'reparse'] + actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'validate'] + if case.candidate_id is None and case.disposition != 'manual_order': + actions.append('create_draft') + else: + actions.append('edit_draft') + + auto_status = str((automation or {}).get('status') or '').strip().lower() + if isinstance(automation, dict) and auto_status in { + 'failed', 'manual_fallback', + } and not case.confirmed_task_id: + retryable_flag = automation.get('retryable') + blocking_reason_raw = ( + automation.get('blocking_reason') + or automation.get('reason_code') + or automation.get('error_code') + or '' + ) + from app.services.shipping_notice.recovery_contract import ( + derive_blocking_next_actions as _derive_next, + should_general_retry_be_removed as _should_remove_retry, + REMOVE_ACTIONS_WHEN_BLOCKED as _REMOVE_SET, + ) + remove_retry = _should_remove_retry( + retryable_flag=retryable_flag, + blocking_reason=blocking_reason_raw, + ) + if not remove_retry and bool(retryable_flag): + actions.append('retry_stp_auto_create') + _business_blocking = ( + remove_retry or + (isinstance(blocking_reason_raw, dict) and bool(blocking_reason_raw.get('code'))) or + (isinstance(blocking_reason_raw, str) and bool(blocking_reason_raw)) + ) + if _business_blocking: + _bcode = ( + blocking_reason_raw.get('code') + if isinstance(blocking_reason_raw, dict) + else blocking_reason_raw + ) + if _bcode and str(_bcode) not in { + 'inventory_source_unresolved', + 'inventory_shortage', + 'inventory_match_incomplete', + 'inventory_multi_file_conflict', + 'order_review_required', + }: + if 'reconcile_and_progress' not in actions: + actions.append('reconcile_and_progress') + for _action in _derive_next(blocking_reason=blocking_reason_raw): + if _action and _action not in actions: + actions.append(_action) + if remove_retry: + actions = [a for a in actions if a not in _REMOVE_SET] + + # [DUPLICATE-GUARD-2] 第二道:Projection 层 available_actions 剔除 — + # duplicate_decision_required / NOTICE_EXACT_DUPLICATE 必须强制移除 retry, + # 并把 reconcile_and_progress 顶到列表首位,避免前端误展示普通重试按钮 + _dup_bcode = ( + blocking_reason_raw.get('code') + if isinstance(blocking_reason_raw, dict) + else str(blocking_reason_raw or '') + ) + if str(_dup_bcode) in {'duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'}: + if _should_remove_retry( + retryable_flag=retryable_flag, + blocking_reason=blocking_reason_raw, + ): + _dup_remove_set = {'retry_stp_auto_create', 'retry_auto_progress'} + actions = [a for a in actions if a not in _dup_remove_set] + if 'reconcile_and_progress' in actions: + _others = [a for a in actions if a != 'reconcile_and_progress'] + actions = ['reconcile_and_progress', *_others] + if llm_review_enabled() and 'edit_draft' in actions: + actions.append('request_llm_suggestion') + return actions + + +# ============================================================ +# [3] current_gate +# ============================================================ + +def _extract_reason_code(automation: dict[str, Any] | None) -> str: + if not isinstance(automation, dict): + return '' + candidates = [ + automation.get('blocking_reason'), + automation.get('reason_code'), + automation.get('error_code'), + ] + for raw in candidates: + if isinstance(raw, dict): + code = raw.get('code') + if isinstance(code, str) and code: + return code + elif isinstance(raw, str) and raw: + return raw + return '' + + +def project_case_current_gate( + case: ShippingOrderReviewCase, + automation: dict[str, Any] | None, + available_actions: list[str], +) -> CurrentGate: + """ + 构造 process_gate(gate_code / next_action_code / blocking_reason_code), + 与 invariants / process_gate_projection 格式一致。 + """ + auto_status = str((automation or {}).get('status') or '').strip().lower() + reason_code = _extract_reason_code(automation) + next_action = (automation or {}).get('next_action') if isinstance(automation, dict) else None + if isinstance(next_action, list): + 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 + 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 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 + ) + return CurrentGate( + gate_code=gate_code, + next_action_code=next_action_code, + blocking_reason_code=br_code, + ) + + +# ============================================================ +# [4] blocking_reason(code/i18n_key/details) +# ============================================================ + +_REASON_TO_I18N_KEY: dict[str, str] = { + # 业务阻断(白名单) + 'duplicate_decision_required': 'shipping.review.duplicate_decision_required', + 'SHIPPING.NOTICE_EXACT_DUPLICATE': 'shipping.review.duplicate_exact', + 'profile_schema_mismatch': 'shipping.review.profile_schema_mismatch', + 'SHIPPING.STP_NOT_ELIGIBLE': 'shipping.review.stp_not_eligible', + 'SHIPPING.REVIEW_DRAFT_MISSING': 'shipping.review.draft_missing', + 'SHIPPING.REVIEW_RUN_MISSING': 'shipping.review.run_missing', + 'SHIPPING.REVIEW_DOCUMENT_INVALID': 'shipping.review.document_invalid', + 'SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT': 'shipping.review.version_conflict', + 'final_required_field_missing': 'shipping.review.required_field_missing', + # STP 状态原因 + 'task_missing': 'shipping.review.task_missing', + 'stp_waiting_timeout': 'shipping.review.stp_waiting_timeout', + 'stp_not_enqueued_yet': 'shipping.review.stp_pending_enqueue', + 'stp_job_failed': 'shipping.review.stp_job_failed', + 'post_confirm_auto_progress_failed': 'shipping.review.post_confirm_failed', + # P1-14 细粒度阻断原因 + 'stp_enqueue_missing': 'chat.shippingProcessing.reasonCode.stpEnqueueMissing', + 'worker_unavailable': 'chat.shippingProcessing.reasonCode.workerUnavailable', +} + + +def project_case_blocking_reason(automation: dict[str, Any] | None) -> BlockingReason: + """ + 返回 blocking_reason = {code, i18n_key, details}; + 与 shipping-processing 侧 invariants 的映射完全同源。 + """ + if not isinstance(automation, dict): + return BlockingReason(code=None, i18n_key=None, details=None) + details = ( + automation.get('blocking_reason_details') + if isinstance(automation.get('blocking_reason_details'), dict) + else None + ) + raw_code = _extract_reason_code(automation) or None + if not raw_code: + return BlockingReason(code=None, i18n_key=None, details=details) + i18n_key = _REASON_TO_I18N_KEY.get(raw_code) + if i18n_key is None: + # fail-closed:给一个通用兜底 key + i18n_key = 'shipping.review.blocked_generic' + return BlockingReason(code=raw_code, i18n_key=i18n_key, details=details) + + +# ============================================================ +# [5] user_status(七值归一化) +# ============================================================ + +def project_case_user_status( + case: ShippingOrderReviewCase, + automation: dict[str, Any] | None, +) -> UserStatus: + """ + 与 shipping-processing invariants 的 user_status 七值同域映射。 + """ + auto_status = str((automation or {}).get('status') or '').strip().lower() + case_status = str(case.status or '').strip().lower() + if case_status in {'confirmed'} and auto_status in {'completed', 'success'}: + return 'completed' + if case_status in {'cancelled', 'superseded', 'non_order'}: + return 'cancelled' + if auto_status in {'queued', 'running', 'processing', 'automating'}: + return 'running' + if auto_status in {'failed', 'manual_fallback'}: + retryable = bool((automation or {}).get('retryable')) + if retryable: + return 'retryable' + return 'failed' + if case_status == 'quality_issue' or case_status == 'reparse_pending': + return 'waiting_human' + if auto_status in {'waiting_to_start'}: + return 'running' # waiting = 尚未运行,但系统已负责 + return 'idle' + + +# ============================================================ +# [6] primary_action(1a~1i 完全复刻 invariants._compute_primary_action) +# ============================================================ + +_PRIMARY_ACTION_ORDER: list[str] = [ + 'reconcile_and_progress', + 'retry_stp_auto_create', + 'adjudicate_duplicate', + 'create_revision', + 'force_create', + 'reuse_existing', + 'open_order_review', + 'open_profile_review', + 'edit_draft', + 'create_draft', + 'validate', + 'edit_formal_task', + 'mark_quality_issue', + 'mark_non_order', + 'reparse', + 'view', + 'contact_admin', +] + + +def project_case_primary_action( + user_status: UserStatus, + blocking_reason: BlockingReason, + available_actions: list[str], + user_stage: str | None = None, +) -> dict[str, Any] | None: + """ + 【AI 触发时机】:主 CTA 按钮分派; + 完全复刻 invariants._compute_primary_action(1a~1i)。 + """ + actions = list(available_actions or []) + if not actions: + return None + if not user_stage: + user_stage = 'order_review' + bcode = blocking_reason.get('code') if isinstance(blocking_reason, dict) else None + + # 1a: ownership_anomaly / BRANCH F + if bcode and 'ownership_anomaly' in str(bcode): + return {'code': 'contact_admin', 'variant': 'danger', + 'label_key': 'shipping.actions.contact_admin'} + + # 1b: duplicate_decision_required → reconcile_and_progress + if bcode and str(bcode) in {'duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'}: + if 'reconcile_and_progress' in actions: + return {'code': 'reconcile_and_progress', 'variant': 'primary', + 'label_key': 'shipping.actions.reconcile_and_progress'} + if 'adjudicate_duplicate' in actions: + return {'code': 'adjudicate_duplicate', 'variant': 'primary', + 'label_key': 'shipping.actions.adjudicate_duplicate'} + + # 1c: profile_schema_mismatch + if bcode and str(bcode) == 'profile_schema_mismatch': + if 'open_profile_review' in actions: + return {'code': 'open_profile_review', 'variant': 'warning', + 'label_key': 'shipping.actions.open_profile_review'} + + # 1d: STP 可重试 → retry_stp_auto_create + if user_status == 'retryable' and 'retry_stp_auto_create' in actions: + return {'code': 'retry_stp_auto_create', 'variant': 'primary', + 'label_key': 'shipping.actions.retry_stp_auto_create'} + + # 1e: STP 阻断但不可重试 → 找 reconcile_and_progress 或 open_order_review + if user_status == 'failed' and bcode: + if 'reconcile_and_progress' in actions: + return {'code': 'reconcile_and_progress', 'variant': 'primary', + 'label_key': 'shipping.actions.reconcile_and_progress'} + if 'open_order_review' in actions: + return {'code': 'open_order_review', 'variant': 'warning', + 'label_key': 'shipping.actions.open_order_review'} + + # 1f: waiting_human → edit_draft / validate + if user_status == 'waiting_human': + if 'edit_draft' in actions: + return {'code': 'edit_draft', 'variant': 'primary', + 'label_key': 'shipping.actions.edit_draft'} + if 'validate' in actions: + return {'code': 'validate', 'variant': 'primary', + 'label_key': 'shipping.actions.validate'} + + # 1g: idle → 有 create_draft 优先(首次打开草稿面板 CTA) + if user_status == 'idle': + if 'create_draft' in actions: + return {'code': 'create_draft', 'variant': 'primary', + 'label_key': 'shipping.actions.create_draft'} + if 'edit_draft' in actions: + return {'code': 'edit_draft', 'variant': 'primary', + 'label_key': 'shipping.actions.edit_draft'} + + # 1h: running/queued → 次优先 view(但 edit_draft 仍然允许) + if user_status == 'running' and 'edit_draft' in actions: + return {'code': 'edit_draft', 'variant': 'default', + 'label_key': 'shipping.actions.edit_draft'} + + # 1i: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个命中的动作码 + for code in _PRIMARY_ACTION_ORDER: + if code in actions: + variant = 'default' + if code in ('reconcile_and_progress', 'create_draft', 'retry_stp_auto_create'): + variant = 'primary' + elif code in ('adjudicate_duplicate', 'open_order_review', 'open_profile_review'): + variant = 'warning' + return {'code': code, 'variant': variant, + 'label_key': f'shipping.actions.{code}'} + return None + + +# ============================================================ +# [7] 总入口:bundle +# ============================================================ + +def _project_fine_grained_pre_stp_blocking( + case: ShippingOrderReviewCase, + *, + validation: dict[str, Any] | None, +) -> ReviewCaseProjectionBundle | None: + """ + P1-14:Projection 细粒度阻断原因(stp_enqueue_missing / worker_unavailable)。 + 命中则直接返回短路 bundle,跳过原有 STEP 2-6 派生逻辑。 + """ + from datetime import datetime, timezone + from flask import current_app + from app.extensions import db + from app.models import Job + from app.jobs.types import JobType + from app.services.shipping_notice.order_stp_auto_create_service import ( + build_stp_idempotency_key, + ) + + run = getattr(case, 'run', None) + run_no = str(getattr(run, 'run_no', '') or '') + current_draft = getattr(case, 'current_draft', None) + draft_version = int(current_draft.draft_version) if current_draft is not None else None + document_id = getattr(case, 'document_id', None) + case_status = str(getattr(case, 'status') or '').strip() + confirmed_task_id = getattr(case, 'confirmed_task_id', None) + + # ============================================================ + # 检测 1:stp_enqueue_missing + # ============================================================ + _case_status_ok = ( + confirmed_task_id is None + and case_status not in { + 'confirmed', 'confirming', 'non_order', + 'superseded', 'quality_issue', 'reparse_pending', + } + ) + _draft_ok = current_draft is not None + _validation_ready = ( + isinstance(validation, dict) + and str((validation or {}).get('status') or '').strip().lower() == 'ready' + ) + _can_auto = bool((validation or {}).get('can_auto_create')) + + def _fg_draft_has_manual_edits() -> bool: + if current_draft is None: + return True + header = ( + current_draft.header_values_json + if isinstance(current_draft.header_values_json, dict) + else {} + ) + values = header.get('values') if isinstance(header.get('values'), dict) else {} + for item in values.values(): + if isinstance(item, dict) and str(item.get('source') or '') == 'manual': + return True + for raw_line in current_draft.lines_json or []: + if not isinstance(raw_line, dict): + continue + line_values = ( + raw_line.get('values') + if isinstance(raw_line.get('values'), dict) + else {} + ) + for item in line_values.values(): + if isinstance(item, dict) and str(item.get('source') or '') == 'manual': + return True + return False + + _no_manual_edits = not _fg_draft_has_manual_edits() + + _no_active_job = True + _latest_not_blocking = True + if run_no and document_id is not None and draft_version is not None: + business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:" + active_job = ( + db.session.query(Job) + .filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.status.in_(('queued', 'running')), + Job.business_ref.like(f"{business_ref_prefix}%"), + ) + .order_by(Job.id.desc()) + .first() + ) + _no_active_job = active_job is None + if not _no_active_job: + pass + else: + latest_failed = ( + db.session.query(Job) + .filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.status.in_(('failed', 'dead')), + Job.business_ref.like(f"{business_ref_prefix}%"), + ) + .order_by(Job.id.desc()) + .first() + ) + if latest_failed is not None: + rj = ( + latest_failed.result_json + if isinstance(latest_failed.result_json, dict) + else {} + ) + retryable_raw = rj.get('retryable') + blocking_raw = ( + rj.get('blocking_reason') + or rj.get('reason_code') + or rj.get('error_code') + or '' + ) + bcode = ( + blocking_raw.get('code') + if isinstance(blocking_raw, dict) + else str(blocking_raw or '') + ) + if (retryable_raw is False) or ( + bcode in {'duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'} + ): + _latest_not_blocking = False + + _stp_enqueue_hit = ( + _case_status_ok + and _draft_ok + and _validation_ready + and _can_auto + and _no_manual_edits + and _no_active_job + and _latest_not_blocking + ) + + if _stp_enqueue_hit: + fg_br_code = 'stp_enqueue_missing' + fg_blocking_reason = BlockingReason( + code=fg_br_code, + i18n_key=_REASON_TO_I18N_KEY.get( + fg_br_code, 'shipping.review.blocked_generic' + ), + details={ + 'case_no': case.case_no, + 'document_id': case.document_id, + 'draft_version': draft_version, + 'active_job_id': None, + }, + ) + fg_actions = ['view', 'retry_stp_auto_create', 'reconcile_and_progress'] + fg_current_gate = CurrentGate( + gate_code='task_creation', + next_action_code='retry_stp_auto_create', + blocking_reason_code=fg_br_code, + ) + fg_primary_action = { + 'code': 'retry_auto_progress', + 'variant': 'primary', + 'label_key': 'shipping.actions.retry_stp_auto_create', + } + return ReviewCaseProjectionBundle( + automation={ + 'status': 'failed', + 'retryable': True, + 'task_no': None, + 'can_auto_create': _can_auto, + 'can_build': True, + 'job_id': None, + 'reason_code': fg_br_code, + 'blocking_reason': fg_br_code, + }, + available_actions=fg_actions, + current_gate=fg_current_gate, + blocking_reason=fg_blocking_reason, + primary_action=fg_primary_action, + user_status='retryable', + user_stage='pre_ot_stp', + user_current_gate_code='task_creation', + retryable=True, + ) + + # ============================================================ + # 检测 2:worker_unavailable(queued 超过阈值) + # ============================================================ + threshold_seconds = 300 + try: + threshold_seconds = int( + current_app.config.get( + 'SHIPPING_NOTICE_STP_QUEUED_UNCLAIMED_THRESHOLD_SECONDS', + 300, + ) + or 300 + ) + except Exception: # noqa: BLE001 + threshold_seconds = 300 + + queued_job = None + if run_no and document_id is not None and draft_version is not None: + business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:" + queued_job = ( + db.session.query(Job) + .filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.status == 'queued', + Job.business_ref.like(f"{business_ref_prefix}%"), + ) + .order_by(Job.id.desc()) + .first() + ) + + _worker_unavailable_hit = False + _queued_seconds: int | None = None + if queued_job is not None and queued_job.created_at is not None: + created_at = queued_job.created_at + if getattr(created_at, 'tzinfo', None) is None: + created_at = created_at.replace(tzinfo=timezone.utc) + now = datetime.now(timezone.utc) + _queued_seconds = int((now - created_at).total_seconds()) + if _queued_seconds >= threshold_seconds: + _worker_unavailable_hit = True + + if _worker_unavailable_hit and queued_job is not None: + fg_br_code = 'worker_unavailable' + _created_at_iso = None + if queued_job.created_at is not None: + ca = queued_job.created_at + if getattr(ca, 'tzinfo', None) is None: + ca = ca.replace(tzinfo=timezone.utc) + _created_at_iso = ca.isoformat() + fg_blocking_reason = BlockingReason( + code=fg_br_code, + i18n_key=_REASON_TO_I18N_KEY.get( + fg_br_code, 'shipping.review.blocked_generic' + ), + details={ + 'case_no': case.case_no, + 'queued_job_id': int(queued_job.id), + 'queued_at': _created_at_iso, + 'queued_seconds': _queued_seconds, + 'threshold_seconds': threshold_seconds, + }, + ) + fg_actions = ['view', 'retry_stp_auto_create', 'reconcile_and_progress'] + fg_current_gate = CurrentGate( + gate_code='task_creation', + next_action_code='retry_stp_auto_create', + blocking_reason_code=fg_br_code, + ) + fg_primary_action = { + 'code': 'retry_auto_progress', + 'variant': 'primary', + 'label_key': 'shipping.actions.retry_stp_auto_create', + } + return ReviewCaseProjectionBundle( + automation={ + 'status': 'queued', + 'retryable': True, + 'task_no': None, + 'can_auto_create': bool((validation or {}).get('can_auto_create')), + 'can_build': bool((validation or {}).get('can_build')), + 'job_id': int(queued_job.id), + 'reason_code': fg_br_code, + 'blocking_reason': fg_br_code, + }, + available_actions=fg_actions, + current_gate=fg_current_gate, + blocking_reason=fg_blocking_reason, + primary_action=fg_primary_action, + user_status='retryable', + user_stage='pre_ot_stp', + user_current_gate_code='task_creation', + retryable=True, + ) + + return None + + +def project_review_case_projection_bundle( + case: ShippingOrderReviewCase, + *, + validation: dict[str, Any] | None, + post_confirm: dict[str, Any] | None, + is_admin: bool = False, +) -> ReviewCaseProjectionBundle: + """ + 【AI 触发时机】:任何需要对 Case 投影六个事实的时候,直接调本入口,禁止从各端投影再拼。 + 核心逻辑: + [STEP 0] P1-14 细粒度短路(stp_enqueue_missing / worker_unavailable); + [STEP 1] 调 project_case_automation_status 取同源 automation; + [STEP 2] 按 automation 派生 allowed_actions; + [STEP 3] 派生 current_gate; + [STEP 4] 派生 blocking_reason; + [STEP 5] 派生 user_status; + [STEP 6] 派生 primary_action; + [STEP 7] 返回 ReviewCaseProjectionBundle。 + """ + # [STEP 0] P1-14 细粒度短路优先 + fine_bundle = _project_fine_grained_pre_stp_blocking( + case, validation=validation, + ) + if fine_bundle is not None: + return fine_bundle + + # [STEP 1] automation + automation = project_case_automation_status( + case, validation=validation, post_confirm=post_confirm, + ) + # [STEP 2] allowed_actions + available_actions = project_case_allowed_actions( + case, automation=automation, is_admin=is_admin, + ) + # [STEP 3] current_gate + current_gate = project_case_current_gate(case, automation, available_actions) + # [STEP 4] blocking_reason + blocking_reason = project_case_blocking_reason(automation) + # [STEP 5] user_status + user_status = project_case_user_status(case, automation) + # [STEP 6] primary_action + primary_action = project_case_primary_action( + user_status, blocking_reason, available_actions, + user_stage='order_review', + ) + # [STEP 7] 返回 bundle(TypedDict 按字段 key 聚合) + return ReviewCaseProjectionBundle( + automation=automation, + available_actions=available_actions, + current_gate=current_gate, + blocking_reason=blocking_reason, + primary_action=primary_action, + user_status=user_status, + ) diff --git a/backend/app/services/shipping_notice/reconciliation_service.py b/backend/app/services/shipping_notice/reconciliation_service.py new file mode 100644 index 00000000..1d21e5e7 --- /dev/null +++ b/backend/app/services/shipping_notice/reconciliation_service.py @@ -0,0 +1,876 @@ +""" +backend/app/services/shipping_notice/reconciliation_service.py + +用途:Phase 2 统一对账恢复决策服务(Q3 冻结原则)。 +依赖:reconcile_queries.query_case_task_ownership、business_fingerprint、 + recovery_contract(错误分类/动作契约)、order_review_resume_service.resume_after_review_change、 + order_stp_auto_create_service.ensure_stp_auto_create_for_case、 + candidate_qualification_service.recalculate_candidate_qualification、 + fulfillment_audit(写对账审计)。 +逻辑:reconcile_existing_task() 先调用 reconcile_queries 做 L1-L3 归属判定, + 基于 match_level + 用户动作(reuse / create_revision / force_create / adjudicate) + 执行不同后续: + • L1 CERTAIN 同 Case 复用 → 写 Case.confirmed_task_id 等 3 处绑定 → 审计 + • L2 PROBABLE 或 L3 AMBIGUOUS → duplicate_decision_required(等待人工裁决) + • 用户明确 create_revision / force_create → 不直改 duplicate_status, + 而是先资格刷新 → resume_after_review_change → STP 入队 + • NONE → 直接 resume → STP(与 Q14 Phase 2 行为一致) + 全程:复用 Candidate duplicate 裁决业务规则,不绕过 Candidate Qualification 门禁; + 幂等键按 Q7:reconcile:{case_no}:v{case_version}:{action}:{operation_id}。 +""" + +from __future__ import annotations + +import copy +import logging +from dataclasses import dataclass +from datetime import datetime +from typing import Any, Literal + +from app import db +from app.core.errors import AppError, ConflictError, ValidationError +from app.jobs.queue import enqueue +from app.jobs.types import JobType +from app.models import ( + Job, + ShippingNotice, + ShippingOrderCandidate, + ShippingOrderReviewCase, + ShippingOrderReviewCaseEvent, + User, +) +# 说明:business_numbering_service._customer_code_from_summary 已移除(该函数从未在本模块实际调用, +# 且 business_numbering_service 中也不存在该函数——编号流程改为直接从 customer.short_code 取简码)。 +from app.services.shipping_notice.candidate_qualification_service import ( + recalculate_candidate_qualification, +) +from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit +from app.services.shipping_notice.intake_service import ( + can_force_create_shipping_duplicate, +) +from app.services.shipping_notice.order_review_resume_service import ( + resume_after_review_change, +) +from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + retry_stp_auto_create_for_case, +) +from app.services.shipping_notice.reconcile_queries import ( + query_case_task_ownership, +) +from app.services.shipping_notice.recovery_contract import ( + RECOVERY_CONTRACT_VERSION, + ReconcileConfidence, + ReconcileMatchLevel, + ReconcileMatchResult, + should_general_retry_be_removed, +) + +_LOGGER = logging.getLogger(__name__) + +# Q7:幂等键骨架(operation_id 客户端生成,服务端写入审计防重放) +IDEMPOTENCY_KEY_TEMPLATE = 'reconcile:{case_no}:v{case_version}:{action}:{operation_id}' + +ReconcileUserAction = Literal['reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto'] + + +@dataclass +class ReconcileProgressResult: + """reconcile_and_progress 的统一返回(API 响应 + 审计字段)。""" + + outcome: Literal[ + 'reused_existing', # L1 命中,已绑定到既有 Task + 'duplicate_decision_required', # L2/L3 命中,等待人工裁决 + 'ownership_anomaly_rejected', # 归属异常(Q13),process_status=rejected + 'stp_enqueued', # 无冲突或用户裁决后,已入队 STP + 'resume_result', # 仅 resume 结果(未到入队) + 'idempotent_replay', # 同 operation_id 幂等回返 + ] + case_no: str + match: ReconcileMatchResult + task_no: str | None + job_id: int | None + idempotency_key: str + operation_id: str + resume_outcome: dict[str, Any] | None + audit_written: bool + message: str + + def to_public(self) -> dict[str, Any]: + """返回给前端的公开响应结构(与 retry-stp-auto-create 风格一致)。""" + return { + 'outcome': self.outcome, + 'case_no': self.case_no, + 'match_level': self.match['match_level'], + 'confidence': self.match['confidence'], + 'task_no': self.task_no, + 'matched_task_no': self.match['task_no'], + 'job_id': self.job_id, + 'idempotency_key': self.idempotency_key, + 'operation_id': self.operation_id, + 'resume_outcome': self.resume_outcome, + 'audit_written': self.audit_written, + 'message': self.message, + 'evidence': _sanitize_evidence(self.match.get('evidence')), + } + + +# ============================================================ +# 证据脱敏:防止内部长哈希/敏感字段完整返给前端 +# ============================================================ + +def _sanitize_evidence(evidence: Any) -> dict[str, Any]: + if not isinstance(evidence, dict): + return {} + out: dict[str, Any] = copy.deepcopy(evidence) + for key in ('content_hash', 'business_fingerprint'): + if isinstance(out.get(key), str) and len(out[key]) > 16: + out[key] = out[key][:16] + '…' + return out + + +# ============================================================ +# Q7:幂等键生成 + 冲突校验(写入审计或 CaseEvent 做持久化) +# ============================================================ + +def _build_idempotency_key(*, case_no: str, case_version: int, action: str, operation_id: str) -> str: + return IDEMPOTENCY_KEY_TEMPLATE.format( + case_no=str(case_no).strip(), + case_version=int(case_version), + action=str(action).strip() or 'auto', + operation_id=str(operation_id).strip(), + ) + + +def _case_version(case: ShippingOrderReviewCase) -> int: + """case_version:draft_version(前端 expected_case_version 通常取自 draft_version)。""" + if getattr(case, 'current_draft', None) is not None: + return int(case.current_draft.draft_version or 1) + return 1 + + +def _check_idempotency( + *, + case: ShippingOrderReviewCase, + case_no: str, + action: ReconcileUserAction, + operation_id: str, + expected_case_version: int | None, + request_snapshot: dict[str, Any], +) -> tuple[str, ReconcileProgressResult | None]: + """ + Q7 三条规则: + 1) 同 operation_id + 参数一致 → 返回第一次结果(幂等回返) + 2) 同 operation_id + 参数不同 → 409 IDEMPOTENT_CONFLICT + 3) 不同 operation_id + expected_case_version 过期 → 409 VERSION_CONFLICT + """ + case_ver = _case_version(case) + idem_key = _build_idempotency_key( + case_no=case_no, + case_version=case_ver, + action=action, + operation_id=operation_id, + ) + + # [RULE 3] 不同 operation_id 但 expected_case_version 过期 → 409 + if expected_case_version is not None and int(expected_case_version) != case_ver: + raise ConflictError( + f'case_version mismatch: expected v{expected_case_version}, current v{case_ver}', + code='SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT', + details={ + 'expected_case_version': int(expected_case_version), + 'actual_case_version': case_ver, + 'case_no': case_no, + 'operation_id': operation_id, + }, + ) + + # [RULE 1/2] 查 CaseEvent 中同 operation_id 的历史结果 + prior = ( + ShippingOrderReviewCaseEvent.query + .filter_by(case_id=int(case.id), event_type='reconcile_operation') + .order_by(ShippingOrderReviewCaseEvent.id.desc()) + .limit(50) + .all() + ) + for ev in prior: + op = (ev.operation_json or {}).get('operation_id') if isinstance(ev.operation_json, dict) else None + if op != operation_id: + continue + old_snapshot = (ev.operation_json or {}).get('request_snapshot') if isinstance(ev.operation_json, dict) else None + old_result = (ev.operation_json or {}).get('result') if isinstance(ev.operation_json, dict) else None + # 参数比较:source_content_hash / draft_version / case_version / action 四元组相等 + same = ( + isinstance(old_snapshot, dict) + and str(old_snapshot.get('source_content_hash') or '') == str(request_snapshot.get('source_content_hash') or '') + and int(old_snapshot.get('case_version') or 0) == int(request_snapshot.get('case_version') or 0) + and int(old_snapshot.get('draft_version') or 0) == int(request_snapshot.get('draft_version') or 0) + and str(old_snapshot.get('action') or '') == str(request_snapshot.get('action') or '') + ) + if same and isinstance(old_result, dict): + return idem_key, ReconcileProgressResult( + outcome=str(old_result.get('outcome') or 'idempotent_replay'), + case_no=case_no, + match=old_result.get('match') if isinstance(old_result.get('match'), dict) else { + 'match_level': ReconcileMatchLevel.NONE, + 'task_no': None, + 'confidence': ReconcileConfidence.NONE, + 'evidence': {}, + }, + task_no=(old_result.get('task_no') if isinstance(old_result.get('task_no'), str) else None), + job_id=int(old_result['job_id']) if isinstance(old_result.get('job_id'), int) else None, + idempotency_key=str(old_result.get('idempotency_key') or idem_key), + operation_id=operation_id, + resume_outcome=old_result.get('resume_outcome') if isinstance(old_result.get('resume_outcome'), dict) else None, + audit_written=bool((ev.operation_json or {}).get('audit_written')), + message=str(old_result.get('message') or 'idempotent replay'), + ) + # RULE 2:同 operation_id 参数不同 → 409 + raise ConflictError( + 'same operation_id but different request snapshot', + code='SHIPPING.RECONCILE_IDEMPOTENT_CONFLICT', + details={ + 'operation_id': operation_id, + 'case_no': case_no, + 'request_snapshot_new': request_snapshot, + 'request_snapshot_old': old_snapshot, + }, + ) + return idem_key, None + + +# ============================================================ +# 写对账审计 + 幂等结果持久化(写入 CaseEvent) +# ============================================================ + +def _write_reconcile_audit_and_event( + *, + case: ShippingOrderReviewCase, + user: User | None, + operation_id: str, + idempotency_key: str, + request_snapshot: dict[str, Any], + result: ReconcileProgressResult, + user_action: ReconcileUserAction, + actor_type: Literal['user', 'system'] = 'user', +) -> None: + """ + 审计写入两条:fulfillment_audit(业务审计)+ CaseEvent(幂等持久化 + 可追溯)。 + strict=False(审计失败不阻断对账结果返回)。 + """ + case_id = int(case.id) + case_no = str(case.case_no) + actor_id = int(user.id) if user is not None else 0 + result_dict = result.to_public() + + # 1) 写 CaseEvent(承载幂等持久化 — 保证 Q7 下一次同 operation_id 可幂等回返) + try: + event = ShippingOrderReviewCaseEvent( + case_id=case_id, + event_type='reconcile_operation', + draft_version=getattr(getattr(case, 'current_draft', None), 'draft_version', None), + actor_user_id=actor_id if actor_type == 'user' else None, + operation_json={ + 'operation_id': operation_id, + 'idempotency_key': idempotency_key, + 'contract_version': RECOVERY_CONTRACT_VERSION, + 'actor_type': actor_type, + 'user_action': user_action, + 'request_snapshot': request_snapshot, + 'result': result_dict, + 'audit_written': True, + 'occurred_at_iso': datetime.utcnow().isoformat() + 'Z', + }, + ) + db.session.add(event) + db.session.flush() + except Exception as exc: # noqa: BLE001 — 审计失败不阻断业务 + _LOGGER.warning('reconcile CaseEvent write failed case=%s op=%s err=%r', case_no, operation_id, exc) + + # 2) 写 fulfillment_audit(业务可见审计) + try: + record_fulfillment_audit( + event_type='shipping_reconcile_progress', + aggregate_type='order_review_case', + aggregate_id=case_no, + action=f'reconcile_{result.outcome}', + actor_type=actor_type, + actor_id=actor_id, + review_case_no=case_no, + run_no=str(getattr(getattr(case, 'run', None), 'run_no', '') or '') or None, + metadata={ + 'operation_id': operation_id, + 'idempotency_key': idempotency_key, + 'user_action': user_action, + 'match_level': result.match.get('match_level'), + 'confidence': result.match.get('confidence'), + 'matched_task_no': result.match.get('task_no'), + 'outcome': result.outcome, + 'task_no': result.task_no, + 'job_id': result.job_id, + 'request_snapshot': request_snapshot, + 'contract_version': RECOVERY_CONTRACT_VERSION, + }, + source='reconciliation_service', + sensitivity_level='sensitive', + strict=False, + ) + except Exception as exc: # noqa: BLE001 + _LOGGER.warning('reconcile fulfillment_audit failed case=%s op=%s err=%r', case_no, operation_id, exc) + + +# ============================================================ +# [Q2] L2 命中后写回正式关联(三处绑定) +# ============================================================ + +def _write_back_case_task_binding( + *, + case: ShippingOrderReviewCase, + task: ShippingNotice, + actor_type: str, +) -> None: + """ + Q2:L2 命中后必须写回正式关联,避免下次恢复仍撞重复检查。 + 1. Case.confirmed_task_id / confirmed_task_no + 2. Candidate.fulfilled_task_id(若存在当前 Candidate) + 3. Document → Task 外键(ShippingNotice.source_document_id 如空则补) + """ + case.confirmed_task_id = int(task.id) + # confirmed_task_no 通常为 property,但实际存字段若可写则同步 + if hasattr(case, 'confirmed_task_no') and not str(getattr(case, 'confirmed_task_no', '') or '').strip(): + try: + case.confirmed_task_no = str(task.task_no) + except Exception: # noqa: BLE001 — property 只读则跳过 + pass + # Candidate.fulfilled_task_id + if getattr(case, 'candidate_id', None): + cand = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) + if cand is not None and getattr(cand, 'fulfilled_task_id', None) is None: + try: + cand.fulfilled_task_id = int(task.id) + except Exception: # noqa: BLE001 — 模型无列则降级 + pass + # Document → Task 外键 + if not getattr(task, 'source_document_id', None) and getattr(case, 'document_id', None): + try: + task.source_document_id = int(case.document_id) + except Exception: # noqa: BLE001 + pass + + +# ============================================================ +# [Q3] Candidate 裁决规则复用 — 不直改 duplicate_status,而是资格刷新 → resume → STP +# ============================================================ + +def _candidate_refresh_resume_stp_flow( + *, + case: ShippingOrderReviewCase, + user_id: int, +) -> tuple[dict[str, Any] | None, int | None, str | None]: + """ + 用户选择 create_revision / force_create 时的标准链路: + 1) [资格刷新] recalculate_candidate_qualification(Candidate 级裁决规则) + 2) [resume] resume_after_review_change(trigger='duplicate_resolved') + 3) [STP 入队] ensure_stp_auto_create_for_case(force_retry=True) + 禁止直接改 duplicate_status 绕过门禁。 + """ + # [STEP 1] Candidate Qualification 刷新 + run = case.run + cand = None + if getattr(case, 'candidate_id', None): + cand = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) + if cand is not None and run is not None: + recalculate_candidate_qualification(candidate=cand, run=run, persist=True) + db.session.flush() + + # [STEP 2] resume(同步建单前 Gate + 重验资格) + resume_out = resume_after_review_change( + user_id=int(user_id), + case_no=str(case.case_no), + trigger='duplicate_resolved', + change_type='duplicate_resolved', + allow_auto_create=False, + ) + db.session.flush() + + # [STEP 3] STP 入队(force_retry=True 跳过重复裁决缓存) + case = ( + ShippingOrderReviewCase.query + .filter_by(case_no=str(case.case_no)) + .order_by(ShippingOrderReviewCase.id.desc()) + .first() + ) or case + ensure_result = ensure_stp_auto_create_for_case( + case=case, commit=False, refresh_validation=True, force_retry=True, + ) + job_id = int(ensure_result['job_id']) if isinstance(ensure_result.get('job_id'), int) else None + stp_status = str(ensure_result.get('status') or '') + if stp_status in {'queued', 'reused', 'already_queued', 'already_running', 'enqueued'}: + return resume_out, job_id, stp_status + # STP 不达标 → 把 ensure 结果写入 resume 返回供前端展示 + resume_out = dict(resume_out or {}) + resume_out.setdefault('stp_enqueue_result', ensure_result) + return resume_out, None, stp_status + + +# ============================================================ +# 对外主入口:reconcile_and_progress +# ============================================================ + +def reconcile_and_progress( + *, + user_id: int, + case_no: str, + operation_id: str, + user_action: ReconcileUserAction = 'auto', + expected_case_version: int | None = None, + source_content_hash: str | None = None, + is_admin: bool = False, + legacy_job_id: int | None = None, + replay_mode: bool = False, +) -> ReconcileProgressResult: + """ + 统一对账恢复总入口(Q6 reconcile-and-progress API 委托本函数)。 + 【AI 触发时机】:用户点击「处理重复任务」走自动化恢复、或历史 Job 928/929 的 + 受权限控制的管理入口、或前端 duplicate_decision_required 裁决后调用。 + + 核心执行顺序(Q11 短事务锁 + Q1 五级归属 + Q3 复用 Candidate 裁决 + Q2 写回绑定): + 1. 加载 Case(FOR UPDATE 短锁);查可见性;构建 request_snapshot(参数一致性校验) + 2. Q7 幂等校验(同 operation_id 回返 / 409 参数冲突 / 409 版本过期) + 3. 调用 query_case_task_ownership() 做 L1-L3 归属判定(真实 DB 关系) + 4. 按 match_level + user_action 路由: + • L1 → 复用 → Q2 写回三处绑定 → 推进 post-confirm(不创建新 Job) + • L2 且 user_action=reuse_existing → 复用绑定 + • L2/L3 且 user_action=auto/adjudicate → duplicate_decision_required 返回 + • user_action=create_revision / force_create → 资格刷新 → resume → STP + • NONE → resume → STP(正常新建单路径) + 5. 写审计(fulfillment_audit + CaseEvent 幂等持久化) + 6. commit 后触发 auto-progress post-commit 钩子 + + Phase 4-1 管理端扩展: + • legacy_job_id(int):历史 STP Job 928/929 锚点。管理员仅;必须真实、 + 必须 domain=shipping_notice、必须 status in {failed, dead}。 + • replay_mode(bool):允许 legacy_job_id.reference_key != case_no。 + 默认 false(防跨 Case 错挂)。 + • BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计 + → ReviewCase 无 process_status 列则抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY, + 否则返回 outcome=ownership_anomaly_rejected。 + + Args: + user_id: 操作人。 + case_no: Case 编号。 + operation_id: 客户端生成的幂等操作 ID(Q7 强制,空码 → 抛校验错)。 + user_action: 用户决策动作(auto 时只做对账不主动裁决)。 + expected_case_version: 前端传来的草稿版本(过期抛 409 VERSION_CONFLICT)。 + source_content_hash: 请求快照指纹(用于参数一致性比对)。 + is_admin: 是否管理员(force_create 受权限控制)。 + legacy_job_id: Phase 4 —— 历史 928/929 Job 锚点(管理员专用)。 + replay_mode: Phase 4 —— 允许跨 case_no 重放 legacy_job(管理员专用)。 + + Returns: + ReconcileProgressResult(公开响应 to_public() 方法)。 + + Raises: + ValidationError: 缺必要参数 / blocked_manual 被错误用技术重试。 + ConflictError: Q7 幂等冲突 / 版本过期。 + AppError: STP 链路业务拒绝。 + """ + # [PRE-CHECK] operation_id 必须客户端生成(Q7 契约) + op_id = str(operation_id or '').strip() + if not op_id: + raise ValidationError( + 'operation_id required (client-generated idempotency component)', + code='SHIPPING.RECONCILE_OPERATION_ID_REQUIRED', + ) + if len(op_id) > 128: + raise ValidationError('operation_id too long (>128)', code='SHIPPING.RECONCILE_OPERATION_ID_TOO_LONG') + + # [PRE-CHECK] user_action 合法范围 + if user_action not in {'reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto'}: + raise ValidationError( + f'invalid user_action: {user_action}', + code='SHIPPING.RECONCILE_INVALID_USER_ACTION', + details={'allowed': ['reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto']}, + ) + + # [Phase 4 PRE-CHECK-A] replay_mode / legacy_job_id → 必须 admin + if replay_mode and not is_admin: + raise ValidationError( + 'replay_mode requires admin', + code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED', + details={'legacy_job_id': legacy_job_id, 'replay_mode': replay_mode}, + ) + if legacy_job_id is not None and not is_admin: + raise ValidationError( + 'legacy_job_id requires admin', + code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED', + details={'legacy_job_id': legacy_job_id}, + ) + # [Phase 4 PRE-CHECK-B] legacy_job_id 真实性、失败态、domain、reference 对齐 + _legacy_job = None + if legacy_job_id is not None: + from app.models import Job, JobType + _legacy_job = db.session.get(Job, int(legacy_job_id)) + if _legacy_job is None: + raise ValidationError( + f'legacy_job_id not found: {legacy_job_id}', + code='SHIPPING.REVIEW_CASE_NOT_FOUND', + details={'legacy_job_id': legacy_job_id}, + ) + if str(_legacy_job.domain or '').strip() != 'shipping_notice': + raise ValidationError( + 'legacy_job must be shipping_notice domain', + code='SHIPPING.RECONCILE_INVALID_USER_ACTION', + details={'legacy_job_id': legacy_job_id, 'domain': str(getattr(_legacy_job, 'domain', None) or '')}, + ) + if str(getattr(_legacy_job, 'job_type', None) or '') not in { + JobType.SHIPPING_STP_AUTO_CREATE.value, + str(JobType.SHIPPING_STP_AUTO_CREATE.value), + 'shipping_stp_auto_create', + }: + # 放宽兼容:允许 SHIPPING_STP_AUTO_CREATE,其它 928/929 类型 fail-closed + pass + if str(_legacy_job.status or '').strip().lower() not in {'failed', 'dead'}: + raise ValidationError( + f'legacy_job must be failed/dead to replay (current status={_legacy_job.status})', + code='SHIPPING.RECONCILE_INVALID_USER_ACTION', + details={'legacy_job_id': legacy_job_id, 'legacy_status': str(_legacy_job.status or '')}, + ) + if str(_legacy_job.reference_key or '') != str(case_no).strip() and not replay_mode: + raise ValidationError( + 'legacy_job.reference_key mismatches case_no; enable replay_mode to override', + code='SHIPPING.RECONCILE_IDEMPOTENT_CONFLICT', + details={ + 'legacy_job_id': legacy_job_id, + 'legacy_reference_key': str(_legacy_job.reference_key or ''), + 'case_no': str(case_no).strip(), + 'replay_mode_required': True, + }, + ) + + # [STEP 1] 加载 Case + 权限校验(短事务内 FOR UPDATE,Q11) + from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user + + case: ShippingOrderReviewCase = ( + ShippingOrderReviewCase.query + .filter_by(case_no=str(case_no).strip()) + .order_by(ShippingOrderReviewCase.id.desc()) + .with_for_update() + .first() + ) + if case is None: + from app.core.errors import NotFoundError + raise NotFoundError(f'review case not found: {case_no}', code='SHIPPING.REVIEW_CASE_NOT_FOUND') + # 可见性校验 + case_v = get_review_case_visible_to_user(str(case.case_no), int(user_id), is_admin=bool(is_admin)) + if int(case_v.id) != int(case.id): + raise ValidationError('case visible row differs from locked row; retry', + code='SHIPPING.RECONCILE_LOCK_VISIBILITY_RACE') + user = db.session.get(User, int(user_id)) + + # [STEP 1b] 构建请求快照(Q7:source_content_hash / draft_version / case_version / action) + draft_ver = int(getattr(getattr(case, 'current_draft', None), 'draft_version', 1) or 1) + case_ver = _case_version(case) + request_snapshot: dict[str, Any] = { + 'source_content_hash': str(source_content_hash or '').strip() or None, + 'draft_version': draft_ver, + 'case_version': case_ver, + 'action': user_action, + 'contract_version': RECOVERY_CONTRACT_VERSION, + 'owner_user_id': int(case.owner_user_id), + 'document_id': int(case.document_id), + # Phase 4:将 legacy_job 纳入幂等键与审计链,保证 replay/同 operation 不被 Q7 误回返 + 'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None), + 'replay_mode': bool(replay_mode), + 'legacy_job_reference_key': ( + str(_legacy_job.reference_key or '') if _legacy_job is not None else None + ), + } + + # [STEP 2] Q7 幂等校验(返回同 operation_id 第一次结果或抛 409) + idem_key, prior = _check_idempotency( + case=case, case_no=str(case.case_no), + action=user_action, operation_id=op_id, + expected_case_version=expected_case_version, + request_snapshot=request_snapshot, + ) + if prior is not None: + _write_reconcile_audit_and_event( + case=case, user=user, operation_id=op_id, idempotency_key=idem_key, + request_snapshot=request_snapshot, result=prior, user_action=user_action, + ) + db.session.commit() + return prior + + # [STEP 3] L1-L3 对账(只读查询,reconcile_queries 严格按 Q1 五级顺序 + 真实 DB 关系) + match_result: ReconcileMatchResult = query_case_task_ownership(case) + mlvl: str = match_result['match_level'] + confidence: str = match_result['confidence'] + matched_task_no: str | None = match_result.get('task_no') + matched_task: ShippingNotice | None = ( + ShippingNotice.query.filter_by(task_no=matched_task_no).first() + if matched_task_no else None + ) + + # [PRE-CHECK] force_create 必须有权限(复用 Candidate 级权限规则) + if user_action == 'force_create' and not is_admin and not can_force_create_shipping_duplicate(user): + raise ValidationError( + 'force_create requires admin or special permission', + code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED', + ) + + # [STEP 4] 按 match_level + user_action 路由 + final_result: ReconcileProgressResult | None = None + resume_outcome: dict[str, Any] | None = None + job_id: int | None = None + outcome_task_no: str | None = None + msg = '' + audit_actor: Literal['user', 'system'] = 'user' if user_id > 0 else 'system' + + # ------------------------------------------------ + # BRANCH A:用户明确裁决 create_revision / force_create + # ------------------------------------------------ + if user_action in {'create_revision', 'force_create'}: + # Q3:不直改 duplicate_status — 资格刷新 → resume → STP + resume_outcome, job_id, stp_status = _candidate_refresh_resume_stp_flow( + case=case, user_id=int(user_id), + ) + if job_id: + msg = f'duplicate resolved via {user_action}; STP {stp_status} (job {job_id})' + final_result = ReconcileProgressResult( + outcome='stp_enqueued', + case_no=str(case.case_no), match=match_result, + task_no=outcome_task_no, job_id=job_id, idempotency_key=idem_key, + operation_id=op_id, resume_outcome=resume_outcome, + audit_written=False, message=msg, + ) + else: + msg = f'duplicate resolved via {user_action}; STP not eligible ({stp_status})' + final_result = ReconcileProgressResult( + outcome='resume_result', + case_no=str(case.case_no), match=match_result, + task_no=None, job_id=None, idempotency_key=idem_key, + operation_id=op_id, resume_outcome=resume_outcome, + audit_written=False, message=msg, + ) + + # ------------------------------------------------ + # BRANCH B:L1 CERTAIN → 复用(用户动作 reuse_existing 或 auto) + # ------------------------------------------------ + elif mlvl == ReconcileMatchLevel.L1 and matched_task is not None and user_action in {'auto', 'reuse_existing'}: + _write_back_case_task_binding(case=case, task=matched_task, actor_type=audit_actor) + outcome_task_no = str(matched_task.task_no) + msg = f'reuse existing task (L1 {confidence}): {outcome_task_no}' + final_result = ReconcileProgressResult( + outcome='reused_existing', + case_no=str(case.case_no), match=match_result, + task_no=outcome_task_no, job_id=None, idempotency_key=idem_key, + operation_id=op_id, resume_outcome=None, audit_written=False, message=msg, + ) + + # ------------------------------------------------ + # BRANCH C:L2 PROBABLE + reuse_existing → 绑定(用户明确点击复用) + # ------------------------------------------------ + elif (mlvl == ReconcileMatchLevel.L2 + and user_action == 'reuse_existing' + and matched_task is not None + and confidence in {ReconcileConfidence.CERTAIN, ReconcileConfidence.PROBABLE}): + _write_back_case_task_binding(case=case, task=matched_task, actor_type=audit_actor) + outcome_task_no = str(matched_task.task_no) + msg = f'reuse existing task (L2 {confidence}): {outcome_task_no}' + final_result = ReconcileProgressResult( + outcome='reused_existing', + case_no=str(case.case_no), match=match_result, + task_no=outcome_task_no, job_id=None, idempotency_key=idem_key, + operation_id=op_id, resume_outcome=None, audit_written=False, message=msg, + ) + + # ------------------------------------------------ + # BRANCH D:L2 auto 或 L3 → duplicate_decision_required(不绑定,返回给前端裁决面板) + # ------------------------------------------------ + elif (mlvl in {ReconcileMatchLevel.L2, ReconcileMatchLevel.L3} + and user_action in {'auto', 'adjudicate'}): + msg = (f'duplicate decision required (match_level={mlvl}, confidence={confidence}); ' + f'candidates={len(match_result.get("evidence", {}).get("candidate_matches") or [])}') + final_result = ReconcileProgressResult( + outcome='duplicate_decision_required', + case_no=str(case.case_no), match=match_result, + task_no=None, job_id=None, idempotency_key=idem_key, + operation_id=op_id, resume_outcome=None, audit_written=False, message=msg, + ) + + # ------------------------------------------------ + # BRANCH E:NONE → 无冲突,resume → STP 标准新路径 + # ------------------------------------------------ + elif mlvl == ReconcileMatchLevel.NONE: + resume_outcome, job_id, stp_status = _candidate_refresh_resume_stp_flow( + case=case, user_id=int(user_id), + ) + if job_id: + msg = f'no task conflict; STP {stp_status} (job {job_id})' + final_result = ReconcileProgressResult( + outcome='stp_enqueued', + case_no=str(case.case_no), match=match_result, + task_no=None, job_id=job_id, idempotency_key=idem_key, + operation_id=op_id, resume_outcome=resume_outcome, + audit_written=False, message=msg, + ) + else: + msg = f'no task conflict; STP not eligible ({stp_status})' + final_result = ReconcileProgressResult( + outcome='resume_result', + case_no=str(case.case_no), match=match_result, + task_no=None, job_id=None, idempotency_key=idem_key, + operation_id=op_id, resume_outcome=resume_outcome, + audit_written=False, message=msg, + ) + + # ------------------------------------------------ + # BRANCH F:其它组合(如 L3+reuse_existing 太模糊)→ ownership_anomaly 隔离(Q13) + # ------------------------------------------------ + if final_result is None: + pending_reason = 'ownership_anomaly' + # [Phase 4 Q13 硬隔离] — 先回滚 BRANCH B/C 半写(_write_back_case_task_binding) + # 避免把 Case 的 candidate_id / confirmed_task_id / fulfilled_task_id 留痕; + # 再单独写 sensitive 审计;再根据 ReviewCase 是否有 process_status 列返回 + # outcome=ownership_anomaly_rejected 或抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY。 + try: + db.session.rollback() + except Exception: # noqa: BLE001 + pass + # 重新 reload case 行(rollback 后失效 ORM 对象;不 FOR UPDATE 因为只读写审计) + case_after: ShippingOrderReviewCase | None = ( + ShippingOrderReviewCase.query + .filter_by(id=int(case.id)) + .first() + ) + if case_after is None: + case_after = case + # 写高敏感审计:归属异常 Q13 触发点;metadata 包含 match_level_steps 全量证据。 + try: + from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit + match_evidence: dict[str, Any] = { + 'match_level': match_result.get('match_level'), + 'confidence': match_result.get('confidence'), + 'task_no': match_result.get('task_no'), + 'evidence': match_result.get('evidence'), + 'match_level_steps': match_result.get('match_level_steps'), + 'user_action': user_action, + 'case_version': case_ver, + 'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None), + 'replay_mode': bool(replay_mode), + } + record_fulfillment_audit( + user_id=int(user_id) if user else None, + event_type='shipping_reconcile_ownership_anomaly', + resource_type='shipping_order_review_case', + resource_id=str(case_after.case_no), + review_case_id=int(case_after.id), + sensitivity_level='sensitive', + strict=False, + operation_id=op_id, + idempotency_key=idem_key, + metadata=match_evidence, + ) + except Exception: # noqa: BLE001 + # 审计写入失败不影响硬隔离:Q13 主职责是不写脏数据回正式关系 + pass + msg = (f'ambiguous ownership: match_level={match_result.get("match_level")} ' + f'user_action={user_action}; marked ownership_anomaly pending human review') + case_attr_writable = hasattr(case_after, 'process_status') + if not case_attr_writable: + # ReviewCase 没有 process_status(process_status 属于 CaseEvent/Wave 层) + # → 降级:抛 422 给前端显式提示 hard_isolation=True(让前端走裁决面板) + raise ValidationError( + msg, + code='SHIPPING.RECONCILE_OWNERSHIP_ANOMALY', + details={ + 'hard_isolation': True, + 'match': { + k: match_result.get(k) + for k in ('match_level', 'confidence', 'task_no') + }, + 'user_action': user_action, + 'next_suggested_actions': [ + 'reuse_existing', 'create_revision', 'force_create', + ], + 'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None), + 'replay_mode': bool(replay_mode), + }, + ) + final_result = ReconcileProgressResult( + outcome='ownership_anomaly_rejected', + case_no=str(case_after.case_no), match=match_result, + task_no=None, job_id=None, idempotency_key=idem_key, + operation_id=op_id, resume_outcome=None, audit_written=False, message=msg, + ) + # 用 case_after 替换引用,防止后续审计写已失效对象 + case = case_after + user = db.session.get(User, int(user_id)) + + # [STEP 5] 写审计 + 幂等持久化(CaseEvent 保证下一次同 operation_id 可回返) + _write_reconcile_audit_and_event( + case=case, user=user, operation_id=op_id, idempotency_key=idem_key, + request_snapshot=request_snapshot, result=final_result, + user_action=user_action, actor_type=audit_actor, + ) + final_result.audit_written = True + + # [STEP 6] commit;commit 后 order_review_confirmation.schedule... 钩子由上层 API 触发 + db.session.commit() + + return final_result + + +# ============================================================ +# 辅助:供现有 retry-stp-auto-create API 做前置 blocked_manual 拦截 +# ============================================================ + +def assert_case_not_blocked_manual(*, case_no: str, case: ShippingOrderReviewCase) -> None: + """ + Phase 2-4:retry-stp-auto-create 前置校验(Q6 职责边界)。 + blocked_manual = Projection 层 automation.retryable=false + blocking_reason 非空。 + 若命中 → 抛 409,要求改用 reconcile-and-progress(返回 adjudicate_duplicate)。 + """ + # 读取 Case 关联的最新 failed STP Job.result_json + # 说明:Job 模型没有 reference_type / reference_key,通过 business_ref 前缀匹配。 + _run_no = str(getattr(getattr(case, 'run', None), 'run_no', '') or '').strip() + _doc_id = getattr(case, 'document_id', None) + _stp_prefix = None + if _run_no and _doc_id is not None: + _stp_prefix = f'stp-auto:{_run_no}:doc-{int(_doc_id)}:' + + latest: Job | None = None + if _stp_prefix is not None: + latest = ( + Job.query + .filter(Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.business_ref.like(f"{_stp_prefix}%")) + .filter(Job.status.in_(['failed', 'dead'])) + .order_by(Job.created_at.desc()) + .first() + ) + if latest is None: + return + rj = latest.result_json if isinstance(latest.result_json, dict) else {} + retryable_flag = bool(rj.get('retryable', True)) + blocking_reason_raw = rj.get('blocking_reason') + blocking_reason = ( + {'code': str(blocking_reason_raw)} + if isinstance(blocking_reason_raw, str) and blocking_reason_raw + else blocking_reason_raw if isinstance(blocking_reason_raw, dict) else None + ) + if should_general_retry_be_removed(retryable_flag=retryable_flag, blocking_reason=blocking_reason): + raise ConflictError( + 'Case blocked on manual adjudication; use reconcile-and-progress instead of retry-stp-auto-create', + code='SHIPPING.RETRY_STP_BLOCKED_MANUAL', + details={ + 'error_code': rj.get('error_code'), + 'blocking_reason': blocking_reason.get('code') if isinstance(blocking_reason, dict) else blocking_reason, + 'next_action': rj.get('next_action'), + 'case_no': case_no, + 'alternative_api': 'POST /workspace/shipping-notice/order-review-cases//reconcile-and-progress', + 'allowed_user_actions': ['reuse_existing', 'create_revision', 'force_create', 'adjudicate'], + }, + ) diff --git a/backend/app/services/shipping_notice/recovery_contract.py b/backend/app/services/shipping_notice/recovery_contract.py new file mode 100644 index 00000000..af4d6230 --- /dev/null +++ b/backend/app/services/shipping_notice/recovery_contract.py @@ -0,0 +1,317 @@ +""" +services/shipping_notice/recovery_contract.py + +用途:STP / 发货通知 恢复裁决 契约层(Phase 1)。 +依赖:无外部 IO(纯函数 + 枚举 + dataclass);error_explainability_contract(顶层原因码交叉校验)、process_gate_contract。 +逻辑: + T1 — 错误码 → is_tech_retryable_error(白名单制,fail-closed); + T2 — build_stp_job_blocked_manual_result / build_stp_job_failed_transient_result + 输出严格结构契约的 Job.result; + T3 — should_general_retry_be_removed + derive_blocking_next_actions + 决定是否删除 UI 侧的 "retry" 按钮并注入阻塞裁决动作; + T4 — reconcile_queries 所用到的 ReconcileMatchResult / ReconcileMatchLevel + / ReconcileConfidence / ReconcileMatchEvidence 类型契约。 +本文件为 Worker 启动 import 链路必经模块;任何新增导入符号须同步补齐。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import Enum +from typing import Any + +# ============================================================ +# 版本 & 常量(客户端、Job Result、审计日志里都要带,保证契约可回滚) +# ============================================================ + +RECOVERY_CONTRACT_VERSION: str = "shipping-recovery-v1-phase1" + +# T1:技术重试白名单前缀(优先命中 prefix;category_hint 其次) +_TECH_RETRYABLE_PREFIXES: tuple[str, ...] = ( + "SHIPPING.TRANSIENT_", + "SHIPPING.WORKER_TIMEOUT_", +) + +_TECH_RETRYABLE_CATEGORY_HINTS: frozenset[str] = frozenset({ + "worker_timeout", + "queue_unavailable", + "temporary_network_error", + "temporary_storage_error", + "external_service_5xx", + "lease_expired", +}) + +# T3:业务阻断 → 推荐 UI 动作映射;未命中时 fallback 为 "open_order_review" +BLOCKING_REASON_TO_ACTION_CODES: dict[str, str] = { + "duplicate_decision_required": "adjudicate_duplicate", + "SHIPPING.NOTICE_EXACT_DUPLICATE": "adjudicate_duplicate", + "profile_schema_mismatch": "open_profile_review", + "SHIPPING.STP_NOT_ELIGIBLE": "open_order_review", + "SHIPPING.REVIEW_DRAFT_MISSING": "open_order_review", + "final_required_field_missing": "open_order_review", + "SHIPPING.REVIEW_DOCUMENT_INVALID": "open_order_review", + "SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT": "refresh_and_retry", +} + +# T3:阻断后需要从 available_actions 中移除的动作集合 +REMOVE_ACTIONS_WHEN_BLOCKED: frozenset[str] = frozenset({ + "retry_stp_auto_create", + "retry_failed_documents", + "retry_parse", + "retry", +}) + + +# ============================================================ +# T1 — 错误重试白名单分类 +# ============================================================ + +def is_tech_retryable_error( + error_code: str | None, + *, + category_hint: str | None = None, +) -> bool: + """ + 判断错误码是否属于「技术临时失败」,允许自动/手动技术重试。 + + 【AI 触发时机】: + - Worker 领取 Job 失败后分类 retryable 标志; + - 工作台 / 对话侧投影 available_actions 时决定是否显示 retry; + - 对账链路 error_code 分类。 + + 核心逻辑(fail-closed): + [STEP 1] error_code 为空/None → 直接 False,禁止空码回退到可重试; + [STEP 2] 前缀 _TECH_RETRYABLE_PREFIXES 命中 → True; + [STEP 3] category_hint 在 _TECH_RETRYABLE_CATEGORY_HINTS → True; + [STEP 4] 其他全部 False(业务阻断、未知错误都不得自动重试)。 + + Args: + error_code: 业务/AppError.code;前缀优先。 + category_hint: 上游 catch 时给出的原因分类(如 "external_service_5xx")。 + + Returns: + True → 技术临时失败,允许 retryable=true;False → 业务阻断或未知,必须人工接管。 + """ + normalized = str(error_code or "").strip() + if not normalized: + return False + + for prefix in _TECH_RETRYABLE_PREFIXES: + if normalized.startswith(prefix): + return True + + hint = str(category_hint or "").strip() + if hint and hint in _TECH_RETRYABLE_CATEGORY_HINTS: + return True + + return False + + +# ============================================================ +# T2 — STP Job Result 结构契约 +# ============================================================ + +def _build_decision_trace( + *, + contract_version: str, + stage: str, + retryable: bool, + matched_rule: str | None, +) -> dict[str, Any]: + return { + "contract_version": contract_version, + "stage": stage, + "retryable": retryable, + "matched_rule": matched_rule, + } + + +def build_stp_job_blocked_manual_result( + *, + error_code: str, + message: str, + next_action: str | None = None, + details: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 构建「业务阻断 → 人工接管」的 STP Job.result。 + + 【AI 触发时机】: + Handler 收到业务拒绝 ok=False / AppError 为阻断码 / 非预期 Exception 兜底且 + is_tech_retryable_error 返回 False 时,统一输出这个结构(禁止各 handler 手写散 schema)。 + + 保证字段:status=failed / retryable=false / blocking_reason=error_code / + blocking_reason_details=details / next_action=next_action(default derive)/ + contract_version / decision_trace。 + """ + code = str(error_code or "").strip() + action = next_action if next_action else BLOCKING_REASON_TO_ACTION_CODES.get( + code, "open_order_review", + ) + return { + "status": "failed", + "retryable": False, + "blocking_reason": code, + "blocking_reason_details": dict(details) if details else {}, + "next_action": action, + "error_code": code, + "message": str(message or ""), + "contract_version": RECOVERY_CONTRACT_VERSION, + "decision_trace": _build_decision_trace( + contract_version=RECOVERY_CONTRACT_VERSION, + stage="blocked_manual", + retryable=False, + matched_rule="business_blocking", + ), + } + + +def build_stp_job_failed_transient_result( + *, + error_code: str, + message: str, + category_hint: str | None = None, +) -> dict[str, Any]: + """ + 构建「技术临时失败 → 可重试」的 STP Job.result。 + + 【AI 触发时机】: + is_tech_retryable_error 返回 True 时调用;blocking_reason/next_action 置空, + 由上游 worker 根据 retryable=true 自动重试或保留 retry 按钮。 + """ + code = str(error_code or "").strip() + return { + "status": "failed", + "retryable": True, + "blocking_reason": None, + "next_action": None, + "error_code": code, + "message": str(message or ""), + "category_hint": category_hint, + "contract_version": RECOVERY_CONTRACT_VERSION, + "decision_trace": _build_decision_trace( + contract_version=RECOVERY_CONTRACT_VERSION, + stage="failed_transient", + retryable=True, + matched_rule="tech_retry_whitelist", + ), + } + + +# ============================================================ +# T3 — UI 动作注入 / 删除 +# ============================================================ + +# 内部辅助:从 str | dict | None 的 blocking_reason 输入中归一化取出 code 字符串 +def _extract_blocking_reason_code( + blocking_reason: str | dict[str, Any] | None, +) -> str: + if blocking_reason is None: + return "" + if isinstance(blocking_reason, dict): + # 兼容 order_review_projection 的 dict 格式:{'code': 'xxx', ...} + code = blocking_reason.get("code") or blocking_reason.get("error_code") or blocking_reason.get("blocking_reason") or "" + return str(code or "").strip() + return str(blocking_reason or "").strip() + + +def should_general_retry_be_removed( + *, + retryable_flag: bool, + blocking_reason: str | dict[str, Any] | None, +) -> bool: + """ + 判定是否应该从 available_actions 中移除通用的 "retry_*" 动作。 + + 【AI 触发时机】:order_review_projection、shipping_processing_projection 汇总 available_actions 时。 + 规则:retryable_flag=False 且 blocking_reason 在映射表中 → True;否则保留。 + 兼容 blocking_reason 入参为 dict({'code': 'xxx'})的情况,见测试 T3。 + """ + if bool(retryable_flag): + return False + reason = _extract_blocking_reason_code(blocking_reason) + if not reason: + return False + if reason in BLOCKING_REASON_TO_ACTION_CODES: + return True + # 只要是业务阻断(非 retryable),默认也移除 retry,避免用户点了无意义重试 + return True + + +def derive_blocking_next_actions( + *, + blocking_reason: str | dict[str, Any] | None, +) -> list[str]: + """ + 根据阻断原因输出推荐动作列表(按优先级降序,0~N 个)。 + + 【AI 触发时机】: + Projection 层注入 available_actions 时优先把返回的动作插到最前面; + 空阻断原因返回空列表(不注入任何动作)。 + 兼容 dict 入参,见测试 T3。 + """ + reason = _extract_blocking_reason_code(blocking_reason) + if not reason: + return [] + action = BLOCKING_REASON_TO_ACTION_CODES.get(reason) + if not action: + return ["open_order_review"] + return [action] + + +# ============================================================ +# T4-extra — 复核 Draft 重新校验 Job 的幂等键契约 +# ============================================================ + +def build_review_revalidate_job_ref(case_no: Any, draft_version: Any) -> str: + """ + 构造复核 Draft 重新校验 Job 的 business_ref 幂等键(纯字符串拼接,零依赖)。 + + 【AI 触发时机】: + - Draft 校验失败事件(draft_validated 除外)后入队用; + - Worker 消费 handler 中按同键 dedupe queued/running; + - PATCH /cases//revalidate API 入队幂等键。 + + 同 case_no + 同 draft_version 保证只保留一条有效入队,避免同一版本重复校验刷 Worker。 + """ + return f'review-revalidate:{str(case_no or "").strip()}:v{int(draft_version or 0)}' + + +# ============================================================ +# T4 — 对账链路类型契约 +# ============================================================ + +class ReconcileMatchLevel(str, Enum): + """对账匹配级别(从高到低,优先级顺序决定采用哪条匹配结果)。""" + NONE = "none" + L3 = "L3" # 业务指纹相似 + L2 = "L2" # 文档/PO 关联 + L1 = "L1" # Case.confirmed_task_id / 显式绑定 + + +class ReconcileConfidence(str, Enum): + """匹配置信度,用于前端彩色徽标 & 人工复核筛选。""" + NONE = "none" + LOW = "low" + MEDIUM = "medium" + HIGH = "high" + CERTAIN = "certain" + + +@dataclass +class ReconcileMatchEvidence: + """匹配证据链,便于人工复核追溯判定步骤。""" + case_no: str + match_level_steps: list[dict[str, Any]] = field(default_factory=list) + document_overlap: dict[str, Any] | None = None + fingerprint_similarity: float | None = None + extra: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class ReconcileMatchResult: + """对账查询层统一输出结构。""" + match_level: ReconcileMatchLevel + task_no: str | None + confidence: ReconcileConfidence + evidence: ReconcileMatchEvidence diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index 23efc2a0..79c5281f 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -137,7 +137,7 @@ def write_inventory_export_batch_trigger( source = {**source, **trigger_source} business_connector = str(source.get("connector_type") or "").strip().lower() worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector) - inventory_sources.append({ + item = { "source_code": source.get("source_code"), "connector_type": business_connector, "worker_connector_type": worker_connector, @@ -151,13 +151,20 @@ def write_inventory_export_batch_trigger( "credential_envelope": source.get("credential_envelope") or {}, # 配置测试回调据此将批次结果精确回写到各自站点运行。 "validation_run_no": source.get("validation_run_no"), - }) + } + # v2 逐源身份必须由后端显式写入,Worker 不得重新生成。 + for identity_key in ("task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version", "expected_warehouse_id", "lease_token"): + if source.get(identity_key) is not None: + item[identity_key] = source[identity_key] + inventory_sources.append(item) if not inventory_sources: return None body = { "action": "inventory_export_batch", - "run_no": run_no, + "schema_version": "shipping_inventory_rpa.v2", + "batch_run_no": run_no, + "run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段 "trigger_type": "scheduled", "requested_at": datetime.utcnow().isoformat(), "inventory_sources": inventory_sources, @@ -201,11 +208,22 @@ def write_inventory_export_trigger_for_task( rpa_source.setdefault('credential_envelope', {}) body = dict(payload or {}) if inventory_rpa_batch_enabled(): - run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}" + run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}") + source_item = dict(rpa_source) + source_item.update({ + "task_no": task_no, + "attempt_no": body.get("attempt_no"), + "source_run_no": body.get("source_run_no"), + "candidate_set_id": body.get("candidate_set_id"), + "candidate_set_version": body.get("candidate_set_version"), + "expected_warehouse_id": body.get("expected_warehouse_id"), + "lease_token": body.get("lease_token"), + }) return write_inventory_export_batch_trigger( run_no, - [rpa_source], + [source_item], payload={ + "schema_version": "shipping_inventory_rpa.v2", "trigger_type": "on_demand", "task_no": task_no, **body, diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 4cfb280e..887aae57 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -39,6 +39,7 @@ from app.models import ( ShippingOrderTask, ) from app.services.shipping_notice.processing_projection_invariants import ( + apply_user_projection_fields, derivation_status_for_extraction_run, reconcile_processing_projection_facts, ) @@ -486,6 +487,7 @@ def project_intake_work_item( { 'work_item_type': 'order_intake', 'work_item_no': str(intake.intake_no), + 'has_formal_ot': False, 'source_type': source_type, 'root_order_task_no': None, 'shipping_notice_no': None, @@ -850,11 +852,23 @@ def _order_task_current_gate( or 'order_task_failed' ) if status in {'failed', 'technical_retrying'}: + from app.services.shipping_notice.recovery_contract import ( + derive_blocking_next_actions as _derive_next, + is_tech_retryable_error as _is_tech, + ) + # [Phase 1-4] 以 error_code/blocking_reason_code 统一分类: + # 技术白名单 → retry_failed_documents;业务阻断 → derive_next 的第一个动作。 + blocking_reason_code = error_code + if _is_tech(blocking_reason_code): + next_action = 'retry_failed_documents' + else: + actions = _derive_next(blocking_reason=blocking_reason_code) + next_action = actions[0] if actions else 'open_order_review' return { 'gate_code': 'order_extraction', 'status': 'blocked', - 'next_action_code': 'retry_failed_documents', - 'blocking_reason_code': error_code, + 'next_action_code': next_action, + 'blocking_reason_code': blocking_reason_code, 'attempt_no': 0, } if status in {'review_required', 'waiting_review', 'pending_review'}: @@ -1051,13 +1065,20 @@ def _project_order_task_work_item( if linked_case is not None: case_no = str(getattr(linked_case, 'case_no', None) or '').strip() or None + notice_no_for_task = _notice_no_for_order_task(order_task) + has_formal_ot = bool( + order_task is not None + and getattr(order_task, 'shipping_notice_id', None) is not None + and notice_no_for_task is not None + ) payload = reconcile_processing_projection_facts( { 'work_item_type': 'order_task', 'work_item_no': user_task_no, + 'has_formal_ot': has_formal_ot, 'source_type': source_type, 'root_order_task_no': root_task_no, - 'shipping_notice_no': _notice_no_for_order_task(order_task), + 'shipping_notice_no': notice_no_for_task, 'run_no': run_no, 'case_no': case_no, 'conversation_id': str(run.conversation_id or '').strip() or None, @@ -1098,6 +1119,111 @@ def _project_order_task_work_item( # [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。 record_projection_inconsistency_audit(payload) payload.pop('projection_inconsistency_code', None) + # [T8 用户态 Projection 7 字段] 新增 status/stage/current_gate/blocking_reason/retryable/primary_action/facts, + # 同时保存旧枚举到 legacy_status/stage/current_gate,保证旧客户端兼容。 + payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task) + + # [Phase 3] 当 work_item 关联真实 open_case(未确认 Case 或 candidate_id 回链 Case)→ + # 用共享 bundle 权威覆盖 6 个字段,保证与 Case 详情页两端绝对同源,消除 notice/OT 侧投影漂移。 + # 动作集合按 review_domain_codes 分层:notice/OT 老履约动作保留,建单前裁决动作由 bundle 权威替换。 + if open_case is not None: + try: + from app.services.shipping_notice.reconciliation_projector import ( + REVIEW_DOMAIN_ACTION_CODES, + project_review_case_projection_bundle, + ) + validation_snapshot = None + draft = getattr(open_case, 'current_draft', None) + if draft is not None and getattr(draft, 'validation_result_json', None) is not None: + validation_snapshot = dict(draft.validation_result_json or {}) + post_confirm_snapshot = None + if case_no: + from app.services.shipping_notice.order_review_projection import ( + _project_post_confirm_auto_progress, + ) + post_confirm_snapshot = _project_post_confirm_auto_progress(open_case) + bundle = project_review_case_projection_bundle( + open_case, + validation=validation_snapshot, + post_confirm=post_confirm_snapshot, + is_admin=False, + ) + # 六字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions / retryable + if isinstance(bundle.get('user_status'), str): + 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): + payload['primary_action'] = dict(bundle['primary_action']) + if isinstance(bundle.get('current_gate'), dict): + current_gate = dict(payload.get('current_gate') or {}) + current_gate.update(bundle['current_gate']) + payload['current_gate'] = current_gate + if isinstance(bundle.get('available_actions'), list): + old_actions = list(payload.get('available_actions') or []) + keep_notice_side = [a for a in old_actions if a not in REVIEW_DOMAIN_ACTION_CODES] + bundle_actions = list(bundle['available_actions']) + # 去重合并:notice 侧老动作为基,裁决动作 bundle 权威追加并去重。 + merged: list[str] = [] + for a in [*bundle_actions, *keep_notice_side]: + if a and a not in merged: + merged.append(a) + payload['available_actions'] = merged + retry_flag = bool((bundle.get('automation') or {}).get('retryable')) + if retry_flag or str(payload.get('user_status') or '') == 'retryable': + payload['retryable'] = True + except Exception: # noqa: BLE001 + # 只读投影失败不阻断列表输出(fail-closed 兜底 invariants 结果) + pass + + # 题4A:注入 inventory_preparation 结构化字段(题7A:区分 failed/exhausted_sources); + # 仅当 inventory 阶段或更早、且已挂正式 Notice 时才填充;其他阶段填 None 避免误导。 + inventory_preparation = None + if notice is not None: + try: + from app.services.shipping_notice.task_retry_decision_service import ( + summarize_inventory_rpa_latest_attempts, + ) + + snapshot_src = summarize_inventory_rpa_latest_attempts(notice, include_gate_status=True) + required_sources = list(snapshot_src.get('required_frozen_sources') or []) + prepared_sources = list(snapshot_src.get('prepared_source_codes') or []) + pending_sources = list(snapshot_src.get('pending_source_codes') or []) + failed_sources = list(snapshot_src.get('failed_source_codes') or []) + exhausted_sources = list(snapshot_src.get('exhausted_source_codes') or []) + active_attempt_count = int(snapshot_src.get('active_attempt_count') or 0) + latest_attempts = dict(snapshot_src.get('latest_attempts') or {}) + # 快照载入状态补入 prepared_sources(如果快照就绪且 inventory_lines_json 已保存但 per_source 尚未标记 prepared) + if notice.inventory_lines_json and notice.inventory_snapshot_id: + for code in required_sources: + if code and code not in prepared_sources and code not in pending_sources: + prepared_sources.append(code) + inventory_preparation = { + 'required_sources': required_sources, + 'prepared_sources': prepared_sources, + 'pending_sources': pending_sources, + 'failed_sources': failed_sources, + 'exhausted_sources': exhausted_sources, + 'active_attempt_count': active_attempt_count, + 'latest_attempts': latest_attempts, + 'gate_attempt_active': bool(snapshot_src.get('gate_attempt_active')), + } + except Exception: # noqa: BLE001 + inventory_preparation = None + payload['inventory_preparation'] = inventory_preparation + + # 题4A & 题7A:根据 inventory_preparation 统一折叠 retryable(仅当没有 pending/running + (failed or exhausted) 时,保证可重试为 true; + # 若 active_attempt_count > 0 说明正在执行,强制 retryable=false)。原 retryable 为 false 时不要强行改 true(人工态不改)。 + inv = inventory_preparation + if isinstance(inv, dict): + active = bool(inv.get('active_attempt_count')) or bool(inv.get('gate_attempt_active')) + has_pending = bool(inv.get('pending_sources')) + has_fail = bool(inv.get('failed_sources')) or bool(inv.get('exhausted_sources')) + if active or has_pending: + payload['retryable'] = False + elif has_fail and payload.get('retryable') is not False: + payload['retryable'] = True + return payload @@ -1176,8 +1302,15 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str: Returns: needs_action | processing | completed 之一。 """ + 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() + if user_status in {'waiting_human', 'retryable', 'failed'}: + return 'needs_action' + if user_status in {'completed', 'cancelled'}: + return 'completed' + if user_status == 'running': + return 'processing' if status in {'failed', 'blocked'} or stage == 'waiting_review' or status == 'waiting_review': return 'needs_action' if status == 'completed' or stage == 'completed': @@ -1195,8 +1328,17 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> Returns: 稳定展示码。 """ + 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() + if user_status == 'waiting_human': + return 'pending_review' + if user_status == 'retryable': + return 'failed' + if user_status in {'completed', 'cancelled', 'failed'}: + return user_status + if user_status == 'running': + return 'processing' if status == 'failed': return 'failed' if status == 'waiting_review' or stage == 'waiting_review': @@ -1232,24 +1374,52 @@ 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) - available_actions = list(item.get('available_actions') or []) - primary_action = available_actions[0] if available_actions else 'view_details' run_no = None workflow_no = None + resolved_primary: str | None = None order_task = ( ShippingOrderTask.query.filter_by(task_no=user_task_no).first() if user_task_no else None ) + run = None if order_task is not None and order_task.extraction_run_id: run = db.session.get(ShippingOrderProcessingRun, int(order_task.extraction_run_id)) - if run is not None: - run_no = str(run.run_no or '').strip() or None - from app.services.shipping_notice.conversation_processing_projection import ( - _resolve_workflow_no, + if run is None and user_task_no: + # [ROOT-3 FIX] fallback:拿代表 Run(与旧 embedded 投影同选择规则) + run_candidate = ( + ShippingOrderProcessingRun.query.filter( + ShippingOrderProcessingRun.user_task_no == user_task_no, + ShippingOrderProcessingRun.superseded_by_run_id.is_(None), ) - - workflow_no = _resolve_workflow_no(run) + .order_by( + ShippingOrderProcessingRun.last_activity_at.desc().nullslast(), + ShippingOrderProcessingRun.created_at.desc(), + ) + .first() + ) + if run_candidate is not None: + run = run_candidate + if run is not None: + run_no = str(run.run_no or '').strip() or None + from app.services.shipping_notice.conversation_processing_projection import ( + _resolve_workflow_no, + ) + workflow_no = _resolve_workflow_no(run) + # 会话兼容投影必须直接复用最终 work_item 的用户态字段, + # 不能再回退旧 run 级契约,否则会把 running OT 重新投影成 pending_review。 + available_actions = list(item.get('available_actions') or []) + primary_action_raw = item.get('primary_action') + if isinstance(primary_action_raw, dict): + resolved_primary = str(primary_action_raw.get('code') or '').strip() or None + elif isinstance(primary_action_raw, str): + resolved_primary = str(primary_action_raw or '').strip() or None + if resolved_primary is not None: + primary_action = resolved_primary + elif available_actions: + primary_action = available_actions[0] + else: + primary_action = 'focus_task' return { 'user_task_no': user_task_no, 'submission_ordinal': None, @@ -1433,7 +1603,33 @@ def project_conversation_processing_items( ) work_items: list[dict[str, Any]] = [] - # [STEP 1] OT 是统一进度聚合根;禁止为构造统一投影先执行旧 Run 级会话投影。 + # [LEGACY-UNIFY ROOT-2] STEP 1a:先按旧 conversation_processing_projection 的代表 Run 选择规则 + # (superseded IS NULL + 右侧可见状态白名单 + last_activity_at desc)选 latest_by_task, + # 保证 unified 与旧 embedded 选到同一条代表 Run,杜绝 status_label / run_no 漂移。 + from app.services.shipping_notice.conversation_processing_projection import ( + _RIGHT_PANEL_RUN_STATUSES, + ) + legacy_seed_runs = ( + ShippingOrderProcessingRun.query.filter( + ShippingOrderProcessingRun.user_id == int(user_id), + ShippingOrderProcessingRun.conversation_id == normalized, + ShippingOrderProcessingRun.superseded_by_run_id.is_(None), + ShippingOrderProcessingRun.user_task_no.isnot(None), + ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)), + ) + .order_by( + ShippingOrderProcessingRun.last_activity_at.desc().nullslast(), + ShippingOrderProcessingRun.created_at.desc(), + ) + .all() + ) + latest_by_task: dict[str, ShippingOrderProcessingRun] = {} + for seed_run in legacy_seed_runs: + seed_task_no = str(getattr(seed_run, 'user_task_no', None) or '').strip() + if seed_task_no and seed_task_no not in latest_by_task: + latest_by_task[seed_task_no] = seed_run + + # STEP 1b:会话内 OT 实体列表(保留 updated_at desc 排序,前端卡片顺序仍靠 OT 更新时间) order_tasks = ( ShippingOrderTask.query.filter( ShippingOrderTask.user_id == int(user_id), @@ -1464,7 +1660,7 @@ def project_conversation_processing_items( for task in order_tasks if not task.extraction_run_id and str(task.task_no or '').strip() ] - latest_run_by_task: dict[str, ShippingOrderProcessingRun] = {} + fallback_run_by_task: dict[str, ShippingOrderProcessingRun] = {} if missing_task_nos: fallback_runs = ( ShippingOrderProcessingRun.query.filter( @@ -1480,21 +1676,120 @@ def project_conversation_processing_items( ) for fallback_run in fallback_runs: task_no = str(fallback_run.user_task_no or '').strip() - if task_no and task_no not in latest_run_by_task: - latest_run_by_task[task_no] = fallback_run + if task_no and task_no not in fallback_run_by_task: + fallback_run_by_task[task_no] = fallback_run + # STEP 1c:按 OT 实体顺序投影;[LEGACY-UNIFY ROOT-1] run is None 时不 continue,用 OT 自身字段构造最小 work_item for order_task in order_tasks: task_no = str(order_task.task_no or '').strip() - run = ( - runs_by_id.get(int(order_task.extraction_run_id)) - if order_task.extraction_run_id - else latest_run_by_task.get(task_no) - ) - if run is None: + if not task_no: continue - projected = _project_order_task_work_item(run, order_task=order_task) - if projected is not None: - work_items.append(projected) + # 选 Run 优先级:A) 旧投影等价代表 → B) OT 自身 extraction_run_id → C) 原 fallback + run: ShippingOrderProcessingRun | None = latest_by_task.get(task_no) + if run is None and order_task.extraction_run_id: + run = runs_by_id.get(int(order_task.extraction_run_id)) + if run is None: + run = fallback_run_by_task.get(task_no) + + if run is not None: + projected = _project_order_task_work_item(run, order_task=order_task) + if projected is not None: + work_items.append(projected) + continue + # [ROOT-1 FIX] 找不到任何 Run 上下文:直接用 OT 自身字段构造最小 order_task work_item, + # 保证 work_items / conversation_processing 能输出 OT 语义,不被吞回 intake-only。 + user_task_no = task_no + source_type = 'extraction_run' + stage = ( + str(getattr(order_task, 'stage', None) or '').strip().lower() + or 'candidate_creating' + ) + if stage not in SHIPPING_PROCESSING_STAGES: + stage = 'candidate_creating' + raw_status = str(getattr(order_task, 'status', None) or '').strip().lower() + status = raw_status if raw_status in SHIPPING_PROCESSING_STATUSES else 'processing' + if status == 'completed' and stage != 'completed': + status = 'processing' + notice_min = None + stage_label_key = None + invalidated_from_stage = None + excel_ready = False + if getattr(order_task, 'shipping_notice_id', None): + nid = int(order_task.shipping_notice_id) + notice_min = db.session.get(ShippingNotice, nid) + if notice_min is not None: + from app.services.shipping_notice.order_review_workbench_projection import ( + project_stage_for_task, + ) + shared = project_stage_for_task(notice_min) + shared_code = str(shared.get('code') or '').strip().lower() + if shared_code in SHIPPING_PROCESSING_STAGES: + stage = shared_code + stage_label_key = str(shared.get('label_key') or '').strip() or None + from app.services.shipping_notice.task_workflow import ( + read_notice_invalidated_from_stage, + ) + from app.services.shipping_notice.schema_edit_policy import ( + is_excel_ready_for_task, + ) + invalidated_from_stage = read_notice_invalidated_from_stage(notice_min) + excel_ready = is_excel_ready_for_task(notice_min) + if ( + invalidated_from_stage + and excel_ready + and stage in {'freight_uploading', 'completed'} + ): + invalidated_from_stage = None + if not stage_label_key and stage == 'order_creating': + stage_label_key = 'waiting_system_start' + legacy_actions_min: list[str] = [] + notice_no_min = _notice_no_for_order_task(order_task) + has_formal_ot_min = bool( + getattr(order_task, 'shipping_notice_id', None) is not None + and notice_no_min is not None + ) + payload_min = reconcile_processing_projection_facts( + { + 'work_item_type': 'order_task', + 'work_item_no': user_task_no, + 'has_formal_ot': has_formal_ot_min, + 'source_type': source_type, + 'root_order_task_no': user_task_no, + 'shipping_notice_no': notice_no_min, + 'run_no': None, + 'case_no': None, + 'conversation_id': normalized, + 'submission_no': None, + 'intake_no': None, + 'status': status, + 'stage': stage, + 'stage_label_key': stage_label_key or ( + 'waiting_system_start' if stage == 'order_creating' else stage + ), + 'progress_version': int( + getattr(order_task, 'progress_version', None) or 1 + ), + 'last_activity_at': _iso( + getattr(order_task, 'updated_at', None) + ) or '', + 'current_gate': None, + 'available_actions': legacy_actions_min, + 'source_summary': { + 'filename': None, + 'document_count': 0, + 'document_id': None, + }, + 'child_order_tasks': [], + }, + legacy_actions=legacy_actions_min, + invalidated_from_stage=invalidated_from_stage, + excel_ready=excel_ready, + ) + payload_min.pop('projection_inconsistency_code', None) + payload_min = apply_user_projection_fields( + payload_min, notice=notice_min, order_task=order_task + ) + work_items.append(payload_min) linked_intake_ids = _intake_ids_linked_to_active_ot( user_id=int(user_id), diff --git a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py new file mode 100644 index 00000000..3bd338e0 --- /dev/null +++ b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py @@ -0,0 +1,377 @@ +""" +services/shipping_notice/shipping_recovery_sweeper_service.py + +用途:Shipping Recovery Sweeper 服务——补偿长时间停留在 unreviewed/draft/ready + 且 STP Job 缺失的 Review Case,触发 reconcile → ensure_stp → 入队 STP Job。 +依赖: + - app.db(SQLAlchemy session + text() SQL 执行) + - app.models(ShippingOrderReviewCase、Job) + - app.services.shipping_notice.order_review_auto_progress_coordinator(延迟 import) + - app.services.shipping_notice.recovery_contract(错误分类契约,供后续决策引用) + - app.services.shipping_notice.queue_service(业务 Job 定义,domain/job_type 常量对齐) +逻辑: + _fetch_sweeper_case_candidates 只读 + SKIP LOCKED 语义批量捞取候选 case_id; + shipping_recovery_tick 主入口对每个 case 开 SAVEPOINT + FOR UPDATE SKIP LOCKED + + pg_advisory_xact_lock 后调用 reconcile_single_case_for_auto_progress。 +注意:order_review_auto_progress_coordinator 不在顶层 import,避免与 + order_stp_auto_create_service / order_review_draft_service 形成 + circular import(coord 运行时会延迟 import stp / draft)。 +""" + +from __future__ import annotations + +import logging +from typing import Any + +from flask import current_app +from sqlalchemy import String, and_, cast, exists, func, not_, select, text + +from app import db +from app.models import ( + Job, + ShippingOrderProcessingRun, + ShippingOrderReviewCase, + ShippingOrderReviewDraft, + ShippingNotice, + ShippingProcessExecution, + ShippingTaskInventoryRpaAttempt, +) + +# 注意: +# 1) order_review_auto_progress_coordinator 不在顶层 import,避免 circular import。 +# 2) order_stp_auto_create_service 也不在顶层 import(虽然当前仅用纯函数,但未来 +# stp 可能顶层再 import sweeper / coord,统一延迟更安全)。 +# 两者都延迟 import 到 shipping_recovery_tick / _stp_prefix_expr 调用点。 + +_LOGGER = logging.getLogger(__name__) + + +_STP_JOB_TYPES = ('shipping_stp_auto_create',) +_STP_JOB_DOMAIN = 'shipping_notice' +_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。 + + 核心逻辑:只扫描 active Execution,submit_auto_progress 在 Task 锁 + 部分唯一索引下二次判定, + 因此多个 shipping worker tick 不会为同一 Task 创建两个决策 Job。 + """ + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + + rows = ( + ShippingNotice.query.join( + ShippingProcessExecution, + ShippingNotice.active_process_execution_id == ShippingProcessExecution.id, + ) + .filter( + ShippingProcessExecution.status == 'active', + ShippingNotice.process_status.notin_(('cancelled', 'canceled', 'closed', 'rejected')), + ).limit(50).all() + ) + recovered = 0 + for task in rows: + result = submit_auto_progress(task=task, trigger='recovery_sweeper', commit=False) + if result.get('status') == 'queued' and not result.get('reused'): + recovered += 1 + return recovered + + +def _json_text_expr(json_column, key: str): + """ + 从 PostgreSQL JSON/JSONB 列中提取文本值。 + + 这里统一用 ``->>`` 而不是 ``jsonb_extract_path_text``,因为本项目这些字段当前 + 在数据库里是 ``json`` 列而非 ``jsonb``。``->>`` 对 json/jsonb 都可工作, + 可以避免 worker 启动阶段因函数签名不匹配直接报错退出。 + """ + return json_column.op('->>')(key) + + +def _stp_business_ref_like_expr(*, run_no_expr, document_id_expr): + """ + 构造 STP Job business_ref LIKE 前缀表达式(ORM 层拼,彻底避免 text() 中 + `%doc%` 被 SQLAlchemy 误识别为绑定参数 `:doc` 的坑)。 + + LIKE 语义:``stp-auto::doc-:<任意后缀>%`` + + Args: + run_no_expr: SQL 表达式或列(ShippingOrderProcessingRun.run_no)。 + document_id_expr: SQL 表达式或列(ShippingOrderReviewCase.document_id)。 + + Returns: + LIKE 字符串表达式,可直接放到 ``Job.business_ref.like(...)`` 里。 + """ + # CONCAT 参数顺序:stp-auto: + run_no + :doc- + document_id + : + % + # 每个片段独立传入,PostgreSQL 会自动类型统一,不引入 text() 解析歧义。 + return func.CONCAT( + _STP_PREFIX_HEAD, + _STP_PREFIX_SEGMENT_SEP, + cast(run_no_expr, String), + _STP_PREFIX_SEGMENT_SEP, + 'doc-', + cast(document_id_expr, String), + _STP_PREFIX_SEGMENT_SEP, + '%', + ) + + +def _fetch_sweeper_case_candidates(*, max_age_hours: int = 72) -> list[int]: + """ + 查询符合补偿条件的 ReviewCase 主键列表(只读 + SKIP LOCKED 语义)。 + + 候选条件: + 1. rc.status IN ('unreviewed','draft','ready') + 2. rc.confirmed_task_id IS NULL(尚未绑定建单结果) + 3. rc.updated_at >= NOW() - N 小时(最近活跃,避免扫历史堆) + 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)→ 尊重人工对账边界。 + + 单批上限 LIMIT 50,按 updated_at + id 倒序优先处理最近更新。 + + 【实现决策】: + - 全部用 SQLAlchemy ORM 表达式重写,彻底消除 text() 里 `stp-auto:%:doc-` 被 + SQLAlchemy 误识别为绑定参数 `:doc` 的坑。 + - run_no 来自真实 JOIN shipping_order_processing_runs,不再在 text() 里 LIKE CONCAT + 走错误前缀;与 build_stp_idempotency_key(run_no, document_id, ...) 严格一致。 + + Args: + max_age_hours: 只扫描最近 N 小时内更新过的 Case;默认 72。 + + Returns: + 符合条件的 case_id 列表(按 rc.updated_at DESC, rc.id DESC)。 + """ + rc = ShippingOrderReviewCase.__table__.alias('rc') + d = ShippingOrderReviewDraft.__table__.alias('d') + r = ShippingOrderProcessingRun.__table__.alias('r') + j = Job.__table__.alias('j') + j2 = Job.__table__.alias('j2') + + stp_prefix_like = _stp_business_ref_like_expr( + run_no_expr=r.c.run_no, + document_id_expr=rc.c.document_id, + ) + + # j:queued/running 匹配 → 要求不存在 + active_stp_exists = exists().where(and_( + j.c.domain == _STP_JOB_DOMAIN, + j.c.job_type.in_(_STP_JOB_TYPES), + j.c.status.in_(_STP_ACTIVE_STATUSES), + j.c.business_ref.like(stp_prefix_like), + )) + + # j2:retryable=false 的业务阻断失败 → 要求不存在 + blocking_code_expr = _json_text_expr(j2.c.result_json, 'blocking_reason') + 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), + )) + + status_expr = _json_text_expr(d.c.validation_result_json, 'status') + can_auto_create_expr = _json_text_expr(d.c.validation_result_json, 'can_auto_create') + + stmt = ( + select(rc.c.id) + .select_from(rc.join(d, d.c.id == rc.c.current_draft_id).join(r, r.c.id == rc.c.run_id)) + .where(and_( + rc.c.status.in_(('unreviewed', 'draft', 'ready')), + rc.c.confirmed_task_id.is_(None), + # [注意] 直接 text(f"INTERVAL '{N} HOURS'") 而非 TextClause * int, + # 也不用 cast(str, db.Interval)。max_age_hours 来自 int(config or 72), + # 必为纯数字字面量,不存在 SQL 注入风险;此写法与迁移脚本的 + # "INTERVAL '72 hours'" 字面量完全等价,最稳妥。 + rc.c.updated_at >= func.NOW() - text( + f"INTERVAL '{int(max_age_hours)} HOURS'" + ), + status_expr == 'ready', + cast(can_auto_create_expr, String).cast(db.Boolean).is_(True), + not_(active_stp_exists), + not_(blocking_stp_exists), + )) + .order_by(rc.c.updated_at.desc(), rc.c.id.desc()) + .limit(50) + ) + + rows = db.session.execute(stmt).fetchall() + return [int(row[0]) for row in rows] + + +def shipping_recovery_tick() -> int: + """ + 主入口:执行一轮 Sweeper 补偿,返回本轮成功处理(非跳过)的 Case 数量。 + + 执行步骤: + [STEP 1] 从 Config 读取 SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS, + 调用 _fetch_sweeper_case_candidates 捞取候选 case_id。 + [STEP 2] 逐个 case_id 循环: + * 开 SAVEPOINT(session.begin_nested()) + * SELECT ... FOR UPDATE SKIP LOCKED 按 id 取 Case(被其他 Sweeper/Worker 持有则跳过) + * pg_advisory_xact_lock(hashtext('shipping_stp_sweeper'), :case_id) 事务级咨询锁 + * 调 reconcile_single_case_for_auto_progress(case=case, trigger='recovery_sweeper', + refresh_validation=True) + * commit 当前 savepoint;异常则 rollback savepoint + [STEP 3] 返回成功执行(非 FOR UPDATE SKIP LOCKED 跳过)的 Case 计数。 + + 注意:Sweeper 不直接执行 confirm_review_case / 建单,只负责触发 + reconcile → ensure_stp → 入队 STP Job,与 Q3/Q11 职责边界一致。 + + Returns: + 本轮成功调用 reconcile(即未被 SKIP LOCKED/其它互斥跳过)的 Case 数量。 + """ + max_age_hours = int(getattr( + current_app.config, + 'SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS', + 72, + ) or 72) + + # [STEP 0] 先收敛逐源库存 RPA 的陈旧 queued/running Attempt。 + # shipping-worker 不消费 Windows Trigger 文件;若不在 recovery 周期调用该 + # 扫描,Worker 离线或共享目录失效会让 Attempt 永久停在 queued,前端也会 + # 继续显示“可重试”并造成重复点击。扫描只更新 Attempt 事实,后续投影会 + # 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。 + inventory_timeout_seconds = max(int(getattr( + current_app.config, + 'SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS', + 900, + ) or 900), 1) + inventory_scan_count = _scan_stale_inventory_attempts( + timeout_seconds=inventory_timeout_seconds, + ) + auto_progress_recovered = _recover_auto_progress_jobs() + + # [延迟 import] 放在 tick 主入口首条语句,避免 sweeper 顶层 import coord 时与 + # order_stp_auto_create_service / order_review_draft_service 互导回环。 + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_single_case_for_auto_progress, + ) + + case_ids = _fetch_sweeper_case_candidates(max_age_hours=max_age_hours) + if not case_ids: + _LOGGER.debug( + 'shipping_recovery_tick: no candidate cases inventory_scanned=%s', + inventory_scan_count, + ) + try: + db.session.commit() + except Exception: # noqa: BLE001 + db.session.rollback() + _LOGGER.warning('shipping_recovery_tick: inventory scan commit failed', exc_info=True) + return inventory_scan_count + auto_progress_recovered + + processed_count = 0 + for case_id in case_ids: + nested = db.session.begin_nested() + try: + locked_case = ( + ShippingOrderReviewCase.query + .filter_by(id=int(case_id)) + .with_for_update(skip_locked=True) + .first() + ) + if locked_case is None: + _LOGGER.debug( + 'shipping_recovery_tick: case_id=%s skipped (FOR UPDATE SKIP LOCKED)', + case_id, + ) + nested.rollback() + continue + + db.session.execute(text( + "SELECT pg_advisory_xact_lock(hashtext('shipping_stp_sweeper'), :case_id)" + ), {"case_id": int(case_id)}) + + reconcile_single_case_for_auto_progress( + case=locked_case, + trigger='recovery_sweeper', + refresh_validation=True, + ) + nested.commit() + processed_count += 1 + except Exception as exc: # noqa: BLE001 — 单 Case 异常不阻断本轮 + try: + nested.rollback() + except Exception: # noqa: BLE001 + pass + _LOGGER.warning( + 'shipping_recovery_tick: case_id=%s reconcile failed err=%s', + case_id, + str(exc)[:300], + exc_info=True, + ) + + try: + db.session.commit() + except Exception: # noqa: BLE001 + db.session.rollback() + _LOGGER.warning('shipping_recovery_tick: final session commit failed', exc_info=True) + + _LOGGER.info( + 'shipping_recovery_tick: candidates=%s processed=%s inventory_scanned=%s max_age_hours=%s', + len(case_ids), + processed_count, + inventory_scan_count, + max_age_hours, + ) + return processed_count + inventory_scan_count + auto_progress_recovered + + +def _scan_stale_inventory_attempts(*, timeout_seconds: int) -> int: + """扫描所有活动逐源库存 Attempt,并收敛超时记录。 + + 【AI 触发时机】:shipping worker recovery tick 每轮调用;不负责创建新 + Attempt 或执行 RPA,只负责把无人领取/无回调的事实从 queued/running 收敛 + 为 failed,避免活动锁长期阻止人工重试。 + + Returns: + 本轮收敛的 Attempt 数量。 + """ + task_nos = [ + str(row[0]) + for row in db.session.query(ShippingTaskInventoryRpaAttempt.task_no) + .filter(ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running'))) + .distinct() + .all() + ] + if not task_nos: + return 0 + + from app.services.shipping_notice.per_source_rpa_service import per_source_timeout_scan + + total = 0 + for task in ( + ShippingNotice.query + .filter(ShippingNotice.task_no.in_(task_nos)) + .all() + ): + try: + result = per_source_timeout_scan( + task, + timeout_seconds=timeout_seconds, + session=db.session, + ) + total += int(result.get('timed_out_count') or 0) + except Exception: # noqa: BLE001 — 单任务扫描失败不阻断其它恢复项 + _LOGGER.warning( + 'shipping_recovery_tick: inventory attempt scan failed task_no=%s', + task.task_no, + exc_info=True, + ) + if total: + db.session.flush() + return total diff --git a/backend/app/services/shipping_notice/stp_inventory_freeze.py b/backend/app/services/shipping_notice/stp_inventory_freeze.py index 5bb3799c..96ece045 100644 --- a/backend/app/services/shipping_notice/stp_inventory_freeze.py +++ b/backend/app/services/shipping_notice/stp_inventory_freeze.py @@ -13,6 +13,12 @@ from __future__ import annotations from typing import Any from app.models import ShippingNotice +from app.services.shipping_notice.inventory_candidate_freeze_service import ( + freeze_candidates_for_task, +) +from app.services.shipping_notice.inventory_candidate_projection import ( + get_active_candidate_sources, +) from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication from app.services.shipping_notice.inventory_source_repository import ( get_database_inventory_source, @@ -93,14 +99,6 @@ def freeze_stp_inventory_candidates_on_task( ], }] - payload = dict(task.step_payload_json or {}) - payload['line_inventory_candidates'] = { - 'source_codes': valid_codes, - 'lines': evidence[0]['line_projections'], - 'frozen_at': 'build', - } - task.step_payload_json = payload - if len(valid_codes) == 1 and sources: adjudication = InventorySourceAdjudication( status='resolved', @@ -142,6 +140,23 @@ def freeze_stp_inventory_candidates_on_task( reason='no_valid_candidates_at_build', ) + freeze_result = None + if valid_codes: + freeze_result = freeze_candidates_for_task( + task, + adjudication=adjudication, + line_projections=line_projections, + ) + + payload = dict(task.step_payload_json or {}) + payload['line_inventory_candidates'] = { + 'source_codes': valid_codes, + 'lines': evidence[0]['line_projections'], + 'frozen_at': 'build', + 'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None), + } + task.step_payload_json = payload + apply_inventory_source_adjudication(task, adjudication) # 多候选时 apply 会清空 task.inventory_source_code;保留 line_inventory_candidates。 if adjudication.status == 'candidates_frozen': @@ -150,6 +165,7 @@ def freeze_stp_inventory_candidates_on_task( 'source_codes': valid_codes, 'lines': evidence[0]['line_projections'], 'frozen_at': 'build', + 'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None), } resolution = dict(payload.get('inventory_source_resolution') or {}) resolution['status'] = 'candidates_frozen' @@ -188,6 +204,11 @@ def freeze_stp_inventory_candidates_on_task( }, source='system', ) + # 候选版本冻结完成是正式 AutoProgress 触发源。仅提交当前 Gate,绝不在 + # 建单事务里直接推进库存/RPA/匹配。 + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + + submit_auto_progress(task=task, trigger='candidate_set_frozen', commit=False) return adjudication @@ -201,12 +222,10 @@ def task_frozen_inventory_source_codes(task: ShippingNotice) -> list[str]: Returns: 大写 source_code 列表。 """ - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - frozen = payload.get('line_inventory_candidates') if isinstance(payload.get('line_inventory_candidates'), dict) else {} codes = [ - str(code or '').strip().upper() - for code in (frozen.get('source_codes') or []) - if str(code or '').strip() + str(source.source_code or '').strip().upper() + for source in get_active_candidate_sources(task) + if str(source.source_code or '').strip() ] if codes: return list(dict.fromkeys(codes)) diff --git a/backend/app/services/shipping_notice/stp_line_inventory_match.py b/backend/app/services/shipping_notice/stp_line_inventory_match.py index 0c3a52c1..2633f2ba 100644 --- a/backend/app/services/shipping_notice/stp_line_inventory_match.py +++ b/backend/app/services/shipping_notice/stp_line_inventory_match.py @@ -14,7 +14,12 @@ from __future__ import annotations from decimal import Decimal, InvalidOperation from typing import Any +from app import db from app.models import ShippingOrderSnapshot, ShippingNotice +from app.services.shipping_notice.inventory_candidate_projection import ( + get_active_candidate_lines, + get_active_candidate_set, +) from app.services.shipping_notice.inventory_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, @@ -107,7 +112,9 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: """ 为任务准备全部冻结候选源的有效库存行(打上 __source_code 标签)。 - 核心逻辑:只查询冻结候选;任一候选无 ready 快照则记录 missing;全部缺失则不可匹配。 + 核心逻辑:required = 行级 InventoryCandidateLine 引用到的源;任务级未被任何行引用的源 = + optional(不阻塞 missing 统计)。任一 required 源无 ready 快照则记录 missing; + 全部 required 缺失则不可匹配。 Args: task: 已冻结候选的发货任务。 @@ -118,21 +125,46 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot - codes = task_frozen_inventory_source_codes(task) - if not codes: - single = str(task.inventory_source_code or '').strip().upper() - codes = [single] if single else [] + current_set = get_active_candidate_set(task) + if current_set is None: + return { + 'status': 'blocked', + 'error_code': 'inventory_candidates_missing', + 'candidate_set_id': None, + 'required_source_codes': [], + 'optional_source_codes': [], + 'lines': [], + 'loaded_source_codes': [], + 'missing_source_codes': [], + 'evidence': [], + } + + candidate_lines = get_active_candidate_lines(task) + task_level_codes = list(task_frozen_inventory_source_codes(task)) + required_codes: list[str] = [] + for line in candidate_lines: + for raw in list(getattr(line, 'source_codes_json', None) or []): + code = str(raw or '').strip().upper() + if code and code not in required_codes: + required_codes.append(code) + optional_codes = [c for c in task_level_codes if c not in required_codes] merged: list[dict[str, Any]] = [] missing: list[str] = [] loaded: list[str] = [] evidence: list[dict[str, Any]] = [] - for code in codes: + for code in required_codes + optional_codes: + in_required = code in required_codes source = get_database_inventory_source(code) if source is None: - missing.append(code) - evidence.append({'source_code': code, 'status': 'source_disabled'}) + if in_required: + missing.append(code) + evidence.append({ + 'source_code': code, + 'status': 'source_disabled', + 'required': in_required, + }) continue warehouse_id = ( str(source.get('fixed_warehouse_id') or '').strip().upper() or None @@ -141,8 +173,13 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: ) snapshot = find_latest_ready_snapshot(code, warehouse_id) if snapshot is None: - missing.append(code) - evidence.append({'source_code': code, 'status': 'snapshot_missing'}) + if in_required: + missing.append(code) + evidence.append({ + 'source_code': code, + 'status': 'snapshot_missing', + 'required': in_required, + }) continue lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)] if not lines: @@ -151,11 +188,13 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: except (OSError, ValueError): lines = [] if not lines: - missing.append(code) + if in_required: + missing.append(code) evidence.append({ 'source_code': code, 'status': 'snapshot_empty', 'inventory_file_no': snapshot.inventory_file_no, + 'required': in_required, }) continue for row in lines: @@ -167,43 +206,76 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: evidence.append({ 'source_code': code, 'status': 'loaded', + 'candidate_set_id': int(current_set.id), 'inventory_file_no': snapshot.inventory_file_no, 'line_count': len(lines), + 'required': in_required, }) payload = dict(task.step_payload_json or {}) payload['candidate_inventory_prep'] = { + 'candidate_set_id': int(current_set.id), + 'candidate_set_version': int(current_set.set_version), 'loaded_source_codes': loaded, 'missing_source_codes': missing, + 'optional_source_codes': optional_codes, + 'required_source_codes': required_codes, 'evidence': evidence, } task.step_payload_json = payload - if not merged: + if not merged and required_codes: return { 'status': 'missing_files', + 'candidate_set_id': int(current_set.id), 'lines': [], 'missing_source_codes': missing, 'loaded_source_codes': loaded, 'evidence': evidence, + 'required_source_codes': required_codes, } if missing: return { 'status': 'partial_missing', + 'candidate_set_id': int(current_set.id), 'lines': merged, 'missing_source_codes': missing, 'loaded_source_codes': loaded, 'evidence': evidence, + 'required_source_codes': required_codes, } return { 'status': 'ready', + 'candidate_set_id': int(current_set.id), 'lines': merged, 'missing_source_codes': [], 'loaded_source_codes': loaded, 'evidence': evidence, + 'required_source_codes': required_codes, } +def attach_candidate_scope_to_order_lines( + task: ShippingNotice, + order_lines: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """为订单行附加当前 active CandidateLine 的 allowed_source_codes 快照。""" + candidate_lines = { + int(row.line_no): row + for row in get_active_candidate_lines(task) + } + scoped_lines: list[dict[str, Any]] = [] + for index, line in enumerate(order_lines): + candidate_line = candidate_lines.get(index + 1) + scoped_lines.append({ + **line, + 'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None, + 'candidate_scope_present': candidate_line is not None, + 'allowed_source_codes': list(getattr(candidate_line, 'source_codes_json', None) or []), + }) + return scoped_lines + + def match_order_lines_across_candidates( *, order_lines: list[dict[str, Any]], @@ -255,14 +327,35 @@ def match_order_lines_across_candidates( header_reservation_id=header_reservation_id, ) required = _qty(line.get('quantity') if line.get('quantity') is not None else line.get('__required_qty', line.get('qty'))) + has_candidate_scope = ( + 'allowed_source_codes' in line + or 'candidate_inventory_source_codes' in line + or 'candidate_line_id' in line + or 'candidate_scope_present' in line + ) + allowed_source_codes = [ + str(code or '').strip().upper() + for code in (line.get('allowed_source_codes') or line.get('candidate_inventory_source_codes') or []) + if str(code or '').strip() + ] # [STEP] 订单带单位时只命中同单位库存;双方皆空则退化为料号+预约单。 - source_hits = [ + all_source_hits = [ buckets[key] for key in buckets if key[0] == (effective or '') and key[1] == part and key[2] == unit ] if effective and part else [] + # 正式匹配必须存在结构化 CandidateLine,并严格限制在该行允许源内。 + # 缺少行级范围本身就是候选事实缺失,不能退化为任务级并集匹配。 + source_hits = [ + item for item in all_source_hits + if ( + item['source_code'] in allowed_source_codes + if has_candidate_scope + else True + ) + ] if not effective or not part: disposition = 'not_found' @@ -279,6 +372,24 @@ def match_order_lines_across_candidates( 'resolved_inventory_source_code': None, } has_block = True + elif has_candidate_scope and all_source_hits and not source_hits: + disposition = 'invalid' + result = { + 'line_index': index, + 'part_number': part, + 'reservation_id': effective, + 'unit': unit or None, + 'required_qty': float(required), + 'available_qty': float(sum(item['available_qty'] for item in all_source_hits)), + 'shortage_qty': 0.0, + 'line_status': 'invalid', + 'disposition': disposition, + 'resolved_inventory_source_code': None, + 'candidate_hit_source_codes': [item['source_code'] for item in all_source_hits], + 'out_of_candidate_scope': True, + 'allowed_source_codes_snapshot': list(allowed_source_codes), + } + has_block = True elif len(source_hits) > 1: disposition = 'multi_file_conflict' result = { @@ -362,11 +473,13 @@ def match_order_lines_across_candidates( 'unit': unit or None, 'resolved_inventory_source_code': result.get('resolved_inventory_source_code'), 'candidate_hit_source_codes': result.get('candidate_hit_source_codes'), + 'allowed_source_codes_snapshot': list(allowed_source_codes), + 'out_of_candidate_scope': bool(result.get('out_of_candidate_scope')), 'inventory_file_no': result.get('inventory_file_no'), 'inventory_row_ref': result.get('inventory_row_ref'), }) if float(result.get('shortage_qty') or 0) > 0 or result.get('disposition') in { - 'not_found', 'multi_file_conflict', 'shortage', + 'not_found', 'multi_file_conflict', 'shortage', 'invalid', }: shortages.append(result) diff --git a/backend/app/services/shipping_notice/task_retry_decision_service.py b/backend/app/services/shipping_notice/task_retry_decision_service.py index 120e7840..15eb38b1 100644 --- a/backend/app/services/shipping_notice/task_retry_decision_service.py +++ b/backend/app/services/shipping_notice/task_retry_decision_service.py @@ -87,7 +87,9 @@ def retry_task_with_decision( raise NotFoundError('Not found') decision_version = int(getattr(task, 'order_data_version', None) or 1) - decided = _decide(task, scope=scope_norm, line_key=line) + # 题2B:先检查最新逐源 Attempt 活跃状态(不再依赖 pending_human_reason 滞后字段),避免误判 + latest_active = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True) + decided = _decide(task, scope=scope_norm, line_key=line, latest_active=latest_active) action = str(decided.get('action') or ACTION_NOOP) idempotency_key = _build_idempotency_key( task=task, @@ -96,29 +98,35 @@ def retry_task_with_decision( line_key=line, ) - # [STEP] 幂等:同键活跃运行中直接回放。 - if _is_inventory_rpa_active(task) and action in {ACTION_FETCH_INVENTORY, ACTION_REMATCH, ACTION_AUTO_PROGRESS}: - result = _result_payload( - task=task, - action=ACTION_NOOP, - status=STATUS_RUNNING, - retryable=False, - reason_code='already_running', - decision_version=decision_version, - idempotency_key=idempotency_key, - idempotent_replay=True, - message='已有库存处理在运行', + # [STEP] 幂等:逐源有 queued/running 且本次动作是 fetch/rematch/auto_progress → 直接回放 already_running。 + # 按实际冻结源过滤(仅判断属于 required_frozen_sources 的 pending Attempt)。 + need_inv_rpa = action in {ACTION_FETCH_INVENTORY, ACTION_REMATCH, ACTION_AUTO_PROGRESS} + if need_inv_rpa: + pending_required = bool( + set(latest_active['pending_source_codes']) & set(latest_active['required_frozen_sources'] or []) ) - _audit_decision( - task=task, - user_id=int(user_id), - scope=scope_norm, - line_key=line, - trigger=trigger, - reason=reason, - result=result, - ) - return result + if pending_required or bool(latest_active['gate_attempt_active']): + result = _result_payload( + task=task, + action=ACTION_NOOP, + status=STATUS_RUNNING, + retryable=False, + reason_code='already_running', + decision_version=decision_version, + idempotency_key=idempotency_key, + idempotent_replay=True, + message='已有库存处理在运行', + ) + _audit_decision( + task=task, + user_id=int(user_id), + scope=scope_norm, + line_key=line, + trigger=trigger, + reason=reason, + result=result, + ) + return result executed = _execute( task=task, @@ -128,6 +136,7 @@ def retry_task_with_decision( decision_version=decision_version, idempotency_key=idempotency_key, line_key=line, + trigger=trigger, ) _audit_decision( task=task, @@ -167,12 +176,22 @@ def _decide( *, scope: Scope, line_key: str | None, + latest_active: dict[str, Any] | None = None, ) -> dict[str, Any]: - """按冻结优先级计算 RetryDecision。""" + """按冻结优先级计算 RetryDecision。 + + 【retryable 语义】:表示当前阻塞可通过触发 retry 操作来尝试推进。 + - true:resolve_source / fetch_inventory / rematch 等系统可恢复动作 + - false:running/queued(已在执行)、needs_human(需人工决策)、completed/cancelled(终态) + """ from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable process_status = str(getattr(task, 'process_status', None) or '').strip().lower() pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower() + # 题2B:统一直接用入参 latest_active(调用方已查逐源 Attempt);无入参时回落旧实现 + active = latest_active if isinstance(latest_active, dict) else ( + summarize_inventory_rpa_latest_attempts(task, include_gate_status=True) + ) if process_status in {'completed', 'fulfilled', 'closed', 'cancelled'}: return { @@ -181,7 +200,19 @@ def _decide( 'retryable': False, 'reason_code': 'already_completed', } - if pending in {PH_RPA_PENDING, PH_UPLOAD_PENDING} or _is_inventory_rpa_active(task): + # 库存 RPA 是否运行以逐源 Attempt 为准;pending_human_reason 可能在失败后残留。 + if pending == PH_UPLOAD_PENDING: + return { + 'action': ACTION_NOOP, + 'status': STATUS_RUNNING, + 'retryable': False, + 'reason_code': 'already_running', + } + # task 整单 running(仅 scope=task 模式 & 非 line 单独 rematch 场景可通过(见题3B:line 单独决策里处理 running 不阻塞) + if scope != 'line' and ( + active.get('active_attempt_count', 0) > 0 + or bool(active.get('gate_attempt_active')) + ): return { 'action': ACTION_NOOP, 'status': STATUS_RUNNING, @@ -197,9 +228,7 @@ def _decide( } if scope == 'line' and line_key: - return _decide_for_line(task, line_key=line_key) - - # [STEP] 库存源不稳定:先解析源,不得直接写 RPA。 + return _decide_for_line(task, line_key=line_key, latest_active=active) if not is_inventory_source_stable(task): status = str(getattr(task, 'inventory_source_status', None) or '').strip().lower() if status in {'ambiguous', 'candidates_frozen', 'conflicted', 'unresolved', ''}: @@ -217,20 +246,22 @@ def _decide( 'retryable': False, 'reason_code': 'inventory_source_candidates_need_human', } + # resolve_source:单一候选或歧义已人工消除 → 可通过重试自动推进 return { 'action': ACTION_RESOLVE_SOURCE, 'status': STATUS_RUNNING, - 'retryable': False, + 'retryable': True, 'reason_code': 'inventory_source_unstable', } has_lines = bool(getattr(task, 'inventory_lines_json', None)) snapshot_id = getattr(task, 'inventory_snapshot_id', None) if not has_lines and not snapshot_id: + # fetch_inventory:无有效快照 → 可重试复用文件或触发 RPA return { 'action': ACTION_FETCH_INVENTORY, 'status': STATUS_RUNNING, - 'retryable': False, + 'retryable': True, 'reason_code': 'inventory_snapshot_missing', } @@ -244,10 +275,11 @@ def _decide( 'reason_code': match_hint.get('reason_code') or 'inventory_shortage', } if match_hint.get('needs_rematch'): + # rematch:有有效快照但匹配未完成或执行失败 → 可重试匹配 return { 'action': ACTION_REMATCH, 'status': STATUS_RUNNING, - 'retryable': False, + 'retryable': True, 'reason_code': 'inventory_match_incomplete', } @@ -260,19 +292,35 @@ def _decide( } -def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]: - """行级决策:只处理该行库存事实。""" +def _decide_for_line( + task: ShippingNotice, + *, + line_key: str, + latest_active: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 行级决策(题3B):仅该行需要 fetch_inventory(缺快照)时才按整单 RPA running 互斥; + 若已有 inventory_snapshot_id 存在且该行未完成,直接放行 ACTION_REMATCH, + 不因为其他无关源的 queued/running 阻塞(避免"行A RPA 跑时,行B 明明有快照也不能重匹配"的误判)。 + + 题10A:行 → 依赖库存源映射优先级: + build_eligibility.line_projections[i].candidate_inventory_source_codes 优先, + 为空时回退到任务级冻结源 required_frozen_sources。 + """ from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable from app.services.shipping_notice.line_inventory_match_projection import ( project_line_inventory_view, project_line_retryable, ) + active = latest_active if isinstance(latest_active, dict) else ( + summarize_inventory_rpa_latest_attempts(task, include_gate_status=True) + ) if not is_inventory_source_stable(task): return { 'action': ACTION_RESOLVE_SOURCE, 'status': STATUS_RUNNING, - 'retryable': False, + 'retryable': True, 'reason_code': 'inventory_source_unstable', } @@ -293,6 +341,15 @@ def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]: 'matching_rule_version': getattr(row, 'matching_rule_version', None) if row else None, 'detail_json': dict(getattr(row, 'detail_json', None) or {}) if row else {}, } + # 题10A:先尝试从 build_eligibility 读行候选源(优先),缺省时用任务冻结源作为 line_dependent_codes。 + line_dependent_codes = _line_dependent_inventory_source_codes(task, line_key) + if not line_dependent_codes: + line_dependent_codes = list(active.get('required_frozen_sources') or []) + # 行级 fetch running 判断:仅按 line_dependent_codes & pending_source_codes 交集非空时才算 already_running, + # 或 Gate Attempt 全局在 running。 + inv_running_for_line = bool(set(line_dependent_codes) & set(active.get('pending_source_codes') or [])) + line_running_flag = inv_running_for_line or bool(active.get('gate_attempt_active')) + view = project_line_inventory_view( has_formal_ot=True, fact=fact, @@ -300,7 +357,7 @@ def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]: stored_line_status=None, decision_source=None, can_fulfill_complete_line=False, - inventory_rpa_running=_is_inventory_rpa_active(task), + inventory_rpa_running=line_running_flag, ) user_status = str(view.get('user_line_status') or '') if user_status in {'shortage', 'source_conflict'}: @@ -313,7 +370,7 @@ def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]: if not project_line_retryable( inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []), user_line_status=user_status, - inventory_rpa_running=_is_inventory_rpa_active(task), + inventory_rpa_running=line_running_flag, ): return { 'action': ACTION_NOOP, @@ -323,22 +380,69 @@ def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]: } inv_actions = set(view.get('inventory_allowed_actions') or []) if 'retry_inventory_matching' in inv_actions and view.get('inventory_snapshot_id'): + # 题3B:快照已存在,直接放行 REMATCH,不被其他行/源的 RPA running 阻塞 return { 'action': ACTION_REMATCH, 'status': STATUS_RUNNING, - 'retryable': False, + 'retryable': True, 'reason_code': 'inventory_match_incomplete', 'line_key': line_key, } + # 缺快照,需要 fetch_inventory:如果行依赖的源正好在 running,就阻塞 already_running + if inv_running_for_line or bool(active.get('gate_attempt_active')): + return { + 'action': ACTION_NOOP, + 'status': STATUS_RUNNING, + 'retryable': False, + 'reason_code': 'already_running', + 'line_key': line_key, + } return { 'action': ACTION_FETCH_INVENTORY, 'status': STATUS_RUNNING, - 'retryable': False, + 'retryable': True, 'reason_code': 'inventory_snapshot_missing', 'line_key': line_key, } +def _line_dependent_inventory_source_codes(task: ShippingNotice, line_key: str) -> list[str]: + """题10A:行依赖库存源映射(build_eligibility.line_projections[i].candidate_inventory_source_codes 优先。""" + try: + from app.services.shipping_notice.order_build_eligibility_service import ( + assess_order_build_eligibility as build_fn, + ) + + eligibility = build_fn(task, mode='case_review') + except Exception: # noqa: BLE001 + eligibility = None + out: list[str] = [] + # 常见结构:{ line_projections: [ { line_key, candidate_inventory_source_codes: [] } ] + if isinstance(eligibility, dict): + projections = eligibility.get('line_projections') or eligibility.get('build_eligibility.line_projections') or [] + elif eligibility and hasattr(eligibility, '__iter__'): + projections = getattr(eligibility, 'line_projections') or [] + else: + projections = [] + key = str(line_key or '').strip() + for p in (projections or []): + p_line = str( + p.get('line_key') if isinstance(p, dict) else getattr(p, 'line_key', None) + or '' + ) + if p_line != key: + continue + codes = ( + p.get('candidate_inventory_source_codes') if isinstance(p, dict) + else getattr(p, 'candidate_inventory_source_codes', None) + ) + for code in (codes or []): + c = str(code or '').strip().upper() + if c and c not in out: + out.append(c) + return out + + def _execute( *, task: ShippingNotice, @@ -348,6 +452,7 @@ def _execute( decision_version: int, idempotency_key: str, line_key: str | None, + trigger: str = 'user_retry', ) -> dict[str, Any]: """执行决策动作并映射统一响应。""" from app.services.shipping_notice.inventory_source_gate import ( @@ -405,29 +510,36 @@ def _execute( action = ACTION_FETCH_INVENTORY if action == ACTION_FETCH_INVENTORY: - # 先尝试复用快照;仍无则显式 retry_rpa。 - reused = ensure_inventory({ - 'task_id': task.task_no, - 'mode': 'auto', - 'operator_id': int(user_id), - '_trusted_user_id': int(user_id), - 'event_source': 'workspace_api', - }) - if str((reused or {}).get('status') or '') in {'ok', 'completed'}: - if continue_auto_progress: - return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs) - return _map_tool_result( - reused, - action=ACTION_FETCH_INVENTORY, - base_kwargs=base_kwargs, - message='已复用库存快照', - ) + # 题1C:按调用来源分流。 + # user_retry / user_line_retry:直接 mode='retry_rpa',显式重试无论 auto 是否已 exhausted 都开新 Attempt。 + # conversation_retry / system_auto_progress 等:先 mode='auto' 复用快照,失败再 mode='retry_rpa' 兜底。 + trigger_norm = str(trigger or '').strip().lower() + user_explicit = trigger_norm in {'user_retry', 'user_line_retry'} + if not user_explicit: + reused = ensure_inventory({ + 'task_id': task.task_no, + 'mode': 'auto', + 'operator_id': int(user_id), + '_trusted_user_id': int(user_id), + 'event_source': 'workspace_api', + 'trigger': trigger_norm, + }) + if str((reused or {}).get('status') or '') in {'ok', 'completed'}: + if continue_auto_progress: + return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs) + return _map_tool_result( + reused, + action=ACTION_FETCH_INVENTORY, + base_kwargs=base_kwargs, + message='已复用库存快照', + ) fetched = ensure_inventory({ 'task_id': task.task_no, 'mode': 'retry_rpa', 'operator_id': int(user_id), '_trusted_user_id': int(user_id), 'event_source': 'workspace_api', + 'trigger': trigger_norm, }) return _map_tool_result( fetched, @@ -440,13 +552,28 @@ def _execute( ) if action == ACTION_REMATCH: - matched = shipping_tools.match_inventory({ - 'task_id': task.task_no, - 'operator_id': int(user_id), - '_trusted_user_id': int(user_id), - 'event_source': 'workspace_api', - 'line_key': line_key, - }) + # 题5B:有 line_key → 调用新 match_inventory_line 只对目标行匹配,避免整单重算覆盖其他行; + # 否则(例如 scope=task 且缺快照或整单重算)仍走原 match_inventory。 + norm_line_key = str(line_key or '').strip() + if norm_line_key: + matched = shipping_tools.match_inventory_line( + { + 'task_id': task.task_no, + 'operator_id': int(user_id), + '_trusted_user_id': int(user_id), + 'event_source': 'workspace_api', + 'trigger': trigger_norm, + }, + line_key=norm_line_key, + ) + else: + matched = shipping_tools.match_inventory({ + 'task_id': task.task_no, + 'operator_id': int(user_id), + '_trusted_user_id': int(user_id), + 'event_source': 'workspace_api', + 'trigger': trigger_norm, + }) mapped = _map_tool_result( matched, action=ACTION_REMATCH, @@ -614,14 +741,137 @@ def _build_idempotency_key( def _is_inventory_rpa_active(task: ShippingNotice) -> bool: - """库存 RPA 是否仍在等待。""" - pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower() - process = str(getattr(task, 'process_status', None) or '').strip().lower() - if pending == PH_RPA_PENDING: - return True - if process == 'waiting_inventory' and pending == PH_RPA_PENDING: - return True - return False + """库存 RPA 是否仍在等待(旧兼容实现,等价于 summary.active_attempt_count > 0)。""" + return summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)['active_attempt_count'] > 0 + + +def summarize_inventory_rpa_latest_attempts( + task: ShippingNotice, + *, + include_gate_status: bool = False, +) -> dict[str, Any]: + """ + 汇总逐源库存 RPA Attempt 最新状态(题2B:按冻结源过滤,不再依赖 pending_human_reason 滞后字段)。 + + 【AI 触发时机】:Projection retryable/status 计算、重试决策幂等守卫、already_running 返回时统一读取。 + + 核心逻辑: + [STEP 1] 读取 required_frozen_sources(= Task 级 inventory_source_code 单源 或 T3 冻结多源列表) + [STEP 2] 对每个 required source 查最新 attempt;汇总 prepared / pending / failed / exhausted。 + [STEP 3] active_attempt_count = pending 数量;同时给出 latest_attempts 的结构化视图。 + [STEP 4] 可选 include_gate_status:补充 Process Gate Attempt 的 queued/running。 + """ + from app.models import ( + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, + ShippingTaskInventoryRpaAttempt, + ) + from app.services.shipping_notice.stp_inventory_freeze import ( + task_frozen_inventory_source_codes, + ) + + task_no = str(task.task_no or '').strip() + frozen_sources: list[str] = [ + str(code) for code in (task_frozen_inventory_source_codes(task) or []) if code + ] + if not frozen_sources: + single = str(task.inventory_source_code or '').strip().upper() + if single: + frozen_sources = [single] + required_frozen_sources: list[str] = list(dict.fromkeys(frozen_sources)) + + prepared: list[str] = [] + pending: list[str] = [] + failed: list[str] = [] + exhausted: list[str] = [] + latest_attempts: dict[str, dict[str, Any]] = {} + + if task_no: + # 先一次性查出 (task_no, source_code) → 最新 attempt + rows = ( + ShippingTaskInventoryRpaAttempt.query + .filter(ShippingTaskInventoryRpaAttempt.task_no == task_no) + .order_by( + ShippingTaskInventoryRpaAttempt.source_code.asc(), + ShippingTaskInventoryRpaAttempt.attempt_no.desc(), + ShippingTaskInventoryRpaAttempt.id.desc(), + ) + .all() + ) + latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {} + for row in rows: + key = str(row.source_code or '').strip().upper() or None + if not key or key in latest_by_source: + continue + latest_by_source[key] = row + + for code in required_frozen_sources: + key = str(code or '').strip().upper() or None + if not key: + continue + att = latest_by_source.get(key) + if not att: + latest_attempts[key] = { + 'attempt_no': 0, + 'run_no': None, + 'status': 'not_started', + 'error_code': None, + 'error_message': None, + } + continue + st = str(att.status or '').strip().lower() + latest_attempts[key] = { + 'attempt_no': int(att.attempt_no or 0), + 'run_no': str(att.run_no or '') or None, + 'status': st, + 'error_code': str(att.error_code or '') or None, + 'error_message': str(att.error_message or '') or None, + } + if st in {'queued', 'running'}: + pending.append(key) + elif st in {'succeeded', 'consumed'}: + prepared.append(key) + elif st == 'exhausted': + exhausted.append(key) + failed.append(key) + elif st in {'failed', 'trigger_write_error'}: + failed.append(key) + + active_attempt_count = len(pending) + gate_attempt_active = False + task_id = getattr(task, 'id', None) + if include_gate_status and task_id is not None: + any_active = bool( + db.session.query(ShippingProcessGateAttempt.id) + .join( + ShippingProcessGate, + ShippingProcessGateAttempt.gate_id == ShippingProcessGate.id, + ) + .join( + ShippingProcessExecution, + ShippingProcessGate.execution_id == ShippingProcessExecution.id, + ) + .filter(ShippingProcessGateAttempt.status.in_(('queued', 'running'))) + .filter(ShippingProcessExecution.task_id == int(task_id)) + .limit(1) + .first() + ) + gate_attempt_active = any_active + if any_active and active_attempt_count <= 0: + active_attempt_count = 1 + + return { + 'task_no': task_no or None, + 'required_frozen_sources': required_frozen_sources, + 'prepared_source_codes': prepared, + 'pending_source_codes': pending, + 'failed_source_codes': failed, + 'exhausted_source_codes': exhausted, + 'active_attempt_count': int(active_attempt_count), + 'gate_attempt_active': bool(gate_attempt_active), + 'latest_attempts': latest_attempts, + } def _frozen_or_candidate_codes(task: ShippingNotice) -> list[str]: @@ -695,7 +945,7 @@ def _audit_decision( owner_user_id=int(getattr(task, 'user_id', 0) or user_id), reason_code=str(result.get('reason_code') or '') or None, reason=str(reason or trigger)[:200], - result='success' if result.get('status') != STATUS_FAILED else 'failed', + result='success' if result.get('status') != STATUS_FAILED else 'failure', error_code=str(result.get('reason_code') or '') if result.get('status') == STATUS_FAILED else None, metadata={ 'scope': scope, diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index 52aaec05..178e6ed1 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -192,6 +192,28 @@ def auto_match_enabled() -> bool: return cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True) +def auto_candidate_freeze_enabled() -> bool: + """ + [T10 周一受控测试] 是否在解析确认后自动冻结候选集合。 + 核心语义:路由解析通过 → 立即生成任务级+行级候选,进入 AUTO_INVENTORY_PREPARE; + 关闭则停在 inventory_source_unresolved 待人工确认源。默认 true(受控测试开启)。 + """ + return cfg_bool("SHIPPING_NOTICE_AUTO_CANDIDATE_FREEZE_ENABLED", True) + + +def auto_inventory_prepare_enabled() -> bool: + """ + [T10 周一受控测试] 是否在候选冻结后自动按 source_code 触发 per-source RPA Attempt。 + 关闭则停在 candidates_frozen(等待外部 API 或人工发 Trigger)。默认 true(受控测试开启)。 + """ + return cfg_bool("SHIPPING_NOTICE_AUTO_INVENTORY_PREPARE_ENABLED", True) + + +def auto_generate_excel_enabled() -> bool: + """[T10 周一受控测试] 是否在库存匹配全 matched 后自动调用 generate_excel。默认 true。""" + return cfg_bool("SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED", True) + + def auto_chain_fallback_enabled() -> bool: """Hxops chat 是否在 match 后自动串联 export/upload(全局开关)。""" return cfg_bool("SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK", True) diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index ca596638..2e6e90c6 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -69,6 +69,7 @@ def confirm_temporary_inventory_use(payload: dict): # 履约阶段 match_inventory = fulfillment_workflow.match_inventory +match_inventory_line = fulfillment_workflow.match_inventory_line generate_excel = fulfillment_workflow.generate_excel upload_to_freight = fulfillment_workflow.upload_to_freight rpa_report_upload = fulfillment_workflow.rpa_report_upload diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 33b99f77..555e9a03 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -396,6 +396,9 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: Returns: stp_facts 字典或 None。 """ + from app.services.shipping_notice.inventory_candidate_projection import ( + project_inventory_candidate_facts, + ) from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS @@ -403,25 +406,26 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} status = str(task.inventory_source_status or '').strip() method = str(task.inventory_source_method or '').strip() - candidates = payload.get('line_inventory_candidates') if isinstance(payload.get('line_inventory_candidates'), dict) else {} resolutions_raw = payload.get('line_inventory_resolutions') resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else [] multi_block = bool(payload.get('multi_source_excel_block')) - frozen_codes = list(candidates.get('source_codes') or []) or task_frozen_inventory_source_codes(task) + candidate_projection = project_inventory_candidate_facts(task) + frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(task) has_stp = ( status in {'candidates_frozen', 'resolved'} or method.startswith('stp') or bool(frozen_codes) or bool(resolutions) or multi_block - or bool(payload.get('line_inventory_candidates')) + or bool(candidate_projection.get('current_set')) ) if not has_stp: return None counts: dict[str, int] = {} compact_resolutions: list[dict[str, Any]] = [] - for item in resolutions: + resolution_source = list(candidate_projection.get('line_resolutions') or []) or resolutions + for item in resolution_source: disposition = str(item.get('disposition') or 'unknown') counts[disposition] = counts.get(disposition, 0) + 1 compact_resolutions.append({ @@ -441,6 +445,14 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: 'inventory_source_code': str(task.inventory_source_code or '').strip().upper() or None, 'inventory_source_method': method or None, 'frozen_candidate_codes': [str(code).strip().upper() for code in frozen_codes if str(code or '').strip()], + 'candidate_set_id': candidate_projection.get('candidate_set_id'), + 'candidate_set_version': candidate_projection.get('candidate_set_version'), + 'candidate_set_status': candidate_projection.get('candidate_set_status'), + 'candidate_source_codes': list(candidate_projection.get('candidate_source_codes') or []), + 'prepared_source_codes': list(candidate_projection.get('prepared_source_codes') or []), + 'pending_source_codes': list(candidate_projection.get('pending_source_codes') or []), + 'failed_source_codes': list(candidate_projection.get('failed_source_codes') or []), + 'source_attempts': dict(candidate_projection.get('source_attempts') or {}), 'resolution_counts': counts, 'line_resolutions': compact_resolutions, 'multi_source_excel_block': multi_block, diff --git a/backend/migrations/versions/cp1a2b3c4d5e_add_inventory_candidate_freeze_tables.py b/backend/migrations/versions/cp1a2b3c4d5e_add_inventory_candidate_freeze_tables.py new file mode 100644 index 00000000..9598376f --- /dev/null +++ b/backend/migrations/versions/cp1a2b3c4d5e_add_inventory_candidate_freeze_tables.py @@ -0,0 +1,272 @@ +""" +migrations/versions/cp1a2b3c4d5e_add_inventory_candidate_freeze_tables.py + +用途:决策 C1 —— 库存候选冻结结构化表。新增 3 张表: + shipping_inventory_candidate_sets(候选集合根) + shipping_inventory_candidate_sources(任务级候选源,有序) + shipping_inventory_candidate_lines(行级候选源,source_codes_json 有序列表) + 同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] + 作为不可变审计副本。 +依赖:shipping_notices、shipping_order_review_cases、shipping_process_executions、 + users、shipping_inventory_routing_rules(外键均为 SET NULL / CASCADE,不破坏历史)。 +逻辑:Revises dc9a4a2683df_merge_heads; + 新增表 + 唯一索引 + 部分唯一索引(PostgreSQL WHERE 条件); + 不修改任何已有表字段,纯新增不破坏历史数据。 + +Revision ID: cp1a2b3c4d5e +Revises: dc9a4a2683df +Create Date: 2026-08-07 16:00:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'cp1a2b3c4d5e' +down_revision = 'dc9a4a2683df' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建候选冻结 3 张结构化表及配套索引/约束。""" + + # [STEP 1] 候选集合根(Set) + op.create_table( + 'shipping_inventory_candidate_sets', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('set_version', sa.Integer(), nullable=False, server_default=sa.text('1')), + sa.Column( + 'task_id', + sa.Integer(), + sa.ForeignKey('shipping_notices.id', ondelete='CASCADE'), + nullable=True, + ), + sa.Column( + 'review_case_id', + sa.Integer(), + sa.ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), + nullable=True, + ), + sa.Column( + 'execution_id', + sa.Integer(), + sa.ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), + nullable=True, + ), + sa.Column('frozen_at', sa.DateTime(), nullable=False), + sa.Column( + 'frozen_by_id', + sa.Integer(), + sa.ForeignKey('users.id'), + nullable=True, + ), + sa.Column('input_fingerprint', sa.String(length=64), nullable=False), + sa.Column('routing_rule_version_json', sa.JSON(), nullable=True), + sa.Column('manifest_snapshot_sha256', sa.String(length=64), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('remark', sa.Text(), nullable=True), + # 至少绑定 task 或 review_case 其中之一(跨方言表达式:PG/SQLite 都支持) + sa.CheckConstraint( + 'task_id IS NOT NULL OR review_case_id IS NOT NULL', + name='ck_shipping_inv_cand_sets_binding', + ), + sa.CheckConstraint('set_version >= 1', name='ck_shipping_inv_cand_sets_version'), + ) + # 幂等唯一:同一绑定对象 + 输入指纹相同 = 同一 Set + bind = op.get_bind() + if bind.dialect.name == 'postgresql': + op.execute(sa.text( + 'CREATE UNIQUE INDEX uq_shipping_inv_cand_sets_task_fp ' + 'ON shipping_inventory_candidate_sets (task_id, input_fingerprint) ' + 'WHERE task_id IS NOT NULL' + )) + op.execute(sa.text( + 'CREATE UNIQUE INDEX uq_shipping_inv_cand_sets_review_fp ' + 'ON shipping_inventory_candidate_sets (review_case_id, input_fingerprint) ' + 'WHERE review_case_id IS NOT NULL' + )) + else: + # SQLite / 其他方言:普通唯一索引(NULL 视为 DISTINCT 行为依赖方言,但查询层会判 NULL) + op.create_unique_constraint( + 'uq_shipping_inv_cand_sets_task_fp', + 'shipping_inventory_candidate_sets', + ['task_id', 'input_fingerprint'], + ) + op.create_unique_constraint( + 'uq_shipping_inv_cand_sets_review_fp', + 'shipping_inventory_candidate_sets', + ['review_case_id', 'input_fingerprint'], + ) + op.create_index( + 'ix_shipping_inv_cand_sets_task_frozen', + 'shipping_inventory_candidate_sets', + ['task_id', 'frozen_at'], + ) + op.create_index( + 'ix_shipping_inv_cand_sets_review_frozen', + 'shipping_inventory_candidate_sets', + ['review_case_id', 'frozen_at'], + ) + + # [STEP 2] 任务级候选源(Source),按 candidate_order 有序 + op.create_table( + 'shipping_inventory_candidate_sources', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column( + 'candidate_set_id', + sa.Integer(), + sa.ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), + nullable=False, + ), + sa.Column('source_code', sa.String(length=64), nullable=False), + sa.Column('candidate_order', sa.Integer(), nullable=False), + sa.Column( + 'candidate_origin', + sa.String(length=32), + nullable=False, + server_default=sa.text("'rule'"), + ), + sa.Column( + 'routing_rule_id', + sa.Integer(), + sa.ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), + nullable=True, + ), + sa.Column('routing_rule_version', sa.Integer(), nullable=True), + sa.Column('source_config_version', sa.String(length=64), nullable=True), + sa.Column( + 'override_by_id', + sa.Integer(), + sa.ForeignKey('users.id'), + nullable=True, + ), + sa.Column('override_reason', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint( + 'candidate_set_id', 'source_code', + name='uq_shipping_inv_cand_sources_set_source', + ), + sa.CheckConstraint( + "candidate_origin IN ('rule', 'manual_override')", + name='ck_shipping_inv_cand_sources_origin', + ), + sa.CheckConstraint( + 'candidate_order >= 1', + name='ck_shipping_inv_cand_sources_order', + ), + ) + op.create_index( + 'ix_shipping_inv_cand_sources_set_order', + 'shipping_inventory_candidate_sources', + ['candidate_set_id', 'candidate_order'], + ) + + # [STEP 3] 行级候选源(Line),按 line_no 对齐;source_codes_json 有序列表 + op.create_table( + 'shipping_inventory_candidate_lines', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column( + 'candidate_set_id', + sa.Integer(), + sa.ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), + nullable=False, + ), + sa.Column('line_no', sa.Integer(), nullable=False), + sa.Column('part_number', sa.String(length=128), nullable=True), + sa.Column('reservation_id', sa.String(length=128), nullable=True), + sa.Column('source_codes_json', sa.JSON(), nullable=False, server_default=sa.text("'[]'::json")), + sa.Column( + 'override_by_id', + sa.Integer(), + sa.ForeignKey('users.id'), + nullable=True, + ), + sa.Column('override_reason', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint( + 'candidate_set_id', 'line_no', + name='uq_shipping_inv_cand_lines_set_line', + ), + ) + op.create_index( + 'ix_shipping_inv_cand_lines_set_pn_resv', + 'shipping_inventory_candidate_lines', + ['candidate_set_id', 'part_number', 'reservation_id'], + ) + + +def downgrade() -> None: + """回滚 3 张候选冻结表及索引(纯新增,无破坏性)。""" + + op.drop_index( + 'ix_shipping_inv_cand_lines_set_pn_resv', + table_name='shipping_inventory_candidate_lines', + ) + op.drop_constraint( + 'uq_shipping_inv_cand_lines_set_line', + 'shipping_inventory_candidate_lines', + type_='unique', + ) + op.drop_table('shipping_inventory_candidate_lines') + + op.drop_index( + 'ix_shipping_inv_cand_sources_set_order', + table_name='shipping_inventory_candidate_sources', + ) + op.drop_constraint( + 'ck_shipping_inv_cand_sources_order', + 'shipping_inventory_candidate_sources', + type_='check', + ) + op.drop_constraint( + 'ck_shipping_inv_cand_sources_origin', + 'shipping_inventory_candidate_sources', + type_='check', + ) + op.drop_constraint( + 'uq_shipping_inv_cand_sources_set_source', + 'shipping_inventory_candidate_sources', + type_='unique', + ) + op.drop_table('shipping_inventory_candidate_sources') + + op.drop_index( + 'ix_shipping_inv_cand_sets_review_frozen', + table_name='shipping_inventory_candidate_sets', + ) + op.drop_index( + 'ix_shipping_inv_cand_sets_task_frozen', + table_name='shipping_inventory_candidate_sets', + ) + bind = op.get_bind() + if bind.dialect.name == 'postgresql': + op.execute(sa.text('DROP INDEX IF EXISTS uq_shipping_inv_cand_sets_review_fp')) + op.execute(sa.text('DROP INDEX IF EXISTS uq_shipping_inv_cand_sets_task_fp')) + else: + op.drop_constraint( + 'uq_shipping_inv_cand_sets_review_fp', + 'shipping_inventory_candidate_sets', + type_='unique', + ) + op.drop_constraint( + 'uq_shipping_inv_cand_sets_task_fp', + 'shipping_inventory_candidate_sets', + type_='unique', + ) + op.drop_constraint( + 'ck_shipping_inv_cand_sets_version', + 'shipping_inventory_candidate_sets', + type_='check', + ) + op.drop_constraint( + 'ck_shipping_inv_cand_sets_binding', + 'shipping_inventory_candidate_sets', + type_='check', + ) + op.drop_table('shipping_inventory_candidate_sets') diff --git a/backend/migrations/versions/dq2e3f4g5h6i_add_per_source_inventory_rpa_attempts.py b/backend/migrations/versions/dq2e3f4g5h6i_add_per_source_inventory_rpa_attempts.py new file mode 100644 index 00000000..ef7aa80f --- /dev/null +++ b/backend/migrations/versions/dq2e3f4g5h6i_add_per_source_inventory_rpa_attempts.py @@ -0,0 +1,133 @@ +"""T4 add per-source inventory RPA attempts table + +Revision ID: dq2e3f4g5h6i +Revises: cp1a2b3c4d5e +Create Date: 2026-08-16 10:00:00.000000 + +""" +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = 'dq2e3f4g5h6i' +down_revision = 'cp1a2b3c4d5e' +branch_labels = None +depends_on = None + + +PER_SOURCE_STATUS_VALUES = ( + 'queued', 'running', 'succeeded', 'failed', + 'consumed', 'superseded', 'exhausted', +) + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + 'shipping_task_inventory_rpa_attempts', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('task_no', sa.String(length=64), nullable=False), + sa.Column('source_code', sa.String(length=32), nullable=False), + sa.Column('attempt_no', sa.Integer(), nullable=False), + sa.Column('run_no', sa.String(length=64), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'), + sa.Column('trigger_file_path', sa.String(length=1024), nullable=True), + sa.Column('callback_file_path', sa.String(length=1024), nullable=True), + sa.Column('inventory_file_no', sa.String(length=128), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('error_code', sa.String(length=64), nullable=True), + sa.Column('lease_token', sa.String(length=128), nullable=True), + sa.Column('leased_at', sa.DateTime(timezone=False), nullable=True), + sa.Column('lease_expires_at', sa.DateTime(timezone=False), nullable=True), + sa.Column( + 'callback_payload_json', + postgresql.JSONB(astext_type=sa.Text()), + nullable=False, + server_default=sa.text("'{}'::jsonb"), + ), + sa.Column( + 'extra_json', + postgresql.JSONB(astext_type=sa.Text()), + nullable=False, + server_default=sa.text("'{}'::jsonb"), + ), + sa.Column('triggered_at', sa.DateTime(timezone=False), nullable=True), + sa.Column('callback_received_at', sa.DateTime(timezone=False), nullable=True), + sa.Column('consumed_at', sa.DateTime(timezone=False), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=False), nullable=False, + server_default=sa.func.now()), + sa.Column('updated_at', sa.DateTime(timezone=False), nullable=False, + server_default=sa.func.now()), + # 三元组唯一:同一运行号同一源只允许一条 + sa.UniqueConstraint( + 'task_no', 'source_code', 'run_no', + name='uq_shipping_task_inv_rpa_triplet', + ), + # Attempt status 枚举约束 + sa.CheckConstraint( + "status IN ('queued','running','succeeded','failed','consumed','superseded','exhausted')", + name='ck_shipping_task_inv_rpa_status_enum', + ), + # Attempt 编号 ≥ 1 + sa.CheckConstraint( + 'attempt_no >= 1', + name='ck_shipping_task_inv_rpa_attempt_positive', + ), + sa.PrimaryKeyConstraint('id', name='pk_shipping_task_inv_rpa_attempts'), + ) + + # === PostgreSQL:部分唯一索引 + 高级索引 === + # 活动 Attempt 每源唯一 + op.execute( + """ + CREATE UNIQUE INDEX IF NOT EXISTS uq_shipping_task_inv_rpa_active_per_source + ON shipping_task_inventory_rpa_attempts (task_no, source_code) + WHERE status IN ('queued','running'); + """ + ) + # 常用查询:按 task+source 取最新 attempt + op.create_index( + 'ix_shipping_task_inv_rpa_task_source', + 'shipping_task_inventory_rpa_attempts', + ['task_no', 'source_code', 'attempt_no'], + ) + # 扫描 stale running / queued + op.create_index( + 'ix_shipping_task_inv_rpa_status_updated', + 'shipping_task_inventory_rpa_attempts', + ['status', 'updated_at'], + ) + # task_no 单独索引(回调入口只传 task_no + source_code + run_no) + op.create_index( + 'ix_shipping_task_inv_rpa_task_no', + 'shipping_task_inventory_rpa_attempts', + ['task_no'], + ) + # source_code 单独索引(按源统计 attempt) + op.create_index( + 'ix_shipping_task_inv_rpa_source_code', + 'shipping_task_inventory_rpa_attempts', + ['source_code'], + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + # PostgreSQL 部分唯一索引 + op.execute( + """ + DROP INDEX IF EXISTS uq_shipping_task_inv_rpa_active_per_source; + """ + ) + + op.drop_index('ix_shipping_task_inv_rpa_source_code', table_name='shipping_task_inventory_rpa_attempts') + op.drop_index('ix_shipping_task_inv_rpa_task_no', table_name='shipping_task_inventory_rpa_attempts') + op.drop_index('ix_shipping_task_inv_rpa_status_updated', table_name='shipping_task_inventory_rpa_attempts') + op.drop_index('ix_shipping_task_inv_rpa_task_source', table_name='shipping_task_inventory_rpa_attempts') + + op.drop_table('shipping_task_inventory_rpa_attempts') + # ### end Alembic commands ### diff --git a/backend/migrations/versions/er5f6g7h8i9j_add_line_match_evidence_fields.py b/backend/migrations/versions/er5f6g7h8i9j_add_line_match_evidence_fields.py new file mode 100644 index 00000000..7377bd3a --- /dev/null +++ b/backend/migrations/versions/er5f6g7h8i9j_add_line_match_evidence_fields.py @@ -0,0 +1,58 @@ +"""T6 add line_match_evidence_fields to line inventory matches + +Revision ID: er5f6g7h8i9j +Revises: dq2e3f4g5h6i +Create Date: 2026-08-16 11:00:00.000000 + +""" +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = 'er5f6g7h8i9j' +down_revision = 'dq2e3f4g5h6i' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('shipping_notice_line_inventory_matches', schema=None) as batch_op: + batch_op.add_column(sa.Column('matched_file_no', sa.String(length=128), nullable=True)) + batch_op.add_column(sa.Column('matched_row_index', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('evidence_ref', sa.String(length=512), nullable=True)) + batch_op.add_column( + sa.Column('match_attempt_id', sa.Integer(), sa.ForeignKey( + 'shipping_process_gate_attempts.id', ondelete='SET NULL', + ), nullable=True), + ) + batch_op.create_index( + 'ix_shipping_notice_line_inv_match_matched_file_no', + ['matched_file_no'], unique=False, + ) + batch_op.create_index( + 'ix_shipping_notice_line_inv_match_match_attempt_id', + ['match_attempt_id'], unique=False, + ) + # 证据查询常用组合:按行+file_no 快速定位,避免全表扫描 + batch_op.create_index( + 'ix_shipping_notice_line_inv_match_task_evidence', + ['task_id', 'matched_file_no', 'matched_row_index'], + unique=False, + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('shipping_notice_line_inventory_matches', schema=None) as batch_op: + batch_op.drop_index('ix_shipping_notice_line_inv_match_task_evidence') + batch_op.drop_index('ix_shipping_notice_line_inv_match_match_attempt_id') + batch_op.drop_index('ix_shipping_notice_line_inv_match_matched_file_no') + batch_op.drop_column('match_attempt_id') + batch_op.drop_column('evidence_ref') + batch_op.drop_column('matched_row_index') + batch_op.drop_column('matched_file_no') + # ### end Alembic commands ### diff --git a/backend/migrations/versions/fs1a2b3c4d5e_merge_ct4d_er5f_heads.py b/backend/migrations/versions/fs1a2b3c4d5e_merge_ct4d_er5f_heads.py new file mode 100644 index 00000000..73f144da --- /dev/null +++ b/backend/migrations/versions/fs1a2b3c4d5e_merge_ct4d_er5f_heads.py @@ -0,0 +1,24 @@ +"""merge ct4d5e6f7a8b and er5f6g7h8i9j heads + +Revision ID: fs1a2b3c4d5e +Revises: ct4d5e6f7a8b, er5f6g7h8i9j +Create Date: 2026-08-07 16:30:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'fs1a2b3c4d5e' +down_revision = ('ct4d5e6f7a8b', 'er5f6g7h8i9j') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/migrations/versions/ft1a2b3c4d5e_expand_shipping_order_review_suggestion_v2.py b/backend/migrations/versions/ft1a2b3c4d5e_expand_shipping_order_review_suggestion_v2.py new file mode 100644 index 00000000..d65dd203 --- /dev/null +++ b/backend/migrations/versions/ft1a2b3c4d5e_expand_shipping_order_review_suggestion_v2.py @@ -0,0 +1,150 @@ +""" +expand_shipping_order_review_suggestion_v2 + +Phase 0 DB Schema 变更:为订单复核 LLM 建议表扩展 v2 契约。 + +变更点: + 1. status Check Constraint 新增 gated_failed + 2. evidence_level Check Constraint 新增 L2_row/L3_table/L4_page/L5_document(保留 L2_table/L3_page/L4_pdf 不篡改旧语义) + 3. 新增 8 个 provider & trace 独立列: + provider / provider_conversation_id / provider_message_id + latency_ms / context_hash / evidence_count + context_truncated / auto_upgrade_reason + 4. 新增 3 个索引: + ix_shipping_order_review_suggestions_provider_conversation + ix_shipping_order_review_suggestions_context_hash + ix_shipping_order_review_suggestions_status_created + +策略:历史行保持 NULL / server_default,不回填。旧等级和旧状态不做语义迁移或覆盖。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = 'ft1a2b3c4d5e' +down_revision = 'fs1a2b3c4d5e' +branch_labels = None +depends_on = None + +TABLE_NAME = 'shipping_order_review_suggestions' + +# --------------------------------------------------------------------------- +# Constraint 名称(与模型 __table_args__ 完全一致,drop/create 必须同名) +# --------------------------------------------------------------------------- +CK_STATUS = 'ck_shipping_order_review_suggestions_status' +CK_LEVEL = 'ck_shipping_order_review_suggestions_evidence_level' + +NEW_STATUS_ENUM = ( + "'pending', 'gated_failed', 'validated', 'validation_failed', " + "'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable'" +) +NEW_LEVEL_ENUM = ( + "'L1_field', 'L2_table', 'L3_page', 'L4_pdf', " + "'L2_row', 'L3_table', 'L4_page', 'L5_document'" +) + +IX_PROVIDER_CONV = 'ix_shipping_order_review_suggestions_provider_conversation' +IX_CONTEXT_HASH = 'ix_shipping_order_review_suggestions_context_hash' +IX_STATUS_CREATED = 'ix_shipping_order_review_suggestions_status_created' + + +def upgrade() -> None: + # [STEP 1] status Check Constraint:删除旧版 → 追加新版(含 gated_failed) + op.drop_constraint(CK_STATUS, TABLE_NAME, type_='check') + op.create_check_constraint( + CK_STATUS, + TABLE_NAME, + f"status IN ({NEW_STATUS_ENUM})", + ) + + # [STEP 2] evidence_level Check Constraint:删除旧版 → 追加新版 + op.drop_constraint(CK_LEVEL, TABLE_NAME, type_='check') + op.create_check_constraint( + CK_LEVEL, + TABLE_NAME, + f"evidence_level IN ({NEW_LEVEL_ENUM})", + ) + + # [STEP 3] 新增 8 个独立列;历史保持 NULL / server_default,不回填 + with op.batch_alter_table(TABLE_NAME, schema=None) as batch_op: + batch_op.add_column( + sa.Column('provider', sa.String(length=32), nullable=True), + ) + batch_op.add_column( + sa.Column('provider_conversation_id', sa.String(length=128), nullable=True), + ) + batch_op.add_column( + sa.Column('provider_message_id', sa.String(length=128), nullable=True), + ) + batch_op.add_column( + sa.Column('latency_ms', sa.Integer(), nullable=True), + ) + batch_op.add_column( + sa.Column('context_hash', sa.String(length=64), nullable=True), + ) + batch_op.add_column( + sa.Column( + 'evidence_count', + sa.Integer(), + nullable=False, + server_default=sa.text('0'), + default=0, + ), + ) + batch_op.add_column( + sa.Column( + 'context_truncated', + sa.Boolean(), + nullable=False, + server_default=sa.text('false'), + default=False, + ), + ) + batch_op.add_column( + sa.Column('auto_upgrade_reason', sa.String(length=64), nullable=True), + ) + + # [STEP 4] 新增 3 个索引 + op.create_index(IX_PROVIDER_CONV, TABLE_NAME, ['provider_conversation_id'], unique=False) + op.create_index(IX_CONTEXT_HASH, TABLE_NAME, ['context_hash'], unique=False) + op.create_index(IX_STATUS_CREATED, TABLE_NAME, ['status', 'created_at'], unique=False) + + +def downgrade() -> None: + # [STEP 1] 移除 3 个新索引 + op.drop_index(IX_STATUS_CREATED, table_name=TABLE_NAME) + op.drop_index(IX_CONTEXT_HASH, table_name=TABLE_NAME) + op.drop_index(IX_PROVIDER_CONV, table_name=TABLE_NAME) + + # [STEP 2] 移除 8 个新列 + with op.batch_alter_table(TABLE_NAME, schema=None) as batch_op: + batch_op.drop_column('auto_upgrade_reason') + batch_op.drop_column('context_truncated') + batch_op.drop_column('evidence_count') + batch_op.drop_column('context_hash') + batch_op.drop_column('latency_ms') + batch_op.drop_column('provider_message_id') + batch_op.drop_column('provider_conversation_id') + batch_op.drop_column('provider') + + # [STEP 3] evidence_level Check Constraint:回退到 v1 四枚举 + op.drop_constraint(CK_LEVEL, TABLE_NAME, type_='check') + op.create_check_constraint( + CK_LEVEL, + TABLE_NAME, + "evidence_level IN ('L1_field', 'L2_table', 'L3_page', 'L4_pdf')", + ) + + # [STEP 4] status Check Constraint:回退到 v1,移除 gated_failed + op.drop_constraint(CK_STATUS, TABLE_NAME, type_='check') + op.create_check_constraint( + CK_STATUS, + TABLE_NAME, + ( + "status IN ('pending', 'validated', 'validation_failed', " + "'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable')" + ), + ) diff --git a/backend/migrations/versions/fu2b3c4d5e6f_add_review_revalidate_progress_active_unique.py b/backend/migrations/versions/fu2b3c4d5e6f_add_review_revalidate_progress_active_unique.py new file mode 100644 index 00000000..9dafdc2f --- /dev/null +++ b/backend/migrations/versions/fu2b3c4d5e6f_add_review_revalidate_progress_active_unique.py @@ -0,0 +1,123 @@ +""" +backend/migrations/versions/fu2b3c4d5e6f_add_review_revalidate_progress_active_unique.py + +用途:为 Review Revalidate Progress Job(SHIPPING_REVIEW_REVALIDATE_PROGRESS) + 增加 active(queued/running) 状态下的 domain+job_type+business_ref 部分唯一索引, + 保证同 Case + 同 draft_version 只允许一条异步协调任务在队列中或执行中。 +依赖:Alembic revision ft1a2b3c4d5e;与 STP 的 cq1a2b3c4d5e 结构严格同构。 +逻辑:先合并同 domain/business_ref 的多条 queued/running Revalidate Job(保留最大 id), + 再加部分唯一索引;index_exists / column_exists 幂等,重复执行安全。 + +Revision ID: fu2b3c4d5e6f +Revises: ft1a2b3c4d5e +Create Date: 2026-08-08 01:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = 'fu2b3c4d5e6f' +down_revision = 'ft1a2b3c4d5e' +branch_labels = None +depends_on = None + + +def _index_names(table: str) -> set[str]: + bind = op.get_bind() + inspector = sa.inspect(bind) + return {str(ix.get('name') or '') for ix in inspector.get_indexes(table)} + + +def _dedupe_active_revalidate_jobs() -> None: + """同 domain/business_ref 的多条 queued/running Revalidate Job:保留最大 id,其余标 cancelled。""" + bind = op.get_bind() + groups = bind.execute( + sa.text( + """ + SELECT domain, business_ref + FROM jobs + WHERE job_type = 'shipping_review_revalidate_progress' + AND status IN ('queued', 'running') + AND business_ref IS NOT NULL + GROUP BY domain, business_ref + HAVING COUNT(*) > 1 + """ + ) + ).fetchall() + for row in groups: + domain = str(row[0]) if len(row) > 0 else '' + business_ref = str(row[1]) if len(row) > 1 else '' + ids = [ + int(sub[0]) + for sub in bind.execute( + sa.text( + """ + SELECT id + FROM jobs + WHERE domain = :domain + AND job_type = 'shipping_review_revalidate_progress' + AND business_ref = :business_ref + AND status IN ('queued', 'running') + ORDER BY id DESC + """ + ), + {'domain': domain, 'business_ref': business_ref}, + ).fetchall() + ] + if len(ids) < 2: + continue + keep_id = ids[0] + for drop_id in ids[1:]: + bind.execute( + sa.text( + """ + UPDATE jobs + SET status = 'cancelled', + message = '并发去重:合并 active shipping_review_revalidate_progress', + progress = 100, + locked_by = NULL, + locked_at = NULL, + finished_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP + WHERE id = :drop_id + AND id <> :keep_id + AND status IN ('queued', 'running') + """ + ), + {'drop_id': drop_id, 'keep_id': keep_id}, + ) + + +def upgrade() -> None: + """加 Revalidate active 部分唯一索引;前置去重防唯一冲突。""" + _dedupe_active_revalidate_jobs() + if 'uq_jobs_shipping_review_revalidate_progress_active_ref' not in _index_names('jobs'): + op.create_index( + 'uq_jobs_shipping_review_revalidate_progress_active_ref', + 'jobs', + ['domain', 'job_type', 'business_ref'], + unique=True, + postgresql_where=sa.text( + "domain = 'shipping_notice' " + "AND job_type = 'shipping_review_revalidate_progress' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + sqlite_where=sa.text( + "domain = 'shipping_notice' " + "AND job_type = 'shipping_review_revalidate_progress' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + ) + + +def downgrade() -> None: + """删除 Revalidate active 唯一索引。""" + if 'uq_jobs_shipping_review_revalidate_progress_active_ref' in _index_names('jobs'): + op.drop_index( + 'uq_jobs_shipping_review_revalidate_progress_active_ref', + table_name='jobs', + ) diff --git a/backend/migrations/versions/gv3c4d5e6f7g_add_task_candidate_active_pointer_and_versioned_match.py b/backend/migrations/versions/gv3c4d5e6f7g_add_task_candidate_active_pointer_and_versioned_match.py new file mode 100644 index 00000000..ed33e0de --- /dev/null +++ b/backend/migrations/versions/gv3c4d5e6f7g_add_task_candidate_active_pointer_and_versioned_match.py @@ -0,0 +1,207 @@ +""" +为库存候选增加 active pointer、生命周期与版本化匹配证据字段 + +Revision ID: gv3c4d5e6f7g +Revises: fu2b3c4d5e6f +Create Date: 2026-08-08 22:20:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = 'gv3c4d5e6f7g' +down_revision = 'fu2b3c4d5e6f' +branch_labels = None +depends_on = None + + +def _column_names(table: str) -> set[str]: + inspector = sa.inspect(op.get_bind()) + return {str(col.get('name') or '') for col in inspector.get_columns(table)} + + +def _index_names(table: str) -> set[str]: + inspector = sa.inspect(op.get_bind()) + return {str(ix.get('name') or '') for ix in inspector.get_indexes(table)} + + +def _constraint_names(table: str) -> set[str]: + inspector = sa.inspect(op.get_bind()) + names: set[str] = set() + for item in inspector.get_check_constraints(table): + names.add(str(item.get('name') or '')) + for item in inspector.get_unique_constraints(table): + names.add(str(item.get('name') or '')) + for item in inspector.get_foreign_keys(table): + names.add(str(item.get('name') or '')) + return names + + +def upgrade() -> None: + bind = op.get_bind() + dialect = bind.dialect.name + + shipping_cols = _column_names('shipping_notices') + if 'active_inventory_candidate_set_id' not in shipping_cols: + with op.batch_alter_table('shipping_notices') as batch: + batch.add_column(sa.Column('active_inventory_candidate_set_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_notices_active_inventory_candidate_set_id', + 'shipping_inventory_candidate_sets', + ['active_inventory_candidate_set_id'], + ['id'], + ) + batch.create_index( + 'ix_shipping_notices_active_inventory_candidate_set_id', + ['active_inventory_candidate_set_id'], + unique=False, + ) + + cand_cols = _column_names('shipping_inventory_candidate_sets') + cand_constraints = _constraint_names('shipping_inventory_candidate_sets') + with op.batch_alter_table('shipping_inventory_candidate_sets') as batch: + if 'lifecycle_status' not in cand_cols: + batch.add_column(sa.Column('lifecycle_status', sa.String(length=32), nullable=False, server_default='frozen')) + if 'superseded_at' not in cand_cols: + batch.add_column(sa.Column('superseded_at', sa.DateTime(), nullable=True)) + if 'superseded_by_set_id' not in cand_cols: + batch.add_column(sa.Column('superseded_by_set_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_inv_cand_sets_superseded_by_set_id', + 'shipping_inventory_candidate_sets', + ['superseded_by_set_id'], + ['id'], + ) + if 'invalidated_at' not in cand_cols: + batch.add_column(sa.Column('invalidated_at', sa.DateTime(), nullable=True)) + if 'invalidated_reason' not in cand_cols: + batch.add_column(sa.Column('invalidated_reason', sa.Text(), nullable=True)) + if 'ck_shipping_inv_cand_sets_lifecycle' not in cand_constraints: + batch.create_check_constraint( + 'ck_shipping_inv_cand_sets_lifecycle', + "lifecycle_status IN ('draft', 'frozen', 'superseded', 'invalidated')", + ) + if 'uq_shipping_inv_cand_sets_task_version' not in cand_constraints: + batch.create_unique_constraint( + 'uq_shipping_inv_cand_sets_task_version', + ['task_id', 'set_version'], + ) + + line_cols = _column_names('shipping_inventory_candidate_lines') + if 'source_line_no' not in line_cols: + with op.batch_alter_table('shipping_inventory_candidate_lines') as batch: + batch.add_column(sa.Column('source_line_no', sa.String(length=64), nullable=True)) + + match_cols = _column_names('shipping_notice_line_inventory_matches') + match_constraints = _constraint_names('shipping_notice_line_inventory_matches') + with op.batch_alter_table('shipping_notice_line_inventory_matches') as batch: + if 'candidate_set_id' not in match_cols: + batch.add_column(sa.Column('candidate_set_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_notice_line_inv_match_candidate_set_id', + 'shipping_inventory_candidate_sets', + ['candidate_set_id'], + ['id'], + ) + if 'candidate_set_version' not in match_cols: + batch.add_column(sa.Column('candidate_set_version', sa.Integer(), nullable=True)) + if 'candidate_line_id' not in match_cols: + batch.add_column(sa.Column('candidate_line_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_notice_line_inv_match_candidate_line_id', + 'shipping_inventory_candidate_lines', + ['candidate_line_id'], + ['id'], + ) + if 'allowed_source_codes_snapshot' not in match_cols: + batch.add_column(sa.Column('allowed_source_codes_snapshot', sa.JSON(), nullable=True)) + if 'matched_qty' not in match_cols: + batch.add_column(sa.Column('matched_qty', sa.String(length=32), nullable=True)) + if 'evidence_checksum' not in match_cols: + batch.add_column(sa.Column('evidence_checksum', sa.String(length=64), nullable=True)) + if 'ck_shipping_notice_line_inv_match_result' in match_constraints: + batch.drop_constraint('ck_shipping_notice_line_inv_match_result', type_='check') + if 'ck_shipping_notice_line_inv_match_status' in match_constraints: + batch.drop_constraint('ck_shipping_notice_line_inv_match_status', type_='check') + batch.create_check_constraint( + 'ck_shipping_notice_line_inv_match_result', + "match_result IN ('matched', 'not_found', 'result_missing', 'preparing', 'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable', 'invalid')", + ) + batch.create_check_constraint( + 'ck_shipping_notice_line_inv_match_status', + "inventory_status IN ('ready', 'preparing', 'mapping_failed', 'source_conflict', 'unavailable', 'invalid_key', 'invalid')", + ) + + if dialect != 'sqlite': + op.execute(sa.text( + "UPDATE shipping_inventory_candidate_sets " + "SET lifecycle_status = 'frozen' " + "WHERE lifecycle_status IS NULL OR lifecycle_status = ''" + )) + + +def downgrade() -> None: + with op.batch_alter_table('shipping_notice_line_inventory_matches') as batch: + for name in ( + 'ck_shipping_notice_line_inv_match_result', + 'ck_shipping_notice_line_inv_match_status', + ): + try: + batch.drop_constraint(name, type_='check') + except Exception: + pass + batch.create_check_constraint( + 'ck_shipping_notice_line_inv_match_result', + "match_result IN ('matched', 'not_found', 'result_missing', 'preparing', 'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable')", + ) + batch.create_check_constraint( + 'ck_shipping_notice_line_inv_match_status', + "inventory_status IN ('ready', 'preparing', 'mapping_failed', 'source_conflict', 'unavailable', 'invalid_key')", + ) + for name in ( + 'evidence_checksum', + 'matched_qty', + 'allowed_source_codes_snapshot', + 'candidate_set_version', + 'candidate_line_id', + 'candidate_set_id', + ): + try: + batch.drop_column(name) + except Exception: + pass + + with op.batch_alter_table('shipping_inventory_candidate_lines') as batch: + try: + batch.drop_column('source_line_no') + except Exception: + pass + + with op.batch_alter_table('shipping_inventory_candidate_sets') as batch: + for name in ( + 'uq_shipping_inv_cand_sets_task_version', + 'ck_shipping_inv_cand_sets_lifecycle', + ): + try: + batch.drop_constraint(name, type_='unique' if name.startswith('uq_') else 'check') + except Exception: + pass + for name in ( + 'invalidated_reason', + 'invalidated_at', + 'superseded_by_set_id', + 'superseded_at', + 'lifecycle_status', + ): + try: + batch.drop_column(name) + except Exception: + pass + + with op.batch_alter_table('shipping_notices') as batch: + try: + batch.drop_column('active_inventory_candidate_set_id') + except Exception: + pass diff --git a/backend/migrations/versions/gw4d5e6f7g8h_freeze_inventory_rpa_v2_contract.py b/backend/migrations/versions/gw4d5e6f7g8h_freeze_inventory_rpa_v2_contract.py new file mode 100644 index 00000000..c57ab2c5 --- /dev/null +++ b/backend/migrations/versions/gw4d5e6f7g8h_freeze_inventory_rpa_v2_contract.py @@ -0,0 +1,54 @@ +"""Freeze inventory RPA Attempt identity and callback v2 facts. + +Revision ID: gw4d5e6f7g8h +Revises: gv3c4d5e6f7g +""" +from alembic import op +import sqlalchemy as sa + +revision = 'gw4d5e6f7g8h' +down_revision = 'gv3c4d5e6f7g' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.alter_column( + 'shipping_task_inventory_rpa_attempts', 'run_no', + new_column_name='source_run_no', + existing_type=sa.String(length=64), + existing_nullable=False, + ) + op.drop_constraint('uq_shipping_task_inv_rpa_triplet', 'shipping_task_inventory_rpa_attempts', type_='unique') + op.create_unique_constraint( + 'uq_shipping_task_inv_rpa_triplet', + 'shipping_task_inventory_rpa_attempts', + ['task_no', 'source_code', 'source_run_no'], + ) + op.add_column('shipping_task_inventory_rpa_attempts', sa.Column('callback_id', sa.String(256), nullable=True)) + op.create_unique_constraint('uq_shipping_task_inv_rpa_callback_id', 'shipping_task_inventory_rpa_attempts', ['callback_id']) + for name, typ in ( + ('claimed_at', sa.DateTime(timezone=False)), + ('worker_id', sa.String(128)), + ('execution_phase', sa.String(64)), + ('file_path', sa.String(1024)), + ('file_sha256', sa.String(64)), + ('file_size', sa.Integer()), + ('file_exists_at_callback', sa.Boolean()), + ('transaction_status', sa.String(32)), + ('transaction_error_code', sa.String(128)), + ('transaction_error_message', sa.Text()), + ): + op.add_column('shipping_task_inventory_rpa_attempts', sa.Column(name, typ, nullable=True)) + op.add_column('shipping_task_inventory_rpa_attempts', sa.Column('file_generated', sa.Boolean(), nullable=False, server_default=sa.false())) + + +def downgrade() -> None: + op.drop_column('shipping_task_inventory_rpa_attempts', 'file_generated') + for name in ('transaction_error_message', 'transaction_error_code', 'transaction_status', 'file_exists_at_callback', 'file_size', 'file_sha256', 'file_path', 'execution_phase', 'worker_id', 'claimed_at'): + op.drop_column('shipping_task_inventory_rpa_attempts', name) + op.drop_constraint('uq_shipping_task_inv_rpa_callback_id', 'shipping_task_inventory_rpa_attempts', type_='unique') + op.drop_column('shipping_task_inventory_rpa_attempts', 'callback_id') + op.drop_constraint('uq_shipping_task_inv_rpa_triplet', 'shipping_task_inventory_rpa_attempts', type_='unique') + op.alter_column('shipping_task_inventory_rpa_attempts', 'source_run_no', new_column_name='run_no', existing_type=sa.String(length=128), existing_nullable=False) + op.create_unique_constraint('uq_shipping_task_inv_rpa_triplet', 'shipping_task_inventory_rpa_attempts', ['task_no', 'source_code', 'run_no']) diff --git a/backend/migrations/versions/gx5h6i7j8k9l_add_shipping_auto_progress_p0_3.py b/backend/migrations/versions/gx5h6i7j8k9l_add_shipping_auto_progress_p0_3.py new file mode 100644 index 00000000..ce48a9d8 --- /dev/null +++ b/backend/migrations/versions/gx5h6i7j8k9l_add_shipping_auto_progress_p0_3.py @@ -0,0 +1,155 @@ +"""Add P0-3 shipping AutoProgress execution scope and Task singleton outbox. + +Revision ID: gx5h6i7j8k9l +Revises: gw4d5e6f7g8h +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'gx5h6i7j8k9l' +down_revision = 'gw4d5e6f7g8h' +branch_labels = None +depends_on = None + + +def _columns(table: str) -> set[str]: + """读取表字段名,使迁移可安全重跑于已有测试数据库。""" + return {str(row['name']) for row in sa.inspect(op.get_bind()).get_columns(table)} + + +def _indexes(table: str) -> set[str]: + """读取现有索引名,避免历史环境重复创建。""" + return {str(row.get('name') or '') for row in sa.inspect(op.get_bind()).get_indexes(table)} + + +def _foreign_keys(table: str) -> dict[tuple[str, ...], str]: + """读取本地字段到外表的外键映射,用于修正候选集 Task 聚合根。""" + return { + tuple(str(name) for name in item.get('constrained_columns') or []): str(item.get('referred_table') or '') + for item in sa.inspect(op.get_bind()).get_foreign_keys(table) + } + + +def upgrade() -> None: + """增加正式编排作用域、Execution 版本绑定和活动 Job 数据库唯一约束。""" + # 早期候选迁移误将实际 ShippingNotice.id 绑定到 shipping_order_tasks;SQLite 不强制 + # FK 会掩盖此问题,但 PostgreSQL 会阻断正式 P0-3 Candidate/Execution 围栏。 + candidate_fks = _foreign_keys('shipping_inventory_candidate_sets') + if candidate_fks.get(('task_id',)) == 'shipping_order_tasks': + with op.batch_alter_table('shipping_inventory_candidate_sets') as batch: + batch.drop_constraint( + next( + str(item.get('name') or '') + for item in sa.inspect(op.get_bind()).get_foreign_keys('shipping_inventory_candidate_sets') + if tuple(item.get('constrained_columns') or []) == ('task_id',) + ), + type_='foreignkey', + ) + batch.create_foreign_key( + 'fk_shipping_inv_cand_sets_task_id', 'shipping_notices', ['task_id'], ['id'], ondelete='CASCADE', + ) + + job_columns = _columns('jobs') + with op.batch_alter_table('jobs') as batch: + for name, target in ( + ('task_id', 'shipping_notices.id'), + ('execution_id', 'shipping_process_executions.id'), + ('gate_id', 'shipping_process_gates.id'), + ('candidate_set_id', 'shipping_inventory_candidate_sets.id'), + ): + if name not in job_columns: + batch.add_column(sa.Column(name, sa.Integer(), nullable=True)) + batch.create_foreign_key(f'fk_jobs_{name}', target.split('.')[0], [name], ['id']) + if 'fencing_token' not in job_columns: + batch.add_column(sa.Column('fencing_token', sa.String(length=64), nullable=True)) + + execution_columns = _columns('shipping_process_executions') + with op.batch_alter_table('shipping_process_executions') as batch: + if 'candidate_set_id' not in execution_columns: + batch.add_column(sa.Column('candidate_set_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_process_executions_candidate_set_id', + 'shipping_inventory_candidate_sets', ['candidate_set_id'], ['id'], + ) + if 'execution_revision' not in execution_columns: + batch.add_column(sa.Column( + 'execution_revision', sa.Integer(), nullable=False, server_default='1', + )) + + notice_columns = _columns('shipping_notices') + if 'active_process_execution_id' not in notice_columns: + with op.batch_alter_table('shipping_notices') as batch: + batch.add_column(sa.Column('active_process_execution_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_notices_active_process_execution_id', + 'shipping_process_executions', ['active_process_execution_id'], ['id'], + ) + batch.create_index('ix_shipping_notices_active_process_execution_id', ['active_process_execution_id']) + + # 兼容旧链的历史 status,同时为 P0-3 supersede/cancel 增加合法值;不收紧旧状态集合。 + with op.batch_alter_table('shipping_process_executions') as batch: + batch.drop_constraint('ck_shipping_process_executions_status', type_='check') + batch.create_check_constraint( + 'ck_shipping_process_executions_status', + "status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed', 'superseded')", + ) + batch.create_index('ix_shipping_process_executions_candidate_set', ['candidate_set_id', 'status']) + with op.batch_alter_table('shipping_process_gates') as batch: + batch.drop_constraint('ck_shipping_process_gates_status', type_='check') + batch.create_check_constraint( + 'ck_shipping_process_gates_status', + "status IN ('pending', 'queued', 'running', 'passed', 'blocked_retryable', " + "'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped', 'cancelled')", + ) + + index_names = _indexes('jobs') + if 'uq_jobs_shipping_auto_progress_one_active_task' not in index_names: + op.create_index( + 'uq_jobs_shipping_auto_progress_one_active_task', 'jobs', ['task_id'], unique=True, + postgresql_where=sa.text( + "domain = 'shipping_notice' AND job_type = 'shipping_auto_progress' " + "AND status IN ('queued', 'running') AND task_id IS NOT NULL" + ), + sqlite_where=sa.text( + "domain = 'shipping_notice' AND job_type = 'shipping_auto_progress' " + "AND status IN ('queued', 'running') AND task_id IS NOT NULL" + ), + ) + + +def downgrade() -> None: + """回退 P0-3 新增字段和索引;历史状态约束恢复为原始集合。""" + try: + op.drop_index('uq_jobs_shipping_auto_progress_one_active_task', table_name='jobs') + except Exception: + pass + with op.batch_alter_table('shipping_process_gates') as batch: + batch.drop_constraint('ck_shipping_process_gates_status', type_='check') + batch.create_check_constraint( + 'ck_shipping_process_gates_status', + "status IN ('pending', 'queued', 'running', 'passed', 'blocked_retryable', " + "'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped')", + ) + with op.batch_alter_table('shipping_process_executions') as batch: + batch.drop_constraint('ck_shipping_process_executions_status', type_='check') + batch.create_check_constraint( + 'ck_shipping_process_executions_status', + "status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed')", + ) + batch.drop_index('ix_shipping_process_executions_candidate_set') + batch.drop_column('execution_revision') + batch.drop_constraint('fk_shipping_process_executions_candidate_set_id', type_='foreignkey') + batch.drop_column('candidate_set_id') + with op.batch_alter_table('shipping_notices') as batch: + batch.drop_index('ix_shipping_notices_active_process_execution_id') + batch.drop_constraint('fk_shipping_notices_active_process_execution_id', type_='foreignkey') + batch.drop_column('active_process_execution_id') + with op.batch_alter_table('jobs') as batch: + for name in ('candidate_set_id', 'gate_id', 'execution_id', 'task_id'): + batch.drop_constraint(f'fk_jobs_{name}', type_='foreignkey') + batch.drop_column(name) + batch.drop_column('fencing_token') diff --git a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py b/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py new file mode 100644 index 00000000..2802b4de --- /dev/null +++ b/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py @@ -0,0 +1,143 @@ +""" +tests/services/shipping_notice/test_inventory_candidate_projection.py + +用途:验证正式 Task 的 active CandidateSet 读取、缺失阻断与版本化候选事实投影。 +依赖:Flask app fixture、ShippingNotice / CandidateSet / CandidateLine ORM、候选 projector。 +逻辑:覆盖 active pointer 缺失 fail-closed、当前版本 facts 输出,以及 stale 匹配阻断。 +""" + +from __future__ import annotations + +from app import db +from app.models import ( + ShippingInventoryCandidateLine, + ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, + ShippingNotice, + ShippingNoticeLineInventoryMatch, +) +from app.services.shipping_notice.inventory_candidate_projection import ( + project_inventory_candidate_facts, +) +from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines + + +def _task(task_no: str) -> ShippingNotice: + task = ShippingNotice( + task_no=task_no, + process_status='created', + source_type='manual', + ) + db.session.add(task) + db.session.flush() + return task + + +def _candidate_set(task: ShippingNotice, version: int = 1) -> ShippingInventoryCandidateSet: + row = ShippingInventoryCandidateSet( + task_id=int(task.id), + set_version=version, + lifecycle_status='frozen', + input_fingerprint=f'fp-{task.task_no}-{version}', + ) + db.session.add(row) + db.session.flush() + task.active_inventory_candidate_set_id = int(row.id) + db.session.flush() + return row + + +def test_prepare_candidate_inventory_lines_blocks_without_active_set(app): + with app.app_context(): + task = _task('SN-CAND-001') + db.session.commit() + + result = prepare_candidate_inventory_lines(task) + + assert result['status'] == 'blocked' + assert result['error_code'] == 'inventory_candidates_missing' + assert result['candidate_set_id'] is None + + +def test_project_inventory_candidate_facts_reads_current_structured_set(app): + with app.app_context(): + task = _task('SN-CAND-002') + candidate_set = _candidate_set(task, version=2) + source = ShippingInventoryCandidateSource( + candidate_set_id=int(candidate_set.id), + source_code='DBS_DUB', + candidate_order=1, + candidate_origin='rule', + ) + line = ShippingInventoryCandidateLine( + candidate_set_id=int(candidate_set.id), + line_no=1, + source_line_no='00010', + part_number='PN-1', + reservation_id='3000092917', + source_codes_json=['DBS_DUB'], + ) + db.session.add_all([source, line]) + db.session.commit() + + facts = project_inventory_candidate_facts(task, include_history=True) + + assert facts['candidate_set_id'] == candidate_set.id + assert facts['candidate_set_version'] == 2 + assert facts['candidate_set_status'] == 'frozen' + assert facts['candidate_source_codes'] == ['DBS_DUB'] + assert facts['lines'][0]['candidate_line_id'] == line.id + assert facts['lines'][0]['line_no'] == 1 + assert facts['lines'][0]['source_line_no'] == '00010' + assert facts['history'][0]['version'] == 2 + + +def test_project_inventory_candidate_facts_marks_stale_current_match(app): + with app.app_context(): + task = _task('SN-CAND-003') + old_set = _candidate_set(task, version=1) + old_line = ShippingInventoryCandidateLine( + candidate_set_id=int(old_set.id), + line_no=1, + source_codes_json=['DBS_OLD'], + ) + db.session.add(old_line) + db.session.flush() + new_set = ShippingInventoryCandidateSet( + task_id=int(task.id), + set_version=2, + lifecycle_status='frozen', + input_fingerprint='fp-new', + ) + db.session.add(new_set) + db.session.flush() + task.active_inventory_candidate_set_id = int(new_set.id) + db.session.flush() + new_line = ShippingInventoryCandidateLine( + candidate_set_id=int(new_set.id), + line_no=1, + source_codes_json=['DBS_NEW'], + ) + db.session.add(new_line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=int(task.id), + line_key='line-1', + line_index=0, + candidate_set_id=int(old_set.id), + candidate_set_version=1, + candidate_line_id=int(old_line.id), + match_result='matched', + inventory_status='ready', + inventory_source_code='DBS_OLD', + is_current=True, + allowed_source_codes_snapshot=['DBS_OLD'], + detail_json={'disposition': 'ok'}, + )) + db.session.commit() + + facts = project_inventory_candidate_facts(task) + + assert facts['blocking_reason']['code'] == 'inventory_candidate_version_stale' + assert facts['candidate_set_id'] == new_set.id + assert facts['line_resolutions'][0]['candidate_set_id'] == old_set.id diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py new file mode 100644 index 00000000..29324bc5 --- /dev/null +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -0,0 +1,381 @@ +""" +tests/services/shipping_notice/test_reconciliation_phase34_contract.py + +用途:Phase 3 统一 Projection 四事实 + Phase 4 管理端 replay 权限 + + BRANCH F ownership_anomaly rollback 的合同测试。 +依赖:recovery_contract、reconciliation_projector、 + reconciliation_service.reconcile_and_progress(mock 掉 DB 层仅验证纯函数矩阵)。 +逻辑: + [P3 T1] project_case_automation_status 与原 order_review_projection._project_case_automation_status + 的纯状态映射完全对齐(status 七值归一化、retryable 双写、can_auto_create 同源)。 + [P3 T2] project_case_allowed_actions 白名单:业务阻断码 → REMOVE_SET 删除 retry; + reconcile_and_progress 注入;derive_blocking_next_actions 裁决动作。 + [P3 T3] project_case_user_status 七值映射矩阵(completed/cancelled/waiting_human/ + retryable/failed/running/idle)。 + [P3 T4] project_case_primary_action 1a~1i CTA 分派矩阵。 + [P3 T5] project_review_case_projection_bundle 六字段非空(Case + automation + actions)。 + [P4 T6] reconcile_and_progress PRE-CHECK: + a) replay_mode=True + is_admin=False → SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED 422 + b) legacy_job_id=999 + is_admin=False → 422 + [P4 T7] ownership_anomaly BRANCH F: + 断言触发路径最终 outcome=ownership_anomaly_rejected 且不会脏写 + (这里只测 ValidationError 降级情形 hasattr(case,process_status)=False)。 +全部为 pure_unit 或 DB 无关单测,不启动 Flask/Worker,不写 DB。 +""" + +from __future__ import annotations + +import uuid +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + + +# ============================================================ +# 工具:用 SimpleNamespace 构造伪 Model(避免 DB 依赖) +# ============================================================ + + +def _fake_case(**kwargs): + base = { + 'id': 1, + 'case_no': 'CASE-2608-0042', + 'status': 'draft', + 'disposition': None, + 'candidate_id': None, + 'confirmed_task_id': None, + 'document_id': 42, + 'owner_user_id': 7, + 'current_draft': None, + 'run': None, + 'updated_at': None, + } + base.update(kwargs) + return SimpleNamespace(**base) + + +def _fake_job(job_id=928, status='failed', domain='shipping_notice', job_type='shipping_stp_auto_create', + reference_key='CASE-2608-0042', result_json=None): + return SimpleNamespace( + id=job_id, + status=status, + domain=domain, + job_type=job_type, + reference_key=reference_key, + reference_type='shipping_order_review_case_no', + result_json=result_json if isinstance(result_json, dict) else {}, + ) + + +# ============================================================ +# [P3 T1~T5] 纯投影器四事实同源矩阵 +# ============================================================ + +@pytest.mark.pure_unit +@pytest.mark.parametrize( + 'automation_status,retryable_flag,expected_user_status,label', + [ + # 七值映射 T3 + ('completed', False, 'completed', '已完成 → completed'), + ('queued', False, 'running', '入队中 → running'), + ('running', False, 'running', '运行中 → running'), + ('waiting_to_start', False, 'running', '等待启动 → running(系统已负责)'), + ('failed', False, 'failed', '业务阻断失败 → failed'), + ('manual_fallback', True, 'retryable', 'manual_fallback retryable → retryable'), + ('failed', True, 'retryable', '技术失败 retryable → retryable'), + ('idle', False, 'idle', 'Idle → idle(默认)'), + ], + ids=lambda t: t[3] if isinstance(t, tuple) else '', +) +def test_p3_t3_user_status_seven_value_matrix(automation_status, retryable_flag, expected_user_status, label): + """[P3 T3] project_case_user_status 七值归一化与 Q12 invariants 一致。""" + from app.services.shipping_notice.reconciliation_projector import project_case_user_status + + case = _fake_case(status='draft') + automation = {'status': automation_status, 'retryable': bool(retryable_flag)} + got = project_case_user_status(case, automation) + assert got == expected_user_status, label + + +@pytest.mark.pure_unit +@pytest.mark.parametrize( + 'bcode,actions_in,retryable,expected_pa_code,variant,label', + [ + # T4.1a ownership_anomaly → contact_admin + ('ownership_anomaly_xxx', ['view', 'contact_admin'], False, 'contact_admin', 'danger', '1a anomaly → contact_admin'), + # T4.1b duplicate → reconcile_and_progress + ('duplicate_decision_required', ['view', 'reconcile_and_progress', 'adjudicate_duplicate'], False, 'reconcile_and_progress', 'primary', '1b duplicate → reconcile_and_progress'), + ('SHIPPING.NOTICE_EXACT_DUPLICATE', ['view', 'reconcile_and_progress'], False, 'reconcile_and_progress', 'primary', '1b exact dup → reconcile_and_progress'), + # T4.1c profile_schema_mismatch → open_profile_review + ('profile_schema_mismatch', ['view', 'open_profile_review'], False, 'open_profile_review', 'warning', '1c profile mismatch → open_profile_review'), + # T4.1d retryable → retry_stp_auto_create + ('stp_job_failed', ['view', 'retry_stp_auto_create'], True, 'retry_stp_auto_create', 'primary', '1d retryable → retry_stp'), + ], + ids=lambda t: t[6] if isinstance(t, tuple) else '', +) +def test_p3_t4_primary_action_matrix(bcode, actions_in, retryable, expected_pa_code, variant, label): + """[P3 T4] project_case_primary_action 1a~1i 分派正确性。""" + from app.services.shipping_notice.reconciliation_projector import ( + BlockingReason, + UserStatus, + project_case_primary_action, + ) + + user_status: UserStatus = 'failed' if bcode in {'profile_schema_mismatch'} else ( + 'retryable' if retryable else 'waiting_human' + ) + blocking: BlockingReason = BlockingReason(code=bcode, i18n_key=None, details=None) + got = project_case_primary_action(user_status, blocking, list(actions_in)) + assert got is not None, label + assert got['code'] == expected_pa_code, label + assert got['variant'] == variant, label + + +@pytest.mark.pure_unit +def test_p3_t2_allowed_actions_inject_reconcile_and_remove_retry(): + """[P3 T2] 业务阻断 → REMOVE_SET 删除 retry_stp_auto_create 且注入 reconcile_and_progress。""" + from app.services.shipping_notice.reconciliation_projector import project_case_allowed_actions + from app.services.shipping_notice.recovery_contract import REMOVE_ACTIONS_WHEN_BLOCKED + + case = _fake_case(status='draft', candidate_id=1) + automation = { + 'status': 'failed', + 'retryable': False, # 业务阻断 + 'blocking_reason': 'duplicate_decision_required', + 'reason_code': 'duplicate_decision_required', + } + actions = project_case_allowed_actions(case, automation=automation, is_admin=False) + # REMOVE_SET:retry_stp_auto_create / retry / retry_parse 必须剔除 + for forbidden in REMOVE_ACTIONS_WHEN_BLOCKED: + assert forbidden not in actions + # 注入 reconcile_and_progress(统一对账入口) + assert 'reconcile_and_progress' in actions + # 派生裁决动作 adjudicate_duplicate 必须注入 + assert 'adjudicate_duplicate' in actions + + +@pytest.mark.pure_unit +def test_p3_t5_bundle_six_fields_shapes(): + """[P3 T5] bundle 必返回六个只读字段,结构符合 TypedDict 契约。""" + from app.services.shipping_notice.reconciliation_projector import ( + project_review_case_projection_bundle, + ) + + case = _fake_case(status='draft', candidate_id=None) + bundle = project_review_case_projection_bundle( + case, + validation={'can_build': True, 'can_auto_create': True, 'status': 'needs_review'}, + post_confirm=None, + is_admin=False, + ) + for field in ( + 'automation', 'available_actions', 'current_gate', + 'blocking_reason', 'primary_action', 'user_status', + ): + assert field in bundle, f'bundle missing {field}' + assert isinstance(bundle['automation'], dict) + assert isinstance(bundle['available_actions'], list) + assert isinstance(bundle['current_gate'], dict) + assert isinstance(bundle['blocking_reason'], dict) + assert isinstance(bundle['user_status'], str) + # primary_action 可能是 None(极端兜底),但不能是未预期类型 + assert bundle['primary_action'] is None or isinstance(bundle['primary_action'], dict) + + +# ============================================================ +# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询) +# ============================================================ + +def _mock_case_for_p4(case_no='CASE-2608-0042'): + case = _fake_case(status='draft', case_no=case_no, candidate_id=None, confirmed_task_id=None) + case.current_draft = SimpleNamespace( + draft_version=1, + issue_summary_json=[], + validation_result_json={'can_build': True, 'can_auto_create': True}, + ) + case.run = SimpleNamespace( + run_no='RUN-2608-0042', + schema_version_id=1, + id=9, + ) + return case + + +def _install_minimal_mocks(monkeypatch, case=None): + if case is None: + case = _mock_case_for_p4() + + # 1) _require_current_user 的行为在 service 层不被用(函数直接传 user_id/case_no) + # 2) monkeypatch FOR UPDATE 查询和 get_review_case_visible_to_user + from app.services.shipping_notice import reconciliation_service as mod + from app.models import User + + class _CaseQuery: + def filter_by(self, **_kw): + return self + + def filter(self, *_a, **_kw): + return self + + def order_by(self, *_a, **_kw): + return self + + def with_for_update(self): + return self + + def first(self): + return case + + class _UserQuery: + def filter_by(self, **_kw): + return self + + def first(self): + return None + + def _fake_get(coll, _id): # noqa: ARG001 + if coll is User: + return SimpleNamespace(id=1, role='user', email='u@example.com') + return None + + def _fake_visible(case_no, user_id, is_admin): # noqa: ARG001 + return case + + monkeypatch.setattr(mod.ShippingOrderReviewCase, 'query', _CaseQuery()) + monkeypatch.setattr(mod, 'get_review_case_visible_to_user', _fake_visible) + # 避免 Job.query / db.session.get / CaseEvent 等深层调用触发 + monkeypatch.setattr(mod.db.session, 'get', _fake_get) + monkeypatch.setattr(mod.db, 'session', MagicMock( + commit=lambda: None, + rollback=lambda: None, + flush=lambda: None, + add=lambda _x: None, + )) + # L1-L3 对账直接返回 NONE(避免 hit 真 DB) + mod.query_case_task_ownership = lambda *_a, **_kw: { # type: ignore[method-assign] + 'match_level': 'NONE', + 'confidence': 'LOW', + 'task_no': None, + 'candidate_matches': [], + 'evidence': {}, + 'match_level_steps': [], + } + mod._case_version = lambda _c: 1 # type: ignore[attr-defined] + mod._check_idempotency = lambda **kw: (str(uuid.uuid4()), None) # type: ignore[attr-defined] + mod._candidate_refresh_resume_stp_flow = lambda **kw: ({}, None, 'not_eligible') # type: ignore[attr-defined] + mod._write_reconcile_audit_and_event = lambda **kw: None # type: ignore[attr-defined] + return case + + +@pytest.mark.pure_unit +def test_p4_t6a_replay_mode_without_admin_raises(monkeypatch): + """[P4 T6a] replay_mode=True + is_admin=False → 422 SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED。""" + from app.core.errors import ValidationError + from app.services.shipping_notice.reconciliation_service import reconcile_and_progress + + _install_minimal_mocks(monkeypatch) + with pytest.raises(ValidationError) as exc: + reconcile_and_progress( + user_id=1, + case_no='CASE-2608-0042', + operation_id=str(uuid.uuid4()), + user_action='auto', + is_admin=False, + replay_mode=True, + ) + assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED' + + +@pytest.mark.pure_unit +def test_p4_t6b_legacy_job_id_without_admin_raises(monkeypatch): + """[P4 T6b] legacy_job_id=928 + is_admin=False → 422 权限拒绝。""" + from app.core.errors import ValidationError + from app.services.shipping_notice.reconciliation_service import reconcile_and_progress + + _install_minimal_mocks(monkeypatch) + with pytest.raises(ValidationError) as exc: + reconcile_and_progress( + user_id=1, + case_no='CASE-2608-0042', + operation_id=str(uuid.uuid4()), + user_action='auto', + is_admin=False, + legacy_job_id=928, + ) + assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED' + + +@pytest.mark.pure_unit +def test_p4_t6c_legacy_job_requires_failed_or_dead(monkeypatch): + """[P4 T6c] legacy_job 必须是 failed/dead,否则 422。""" + from app.core.errors import ValidationError + from app.services.shipping_notice.reconciliation_service import reconcile_and_progress + + _install_minimal_mocks(monkeypatch) + bad_job = _fake_job(job_id=991, status='running') # 不是失败态 + + from app.services.shipping_notice import reconciliation_service as mod + + def _get(coll, jid): # noqa: ARG001 + if str(getattr(coll, '__name__', '')) == 'Job' and jid == 991: + return bad_job + return None + + monkeypatch.setattr(mod.db.session, 'get', _get) + with pytest.raises(ValidationError): + reconcile_and_progress( + user_id=1, + case_no='CASE-2608-0042', + operation_id=str(uuid.uuid4()), + user_action='auto', + is_admin=True, + legacy_job_id=991, + ) + + +# ============================================================ +# [P4 T7] BRANCH F ownership_anomaly 422 降级(process_status 不存在) +# ============================================================ + +@pytest.mark.pure_unit +def test_p4_t7_branch_f_ownership_anomaly_throws_validation(monkeypatch): + """[P4 T7] L3 + reuse_existing 命中 BRANCH F → 抛 422 hard_isolation=True。""" + from app.core.errors import ValidationError + from app.services.shipping_notice.reconciliation_service import reconcile_and_progress + + case = _mock_case_for_p4() + _install_minimal_mocks(monkeypatch, case=case) + + from app.services.shipping_notice import reconciliation_service as mod + + # 让 L3 → ownership_anomaly:L3 + user_action=reuse_existing (太模糊) + mod.query_case_task_ownership = lambda *_a, **_kw: { # type: ignore[method-assign] + 'match_level': 'L3', + 'confidence': 'LOW', + 'task_no': None, + 'candidate_matches': [], + 'evidence': {'reason': 'too_ambiguous_for_reuse_existing'}, + 'match_level_steps': [ + {'step': 'L1_EXACT', 'matched': False}, + {'step': 'L2_FP', 'matched': False}, + {'step': 'L3_AMBIGUOUS', 'matched': True}, + ], + } + # 关键:模拟 ReviewCase 没有 process_status 列 → BRANCH F 必须抛 422(而非软返回 outcome) + assert not hasattr(case, 'process_status') + + with pytest.raises(ValidationError) as exc: + reconcile_and_progress( + user_id=1, + case_no='CASE-2608-0042', + operation_id=str(uuid.uuid4()), + user_action='reuse_existing', # 非 adjudicate → BRANCH F + is_admin=True, + ) + assert exc.value.code == 'SHIPPING.RECONCILE_OWNERSHIP_ANOMALY' + details = getattr(exc.value, 'details', None) or {} + assert details.get('hard_isolation') is True + assert details.get('match') is not None + # 回滚已调用:验证 db.session.rollback 至少被触发了 1 次(硬隔离验证) + assert mod.db.session.rollback.call_count >= 1 # type: ignore[union-attr] diff --git a/backend/tests/services/shipping_notice/test_recovery_contract_phase1.py b/backend/tests/services/shipping_notice/test_recovery_contract_phase1.py new file mode 100644 index 00000000..50a20318 --- /dev/null +++ b/backend/tests/services/shipping_notice/test_recovery_contract_phase1.py @@ -0,0 +1,158 @@ +""" +tests/services/shipping_notice/test_recovery_contract_phase1.py + +用途:Phase 1 合同测试 — 锁定错误分类白名单与阻断→动作映射的纯函数矩阵。 +依赖:recovery_contract(is_tech_retryable_error、build_stp_job_blocked_manual_result、 + should_general_retry_be_removed、derive_blocking_next_actions)。 +逻辑:纯单元测,不依赖 DB/Worker,确保 T1 错误分类矩阵与 T3 动作注入判定 + 与 Phase 1 冻结契约一致;一旦白名单/阻断规则被误修改将立即红。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.recovery_contract import ( + RECOVERY_CONTRACT_VERSION, + BLOCKING_REASON_TO_ACTION_CODES, + REMOVE_ACTIONS_WHEN_BLOCKED, + build_stp_job_blocked_manual_result, + build_stp_job_failed_transient_result, + derive_blocking_next_actions, + is_tech_retryable_error, + should_general_retry_be_removed, +) + + +# ============================================================ +# T1:is_tech_retryable_error 白名单矩阵(fail-closed) +# ============================================================ + +T1_MATRIX = [ + # (error_code, category_hint, expected_retryable, case_label) + ('SHIPPING.TRANSIENT_NETWORK_TIMEOUT', None, True, 'TRANSIENT_ 前缀 → 技术临时网络'), + ('SHIPPING.TRANSIENT_STORAGE_CONNECTION', None, True, 'TRANSIENT_ 前缀 → 技术存储'), + ('SHIPPING.WORKER_TIMEOUT_LEASE_EXPIRED', None, True, 'WORKER_TIMEOUT_ 前缀'), + ('worker_timeout', 'worker_timeout', True, 'category_hint=worker_timeout'), + ('queue_unavailable', 'queue_unavailable', True, 'category_hint=queue_unavailable'), + ('temporary_network_error', 'temporary_network_error', True, 'category_hint 网络临时'), + ('temporary_storage_error', 'temporary_storage_error', True, 'category_hint 存储临时'), + ('external_service_5xx', 'external_service_5xx', True, 'category_hint 外部 5xx'), + ('lease_expired', 'lease_expired', True, 'category_hint 租约过期'), + # 业务阻断码:默认不可重试(Q5 白名单制,不在即拒绝) + ('SHIPPING.NOTICE_EXACT_DUPLICATE', None, False, '精确重复 — 业务阻断,不可重试'), + ('SHIPPING.STP_NOT_ELIGIBLE', None, False, 'STP 资格不足 — 业务阻断'), + ('SHIPPING.REVIEW_DRAFT_MISSING', None, False, '草稿缺失 — 业务阻断'), + ('SHIPPING.REVIEW_RUN_MISSING', None, False, 'Run 缺失 — 业务阻断'), + ('SHIPPING.REVIEW_DOCUMENT_INVALID', None, False, '文档无效 — 业务阻断'), + ('SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT', None, False, '版本冲突 — 业务阻断,应 409 让前端刷新'), + ('profile_schema_mismatch', None, False, 'Profile 模板不匹配 — 业务阻断'), + ('final_required_field_missing', None, False, '关键字段缺失 — 业务阻断'), + ('duplicate_decision_required', None, False, '等待重复裁决 — 业务阻断'), + # 空码/未知码:fail-closed(默认不可重试,不能因空码回退到 retryable=true) + ('', None, False, '空码 → fail-closed 不可重试'), + ('RANDOM.UNKNOWN_ERROR_XYZ', None, False, '未知码 → fail-closed 不可重试'), + (None, None, False, 'None 码 → fail-closed 不可重试'), + # category_hint 与前缀冲突:前缀优先(空码除外) + ('SHIPPING.TRANSIENT_NETWORK', 'worker_timeout', True, '前缀命中即使 hint 不同也可重试'), +] + + +@pytest.mark.parametrize('error_code, category_hint, expected, label', T1_MATRIX, ids=[m[3] for m in T1_MATRIX]) +def test_t1_is_tech_retryable_error_matrix(error_code, category_hint, expected, label): + """T1:错误码 → 是否允许技术自动重试(白名单制,fail-closed)。""" + _ = label + assert is_tech_retryable_error(error_code, category_hint=category_hint) is expected + + +# ============================================================ +# T1-ext:build_stp_job_*_result 的结构契约(Q4 Job.result_json schema) +# ============================================================ + +def test_t1_blocked_manual_result_shape(): + """阻塞业务错误 → result_json 必含 retryable=false / blocking_reason / next_action。""" + result = build_stp_job_blocked_manual_result( + error_code='SHIPPING.NOTICE_EXACT_DUPLICATE', + message='该文件已存在进行中任务', + next_action='adjudicate_duplicate', + details={'source_content_hash': 'abc123', 'existing_task_no': 'OT-2026-0001'}, + ) + assert result['status'] == 'failed' + assert result['retryable'] is False + assert result['blocking_reason'] == 'SHIPPING.NOTICE_EXACT_DUPLICATE' + assert result['blocking_reason_details'] == { + 'source_content_hash': 'abc123', 'existing_task_no': 'OT-2026-0001', + } + assert result['next_action'] == 'adjudicate_duplicate' + assert result['error_code'] == 'SHIPPING.NOTICE_EXACT_DUPLICATE' + assert result['message'] == '该文件已存在进行中任务' + assert result['contract_version'] == RECOVERY_CONTRACT_VERSION + assert 'decision_trace' in result + + +def test_t1_transient_result_shape(): + """技术临时错误 → retryable=true,blocking_reason/next_action 置空。""" + result = build_stp_job_failed_transient_result( + error_code='SHIPPING.TRANSIENT_NETWORK_TIMEOUT', + message='Dify API 503', + category_hint='external_service_5xx', + ) + assert result['status'] == 'failed' + assert result['retryable'] is True + assert result['blocking_reason'] is None + assert result['next_action'] is None + assert result['contract_version'] == RECOVERY_CONTRACT_VERSION + + +# ============================================================ +# T3:should_general_retry_be_removed + derive 动作矩阵(Q9 后端注入/删除动作) +# ============================================================ + +T3_MATRIX = [ + # (retryable, blocking_code, expected_remove, expected_inject_action, label) + (True, None, False, None, '纯技术失败 → 保留 retry,不注入裁决'), + (False, 'duplicate_decision_required', True, 'adjudicate_duplicate', '重复待决 → 删除 retry + 注入 adjudicate'), + (False, 'SHIPPING.NOTICE_EXACT_DUPLICATE', True, 'adjudicate_duplicate', '精确重复 → 同上'), + (False, 'profile_schema_mismatch', True, 'open_profile_review', 'Profile 不匹配 → 打开模板复核'), + (False, 'SHIPPING.STP_NOT_ELIGIBLE', True, 'open_order_review', 'STP 不满足 → 打开订单复核'), + (False, 'SHIPPING.REVIEW_DRAFT_MISSING', True, 'open_order_review', '草稿缺失 → 打开订单复核'), + (False, 'final_required_field_missing', True, 'open_order_review', '字段缺失 → 打开订单复核'), +] + + +@pytest.mark.parametrize( + 'retryable, bcode, expected_remove, expected_action, label', + T3_MATRIX, ids=[m[4] for m in T3_MATRIX], +) +def test_t3_retry_removed_and_actions_injected(retryable, bcode, expected_remove, expected_action, label): + """T3:业务阻断时删除通用 retry 动作,并注入对应的裁决/复核动作。""" + _ = label + blocking_reason = {'code': bcode} if bcode else None + assert should_general_retry_be_removed( + retryable_flag=retryable, + blocking_reason=blocking_reason, + ) is expected_remove + + if bcode: + derived = derive_blocking_next_actions(blocking_reason=blocking_reason) + if expected_action is not None: + assert expected_action in derived + # REMOVE_ACTIONS_WHEN_BLOCKED 必须包含 retry_stp_auto_create(原 Job 928/929 的主重试入口) + assert 'retry_stp_auto_create' in REMOVE_ACTIONS_WHEN_BLOCKED + assert 'retry' in REMOVE_ACTIONS_WHEN_BLOCKED + assert 'retry_parse' in REMOVE_ACTIONS_WHEN_BLOCKED + + +def test_t3_contract_version_anchor_frozen(): + """契约锚点版本号固定:Phase 1 必须与 shipping-recovery-v1-phase1 对齐,便于审计与迁移。""" + assert RECOVERY_CONTRACT_VERSION == 'shipping-recovery-v1-phase1' + # BLOCKING_REASON_TO_ACTION_CODES 必显式含 6 条核心映射,不能因重构丢失 + for key in ( + 'duplicate_decision_required', + 'SHIPPING.NOTICE_EXACT_DUPLICATE', + 'profile_schema_mismatch', + 'SHIPPING.STP_NOT_ELIGIBLE', + 'SHIPPING.REVIEW_DRAFT_MISSING', + 'final_required_field_missing', + ): + assert key in BLOCKING_REASON_TO_ACTION_CODES diff --git a/backend/tests/test_shipping_auto_progress_controller_phase1.py b/backend/tests/test_shipping_auto_progress_controller_phase1.py new file mode 100644 index 00000000..d00caea4 --- /dev/null +++ b/backend/tests/test_shipping_auto_progress_controller_phase1.py @@ -0,0 +1,556 @@ +""" +tests/test_shipping_auto_progress_controller_phase1.py + +用途:锁定 Shipping Notice 第一阶段(AutoProgress Controller)9 项后端核心合同与 5 项 + Projection 前端行为合同。覆盖:GET 纯读、系统协调器、Draft 校验、客户自动确认、 + Worker 重启 Sweeper 补偿、并发幂等唯一、duplicate 阻断禁止普通 retry、 + 取消 Case 不得复活、迟到回调不得复活、stp_enqueue_missing/worker_unavailable + 细粒度 Projection 注入。 +依赖:pytest、SimpleNamespace/mock、reconciliation_service.assert_case_not_blocked_manual、 + recovery_contract.should_general_retry_be_removed、order_review_customer_service + 下的 project_review_case_customer_resolution(纯读验证)、 + order_review_auto_progress_coordinator、shipping_recovery_sweeper_service、 + case_retry_auto_progress_service、reconciliation_projector。 +逻辑:不启动真实 Worker、不连 PostgreSQL advisory lock;使用 unittest.mock 对 DB 查询、 + enqueue、外部协调器依赖打桩,验证函数内部「事实 → 动作 → 审计」的函数级契约。 +""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + + +TERMINAL_CASE_STATUSES = frozenset({ + 'confirmed', 'confirming', 'non_order', 'superseded', + 'quality_issue', 'reparse_pending', +}) + + +# ========================================================================= +# 后端核心合同(9 项) +# ========================================================================= + + +def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app): + """合同 1:抽取完成 + 资格 ready → 系统 Run 协调器 → STP Job 幂等入队。""" + from app.services.shipping_notice import order_review_auto_progress_coordinator as coord + + run = SimpleNamespace(id=10, run_no='SNER-COORD-1') + case = SimpleNamespace( + id=1, + case_no='SORC-P1-01', + status='draft', + confirmed_task_id=None, + document_id=100, + candidate_id=10, + run_id=10, + run=run, + owner_user_id=1, + current_draft=SimpleNamespace( + draft_version=1, + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + issue_summary_json=[], + header_values_json={}, + lines_json=[], + ), + ) + with patch( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.' + 'ShippingOrderReviewCase', + ) as RC_Mock, patch( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.db', + ), patch.object( + coord, '_customer_step_for_case', return_value={'status': 'skipped_no_shadow'}, + ), patch.object( + coord, 'validate_draft', return_value={'status': 'ready'}, + ), patch.object( + coord, 'ensure_stp_auto_create_for_case', + return_value={'status': 'queued', 'job_id': 1201, + 'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'}, + ) as ensure_mock: + RC_Mock.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [ + SimpleNamespace(id=1), + ] + RC_Mock.query.filter_by.return_value.order_by.return_value.with_entities.return_value.get.return_value = case + RC_Mock.query.get.return_value = case + from sqlalchemy.orm import Session + type(RC_Mock.query).get = staticmethod(lambda *a, **k: case) + with patch.object(coord.db, 'session', MagicMock(spec=Session)) as sess_mock: + sess_mock.get.return_value = case + result = coord.reconcile_run_review_cases_for_auto_progress(run=run) + + assert isinstance(result, list) and len(result) >= 1 + item = result[0] + assert item.get('case_no') == 'SORC-P1-01' + ensure_mock.assert_called_once() + assert item.get('enqueue_status') in {'queued', 'already_queued', 'reused', 'enqueued'} + assert item.get('job_id') == 1201 + + +def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app): + """合同 2:Draft 校验后资格 ready → 单 Case 协调器 → STP 入队。""" + from app.services.shipping_notice import order_review_auto_progress_coordinator as coord + + case = SimpleNamespace( + id=2, + case_no='SORC-P1-02', + status='draft', + confirmed_task_id=None, + document_id=200, + candidate_id=20, + run_id=20, + run=SimpleNamespace(id=20, run_no='SNER-20'), + owner_user_id=1, + current_draft=SimpleNamespace( + draft_version=3, + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + issue_summary_json=[], + header_values_json={}, + lines_json=[], + ), + ) + with patch( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.db', + ), patch.object( + coord, '_customer_step_for_case', return_value={'status': 'skipped'}, + ), patch.object( + coord, 'validate_draft', return_value={'status': 'ready'}, + ), patch.object( + coord, 'ensure_stp_auto_create_for_case', + return_value={'status': 'queued', 'job_id': 2202, 'idempotency_key': 'k-02'}, + ) as ensure_mock: + result = coord.reconcile_single_case_for_auto_progress( + case=case, trigger='draft_validated', refresh_validation=True, + ) + + ensure_mock.assert_called_once() + assert result['enqueue_status'] == 'queued' + assert result['case_no'] == 'SORC-P1-02' + + +def test_contract_03_customer_auto_confirmed_runs_coordinator(app): + """合同 3:客户 Shadow 自动确认 → 协调器客户步骤 → validate → STP 入队。""" + from app.services.shipping_notice import order_review_auto_progress_coordinator as coord + + case = SimpleNamespace( + id=3, case_no='SORC-P1-03', status='unreviewed', confirmed_task_id=None, + document_id=300, candidate_id=30, run_id=30, + run=SimpleNamespace(id=30, run_no='SNER-30'), owner_user_id=1, + current_draft=SimpleNamespace( + draft_version=2, + validation_result_json={'can_build': True, 'can_auto_create': False, 'status': 'draft'}, + issue_summary_json=[], header_values_json={}, lines_json=[], + ), + ) + + def _customer_step(c, actor_type_hint=None): + del c, actor_type_hint + case.current_draft.validation_result_json = { + 'can_build': True, 'can_auto_create': True, 'status': 'ready', + } + return {'status': 'auto_confirmed', 'customer_id': 5555} + + with patch( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.db', + ), patch.object( + coord, '_customer_step_for_case', side_effect=_customer_step, + ), patch.object( + coord, 'validate_draft', return_value={'status': 'ready'}, + ), patch.object( + coord, 'ensure_stp_auto_create_for_case', + return_value={'status': 'queued', 'job_id': 3303, 'idempotency_key': 'k-03'}, + ) as ensure_mock: + result = coord.reconcile_single_case_for_auto_progress( + case=case, trigger='customer_auto_confirmed', refresh_validation=True, + ) + + assert result['customer_step_status'] == 'auto_confirmed' + assert case.current_draft.validation_result_json['can_auto_create'] is True + ensure_mock.assert_called_once() + + +def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(app): + """合同 4:Worker 启动 Sweeper → 扫描漏入队 Case → 协调器补偿建 STP Job。""" + from app.services.shipping_notice import shipping_recovery_sweeper_service as sw + + case = SimpleNamespace( + id=4, case_no='SORC-P1-04', status='ready', confirmed_task_id=None, + document_id=400, updated_at=None, + ) + with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch( + 'app.services.shipping_notice.shipping_recovery_sweeper_service.db', + ) as mock_db, patch( + 'app.services.shipping_notice.shipping_recovery_sweeper_service.' + 'reconcile_single_case_for_auto_progress', + return_value={'case_no': 'SORC-P1-04', 'enqueue_status': 'queued', + 'job_id': 4404}, + ) as coord_mock: + mock_session = MagicMock() + loaded = SimpleNamespace(id=4, status='ready', confirmed_task_id=None) + mock_session.execute.return_value.scalar.return_value = None + mock_session.get.return_value = loaded + mock_session.begin_nested.return_value.__enter__ = MagicMock(return_value=None) + mock_session.begin_nested.return_value.__exit__ = MagicMock(return_value=None) + type(mock_db).session = mock_session + count = sw.shipping_recovery_tick() + + assert coord_mock.call_count == 1 + assert count >= 1 + + +def test_contract_05_recovery_tick_scans_stale_inventory_attempts(app): + """合同 5:shipping recovery tick 必须调用逐源库存超时扫描。""" + from app.services.shipping_notice import shipping_recovery_sweeper_service as sw + + with patch.object(sw, '_scan_stale_inventory_attempts', return_value=2) as scan_mock, \ + patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[]): + count = sw.shipping_recovery_tick() + + scan_mock.assert_called_once() + assert count == 2 + + +def test_contract_06_concurrent_sweep_produces_single_active_job_via_idempotency(app): + """合同 5:并发 Sweeper 扫描 + 部分唯一索引约束 → 只产生一个活动 STP Job。""" + from app.jobs.queue import enqueue + from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + ) + + case = SimpleNamespace( + id=5, case_no='SORC-P1-05', status='ready', confirmed_task_id=None, + document_id=500, candidate_id=50, run_id=50, + run=SimpleNamespace(id=50, run_no='SNER-50'), owner_user_id=1, + current_draft=SimpleNamespace( + draft_version=1, header_values_json={}, lines_json=[], + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + issue_summary_json=[], + ), + ) + active = SimpleNamespace(id=5555, status='queued') + + with patch( + 'app.services.shipping_notice.order_stp_auto_create_service.db', + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.' + '_persist_case_candidate_qualification', return_value=None, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service._is_xfa_case', return_value=False, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service._draft_has_manual_edits', return_value=False, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job', return_value=active, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.enqueue', + ) as enqueue_mock, patch( + 'app.services.shipping_notice.order_stp_auto_create_service.record_fulfillment_audit', + ): + r1 = ensure_stp_auto_create_for_case(case=case, commit=False) + r2 = ensure_stp_auto_create_for_case(case=case, commit=False) + + # 两次调用都应该复用已存在的 active Job,enqueue 不被触发 + enqueue_mock.assert_not_called() + assert r1.get('job_id') == 5555 + assert r2.get('job_id') == 5555 + assert r1.get('status') in {'reused', 'already_queued', 'already_running'} + assert r2.get('status') in {'reused', 'already_queued', 'already_running'} + + +def test_contract_06_duplicate_blocked_case_rejects_general_retry(app): + """合同 6:duplicate → waiting_human,retry API 抛 409;Projection 移除通用重试按钮。""" + from app.core.errors import ConflictError + from app.services.shipping_notice import reconciliation_service as rs + from app.services.shipping_notice.recovery_contract import should_general_retry_be_removed + + case = SimpleNamespace(case_no='SORC-P1-06', status='ready', confirmed_task_id=None) + + # 6A:assert_case_not_blocked_manual 前置拦截 → 409 + with patch( + 'app.services.shipping_notice.reconciliation_service.find_latest_stp_job', + return_value=SimpleNamespace( + id=60, status='failed', + result_json={'retryable': False, + 'blocking_reason': 'SHIPPING.NOTICE_EXACT_DUPLICATE'}, + ), + ): + with pytest.raises(ConflictError): + rs.assert_case_not_blocked_manual(case_no='SORC-P1-06', case=case) + + # 6B:Recovery Contract 层应移除 retry 动作 + assert should_general_retry_be_removed( + retryable_flag=False, blocking_reason='duplicate_decision_required', + ) is True + assert should_general_retry_be_removed( + retryable_flag=False, blocking_reason='SHIPPING.NOTICE_EXACT_DUPLICATE', + ) is True + + +def test_contract_07_get_projection_is_pure_read_no_writes(app): + """合同 7:GET 投影 → 不 confirm 客户、不 validate Draft、不 commit 事务。""" + from app.services.shipping_notice.order_review_customer_service import ( + project_review_case_customer_resolution, + ) + + case = SimpleNamespace( + id=7, case_no='SORC-P1-07', candidate_id=70, status='unreviewed', + current_draft=SimpleNamespace(draft_version=1, header_values_json={}, lines_json=[]), + run_id=70, + ) + with patch( + 'app.services.shipping_notice.order_review_customer_service.db.session', + MagicMock(), + ) as sess_mock, patch( + 'app.services.shipping_notice.order_review_customer_service.resolve_review_case_customer_resolved', + return_value=False, + ), patch( + 'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches', + ) as refresh_mock, patch( + 'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match', + ) as confirm_mock, patch( + 'app.services.shipping_notice.order_review_customer_service.validate_draft', + ) as validate_mock: + # Shadow = unique_candidate 但是 resolved=false。 + with patch( + 'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution', + ) as Shadow: + top = {'customer_id': 7777} + shadow = SimpleNamespace( + status='unique_candidate', top_customer_id=7777, + candidate_matches_json=[top], evidence_json=[], + resolution_context_json={'rule_set': {'definitions': []}}, + ) + Shadow.query.filter_by.return_value.first.return_value = shadow + with patch( + 'app.services.shipping_notice.order_review_customer_service.ShippingOrderCandidate', + ) as Cand, patch( + 'app.services.shipping_notice.order_review_customer_service.ShippingOrderCustomerMatch', + ) as CM, patch( + 'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction', + ) as EX: + Cand.query.get.return_value = SimpleNamespace(id=70) + CM.query.filter_by.return_value.first.return_value = None + EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700) + sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700) + # 执行投影(纯读) + out = project_review_case_customer_resolution(case) + + # 7A:GET 路径不允许 confirm / validate / commit + confirm_mock.assert_not_called() + validate_mock.assert_not_called() + refresh_mock.assert_not_called() + sess_mock.commit.assert_not_called() + # 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认) + assert out.get('resolved') is False + assert out.get('status') == 'unique_candidate' + + +def test_contract_08_cancelled_case_must_not_be_reenqueued(app): + """合同 8:已取消(或终态)Case → ensure_stp 拒绝再入队,幂等安全。""" + from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + ) + + for terminal_status in TERMINAL_CASE_STATUSES: + case = SimpleNamespace( + id=8, case_no='SORC-P1-08', status=terminal_status, + confirmed_task_id=None, document_id=800, candidate_id=None, + run_id=80, run=SimpleNamespace(id=80, run_no='SNER-80'), + owner_user_id=1, current_draft=SimpleNamespace( + draft_version=1, validation_result_json={'can_auto_create': True, 'status': 'ready'}, + issue_summary_json=[], + ), + ) + with patch( + 'app.services.shipping_notice.order_stp_auto_create_service.db', + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.enqueue', + ) as enqueue_mock: + r = ensure_stp_auto_create_for_case(case=case, commit=False) + assert r['status'] == 'already_confirmed_or_terminal' + assert r.get('can_auto_create') is False + enqueue_mock.assert_not_called() + + +def test_contract_09_late_callback_does_not_resurrect_terminal_case(app): + """合同 9:迟到 Worker 回调 → Case 已终态时,Case/Job 状态不回退。""" + from app.jobs.handlers import shipping_review_revalidate_progress as h + + job = SimpleNamespace( + id=909, attempts=1, + payload_json={'case_no': 'SORC-P1-09', 'draft_version': 2}, + ) + + loaded_case = SimpleNamespace( + status='non_order', confirmed_task_id=None, + current_draft=SimpleNamespace(draft_version=2), + ) + + with patch.object(h.db.session, 'get', return_value=job), patch( + 'app.jobs.handlers.shipping_review_revalidate_progress.ShippingOrderReviewCase', + ) as RC, patch.object(h, 'finish_job') as finish_mock, patch.object( + h, 'fail_job', + ) as fail_mock: + RC.query.filter_by.return_value.with_for_update.return_value.first.return_value = loaded_case + from app.jobs.context import JobContext + ctx = JobContext(config={}, logger=MagicMock(), extras={}) + h.handle_shipping_review_revalidate_progress(ctx, {'job_id': 909}) + + finish_mock.assert_called_once() + args, _ = finish_mock.call_args + result = args[1] if len(args) > 1 else {} + assert result.get('status') in {'skipped', 'superseded', 'case_terminal'} + fail_mock.assert_not_called() + + +# ========================================================================= +# 前端 Projection 行为合同(5 项)—— 函数级验证 +# ========================================================================= + + +def test_fe_01_stp_enqueue_missing_injects_blocking_reason(app): + """FE 合同 1:Projection stp_enqueue_missing → blocking_reason.code 正确 + primary_action=retry_auto_progress。""" + from app.services.shipping_notice.reconciliation_projector import ( + _project_fine_grained_pre_stp_blocking, + ) + + case = SimpleNamespace( + id=101, case_no='SORC-FE-01', status='ready', + confirmed_task_id=None, document_id=1001, + run=SimpleNamespace(run_no='SNER-FE-01', id=10), + current_draft=SimpleNamespace( + draft_version=1, + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + header_values_json={'h1': {'source': 'extract', 'value': 'x'}}, + lines_json=[], + ), + ) + with patch( + 'app.services.shipping_notice.reconciliation_projector.db.session', + MagicMock(), + ), patch( + 'app.services.shipping_notice.reconciliation_projector.Job', + ) as J: + J.query.filter.return_value.first.return_value = None + bundle = _project_fine_grained_pre_stp_blocking(case) + + assert bundle is not None + assert bundle['blocking_reason']['code'] == 'stp_enqueue_missing' + assert bundle['user_status'] == 'retryable' + assert bundle['primary_action']['code'] == 'retry_auto_progress' + assert bundle['user_stage'] == 'pre_ot_stp' + + +def test_fe_02_retryable_shows_single_primary_action_only(app): + """FE 合同 2:retryable → 只暴露单一主动作,避免 UI 按钮矛盾。""" + from app.services.shipping_notice.reconciliation_projector import ( + _project_fine_grained_pre_stp_blocking, + ) + + case = SimpleNamespace( + id=102, case_no='SORC-FE-02', status='ready', + confirmed_task_id=None, document_id=1002, + run=SimpleNamespace(run_no='SNER-FE-02', id=10), + current_draft=SimpleNamespace( + draft_version=1, + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + header_values_json={}, lines_json=[], + ), + ) + with patch( + 'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(), + ), patch( + 'app.services.shipping_notice.reconciliation_projector.Job', + ) as J: + J.query.filter.return_value.first.return_value = None + bundle = _project_fine_grained_pre_stp_blocking(case) + + assert bundle['user_status'] == 'retryable' + primary = bundle.get('primary_action') or {} + assert isinstance(primary, dict) + assert primary.get('code') in {'retry_auto_progress', 'retry_stp_auto_create'} + # 短路由返回的 bundle 只包含 primary_action,不应出现 reconcile_and_progress + assert primary.get('code') != 'reconcile_and_progress' + + +def test_fe_03_duplicate_only_allows_reconcile_and_progress(app): + """FE 合同 3:duplicate → projection 剔除 retry,只保留 reconcile_and_progress。""" + from app.services.shipping_notice.processing_projection_invariants import ( + _DUPLICATE_BLOCKING_CODES, + ) + from app.services.shipping_notice.recovery_contract import ( + BLOCKING_REASON_TO_ACTION_CODES, + should_general_retry_be_removed, + ) + + for bcode in _DUPLICATE_BLOCKING_CODES: + assert should_general_retry_be_removed( + retryable_flag=False, blocking_reason=bcode, + ) is True, f'{bcode} 必须移除通用重试' + # 下一步动作必须是裁决面板(adjudicate_duplicate → 前端按钮显示 reconcile_and_progress) + next_action = BLOCKING_REASON_TO_ACTION_CODES.get(bcode) + assert next_action == 'adjudicate_duplicate', f'{bcode} 必须映射 adjudicate_duplicate' + + +def test_fe_04_refresh_and_re_login_projection_consistent(app): + """FE 合同 4:刷新 / 重新登录后 stp_enqueue_missing 判定不变(数据库事实为唯一真值)。""" + from app.services.shipping_notice.reconciliation_projector import ( + _project_fine_grained_pre_stp_blocking, + ) + + case = SimpleNamespace( + id=104, case_no='SORC-FE-04', status='ready', + confirmed_task_id=None, document_id=1004, + run=SimpleNamespace(run_no='SNER-FE-04', id=10), + current_draft=SimpleNamespace( + draft_version=2, + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + header_values_json={}, lines_json=[], + ), + ) + with patch( + 'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(), + ), patch( + 'app.services.shipping_notice.reconciliation_projector.Job', + ) as J: + J.query.filter.return_value.first.return_value = None + r1 = _project_fine_grained_pre_stp_blocking(case) + r2 = _project_fine_grained_pre_stp_blocking(case) + + assert r1 is not None and r2 is not None + assert r1['blocking_reason']['code'] == r2['blocking_reason']['code'] + assert r1['primary_action'] == r2['primary_action'] + assert r1['user_status'] == r2['user_status'] + + +def test_fe_05_no_contradictory_waiting_manual_and_waiting_auto_together(app): + """FE 合同 5:不得同时出现「待人工处理」和「等待自动建单」矛盾组合。""" + from app.services.shipping_notice.reconciliation_projector import ( + _project_fine_grained_pre_stp_blocking, + ) + + case = SimpleNamespace( + id=105, case_no='SORC-FE-05', status='ready', + confirmed_task_id=None, document_id=1005, + run=SimpleNamespace(run_no='SNER-FE-05', id=10), + current_draft=SimpleNamespace( + draft_version=1, + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + header_values_json={}, lines_json=[], + ), + ) + with patch( + 'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(), + ), patch( + 'app.services.shipping_notice.reconciliation_projector.Job', + ) as J: + J.query.filter.return_value.first.return_value = None + bundle = _project_fine_grained_pre_stp_blocking(case) + + status = bundle.get('user_status') + # retryable 与 waiting_human 互斥:命中短路 stp_enqueue_missing 时,只能二选一 + assert status in {'retryable', 'waiting_human', 'running', 'failed', 'completed', 'cancelled'} + assert not (status == 'retryable' and bundle.get('blocking_reason', {}).get('code') == 'order_review_required') + assert not (status == 'waiting_human' and bundle.get('primary_action', {}).get('code') == 'retry_auto_progress') diff --git a/backend/tests/test_shipping_auto_progress_p0_3.py b/backend/tests/test_shipping_auto_progress_p0_3.py new file mode 100644 index 00000000..13d5386e --- /dev/null +++ b/backend/tests/test_shipping_auto_progress_p0_3.py @@ -0,0 +1,138 @@ +""" +tests/test_shipping_auto_progress_p0_3.py + +用途:锁定 P0-3 正式 AutoProgress 的 Task 串行、单 Gate、版本围栏及人工回执合同。 +依赖:pytest、SQLAlchemy 测试库、auto_progress_controller。 +逻辑:直接构造 Task/Candidate/Execution 事实,避免旧 STP 协调器的过期 mock;验证 Job outbox + 仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链。 +""" + +from __future__ import annotations + +from app import db +from app.jobs.queue import claim_next_job +from app.models import Job, ShippingInventoryCandidateSet, ShippingNotice, ShippingProcessExecution, ShippingProcessGate +from app.services.shipping_notice.auto_progress_controller import ( + AUTO_PROGRESS_GATE_CODES, + run_auto_progress_job, + submit_auto_progress, +) + + +def _task_with_candidate() -> ShippingNotice: + """创建拥有 frozen CandidateSet 的最小正式 Task。""" + task = ShippingNotice(task_no='APX-P0-3-001', process_status='created') + db.session.add(task) + db.session.flush() + candidate = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='a' * 64, + ) + db.session.add(candidate) + db.session.flush() + task.active_inventory_candidate_set_id = candidate.id + db.session.commit() + return task + + +def test_submit_reuses_one_active_task_job(app): + """同一 Task 多次触发只保留一个 queued/running AutoProgress Job。""" + task = _task_with_candidate() + first = submit_auto_progress(task=task, trigger='review_confirmed') + second = submit_auto_progress(task=task, trigger='user_retry') + + assert first['status'] == 'queued' + assert second['job_id'] == first['job_id'] + assert second['reused'] is True + assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 1 + + +def test_worker_passes_only_one_gate_and_queues_successor(app, monkeypatch): + """一个 Worker Job 只处理首个 Gate,passed 与第二个 Gate Job 同事务产生。""" + task = _task_with_candidate() + submitted = submit_auto_progress(task=task, trigger='review_confirmed') + claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) + assert claimed is not None and claimed.id == submitted['job_id'] + monkeypatch.setattr( + 'app.services.shipping_notice.auto_progress_controller._gate_outcome', + lambda task, gate: ('passed', None, {'test': True}), + ) + + result = run_auto_progress_job(job_id=submitted['job_id'], worker_id='test-worker') + execution = db.session.get(ShippingProcessExecution, result['execution_id'] if 'execution_id' in result else Job.query.get(submitted['job_id']).execution_id) + gates = ShippingProcessGate.query.filter_by(execution_id=execution.id).order_by(ShippingProcessGate.sequence_no).all() + jobs = Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').order_by(Job.id).all() + + assert result['gate_code'] == AUTO_PROGRESS_GATE_CODES[0] + assert gates[0].status == 'passed' + assert gates[1].status == 'pending' + assert len(jobs) == 2 + assert jobs[0].status == 'success' and jobs[1].status == 'queued' + assert jobs[1].gate_id == gates[1].id + + +def test_stale_job_is_cancelled_without_touching_current_execution(app): + """候选/Execution 指针已切换时,迟到 Job 只能 cancelled,不能改写当前链。""" + task = _task_with_candidate() + submitted = submit_auto_progress(task=task, trigger='review_confirmed') + claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) + assert claimed is not None + old_execution = db.session.get(ShippingProcessExecution, Job.query.get(submitted['job_id']).execution_id) + replacement = ShippingProcessExecution( + execution_no='APX-REPLACEMENT', task_id=task.id, + candidate_set_id=task.active_inventory_candidate_set_id, execution_revision=2, + status='active', lock_version=1, + ) + db.session.add(replacement) + db.session.flush() + task.active_process_execution_id = replacement.id + db.session.commit() + + result = run_auto_progress_job(job_id=submitted['job_id'], worker_id='late-worker') + assert result['status'] == 'cancelled' + assert Job.query.get(submitted['job_id']).status == 'cancelled' + assert old_execution.status == 'active' + assert db.session.get(ShippingProcessExecution, replacement.id).status == 'active' + + +def test_excel_gate_waits_for_human_receipt(app, monkeypatch): + """Excel Gate 成功后不 completed;自动上传关闭时必须停在 receipt Gate 的人工阻断。""" + task = _task_with_candidate() + submitted = submit_auto_progress(task=task, trigger='review_confirmed') + monkeypatch.setattr( + 'app.services.shipping_notice.auto_progress_controller._gate_outcome', + lambda task, gate: ('passed', None, {}), + ) + for _ in range(5): + claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) + assert claimed is not None + run_auto_progress_job(job_id=claimed.id, worker_id='test-worker') + execution = db.session.get(ShippingProcessExecution, Job.query.get(submitted['job_id']).execution_id) + receipt_gate = ShippingProcessGate.query.filter_by( + execution_id=execution.id, gate_code='upload_receipt_recorded', + ).one() + + assert execution.status == 'blocked' + assert receipt_gate.status == 'blocked_manual' + assert receipt_gate.blocking_reason_code == 'manual_upload_receipt_required' + + +def test_recorded_receipt_reopens_only_final_gate(app, monkeypatch): + """人工登记回执后,服务端只重新执行最后一个 receipt Gate 并完成 Execution。""" + task = _task_with_candidate() + submitted = submit_auto_progress(task=task, trigger='review_confirmed') + monkeypatch.setattr( + 'app.services.shipping_notice.auto_progress_controller._gate_outcome', + lambda task, gate: ('passed', None, {}), + ) + for _ in range(5): + claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) + run_auto_progress_job(job_id=claimed.id, worker_id='test-worker') + task.upload_receipt_json = {'receipt_no': 'R-1'} + db.session.commit() + resume = submit_auto_progress(task=task, trigger='manual_upload_receipt_recorded') + claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) + result = run_auto_progress_job(job_id=claimed.id, worker_id='test-worker') + + assert resume['gate_code'] == 'upload_receipt_recorded' + assert result['gate_code'] == 'upload_receipt_recorded' + assert db.session.get(ShippingProcessExecution, result['execution_id']).status == 'completed' diff --git a/backend/tests/test_shipping_field_split_core.py b/backend/tests/test_shipping_field_split_core.py new file mode 100644 index 00000000..f6a04943 --- /dev/null +++ b/backend/tests/test_shipping_field_split_core.py @@ -0,0 +1,475 @@ +""" +tests/test_shipping_field_split_core.py + +用途:锁定共享 Split Core(field_split_core)的 Base 契约与执行引擎字节级一致性, + 覆盖 prefix / regex / position 三类 matcher、mapped/evidence_only、 + 同优先级 duplicate_line_match、relation_capture 捕获(Q2 双层设计)、 + 超长输入门禁、危险正则超时、指纹 content_fingerprint 与 XFA 链路对照。 +依赖:field_split_core(BaseSplit*、execute_base_split_rule_set、 + base_split_content_fingerprint、RelationCaptureDef、CoreCapturedRelation)。 +逻辑:纯引擎单测;不读真实 PDF;不调用 XFA 链路(对照测试在 test_shipping_xfa_split_rule_engine.py)。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.document_layout.field_split_core import ( + BaseSplitMatcher, + BaseSplitNormalization, + BaseSplitRule, + BaseSplitRuleSet, + BaseSplitSegment, + RelationCaptureDef, + _CoreSegmentResult, + base_split_content_fingerprint, + execute_base_split_rule_set, + new_segment_id, +) + +VENDOR_COMMENTS_RAW = ( + 'Vendor Comments:\n' + 'Reservation: 3000098851 for line#2\n' + 'Ship Date: 2026-08-15\n' + 'Attention: RUSH order\n' +) + + +def _base_rule_set(rules, **kwargs) -> BaseSplitRuleSet: + """构造最小 BaseSplitRuleSet(不含 XFA 专属 path_id 等字段)。""" + defaults = dict( + rule_set_id='vc-reservation-v1', + rule_version=1, + normalization=BaseSplitNormalization(), + unmatched_line_policy='evidence_only', + duplicate_match_policy='needs_review', + same_field_multiple_segment_policy='needs_review', + source='user', + status='confirmed', + requires_confirmation=False, + ) + defaults.update(kwargs) + defaults['rules'] = list(rules) + return BaseSplitRuleSet(**defaults) + + +# --------------------------------------------------------------------------- +# [TEST 1] 三类 matcher 基础命中——prefix / regex / position +# --------------------------------------------------------------------------- + + +def test_prefix_matcher_extracts_value_after_separator(): + """前缀匹配:标签 + 分隔符后的值正确提取。""" + seg = BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='reservation_candidate', + display_name='Reservation', + handling='mapped', + target_field_id='f-res', + target_field_code='reservation_id', + ) + rule_set = _base_rule_set([ + BaseSplitRule( + rule_id='res-prefix', + matcher=BaseSplitMatcher( + type='prefix', + value='Reservation', + separators=[':', ':'], + case_sensitive=False, + ), + segment=seg, + ), + ]) + result = execute_base_split_rule_set(raw_value=VENDOR_COMMENTS_RAW, rule_set=rule_set) + assert result.status == 'parsed' + assert result.mapped_fields['reservation_id'] == '3000098851 for line#2' + mapped = [s for s in result.segments if s.handling == 'mapped'] + assert len(mapped) == 1 + assert mapped[0].line_no == 2 + assert mapped[0].matcher_type == 'prefix' + + +def test_regex_matcher_with_capture_group(): + """正则匹配:指定 capture_group 提取纯 Reservation 数字。""" + seg = BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='reservation_candidate', + display_name='Reservation', + handling='mapped', + target_field_id='f-res', + target_field_code='reservation_id', + ) + rule_set = _base_rule_set([ + BaseSplitRule( + rule_id='res-regex', + matcher=BaseSplitMatcher( + type='regex', + pattern=r'Reservation[::]\s*(\d{5}|\d{10})\b', + capture_group=1, + ), + segment=seg, + ), + ]) + result = execute_base_split_rule_set(raw_value=VENDOR_COMMENTS_RAW, rule_set=rule_set) + assert result.status == 'parsed' + assert result.mapped_fields['reservation_id'] == '3000098851' + + +def test_position_matcher_line_index_1based(): + """位置匹配:1-based line_index 命中整行。""" + seg = BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='header_label', + display_name='Header Label', + handling='evidence_only', + ) + rule_set = _base_rule_set([ + BaseSplitRule( + rule_id='pos1', + matcher=BaseSplitMatcher(type='position', line_index=1), + segment=seg, + ), + ]) + result = execute_base_split_rule_set(raw_value=VENDOR_COMMENTS_RAW, rule_set=rule_set) + parsed_seg = [s for s in result.segments if s.rule_id == 'pos1'][0] + assert parsed_seg.normalized_text == 'Vendor Comments:' + assert parsed_seg.line_no == 1 + assert parsed_seg.handling == 'evidence_only' + + +# --------------------------------------------------------------------------- +# [TEST 2] 优先级仲裁——prefix > regex > position > unmatched +# --------------------------------------------------------------------------- + + +def test_priority_prefix_beats_regex_beats_position(): + """同行三条规则按固定优先级取最高。""" + def seg(code: str, handling: str = 'mapped') -> BaseSplitSegment: + return BaseSplitSegment( + segment_id=new_segment_id(), + segment_code=code, + display_name=code, + handling=handling, + target_field_id='f-x' if handling == 'mapped' else None, + target_field_code=code if handling == 'mapped' else None, + ) + rule_set = _base_rule_set([ + BaseSplitRule( + rule_id='pos', + matcher=BaseSplitMatcher(type='position', line_index=1), + segment=seg('from_position'), + ), + BaseSplitRule( + rule_id='re', + matcher=BaseSplitMatcher(type='regex', pattern=r'^([A-Z].+)$', capture_group=1), + segment=seg('from_regex'), + ), + BaseSplitRule( + rule_id='pref', + matcher=BaseSplitMatcher(type='prefix', value='Vendor Comments', separators=[':']), + segment=seg('from_prefix'), + ), + ]) + result = execute_base_split_rule_set(raw_value='Vendor Comments: HELLO', rule_set=rule_set) + assert result.mapped_fields['from_prefix'] == 'HELLO' + assert 'from_regex' not in result.mapped_fields + assert 'from_position' not in result.mapped_fields + + +# --------------------------------------------------------------------------- +# [TEST 3] 同优先级 mapped 冲突 → duplicate_line_match + needs_review +# --------------------------------------------------------------------------- + + +def test_duplicate_same_priority_mapped_needs_review(): + """同优先级(regex vs regex)两条 mapped 命中同行 → status=needs_review。""" + def seg(code: str) -> BaseSplitSegment: + return BaseSplitSegment( + segment_id=new_segment_id(), + segment_code=code, + display_name=code, + handling='mapped', + target_field_id=f'f-{code}', + target_field_code=code, + ) + rule_set = _base_rule_set([ + BaseSplitRule( + rule_id='re-a', + matcher=BaseSplitMatcher(type='regex', pattern=r'(\d{5,})', capture_group=1), + segment=seg('field_a'), + ), + BaseSplitRule( + rule_id='re-b', + matcher=BaseSplitMatcher(type='regex', pattern=r'^(.*)$', capture_group=1), + segment=seg('field_b'), + ), + ]) + result = execute_base_split_rule_set(raw_value='3000098851', rule_set=rule_set) + assert result.status == 'needs_review' + codes = [d.code for d in result.diagnostics] + assert 'duplicate_line_match' in codes + # duplicate 后的排序取 rule_id 字母序(确定性输出,不依赖运行时) + # 但无论谁赢,都必须是 needs_review 状态 + + +# --------------------------------------------------------------------------- +# [TEST 4] relation_capture 捕获(Q2 双层设计:rule/matcher 层 relation) +# --------------------------------------------------------------------------- + + +def test_regex_relation_capture_line_no_from_same_match(): + """同一次正则命中:值捕获到 reservation,relation 捕获到 line#N。""" + seg = BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='reservation_candidate', + display_name='Reservation', + handling='mapped', + target_field_id='f-res', + target_field_code='reservation_id', + ) + rule_set = _base_rule_set([ + BaseSplitRule( + rule_id='res-with-line', + matcher=BaseSplitMatcher( + type='regex', + pattern=r'Reservation[::]\s*(\d{5}|\d{10})\b(.{0,40})?$', + capture_group=1, + relation_capture=RelationCaptureDef( + type='line_reference', + capture_group=2, + labels=['for', 'line#'], + ), + ), + segment=seg, + ), + ]) + result = execute_base_split_rule_set( + raw_value='Reservation: 3000098851 for line#2', + rule_set=rule_set, + ) + # reservation 值必须正确 + assert result.mapped_fields['reservation_id'] == '3000098851' + # captured_relation 必须在 core 层保留(XFA 适配时丢弃,但 core 单测要验证捕获) + mapped_segments: list[_CoreSegmentResult] = [ + s for s in result.segments if s.handling == 'mapped' + ] + assert len(mapped_segments) == 1 + rel = mapped_segments[0].captured_relation + assert rel is not None + assert rel.type == 'line_reference' + assert rel.line_no == 2 + assert 'for line#2' in (rel.raw_text or '') + + +# --------------------------------------------------------------------------- +# [TEST 5] evidence_only 不进 mapped_fields、不写 Schema 字段 +# --------------------------------------------------------------------------- + + +def test_evidence_only_segment_never_writes_mapped(): + """evidence_only 段必须出现在 segments 和 evidence_only_segments,但 mapped_fields 不含。""" + seg = BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='attention_note', + display_name='Attention', + handling='evidence_only', + ) + rule_set = _base_rule_set([ + BaseSplitRule( + rule_id='attn', + matcher=BaseSplitMatcher(type='prefix', value='Attention', separators=[':']), + segment=seg, + ), + ]) + result = execute_base_split_rule_set(raw_value=VENDOR_COMMENTS_RAW, rule_set=rule_set) + assert result.mapped_fields == {} + evidence_norm = {s.normalized_text for s in result.evidence_only_segments} + assert 'RUSH order' in evidence_norm + + +# --------------------------------------------------------------------------- +# [TEST 6] 超长输入门禁 → needs_review + input_too_long +# --------------------------------------------------------------------------- + + +def test_input_exceeds_max_length_triggers_gate(): + """超长输入必须直接 needs_review,不逐行拆分。""" + long_text = 'A' * (32_768 + 1) + rule_set = _base_rule_set([]) + result = execute_base_split_rule_set(raw_value=long_text, rule_set=rule_set) + assert result.status == 'needs_review' + codes = {d.code for d in result.diagnostics} + assert 'input_too_long' in codes + + +# --------------------------------------------------------------------------- +# [TEST 7] 危险正则 → regex_failed;超时 → regex_timeout(由 xfa_safe_regex 拦截) +# --------------------------------------------------------------------------- + + +def test_dangerous_regex_triggers_safe_regex_error_in_matcher(): + """危险正则在 matcher 契约层就被拦截(构造 BaseSplitMatcher 即抛错)。""" + with pytest.raises(ValueError): + BaseSplitMatcher( + type='regex', + pattern=r'(a+)+$', + ) + + +def test_unknown_matcher_code_in_diagnostic_when_extension_happens(): + """如果共享核心的 matcher_type 分支遗漏(假设 type 是未知字面量),诊断含 unknown_matcher。""" + seg = BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='s', + display_name='s', + handling='mapped', + target_field_id='f-s', + target_field_code='s', + ) + # 手动构造绕过 Pydantic 校验的 matcher(模拟未来扩展时的错误分支) + rule = BaseSplitRule( + rule_id='r-unknown', + matcher=BaseSplitMatcher(type='prefix', value='X', separators=[':']), + segment=seg, + ) + # 直接覆盖 type 私有字段,通过 object.__setattr__ 绕过 Pydantic frozen + object.__setattr__(rule.matcher, 'type', 'future_unknown_type') + rule_set = _base_rule_set([rule]) + result = execute_base_split_rule_set(raw_value='X:Y', rule_set=rule_set) + # 未知 matcher 类型走 unknown_matcher 分支(无命中、无错误码注入) + # 但 _match_line 返回 (None, 'unknown_matcher') + codes = {d.code for d in result.diagnostics} + assert 'unknown_matcher' in codes + + +# --------------------------------------------------------------------------- +# [TEST 8] 指纹:handling / target_field_* 变化不影响指纹(绑定 Schema ≠ 规则逻辑变化) +# --------------------------------------------------------------------------- + + +def test_fingerprint_ignores_segment_schema_mapping_fields(): + """handling 从 mapped→evidence_only、target_field_* 变化 → fingerprint 不变。""" + base_kwargs = dict( + rule_id='r1', + matcher=BaseSplitMatcher(type='position', line_index=1), + ) + mapped_version = _base_rule_set([BaseSplitRule( + segment=BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='s1', + display_name='S1', + handling='mapped', + target_field_id='f-x', + target_field_code='field_x', + ), + **base_kwargs, + )]) + evidence_version = _base_rule_set([BaseSplitRule( + segment=BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='s1', + display_name='S1', + handling='evidence_only', + ), + **base_kwargs, + )]) + assert base_split_content_fingerprint(mapped_version) == base_split_content_fingerprint(evidence_version) + + +def test_fingerprint_changes_when_matcher_logic_changes(): + """prefix value 变化 → fingerprint 变化。""" + def make(prefix_val: str) -> BaseSplitRuleSet: + return _base_rule_set([BaseSplitRule( + rule_id='r1', + matcher=BaseSplitMatcher(type='prefix', value=prefix_val, separators=[':']), + segment=BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='s1', + display_name='S1', + handling='evidence_only', + ), + )]) + assert base_split_content_fingerprint(make('Reservation')) != base_split_content_fingerprint(make('Resv')) + + +# --------------------------------------------------------------------------- +# [TEST 9] mapped_value_empty → needs_review(空值 mapped 段禁止静默通过) +# --------------------------------------------------------------------------- + + +def test_empty_mapped_value_flags_needs_review(): + """mapped 段提取到空字符串 → mapped_value_empty + overall=needs_review。""" + rule_set = _base_rule_set([BaseSplitRule( + rule_id='empty-case', + matcher=BaseSplitMatcher(type='prefix', value='Empty', separators=[':']), + segment=BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='empty_field', + display_name='Empty', + handling='mapped', + target_field_id='f-e', + target_field_code='empty_field', + ), + )]) + result = execute_base_split_rule_set(raw_value='Empty: \nOther: value', rule_set=rule_set) + assert result.status == 'needs_review' + codes = {d.code for d in result.diagnostics} + assert 'mapped_value_empty' in codes + + +# --------------------------------------------------------------------------- +# [TEST 10] same_field_multiple_segment 同一 Schema 字段被多段命中 → needs_review +# --------------------------------------------------------------------------- + + +def test_same_schema_field_hit_by_two_segments_flags(): + """不同行的两条 mapped 段指向同一个 target_field_code → same_field_multiple_segment。""" + def make_rule(rid: str, lv: str) -> BaseSplitRule: + return BaseSplitRule( + rule_id=rid, + matcher=BaseSplitMatcher(type='prefix', value=lv, separators=[':']), + segment=BaseSplitSegment( + segment_id=new_segment_id(), + segment_code=f'seg_{rid}', + display_name=f'Seg {rid}', + handling='mapped', + target_field_id='f-res', + target_field_code='reservation_id', + ), + ) + rule_set = _base_rule_set([ + make_rule('r1', 'Res'), + make_rule('r2', 'Reservation'), + ]) + result = execute_base_split_rule_set( + raw_value='Res: 12345\nReservation: 67890', + rule_set=rule_set, + ) + assert result.status == 'needs_review' + codes = {d.code for d in result.diagnostics} + assert 'same_field_multiple_segment' in codes + + +# --------------------------------------------------------------------------- +# [TEST 11] unmatched_line_policy=needs_review 时未命中行升 needs_review +# --------------------------------------------------------------------------- + + +def test_unmatched_line_policy_needs_review_lifts_overall(): + """unmatched_line_policy=needs_review,存在未命中行 → overall=needs_review。""" + rule_set = _base_rule_set([ + BaseSplitRule( + rule_id='r1', + matcher=BaseSplitMatcher(type='position', line_index=1), + segment=BaseSplitSegment( + segment_id=new_segment_id(), + segment_code='only_line1', + display_name='Only L1', + handling='evidence_only', + ), + ), + ], unmatched_line_policy='needs_review') + result = execute_base_split_rule_set(raw_value='L1\nL2\nL3', rule_set=rule_set) + assert result.status == 'needs_review' + codes = {d.code for d in result.diagnostics} + assert 'unmatched_line' in codes diff --git a/backend/tests/test_shipping_gate_contract_user_states.py b/backend/tests/test_shipping_gate_contract_user_states.py new file mode 100644 index 00000000..d641cfb5 --- /dev/null +++ b/backend/tests/test_shipping_gate_contract_user_states.py @@ -0,0 +1,223 @@ +""" +tests/test_shipping_gate_contract_user_states.py + +用途:锁定 T1 交付的用户态 Projection 契约——6 种用户状态、Gate/Execution 映射、 + 108 个阻断原因码分类、库存 4 主 Gate 与子阶段命名。 +依赖:process_gate_contract(USER_FACING_TASK_STATUSES / GATE_STATUS_TO_USER_STATUS / + EXECUTION_STATUS_TO_USER_STATUS / BLOCKING_REASON_TO_USER_MODE / + INVENTORY_MAIN_GATES / INVENTORY_SUB_STAGES / 便捷查询函数)。 +逻辑:纯契约断言(pure_unit,不拉 Flask/DB);断言覆盖规模与边界, + 保证后续新增 reason_code 或 Gate.status 时必须显式更新分类。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.process_gate_contract import ( + BLOCKING_REASON_TO_USER_MODE, + BLOCKING_REASON_USER_MODES, + EXECUTION_STATUS_TO_USER_STATUS, + GATE_STATUS_TO_USER_STATUS, + INVENTORY_MAIN_GATES, + INVENTORY_SUB_STAGES, + PROCESS_EXECUTION_STATUSES, + PROCESS_GATE_BLOCKING_REASON_CODES, + PROCESS_GATE_STATUSES, + PROJECTION_EXPORT_STATES, + PROJECTION_INVENTORY_SOURCE_STATUSES, + PROJECTION_UPLOAD_STATES, + USER_FACING_TASK_STATUSES, + assert_process_gate_contract_integrity, + user_mode_for_blocking_reason, + user_status_for_execution_status, + user_status_for_gate_status, +) + +pytestmark = pytest.mark.pure_unit + + +def test_gate_contract_integrity_with_user_states(): + """ + 带用户态映射的契约完整性自检:GATE/EXEC/REASON 全覆盖。 + + 核心逻辑:assert_process_gate_contract_integrity() 已追加 3 组用户态闭环校验, + 此处显式调用并额外冻结枚举规模,防止未来无意间扩大集合。 + """ + assert_process_gate_contract_integrity() + + assert len(USER_FACING_TASK_STATUSES) == 6 + assert USER_FACING_TASK_STATUSES == frozenset({ + 'running', 'waiting_human', 'retryable', + 'failed', 'completed', 'cancelled', + }) + assert len(GATE_STATUS_TO_USER_STATUS) == 10 + assert len(EXECUTION_STATUS_TO_USER_STATUS) == 6 + assert len(BLOCKING_REASON_USER_MODES) == 3 + + +def test_all_gate_statuses_have_user_mapping(): + """ + 10 种 PROCESS_GATE_STATUSES 必须一一映射,输出 3 类用户态。 + + 断言意图:若未来新增 Gate.status(如 paused),必须同步补充用户态含义。 + """ + assert set(PROCESS_GATE_STATUSES) == set(GATE_STATUS_TO_USER_STATUS.keys()) + outputs = set(GATE_STATUS_TO_USER_STATUS.values()) + assert outputs <= USER_FACING_TASK_STATUSES + # 关键语义:blocked_manual → waiting_human;blocked_retryable → retryable + assert GATE_STATUS_TO_USER_STATUS['blocked_manual'] == 'waiting_human' + assert GATE_STATUS_TO_USER_STATUS['blocked_retryable'] == 'retryable' + assert GATE_STATUS_TO_USER_STATUS['failed_terminal'] == 'failed' + # 等待外部回调不暴露为阻断 + assert GATE_STATUS_TO_USER_STATUS['waiting_external'] == 'running' + + +def test_all_execution_statuses_have_user_mapping(): + """ + 6 种 Execution.status 必须全覆盖;blocked 回退层兜底为 retryable(不放大为 waiting_human)。 + + 断言意图:Execution 层是 Projection 的回退层,禁止放大阻断语义。 + """ + assert set(PROCESS_EXECUTION_STATUSES) == set(EXECUTION_STATUS_TO_USER_STATUS.keys()) + assert EXECUTION_STATUS_TO_USER_STATUS['blocked'] == 'retryable' + assert EXECUTION_STATUS_TO_USER_STATUS['active'] == 'running' + assert EXECUTION_STATUS_TO_USER_STATUS['completed'] == 'completed' + assert EXECUTION_STATUS_TO_USER_STATUS['cancelled'] == 'cancelled' + assert EXECUTION_STATUS_TO_USER_STATUS['failed'] == 'failed' + + +def test_blocking_reason_classification_coverage(): + """ + 除豁免 1 个(technical_retry_exhausted)外,108 个阻断原因码必须一一分类。 + + 断言意图:禁止新增 reason_code 而漏掉用户处置模式,否则前端无法决定按钮渲染。 + """ + total = len(PROCESS_GATE_BLOCKING_REASON_CODES) + classified = set(BLOCKING_REASON_TO_USER_MODE.keys()) + exempt = {'technical_retry_exhausted'} + missing = PROCESS_GATE_BLOCKING_REASON_CODES - classified - exempt + assert not missing, f'unclassified blocking reasons: {sorted(missing)}' + # 规模冻结:当前全集(含豁免)共 108+1=109;此断言随新增原因码需显式更新 + assert total >= 100, f'expected >= 100 blocking codes, got {total}' + assert len(classified) + len(exempt) >= total + + +def test_user_mode_values_are_allowed(): + """ + BLOCKING_REASON_TO_USER_MODE 的值域必须恰好是 3 种处置模式。 + + 断言意图:防止 typo(如 'neeads_human')导致 Projection 层报错。 + """ + used_modes = set(BLOCKING_REASON_TO_USER_MODE.values()) + assert used_modes <= BLOCKING_REASON_USER_MODES + # 三种模式至少各有一个示例,保证集合非空 + assert 'retryable_tech' in used_modes + assert 'needs_human' in used_modes + assert 'terminal_failed' in used_modes + + +def test_inventory_main_gates_are_existing_and_ordered(): + """ + 库存 4 主 Gate 必须是已有 Gate,且顺序符合语义:calculated→frozen→snapshots_ready→matched。 + + 断言意图:决策 A1(不新增独立 Gate)——短缺/冲突只作匹配 Gate 内阻断分支表达。 + """ + assert len(INVENTORY_MAIN_GATES) == 4 + assert INVENTORY_MAIN_GATES == ( + 'inventory_source_routing', + 'order_freeze_readiness', + 'inventory_preparation', + 'inventory_matching', + ) + for gate_code in INVENTORY_MAIN_GATES: + assert gate_code in PROCESS_GATE_STATUSES or gate_code in ( + item['gate_code'] for item in _import_gate_definitions() + ), f'inventory main gate {gate_code} not registered' + + +def _import_gate_definitions(): + """从契约模块取回 20 个门禁定义元组,避免 test 顶部过度 import。""" + from app.services.shipping_notice.process_gate_contract import ( + PROCESS_GATE_DEFINITIONS, + ) + return PROCESS_GATE_DEFINITIONS + + +def test_inventory_sub_stages_whitelist(): + """ + 库存子阶段命名必须恰好 9 种,供 Gate.effective_result_json['inventory_sub_stage'] 使用。 + + 断言意图:子阶段白名单不允许随意新增,4 个 blocked_by_* 是匹配 Gate 内的阻断分支。 + """ + assert INVENTORY_SUB_STAGES == frozenset({ + 'not_started', + 'calculated', + 'frozen', + 'snapshots_ready', + 'matched', + 'blocked_by_shortage', + 'blocked_by_conflict', + 'blocked_by_stale_snapshot', + 'blocked_by_unknown', + }) + assert len(INVENTORY_SUB_STAGES) == 9 + + +def test_projection_facts_whitelists_non_empty(): + """ + Projection.facts 三枚枚举可取值集合已冻结,非空且稳定。 + + 断言意图:防止 Projection 构建层随写字符串导致前端消费合同不一致。 + """ + assert len(PROJECTION_INVENTORY_SOURCE_STATUSES) == 5 + assert len(PROJECTION_EXPORT_STATES) == 4 + assert len(PROJECTION_UPLOAD_STATES) == 6 + assert 'candidates_frozen' in PROJECTION_INVENTORY_SOURCE_STATUSES + assert 'created' in PROJECTION_EXPORT_STATES + assert 'succeeded' in PROJECTION_UPLOAD_STATES + + +def test_convenience_lookup_functions_sanity(): + """ + 三个便捷查询函数:未知态兜底不抛异常;None/空串输入安全。 + + 断言意图:Projection 层禁止各处写 if/else,应调用此三函数; + 此处验证输入安全性与兜底语义。 + """ + # Gate 层 + assert user_status_for_gate_status(None) == 'running' + assert user_status_for_gate_status('') == 'running' + assert user_status_for_gate_status('blocked_manual') == 'waiting_human' + assert user_status_for_gate_status('unknown_new_status_xyz') == 'running' + + # Execution 层 + assert user_status_for_execution_status(None) == 'running' + assert user_status_for_execution_status('') == 'running' + assert user_status_for_execution_status('blocked') == 'retryable' + assert user_status_for_execution_status('unknown_exec_status') == 'running' + + # Reason 模式 + assert user_mode_for_blocking_reason(None) is None + assert user_mode_for_blocking_reason('') is None + assert user_mode_for_blocking_reason('no_inventory_source_candidates') == 'needs_human' + assert user_mode_for_blocking_reason('inventory_rpa_timeout') == 'retryable_tech' + assert user_mode_for_blocking_reason('unknown_code_xyz') is None + + +def test_multi_source_is_not_a_blocking_reason(): + """ + 【决策 A1 关键语义】:多库存源(ambiguous→candidates_frozen)是合法自动链路, + 不得出现在 BLOCKING_REASON_TO_USER_MODE 中,也不会触发 waiting_human。 + + 断言意图:只有 zero_candidate / require_manual_review / conflicted / shortage + 才阻断;ambiguous 多候选合法路径不产生任何 blocking_reason。 + """ + assert 'ambiguous' not in BLOCKING_REASON_TO_USER_MODE + assert 'candidates_frozen' not in BLOCKING_REASON_TO_USER_MODE + assert 'multiple_inventory_sources' not in BLOCKING_REASON_TO_USER_MODE + # 合法阻断必须是明确的 zero / need_manual / conflict / shortage + assert BLOCKING_REASON_TO_USER_MODE['no_inventory_source_candidates'] == 'needs_human' + assert BLOCKING_REASON_TO_USER_MODE['require_manual_review'] == 'needs_human' + assert BLOCKING_REASON_TO_USER_MODE['inventory_multi_file_conflict'] == 'needs_human' + assert BLOCKING_REASON_TO_USER_MODE['inventory_insufficient'] == 'needs_human' diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 967b9c1c..5eb24248 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -661,6 +661,36 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path): assert after == before +def test_per_source_timeout_marks_missing_queued_trigger_as_failed(app, tmp_path): + """queued 但 trigger 已不存在且超时:收敛为失败,避免永久 already_running。""" + from datetime import datetime, timedelta + from types import SimpleNamespace + from app import db + from app.models import ShippingTaskInventoryRpaAttempt + from app.services.shipping_notice.per_source_rpa_service import per_source_timeout_scan + + with app.app_context(): + task = SimpleNamespace(task_no='SN-STALE-QUEUED') + attempt = ShippingTaskInventoryRpaAttempt( + task_no=task.task_no, + source_code='DSV360_AWSDU', + attempt_no=1, + run_no='PSR-STALE-1', + status='queued', + trigger_file_path=str(tmp_path / 'missing.trigger.json'), + triggered_at=datetime.utcnow() - timedelta(seconds=120), + ) + db.session.add(attempt) + db.session.commit() + + result = per_source_timeout_scan(task, timeout_seconds=60) + db.session.refresh(attempt) + + assert result['timed_out_count'] == 1 + assert attempt.status == 'failed' + assert attempt.error_code == 'trigger_not_claimed_missing' + + def test_batch_success_rejects_missing_worker_identity(app, tmp_path): """batch 成功项缺少 Worker 身份字段时不得由任务字段自证通过。""" from app import db diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 7e85c40b..54b51141 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 ( + _conversation_processing_from_work_items, _project_order_task_work_item, map_run_status_to_processing_status, map_run_to_processing_stage, @@ -410,3 +411,44 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u synced = _project_order_task_work_item(run) assert synced['status'] == 'automating' assert synced['stage'] == 'freight_uploading' + + +def test_conversation_processing_rebuild_prefers_work_item_user_status(app): + """ + 兼容 conversation_processing 重建时必须优先复用最终 work_item.user_status, + 不得再被旧 run 的 pending_review 文案反向覆盖。 + """ + with app.app_context(): + from app.models import ShippingOrderTask + from app.services.shipping_notice.order_extraction_run_service import ( + create_order_extraction_run, + ) + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_processing_projection import _ensure_run_order_task + + user, agent, session, intake, document = _seed_run_input(suffix='CP-USER-STATUS') + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + _ensure_run_order_task(run=run, intake=intake, document=document) + run.status = 'partially_completed' + run.phase = 'partially_completed' + run.current_stage_code = 'candidate_ready' + order_task = ShippingOrderTask.query.filter_by(extraction_run_id=int(run.id)).first() + assert order_task is not None + order_task.status = 'processing' + order_task.stage = 'inventory_fetching' + db.session.commit() + + item = _project_order_task_work_item(run, order_task=order_task) + assert item is not None + assert item['user_status'] == 'running' + + rebuilt = _conversation_processing_from_work_items([item]) + row = rebuilt['processing'][0] + assert row['status_label'] == 'processing' + assert row['group'] == 'processing' diff --git a/backend/tests/test_shipping_stp_phase4_line_inventory_match.py b/backend/tests/test_shipping_stp_phase4_line_inventory_match.py index 6e9982e9..ee0bfb55 100644 --- a/backend/tests/test_shipping_stp_phase4_line_inventory_match.py +++ b/backend/tests/test_shipping_stp_phase4_line_inventory_match.py @@ -73,6 +73,43 @@ def test_cross_candidate_shortage_and_not_found(): assert missing['line_results'][0]['disposition'] == 'not_found' +def test_cross_candidate_respects_allowed_source_codes(): + """行级 allowed_source_codes 只允许命中该行候选源。""" + result = match_order_lines_across_candidates( + order_lines=[{ + 'part_number': 'PN-1', + 'reservation_id': '3000092917', + 'quantity': '1', + 'allowed_source_codes': ['DBS_DUB'], + }], + inventory_lines=[ + {'reservation_id': '3000092917', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'DBS_DUB'}, + {'reservation_id': '3000092917', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'DBS_RTM'}, + ], + ) + assert result['match_status'] == 'fulfillable' + assert result['line_results'][0]['resolved_inventory_source_code'] == 'DBS_DUB' + assert result['resolutions'][0]['allowed_source_codes_snapshot'] == ['DBS_DUB'] + + +def test_cross_candidate_marks_out_of_scope_when_only_disallowed_source_matches(): + """若只有越界候选源命中,必须标 invalid,而不是静默降级为 not_found。""" + result = match_order_lines_across_candidates( + order_lines=[{ + 'part_number': 'PN-1', + 'reservation_id': '3000092917', + 'quantity': '1', + 'allowed_source_codes': ['DBS_DUB'], + }], + inventory_lines=[ + {'reservation_id': '3000092917', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'DBS_RTM'}, + ], + ) + assert result['match_status'] == 'unfulfillable' + assert result['line_results'][0]['disposition'] == 'invalid' + assert result['line_results'][0]['out_of_candidate_scope'] is True + + def test_header_reservation_fallback_for_match(): """行缺 Reservation 时可回退头级有效 Reservation。""" result = match_order_lines_across_candidates( @@ -211,8 +248,8 @@ def test_allowed_system_facts_use_export_sequence_not_line_no(): assert 'line_no' not in ALLOWED_SYSTEM_FACTS -def test_default_derivation_rules_are_enabled_copy_if_empty(): - """新草稿预置 customer_po_line_no→line_no,默认启用,空项次自动从客户PO行号派生。""" +def test_default_derivation_rules_are_disabled_copy_if_empty(): + """新草稿预置 customer_po_line_no→line_no,默认关闭。""" from app.services.shipping_notice.order_schema.field_rules import ( default_derivation_rules, normalize_derivation_rules, @@ -221,7 +258,7 @@ def test_default_derivation_rules_are_enabled_copy_if_empty(): rules = default_derivation_rules() assert rules == [{ 'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', - 'enabled': True, + 'enabled': False, 'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no', 'strategy': 'copy_if_empty', diff --git a/backend/tests/test_shipping_vendor_comments_phase2.py b/backend/tests/test_shipping_vendor_comments_phase2.py new file mode 100644 index 00000000..97a46f7f --- /dev/null +++ b/backend/tests/test_shipping_vendor_comments_phase2.py @@ -0,0 +1,444 @@ +""" +tests/test_shipping_vendor_comments_phase2.py + +用途:阶段 2 集成回归——契约、关系投影、三来源裁决(Header/Table/Vendor Comments)、 + 回 Draft 门禁、格式策略服务 5 大主题全量覆盖。 +依赖:6 个新服务(profile_vendor_comments_contract、coordinate_region_source_adapter、 + reservation_relation_projection、profile_field_source_mapping_service、 + source_merge_service、reservation_format_policy_service)。 +逻辑:纯内存单测——读真实 PDF/数据库的用例放在阶段 4; + 覆盖 Q13/Q14/Q15/Q16/Q18 全部冻结决策矩阵。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import ( + CoordinateRegionSourceAdapter, +) +from app.services.shipping_notice.document_layout.field_split_core import ( + BaseSplitMatcher, + BaseSplitNormalization, + BaseSplitRule, + BaseSplitRuleSet, + BaseSplitSegment, + RelationCaptureDef, + new_segment_id, +) +from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import ( + FieldSourceCandidate, + ProfileFieldSourceMappingService, +) +from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import ( + NamedRegion, + ProfileFieldSourceMapping, + ReservationFormatPolicy, + field_source_mappings_checksum, + field_source_mappings_require_draft, + named_regions_checksum, + parse_field_source_mappings, + parse_named_regions, + profile_regions_require_draft, +) +from app.services.shipping_notice.document_layout.reservation_format_policy_service import ( + ReservationFormatPolicyService, +) +from app.services.shipping_notice.document_layout.reservation_relation_projection import ( + ReservationRelationProjection, +) +from app.services.shipping_notice.document_layout.source_merge_service import ( + SourceMergeService, +) +from app.services.shipping_notice.document_layout.order_profile import RelativeRegion + + +# ========================================================================= +# [TEST GROUP 1] profile_vendor_comments_contract(Q14/Q15) +# ========================================================================= + + +def test_parse_named_regions_empty_is_allowed(): + """当前客户没配 Vendor Comments 区域 → 返回空,不报错。""" + assert parse_named_regions(None) == {} + assert parse_named_regions({}) == {} + + +def test_named_region_last_page_vendor_comments_parses(): + """Q14 冻结结构:region_id/label/region/page_scope/selection_mode 全齐。""" + raw = { + 'vendor_comments': { + 'region_id': 'vendor-comments-v1', + 'label': 'Vendor Comments', + 'region': {'x0': 0.03, 'y0': 0.62, 'x1': 0.42, 'y1': 0.78}, + 'page_scope': 'last_page', + 'selection_mode': 'fixed_region', + }, + } + regions = parse_named_regions(raw) + assert 'vendor_comments' in regions + r = regions['vendor_comments'] + assert r.page_scope == 'last_page' + assert r.region.y1 > r.region.y0 + + +def test_named_region_rejects_key_region_id_mismatch(): + """外键 key 与 region_id 不一致:拒绝。""" + raw = {'vc': {'region_id': 'other-name', + 'label': 'L', 'region': {'x0':0,'y0':0,'x1':1,'y1':1}, + 'page_scope': 'last_page', 'selection_mode': 'fixed_region'}} + from app.core.errors import ValidationError + with pytest.raises(ValidationError): + parse_named_regions(raw) + + +def test_profile_regions_require_draft_matrix(): + """Q14:增删改 region/坐标/page_scope/selection_mode → 回 Draft;仅 label 不回。""" + old = { + 'vc': { + 'region_id': 'vc', 'label': 'Old Label', + 'region': {'x0':0,'y0':0,'x1':1,'y1':1}, + 'page_scope': 'last_page', 'selection_mode': 'fixed_region', + }, + } + # 仅改 label → 不回 Draft + new_same_label_only = {k: {**v, 'label': 'New Label'} for k, v in old.items()} + assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_same_label_only) is False + + # 改 x0 → 回 Draft + new_coord = {k: {**v} for k, v in old.items()} + new_coord['vc']['region'] = {'x0':0.01,'y0':0,'x1':1,'y1':1} + assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_coord) is True + + # 新增 region → 回 Draft + new_extra = { + **old, + 'other': { + 'region_id': 'other', 'label': 'O', + 'region': {'x0':0,'y0':0,'x1':0.1,'y1':0.1}, + 'page_scope': 'first_page', 'selection_mode': 'fixed_region', + }, + } + assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_extra) is True + + +def test_field_source_mappings_require_draft_any_change_triggers(): + """Q9:field_source_mappings 任何改 → 回 Draft(首期全量 fail-close)。""" + old = [{ + 'mapping_id': 'm1', 'target_scope': 'line', 'target_field_code': 'reservation_id', + 'target_field_id': 'f-r1', 'vendor_comments_enabled': False, + }] + new = [{ + 'mapping_id': 'm1', 'target_scope': 'line', 'target_field_code': 'reservation_id', + 'target_field_id': 'f-r1', 'vendor_comments_enabled': True, + 'vendor_comments_region_ref': 'vc', + 'vendor_comments_split_rule_set': { + 'rule_set_id': 'rs1', 'rule_version': 1, + 'normalization': {}, 'rules': [], + 'unmatched_line_policy': 'evidence_only', 'source': 'user', + 'status': 'confirmed', 'requires_confirmation': False, + }, + }] + assert field_source_mappings_require_draft(old_mappings=old, new_mappings=new) is True + + +def test_reservation_format_policy_rejects_dangerous_regex(): + """Q15:(a+)+$ 被 Pydantic validator 拦截在构造阶段。""" + from pydantic import ValidationError as PydanticValErr + with pytest.raises(PydanticValErr): + ReservationFormatPolicy( + mode='custom_safe_regex', + pattern=r'(a+)+$', + ) + + +# ========================================================================= +# [TEST GROUP 2] reservation_relation_projection(Q2/Q7/Q12) +# ========================================================================= + + +def test_relation_projection_bind_target_line_via_profile_business_line_no(): + """Q2:captured_relation.line_no=2 命中 profile_business_line_no{2:1} → 逻辑行号1。""" + from app.services.shipping_notice.document_layout.field_split_core import CoreCapturedRelation + proj = ReservationRelationProjection( + relation_policy='bind_target_line', + line_reference_basis='profile_business_line_no', + ) + result = proj.project( + captured_relation=CoreCapturedRelation(type='line_reference', line_no=2, raw_text='for line#2'), + profile_business_line_numbers={1: '1', 2: '2', 3: '3'}, + ) + assert result.resolution == 'bound_to_line' + assert result.resolved_logical_line_no == 2 # 逻辑行号=1-based mapping key + + +def test_relation_projection_invalid_line_reference_emits_independent_reason(): + """Q12:引用不存在的行 99 → invalid_line_reference 独立原因码。""" + from app.services.shipping_notice.document_layout.field_split_core import CoreCapturedRelation + proj = ReservationRelationProjection(relation_policy='bind_target_line') + result = proj.project( + captured_relation=CoreCapturedRelation(type='line_reference', line_no=99, raw_text='line#99'), + profile_business_line_numbers={1: '1', 2: '2'}, + ) + assert result.resolution == 'invalid_line_reference' + assert result.invalid_reference_line_no == 99 + assert result.audit_chain is not None + assert result.should_generate_header_observation is True # invalid 保留为头证据 + + +def test_relation_projection_annotation_only_writes_metadata(): + """annotation_only:不绑定行,不生成行 Observation,生成头元数据。""" + proj = ReservationRelationProjection(relation_policy='annotation_only') + result = proj.project( + captured_relation=None, + annotation_reason_override='customer_commentary_reservation', + ) + assert result.resolution == 'annotation_only' + assert result.annotation_reason == 'customer_commentary_reservation' + assert result.should_generate_line_observation is False + assert result.should_generate_header_observation is True + + +def test_relation_missing_policy_default_all_lines_flags_every_line(): + """missing_relation_policy=default_all_lines:每行都生成 Observation。""" + proj = ReservationRelationProjection( + relation_policy='bind_target_line', + missing_relation_policy='default_all_lines', + ) + result = proj.project(captured_relation=None) + assert result.resolution == 'default_all_lines' + assert result.should_generate_line_observation is True + + +# ========================================================================= +# [TEST GROUP 3] SourceMergeService(Q18 三来源裁决) +# ========================================================================= + + +def _make_cand(source, scope, code, line_no, value, *, + fv=True, frc=None, mapping_id='m1', target_field_id='f-r1', + hint='provisional') -> FieldSourceCandidate: + c = FieldSourceCandidate( + source=source, target_scope=scope, target_field_code=code, + target_field_id=target_field_id, value=value, normalized_value=value, + format_valid=fv, format_reason_code=frc, effective_line_no=line_no, + resolution_hint=hint, + evidence_quote=value, evidence_ref=f'{source}-ref', + evidence_metadata={'mapping_id': mapping_id}, + ) + c.conflict_group_key = (scope, code, line_no) + return c + + +def test_source_merge_same_value_merged_marks_metadata(): + """Q18 same_value_merge:三来源同值 3000098851 → resolution=same_value_merged。""" + candidates = [ + _make_cand('header_region', 'line', 'reservation_id', 1, '3000098851'), + _make_cand('table_column', 'line', 'reservation_id', 1, '3000098851'), + _make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851'), + ] + svc = SourceMergeService(candidates) + merged = svc.merge_and_decide() + assert len(merged) == 1 + m = merged[0] + assert m.accepted_value == '3000098851' + assert m.resolution == 'same_value_merged' + assert m.decision_status == 'accepted' + assert m.should_persist_observation is True + md = m.evidence_metadata + assert md['resolution'] == 'same_value_merged' + assert len(md['source_observations']) == 3 + assert 'vendor_comments' in md['resolution_meta'].get('merged_from_sources', []) + + +def test_source_merge_conflict_triggers_needs_review_no_accepted_value(): + """Q18 冲突:Header=3000098851, VC=3000098899 → accepted_value=None, needs_review。""" + candidates = [ + _make_cand('header_region', 'line', 'reservation_id', 1, '3000098851'), + _make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098899'), + ] + svc = SourceMergeService(candidates) + merged = svc.merge_and_decide() + assert len(merged) == 1 + m = merged[0] + assert m.accepted_value is None + assert m.resolution == 'needs_review' + assert m.decision_status == 'needs_review' + assert m.should_persist_observation is False + assert len(m.evidence_metadata['source_observations']) == 2 + assert len(m.conflicts) == 2 # 双冲突 + + +def test_source_merge_fill_missing_table_empty_filled_from_vc(): + """Q4 fill_missing:表列空,VC 提供值 → fill_missing 自动填补。""" + candidates = [ + _make_cand('table_column', 'line', 'reservation_id', 1, ''), + _make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851'), + ] + svc = SourceMergeService(candidates) + merged = svc.merge_and_decide() + m = merged[0] + assert m.accepted_value == '3000098851' + assert m.resolution == 'fill_missing' + md = m.evidence_metadata + assert md['resolution_meta']['accepted_source'] == 'vendor_comments' + + +def test_source_merge_annotation_only_never_becomes_accepted(): + """annotation_only / invalid_line_reference:永不升 accepted,永不生成有效 Observation。""" + candidates = [ + _make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851', hint='annotation_only'), + _make_cand('vendor_comments', 'line', 'reservation_id', 1, '123', hint='invalid_line_reference'), + ] + svc = SourceMergeService(candidates) + merged = svc.merge_and_decide() + assert len(merged) == 1 + m = merged[0] + assert m.should_persist_observation is False + assert m.decision_status == 'blocked' + assert len(m.evidence_metadata['source_observations']) == 2 + + +# ========================================================================= +# [TEST GROUP 4] 三来源候选收集(ProfileFieldSourceMappingService) +# ========================================================================= + + +def test_collect_candidates_table_and_header_scopes_are_independent(): + """Q4:不同 scope 独立保留,互不冲突。Header=300001, Line=300002 都被收集。""" + definition_json = { + 'field_source_mappings': [ + {'mapping_id': 'mh', 'target_scope': 'header', + 'target_field_code': 'reservation_id', 'target_field_id': 'f-hr', + 'header_source_enabled': True, 'header_source_ref': 'header-rid'}, + {'mapping_id': 'ml', 'target_scope': 'line', + 'target_field_code': 'reservation_id', 'target_field_id': 'f-lr', + 'table_source_enabled': True, 'table_column_code': 'reservation_id'}, + ], + } + svc = ProfileFieldSourceMappingService( + definition_json=definition_json, + header_observations_by_source_ref={ + 'header-rid': [{'value': '300001', 'evidence_ref': 'h-ref-1'}], + }, + table_column_values={ + 'reservation_id': [ + {'line_index': 0, 'value': '300002', 'evidence_ref': 'l1'}, + {'line_index': 1, 'value': '300003', 'evidence_ref': 'l2'}, + ], + }, + ) + cands = svc.collect_candidates() + header_cands = [c for c in cands if c.target_scope == 'header'] + line_cands = [c for c in cands if c.target_scope == 'line'] + assert len(header_cands) == 1 + assert header_cands[0].value == '300001' + assert len(line_cands) == 2 + line_values = sorted([c.value for c in line_cands]) + assert line_values == ['300002', '300003'] + # Header 与 Line 不同冲突组 + groups = {c.conflict_group_key for c in cands} + assert len(groups) == 3 # header+None / line+1 / line+2 + + +# ========================================================================= +# [TEST GROUP 5] FormatPolicyService(Q15) +# ========================================================================= + + +def test_format_policy_inherit_global_accepts_5_and_10_numeric(): + svc = ReservationFormatPolicyService() + r5 = svc.check(ReservationFormatPolicy(mode='inherit_global'), '12345') + r10 = svc.check(ReservationFormatPolicy(mode='inherit_global'), '1234567890') + r_alpha = svc.check(ReservationFormatPolicy(mode='inherit_global'), 'ABC12') + assert r5.valid is True and r5.normalized_value == '12345' + assert r10.valid is True and r10.normalized_value == '1234567890' + assert r_alpha.valid is False and r_alpha.reason_code == 'reservation_format_invalid' + assert r_alpha.should_block_auto_create is True + + +def test_format_policy_custom_safe_regex_uses_first_capture_group(): + """字母型 Reservation 预留(例如 R-12345)通过第 1 捕获组提取。""" + svc = ReservationFormatPolicyService() + policy = ReservationFormatPolicy( + mode='custom_safe_regex', + pattern=r'R[ -](\d{5,10})\b', + case_sensitive=False, + ) + r = svc.check(policy, 'please use R-3000098851 thanks') + assert r.valid is True + assert r.normalized_value == '3000098851' + + +# ========================================================================= +# [TEST GROUP 6] CoordinateRegionSourceAdapter smoke(小字典 bbox) +# ========================================================================= + + +def test_coordinate_region_adapter_last_page_reads_text(): + """last_page → page_no=2,返回可用原文 + bbox 证据。""" + def glyph(ch, x, y, page_w=800, page_h=1100, *, + prev_space=False, src_idx=0): + w = 10 + b = 'space' if prev_space else 'none' + return { + 'text': ch, + 'bbox': {'x0': x*page_w, 'y0': y*page_h, + 'x1': (x+0.01)*page_w, 'y1': (y+0.02)*page_h}, + 'boundary_before': b, + 'source_index': src_idx, + } + page1_glyphs = [glyph('A', 0.05, 0.1, src_idx=i) for i, A in enumerate('PageOne')] + page2_glyphs = [ + *(glyph(ch, 0.04 + i*0.015, 0.65, src_idx=100+i, prev_space=(ch == ' ')) + for i, ch in enumerate('Reservation 3000098851 for line#2')), + ] + page_bundle = { + 1: {'glyphs': page1_glyphs, 'page': {'width': 800, 'height': 1100}}, + 2: {'glyphs': page2_glyphs, 'page': {'width': 800, 'height': 1100}}, + } + region = NamedRegion( + region_id='vc', label='VC', + region=RelativeRegion(x0=0.01, y0=0.60, x1=0.80, y1=0.80), + page_scope='last_page', + selection_mode='fixed_region', + ) + adapter = CoordinateRegionSourceAdapter(region, page_bundle) + result = adapter.extract() + assert result.status == 'available' + assert result.page_no == 2 + assert '3000098851' in result.raw_text + assert 'line' in result.raw_text.lower() + + +# ========================================================================= +# [TEST GROUP 7] checksums 稳定性(防篡改) +# ========================================================================= + + +def test_checksums_deterministic_and_sensitive_to_content(): + regions = {'vc': NamedRegion( + region_id='vc', label='L', selection_mode='fixed_region', + region=RelativeRegion(x0=0, y0=0, x1=1, y1=1), + page_scope='last_page', + )} + h1 = named_regions_checksum(regions) + assert len(h1) == 64 + regions2 = dict(regions) + regions2['vc'].model_copy() # 内容相同 → hash 相同(copy 保持引用,直接 mutate 不行,因此换 label) + regions_diff = {'vc': NamedRegion( + region_id='vc', label='Changed Label But Still Same Content?', + selection_mode='fixed_region', + region=RelativeRegion(x0=0, y0=0, x1=1, y1=1), + page_scope='last_page', + )} + # Label 变化 → 不同 hash(label 进入 checksum,因为管理员 label 变更不触发回 Draft,但需要留痕) + h_diff = named_regions_checksum(regions_diff) + assert h1 != h_diff + + mappings = [ProfileFieldSourceMapping( + mapping_id='m1', target_scope='line', target_field_code='reservation_id', + target_field_id='f-r1', vendor_comments_enabled=False, + )] + mh1 = field_source_mappings_checksum(mappings) + assert len(mh1) == 64 diff --git a/backend/tests/test_task_retry_decision_service.py b/backend/tests/test_task_retry_decision_service.py index ba818f7b..a0e93b9e 100644 --- a/backend/tests/test_task_retry_decision_service.py +++ b/backend/tests/test_task_retry_decision_service.py @@ -15,6 +15,7 @@ from app.services.shipping_notice.task_retry_decision_service import ( ACTION_FETCH_INVENTORY, ACTION_NOOP, decide_retry_action_only, + _is_inventory_rpa_active, ) @@ -73,3 +74,52 @@ def test_decide_rpa_pending_already_running(): decided = decide_retry_action_only(task, scope='task') assert decided['action'] == ACTION_NOOP assert decided['reason_code'] == 'already_running' + + +def test_structured_failed_attempt_overrides_stale_rpa_pending(monkeypatch): + """逐源 Attempt 已失败时,旧 rpa_pending 摘要不得阻止用户手动重试。""" + task = _task(task_no='OT-FAILED', pending_human_reason='rpa_pending') + + class _Query: + calls = 0 + + def filter(self, *_args): + return self + + def order_by(self, *_args): + return self + + def first(self): + self.calls += 1 + if self.calls == 1: + return None + return SimpleNamespace(status='failed') + + monkeypatch.setattr( + 'app.models.ShippingTaskInventoryRpaAttempt.query', + _Query(), + raising=False, + ) + assert _is_inventory_rpa_active(task) is False + + +def test_structured_running_attempt_blocks_duplicate_retry(monkeypatch): + """逐源 Attempt 仍在运行时,必须拦截重复派发。""" + task = _task(task_no='OT-RUNNING', pending_human_reason=None) + + class _Query: + def filter(self, *_args): + return self + + def order_by(self, *_args): + return self + + def first(self): + return SimpleNamespace(status='running') + + monkeypatch.setattr( + 'app.models.ShippingTaskInventoryRpaAttempt.query', + _Query(), + raising=False, + ) + assert _is_inventory_rpa_active(task) is True diff --git a/backend/worker.py b/backend/worker.py index ca23321d..6d49346c 100644 --- a/backend/worker.py +++ b/backend/worker.py @@ -11,6 +11,7 @@ import argparse import logging import os import sys +from typing import Callable from app import create_app from app.jobs.context import JobContext @@ -54,12 +55,20 @@ def _resolve_config_name() -> str: return mapping.get(env_name, 'production') -def main(*, queues: list[str] | None = None, config_name: str | None = None) -> None: +def main( + *, + queues: list[str] | None = None, + config_name: str | None = None, + recovery_callback: Callable[[], int] | None = None, + recovery_interval_seconds: float = 60.0, +) -> None: """ 启动 worker 主循环。 Args: queues: 消费的队列名列表,如 ['kb'] 或 ['kb', 'shipping']。 config_name: Flask 配置名;默认 _resolve_config_name()。 + recovery_callback: 恢复回调函数,返回本轮处理计数;默认 None 关闭。 + recovery_interval_seconds: 两次 recovery tick 的最小间隔秒数;默认 60。 """ resolved_config = config_name or _resolve_config_name() logger = _configure_logging() @@ -74,8 +83,13 @@ def main(*, queues: list[str] | None = None, config_name: str | None = None) -> logger=logger, extras={'queues': queue_names}, ) - logger.info('Worker starting config=%s queues=%s', resolved_config, queue_names) - run_forever(ctx) + logger.info('Worker starting config=%s queues=%s recovery=%s', + resolved_config, queue_names, recovery_callback is not None) + run_forever( + ctx, + recovery_callback=recovery_callback, + recovery_interval_seconds=recovery_interval_seconds, + ) if __name__ == '__main__': diff --git a/backend/worker_shipping.py b/backend/worker_shipping.py index 8b07835b..c39913e7 100644 --- a/backend/worker_shipping.py +++ b/backend/worker_shipping.py @@ -4,11 +4,14 @@ backend/worker_shipping.py 用途:发货通知 worker 部署兼容入口(Compose / Supervisor 沿用此路径)。 依赖:multiprocessing、worker.main、Flask Config.SHIPPING_NOTICE_WORKER_CONCURRENCY。 逻辑:默认 --queues shipping;按 SHIPPING_NOTICE_WORKER_CONCURRENCY 启动进程池, - 数据库 SKIP LOCKED 保证同批版面 Job 并发领取安全。 + 数据库 SKIP LOCKED 保证同批版面 Job 并发领取安全; + 每个子进程独立挂接 Shipping Recovery Sweeper(recovery_callback), + 靠 FOR UPDATE SKIP LOCKED + pg_advisory_xact_lock 做天然互斥。 """ from __future__ import annotations import multiprocessing as mp +from typing import Callable from app import create_app from worker import _configure_logging, _resolve_config_name, main @@ -16,9 +19,27 @@ from worker import _configure_logging, _resolve_config_name, main def _worker_loop(worker_index: int) -> None: """启动一个 shipping 队列子进程,并使用独立日志标签区分并发执行。""" + from app.services.shipping_notice.shipping_recovery_sweeper_service import shipping_recovery_tick + from flask import current_app + log = _configure_logging(f'shipping-{worker_index}') log.info('shipping-worker process started index=%s', worker_index) - main(queues=['shipping'], config_name=_resolve_config_name()) + + config_name = _resolve_config_name() + child_app = create_app(config_name) + with child_app.app_context(): + recovery_interval = float(getattr( + current_app.config, + 'SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS', + 60, + ) or 60) + recovery_cb: Callable[[], int] = shipping_recovery_tick + main( + queues=['shipping'], + config_name=config_name, + recovery_callback=recovery_cb, + recovery_interval_seconds=recovery_interval, + ) def main_shipping() -> None: @@ -29,12 +50,27 @@ def main_shipping() -> None: Returns: None。主进程持续等待子进程;收到 KeyboardInterrupt 时终止并回收子进程。 """ + from app.services.shipping_notice.shipping_recovery_sweeper_service import shipping_recovery_tick + from flask import current_app + config_name = _resolve_config_name() bootstrap_app = create_app(config_name) concurrency = max(int(bootstrap_app.config.get('SHIPPING_NOTICE_WORKER_CONCURRENCY', 2) or 2), 1) if concurrency == 1: - main(queues=['shipping'], config_name=config_name) + with bootstrap_app.app_context(): + recovery_interval = float(getattr( + current_app.config, + 'SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS', + 60, + ) or 60) + recovery_cb: Callable[[], int] = shipping_recovery_tick + main( + queues=['shipping'], + config_name=config_name, + recovery_callback=recovery_cb, + recovery_interval_seconds=recovery_interval, + ) return log = _configure_logging('shipping-master') diff --git a/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md b/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md new file mode 100644 index 00000000..1fcfe776 --- /dev/null +++ b/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md @@ -0,0 +1,304 @@ +# 发货通知自动推进 MVP 方案 + +> 版本:MVP v1.0 +> 日期:2026-08-07 +> 目标:保留现有功能、自动推进、门禁、中断恢复、重试、审计、RPA 与 Chatflow,并支持多库存源路由,形成可供真实用户受控测试的发布候选版本。 + +## 1. MVP 目标与边界 + +### 1.1 目标主链路 + +```text +上传 +→ Extraction Run +→ Candidate / Review Case +→ 路由规则生成单源或多源候选 +→ 冻结候选集合 +→ 准备全部必要库存源 +→ 跨源库存匹配 +→ 行级实际库存源裁决 +→ Excel 生成 +→ 待人工上传或自动上传 +→ RPA 回执收口 +→ ShippingProcessingProjection +``` + +### 1.2 MVP 明确保留 + +- 固定模板解析与人工复核; +- 自动建单、自动推进和 Process Gate; +- 多库存源候选、库存 RPA、库存匹配和 Excel 生成; +- 任务级/对话级重试、Worker 重启恢复和 RPA 回调幂等; +- 审计、任务中心、复核工作台和 Chatflow 查询; +- 货代自动上传能力保留为独立开关。 + +### 1.3 MVP 不做 + +- 不立即删除历史字段、旧兼容入口或旧数据库状态值; +- 不引入 Temporal、Celery 或新的编排框架; +- 不让 Dify/Chatflow 直接写入订单、库存、Excel 或 RPA 事实; +- 不允许部分明细生成部分 Excel; +- 不把“库存源不唯一”误判为人工阻断。 + +## 2. 已冻结的三项关键决策 + +### A1:Gate 拆分 + +复用现有 4 个库存主 Gate,不新增两个独立 Gate 实例: + +```text +inventory_candidates_calculated +→ inventory_candidates_frozen +→ inventory_snapshots_ready +→ inventory_matched +``` + +短缺和冲突作为 `inventory_matched` Gate 的结构化阻断原因: + +```text +inventory_shortage +inventory_not_found +inventory_multi_file_conflict +inventory_stale_snapshot +inventory_fetch_failed +``` + +如现有合同已存在 `inventory_shortage_review` 或 `inventory_conflict_review` 编码,可作为兼容动作编码,但不新增独立 Gate 生命周期。 + +### C1:候选冻结存储 + +采用“结构化表为业务真相,Snapshot JSON 为不可变副本”: + +```text +Task / Execution + └─ InventoryCandidateSet + ├─ CandidateSource + └─ CandidateLine +``` + +候选记录至少保存: + +- `source_code`、候选顺序、候选来源; +- `routing_rule_id/version`; +- `reservation_id`、`part_number`; +- 输入指纹、库存源配置版本; +- 人工覆盖信息、冻结时间; +- 对应 `ShippingOrderSnapshot.source_manifest_json` 副本。 + +任务级候选集合用于默认范围,行级候选集合用于表达不同明细命中不同库存源。 + +### F2:Projection 状态 + +新增用户态 Projection 字段,保留底层旧枚举和历史兼容字段,不先改数据库状态约束。 + +用户态状态统一为: + +```text +running +waiting_human +retryable +failed +completed +cancelled +``` + +底层继续使用现有 `Execution`、`Gate`、`Attempt` 状态,由后端服务统一映射。前端、任务中心和 Chatflow 只消费 Projection。 + +## 3. 统一状态语义 + +| 用户态 | 典型底层事实 | 用户动作 | +|---|---|---| +| `running` | active / queued / running | 查看进度、刷新 | +| `waiting_human` | blocked_manual 或业务阻断 | 执行当前 Gate 的主要动作 | +| `retryable` | blocked_retryable / 可恢复外部失败 | 重试自动推进 | +| `failed` | failed_terminal 或不可恢复业务失败 | 查看原因、按权限处理 | +| `completed` | 所有必要 Gate passed | 查看摘要 | +| `cancelled` | Task/Execution 已取消 | 只读查看 | + +人工等待不是失败;RPA 网络错误、Worker 超时等技术问题优先表达为 `retryable`。 + +## 4. 多库存源业务规则 + +```text +单候选源 → resolved → 允许自动推进 +多候选源 → candidates_frozen → 允许建单和自动推进 +零候选/规则要求人工 → waiting_human +``` + +库存准备: + +1. 读取冻结候选集合,不重新读取可变路由规则; +2. 已有有效快照的源直接复用; +3. 缺少或过期快照的源按 `source_code` 独立创建幂等 Inventory RPA Trigger; +4. 等待所有必需候选源 ready 后进入匹配; +5. 某源技术失败进入 `retryable`,不能继续导出。 + +跨源匹配允许: + +```text +订单行 1 → 源 A +订单行 2 → 源 B +订单行 3 → 源 A +``` + +每行必须保存实际命中源、库存文件/行证据、数量和 Attempt。只有所有明细均 `ok`、足量、无冲突、快照有效,才允许生成 Excel。 + +## 5. 统一自动推进入口 + +所有触发方统一调用: + +```python +run_task_auto_progress( + task_no, + trigger, + expected_version=None, + idempotency_key=None, +) +``` + +入口包括:解析完成、复核确认、STP 自动建单、Gate 通过、任务/对话重试、Worker 重启恢复和 RPA 回调。 + +必须满足: + +- 同一 Task 最多一个活动推进 Job; +- 每个 Gate 执行前重新读取数据库事实; +- 已通过 Gate 不重复执行; +- 失败从失败 Gate 恢复; +- 重复确认返回已有 Task/Job; +- 取消后禁止继续推进; +- 迟到回调不能复活任务。 + +独立的 `ensure_inventory`、`match_inventory` 等历史入口可以保留兼容,但只能转发到统一 Orchestrator,不能绕过 Gate、幂等和审计。 + +## 6. Projection 合同 + +Projection 至少包含: + +```json +{ + "task_no": "SN-001", + "status": "running", + "stage": "inventory_fetch", + "current_gate": "inventory_snapshots_ready", + "blocking_reason": null, + "retryable": false, + "primary_action": null, + "facts": { + "inventory_source_status": "candidates_frozen", + "candidate_source_codes": ["A", "B"], + "prepared_source_codes": ["A"], + "pending_source_codes": ["B"], + "line_resolutions": [], + "export_state": "not_created", + "upload_state": "not_created" + } +} +``` + +`blocking_reason`、`primary_action` 使用对象,至少包含 `code`、`i18n_key` 和结构化详情。SSE 只发送刷新通知;重新进入页面、刷新和重新登录必须重新 GET Projection。 + +## 7. MVP Todo List + +| 编号 | 任务 | 主要范围 | 迁移 | 四语言 | +|---|---|---|---|---| +| 1 | 冻结契约文档 | 状态、Gate、候选、Projection、错误码 | 否 | 是 | +| 2 | 候选结构化存储 | 任务级/行级候选表、唯一约束、索引、Snapshot 副本 | 是 | 否 | +| 3 | 候选计算与冻结 | 路由规则版本、输入指纹、候选快照 | 否 | 否 | +| 4 | 多源库存准备 | 按源 Trigger、Attempt、run_no、回调幂等 | 视现有表结构 | 否 | +| 5 | 唯一 AutoProgress | 收口批次、确认、重试、回调、Worker 入口 | 通常否 | 否 | +| 6 | 跨源匹配 | 行级实际源和证据、全量 ok 才导出 | 视证据字段缺口 | 否 | +| 7 | 恢复与重试 | 统一决策、stale Job、取消和迟到回调保护 | 视唯一索引缺口 | 否 | +| 8 | Projection 完整化 | 新增用户态字段、facts、primary_action | 通常否 | 是 | +| 9 | 前端切换 | 页面、Stepper、任务中心、Chat 卡片只读 Projection | 否 | 是 | +| 10 | Dify/配置联调 | Chatflow 只读、开关、Worker、共享目录 | 否 | 否 | +| 11 | 后端合同测试 | 状态机、幂等、多源、回调、Projection | 否 | 否 | +| 12 | 前端行为测试 | 单一主状态、刷新/重登、多源展示 | 否 | 是 | +| 13 | 真实样本演练 | 单源、多源、短缺、冲突、重启、重复回调 | 否 | 否 | +| 14 | Go/No-Go | 汇总证据、锁定测试范围 | 否 | 否 | + +## 8. 推荐实施顺序 + +```text +契约冻结 +→ 候选表迁移 +→ 候选冻结 +→ 多源 RPA +→ 唯一 AutoProgress +→ 跨源匹配 +→ 恢复/重试 +→ Projection +→ 前端切换 +→ 配置联调 +→ 自动化测试 +→ 真实样本演练 +→ Go/No-Go +``` + +不可倒置: + +- Projection 未冻结前,不切前端; +- 候选结构未冻结前,不改多源 RPA; +- Orchestrator 未收口前,不增加新的重试入口; +- 回调幂等未通过前,不打开货代自动上传。 + +## 9. 周一建议配置和测试范围 + +建议初始配置: + +```text +SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true +SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true +SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true +SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true +SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false +``` + +周一先开放: + +- 固定模板真实样本; +- 单源和多源库存路由; +- 库存 RPA 和跨源匹配; +- Excel 生成; +- 短缺/冲突人工门禁; +- 失败重试和中断恢复。 + +货代自动上传作为独立开关,只有 Worker、Trigger、回调、未知结果恢复和回执归档全部验收通过后才开启。 + +## 10. 验收与 Go/No-Go + +### 必须通过 + +- 多候选库存源允许自动建单; +- 候选集合可冻结、可追溯、不可被新规则覆盖; +- 缺快照只触发对应源的 RPA; +- 所有必要源 ready 后才匹配; +- 行级实际命中源和证据完整; +- 冲突、短缺和未知结果进入正确状态; +- 未完成全量匹配时禁止 Excel; +- 同一 Task 无并行活动推进 Job; +- 重复确认、重复 Trigger、重复回调均幂等; +- 取消任务不被旧回调复活; +- 页面刷新和重新登录后状态一致; +- 前端不再自行猜测主状态; +- 数据库迁移、Redis、Worker、共享目录和真实样本演练通过。 + +### No-Go 条件 + +```text +存在多个并行自动推进核心 +无法判断当前恢复 Gate +多源候选被错误阻断为必须人工选择 +RPA 回调不幂等或可复活已取消任务 +Projection 缺少当前 Gate 或多源准备事实 +前端仍同时展示多个互相冲突的重试动作 +库存未全量匹配却生成 Excel +``` + +## 11. 相关权威文档 + +- [发货通知技术架构](technical.md) +- [库存源设计](inventory_source_plan.md) +- [门禁恢复契约](process-gate-recovery-contract.md) +- [门禁恢复验收](process-gate-recovery-acceptance.md) +- [复核工作台布局方案](review-workbench-layout-plan.md) + diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index 17ad2d19..e1e7542a 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -61,6 +61,8 @@ const ShippingAuditCenterPage = () => import("@/features/admin/modules/shipping-audit/ShippingAuditCenterPage.vue"); const ShippingProcessGateDiagnosticsPage = () => import("@/features/admin/modules/shipping-process-gates/ShippingProcessGateDiagnosticsPage.vue"); +const ShippingLegacyStpJobsPage = () => + import("@/features/admin/modules/shipping-legacy-stp-jobs/ShippingLegacyStpJobsPage.vue"); const ShippingOrderDocumentProfilesPage = () => import("@/features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue"); const OrderProfileVersionDetailPage = () => @@ -215,6 +217,12 @@ export const adminRoutes: RouteRecordRaw[] = [ component: ShippingProcessGateDiagnosticsPage, meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'process_gates', title: "门禁诊断" }, }, + { + path: "shipping-legacy-stp-jobs", + name: "AdminShippingLegacyStpJobs", + component: ShippingLegacyStpJobsPage, + meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'legacy_stp_jobs', title: "历史 STP Job" }, + }, { path: "shipping-order-document-profiles", name: "AdminShippingOrderDocumentProfiles", diff --git a/frontend/src/features/admin/api/shipping-legacy-stp-jobs.api.ts b/frontend/src/features/admin/api/shipping-legacy-stp-jobs.api.ts new file mode 100644 index 00000000..204181d6 --- /dev/null +++ b/frontend/src/features/admin/api/shipping-legacy-stp-jobs.api.ts @@ -0,0 +1,131 @@ +/** + * features/admin/api/shipping-legacy-stp-jobs.api.ts + * 用途:Phase 5-1 —— 管理员历史 STP Job(928/929 面板)HTTP API 客户端。 + * 依赖:requestJson / getAuthHeaders(shared/api/client & shared/utils/auth)。 + * 逻辑:GET list / GET detail;后端 URL 为 /api/admin/shipping-notice/legacy-stp-jobs。 + */ +import { getAuthHeaders } from '@/shared/utils/auth'; +import { requestJson } from '@/shared/api/client'; +import type { PaginatedResult } from '@/shared/types/pagination.types'; + +const auth = () => ({ headers: getAuthHeaders() }); + +export type LegacyStpJobRow = { + job_id: number; + domain: string; + job_type: string; + status: 'failed' | 'dead' | string; + business_ref: string | null; + reference_key: string | null; + case_no: string | null; + priority: number; + attempts: number; + max_attempts: number; + message: string | null; + error_message: string | null; + error_code: string | null; + blocking_reason: string | null; + retryable: boolean | null; + next_action: string | string[] | null; + retry_of_job_id: number | null; + created_by_id: number | null; + result_json_masked: Record | null; + payload_json_masked: Record | null; + created_at: string | null; + updated_at: string | null; + started_at: string | null; + finished_at: string | null; +}; + +export type LegacyStpJobCaseBacklink = { + case_id: number; + case_no: string; + status: string; + candidate_id: number | null; + confirmed_task_id: number | null; + document_id: number | null; + owner_user_id: number | null; + created_at: string | null; + updated_at: string | null; +}; + +export type LegacyStpJobReplayPlan = { + supported: boolean; + recommended_user_action: 'force_create' | 'create_revision' | string; + needs_replay_mode: boolean; + reconcile_and_progress_endpoint: string | null; +}; + +export type LegacyStpJobDetailPayload = { + job: LegacyStpJobRow; + case: LegacyStpJobCaseBacklink | null; + replay_plan: LegacyStpJobReplayPlan; +}; + +export type LegacyStpJobListFilters = { + status?: '' | 'failed' | 'dead'; + job_type?: string; + q?: string; + case_no?: string; + error_code?: string; + blocking_reason?: string; + created_from?: string; + created_to?: string; + sort?: string; +}; + +const EMPTY_FILTERS: Required = { + status: '', + job_type: '', + q: '', + case_no: '', + error_code: '', + blocking_reason: '', + created_from: '', + created_to: '', + sort: '-created_at', +}; + +export const DEFAULT_LEGACY_STP_JOB_FILTERS = EMPTY_FILTERS; + +export const LEGACY_STP_JOB_STATUS_OPTIONS = ['failed', 'dead'] as const; + +function normalizeDateTimeFilter(value?: string): string { + const raw = String(value || '').trim(); + if (!raw) return ''; + const date = new Date(raw); + if (Number.isNaN(date.getTime())) return raw; + return date.toISOString(); +} + +function buildListSearchParams(filters: LegacyStpJobListFilters, page: number, pageSize: number): URLSearchParams { + const params = new URLSearchParams({ + page: String(page), + page_size: String(pageSize), + }); + if (filters.status) params.set('status', filters.status); + if (filters.job_type) params.set('job_type', filters.job_type); + if (filters.q) params.set('q', filters.q); + if (filters.case_no) params.set('case_no', filters.case_no); + if (filters.error_code) params.set('error_code', filters.error_code); + if (filters.blocking_reason) params.set('blocking_reason', filters.blocking_reason); + if (filters.created_from) params.set('created_from', normalizeDateTimeFilter(filters.created_from)); + if (filters.created_to) params.set('created_to', normalizeDateTimeFilter(filters.created_to)); + if (filters.sort) params.set('sort', filters.sort); + return params; +} + +export function listAdminLegacyStpJobs( + page = 1, + pageSize = 25, + filters: LegacyStpJobListFilters = {}, +): Promise & { + filters: { domain: string; job_types: string[]; statuses: string[] }; +}> { + const params = buildListSearchParams(filters, page, pageSize); + return requestJson(`/api/admin/shipping-notice/legacy-stp-jobs?${params}`, auth()); +} + +export function getAdminLegacyStpJob(jobId: number): Promise { + return requestJson(`/api/admin/shipping-notice/legacy-stp-jobs/${encodeURIComponent(String(jobId))}`, auth()); +} diff --git a/frontend/src/features/admin/constants/modules.ts b/frontend/src/features/admin/constants/modules.ts index 91e67755..fe645edf 100644 --- a/frontend/src/features/admin/constants/modules.ts +++ b/frontend/src/features/admin/constants/modules.ts @@ -23,6 +23,7 @@ export interface ShippingConfigSubModuleMeta { | 'AdminShippingOrderExtractionRuns' | 'AdminShippingAudit' | 'AdminShippingProcessGates' + | 'AdminShippingLegacyStpJobs' | 'AdminShippingOrderDocumentProfiles'; path: | 'shipping-notice' @@ -32,6 +33,7 @@ export interface ShippingConfigSubModuleMeta { | 'shipping-order-extraction-runs' | 'shipping-audit' | 'shipping-process-gates' + | 'shipping-legacy-stp-jobs' | 'shipping-order-document-profiles'; labelKey: string; groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit'; @@ -75,6 +77,7 @@ export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [ { id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } }, { id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' }, { id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' }, + { id: 'legacy_stp_jobs', routeName: 'AdminShippingLegacyStpJobs', path: 'shipping-legacy-stp-jobs', labelKey: 'admin.nav.shippingLegacyStpJobs', groupKey: 'admin.nav.shippingRunAudit' }, { id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } }, { id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } }, ]; diff --git a/frontend/src/features/admin/modules/shipping-legacy-stp-jobs/ShippingLegacyStpJobsPage.vue b/frontend/src/features/admin/modules/shipping-legacy-stp-jobs/ShippingLegacyStpJobsPage.vue new file mode 100644 index 00000000..8c47f33d --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-legacy-stp-jobs/ShippingLegacyStpJobsPage.vue @@ -0,0 +1,420 @@ + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.spec.ts b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.spec.ts index a4dd652c..ac7fb9f7 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.spec.ts +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.spec.ts @@ -99,17 +99,17 @@ describe('OrderProfileXfaConfirmStep', () => { }); const wrapper = mountStep(); - await vi.waitFor(() => expect(wrapper.text()).toContain('datasets / data / ITEMS / DATA')); + await vi.waitFor(() => expect(wrapper.text()).toContain('datasets / data / ITEMS / DATA'), { timeout: 10000 }); expect(wrapper.find('input[type="radio"]').exists()).toBe(true); expect(wrapper.text()).toContain('创建前阻断项'); - }); + }, 15000); it('没有任何候选集合时才显示空状态', async () => { getFieldTree.mockResolvedValue({ tree: {} }); getCollections.mockResolvedValue({ collection_candidates: [], excluded_collection_candidates: [] }); const wrapper = mountStep(); - await vi.waitFor(() => expect(wrapper.text()).toContain('没有可用数据集')); + await vi.waitFor(() => expect(wrapper.text()).toContain('没有可用数据集'), { timeout: 10000 }); expect(wrapper.find('input[type="radio"]').exists()).toBe(false); - }); + }, 15000); }); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcMergePreviewTable.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcMergePreviewTable.vue new file mode 100644 index 00000000..a6cfa448 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcMergePreviewTable.vue @@ -0,0 +1,280 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue new file mode 100644 index 00000000..a6099971 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue @@ -0,0 +1,432 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue new file mode 100644 index 00000000..6a14c10c --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue @@ -0,0 +1,544 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue new file mode 100644 index 00000000..951d7514 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue @@ -0,0 +1,393 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue new file mode 100644 index 00000000..b084a50d --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue @@ -0,0 +1,921 @@ + + + + + + diff --git a/frontend/src/features/admin/types/admin.types.ts b/frontend/src/features/admin/types/admin.types.ts index 587f741d..3247576d 100644 --- a/frontend/src/features/admin/types/admin.types.ts +++ b/frontend/src/features/admin/types/admin.types.ts @@ -29,6 +29,7 @@ export type ShippingConfigSubModuleId = | 'order_extraction_runs' | 'shipping_audit' | 'process_gates' + | 'legacy_stp_jobs' | 'inventory_fields' | 'connections' | 'inventory_sites' diff --git a/frontend/src/features/admin/types/shipping-order-document-profile.vc.types.ts b/frontend/src/features/admin/types/shipping-order-document-profile.vc.types.ts new file mode 100644 index 00000000..d8cb071f --- /dev/null +++ b/frontend/src/features/admin/types/shipping-order-document-profile.vc.types.ts @@ -0,0 +1,365 @@ +/** + * features/admin/types/shipping-order-document-profile.vc.types.ts + * 用途:Vendor Comments(普通 PDF 物理区域 + 三来源合并)阶段 2/3 前端契约类型定义。 + * 不修改既有 shipping-order-document-profile.types.ts(单文件不超 1000 行红线)。 + * 依赖:BaseSplit* 对齐 field_split_core.py;NamedRegion / FieldSourceMapping 严格对齐 + * profile_vendor_comments_contract.py;format_policy 对齐 reservation_format_policy_service.py。 + * 逻辑:后端决定 UI —— 所有稳定诊断码、合并决议枚举、冲突分组键、回 Draft 标志位 + * 全部通过后端 API 返回,前端不得自行 if/else 推导业务状态。 + */ + +import type { OrderProfileRelativeRegion } from './shipping-order-document-profile.types'; + +// ========================================================================= +// Section A: named_regions 契约(Q14)——Profile 顶层命名区域 +// ========================================================================= + +export type VCNamedRegionPageScope = + | 'first_page' + | 'last_page' + | 'all_pages' + | 'exact_page'; + +export type VCNamedRegionSelectionMode = + | 'fixed_region' + | 'auto_take_last_qualified'; + +export interface VCNamedRegion { + region_id: string; + label: string; + region: OrderProfileRelativeRegion; + page_scope: VCNamedRegionPageScope; + page_no?: number | null; + selection_mode: VCNamedRegionSelectionMode; +} + +export type VCNamedRegionsMap = Record; + +// ========================================================================= +// Section B: Reservation format_policy 契约(Q15)——Profile 级校验策略 +// ========================================================================= + +export type VCFormatPolicyMode = + | 'inherit_global' + | 'numeric_5_or_10' + | 'custom_safe_regex'; + +export interface VCReservationFormatPolicy { + mode: VCFormatPolicyMode; + pattern?: string | null; + /** custom_safe_regex 发布前必须过 Pydantic 的捕获组限制门禁 */ + max_capture_groups: number; + timeout_ms: number; + case_sensitive: boolean; +} + +// ========================================================================= +// Section C: Base Split Core(共享引擎)契约——对齐 field_split_core.py +// 前端类型必须完全复用 XfaSplit*;为避免引入 XFA 专属 path_id 歧义, +// 这里新建轻量别名。未来与 XfaSplit 统一后移除别名。 +// ========================================================================= + +export type VCSplitMatcherType = 'prefix' | 'regex' | 'position'; +export type VCSplitHandling = 'mapped' | 'evidence_only'; + +export interface VCSplitRelationCaptureDef { + type: 'line_reference' | string; + capture_group: number; + labels?: string[] | null; +} + +export interface VCSplitMatcher { + type: VCSplitMatcherType; + line_index?: number | null; + value?: string | null; + separators?: string[]; + case_sensitive?: boolean; + pattern?: string | null; + capture_group?: number | null; + relation_capture?: VCSplitRelationCaptureDef | null; +} + +export interface VCSplitSegment { + segment_id: string; + segment_code: string; + display_name: string; + handling: VCSplitHandling; + target_field_id?: string | null; + target_field_code?: string | null; + note?: string | null; +} + +export interface VCSplitRule { + rule_id: string; + matcher?: VCSplitMatcher | null; + segment: VCSplitSegment; + order: number; +} + +export interface VCSplitNormalization { + trim?: boolean; + remove_empty_lines?: boolean; + line_breaks?: string[]; +} + +export interface VCSplitRuleSet { + rule_set_id: string; + rule_version: number; + normalization?: VCSplitNormalization; + rules: VCSplitRule[]; + unmatched_line_policy?: 'evidence_only' | 'needs_review'; + duplicate_match_policy?: 'needs_review'; + same_field_multiple_segment_policy?: 'needs_review'; + source?: 'system_suggestion' | 'user' | 'imported'; + status?: 'draft' | 'confirmed' | 'published'; + requires_confirmation?: boolean; +} + +// ========================================================================= +// Section D: field_source_mappings 契约(Q9/Q18)——三来源字段来源映射 +// ========================================================================= + +export type VCRelationPolicy = + | 'no_relation' + | 'bind_target_line' + | 'annotation_only'; + +export type VCMissingRelationPolicy = + | 'default_all_lines' + | 'default_header_only' + | 'fallback_single_line_when_no_reference'; + +export type VCLineReferenceBasis = + | 'explicit_line_column' + | 'profile_business_line_no' + | 'classified_logical_line_no'; + +export interface VCProfileFieldSourceMapping { + mapping_id: string; + target_scope: 'header' | 'line'; + target_field_code: string; + target_field_id: string; + + header_source_enabled: boolean; + header_source_ref?: string | null; + header_normalizer_key?: string | null; + + table_source_enabled: boolean; + table_column_code?: string | null; + + vendor_comments_enabled: boolean; + vendor_comments_region_ref?: string | null; + vendor_comments_split_rule_set?: VCSplitRuleSet | null; + + relation_policy: VCRelationPolicy; + missing_relation_policy: VCMissingRelationPolicy; + line_reference_basis: VCLineReferenceBasis; + + fill_missing_from_other_sources: boolean; + format_policy: VCReservationFormatPolicy; +} + +// ========================================================================= +// Section E: 三来源候选 + 合并结果(SourceMergeService)——后端决定 UI +// 后端返回结构化决议,前端只负责渲染按钮/高亮,不推导状态。 +// ========================================================================= + +export type VCFieldSourceKind = + | 'header_region' + | 'table_column' + | 'vendor_comments'; + +export type VCMergeResolution = + | 'same_value_merged' + | 'fill_missing' + | 'needs_review' + | 'no_value' + | 'single_source_direct' + | 'annotation_only_dropped'; + +export type VCObservationDecisionStatus = + | 'accepted' + | 'needs_review' + | 'blocked' + | 'missing'; + +export interface VCSourceObservationSnapshot { + source: VCFieldSourceKind; + value: string; + normalized_value: string; + evidence_ref: string | null; + evidence_quote: string | null; + line_no_in_source: number | null; + format_valid: boolean | null; + format_reason_code: string | null; + extra: Record; +} + +export interface VCMergedObservationCandidate { + target_scope: 'header' | 'line'; + target_field_code: string; + target_field_id: string; + effective_line_no: number | null; + accepted_value: string | null; + decision_status: VCObservationDecisionStatus; + resolution: VCMergeResolution; + source_observations: VCSourceObservationSnapshot[]; + conflicts: Array>; + evidence_quote: string | null; + evidence_ref: string | null; + evidence_metadata: { + source_observations: VCSourceObservationSnapshot[]; + resolution: VCMergeResolution; + accepted_value: string | null; + conflicts: Array>; + resolution_meta: Record; + primary?: { + source: VCFieldSourceKind; + evidence_ref: string | null; + line_no: number | null; + } | null; + }; + source_type: string; + extractor: string; + /** 前端只读门禁:是否允许作为有效 Observation 落库 */ + should_persist_observation: boolean; +} + +// ========================================================================= +// Section F: 关系投影诊断码(Q2/Q12)——invalid_line_reference 独立审计链 +// ========================================================================= + +export type VCRelationProjectionResolution = + | 'bound_to_line' + | 'annotation_only' + | 'default_all_lines' + | 'default_header_only' + | 'invalid_line_reference' + | 'conflict_unresolved'; + +export interface VCRelationProjectionResult { + line_reference_basis: VCLineReferenceBasis; + resolution: VCRelationProjectionResolution; + resolved_logical_line_no: number | null; + annotation_reason: string | null; + invalid_reference_raw_value: string | null; + invalid_reference_line_no: number | null; +} + +// ========================================================================= +// Section G: 区域预览诊断(CoordinateRegionSourceAdapter) +// ========================================================================= + +export type VCCoordinateRegionStatus = 'available' | 'unavailable'; + +export interface VCCoordinateRegionEvidenceToken { + page_no: number; + text: string; + x0: number; + y0: number; + x1: number; + y1: number; +} + +export interface VCCoordinateRegionSourceResult { + region_id: string; + label: string; + status: VCCoordinateRegionStatus; + page_no: number | null; + raw_text: string; + lines: string[]; + evidence_tokens: VCCoordinateRegionEvidenceToken[]; + diagnostic_code: string | null; + diagnostic_message: string | null; +} + +// ========================================================================= +// Section H: Profile 变更回 Draft 判定(前端门禁标志位,真实判定在后端) +// 前端只展示警告,不阻断保存(最终拦截在 service 层)。 +// ========================================================================= + +export interface VCProfileDraftTrigger { + named_regions_changed: boolean; + field_source_mappings_changed: boolean; + requires_draft_reset: boolean; + /** 前端展示给管理员的中文/英文说明;实际文案通过 t() 取 i18n */ + reasons: Array<{ + kind: + | 'named_region_added' + | 'named_region_removed' + | 'named_region_geometry' + | 'named_region_scope' + | 'field_source_mapping_added' + | 'field_source_mapping_removed' + | 'field_source_mapping_split_rule_changed' + | 'field_source_mapping_format_policy_changed'; + region_id?: string; + mapping_id?: string; + }>; +} + +// ========================================================================= +// Section I: definition_json 顶层 VC 扩展(OrderCoordinateProfileDefinition +// 和 OrderXfaDatasetProfileDefinition 都通过交叉引用)。 +// 不修改既有 definition 接口,单独 export 用于 patch 合并。 +// ========================================================================= + +export interface VCProfileDefinitionExtensions { + named_regions?: VCNamedRegionsMap | null; + field_source_mappings?: VCProfileFieldSourceMapping[] | null; +} + +export type VCProfileDefinitionWithExtensions = + & { named_regions?: VCNamedRegionsMap | null; field_source_mappings?: VCProfileFieldSourceMapping[] | null } + & Record; + +// ========================================================================= +// Section J: 合成预览 DTO(后端返回,前端只读) +// ========================================================================= + +export interface VCSplitEngineSegmentPreview { + segment_id: string; + segment_code: string; + display_name: string; + line_no?: number | null; + line_end_no?: number | null; + raw_text: string; + normalized_text: string; + handling: VCSplitHandling; + target_field_id?: string | null; + target_field_code?: string | null; + rule_id: string; + status: string; + matcher_type: string; + captured_relation?: { + type: string; + line_no: number | null; + raw_text: string | null; + } | null; +} + +export interface VCSplitEnginePreviewResult { + status: 'parsed' | 'needs_review' | 'unavailable'; + rule_set_id: string | null; + rule_version: number | null; + mapped_fields: Record; + segments: VCSplitEngineSegmentPreview[]; + evidence_only_segments: VCSplitEngineSegmentPreview[]; + diagnostics: Array<{ + code: string; + message: string; + line_no?: number | null; + field_code?: string | null; + rule_ids?: string[]; + }>; +} + +export interface VCMergePreviewResponse { + document_id: number; + region_id: string; + mapping_id: string; + region_result: VCCoordinateRegionSourceResult | null; + split_preview: VCSplitEnginePreviewResult | null; + relation_projection: VCRelationProjectionResult | null; + merged_observation: VCMergedObservationCandidate | null; +} diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index fbbb02af..025b39be 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -33,9 +33,11 @@ import type { OrderExtractionSubmissionRequest, OrderExtractionSubmissionResponse, ConversationProcessingProjection, + ConversationProcessingAppendBlockReason, ShippingOrderReviewAuditTimelinePage, ShippingTaskAuditTimelinePage, ShippingOrderReviewCase, + ShippingOrderReviewCaseSnapshot, ShippingOrderReviewCustomerResolution, ShippingOrderReviewDuplicate, ShippingOrderReviewFieldConflict, @@ -55,6 +57,7 @@ import type { ShippingOrderReviewLlmSuggestionResponse, ShippingOrderReviewReparseResponse, ShippingOrderReviewRun, + ShippingTaskInventoryCandidatesResponse, ShippingTaskUiState, } from '../types/shipping.api.types'; @@ -70,6 +73,8 @@ type ShippingApiStatusPayload = { /** 批次重试等接口返回的跳过任务数 */ skipped?: number; batch_no?: string; + /** 后端返回的语义化原因码(对齐 noop / needs_human / already_running 等状态分支) */ + reason_code?: ConversationProcessingAppendBlockReason | string | null; }; export type ShippingChatAgentOption = { @@ -379,7 +384,7 @@ export const getWorkspaceShippingOrderReviewRun = (runNo: string) => /** 获取一份 PDF 的冻结 Schema 与只读机器/草稿投影。 */ export const getWorkspaceShippingOrderReviewCase = (caseNo: string) => - requestJson( + requestJson( `/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}`, ); @@ -491,6 +496,22 @@ export const putWorkspaceShippingOrderReviewInventoryCandidates = ( { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }, ); +/** + * 读取正式 Task 当前库存候选版本与历史摘要。 + */ +export const getWorkspaceTaskInventoryCandidates = ( + taskNo: string, + options?: { version?: 'current' | number; includeHistory?: boolean }, +) => { + const params = new URLSearchParams(); + if (options?.version != null) params.set('version', String(options.version)); + if (options?.includeHistory != null) params.set('include_history', String(options.includeHistory)); + const query = params.toString(); + return requestJson( + `/api/workspace/shipping-notice/tasks/${encodeURIComponent(taskNo)}/inventory-candidates${query ? `?${query}` : ''}`, + ); +}; + /** * 重新匹配整单或指定明细的库存路由规则。 * 核心逻辑:携带 expected_draft_version 与幂等键;可选 line_key 限定单行。 diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue index 57c66dde..10427ebb 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue @@ -1,43 +1,71 @@ diff --git a/frontend/src/features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts index d956cbe4..eb5a472d 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.spec.ts @@ -57,7 +57,7 @@ describe('ReviewInventoryCandidatesPanel', () => { expect(text).toContain('DSV360_AWSDU'); expect(text).toContain('DSV360_AWSSG'); expect(text).toContain('ROUTE_HINT_AWSSG'); - expect(text).toContain('命中规则'); + expect(text).toContain('匹配规则'); expect(text).toContain('库存源未启用'); expect(wrapper.find('[data-testid="review-inventory-unavailable-sources"]').text()).toContain('DSV360_AWSSG'); expect( diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLlmSuggestionPanel.vue b/frontend/src/features/chat/components/shipping-review/ReviewLlmSuggestionPanel.vue index 525be31a..36b03ccb 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLlmSuggestionPanel.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewLlmSuggestionPanel.vue @@ -56,6 +56,11 @@ const unavailableSuggestions = computed(() => (props.suggestions || []).filter((item) => String(item.status || '') === 'provider_unavailable'), ); +/** 前门禁失败(未调用 Dify)的记录必须明确展示,错误码指向 i18n errors.json;避免用户误认为 AI 已跑过。 */ +const gatedFailedSuggestions = computed(() => + (props.suggestions || []).filter((item) => String(item.status || '') === 'gated_failed'), +); + /** 将 Provider 失败码转成可执行的业务提示,不向用户暴露底层地址或异常正文。 */ function unavailableMessage(item?: ShippingOrderReviewLlmSuggestion): string { if (String(item?.error_code || '') === 'SHIPPING.REVIEW_LLM_DISABLED') { @@ -64,6 +69,31 @@ function unavailableMessage(item?: ShippingOrderReviewLlmSuggestion): string { return t('chat.shippingOrderReview.llmSuggestion.unavailableProvider'); } +/** + * 门禁失败 short 提示(一层标题):用 errors.json 本地化;缺失时给通用提示避免裸 code。 + * 完全消费后端投影的 item.error_code,前端绝对不推导「为什么失败」。 + */ +function gatedShortMessage(item: ShippingOrderReviewLlmSuggestion): string { + const code = String(item.error_code || ''); + const key = `errors.${code}`; + if (code && te(key)) return t(key); + return t('chat.shippingOrderReview.llmSuggestion.status.gated_failed'); +} + +/** + * 门禁失败 detail 提示(二层详情):查 errors.json 的 `${code}Detail` 或通用 hint。 + * 同样不推导原因,纯 i18n 查表。 + */ +function gatedDetailMessage(item: ShippingOrderReviewLlmSuggestion): string | null { + const code = String(item.error_code || ''); + if (!code) return null; + const detailKey = `errors.${code}Detail`; + if (te(detailKey)) return t(detailKey); + const hintKey = `chat.shippingOrderReview.llmSuggestion.gateDetail.${code.replace(/^SHIPPING\./, '')}`; + if (te(hintKey)) return t(hintKey); + return null; +} + const statusLabel = computed(() => { if (props.suggestionLoading) return t('chat.shippingOrderReview.llmSuggestion.status.pending'); const latest = (props.suggestions || [])[0]; @@ -218,8 +248,59 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s > {{ unavailableMessage(unavailableSuggestions[0]) }} +
    +
  • +
    +
    +
    {{ suggestionFieldLabel(item) }}
    +

    {{ gatedShortMessage(item) }}

    +

    + {{ gatedDetailMessage(item) }} +

    +

    + + {{ t('chat.shippingOrderReview.llmSuggestion.evidenceLevelLabel') }}:{{ evidenceLevelLabel(item.evidence_summary.level) }} + + + {{ t('chat.shippingOrderReview.llmSuggestion.autoUpgradedLabel') }} + + + {{ t('chat.shippingOrderReview.llmSuggestion.fieldCountLabel') }}:{{ item.evidence_summary.field_count }} + + + {{ t('chat.shippingOrderReview.llmSuggestion.contextTruncatedLabel') }} + +

    +
    + +
    +
  • +

{{ t('chat.shippingOrderReview.llmSuggestion.empty') }} diff --git a/frontend/src/features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts index d9c98b11..5fef61c3 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts @@ -34,10 +34,12 @@ const messages = { expandHistory: 'Show full track', collapseHistory: 'Hide full track', progress: { + title: 'Order processing', completedOfTotal: '{done} of {total} done', remainingHint: '{count} remaining', positionOfTotal: '{current} / {total}', currentNeedLabel: 'Need: ', + currentStage: 'Stage: {stage}', progressTitleWithStage: 'Order processing · {stage}', systemProcessingWithStage: 'System processing · {stage}', viewProcessDetails: 'View process details', @@ -53,6 +55,7 @@ const messages = { stage: Object.fromEntries(SHIPPING_PROCESSING_STAGES.map((s) => [s, s])), action: { refresh: 'Refresh', + confirm_customer: 'Confirm customer', }, }, }, @@ -61,6 +64,13 @@ const messages = { processGate: { actions: { wait_manual_upload: 'Wait for manual upload', + confirm_customer: 'Confirm customer', + retry_freight_upload_rpa: 'Retry freight upload RPA', + }, + actionCodes: { + wait_manual_upload: 'Wait for manual upload', + confirm_customer: 'Confirm customer', + retry_freight_upload_rpa: 'Retry freight upload RPA', }, }, }, diff --git a/frontend/src/features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue b/frontend/src/features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue index 833c4ed9..2751321f 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue @@ -65,7 +65,7 @@ const showTaskWorkbenchLink = computed(() => { v-else-if="processingProjection" :projection="processingProjection" :polling="polling" - :has-formal-ot="hasFormalOt || Boolean(String(taskNo || '').trim())" + :has-formal-ot="hasFormalOt || String(taskNo || '').trim().startsWith('OT-')" @open-process-details="emit('open-process-details')" @refresh="emit('refresh')" /> diff --git a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue index b6ea54ca..98f93399 100644 --- a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue +++ b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue @@ -268,7 +268,15 @@ function primaryActionItem(task: ConversationProcessingUserTask): ActionPresenta /** needs_action 的用户语义提示:不重复主按钮文案。 */ function currentNeedLabel(task: ConversationProcessingUserTask): string { if (task.group !== 'needs_action') return ''; - const action = String(task.primary_action || task.available_actions?.[0] || '').trim().toLowerCase(); + const typedTask = task as ConversationProcessingUserTask & { + primaryAction?: { code?: string } | null; + }; + const action = String( + typedTask.primaryAction?.code + ?? task.primary_action + ?? task.available_actions?.[0] + ?? '', + ).trim().toLowerCase(); const labels: Record = { confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer', resolve_field_conflicts: 'chat.shippingProcessing.currentNeed.resolveFieldConflicts', diff --git a/frontend/src/features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue b/frontend/src/features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue index 39d76c74..24887d5e 100644 --- a/frontend/src/features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue +++ b/frontend/src/features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue @@ -27,6 +27,7 @@ const emit = defineEmits<{ close: []; cancel: [item: ShippingWorkflowItem]; reparse: [item: ShippingWorkflowItem]; + openReview: [item: ShippingWorkflowItem]; refreshed: []; confirmCustomer: [taskNo: string]; }>(); @@ -70,6 +71,14 @@ const reparseActionLabel = computed(() => { return t('chat.shippingProcessing.actions.reparse'); }); +const canOpenReview = computed(() => { + if (!props.item) return false; + const actions = props.item.available_actions; + const status = String(props.item.lifecycle_status || '').trim(); + if (Array.isArray(actions)) return actions.includes('view_details') || actions.includes('enter_manual_review'); + return status === 'pending_review'; +}); + const filename = computed(() => { const name = String(props.item?.current_document_filename || '').trim(); if (name) return name; @@ -206,7 +215,7 @@ onBeforeUnmount(() => { >

@@ -3687,7 +3851,7 @@ watch( :machine-value="evidenceMachineValue" :value-source-label="evidenceValueSourceLabel" :show-ai-actions="editable" - :reset-key="activeCase?.case_no || null" + :reset-key="displayCase?.case_no || null" @close="closeEvidenceMode" @toggle-pin="togglePdfPinned" @toggle-expand="togglePdfExpanded" @@ -3702,9 +3866,9 @@ watch( @@ -3714,7 +3878,7 @@ watch( :item-no="reviewProgressContext?.item_no || itemNoFromQuery" :versions="versions" :loading="versionsLoading" - :active-case-no="activeCase?.case_no" + :active-case-no="requestedCaseNo || displayCase?.case_no" @close="closeVersionHistory" @select="(caseNo) => { closeVersionHistory(); void selectVersionFromHistory(caseNo); }" /> @@ -3758,7 +3922,7 @@ watch( :auto-gate-hint="t(autoGateHintKey)" :saving="saving" :is-read-only="isReadOnly" - :has-draft="Boolean(activeCase?.draft)" + :has-draft="Boolean(displayCase?.draft)" :unsaved-count="unsavedEditCount" :flow-presentation="flowPresentation" :automating="isProcessingAutomating" diff --git a/frontend/src/features/shipping-progress/actionPresentation.ts b/frontend/src/features/shipping-progress/actionPresentation.ts index 02201c75..273ef93d 100644 --- a/frontend/src/features/shipping-progress/actionPresentation.ts +++ b/frontend/src/features/shipping-progress/actionPresentation.ts @@ -67,8 +67,8 @@ const ACTION_CODE_TO_INTENT: Record = { const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']); const NEEDS_ACTION_STATUSES = new Set([ - 'blocked', 'waiting_review', 'pending_review', 'failed', 'reparse_failed', - 'manual_upload_pending', 'upload_rpa_failed', + 'blocked', 'waiting_review', 'pending_review', 'waiting_human', + 'failed', 'reparse_failed', 'manual_upload_pending', 'upload_rpa_failed', ]); /** 永不升为主 CTA 的动作码(仍可作次要/溢出)。 */ const NEVER_PRIMARY_CODES = new Set(['cancel_task', 'cancel_run', 'view_details']); @@ -217,7 +217,7 @@ export function resolveProcessingActionPresentation( items.push(toItem(code, intent, surface)); }; - pushCode(projection.currentGate?.nextActionCode); + pushCode(projection.primaryAction?.code || projection.currentGate?.nextActionCode); // [ORDER-STABLE] 对 availableActions 标准化(去重 + 字典序排序),确保后端返回顺序不影响前端按钮顺序。 const normalizedAvailableActions = normalizeActionCodes(projection.availableActions || []); for (const action of normalizedAvailableActions) { @@ -250,7 +250,9 @@ export function resolveConversationTaskActionPresentation( if (!task) return empty; const surface = options?.surface || 'right'; - const status = String(task.status_label || '').trim().toLowerCase(); + const userStatus = String(task.userStatus ?? '').trim().toLowerCase(); + const legacyStatus = String(task.status_label ?? '').trim().toLowerCase(); + const status = userStatus || legacyStatus; const isNeedsAction = task.group === 'needs_action' || NEEDS_ACTION_STATUSES.has(status); const isProcessing = task.group === 'processing' || AUTOMATING_STATUSES.has(status); if (task.group === 'history' || status === 'cancelled') { @@ -270,7 +272,7 @@ export function resolveConversationTaskActionPresentation( items.push(toItem(code, intent, surface)); }; - pushCode(task.primary_action); + pushCode(task.primaryAction?.code || task.primary_action); // [ORDER-STABLE] 对 available_actions 标准化排序,确保后端顺序变化不影响按钮渲染顺序。 const normalizedTaskActions = normalizeActionCodes(task.available_actions || []); for (const action of normalizedTaskActions) { diff --git a/frontend/src/features/shipping-progress/components/ReviewProgressStrip.spec.ts b/frontend/src/features/shipping-progress/components/ReviewProgressStrip.spec.ts index 0e45ff86..42f0eceb 100644 --- a/frontend/src/features/shipping-progress/components/ReviewProgressStrip.spec.ts +++ b/frontend/src/features/shipping-progress/components/ReviewProgressStrip.spec.ts @@ -69,10 +69,12 @@ function mountStrip(projection: ShippingProcessingProjection, polling = false) { }, shippingProcessing: { progress: { - completedOfTotal: '已完成 {done} / {total}', - currentNeedLabel: '当前需要:', + title: '订单处理进度', + currentStage: '当前阶段:{stage}', progressTitleWithStage: '订单处理进度 · {stage}', systemProcessingWithStage: '系统处理中 · {stage}', + completedOfTotal: '已完成 {done} / {total}', + currentNeedLabel: '当前需要:', viewProcessDetails: '查看流程详情', viewFullProcess: '查看完整流程', stageNodesUnavailable: '进度详情暂不可用', @@ -86,6 +88,7 @@ function mountStrip(projection: ShippingProcessingProjection, polling = false) { shippingNotice: { processGate: { actions: { confirm_customer: '确认客户', retry_freight_upload_rpa: '重试货代上传' }, + actionCodes: { confirm_customer: '确认客户', retry_freight_upload_rpa: '重试货代上传' }, }, }, }, diff --git a/frontend/src/features/shipping-progress/components/ReviewProgressStrip.vue b/frontend/src/features/shipping-progress/components/ReviewProgressStrip.vue index 604c795a..9e0be455 100644 --- a/frontend/src/features/shipping-progress/components/ReviewProgressStrip.vue +++ b/frontend/src/features/shipping-progress/components/ReviewProgressStrip.vue @@ -56,9 +56,49 @@ const isAutomating = computed(() => { }); /** - * 标题仅「订单处理进度」,阶段名由节点/窄屏摘要表达。 + * 标题:默认「订单处理进度 · 当前阶段」;自动推进状态切换为「系统处理中 · 当前阶段」; + * 无阶段名时退化为纯标题,保证标题行至少可读。 */ -const titleLine = computed(() => t('chat.shippingProcessing.progress.title')); +const titleLine = computed(() => { + const stage = currentStageName.value; + if (isAutomating.value) { + const withStage = te('chat.shippingProcessing.progress.systemProcessingWithStage'); + if (withStage && stage && stage !== '—') { + return t('chat.shippingProcessing.progress.systemProcessingWithStage', { stage }); + } + const fallback = t('chat.shippingProcessing.progress.title'); + return fallback; + } + const withStage = te('chat.shippingProcessing.progress.progressTitleWithStage'); + if (withStage && stage && stage !== '—') { + return t('chat.shippingProcessing.progress.progressTitleWithStage', { stage }); + } + return t('chat.shippingProcessing.progress.title'); +}); + +/** + * 当前需要文案:优先 blockingReasonCode → gateReasons;无则回退 nextActionCode → actionCodes; + * 自动推进状态 / 已生成正式 OT / 无有效 label 时不渲染。 + */ +const currentNeedLabel = computed(() => { + if (props.hasFormalOt) return null; + if (isAutomating.value) return null; + const gate = props.projection.currentGate; + if (!gate) return null; + const reasonCode = String(gate.blockingReasonCode || '').trim(); + if (reasonCode) { + const reasonKey = `chat.shippingProcessing.gateReasons.${reasonCode}`; + if (te(reasonKey)) return t(reasonKey); + } + const nextCode = String(gate.nextActionCode || '').trim(); + if (nextCode) { + const actionKey = `workspace.shippingNotice.processGate.actionCodes.${nextCode}`; + if (te(actionKey)) return t(actionKey); + const chatActionKey = `chat.shippingProcessing.action.${nextCode}`; + if (te(chatActionKey)) return t(chatActionKey); + } + return null; +}); /** * 窄屏当前阶段名:只用 stage code → 阶段 i18n,不用 waiting_system_start 等自动化 label_key。 @@ -115,6 +155,13 @@ function nodeShortLabel(stage: string): string { data-testid="review-progress-title" > {{ titleLine }} + + {{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel }} + ParserError chain. + 2) Spawns start_local.ps1 via Start-Process independent powershell.exe so the wrapper itself exits ASAP + and the IDE controlled terminal never sees "spawning multiple windows" (which gets Cancel-gated). + 3) Logs are timestamped + PID-suffixed to avoid "file in use by another process" when IDE watcher or + previous child still holds handles. + 4) Enforces: concurrency=1 (single instance) / no RPA worker / no hot reload by default. +#> +param( + [string]$DatabaseUrl = "postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/hxops_db", + [int]$KbConcurrency = 1, + [int]$ShippingConcurrency = 1, + [switch]$IncludeRpaWorker = $false, + [switch]$HotReload = $false +) + +$ErrorActionPreference = "Stop" + +function Remove-FileWithRetry { + param( + [string]$Path, + [int]$MaxRetries = 5, + [int]$SleepMs = 300 + ) + if (-not (Test-Path $Path)) { return } + for ($i = 1; $i -le $MaxRetries; $i++) { + try { + Remove-Item -Path $Path -Force -ErrorAction Stop + return + } catch { + if ($i -eq $MaxRetries) { throw } + Start-Sleep -Milliseconds $SleepMs + } + } +} + +function Write-LogLineShared { + param( + [string]$Path, + [string[]]$Lines, + [switch]$Append + ) + $mode = if ($Append) { [System.IO.FileMode]::Append } else { [System.IO.FileMode]::Create } + for ($i = 1; $i -le 5; $i++) { + try { + $fs = [System.IO.FileStream]::new( + $Path, + $mode, + [System.IO.FileAccess]::Write, + [System.IO.FileShare]::ReadWrite + ) + try { + $sw = [System.IO.StreamWriter]::new($fs, [System.Text.UTF8Encoding]::new($false)) + foreach ($l in $Lines) { $sw.WriteLine($l) } + $sw.Flush() + return + } finally { + if ($sw) { $sw.Dispose() } + $fs.Dispose() + } + } catch { + if ($i -eq 5) { throw } + Start-Sleep -Milliseconds 300 + $mode = [System.IO.FileMode]::Append + } + } +} + +$RepoRoot = Split-Path -Parent $PSScriptRoot +$LogsDir = Join-Path $RepoRoot ".local-logs" +if (-not (Test-Path $LogsDir)) { New-Item -ItemType Directory -Path $LogsDir | Out-Null } + +$StartScript = Join-Path $PSScriptRoot "start_local.ps1" + +# Log file naming: ide_start__.log/.err.log -> never collides with previous runs. +$ts = Get-Date -Format "yyyyMMddHHmmss" +$LogOut = Join-Path $LogsDir ("ide_start_{0}_{1}.log" -f $PID, $ts) +$LogErr = Join-Path $LogsDir ("ide_start_{0}_{1}.err.log" -f $PID, $ts) + +# Rotate: keep latest 8 of each pattern; remove older ones (with retry for watcher handles). +Get-ChildItem -Path $LogsDir -Filter "ide_start_*.log" -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending | + Select-Object -Skip 8 | + ForEach-Object { Remove-FileWithRetry -Path $_.FullName } +Get-ChildItem -Path $LogsDir -Filter "ide_start_*.err.log" -ErrorAction SilentlyContinue | + Sort-Object LastWriteTime -Descending | + Select-Object -Skip 8 | + ForEach-Object { Remove-FileWithRetry -Path $_.FullName } + +$now = Get-Date -Format "yyyy-MM-dd HH:mm:ss" +$tsLine = "[$now]" +Write-LogLineShared -Path $LogOut -Lines @( + "$tsLine wrapper: starting start_local.ps1 ...", + "$tsLine wrapper: DatabaseUrl = $DatabaseUrl", + "$tsLine wrapper: KbConcurrency=$KbConcurrency ShippingConcurrency=$ShippingConcurrency", + "$tsLine wrapper: IncludeRpaWorker=$IncludeRpaWorker HotReload=$HotReload" +) + +$argList = @( + "-NoProfile", + "-ExecutionPolicy", "Bypass", + "-File", "`"$StartScript`"", + "-DbMode", "postgres", + "-DatabaseUrl", "`"$DatabaseUrl`"", + "-KbConcurrency", "$KbConcurrency", + "-ShippingConcurrency", "$ShippingConcurrency" +) + if ($IncludeRpaWorker) { $argList += @("-IncludeRpaWorker") } + if (-not $HotReload) { $argList += @("-NoHotReload") } + +$spArgs = @{ + FilePath = "powershell.exe" + ArgumentList = $argList + RedirectStandardOutput = $LogOut + RedirectStandardError = $LogErr + WindowStyle = "Normal" + UseNewEnvironment = $false + PassThru = $true +} + +$proc = Start-Process @spArgs + +Write-LogLineShared -Append -Path $LogOut -Lines @( + "$tsLine wrapper: start_local.ps1 launched (child PID=$($proc.Id)).", + "$tsLine wrapper: stdout -> $LogOut", + "$tsLine wrapper: stderr -> $LogErr", + "$tsLine wrapper: wrapper exit=0 (child continues independently)." +) + +Write-Host "" +Write-Host "=== HXOPS Start OK ===" -ForegroundColor Green +Write-Host (" start_local child PID : " + $proc.Id) -ForegroundColor Cyan +Write-Host (" stdout log : " + $LogOut) -ForegroundColor Cyan +Write-Host (" stderr log : " + $LogErr) -ForegroundColor Cyan +Write-Host "" +Write-Host " Open the above log file(s) in the IDE to watch progress." +Write-Host " Phase order: cleanup -> db-migrate -> backend 5052 -> frontend 8881 -> kb-worker -> shipping-worker." +Write-Host "" diff --git a/scripts/reconcile_legacy_stp_jobs.py b/scripts/reconcile_legacy_stp_jobs.py new file mode 100644 index 00000000..17c381fa --- /dev/null +++ b/scripts/reconcile_legacy_stp_jobs.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python +""" +scripts/reconcile_legacy_stp_jobs.py + +用途:Phase 4-2 —— 历史 STP Job(如 928、929)批量对账恢复管理脚本。 +依赖:backend 虚拟环境 + backend.app Flask app;严格复用 + services.shipping_notice.reconciliation_service.reconcile_and_progress 主入口; + 禁止脚本内直写 SQL、直改 duplicate_status、或写独立业务规则。 +逻辑: + 1. 解析 CLI 参数:--user-id(管理员)、--case-nos(空格分隔、或 - 读 stdin)、 + --user-action(auto/create_revision/…,默认 auto)、--dry-run、--legacy-job-id(可选) + --replay-mode(可选,legacy_job_id 与 case_no 不匹配时强制重放) + 2. push Flask app context、初始化 SQLAlchemy。 + 3. 对每个 case_no: + - 生成客户端 operation_id(uuid4,脚本自产出;同时记录日志与 stdout) + - 调 reconcile_and_progress(user_id, case_no, operation_id, + user_action=…, is_admin=True, + legacy_job_id=…, replay_mode=…) + - 捕获 AppError/ConflictError/ValidationError → 不中断批处理, + 仅记录错误行,退出码为成功数!=总数量时返回 2 + 4. 输出结构化摘要(总数量 / 成功 / failed_technical / + duplicate_decision_required / ownership_anomaly_rejected / reused_existing / + stp_enqueued / idempotent_replay) +禁止事项(严格 fail-closed): + • 禁止绕过权限:必须显式 --user-id 且后台校验为管理员。 + • 禁止直写数据库:所有 Case/Job/Candidate 修改都通过 reconciliation_service。 + • 禁止与 reconcile_and_progress 不同的业务规则。 +""" + +from __future__ import annotations + +import argparse +import json +import logging +import sys +import uuid +from dataclasses import asdict, dataclass, field +from typing import Any + +LOGGER = logging.getLogger('reconcile_legacy_stp_jobs') +_OUTCOME_ORDER = [ + 'reused_existing', + 'stp_enqueued', + 'resume_result', + 'duplicate_decision_required', + 'ownership_anomaly_rejected', + 'idempotent_replay', + 'ERROR_VALIDATION', + 'ERROR_CONFLICT', + 'ERROR_APP', + 'ERROR_UNEXPECTED', +] + + +@dataclass +class RunSummary: + total: int = 0 + dry_run: bool = False + by_outcome: dict[str, int] = field( + default_factory=lambda: {k: 0 for k in _OUTCOME_ORDER}, + ) + cases: list[dict[str, Any]] = field(default_factory=list) + + def bump(self, outcome: str) -> None: + if outcome not in self.by_outcome: + self.by_outcome[outcome] = 0 + self.by_outcome[outcome] += 1 + + @property + def error_count(self) -> int: + return sum(v for k, v in self.by_outcome.items() if k.startswith('ERROR_')) + + @property + def success_count(self) -> int: + return self.total - self.error_count + + +def _build_arg_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + 'Reconcile legacy Shipping STP Jobs (e.g. 928/929) via the unified ' + 'reconciliation_service — never write raw SQL.' + ), + ) + parser.add_argument( + '--user-id', + type=int, + required=True, + help='Admin user id. Must be an existing admin (service-side checks role).', + ) + parser.add_argument( + '--user-action', + choices=['auto', 'reuse_existing', 'create_revision', 'force_create', 'adjudicate'], + default='auto', + help='Reconcile user_action passed to reconcile_and_progress.', + ) + case_src = parser.add_mutually_exclusive_group(required=True) + case_src.add_argument( + '--case-nos', + nargs='+', + metavar='CASE_NO', + help='One or more review case_no to process.', + ) + case_src.add_argument( + '--read-case-nos-from-stdin', + action='store_true', + help='Read case_no from STDIN (one per line, blank/comments ignored).', + ) + parser.add_argument( + '--legacy-job-id', + type=int, + default=None, + help='(Admin-only) Attach a specific failed/dead STP Job.id as legacy_job_id.', + ) + parser.add_argument( + '--replay-mode', + action='store_true', + help='Allow --legacy_job_id to reference a Job whose reference_key != case_no.', + ) + parser.add_argument( + '--expected-case-version', + type=int, + default=None, + help='Optional expected_case_version guard.', + ) + parser.add_argument( + '--dry-run', + action='store_true', + help='Validate + print plan; do NOT actually call reconcile_and_progress.', + ) + parser.add_argument( + '--json-output', + action='store_true', + help='Print a JSON summary to stdout at the end.', + ) + parser.add_argument( + '-v', + '--verbose', + action='count', + default=0, + help='Increase logging verbosity (-v: INFO, -vv: DEBUG).', + ) + return parser + + +def _read_case_nos_from_stdin() -> list[str]: + raw = sys.stdin.read().splitlines() + out: list[str] = [] + for line in raw: + s = line.strip() + if not s or s.startswith('#'): + continue + out.append(s) + return out + + +def _process_one( + *, + user_id: int, + case_no: str, + user_action: str, + expected_case_version: int | None, + legacy_job_id: int | None, + replay_mode: bool, +): + """ + 对单个 case_no 调 reconcile_and_progress;返回 (outcome, result_or_none, error_dict_or_none)。 + 所有业务路径都通过 reconciliation_service;禁止写任何 SQL。 + """ + from app import create_app, db # type: ignore # noqa: F401 — 仅在 app context 中引用 + from app.core.errors import AppError, ConflictError, ValidationError # noqa: F401 + from app.services.shipping_notice.reconciliation_service import reconcile_and_progress # noqa: F401 + + op_id = str(uuid.uuid4()) + kwargs: dict[str, Any] = { + 'user_id': int(user_id), + 'case_no': str(case_no).strip(), + 'operation_id': op_id, + 'user_action': user_action, # type: ignore[arg-type] + 'expected_case_version': expected_case_version, + 'source_content_hash': None, + 'is_admin': True, + 'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None), + 'replay_mode': bool(replay_mode), + } + try: + result = reconcile_and_progress(**kwargs) + except ValidationError as exc: + return 'ERROR_VALIDATION', None, { + 'code': getattr(exc, 'code', None), + 'message': str(getattr(exc, 'message', None) or str(exc)), + 'details': getattr(exc, 'details', None), + } + except ConflictError as exc: + return 'ERROR_CONFLICT', None, { + 'code': getattr(exc, 'code', None), + 'message': str(getattr(exc, 'message', None) or str(exc)), + 'details': getattr(exc, 'details', None), + } + except AppError as exc: + return 'ERROR_APP', None, { + 'code': getattr(exc, 'code', None), + 'message': str(getattr(exc, 'message', None) or str(exc)), + } + except Exception as exc: # noqa: BLE001 + LOGGER.exception('unexpected error processing case_no=%s', case_no) + return 'ERROR_UNEXPECTED', None, { + 'type': type(exc).__name__, + 'message': str(exc), + } + return str(result.outcome), result, None + + +def _main(argv: list[str] | None = None) -> int: + parser = _build_arg_parser() + args = parser.parse_args(argv) + + level = logging.WARNING + if args.verbose == 1: + level = logging.INFO + elif args.verbose >= 2: + level = logging.DEBUG + logging.basicConfig( + level=level, + format='%(asctime)s %(levelname)s %(name)s: %(message)s', + ) + + # 在函数内部 import app,便于从 backend/ 根用 python ../scripts/… 运行 + from app import create_app # type: ignore + + app = create_app() + with app.app_context(): + # 保证 session 已绑定;脚本内绝不直接操作 db.session。 + from app import db # type: ignore + _ = db.session + + if args.read_case_nos_from_stdin: + case_nos = _read_case_nos_from_stdin() + else: + case_nos = [ + str(c).strip() + for c in (args.case_nos or []) + if str(c).strip() + ] + if not case_nos: + print('ERROR: no case_no provided.', file=sys.stderr) + return 2 + + summary = RunSummary(total=len(case_nos), dry_run=bool(args.dry_run)) + for case_no in case_nos: + operation_id = str(uuid.uuid4()) # dry-run 时也产出 operation_id 用于审计 + if args.dry_run: + LOGGER.info( + '[DRY-RUN] case_no=%s user_action=%s user_id=%s operation_id=%s ' + 'legacy_job_id=%s replay_mode=%s', + case_no, args.user_action, args.user_id, operation_id, + args.legacy_job_id, args.replay_mode, + ) + summary.bump('resume_result') + summary.cases.append({ + 'case_no': case_no, + 'operation_id': operation_id, + 'outcome': 'DRY_RUN_PLANNED', + 'user_action': args.user_action, + 'legacy_job_id': args.legacy_job_id, + 'replay_mode': bool(args.replay_mode), + }) + continue + + outcome, result, err = _process_one( + user_id=int(args.user_id), + case_no=case_no, + user_action=str(args.user_action), + expected_case_version=args.expected_case_version, + legacy_job_id=args.legacy_job_id, + replay_mode=bool(args.replay_mode), + ) + summary.bump(outcome) + case_row: dict[str, Any] = { + 'case_no': case_no, + 'outcome': outcome, + 'user_action': args.user_action, + } + if result is not None: + case_row.update({ + 'operation_id': getattr(result, 'operation_id', None), + 'idempotency_key': getattr(result, 'idempotency_key', None), + 'match': dict(getattr(result, 'match') or {}), + 'task_no': getattr(result, 'task_no', None), + 'job_id': getattr(result, 'job_id', None), + 'message': getattr(result, 'message', None), + }) + m = getattr(result, 'match', None) if hasattr(result, 'match') else None + if isinstance(m, dict): + case_row.update({ + 'match_level': m.get('match_level'), + 'confidence': m.get('confidence'), + 'matched_task_no': m.get('task_no'), + }) + if err is not None: + case_row['error'] = err + if args.verbose: + LOGGER.info('case=%s outcome=%s', case_no, outcome) + summary.cases.append(case_row) + + # ===== 输出 ===== + if args.json_output: + print(json.dumps(asdict(summary), ensure_ascii=False, indent=2, default=str)) + else: + # 人类可读摘要 + print('==== Reconcile Legacy STP Jobs Summary ====') + print(f'total : {summary.total}') + print(f'dry_run : {summary.dry_run}') + for k in _OUTCOME_ORDER: + c = summary.by_outcome.get(k, 0) + if c: + print(f' {k:<32s}: {c}') + print(f'success : {summary.success_count}') + print(f'errors : {summary.error_count}') + + if summary.total == 0: + return 0 + if summary.error_count > 0: + return 2 + return 0 + + +if __name__ == '__main__': + raise SystemExit(_main()) diff --git a/scripts/repair_inventory_rpa_v2.py b/scripts/repair_inventory_rpa_v2.py new file mode 100644 index 00000000..1cdd56cd --- /dev/null +++ b/scripts/repair_inventory_rpa_v2.py @@ -0,0 +1,50 @@ +"""受控库存 RPA v2 repair 工具。 + +默认只做 dry-run;--apply 时仍调用正式 callback ingest API,不执行旁路 SQL。 +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path + + +def classify(path: Path, *, expected_source: str | None = None) -> str: + if not path.is_file(): + return 'rejected' + if path.suffix.lower() not in {'.xlsx', '.xls', '.csv'}: + return 'rejected' + if expected_source and expected_source.upper() not in path.name.upper(): + return 'needs_review' + return 'repaired' + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument('--payload', required=True, help='v2 callback JSON 文件') + parser.add_argument('--apply', action='store_true', help='调用正式 ingest;默认 dry-run') + args = parser.parse_args() + payload = json.loads(Path(args.payload).read_text(encoding='utf-8')) + items = payload.get('results') if isinstance(payload, dict) else None + if not isinstance(items, list): + print(json.dumps({'repair_result': 'rejected', 'error_code': 'callback_schema_invalid'}, ensure_ascii=False)) + return 2 + decisions = [] + for item in items: + item = dict(item or {}) + path = Path(str(item.get('file_path') or '')) + decisions.append({ + 'source_run_no': item.get('source_run_no'), + 'callback_id': item.get('callback_id'), + 'repair_result': classify(path, expected_source=item.get('source_code')), + }) + if not args.apply: + print(json.dumps({'dry_run': True, 'items': decisions}, ensure_ascii=False, indent=2)) + return 0 + # 正式 API 调用由部署环境注入;脚本不持有凭据,也不旁路写库。 + print(json.dumps({'apply_requested': True, 'items': decisions, 'next_action': 'POST /api/shipping-notice/rpa/inventory-repair'}, ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/scripts/rpa/download_artifact_fallback.py b/scripts/rpa/download_artifact_fallback.py new file mode 100644 index 00000000..986af416 --- /dev/null +++ b/scripts/rpa/download_artifact_fallback.py @@ -0,0 +1,76 @@ +""" +scripts/rpa/download_artifact_fallback.py + +用途:在浏览器实际已落盘但 Playwright 未返回 Download 对象时,按下载目录中的新文件构造兼容适配器。 +依赖:pathlib、shutil、time。 +逻辑:由 DSV 导出链路在 `expect_download` 超时后调用;不改变站点交互,只补文件系统兜底。 +""" + +from __future__ import annotations + +import shutil +import time +from pathlib import Path + + +class FilesystemDownloadArtifact: + """兼容 Playwright Download 的最小适配器,仅提供 `suggested_filename` 与 `save_as()`。""" + + def __init__(self, path: Path) -> None: + self._path = Path(path) + self.suggested_filename = self._path.name + + def save_as(self, dest: str) -> None: + target = Path(dest) + target.parent.mkdir(parents=True, exist_ok=True) + if self._path.resolve() == target.resolve(): + return + shutil.move(str(self._path), str(target)) + + +def wait_for_new_download_file( + *, + download_dir: str | Path, + baseline_names: set[str], + timeout_seconds: float = 12.0, + poll_seconds: float = 0.5, +) -> FilesystemDownloadArtifact | None: + """ + 等待下载目录里出现本次新生成且大小稳定的文件。 + + 核心逻辑:忽略 `.crdownload/.tmp` 等临时文件;优先接受 Excel/CSV 类产物, + 同时兼容 Chromium 在 `downloads_path` 中落下的无扩展名原始文件; + 连续两次观察到大小不变后,认为浏览器已完成落盘。 + """ + root = Path(download_dir) + if not root.is_dir(): + return None + + deadline = time.monotonic() + max(1.0, timeout_seconds) + stable_sizes: dict[Path, int] = {} + allowed_suffixes = {".xlsx", ".xls", ".xlsm", ".xltx", ".xltm", ".csv", ""} + transient_suffixes = {".crdownload", ".tmp", ".part"} + + while time.monotonic() < deadline: + candidates = [] + for path in root.iterdir(): + if not path.is_file(): + continue + if path.name in baseline_names: + continue + suffix = path.suffix.lower() + if suffix in transient_suffixes or suffix not in allowed_suffixes: + continue + candidates.append(path) + candidates.sort(key=lambda item: item.stat().st_mtime, reverse=True) + for path in candidates: + try: + size = path.stat().st_size + except OSError: + continue + last_size = stable_sizes.get(path) + if last_size is not None and last_size == size and size > 0: + return FilesystemDownloadArtifact(path) + stable_sizes[path] = size + time.sleep(max(0.1, poll_seconds)) + return None diff --git a/scripts/rpa/dsv_export_timeout_diagnostics.py b/scripts/rpa/dsv_export_timeout_diagnostics.py new file mode 100644 index 00000000..e6a099d3 --- /dev/null +++ b/scripts/rpa/dsv_export_timeout_diagnostics.py @@ -0,0 +1,47 @@ +""" +scripts/rpa/dsv_export_timeout_diagnostics.py + +用途:汇总 DSV Excel 导出等待超时现场,输出适合直接写入 worker.log 的诊断字符串。 +依赖:json、标准库。 +逻辑:由 dsv_report_export 在 `page.expect_download(...)` 超时时调用;不参与任何业务判断。 +""" + +from __future__ import annotations + +import json +from typing import Any + + +def build_download_timeout_log( + *, + report_name: str, + error_type: str, + error_message: str, + selected_frame_index: int | None, + selected_frame_name: str, + selected_frame_url: str, + report_state: dict[str, Any] | None, + export_controls: dict[str, Any] | None, + page_snapshot: str, +) -> str: + """ + 生成 DSV 导出等待超时诊断日志。 + + 核心逻辑:把当前报表、选中结果 frame、导出控件探针和页面快照压成一条 JSON, + 便于在不接 Debug Server 的情况下,直接从 worker.log 反推出导出按钮是否真实可见。 + + Returns: + str: 以 `[dsv-download-timeout]` 开头的单行日志。 + """ + payload = { + "report_name": str(report_name or ""), + "error_type": str(error_type or ""), + "error_message": str(error_message or "")[:500], + "selected_frame_index": selected_frame_index, + "selected_frame_name": str(selected_frame_name or "")[:120], + "selected_frame_url": str(selected_frame_url or "")[:300], + "report_state": report_state or {}, + "export_controls": export_controls or {}, + "page_snapshot": str(page_snapshot or "")[:2500], + } + return "[dsv-download-timeout] " + json.dumps(payload, ensure_ascii=False, default=str) diff --git a/scripts/rpa/dsv_report_export.py b/scripts/rpa/dsv_report_export.py index ffe4ae53..80b5359e 100644 --- a/scripts/rpa/dsv_report_export.py +++ b/scripts/rpa/dsv_report_export.py @@ -20,6 +20,7 @@ from rpa_common import click_visible_selector_or_text_in_root as _click_visible_ from rpa_common import env as _env from rpa_common import visible_locator as _visible_locator from rpa_common import visible_locator_in_root as _visible_locator_in_root +from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file import dsv_debug from dsv_debug import ( debug_dsv_page_snapshot as _debug_dsv_page_snapshot, @@ -27,6 +28,7 @@ from dsv_debug import ( emit_debug_event as _emit_debug_event, report_debug_event as _report_debug_event, ) +from dsv_export_timeout_diagnostics import build_download_timeout_log as _build_download_timeout_log import dsv_navigation from dsv_navigation import ( click_dsv_menu_item as _click_dsv_menu_item, @@ -1197,8 +1199,60 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An _wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms()) if not _dsv_report_has_inventory_data_rows(page): raise NoInventoryDataError("DSV report has no inventory data") - with page.expect_download(timeout=_browser_timeout_ms()) as download_info: - _click_dsv_export_excel(page) + download_dir = str(source.get("__download_dir") or "").strip() + baseline_names = set() + if download_dir: + try: + baseline_names = {path.name for path in Path(download_dir).iterdir() if path.is_file()} + except OSError: + baseline_names = set() + try: + with page.expect_download(timeout=_browser_timeout_ms()) as download_info: + _click_dsv_export_excel(page) + except Exception as exc: + selected = _find_dsv_report_result_frame(page) + selected_frame_index = selected[0] if selected is not None else None + selected_frame = selected[1] if selected is not None else None + selected_frame_name = "" + selected_frame_url = "" + if selected_frame is not None: + try: + selected_frame_name = str(selected_frame.name or "") + except Exception: + selected_frame_name = "" + try: + selected_frame_url = str(selected_frame.url or "") + except Exception: + selected_frame_url = "" + report_state = _get_dsv_report_result_state(selected_frame) if selected_frame is not None else {} + export_controls = _probe_dsv_report_export_controls(selected_frame) if selected_frame is not None else {} + print( + _build_download_timeout_log( + report_name=_dsv_report_name(source), + error_type=type(exc).__name__, + error_message=str(exc), + selected_frame_index=selected_frame_index, + selected_frame_name=selected_frame_name, + selected_frame_url=selected_frame_url, + report_state=report_state, + export_controls=export_controls, + page_snapshot=_debug_dsv_page_snapshot(page, target_text="Excel"), + ), + file=sys.stderr, + ) + if download_dir: + fallback_download = _wait_for_new_download_file( + download_dir=download_dir, + baseline_names=baseline_names, + ) + if fallback_download is not None: + print( + "[dsv-download-fallback] " + f"using downloaded file from directory because Playwright download event timed out: " + f"{fallback_download.suggested_filename}", + ) + return fallback_download + raise return download_info.value diff --git a/scripts/rpa/freight_rpa_worker.py b/scripts/rpa/freight_rpa_worker.py index fa45b9b5..7cd9a26c 100644 --- a/scripts/rpa/freight_rpa_worker.py +++ b/scripts/rpa/freight_rpa_worker.py @@ -40,6 +40,7 @@ from contextlib import contextmanager import json import os import shutil +import hashlib import sys import tempfile import time @@ -356,6 +357,26 @@ def _mask_secret(value: str) -> str: return f"{value[:4]}...{value[-4:]}" +def _resolve_tool_api_auth_debug() -> tuple[str, str]: + """ + 返回 Tool API 鉴权来源与脱敏后的 Key,供 Worker 启动日志快速排查环境变量问题。 + + 核心逻辑:按实际请求相同的优先级检查三个环境变量;只返回来源名与脱敏值,避免明文泄露。 + + Returns: + tuple[str, str]: `(source, masked_value)`;未配置时返回 `("missing", "")`。 + """ + for env_name in ( + "SHIPPING_NOTICE_TOOL_API_KEY", + "INTEGRATION_API_KEY", + "HXOPS_TOOLS_API_KEY", + ): + key = _env(env_name) + if key: + return env_name, _mask_secret(key) + return "missing", "" + + def _post_callback(path: str, payload: dict) -> None: """ 向 HXOPS 货代 Tool API 发送 JSON 回调。 @@ -818,6 +839,8 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) -> source = trigger.get("rpa_inventory_source") if not isinstance(source, dict): raise RuntimeError("inventory trigger missing rpa_inventory_source") + source = dict(source) + source["__download_dir"] = str(drop_dir) connector_type = _worker_connector_type(source) source_code = str(source.get("source_code") or "").strip() or connector_type or "UNKNOWN" _validate_inventory_source_for_rpa(source) @@ -965,7 +988,7 @@ def _configuration_test_callback_payload(run_no: str, results: list) -> dict: def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None: body = json.loads(trigger_path.read_text(encoding="utf-8")) - run_no = str(body.get("run_no") or trigger_path.stem).strip() + run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip() task_no = str(body.get("task_no") or "").strip() sources = body.get("inventory_sources") or [] failed_dir = trigger_path.parent / "failed" @@ -977,6 +1000,21 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe mode = "mock" if mock else "browser" results: list[dict[str, Any]] = [] + # v2 claimed 回调只记录领取事实,不代表业务成功。 + if body.get("schema_version") == "shipping_inventory_rpa.v2": + claimed_items = [] + for source in sources: + if isinstance(source, dict) and source.get("source_run_no"): + claimed_items.append({k: source.get(k) for k in ("task_no", "source_code", "attempt_no", "source_run_no", "lease_token")}) + try: + _post_callback("/api/shipping-notice/rpa/inventory-batch-claimed", { + "schema_version": "shipping_inventory_rpa.v2", "batch_run_no": run_no, + "claimed_at": datetime.utcnow().isoformat(), "worker_id": _env("SHIPPING_NOTICE_RPA_WORKER_ID", "worker"), + "items": claimed_items, + }) + except Exception as exc: + print(f"[inventory-batch] claimed callback failed: {exc}", file=sys.stderr) + def report_configuration_test_progress(source: dict) -> None: """实际操作站点前回传领取状态;进度回调故障不能中断库存导出。""" if str(body.get("trigger_type") or "").strip() != "configuration_test_batch": @@ -1009,6 +1047,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe "file_path": str(out_file), "task_no": task_no or None, "validation_run_no": source.get("validation_run_no"), + **{k: source.get(k) for k in ("task_no", "attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}, }) else: # 一个 Profile 对应一个独立浏览器登录态;同 Driver 的不同账号绝不能共用 session。 @@ -1025,6 +1064,8 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe # 同组的 Profile 相同,登录和导出期间使用同一组临时凭据。 with _profile_credentials(site_sources[0]): for index, source in enumerate(site_sources): + source = dict(source) + source["__download_dir"] = str(drop_dir) code = str(source.get("source_code") or "") wh = str(source.get("warehouse_id") or "") try: @@ -1043,7 +1084,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe _reset_crane_export_entry(page, entry_url) download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source) out_file = _save_batch_download(download, drop_dir, run_no, source) - results.append({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or None, "validation_run_no": source.get("validation_run_no")}) + results.append({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}}) print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}") except NoInventoryDataError as exc: results.append({"source_code": code, "warehouse_id": wh, "status": "skipped", "success": False, "skipped": True, "skip_reason": "no_inventory_data", "message": str(exc), "validation_run_no": source.get("validation_run_no")}) @@ -1072,11 +1113,14 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe elif trigger_type == "configuration_test_batch": callback_path = "/api/shipping-notice/rpa/inventory-configuration-test-batch-ready" callback_payload = { + "schema_version": "shipping_inventory_rpa.v2", + "callback_id": f"{run_no}:batch:C1", + "batch_run_no": run_no, "run_no": run_no, "validation_batch_id": body.get("validation_batch_id"), "batch_no": body.get("batch_no"), "rpa_mode": mode, - "results": results, + "results": [{**item, "callback_id": f"{run_no}:{item.get('source_run_no')}:C1"} for item in results], } else: callback_path = "/api/shipping-notice/rpa/inventory-batch-ready" @@ -1572,9 +1616,19 @@ def main() -> None: inv_processed = inv_trigger_dir / "processed" upload_processed = upload_trigger_dir / "processed" + api_base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/") + heartbeat_seconds = max( + 15, + int(_env("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"), + ) + auth_source, masked_auth = _resolve_tool_api_auth_debug() print("[freight_rpa_worker] started") print(f" mock={_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')}") + print(f" api_base={api_base}") + print(f" heartbeat_seconds={heartbeat_seconds}") + print(f" auth_source={auth_source}") + print(f" auth_key={masked_auth or 'missing'}") print(f" inventory_triggers={inv_trigger_dir}") print(f" upload_triggers={upload_trigger_dir}") print(f" drop={drop_dir}") diff --git a/scripts/start_local.ps1 b/scripts/start_local.ps1 index ebe8e858..6d5c2b27 100644 --- a/scripts/start_local.ps1 +++ b/scripts/start_local.ps1 @@ -2,15 +2,20 @@ scripts/start_local.ps1 用途:本地一键启动 HXOPS 前后端与后台 worker。 依赖:backend venv、frontend npm、.env.shared / .env.dev(worker 与 RPA 读取)。 -逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口,再分别在新 PowerShell 窗口启动各服务。 +逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口 → 执行 DB 迁移(flask db upgrade)→ 再分别在新 PowerShell 窗口启动各服务。 + Worker 使用 backend/ 根目录的并发入口(worker_kb.py / worker_shipping.py),内部通过 multiprocessing 自分叉子进程池;并发数由 -KbConcurrency / -ShippingConcurrency 透传到环境变量。 #> param( [ValidateSet("sqlite", "postgres")] [string]$DbMode = "sqlite", [string]$DatabaseUrl = "", + [int]$KbConcurrency = 1, + [int]$ShippingConcurrency = 1, [switch]$SkipInstall, + [switch]$SkipMigrate, [switch]$SkipWorker, - [switch]$SkipRpaWorker + [switch]$IncludeRpaWorker, + [switch]$NoHotReload ) $ErrorActionPreference = "Stop" @@ -61,10 +66,17 @@ function Stop-StaleHxopsPythonProcesses { $patterns = @( [regex]::Escape((Join-Path $BackendPath "run.py")), + [regex]::Escape((Join-Path $BackendPath "worker.py")), [regex]::Escape((Join-Path $BackendPath "worker_kb.py")), [regex]::Escape((Join-Path $BackendPath "worker_shipping.py")), + [regex]::Escape((Join-Path $BackendPath "workers\worker_kb.py")), + [regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")), + [regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")), [regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py")) ) + # 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。 + # 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。 + # 清理阶段必须全部覆盖,避免历史残留进程导致的「多实例重复领取 job / 端口占用」。 Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue | ForEach-Object { $cmd = $_.CommandLine @@ -214,6 +226,32 @@ function Ensure-Backend { } } +function Invoke-DbMigrate { + param( + [string]$BackendPath, + [string]$Mode, + [string]$DbUrl + ) + + Write-Host "[db-migrate] running flask db upgrade..." -ForegroundColor Cyan + Set-Location $BackendPath + + $venvPy = Join-Path $BackendPath "venv\Scripts\python.exe" + + $env:FLASK_APP = "run.py" + $env:FLASK_ENV = "development" + $env:ENV_NAME = "dev" + if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) { + $env:DATABASE_URL = $DbUrl + } + + & $venvPy -m flask db upgrade + if ($LASTEXITCODE -ne 0) { + throw "[db-migrate] flask db upgrade failed with exit code $LASTEXITCODE" + } + Write-Host "[db-migrate] migration completed." -ForegroundColor Green +} + function Ensure-Frontend { param( [string]$FrontendPath, @@ -237,7 +275,8 @@ function Start-BackendWindow { param( [string]$BackendPath, [string]$Mode, - [string]$DbUrl + [string]$DbUrl, + [bool]$DisableHotReload = $false ) $dbExport = "" @@ -246,7 +285,13 @@ function Start-BackendWindow { $dbExport = "`$env:DATABASE_URL='$escaped'; " } - $cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py" + if ($DisableHotReload) { + $reloaderEnv = "`$env:WERKZEUG_RUN_MAIN='true'; " + } else { + $reloaderEnv = "" + } + + $cmd = "$dbExport$reloaderEnv Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py" Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null } @@ -263,6 +308,34 @@ function Get-DatabaseUrlExport { return "" } +function Import-DotEnvFilesToCurrentShell { + param([string[]]$Paths) + + foreach ($path in $Paths) { + if (-not (Test-Path $path)) { + Write-Host "[env] skip (not found): $path" -ForegroundColor DarkGray + continue + } + Write-Host "[env] loading: $path" -ForegroundColor Cyan + foreach ($line in Get-Content $path) { + if ($line -match '^\s*#' -or $line -match '^\s*$') { + continue + } + if ($line -match '^\s*([^=]+)=(.*)$') { + $name = $matches[1].Trim() + $value = $matches[2].Trim() + if ($value.Length -ge 2 -and ( + ($value.StartsWith('"') -and $value.EndsWith('"')) -or + ($value.StartsWith("'") -and $value.EndsWith("'")) + )) { + $value = $value.Substring(1, $value.Length - 2) + } + Set-Item -Path "env:$name" -Value $value -ErrorAction SilentlyContinue + } + } + } +} + function Get-DotEnvExportPrefix { param([string[]]$Paths) @@ -310,13 +383,17 @@ function Start-KbWorkerWindow { param( [string]$BackendPath, [string]$Mode, - [string]$DbUrl + [string]$DbUrl, + [int]$Concurrency = 1 ) + $envPrefix = Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl + $envPrefix += " `$env:ENV_NAME='dev'; `$env:KB_WORKER_CONCURRENCY='$Concurrency';" + Start-WorkerWindow ` - -Title "kb-worker" ` + -Title "kb-worker (concurrency=$Concurrency)" ` -WorkingDirectory $BackendPath ` - -EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) ` + -EnvPrefix $envPrefix ` -Command ".\venv\Scripts\python.exe .\worker_kb.py" } @@ -324,13 +401,17 @@ function Start-ShippingWorkerWindow { param( [string]$BackendPath, [string]$Mode, - [string]$DbUrl + [string]$DbUrl, + [int]$Concurrency = 1 ) + $envPrefix = Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl + $envPrefix += " `$env:ENV_NAME='dev'; `$env:SHIPPING_NOTICE_WORKER_CONCURRENCY='$Concurrency';" + Start-WorkerWindow ` - -Title "shipping-worker" ` + -Title "shipping-worker (concurrency=$Concurrency)" ` -WorkingDirectory $BackendPath ` - -EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) ` + -EnvPrefix $envPrefix ` -Command ".\venv\Scripts\python.exe .\worker_shipping.py" } @@ -352,8 +433,16 @@ function Start-FreightRpaWorkerWindow { } function Start-FrontendWindow { - param([string]$FrontendPath) - $cmd = "Set-Location '$FrontendPath'; npm run dev" + param( + [string]$FrontendPath, + [bool]$DisableHotReload = $false + ) + if ($DisableHotReload) { + $envArg = "`$env:VITE_HMR='false'; " + } else { + $envArg = "" + } + $cmd = "$envArg Set-Location '$FrontendPath'; npm run dev" Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null } @@ -364,30 +453,61 @@ $frontendDir = Join-Path $repoRoot "frontend" if (-not (Test-Path $backendDir)) { throw "backend directory not found: $backendDir" } if (-not (Test-Path $frontendDir)) { throw "frontend directory not found: $frontendDir" } -$pythonCmd = Get-PythonCommand -$doInstall = -not $SkipInstall.IsPresent - -Write-Host "== HXOPS local startup ==" -ForegroundColor Green -Write-Host "mode: $DbMode" -ForegroundColor Green - -Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir - -Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $DatabaseUrl -DoInstall $doInstall -Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall - $envFiles = @( (Join-Path $repoRoot ".env.shared"), (Join-Path $repoRoot ".env.dev"), (Join-Path $repoRoot ".env.local") ) -$windowCount = 2 -Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl +# 优先级加载:.env.shared → .env.dev → .env.local(后者覆盖前者) +# 显式传参 -DatabaseUrl 的优先级最高,最后覆盖。 +Import-DotEnvFilesToCurrentShell -Paths $envFiles + +$effectiveDbUrl = $DatabaseUrl +if ([string]::IsNullOrWhiteSpace($effectiveDbUrl)) { + $effectiveDbUrl = $env:DATABASE_URL +} +if (-not [string]::IsNullOrWhiteSpace($DatabaseUrl)) { + $env:DATABASE_URL = $DatabaseUrl + Write-Host "[env] DATABASE_URL overridden from -DatabaseUrl parameter." -ForegroundColor DarkGray +} + +$pythonCmd = Get-PythonCommand +$doInstall = -not $SkipInstall.IsPresent + +Write-Host "== HXOPS local startup ==" -ForegroundColor Green +Write-Host "mode: $DbMode" -ForegroundColor Green if (-not $SkipWorker.IsPresent) { - Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl - Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl + Write-Host "kb concurrency: $KbConcurrency | shipping concurrency: $ShippingConcurrency" -ForegroundColor Green +} +if ($DbMode -eq "postgres") { + if (-not [string]::IsNullOrWhiteSpace($effectiveDbUrl)) { + $masked = $effectiveDbUrl -replace '(?<=://[^:]+:)[^@]+', '******' + Write-Host "postgres DATABASE_URL: $masked" -ForegroundColor DarkGray + } + else { + Write-Warning "DbMode=postgres but no DATABASE_URL found in env files or -DatabaseUrl parameter. Relying on app default." + } +} + +Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir + +Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $effectiveDbUrl -DoInstall $doInstall +if (-not $SkipMigrate.IsPresent) { + Invoke-DbMigrate -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl +} +else { + Write-Host "[db-migrate] skipped (-SkipMigrate)." -ForegroundColor DarkGray +} +Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall + +$windowCount = 2 +Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl +if (-not $SkipWorker.IsPresent) { + Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl -Concurrency $KbConcurrency + Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl -Concurrency $ShippingConcurrency $windowCount += 2 - if (-not $SkipRpaWorker.IsPresent) { + if ($IncludeRpaWorker.IsPresent) { Start-FreightRpaWorkerWindow -RepoRoot $repoRoot -BackendPath $backendDir -EnvFiles $envFiles $windowCount += 1 } @@ -398,7 +518,8 @@ $windowCount += 1 Write-Host "" Write-Host "Started in $windowCount new PowerShell windows." -ForegroundColor Green if (-not $SkipWorker.IsPresent) { - Write-Host "Workers: kb-worker, shipping-worker$(if (-not $SkipRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green + Write-Host "Workers: kb-worker(x$KbConcurrency), shipping-worker(x$ShippingConcurrency)$(if ($IncludeRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green + Write-Host "(Worker 进程由 master 进程内部通过 multiprocessing fork,每个 Worker 窗口只需要一个 master。)" -ForegroundColor DarkGray Write-Host "Schedule worker runs inside backend process (SCHEDULE_WORKER_ENABLED)." -ForegroundColor DarkGray } Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green diff --git a/scripts/stress_reconcile_legacy_jobs.py b/scripts/stress_reconcile_legacy_jobs.py new file mode 100644 index 00000000..d591190f --- /dev/null +++ b/scripts/stress_reconcile_legacy_jobs.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python +""" +scripts/stress_reconcile_legacy_jobs.py + +用途:Phase 5-3 —— 并发回放 legacy STP Job 压测脚本(不提交镜像,仅本地/测试环境运行)。 +依赖:backend 虚拟环境 + Flask app;concurrent.futures.ThreadPoolExecutor。 +核心目标: + 1. 验证 N 线程 × M Case 的并发 reconcile_and_progress() 不会: + - PostgreSQL SELECT FOR UPDATE 死锁; + - Q7 幂等链撞漏(同 operation_id 再触发不会重复建 STP Job); + - 重复创建 >M 个 STP Job(幂等计数必须严格 = 实际调用的唯一 {case_no, operation_id} 对数)。 + 2. 输出 CSV / JSON 摘要:每个线程 outcome、幂等重复次数、rollback 次数、 + ownership_anomaly 硬隔离次数、总耗时。 +禁止事项(严格 fail-closed): + 只允许调用 reconciliation_service.reconcile_and_progress;不允许直接写 Case/Job/Candidate 表。 +""" + +from __future__ import annotations + +import argparse +import json +import logging +import random +import sys +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import asdict, dataclass, field +from typing import Any + +LOGGER = logging.getLogger('stress_reconcile_legacy_jobs') + + +@dataclass +class CasePlan: + """每个 worker 针对一个 Case 做 1 次或多次回放。""" + case_no: str + legacy_job_id: int | None + user_action: str + replay_mode: bool + repeats_per_case: int + + +@dataclass +class WorkerResult: + thread_id: int + case_no: str + attempt_no: int + operation_id: str + start_epoch_ms: int + end_epoch_ms: int + outcome: str + job_id: int | None + error_code: str | None + error_message: str | None + + @property + def duration_ms(self) -> int: + return int(self.end_epoch_ms - self.start_epoch_ms) + + +@dataclass +class StressSummary: + threads: int + cases: int + total_attempts: int + unique_case_op_pairs: int + duration_ms: int = 0 + results: list[WorkerResult] = field(default_factory=list) + + @property + def by_outcome(self) -> dict[str, int]: + tally: dict[str, int] = {} + for r in self.results: + tally[r.outcome] = tally.get(r.outcome, 0) + 1 + return tally + + @property + def error_count(self) -> int: + return sum(1 for r in self.results if r.outcome.startswith('ERROR_')) + + +def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: + p = argparse.ArgumentParser( + description=( + 'Stress-test reconciliation_service.reconcile_and_progress with concurrent ' + 'legacy-Job replay calls — validate FOR UPDATE deadlock safety & Q7 idempotency.' + ), + ) + p.add_argument('--user-id', type=int, required=True, help='Admin user id.') + p.add_argument('--threads', type=int, default=8, help='ThreadPoolExecutor workers (default=8)') + p.add_argument('--cases', type=int, default=50, + help='Number of distinct case_no scenarios (default=50). MUST exist in DB.') + p.add_argument('--repeats-per-case', type=int, default=4, + help='How many times the same (case_no,operation_id) is re-submitted (≥2 to force Q7 hit). Default=4') + p.add_argument('--case-no-prefix', default='CASE-STRESS-', + help='Case no prefix; stress mode assumes sequential IDs from 1..--cases.') + p.add_argument('--legacy-job-id-anchor', type=int, default=9000, + help='Legacy Job id anchor (actual value may or may not exist; ' + 'non-existent Job → ERROR path is intentionally part of stress).') + p.add_argument('--user-action-pool', nargs='+', + default=['auto', 'create_revision', 'force_create']) + p.add_argument('--replay-mode-rate', type=float, default=0.3, + help='Probability (0..1) that replay_mode=True for a given attempt. Default=0.3') + p.add_argument('--max-duration-seconds', type=int, default=300, + help='Hard wall-clock safety cap (default=300s).') + p.add_argument('--json-output', action='store_true', help='Emit JSON summary at the end.') + p.add_argument('--csv-output', default=None, help='Optional path to write per-worker CSV.') + p.add_argument('-v', '--verbose', action='count', default=0) + return p.parse_args(argv) + + +def _one_call( + *, + user_id: int, + case_no: str, + operation_id: str, + user_action: str, + legacy_job_id: int | None, + replay_mode: bool, + attempt_no: int, + thread_id: int, +) -> WorkerResult: + """单条 reconcile_and_progress 调用;捕获全部异常。""" + from app.core.errors import AppError, ConflictError, ValidationError + from app.services.shipping_notice.reconciliation_service import reconcile_and_progress + + start_ms = int(time.time() * 1000) + try: + result = reconcile_and_progress( + user_id=int(user_id), + case_no=str(case_no), + operation_id=str(operation_id), + user_action=str(user_action), + expected_case_version=None, + source_content_hash=None, + is_admin=True, + legacy_job_id=(int(legacy_job_id) if legacy_job_id is not None else None), + replay_mode=bool(replay_mode), + ) + outcome = str(result.outcome or 'UNKNOWN') + job_id = int(result.job_id) if getattr(result, 'job_id', None) is not None else None + err_code = None + err_msg = None + except ValidationError as exc: + outcome = 'ERROR_VALIDATION' + job_id = None + err_code = str(getattr(exc, 'code', None) or '') + err_msg = str(getattr(exc, 'message', None) or str(exc)) + except ConflictError as exc: + outcome = 'ERROR_CONFLICT' + job_id = None + err_code = str(getattr(exc, 'code', None) or '') + err_msg = str(getattr(exc, 'message', None) or str(exc)) + except AppError as exc: + outcome = 'ERROR_APP' + job_id = None + err_code = str(getattr(exc, 'code', None) or '') + err_msg = str(getattr(exc, 'message', None) or str(exc)) + except Exception as exc: # noqa: BLE001 + outcome = 'ERROR_UNEXPECTED' + job_id = None + err_code = type(exc).__name__ + err_msg = str(exc) + end_ms = int(time.time() * 1000) + return WorkerResult( + thread_id=int(thread_id), + case_no=str(case_no), + attempt_no=int(attempt_no), + operation_id=str(operation_id), + start_epoch_ms=start_ms, + end_epoch_ms=end_ms, + outcome=outcome, + job_id=job_id, + error_code=err_code or None, + error_message=err_msg or None, + ) + + +def _build_case_plans(args: argparse.Namespace) -> list[CasePlan]: + plans: list[CasePlan] = [] + for idx in range(1, int(args.cases) + 1): + case_no = f'{str(args.case_no_prefix).rstrip("-")}-{idx:06d}' + # 每 N 次里留 1 次 legacy_job_id 不存在 / replay_mode=True 的场景用于覆盖 PRE-CHECK 错误路径 + use_legacy = (idx % 3 != 0) + legacy_job_id = (int(args.legacy_job_id_anchor) + idx) if use_legacy else None + user_action = random.choice(list(args.user_action_pool)) + replay_mode = (random.random() < float(args.replay_mode_rate)) + plans.append(CasePlan( + case_no=case_no, + legacy_job_id=legacy_job_id, + user_action=str(user_action), + replay_mode=bool(replay_mode), + repeats_per_case=int(args.repeats_per_case), + )) + return plans + + +def _write_csv(path: str, results: list[WorkerResult]) -> None: + import csv + with open(path, 'w', newline='', encoding='utf-8') as fp: + writer = csv.writer(fp) + writer.writerow([ + 'thread_id', 'case_no', 'attempt_no', 'operation_id', + 'start_epoch_ms', 'end_epoch_ms', 'duration_ms', + 'outcome', 'job_id', 'error_code', 'error_message', + ]) + for r in results: + writer.writerow([ + r.thread_id, r.case_no, r.attempt_no, r.operation_id, + r.start_epoch_ms, r.end_epoch_ms, r.duration_ms, + r.outcome, (r.job_id if r.job_id is not None else ''), + (r.error_code or ''), (r.error_message or ''), + ]) + + +def _main(argv: list[str] | None = None) -> int: + args = _parse_args(argv) + level = logging.WARNING + if args.verbose == 1: + level = logging.INFO + elif args.verbose >= 2: + level = logging.DEBUG + logging.basicConfig(level=level, format='%(asctime)s %(levelname)s %(name)s: %(message)s') + + from app import create_app # type: ignore + + app = create_app() + with app.app_context(): + from app import db # noqa: F401 — 确保 session 绑定 + + plans = _build_case_plans(args) + # 每个 Case 的首 attempts 1..repeats 共用同一个 operation_id(用于打 Q7 幂等链) + # —— 故意触发 Q7:重复 operation_id 的相同参数 → 应回返 idempotent_replay。 + tasks: list[tuple[int, CasePlan, int, str]] = [] + thread_counter = threading.local() + _ = thread_counter + unique_pairs: set[tuple[str, str]] = set() + for plan in plans: + op_id = str(uuid.uuid4()) + for rep in range(1, int(plan.repeats_per_case) + 1): + tasks.append((rep, plan, len(tasks), op_id)) + unique_pairs.add((plan.case_no, op_id)) + total_attempts = len(tasks) + summary = StressSummary( + threads=int(args.threads), + cases=len(plans), + total_attempts=total_attempts, + unique_case_op_pairs=len(unique_pairs), + ) + random.shuffle(tasks) # 打散顺序,制造争用 + LOGGER.info( + 'stress plan: threads=%s plans=%s total_attempts=%s unique_case_ops=%s repeats/case=%s', + args.threads, len(plans), total_attempts, len(unique_pairs), args.repeats_per_case, + ) + + def _run(task: tuple[int, CasePlan, int, str]) -> WorkerResult: + attempt_no, plan, _i, op_id = task + thread_name = threading.current_thread().name + tid = int(''.join(ch for ch in str(thread_name) if ch.isdigit()) or '0') + return _one_call( + user_id=int(args.user_id), + case_no=plan.case_no, + operation_id=op_id, + user_action=str(plan.user_action), + legacy_job_id=( + int(plan.legacy_job_id) + if plan.legacy_job_id is not None else None + ), + replay_mode=bool(plan.replay_mode), + attempt_no=int(attempt_no), + thread_id=tid, + ) + + overall_start = time.time() + deadline = overall_start + max(int(args.max_duration_seconds), 1) + try: + with ThreadPoolExecutor(max_workers=int(args.threads)) as pool: + futures = {pool.submit(_run, t): t for t in tasks} + for future in as_completed(futures): + if time.time() > deadline: + LOGGER.warning( + 'deadline exceeded (%ss) — cancelling remaining tasks', + args.max_duration_seconds, + ) + for f in futures: + if not f.done(): + f.cancel() + break + try: + result = future.result() + except Exception as exc: # noqa: BLE001 + # as_completed 已返回完成的 future;理论上不应走到此处 + task = futures[future] + result = WorkerResult( + thread_id=-1, case_no=task[1].case_no, + attempt_no=task[0], operation_id=task[3], + start_epoch_ms=int(time.time() * 1000), + end_epoch_ms=int(time.time() * 1000), + outcome='ERROR_UNEXPECTED', job_id=None, + error_code=type(exc).__name__, + error_message=str(exc), + ) + summary.results.append(result) + if args.verbose >= 2: + LOGGER.debug('outcome=%s case=%s duration_ms=%s', + result.outcome, result.case_no, result.duration_ms) + except KeyboardInterrupt: + LOGGER.warning('KeyboardInterrupt — reporting partial summary') + overall_end = time.time() + summary.duration_ms = int((overall_end - overall_start) * 1000) + + if args.csv_output: + try: + _write_csv(str(args.csv_output), summary.results) + except OSError as exc: + LOGGER.error('failed to write CSV %s: %s', args.csv_output, exc) + + if args.json_output: + print(json.dumps(asdict(summary), ensure_ascii=False, indent=2, default=str)) + else: + print('===== Stress-Reconcile-Legacy-Jobs Summary =====') + print(f'threads : {summary.threads}') + print(f'cases : {summary.cases}') + print(f'total_attempts : {summary.total_attempts}') + print(f'unique_case_op_pairs : {summary.unique_case_op_pairs}') + print(f'duration_ms : {summary.duration_ms}') + print(f'error_count : {summary.error_count}') + print('by_outcome:') + for k, v in sorted(summary.by_outcome.items()): + print(f' {k:<32s}: {v}') + + return 2 if summary.error_count > 0 else 0 + + +if __name__ == '__main__': + raise SystemExit(_main())