diff --git a/.env.shared b/.env.shared index a3d46810..906d8ccd 100644 --- a/.env.shared +++ b/.env.shared @@ -185,9 +185,9 @@ FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈 # 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。 SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=true # OT 后行级自动履约(默认关):关闭时只上线匹配事实契约/明细库存列;禁止自动决定与 wave。 -SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false +SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=true # 发货通知专用 Worker 进程数;版面解析为长任务,默认并发处理同批两份文档。 -SHIPPING_NOTICE_WORKER_CONCURRENCY=2 +SHIPPING_NOTICE_WORKER_CONCURRENCY=10 # Layout Job 内整页 OCR 结果复用(PR-1);共享默认关,dev/test 环境文件覆盖为 true,prod 保持 false 灰度。 SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false # PDFium 字符预读复用与按需补图(PR-2);共享默认关,dev/test 开启,prod 灰度。 @@ -212,7 +212,7 @@ SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow # RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。 # 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。 -SHIPPING_NOTICE_RPA_CREDENTIAL_KEY= +SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE= # 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。 SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300 # 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。 diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index ce18d649..a1818571 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -28,7 +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 import app.api.admin.linked_services # noqa: F401 import app.api.admin.procurement_contract # noqa: F401 import app.api.admin.training_configs # noqa: F401 diff --git a/backend/app/api/admin/shipping_legacy_stp_jobs.py b/backend/app/api/admin/shipping_legacy_stp_jobs.py deleted file mode 100644 index bb06262d..00000000 --- a/backend/app/api/admin/shipping_legacy_stp_jobs.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -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/admin/shipping_order_extraction.py b/backend/app/api/admin/shipping_order_extraction.py index 580d9541..7335e5c8 100644 --- a/backend/app/api/admin/shipping_order_extraction.py +++ b/backend/app/api/admin/shipping_order_extraction.py @@ -32,6 +32,40 @@ def _query_int(name: str, default: int) -> int: raise ValidationError(f'{name} must be an integer') from exc +@admin_bp.route('/shipping-notice/legacy-supplement-conflicts/reassess', methods=['POST']) +@require_admin +def reassess_shipping_legacy_supplement_conflicts(): + """受控重评估历史正文补充冲突;全量操作必须显式确认,结果只返回脱敏统计。""" + body = request.get_json(silent=True) + if body is None: + body = {} + if not isinstance(body, dict): + raise ValidationError('JSON body must be an object') + include_all_raw = body.get('include_all', False) + if not isinstance(include_all_raw, bool): + raise ValidationError('include_all must be a boolean') + include_all = include_all_raw + if include_all and str(body.get('confirmation') or '') != 'REASSESS_LEGACY_SUPPLEMENT_CONFLICTS': + raise ValidationError('confirmation is required for include_all') + candidate_no = str(body.get('candidate_no') or '').strip() or None + run_no = str(body.get('run_no') or '').strip() or None + if not (candidate_no or run_no or include_all): + raise ValidationError('candidate_no, run_no, or include_all is required') + from app.services.shipping_notice.legacy_supplement_conflict_reassessment_service import ( + reassess_legacy_supplement_conflicts, + ) + + result = reassess_legacy_supplement_conflicts( + actor_id=int(g.current_user.id), + request_id=getattr(g, 'request_id', None), + candidate_no=candidate_no, + run_no=run_no, + include_all=include_all, + ) + db.session.commit() + return ok(result, request_id=getattr(g, 'request_id', None)) + + @admin_bp.route('/shipping-notice/order-extraction-runs/health', methods=['GET']) @require_admin def get_shipping_order_extraction_health(): diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index eaea5da6..62001c0a 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -137,24 +137,21 @@ def _merge_user_attachments_from_terminal_event( def _build_chat_adapter_hints( *, shipping_task_id: str | None = None, - shipping_batch_no: str | None = None, shipping_intake_nos: list[str] | None = None, ) -> dict | None: """ 构建聊天入口分发给领域 adapter 的提示字典。 - 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示, + 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示, 统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。 """ task_id = str(shipping_task_id or '').strip() - batch_no = str(shipping_batch_no or '').strip() intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()}) - if not task_id and not batch_no and not intake_nos: + if not task_id and not intake_nos: return None return { 'shipping_notice': { 'task_id': task_id or None, - 'batch_no': batch_no or None, 'intake_nos': intake_nos, 'capability': 'order_extraction' if intake_nos else None, 'contract_version': 'shipping-order-extraction-v1' if intake_nos else None, @@ -1574,7 +1571,6 @@ def chat_completions(): # 前端传入的 conversation_id 在 B2 里代表本地 session_id conversation_id = data.get('conversation_id') shipping_task_id = str(data.get('task_id') or '').strip() - shipping_batch_no = str(data.get('batch_no') or '').strip() raw_shipping_intakes = data.get('shipping_intake_nos') if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list): raise ValidationError('shipping_intake_nos must be a list') @@ -1720,11 +1716,9 @@ def chat_completions(): normalized_files=normalized_files, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, shipping_intake_nos=shipping_intake_nos, ), shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, kb_type=kb_type, ) @@ -1763,7 +1757,6 @@ def chat_completions(): user_role=user_proxy.role, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, shipping_intake_nos=shipping_intake_nos, ), ), diff --git a/backend/app/api/chat/completions.py b/backend/app/api/chat/completions.py index b00a8731..10ee1ad6 100644 --- a/backend/app/api/chat/completions.py +++ b/backend/app/api/chat/completions.py @@ -39,7 +39,6 @@ def chat_completions(): # 前端传入的 conversation_id 在 B2 里代表本地 session_id conversation_id = data.get('conversation_id') shipping_task_id = str(data.get('task_id') or '').strip() - shipping_batch_no = str(data.get('batch_no') or '').strip() kb_type = data.get('kb_type', '企业知识库') files = data.get('files') request_id = uuid.uuid4().hex[:12] @@ -128,6 +127,13 @@ def chat_completions(): else: session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running') + # [STEP 1] SSE 生成器可能在请求 scoped Session 清理后才开始迭代;提前快照会话标量, + # 避免流内事务提交使 ORM 实例过期后触发 DetachedInstanceError。 + local_session_id = str(session.session_id) + initial_session_status = str(session.status or 'running') + initial_external_conversation_id = str(external_conversation_id or '').strip() or None + stream_session = SimpleNamespace(session_id=local_session_id) + normalized_files: list[dict] | None = None if files is not None: if not isinstance(files, list): @@ -162,16 +168,14 @@ def chat_completions(): display_query=display_query, user=user_proxy, agent=agent_proxy, - session=session, - external_conversation_id=external_conversation_id, + session=stream_session, + external_conversation_id=initial_external_conversation_id, request_id=request_id, normalized_files=normalized_files, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, ), shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, kb_type=kb_type, ) @@ -185,8 +189,8 @@ def chat_completions(): agent=agent_proxy, query=query, agent_id=agent_id, - session_id=session.session_id, - external_conversation_id=external_conversation_id, + session_id=local_session_id, + external_conversation_id=initial_external_conversation_id, normalized_files=normalized_files, kb_type=kb_type, leave_supported=leave_supported, @@ -198,19 +202,18 @@ def chat_completions(): query, user_proxy.id, agent_proxy, - external_conversation_id, + initial_external_conversation_id, request_id=request_id, - session_id=session.session_id, + session_id=local_session_id, files=normalized_files, inputs=build_chat_dify_inputs( agent_proxy, - session_id=session.session_id, + session_id=local_session_id, request_id=request_id, trigger_source="frontend_chat", user_role=user_proxy.role, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, ), ), ) @@ -226,14 +229,14 @@ def chat_completions(): relay_first_chunk_at: float | None = None created_event = { 'event': 'session_created', - 'conversation_id': session.session_id, - 'provider_conversation_id': session.external_conversation_id, - 'session_status': session.status, + 'conversation_id': local_session_id, + 'provider_conversation_id': initial_external_conversation_id, + 'session_status': initial_session_status, } yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n" - known_provider_conversation_id = session.external_conversation_id - known_status = session.status + known_provider_conversation_id = initial_external_conversation_id + known_status = initial_session_status emitted_handler_state_keys: set[str] = set() from app.services.chat.stream_relay import ( @@ -276,7 +279,7 @@ def chat_completions(): updated_session = _update_chat_session( user_id, agent_id, - session.session_id, + local_session_id, status=known_status, external_conversation_id=known_provider_conversation_id, touch=True, @@ -285,7 +288,7 @@ def chat_completions(): known_status = updated_session.status event_data['provider_conversation_id'] = provider_conversation_id - event_data['conversation_id'] = session.session_id + event_data['conversation_id'] = local_session_id event_data['session_status'] = known_status if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'): relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None @@ -293,7 +296,7 @@ def chat_completions(): current_app.logger.info( '[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s', request_id, - session.session_id, + local_session_id, relay_first_ms, relay_total_ms, event_name, @@ -311,8 +314,8 @@ 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, session.session_id) - payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'} + current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id) + 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" # 返回 SSE 响应,mimetype 设为 text/event-stream diff --git a/backend/app/api/chat/core.py b/backend/app/api/chat/core.py index 63861bcc..285b4f6b 100644 --- a/backend/app/api/chat/core.py +++ b/backend/app/api/chat/core.py @@ -10,21 +10,19 @@ from __future__ import annotations from .shared import * # noqa: F403 -def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None: +def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None: """ 构建聊天入口分发给领域 adapter 的提示字典。 - 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示, + 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示, 统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。 """ task_id = str(shipping_task_id or '').strip() - batch_no = str(shipping_batch_no or '').strip() - if not task_id and not batch_no: + if not task_id: return None return { 'shipping_notice': { 'task_id': task_id or None, - 'batch_no': batch_no or None, } } diff --git a/backend/app/api/chat_turns.py b/backend/app/api/chat_turns.py index ec2402f5..2edaed82 100644 --- a/backend/app/api/chat_turns.py +++ b/backend/app/api/chat_turns.py @@ -2,7 +2,7 @@ backend/app/api/chat_turns.py 用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。 -依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。 +依赖:app.core.decorators、ChatTurnRuntime、chat_bp。 逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。 """ @@ -77,7 +77,6 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None: """ 将 multipart 附件写入 Turn input.payload。 - - shipping.create_batch_from_notices:预检 notice_items - shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节 """ if not uploads: @@ -87,26 +86,7 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None: payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {} payload = dict(payload) - if action_type == "shipping.create_batch_from_notices": - from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch - from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads - - temp_request_id = uuid.uuid4().hex - try: - notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads) - finally: - cleanup_temp_notice_uploads(temp_request_id) - if not notice_items: - raise ValidationError( - "未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试", - details={"file_summary": file_summary}, - ) - payload["notice_items"] = notice_items - payload["file_summary"] = file_summary - conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip() - if conversation_id: - payload["conversation_id"] = conversation_id - elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"): + if action_type in ("shipping.upload_inventory", "shipping.replace_notice"): staged = _stage_upload_files(uploads) if not staged: raise ValidationError("file is required") diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 5d54b9fd..674459d1 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -3,15 +3,13 @@ api/shipping_notice_tools.py 用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。 依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、 - batch_legacy_removed(create_batch 410)。 + tool_api_url。 逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError; `_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计; - co8 后 /tools/create_batch 固定 410,改走 order-extraction-submissions。 + 历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。 """ from __future__ import annotations -import uuid - from flask import Blueprint, current_app, jsonify, request, send_file from app import db @@ -118,11 +116,11 @@ def _payload() -> dict: return payload -def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None, batch_no: str | None = None) -> None: +def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None: """Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。""" from app.models import ShippingAuditEvent from app.services.shipping_notice.chat_tool_capability import require_chat_capability - claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no, batch_no=batch_no) + claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no) db.session.add(ShippingAuditEvent( event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']), task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']), @@ -130,10 +128,6 @@ def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True}, )) -def _generate_batch_no() -> str: - from datetime import datetime - return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" - @shipping_notice_bp.route('/tools/openapi.json', methods=['GET']) def openapi_spec(): """返回 Dify 导入用的 OpenAPI JSON 文档。""" @@ -192,19 +186,6 @@ def tool_confirm_temporary_inventory_use(): """ return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload())) -@shipping_notice_bp.route('/tools/create_batch', methods=['POST']) -def tool_create_batch(): - """ - 历史建批 Tool(已下线)。 - 【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='tools.create_batch') - @shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST']) def tool_update_notice_fields(): """ @@ -328,32 +309,6 @@ def tool_get_task_status(): _require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None) return jsonify(shipping_tools.get_task_status(payload)) -@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST']) -def tool_get_batch_status(): - """ - 历史批次状态查询(已下线)。 - 【AI 触发时机】:禁止调用;请改用 get_task_status 或 shipping-processing。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='tools.get_batch_status') - -@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST']) -def tool_switch_focus_task(): - """ - 历史批次焦点切换(已下线)。 - 【AI 触发时机】:禁止调用;shipping_batches 已物理删除。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='tools.switch_focus_task') - @shipping_notice_bp.route('/rpa/heartbeat', methods=['POST']) def rpa_worker_heartbeat(): """ diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 1a7f7d83..3da2db10 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -3,16 +3,17 @@ backend/app/api/workspace/shipping_notice.py 用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。 依赖:app.core.auth.jwt、app.core.errors、app.core.response.ok、shipping_notice.query_service / - tools / notice_upload / ui_state、shipping_processing_projection、batch_legacy_removed。 + tools / notice_upload / ui_state、shipping_processing_projection。 逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与 - 统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint; - `/shipping-processing/*` 为统一进度读源;co8 后 `/shipping-batches*` 写 410 / 读空或 404; + 统一 AppError;人工上传仅确认唯一 Excel 已上传,不采集回执或凭据;Chat Turn 履约写路径已废弃,请改走本 Blueprint; + `/shipping-processing/*` 为统一进度读源;历史 `/shipping-batches*` 已删除; Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。 """ from __future__ import annotations import uuid from io import BytesIO +from time import perf_counter from typing import Any from flask import Blueprint, Response, current_app, g, request, send_file @@ -32,9 +33,7 @@ from app.services.shipping_notice.processing_ownership import assert_notice_task from app.services.shipping_notice.query_service import ( EXPORT_MIME_TYPE, count_my_todos, - get_conversation_batch_workspace, get_task_for_user, - list_batches_for_user, list_my_todos, list_tasks_page_for_user, resolve_task_export_download, @@ -148,9 +147,8 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) def workspace_shipping_tasks(): - """分页列出当前用户可见的发货任务,可按批次与处理状态过滤。""" + """分页列出当前用户可见的发货任务,可按处理状态过滤。""" user = _require_user() - batch_no = str(request.args.get('batch_no') or '').strip() or None lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None try: page = int(request.args.get('page') or 1) @@ -161,7 +159,6 @@ def workspace_shipping_tasks(): raise ValidationError('page must be positive and page_size must be between 1 and 100') return _ok(list_tasks_page_for_user( user.id, - batch_no=batch_no, lifecycle_status=lifecycle_status, page=page, page_size=page_size, @@ -309,116 +306,16 @@ def workspace_batch_restore_shipping_tasks(): """批量恢复回收站内仍为 active 的纯误建任务。""" return _batch_dispose('restore') -@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET']) -def workspace_shipping_batches(): - """列出当前用户的发货批次摘要;co8 后 shipping_batches 已 DROP,恒返回空列表。""" - user = _require_user() - limit = int(request.args.get('limit') or 100) - return _ok(list_batches_for_user(user.id, limit=limit)) - - -@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST']) -def workspace_create_shipping_batch_from_notices(): - """ - 历史:多附件建批(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - _require_user() - raise_shipping_batches_removed(action='workspace.create_from_notices') - - -@workspace_shipping_notice_bp.route('/shipping-batches/', methods=['GET']) -def workspace_shipping_batch_detail(batch_no: str): - """批次详情;shipping_batches 已 DROP,恒 404。""" - _require_user() - del batch_no - raise NotFoundError('Not found') - - -@workspace_shipping_notice_bp.route('/shipping-batches//ui-state', methods=['GET']) -def workspace_shipping_batch_ui_state(batch_no: str): - """批次 UI State;shipping_batches 已 DROP,恒 404。""" - _require_user() - del batch_no - raise NotFoundError('Not found') - - -@workspace_shipping_notice_bp.route('/shipping-batches//tasks', methods=['GET']) -def workspace_shipping_batch_tasks(batch_no: str): - """批次任务列表;shipping_batches 已 DROP,恒 404。""" - _require_user() - del batch_no - raise NotFoundError('Not found') - - -@workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['GET']) -def workspace_shipping_batch_focus_task(batch_no: str): - """批次焦点任务;shipping_batches 已 DROP,恒 404。""" - _require_user() - del batch_no - raise NotFoundError('Not found') - - -@workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['POST']) -def workspace_switch_shipping_batch_focus_task(batch_no: str): - """ - 切换批次焦点(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - _require_user() - del batch_no - raise_shipping_batches_removed(action='workspace.switch_batch_focus') - - -@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST']) -def workspace_create_shipping_batch_from_intakes(): - """ - 历史:从 Intake 建批(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - _require_user() - raise_shipping_batches_removed(action='workspace.create_from_intakes') - - -@workspace_shipping_notice_bp.route('/shipping-batches//retry-pending', methods=['POST']) -def workspace_retry_shipping_batch_pending(batch_no: str): - """ - 历史:重试批次待推进任务(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - _require_user() - del batch_no - raise_shipping_batches_removed(action='workspace.retry_batch_pending') - - @workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST']) def workspace_shipping_export_archive(): - """按批次或显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。""" + """按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。""" user = _require_user() data = request.get_json(silent=True) or {} task_nos = data.get('task_nos') if task_nos is not None and not isinstance(task_nos, list): raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') from app.services.shipping_notice.export_archive import build_export_archive - stream, filename, _manifest = build_export_archive( - user_id=user.id, batch_no=str(data.get('batch_no') or '').strip() or None, task_nos=task_nos, - ) + stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or []) response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') response.call_on_close(stream.close) return response @@ -565,13 +462,6 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str): db.session.commit() return _ok(result) -@workspace_shipping_notice_bp.route('/shipping-conversations//batch-workspace', methods=['GET']) -def workspace_shipping_conversation_batch_workspace(conversation_id: str): - """返回一个 Agent 会话下的多批次执行工作台快照;co8 后恒为空工作台。""" - user = _require_user() - return _ok(get_conversation_batch_workspace(conversation_id, user.id)) - - @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) def workspace_create_shipping_task_from_notice(): """接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。""" @@ -696,6 +586,22 @@ def workspace_list_shipping_task_audit_timeline(task_no: str): return _ok(payload) +@workspace_shipping_notice_bp.route('/shipping-tasks//freight-notice-groups', methods=['GET']) +def workspace_shipping_task_freight_notice_groups(task_no: str): + """读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。""" + user = _require_user() + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' + from app.services.shipping_notice.query_service import ( + get_task_visible_to_user, + list_freight_notice_groups_for_task, + ) + + task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin) + if not task: + raise NotFoundError('Not found') + return _ok(list_freight_notice_groups_for_task(task, user_id=int(user.id), is_admin=is_admin)) + + @workspace_shipping_notice_bp.route('/shipping-tasks//ui-state', methods=['GET']) def workspace_shipping_task_ui_state(task_no: str): """ @@ -719,60 +625,6 @@ def workspace_shipping_task_chat_actions(task_no: str): raise NotFoundError('Not found') return _ok(build_chat_actions_payload(task)) -@workspace_shipping_notice_bp.route('/shipping-tasks//retry', methods=['POST']) -def workspace_retry_shipping_task(task_no: str): - """ - 用户侧重试当前正式 OT:统一决策器选择 resolve_source / fetch / rematch / auto_progress。 - - 核心逻辑:委托 task_retry_decision_service.retry_task_with_decision(scope=task); - 不再直接调用通用 retry_task 重置编排器。 - """ - user = _require_user() - task = get_task_for_user(task_no, user.id) - 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 - - return _ok(retry_task_with_decision( - task_no=str(task.task_no), - user_id=int(user.id), - scope='task', - reason=str(data.get('reason') or data.get('comment') or 'user_retry'), - trigger='user_retry', - continue_auto_progress=False, - )) - - -@workspace_shipping_notice_bp.route( - '/shipping-tasks//lines//retry', - methods=['POST'], -) -def workspace_retry_shipping_task_line(task_no: str, line_key: str): - """ - 行级统一「重试」:与任务级共用决策器,scope=line。 - - 核心逻辑:前端不传内部动作码;后端按行库存事实选择 fetch/rematch/needs_human。 - """ - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - _assert_fulfillment_task_ownership(task, user.id) - data = request.get_json(silent=True) or {} - from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision - - return _ok(retry_task_with_decision( - task_no=str(task.task_no), - user_id=int(user.id), - scope='line', - line_key=str(line_key or '').strip(), - reason=str(data.get('reason') or 'user_retry_inventory'), - trigger='user_line_retry', - continue_auto_progress=False, - )) - - @workspace_shipping_notice_bp.route('/shipping-tasks//update-notice-fields', methods=['POST']) def workspace_update_shipping_notice_fields(task_no: str): """更新发货通知单头字段。""" @@ -802,7 +654,7 @@ def workspace_update_shipping_notice_fields(task_no: str): @workspace_shipping_notice_bp.route('/shipping-freight-cancellations//complete', methods=['POST']) def workspace_complete_shipping_freight_cancellation(cancellation_id: int): - """登记货代撤销回执并解除合法后继版本的履约阻断。""" + """登记已取得外部撤销确认并解除合法后继版本的履约阻断。""" user = _require_user() data = request.get_json(silent=True) or {} from app.models import ShippingFreightCancellation @@ -814,9 +666,7 @@ def workspace_complete_shipping_freight_cancellation(cancellation_id: int): raise NotFoundError('Not found') from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation row = complete_freight_cancellation( - cancellation_id=cancellation.id, actor_id=int(user.id), - freight_receipt_no=str(data.get('freight_receipt_no') or ''), - receipt_asset_id=data.get('receipt_asset_id'), note=str(data.get('note') or ''), + cancellation_id=cancellation.id, actor_id=int(user.id), note=str(data.get('note') or ''), ) db.session.commit() return _ok({'id': row.id, 'status': row.status, 'old_task_id': row.old_task_id, 'new_task_id': row.new_task_id}) @@ -998,9 +848,10 @@ def workspace_auto_progress_shipping_task(task_no: str): @workspace_shipping_notice_bp.route('/shipping-tasks//mark-manual-uploaded', methods=['POST']) def workspace_mark_manual_uploaded(task_no: str): """ - 登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。 + 兼容旧 task_no 的人工上传确认;不再提交或记录截图/PDF、货代回执号。 - 核心逻辑:委托 upload_to_freight(mode=manual_confirm);禁止 RPA。 + 核心逻辑:仅委托 upload_to_freight(mode=manual_confirm),新客户端必须改用 + business_no 的 `/shipping-notices//confirm-uploaded`。 """ user = _require_user() task = get_task_for_user(task_no, user.id) @@ -1016,21 +867,232 @@ def workspace_mark_manual_uploaded(task_no: str): 'actor_id': user.id, '_trusted_user_id': user.id, 'event_source': 'workspace_api', - 'evidence_asset_no': data.get('evidence_asset_no'), - 'freight_ref_no': data.get('freight_ref_no'), 'artifact_id': data.get('artifact_id'), } result = shipping_tools.upload_to_freight(payload) if isinstance(result, dict) and str(result.get('status') or '') == 'ok': - # 回执先由既有服务原子登记;随后仅提交 upload_receipt_recorded Gate,由服务端复核事实后 completed。 + # 人工确认已由服务原子登记;随后只推进最终上传 Gate。 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), + str(task.task_no), trigger='manual_upload_confirmed', operator_id=int(user.id), ) return _ok(result) +def _confirm_notice_uploaded(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]: + """ + 按发货通知单号确认唯一 Excel 已上传;内部 task_no 仅用于既有状态机和审计追溯。 + + Args: + business_no: 对外发货通知单号,禁止调用方以 task_no 代替。 + user_id: 当前服务端会话用户。 + artifact_id: 可选唯一 Excel Artifact 主键;不传时由服务端解析。 + + Returns: + 包含 business_no 和既有上传结果的字典。 + + Raises: + NotFoundError: 通知单不存在或当前用户无写权限。 + """ + task = get_task_for_user(str(business_no).strip().upper(), user_id) + if task is None or str(task.business_no or '').upper() != str(business_no).strip().upper(): + raise NotFoundError('Shipping notice not found') + _assert_fulfillment_task_ownership(task, user_id) + from app.services.shipping_notice import tools as shipping_tools + + result = shipping_tools.upload_to_freight({ + 'task_id': task.task_no, + 'mode': 'manual_confirm', + 'operator_id': user_id, + 'actor_id': user_id, + '_trusted_user_id': user_id, + 'event_source': 'workspace_api', + 'artifact_id': artifact_id, + }) + if isinstance(result, dict) and str(result.get('status') or '') == 'ok': + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + + run_task_auto_progress( + str(task.task_no), trigger='manual_upload_confirmed', operator_id=user_id, + ) + return {'business_no': str(task.business_no), **dict(result or {})} + + +def _load_business_notice_for_user(*, business_no: str, user_id: int) -> ShippingNotice: + """ + 按精确发货通知单号加载当前用户可操作的 Notice。 + + 核心逻辑:先由既有用户归属查询过滤,再二次比较 Notice.business_no;禁止 task_no、 + 历史聚合编号或模糊引用进入新的货代操作入口。 + + Args: + business_no: 对外发货通知单号。 + user_id: 当前服务端会话用户主键。 + + Returns: + 当前用户拥有履约写权限的 ShippingNotice。 + + Raises: + NotFoundError: 编号不存在或用户不可访问。 + """ + normalized = str(business_no or '').strip().upper() + task = get_task_for_user(normalized, user_id) + if task is None or str(task.business_no or '').strip().upper() != normalized: + raise NotFoundError('Shipping notice not found') + _assert_fulfillment_task_ownership(task, user_id) + return task + + +def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]: + """按 business_no 发起单张通知的货代 RPA 上传或重试。""" + task = _load_business_notice_for_user(business_no=business_no, user_id=user_id) + from app.services.shipping_notice import tools as shipping_tools + + result = shipping_tools.upload_to_freight({ + 'task_id': task.task_no, + 'mode': 'retry_upload', + 'operator_id': user_id, + 'actor_id': user_id, + '_trusted_user_id': user_id, + 'event_source': 'workspace_api', + 'artifact_id': artifact_id, + }) + return {'business_no': str(task.business_no), **dict(result or {})} + + +@workspace_shipping_notice_bp.route('/shipping-notices//confirm-uploaded', methods=['POST']) +def workspace_confirm_shipping_notice_uploaded(business_no: str): + """确认一张发货通知单的唯一 Excel 已人工上传,不接收回执号或截图/PDF。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_artifact_id = data.get('artifact_id') + try: + artifact_id = int(raw_artifact_id) if raw_artifact_id is not None else None + except (TypeError, ValueError) as exc: + raise ValidationError('artifact_id must be an integer') from exc + return _ok(_confirm_notice_uploaded( + business_no=business_no, user_id=int(user.id), artifact_id=artifact_id, + )) + + +@workspace_shipping_notice_bp.route('/shipping-notices//rpa-upload', methods=['POST']) +def workspace_start_shipping_notice_rpa_upload(business_no: str): + """按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_artifact_id = data.get('artifact_id') + try: + artifact_id = int(raw_artifact_id) if raw_artifact_id is not None else None + except (TypeError, ValueError) as exc: + raise ValidationError('artifact_id must be an integer') from exc + return _ok(_start_notice_rpa_upload( + business_no=business_no, user_id=int(user.id), artifact_id=artifact_id, + ), status=202) + + +@workspace_shipping_notice_bp.route('/shipping-notices/batch/confirm-uploaded', methods=['POST']) +def workspace_batch_confirm_shipping_notices_uploaded(): + """批量确认多个通知单已上传;每张通知单独立事务裁决,单项失败不回滚其他单。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_values = data.get('business_nos') + if not isinstance(raw_values, list): + raise ValidationError('business_nos must be a non-empty list') + business_nos = list(dict.fromkeys( + str(value or '').strip().upper() for value in raw_values if str(value or '').strip() + )) + if not business_nos or len(business_nos) > 100: + raise ValidationError('business_nos must contain 1 to 100 business numbers') + results: list[dict[str, Any]] = [] + for business_no in business_nos: + try: + result = _confirm_notice_uploaded(business_no=business_no, user_id=int(user.id)) + db.session.commit() + results.append({'business_no': business_no, 'status': 'confirmed', 'result': result}) + except AppError as exc: + db.session.rollback() + results.append({'business_no': business_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message}) + except Exception: + db.session.rollback() + raise + return _ok({'results': results}) + + +@workspace_shipping_notice_bp.route('/shipping-notices/batch/rpa-upload', methods=['POST']) +def workspace_batch_start_shipping_notice_rpa_upload(): + """批量发起 RPA 上传;每个 business_no 独立提交,单项失败不影响其他通知单。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_values = data.get('business_nos') + if not isinstance(raw_values, list): + raise ValidationError('business_nos must be a non-empty list') + business_nos = list(dict.fromkeys( + str(value or '').strip().upper() for value in raw_values if str(value or '').strip() + )) + if not business_nos or len(business_nos) > 100: + raise ValidationError('business_nos must contain 1 to 100 business numbers') + results: list[dict[str, Any]] = [] + for business_no in business_nos: + try: + result = _start_notice_rpa_upload(business_no=business_no, user_id=int(user.id)) + db.session.commit() + result_status = 'accepted' if str(result.get('status') or '').lower() in {'ok', 'running'} else 'blocked' + results.append({'business_no': business_no, 'status': result_status, 'result': result}) + except AppError as exc: + db.session.rollback() + results.append({'business_no': business_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message}) + except Exception: + db.session.rollback() + raise + return _ok({'results': results}, status=202) + + +@workspace_shipping_notice_bp.route('/shipping-notices//export', methods=['GET']) +def workspace_shipping_notice_export(business_no: str): + """按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。""" + user = _require_user() + task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id)) + err_msg = task_export_error_message(task) + if err_msg: + raise NotFoundError(err_msg) + resolved = resolve_task_export_download(task) + assert resolved is not None + path, download_name = resolved + from app.services.shipping_notice.fulfillment_audit import record_access_audit + record_access_audit( + action='download_notice_excel', + aggregate_type='shipping_notice', + aggregate_id=str(task.business_no), + actor_id=user.id, + task_no=str(task.task_no), + reason_code='excel_downloaded', + metadata={'business_no': str(task.business_no), 'export': 'excel'}, + ) + return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE) + + +@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST']) +def workspace_shipping_notice_export_archive(): + """按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_values = data.get('business_nos') + if not isinstance(raw_values, list): + raise ValidationError('business_nos must be a non-empty list') + business_nos = list(dict.fromkeys( + str(value or '').strip().upper() for value in raw_values if str(value or '').strip() + )) + if not business_nos or len(business_nos) > 100: + raise ValidationError('business_nos must contain 1 to 100 business numbers') + from app.services.shipping_notice.export_archive import build_export_archive + + stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos) + response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') + response.call_on_close(stream.close) + return response + + @workspace_shipping_notice_bp.route('/shipping-tasks//export', methods=['GET']) def workspace_shipping_task_export(task_no: str): """下载当前用户可访问任务的出货 Excel;写入统一访问审计。""" @@ -1265,11 +1327,17 @@ def workspace_get_shipping_processing_conversation(conversation_id: str): user = _require_user() from app.services.shipping_notice.shipping_processing_projection import ( project_conversation_processing_items, + project_conversation_processing_summary, ) agent_raw = request.args.get('agent_id') agent_id = int(agent_raw) if agent_raw not in (None, '') else None - payload = project_conversation_processing_items( + projector = ( + project_conversation_processing_summary + if str(request.args.get('view') or '').strip().lower() == 'summary' + else project_conversation_processing_items + ) + payload = projector( user_id=user.id, conversation_id=str(conversation_id or '').strip(), agent_id=agent_id, @@ -1352,7 +1420,21 @@ def workspace_mark_conversation_task_viewed(task_no: str): @workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/', methods=['GET']) def workspace_get_shipping_order_extraction_run(run_no: str): - """查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端;访问留痕。""" + """ + 查询当前用户的一次订单抽取 Run,并返回可与浏览器 HAR 对齐的读取分段耗时。 + + 核心逻辑:先按当前用户加载 Run,再投影为工作台 DTO;保留原有访问审计,响应仅新增 + `Server-Timing` 指标,不暴露正文快照或改变业务数据。 + + Args: + run_no: 当前用户有权访问的订单抽取 Run 业务编号。 + + Returns: + Flask 成功响应,正文为既有 Run DTO,Header 含 run_lookup 和 workspace_projection 耗时。 + + Raises: + AppError: Run 不存在或当前用户无权访问时由服务层抛出。 + """ user = _require_user() from app.services.shipping_notice.fulfillment_audit import record_access_audit from app.services.shipping_notice.order_extraction_run_service import ( @@ -1360,8 +1442,12 @@ def workspace_get_shipping_order_extraction_run(run_no: str): serialize_order_extraction_run, ) + lookup_started = perf_counter() run = get_order_extraction_run(user_id=user.id, run_no=run_no) + lookup_ms = (perf_counter() - lookup_started) * 1000 + projection_started = perf_counter() payload = serialize_order_extraction_run(run) + projection_ms = (perf_counter() - projection_started) * 1000 # 轮询接口 60s 节流:窗口内复用最近访问痕迹,仍可追溯访问者与范围。 record_access_audit( action='view_order_extraction_run', @@ -1372,7 +1458,12 @@ def workspace_get_shipping_order_extraction_run(run_no: str): conversation_id=run.conversation_id, metadata={'status': str(run.status or ''), 'poll': True}, ) - return _ok(payload) + response = current_app.make_response(_ok(payload)) + response.headers['Server-Timing'] = ( + f'run_lookup;dur={lookup_ms:.1f}, ' + f'workspace_projection;dur={projection_ms:.1f}' + ) + return response @workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs//progress-events', methods=['GET']) @@ -1417,14 +1508,24 @@ def workspace_list_shipping_order_extraction_documents(run_no: str): @workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs//review', methods=['GET']) def workspace_get_shipping_order_review_run(run_no: str): - """读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。""" + """ + 读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。 + + 通过 Server-Timing 暴露查找与投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变 + JSON 响应契约或业务数据。 + """ 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_run from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user - payload = serialize_review_run(get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin)) + lookup_started = perf_counter() + review_run = get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin) + lookup_ms = (perf_counter() - lookup_started) * 1000 + projection_started = perf_counter() + payload = serialize_review_run(review_run) + projection_ms = (perf_counter() - projection_started) * 1000 record_access_audit( action='view_order_review_run', aggregate_type='order_extraction_run', @@ -1432,20 +1533,34 @@ def workspace_get_shipping_order_review_run(run_no: str): actor_id=user.id, run_no=str(run_no), ) - return _ok(payload) + response = current_app.make_response(_ok(payload)) + response.headers['Server-Timing'] = ( + f'review_lookup;dur={lookup_ms:.1f}, ' + f'review_projection;dur={projection_ms:.1f}' + ) + return response @workspace_shipping_notice_bp.route('/shipping-notice/order-review-queue/', methods=['GET']) def workspace_get_shipping_order_review_queue(run_no: str): - """读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。""" + """ + 读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。 + + 通过 Server-Timing 暴露查找与投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变 + JSON 响应契约或业务数据。 + """ 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_queue from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user + lookup_started = perf_counter() runs = get_review_queue_visible_to_user(run_no, user.id, is_admin=is_admin) + lookup_ms = (perf_counter() - lookup_started) * 1000 + projection_started = perf_counter() payload = serialize_review_queue(runs) + projection_ms = (perf_counter() - projection_started) * 1000 record_access_audit( action='view_order_review_queue', aggregate_type='conversation', @@ -1455,12 +1570,22 @@ def workspace_get_shipping_order_review_queue(run_no: str): run_no=str(run_no), metadata={'item_count': len(payload.get('items') or [])}, ) - return _ok(payload) + response = current_app.make_response(_ok(payload)) + response.headers['Server-Timing'] = ( + f'queue_lookup;dur={lookup_ms:.1f}, ' + f'queue_projection;dur={projection_ms:.1f}' + ) + return response @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 越权访问;访问留痕。 + + 通过 Server-Timing 暴露查找与快照投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变 + JSON 响应契约或业务数据。 + """ user = _require_user() is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' from app.services.shipping_notice.fulfillment_audit import record_access_audit @@ -1470,10 +1595,12 @@ def workspace_get_shipping_order_review_case(case_no: str): from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user # 只读:禁止在 GET 中入队 STP(入队仅抽取收尾 / resume / 显式 retry POST)。 - snapshot = build_order_review_case_snapshot( - get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin), - is_admin=is_admin, - ) + lookup_started = perf_counter() + review_case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin) + lookup_ms = (perf_counter() - lookup_started) * 1000 + projection_started = perf_counter() + snapshot = build_order_review_case_snapshot(review_case, is_admin=is_admin) + projection_ms = (perf_counter() - projection_started) * 1000 record_access_audit( action='view_order_review_case', aggregate_type='order_review_case', @@ -1486,7 +1613,12 @@ def workspace_get_shipping_order_review_case(case_no: str): else None ), ) - return _ok(snapshot) + response = current_app.make_response(_ok(snapshot)) + response.headers['Server-Timing'] = ( + f'case_lookup;dur={lookup_ms:.1f}, ' + f'case_projection;dur={projection_ms:.1f}' + ) + return response @workspace_shipping_notice_bp.route( @@ -1575,21 +1707,6 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str): 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( @@ -1600,8 +1717,6 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str): 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()) @@ -1808,26 +1923,24 @@ def workspace_delete_shipping_order_review_line(case_no: str, line_key: str): def workspace_validate_shipping_order_review_draft(case_no: str): """显式重跑当前草稿校验,并触发统一恢复协调器(可 auto_gate)。""" user = _require_user() - from app.services.shipping_notice.order_review_draft_service import validate_draft from app.services.shipping_notice.order_review_resume_service import ( attach_resume_outcome, resume_after_review_change, ) payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated') - result = validate_draft( - user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'), - ) - db.session.commit() + # 保存校验必须由统一恢复协调器编排:唯一客户候选自动确认 → Draft 校验 → + # Gate/资格/STP。若先独立校验,会在同一次点击中把 unique_candidate 误判为未确认。 resume = resume_after_review_change( user_id=user.id, case_no=case_no, trigger='draft_validated', change_type=None, - skip_validate=True, + skip_validate=False, allow_auto_create=True, + expected_draft_version=payload.get('expected_draft_version'), ) - return _ok(attach_resume_outcome({'case': result}, resume)) + return _ok(attach_resume_outcome({'case': resume.get('case')}, resume)) @workspace_shipping_notice_bp.route( @@ -2003,24 +2116,13 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): 为选中完整明细行创建履约波次。 Body: line_keys[], expected_draft_version, idempotency_key, reason? - 已有正式 OT 时走 create_post_ot_fulfillment_wave + schedule_post_ot_wave_progress; - 禁止调用 schedule_auto_progress_after_review_confirm。 - 无正式 OT 时保留历史 create_fulfillment_wave(BE-8 兼容分支,仅建单前兜底; - 响应标记 legacy_pre_ot_wave=true,后续版本可收敛删除)。 + 只允许正式 OT 走 create_post_ot_fulfillment_wave + + schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须 + 先完成正式建单,避免同一业务动作存在两套推进事实。 """ - import logging - user = _require_user() data = request.get_json(silent=True) or {} - from app.services.shipping_notice.order_review_confirmation_service import ( - finalize_sync_auto_progress_after_commit, - resolve_confirm_outcome, - schedule_auto_progress_after_review_confirm, - ) from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit - from app.services.shipping_notice.order_review_fulfillment_decision_service import ( - create_fulfillment_wave, - ) from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( create_post_ot_fulfillment_wave, @@ -2064,40 +2166,12 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): result['auto_progress'] = progress result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started')) result['post_ot_wave'] = True - result['legacy_pre_ot_wave'] = False return _ok(result) - # [STEP] BE-8:无正式 OT 的历史 wave→confirm 路径;仅兼容,不作为 OT 后主路径。 - logging.getLogger(__name__).warning( - 'shipping_review_fulfillment_wave_legacy_pre_ot case_no=%s line_count=%s', - case_no, - len(line_keys), + raise ValidationError( + 'A formal order task is required before creating a fulfillment wave', + code='SHIPPING.FORMAL_OT_REQUIRED', ) - result = create_fulfillment_wave( - user_id=user.id, - case_no=case_no, - line_keys=line_keys, - expected_draft_version=data.get('expected_draft_version'), - idempotency_key=idem, - reason=reason, - ) - progress = schedule_auto_progress_after_review_confirm( - task_no=result.get('task_no'), - idempotent_replay=bool(result.get('idempotent_replay')), - created_by_id=int(user.id), - commit=False, - ) - db.session.commit() - progress = finalize_sync_auto_progress_after_commit(progress) - result = dict(result) - result.pop('trigger_auto_progress', None) - result['confirm_ok'] = True - result['confirm_outcome'] = resolve_confirm_outcome(progress) - result['auto_progress'] = progress - result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started')) - result['post_ot_wave'] = False - result['legacy_pre_ot_wave'] = True - return _ok(result) @workspace_shipping_notice_bp.route( @@ -2844,8 +2918,8 @@ def workspace_list_shipping_order_extraction_runs(): page_raw = request.args.get('page') page_size_raw = request.args.get('page_size') from app.services.shipping_notice.order_extraction_run_service import ( - list_order_extraction_runs, - serialize_order_extraction_run, + list_order_extraction_run_summaries, + serialize_order_extraction_run_list_item, ) if page_raw is not None or page_size_raw is not None: @@ -2854,7 +2928,7 @@ def workspace_list_shipping_order_extraction_runs(): page_size = int(page_size_raw or 20) except (TypeError, ValueError) as exc: raise ValidationError('page and page_size must be integers') from exc - payload = list_order_extraction_runs( + payload = list_order_extraction_run_summaries( user_id=user.id, conversation_id=conversation_id, status=status, @@ -2863,7 +2937,7 @@ def workspace_list_shipping_order_extraction_runs(): ) assert isinstance(payload, dict) return _ok({ - 'items': [serialize_order_extraction_run(row) for row in payload['items']], + 'items': [serialize_order_extraction_run_list_item(row) for row in payload['items']], 'total': payload['total'], 'page': payload['page'], 'page_size': payload['page_size'], @@ -2873,14 +2947,14 @@ def workspace_list_shipping_order_extraction_runs(): limit = int(request.args.get('limit') or 50) except (TypeError, ValueError) as exc: raise ValidationError('limit must be an integer') from exc - rows = list_order_extraction_runs( + rows = list_order_extraction_run_summaries( user_id=user.id, conversation_id=conversation_id, status=status, limit=limit, ) assert isinstance(rows, list) - return _ok({'items': [serialize_order_extraction_run(row) for row in rows]}) + return _ok({'items': [serialize_order_extraction_run_list_item(row) for row in rows]}) @workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST']) diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 8fecd313..f0589dcd 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -17,7 +17,6 @@ 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, diff --git a/backend/app/jobs/handlers/shipping_auto_progress.py b/backend/app/jobs/handlers/shipping_auto_progress.py deleted file mode 100644 index 50f2aa56..00000000 --- a/backend/app/jobs/handlers/shipping_auto_progress.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -jobs/handlers/shipping_auto_progress.py - -用途:终态化历史 APX AutoProgress Job。 -依赖:JobContext、auto_progress_controller。 -逻辑:Job 已由通用队列领取为 running;本 Handler 仅委托控制器取消遗留 APX - Job 并保留审计。正式 20-Gate 只能由 shipping_process_gate Handler 执行。 -""" - -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: - """终态化历史 APX Job;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_order_extraction.py b/backend/app/jobs/handlers/shipping_order_extraction.py index 9ff29f28..bf1f4cd2 100644 --- a/backend/app/jobs/handlers/shipping_order_extraction.py +++ b/backend/app/jobs/handlers/shipping_order_extraction.py @@ -1018,7 +1018,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: 1 for order in merged_unit_orders if isinstance(order, dict) for conflict in order.get('conflicts') or [] if isinstance(conflict, dict) - if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous' + if str(conflict.get('reason') or '').strip() in { + 'supplement_relation_ambiguous', 'supplement_field_conflict', + } ) supplement_status = ( 'conflict' @@ -1148,7 +1150,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: ) # 收口摘要保留可投影的处理事实,供 Run 级 handling_items 区分待补/冲突/冻结/复核。 summary = { - 'run_no': run.run_no, 'batch_no': result.get('batch_no'), + 'run_no': run.run_no, 'created_count': int(result.get('created_count') or 0), 'opened_existing_count': int(result.get('opened_existing_count') or 0), 'pending_count': int(result.get('pending_count') or 0), diff --git a/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py index 40e4882d..987f87e8 100644 --- a/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py +++ b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py @@ -63,12 +63,13 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non try: from app.services.shipping_notice.fulfillment_workflow import generate_excel - # [STEP] 为本 OT 生成/刷新发货 Excel;wave_no 写入上下文供审计与后续过滤。 + # [STEP] 为本次独立 Notice 生成 Excel,禁止捎带同 PO 的其他项次。 gen = generate_excel({ 'task_id': task.task_no, 'wave_no': wave_no, 'line_keys': list(frozen.get('line_keys') or []), 'post_ot_wave': True, + '_orchestrator_internal_dispatch': True, }) status = str((gen or {}).get('status') or '').strip().lower() if status in {'failed', 'error'}: diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 775246ed..5d4b6f54 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -22,8 +22,6 @@ class JobType(StrEnum): SHIPPING_PROCESS_GATE = 'shipping_process_gate' # RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。 SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process' - # 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。 - SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress' # 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。 SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark' # 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm) @@ -72,7 +70,6 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', 'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', 'shipping_inventory_callback_process', - 'shipping_auto_progress', 'shipping_stp_auto_create', 'shipping_line_auto_fulfill', 'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress', }), diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 0098b220..cf357e86 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -151,7 +151,6 @@ from app.models.shipping_receipt_report import ( from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession from app.models.shipping_customer import ( ShippingBusinessSequence, - ShippingCase, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -290,7 +289,6 @@ __all__ = [ 'ShippingCustomerSiteIdentifier', 'ShippingCustomerImportBatch', 'ShippingCustomerImportRow', - 'ShippingCase', 'ShippingBusinessSequence', 'ShippingCustomerShadowResolution', 'ShippingCustomerShadowMatch', diff --git a/backend/app/models/job.py b/backend/app/models/job.py index aa83ff33..df7ef9cd 100644 --- a/backend/app/models/job.py +++ b/backend/app/models/job.py @@ -30,25 +30,6 @@ 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( diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 072b4842..f658dbdc 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -25,6 +25,7 @@ from typing import List, Optional from sqlalchemy import ( Boolean, CheckConstraint, + Date, DateTime, Float, ForeignKey, @@ -54,6 +55,7 @@ class ShippingNotice(Base): Index('ix_shipping_notices_conversation', 'conversation_id'), Index('ix_shipping_notices_current_step', 'current_step'), Index('ix_shipping_notices_upload_status', 'upload_status'), + Index('ix_shipping_notices_business_no', 'business_no'), 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'), @@ -70,11 +72,16 @@ class ShippingNotice(Base): id: Mapped[int] = mapped_column(primary_key=True) task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) - shipping_case_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_cases.id'), - index=True, - nullable=True, + customer_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_customers.id'), index=True, nullable=True, ) + customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) + # 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。 + business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True) + business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=True) + business_sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + business_numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) source_type: Mapped[str] = mapped_column(String(32), default='manual') @@ -234,11 +241,7 @@ class ShippingNotice(Base): created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - shipping_case: Mapped[Optional['ShippingCase']] = relationship( - 'ShippingCase', - back_populates='tasks', - lazy='joined', - ) + customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', lazy='joined') events: Mapped[List['ShippingTaskEvent']] = relationship( 'ShippingTaskEvent', back_populates='task', diff --git a/backend/app/models/shipping_customer.py b/backend/app/models/shipping_customer.py index 38d7dcdc..2828e693 100644 --- a/backend/app/models/shipping_customer.py +++ b/backend/app/models/shipping_customer.py @@ -1,9 +1,9 @@ """ backend/app/models/shipping_customer.py -用途:货代标准客户、客户识别证据、业务单聚合与业务编号流水模型。 +用途:货代标准客户、客户识别证据与业务编号流水模型。 依赖:models.base.Base、users、shipping_notices。 -逻辑:客户主数据提供稳定身份;ShippingCase 聚合 Notice 修订链;流水表供后续编号服务原子递增。 +逻辑:客户主数据提供稳定身份;发货通知自持履约事实;流水表供编号服务原子递增。 """ from __future__ import annotations @@ -55,7 +55,6 @@ class ShippingCustomer(Base): back_populates='customer', cascade='all, delete-orphan', ) - cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer') merged_into_customer: Mapped[Optional['ShippingCustomer']] = relationship( 'ShippingCustomer', remote_side='ShippingCustomer.id', @@ -189,40 +188,6 @@ class ShippingCustomerSiteIdentifier(Base): site: Mapped['ShippingCustomerSite'] = relationship('ShippingCustomerSite', back_populates='identifiers') -class ShippingCase(Base): - """一票发货业务聚合;多个线性任务修订版本共享同一业务单。""" - - __tablename__ = 'shipping_cases' - __table_args__ = ( - Index('ix_shipping_cases_customer_created', 'customer_id', 'created_at'), - Index('ix_shipping_cases_status_created', 'status', 'created_at'), - UniqueConstraint('replaces_case_id', name='uq_shipping_cases_replaces_case_id'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - case_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) - customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True) - business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True) - customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) - customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) - business_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) - sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) - numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - numbering_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') - status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open') - replaces_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_cases.id'), nullable=True) - created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) - created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) - updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - - customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', back_populates='cases') - tasks: Mapped[List['ShippingNotice']] = relationship( - 'ShippingNotice', - back_populates='shipping_case', - lazy='selectin', - ) - - class ShippingBusinessSequence(Base): """按业务类型、客户和 Asia/Shanghai 业务日期保存当前流水值。""" diff --git a/backend/app/models/shipping_excel_template.py b/backend/app/models/shipping_excel_template.py index 3320abcd..91a069cf 100644 --- a/backend/app/models/shipping_excel_template.py +++ b/backend/app/models/shipping_excel_template.py @@ -4,7 +4,7 @@ models/shipping_excel_template.py 用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。 依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。 逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和; - co8e9f0a1b2c 已删除 export artifact 的 batch_id 列。 + co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。 """ from __future__ import annotations diff --git a/backend/app/models/shipping_freight_cancellation.py b/backend/app/models/shipping_freight_cancellation.py index a0199351..a54c19e1 100644 --- a/backend/app/models/shipping_freight_cancellation.py +++ b/backend/app/models/shipping_freight_cancellation.py @@ -12,7 +12,7 @@ from app.models.base import Base class ShippingFreightCancellation(Base): - """已上传旧 Notice 的撤销申请与货代回执;成功前新版本不得履约。""" + """已上传旧 Notice 的撤销申请与外部撤销确认;成功前新版本不得履约。""" __tablename__ = 'shipping_notice_freight_cancellations' __table_args__ = ( diff --git a/backend/app/models/shipping_fulfillment.py b/backend/app/models/shipping_fulfillment.py index 9e6f7670..267371e2 100644 --- a/backend/app/models/shipping_fulfillment.py +++ b/backend/app/models/shipping_fulfillment.py @@ -155,8 +155,9 @@ class ShippingUploadAttempt(Base): finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + # 历史资产关联字段仅为兼容旧数据;新货代上传不写截图或文件证据。 evidence_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True) - # [BE-05] RPA 成功时持久化绿色 DOM 证据(kind/selector/observed_at/filename 等)。 + # RPA 仅保存最小状态摘要(kind/selector/observed_at/filename 等),不保存截图或 DOM。 success_evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) operator_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) diff --git a/backend/app/models/shipping_order_review_wave_line.py b/backend/app/models/shipping_order_review_wave_line.py index 940d703b..19b4427d 100644 --- a/backend/app/models/shipping_order_review_wave_line.py +++ b/backend/app/models/shipping_order_review_wave_line.py @@ -1,7 +1,7 @@ """ models/shipping_order_review_wave_line.py -用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一个 Task。 +用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。 依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。 逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入; (review_case_id, line_key) 数据库唯一约束防并发重复入波次。 diff --git a/backend/app/services/admin/shipping_customer_lifecycle_service.py b/backend/app/services/admin/shipping_customer_lifecycle_service.py index 42c3cf5d..6d123479 100644 --- a/backend/app/services/admin/shipping_customer_lifecycle_service.py +++ b/backend/app/services/admin/shipping_customer_lifecycle_service.py @@ -16,7 +16,6 @@ from sqlalchemy import select from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingBusinessSequence, - ShippingCase, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -27,6 +26,7 @@ from app.models import ( ShippingOrderCustomerMatch, ShippingCustomerShadowMatch, ShippingCustomerShadowResolution, + ShippingNotice, ) @@ -62,7 +62,7 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An } shadow_normalized = len(matched_resolution_ids) blockers = { - 'business_cases': db.session.query(ShippingCase.id).filter_by(customer_id=customer.id).count(), + 'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(), 'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(), 'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(), 'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(), diff --git a/backend/app/services/admin/shipping_customer_service.py b/backend/app/services/admin/shipping_customer_service.py index 417ad456..2dce356e 100644 --- a/backend/app/services/admin/shipping_customer_service.py +++ b/backend/app/services/admin/shipping_customer_service.py @@ -17,7 +17,6 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( - ShippingCase, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -25,6 +24,7 @@ from app.models import ( ShippingCustomerSite, ShippingCustomerSiteIdentifier, ShippingIdentityEvidence, + ShippingNotice, ) from app.services.shipping_notice.customer_normalization import ( clean_text, @@ -117,7 +117,7 @@ def serialize_customer( record: ShippingCustomer, *, include_identifiers: bool = False, - case_count: int | None = None, + notice_count: int | None = None, identifier_count: int | None = None, identity_evidence_count: int | None = None, ) -> dict[str, Any]: @@ -127,7 +127,7 @@ def serialize_customer( Args: record: 标准客户 ORM 记录。 include_identifiers: 是否附带识别证据明细。 - case_count: 列表查询预聚合的业务单数量;为空时现场查询。 + notice_count: 列表查询预聚合的发货通知数量;为空时现场查询。 identifier_count: 历史固定类型证据数量,仅供存量审计显示。 identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。 Returns: @@ -144,7 +144,7 @@ def serialize_customer( 'updated_by_id': record.updated_by_id, 'created_at': record.created_at.isoformat() if record.created_at else None, 'updated_at': record.updated_at.isoformat() if record.updated_at else None, - 'case_count': case_count if case_count is not None else db.session.query(ShippingCase.id).filter_by(customer_id=record.id).count(), + 'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(), 'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(), 'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query( ShippingIdentityEvidence.id, @@ -173,9 +173,9 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]: Returns: items、total、page、page_size、pages。 """ - case_counts = ( - db.session.query(ShippingCase.customer_id.label('customer_id'), func.count(ShippingCase.id).label('case_count')) - .group_by(ShippingCase.customer_id) + notice_counts = ( + db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count')) + .group_by(ShippingNotice.customer_id) .subquery() ) identifier_counts = ( @@ -207,12 +207,12 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]: query = ( db.session.query( ShippingCustomer, - func.coalesce(case_counts.c.case_count, 0), + func.coalesce(notice_counts.c.notice_count, 0), func.coalesce(identifier_counts.c.identifier_count, 0), func.coalesce(identity_evidence_counts.c.identity_evidence_count, 0) + func.coalesce(site_identity_evidence_counts.c.identity_evidence_count, 0), ) - .outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id) + .outerjoin(notice_counts, notice_counts.c.customer_id == ShippingCustomer.id) .outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id) .outerjoin(identity_evidence_counts, identity_evidence_counts.c.customer_id == ShippingCustomer.id) .outerjoin(site_identity_evidence_counts, site_identity_evidence_counts.c.customer_id == ShippingCustomer.id) @@ -244,10 +244,10 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]: return { 'items': [ serialize_customer( - customer, case_count=int(case_count), identifier_count=int(identifier_count), + customer, notice_count=int(notice_count), identifier_count=int(identifier_count), identity_evidence_count=int(identity_evidence_count), ) - for customer, case_count, identifier_count, identity_evidence_count in items + for customer, notice_count, identifier_count, identity_evidence_count in items ], 'total': total, 'page': page, diff --git a/backend/app/services/agent_registry/handlers/base.py b/backend/app/services/agent_registry/handlers/base.py index 2fde91ab..caafabc2 100644 --- a/backend/app/services/agent_registry/handlers/base.py +++ b/backend/app/services/agent_registry/handlers/base.py @@ -17,7 +17,7 @@ class ChatStreamContext: """ /api/chat/completions 单次流式请求上下文。 - 核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id/batch_no)。 + 核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id)。 """ query: str @@ -30,7 +30,6 @@ class ChatStreamContext: normalized_files: list[dict] | None = None adapter_hints: dict[str, Any] | None = None shipping_task_id: str = '' - shipping_batch_no: str = '' kb_type: str = '企业知识库' hxops_turn_id: str | None = None diff --git a/backend/app/services/agent_registry/handlers/shipping_notice.py b/backend/app/services/agent_registry/handlers/shipping_notice.py index d0320efc..09fe96a9 100644 --- a/backend/app/services/agent_registry/handlers/shipping_notice.py +++ b/backend/app/services/agent_registry/handlers/shipping_notice.py @@ -1,5 +1,5 @@ """ -用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务/批次 UI State。 +用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务 UI State。 依赖:shipping_notice.query_service/ui_state、agent_registry.handlers.registry。 逻辑:根据显式 task/batch 上下文构造并推送 UI State;订单抽取由后台 Run/Worker 独立执行。 """ @@ -36,7 +36,7 @@ class ShippingNoticeHandler(AgentHandler): """ 货代发货通知业务 Handler。 - 核心逻辑:按 adapter_hints / task_id / batch_no 构造 shipping_ui_state,供实时消息使用。 + 核心逻辑:按 adapter_hints / task_id 构造 shipping_ui_state,供实时消息使用。 订单抽取状态卡由 Run API 和本地消息持久化恢复,不进入普通 Dify Chatflow 生命周期。 """ @@ -51,57 +51,36 @@ class ShippingNoticeHandler(AgentHandler): """ 构造 shipping_ui_state SSE 事件。 - 核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。 + 核心逻辑:只接受显式 task_id;失败时记录日志并返回 None。 """ if not _uses_shipping_ui_state_progress(ctx.agent): return None task_id = str(ctx.shipping_task_id or '').strip() - batch_no = str(ctx.shipping_batch_no or '').strip() shipping_hints = self._shipping_hints(ctx) - if not task_id and not batch_no: + if not task_id: task_id = str(shipping_hints.get('task_id') or '').strip() - batch_no = str(shipping_hints.get('batch_no') or '').strip() - if not task_id and not batch_no: + if not task_id: return None try: - from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref - from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state + from app.services.shipping_notice.query_service import get_task_by_ref + from app.services.shipping_notice.ui_state import build_task_ui_state - task = get_task_by_ref(task_id) if task_id else None - batch = get_batch_by_no(batch_no) if batch_no else None + task = get_task_by_ref(task_id) session_id = str(getattr(ctx.session, 'session_id', '') or '') if task is not None: return { 'event': 'shipping_ui_state', 'conversation_id': session_id, 'task_no': task.task_no, - 'batch_no': None, 'ui_state': build_task_ui_state(task), } - if batch is not None: - batch_ui_state = build_batch_ui_state(batch) - focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {} - focus_ui_state = ( - batch_ui_state.get('focus_task_ui_state') - if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) - else None - ) - return { - 'event': 'shipping_ui_state', - 'conversation_id': session_id, - 'batch_no': batch.batch_no, - 'task_no': focus_task.get('task_no'), - 'batch_ui_state': batch_ui_state, - **({'ui_state': focus_ui_state} if focus_ui_state is not None else {}), - } except Exception: if current_app: current_app.logger.exception( - '[shipping-handler] build_ui_state failed request_id=%s task_id=%s batch_no=%s', + '[shipping-handler] build_ui_state failed request_id=%s task_id=%s', ctx.request_id, task_id, - batch_no, ) return None @@ -110,18 +89,11 @@ class ShippingNoticeHandler(AgentHandler): if str(event.get('event') or '') != 'shipping_ui_state': return None ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {} - batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {} - focus_state = ( - batch_ui_state.get('focus_task_ui_state') - if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) - else {} - ) - checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint') + checkpoint = ui_state.get('checkpoint') return json.dumps({ 'task_no': event.get('task_no'), - 'batch_no': event.get('batch_no'), 'checkpoint': checkpoint, - 'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'), + 'updated_at': ui_state.get('updated_at'), }, ensure_ascii=False, sort_keys=True) @staticmethod diff --git a/backend/app/services/agent_runtime_context/parser.py b/backend/app/services/agent_runtime_context/parser.py index 2f7c9c61..7ac4e006 100644 --- a/backend/app/services/agent_runtime_context/parser.py +++ b/backend/app/services/agent_runtime_context/parser.py @@ -28,7 +28,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset( "platform.request_id", "platform.locale", "platform.trigger_source", - "refs.batch_no", "refs.task_no", "refs.run_purpose", "refs.capability", @@ -40,7 +39,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset( "refs.hxops_turn_id", "domain.type", "domain.summary", - "domain.state_hint.batch_no", "domain.state_hint.focus_task_no", "domain.state_hint.schedule_task_id", "domain.state_hint.hxops_turn_id", diff --git a/backend/app/services/chat/action_registry.py b/backend/app/services/chat/action_registry.py index 9f96c1d9..21ddb00f 100644 --- a/backend/app/services/chat/action_registry.py +++ b/backend/app/services/chat/action_registry.py @@ -3,7 +3,7 @@ backend/app/services/chat/action_registry.py 用途:Chat Turn Action Handler 注册与解析。 依赖:turn_context.TurnContext、action_schema.TurnEvent、agent_registry.resolver。 -逻辑:各领域在 chat_action_handlers / maintenance_chat_actions 等模块注册 handler;turn_runtime 调用 resolve。 +逻辑:各领域在各自 action handler 模块注册 handler;turn_runtime 调用 resolve。 """ from __future__ import annotations @@ -78,8 +78,6 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler: def ensure_handlers_loaded() -> None: """延迟导入各领域 handler 模块以完成注册。""" - from app.services.shipping_notice import chat_action_handlers as _shipping_handlers # noqa: F401 from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401 - _ = _shipping_handlers _ = _shipping_extended diff --git a/backend/app/services/chat/turn_events.py b/backend/app/services/chat/turn_events.py index 74deb1a0..af2394ab 100644 --- a/backend/app/services/chat/turn_events.py +++ b/backend/app/services/chat/turn_events.py @@ -73,8 +73,6 @@ def emit_ui_state_updated(*, domain: str, conversation_id: str, payload: dict[st shipping_payload["ui_state"] = payload["ui_state"] if payload.get("task_no"): shipping_payload["task_no"] = payload["task_no"] - if payload.get("batch_no"): - shipping_payload["batch_no"] = payload["batch_no"] return modern + sse_frame(shipping_payload) diff --git a/backend/app/services/shipping_notice/apx_runtime_audit.py b/backend/app/services/shipping_notice/apx_runtime_audit.py deleted file mode 100644 index 1843f057..00000000 --- a/backend/app/services/shipping_notice/apx_runtime_audit.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -APX 历史运行时只读清点。 - -用途:在正式 20-Gate 单轨切换前,统计数据库中仍处于运行态的 APX Execution/Job。 -依赖:ShippingProcessExecution、Job ORM 模型。 -逻辑:仅执行 SELECT,区分运行态与历史终态;调用方据此决定迁移或人工关闭,不在本模块修改数据。 -""" - -from __future__ import annotations - -from app.models import Job, ShippingProcessExecution - - -_EXECUTION_RUNTIME_STATUSES = ('active', 'blocked', 'waiting_external') -_JOB_RUNTIME_STATUSES = ('queued', 'running', 'active') - - -def audit_apx_runtime_state() -> dict[str, object]: - """只读统计 APX Execution/Job 运行态与历史态数量。 - - Returns: - 包含 execution/job 两组计数。APX Job 通过 execution_no、business_ref 或 - payload 中的 execution_id 关联;任何写操作都不在此函数执行。 - """ - apx_executions = ShippingProcessExecution.query.filter( - ShippingProcessExecution.execution_no.ilike('APX-%') - ).all() - runtime_execution_ids = { - int(row.id) for row in apx_executions - if str(row.status or '').lower() in _EXECUTION_RUNTIME_STATUSES - } - apx_jobs = Job.query.filter( - Job.domain == 'shipping_notice', - Job.status.in_(_JOB_RUNTIME_STATUSES), - ).all() - runtime_job_count = 0 - for job in apx_jobs: - if int(job.execution_id or 0) in runtime_execution_ids: - runtime_job_count += 1 - continue - if str(job.business_ref or '').upper().find('APX-') >= 0: - runtime_job_count += 1 - continue - payload = job.payload_json if isinstance(job.payload_json, dict) else {} - if str(payload.get('execution_no') or '').upper().startswith('APX-'): - runtime_job_count += 1 - - return { - 'execution': { - 'active_count': len(runtime_execution_ids), - 'historical_count': len(apx_executions) - len(runtime_execution_ids), - }, - 'job': { - 'active_count': runtime_job_count, - }, - } - diff --git a/backend/app/services/shipping_notice/attachment_integrity.py b/backend/app/services/shipping_notice/attachment_integrity.py index c2268ec2..90eca8e8 100644 --- a/backend/app/services/shipping_notice/attachment_integrity.py +++ b/backend/app/services/shipping_notice/attachment_integrity.py @@ -3,7 +3,7 @@ services/shipping_notice/attachment_integrity.py 用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。 依赖:error_explainability_contract(warning→稳定原因码)、标准库。 -逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用; +逻辑:由 intake_service.retry_intake_parse 调用; BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致 (由 tests 校验两端前缀集合);可投影 attachment_reason_codes 供审计/UI。 """ diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index a14435c4..f66dfd61 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -24,14 +24,6 @@ from app.services.shipping_notice.process_gate_contract import action_belongs_to 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_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'}) @@ -107,16 +99,6 @@ def _new_execution_no() -> str: 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: - """ - 禁止创建 APX 六 Gate Execution。 - - APX 仅保留历史数据兼容;新任务和恢复入口必须通过正式 20-Gate - ``ensure_execution_for_workflow_version`` 创建 Execution。 - """ - raise RuntimeError('shipping_apx_creation_disabled') - - def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool: """按完整 20-Gate 合同识别正式 Execution;Task-only 正式链同样有效。""" from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES @@ -200,8 +182,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | """ 锁定并取得当前唯一活动 Execution。 - 核心逻辑:正式 20-Gate 链是唯一运行时状态机;历史 APX 仅可读, - 不得被重新激活或继续排队。候选版本变化仍按原规则 superseded。 + 核心逻辑:正式 20-Gate 链是唯一运行时状态机;候选版本变化仍按原规则 superseded。 """ all_active = ( ShippingProcessExecution.query @@ -230,6 +211,10 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | formal.updated_at = _utc_now() db.session.flush() return formal + if all_active: + raise RuntimeError('shipping_process_execution_contract_invalid') + if execution is not None and not _is_formal_process_execution(execution): + raise RuntimeError('shipping_process_execution_contract_invalid') 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' @@ -238,7 +223,6 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')), ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) execution = None - # APX 仅作为历史数据兼容:新任务或无正式链 Task 一律创建正式 20-Gate。 if execution is not None: execution.status = 'superseded' execution.updated_at = _utc_now() @@ -286,10 +270,7 @@ def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) Job.query.filter( Job.domain == 'shipping_notice', - Job.job_type.in_(( - JobType.SHIPPING_AUTO_PROGRESS.value, - JobType.SHIPPING_PROCESS_GATE.value, - )), + Job.job_type == JobType.SHIPPING_PROCESS_GATE.value, Job.task_id == int(task.id), Job.status == 'queued', ).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False) @@ -305,8 +286,7 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi ShippingProcessGate.query.filter_by(execution_id=int(execution.id)) .order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all() ) - # 正式运行时只接受 20-Gate 合同;AUTO_PROGRESS_GATE_CODES 仅保留给历史 - # APX 数据读取/迁移测试,不能再作为新任务的状态机校验来源。 + # 正式运行时只接受 20-Gate 合同。 from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES expected = list(PROCESS_GATE_CODES) @@ -321,9 +301,9 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi 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': + # 人工上传确认是外部完成声明,不是“重试业务动作”。确认成功后仅允许 + # 服务端重新读取 Attempt 事实并通过最后一个 Gate。 + if gate.gate_code == 'manual_upload_handoff' and gate.status == 'blocked_manual': return gate, None return None, None return None, None @@ -385,9 +365,8 @@ def submit_auto_progress( 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) if _is_formal_process_execution(execution): - # 正式 Case 的 20 Gate Execution 是唯一业务真相;APX 六 Gate 仅兼容 - # 无 Case 的旧 Task。先同步已落库事实,再把当前技术 Gate 交给唯一 - # ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。 + # 正式 20-Gate Execution 是唯一业务真相;先同步已落库事实,再把当前技术 + # Gate 交给唯一 ProcessGate Job/Attempt 通道。 from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_contract import is_technical_gate_party from app.services.shipping_notice.process_gate_executor import is_navigation_action @@ -496,39 +475,5 @@ def submit_auto_progress( if commit: db.session.commit() return result - # 理论上 _active_execution_for_task 已将活动 APX 收敛为正式链;若仍出现 - # 非正式 Execution,必须 fail-closed,禁止重新创建旧 APX Job。 - if not _is_formal_process_execution(execution): - if commit: - db.session.commit() - return { - 'status': 'legacy_readonly', - 'reason_code': 'shipping_apx_runtime_disabled', - 'execution_id': int(execution.id), - } - - -def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]: - """ - 将历史 APX AutoProgress Job 终态化,禁止六 Gate 状态机继续运行。 - - APX 已下线为只读历史兼容。Worker 仍消费遗留 queued/running Job, - 但只能取消并保留审计,绝不能触发库存、匹配、Excel 或下一 Gate。 - """ - job = Job.query.filter_by(id=int(job_id)).with_for_update().first() - if job is None or job.status != 'running': - return {'status': 'noop'} - now = _utc_now() - gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first() - job.status = 'cancelled' - job.finished_at = now - job.message = 'APX historical auto-progress runtime disabled' - if gate is not None and gate.status in {'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual'}: - gate.status = 'cancelled' - gate.updated_at = now - db.session.commit() - return { - 'status': 'legacy_readonly', - 'reason_code': 'shipping_apx_runtime_disabled', - 'execution_id': int(job.execution_id) if job.execution_id else None, - } + # 运行时只接受正式合同;数据不一致时 fail-closed。 + raise RuntimeError('shipping_process_execution_contract_invalid') diff --git a/backend/app/services/shipping_notice/batch_create_idempotency.py b/backend/app/services/shipping_notice/batch_create_idempotency.py index 6c951f96..e5c25563 100644 --- a/backend/app/services/shipping_notice/batch_create_idempotency.py +++ b/backend/app/services/shipping_notice/batch_create_idempotency.py @@ -1,136 +1,22 @@ """ services/shipping_notice/batch_create_idempotency.py -用途:发货通知建单幂等键标准化、跨请求文件内容重复校验(co8 起批次回查已移除)。 -依赖:models.ShippingNotice、query_service、batch_legacy_removed。 -逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。 +用途:发货通知跨请求文件内容重复校验。 +依赖:models.ShippingNotice。 +逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。 """ from __future__ import annotations -import hashlib -import logging import re import zlib -from typing import Any, Iterable +from typing import Iterable from sqlalchemy import text -from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import AppError, ConflictError from app.models import ShippingNotice -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - -logger = logging.getLogger(__name__) - -_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128 -_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$") - - - -def normalize_create_idempotency_key(raw: str | None) -> str | None: - """ - 标准化建单幂等键:去首尾空格、校验长度与安全字符集。 - - Args: - raw: HTTP Header / payload 中的原始幂等键。 - - Returns: - 标准化后的幂等键;空值返回 None。 - - Raises: - ValidationError: 键非空但格式或长度不合法(SHIPPING.IDEMPOTENCY_KEY_INVALID)。 - """ - value = str(raw or "").strip() - if not value: - return None - if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN: - raise AppError( - code="SHIPPING.IDEMPOTENCY_KEY_INVALID", - message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符", - http_status=400, - ) - if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value): - raise AppError( - code="SHIPPING.IDEMPOTENCY_KEY_INVALID", - message="幂等键仅允许字母、数字及 . _ : - 字符", - http_status=400, - ) - return value - - -def warn_missing_create_idempotency_key(*, source: str) -> None: - """兼容期记录缺少建单幂等键的告警,不阻断旧客户端。""" - logger.warning( - "shipping batch create without create_idempotency_key source=%s", - source, - ) - - -def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]]) -> str: - """ - 根据 notice_items 的 source_content_hash 计算稳定文件集合指纹。 - - 核心逻辑:排序后拼接哈希再 SHA-256,与批次 process_summary_json.create_content_fingerprint 对齐。 - """ - hashes: list[str] = [] - for item in notice_items: - if not isinstance(item, dict): - continue - source_hash = str(item.get("source_content_hash") or "").strip().lower() - if not source_hash: - continue - candidate_id = str(item.get("source_candidate_id") or "").strip() - if candidate_id: - hashes.append( - "|".join( - [ - candidate_id, - source_hash, - str(item.get("business_fingerprint") or "").strip().lower(), - str(item.get("content_fingerprint") or "").strip().lower(), - ] - ) - ) - else: - # 旧单文件/直接上传路径保持纯文件哈希,兼容历史批次回放。 - hashes.append(source_hash) - hashes = sorted(set(hashes)) - if not hashes: - return "" - return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower() - - -def batch_stored_content_fingerprint(batch: Any) -> str | None: - """shipping_batches 已删除;保留签名供过渡调用方,固定返回 None。""" - del batch - return None - - -def assert_idempotent_batch_content_matches( - batch: Any, - notice_items: list[dict[str, Any]], -) -> None: - """shipping_batches 已删除;幂等批次内容校验不再适用。""" - del batch, notice_items - - -def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> None: - """ - 按用户与建单幂等键查找已有批次。 - - Returns: - 固定 None(shipping_batches 已删除)。 - """ - del user_id, create_idempotency_key - return None - - -def build_existing_batch_tool_response(batch: Any, *, user_id: int) -> dict[str, Any]: - """shipping_batches 已删除;禁止构建批次重放响应。""" - del batch, user_id - raise_shipping_batches_removed() def _advisory_lock_key(*parts: str) -> int: @@ -161,7 +47,6 @@ def assert_no_exact_duplicate_notices( user_id: int, notice_items: list[dict[str, Any]], *, - exclude_batch_id: int | None = None, exclude_task_ids: Iterable[int] | None = None, ) -> None: """ @@ -175,7 +60,6 @@ def assert_no_exact_duplicate_notices( Args: user_id: 建单用户。 notice_items: 含 source_content_hash / duplicate_resolution_type 的通知项。 - exclude_batch_id: 可选;忽略同批次内任务。 exclude_task_ids: 可选;忽略这些已存在 Task(同 Case 既有波次)。 Raises: @@ -234,28 +118,25 @@ def dedupe_notice_items_by_content_hash(notice_items: list[dict[str, Any]]) -> l return unique -def handle_batch_create_integrity_error( - *, - user_id: int, - create_idempotency_key: str | None, - exc: IntegrityError, -) -> dict[str, Any] | None: - """ - 捕获批次建单唯一约束竞争,回滚后回查已有批次。 +_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128 +_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$") - Returns: - 幂等重放响应;无法回查时返回 None,由上层继续抛出原异常。 - """ - db.session.rollback() - key = str(create_idempotency_key or "").strip() - if not key: + +def normalize_create_idempotency_key(raw: str | None) -> str | None: + """标准化 Review Case 确认幂等键,防止同一确认请求重复创建任务。""" + value = str(raw or "").strip() + if not value: return None - batch = find_batch_by_create_idempotency(user_id, key) - if not batch: - return None - logger.info( - "shipping batch create idempotency race resolved batch_no=%s user_id=%s", - batch.batch_no, - user_id, - ) - return build_existing_batch_tool_response(batch, user_id=user_id) + if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN: + raise AppError( + code="SHIPPING.IDEMPOTENCY_KEY_INVALID", + message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符", + http_status=400, + ) + if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value): + raise AppError( + code="SHIPPING.IDEMPOTENCY_KEY_INVALID", + message="幂等键仅允许字母、数字及 . _ : - 字符", + http_status=400, + ) + return value diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py deleted file mode 100644 index 1004a076..00000000 --- a/backend/app/services/shipping_notice/batch_from_intakes.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -backend/app/services/shipping_notice/batch_from_intakes.py - -用途:从已解析 ShippingOrderIntake 确认建批的共享编排(co8 起 shipping_batches 已删除,入口阻断)。 -依赖:batch_legacy_removed。 -逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块; - create_shipping_batch_from_intakes / create_shipping_batch_from_candidates 在入口抛出 ValidationError。 -""" - -from __future__ import annotations - -from typing import Any - -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - -def create_shipping_batch_from_candidates( - *, - user_id: int, - conversation_id: str | None, - intake_nos: list[str], - candidate_nos: list[str], - create_idempotency_key: str | None = None, -) -> dict[str, Any]: - """ - 根据选定 Candidate 创建批次。 - - Raises: - ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。 - """ - del user_id, conversation_id, intake_nos, candidate_nos, create_idempotency_key - raise_shipping_batches_removed() - - -def create_shipping_batch_from_intakes( - *, - user_id: int, - conversation_id: str | None, - intake_nos: list[str], - candidate_nos: list[str] | None = None, - create_idempotency_key: str | None = None, -) -> dict[str, Any]: - """ - 根据已解析且未消费的 intake 列表创建批次。 - - Raises: - ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。 - """ - del user_id, conversation_id, intake_nos, candidate_nos, create_idempotency_key - raise_shipping_batches_removed() diff --git a/backend/app/services/shipping_notice/batch_from_notices.py b/backend/app/services/shipping_notice/batch_from_notices.py deleted file mode 100644 index 3f32af09..00000000 --- a/backend/app/services/shipping_notice/batch_from_notices.py +++ /dev/null @@ -1,142 +0,0 @@ -""" -services/shipping_notice/batch_from_notices.py - -用途:从发货通知附件创建批次的共享编排(workspace API 与 Chat Turn handler 共用)。 -依赖:shipping_tools、notice_upload、batch_orchestrator、batch_create_idempotency、query_service。 -逻辑:workspace/shipping_notice 与 chat_action_handlers 均调用本模块,避免建批逻辑双份维护。 -""" - -from __future__ import annotations - -from typing import Any - -from flask import current_app -from sqlalchemy.exc import IntegrityError - -from app.services.shipping_notice import tools as shipping_tools -from app.services.shipping_notice.batch_create_idempotency import ( - assert_idempotent_batch_content_matches, - build_existing_batch_tool_response, - dedupe_notice_items_by_content_hash, - find_batch_by_create_idempotency, - handle_batch_create_integrity_error, - normalize_create_idempotency_key, - warn_missing_create_idempotency_key, -) -from app.services.shipping_notice.notice_upload import build_notice_file_summary -from app.services.shipping_notice.query_service import get_focus_task_for_batch, serialize_task_summary - - -def create_shipping_batch_from_notice_items( - *, - user_id: int, - conversation_id: str | None, - notice_items: list[dict[str, Any]], - file_summary: dict[str, Any] | None = None, - create_idempotency_key: str | None = None, - defer_commit: bool = False, - start_orchestrator: bool | None = None, -) -> dict[str, Any]: - """ - 根据已抽取的发货通知条目创建批次并可选启动编排器。 - - 核心逻辑:优先按建单幂等键回查已有批次;新建时写入 create_idempotency_key 并捕获唯一约束竞争。 - intake 路径应传 defer_commit=True,避免批次先提交导致上层 ingested 关联/审计断点。 - - Args: - user_id: 当前用户 ID。 - conversation_id: 可选 Agent 会话 ID。 - notice_items: notice_upload 产出的 notice item 列表。 - file_summary: 可选文件预检摘要,写入响应供前端展示。 - create_idempotency_key: 建单幂等键(与 ShippingNotice.idempotency_key 货代上传幂等分离)。 - defer_commit: True 时下层仅 flush,由调用方最终 commit。 - start_orchestrator: 是否启动编排器;默认与 defer_commit 相反(延后提交时不启动)。 - - Returns: - 与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。 - - Raises: - ValidationError: notice_items 为空,或 shipping_batches 已删除(co8)。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed() - - -def format_batch_created_assistant_message( - result: dict[str, Any], - *, - file_count: int = 0, -) -> str: - """ - 格式化建批成功后写入 Chat Turn assistant 气泡的文案。 - - 核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构;幂等重放时提示已恢复批次。 - """ - if bool(result.get("idempotent_replay")): - batch_no = str(result.get("batch_no") or "").strip() - return f"已恢复此前创建的批次。\n批次编号:{batch_no}" if batch_no else "已恢复此前创建的批次。" - - data = result.get("data") if isinstance(result.get("data"), dict) else {} - batch = data.get("batch") if isinstance(data.get("batch"), dict) else {} - tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else [] - focus_task = tasks[0] if tasks and isinstance(tasks[0], dict) else {} - task_id = str( - (data.get("focus_task") or {}).get("task_no") - if isinstance(data.get("focus_task"), dict) - else "" - ).strip() or str(result.get("task_id") or focus_task.get("task_id") or "").strip() - batch_no = str(result.get("batch_no") or batch.get("batch_no") or "").strip() - focus_progress = "" - if focus_task.get("batch_index") and focus_task.get("batch_total"): - focus_progress = f"当前第 {focus_task['batch_index']}/{focus_task['batch_total']} 票" - count = int(file_count or batch.get("file_count") or len(tasks) or 0) - hint = str(result.get("message") or "").strip() - status = str(result.get("status") or "").strip() - orchestrator_started = bool(data.get("orchestrator_started")) - tail = "请根据提示进行确认/驳回。" if status == "needs_human" else "" - lines = [ - hint or f"已处理 {count} 份发货通知附件", - f"批次编号:{batch_no}" if batch_no else "", - f"当前任务:{task_id}" if task_id else "", - focus_progress, - f"后台已开始按票拆分处理,本批 {count} 票会逐步更新状态。" if orchestrator_started else "", - tail, - ] - return "\n".join(line for line in lines if line) - - -def intake_notice_uploads_for_batch( - request_id: str, - uploads: list, -) -> tuple[list[dict[str, Any]], dict[str, Any]]: - """ - 预检并抽取发货通知附件,返回 notice_items 与 file_summary。 - - Args: - request_id: 请求级临时目录 ID。 - uploads: Werkzeug FileStorage 列表。 - - Returns: - (notice_items, file_summary) - """ - max_files = max(int(current_app.config.get('SHIPPING_NOTICE_BATCH_MAX_FILES', 20) or 20), 1) - if len(uploads) > max_files: - from app.core.errors import ValidationError - - raise ValidationError( - '批量上传文件数超过限制', - code='SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED', - details={'max_files': max_files, 'received_files': len(uploads)}, - ) - from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads - - accepted, rejected, duplicate_files = intake_temp_notice_uploads(request_id, uploads) - file_summary = build_notice_file_summary( - total_files=len(uploads), - accepted=accepted, - rejected=rejected, - duplicate_files=duplicate_files, - ) - notice_items = [item.to_notice_item() for item in accepted] - return notice_items, file_summary diff --git a/backend/app/services/shipping_notice/batch_legacy_removed.py b/backend/app/services/shipping_notice/batch_legacy_removed.py deleted file mode 100644 index f50cf156..00000000 --- a/backend/app/services/shipping_notice/batch_legacy_removed.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -backend/app/services/shipping_notice/batch_legacy_removed.py - -用途:shipping_batches 表物理删除(co8e9f0a1b2c)后的统一阻断与文案常量。 -依赖:app.core.errors.AppError。 -逻辑:create_batch / batch_from_* 等写路径在入口调用 raise_shipping_batches_removed(HTTP 410); - 读路径 list API 返回空集,按 batch_no 查询返回 None。 -""" - -from __future__ import annotations - -from app.core.errors import AppError - -SHIPPING_BATCHES_REMOVED_MESSAGE = ( - "shipping_batches removed (migration co8e9f0a1b2c)" -) - - -def raise_shipping_batches_removed(*, action: str | None = None) -> None: - """ - 阻断仍依赖 shipping_batches 表的写路径。 - - 核心逻辑:ORM 已移除 ShippingBatch;调用方须在入口尽早抛出,避免 SQLAlchemy 访问已 DROP 表。 - - Args: - action: 可选调用方动作名,写入 error.details 便于排查。 - - Raises: - AppError: HTTP 410,code=SHIPPING.BATCHES_REMOVED。 - """ - details = {'migration': 'co8e9f0a1b2c', 'replacement': 'order-extraction-submissions'} - if action: - details['action'] = str(action) - raise AppError( - code='SHIPPING.BATCHES_REMOVED', - message=SHIPPING_BATCHES_REMOVED_MESSAGE, - http_status=410, - details=details, - retryable=False, - ) diff --git a/backend/app/services/shipping_notice/batch_orchestrator.py b/backend/app/services/shipping_notice/batch_orchestrator.py index be58573b..0bba968a 100644 --- a/backend/app/services/shipping_notice/batch_orchestrator.py +++ b/backend/app/services/shipping_notice/batch_orchestrator.py @@ -1,34 +1,29 @@ """ services/shipping_notice/batch_orchestrator.py -用途:发货通知批次/单票后台编排器。 -依赖:query_service、task_workflow、shipping_notice.tools、tool_common。 -逻辑:批次线程只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止; +用途:发货通知单票后台编排器。 +依赖:query_service、shipping_notice.tools、tool_common。 +逻辑:持久化队列只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止; 复核/STP 确认后已挂 current_order_extraction_id 的 created 任务走 auto_progress。 """ from __future__ import annotations -from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any from flask import current_app from app import db -from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING +from app.services.shipping_notice.constants import PH_RPA_PENDING from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job -from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks -from app.services.shipping_notice.task_workflow import recompute_batch_summary +from app.services.shipping_notice.query_service import get_task_by_ref from app.services.shipping_notice.tool_common import ( auto_progress_enabled, cfg_bool, - cfg_int, log_task_event, - switch_batch_focus, ) -from app.services.shipping_notice.tools import auto_progress, submit_decision +from app.services.shipping_notice.tools import auto_progress -_RUNNING_BATCHES: set[str] = set() _RUNNING_TASKS: set[str] = set() @@ -37,11 +32,6 @@ def batch_orchestrator_enabled() -> bool: return cfg_bool("SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED", True) -def batch_dispatch_concurrency() -> int: - """单个批次最多并发派发多少张票。""" - return cfg_int("SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY", 3, min_value=1) - - def _normalize_ref(value: str | None) -> str: return str(value or "").strip().upper() @@ -85,29 +75,6 @@ def _should_orchestrate_task(task: Any) -> bool: return True -def _is_retryable_task(task: Any) -> bool: - """判断任务是否允许由批次重试入口重新派发。""" - from app.services.shipping_notice.task_disposition_service import task_is_active - - if not task_is_active(task): - return False - pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower() - if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}: - return False - if getattr(task, "review_status", None): - return False - if pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}: - return True - if getattr(task, "pending_human_reason", None): - return False - return True - - -def _refresh_batch_focus(task_no: str) -> None: - """shipping_batches 已删除;批次焦点刷新无操作。""" - del task_no - - def _run_single_task(task_no: str) -> dict[str, str | None]: """ 后台执行单票任务的一轮推进。 @@ -141,9 +108,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: ), } - _refresh_batch_focus(task.task_no) - task = get_task_by_ref(normalized_task_no) - assert task is not None log_task_event( task, "backend_orchestrator_task_started", @@ -235,70 +199,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: _unmark_running(_RUNNING_TASKS, normalized_task_no) -def _background_task_runner(app: Any, task_no: str) -> None: - try: - with app.app_context(): - _run_single_task(task_no) - finally: - _unmark_running(_RUNNING_BATCHES, f"TASK::{task_no}") - - -def _background_batch_runner(app: Any, batch_no: str) -> None: - normalized_batch_no = _normalize_ref(batch_no) - try: - with app.app_context(): - batch = get_batch_by_no(normalized_batch_no) - if not batch: - return - recompute_batch_summary(batch) - db.session.commit() - - task_nos = [task.task_no for task in list_sorted_batch_tasks(batch)] - if not task_nos: - return - - max_workers = min(batch_dispatch_concurrency(), len(task_nos)) - if max_workers <= 1: - for task_no in task_nos: - _refresh_batch_focus(task_no) - _run_single_task(task_no) - batch = get_batch_by_no(normalized_batch_no) - if not batch: - break - else: - app_obj = current_app._get_current_object() - with ThreadPoolExecutor( - max_workers=max_workers, - thread_name_prefix=f"shipping-batch-{normalized_batch_no}", - ) as executor: - future_map = { - executor.submit(_run_task_with_app_context, app_obj, task_no): task_no - for task_no in task_nos - } - for future in as_completed(future_map): - task_no = future_map[future] - try: - future.result() - except Exception as exc: - task = get_task_by_ref(task_no) - if task: - task.error_message = str(exc) - log_task_event( - task, - "backend_orchestrator_task_failed", - {"error": str(exc)[:1000], "source": "batch_dispatcher"}, - ) - db.session.commit() - - batch = get_batch_by_no(normalized_batch_no) - if batch: - recompute_batch_summary(batch) - db.session.commit() - finally: - db.session.remove() - _unmark_running(_RUNNING_BATCHES, normalized_batch_no) - - def start_task_orchestrator(task_no: str | None) -> bool: """将单票后台任务写入持久化队列。""" normalized_task_no = _normalize_ref(task_no) @@ -308,80 +208,3 @@ def start_task_orchestrator(task_no: str | None) -> bool: return ok and result in {"queued_for_worker", "already_queued", "done", "ok", "running", "needs_human", "skipped"} -def start_batch_orchestrator(batch_no: str | None) -> bool: - """批次入口改为逐票入队,由 worker 消费,不再在 web 进程内起长线程。""" - normalized_batch_no = _normalize_ref(batch_no) - if not normalized_batch_no or not batch_orchestrator_enabled(): - return False - batch = get_batch_by_no(normalized_batch_no) - if not batch: - return False - - started = False - for task in list_sorted_batch_tasks(batch): - ok, _result = enqueue_shipping_notice_job( - task_no=task.task_no, - created_by_id=getattr(batch, "user_id", None), - batch_no=batch.batch_no, - ) - started = started or ok - recompute_batch_summary(batch) - db.session.commit() - return started - - -def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]: - """重试批次中可恢复的任务;RPA 耗尽态会手动开启新一轮库存导出。""" - normalized_batch_no = _normalize_ref(batch_no) - if not normalized_batch_no: - return {"status": "failed", "message": "batch_no is required"} - batch = get_batch_by_no(normalized_batch_no) - if not batch: - return {"status": "failed", "message": "batch not found"} - - started = 0 - skipped = 0 - for task in list_sorted_batch_tasks(batch): - if not _is_retryable_task(task): - skipped += 1 - continue - pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower() - if pending_reason == PH_RPA_PENDING and not getattr(task, "inventory_lines_json", None): - # 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。 - from app.services.shipping_notice.progress_workflow import run_task_auto_progress - - result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator') - status = str(result.get("status") or "").strip().lower() - if status in {"ok", "running", "needs_human"}: - started += 1 - else: - skipped += 1 - continue - if pending_reason == PH_RPA_EXHAUSTED: - result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"}) - status = str(result.get("status") or "").strip().lower() - if status in {"ok", "running", "needs_human"}: - started += 1 - else: - skipped += 1 - continue - if start_task_orchestrator(task.task_no): - started += 1 - else: - skipped += 1 - - recompute_batch_summary(batch) - db.session.commit() - return { - "status": "ok", - "batch_no": batch.batch_no, - "started": started, - "skipped": skipped, - "message": f"已为批次 {batch.batch_no} 重试 {started} 个任务,跳过 {skipped} 个任务。", - } - - -def _run_task_with_app_context(app: Any, task_no: str) -> dict[str, str | None]: - """批次派发时为单票补充独立 app/db 上下文,避免批次线程串行阻塞。""" - with app.app_context(): - return _run_single_task(task_no) diff --git a/backend/app/services/shipping_notice/business_case_service.py b/backend/app/services/shipping_notice/business_case_service.py deleted file mode 100644 index 350e093f..00000000 --- a/backend/app/services/shipping_notice/business_case_service.py +++ /dev/null @@ -1,88 +0,0 @@ -""" -services/shipping_notice/business_case_service.py - -用途:为新建货代任务创建或继承业务单聚合。 -依赖:db、ShippingCase、ShippingNotice、uuid/datetime。 -逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。 -""" - -from __future__ import annotations - -import uuid -from datetime import datetime - -from app import db -from app.core.errors import ConflictError -from app.models import ShippingCase, ShippingNotice - - -def generate_shipping_case_no() -> str: - """生成内部业务单聚合编号;仅用于系统关联,不对外替代 business_no。""" - return f"SC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" - - -def create_shipping_case(*, created_by_id: int | None = None) -> ShippingCase: - """ - 创建未绑定客户、未编号的业务单聚合。 - - Args: - created_by_id: 创建任务的用户 ID,可为空。 - Returns: - 尚未提交事务的 ShippingCase。 - """ - case = ShippingCase( - case_no=generate_shipping_case_no(), - created_by_id=created_by_id, - numbering_status='pending', - status='open', - ) - db.session.add(case) - db.session.flush() - return case - - -def resolve_shipping_case_for_new_task( - *, - supersedes_task_id: int | None = None, - duplicate_resolution_type: str | None = None, - created_by_id: int | None = None, -) -> ShippingCase: - """ - 为即将创建的任务解析业务单归属。 - - 核心逻辑:revision 必须继承父任务业务单;normal/force_create 均创建独立业务单, - 保证强制新建重新占用未来流水。 - - Args: - supersedes_task_id: 修订目标任务主键,仅 revision 使用。 - duplicate_resolution_type: normal/revision/force_create。 - created_by_id: 新任务创建人。 - Returns: - 新任务应关联的 ShippingCase。 - Raises: - ConflictError: revision 缺少或找不到父任务。 - """ - resolution_type = str(duplicate_resolution_type or 'normal').strip().lower() - if resolution_type != 'revision': - return create_shipping_case(created_by_id=created_by_id) - - if not supersedes_task_id: - raise ConflictError( - '修订任务缺少父任务', - code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', - ) - parent = db.session.get(ShippingNotice, int(supersedes_task_id)) - if parent is None: - raise ConflictError( - '修订目标任务不存在', - code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', - details={'supersedes_task_id': supersedes_task_id}, - ) - if parent.shipping_case is None: - raise ConflictError( - '修订目标任务缺少业务单关联', - code='SHIPPING_NOTICE.REVISION_CASE_MISSING', - details={'supersedes_task_id': supersedes_task_id}, - ) - return parent.shipping_case - diff --git a/backend/app/services/shipping_notice/business_numbering_service.py b/backend/app/services/shipping_notice/business_numbering_service.py index ea853062..847b2636 100644 --- a/backend/app/services/shipping_notice/business_numbering_service.py +++ b/backend/app/services/shipping_notice/business_numbering_service.py @@ -2,7 +2,7 @@ services/shipping_notice/business_numbering_service.py 用途:为已确认客户的货代业务单分配不可变业务编号。 -依赖:ShippingCase/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。 +依赖:ShippingNotice/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。 逻辑:锁定业务单后按客户与上海业务日期原子递增流水;编号写入业务单快照,事务由调用方提交。 """ @@ -15,7 +15,7 @@ from sqlalchemy import update from app import db from app.core.errors import ConflictError -from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer +from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE BUSINESS_TYPE = "shipping_notice" @@ -121,50 +121,46 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int: return int(value) -def assign_business_number(case: ShippingCase, *, moment: datetime | None = None) -> str: +def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | None = None) -> str: """ - 为业务单幂等分配业务编号,调用方负责同事务提交。 - - 核心逻辑:已有编号直接返回;否则校验启用客户与简码快照,取得上海日期流水并写入不可变编号字段。 + 为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。 Args: - case: 已加锁且已绑定标准客户的业务单。 - moment: 可选测试时刻。 - Returns: - 分配或已存在的业务编号。 - Raises: - ConflictError: 客户无效、简码缺失或当日两位流水耗尽。 - """ - if case.business_no: - return str(case.business_no) - if case.customer_id is None: - raise ConflictError( - "Shipping case customer must be confirmed before numbering", - code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED", - ) - customer = db.session.get(ShippingCustomer, int(case.customer_id)) - if customer is None or customer.status != "active": - raise ConflictError( - "Active customer is required before numbering", - code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID", - ) + notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。 + moment: 可选时刻,测试时用于固定上海业务日期。 - short_code = str(customer.short_code or "").strip().upper() + Returns: + 分配或已存在的 business_no。 + + Raises: + ConflictError: 通知单缺少客户或客户无效。 + """ + if notice.business_no: + return str(notice.business_no) + if notice.customer_id is None: + raise ConflictError( + 'Shipping notice customer must be confirmed before numbering', + code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED', + ) + customer = db.session.get(ShippingCustomer, int(notice.customer_id)) + if customer is None or customer.status != 'active': + raise ConflictError( + 'Active customer is required before numbering', + code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID', + ) + short_code = str(customer.short_code or '').strip().upper() if not SHORT_CODE_RE.fullmatch(short_code): raise ConflictError( - "Customer short code is invalid for business numbering", - code="SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID", - details={"customer_id": customer.id, "short_code": short_code}, + 'Customer short code is invalid for business numbering', + code='SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID', ) business_date = shanghai_business_date(moment) sequence_value = _next_sequence_value(customer.id, business_date) - business_no = format_business_no(short_code, business_date, sequence_value) - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = short_code - case.business_date = business_date - case.sequence_value = sequence_value - case.numbering_rule_version = NUMBERING_RULE_VERSION - case.numbering_status = "assigned" - case.business_no = business_no + notice.business_no = format_business_no(short_code, business_date, sequence_value) + notice.business_date = business_date + notice.business_sequence_value = sequence_value + notice.business_numbering_rule_version = NUMBERING_RULE_VERSION + notice.customer_name_snapshot = customer.standard_name + notice.customer_short_code_snapshot = short_code db.session.flush() - return business_no + return str(notice.business_no) diff --git a/backend/app/services/shipping_notice/candidate_qualification_contract.py b/backend/app/services/shipping_notice/candidate_qualification_contract.py index ba6c561f..24566bc9 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_contract.py +++ b/backend/app/services/shipping_notice/candidate_qualification_contract.py @@ -25,8 +25,6 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({ CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v3.0-unified-profile' # 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。 -# VC 门禁 vc_source_merged_clean 放在 field_conflicts_resolved 之后, -# 以便冲突项先被 PDF 优先裁决,剩余 needs_review 项再由本门禁拦截。 CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = ( 'auto_create_enabled', 'route_stp_eligible', @@ -35,7 +33,6 @@ 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', @@ -50,7 +47,6 @@ CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = { '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', @@ -67,8 +63,6 @@ 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 e24516f8..aa8b8e0b 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_service.py +++ b/backend/app/services/shipping_notice/candidate_qualification_service.py @@ -26,6 +26,7 @@ from app.extensions import db from app.models import ( ShippingOrderCandidate, ShippingOrderCandidateQualification, + ShippingOrderExtraction, ShippingOrderCustomerMatch, ) from app.services.shipping_notice.candidate_qualification_contract import ( @@ -34,11 +35,6 @@ 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.tool_common import extraction_emergency_stop_enabled @@ -75,6 +71,47 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85' # 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。 # 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。 _NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'}) +_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'}) +_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'}) + + +def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> bool: + """按冻结字段配置判断证据缺失是否只是可选字段诊断。 + + 核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有 + ``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法 + 追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知 + 字段继续 fail-closed。 + """ + reason = str(item.get('reason') or item.get('code') or '').strip() + if reason not in _EVIDENCE_GAP_REASONS: + return False + field_code = str(item.get('field') or item.get('field_code') or '').strip() + if not field_code: + return False + + config = item.get('field_config') if isinstance(item.get('field_config'), dict) else None + extraction_id = getattr(candidate, 'order_extraction_id', None) + if config is None and extraction_id is not None: + try: + extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) + definition = ( + extraction.schema_version.definition_json + if extraction is not None and extraction.schema_version is not None + else {} + ) + config = next( + ( + raw for raw in (definition.get('fields') or []) + if isinstance(raw, dict) and str(raw.get('field_code') or '').strip() == field_code + ), + None, + ) + except Exception: # noqa: BLE001 - 门禁读取配置失败时继续保守阻断 + config = None + if config is not None: + return not bool(config.get('required')) and not bool(config.get('auto_create_key_field')) + return field_code in _OPTIONAL_INTERNAL_FIELD_CODES def blocking_candidate_conflicts(candidate: Any) -> list[Any]: @@ -84,10 +121,6 @@ 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 或兼容替身。 @@ -97,76 +130,39 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]: conflicts = getattr(candidate, 'conflicts_json', None) if not isinstance(conflicts, list): return [] if not conflicts else [conflicts] - return [ - item for item in conflicts - if not ( - isinstance(item, dict) - and str(item.get('reason') or item.get('code') or '').strip() - in _NON_BLOCKING_CONFLICT_REASONS - ) - ] - - -# --------------------------------------------------------------------------- -# 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): + blocking: list[Any] = [] + for item in conflicts: + # 非字典遗留值无法判明严重度与裁决状态,继续 fail-closed。 + if not isinstance(item, dict): + blocking.append(item) 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 + reason = str(item.get('reason') or item.get('code') or '').strip() + if reason in _NON_BLOCKING_CONFLICT_REASONS: + continue + if field_evidence_gap_is_non_blocking(candidate, item): + continue + # 新 Finding 有稳定 key 时,Gate 只消费未解决的 blocking 项;禁止把可提示 + # 的 review_required 误升级为自动建单硬阻断。 + if str(item.get('conflict_key') or '').strip(): + if ( + str(item.get('severity') or '').strip() == 'blocking' + and str(item.get('resolution_status') or 'unresolved').strip() == 'unresolved' + ): + blocking.append(item) + continue + # 旧结构无稳定键/裁决状态,不能安全推定其已解决,保持历史 fail-closed。 + blocking.append(item) + return blocking -def _vc_fine_grained_reason(candidate: Any) -> str | None: +def current_open_candidate_conflicts(candidate: Any) -> list[Any]: + """返回当前仍开放且会阻断自动建单的 Candidate 冲突。 + + 复核投影与资格门禁必须共享这一入口:历史冲突记录只有在明确标记为 + ``blocking + unresolved`` 时才是当前阻断事实;无法判定的旧结构继续 + fail-closed,避免通过空投影或猜测放行自动建单。 """ - 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 + return blocking_candidate_conflicts(candidate) def resolve_candidate_customer_resolved( @@ -353,7 +349,6 @@ 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) @@ -366,7 +361,6 @@ 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, @@ -384,11 +378,6 @@ 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') ) @@ -402,20 +391,7 @@ def evaluate_candidate_qualification( blocking_reason_codes=blocking_reason_codes, ) - # [STEP 3b] 证据快照追加 VC 合并概览(脱敏,仅计数)—— 注意:必须在 STEP 4 status - # 计算之后执行,因为 status 不依赖 evidence_snapshot,保证零回归。 evidence_snapshot = _evidence_snapshot(candidate) - 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/chat_action_extended_handlers.py b/backend/app/services/shipping_notice/chat_action_extended_handlers.py index a64d3c54..82f08c51 100644 --- a/backend/app/services/shipping_notice/chat_action_extended_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_extended_handlers.py @@ -1,10 +1,10 @@ """ backend/app/services/shipping_notice/chat_action_extended_handlers.py -用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。 -依赖:shipping_tools、task_workflow、batch_legacy_removed、shipping_turn_helpers、action_registry。 +用途:货代 Chat Turn 扩展 Action Handler(通知重传/缺口查询)。 +依赖:shipping_tools、task_workflow、shipping_turn_helpers、action_registry。 逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大; - co8 后 switch_batch_focus 固定 410。 + 历史批次焦点切换动作已删除。 """ from __future__ import annotations @@ -16,7 +16,6 @@ from app.services.chat.action_registry import register_action_handler from app.services.chat.action_schema import TurnEvent from app.services.chat.turn_context import TurnContext from app.services.shipping_notice import tools as shipping_tools -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed from app.services.shipping_notice.query_service import ( get_task_by_ref, get_task_for_user, @@ -164,21 +163,6 @@ class ShippingUploadInventoryAction: yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"}) -class ShippingSwitchBatchFocusAction: - action_type = "shipping.switch_batch_focus" - - def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: - """ - 历史批次切票(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - del ctx - raise_shipping_batches_removed(action='shipping.switch_batch_focus') - yield from () # pragma: no cover — raise 后不可达,满足 Iterator 注解 - - class ShippingQueryShortageDetailsAction: action_type = "shipping.query_shortage_details" @@ -194,7 +178,6 @@ class ShippingQueryShortageDetailsAction: _HANDLERS = ( ShippingReplaceNoticeAction(), ShippingUploadInventoryAction(), - ShippingSwitchBatchFocusAction(), ShippingQueryShortageDetailsAction(), ) diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py deleted file mode 100644 index 1cb907e6..00000000 --- a/backend/app/services/shipping_notice/chat_action_handlers.py +++ /dev/null @@ -1,64 +0,0 @@ -""" -backend/app/services/shipping_notice/chat_action_handlers.py - -用途:货代发货通知 Chat Turn Action Handler 注册实现。 -依赖:query_service、ui_state、action_registry、 - batch_legacy_removed。 -逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow; - co8 后 create_batch_* 动作统一 raise_shipping_batches_removed,改走 order-extraction-submissions。 -""" - -from __future__ import annotations - -from typing import Iterator - -from app.services.chat.action_registry import register_action_handler -from app.services.chat.action_schema import TurnEvent -from app.services.chat.turn_context import TurnContext - - -class ShippingCreateBatchFromNoticesAction: - """历史:上传发货通知并创建 shipping_batches;co8 后已下线。""" - - action_type = "shipping.create_batch_from_notices" - - def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: - """ - 拒绝旧建批 Turn。 - - 核心逻辑:shipping_batches 已 DROP;客户端须走 Intake + order-extraction-submissions。 - """ - del ctx - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='shipping.create_batch_from_notices') - if False: # pragma: no cover — 满足 Iterator 注解 - yield TurnEvent(event='step.started', data={}) - - -class ShippingCreateBatchFromIntakesAction: - """历史:基于 Intake 确认建批;co8 后已下线,改走订单抽取提交。""" - - action_type = "shipping.create_batch_from_intakes" - - def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: - """ - 拒绝旧建批 Turn。 - - 核心逻辑:请使用 POST /order-extraction-submissions 创建 OT/Run。 - """ - del ctx - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='shipping.create_batch_from_intakes') - if False: # pragma: no cover - yield TurnEvent(event='step.started', data={}) - - -_HANDLERS = ( - ShippingCreateBatchFromNoticesAction(), - ShippingCreateBatchFromIntakesAction(), -) - -for _handler in _HANDLERS: - register_action_handler(_handler) diff --git a/backend/app/services/shipping_notice/chat_actions.py b/backend/app/services/shipping_notice/chat_actions.py index 31a8928c..44368a67 100644 --- a/backend/app/services/shipping_notice/chat_actions.py +++ b/backend/app/services/shipping_notice/chat_actions.py @@ -26,7 +26,6 @@ def build_chat_actions_payload(task) -> dict: state = build_task_ui_state(task) return { "task_no": state.get("task_no"), - "batch_no": state.get("batch_no"), "checkpoint": state.get("checkpoint"), "stage": state.get("stage"), "todo": state.get("todo"), diff --git a/backend/app/services/shipping_notice/chat_tool_capability.py b/backend/app/services/shipping_notice/chat_tool_capability.py index 90499145..7174b069 100644 --- a/backend/app/services/shipping_notice/chat_tool_capability.py +++ b/backend/app/services/shipping_notice/chat_tool_capability.py @@ -16,7 +16,7 @@ from app.core.errors import ForbiddenError from app.models import ChatSession, ShippingNotice -READ_SCOPES = frozenset({'get_shipping_status', 'get_batch_status'}) +READ_SCOPES = frozenset({'get_shipping_status'}) def _secret() -> bytes: @@ -26,15 +26,15 @@ def _secret() -> bytes: return value.encode('utf-8') -def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None, batch_no: str | None) -> str: +def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None) -> str: """为单次 Chatflow 注入签名、短效且绑定会话/对象的只读令牌。""" - body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'batch': str(batch_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex} + body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex} raw = json.dumps(body, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() signature = hmac.new(_secret(), raw, hashlib.sha256).digest() return base64.urlsafe_b64encode(raw).decode().rstrip('=') + '.' + base64.urlsafe_b64encode(signature).decode().rstrip('=') -def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None, batch_no: str | None = None) -> dict[str, Any]: +def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None) -> dict[str, Any]: """验证令牌签名、时效、scope、会话归属及请求对象,拒绝猜测他人编号。""" try: encoded, signed = str(token or '').split('.', 1) @@ -53,6 +53,4 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none() if task is None or str(body.get('task') or '').upper() != task.task_no: raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED') - if batch_no and str(body.get('batch') or '').upper() != str(batch_no).upper(): - raise ForbiddenError('Batch is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED') return body diff --git a/backend/app/services/shipping_notice/context_adapter.py b/backend/app/services/shipping_notice/context_adapter.py index fe440674..302960b2 100644 --- a/backend/app/services/shipping_notice/context_adapter.py +++ b/backend/app/services/shipping_notice/context_adapter.py @@ -33,7 +33,7 @@ def build_shipping_notice_context_adapter( Args: agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。 session_id: HXOPS 会话 ID。 - adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id、batch_no。 + adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id。 request_id: 请求追踪 ID。 trigger_source: 触发来源。 locale: 用户语言。 @@ -46,7 +46,6 @@ def build_shipping_notice_context_adapter( return build_dify_chat_inputs( session_id, task_id=shipping_hints.get('task_id'), - batch_no=shipping_hints.get('batch_no'), trigger_source=trigger_source, request_id=request_id, locale=locale, diff --git a/backend/app/services/shipping_notice/customer_auto_resolution.py b/backend/app/services/shipping_notice/customer_auto_resolution.py index 063758bf..b3fdbf7e 100644 --- a/backend/app/services/shipping_notice/customer_auto_resolution.py +++ b/backend/app/services/shipping_notice/customer_auto_resolution.py @@ -15,7 +15,6 @@ from typing import Any from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( - ShippingCase, ShippingCustomer, ShippingCustomerShadowResolution, ShippingIdentityEvidence, @@ -35,9 +34,8 @@ from app.services.shipping_notice.customer_normalization import ( normalize_domain, normalize_email, ) -from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int -from app.services.shipping_notice.business_case_service import generate_shipping_case_no -from app.services.shipping_notice.business_numbering_service import assign_business_number +from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no +from app.services.shipping_notice.business_numbering_service import assign_notice_business_number AUTO_RESOLUTION_VERSION = "customer-auto-v2" CUSTOMER_AUDIT_EVENT_TYPES = ( @@ -297,8 +295,18 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: Returns: status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。 """ - # [PARAM_TUNING] 业务策略改为:已发布识别指纹唯一命中即可自动确认; - # 不再以全局开关、历史标注样本量或准确率二次阻断唯一确定结果。 + # [STEP 1] 总开关关闭时不评估证据,保证环境可安全降级至人工确认。 + if not auto_customer_resolution_enabled(): + return { + 'status': 'disabled', + 'rule_version': AUTO_RESOLUTION_VERSION, + 'customer_id': None, + 'evidence': [], + 'quality_gate': { + 'status': 'disabled', + 'is_eligible': False, + }, + } if task.source_candidate_id is None: return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} shadow = db.session.query(ShippingCustomerShadowResolution).filter_by( @@ -313,11 +321,16 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: if shadow is None: return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} - return {**_resolve_auto_customer_from_shadow_resolution(shadow), 'quality_gate': { - 'status': 'bypassed_unique_match_policy', - 'is_eligible': True, - 'reason': '唯一识别指纹命中直接自动确认', - }} + decision = _resolve_auto_customer_from_shadow_resolution(shadow) + quality_gate = _auto_confirmation_quality_gate() + if not quality_gate['is_eligible']: + return { + **decision, + 'status': str(quality_gate['status']), + 'customer_id': None, + 'quality_gate': quality_gate, + } + return {**decision, 'quality_gate': quality_gate} def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: @@ -327,7 +340,7 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: 核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。 """ if task.customer_resolution_status == "confirmed": - return {"status": "already_confirmed", "customer_id": task.shipping_case.customer_id if task.shipping_case else None} + return {"status": "already_confirmed", "customer_id": task.customer_id} decision = resolve_auto_customer_from_shadow(task) db.session.add(ShippingTaskEvent( task_id=task.id, @@ -350,11 +363,11 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: event_type="customer_auto_confirmed", detail_json={ **decision, - "business_no": updated.shipping_case.business_no if updated.shipping_case else None, + "business_no": updated.business_no, }, )) db.session.flush() - return {**decision, "status": "auto_confirmed", "business_no": updated.shipping_case.business_no} + return {**decision, "status": "auto_confirmed", "business_no": updated.business_no} def correct_numbered_task_customer( @@ -365,10 +378,10 @@ def correct_numbered_task_customer( actor_id: int | None, ) -> dict[str, Any]: """ - 更正已编号业务单的标准客户,同时保留原号作废与替代关系。 + 更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。 - 核心逻辑:锁定原业务单并校验未上传 → 创建替代业务单和新号 → 迁移整条任务版本链 → - 清理当前版本的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。 + 核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice → + 清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。 Args: task: 原业务号或技术号定位到的当前任务版本。 @@ -387,31 +400,23 @@ def correct_numbered_task_customer( "Customer correction reason is required", code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED", ) - if task.shipping_case_id is None: - raise ConflictError( - "Numbered shipping case is required for customer correction", - code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED", - ) - - original_case = ( - db.session.query(ShippingCase) - .filter(ShippingCase.id == int(task.shipping_case_id)) + original = ( + db.session.query(ShippingNotice) + .filter(ShippingNotice.id == int(task.id)) .with_for_update() .one_or_none() ) - if original_case is None: - raise NotFoundError("Shipping case not found", code="SHIPPING.CASE_NOT_FOUND") - if not original_case.business_no: + if original is None or not original.business_no: raise ConflictError( - "Numbered shipping case is required for customer correction", + "Numbered shipping notice is required for customer correction", code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED", ) - existing_replacement = db.session.query(ShippingCase.id).filter_by( - replaces_case_id=original_case.id, + existing_replacement = db.session.query(ShippingNotice.id).filter_by( + supersedes_task_id=original.id, ).first() - if existing_replacement is not None or original_case.status == "voided": + if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided': raise ConflictError( - "Shipping case has already been replaced", + "Shipping notice has already been replaced", code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED", ) @@ -422,117 +427,79 @@ def correct_numbered_task_customer( raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED") if customer.status != "active": raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE") - if original_case.customer_id == customer.id: + if original.customer_id == customer.id: raise ValidationError( "Corrected customer must differ from the current customer", code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED", ) - versions = ( - db.session.query(ShippingNotice) - .filter_by(shipping_case_id=original_case.id) - .order_by(ShippingNotice.document_version.asc(), ShippingNotice.id.asc()) - .with_for_update() - .all() - ) - if not versions: + if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}: raise ConflictError( - "Shipping case has no task versions", - code="SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING", - ) - if any( - str(getattr(version, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} - or str(version.upload_status or "").lower() in {"uploaded", "succeeded", "success"} - for version in versions - ): - raise ConflictError( - "Uploaded shipping cases require an external cancellation workflow before correction", + "Uploaded shipping notices require an external cancellation workflow before correction", code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED", ) - old_business_no = str(original_case.business_no) - replacement = ShippingCase( - case_no=generate_shipping_case_no(), + old_business_no = str(original.business_no) + now = datetime.utcnow() + customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest() + replacement = ShippingNotice( + task_no=generate_task_no(), + user_id=original.user_id, + conversation_id=original.conversation_id, + source_type=original.source_type, + source_file_name=original.source_file_name, + source_file_type=original.source_file_type, + source_content_hash=original.source_content_hash, + source_asset_id=original.source_asset_id, + source_intake_id=original.source_intake_id, + source_candidate_id=original.source_candidate_id, + order_task_id=original.order_task_id, + business_fingerprint=original.business_fingerprint, + fingerprint_version=original.fingerprint_version, + content_fingerprint=original.content_fingerprint, + content_fingerprint_version=original.content_fingerprint_version, + document_version=int(original.document_version or 1) + 1, + supersedes_task_id=original.id, + raw_content=original.raw_content, customer_id=customer.id, customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code, - numbering_status="pending", - status="open", - replaces_case_id=original_case.id, - created_by_id=actor_id, + customer_resolution_status="confirmed", + customer_resolution_method="admin_correction", + customer_identity_fingerprint=customer_fingerprint, + customer_confirmed_by=actor_id, + customer_confirmed_at=now, ) db.session.add(replacement) db.session.flush() - new_business_no = assign_business_number(replacement) - - original_case.status = "voided" - original_case.numbering_status = "voided" - now = datetime.utcnow() - customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest() - latest = max(versions, key=lambda item: (int(item.document_version or 1), int(item.id))) - for version in versions: - version.shipping_case_id = replacement.id - version.customer_resolution_status = "confirmed" - version.customer_resolution_method = "admin_correction" - version.customer_identity_fingerprint = customer_fingerprint - version.customer_confirmed_by = actor_id - version.customer_confirmed_at = now - db.session.add(ShippingTaskEvent( - task_id=version.id, - event_type="customer_correction_applied", - detail_json={ - "old_case_id": original_case.id, - "new_case_id": replacement.id, - "old_business_no": old_business_no, - "new_business_no": new_business_no, - "old_customer_id": original_case.customer_id, - "new_customer_id": customer.id, - "reason": correction_reason, - "actor_id": actor_id, - }, - )) + new_business_no = assign_notice_business_number(replacement) + original.lifecycle_status = 'voided' + original.voided_at = now + original.voided_by_id = actor_id + original.void_reason = f'customer_correction:{correction_reason}' + correction_detail = { + "old_notice_id": original.id, + "new_notice_id": replacement.id, + "old_business_no": old_business_no, + "new_business_no": new_business_no, + "old_customer_id": original.customer_id, + "new_customer_id": customer.id, + "reason": correction_reason, + "actor_id": actor_id, + } + db.session.add(ShippingTaskEvent(task_id=original.id, event_type="customer_correction_applied", detail_json=correction_detail)) + db.session.add(ShippingTaskEvent(task_id=replacement.id, event_type="customer_correction_applied", detail_json=correction_detail)) # 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。 - latest.inventory_source_code = None - latest.inventory_connector_type = None - latest.inventory_warehouse_id = None - latest.inventory_source_status = None - latest.inventory_source_method = None - latest.inventory_source_confirmed_by = None - latest.inventory_source_confirmed_at = None - latest.inventory_source_config_version = None - latest.inventory_routing_fingerprint = None - latest.inventory_rpa_consumed_run_no = None - latest.inventory_snapshot_id = None - latest.inventory_lines_json = None - latest.match_status = None - latest.shortage_json = None - latest.line_results_json = None - latest.export_file_path = None - latest.export_file_name = None - latest.freight_ref_no = None - latest.upload_status = None - latest.upload_mode = None - latest.upload_attempt = 0 - latest.upload_started_at = None - latest.upload_finished_at = None - latest.upload_error_code = None - latest.upload_error_message = None - latest.upload_receipt_json = None - latest.idempotency_key = None - latest.current_step = None - latest.review_status = None - latest.pending_human_reason = None - latest.error_message = None db.session.commit() return { - "task_no": latest.task_no, - "old_case_id": original_case.id, - "new_case_id": replacement.id, + "task_no": replacement.task_no, + "old_notice_id": original.id, + "new_notice_id": replacement.id, "old_business_no": old_business_no, "new_business_no": new_business_no, "customer_id": customer.id, - "affected_task_count": len(versions), + "affected_task_count": 1, } diff --git a/backend/app/services/shipping_notice/customer_identity_gate.py b/backend/app/services/shipping_notice/customer_identity_gate.py index ff57ed42..ea193393 100644 --- a/backend/app/services/shipping_notice/customer_identity_gate.py +++ b/backend/app/services/shipping_notice/customer_identity_gate.py @@ -16,21 +16,17 @@ from sqlalchemy import or_ from app import db from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError -from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent +from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent from app.services.shipping_notice.customer_normalization import clean_text -from app.services.shipping_notice.business_numbering_service import assign_business_number CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' def customer_identity_is_confirmed(task: ShippingNotice) -> bool: - """判断任务是否已关联业务单并通过标准客户确认。""" - if task.shipping_case_id is None: + """判断 Notice 自身是否已通过标准客户确认。""" + if task.customer_id is None: return False - case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id)) - if case is None or case.customer_id is None: - return False - customer = db.session.get(ShippingCustomer, int(case.customer_id)) + customer = db.session.get(ShippingCustomer, int(task.customer_id)) return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed') @@ -46,9 +42,6 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con """ if customer_identity_is_confirmed(task): return - case = task.shipping_case or ( - db.session.get(ShippingCase, int(task.shipping_case_id)) if task.shipping_case_id else None - ) raise AppError( code=CUSTOMER_GATE_ERROR_CODE, message='标准客户尚未确认,无法继续后续流程', @@ -56,9 +49,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con details={ 'operation': operation, 'task_no': task.task_no, - 'shipping_case_id': task.shipping_case_id, 'customer_resolution_status': task.customer_resolution_status or 'pending', - 'customer_id': case.customer_id if case else None, + 'customer_id': task.customer_id, }, ) @@ -87,10 +79,10 @@ def confirm_task_customer( commit: bool = True, ) -> ShippingNotice: """ - 人工确认任务所属标准客户,并同步共享业务单下所有任务版本。 + 人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。 - 核心逻辑:锁定业务单 → 校验启用客户 → 原子分配业务号 → 同步 revision 任务确认状态和事件。 - 客户确认与编号同事务提交,任何一步失败都不留下半确认状态。 + 核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。 + 客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。 Args: task: 待确认客户的任务。 @@ -99,19 +91,14 @@ def confirm_task_customer( resolution_method: manual/auto_rule 等审计方法。 commit: 是否提交事务;批次编排传 False 由外层统一提交。 """ - if task.shipping_case_id is None: - raise ConflictError( - 'Shipping task is missing its required shipping case', - code='SHIPPING.CUSTOMER_CASE_REQUIRED', - ) - case = ( - db.session.query(ShippingCase) - .filter(ShippingCase.id == int(task.shipping_case_id)) - .with_for_update() - .one_or_none() + task = ( + db.session.query(ShippingNotice) + .filter(ShippingNotice.id == int(task.id)) + # ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN; + # PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。 + .with_for_update(of=ShippingNotice) + .one() ) - if case is None: - raise NotFoundError('Shipping case not found', code='SHIPPING.CASE_NOT_FOUND') customer = db.session.get(ShippingCustomer, int(customer_id)) if customer is None: raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') @@ -119,50 +106,35 @@ def confirm_task_customer( raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED') if customer.status != 'active': raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') - if case.business_no and case.customer_id not in {None, customer.id}: + if task.business_no and task.customer_id not in {None, customer.id}: raise ConflictError( - 'Numbered shipping case customer cannot be changed silently', - code='SHIPPING.CUSTOMER_NUMBERED_CASE_LOCKED', + 'Numbered shipping notice customer cannot be changed silently', + code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED', ) now = datetime.utcnow() - previous_customer_id = case.customer_id - number_was_assigned = bool(case.business_no) - case.customer_id = customer.id - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = customer.short_code - business_no = assign_business_number(case) + previous_customer_id = task.customer_id + task.customer_id = customer.id + task.customer_name_snapshot = customer.standard_name + task.customer_short_code_snapshot = customer.short_code fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest() - tasks = db.session.query(ShippingNotice).filter_by(shipping_case_id=case.id).all() - for version in tasks: - version.customer_resolution_status = 'confirmed' - version.customer_resolution_method = resolution_method - version.customer_identity_fingerprint = fingerprint - version.customer_confirmed_by = actor_id - version.customer_confirmed_at = now - db.session.add(ShippingTaskEvent( - task_id=version.id, - event_type='customer_confirmed', - detail_json={ - 'customer_id': customer.id, - 'standard_name': customer.standard_name, - 'short_code': customer.short_code, - 'previous_customer_id': previous_customer_id, - 'method': resolution_method, - 'business_no': business_no, - }, - )) - if not number_was_assigned: - db.session.add(ShippingTaskEvent( - task_id=version.id, - event_type='business_number_assigned', - detail_json={ - 'business_no': business_no, - 'business_date': case.business_date.isoformat() if case.business_date else None, - 'sequence_value': case.sequence_value, - 'numbering_rule_version': case.numbering_rule_version, - }, - )) + task.customer_resolution_status = 'confirmed' + task.customer_resolution_method = resolution_method + task.customer_identity_fingerprint = fingerprint + task.customer_confirmed_by = actor_id + task.customer_confirmed_at = now + db.session.add(ShippingTaskEvent( + task_id=task.id, + event_type='customer_confirmed', + detail_json={ + 'customer_id': customer.id, + 'standard_name': customer.standard_name, + 'short_code': customer.short_code, + 'previous_customer_id': previous_customer_id, + 'method': resolution_method, + 'business_no': task.business_no, + }, + )) if commit: db.session.commit() return db.session.get(ShippingNotice, int(task.id)) diff --git a/backend/app/services/shipping_notice/customer_shadow_resolution.py b/backend/app/services/shipping_notice/customer_shadow_resolution.py index 3d8bee67..f20e7c0d 100644 --- a/backend/app/services/shipping_notice/customer_shadow_resolution.py +++ b/backend/app/services/shipping_notice/customer_shadow_resolution.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/customer_shadow_resolution.py 用途:对订单 Candidate 执行只读客户影子识别,并提供质量报告与人工标签。 依赖:客户主数据/识别证据、Candidate/Intake、customer_normalization。 -逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingNotice 或业务编号。 +逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingNotice 或业务编号。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index d329b992..62a3abda 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -3,7 +3,7 @@ services/shipping_notice/dify_inputs.py 用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。 依赖:agent_runtime_context 平台协议、models.ShippingNotice、shipping_notice.runtime_context。 -逻辑:由 Context Adapter / api/chat 调用;本模块按会话号解析当前批次/任务焦点, +逻辑:由 Context Adapter / api/chat 调用;本模块只使用显式任务锚点, 仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。 发货通知识别请使用 agent_registry.resolver.resolve_agent_code == 'shipping_notice'。 """ @@ -19,14 +19,8 @@ from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPU from app.services.shipping_notice.runtime_context import build_shipping_runtime_context -def _latest_batch_for_conversation(conversation_id: str) -> None: - """shipping_batches 已删除;固定返回 None。""" - del conversation_id - return None - - def _task_by_task_no(task_id: str) -> ShippingNotice | None: - """按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。""" + """按显式 task_id 获取任务;禁止按会话号猜测当前任务。""" normalized = str(task_id or "").strip().upper() if not normalized: return None @@ -66,8 +60,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) - """ 解析当前显式焦点任务行。 - 核心逻辑:优先复用已查出的显式 task;若焦点来自 batch.current_focus_task_no,再按 task_no 查询, - 但不在无焦点时回退到最近任务,避免多票批次串单。 + 核心逻辑:优先复用已查出的显式 task;不在无焦点时回退到最近任务,避免多票串单。 Args: focus_task: 已解析出的焦点任务号。 @@ -88,7 +81,6 @@ def build_dify_chat_inputs( conversation_id: str | None = None, *, task_id: str | None = None, - batch_no: str | None = None, trigger_source: str | None = None, request_id: str | None = None, locale: str | None = None, @@ -108,7 +100,6 @@ def build_dify_chat_inputs( return {} explicit_task = str(task_id or "").strip().upper() - explicit_batch = str(batch_no or "").strip().upper() explicit_temporary_session = str(temporary_inventory_session_no or '').strip().upper() resolved_temporary_session = ( explicit_temporary_session @@ -119,28 +110,12 @@ def build_dify_chat_inputs( ) ) - batch = _latest_batch_for_conversation(conv_id) explicit_task_row = _task_by_task_no(explicit_task) - focus_task = explicit_task - if not focus_task and batch and batch.current_focus_task_no: - focus_task = str(batch.current_focus_task_no or "").strip().upper() - - focus_batch = explicit_batch - if not focus_batch and batch and batch.batch_no: - focus_batch = str(batch.batch_no or "").strip().upper() - elif ( - not focus_batch - and explicit_task_row - and getattr(explicit_task_row, "batch", None) is not None - and getattr(explicit_task_row.batch, "batch_no", None) - ): - focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper() runtime_context = build_shipping_runtime_context( session_id=conv_id, task=_focus_task_row(focus_task, explicit_task_row), - batch=batch or getattr(explicit_task_row, "batch", None), trigger_source=trigger_source, request_id=request_id, locale=locale, @@ -161,7 +136,7 @@ def build_dify_chat_inputs( session = ChatSession.query.filter_by(session_id=conv_id).one_or_none() capability_token = issue_chat_capability( user_id=session.user_id, session_id=conv_id, agent_id=session.agent_id, - task_no=focus_task, batch_no=focus_batch, + task_no=focus_task, ) if session is not None else None return { AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context), diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index d38c1d7c..ec9a04c3 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -431,6 +431,62 @@ def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]: } +def _serialize_candidate_status_brief( + cand: ShippingOrderCandidate, + *, + documents: dict[int, str | None], +) -> dict[str, Any]: + """序列化 Intake 状态列表所需的 Candidate 最小字段,不读取审核证据详情。""" + from app.services.shipping_notice.duplicate_detection import _allowed_actions_for + + status = str(cand.duplicate_status or 'unchecked') + blocking = status in { + 'exact_file', + 'same_active_task', + 'same_completed_task', + 'possible_duplicate', + 'same_business_content', + 'possible_revision', + } + strength = str(cand.fingerprint_strength or 'unavailable') + if strength == 'unavailable' and status == 'none': + blocking = False + structured = cand.structured_result_json if isinstance(cand.structured_result_json, dict) else {} + business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {} + return { + 'candidate_no': cand.candidate_no, + 'primary_document_id': cand.primary_document_id, + 'primary_document_filename': documents.get(int(cand.primary_document_id)) + if cand.primary_document_id is not None else None, + 'po_number': cand.po_number or business_summary.get('po_number'), + 'validation_status': cand.validation_status, + 'candidate_status': cand.candidate_status, + 'acceptance_mode': cand.acceptance_mode, + 'extraction_source': cand.extraction_source, + 'selected': bool(cand.selected), + 'conflicts': list(cand.conflicts_json or []), + 'missing_fields': list(cand.missing_fields_json or []), + 'business_summary': business_summary, + 'duplicate': { + 'status': status, + 'blocking': blocking, + 'fingerprint_strength': strength, + 'matches': list(cand.duplicate_matches_json or []), + 'allowed_actions': _allowed_actions_for( + status=status, + fingerprint_strength=strength, + matches=list(cand.duplicate_matches_json or []), + ), + }, + 'duplicate_resolution': { + 'action': cand.duplicate_resolution, + 'target_task_no': cand.duplicate_target_task_no, + 'reason': cand.duplicate_resolution_reason, + } if cand.duplicate_resolution else None, + 'consumed_task_id': cand.consumed_task_id, + } + + def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list[dict[str, Any]]: """列出 Intake 下 Document 摘要。""" rows = ( @@ -442,15 +498,36 @@ def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list return [_serialize_document_brief(row, include_text=include_text) for row in rows] -def list_intake_candidates(intake_id: int) -> list[dict[str, Any]]: - """列出 Intake 下 Candidate 摘要。""" +def list_intake_candidates( + intake_id: int, + *, + include_details: bool = True, +) -> list[dict[str, Any]]: + """列出 Intake 下 Candidate 摘要;状态列表可省略重型审核证据。""" rows = ( db.session.query(ShippingOrderCandidate) .filter(ShippingOrderCandidate.intake_id == int(intake_id)) .order_by(ShippingOrderCandidate.id.asc()) .all() ) - return [_serialize_candidate_brief(row) for row in rows] + if include_details: + return [_serialize_candidate_brief(row) for row in rows] + + document_ids = { + int(row.primary_document_id) + for row in rows + if row.primary_document_id is not None + } + documents = { + int(row.id): row.filename + for row in ( + db.session.query(ShippingOrderDocument.id, ShippingOrderDocument.filename) + .filter(ShippingOrderDocument.id.in_(document_ids)) + .all() + if document_ids else [] + ) + } + return [_serialize_candidate_status_brief(row, documents=documents) for row in rows] _UNCHECKED_DUP: dict[str, Any] = { 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 deleted file mode 100644 index 130cdeb5..00000000 --- a/backend/app/services/shipping_notice/document_layout/coordinate_region_source_adapter.py +++ /dev/null @@ -1,231 +0,0 @@ -""" -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/coordinate_table_reconstruction.py b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py index 0f619601..e6fc1a96 100644 --- a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py +++ b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py @@ -8,6 +8,7 @@ from __future__ import annotations +import math import re from statistics import median from typing import Any, Literal @@ -15,9 +16,13 @@ from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, model_validator from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.coordinate_transform import ( + apply_coordinate_transform_to_region, +) from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value +from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value from app.services.shipping_notice.reservation_id import validated_reservation_id @@ -27,6 +32,186 @@ _DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE) DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no' +def reconstruction_exclusion_regions( + table_region: dict[str, Any], *, include_header_layouts: bool = False, +) -> list[dict[str, Any]]: + """返回明细重建的显式普通排除区;表头框只保留作语义和预览证据。""" + exclusions = [ + dict(item) for item in (table_region.get('exclusion_regions') or []) + if isinstance(item, dict) + ] + if include_header_layouts: + exclusions.extend( + dict(item['region']) + for item in (table_region.get('header_layouts') or []) + if isinstance(item, dict) and isinstance(item.get('region'), dict) + ) + return exclusions + + +def coordinate_profile_character_candidates( + *, + table_region: dict[str, Any], + reference_page_frame: dict[str, Any] | None = None, + page_size: dict[str, Any], + page_characters: list[dict[str, Any]] | None, + table_characters: list[dict[str, Any]] | None, + raw_table_bbox: dict[str, Any] | None = None, + table_id: str | None = None, + page_no: int = 1, + coordinate_transform: dict[str, Any] | None = None, + allow_table_fallback: bool = True, +) -> tuple[list[dict[str, Any]] | None, dict[str, float] | None]: + """按统一契约选择当前表区字符:整页证据优先,真实表框仅扩展纵向范围。 + + 模板区域的横向边界始终有效;真实物理表的纵向边界用于覆盖跨行表框。 + 缺少整页证据时仅回退到该表的冻结字符,不把其它页面或其它表带入。 + """ + try: + page_bbox = { + 'x0': 0.0, 'y0': 0.0, + 'x1': float(page_size['width']), 'y1': float(page_size['height']), + } + except (KeyError, TypeError, ValueError): + return None, None + if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0: + return None, None + projected = apply_coordinate_transform_to_region( + table_region, coordinate_transform=coordinate_transform, + ) + if projected is None: + return None, page_bbox + try: + reference_width = float(reference_page_frame['width']) if reference_page_frame is not None else page_bbox['x1'] + reference_height = float(reference_page_frame['height']) if reference_page_frame is not None else page_bbox['y1'] + except (KeyError, TypeError, ValueError): + return None, page_bbox + if reference_width <= 0 or reference_height <= 0: + return None, page_bbox + region_bbox = { + 'x0': projected['x0'] * reference_width, 'y0': projected['y0'] * reference_height, + 'x1': projected['x1'] * reference_width, 'y1': projected['y1'] * reference_height, + } + is_virtual_page = str(table_id or '') == f'page-{int(page_no)}' + if not is_virtual_page and isinstance(raw_table_bbox, dict): + try: + if not ( + float(raw_table_bbox['x0']) < region_bbox['x1'] + and float(raw_table_bbox['x1']) > region_bbox['x0'] + and float(raw_table_bbox['y0']) < region_bbox['y1'] + and float(raw_table_bbox['y1']) > region_bbox['y0'] + ): + return None, page_bbox + evidence_bbox = dict(region_bbox) + evidence_bbox['y0'] = min(region_bbox['y0'], float(raw_table_bbox['y0'])) + evidence_bbox['y1'] = max(region_bbox['y1'], float(raw_table_bbox['y1'])) + except (KeyError, TypeError, ValueError): + return None, page_bbox + else: + evidence_bbox = region_bbox + if isinstance(page_characters, list): + page_candidates = [ + item for item in page_characters + if isinstance(item, dict) and _character_center_in_region(item, evidence_bbox) + ] + # 页级快照可能只包含订单头或被上游裁剪过;空的页级候选不能遮蔽 + # 当前物理表仍然有效的冻结字符证据。 + if page_candidates: + return page_candidates, page_bbox + if allow_table_fallback and isinstance(table_characters, list): + return table_characters, page_bbox + return None, page_bbox + + +def _character_center_in_region(character: dict[str, Any], region: dict[str, float]) -> bool: + """判断字符中心点是否落入绝对坐标区域。""" + bbox = character.get('bbox') if isinstance(character.get('bbox'), dict) else None + if bbox is None: + return False + try: + center_x = (float(bbox['x0']) + float(bbox['x1'])) / 2 + center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2 + except (KeyError, TypeError, ValueError): + return False + return region['x0'] <= center_x <= region['x1'] and region['y0'] <= center_y <= region['y1'] + + +def reconstruct_coordinate_profile_rows_with_strategy( + *, + characters: list[PositionedCharacter | dict[str, Any]], + table_bbox: LayoutBBox | dict[str, Any], + line_layouts: list[dict[str, Any]], + table_region: dict[str, Any] | None = None, + termination_rules: list[dict[str, Any]] | None = None, + exclusion_regions: list[dict[str, Any]] | None = None, + dynamic_exclusion_regions: list[dict[str, Any]] | None = None, + line_start_field_code: str | None = None, + include_deleted: bool = False, + schema_field_metadata: list[dict[str, Any]] | None = None, + initial_fields: dict[str, str] | None = None, + initial_next_offset: int = 0, + coordinate_transform: dict[str, Any] | None = None, + page_no: int = 1, +) -> tuple[list['CoordinateProfileLogicalRow'], Any]: + """统一评估 fixed/adaptive/dynamic,并返回唯一安全的坐标明细结果。""" + from app.services.shipping_notice.document_layout.runtime_parse_strategy import ( + resolve_runtime_parse_strategy, + ) + + fixed_rows = reconstruct_coordinate_profile_rows( + characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, + table_region=table_region, termination_rules=termination_rules, + exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code, + include_deleted=include_deleted, row_reconstruction_mode='fixed_subrows', + schema_field_metadata=schema_field_metadata, initial_fields=initial_fields, + initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform, + ) + adaptive_rows = reconstruct_coordinate_profile_rows( + characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, + table_region=table_region, termination_rules=termination_rules, + exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code, + include_deleted=include_deleted, row_reconstruction_mode='adaptive_record_columns', + schema_field_metadata=schema_field_metadata, initial_fields=initial_fields, + initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform, + ) + dynamic_rows = reconstruct_coordinate_profile_rows( + characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, + table_region=table_region, termination_rules=termination_rules, + exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code, + include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns', + schema_field_metadata=schema_field_metadata, initial_fields=initial_fields, + initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform, + ) + + def strategy_rows(rows: list[CoordinateProfileLogicalRow]) -> list[dict[str, Any]]: + return [ + { + 'status': 'parsed' if not row.issues else 'needs_review', + 'issues': list(row.issues), + 'fields': [ + {'field_code': code, 'value': value} + for code, value in row.fields.items() + ], + } + for row in rows + ] + + strategy = resolve_runtime_parse_strategy( + page_glyphs={str(page_no): characters}, + fixed_rows=strategy_rows(fixed_rows), + adaptive_rows=strategy_rows(adaptive_rows), + dynamic_rows=strategy_rows(dynamic_rows), + ) + if strategy.status != 'selected' or strategy.row_mode is None: + return [], strategy + return ( + fixed_rows if strategy.row_mode == 'fixed_subrows' + else adaptive_rows if strategy.row_mode == 'adaptive_record_columns' + else dynamic_rows, + strategy, + ) + + def resolve_line_start_field_code(value: Any = None) -> str: """ 规范化模板起行锚点字段编码。 @@ -56,6 +241,59 @@ def is_valid_line_start_value(raw: Any) -> bool: return bool(text and _LINE_NUMBER_PATTERN.fullmatch(text)) +def _is_record_start( + values: dict[str, str], + fields: list[dict[str, Any]], + line_start_field_code: str, + schema_fields: dict[str, dict[str, Any]] | None = None, +) -> bool: + """用冻结 Schema 的字段类型/校验结果确认明细起行,不依赖业务字段名或列序。""" + if schema_fields is None: + start_value = values.get(line_start_field_code, '') + return is_valid_line_start_value(start_value) + start_field_configured = any( + str(field.get('field_code') or '') == line_start_field_code for field in fields + ) + start_value = values.get(line_start_field_code, '') + def schema_valid(code: str, raw: str) -> bool: + config = schema_fields.get(code) + if not config or not str(raw or '').strip(): + return False + try: + normalized = normalize_order_field_value(raw, config) + except Exception: + return False + return normalized not in (None, '') and validate_order_field_value(normalized, config) + + # 起行字段的 Schema 类型只负责保留/解析值;它被模板配置为起行锚点后, + # 还必须满足通用行号形态,避免 string 字段把表头文本(如 ``0rd``/``B``) + # 当成明细起点。该规则只作用于配置的锚点,不依赖任何业务字段名。 + has_start_anchor = ( + is_valid_line_start_value(start_value) + and schema_valid(line_start_field_code, start_value) + ) + corroborating = sum( + 1 for field in fields + if (code := str(field.get('field_code') or '')) + and code != line_start_field_code + and schema_valid(code, values.get(code, '')) + ) + configured_corroborating_fields = sum( + 1 for field in fields + if (code := str(field.get('field_code') or '')) + and code != line_start_field_code + and code in schema_fields + ) + if has_start_anchor: + # 若模板只绑定起行字段,Schema 没有第二个坐标字段可供交叉验证, + # 允许该锚点单独起行;一旦存在其它已绑定字段,必须有至少一个有效值。 + return corroborating >= 1 or configured_corroborating_fields == 0 + # A profile that explicitly configures a start field must not silently fall back + # to unrelated fields when that anchor is absent. Profiles without such a field + # may use a position-independent two-field business signature. + return not start_field_configured and corroborating >= 2 + + class CoordinateReconstructionModel(BaseModel): """为坐标重建的中间证据启用严格契约,禁止调用方注入未定义字段。""" @@ -109,7 +347,7 @@ _HEADER_TERMS = frozenset({ 'brand', 'manufacturer', 'delivery', 'shipping', 'drawing', 'rev', }) _SUMMARY_PATTERN = re.compile( - r'(?:total\s*amount|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)', + r'(?:\btotal(?:\s*amount)?\b|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)', re.IGNORECASE, ) @@ -268,7 +506,9 @@ def reconstruct_coordinate_profile_rows( include_deleted: bool = False, line_start_field_code: str | None = None, include_unanchored_rows: bool = False, - row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows', + row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] = 'fixed_subrows', + coordinate_transform: dict[str, Any] | None = None, + schema_field_metadata: list[dict[str, Any]] | None = None, ) -> list[CoordinateProfileLogicalRow]: """ 按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。 @@ -279,8 +519,33 @@ def reconstruct_coordinate_profile_rows( 才是已授权的删除证据;未授权删除文字会被忽略。``include_deleted`` 仅供标注预览 返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启 ``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。 + ``coordinate_transform`` 只能接收共同 matcher 已确认的 ``status=applied`` 平移; + 它只在当前调用的内存副本投影表区、物理行和字段区域,绝不修改冻结 Profile。 """ + projected = _project_coordinate_profile_regions( + table_region=table_region, + line_layouts=line_layouts, + termination_rules=termination_rules, + exclusion_regions=exclusion_regions, + coordinate_transform=coordinate_transform, + ) + if projected is None: + return [] + table_region = projected['table_region'] + line_layouts = projected['line_layouts'] + termination_rules = projected['termination_rules'] + exclusion_regions = projected['exclusion_regions'] start_field_code = resolve_line_start_field_code(line_start_field_code) + schema_fields = { + str(item.get('field_code') or ''): item + for item in (schema_field_metadata or []) + if ( + isinstance(item, dict) + and item.get('field_code') + and item.get('enabled', True) + and str(item.get('scope') or '') == 'line' + ) + } if schema_field_metadata is not None else None bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox) ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1)) if not ordered_layouts or [item.get('row_offset') for item in ordered_layouts] != list(range(len(ordered_layouts))): @@ -302,6 +567,11 @@ def reconstruct_coordinate_profile_rows( _absolute_relative_region(bbox, item) for item in (exclusion_regions or []) if isinstance(item, dict) ] + # 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其 + # “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions, + # 从而保留管理员配置的普通排除区。 + if row_reconstruction_mode == 'dynamic_x_columns': + exclusions = [] # [STEP 1] 删除文字不是全局业务规则;只有管理员用排除区显式圈定后才授权删除上一条明细。 marker_indices: set[int] = set() authorized_marker_indices: set[int] = set() @@ -333,6 +603,16 @@ def reconstruct_coordinate_profile_rows( # This mode is opt-in per table region. It supports documents whose stable # columns stay put while optional descriptions move values across visual rows. + if row_reconstruction_mode == 'dynamic_x_columns': + return _reconstruct_dynamic_x_columns_profile_rows( + glyphs=glyphs, + table_bbox=bbox, + ordered_layouts=ordered_layouts, + termination_rules=termination_rules or [], + include_deleted=include_deleted, + line_start_field_code=start_field_code, + schema_fields=schema_fields, + ) if row_reconstruction_mode == 'adaptive_record_columns': return _reconstruct_adaptive_record_columns_profile_rows( glyphs=glyphs, @@ -341,6 +621,7 @@ def reconstruct_coordinate_profile_rows( termination_rules=termination_rules or [], include_deleted=include_deleted, line_start_field_code=start_field_code, + schema_fields=schema_fields, ) relative_y_rows = _reconstruct_relative_y_profile_rows( @@ -352,6 +633,7 @@ def reconstruct_coordinate_profile_rows( include_deleted=include_deleted, line_start_field_code=start_field_code, include_unanchored_rows=include_unanchored_rows, + schema_fields=schema_fields, ) if relative_y_rows is not None: return relative_y_rows @@ -414,7 +696,7 @@ def reconstruct_coordinate_profile_rows( flush(role='deleted') continue main_values, main_evidence, main_issues = values_for(band, ordered_layouts[0]) - if is_valid_line_start_value(main_values.get(start_field_code, '')): + if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code, schema_fields): flush() current, current_evidence = main_values, main_evidence sources, next_offset, current_issues = [row_index], 1, main_issues @@ -451,6 +733,80 @@ def reconstruct_coordinate_profile_rows( return results if include_deleted else [row for row in results if row.role != 'deleted'] +def _project_coordinate_profile_regions( + *, + table_region: dict[str, Any] | None, + line_layouts: list[dict[str, Any]], + termination_rules: list[dict[str, Any]] | None, + exclusion_regions: list[dict[str, Any]] | None, + coordinate_transform: dict[str, Any] | None, +) -> dict[str, Any] | None: + """对当前重建调用复制并投影受 matcher 证明的统一坐标变换。 + + 未传变换时保留 legacy 行为。传入变换必须是有限、页面内的 ``applied`` + 变换;任何伪造、过界或未知状态都返回 ``None``,由调用方保持 Review, + 不能静默回退到旧绝对坐标。 + """ + def project_region(region: Any) -> dict[str, float] | None: + if not isinstance(region, dict): + return None + return apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform) + + projected_table = project_region(table_region) if table_region is not None else None + projected_layouts = [] + projected_terminations: list[dict[str, Any]] | None = [] if termination_rules is not None else None + projected_exclusions: list[dict[str, float]] | None = [] if exclusion_regions is not None else None + if table_region is not None and projected_table is None: + return None + for layout in line_layouts: + if not isinstance(layout, dict): + return None + copied = dict(layout) + region = copied.get('region') + if region is not None: + projected_region = project_region(region) + if projected_region is None: + return None + copied['region'] = projected_region + fields = [] + for field in copied.get('field_regions') or []: + if not isinstance(field, dict): + return None + projected_field = dict(field) + projected_region = project_region(field.get('region')) + if projected_region is None: + return None + projected_field['region'] = projected_region + fields.append(projected_field) + copied['field_regions'] = fields + projected_layouts.append(copied) + for rule in termination_rules or []: + if not isinstance(rule, dict): + return None + copied = dict(rule) + anchor = copied.get('anchor') + region = anchor.get('region') if isinstance(anchor, dict) else None + if region is not None: + projected_region = project_region(region) + if projected_region is None: + return None + copied['anchor'] = {**anchor, 'region': projected_region} + assert projected_terminations is not None + projected_terminations.append(copied) + for region in exclusion_regions or []: + projected_region = project_region(region) + if projected_region is None: + return None + assert projected_exclusions is not None + projected_exclusions.append(projected_region) + return { + 'table_region': projected_table, + 'line_layouts': projected_layouts, + 'termination_rules': projected_terminations, + 'exclusion_regions': projected_exclusions, + } + + def _reconstruct_adaptive_record_columns_profile_rows( *, glyphs: list[tuple[int, PositionedCharacter]], @@ -459,6 +815,7 @@ def _reconstruct_adaptive_record_columns_profile_rows( termination_rules: list[dict[str, Any]], include_deleted: bool, line_start_field_code: str, + schema_fields: dict[str, dict[str, Any]] | None = None, ) -> list[CoordinateProfileLogicalRow]: """按起行锚点分段,并在每段内用字段列及格式读取可变视觉子行。""" main_fields = ordered_layouts[0].get('field_regions') or [] @@ -489,6 +846,7 @@ def _reconstruct_adaptive_record_columns_profile_rows( main_fields=main_fields, table_bbox=table_bbox, line_start_field_code=line_start_field_code, + schema_fields=schema_fields, ) ] results: list[CoordinateProfileLogicalRow] = [] @@ -503,6 +861,17 @@ def _reconstruct_adaptive_record_columns_profile_rows( for field in fields: code = str(field['field_code']) region = _absolute_relative_region(table_bbox, field['region']) + # 自适应列模式只能为单视觉 band 选择候选。若 Schema 绑定的 + # 字段框明确跨越多个 band(如换行客户料号),该模式的单 band + # 候选必然不完整,必须交给 fixed 几何重建处理。 + if schema_fields is not None: + intersecting = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + if len(intersecting) > 1: + issues.append(f'coordinate_profile_field_band_ambiguous:{code}') + continue candidates: list[tuple[float, int, dict[str, str]]] = [] for band_index, (_, band) in enumerate(record): raw = _adaptive_field_raw(band=band, region=region, field_code=code) @@ -535,7 +904,7 @@ def _reconstruct_adaptive_record_columns_profile_rows( issues.append(f'coordinate_profile_composite_conflict:{extracted_code}') else: values[extracted_code] = extracted_value - if is_valid_line_start_value(values.get(line_start_field_code, '')): + if _is_record_start(values, main_fields, line_start_field_code, schema_fields): results.append(CoordinateProfileLogicalRow( fields=values, source_row_indices=[row_index for row_index, _ in record], @@ -545,6 +914,87 @@ def _reconstruct_adaptive_record_columns_profile_rows( return results if include_deleted else [row for row in results if row.role != 'deleted'] +def _reconstruct_dynamic_x_columns_profile_rows( + *, + glyphs: list[tuple[int, PositionedCharacter]], + table_bbox: LayoutBBox, + ordered_layouts: list[dict[str, Any]], + termination_rules: list[dict[str, Any]], + include_deleted: bool, + line_start_field_code: str, + schema_fields: dict[str, dict[str, Any]] | None = None, +) -> list[CoordinateProfileLogicalRow]: + """按每条记录的有效起行锚点平移完整字段框,恢复稳定 X、漂移 Y 的明细。""" + main_fields = ordered_layouts[0].get('field_regions') or [] + start_field = next( + (item for item in main_fields if isinstance(item, dict) and item.get('field_code') == line_start_field_code), + None, + ) + if not isinstance(start_field, dict) or not isinstance(start_field.get('region'), dict): + return [] + fields = [ + field for layout in ordered_layouts for field in (layout.get('field_regions') or []) + if isinstance(field, dict) and isinstance(field.get('region'), dict) and field.get('field_code') + ] + bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = [] + for row_index, band in enumerate(_group_visual_rows(glyphs)): + text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip() + if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, table_bbox, termination_rules): + break + bands.append((row_index, band)) + start_region = _absolute_relative_region(table_bbox, start_field['region']) + anchors = [ + index for index, (_row_index, band) in enumerate(bands) + if _is_adaptive_record_start( + band=band, start_region=start_region, main_fields=main_fields, + table_bbox=table_bbox, line_start_field_code=line_start_field_code, + schema_fields=schema_fields, + ) + ] + results: list[CoordinateProfileLogicalRow] = [] + expected_anchor_center = (start_region.y0 + start_region.y1) / 2 + for anchor_index, start in enumerate(anchors): + end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(bands) + record = bands[start:end] + anchor_box = _band_bbox(record[0][1]) + delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center + values: dict[str, str] = {} + issues: list[str] = [] + for field in fields: + code = str(field['field_code']) + saved = _absolute_relative_region(table_bbox, field['region']) + region = LayoutBBox( + x0=saved.x0, y0=saved.y0 + delta_y, + x1=saved.x1, y1=saved.y1 + delta_y, + ) + selected_bands = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + raw = _text_in_multiline_region( + selected_bands, region, + compact=code in {'part_number', 'customer_part_number', 'aws_part_number'}, + ) + if not raw: + continue + extracted = extract_profile_field_value( + extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw, + ) + for extracted_code, extracted_value in extracted.items(): + previous = values.get(extracted_code) + if previous is not None and previous != extracted_value: + issues.append(f'coordinate_profile_composite_conflict:{extracted_code}') + else: + values[extracted_code] = extracted_value + if _is_record_start(values, main_fields, line_start_field_code, schema_fields): + results.append(CoordinateProfileLogicalRow( + fields=values, + source_row_indices=[row_index for row_index, _band in record], + role='data', issues=issues, + )) + return results if include_deleted else [row for row in results if row.role != 'deleted'] + + def _adaptive_field_raw( *, band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, field_code: str, ) -> str: @@ -562,22 +1012,43 @@ def _adaptive_field_raw( def _is_adaptive_record_start( *, band: list[tuple[int, PositionedCharacter]], start_region: LayoutBBox, main_fields: list[dict[str, Any]], table_bbox: LayoutBBox, line_start_field_code: str, + schema_fields: dict[str, dict[str, Any]] | None = None, ) -> bool: - """要求起行号及同一主行的其他绑定字段共同成立,排除页眉、地址中的孤立数字。""" - if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)): - return False - evidence_fields = [ - item for item in main_fields - if item.get('field_code') != line_start_field_code and item.get('field_code') in { - 'part_number', 'customer_part_number', 'aws_part_number', - } - ] - return all( - _is_compact_identifier( - _text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region'])) + """按当前主视觉行的 Schema 字段值判断起行,不依赖业务字段名。""" + if schema_fields is None: + if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)): + return False + # 低层旧调用未提供 Schema 时仍使用通用文本形态交叉验证, + # 但不再按业务字段名建立白名单。 + evidence_fields = [ + item for item in main_fields + if isinstance(item, dict) + and item.get('field_code') != line_start_field_code + and isinstance(item.get('region'), dict) + ] + return all( + _is_compact_identifier( + _text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region'])) + ) + for field in evidence_fields ) - for field in evidence_fields - ) + values: dict[str, str] = {} + for field in main_fields: + if not isinstance(field, dict) or not isinstance(field.get('region'), dict): + continue + code = str(field.get('field_code') or '') + if not code or code not in schema_fields: + continue + raw = _adaptive_field_raw( + band=band, + region=_absolute_relative_region(table_bbox, field['region']), + field_code=code, + ) + extracted = extract_profile_field_value( + extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw, + ) + values.update(extracted) + return _is_record_start(values, main_fields, line_start_field_code, schema_fields) def _is_compact_identifier(raw: str) -> bool: @@ -623,6 +1094,7 @@ def _reconstruct_relative_y_profile_rows( include_deleted: bool, line_start_field_code: str, include_unanchored_rows: bool, + schema_fields: dict[str, dict[str, Any]] | None = None, ) -> list[CoordinateProfileLogicalRow] | None: """ 将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。 @@ -647,6 +1119,18 @@ def _reconstruct_relative_y_profile_rows( ) if start_field is None: return None + + def values_for_band(band: list[tuple[int, PositionedCharacter]]) -> dict[str, str]: + values: dict[str, str] = {} + for field in fields: + code = str(field.get('field_code') or '') + region = _absolute_relative_region(table_bbox, field['region']) + raw = _text_in_horizontal_region(band, region) + extracted = extract_profile_field_value( + extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw, + ) + values.update(extracted) + return values bands = _group_visual_rows(glyphs) usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = [] for row_index, band in enumerate(bands): @@ -661,16 +1145,17 @@ def _reconstruct_relative_y_profile_rows( anchors: list[int] = [] for index, (_, band) in enumerate(usable_bands): start_text = _text_in_horizontal_region(band, start_region) - if is_valid_line_start_value(start_text): + if schema_fields is None and is_valid_line_start_value(start_text): anchors.append(index) + elif schema_fields is not None: + values = values_for_band(band) + if _is_record_start(values, fields, line_start_field_code, schema_fields): + anchors.append(index) if not anchors: return [] - sample_end = anchors[1] if len(anchors) > 1 else len(usable_bands) - sample_record = usable_bands[anchors[0]:sample_end] - field_band_indices = _calibrate_field_band_indices( - fields=fields, sample_record=sample_record, table_bbox=table_bbox, - ) + start_region = _absolute_relative_region(table_bbox, start_field['region']) + expected_anchor_center = (start_region.y0 + start_region.y1) / 2 results: list[CoordinateProfileLogicalRow] = [] for anchor_index, start in enumerate(anchors): end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands) @@ -680,23 +1165,34 @@ def _reconstruct_relative_y_profile_rows( )) for _, band in record) values: dict[str, str] = {} issues: list[str] = [] - matched_bands, alignment_issues = _match_field_band_groups( - fields=fields, - record=record, - expected_indices=field_band_indices, - table_bbox=table_bbox, - line_start_field_code=line_start_field_code, - ) - issues.extend(alignment_issues) + anchor_box = _band_bbox(record[0][1]) + delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center for field in fields: code = str(field.get('field_code') or '') if not code: continue - band_index = matched_bands.get(id(field)) - if band_index is None: + saved = _absolute_relative_region(table_bbox, field['region']) + region = LayoutBBox( + x0=saved.x0, y0=saved.y0 + delta_y, + x1=saved.x1, y1=saved.y1 + delta_y, + ) + # A visual field box may intentionally span multiple PDF text lines + # (for example a wrapped customer part number). The previous + # one-band assignment treated that as an ambiguity and dropped the + # field, which caused two vertically stacked part-number fields to + # become empty or reuse the same prefix. When the configured field + # region intersects multiple bands, read all of its own glyphs; + # single-band fields retain the calibrated matching behavior. + intersecting = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + if not intersecting: continue - region = _absolute_relative_region(table_bbox, field['region']) - raw = _text_in_horizontal_region(record[band_index][1], region) + raw = _text_in_multiline_region( + intersecting, region, + compact=code in {'part_number', 'customer_part_number', 'aws_part_number'}, + ) if not raw: continue extracted = extract_profile_field_value( @@ -708,7 +1204,7 @@ def _reconstruct_relative_y_profile_rows( issues.append(f'coordinate_profile_composite_conflict:{extracted_code}') else: values[extracted_code] = extracted_value - if is_valid_line_start_value(values.get(line_start_field_code, '')): + if _is_record_start(values, fields, line_start_field_code, schema_fields): results.append(CoordinateProfileLogicalRow( fields=values, source_row_indices=[row_index for row_index, _ in record], @@ -819,6 +1315,86 @@ def suggest_multi_subrow_layouts( return suggestions +def derive_incomplete_table_bbox( + *, + characters: list[PositionedCharacter | dict[str, Any]], + table_bbox: LayoutBBox | dict[str, Any], +) -> dict[str, float] | None: + """从页级字符证据修复只覆盖表头的候选表格框。 + + 该函数只允许沿原候选框的纵向向下扩展:必须先看到可靠的明细起行锚点, + 并在其后遇到明确的合计/终止行;否则返回 ``None``。横向边界始终继承原候选, + 因而不会把页面上的其他表格或普通文本合并进来。 + + Args: + characters: 同页完整 PDF/OCR 字符坐标,而不是已按错误表框截取的字符。 + table_bbox: MinerU 或其他结构引擎产出的原始表格候选框。 + + Returns: + 可验证的派生绝对表格框;证据不唯一或缺失时返回 ``None``。 + """ + bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox) + if bbox.x1 <= bbox.x0 or bbox.y1 <= bbox.y0: + return None + try: + positioned = [ + ( + index, + item if isinstance(item, PositionedCharacter) + else PositionedCharacter.model_validate(item), + ) + for index, item in enumerate(characters) + ] + except Exception: + return None + # 只取原表横向范围内的字符,纵向上限使用页面证据的最大 y 值。 + candidates = [ + item for item in positioned + if bbox.x0 <= (item[1].bbox.x0 + item[1].bbox.x1) / 2 <= bbox.x1 + and (item[1].bbox.y0 + item[1].bbox.y1) / 2 >= bbox.y0 + ] + if not candidates: + return None + bands = _group_visual_rows(candidates) + anchor_bands: list[list[tuple[int, PositionedCharacter]]] = [] + summary_y0: float | None = None + for band in bands: + band_bbox = _band_bbox(band) + text = ''.join( + glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0) + ).strip() + if band_bbox.y1 <= bbox.y1: + continue + if _SUMMARY_PATTERN.search(text): + if anchor_bands: + summary_y0 = band_bbox.y0 + break + continue + if _band_starts_item(band, bbox): + anchor_bands.append(band) + if not anchor_bands: + return None + last_data_y1 = max(glyph.bbox.y1 for band in anchor_bands for _, glyph in band) + # 续行属于同一表格,但不能将其误当成新的表格边界;取终止行前的最后字符。 + for band in bands: + band_bbox = _band_bbox(band) + if band_bbox.y0 < anchor_bands[0][0][1].bbox.y0: + continue + text = ''.join( + glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0) + ).strip() + if _SUMMARY_PATTERN.search(text): + break + last_data_y1 = max(last_data_y1, band_bbox.y1) + end_y = summary_y0 if summary_y0 is not None else last_data_y1 + if end_y <= bbox.y1: + return None + return { + 'x0': float(bbox.x0), 'y0': float(bbox.y0), + 'x1': float(bbox.x1), 'y1': float(end_y), + } + + def suggest_header_regions( *, characters: list[PositionedCharacter | dict[str, Any]], @@ -1028,7 +1604,7 @@ def reconstruct_multi_subrow_table( continue main_values = _band_field_values(band, anchors[0]) - if is_valid_line_start_value(main_values.get(start_field_code, '')): + if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code): flush() current_fields = main_values current_sources = [row_index] @@ -1196,13 +1772,17 @@ def _absolute_relative_region(table_bbox: LayoutBBox, relative: dict[str, Any]) def _inside_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool: - """仅收集中心在管理员框选区域内的字符,边缘字符不跨区域复制。""" - return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1 + """按纵向中心和有效横向重叠收集字符,避免字段边界截断字形。""" + return ( + _inside_horizontal_region(glyph_bbox, region) + and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1 + ) def _inside_horizontal_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool: - """仅按标注框横向范围筛选字符,使同一行版式可应用到整张表的重复明细。""" - return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 + """接受与字段框正向相交的字形,防止紧贴边界的料号标点被截断。""" + overlap = min(glyph_bbox.x1, region.x1) - max(glyph_bbox.x0, region.x0) + return overlap > 0 def _has_relative_y_subregions(parent: dict[str, Any], fields: list[dict[str, Any]]) -> bool: @@ -1325,6 +1905,26 @@ def _text_in_region( return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit) +def _regions_overlap_vertically(left: LayoutBBox, right: LayoutBBox) -> bool: + """判断字段框与视觉 band 是否有纵向证据交集。""" + return min(left.y1, right.y1) > max(left.y0, right.y0) + + +def _text_in_multiline_region( + bands: list[list[tuple[int, PositionedCharacter]]], + region: LayoutBBox, + *, + compact: bool = False, +) -> str: + """按视觉行顺序读取跨行字段,料号换行时去除行间空白。""" + lines: list[str] = [] + for band in sorted(bands, key=lambda item: _band_bbox(item).y0): + text = _text_in_region(band, region).strip() + if text: + lines.append(text) + return ('' if compact else ' ').join(lines) + + def _text_in_horizontal_region( band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, ) -> str: diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_transform.py b/backend/app/services/shipping_notice/document_layout/coordinate_transform.py new file mode 100644 index 00000000..4aae338a --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/coordinate_transform.py @@ -0,0 +1,133 @@ +""" +services/shipping_notice/document_layout/coordinate_transform.py + +用途:对冻结 Profile 的归一化几何区域应用 matcher 已证明的受限坐标变换。 +依赖:标准库数学运算;由 Profile matcher 求解、订单头和订单行解析共同消费。 +逻辑:默认保持 legacy 绝对坐标;仅接受已应用且通过残差/边界门禁的平移或仿射矩阵, + 任何无效、过界或无法由稳定锚点证明的变换都返回 None 以进入 Review。 +""" + +from __future__ import annotations + +import math +from copy import deepcopy +from typing import Any + + +def apply_coordinate_transform_to_region( + region: dict[str, Any], *, coordinate_transform: dict[str, Any] | None, +) -> dict[str, float] | None: + """将 Profile 相对区域投影到当前文档坐标系,非法变换 fail-closed。 + + Args: + region: 含 x0/y0/x1/y1 的冻结归一化矩形。 + coordinate_transform: Matcher 唯一候选附带的 ``status=applied`` 变换;None 表示 legacy。 + + Returns: + 投影后的页内 bbox;矩阵将矩形四角包络,旋转后仍保留完整证据范围。 + """ + try: + corners = [ + (float(region['x0']), float(region['y0'])), + (float(region['x0']), float(region['y1'])), + (float(region['x1']), float(region['y0'])), + (float(region['x1']), float(region['y1'])), + ] + except (KeyError, TypeError, ValueError): + return None + if not all(math.isfinite(value) for pair in corners for value in pair): + return None + if coordinate_transform is None: + return _bounded_bbox(corners) + matrix = coordinate_transform_matrix(coordinate_transform) + if matrix is None: + return None + return _bounded_bbox([_apply_matrix(matrix, x=x, y=y) for x, y in corners]) + + +def coordinate_transform_matrix(value: dict[str, Any]) -> tuple[float, float, float, float, float, float] | None: + """解析并校验 matcher 输出;无 matrix 的历史 applied 结果仅视为平移。""" + if not isinstance(value, dict) or value.get('status') != 'applied': + return None + raw = value.get('matrix') + if isinstance(raw, list) and len(raw) == 6: + try: + matrix = tuple(float(item) for item in raw) + except (TypeError, ValueError): + return None + else: + try: + matrix = (1.0, 0.0, float(value['translate_x']), 0.0, 1.0, float(value['translate_y'])) + except (KeyError, TypeError, ValueError): + return None + if not all(math.isfinite(item) for item in matrix): + return None + a, b, _tx, d, e, _ty = matrix + determinant = a * e - b * d + if determinant <= 0 or determinant < .50 or determinant > 1.50: + return None + return matrix + + +def project_coordinate_profile_payload( + payload: dict[str, Any], *, coordinate_transform: dict[str, Any] | None, +) -> dict[str, Any] | None: + """复制并统一投影 Profile 的订单头、表区、行区、字段和终止区,不回写冻结定义。""" + if coordinate_transform is None: + return deepcopy(payload) + projected = deepcopy(payload) + + def project(region: Any) -> bool: + if not isinstance(region, dict): + return False + next_region = apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform) + if next_region is None: + return False + region.clear() + region.update(next_region) + return True + + for layout in projected.get('order_field_layouts') or []: + if not isinstance(layout, dict): + return None + for key in ('absolute_value_region', 'fallback_value_region'): + region = layout.get(key) + if region is not None and not project(region): + return None + anchor = layout.get('anchor') + if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']): + return None + for table in projected.get('table_regions') or []: + if not isinstance(table, dict) or not project(table.get('region')): + return None + for layout in [*(table.get('header_layouts') or []), *(table.get('line_layouts') or [])]: + if not isinstance(layout, dict) or not project(layout.get('region')): + return None + for field in layout.get('field_regions') or []: + if not isinstance(field, dict) or not project(field.get('region')): + return None + for rule in table.get('termination_rules') or []: + anchor = rule.get('anchor') if isinstance(rule, dict) else None + if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']): + return None + for region in table.get('exclusion_regions') or []: + if not project(region): + return None + return projected + + +def _apply_matrix(matrix: tuple[float, float, float, float, float, float], *, x: float, y: float) -> tuple[float, float]: + """应用二维仿射矩阵,输入输出均为页内归一化坐标。""" + a, b, tx, d, e, ty = matrix + return a * x + b * y + tx, d * x + e * y + ty + + +def _bounded_bbox(corners: list[tuple[float, float]]) -> dict[str, float] | None: + """将投影角点收敛为页内 bbox;旋转后越页的区域必须 Review。""" + if not corners or not all(math.isfinite(value) for pair in corners for value in pair): + return None + x0, x1 = min(x for x, _ in corners), max(x for x, _ in corners) + y0, y1 = min(y for _, y in corners), max(y for _, y in corners) + if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1): + return None + return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1} diff --git a/backend/app/services/shipping_notice/document_layout/lifecycle.py b/backend/app/services/shipping_notice/document_layout/lifecycle.py index 37925030..85265779 100644 --- a/backend/app/services/shipping_notice/document_layout/lifecycle.py +++ b/backend/app/services/shipping_notice/document_layout/lifecycle.py @@ -11,6 +11,7 @@ backend/app/services/shipping_notice/document_layout/lifecycle.py from __future__ import annotations import hashlib +import gzip import json import logging from datetime import datetime @@ -22,6 +23,7 @@ from sqlalchemy import and_, func, or_, update from app.extensions import db from app.models import ( + FileAsset, ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake, @@ -51,6 +53,81 @@ ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({ 'shipping_document_layout_candidate_glyphs_compacted', 'shipping_document_layout_candidate_page_metadata_compacted', }) +COORDINATE_EVIDENCE_REF_KEY = 'coordinate_evidence_ref' +COORDINATE_EVIDENCE_SCHEMA_VERSION = 'shipping_order_coordinate_evidence.v1' + + +def _coordinate_evidence_bytes(evidence: dict[str, Any]) -> bytes: + """将完整坐标证据以稳定 gzip JSON 编码,供不可变 FileAsset 保存。""" + raw = json.dumps(evidence, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8') + return gzip.compress(raw, compresslevel=6, mtime=0) + + +def _persist_coordinate_evidence_asset(*, document: ShippingOrderDocument, evidence: dict[str, Any]) -> dict[str, Any] | None: + """复用现有 FileAsset/MinIO 保存完整坐标证据并返回轻量引用。""" + 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 {} + if not any(isinstance(value, list) and value for value in (*tables.values(), *page_glyphs.values())): + return None + from app.services.file_assets.service import create_derived_file_asset_from_bytes + + parent = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None + intake = db.session.get(ShippingOrderIntake, int(document.intake_id)) + user_id = getattr(intake, 'user_id', None) + if parent is None or user_id is None: + return None + data = _coordinate_evidence_bytes(evidence) + asset, created = create_derived_file_asset_from_bytes( + user_id=int(user_id), parent=parent, data=data, + filename=f'{document.id}-coordinate-evidence.json.gz', + mime_type='application/json+gzip', asset_role='layout_coordinate_evidence', + ) + asset.lifecycle_status = 'referenced' + asset.expires_at = None + asset.deleted_at = None + if created or int(asset.reference_count or 0) == 0: + asset.reference_count = max(int(asset.reference_count or 0), 1) + return { + 'asset_no': str(asset.asset_no), + 'checksum': hashlib.sha256(data).hexdigest(), + 'size': len(data), + 'schema_version': str(evidence.get('version') or COORDINATE_EVIDENCE_SCHEMA_VERSION), + } + + +def _has_coordinate_evidence(evidence: Any) -> bool: + """判断证据是否含有可外置的字符集合;空占位结构保持原快照兼容。""" + if not isinstance(evidence, dict): + return False + for key in ('tables', 'page_glyphs'): + values = evidence.get(key) + if isinstance(values, dict) and any(isinstance(item, list) and item for item in values.values()): + return True + return False + + +def _hydrate_coordinate_evidence(*, payload: dict[str, Any], document: ShippingOrderDocument) -> dict[str, Any]: + """从现有 FileAsset 引用加载完整坐标证据;读取失败时保持缺证据状态。""" + ref = payload.get(COORDINATE_EVIDENCE_REF_KEY) + if not isinstance(ref, dict): + return payload + asset_no = str(ref.get('asset_no') or '').strip() + if not asset_no: + return payload + asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).first() + if asset is None: + return payload + try: + from app.services.file_assets.service import read_asset_bytes + evidence = json.loads(gzip.decompress(read_asset_bytes(asset)).decode('utf-8')) + except Exception: + _LOGGER.exception('coordinate evidence asset load failed document_id=%s asset_no=%s', document.id, asset_no) + return payload + if _has_coordinate_evidence(evidence): + hydrated = dict(payload) + hydrated['coordinate_evidence'] = evidence + return hydrated + return payload def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: dict[str, Any]) -> bool: @@ -61,10 +138,8 @@ def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: """ if Path(str(document.filename or '')).suffix.lower() != '.pdf': return True - evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {} - complete = isinstance(evidence.get('pages'), dict) and isinstance(evidence.get('page_glyphs'), dict) - recoverable = bool(document.asset_id) and isinstance(payload.get('layout_candidate'), dict) - return complete or recoverable + ref = payload.get(COORDINATE_EVIDENCE_REF_KEY) + return isinstance(ref, dict) and bool(str(ref.get('asset_no') or '').strip()) def _layout_version_reusable(*, document: ShippingOrderDocument, version: ShippingDocumentLayoutVersion) -> bool: @@ -188,6 +263,13 @@ def _fit_layout_payload_to_budget( coordinate_evidence = candidate.get('coordinate_evidence') if isinstance(coordinate_evidence, dict): + # [STEP] 仅在即将删除逐字符坐标时固定模板身份特征,避免改变未压缩快照的 + # checksum;后续 matcher 只能读取此投影,不能退化为页面/表框高分猜测。 + if coordinate_evidence.get('page_glyphs') is not None or coordinate_evidence.get('tables') is not None: + from app.services.shipping_notice.document_layout.order_profile_matcher import ( + build_layout_matching_features, + ) + candidate['matching_features'] = build_layout_matching_features(layout=candidate) if coordinate_evidence.pop('page_glyphs', None) is not None: issues.append('shipping_document_layout_page_glyphs_compacted') if coordinate_evidence.pop('tables', None) is not None: @@ -200,14 +282,17 @@ def _fit_layout_payload_to_budget( def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] | None: """读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。""" - version = document.current_layout_version + version = ( + db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id)) + if document.current_layout_version_id else document.current_layout_version + ) if ( version is None or str(version.status or '') not in CURRENT_LAYOUT_STATUSES or not isinstance(version.payload_json, dict) ): return None - return dict(version.payload_json) + return _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document) def _bind_inline_xfa_structure_analysis( @@ -315,6 +400,16 @@ def record_inline_layout_snapshot( 超大 payload 不落正文,只创建 failed 审计版本;相同内容/parser/checksum 重试复用旧终态。 """ payload = dict(snapshot) + evidence = payload.get('coordinate_evidence') + if _has_coordinate_evidence(evidence): + evidence_ref = _persist_coordinate_evidence_asset(document=document, evidence=evidence) + if evidence_ref is None and str(payload.get('status') or '') == 'ready': + payload = {**payload, 'status': 'failed', 'issues': [ + *list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed', + ]} + elif evidence_ref is not None: + payload.pop('coordinate_evidence', None) + payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref parser_key = str(parser_key or current_layout_parser_key()) max_bytes = max(int(current_app.config.get( 'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000, @@ -936,19 +1031,30 @@ def complete_layout_version( if version is None or version.status != 'running' or version.lease_token != lease_token: db.session.rollback() return False + payload = dict(snapshot) + evidence = payload.get('coordinate_evidence') + if _has_coordinate_evidence(evidence): + evidence_ref = _persist_coordinate_evidence_asset(document=version.document, evidence=evidence) + if evidence_ref is None and str(payload.get('status') or '') == 'ready': + payload = {**payload, 'status': 'failed', 'issues': [ + *list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed', + ]} + elif evidence_ref is not None: + payload.pop('coordinate_evidence', None) + payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref max_bytes = max(int(current_app.config.get( 'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000, )), 1) fitted_snapshot, compact_issues, payload_size = _fit_layout_payload_to_budget( - snapshot, max_bytes=max_bytes, + payload, max_bytes=max_bytes, ) - stored_for_identity = fitted_snapshot if fitted_snapshot is not None else snapshot + stored_for_identity = fitted_snapshot if fitted_snapshot is not None else payload checksum, _ = canonical_layout_payload(stored_for_identity) - issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues)) - provider_status = str(snapshot.get('status') or 'failed') + issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues)) + provider_status = str(payload.get('status') or 'failed') status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed' if status == 'ready' and not _ready_layout_evidence_complete( - document=version.document, payload=snapshot, + document=version.document, payload=payload, ): status = 'failed' issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_incomplete'}) @@ -960,12 +1066,12 @@ def complete_layout_version( status = 'failed' now = datetime.utcnow() version.status = status - version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None - version.backend = str(snapshot.get('backend') or LAYOUT_BACKEND)[:32] + version.parser_version = str(payload.get('provider_version') or '')[:64] or None + version.backend = str(payload.get('backend') or LAYOUT_BACKEND)[:32] version.payload_json = stored_payload version.payload_checksum = checksum version.payload_size_bytes = payload_size - version.quality_json = dict(snapshot['capability']) if isinstance(snapshot.get('capability'), dict) else None + version.quality_json = dict(payload['capability']) if isinstance(payload.get('capability'), dict) else None version.issues_json = sorted(set(issues)) version.lease_token = None version.finished_at = now diff --git a/backend/app/services/shipping_notice/document_layout/native_pdf.py b/backend/app/services/shipping_notice/document_layout/native_pdf.py index da7b1f96..9d6ff9db 100644 --- a/backend/app/services/shipping_notice/document_layout/native_pdf.py +++ b/backend/app/services/shipping_notice/document_layout/native_pdf.py @@ -93,56 +93,62 @@ def extract_native_pdf_pages( """ if not content or render_scale <= 0: raise ValueError('native PDF content and positive render scale are required') - pdf = pdfium.PdfDocument(content) pages: list[NativePdfPage] = [] - for page_index in range(len(pdf)): - page = pdf[page_index] - width, height = page.get_size() - text_page = page.get_textpage() - characters: list[PositionedCharacter] = [] - pending_boundary: str = 'none' - for char_index in range(text_page.count_chars()): - text = text_page.get_text_range(char_index, 1) - if not text: - continue - if not normalize_layout_text(text): - if any(character in {'\r', '\n'} for character in text): - pending_boundary = 'line_break' - elif pending_boundary == 'none' and any(character.isspace() for character in text): - pending_boundary = 'space' - continue - left, bottom, right, top = text_page.get_charbox(char_index, loose=True) - if right <= left or top <= bottom: - # 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。 - pending_boundary = 'none' - continue + pdf = pdfium.PdfDocument(content) + try: + for page_index in range(len(pdf)): + page = pdf[page_index] + text_page = None try: - # 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。 - characters.append(PositionedCharacter( - text=text, - bbox=LayoutBBox( - x0=left, y0=height - top, x1=right, y1=height - bottom, - ), - source_index=char_index, - boundary_before=pending_boundary, + width, height = page.get_size() + text_page = page.get_textpage() + characters: list[PositionedCharacter] = [] + pending_boundary: str = 'none' + for char_index in range(text_page.count_chars()): + text = text_page.get_text_range(char_index, 1) + if not text: + continue + if not normalize_layout_text(text): + if any(character in {'\r', '\n'} for character in text): + pending_boundary = 'line_break' + elif pending_boundary == 'none' and any(character.isspace() for character in text): + pending_boundary = 'space' + continue + left, bottom, right, top = text_page.get_charbox(char_index, loose=True) + if right <= left or top <= bottom: + # 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。 + pending_boundary = 'none' + continue + try: + # 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。 + characters.append(PositionedCharacter( + text=text, + bbox=LayoutBBox( + x0=left, y0=height - top, x1=right, y1=height - bottom, + ), + source_index=char_index, + boundary_before=pending_boundary, + )) + pending_boundary = 'none' + except ValueError: + pending_boundary = 'none' + continue + characters = _assign_page_line_ids(characters, page_no=page_index + 1) + rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360 + pages.append(NativePdfPage( + page_no=page_index + 1, + width=float(width), + height=float(height), + rotation=rotation if rotation in {0, 90, 180, 270} else 0, + characters=characters, + image=_render_native_pdf_page(page, render_scale) if render_images else None, )) - pending_boundary = 'none' - except ValueError: - pending_boundary = 'none' - continue - characters = _assign_page_line_ids(characters, page_no=page_index + 1) - rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360 - pages.append(NativePdfPage( - page_no=page_index + 1, - width=float(width), - height=float(height), - rotation=rotation if rotation in {0, 90, 180, 270} else 0, - characters=characters, - image=( - np.asarray(page.render(scale=render_scale).to_numpy()).copy() - if render_images else None - ), - )) + finally: + if text_page is not None: + text_page.close() + page.close() + finally: + pdf.close() return pages @@ -191,27 +197,43 @@ def attach_native_pdf_page_images( return [] if all(page.image is not None for page in pages): return list(pages) - pdf = pdfium.PdfDocument(content) attached: list[NativePdfPage] = [] - for page in pages: - if page.image is not None: - attached.append(page) - continue - index = int(page.page_no) - 1 - if index < 0 or index >= len(pdf): - raise ValueError('native PDF page_no is out of range for image attach') - image = np.asarray(pdf[index].render(scale=render_scale).to_numpy()).copy() - attached.append(NativePdfPage( - page_no=page.page_no, - width=page.width, - height=page.height, - rotation=page.rotation, - characters=page.characters, - image=image, - )) + pdf = pdfium.PdfDocument(content) + try: + for native_page in pages: + if native_page.image is not None: + attached.append(native_page) + continue + index = int(native_page.page_no) - 1 + if index < 0 or index >= len(pdf): + raise ValueError('native PDF page_no is out of range for image attach') + page = pdf[index] + try: + image = _render_native_pdf_page(page, render_scale) + finally: + page.close() + attached.append(NativePdfPage( + page_no=native_page.page_no, + width=native_page.width, + height=native_page.height, + rotation=native_page.rotation, + characters=native_page.characters, + image=image, + )) + finally: + pdf.close() return attached +def _render_native_pdf_page(page: Any, render_scale: float) -> np.ndarray: + """将 PDFium 页面复制为独立 ndarray 后立即释放临时 bitmap,避免其 finalizer 滞留到进程退出。""" + bitmap = page.render(scale=render_scale) + try: + return np.asarray(bitmap.to_numpy()).copy() + finally: + bitmap.close() + + def build_native_pdf_text_table_fallbacks( content: bytes, *, @@ -232,17 +254,24 @@ def build_native_pdf_text_table_fallbacks( continue start_index, end_index = header header_lines = lines[start_index:end_index + 1] - body_lines = lines[end_index + 1:] - stop_index = next(( - index for index, line in enumerate(body_lines) - if _is_fallback_total(line) or _is_fallback_separator(line) - ), len(body_lines)) - body_lines = body_lines[:stop_index] - if not body_lines: - continue boundaries = _fallback_column_boundaries(header_lines, page.width) if len(boundaries) < 3: continue + body_lines: list[dict[str, Any]] = [] + has_data_row = False + for line in lines[end_index + 1:]: + if _is_fallback_total(line): + break + if _is_fallback_separator(line): + # 采购订单常在表头和首条明细之间画横线;只有已见明细后的横线才是表尾。 + if has_data_row: + break + continue + body_lines.append(line) + if _fallback_data_row(_fallback_cells([line], boundaries)): + has_data_row = True + if not body_lines: + continue header_cells = _fallback_cells(header_lines, boundaries) body_cells = [_fallback_cells([line], boundaries) for line in body_lines] if not any(_fallback_data_row(row) for row in body_cells): 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 c0f993b4..a285b0f7 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 @@ -29,13 +29,32 @@ def ensure_on_demand_coordinate_evidence( for key in legacy_keys if isinstance(layout.get(key), dict) } - # Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。 + # Run 快照可能早于最近一次布局重试;当前 Layout 是最新解析事实,同页坐标必须 + # 优先于 Run 快照,后者只能补齐当前 Layout 尚未保存的页或表。 current_version = getattr(document, 'current_layout_version', None) current_payload = getattr(current_version, 'payload_json', None) if isinstance(current_payload, dict): current_evidence = current_payload.get('coordinate_evidence') if isinstance(current_evidence, dict): - evidence = {**current_evidence, **evidence} + merged_current = dict(evidence) + for key in ('pages', 'page_glyphs', 'tables'): + snapshot_mapping = _coordinate_mapping(evidence.get(key)) + current_mapping = _coordinate_mapping(current_evidence.get(key)) + # 仅合并实际存在的坐标类别。空 tables 不得写入轻量快照,否则会让 + # 顶层业务 tables 列表与坐标表映射的边界在后续调用中变得模糊。 + if snapshot_mapping or current_mapping: + merged_current[key] = {**snapshot_mapping, **current_mapping} + snapshot_sources = _coordinate_mapping(evidence.get('sources')) + current_sources = _coordinate_mapping(current_evidence.get('sources')) + merged_current['sources'] = { + **snapshot_sources, + **current_sources, + 'pages': { + **_coordinate_mapping(snapshot_sources.get('pages')), + **_coordinate_mapping(current_sources.get('pages')), + }, + } + evidence = merged_current for key in ('pages', 'page_glyphs', 'sources', 'tables'): if key not in evidence and isinstance(current_payload.get(key), dict): evidence[key] = current_payload[key] @@ -44,8 +63,24 @@ 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')) - if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}): - return layout + available_page_nos = { + int(page_no) for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs + } + if page_nos is not None and page_nos.issubset(available_page_nos): + # 当前 Layout 可能补齐了 Run 冻结快照中已被压缩的坐标证据。必须返回 + # 合并后的运行期 Layout;返回原 layout 会让调用方重新丢失这些字符坐标, + # 从而使同版式 PDF 因快照压缩路径不同进入不同的匹配分支。 + next_layout = dict(layout) + merged_evidence = {**evidence, 'pages': pages} + if page_glyphs: + merged_evidence['page_glyphs'] = page_glyphs + if tables: + merged_evidence['tables'] = tables + if sources or source_pages: + merged_evidence['sources'] = {**sources, 'pages': source_pages} + next_layout['coordinate_evidence'] = merged_evidence + return next_layout tables_by_page: dict[int, list[dict[str, Any]]] = {} for raw_table in layout.get('tables') or []: if not isinstance(raw_table, dict): @@ -108,8 +143,12 @@ def ensure_on_demand_coordinate_evidence( if table_id and chars: tables[table_id] = chars next_layout = dict(layout) - next_layout['coordinate_evidence'] = { - **evidence, 'pages': pages, 'page_glyphs': page_glyphs, - 'tables': tables, 'sources': {**sources, 'pages': source_pages}, - } + merged_evidence = {**evidence, 'pages': pages} + if page_glyphs: + merged_evidence['page_glyphs'] = page_glyphs + if tables: + merged_evidence['tables'] = tables + if sources or source_pages: + merged_evidence['sources'] = {**sources, 'pages': source_pages} + next_layout['coordinate_evidence'] = merged_evidence return next_layout diff --git a/backend/app/services/shipping_notice/document_layout/order_field_extraction.py b/backend/app/services/shipping_notice/document_layout/order_field_extraction.py index 4d08953d..b2b4d351 100644 --- a/backend/app/services/shipping_notice/document_layout/order_field_extraction.py +++ b/backend/app/services/shipping_notice/document_layout/order_field_extraction.py @@ -14,12 +14,16 @@ from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.coordinate_transform import ( + project_coordinate_profile_payload, +) from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row from app.services.shipping_notice.document_layout.order_profile import ( AnchorRelativeRegion, AnchorRule, OrderCoordinateProfile, OrderFieldLayout, + ReferencePageFrame, RelativeRegion, ) from app.services.shipping_notice.order_schema.field_rules import ( @@ -49,6 +53,8 @@ class OrderFieldExtraction(BaseModel): def extract_order_fields( *, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False, + coordinate_transform: dict[str, Any] | None = None, + allow_fixed_region_confirmation: bool = False, ) -> list[OrderFieldExtraction]: """ 用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。 @@ -59,24 +65,53 @@ def extract_order_fields( coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。 allow_ocr_preview_fallback: 仅管理端视觉样本值预览可启用。它允许已确认的 PDF 坐标字段临时读取 OCR 候选,但结果仍固定为 needs_review,不能用于正式运行时取值。 + allow_fixed_region_confirmation: 仅唯一匹配模板的正式运行或当前模板盲测回放可启用。 + 它只允许原生 PDF 坐标的无标签固定区域成为 confirmed;OCR、未匹配模板和 + 普通预览仍保持 needs_review。 Returns: 每个已绑定布局对应一个候选,按模板声明顺序返回。 """ + effective_profile = _project_coordinate_transform(profile, coordinate_transform) + if effective_profile is None: + return [ + _unavailable(layout, 'order_field_coordinate_transform_invalid') + for layout in profile.order_field_layouts + ] return [ _extract_layout( layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence, + reference_page_frames=effective_profile.reference_page_frames, allow_ocr_preview_fallback=allow_ocr_preview_fallback, + allow_fixed_region_confirmation=allow_fixed_region_confirmation, ) - for layout in profile.order_field_layouts + for layout in effective_profile.order_field_layouts ] +def _project_coordinate_transform( + profile: OrderCoordinateProfile, coordinate_transform: dict[str, Any] | None, +) -> OrderCoordinateProfile | None: + """把 matcher 唯一确认的统一变换投影到订单头布局,禁止二次估算。""" + if coordinate_transform is None: + return profile + payload = project_coordinate_profile_payload( + profile.model_dump(mode='python'), coordinate_transform=coordinate_transform, + ) + if payload is None: + return None + try: + return OrderCoordinateProfile.model_validate(payload) + except Exception: + return None + + def _extract_layout( *, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], - allow_ocr_preview_fallback: bool = False, + reference_page_frames: dict[int, ReferencePageFrame], + allow_ocr_preview_fallback: bool = False, allow_fixed_region_confirmation: bool = False, ) -> OrderFieldExtraction: """处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。""" config = schema_fields.get(layout.field_id) @@ -112,6 +147,7 @@ def _extract_layout( results: list[OrderFieldExtraction] = [] for page_no, glyphs, width, height, source in candidates: + reference_page_frame = reference_page_frames.get(page_no) if not _source_allowed( layout, config=config, @@ -123,18 +159,25 @@ def _extract_layout( if layout.anchor is None: results.append(_read_value_region( layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, - region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None, - fallback=True, + region=_absolute_relative_region( + layout.fallback_value_region, width=width, height=height, + reference_page_frame=reference_page_frame, + ), anchor_bbox=None, + fallback=not (allow_fixed_region_confirmation and source == 'pdf_coordinate'), )) continue matches = _find_anchor_matches( glyphs, layout.anchor, page_width=width, page_height=height, - ignore_reference_region=_uses_movable_anchor_value_region(layout=layout, width=width, height=height), + reference_page_frame=reference_page_frame, + ignore_reference_region=_uses_movable_anchor_value_region( + layout=layout, width=width, height=height, reference_page_frame=reference_page_frame, + ), ) if not matches: reference_anchor = ( _anchor_from_reference_region( glyphs, anchor=layout.anchor, page_width=width, page_height=height, + reference_page_frame=reference_page_frame, ) if _is_placeholder_anchor_text(layout.anchor.text) else None ) @@ -144,7 +187,10 @@ def _extract_layout( # intent, but it must remain review-only until the label is fixed. results.append(_read_value_region( layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, - region=_absolute_value_region(layout=layout, anchor=reference_anchor, width=width, height=height), + region=_absolute_value_region( + layout=layout, anchor=reference_anchor, width=width, height=height, + reference_page_frame=reference_page_frame, + ), anchor_bbox=reference_anchor, fallback=False, review_issue='order_field_anchor_text_mismatch', )) @@ -160,7 +206,10 @@ def _extract_layout( anchor_bbox, _indices = matches[0] results.append(_read_value_region( layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, - region=_absolute_value_region(layout=layout, anchor=anchor_bbox, width=width, height=height), anchor_bbox=anchor_bbox, fallback=False, + region=_absolute_value_region( + layout=layout, anchor=anchor_bbox, width=width, height=height, + reference_page_frame=reference_page_frame, + ), anchor_bbox=anchor_bbox, fallback=False, )) usable = [item for item in results if item.status != 'unavailable'] if len(usable) == 1: @@ -294,6 +343,7 @@ def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], reg def _find_anchor_matches( glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None, + reference_page_frame: ReferencePageFrame | None = None, ignore_reference_region: bool = False, ) -> list[tuple[LayoutBBox, list[int]]]: """在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。""" @@ -321,23 +371,22 @@ def _find_anchor_matches( compact, position=position, length=len(normalized), anchor=anchor, ): bbox = _union_bbox([item for _index, item in consumed]) - if ignore_reference_region or _anchor_bbox_in_reference_region( - bbox, anchor=anchor, page_width=page_width, page_height=page_height, - ): - matches.append((bbox, [index for index, _item in consumed])) + # 先按文本收集全部精确命中;保存的参考框只用于多个同名标签 + # 的消歧,不能让同版式样本中唯一但位置变化的标签直接丢失。 + matches.append((bbox, [index for index, _item in consumed])) start = position + max(len(label), 1) unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {} for bbox, indices in matches: unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices) resolved = list(unique.values()) - # An unlocked label may shift between documents, so its reference box must - # not suppress a sole match. When the same label occurs multiple times, - # however, the saved canvas position is decisive evidence for this sample. + # 唯一文本命中不受历史参考框限制;同名标签多次出现时,保存位置才是 + # 当前样本的消歧证据。若位置也无法唯一消歧,调用方会进入人工复核。 if len(resolved) > 1 and anchor.region is not None and page_width and page_height: positioned = [ item for item in resolved if _anchor_bbox_in_reference_region( - item[0], anchor=anchor, page_width=page_width, page_height=page_height, enforce=True, + item[0], anchor=anchor, page_width=page_width, page_height=page_height, + reference_page_frame=reference_page_frame, enforce=True, ) ] if len(positioned) == 1: @@ -370,6 +419,7 @@ def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) -> def _anchor_bbox_in_reference_region( bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None, + reference_page_frame: ReferencePageFrame | None = None, enforce: bool = False, ) -> bool: """锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。""" @@ -377,17 +427,22 @@ def _anchor_bbox_in_reference_region( return True if page_width is None or page_height is None or page_width <= 0 or page_height <= 0: return False - region = _absolute_relative_region(anchor.region, width=page_width, height=page_height) + region = _absolute_relative_region( + anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame, + ) return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region) def _anchor_from_reference_region( glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float, + reference_page_frame: ReferencePageFrame | None = None, ) -> LayoutBBox | None: """为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。""" if anchor.region is None: return None - region = _absolute_relative_region(anchor.region, width=page_width, height=page_height) + region = _absolute_relative_region( + anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame, + ) selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)] return _union_bbox(selected) if selected else None @@ -473,11 +528,19 @@ def _source_allowed( return not ('coordinate' in required_levels and source != 'pdf_coordinate') -def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox: - """将固定低可靠度归一化页区投影为当前页面绝对框。""" +def _absolute_relative_region( + region: RelativeRegion | None, *, width: float, height: float, + reference_page_frame: ReferencePageFrame | None = None, +) -> LayoutBBox: + """将区域投影为 PDF 点坐标;有标注页框时不得随当前长页高度缩放。""" if region is None: raise ValueError('fallback order field region is required') - return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height) + projection_width = reference_page_frame.width if reference_page_frame is not None else width + projection_height = reference_page_frame.height if reference_page_frame is not None else height + return LayoutBBox( + x0=region.x0 * projection_width, y0=region.y0 * projection_height, + x1=region.x1 * projection_width, y1=region.y1 * projection_height, + ) def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox: @@ -491,14 +554,17 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB ) -def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox: - """读取管理员值框;右侧/下方字段只随标签平移,绝不按标签框尺寸缩放。""" +def _absolute_value_region( + *, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float, + reference_page_frame: ReferencePageFrame | None = None, +) -> LayoutBBox: + """读取管理员值框;有保存参考锚点时整框随唯一命中标签平移,绝不缩放。""" if layout.value_region is not None: if layout.anchor is None or layout.anchor.region is None: return _absolute_anchor_region(layout.value_region, anchor) if layout.value_mode not in {'right_of_anchor', 'below_anchor'}: return _absolute_anchor_region(layout.value_region, anchor) - reference = _absolute_relative_region(layout.anchor.region, width=width, height=height) + reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame) saved = _absolute_anchor_region(layout.value_region, reference) if layout.value_mode == 'right_of_anchor': region = _absolute_anchor_region(layout.value_region, anchor) @@ -509,19 +575,33 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt x1=anchor.x1 + projected_width, y1=region.y1, ) elif layout.absolute_value_region is not None: - saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height) + saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame) if layout.anchor is None or layout.anchor.region is None: return saved - reference = _absolute_relative_region(layout.anchor.region, width=width, height=height) + reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame) else: raise ValueError('anchored order field has no value region') if layout.value_mode not in {'right_of_anchor', 'below_anchor'}: + # absolute_value_region 记录的是标注页上的完整取值框。标签在当前 + # 文档因可选单头内容整体移动时,single_line/multi_line 也必须保留 + # 框的形状,并以该字段自己的唯一锚点中心作同量平移。 + if layout.absolute_value_region is not None: + reference_center_x = (reference.x0 + reference.x1) / 2 + reference_center_y = (reference.y0 + reference.y1) / 2 + anchor_center_x = (anchor.x0 + anchor.x1) / 2 + anchor_center_y = (anchor.y0 + anchor.y1) / 2 + return LayoutBBox( + x0=saved.x0 + anchor_center_x - reference_center_x, + y0=saved.y0 + anchor_center_y - reference_center_y, + x1=saved.x1 + anchor_center_x - reference_center_x, + y1=saved.y1 + anchor_center_y - reference_center_y, + ) return saved anchor_center_x, anchor_center_y = (anchor.x0 + anchor.x1) / 2, (anchor.y0 + anchor.y1) / 2 if _regions_overlap(anchor, reference): return saved if layout.absolute_value_region is not None and not _uses_movable_anchor_value_region( - layout=layout, width=width, height=height, + layout=layout, width=width, height=height, reference_page_frame=reference_page_frame, ): return saved if layout.value_mode == 'right_of_anchor': @@ -536,7 +616,10 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt ) -def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, height: float) -> bool: +def _uses_movable_anchor_value_region( + *, layout: OrderFieldLayout, width: float, height: float, + reference_page_frame: ReferencePageFrame | None = None, +) -> bool: """判断新相对规则或同一行的旧右侧框是否应跟随实际标签移动。""" if layout.value_region is not None: return layout.value_mode in {'right_of_anchor', 'below_anchor'} @@ -545,8 +628,8 @@ def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, or layout.value_mode not in {'right_of_anchor', 'below_anchor'} ): return False - reference = _absolute_relative_region(layout.anchor.region, width=width, height=height) - saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height) + reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame) + saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame) tolerance = max(reference.y1 - reference.y0, saved.y1 - saved.y0) * 2 return saved.y0 <= reference.y1 + tolerance and reference.y0 <= saved.y1 + tolerance diff --git a/backend/app/services/shipping_notice/document_layout/order_profile.py b/backend/app/services/shipping_notice/document_layout/order_profile.py index 156a30cd..6b416d38 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -50,6 +50,15 @@ class RelativeRegion(OrderProfileModel): return self +class ReferencePageFrame(OrderProfileModel): + """冻结标注样本的 PDF CropBox 点尺寸,供跨页高变化时还原相对区域。""" + + width: float = Field(gt=0) + height: float = Field(gt=0) + origin: Literal['pdf_top_left'] = 'pdf_top_left' + box: Literal['cropbox'] = 'cropbox' + + class AnchorRelativeRegion(OrderProfileModel): """仅接收历史锚点相对值框;新模板统一保存 absolute_value_region。""" @@ -251,7 +260,7 @@ class TableRegionProfile(OrderProfileModel): page_no: int | None = Field(default=None, ge=1) region: RelativeRegion # 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。 - line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$') + line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$') # 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。 row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows' # 人工确认本表区自动标注时采用的视觉几何来源;仅用于审计、盲测和冲突复核, @@ -291,7 +300,7 @@ class TableRegionProfile(OrderProfileModel): if len(fields) != len(set(fields)): raise ValueError('field_code may bind to only one coordinate region per table') # 草稿可先框物理行;一旦主行开始绑字段,就必须包含起行锚点。 - if self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in { + if self.line_start_field_code and self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in { field.field_code for field in self.line_layouts[0].field_regions }: raise ValueError('main line layout must bind the configured line-start field') @@ -427,6 +436,58 @@ class DocumentMatchProfile(OrderProfileModel): return self +class AnchorFrameCoordinateModel(OrderProfileModel): + """声明以稳定静态文字建立运行时受限几何坐标框架的 Profile 能力。""" + + type: Literal['anchor_frame'] + anchors: list[AnchorRule] = Field(min_length=1, max_length=4) + max_translate_x: float = Field(default=.03, ge=0, le=.15) + max_translate_y: float = Field(default=.06, ge=0, le=.20) + transform_mode: Literal['translate', 'affine'] = 'translate' + max_scale_delta: float = Field(default=.03, ge=0, le=.10) + max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0) + max_residual: float = Field(default=.01, gt=0, le=.05) + + @model_validator(mode='after') + def validate_anchor_frame(self) -> 'AnchorFrameCoordinateModel': + """要求每个框架锚点都有基线区域且身份唯一,避免运行时从全文猜测基准。""" + if any(anchor.region is None for anchor in self.anchors): + raise ValueError('anchor frame anchors require baseline regions') + ids = [anchor.anchor_id for anchor in self.anchors] + if len(ids) != len(set(ids)): + raise ValueError('anchor frame anchor ids must be unique') + if self.transform_mode == 'affine' and len(self.anchors) < 3: + raise ValueError('affine coordinate model requires at least three frame anchors') + return self + + +class CoordinateModel(OrderProfileModel): + """定义坐标模板是否启用锚点框架;legacy 保持既有绝对坐标行为。""" + + type: Literal['legacy', 'anchor_frame'] = 'legacy' + anchors: list[AnchorRule] = Field(default_factory=list, max_length=4) + max_translate_x: float = Field(default=.03, ge=0, le=.15) + max_translate_y: float = Field(default=.06, ge=0, le=.20) + transform_mode: Literal['translate', 'affine'] = 'translate' + max_scale_delta: float = Field(default=.03, ge=0, le=.10) + max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0) + max_residual: float = Field(default=.01, gt=0, le=.05) + + @model_validator(mode='after') + def validate_coordinate_model(self) -> 'CoordinateModel': + """仅 anchor_frame 允许锚点配置;legacy 必须是空声明以保证路径隔离。""" + if self.type == 'legacy' and self.anchors: + raise ValueError('legacy coordinate model must not define frame anchors') + if self.type == 'anchor_frame': + AnchorFrameCoordinateModel( + type='anchor_frame', anchors=self.anchors, + max_translate_x=self.max_translate_x, max_translate_y=self.max_translate_y, + transform_mode=self.transform_mode, max_scale_delta=self.max_scale_delta, + max_rotation_degrees=self.max_rotation_degrees, max_residual=self.max_residual, + ) + return self + + class OrderCoordinateProfile(OrderProfileModel): """唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。""" profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$') @@ -435,6 +496,8 @@ class OrderCoordinateProfile(OrderProfileModel): table_regions: list[TableRegionProfile] = Field(min_length=1) order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list) draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list) + coordinate_model: CoordinateModel = Field(default_factory=CoordinateModel) + reference_page_frames: dict[int, ReferencePageFrame] = Field(default_factory=dict) @model_validator(mode='after') def validate_profile_rules(self) -> 'OrderCoordinateProfile': 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 ffb840f5..11d12dc3 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 @@ -9,6 +9,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py from __future__ import annotations +from copy import deepcopy +import math import re from typing import Any, Literal @@ -17,8 +19,13 @@ from pydantic import BaseModel, ConfigDict, Field from app.services.shipping_notice.document_layout.coordinate_region_text import ( positioned_token_spans, read_coordinate_region_text, + visual_glyph_rows, +) +from app.services.shipping_notice.document_layout.coordinate_transform import ( + apply_coordinate_transform_to_region, ) from app.services.shipping_notice.document_layout.order_profile import ( + AnchorRule, CRITICAL_STRUCTURE_DIMENSION_KEYS, MatchDimensionResult, MatchDimensionState, @@ -31,6 +38,11 @@ from app.services.shipping_notice.document_layout.order_profile_signature import ) +# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义, +# 避免无意义的版本兼容分支。 +LAYOUT_MATCHING_FEATURES_VERSION = 'v1' + + def _anchor_comparable_text(value: Any) -> str: """规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。""" return ''.join(str(value or '').casefold().split()) @@ -66,6 +78,7 @@ class ProfileMatchCandidate(BaseModel): dimension_scores: ProfileMatchDimensionScores | None = None dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict) margin_to_next: float | None = Field(default=None, ge=0, le=1) + coordinate_transform: dict[str, Any] | None = None class ProfileMatchResult(BaseModel): @@ -136,15 +149,24 @@ def match_frozen_coordinate_profiles( document_match=definition.get('document_match'), table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, ) except (TypeError, ValueError): continue reason_codes: list[str] = [] signature_body, signature_meta = _extract_matching_signature(raw) + coordinate_transform, transform_reasons = _resolve_coordinate_transform( + profile=profile, pages=pages, page_glyphs=page_glyphs, + ) + reason_codes.extend(transform_reasons) + observed_signature = _translate_signature( + signature=signature_body, coordinate_transform=coordinate_transform, + ) observed = _observe_layout_features( layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables, - page_glyphs=page_glyphs, signature=signature_body, + page_glyphs=page_glyphs, signature=observed_signature, ) if signature_body is None: reason_codes.append('profile_signature_missing') @@ -190,7 +212,7 @@ def match_frozen_coordinate_profiles( dimension_results, hard_conflict_codes = _compute_dimension_results( profile=profile, - signature=signature_body, + signature=observed_signature, observed=observed, tables=tables, pages=pages, @@ -200,6 +222,11 @@ def match_frozen_coordinate_profiles( customer_hint_id=customer_hint_id, ) reason_codes.extend(hard_conflict_codes) + if _profile_requires_unavailable_structure_evidence( + signature=observed_signature, + dimension_results=dimension_results, + ): + reason_codes.append('profile_coordinate_evidence_unavailable') weights = profile.document_match.scoring_weights score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results) @@ -223,6 +250,7 @@ def match_frozen_coordinate_profiles( matched_anchor_count=sum(required_hits) + sum(optional_hits), dimension_scores=dimension_scores, dimension_states=dimension_states, + coordinate_transform=coordinate_transform, ))) rendered = sorted( @@ -251,6 +279,11 @@ def match_frozen_coordinate_profiles( candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6) if not hard_valid: + if any('profile_coordinate_evidence_unavailable' in item.reason_codes for item in rendered): + return ProfileMatchResult( + status='evidence_insufficient', candidates=rendered, + top1_score=top1_score, top2_score=top2_score, margin=margin, + ) if not rendered: return ProfileMatchResult( status='no_match', candidates=rendered, @@ -305,6 +338,134 @@ def match_frozen_coordinate_profiles( ) +def build_layout_matching_features(*, layout: dict[str, Any]) -> dict[str, Any]: + """从完整坐标证据派生可持久化的候选表头特征,不保留逐字符正文。 + + 特征生成不依赖任何 Profile;保存所有候选视觉行,运行时再由冻结签名选择, + 避免“无 Profile 时猜一条表头”导致压缩后永久保存错误列拓扑。 + """ + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + 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 {} + tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] + first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None) + aspect_ratio = 0.0 + if isinstance(first_page, dict): + try: + width, height = float(first_page.get('width') or 0), float(first_page.get('height') or 0) + aspect_ratio = round(width / height, 6) if width > 0 and height > 0 else 0.0 + except (TypeError, ValueError): + pass + rendered_tables: list[dict[str, Any]] = [] + for table in tables: + bbox = _normalized_table_bbox(table=table, pages=pages) + if bbox is None: + continue + candidates = _observe_header_candidates( + glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, + primary_bbox=bbox, + ) + rendered_tables.append({ + 'bbox': bbox, + 'header_candidates': candidates, + }) + result = { + 'version': LAYOUT_MATCHING_FEATURES_VERSION, + 'page_structure': { + 'aspect_ratio': aspect_ratio, + 'page_count': len(pages), + 'table_count': len(tables), + }, + 'tables': rendered_tables, + 'static_text_centers': _observe_static_text_centers( + glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, + ), + } + if not result['static_text_centers']: + result.pop('static_text_centers') + return result + + +def _observe_header_candidates( + *, glyph_tables: dict[str, Any], page_glyphs: dict[str, Any], + pages: dict[str, Any], primary_bbox: list[float], +) -> list[dict[str, Any]]: + """提取主表顶部视觉行候选;不把数据行固化成唯一表头。""" + if not primary_bbox or len(primary_bbox) != 4: + return [] + page = pages.get('1') or pages.get(1) + glyphs = page_glyphs.get('1') or page_glyphs.get(1) + if not isinstance(glyphs, list): + glyphs = [g for values in glyph_tables.values() if isinstance(values, list) for g in values] + if not isinstance(page, dict) or not glyphs: + return [] + width, height = float(page.get('width') or 0), float(page.get('height') or 0) + if width <= 0 or height <= 0: + return [] + table_height = max(0.001, primary_bbox[3] - primary_bbox[1]) + rows = visual_glyph_rows(glyphs) + candidates: list[dict[str, Any]] = [] + for row in rows: + centers_y = [ + ((float(g['bbox']['y0']) + float(g['bbox']['y1'])) / 2) / height + for g in row if isinstance(g.get('bbox'), dict) + ] + if not centers_y: + continue + y = sum(centers_y) / len(centers_y) + if y < primary_bbox[1] or y > primary_bbox[1] + table_height * 0.30: + continue + spans = [ + item for item in positioned_token_spans(row, respect_explicit_spaces=False) + if _usable_observed_header_token(str(item.get('text') or '')) + ][:32] + if not spans: + continue + tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans] + centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans] + table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001) + widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans] + bbox = [ + round(min(float(g['bbox']['x0']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6), + round(min(float(g['bbox']['y0']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6), + round(max(float(g['bbox']['x1']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6), + round(max(float(g['bbox']['y1']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6), + ] + candidates.append({'bbox': bbox, 'header_tokens': tokens, 'column_centers': centers, 'column_width_ratios': widths}) + candidates.sort(key=lambda item: (item['bbox'][1], -len(item['header_tokens']))) + return candidates[:8] + + +def _normalized_table_bbox(*, table: dict[str, Any], pages: dict[str, Any]) -> list[float] | None: + """将 Layout 表框转为页内归一化坐标;缺页尺寸时仅接受已经归一化的表框。""" + bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None + if bbox is None: + return None + try: + values = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')] + except (KeyError, TypeError, ValueError): + return None + if values[2] <= values[0] or values[3] <= values[1]: + return None + if max(values) <= 1: + return [round(value, 6) for value in values] + page_no = table.get('page_no') or 1 + page = pages.get(str(page_no)) or pages.get(page_no) + if not isinstance(page, dict): + return None + try: + width, height = float(page.get('width') or 0), float(page.get('height') or 0) + except (TypeError, ValueError): + return None + if width <= 0 or height <= 0: + return None + return [ + round(values[0] / width, 6), round(values[1] / height, 6), + round(values[2] / width, 6), round(values[3] / height, 6), + ] + + def _selected_result( *, raw: dict[str, Any], @@ -343,6 +504,340 @@ def _extract_matching_signature(raw: dict[str, Any]) -> tuple[dict[str, Any] | N return signature, matching if isinstance(matching, dict) else {} +def _resolve_coordinate_transform( + *, profile: OrderCoordinateProfile, pages: dict[str, Any], page_glyphs: dict[str, Any], +) -> tuple[dict[str, Any] | None, list[str]]: + """根据冻结的模板身份锚点求受限平移,任何不确定性都返回硬失败原因。 + + Args: + profile: 当前冻结坐标 Profile;旧 ``anchor_frame`` 优先,其他模板复用已框选的 + 必选文档匹配标签,不要求管理员选择坐标模型。 + pages: 当前 Layout 的页尺寸证据。 + page_glyphs: 当前 Layout 的页级 PDF/OCR 字符坐标。 + + Returns: + ``(transform, reason_codes)``。没有可证明的静态标签时返回 ``(None, [])``; + 有标签时仅在全部唯一且变换位于受限范围内返回 ``status=applied``。 + """ + model = profile.coordinate_model + anchors = list(model.anchors) + max_translate_x = model.max_translate_x + max_translate_y = model.max_translate_y + if model.type != 'anchor_frame': + anchors = [ + AnchorRule( + anchor_id=anchor.anchor_id, + text=anchor.label, + match_mode='exact', + region=anchor.label_region, + position_locked=True, + minimum_evidence_level=anchor.minimum_evidence_level, + ) + for anchor in profile.document_match.required_anchors + if anchor.label_region is not None + ] + # 没有已框选的稳定标签时保持绝对坐标兼容;不从全文猜测校正基准。 + if not anchors: + return None, [] + if not anchors: + return None, [] + + deltas: list[tuple[float, float]] = [] + anchor_points: list[tuple[float, float, float, float]] = [] + anchor_ids: list[str] = [] + for anchor in anchors: + found = _find_anchor_rule_matches( + anchor=anchor, pages=pages, page_glyphs=page_glyphs, + max_translate_x=min(.30, max_translate_x * 2), + max_translate_y=min(.30, max_translate_y * 2), + ) + if not found: + return None, ['profile_anchor_frame_anchor_missing'] + if len(found) != 1: + return None, ['profile_anchor_frame_anchor_ambiguous'] + page_no, bbox = found[0] + page = pages.get(str(page_no)) or pages.get(page_no) + if not isinstance(page, dict) or anchor.region is None: + return None, ['profile_anchor_frame_coordinate_evidence_unavailable'] + try: + width, height = float(page['width']), float(page['height']) + except (KeyError, TypeError, ValueError): + return None, ['profile_anchor_frame_coordinate_evidence_unavailable'] + if width <= 0 or height <= 0: + return None, ['profile_anchor_frame_coordinate_evidence_unavailable'] + observed_x = (bbox[0] + bbox[2]) / 2 / width + observed_y = (bbox[1] + bbox[3]) / 2 / height + expected_x = (anchor.region.x0 + anchor.region.x1) / 2 + expected_y = (anchor.region.y0 + anchor.region.y1) / 2 + deltas.append((observed_x - expected_x, observed_y - expected_y)) + anchor_points.append((expected_x, expected_y, observed_x, observed_y)) + anchor_ids.append(anchor.anchor_id) + + if model.type == 'anchor_frame' and model.transform_mode == 'affine': + transform, reason = _resolve_affine_coordinate_transform( + anchor_points=anchor_points, anchor_ids=anchor_ids, model=model, + ) + return transform, [] if transform is not None else [reason] + + first_x, first_y = deltas[0] + if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]): + return None, ['profile_anchor_frame_anchor_inconsistent'] + if abs(first_x) > max_translate_x or abs(first_y) > max_translate_y: + return None, ['profile_anchor_frame_transform_out_of_range'] + return { + 'status': 'applied', + 'translate_x': round(first_x, 6), + 'translate_y': round(first_y, 6), + 'anchor_ids': anchor_ids, + 'reason_codes': [], + }, [] + + +def _resolve_affine_coordinate_transform( + *, anchor_points: list[tuple[float, float, float, float]], anchor_ids: list[str], model: Any, +) -> tuple[dict[str, Any] | None, str]: + """以 Profile 显式声明的三个以上稳定锚点求受限仿射,无法证明即失败关闭。""" + if len(anchor_points) < 3: + return None, 'profile_anchor_frame_affine_anchor_insufficient' + matrix_x = _least_squares_affine_axis(anchor_points, observed_index=2) + matrix_y = _least_squares_affine_axis(anchor_points, observed_index=3) + if matrix_x is None or matrix_y is None: + return None, 'profile_anchor_frame_affine_anchor_degenerate' + a, b, tx = matrix_x + d, e, ty = matrix_y + determinant = a * e - b * d + scale_x, scale_y = math.hypot(a, d), math.hypot(b, e) + rotation_degrees = abs(math.degrees(math.atan2(d, a))) + residual = max( + math.hypot(a * x + b * y + tx - observed_x, d * x + e * y + ty - observed_y) + for x, y, observed_x, observed_y in anchor_points + ) + if not all(math.isfinite(value) for value in (determinant, scale_x, scale_y, rotation_degrees, residual)): + return None, 'profile_anchor_frame_affine_invalid' + if determinant <= 0: + return None, 'profile_anchor_frame_affine_invalid' + if max(abs(scale_x - 1), abs(scale_y - 1)) > model.max_scale_delta: + return None, 'profile_anchor_frame_affine_scale_out_of_range' + if rotation_degrees > model.max_rotation_degrees: + return None, 'profile_anchor_frame_affine_rotation_out_of_range' + if residual > model.max_residual: + return None, 'profile_anchor_frame_affine_residual_out_of_range' + if abs(tx) > model.max_translate_x or abs(ty) > model.max_translate_y: + return None, 'profile_anchor_frame_transform_out_of_range' + return { + 'status': 'applied', + 'matrix': [round(value, 6) for value in (a, b, tx, d, e, ty)], + 'translate_x': round(tx, 6), + 'translate_y': round(ty, 6), + 'anchor_ids': anchor_ids, + 'residual': round(residual, 6), + 'reason_codes': [], + }, '' + + +def _least_squares_affine_axis( + points: list[tuple[float, float, float, float]], *, observed_index: int, +) -> tuple[float, float, float] | None: + """用正规方程拟合单个仿射轴;共线锚点会因奇异矩阵而被拒绝。""" + count = float(len(points)) + sum_x = sum(item[0] for item in points) + sum_y = sum(item[1] for item in points) + sum_xx = sum(item[0] * item[0] for item in points) + sum_xy = sum(item[0] * item[1] for item in points) + sum_yy = sum(item[1] * item[1] for item in points) + sum_z = sum(item[observed_index] for item in points) + sum_xz = sum(item[0] * item[observed_index] for item in points) + sum_yz = sum(item[1] * item[observed_index] for item in points) + determinant = ( + sum_xx * (sum_yy * count - sum_y * sum_y) + - sum_xy * (sum_xy * count - sum_y * sum_x) + + sum_x * (sum_xy * sum_y - sum_yy * sum_x) + ) + if not math.isfinite(determinant) or abs(determinant) < 1e-9: + return None + matrix = ((sum_xx, sum_xy, sum_x), (sum_xy, sum_yy, sum_y), (sum_x, sum_y, count)) + target = (sum_xz, sum_yz, sum_z) + values = [] + for column in range(3): + replaced = tuple( + tuple(target[row] if index == column else matrix[row][index] for index in range(3)) + for row in range(3) + ) + value = _determinant_3x3(replaced) / determinant + if not math.isfinite(value): + return None + values.append(value) + return values[0], values[1], values[2] + + +def _determinant_3x3(matrix: tuple[tuple[float, float, float], ...]) -> float: + """返回 3x3 矩阵行列式,供无额外数值依赖的仿射拟合使用。""" + return ( + matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1]) + - matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]) + + matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]) + ) + + +def _find_anchor_rule_matches( + *, anchor: AnchorRule, pages: dict[str, Any], page_glyphs: dict[str, Any], + max_translate_x: float, max_translate_y: float, +) -> list[tuple[int, list[float]]]: + """在基线区加声明平移窗口内寻找唯一锚点,绝不退化为全文弱匹配。""" + if anchor.region is None: + return [] + expected = [_anchor_comparable_text(value) for value in [anchor.text, *anchor.aliases]] + rendered: list[tuple[int, list[float]]] = [] + for raw_page_no, page in pages.items(): + try: + page_no, width, height = int(raw_page_no), float(page['width']), float(page['height']) + except (KeyError, TypeError, ValueError): + continue + glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no) + if width <= 0 or height <= 0 or not isinstance(glyphs, list): + continue + for line in _group_glyph_lines(glyphs): + ordered = sorted(line, key=lambda item: float((item.get('bbox') or {}).get('x0') or 0)) + comparable_parts: list[str] = [] + glyph_spans: list[tuple[int, int, dict[str, Any]]] = [] + for item in ordered: + part = _anchor_comparable_text(item.get('text') or '') + if not part: + continue + start = len(''.join(comparable_parts)) + comparable_parts.append(part) + glyph_spans.append((start, start + len(part), item)) + text = ''.join(comparable_parts) + if not text: + continue + matched_box_sets: list[list[dict[str, Any]]] = [] + for value in expected: + if not value: + continue + starts: list[int] = [] + offset = text.find(value) + while offset >= 0: + starts.append(offset) + offset = text.find(value, offset + 1) + if anchor.match_mode == 'exact' and not _anchor_rule_text_matches(value, text, mode='contains'): + starts = [] + for start in starts: + end = start + len(value) + matched_box_sets.append([ + item for span_start, span_end, item in glyph_spans + if span_start < end and span_end > start + ]) + if matched_box_sets: + break + if len(matched_box_sets) != 1 or not matched_box_sets[0]: + if len(matched_box_sets) > 1: + rendered.extend((page_no, [ + min(float(item['bbox']['x0']) for item in boxes if isinstance(item.get('bbox'), dict)), + min(float(item['bbox']['y0']) for item in boxes if isinstance(item.get('bbox'), dict)), + max(float(item['bbox']['x1']) for item in boxes if isinstance(item.get('bbox'), dict)), + max(float(item['bbox']['y1']) for item in boxes if isinstance(item.get('bbox'), dict)), + ]) for boxes in matched_box_sets if boxes) + continue + matched_boxes = matched_box_sets[0] + if not matched_boxes: + continue + boxes = [item.get('bbox') for item in matched_boxes if isinstance(item.get('bbox'), dict)] + if not boxes: + continue + bbox = [ + min(float(item['x0']) for item in boxes), min(float(item['y0']) for item in boxes), + max(float(item['x1']) for item in boxes), max(float(item['y1']) for item in boxes), + ] + center_x, center_y = (bbox[0] + bbox[2]) / 2 / width, (bbox[1] + bbox[3]) / 2 / height + if ( + max(0, anchor.region.x0 - max_translate_x) <= center_x <= min(1, anchor.region.x1 + max_translate_x) + and max(0, anchor.region.y0 - max_translate_y) <= center_y <= min(1, anchor.region.y1 + max_translate_y) + ): + rendered.append((page_no, bbox)) + return rendered + + +def _group_glyph_lines(glyphs: list[dict[str, Any]]) -> list[list[dict[str, Any]]]: + """按字符中心 Y 聚合视觉行,供框架锚点精确匹配,不改变既有字段提取逻辑。""" + lines: list[list[dict[str, Any]]] = [] + for glyph in sorted((item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)), key=lambda item: (float(item['bbox'].get('y0') or 0), float(item['bbox'].get('x0') or 0))): + bbox = glyph['bbox'] + try: + center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2 + glyph_height = max(.01, float(bbox['y1']) - float(bbox['y0'])) + except (KeyError, TypeError, ValueError): + continue + if lines: + previous = lines[-1][0]['bbox'] + previous_y = (float(previous['y0']) + float(previous['y1'])) / 2 + previous_height = max(.01, float(previous['y1']) - float(previous['y0'])) + if abs(center_y - previous_y) <= max(glyph_height, previous_height) * .65: + lines[-1].append(glyph) + continue + lines.append([glyph]) + return lines + + +def _anchor_rule_text_matches(expected: str, observed: str, *, mode: str) -> bool: + """按 AnchorRule 的 exact/contains 合约比较已规范化文本。""" + return expected == observed if mode == 'exact' else expected in observed + + +def _translate_signature( + *, signature: dict[str, Any] | None, coordinate_transform: dict[str, Any] | None, +) -> dict[str, Any] | None: + """将当前 Profile 签名映射到共同坐标框架,非法变换必须使证据失效。""" + if not signature or not coordinate_transform or coordinate_transform.get('status') != 'applied': + return signature + translated = deepcopy(signature) + + def project_bbox(value: Any) -> list[float] | None: + if not isinstance(value, list) or len(value) != 4: + return None + projected = apply_coordinate_transform_to_region( + {'x0': value[0], 'y0': value[1], 'x1': value[2], 'y1': value[3]}, + coordinate_transform=coordinate_transform, + ) + if projected is None: + return None + return [projected['x0'], projected['y0'], projected['x1'], projected['y1']] + + for pattern in translated.get('table_patterns') or []: + if not isinstance(pattern, dict): + continue + bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else {} + median = bbox.get('median') if isinstance(bbox.get('median'), list) else None + if median: + projected = project_bbox(median) + if projected is None: + return None + bbox['median'] = projected + header = pattern.get('header_bbox') + if header is not None: + projected = project_bbox(header) + if projected is None: + return None + pattern['header_bbox'] = projected + for relation in translated.get('field_relation_graph') or []: + if isinstance(relation, dict): + # 同一平移不会改变两锚点的相对关系,特意不修改 dx/dy。 + continue + return translated + + +def _profile_requires_unavailable_structure_evidence( + *, signature: dict[str, Any] | None, + dimension_results: dict[str, MatchDimensionResult], +) -> bool: + """关键模板结构维度缺证据即禁止自动选中,不能靠缩小评分分母获得 hard match。""" + if not signature: + return False + return any( + dimension_results[key].state == 'unavailable' + for key in CRITICAL_STRUCTURE_DIMENSION_KEYS + ) + + def _aggregate_dimension_score( *, weights: Any, @@ -664,6 +1159,17 @@ def _observe_layout_features( signature: dict[str, Any] | None, ) -> dict[str, Any]: """从冻结 layout 聚合非敏感结构特征供维度比对。""" + persisted = layout.get('matching_features') + # 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v1 投影。 + if isinstance(page_glyphs, dict) and any(isinstance(value, list) and value for value in page_glyphs.values()): + persisted = None + if isinstance(persisted, dict) and persisted.get('version') == LAYOUT_MATCHING_FEATURES_VERSION: + observed = _observed_features_from_persisted_projection( + features=persisted, signature=signature, + ) + if observed is not None: + return observed + first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None) aspect_ratio = 0.0 if isinstance(first_page, dict): @@ -699,6 +1205,127 @@ def _observe_layout_features( } +def _observed_features_from_persisted_projection( + *, features: dict[str, Any], signature: dict[str, Any] | None, +) -> dict[str, Any] | None: + """将完整的事实投影恢复为 matcher 输入,缺任一关键结构则拒绝匹配。 + + 投影生成时没有 Profile 上下文,因此会保留同一主表的多个视觉行候选。运行期只能 + 根据冻结签名的 token、顺序和列几何联合选择;按列数选最近候选会把数据行误作表头。 + """ + page_structure = features.get('page_structure') + tables = features.get('tables') + if not isinstance(page_structure, dict) or not isinstance(tables, list): + return None + candidates = [ + item for item in tables + if isinstance(item, dict) + and _is_complete_persisted_table_candidate(item) + ] + if not candidates: + return None + selected = _select_persisted_header_candidate(candidates=candidates, signature=signature) + if selected is None: + return None + primary, bbox = selected + centers = primary.get('column_centers') + widths = primary.get('column_width_ratios') + tokens = primary.get('header_tokens') + if not ( + isinstance(bbox, list) and len(bbox) == 4 + and isinstance(centers, list) and isinstance(widths, list) and isinstance(tokens, list) + ): + return None + return { + 'aspect_ratio': float(page_structure.get('aspect_ratio') or 0), + 'table_count': int(page_structure.get('table_count') or len(candidates)), + 'page_count': int(page_structure.get('page_count') or 0), + 'primary_table_bbox': bbox, + 'header_tokens': tokens, + 'column_count': len(centers), + 'column_centers': centers, + 'column_width_ratios': widths, + 'static_text_centers': ( + features.get('static_text_centers') + if isinstance(features.get('static_text_centers'), dict) else {} + ), + } + + +def _is_complete_persisted_table_candidate(candidate: dict[str, Any]) -> bool: + """校验 v1 投影的表和表头候选契约,防止不完整旧数据参与高分匹配。""" + bbox = candidate.get('bbox') + headers = candidate.get('header_candidates') + if not isinstance(bbox, list) or len(bbox) != 4 or not isinstance(headers, list): + return False + return any(_is_complete_persisted_header_candidate(item) for item in headers if isinstance(item, dict)) + + +def _is_complete_persisted_header_candidate(candidate: dict[str, Any]) -> bool: + """候选行必须同时保留 token、列中心和列宽,不能用残缺结构猜测。""" + tokens = candidate.get('header_tokens') + centers = candidate.get('column_centers') + widths = candidate.get('column_width_ratios') + return ( + isinstance(tokens, list) + and isinstance(centers, list) + and isinstance(widths, list) + and bool(tokens) + and bool(centers) + and len(centers) == len(widths) + ) + + +def _select_persisted_header_candidate( + *, candidates: list[dict[str, Any]], signature: dict[str, Any] | None, +) -> tuple[dict[str, Any], list[float]] | None: + """按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。""" + expected_tokens = [ + str(token).casefold() + for pattern in (signature or {}).get('table_patterns') or [] + if isinstance(pattern, dict) + for token in pattern.get('header_tokens') or [] + ] + expected_order = [ + str(token).casefold() + for pattern in (signature or {}).get('table_patterns') or [] + if isinstance(pattern, dict) + for token in pattern.get('header_order') or [] + ] + expected_centers = _signature_column_values(signature or {}, 'column_centers') + expected_widths = _signature_column_values(signature or {}, 'column_width_ratios') + if not expected_tokens or not expected_centers: + return None + + scored: list[tuple[float, float, float, int, dict[str, Any], list[float]]] = [] + for table in candidates: + bbox = table['bbox'] + for header in table['header_candidates']: + if not isinstance(header, dict) or not _is_complete_persisted_header_candidate(header): + continue + tokens = [str(token).casefold() for token in header['header_tokens']] + centers = header['column_centers'] + widths = header['column_width_ratios'] + token_ratio = sum(token in tokens for token in expected_tokens) / len(expected_tokens) + shared = [token for token in expected_order if token in tokens] + order_ratio = 1.0 + if len(shared) > 1: + positions = [tokens.index(token) for token in shared] + order_ratio = sum(left < right for left, right in zip(positions, positions[1:])) / (len(positions) - 1) + center_ratio = _sequence_similarity(expected_centers, centers, tolerance=0.08) + width_ratio = _sequence_similarity(expected_widths, widths, tolerance=0.16) if expected_widths else 1.0 + count_ratio = min(len(expected_centers), len(centers)) / max(len(expected_centers), len(centers)) + score = .50 * token_ratio + .15 * order_ratio + .25 * center_ratio + .05 * width_ratio + .05 * count_ratio + # token 语义或几何任一缺失都不足以把压缩投影作为结构事实。 + if token_ratio < .50 or center_ratio < .50: + continue + scored.append((score, token_ratio, center_ratio, len(tokens), header, bbox)) + if not scored: + return None + _, _, _, _, header, bbox = max(scored, key=lambda item: item[:4]) + return header, bbox + + def _select_signature_primary_table_bbox( *, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None, ) -> list[float] | None: @@ -881,11 +1508,13 @@ def _observe_static_text_centers( result: dict[str, list[float]] = {} for row in rows: ordered = sorted(row, key=lambda item: item['bbox'].get('x0', 0)) - text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered)) - if not text: + text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))[:80] + if not text or len(text) >= 80: continue xs = [(float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 / width for item in ordered] ys = [(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 / height for item in ordered] + if len(result) >= 32: + break result[text] = [round(sum(xs) / len(xs), 4), round(sum(ys) / len(ys), 4)] return result diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py b/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py index 88d77e0c..6625a69d 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py @@ -51,6 +51,8 @@ def validate_profile_parse_candidate( document_match=profile_def.get('document_match') or {'required_anchors': [], 'optional_anchors': []}, table_regions=profile_def.get('table_regions') or [], order_field_layouts=profile_def.get('order_field_layouts') or [], + coordinate_model=profile_def.get('coordinate_model') or {}, + reference_page_frames=profile_def.get('reference_page_frames') or {}, ) except (TypeError, ValueError): return { 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 deleted file mode 100644 index 9f1bb1f2..00000000 --- a/backend/app/services/shipping_notice/document_layout/profile_field_source_mapping_service.py +++ /dev/null @@ -1,456 +0,0 @@ -""" -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 deleted file mode 100644 index ec5f348d..00000000 --- a/backend/app/services/shipping_notice/document_layout/profile_vendor_comments_contract.py +++ /dev/null @@ -1,338 +0,0 @@ -""" -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 deleted file mode 100644 index 58dd3c9a..00000000 --- a/backend/app/services/shipping_notice/document_layout/reservation_format_policy_service.py +++ /dev/null @@ -1,152 +0,0 @@ -""" -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 deleted file mode 100644 index 50fc9d67..00000000 --- a/backend/app/services/shipping_notice/document_layout/reservation_relation_projection.py +++ /dev/null @@ -1,228 +0,0 @@ -""" -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_parse_strategy.py b/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py new file mode 100644 index 00000000..f4b2e295 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py @@ -0,0 +1,244 @@ +""" +services/shipping_notice/document_layout/runtime_parse_strategy.py + +用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。 +依赖:仅标准库;由正式抽取与模板质量验证共同调用。 +逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Literal + + +RowMode = Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] +StrategyStatus = Literal['selected', 'needs_review'] + + +@dataclass(frozen=True) +class RuntimeParseStrategy: + """当前文档的临时解析计划,不写回 Profile 或改变后续 Candidate Gate。""" + + status: StrategyStatus + page_nos: tuple[int, ...] + row_mode: RowMode | None + reason_codes: tuple[str, ...] + + +def resolve_runtime_parse_strategy( + *, page_glyphs: dict[str, Any], fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]], + dynamic_rows: list[dict[str, Any]] | None = None, +) -> RuntimeParseStrategy: + """按页级证据与三种重建结果选择唯一安全策略。 + + Args: + page_glyphs: 当前 Layout 的页级坐标事实;空页不进入续页候选。 + fixed_rows: 固定子行重建结果。 + adaptive_rows: 自适应列重建结果。 + dynamic_rows: 不受静态表头排除区影响的动态 X 列重建结果。 + + Returns: + ``selected`` 时调用方只消费 ``row_mode`` 对应结果;关键行不同或均不可用时返回 + ``needs_review``,由既有 Route/Candidate Gate 阻断自动建单。 + """ + page_nos = tuple(sorted( + int(page_no) for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and int(page_no) > 0 and isinstance(glyphs, list) and glyphs + )) + fixed_valid = _valid_rows(fixed_rows) + adaptive_valid = _valid_rows(adaptive_rows) + dynamic_valid = _valid_rows(dynamic_rows or []) + baseline_rows: list[dict[str, Any]] = [] + baseline = None + if fixed_valid and not adaptive_valid: + baseline_rows = fixed_valid + baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) + elif adaptive_valid and not fixed_valid: + baseline_rows = adaptive_valid + baseline = RuntimeParseStrategy( + 'selected', page_nos, 'adaptive_record_columns', + ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',), + ) + elif fixed_valid and adaptive_valid: + relation = _compare_row_field_completeness(fixed_valid, adaptive_valid) + if relation == 'fixed_preferred': + baseline_rows = fixed_valid + baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) + elif relation == 'adaptive_preferred': + baseline_rows = adaptive_valid + baseline = RuntimeParseStrategy( + 'selected', page_nos, 'adaptive_record_columns', + ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',), + ) + elif relation == 'same': + baseline_rows = fixed_valid + baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) + else: + return RuntimeParseStrategy( + 'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',), + ) + if baseline is None and dynamic_valid: + return RuntimeParseStrategy( + 'selected', page_nos, 'dynamic_x_columns', + ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',), + ) + if baseline is not None and dynamic_valid: + relation = _compare_dynamic_row_coverage( + baseline_rows=baseline_rows, dynamic_rows=dynamic_valid, + ) + if relation == 'dynamic_preferred': + return RuntimeParseStrategy( + 'selected', page_nos, 'dynamic_x_columns', + ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',), + ) + if relation == 'ambiguous': + return RuntimeParseStrategy( + 'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',), + ) + if baseline is not None: + return baseline + return RuntimeParseStrategy( + 'needs_review', page_nos, None, ('PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',), + ) + + +def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]: + """为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。 + + 历史 ``page_scope`` 仅描述样本标注页,不能要求管理员预判每份文件的续页。 + 当前页已有专属表区时只使用它;没有时复用首页/通用表区,后续仍由行重建结果 + 决定是否确实存在明细,避免把页面范围配置变成自动建单依据。 + """ + if page_no < 1: + return () + valid_regions = [ + region for region in table_regions + if isinstance(region, dict) and str(region.get('region_id') or '') + ] + exact = tuple( + str(region['region_id']) for region in valid_regions + if region.get('page_scope') == 'exact_page' and region.get('page_no') == page_no + ) + if exact: + return exact + first_page = tuple( + str(region['region_id']) for region in valid_regions + if region.get('page_scope') == 'first_page' + ) + if page_no == 1 and first_page: + return first_page + continuation = tuple( + str(region['region_id']) for region in valid_regions + if page_no > 1 and region.get('page_scope') == 'continuation_pages' + ) + if continuation: + return continuation + all_pages = tuple( + str(region['region_id']) for region in valid_regions + if region.get('page_scope') == 'all_pages' + ) + if all_pages: + return all_pages + if first_page: + return first_page + return tuple( + str(region['region_id']) for region in valid_regions + if region.get('page_scope') == 'exact_page' and region.get('page_no') == 1 + ) + + +def _valid_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """只接受无 issue 的已解析行;不将预览或待复核候选当作可自动建单事实。""" + return [ + row for row in rows + if isinstance(row, dict) and row.get('status') == 'parsed' and not row.get('issues') + ] + + +def _business_row_identity(rows: list[dict[str, Any]]) -> tuple[tuple[tuple[str, str], ...], ...]: + """比较两种重建的完整业务字段,缺值也保留以避免静默视作相同。""" + result: list[tuple[tuple[str, str], ...]] = [] + for row in rows: + values = [ + (str(field.get('field_code') or ''), str(field.get('value') or '')) + for field in row.get('fields') or [] if isinstance(field, dict) + ] + result.append(tuple(sorted(values))) + return tuple(result) + + +def _compare_row_field_completeness( + fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]], +) -> Literal['fixed_preferred', 'adaptive_preferred', 'same', 'ambiguous']: + """比较两种重建的字段集合,允许一方仅缺失字段而不丢弃整条明细。 + + 只有对应行数量相同、重叠字段值一致,且所有行都呈现同一方向的字段超集关系时, + 才自动选择更完整的结果;任一字段值冲突或方向不一致都继续进入 Review。 + """ + if len(fixed_rows) != len(adaptive_rows): + return 'ambiguous' + directions: set[str] = set() + for fixed, adaptive in zip(fixed_rows, adaptive_rows): + fixed_fields = _row_fields(fixed) + adaptive_fields = _row_fields(adaptive) + shared = fixed_fields.keys() & adaptive_fields.keys() + conflicts = [code for code in shared if fixed_fields[code] != adaptive_fields[code]] + if conflicts: + # 坐标字段框是模板的权威边界。若 adaptive 只读到 fixed 值的 + # 前缀(典型的跨视觉行料号),完整的 fixed 值应胜出;真正的 + # 不同业务值仍保持 Review,避免把冲突静默吞掉。 + if all( + fixed_fields[code].startswith(adaptive_fields[code]) + and len(fixed_fields[code]) > len(adaptive_fields[code]) + for code in conflicts + ): + directions.add('fixed') + else: + return 'ambiguous' + if fixed_fields.keys() > adaptive_fields.keys(): + directions.add('fixed') + elif adaptive_fields.keys() > fixed_fields.keys(): + directions.add('adaptive') + if not directions: + return 'same' + if len(directions) == 1: + return 'fixed_preferred' if 'fixed' in directions else 'adaptive_preferred' + return 'ambiguous' + + +def _compare_dynamic_row_coverage( + *, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]], +) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']: + """仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。""" + if len(dynamic_rows) < len(baseline_rows): + return 'baseline_preferred' + remaining = [_row_fields(row) for row in dynamic_rows] + for baseline in baseline_rows: + baseline_fields = _row_fields(baseline) + matches = [] + for index, dynamic_fields in enumerate(remaining): + if not baseline_fields.keys() <= dynamic_fields.keys(): + continue + if all( + dynamic_fields[code] == value + or ( + dynamic_fields[code].startswith(value) + and len(dynamic_fields[code]) > len(value) + ) + for code, value in baseline_fields.items() + ): + matches.append(index) + if len(matches) != 1: + return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred' + remaining.pop(matches[0]) + return 'dynamic_preferred' if remaining else 'baseline_preferred' + + +def _row_fields(row: dict[str, Any]) -> dict[str, str]: + """将策略行字段规整为可比较映射;不引入业务字段白名单。""" + return { + str(field.get('field_code') or ''): str(field.get('value') or '') + for field in row.get('fields') or [] + if isinstance(field, dict) and str(field.get('field_code') or '') + } 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 deleted file mode 100644 index ed215614..00000000 --- a/backend/app/services/shipping_notice/document_layout/source_merge_service.py +++ /dev/null @@ -1,342 +0,0 @@ -""" -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 deleted file mode 100644 index 787acda5..00000000 --- a/backend/app/services/shipping_notice/document_layout/vc_source_candidate_conflicts.py +++ /dev/null @@ -1,195 +0,0 @@ -""" -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 deleted file mode 100644 index 54a6470f..00000000 --- a/backend/app/services/shipping_notice/document_layout/vc_source_evidence_integration.py +++ /dev/null @@ -1,230 +0,0 @@ -""" -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 deleted file mode 100644 index c2d01f77..00000000 --- a/backend/app/services/shipping_notice/document_layout/vc_source_gate_contract.py +++ /dev/null @@ -1,204 +0,0 @@ -""" -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_split_rule_contract.py b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py index c5c82bc5..4dc63539 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 @@ -63,6 +63,7 @@ XFA_SPLIT_UNMATCHED_PRIORITY: Final[int] = 3 XfaSplitHandling = Literal['mapped', 'evidence_only'] XfaSplitMatcherType = Literal['position', 'prefix', 'regex'] +XfaSplitPostProcessorType = Literal['prefix'] XfaSplitSourceScope = Literal['header', 'line'] XfaSplitUnmatchedPolicy = Literal['evidence_only', 'needs_review'] XfaSplitDuplicatePolicy = Literal['needs_review'] @@ -170,6 +171,28 @@ class XfaSplitSegment(BaseSplitSegment): return self +class XfaSplitPostProcessor(XfaContractModel): + """位置/正则命中后的受限二次取值器,当前仅支持从标签后提取值。""" + + type: XfaSplitPostProcessorType + value: str = Field(min_length=1, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH) + separators: list[str] = Field(default_factory=lambda: [':', ':']) + case_sensitive: bool = False + + @model_validator(mode='after') + def validate_prefix_shape(self) -> 'XfaSplitPostProcessor': + """标签和分隔符均为受限静态文本,避免引入脚本式 pipeline。""" + value = str(self.value or '').strip() + separators = [str(item) for item in (self.separators or []) if str(item)] + if not value: + raise ValueError('prefix post processor requires non-empty value') + if not separators: + raise ValueError('prefix post processor requires at least one separator') + object.__setattr__(self, 'value', value) + object.__setattr__(self, 'separators', separators) + return self + + class XfaSplitMatcher(BaseSplitMatcher): """ 单行匹配器:position / prefix / regex。 @@ -185,6 +208,7 @@ class XfaSplitMatcher(BaseSplitMatcher): case_sensitive: bool = False pattern: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH) capture_group: int | None = Field(default=None, ge=0, le=XFA_SPLIT_MAX_REGEX_GROUPS) + post_processors: list[XfaSplitPostProcessor] = Field(default_factory=list, max_length=1) @model_validator(mode='after') def validate_matcher_shape(self) -> 'XfaSplitMatcher': 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 3d395d3c..ec5ac6b7 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 @@ -27,6 +27,7 @@ from app.services.shipping_notice.document_layout.field_split_core import ( ) from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue from app.services.shipping_notice.document_layout.xfa_split_rule_contract import ( + XfaSplitPostProcessor, XfaSplitRuleSet, ) @@ -139,6 +140,56 @@ def _core_result_to_xfa(core: _CoreSplitEngineResult) -> XfaSplitEngineResult: ) +def _apply_prefix_post_processor(value: str, processor: XfaSplitPostProcessor) -> str | None: + """从已定位行中提取指定标签及分隔符后的值;未命中必须显式进入复核。""" + source = str(value or '') + comparable = source if processor.case_sensitive else source.lower() + label = processor.value if processor.case_sensitive else processor.value.lower() + start = comparable.find(label) + if start < 0: + return None + tail_start = start + len(label) + tail = source[tail_start:] + for separator in processor.separators: + if tail.startswith(separator): + return tail[len(separator):].strip() + return None + + +def _apply_xfa_post_processors( + result: XfaSplitEngineResult, + *, + rule_set: XfaSplitRuleSet, +) -> XfaSplitEngineResult: + """对已由正式 matcher 定位的行执行受限后处理,并重新聚合正式字段。""" + rules = {rule.rule_id: rule for rule in rule_set.rules} + mapped_fields: dict[str, str] = {} + needs_review = result.status == 'needs_review' + for segment in result.segments: + rule = rules.get(segment.rule_id) + for processor in (rule.matcher.post_processors if rule else []): + extracted = _apply_prefix_post_processor(segment.normalized_text, processor) + if extracted is None: + segment.normalized_text = '' + segment.status = 'needs_review' + needs_review = True + result.diagnostics.append(XfaSplitDiagnostic( + code='post_processor_no_match', + message=f'Rule {segment.rule_id} post processor did not match the selected line', + line_no=segment.line_no, + field_code=segment.target_field_code, + rule_ids=[segment.rule_id], + )) + break + segment.normalized_text = extracted + if segment.handling == 'mapped' and segment.target_field_code: + mapped_fields[segment.target_field_code] = segment.normalized_text + result.mapped_fields = mapped_fields + if needs_review: + result.status = 'needs_review' + return result + + # --------------------------------------------------------------------------- # 对外执行入口——签名 100% 不变 # --------------------------------------------------------------------------- @@ -177,7 +228,7 @@ def execute_split_rule_set( rule_set=rule_set, lines=lines, ) - return _core_result_to_xfa(core_result) + return _apply_xfa_post_processors(_core_result_to_xfa(core_result), rule_set=rule_set) def execute_split_on_leaf( diff --git a/backend/app/services/shipping_notice/document_profile_quality_service.py b/backend/app/services/shipping_notice/document_profile_quality_service.py index 3935dcbf..2d753d23 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -16,7 +16,7 @@ from decimal import Decimal from typing import Any from app import db -from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError +from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingDocumentProfileTestRun, ShippingDocumentProfileTestSample, @@ -30,13 +30,18 @@ from app.models import ( ShippingOrderDocumentProfileSample, ) from app.services.shipping_notice.document_layout.html_table import parse_html_grid -from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot +from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot, _hydrate_coordinate_evidence from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile -from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows +from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + coordinate_profile_character_candidates, + reconstruct_coordinate_profile_rows, reconstruction_exclusion_regions, + reconstruct_coordinate_profile_rows_with_strategy, +) +from app.services.shipping_notice.document_layout.runtime_parse_strategy import resolve_runtime_parse_strategy from app.services.shipping_notice.document_layout.order_field_extraction import ( _is_placeholder_anchor_text, extract_order_fields, ) -from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence +from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text from app.services.shipping_notice import order_document_profile_service as profile_service from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter from app.services.shipping_notice.order_document_profile_service import ( @@ -44,6 +49,10 @@ from app.services.shipping_notice.order_document_profile_service import ( _normalize_definition, _require_schema_version, ) from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value +from app.services.shipping_notice.reservation_region import ( + apply_reservation_region_candidates, + extract_reservation_from_region_text, +) # 日常模板维护采用一份独立样本门槛;字段 confirmed、人工真值一致、 @@ -126,109 +135,50 @@ def _table_html(document_id: int, table_id: str) -> str: raise ValidationError('Test sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') -def _coordinate_table_available(document_id: int, table_id: str) -> bool: - """确认 v2 盲测有冻结页面尺寸和目标表的字符证据,不要求 MinerU HTML。""" - document = db.session.get(ShippingOrderDocument, int(document_id)) - layout = current_layout_snapshot(document) if document is not None else {} - raw_table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)), None) - evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {} - return bool( - isinstance(raw_table, dict) - and isinstance((evidence.get('tables') or {}).get(str(table_id)), list) - and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or '')), dict) - ) - - -def _recover_coordinate_table_for_preview( - *, document: ShippingOrderDocument, layout: dict[str, Any], raw_table: dict[str, Any], table_id: str, -) -> dict[str, Any]: - """仅为盲测复核临时恢复表格及整页坐标,不写回冻结布局或正式解析输入。""" - recovered = ensure_on_demand_coordinate_evidence( - document=document, layout=layout, - page_nos={int(raw_table.get('page_no') or 1)}, - table_by_page={int(raw_table.get('page_no') or 1): raw_table}, - ) - evidence = recovered.get('coordinate_evidence') if isinstance(recovered.get('coordinate_evidence'), dict) else {} - if ( - isinstance((evidence.get('tables') or {}).get(str(table_id)), list) - and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or 1)), dict) - ): - return recovered +def _coordinate_table_available_in_layout(layout: dict[str, Any], *, table_id: str, page_no: int) -> bool: + """判断运行期布局是否已有目标表与页面坐标证据。""" evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} - tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} - pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} - page_no = str(raw_table.get('page_no') or 1) - page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} - page_sources = (evidence.get('sources') or {}).get('pages') if isinstance(evidence.get('sources'), dict) else {} - if ( - isinstance(tables.get(table_id), list) - and isinstance(pages.get(page_no), dict) - and isinstance(page_glyphs.get(page_no), list) - and str((page_sources or {}).get(page_no) or '') in {'pdf_coordinate', 'ocr_coordinate'} - ): - return layout - if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'): - return layout - try: - from app.models import FileAsset - from app.services.file_assets.service import read_asset_bytes - from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages - from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines - from app.services.shipping_notice.order_document_profile_service import ( - _native_characters_in_table, _ocr_lines_to_characters, _ocr_lines_to_page_characters, - ) - - asset = db.session.get(FileAsset, document.asset_id) - if asset is None: - return layout - page = next( - item for item in extract_native_pdf_pages(read_asset_bytes(asset)) - if item.page_no == int(raw_table.get('page_no') or 0) - ) - native_characters = list(getattr(page, 'characters', []) or []) - full_page_characters = [item.model_dump(mode='json') for item in native_characters] - source = 'pdf_coordinate' - characters = _native_characters_in_table( - characters=native_characters, table_bbox=raw_table.get('bbox') or {}, - ) - if not characters: - ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height) - full_page_characters = _ocr_lines_to_page_characters(lines=ocr_lines) - characters = _ocr_lines_to_characters(lines=ocr_lines, table_bbox=raw_table.get('bbox') or {}) - source = 'ocr_coordinate' - if not characters or not full_page_characters: - return layout - next_layout = dict(layout) - next_evidence = dict(evidence) - next_evidence['tables'] = {**tables, table_id: characters} - next_evidence['pages'] = { - **pages, str(page.page_no): {'width': page.width, 'height': page.height}, - } - next_evidence['page_glyphs'] = {**page_glyphs, str(page.page_no): full_page_characters} - sources = dict(evidence.get('sources') or {}) - sources['pages'] = {**dict(sources.get('pages') or {}), str(page.page_no): source} - next_evidence['sources'] = sources - next_layout['coordinate_evidence'] = next_evidence - return next_layout - except Exception: - return layout + return bool( + isinstance((evidence.get('tables') or {}).get(str(table_id)), list) + and isinstance((evidence.get('pages') or {}).get(str(page_no)), dict) + ) def _region_characters_for_quality( *, region: Any, evidence: dict[str, Any], raw_table: dict[str, Any], table_id: str, ) -> list[dict[str, Any]] | None: - """为盲测按模板显式策略选取冻结字符;旧模板始终沿用表格局部证据。""" - table_characters = (evidence.get('tables') or {}).get(str(table_id)) - if getattr(region, 'row_reconstruction_mode', 'fixed_subrows') != 'adaptive_record_columns': - return table_characters if isinstance(table_characters, list) else None + """为盲测选择当前页字符,确保与编辑器预览和正式解析共用同一输入事实。""" page_no = str(raw_table.get('page_no') or 1) page_characters = (evidence.get('page_glyphs') or {}).get(page_no) if isinstance(page_characters, list): return page_characters - # 冻结快照仍可能来自升级前的证据结构;保持该模板原有表格证据可读。 + # 旧冻结快照可能没有页级坐标;仅在该事实缺失时回退当前物理表的字符。 + table_characters = (evidence.get('tables') or {}).get(str(table_id)) return table_characters if isinstance(table_characters, list) else None +def _quality_page_characters( + *, region: Any, evidence: dict[str, Any], raw_table: dict[str, Any], page_no: int, +) -> list[dict[str, Any]] | None: + """按表格实例隔离盲测行证据,禁止后续页重复消费首页 table glyphs。""" + table_page_no = int(raw_table.get('page_no') or 1) + if page_no == table_page_no: + return _region_characters_for_quality( + region=region, evidence=evidence, raw_table=raw_table, + table_id=str(raw_table.get('table_id') or ''), + ) + continuation = getattr(region, 'continuation_rule', None) + allow_cross_page = bool( + continuation.get('allow_cross_page') + if isinstance(continuation, dict) + else getattr(continuation, 'allow_cross_page', False) + ) + if not allow_cross_page: + return None + page_glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no)) + return page_glyphs if isinstance(page_glyphs, list) else None + + def _ensure_order_field_evidence( *, document: ShippingOrderDocument, layout: dict[str, Any], parser: OrderCoordinateProfile, ) -> dict[str, Any]: @@ -396,7 +346,9 @@ def _candidate_for_sample( 'Blind-test preview layout changed', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE', ) - layout = dict(frozen_version.payload_json) if frozen_version is not None else ( + layout = _hydrate_coordinate_evidence( + payload=dict(frozen_version.payload_json), document=document, + ) if frozen_version is not None and document is not None else ( current_layout_snapshot(document) if document is not None else None ) is_document_candidate = str(table_id) == DOCUMENT_CANDIDATE_TABLE_ID @@ -409,21 +361,9 @@ def _candidate_for_sample( # 失败版本不会成为“当前成功快照”,但文档级盲测仍需以其安全元数据 # 为起点从原文件临时恢复坐标;这里不把失败布局提升为正式快照。 layout = dict(document.current_layout_version.payload_json) - if document is None: - raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') - if is_document_candidate and not layout: - # 上传与复核解耦后,后台 Layout 可能仍为 queued/running 且尚无 payload。 - # 文档级候选从安全空骨架进入现有原 PDF 按需恢复链,不等待、不取消也不写回后台任务。 - layout = {'status': 'pending', 'tables': [], 'issues': []} - if not layout: + if document is None or not layout: raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') if isinstance(parser, OrderCoordinateProfile): - if is_document_candidate: - # [STEP 1] MinerU 未产出表格时,盲测仍以原文件字符坐标运行当前模板; - # 证据只驻留本次调用,绝不写回布局或改变生产模板命中输入。 - layout = ensure_on_demand_coordinate_evidence( - document=document, layout=layout, page_nos=None, - ) layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser) schema_fields = { str(item.get('field_id') or ''): item @@ -435,20 +375,12 @@ def _candidate_for_sample( item for item in layout.get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id) ), None) - if isinstance(raw_table, dict) and frozen_version is None: - layout = _recover_coordinate_table_for_preview( - document=document, layout=layout, raw_table=raw_table, table_id=str(table_id), - ) evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} - if ( - not is_document_candidate - and not _coordinate_table_available(document_id, table_id) - and not isinstance((evidence.get('tables') or {}).get(str(table_id)), list) - ): + if not isinstance((evidence.get('tables') or {}).get(str(table_id)), list): raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} - if is_document_candidate and not any(isinstance(value, list) and value for value in page_glyphs.values()): + if not any(isinstance(value, list) and value for value in page_glyphs.values()): raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') rows: list[dict[str, Any]] = [] for region in parser.table_regions: @@ -456,19 +388,14 @@ def _candidate_for_sample( # layout. They are valid template regions, but cannot reconstruct rows. if not region.line_layouts: continue - if is_document_candidate: - eligible_pages = [ - int(page_no) for page_no in pages - if str(page_no).isdigit() - and ( - region.page_scope == 'all_pages' - or (region.page_scope == 'first_page' and int(page_no) == 1) - or (region.page_scope == 'continuation_pages' and int(page_no) > 1) - or (region.page_scope == 'exact_page' and int(page_no) == region.page_no) - ) - ] - else: - eligible_pages = [int(raw_table.get('page_no') or 1)] if isinstance(raw_table, dict) else [] + # ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中 + # 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。 + eligible_pages = [ + int(page_no) for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs + ] + if not eligible_pages and isinstance(raw_table, dict): + eligible_pages = [int(raw_table.get('page_no') or 1)] for page_no in sorted(eligible_pages): page = pages.get(str(page_no)) if not isinstance(page, dict): @@ -477,31 +404,115 @@ def _candidate_for_sample( table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])} except (KeyError, TypeError, ValueError): continue - characters = ( - page_glyphs.get(str(page_no)) - if is_document_candidate - else _region_characters_for_quality( - region=region, evidence=evidence, raw_table=raw_table, table_id=str(table_id), + if is_document_candidate: + characters = page_glyphs.get(str(page_no)) + elif not isinstance(raw_table, dict): + characters = None + else: + characters = _quality_page_characters( + region=region, evidence=evidence, raw_table=raw_table, page_no=page_no, ) + candidate_table_bbox = raw_table.get('bbox') if isinstance(raw_table, dict) and page_no == int(raw_table.get('page_no') or 1) else None + characters, _candidate_page_bbox = coordinate_profile_character_candidates( + table_region=region.region.model_dump(), page_size=page, + reference_page_frame=( + region_frame.model_dump() + if (region_frame := parser.reference_page_frames.get(page_no)) is not None else None + ), + page_characters=characters if isinstance(characters, list) else None, + table_characters=(evidence.get('tables') or {}).get(str(raw_table.get('table_id') or '')) if isinstance(raw_table, dict) else None, + raw_table_bbox=candidate_table_bbox, + table_id=str(raw_table.get('table_id') or '') if isinstance(raw_table, dict) else None, + page_no=page_no, + allow_table_fallback=( + isinstance(raw_table, dict) + and page_no == int(raw_table.get('page_no') or 1) + ), ) if not isinstance(characters, list): continue - rows.extend(item.fields for item in reconstruct_coordinate_profile_rows( - characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox, + # 表头布局只描述列语义和预览高亮,不能作为静态删除区;否则单头高度变化时 + # 会在起行锚点识别前误删首条明细字符。仅应用管理员明确配置的普通排除区。 + reconstruction_exclusions = reconstruction_exclusion_regions(region.model_dump()) + reconstruction_table_bbox = ( + { + 'x0': 0, 'y0': 0, + 'x1': region_frame.width, 'y1': region_frame.height, + } + if region_frame is not None else table_bbox + ) + chosen_rows, strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_table_bbox, line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(), termination_rules=[item.model_dump() for item in region.termination_rules], - exclusion_regions=[item.model_dump() for item in region.exclusion_regions], + exclusion_regions=reconstruction_exclusions, + dynamic_exclusion_regions=reconstruction_exclusions, line_start_field_code=region.line_start_field_code, - row_reconstruction_mode=region.row_reconstruction_mode, - ) if not item.issues) + schema_field_metadata=list(schema_fields.values()), + ) + if strategy.status == 'selected': + rows.extend(item.fields for item in chosen_rows if not item.issues) order_fields = [ { 'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status, 'field_id': item.field_id, 'scope': item.scope, 'page_no': item.page_no, 'issues': list(item.issues), } - for item in extract_order_fields(profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence) + for item in extract_order_fields( + profile=parser, + schema_fields=schema_fields, + coordinate_evidence=evidence, + allow_fixed_region_confirmation=True, + ) ] + # 盲测与正式解析共用 Reservation 区域解析和归属契约;区域页可以不同于明细页。 + profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + reservation_region = profile_definition.get('reservation_id_region') + if isinstance(reservation_region, dict): + region = reservation_region.get('region') + try: + reservation_page_no = int(reservation_region.get('page_no') or 0) + except (TypeError, ValueError): + reservation_page_no = 0 + if isinstance(region, dict) and reservation_page_no > 0: + layout = _ensure_page_coordinate_evidence( + document=document, layout=layout, page_no=reservation_page_no, + ) + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + page = (evidence.get('pages') or {}).get(str(reservation_page_no)) + glyphs = (evidence.get('page_glyphs') or {}).get(str(reservation_page_no)) + if isinstance(page, dict) and isinstance(glyphs, list): + candidates = extract_reservation_from_region_text( + read_coordinate_region_text(glyphs=glyphs, page=page, region=region), + ) + reservation_fields = { + str(field.get('scope') or ''): field + for field in schema_fields.values() + if str(field.get('field_code') or '') == 'reservation_id' + } + applied = apply_reservation_region_candidates( + candidates=candidates, + header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None, + line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None, + line_count=len(rows), + ) + if applied.header_value and reservation_fields.get('header'): + header = reservation_fields['header'] + order_fields.append({ + 'field_code': str(header.get('field_code') or ''), 'value': applied.header_value, + 'status': 'confirmed', 'field_id': str(header.get('field_id') or ''), 'scope': 'header', + 'page_no': reservation_page_no, 'issues': [], + }) + if reservation_fields.get('line'): + for line_no, value in applied.line_values.items(): + if isinstance(rows[line_no - 1], dict): + rows[line_no - 1]['reservation_id'] = value + if applied.needs_review: + return { + 'document_id': document.id, 'table_id': str(table_id), 'rows': rows, + 'order_fields': order_fields, 'reservation_region_status': 'needs_review', + 'reservation_region_review_reasons': list(applied.review_reasons), + } return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields} raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') @@ -562,7 +573,7 @@ def _common_blind_sample_descriptors( layout_version = ShippingDocumentLayoutVersion.query.filter_by(document_id=document.id).order_by( ShippingDocumentLayoutVersion.version.desc(), ShippingDocumentLayoutVersion.id.desc(), ).first() - layout = dict(layout_version.payload_json) if layout_version is not None and isinstance(layout_version.payload_json, dict) else {} + layout = current_layout_snapshot(document) or {} tables = layout.get('tables') if isinstance(layout.get('tables'), list) else [] if ( layout_version is None or layout_version.status != 'ready' @@ -595,7 +606,9 @@ def _common_blind_sample_descriptors( except ValidationError: continue header_preview = [slot.text for slot in (grid.rows[0] if grid.rows else []) if slot is not None and slot.text][:3] - coordinate_evidence_ready = _coordinate_table_available(document.id, table_id) + coordinate_evidence_ready = _coordinate_table_available_in_layout( + layout, table_id=table_id, page_no=int(table.get('page_no') or 1), + ) descriptors.append({ 'document_id': document.id, 'table_id': table_id, 'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '', @@ -634,6 +647,11 @@ def _compare_blind_candidate( failures: list[str] = [] total = 0 matched = 0 + if candidate.get('reservation_region_status') == 'needs_review': + failures.extend([ + f'reservation_region:{reason}' + for reason in candidate.get('reservation_region_review_reasons') or ['needs_review'] + ]) for field in candidate.get('order_fields') or []: if not isinstance(field, dict): continue @@ -820,7 +838,7 @@ def _prepare_common_blind_sample( or not isinstance(version.payload_json, dict) ): raise ConflictError('Blind-test preview layout changed', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE') - layout = dict(version.payload_json) + layout = _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document) raw_table = next(( item for item in layout.get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id) @@ -1084,11 +1102,6 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]: or last_run.status != 'passed' or last_run.profile_checksum != _quality_checksum(profile) ): raise ConflictError('A current passing blind test run is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY') - if int(actor_id) == int(suite.created_by_id): - raise ForbiddenError( - 'Editor cannot approve own blind test suite', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY', - ) suite.status = 'approved' # A coordinate-template approval is also its publish-quality credential. # Validate the remaining publish prerequisites before committing approval so diff --git a/backend/app/services/shipping_notice/duplicate_detection.py b/backend/app/services/shipping_notice/duplicate_detection.py index c8b6f1eb..fad92a0a 100644 --- a/backend/app/services/shipping_notice/duplicate_detection.py +++ b/backend/app/services/shipping_notice/duplicate_detection.py @@ -41,7 +41,7 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}: return 'closed' upload = str(get('upload_status', '') or '').strip().lower() - if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no') or get('upload_receipt_json'): + if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'): return 'completed' return 'active' diff --git a/backend/app/services/shipping_notice/email_allocation_table_parser.py b/backend/app/services/shipping_notice/email_allocation_table_parser.py index d5198358..aa4f11f2 100644 --- a/backend/app/services/shipping_notice/email_allocation_table_parser.py +++ b/backend/app/services/shipping_notice/email_allocation_table_parser.py @@ -61,19 +61,31 @@ def _normalize_schema_row( def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]: - """将首行映射为 Schema 订单字段或邮件专属字段;重复映射直接标为复核。""" + """将首行映射为 Schema 订单字段;同字段多个别名按 Schema 顺序保留首选列。""" schema_headers = _schema_headers(schema_definition) mapped: dict[int, str] = {} + selected_by_field: dict[str, tuple[int, int]] = {} issues: list[str] = [] for column, slot in enumerate(grid.rows[0]): normalized = normalize_table_header(slot.text if slot is not None else '').casefold() schema_field = schema_headers.get(normalized) hits = [schema_field] if schema_field else [] if len(hits) == 1: - if hits[0] in mapped.values(): - issues.append('email_supplement_duplicate_header') + field_code = str(hits[0]) + priority = _schema_header_priority(schema_definition, field_code, normalized) + previous = selected_by_field.get(field_code) + if previous is None: + mapped[column] = field_code + selected_by_field[field_code] = (priority, column) else: - mapped[column] = hits[0] + previous_priority, previous_column = previous + # 同一业务字段出现两个已配置别名时,按 Schema 中 field_code、 + # display_name、aliases 的声明顺序选择唯一证据列;不把同一行 + # 的 Source / hub code 误判为冲突,也不允许后一个列覆盖首选值。 + if priority < previous_priority: + mapped.pop(previous_column, None) + mapped[column] = field_code + selected_by_field[field_code] = (priority, column) elif len(hits) > 1: issues.append('email_supplement_header_ambiguous') if not ({'customer_po_number', 'po_number'} & set(mapped.values())): @@ -81,6 +93,21 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in return mapped, sorted(set(issues)) +def _schema_header_priority(schema_definition: dict[str, Any], field_code: str, normalized_header: str) -> int: + """返回字段表头的 Schema 声明顺序,供同字段多别名确定性裁决。""" + priorities: list[int] = [] + for raw in schema_definition.get('fields') or []: + if not isinstance(raw, dict) or not raw.get('enabled', True): + continue + if str(raw.get('field_code') or '').strip() != field_code: + continue + candidates = (field_code, raw.get('display_name'), *(raw.get('aliases') or [])) + for priority, value in enumerate(candidates): + if normalize_table_header(value).casefold() == normalized_header: + priorities.append(priority) + return min(priorities) if priorities else 2**31 - 1 + + def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]: """收集邮件补充允许的 Schema 别名;跨字段冲突必须显式保留为不可映射。""" headers: dict[str, str | None] = {} diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index 2c9c860d..2babdf63 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -531,7 +531,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { '字段已按 PDF 优先裁决,请核对辅助证据差异', ), 'evidence_missing': _meta('owner', 'open_order_review', '关键识别结果缺少有效证据'), - 'customer_unresolved': _meta('owner', 'confirm_customer', '未能识别客户'), + 'customer_unresolved': _meta('owner', 'confirm_customer', '客户尚未确认'), 'customer_ambiguous': _meta('owner', 'confirm_customer', '匹配到多个客户'), 'customer_out_of_scope': _meta('owner', 'confirm_customer', '客户不在当前业务范围内'), 'reservation_missing': _meta('owner', 'edit_reservation', '缺少有效 Reservation'), @@ -566,10 +566,10 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'), 'inventory_preparation_failed': _meta('owner', 'retry_inventory_preparation', '库存准备失败,请重试或上传库存文件'), 'inventory_rpa_queued': _meta('worker', 'poll_inventory_preparation', 'RPA 任务已排队等待执行'), - 'inventory_rpa_timeout': _meta('worker', 'retry_inventory_preparation', 'RPA 执行超时'), + 'inventory_rpa_timeout': _meta('worker', 'reload_inventory_result', 'RPA 执行超时'), 'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'), 'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'), - 'inventory_rpa_exhausted': _meta('owner', 'upload_inventory_file', '库存源重试次数已耗尽'), + 'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'), 'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'), 'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'), 'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'), @@ -583,7 +583,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'), 'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'), 'artifact_generation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 生成失败'), - 'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并登记结果'), + 'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并确认已上传'), 'upload_rpa_pending': _meta('worker', 'poll_freight_upload_rpa', '货代平台上传任务等待执行'), 'upload_rpa_failed': _meta('worker', 'retry_freight_upload_rpa', '货代平台上传失败,可重试 RPA'), 'upload_rpa_login_failed': _meta('admin', 'retry_freight_upload_rpa', '货代平台登录失败,请检查凭据后重试'), @@ -601,7 +601,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'void_blocked_external_uploaded': _meta('owner', '', '已存在外部履约,禁止作废,请归档'), 'task_rejected_by_user': _meta('owner', '', '订单候选/任务已由用户驳回'), 'task_closed_after_upload': _meta('owner', '', '上传完成后任务已关闭'), - 'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '缺少上传回执,暂不可关闭'), + 'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '尚未确认已上传,暂不可关闭'), 'late_callback_ignored': _meta('system', '', '迟到的外部回调已忽略'), 'excel_downloaded': _meta('owner', '', '已下载发货 Excel'), 'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'), diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index b76f1414..881f86f9 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -24,9 +24,11 @@ from openpyxl import load_workbook from openpyxl.cell.cell import MergedCell from sqlalchemy import func from app import db +from app.core.errors import ConflictError from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, + ShippingNoticeLine, ShippingInventoryField, ShippingInventorySource, ShippingOrderSnapshot, @@ -37,6 +39,31 @@ from app.path_utils import resolve_backend_relative_path from app.services.file_assets.storage import file_asset_storage +def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None: + """ + 确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。 + + Args: + task: 当前发货通知单。 + + Raises: + ConflictError: 已存在任意导出 Artifact;后续库存必须创建新的发货通知单。 + """ + if task.id is None: + return + existing = ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first() + if existing is not None: + raise ConflictError( + 'A shipping notice can generate only one Excel artifact', + code='SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED', + details={ + 'task_no': task.task_no, + 'business_no': task.business_no, + 'artifact_no': existing.artifact_no, + }, + ) + + def _storage_root() -> Path: """返回发货通知文件根目录。""" configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip() @@ -45,8 +72,22 @@ def _storage_root() -> Path: return Path(current_app.instance_path) / 'shipping_notice' +def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice: + """后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。""" + if notice.order_snapshot_id: + return notice + if notice.order_task_id: + source = ShippingNotice.query.filter( + ShippingNotice.order_task_id == int(notice.order_task_id), + ShippingNotice.order_snapshot_id.isnot(None), + ).order_by(ShippingNotice.id.asc()).first() + if source is not None: + return source + return notice + + def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]: - """从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。""" + """从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。""" from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked assert_task_not_supersession_blocked(task) snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None @@ -62,19 +103,10 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None: - """生成本次 Excel 使用的 Pull Request Number;不回写业务单主编号。""" - case = task.shipping_case - if case is None or not case.business_no: - return None - business_no = str(case.business_no).strip() - prefix = business_no[:-8] if len(business_no) > 8 else business_no - sequence = business_no[-2:] if len(business_no) >= 2 and business_no[-2:].isdigit() else '' - if not sequence and case.sequence_value: - sequence = f'{int(case.sequence_value):02d}' - if not sequence: - return None - export_date = export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date() - return f'{prefix}{export_date.strftime("%y%m%d")}{sequence}' + """返回当前发货通知单编号;履约路径不回退到其他聚合标识。""" + if task.business_no: + return str(task.business_no).strip() + return None def _clear_template_data_rows(ws: Any, start_row: int) -> None: @@ -92,6 +124,7 @@ def _system_fact( *, export_sequence: int | None = None, excel_business_no: str | None = None, + notice_no: str | None = None, export_date: date | None = None, ) -> Any: """ @@ -106,8 +139,8 @@ def _system_fact( 对应系统事实值;未知键返回 None。 """ values = { - 'task_no': task.task_no, - 'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None), + 'task_no': notice_no or task.task_no, + 'business_no': notice_no or excel_business_no or task.business_no, 'warehouse_id': task.inventory_warehouse_id, 'inventory_source_code': task.inventory_source_code, 'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(), @@ -160,6 +193,7 @@ def _mapping_value( mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any], header_values: dict[str, Any] | None = None, export_sequence: int | None = None, excel_business_no: str | None = None, + notice_no: str | None = None, export_date: date | None = None, ) -> Any: """ @@ -196,12 +230,17 @@ def _mapping_value( task, key, export_sequence=export_sequence if key == 'export_sequence' else None, excel_business_no=excel_business_no, + notice_no=notice_no, export_date=export_date, ) if key == 'export_sequence' and value is None: value = order_values.get('__export_sequence') else: value = key + # 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串; + # 尤其金额字段不得由数量/单价等相邻字段隐式推导或伪装为已提供。 + if kind == 'order_field' and value is None: + return None return _format_value(value, mapping['formatter']) @@ -389,6 +428,7 @@ def _filename( template: ShippingExcelTemplate, *, excel_business_no: str | None = None, + notice_no: str | None = None, ) -> str: """按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。""" pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip() @@ -397,16 +437,15 @@ def _filename( if not pattern: raise ValueError('发货 Excel 文件名规则未配置') now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S') - shipping_case = task.shipping_case values = { - 'task_no': task.task_no, - 'business_no': excel_business_no or (shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no), + 'task_no': notice_no or task.task_no, + 'business_no': notice_no or excel_business_no or task.business_no or task.task_no, 'source_code': task.inventory_source_code or '', 'ts': now, 'date': now[:8], - 'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '', - 'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '', - 'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '', + 'customer_short_code': task.customer_short_code_snapshot or '', + 'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '', + 'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '', } try: return _safe_filename(pattern.format(**values)) @@ -418,6 +457,7 @@ def _input_checksum( task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate, snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], + notice_id: int | None = None, ) -> str: """以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。""" payload = { @@ -426,12 +466,15 @@ def _input_checksum( 'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id, 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id, 'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines, + 'notice_id': notice_id, } raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str) return hashlib.sha256(raw.encode('utf-8')).hexdigest() -def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExportArtifact]: +def generate_shipment_excel( + task: ShippingNotice, +) -> tuple[str, str, ShippingExportArtifact]: """ 按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。 【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。 @@ -441,56 +484,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp Raises: ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。 - AppError: [T6 硬门禁] 行级库存匹配存在非 matched 行(shortage / not_found / conflict)。 + AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。 """ 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 前复用库存满足性判定:每行须库存充足, - # 或为带原因的正式短缺放行;未匹配/冲突绝不能用放行绕过。 - 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), - ).limit(20).all() - # 行级库存事实是当前正式放行 Gate 的真相。历史导出任务可能只有 - # Reservation 核验轮次;这类任务继续由下方 Reservation 选择保护,不能因 - # 缺少新表事实被误判为“未匹配”。 - has_line_match_facts = bool(pending_rows) - from app.services.shipping_notice.fulfillment_workflow import match_completed - if has_line_match_facts and not match_completed(task): - 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( - code='SHIPPING.EXCEL_NOT_READY', - message='存在未满足或未放行的库存行,禁止生成发货 Excel(请先处理短缺或冲突)。', - http_status=409, - details={ - 'blocking_reason_code': 'inventory_match_incomplete', - 'pending_count': len(pending_rows), - 'pending_rows_preview': details, - 'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。', - }, - ) + assert_notice_has_no_export_artifact(task) + # [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。 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: @@ -520,18 +523,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp # applies only when the published template actually consumes that system fact. if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip(): raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel') - active_artifact = ShippingExportArtifact.query.filter( - ShippingExportArtifact.task_id == task.id, - ShippingExportArtifact.status.in_({'ready', 'uploading'}), - ).first() - if active_artifact is not None: - raise ValueError('当前任务存在待上传的发货 Excel,必须先完成或授权作废该 Artifact') - snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + source_notice = _source_notice_for_order_facts(task) + snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于导出的冻结订单快照') header_values, all_line_values = order_field_id_values(task) export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date() - excel_business_no = _excel_business_no(task, export_date=export_date) from app.services.shipping_notice.reservation_service import ( current_available_snapshot_line_ids, reserve_available_for_artifact, @@ -546,12 +543,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp release_overrides_by_source_line: dict[int, dict[str, Any]] = {} released_source_line_indexes: set[int] = set() - if task.id is not None: + if source_notice.id is not None: release_rows = ( ShippingOrderReviewLineDecision.query .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) .filter( - ShippingOrderReviewCase.confirmed_task_id == int(task.id), + ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id), ShippingOrderReviewLineDecision.is_active.is_(True), ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', ) @@ -570,10 +567,19 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp for source_index, line in enumerate(snapshot.lines) if source_index in release_overrides_by_source_line } - verification, available_line_ids = current_available_snapshot_line_ids( - task, - released_snapshot_line_ids=released_snapshot_line_ids, - ) + selected_snapshot_line_ids = { + int(row.snapshot_line_id) + for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all() + if row.snapshot_line_id is not None + } + try: + verification, available_line_ids = current_available_snapshot_line_ids( + source_notice, + released_snapshot_line_ids=released_snapshot_line_ids, + selected_snapshot_line_ids=selected_snapshot_line_ids or None, + ) + except ConflictError: + raise # [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。 line_values = [] for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)): @@ -587,7 +593,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution # [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。 - inventory_lines = resolve_inventory_lines_for_execution(task) + inventory_lines = resolve_inventory_lines_for_execution(source_notice) release_overrides_by_line = _release_overrides_for_export_lines( line_values=line_values, release_overrides_by_source_line=release_overrides_by_source_line, @@ -609,9 +615,17 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp ) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values] header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields) + # [STEP 4] Notice 的业务单号与首个 Excel 同一事务产生。此处已完成业务、 + # 库存和导出行校验;随后 Excel、Artifact 或 Reservation 任一步失败都会回滚编号流水。 + if not task.business_no: + from app.services.shipping_notice.business_numbering_service import assign_notice_business_number + + assign_notice_business_number(task) + excel_business_no = _excel_business_no(task, export_date=export_date) filename = _filename(task, template, excel_business_no=excel_business_no) artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}' - directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no + directory_key = task.task_no + directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / directory_key directory.mkdir(parents=True, exist_ok=True) path = directory / f'{artifact_no}_{filename}' template_bytes = file_asset_storage.get_bytes(template.storage_key) @@ -654,14 +668,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp wb.close() content = path.read_bytes() - # 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是 - # 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。 + # 当前 Notice 的唯一 Excel;后续分批履约必须先创建新的 Notice, + # 因而不得在此处替换或追加当前 Notice 的 Artifact。 artifact = ShippingExportArtifact( - artifact_no=artifact_no, task_id=task.id, template_id=template.id, + artifact_no=artifact_no, task_id=task.id, + template_id=template.id, order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id, inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id, input_checksum=_input_checksum( task, source, template, snapshot, header_values, line_values, inventory_lines, + notice_id=int(task.id), ), file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(), file_size=len(content), status='ready', @@ -669,10 +685,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp db.session.add(artifact) db.session.flush() reserve_available_for_artifact( - task, + source_notice, artifact=artifact, verification=verification, released_snapshot_line_ids=released_snapshot_line_ids, + selected_snapshot_line_ids=selected_snapshot_line_ids or None, ) return str(path), filename, artifact except Exception: diff --git a/backend/app/services/shipping_notice/export_archive.py b/backend/app/services/shipping_notice/export_archive.py index 4203be3f..117bac2c 100644 --- a/backend/app/services/shipping_notice/export_archive.py +++ b/backend/app/services/shipping_notice/export_archive.py @@ -1,9 +1,9 @@ """ services/shipping_notice/export_archive.py -用途:为一个批次或显式任务集合生成受权限控制的发货 Excel ZIP 下载包。 +用途:为显式任务集合生成受权限控制的发货 Excel ZIP 下载包。 依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。 -逻辑:选择每票全部 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。 +逻辑:选择每张通知唯一可下载 Artifact,校验文件 checksum,处理重名并写入 manifest.json。 """ from __future__ import annotations @@ -18,36 +18,30 @@ from zipfile import ZIP_DEFLATED, ZipFile from app.core.errors import NotFoundError, ValidationError from app.models import ShippingExportArtifact, ShippingNotice -from app.services.shipping_notice.query_service import ( - get_batch_for_user, - get_task_for_user, - list_sorted_batch_tasks, - resolve_task_export_download, -) +from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download MAX_ARCHIVE_TASKS = 100 -def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingNotice], str]: - """按批次或任务号选择当前用户任务;两种模式互斥且禁止部分越权成功。""" - normalized_batch = str(batch_no or '').strip() - normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip())) - if bool(normalized_batch) == bool(normalized_tasks): - raise ValidationError('Provide exactly one of batch_no or task_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') - if normalized_batch: - batch = get_batch_for_user(normalized_batch, user_id) - if batch is None: - raise NotFoundError('Shipping batch not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') - tasks = list_sorted_batch_tasks(batch) - archive_key = normalized_batch - else: - tasks = [] - for task_no in normalized_tasks: - task = get_task_for_user(task_no, user_id) - if task is None: - raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') - tasks.append(task) - archive_key = 'selected' +def _select_tasks( + *, + user_id: int, + task_refs: list[str] | None, + selection_name: str, + require_business_no: bool = False, +) -> tuple[list[ShippingNotice], str]: + """按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。""" + normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip())) + if not normalized_tasks: + raise ValidationError(f'{selection_name} is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') + tasks = [] + for task_no in normalized_tasks: + task = get_task_for_user(task_no, user_id) + if task is None or ( + require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper() + ): + raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') + tasks.append(task) if not tasks: raise ValidationError('No shipping tasks selected', code='SHIPPING.EXPORT_ARCHIVE_EMPTY') if len(tasks) > MAX_ARCHIVE_TASKS: @@ -55,7 +49,7 @@ def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | N f'At most {MAX_ARCHIVE_TASKS} tasks can be downloaded at once', code='SHIPPING.EXPORT_ARCHIVE_TOO_LARGE', details={'max_tasks': MAX_ARCHIVE_TASKS}, ) - return tasks, archive_key + return tasks, 'selected' def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExportArtifact]]: @@ -92,7 +86,10 @@ def _archive_name(filename: str, task_no: str, used: set[str]) -> str: def build_export_archive( - *, user_id: int, batch_no: str | None = None, task_nos: list[str] | None = None, + *, + user_id: int, + task_nos: list[str] | None = None, + business_nos: list[str] | None = None, ) -> tuple[BinaryIO, str, dict]: """ 生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。 @@ -100,7 +97,16 @@ def build_export_archive( Returns: (定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。 """ - tasks, archive_key = _select_tasks(user_id=user_id, batch_no=batch_no, task_nos=task_nos) + if task_nos is not None and business_nos is not None: + raise ValidationError('select either task_nos or business_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') + selection_values = business_nos if business_nos is not None else task_nos + selection_name = 'business_nos' if business_nos is not None else 'task_nos' + tasks, archive_key = _select_tasks( + user_id=user_id, + task_refs=selection_values, + selection_name=selection_name, + require_business_no=business_nos is not None, + ) artifacts = _ready_artifacts(tasks) # 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。 stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b') @@ -129,7 +135,7 @@ def build_export_archive( included += 1 entries.append(entry) manifest = { - 'archive_version': 1, 'selection': {'batch_no': batch_no, 'task_nos': task_nos or []}, + 'archive_version': 1, 'selection': {selection_name: selection_values}, 'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks), 'included_count': included, 'excluded_count': len(entries) - included, 'entries': entries, } diff --git a/backend/app/services/shipping_notice/freight_cancellation_service.py b/backend/app/services/shipping_notice/freight_cancellation_service.py index ebe6a485..b7bf5c5e 100644 --- a/backend/app/services/shipping_notice/freight_cancellation_service.py +++ b/backend/app/services/shipping_notice/freight_cancellation_service.py @@ -1,10 +1,10 @@ """ services/shipping_notice/freight_cancellation_service.py -用途:货代撤销回执登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。 +用途:外部撤销确认登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。 依赖:ShippingFreightCancellation、ShippingNotice、ShippingTaskEvent、Workflow Item Version、 fulfillment_audit。 -逻辑:complete_freight_cancellation 登记回执并作废旧任务;mark_cancelled_task_readonly +逻辑:complete_freight_cancellation 登记外部撤销确认并作废旧任务;mark_cancelled_task_readonly 在用户取消已建单 WorkflowItem 时将 Task 置 pending_void、Excel/Version 只读, 并写前后快照审计。 """ @@ -24,19 +24,15 @@ def complete_freight_cancellation( *, cancellation_id: int, actor_id: int, - freight_receipt_no: str, - receipt_asset_id: int, note: str | None = None, ) -> ShippingFreightCancellation: """ - 登记可追溯的货代撤销回执,随后作废旧任务并解除新版本的履约阻断。 + 登记可追溯的外部撤销确认,随后作废旧任务并解除新版本的履约阻断。 Args: cancellation_id: 撤销单主键。 actor_id: 操作人。 - freight_receipt_no: 货代回执号。 - receipt_asset_id: 回执 FileAsset。 - note: 可选备注。 + note: 外部撤销确认原因,必填。 Returns: 更新后的 ShippingFreightCancellation。 @@ -46,9 +42,9 @@ def complete_freight_cancellation( raise NotFoundError('Freight cancellation not found', code='SHIPPING.FREIGHT_CANCELLATION_NOT_FOUND') if row.status == 'cancelled': return row - receipt = str(freight_receipt_no or '').strip() - if not receipt or not receipt_asset_id: - raise ValidationError('Cancellation receipt number and file are required', code='SHIPPING.FREIGHT_CANCELLATION_RECEIPT_REQUIRED') + confirmation_note = str(note or '').strip() + if not confirmation_note: + raise ValidationError('External cancellation confirmation note is required', code='SHIPPING.FREIGHT_CANCELLATION_CONFIRMATION_REQUIRED') old = ShippingNotice.query.filter_by(id=row.old_task_id).with_for_update().one() new = ShippingNotice.query.filter_by(id=row.new_task_id).with_for_update().one() if new.supersedes_task_id != old.id: @@ -56,9 +52,9 @@ def complete_freight_cancellation( row.status = 'cancelled' row.completed_by_id = int(actor_id) row.completed_at = datetime.utcnow() - row.freight_receipt_no = receipt - row.receipt_asset_id = int(receipt_asset_id) - row.failure_reason = str(note or '').strip() or None + row.freight_receipt_no = None + row.receipt_asset_id = None + row.failure_reason = confirmation_note old.lifecycle_status = 'voided' old.voided_at = datetime.utcnow() old.voided_by_id = int(actor_id) @@ -72,7 +68,7 @@ def complete_freight_cancellation( actor_id=actor_id, detail_json={ 'cancellation_id': row.id, - 'receipt_no': receipt, + 'confirmation_note': confirmation_note, 'new_task_no': new.task_no, 'reason_code': 'task_voided_for_correction', }, @@ -83,7 +79,7 @@ def complete_freight_cancellation( actor_id=actor_id, detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no}, )) - # 统一审计:货代回执登记必须可按 reason_code 检索 + # 统一审计:外部撤销确认必须可按 reason_code 检索。 record_fulfillment_audit( event_type='freight_cancellation_completed', aggregate_type='shipping_task', @@ -97,13 +93,13 @@ def complete_freight_cancellation( before={'lifecycle_status': 'active'}, after={ 'lifecycle_status': 'voided', - 'freight_receipt_no': receipt, + 'external_cancellation_confirmed': True, 'new_task_no': new.task_no, 'cancellation_id': int(row.id), }, metadata={ 'cancellation_id': int(row.id), - 'receipt_asset_id': int(receipt_asset_id), + 'confirmation_note': confirmation_note, 'new_task_no': str(new.task_no), }, source='workspace_api', diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index aefb6fbd..6d350a5e 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -7,12 +7,12 @@ services/shipping_notice/fulfillment_workflow.py tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、 order_task_stage_machine。 逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match; - STP 多候选:跨文件匹配后仅全部 ok 记 completed+100% 并自动 Excel;partial/冲突记 needs_human; + STP 多候选:跨文件匹配后仅全部 ok 记 completed+100%;partial 仍可按滚动库存生成已满足行 Excel; AUTO_UPLOAD 默认 false(须环境显式 true;缺失键 fail-closed 并告警); 开启时 Excel 后先做货代 RPA 就绪校验再触发(stage=upload_rpa_pending);关闭时停于人工上传; 工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件; - upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工凭据); - RPA 成功须带白名单 kind + page_url + dom_snippet/dom_sha256,并尽量落 evidence_asset; + upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工确认); + RPA 成功须带受信回调中的白名单状态信息;不保存截图、DOM 文件或证据资产; Excel 生成成功写路径清除 invalidated_from_stage(BE-02,禁止投影 GET 清库)。 """ @@ -124,10 +124,10 @@ def _normalize_rpa_success_evidence( expected_filename: str | None = None, ) -> dict[str, Any] | None: """ - 校验 RPA 成功回调中的 success_evidence(BE-05 fail-closed)。 + 校验 RPA 成功回调中的受信状态摘要(fail-closed)。 核心逻辑:kind 须在白名单;selector / observed_at / filename / page_url 必填; - 必须带 dom_snippet + 匹配的 dom_sha256(不可变 DOM 证据); + 必须带经 Worker 校验过的 selector、观察时间、文件名和页面定位; 若提供 expected_filename 则须与证据文件名一致(大小写不敏感)。 Args: @@ -137,8 +137,6 @@ def _normalize_rpa_success_evidence( Returns: 规范化 evidence dict;缺失/非法时 None。 """ - import hashlib - raw = payload.get('success_evidence') if not isinstance(raw, dict): return None @@ -155,16 +153,13 @@ def _normalize_rpa_success_evidence( return None if not dom_snippet or not dom_sha256: return None - # [BE-05] 片段与哈希必须自洽,防止 Worker 自报成功却无对应 DOM。 - computed = hashlib.sha256(dom_snippet.encode('utf-8')).hexdigest().lower() - if computed != dom_sha256: + import hashlib + if hashlib.sha256(dom_snippet.encode('utf-8')).hexdigest().lower() != dom_sha256: return None if expected_filename: expected = str(expected_filename).strip() if expected and filename.lower() != expected.lower(): return None - screenshot_sha256 = str(raw.get('screenshot_sha256') or '').strip().lower() or None - screenshot_base64 = str(raw.get('screenshot_base64') or '').strip() or None return { 'kind': kind, 'selector': selector, @@ -174,42 +169,22 @@ def _normalize_rpa_success_evidence( 'page_url': page_url, 'dom_snippet': dom_snippet[:8000], 'dom_sha256': dom_sha256, - 'screenshot_sha256': screenshot_sha256, - 'screenshot_base64': screenshot_base64, + 'screenshot_sha256': str(raw.get('screenshot_sha256') or '').strip().lower() or None, + 'screenshot_base64': str(raw.get('screenshot_base64') or '').strip() or None, } -def _persist_rpa_success_evidence_asset( - *, - task: 'ShippingNotice', - attempt: Any, - success_evidence: dict[str, Any], -) -> int | None: - """ - 将 RPA 成功 DOM/截图落为 FileAsset,并回写 attempt.evidence_asset_id。 - - 核心逻辑:优先截图 PNG;否则将脱敏 DOM 片段存为 .html;绑定后从 JSON 去掉 base64 大字段。 - - Args: - task: 发货 Notice。 - attempt: ShippingUploadAttempt。 - success_evidence: 已规范化证据(可含 screenshot_base64)。 - - Returns: - FileAsset.id;落库失败时 None(证据仍留在 success_evidence_json)。 - """ +def _persist_rpa_success_evidence_asset(*, task: 'ShippingNotice', attempt: Any, success_evidence: dict[str, Any]) -> int | None: + """将受信 RPA 的 DOM/可选截图保存为内部审计资产;人工上传路径不调用本函数。""" import base64 import hashlib - from app.models import FileAsset - from app.services.file_assets.service import generate_asset_no, _build_storage_key + from app.services.file_assets.service import generate_asset_no, _build_storage_key, mark_asset_referenced from app.services.file_assets.storage import file_asset_storage - from app.services.file_assets.service import mark_asset_referenced if not getattr(task, 'user_id', None): success_evidence.pop('screenshot_base64', None) return None - raw_b64 = str(success_evidence.pop('screenshot_base64', None) or '').strip() data: bytes | None = None filename = f"rpa-success-{int(attempt.id)}.html" @@ -220,41 +195,22 @@ def _persist_rpa_success_evidence_asset( except Exception: data = None if data: - filename = f"rpa-success-{int(attempt.id)}.png" - mime_type = 'image/png' + filename, mime_type = f"rpa-success-{int(attempt.id)}.png", 'image/png' if not data: - snippet = str(success_evidence.get('dom_snippet') or '').encode('utf-8') - if not snippet: - return None - data = snippet + data = str(success_evidence.get('dom_snippet') or '').encode('utf-8') or None + if not data: + return None content_hash = hashlib.sha256(data).hexdigest().lower() expected_shot = str(success_evidence.get('screenshot_sha256') or '').strip().lower() if expected_shot and filename.endswith('.png') and expected_shot != content_hash: return None asset_no = generate_asset_no() - storage_key = _build_storage_key( - user_id=int(task.user_id), - asset_no=asset_no, - filename=filename, - ) - asset = FileAsset( - asset_no=asset_no, - owner_user_id=int(task.user_id), - original_filename=filename, - parent_asset_id=None, - asset_role='rpa_success_evidence', - source_attachment_key=f'rpa-success:{int(attempt.id)}', - storage_provider='minio', - storage_bucket=file_asset_storage.bucket_name, - storage_key=storage_key, - content_hash=content_hash, - file_size=len(data), - mime_type=mime_type, - extension=filename.rsplit('.', 1)[-1], - upload_status='uploading', - lifecycle_status='temporary', - reference_count=0, - ) + storage_key = _build_storage_key(user_id=int(task.user_id), asset_no=asset_no, filename=filename) + asset = FileAsset(asset_no=asset_no, owner_user_id=int(task.user_id), original_filename=filename, + parent_asset_id=None, asset_role='rpa_success_evidence', source_attachment_key=f'rpa-success:{int(attempt.id)}', + storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, + content_hash=content_hash, file_size=len(data), mime_type=mime_type, extension=filename.rsplit('.', 1)[-1], + upload_status='uploading', lifecycle_status='temporary', reference_count=0) db.session.add(asset) db.session.flush() try: @@ -271,7 +227,6 @@ def _persist_rpa_success_evidence_asset( return int(asset.id) - def _hash_rpa_evidence_field(value: str | None) -> str | None: """对 evidence 中的 filename/reference 做 sha256,审计禁止落原文。""" if not value: @@ -628,9 +583,9 @@ def _sync_workflow_stage( def match_completed(task: ShippingNotice) -> bool: """ - STP 制单门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时允许生成 Excel。 + STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。 - 核心逻辑:禁止 partial / 任意一行短缺、冲突、未命中进入自动制单或 Excel 门禁。 + 核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。 """ from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision @@ -663,6 +618,52 @@ def match_completed(task: ShippingNotice) -> bool: return True +def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]: + """读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。""" + from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderSnapshot + from app.services.shipping_notice.export import _source_notice_for_order_facts + + source_notice = _source_notice_for_order_facts(task) + snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None + if snapshot is None or source_notice.id is None: + return set() + decisions = ( + ShippingOrderReviewLineDecision.query + .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) + .filter( + ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id), + ShippingOrderReviewLineDecision.is_active.is_(True), + ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', + ) + .all() + ) + released_indexes = { + int(decision.line_index) + for decision in decisions + if decision.line_index is not None + } + return { + int(line.id) + for index, line in enumerate(snapshot.lines) + if index in released_indexes + } + + +def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]: + """返回当前库存轮次可先行导出的冻结订单行;不代表整单已满足。""" + from app.services.shipping_notice.export import _source_notice_for_order_facts + from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids + + try: + _verification, line_ids = current_available_snapshot_line_ids( + _source_notice_for_order_facts(task), + released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task), + ) + except ConflictError: + return set() + return set(line_ids) + + def _match_step_progress_fields( *, match_status: str, @@ -708,7 +709,8 @@ def excel_gate_error(task: ShippingNotice) -> str | None: """校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。""" if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} and task.export_file_path: return None - if not match_completed(task): + # 滚动履约允许先导出当前完整满足/已审计放行的行;剩余短缺行继续保留在库存满足性 Gate。 + if not match_completed(task) and not exportable_snapshot_line_ids(task): return "workflow.fulfillment.excel_gate_unmatched" return None @@ -757,10 +759,10 @@ def try_auto_chain_after_match( tool_payload = merge_tool_payload(task, payload) - # [STEP 1] 低风险:匹配成功后自动生成 Excel。 + # [STEP 1] 低风险:存在可导出行时自动生成下一份滚动 Excel。 if _auto_generate_excel_enabled(): db.session.refresh(task) - if not task.export_file_path and match_completed(task): + if not task.export_file_path and excel_gate_error(task) is None: gen = generate_excel(tool_payload) if gen.get("status") != "ok": return gen @@ -904,6 +906,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, 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 @@ -1680,7 +1683,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: 基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。 【AI 触发时机】:本轮至少一个预约单完整满足且用户确认制单时调用;未匹配前禁止调用。 - 核心逻辑:已有导出文件时直接返回成功;否则走 excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。 + 核心逻辑:已有导出文件时直接返回成功;否则按当前可导出行通过 excel_gate_error,生成滚动 Excel;未满足行保留在库存满足性 Gate。 Args: payload: 须含 task_id 或 conversation_id。 @@ -1766,7 +1769,11 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids try: - _verification, available_line_ids = current_available_snapshot_line_ids(task) + from app.services.shipping_notice.export import _source_notice_for_order_facts + + _verification, available_line_ids = current_available_snapshot_line_ids( + _source_notice_for_order_facts(task), + ) except ConflictError: available_line_ids = set() if not available_line_ids: @@ -1780,7 +1787,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: ) # [STEP 2] 先校验是否满足导出门禁。 - # 只有库存匹配完成后才允许生成货代 Excel;但 waiting_upload/uploaded 仍应视为“已完成匹配”。 + # 只要当前库存轮次存在可导出行即可生成滚动 Excel;未满足行继续停留在库存满足性 Gate。 gate_error = excel_gate_error(task) if gate_error: return tool_response( @@ -1894,22 +1901,25 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: status="ok", task_id=task.task_no, message=t("workflow.fulfillment.generate_done", lang=lang).format(file=filename), - data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"}, + data={ + **serialize_task_for_tool(task), + "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export", + }, ) def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: """ - 货代上传入口:RPA 自动/重试,或人工凭据登记。 + 货代上传入口:RPA 自动/重试,或人工确认唯一 Excel 已上传。 【AI 触发时机】:AUTO_UPLOAD 开启且 Excel 就绪时可由 auto_progress 以 mode=auto 调用; - 人工接管后使用 mode=manual_confirm。 + 人工接管后使用 mode=manual_confirm;工作台对外必须先按 business_no 定位 Notice。 核心逻辑:mode=auto|retry_upload → 触发 RPA(受 AUTO_UPLOAD 与重试上限约束); - mode=manual_confirm → 校验凭据后标记 UPLOADED 并关闭 WorkflowItem。 + mode=manual_confirm → 校验唯一 Artifact 后标记 UPLOADED 并关闭 WorkflowItem。 Args: - payload: 须含 task_id;mode=auto|retry_upload|manual_confirm; - manual_confirm 须含 evidence_asset_no、operator_id。 + payload: 内部须含 task_id;mode=auto|retry_upload|manual_confirm; + manual_confirm 须含服务端可信 operator_id,不接收回执或截图/PDF。 Returns: dict[str, Any]: status 可为 ok / running / needs_human / failed。 @@ -1973,11 +1983,11 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: return tool_response( status='failed', task=task, - message='货代自动上传未开启,请人工下载 Excel 并登记上传凭据。', + message='货代自动上传未开启,请人工下载 Excel 并确认已上传。', data=serialize_task_for_tool(task), forbidden_next_tools=['upload_to_freight'], stop_agent_turn=True, - next_required_action='请在任务处理工作台使用「登记人工上传」。', + next_required_action='请在任务处理工作台使用「确认已上传」。', ) return _trigger_freight_upload_rpa( task, @@ -1995,16 +2005,12 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: ) operator_id = payload.get('operator_id') - evidence_asset_no = str(payload.get('evidence_asset_no') or '') - freight_ref_no = str(payload.get('freight_ref_no') or '') before_upload_status = str(task.upload_status or '') try: attempt = record_manual_upload( task, artifact_id=artifact_id, - evidence_asset_no=evidence_asset_no, operator_id=int(operator_id), - freight_ref_no=freight_ref_no, ) except (ConflictError, ValidationError, TypeError, ValueError) as exc: return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task)) @@ -2032,8 +2038,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: metadata={ 'attempt_id': attempt.id, 'artifact_id': attempt.artifact_id, - 'evidence_asset_no': evidence_asset_no, - 'freight_ref_no': freight_ref_no or None, }, source='workspace_api', sensitivity_level='sensitive', @@ -2072,7 +2076,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: 说明:本期主流程不触发货代 RPA 上传;本回调仅保留兼容,不应由业务主动调用。 核心逻辑:success=True → UPLOADED + freight_ref_no;失败 → UPLOAD_FAILED,达最大重试转人工。 - 缺省或非法 success **fail-closed 为失败**;success=True 必须带 success_evidence.kind。 + 缺省或非法 success **fail-closed 为失败**;success=True 必须带受信状态摘要。 Args: payload: 须含 task_id;success(bool,缺省视为失败);success_evidence(成功必填); @@ -2123,37 +2127,14 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: task=task, message=( 'RPA upload success requires success_evidence ' - '(kind whitelist, selector, observed_at, filename matching artifact, ' - 'page_url, dom_snippet+dom_sha256)' + '(kind whitelist, selector, observed_at, filename matching artifact and page_url)' ), data=serialize_task_for_tool(task), ) - # [BE-05] 结构化证据必须落 FileAsset;资产失败不得判定上传成功。 - evidence_asset_id = _persist_rpa_success_evidence_asset( - task=task, - attempt=attempt, - success_evidence=success_evidence, - ) - if evidence_asset_id is None: - return tool_response( - status='failed', - task=task, - message=( - 'RPA upload success requires persisted evidence asset ' - '(DOM/screenshot FileAsset); status remains recoverable' - ), - data={ - **serialize_task_for_tool(task), - 'upload_evidence_persist_failed': True, - }, - ) + if _persist_rpa_success_evidence_asset(task=task, attempt=attempt, success_evidence=success_evidence) is None: + return tool_response(status='failed', task=task, message='RPA upload success requires persisted internal audit asset', data=serialize_task_for_tool(task)) if hasattr(attempt, 'success_evidence_json'): - # 回调体中的 base64 已在 persist 时 pop;落库保留 snippet/哈希/asset 引用。 - attempt.success_evidence_json = { - key: value - for key, value in dict(success_evidence).items() - if key != 'screenshot_base64' - } + attempt.success_evidence_json = {key: value for key, value in dict(success_evidence).items() if key != 'screenshot_base64'} try: completed = complete_attempt( attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'), diff --git a/backend/app/services/shipping_notice/generic_order_gate.py b/backend/app/services/shipping_notice/generic_order_gate.py index a69571fc..fb1f7f32 100644 --- a/backend/app/services/shipping_notice/generic_order_gate.py +++ b/backend/app/services/shipping_notice/generic_order_gate.py @@ -22,6 +22,7 @@ from app.services.shipping_notice.generic_order_parser import ( parse_generic_orders, ) from app.services.shipping_notice.order_extraction_route_contract import GENERIC_GATE_POLICY_VERSION +from app.services.shipping_notice.generic_parse_plan import validate_generic_parse_plan @dataclass(frozen=True) @@ -49,6 +50,9 @@ def evaluate_generic_extraction_gate( schema: dict[str, Any], intake: dict[str, Any], unit: Any, + parse_plan: dict[str, Any] | None = None, + layout_snapshot: dict[str, Any] | None = None, + require_parse_plan: bool = False, ) -> GenericGateResult: """ 执行通用解析并评估完整性门禁;fail-closed 于未映射列、未知行、多 PO/客户、续行与必填字段缺失。 @@ -68,13 +72,28 @@ def evaluate_generic_extraction_gate( Returns: GenericGateResult;passed 为 True 时 parse_result.orders 非空。 """ - completeness = build_generic_completeness_report(candidates) + # 生产工作流必须传入冻结 Plan;保留无 Plan 参数的纯函数调用,供已有诊断和 + # 单元测试直接评估候选完整性,不把它接入自动建单路径。 + plan_validation = None + effective_candidates = candidates + if parse_plan is not None or require_parse_plan: + plan_validation = validate_generic_parse_plan( + plan=parse_plan, + schema_checksum=str(schema.get('checksum') or ''), + layout_snapshot=layout_snapshot or {}, + runtime_candidates=candidates, + ) + effective_candidates = plan_validation.candidates + completeness = build_generic_completeness_report(effective_candidates) gate_codes: list[str] = [] stable_codes: list[str] = [] + if plan_validation is not None and not plan_validation.passed: + gate_codes.extend(plan_validation.reason_codes) + gate_codes.extend(_completeness_gate_codes(completeness)) parse_result = parse_generic_orders( - candidates=candidates, + candidates=effective_candidates, definition=definition, schema=schema, intake=intake, @@ -83,7 +102,7 @@ def evaluate_generic_extraction_gate( if parse_result.reason_code: stable_codes.append(parse_result.reason_code) - customer_values = collect_customer_field_values(candidates, definition=definition) + customer_values = collect_customer_field_values(effective_candidates, definition=definition) if len(customer_values) > 1: gate_codes.append('multiple_customer') stable_codes.append('generic_gate_blocked') diff --git a/backend/app/services/shipping_notice/generic_parse_plan.py b/backend/app/services/shipping_notice/generic_parse_plan.py new file mode 100644 index 00000000..1f571a5f --- /dev/null +++ b/backend/app/services/shipping_notice/generic_parse_plan.py @@ -0,0 +1,137 @@ +""" +services/shipping_notice/generic_parse_plan.py + +用途:将自动标注的 layout_schema_candidates 编译为 Run 冻结的通用解析计划。 +依赖:冻结 Schema、Layout candidate 与 schema_mapping 的 cell 级证据。 +逻辑:候选映射只可作为 Plan 输入;生产通用解析必须先校验 Plan 的 Schema、Layout、 + 候选和字段证据身份,不能直接把运行时候选当作业务事实。 +""" + +from __future__ import annotations + +import hashlib +import json +from copy import deepcopy +from dataclasses import dataclass +from typing import Any + + +GENERIC_PARSE_PLAN_VERSION = 'generic_parse_plan.v1' + + +def _checksum(payload: Any) -> str: + """生成稳定 JSON checksum;Plan 身份不得依赖字典插入顺序。""" + encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str) + return hashlib.sha256(encoded.encode('utf-8')).hexdigest() + + +def layout_checksum(layout_snapshot: dict[str, Any]) -> str | None: + """提取结构 Layout 身份;按需坐标补全不应改变已冻结的版面身份。""" + candidate = layout_snapshot.get('layout_candidate') if isinstance(layout_snapshot, dict) else None + return _checksum(candidate) if isinstance(candidate, dict) else None + + +def _field_evidence_errors(candidates: list[dict[str, Any]]) -> list[str]: + """校验每个将进入订单的字段都能回溯到冻结 Layout cell 证据。""" + errors: list[str] = [] + for table_index, table in enumerate(candidates): + if not isinstance(table, dict): + errors.append(f'table:{table_index}:invalid') + continue + for row in table.get('rows') or []: + if not isinstance(row, dict) or str(row.get('role') or '') != 'data': + continue + for field in row.get('fields') or []: + if not isinstance(field, dict) or field.get('value') in (None, ''): + continue + if not field.get('field_id'): + errors.append(f'table:{table_index}:field_id_missing') + if not field.get('evidence_ref') or not field.get('cell_id'): + errors.append(f'table:{table_index}:field_evidence_missing') + return sorted(set(errors)) + + +def compile_generic_parse_plan( + *, + candidates: list[dict[str, Any]], + schema_checksum: str, + layout_snapshot: dict[str, Any], +) -> dict[str, Any]: + """ + 将自动标注候选编译为可冻结 Parse Plan。 + + 自动标注本身不具有生产资格。该函数只记录候选的输入身份和字段证据,后续仍由 + generic_order_gate 检查表/行完整性、必填字段和业务冲突。 + """ + # Plan 冻结前仍在同一 Worker 内构建订单;不得借深拷贝把 Decimal/date 等 + # 业务值提前变成字符串,JSON 落库阶段由 Run 的统一冻结器处理。 + copied = deepcopy(candidates if isinstance(candidates, list) else []) + source_statuses = [ + str(item.get('mapping_status') or 'candidate') + for item in copied if isinstance(item, dict) + ] + errors = _field_evidence_errors(copied) + if not str(schema_checksum or '').strip(): + errors.append('schema_checksum_missing') + resolved_layout_checksum = layout_checksum(layout_snapshot) + if not resolved_layout_checksum: + errors.append('layout_checksum_missing') + if any(status not in {'accepted', 'candidate'} for status in source_statuses): + errors.append('mapping_status_unqualified') + payload = { + 'version': GENERIC_PARSE_PLAN_VERSION, + 'schema_checksum': str(schema_checksum or ''), + 'layout_checksum': resolved_layout_checksum, + 'candidates': copied, + 'candidate_checksum': _checksum(copied), + 'mapping_decisions': [{ + 'page_no': item.get('page_no'), 'table_id': item.get('table_id'), + 'source_mapping_status': str(item.get('mapping_status') or 'candidate'), + 'decision': 'auto_qualified' if str(item.get('mapping_status') or 'candidate') in {'accepted', 'candidate'} else 'rejected', + } for item in copied if isinstance(item, dict)], + 'evidence_errors': sorted(set(errors)), + } + payload['status'] = 'qualified' if not payload['evidence_errors'] else 'rejected' + payload['checksum'] = _checksum(payload) + return payload + + +@dataclass(frozen=True) +class GenericParsePlanValidation: + """生产 Gate 使用的 Parse Plan 校验结论。""" + + passed: bool + reason_codes: list[str] + candidates: list[dict[str, Any]] + + +def validate_generic_parse_plan( + *, + plan: Any, + schema_checksum: str, + layout_snapshot: dict[str, Any], + runtime_candidates: list[dict[str, Any]] | None = None, +) -> GenericParsePlanValidation: + """验证冻结 Plan 未被 Schema、Layout 或候选映射漂移污染。""" + if not isinstance(plan, dict): + return GenericParsePlanValidation(False, ['generic_parse_plan_missing'], []) + candidates = plan.get('candidates') if isinstance(plan.get('candidates'), list) else [] + reasons: list[str] = [] + if str(plan.get('version') or '') != GENERIC_PARSE_PLAN_VERSION: + reasons.append('generic_parse_plan_version_invalid') + payload = {key: value for key, value in plan.items() if key != 'checksum'} + if str(plan.get('checksum') or '') != _checksum(payload): + reasons.append('generic_parse_plan_checksum_invalid') + if str(plan.get('status') or '') != 'qualified': + reasons.append('generic_parse_plan_unqualified') + if str(plan.get('schema_checksum') or '') != str(schema_checksum or ''): + reasons.append('generic_parse_plan_schema_changed') + if str(plan.get('layout_checksum') or '') != str(layout_checksum(layout_snapshot) or ''): + reasons.append('generic_parse_plan_layout_changed') + if str(plan.get('candidate_checksum') or '') != _checksum(candidates): + reasons.append('generic_parse_plan_candidate_changed') + if runtime_candidates is not None and _checksum(runtime_candidates) != str(plan.get('candidate_checksum') or ''): + reasons.append('generic_parse_plan_runtime_candidate_changed') + if plan.get('evidence_errors'): + reasons.append('generic_parse_plan_evidence_missing') + return GenericParsePlanValidation(not reasons, sorted(set(reasons)), candidates) diff --git a/backend/app/services/shipping_notice/intake_service.py b/backend/app/services/shipping_notice/intake_service.py index 15e975fc..5e6d5f59 100644 --- a/backend/app/services/shipping_notice/intake_service.py +++ b/backend/app/services/shipping_notice/intake_service.py @@ -172,6 +172,7 @@ def serialize_intake( *, asset: FileAsset | None = None, include_parse_texts: bool = False, + include_candidate_details: bool = True, ) -> dict[str, Any]: """ 对外序列化接入记录(含业务摘要、Document/Candidate 与重复检测)。 @@ -179,6 +180,8 @@ def serialize_intake( Args: include_parse_texts: True 时返回 structured 中的附件全文/正文(详情接口), 并附带 documents 全文;False 时返回瘦身 parse_summary 与精简 documents/candidates。 + include_candidate_details: False 时仅返回恢复输入状态所需的 Candidate 字段, + 避免活跃列表传输 evidence / field_adjudication 等重型审核数据。 """ from app.services.shipping_notice.document_candidate_persist import ( list_intake_candidates, @@ -198,7 +201,10 @@ def serialize_intake( } parse_summary = structured if include_parse_texts else _lean_parse_summary(structured) documents = list_intake_documents(int(intake.id), include_text=include_parse_texts) - candidates = list_intake_candidates(int(intake.id)) + candidates = list_intake_candidates( + int(intake.id), + include_details=include_candidate_details, + ) layout_summary = _serialize_intake_layout_summary(int(intake.id)) payload: dict[str, Any] = { 'intake_no': intake.intake_no, @@ -571,7 +577,14 @@ def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | if conv: query = query.filter(ShippingOrderIntake.conversation_id == conv) rows = query.order_by(ShippingOrderIntake.created_at.desc()).limit(50).all() - return [serialize_intake(intake, asset=asset) for intake, asset in rows] + return [ + serialize_intake( + intake, + asset=asset, + include_candidate_details=False, + ) + for intake, asset in rows + ] def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str, Any]]: @@ -588,7 +601,14 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str ) .all() ) - return [serialize_intake(intake, asset=asset) for intake, asset in rows] + return [ + serialize_intake( + intake, + asset=asset, + include_candidate_details=False, + ) + for intake, asset in rows + ] def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]: diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index a3de3664..8e34636c 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -1,7 +1,7 @@ """ services/shipping_notice/inventory_file_store.py -用途:管理货代发货批次级库存快照文件、任务 link 与解析结果投影。 +用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。 依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。 逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。 """ @@ -30,8 +30,6 @@ from app.services.shipping_notice.inventory_source_gate import ( task_inventory_identity, ) from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version -from app.services.shipping_notice.query_service import list_sorted_batch_tasks - def _can_relink_inventory(task: ShippingNotice) -> bool: """判断任务是否允许被新的批次库存快照影响;终态任务不能回退。""" return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \ @@ -228,13 +226,13 @@ def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> ) -def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile: +def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile: """ - 保存库存 Excel 并创建批次级库存快照。 + 保存库存 Excel 并创建任务级库存快照。 - 【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。 + 【AI 触发时机】:用户为当前发货任务上传库存快照时调用。 核心逻辑:文件必须通过库存站点 published 解析方案的结构门禁并完成确定性解析; - 快照须携带任务正式库存源身份,批次 link 仅覆盖与上传票库存源一致的可重链任务。 + 快照须携带任务正式库存源身份,只绑定当前任务。 """ if not is_inventory_source_stable(task): raise AppError( @@ -360,7 +358,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh ) raise AppError( code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", - message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝批次绑定", + message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝快照绑定", http_status=409, ) created_links.append(link) diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index 65636141..a734c743 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -18,13 +18,10 @@ from app.services.shipping_notice.constants import ( CP_INVENTORY_SOURCE_REVIEW, ) from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response -from app.services.shipping_notice.inventory_file_store import ( - save_batch_inventory_upload, -) +from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload from app.services.shipping_notice.query_service import ( get_task_by_ref, resolve_task_from_payload, - serialize_batch_for_tool, serialize_task_for_tool, ) from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues @@ -176,7 +173,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: detail=t("workflow.inventory.uploading_detail", lang=lang).format(filename=filename), ) db.session.flush() - inv_file = save_batch_inventory_upload(task, upload) + inv_file = save_task_inventory_upload(task, upload) inventory_lines = [ item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict) ] @@ -220,7 +217,6 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: { "inventory_file_no": inv_file.inventory_file_no, "share_mode": inv_file.share_mode, - "batch_no": None, }, ) return inventory_loaded_response( 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 deleted file mode 100644 index a8c5ca75..00000000 --- a/backend/app/services/shipping_notice/legacy_stp_job_admin_service.py +++ /dev/null @@ -1,297 +0,0 @@ -""" -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/legacy_supplement_conflict_reassessment_service.py b/backend/app/services/shipping_notice/legacy_supplement_conflict_reassessment_service.py new file mode 100644 index 00000000..f800a0eb --- /dev/null +++ b/backend/app/services/shipping_notice/legacy_supplement_conflict_reassessment_service.py @@ -0,0 +1,296 @@ +""" +services/shipping_notice/legacy_supplement_conflict_reassessment_service.py + +用途:将历史邮件正文补充冲突升级为可展示、可追溯的统一 Finding,并重算 Candidate 资格。 +依赖:ShippingOrderCandidate/Run、candidate_qualification_service、fulfillment_audit。 +逻辑:历史 `{field, reason}` 没有双方值或证据,不能猜测为已解决;本服务仅将其转为 + `supplement_conflict_evidence_insufficient`,保留 blocking 门禁并给出重新识别恢复入口。 + 已含 conflict_key 的新 Finding 不改写;真实值比较仍由冻结输入的新解析链负责。 +""" + +from __future__ import annotations + +from typing import Any + +from app.extensions import db +from app.models import ( + ShippingOrderCandidate, + ShippingOrderProcessingPlan, + ShippingOrderProcessingRun, + ShippingOrderProcessingUnit, +) +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.order_supplement_merge import merge_email_supplements + + +_LEGACY_REASON = 'supplement_field_conflict' +_EVIDENCE_GAP_REASON = 'supplement_conflict_evidence_insufficient' + + +def _legacy_finding_key(item: dict[str, Any]) -> str: + """为无法复原证据的旧 Finding 生成稳定键,避免继续以无键记录阻断。""" + field = str(item.get('field') or 'unknown_field').strip() or 'unknown_field' + try: + line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1 + except (TypeError, ValueError): + line_index = -1 + return f'{line_index}:{field}' + + +def is_legacy_supplement_conflict(item: Any) -> bool: + """判断记录是否是没有稳定裁决身份与双方证据的历史正文补充冲突。""" + return ( + isinstance(item, dict) + and str(item.get('reason') or '').strip() == _LEGACY_REASON + and not str(item.get('conflict_key') or '').strip() + ) + + +def upgrade_legacy_supplement_conflicts(conflicts: Any) -> tuple[list[Any], int]: + """ + 将旧简略冲突升级为统一证据缺失 Finding。 + + 核心逻辑:旧记录仅有字段与原因,缺失 PDF/EML 原值、document_id、evidence_ref, + 无法安全裁决或判定为格式等价;因此保持 fail-closed,但使 Case 显示明确恢复动作。 + + Returns: + (升级后的冲突列表, 本次升级数量)。 + """ + source = list(conflicts or []) if isinstance(conflicts, list) else [] + upgraded: list[Any] = [] + changed = 0 + seen_keys: set[str] = set() + for item in source: + if not is_legacy_supplement_conflict(item): + upgraded.append(item) + if isinstance(item, dict): + key = str(item.get('conflict_key') or '').strip() + if key: + seen_keys.add(key) + continue + key = _legacy_finding_key(item) + if key in seen_keys: + changed += 1 + continue + seen_keys.add(key) + field = str(item.get('field') or 'unknown_field').strip() or 'unknown_field' + try: + line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1 + except (TypeError, ValueError): + line_index = -1 + upgraded.append({ + 'conflict_key': key, + 'severity': 'blocking', + 'reason': _EVIDENCE_GAP_REASON, + 'resolution_status': 'unresolved', + 'field': field, + 'scope': str(item.get('scope') or 'unscoped'), + 'line_index': line_index if line_index >= 0 else None, + 'values': [], + 'sources': [], + 'rule_version': 'legacy-supplement-conflict.v1', + 'legacy_reason': _LEGACY_REASON, + 'recovery_action': 'reparse_current_pdf', + }) + changed += 1 + return upgraded, changed + + +def _without_legacy_supplement_conflicts(conflicts: Any) -> list[Any]: + """去除待重建的旧 Finding,保留其他解析/业务门禁。""" + return [ + item for item in (conflicts or []) + if not is_legacy_supplement_conflict(item) + ] if isinstance(conflicts, list) else [] + + +def _supplement_findings(conflicts: Any) -> list[dict[str, Any]]: + """从重算订单结果读取当前正文补充 Finding,不借用其他门禁事实。""" + return [ + item for item in (conflicts or []) + if isinstance(item, dict) + and str(item.get('reason') or '').strip() == _LEGACY_REASON + ] if isinstance(conflicts, list) else [] + + +def reassess_legacy_supplement_conflicts_from_frozen_order( + *, + candidate_conflicts: Any, + frozen_order: Any, + supplements_by_intake: Any, + schema_definition: Any, +) -> tuple[list[Any], str, int]: + """ + 使用冻结订单和邮件补充事实按当前合并规则重算旧冲突。 + + Returns: + (新冲突, rebuilt|evidence_insufficient|not_applicable, 处理的旧记录数)。 + """ + legacy_count = sum(1 for item in (candidate_conflicts or []) if is_legacy_supplement_conflict(item)) \ + if isinstance(candidate_conflicts, list) else 0 + if not legacy_count: + return list(candidate_conflicts or []) if isinstance(candidate_conflicts, list) else [], 'not_applicable', 0 + if not ( + isinstance(frozen_order, dict) + and isinstance(supplements_by_intake, dict) + and isinstance(schema_definition, dict) + and isinstance(schema_definition.get('fields'), list) + ): + upgraded, _ = upgrade_legacy_supplement_conflicts(candidate_conflicts) + return upgraded, 'evidence_insufficient', legacy_count + replay_order = dict(frozen_order) + replay_order['conflicts'] = _without_legacy_supplement_conflicts(replay_order.get('conflicts')) + try: + rebuilt_order = merge_email_supplements( + orders=[replay_order], + supplements_by_intake=supplements_by_intake, + schema_definition=schema_definition, + )[0] + except (TypeError, ValueError): + upgraded, _ = upgrade_legacy_supplement_conflicts(candidate_conflicts) + return upgraded, 'evidence_insufficient', legacy_count + # Candidate 的非补充门禁由其自身持有;只用重算结果替换旧正文补充项。 + preserved = _without_legacy_supplement_conflicts(candidate_conflicts) + rebuilt = _supplement_findings(rebuilt_order.get('conflicts')) + return [*preserved, *rebuilt], 'rebuilt', legacy_count + + +def _frozen_reassessment_inputs( + *, candidate: ShippingOrderCandidate, run: ShippingOrderProcessingRun | None, +) -> tuple[dict[str, Any] | None, dict[int, dict[str, Any]] | None, dict[str, Any] | None]: + """按 Candidate 所属 Unit 定位冻结订单、邮件补充与 Schema;歧义时拒绝猜测。""" + if run is None: + return None, None, None + snapshot = run.input_snapshot_json if isinstance(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 None + supplements = { + int(intake.get('intake_id') or 0): supplement + for intake in snapshot.get('intakes') or [] if isinstance(intake, dict) + for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict) + if int(intake.get('intake_id') or 0) > 0 + } + units = ( + ShippingOrderProcessingUnit.query + .join(ShippingOrderProcessingPlan, ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id) + .filter( + ShippingOrderProcessingPlan.run_id == int(run.id), + ShippingOrderProcessingUnit.document_id == int(candidate.primary_document_id), + ) + .order_by(ShippingOrderProcessingUnit.id.asc()) + .all() + ) + if len(units) != 1: + return None, supplements, definition + orders = (units[0].result_json or {}).get('orders') if isinstance(units[0].result_json, dict) else None + if not isinstance(orders, list): + return None, supplements, definition + index = candidate.source_order_index + if isinstance(index, int) and 0 <= index < len(orders) and isinstance(orders[index], dict): + return dict(orders[index]), supplements, definition + exact = [ + item for item in orders + if isinstance(item, dict) + and int(item.get('primary_document_id') or 0) == int(candidate.primary_document_id) + ] + return (dict(exact[0]) if len(exact) == 1 else None), supplements, definition + + +def reassess_legacy_supplement_conflicts( + *, + actor_id: int, + request_id: str | None = None, + candidate_no: str | None = None, + run_no: str | None = None, + include_all: bool = False, +) -> dict[str, Any]: + """ + 对指定范围的旧正文补充冲突执行一次可审计重评估。 + + AI 触发时机:仅管理员确认历史数据修复时调用;普通用户保存草稿或读取 Case 不调用。 + 范围必须指定 Candidate、Run,或显式 include_all,避免误触发全量写操作。 + """ + normalized_candidate_no = str(candidate_no or '').strip().upper() or None + normalized_run_no = str(run_no or '').strip().upper() or None + if not (normalized_candidate_no or normalized_run_no or include_all): + raise ValueError('candidate_no, run_no, or include_all is required') + + query = ShippingOrderCandidate.query.filter(ShippingOrderCandidate.is_current_version.is_(True)) + if normalized_candidate_no: + query = query.filter(ShippingOrderCandidate.candidate_no == normalized_candidate_no) + if normalized_run_no: + query = query.join( + ShippingOrderProcessingRun, + ShippingOrderProcessingRun.id == ShippingOrderCandidate.order_extraction_run_id, + ).filter(ShippingOrderProcessingRun.run_no == normalized_run_no) + + report = { + 'scanned_count': 0, + 'legacy_conflict_candidate_count': 0, + 'upgraded_finding_count': 0, + 'qualification_recalculated_count': 0, + 'candidate_nos': [], + 'scope': { + 'candidate_no': normalized_candidate_no, + 'run_no': normalized_run_no, + 'include_all': bool(include_all), + }, + } + for candidate in query.with_for_update().all(): + report['scanned_count'] += 1 + legacy_count = sum( + 1 for item in (candidate.conflicts_json or []) if is_legacy_supplement_conflict(item) + ) if isinstance(candidate.conflicts_json, list) else 0 + if not legacy_count: + continue + run = ( + db.session.get(ShippingOrderProcessingRun, int(candidate.order_extraction_run_id)) + if candidate.order_extraction_run_id else None + ) + frozen_order, supplements, definition = _frozen_reassessment_inputs(candidate=candidate, run=run) + after_conflicts, reassessment_status, changed = reassess_legacy_supplement_conflicts_from_frozen_order( + candidate_conflicts=candidate.conflicts_json, + frozen_order=frozen_order, + supplements_by_intake=supplements, + schema_definition=definition, + ) + before = {'legacy_supplement_conflict_count': legacy_count} + candidate.conflicts_json = after_conflicts + report['legacy_conflict_candidate_count'] += 1 + if reassessment_status == 'evidence_insufficient': + report['upgraded_finding_count'] += changed + else: + report.setdefault('rebuilt_candidate_count', 0) + report['rebuilt_candidate_count'] += 1 + report['candidate_nos'].append(str(candidate.candidate_no)) + recalculate_candidate_qualification( + candidate=candidate, + run=run, + evaluated_by_id=actor_id, + request_id=request_id, + ) + report['qualification_recalculated_count'] += 1 + record_fulfillment_audit( + event_type='legacy_supplement_conflict_reassessed', + aggregate_type='shipping_notice_candidate', + aggregate_id=str(candidate.candidate_no), + action='reassess_legacy_supplement_conflict', + actor_type='admin', + actor_id=actor_id, + run_no=str(run.run_no) if run is not None else None, + reason_code=_EVIDENCE_GAP_REASON, + before=before, + after={ + 'reassessment_status': reassessment_status, + 'replaced_legacy_finding_count': changed, + 'remaining_supplement_finding_count': len(_supplement_findings(after_conflicts)), + 'recovery_action': 'reparse_current_pdf' if reassessment_status == 'evidence_insufficient' else None, + }, + metadata={'request_id': request_id, 'migration_version': 'legacy-supplement-conflict.v1'}, + source='legacy_supplement_conflict_reassessment', + ) + report['candidate_nos'].sort() + return report diff --git a/backend/app/services/shipping_notice/lifecycle_projection.py b/backend/app/services/shipping_notice/lifecycle_projection.py index 6ba2cc8c..7b702675 100644 --- a/backend/app/services/shipping_notice/lifecycle_projection.py +++ b/backend/app/services/shipping_notice/lifecycle_projection.py @@ -1,9 +1,9 @@ """ services/shipping_notice/lifecycle_projection.py -用途:为批次进度、任务详情与订单生命周期工作台裁决同一份四阶段业务生命周期。 -依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。 -逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。 +用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。 +依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。 +逻辑:正式 Process Gate 优先,其次是可解释阻断原因;无正式事实时保持未分类。 本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。 """ @@ -18,6 +18,7 @@ LIFECYCLE_STAGES: tuple[dict[str, str], ...] = ( {'code': 'intake_parse', 'label': '接收解析'}, {'code': 'order_review', 'label': '订单复核'}, {'code': 'fulfillment_prep', 'label': '通知准备'}, + {'code': 'freight_upload', 'label': '货代上传'}, {'code': 'upload_complete', 'label': '通知完成'}, ) @@ -43,26 +44,33 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = { 'inventory_sufficiency': 'fulfillment_prep', 'excel_readiness': 'fulfillment_prep', 'artifact_generation': 'fulfillment_prep', - 'freight_upload_rpa': 'upload_complete', - 'manual_upload_handoff': 'upload_complete', + 'freight_upload_rpa': 'freight_upload', + 'manual_upload_handoff': 'freight_upload', } -# 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。 -LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = ( - ('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}), - ('order_review', { - 'customer_resolving', 'duplicate_checking', 'order_creating', 'review_required', - 'waiting_review', 'waiting_human_review', 'waiting_human', 'pre_ot_stp', 'order_review', - }), - ('fulfillment_prep', { - 'inventory_source_resolving', 'inventory_fetching', 'inventory_fetch', 'inventory_preparation', - 'inventory_candidates_calculated', 'inventory_candidates_frozen', 'inventory_snapshots_ready', - 'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating', - 'excel_generate', 'excel_generated', - }), - ('upload_complete', {'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'completed'}), -) - +# 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于 +# 读模型展示,不推进订单、不创建任务,也不授予任何动作。正式 Gate 仍在 +# 技术阶段缺失时提供兜底,避免历史数据被无条件覆盖。 +LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { + 'upload_received': 'intake_parse', + 'email_parsing': 'intake_parse', + 'document_parsing': 'intake_parse', + 'email_adjudicating': 'intake_parse', + 'candidate_creating': 'intake_parse', + 'waiting_review': 'order_review', + 'customer_resolving': 'order_review', + 'duplicate_checking': 'order_review', + 'inventory_source_resolving': 'order_review', + 'order_creating': 'fulfillment_prep', + 'inventory_fetching': 'fulfillment_prep', + 'inventory_preparation': 'fulfillment_prep', + 'inventory_matching': 'fulfillment_prep', + 'inventory_sufficiency': 'fulfillment_prep', + 'excel_generating': 'fulfillment_prep', + 'freight_uploading': 'freight_upload', + 'manual_upload_handoff': 'freight_upload', + 'completed': 'upload_complete', +} def lifecycle_entries( *, @@ -101,19 +109,32 @@ def project_lifecycle( *, current_gate: dict[str, Any] | None, blocking_reason: dict[str, Any] | None, - legacy_stage: str | None, has_candidate_context: bool, has_intake_parse_context: bool = False, + verified_upload_success: bool = False, + processing_stage: str | None = None, ) -> dict[str, Any]: - """按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。 + """按成功事实 → Gate → 已持久化阶段 → 阻断归属的固定优先级裁决生命周期。 - ``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。 + ``processing_stage`` 是订单处理流程已写入的事实,仅映射展示工作面;它不能 + 授权动作或推进流程。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算 + 阶段或放开按钮。 """ gate = current_gate if isinstance(current_gate, dict) else {} gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower() - if gate_code in LIFECYCLE_STAGE_BY_GATE: + # 成功事实高于当前 Gate/历史阶段:异步回调成功后旧 Gate 尚未清理时,用户仍应 + # 看到已完成;反之任何技术完成、回执文本或旧 completed 都不能越过此条件。 + if verified_upload_success: + lifecycle_stage = 'upload_complete' + authority = 'verified_upload_success' + elif gate_code in LIFECYCLE_STAGE_BY_GATE: lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code] authority = 'process_gate' + elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE: + lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[ + str(processing_stage or '').strip().lower() + ] + authority = 'processing_stage' else: reason = blocking_reason if isinstance(blocking_reason, dict) else {} reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip() @@ -122,12 +143,8 @@ def project_lifecycle( lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[owning_gate] authority = 'blocking_reason' else: - normalized_legacy = str(legacy_stage or '').strip().lower() - lifecycle_stage = next( - (code for code, aliases in LIFECYCLE_STAGE_RANGES if normalized_legacy in aliases), - normalized_legacy if normalized_legacy in LIFECYCLE_STAGE_CODES else None, - ) - authority = 'legacy_fallback' if lifecycle_stage else 'unclassified' + lifecycle_stage = None + authority = 'unclassified' return { 'lifecycle_stage': lifecycle_stage, 'lifecycle_entries': lifecycle_entries( diff --git a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py index 8cf9316f..973b9d34 100644 --- a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py +++ b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py @@ -26,6 +26,9 @@ from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( create_post_ot_fulfillment_wave, list_eligible_post_ot_line_keys, ) +from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + project_review_case_line_decisions, +) from app.services.shipping_notice.post_ot_wave_progress_service import schedule_post_ot_wave_progress @@ -114,6 +117,12 @@ def coordinate_post_ot_auto_fulfill( } eligible = list_eligible_post_ot_line_keys(case) + projection = project_review_case_line_decisions(case) + unassigned = [ + str(item.get('line_key') or '') + for item in list(projection.get('lines') or []) + if str(item.get('line_status') or '') not in {'task_created', 'fulfilled', 'closed_unfulfillable'} + ] if not eligible: return { 'status': 'idle', @@ -122,6 +131,16 @@ def coordinate_post_ot_auto_fulfill( 'case_no': case.case_no, 'accepted_line_keys': [], } + # [STEP] 自动制单只处理唯一开放明细。多条明细必须由用户勾选后合并, + # 绝不静默替用户决定 Notice 的合并范围。 + if len(eligible) != 1 or set(eligible) != set(unassigned): + return { + 'status': 'idle', + 'reason': 'manual_wave_selection_required', + 'trigger': trigger, + 'case_no': case.case_no, + 'accepted_line_keys': [], + } idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}' try: diff --git a/backend/app/services/shipping_notice/notice_line_service.py b/backend/app/services/shipping_notice/notice_line_service.py index b4a6dfd6..f52632cf 100644 --- a/backend/app/services/shipping_notice/notice_line_service.py +++ b/backend/app/services/shipping_notice/notice_line_service.py @@ -14,13 +14,19 @@ from app import db from app.models import ShippingNoticeLine, ShippingOrderSnapshot -def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrderSnapshot) -> int: +def replace_notice_lines_from_snapshot( + *, + notice_id: int, + snapshot: ShippingOrderSnapshot, + snapshot_line_ids: set[int] | None = None, +) -> int: """ 用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。 Args: notice_id: shipping_notices.id。 snapshot: 已 flush 且带 lines 的 Snapshot。 + snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。 Returns: 写入行数。 @@ -28,7 +34,10 @@ def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrde db.session.query(ShippingNoticeLine).filter_by(notice_id=int(notice_id)).delete(synchronize_session=False) now = datetime.utcnow() rows: list[ShippingNoticeLine] = [] + selected_ids = {int(item) for item in (snapshot_line_ids or set())} for line in list(snapshot.lines or []): + if selected_ids and int(line.id) not in selected_ids: + continue rows.append( ShippingNoticeLine( notice_id=int(notice_id), diff --git a/backend/app/services/shipping_notice/open_existing_reservation_backfill.py b/backend/app/services/shipping_notice/open_existing_reservation_backfill.py index df24e08c..63da9d40 100644 --- a/backend/app/services/shipping_notice/open_existing_reservation_backfill.py +++ b/backend/app/services/shipping_notice/open_existing_reservation_backfill.py @@ -1,9 +1,9 @@ """ backend/app/services/shipping_notice/open_existing_reservation_backfill.py -用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到旧任务(兼容入口)。 +用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到既有任务。 依赖:task_candidate_reconciliation、tool_common。 -逻辑:batch_from_intakes 仍调用本模块;内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。 +逻辑:内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/order_auto_freeze_execution.py b/backend/app/services/shipping_notice/order_auto_freeze_execution.py deleted file mode 100644 index 7634bd94..00000000 --- a/backend/app/services/shipping_notice/order_auto_freeze_execution.py +++ /dev/null @@ -1,353 +0,0 @@ -""" -services/shipping_notice/order_auto_freeze_execution.py - -用途:消费 Run 级自动冻结门禁摘要,把当前 Run 已接受的候选订单落成 Task 并冻结为 Snapshot。 -依赖:Run/Candidate/Task 模型、候选建批编排与订单冻结服务。 -逻辑:只有当 run.auto_freeze_policy_json 已明确放行时才执行;执行范围严格限定在当前 Run, - 建单与冻结均只处理本轮 eligible 的 accepted + selected 候选集合,禁止扩大到 Run 内其它已消费候选; - 单任务冻结使用 savepoint,失败回滚该任务半成品,禁止外层误提交已冻结状态。 -""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any - -from app import db -from app.models import ( - ShippingOrderCandidate, - ShippingOrderCustomerMatch, - ShippingOrderExtraction, - ShippingOrderProcessingRun, - ShippingNotice, -) -from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates -from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot - - -def maybe_execute_run_auto_freeze( - *, - run: ShippingOrderProcessingRun, - submission_result: dict[str, Any], -) -> dict[str, Any]: - """在门禁已放行时消费当前 Run 的 accepted Candidate,并自动冻结其新建任务。""" - result = dict(submission_result or {}) - policy = run.auto_freeze_policy_json if isinstance(run.auto_freeze_policy_json, dict) else {} - if not bool(policy.get('enabled')): - return result - - # [STEP 1] 冻结候选集合在建单前冻结;后续冻结不得重新扩大范围。 - candidate_nos = _eligible_candidate_nos(run) - create_result: dict[str, Any] | None = None - if candidate_nos: - create_result = create_shipping_batch_from_candidates( - user_id=int(run.user_id), - conversation_id=run.conversation_id, - intake_nos=_snapshot_intake_nos(run), - candidate_nos=candidate_nos, - create_idempotency_key=f"extract:{str(run.input_snapshot_hash or '')[:48]}", - ) - - frozen_task_nos, blocked_tasks = _freeze_created_tasks( - run=run, - policy=policy, - candidate_nos=candidate_nos, - ) - refreshed = _refresh_submission_result( - run=run, - previous_result=result, - create_result=create_result, - ) - refreshed['auto_freeze'] = { - 'enabled': True, - 'frozen_task_nos': frozen_task_nos, - 'blocked_tasks': blocked_tasks, - 'eligible_candidate_nos': list(candidate_nos), - } - return refreshed - - -def _eligible_candidate_nos(run: ShippingOrderProcessingRun) -> list[str]: - """只返回当前 Run 中可以自动建单的 accepted + selected 候选。""" - rows = ( - ShippingOrderCandidate.query - .filter_by( - order_extraction_run_id=int(run.id), - is_current_version=True, - candidate_status='accepted', - selected=True, - ) - .filter(ShippingOrderCandidate.consumed_task_id.is_(None)) - .order_by(ShippingOrderCandidate.id.asc()) - .all() - ) - return [str(item.candidate_no) for item in rows if str(item.candidate_no or '').strip()] - - -def _snapshot_intake_nos(run: ShippingOrderProcessingRun) -> list[str]: - """从 Run 冻结快照提取 Intake 编号,确保自动消费范围不越过本轮输入。""" - snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} - intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else [] - return [ - str(item.get('intake_no') or '').strip().upper() - for item in intakes - if isinstance(item, dict) and str(item.get('intake_no') or '').strip() - ] - - -def _freeze_created_tasks( - *, - run: ShippingOrderProcessingRun, - policy: dict[str, Any], - candidate_nos: list[str], -) -> tuple[list[str], list[dict[str, Any]]]: - """ - 冻结本轮 eligible 且已消费的任务。 - - 核心逻辑:候选集合必须与建单前 `_eligible_candidate_nos` 完全一致; - 禁止扫描 Run 下全部 consumed 候选(避免误冻人工/其它路径任务)。 - """ - eligible = { - str(item).strip() - for item in (candidate_nos or []) - if str(item).strip() - } - if not eligible: - return [], [] - - candidates = ( - ShippingOrderCandidate.query - .filter_by( - order_extraction_run_id=int(run.id), - is_current_version=True, - candidate_status='accepted', - selected=True, - ) - .filter(ShippingOrderCandidate.consumed_task_id.isnot(None)) - .filter(ShippingOrderCandidate.candidate_no.in_(tuple(eligible))) - .order_by(ShippingOrderCandidate.id.asc()) - .all() - ) - frozen_task_nos: list[str] = [] - blocked_tasks: list[dict[str, Any]] = [] - for candidate in candidates: - if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing': - continue - task = db.session.get(ShippingNotice, int(candidate.consumed_task_id or 0)) - if task is None: - continue - # [STEP] 单任务 savepoint:冻结失败必须回滚本任务已 flush 的快照/指针/客户继承, - # 禁止外层事务提交“返回阻断但库内已冻结”的半成品。 - try: - with db.session.begin_nested(): - _inherit_confirmed_ordering_customer(run=run, task=task, policy=policy) - snapshot = freeze_order_snapshot( - task, - actor_id=None, - expected_order_data_version=int(task.order_data_version or 1), - freeze_mode='auto', - auto_freeze_policy=policy, - ) - # [STEP] 与冻结同 savepoint:进度事件失败则回滚本任务冻结半成品。 - from app.services.shipping_notice.order_extraction_progress import record_run_progress - - record_run_progress( - run=run, - event_code='order_auto_frozen', - summary={ - 'task_no': str(task.task_no or ''), - 'candidate_no': str(candidate.candidate_no or ''), - 'snapshot_id': int(getattr(snapshot, 'id', 0) or 0) or None, - 'freeze_source': str((policy or {}).get('freeze_source') or '') or None, - }, - commit=False, - ) - frozen_task_nos.append(str(task.task_no or f"snapshot-{snapshot.id}")) - except Exception as exc: # pragma: no cover - 阻断明细由调用侧测试断言 - blocked_tasks.append({ - 'candidate_no': str(candidate.candidate_no or ''), - 'task_no': str(task.task_no or ''), - 'code': str(getattr(exc, 'code', '') or ''), - 'message': str(exc), - 'details': getattr(exc, 'details', None), - }) - return frozen_task_nos, blocked_tasks - - -def _inherit_confirmed_ordering_customer( - *, - run: ShippingOrderProcessingRun, - task: ShippingNotice, - policy: dict[str, Any], -) -> None: - """把 Run 已确认的唯一 Bill-to 客户补写到当前任务 Extraction,供自动冻结门禁复用。""" - confirmed_ids = sorted({ - int(item) - for item in (policy.get('confirmed_customer_ids') or []) - if str(item).strip().isdigit() - }) - if len(confirmed_ids) != 1 or not task.current_order_extraction_id: - return - extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id)) - if extraction is None: - return - target = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(extraction.id), - role='bill_to', - ).one_or_none() - if ( - target is not None - and target.status == 'confirmed' - and int(target.customer_id or 0) == confirmed_ids[0] - and bool(target.customer_short_code_snapshot) - and bool(target.identity_fingerprint) - and bool(target.identity_rule_version) - ): - return - if target is not None and target.status == 'confirmed' and target.customer_id not in {None, confirmed_ids[0]}: - return - source = ( - ShippingOrderCustomerMatch.query - .join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id) - .filter( - ShippingOrderExtraction.run_id == int(run.id), - ShippingOrderCustomerMatch.role == 'bill_to', - ShippingOrderCustomerMatch.status == 'confirmed', - ShippingOrderCustomerMatch.customer_id == confirmed_ids[0], - ) - .order_by(ShippingOrderCustomerMatch.confirmed_at.desc(), ShippingOrderCustomerMatch.id.desc()) - .first() - ) - if source is None: - return - if target is None: - target = ShippingOrderCustomerMatch( - extraction_id=int(extraction.id), - role='bill_to', - identity_components_json={}, - candidates_json=[], - ) - db.session.add(target) - target.raw_name = source.raw_name - target.normalized_name = source.normalized_name - target.source_system = source.source_system - target.external_code = source.external_code - target.identity_fingerprint = source.identity_fingerprint - target.identity_rule_version = source.identity_rule_version - target.identity_components_json = dict(source.identity_components_json or {}) - target.status = 'confirmed' - target.customer_id = source.customer_id - target.site_id = source.site_id - target.customer_name_snapshot = source.customer_name_snapshot - target.customer_short_code_snapshot = source.customer_short_code_snapshot - target.candidates_json = list(source.candidates_json or []) - target.resolution_method = source.resolution_method or 'run_auto_freeze_inherited' - target.confirmation_reason = source.confirmation_reason or 'run_auto_freeze_inherited' - target.confirmed_by_id = source.confirmed_by_id - target.confirmed_at = source.confirmed_at or datetime.utcnow() - target.updated_at = datetime.utcnow() - db.session.flush() - - -def _refresh_submission_result( - *, - run: ShippingOrderProcessingRun, - previous_result: dict[str, Any], - create_result: dict[str, Any] | None, -) -> dict[str, Any]: - """按当前 Run 持久化事实重建摘要,确保自动建单后 created/pending 计数可恢复。""" - candidates = ( - ShippingOrderCandidate.query - .filter_by(order_extraction_run_id=int(run.id), is_current_version=True) - .order_by(ShippingOrderCandidate.id.asc()) - .all() - ) - pending_by_candidate_no = { - str(item.get('candidate_no') or ''): item - for item in previous_result.get('pending_orders') or [] - if isinstance(item, dict) and str(item.get('candidate_no') or '').strip() - } - created: list[dict[str, Any]] = [] - opened_existing: list[dict[str, Any]] = [] - pending_orders: list[dict[str, Any]] = [] - created_with_missing_fields_count = 0 - for candidate in candidates: - if candidate.consumed_task_id is None: - pending_item = pending_by_candidate_no.get(str(candidate.candidate_no or '')) - if pending_item is not None: - pending_orders.append(pending_item) - continue - task = db.session.get(ShippingNotice, int(candidate.consumed_task_id)) - if task is None: - continue - if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing': - opened_existing.append({ - 'candidate_no': candidate.candidate_no, - 'task_no': task.task_no, - 'batch_no': None, - }) - continue - created.append({'task_no': task.task_no}) - if candidate.missing_fields_json: - created_with_missing_fields_count += 1 - created_with_missing_fields_count = min(created_with_missing_fields_count, len(created)) - non_shipping_orders = list(previous_result.get('non_shipping_orders') or []) - refreshed = { - 'status': 'ok', - 'request_id': str(run.run_no), - 'batch_no': ( - create_result.get('batch_no') - if isinstance(create_result, dict) and create_result.get('batch_no') - else previous_result.get('batch_no') - ), - 'created': created, - 'opened_existing': opened_existing, - 'pending_orders': pending_orders, - 'non_shipping_orders': non_shipping_orders, - 'created_count': len(created), - 'opened_existing_count': len(opened_existing), - 'pending_count': len(pending_orders), - 'non_shipping_count': len(non_shipping_orders), - 'created_with_missing_fields_count': created_with_missing_fields_count, - } - refreshed['message'] = _build_submission_message( - created_count=refreshed['created_count'], - opened_existing_count=refreshed['opened_existing_count'], - pending_count=refreshed['pending_count'], - non_shipping_count=refreshed['non_shipping_count'], - created_with_missing_fields_count=created_with_missing_fields_count, - ) - return refreshed - - -def _build_submission_message( - *, - created_count: int, - opened_existing_count: int, - pending_count: int, - non_shipping_count: int, - created_with_missing_fields_count: int, -) -> str: - """生成自动冻结执行后的统一结果摘要,保持与订单抽取主链路文案一致。""" - if not created_count and not opened_existing_count and not pending_count: - if non_shipping_count: - return f'未识别到需要处理的发货订单,已忽略 {non_shipping_count} 项非发货内容;本次未创建任务。' - return '未识别到发货订单,本次未创建任务。' - - parts: list[str] = [] - if created_count: - parts.append(f'已创建 {created_count} 个发货任务') - if opened_existing_count: - parts.append(f'已打开 {opened_existing_count} 个已有任务') - if pending_count: - prefix = '另有' if parts else '有' - parts.append(f'{prefix} {pending_count} 个订单需要补充信息或处理冲突') - if non_shipping_count: - parts.append(f'已忽略 {non_shipping_count} 项非发货内容') - message = ';'.join(parts) + '。' - if created_with_missing_fields_count: - message += ( - f'其中 {created_with_missing_fields_count} 个新建任务仍缺少 Reservation ID,' - '可通过自然对话补充。' - ) - return message diff --git a/backend/app/services/shipping_notice/order_document_profile_creation_service.py b/backend/app/services/shipping_notice/order_document_profile_creation_service.py index e9377736..9de2fa43 100644 --- a/backend/app/services/shipping_notice/order_document_profile_creation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_creation_service.py @@ -39,6 +39,8 @@ def _initial_coordinate_definition(main_table_id: str) -> dict[str, Any]: """生成未标注但合法的坐标草稿起点;编辑器后续才添加锚点、表头和行布局。""" region_suffix = re.sub(r'[^a-z0-9_]+', '_', main_table_id.lower()).strip('_') or 'table' return { + # 视觉主表身份必须随共同定义冻结;annotation/training 只保存该身份的样本绑定。 + 'main_table_id': str(main_table_id).strip(), 'document_match': { 'document_type': 'purchase_order', 'page_pattern': 'one_or_more', 'required_anchors': [], 'optional_anchors': [], 'minimum_score': 0, 'minimum_margin': 0, diff --git a/backend/app/services/shipping_notice/order_document_profile_pdf_automark_service.py b/backend/app/services/shipping_notice/order_document_profile_pdf_automark_service.py index 17f15d17..872a8c67 100644 --- a/backend/app/services/shipping_notice/order_document_profile_pdf_automark_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_pdf_automark_service.py @@ -550,6 +550,38 @@ def _fuse_header_regions_with_column_geometry( }) if fused_headers: result['header_regions'] = [*(result.get('header_regions') or []), *fused_headers] + # Widget 仅按“表格内有值控件”聚类,动态 XFA 的表头控件也可能带展示值。 + # 表头文字已通过独立坐标证据确认时,与该表头带实质重叠的 Widget 行不能再 + # 作为明细行候选,否则画布会同时保存 header_field 与 field。 + def _overlaps_fused_header(layout: Any) -> bool: + if not isinstance(layout, dict) or not isinstance(layout.get('region'), dict): + return False + try: + lx0, ly0, lx1, ly1 = (float(layout['region'][key]) for key in ('x0', 'y0', 'x1', 'y1')) + except (KeyError, TypeError, ValueError): + return False + layout_width, layout_height = lx1 - lx0, ly1 - ly0 + if layout_width <= 0 or layout_height <= 0: + return False + for header in fused_headers: + region = header.get('region') if isinstance(header, dict) else None + if not isinstance(region, dict): + continue + try: + hx0, hy0, hx1, hy1 = (float(region[key]) for key in ('x0', 'y0', 'x1', 'y1')) + except (KeyError, TypeError, ValueError): + continue + header_width, header_height = hx1 - hx0, hy1 - hy0 + horizontal_overlap = max(0.0, min(lx1, hx1) - max(lx0, hx0)) + vertical_overlap = max(0.0, min(ly1, hy1) - max(ly0, hy0)) + if header_width > 0 and header_height > 0 and \ + horizontal_overlap / min(layout_width, header_width) >= 0.8 and \ + vertical_overlap / min(layout_height, header_height) >= 0.8: + return True + return False + result['subrow_layouts'] = [ + layout for layout in layouts if not _overlaps_fused_header(layout) + ] return result @@ -632,6 +664,41 @@ def _field_binding_source_conflicts(candidates: list[dict[str, Any]]) -> list[di return conflicts +def _merge_duplicate_field_binding_candidates(candidates: list[dict[str, Any]]) -> list[dict[str, Any]]: + """合并同字段同页同坐标的多来源候选,保留全部证据来源。""" + merged: dict[tuple[str, str, str, int, tuple[float, float, float, float]], dict[str, Any]] = {} + order: list[tuple[str, str, str, int, tuple[float, float, float, float]]] = [] + unkeyed_candidates: list[dict[str, Any]] = [] + for candidate in candidates: + binding = candidate.get('binding') if isinstance(candidate, dict) else None + visual = binding.get('visual_binding') if isinstance(binding, dict) else None + bbox = visual.get('normalized_bbox') if isinstance(visual, dict) else None + if not isinstance(binding, dict) or not isinstance(visual, dict) or not isinstance(bbox, dict): + # 缺少完整坐标的候选无法安全判定为重复,但仍是待人工复核的视觉证据。 + unkeyed_candidates.append(candidate) + continue + try: + geometry = tuple(round(float(bbox[key]), 6) for key in ('x0', 'y0', 'x1', 'y1')) + page_no = int(visual.get('page_no') or 1) + except (KeyError, TypeError, ValueError): + unkeyed_candidates.append(candidate) + continue + key = ( + str(binding.get('field_id') or ''), str(binding.get('field_code') or ''), + str(binding.get('scope') or ''), page_no, geometry, + ) + existing = merged.get(key) + if existing is None: + merged[key] = candidate + order.append(key) + continue + existing['evidence_sources'] = list(dict.fromkeys([ + *(existing.get('evidence_sources') or []), *(candidate.get('evidence_sources') or []), + ])) + existing['needs_review'] = bool(existing.get('needs_review') or candidate.get('needs_review')) + return [*unkeyed_candidates, *(merged[key] for key in order)] + + def _execute_visual_automark( *, payload: dict[str, Any], profile_id: int, document_id: int, table_id: str, ) -> dict[str, Any]: @@ -873,8 +940,9 @@ def _execute_visual_automark( table_candidates.append(_table_reconstruction_candidate( source='opencv_geometry', reconstruction=opencv_reconstruction, )) - candidates = table_candidates + field_candidates + widget_candidates - field_conflicts = _field_binding_source_conflicts(field_candidates + widget_candidates) + field_candidates = _merge_duplicate_field_binding_candidates(field_candidates + widget_candidates) + candidates = table_candidates + field_candidates + field_conflicts = _field_binding_source_conflicts(field_candidates) conflicts: list[dict[str, Any]] = [] reconstructions_by_source = { 'pdf_coordinate': native_reconstruction, @@ -941,24 +1009,15 @@ def enqueue_pdf_automark( ).order_by(ShippingOrderDocumentProfileSample.id.asc()).first() if annotation is None or annotation.table_id != resolved_table_id: raise ValidationError('Automark requires the frozen annotation sample table', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') - if not annotation.layout_version_id or not annotation.layout_payload_checksum: - raise ValidationError('Annotation sample layout evidence is not frozen', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') + from app.services.shipping_notice.order_document_profile_service import require_profile_sample_automark_ready + readiness = require_profile_sample_automark_ready(profile=profile, sample=annotation, actor_id=actor_id) document = db.session.get(ShippingOrderDocument, int(document_id)) - current_checksum = str( - getattr(getattr(document, 'current_layout_version', None), 'payload_checksum', '') or '', - ) - if ( - document is None - or int(document.current_layout_version_id or 0) != int(annotation.layout_version_id) - or current_checksum != str(annotation.layout_payload_checksum) - ): - raise ValidationError('Annotation sample layout is stale and must be refrozen', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') payload = { 'profile_id': int(profile_id), 'document_id': int(document_id), 'table_id': resolved_table_id, 'schema_version_id': int(schema_version_id) if schema_version_id else None, 'page_no': int(page_no) if page_no else 1, 'actor_id': int(actor_id), - 'layout_version_id': int(annotation.layout_version_id), - 'layout_payload_checksum': str(annotation.layout_payload_checksum), + 'layout_version_id': int(readiness['layout_version_id']), + 'layout_payload_checksum': str(readiness['layout_payload_checksum']), } ref = f'pdf-automark:{int(profile_id)}:{int(document_id)}:{payload["table_id"] or "page"}:{payload["page_no"]}' job_id = enqueue( diff --git a/backend/app/services/shipping_notice/order_document_profile_preview_service.py b/backend/app/services/shipping_notice/order_document_profile_preview_service.py index 76e7eb90..5cbdbbc1 100644 --- a/backend/app/services/shipping_notice/order_document_profile_preview_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_preview_service.py @@ -31,6 +31,7 @@ from app.services.shipping_notice.document_layout.coordinate_region_text import from app.services.shipping_notice.preview_grant_store import preview_grant_store from app.services.shipping_notice import order_document_profile_service as profile_service from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter +from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text PREVIEW_GRANT_TTL_SECONDS = 120 diff --git a/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py b/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py index e5f6d86d..3f9d296c 100644 --- a/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py @@ -7,7 +7,7 @@ services/shipping_notice/order_document_profile_publish_check_service.py 逻辑:报告冻结当前草稿身份与签名/重叠引用;XFA 模式使用结构签名、路径/集合/对账阻断, 以及字段级混合数据源可发布性与跨源 OCR mismatch 清零; 不再要求 flatten/synthetic ready / renderer_version / preview checksum; - 消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;编辑人不得批准自己的 Revision。 + 消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;管理员可确认发布自己的草稿。 """ from __future__ import annotations @@ -15,11 +15,10 @@ import secrets from datetime import datetime from typing import Any -from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError +from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db from app.models import ( ShippingOrderDocumentProfile, - ShippingOrderDocumentProfileAudit, ShippingOrderDocumentProfileDraftRevision, ShippingOrderDocumentProfileEditLease, ShippingOrderDocumentProfilePublishCheckReport, @@ -121,40 +120,6 @@ def _signature_status(profile: ShippingOrderDocumentProfile, revision: ShippingO return payload -def _find_last_profile_editor_id(profile_id: int) -> int | None: - """ - 查找最近一次编辑 Profile 映射/拆分规则的管理员 ID。 - - 核心逻辑:优先审计映射事件;回退至最新 DraftRevision.created_by_id。 - """ - editor_events = ( - 'draft_saved', - 'xfa_mapping_saved', - 'xfa_split_rule_suggested', - 'xfa_segment_mapping_updated', - ) - audit = ( - db.session.query(ShippingOrderDocumentProfileAudit) - .filter( - ShippingOrderDocumentProfileAudit.profile_id == int(profile_id), - ShippingOrderDocumentProfileAudit.event_type.in_(editor_events), - ) - .order_by(ShippingOrderDocumentProfileAudit.id.desc()) - .first() - ) - if audit is not None and audit.actor_id is not None: - return int(audit.actor_id) - revision = ( - db.session.query(ShippingOrderDocumentProfileDraftRevision) - .filter_by(profile_id=int(profile_id)) - .order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()) - .first() - ) - if revision is not None and revision.created_by_id is not None: - return int(revision.created_by_id) - return None - - def _overlap_summary_from_run( run: ShippingOrderDocumentProfileValidationRun | None, ) -> dict[str, Any] | None: @@ -374,6 +339,7 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None and candidate.run_type == 'layout_signature' and candidate.status == 'passed' and candidate.definition_checksum == revision.definition_checksum + and validation_service._signature_uses_current_evidence_contract(candidate) ): signature_run = candidate if signature_run is None: @@ -491,14 +457,6 @@ def consume_report(profile_id: int, report_no: str, *, data: dict[str, Any], act raise ConflictError('Publish check report is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID') if row.blocking_items_json: raise ValidationError('Publish check has blocking items', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID') - if actor_id is not None: - editor_id = _find_last_profile_editor_id(profile.id) - if editor_id is not None and int(editor_id) == int(actor_id): - raise ValidationError( - 'Editor cannot approve own version', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID', - details={'key': 'editor_cannot_approve_own_version'}, - ) confirmed = {str(item) for item in data.get('confirmed_warning_keys') or []} required = {str(item.get('key')) for item in row.warning_items_json or []} if confirmed != required: diff --git a/backend/app/services/shipping_notice/order_document_profile_service.py b/backend/app/services/shipping_notice/order_document_profile_service.py index 6b8fdbbc..88ccac5f 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -9,6 +9,7 @@ backend/app/services/shipping_notice/order_document_profile_service.py from __future__ import annotations +import base64 import hashlib import io import json @@ -39,7 +40,11 @@ from app.models import ( ) from app.services.shipping_notice.document_layout.html_table import parse_html_grid from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + coordinate_profile_character_candidates, + derive_incomplete_table_bbox, reconstruct_coordinate_profile_rows, + reconstruct_coordinate_profile_rows_with_strategy, + reconstruction_exclusion_regions, suggest_header_layouts, suggest_header_regions, suggest_multi_subrow_layouts, @@ -70,6 +75,7 @@ from app.services.shipping_notice.order_profile_value_adapter import ( OrderProfileValueAdapter, get_value_adapter, ) +from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$') @@ -422,6 +428,42 @@ def _normalize_definition( ) profile_fields = _schema_profile_fields(schema_version) + reservation_region = raw.get('reservation_id_region') + if reservation_region is not None: + if not isinstance(reservation_region, dict): + raise ValidationError( + 'reservation_id_region must be an object', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID', + ) + reservation_fields = { + scope: field for (scope, code), field in profile_fields.items() + if code == 'reservation_id' + } + # 一个区域可以同时承载整单 Reservation 和指定明细行 Reservation: + # Header 是无行号值的权威落点;Line 字段启用后才消费带行号的值。 + if 'header' not in reservation_fields: + raise ValidationError( + 'Schema must enable header reservation_id for unnumbered Reservation values', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID', + details={'scopes': sorted(reservation_fields), 'required_scope': 'header'}, + ) + region = reservation_region.get('region') + page_no = reservation_region.get('page_no') + if not isinstance(region, dict) or page_no is None: + raise ValidationError( + 'reservation_id_region requires region and page_no', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID', + ) + try: + from app.services.shipping_notice.document_layout.order_profile import RelativeRegion + RelativeRegion.model_validate(region) + if int(page_no) < 1: + raise ValueError('page_no must be positive') + except (TypeError, ValueError) as exc: + raise ValidationError( + 'reservation_id_region geometry is invalid', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID', + ) from exc if raw.get('header_mappings') is not None or raw.get('source_contract') is not None or raw.get('line_mapping') is not None: raise ValidationError( 'Coordinate definition must not mix value-source mapping keys', @@ -438,6 +480,8 @@ def _normalize_definition( 'table_regions': raw.get('table_regions'), 'order_field_layouts': raw.get('order_field_layouts') or [], 'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [], + 'coordinate_model': raw.get('coordinate_model') or {}, + 'reference_page_frames': raw.get('reference_page_frames') or {}, } for table_region in normalized['table_regions'] or []: if not isinstance(table_region, dict): @@ -501,6 +545,13 @@ def _normalize_definition( } for target in sorted(outputs) ] + # Legacy Vendor Comments mappings are intentionally rejected at the API + # boundary; the only supported special evidence is reservation_id_region. + if raw.get('named_regions') is not None or raw.get('field_source_mappings') is not None: + raise ValidationError( + 'Legacy Vendor Comments mappings are no longer supported; use reservation_id_region', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEGACY_VENDOR_COMMENTS_UNSUPPORTED', + ) for order_field in normalized['order_field_layouts']: if not isinstance(order_field, dict): continue @@ -510,6 +561,24 @@ def _normalize_definition( field = profile_fields.get(('header', code)) if field is None: raise ValidationError('Order field binding must target a header Schema field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID') + # [STEP] Address layouts saved by the affected workbench version could inherit + # the first page anchor (Number). Reject that proven bad binding at the API + # boundary so stale browsers or direct requests cannot persist it again. + anchor = order_field.get('anchor') + anchor_text = ( + str(anchor.get('text') or '').strip().casefold() + if isinstance(anchor, dict) else '' + ) + if code in {'ship_to_address', 'bill_to_address'} and anchor_text == 'number': + raise ValidationError( + 'Address field cannot bind to the Number anchor', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID', + details={ + 'reason': 'order_field_anchor_semantic_mismatch', + 'field_code': code, + 'anchor_text': str(anchor.get('text') or '').strip(), + }, + ) order_field['field_id'] = str(field['field_id']) order_field['scope'] = 'header' normalizer = order_field.get('normalizer_key') @@ -550,6 +619,8 @@ def _normalize_definition( table_regions=normalized['table_regions'], order_field_layouts=normalized['order_field_layouts'], draft_unbound_order_field_layouts=normalized['draft_unbound_order_field_layouts'], + coordinate_model=normalized['coordinate_model'], + reference_page_frames=normalized['reference_page_frames'], ) except (TypeError, ValueError) as exc: # Pydantic locations only describe the submitted contract, so exposing the @@ -576,11 +647,24 @@ def _normalize_definition( code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', ) from exc result = { + # 不能在坐标定义规范化时丢弃创建向导冻结的视觉主表身份。 + 'main_table_id': str(raw.get('main_table_id') or '').strip() or None, 'document_match': contract.document_match.model_dump(), 'table_regions': [item.model_dump() for item in contract.table_regions], 'order_field_layouts': [item.model_dump() for item in contract.order_field_layouts], 'draft_unbound_order_field_layouts': [item.model_dump() for item in contract.draft_unbound_order_field_layouts], + 'coordinate_model': contract.coordinate_model.model_dump(), + 'reference_page_frames': { + str(page_no): frame.model_dump() + for page_no, frame in contract.reference_page_frames.items() + }, } + if reservation_region is not None: + result['reservation_id_region'] = { + 'region': dict(reservation_region['region']), + 'page_scope': 'exact_page', + 'page_no': int(reservation_region['page_no']), + } if unified_bindings: result['bindings'] = unified_bindings result['template_mode'] = 'coordinate' @@ -660,6 +744,8 @@ def _normalize_visual_definition_for_preview( 'table_regions': table_regions, 'order_field_layouts': order_field_layouts, 'draft_unbound_order_field_layouts': draft_unbound_order_field_layouts, + 'coordinate_model': raw.get('coordinate_model') or {}, + 'reference_page_frames': raw.get('reference_page_frames') or {}, } return _normalize_definition(visual, schema_version=schema_version, preferred_template_mode='coordinate') @@ -674,6 +760,8 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, ) @@ -1004,11 +1092,42 @@ def read_preview_page_region_text( source = 'acroform_widget' elif len(matched_widgets) > 1: source = 'acroform_widget_ambiguous' + if not text: + text = _read_rendered_preview_crop_text(data.get('rendered_image_base64')) + if text: + source = 'xfa_rendered_ocr' _audit(profile_id=int(profile_id), document_id=document.id, event_type='preview_region_text_read', actor_id=actor_id, detail={ 'page_no': int(page_no), 'character_count': len(text), 'source': source, }) db.session.commit() - return {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'} + result = {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'} + if data.get('purpose') == 'reservation_id_region': + result['reservation_candidates'] = extract_reservation_from_region_text(text) + return result + + +def _read_rendered_preview_crop_text(rendered_image_base64: Any) -> str: + """读取浏览器 PDF.js XFA 画布的受控裁剪图文字,仅用于视觉标注回读。""" + raw = str(rendered_image_base64 or '') + prefix = 'data:image/png;base64,' + if not raw.startswith(prefix): + return '' + try: + payload = base64.b64decode(raw[len(prefix):], validate=True) + if not payload or len(payload) > 2 * 1024 * 1024: + return '' + import numpy as np + from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines + + image = Image.open(io.BytesIO(payload)).convert('RGB') + pixels = np.asarray(image) + height, width = pixels.shape[:2] + if width < 8 or height < 8 or width * height > 4_000_000: + return '' + lines = extract_ocr_lines(pixels, page_width=float(width), page_height=float(height)) + return ' '.join(str(item.text).strip() for item in lines if str(item.text).strip()).strip() + except Exception: + return '' def preview_profile_region( @@ -1032,6 +1151,8 @@ def preview_profile_region( profile_code=profile.profile_code, version=profile.version, document_match=definition['document_match'], table_regions=definition['table_regions'], order_field_layouts=definition['order_field_layouts'], + coordinate_model=definition['coordinate_model'], + reference_page_frames=definition['reference_page_frames'], ) table_id = str(data.get('table_id') or '').strip() if not table_id: @@ -1084,6 +1205,10 @@ def preview_profile_region( except (KeyError, TypeError, ValueError) as exc: raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc strict = bool(data.get('strict')) + schema_field_metadata = [ + item for item in (profile.schema_version.definition_json or {}).get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line' + ] rows = [] involved_field_codes: list[str] = [] seen_field_codes: set[str] = set() @@ -1097,11 +1222,21 @@ def preview_profile_region( # Header-only pages document column semantics but must never emit data rows. if not table_region.line_layouts: continue - # Adaptive regions explicitly require page evidence because a detected - # table bbox may contain headers only when MinerU misses detail rows. - region_characters = characters - if table_region.row_reconstruction_mode == 'adaptive_record_columns': - region_characters = (evidence.get('page_glyphs') or {}).get(str(raw_table.get('page_no') or 1)) + # 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema + # 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。 + reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump()) + reference_page_frame = contract.reference_page_frames.get(int(raw_table.get('page_no') or 1)) + region_characters, _candidate_page_bbox = coordinate_profile_character_candidates( + table_region=table_region.region.model_dump(), page_size=page, + reference_page_frame=( + reference_page_frame.model_dump() if reference_page_frame is not None else None + ), + page_characters=(evidence.get('page_glyphs') or {}).get(str(raw_table.get('page_no') or 1)), + table_characters=characters, + raw_table_bbox=raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None, + table_id=table_id, page_no=int(raw_table.get('page_no') or 1), + allow_table_fallback=True, + ) if not isinstance(region_characters, list): continue # ??????????????????????????? Schema ??? @@ -1116,31 +1251,22 @@ def preview_profile_region( if field_code and field_code not in seen_field_codes: seen_field_codes.add(field_code) involved_field_codes.append(field_code) - reconstructed_rows = reconstruct_coordinate_profile_rows( - characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox, + reconstructed_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=[item for item in region_characters if isinstance(item, dict)], + table_bbox=( + {'x0': 0, 'y0': 0, 'x1': reference_page_frame.width, 'y1': reference_page_frame.height} + if reference_page_frame is not None else page_bbox + ), line_layouts=[item.model_dump() for item in table_region.line_layouts], table_region=table_region.region.model_dump(), termination_rules=[item.model_dump() for item in table_region.termination_rules], - exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions], + exclusion_regions=reconstruction_exclusions, + dynamic_exclusion_regions=reconstruction_exclusions, # ????????????????????????????????? include_deleted=not strict, line_start_field_code=table_region.line_start_field_code, - row_reconstruction_mode=table_region.row_reconstruction_mode, + schema_field_metadata=schema_field_metadata, ) - # Preview must expose coordinate reads for correction even when the current - # sample's start marker is missing; the production extraction path remains strict. - if not reconstructed_rows and not strict: - reconstructed_rows = reconstruct_coordinate_profile_rows( - characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox, - line_layouts=[item.model_dump() for item in table_region.line_layouts], - table_region=table_region.region.model_dump(), - termination_rules=[item.model_dump() for item in table_region.termination_rules], - exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions], - include_deleted=True, - line_start_field_code=table_region.line_start_field_code, - include_unanchored_rows=True, - row_reconstruction_mode=table_region.row_reconstruction_mode, - ) rows.extend(reconstructed_rows) # ?????????????????????????????? if strict: @@ -1197,6 +1323,8 @@ def suggest_profile_header( profile_code=profile.profile_code, version=profile.version, document_match=definition['document_match'], table_regions=definition['table_regions'], order_field_layouts=definition['order_field_layouts'], + coordinate_model=definition['coordinate_model'], + reference_page_frames=definition['reference_page_frames'], ) table_id = str(data.get('table_id') or '').strip() layout = _document_layout(document) @@ -1391,6 +1519,28 @@ def _document_layout(document: ShippingOrderDocument) -> dict[str, Any]: return layout +def _reference_page_frames(layout: dict[str, Any]) -> dict[str, dict[str, Any]]: + """从标注样本冻结 Layout 提取 PDF CropBox 点尺寸,拒绝使用浏览器提交的物理尺寸。""" + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + frames: dict[str, dict[str, Any]] = {} + for page_no, page in pages.items(): + try: + normalized_page_no = int(page_no) + width, height = float(page['width']), float(page['height']) + except (KeyError, TypeError, ValueError): + continue + if normalized_page_no < 1 or width <= 0 or height <= 0: + continue + frames[str(normalized_page_no)] = { + 'width': width, + 'height': height, + 'origin': 'pdf_top_left', + 'box': 'cropbox', + } + return frames + + def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDocumentLayoutVersion: """????????? ready Layout ???????????????????????""" version = document.current_layout_version @@ -1406,6 +1556,166 @@ def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDo return version +def refresh_profile_sample_readiness( + *, profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample, + actor_id: int | None = None, commit: bool = False, +) -> dict[str, Any]: + """刷新模板样本的 Layout/主表/证据状态,并在条件满足时幂等冻结现有证据字段。 + + [STEP 1] 上传物化、Layout ready、主表绑定和证据冻结是四个独立状态; + 本函数只在 ready Layout 且内容身份一致时写回既有样本字段,绝不创建新实体, + 也不会在 Layout 尚未完成时把样本伪装成可自动标注。 + + Args: + profile: 必须是当前模板 Profile。 + sample: Profile 的 annotation/training 样本绑定。 + actor_id: 产生冻结审计时的管理员身份,可为空(后台布局收口)。 + commit: 是否提交当前事务;保存草稿时由外层事务统一提交。 + + Returns: + 包含 layout_status、main_table_status、evidence_status 和 automark_ready 的安全状态。 + """ + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + if document is None: + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(sample.document_id), 'layout_status': 'missing', + 'main_table_status': 'missing', 'evidence_status': 'unavailable', + 'automark_ready': False, 'reason_code': 'document_missing', + } + from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot + + layout = current_layout_snapshot(document) or {} + version = ( + db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id)) + if document.current_layout_version_id else None + ) + if ( + version is None or str(version.status or '') != 'ready' + or not isinstance(version.payload_json, dict) + ): + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': str(getattr(version, 'status', None) or 'pending'), + 'main_table_status': 'pending', 'evidence_status': 'pending', + 'automark_ready': False, 'reason_code': 'layout_not_ready', + } + tables = [ + item for item in (layout.get('tables') or []) + if isinstance(item, dict) and str(item.get('table_id') or '').strip() + ] + table_id = str(sample.table_id or '').strip() + if not table_id: + definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + configured = str(definition.get('main_table_id') or '').strip() + if configured: + table_id = configured + elif len(tables) == 1: + table_id = str(tables[0]['table_id']).strip() + else: + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': 'ready', + 'main_table_status': 'ambiguous' if tables else 'missing', + 'evidence_status': 'pending', 'automark_ready': False, + 'reason_code': 'main_table_ambiguous' if tables else 'main_table_missing', + } + if not any(str(item.get('table_id') or '') == table_id for item in tables): + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': 'ready', + 'main_table_status': 'missing', 'evidence_status': 'stale', + 'automark_ready': False, 'reason_code': 'main_table_missing', + } + content_hash = str(document.content_hash or '').strip().lower() + source_hash = str(version.source_content_hash or '').strip().lower() + if len(content_hash) != 64 or len(source_hash) != 64 or content_hash != source_hash: + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': 'ready', + 'main_table_status': 'bound', 'evidence_status': 'stale', + 'automark_ready': False, 'reason_code': 'layout_content_hash_mismatch', + } + from app.services.shipping_notice.document_layout.lifecycle import canonical_layout_payload + payload_checksum, _ = canonical_layout_payload(version.payload_json or {}) + stored_checksum = str(version.payload_checksum or '').strip().lower() + if len(stored_checksum) != 64 or payload_checksum != stored_checksum: + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': 'ready', + 'main_table_status': 'bound', 'evidence_status': 'stale', + 'automark_ready': False, 'reason_code': 'layout_checksum_mismatch', + } + changed = ( + sample.table_id != table_id + or sample.layout_version_id != int(version.id) + or str(sample.layout_payload_checksum or '').lower() != stored_checksum + or str(sample.source_content_hash or '').lower() != content_hash + or str(sample.layout_contract_version or '') != str(version.contract_version or '').strip() + or str(sample.parser_key or '') != str(version.parser_key or '').strip() + or str(sample.parser_name or '') != str(version.parser_name or '').strip() + or str(sample.parser_version or '') != str(version.parser_version or '').strip() + ) + sample.table_id = table_id + sample.layout_version_id = int(version.id) + sample.layout_payload_checksum = stored_checksum + sample.source_content_hash = content_hash + sample.layout_contract_version = str(version.contract_version or '').strip() or None + sample.parser_key = str(version.parser_key or '').strip() or None + sample.parser_name = str(version.parser_name or '').strip() or None + sample.parser_version = str(version.parser_version or '').strip() or None + # Layout identity or parser provenance changed means this is a new evidence freeze, + # not merely a repeated read of the same frozen sample. + sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at + sample.source_filename_snapshot = str(document.filename or '').strip() or None + sample.page_count_snapshot = _layout_page_count(version.payload_json or {}) + sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id) + if changed: + _audit( + profile_id=profile.id, document_id=document.id, + event_type='profile_sample_evidence_frozen', actor_id=actor_id, + detail={ + 'sample_id': int(sample.id), 'sample_role': sample.sample_role, + 'layout_version_id': int(version.id), 'table_id': table_id, + 'layout_payload_checksum': stored_checksum, + }, + ) + if commit: + db.session.commit() + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'table_id': table_id, + 'layout_status': 'ready', 'main_table_status': 'bound', + 'evidence_status': 'frozen', 'automark_ready': True, + 'layout_version_id': int(version.id), 'layout_payload_checksum': stored_checksum, + 'reason_code': None, + } + + +def require_profile_sample_automark_ready( + *, profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample, + actor_id: int | None = None, +) -> dict[str, Any]: + """自动标注入队前唯一强门禁;未满足证据条件时返回稳定、可操作的错误码。""" + state = refresh_profile_sample_readiness(profile=profile, sample=sample, actor_id=actor_id, commit=False) + if state.get('automark_ready'): + return state + reason = str(state.get('reason_code') or 'profile_sample_not_ready') + code_by_reason = { + 'layout_not_ready': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_NOT_READY', + 'main_table_missing': 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_REQUIRED', + 'main_table_ambiguous': 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS', + 'layout_content_hash_mismatch': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE', + 'layout_checksum_mismatch': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE', + 'document_missing': 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', + } + raise ValidationError( + 'Profile sample is not ready for PDF automark', + code=code_by_reason.get(reason, 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'), + details=state, + ) + + def _layout_page_count(payload: dict[str, Any]) -> int | None: """????????????? payload ?? pages?????????????""" pages = payload.get('pages') @@ -1487,7 +1797,7 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr ensure_inline_xfa_structure_analysis_identity, record_inline_layout_snapshot, ) - from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence + from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by( ShippingOrderDocumentProfileSample.id.asc(), @@ -1505,28 +1815,17 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) layout_version = _current_ready_layout_version(document) - required_pages = _profile_sample_coordinate_pages( - profile, sample=sample, layout_payload=layout_version.payload_json or {}, + hydrated_layout = _hydrate_coordinate_evidence( + payload=dict(layout_version.payload_json or {}), document=document, ) - if not _layout_has_page_coordinate_evidence(layout_version.payload_json or {}, page_nos=required_pages): - # [STEP 1] ??????????????????? - recovered = ensure_on_demand_coordinate_evidence( - document=document, layout=dict(layout_version.payload_json or {}), page_nos=required_pages, + required_pages = _profile_sample_coordinate_pages( + profile, sample=sample, layout_payload=hydrated_layout, + ) + if not _layout_has_page_coordinate_evidence(hydrated_layout, page_nos=required_pages): + raise ConflictError( + 'Profile sample page coordinate evidence is unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) - if not _layout_has_page_coordinate_evidence(recovered, page_nos=required_pages): - raise ConflictError( - 'Profile sample page coordinate evidence is unavailable', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', - ) - layout_version = record_inline_layout_snapshot( - document, recovered, - parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1', - ) - if str(layout_version.status or '') != 'ready': - raise ConflictError( - 'Profile sample page coordinate evidence cannot be frozen', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', - ) # XFA 视觉补证生成的派生 Layout 必须具有同版本的 datasets 结构分析; # 此处在共同样本冻结边界补齐历史快照,禁止值源 adapter 回退到旧 Layout。 ensure_inline_xfa_structure_analysis_identity( @@ -1641,7 +1940,10 @@ def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tupl def _ensure_page_coordinate_evidence( *, document: ShippingOrderDocument, layout: dict[str, Any], page_no: int, ) -> dict[str, Any]: - """???????????????????????????????????""" + """从当前布局的外置证据引用读取页面坐标;缺失时保持缺失,不重读原 PDF。""" + from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence + + return _hydrate_coordinate_evidence(payload=dict(layout), document=document) glyphs, source = _page_coordinate_characters(layout, page_no=page_no) if glyphs and source in {'pdf_coordinate', 'ocr_coordinate'}: return layout @@ -1931,6 +2233,8 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> document_match=definition['document_match'], table_regions=definition['table_regions'], order_field_layouts=definition['order_field_layouts'], draft_unbound_order_field_layouts=definition['draft_unbound_order_field_layouts'], + coordinate_model=definition['coordinate_model'], + reference_page_frames=definition['reference_page_frames'], ) layout = _document_layout(document) if isinstance(raw_page_nos, list) and any(item.page_scope == 'all_pages' for item in profile.order_field_layouts): @@ -2078,7 +2382,7 @@ def _apply_acroform_widget_preview_fallback( def _widget_is_within_visual_value_region(*, widget_bbox: Any, region: dict[str, float]) -> bool: - """接受中心点落框或至少 80% 面积相交的 Widget,避免邻近控件串值。""" + """仅接受几乎完整落入标注框的 Widget,禁止局部框回填整段 /V。""" if not isinstance(widget_bbox, dict): return False try: @@ -2087,9 +2391,10 @@ def _widget_is_within_visual_value_region(*, widget_bbox: Any, region: dict[str, return False if x1 <= x0 or y1 <= y0: return False - center_inside = region['x0'] <= (x0 + x1) / 2 <= region['x1'] and region['y0'] <= (y0 + y1) / 2 <= region['y1'] intersection = max(0.0, min(x1, region['x1']) - max(x0, region['x0'])) * max(0.0, min(y1, region['y1']) - max(y0, region['y0'])) - return center_inside or intersection / ((x1 - x0) * (y1 - y0)) >= .8 + # Widget /V 是整个控件值。只要框没有完整覆盖控件,就无法证明 /V 属于局部区域; + # 此时必须交给浏览器当前画布的局部 OCR,而不能以中心点或部分面积猜测。 + return intersection / ((x1 - x0) * (y1 - y0)) >= .98 def _read_acroform_widgets_for_preview(*, document: ShippingOrderDocument) -> list[Any]: @@ -2510,6 +2815,36 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st if intake is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') documents = ShippingOrderDocument.query.filter_by(intake_id=intake.id).all() + readiness: list[dict[str, Any]] = [] + document_layout_states: list[str] = [] + for document in documents: + # 测试/后台轮询都可能只载入 current_layout_version_id;显式按 ID 读取, + # 不能因 ORM relationship 尚未加载把实际 failed/ready 误报为 pending。 + version = ( + db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id)) + if document.current_layout_version_id else None + ) + if version is None: + # failed Layout 不会成为 current_layout_version;上传状态仍须如实展示最近一次 + # 解析结论,不能因为没有 current 指针把失败伪装成仍在等待。 + version = ( + ShippingDocumentLayoutVersion.query + .filter_by(document_id=document.id) + .order_by(ShippingDocumentLayoutVersion.version.desc()) + .first() + ) + document_layout_states.append(str(getattr(version, 'status', None) or 'pending')) + bindings = ShippingOrderDocumentProfileSample.query.filter_by(document_id=document.id).all() + for sample in bindings: + profile = db.session.get(ShippingOrderDocumentProfile, int(sample.profile_id)) + if profile is None or profile.status != 'draft': + continue + state = refresh_profile_sample_readiness( + profile=profile, sample=sample, actor_id=actor_id, commit=False, + ) + readiness.append(state) + if readiness: + db.session.commit() if intake.parse_status in {'parse_failed', 'failed', 'error'}: status = 'failed' error_code = intake.error_code @@ -2520,12 +2855,29 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st # ???? PDF Document??????? EML / Layout? status = 'parsing' error_code = None + ready_values = [bool(item.get('automark_ready')) for item in readiness] return { 'intake_no': intake.intake_no, 'parse_status': status, 'document_count': len(documents), 'document_ids': [int(document.id) for document in documents], 'error_code': error_code, + 'layout_status': ( + 'ready' if readiness and all(item.get('layout_status') == 'ready' for item in readiness) + else ( + readiness[0].get('layout_status') + if readiness + else ('ready' if document_layout_states and all(item == 'ready' for item in document_layout_states) + else (document_layout_states[0] if document_layout_states else 'pending')) + ) + ), + 'evidence_status': ( + 'frozen' if readiness and all(item.get('evidence_status') == 'frozen' for item in readiness) + else (readiness[0].get('evidence_status') if readiness else 'pending') + ), + 'automark_ready': bool(readiness) and all(ready_values), + 'automark_reason_code': next((item.get('reason_code') for item in readiness if item.get('reason_code')), None), + 'sample_readiness': readiness, } @@ -2683,11 +3035,33 @@ def suggest_coordinate_reconstruction( if field.get('auto_annotation_enabled', True) and set(field.get('allowed_sources') or []) & {'pdf_coordinate', 'ocr_coordinate'} ] + effective_characters = characters + effective_table_bbox = dict(raw_table['bbox']) + table_bbox_source = 'layout_table' suggestions = suggest_multi_subrow_layouts( - characters=characters, table_bbox=raw_table['bbox'], + characters=effective_characters, table_bbox=effective_table_bbox, ) if not suggestions: - raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') + # MinerU can return a header-only table bbox. Use complete page evidence + # to derive a candidate boundary, while retaining the original fact. + page_characters, page_source = _page_coordinate_characters( + layout, page_no=int(raw_table.get('page_no') or 1), + ) + if page_characters and page_source in {'pdf_coordinate', 'ocr_coordinate'}: + derived_bbox = derive_incomplete_table_bbox( + characters=page_characters, table_bbox=effective_table_bbox, + ) + if derived_bbox is not None: + derived_suggestions = suggest_multi_subrow_layouts( + characters=page_characters, table_bbox=derived_bbox, + ) + if derived_suggestions: + effective_characters = page_characters + effective_table_bbox = derived_bbox + suggestions = derived_suggestions + table_bbox_source = 'page_coordinate_derived' + if not suggestions: + raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') raw_row_offset = data.get('row_offset') if raw_row_offset is not None: try: @@ -2709,14 +3083,16 @@ def suggest_coordinate_reconstruction( page = (layout.get('coordinate_evidence') or {}).get('pages', {}).get(str(raw_table.get('page_no') or 1), {}) try: page_width, page_height = float(page['width']), float(page['height']) - table_bbox = raw_table['bbox'] + table_bbox = effective_table_bbox table_region = { 'x0': float(table_bbox['x0']) / page_width, 'y0': float(table_bbox['y0']) / page_height, 'x1': float(table_bbox['x1']) / page_width, 'y1': float(table_bbox['y1']) / page_height, } except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc: raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc - header_suggestions = suggest_header_regions(characters=characters, table_bbox=raw_table['bbox']) + header_suggestions = suggest_header_regions( + characters=effective_characters, table_bbox=effective_table_bbox, + ) # Only exact, unique aliases can bind a column. Position is considered only after # the label itself is proven, preventing shifted documents from remapping fields. aliases: dict[str, str | None] = {} @@ -2791,6 +3167,8 @@ def suggest_coordinate_reconstruction( 'table_region': table_region, 'header_regions': serialized_headers, 'subrow_layouts': serialized, + 'table_bbox_source': table_bbox_source, + 'original_table_bbox': dict(raw_table['bbox']), 'status': 'needs_review', } @@ -3002,6 +3380,16 @@ def save_draft( ) mapping_issues = normalized.pop('_mapping_issues', None) if isinstance(normalized, dict) else None definition = normalized + # [STEP 1] 坐标模板的物理参考框由 annotation Layout 生成;长页样本不会改变 + # 已标注的 PDF 点坐标,客户端也不能伪造该基准。 + if template_mode == 'coordinate' and annotation_document is not None: + reference_page_frames = _reference_page_frames(_document_layout(annotation_document)) + if not reference_page_frames: + raise ValidationError( + 'Annotation sample page dimensions are unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) + definition['reference_page_frames'] = reference_page_frames if value_adapter.requires_split_rule_confirmation and isinstance(definition, dict): confirmation_tokens = data.get('split_rule_confirmation_tokens') if not isinstance(confirmation_tokens, dict): @@ -3114,6 +3502,9 @@ def save_draft( created_by_id=actor_id, ) db.session.add(sample) + # readiness audit records sample_id; assign it within this outer save transaction + # before the shared evidence-freeze service is invoked. + db.session.flush() layout = _document_layout(annotation_document) if not any( isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id @@ -3124,6 +3515,8 @@ def save_draft( code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', ) sample.table_id = visual_main_table_id + # Layout ready 后立即尝试冻结样本证据;尚未 ready 时保留草稿并由状态接口/自动标注入口继续门禁。 + refresh_profile_sample_readiness(profile=profile, sample=sample, actor_id=actor_id, commit=False) _refresh_training_sample_count(profile) audit_summary = _definition_audit_summary(definition) if previous_definition is None: diff --git a/backend/app/services/shipping_notice/order_document_profile_validation_service.py b/backend/app/services/shipping_notice/order_document_profile_validation_service.py index 182b3ed9..b584ee46 100644 --- a/backend/app/services/shipping_notice/order_document_profile_validation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_validation_service.py @@ -38,6 +38,10 @@ from app.services.shipping_notice.document_layout.xfa_contract import ( XFA_PARSER_IDENTITY, ) + +# 签名生成必须先解引用压缩 Layout 的 FileAsset 坐标证据;旧签名不具备该输入契约。 +LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION = 'v1' + def _profile(profile_id: int) -> ShippingOrderDocumentProfile: """读取可验证草稿;发布和退役版本不能被新的草稿验证记录替代。""" profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) @@ -448,8 +452,15 @@ def _training_samples(profile: ShippingOrderDocumentProfile) -> list[ShippingOrd def _load_sample_layout(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any]: - """加载样本冻结或当前 ready layout;签名只消费坐标证据摘要,不复制原件。""" - from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot + """加载样本冻结或当前 ready layout,并解引用压缩快照的 FileAsset 坐标证据。 + + 冻结 Layout 是签名和发布校验的历史事实;当 payload 只保留 + ``coordinate_evidence_ref`` 时,必须恢复其不可变坐标证据,不能误判为无版面证据。 + """ + from app.services.shipping_notice.document_layout.lifecycle import ( + _hydrate_coordinate_evidence, + current_layout_snapshot, + ) from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ( ensure_on_demand_coordinate_evidence, ) @@ -460,6 +471,11 @@ def _load_sample_layout(sample: ShippingOrderDocumentProfileSample) -> dict[str, from app.models import ShippingDocumentLayoutVersion frozen = db.session.get(ShippingDocumentLayoutVersion, int(sample.layout_version_id)) if frozen is not None and isinstance(frozen.payload_json, dict): + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + if document is not None: + return _hydrate_coordinate_evidence( + payload=dict(frozen.payload_json), document=document, + ) return dict(frozen.payload_json) document = db.session.get(ShippingOrderDocument, int(sample.document_id)) if document is None: @@ -675,6 +691,7 @@ def _build_coordinate_identity_snapshot( evidence = (snapshot.get('signature') or {}).get('evidence_quality') or {} return snapshot, { 'signature_version': LAYOUT_SIGNATURE_ID, + 'evidence_contract_version': LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION, 'signature_checksum': snapshot.get('signature_checksum'), 'matcher_policy_version': MATCHER_POLICY_ID, 'source_sample_count': evidence.get('source_sample_count') or len(samples), @@ -728,7 +745,15 @@ def _resolve_profile_identity_signature_run( or run.run_type != 'layout_signature' or run.status != 'passed' or run.definition_checksum != revision.definition_checksum + or not _signature_uses_current_evidence_contract(run) ): + if auto_run: + run_profile_identity_signature( + profile.id, data={}, actor_id=actor_id, browser_session_id=browser_session_id, + lease_token=lease_token, operation_id=str(operation_id or secrets.token_hex(16)), + ) + db.session.refresh(profile) + return _resolve_profile_identity_signature_run(profile, revision, auto_run=False) raise ValidationError( 'Profile identity signature is stale for the current draft', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE', @@ -742,6 +767,12 @@ def _resolve_profile_identity_signature_run( return run +def _signature_uses_current_evidence_contract(run: ShippingOrderDocumentProfileValidationRun) -> bool: + """仅允许已按当前 FileAsset 解引用契约生成的签名进入发布唯一性校验。""" + summary = getattr(run, 'summary_json', None) + return isinstance(summary, dict) and summary.get('evidence_contract_version') == LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION + + def resolve_profile_identity_signature( profile: ShippingOrderDocumentProfile, revision: ShippingOrderDocumentProfileDraftRevision, @@ -785,10 +816,16 @@ def _match_thresholds(definition: dict[str, Any]) -> dict[str, float]: """从 document_match 提取发布唯一性门禁阈值。""" document_match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {} thresholds = document_match.get('scoring_thresholds') if isinstance(document_match.get('scoring_thresholds'), dict) else {} + + def configured_or_default(source: dict[str, Any], key: str, default: float) -> float: + """保留合法的 0 阈值;只有缺失或空值才回退默认门禁。""" + value = source.get(key) + return float(default if value is None else value) + return { - 'minimum_score': float(document_match.get('minimum_score') or 0.9), - 'minimum_margin': float(document_match.get('minimum_margin') or 0.12), - 'evidence_coverage_minimum': float(thresholds.get('evidence_coverage_minimum') or 0.70), + 'minimum_score': configured_or_default(document_match, 'minimum_score', 0.9), + 'minimum_margin': configured_or_default(document_match, 'minimum_margin', 0.12), + 'evidence_coverage_minimum': configured_or_default(thresholds, 'evidence_coverage_minimum', 0.70), } @@ -1031,7 +1068,15 @@ def _resolve_layout_signature_run( or run.run_type != 'layout_signature' or run.status != 'passed' or run.definition_checksum != revision.definition_checksum + or not _signature_uses_current_evidence_contract(run) ): + if auto_run: + run_profile_identity_signature( + profile.id, data={}, actor_id=actor_id, browser_session_id=browser_session_id, + lease_token=lease_token, operation_id=str(operation_id or secrets.token_hex(16)), + ) + db.session.refresh(profile) + return _resolve_layout_signature_run(profile, revision, auto_run=False) raise ValidationError( 'Layout signature is stale for the current draft', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE', diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 9306a936..b64338ad 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -13,6 +13,24 @@ backend/app/services/shipping_notice/order_extraction.py from __future__ import annotations +def reconcile_review_case_after_unit(*, run: Any, unit: Any) -> Any: + """ + Unit 结果已消费时,确保 Review Case 后仍执行统一校验/自动推进协调。 + + Args: + run: Unit 所属的订单抽取 Run。 + unit: 已消费、需要回放的 PDF Unit。 + + Returns: + 确保后的 Review Case;协调器副作用会刷新校验结果并按资格决定后续自动推进。 + """ + from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit + from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run + + case = ensure_review_case_for_unit(run=run, unit=unit) + maybe_stp_auto_create_for_run(run=run) + return case + import hashlib import json from datetime import datetime @@ -34,7 +52,6 @@ from app.models import ( ShippingNotice, ShippingOrderExtraction, ) -from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates from app.services.shipping_notice.business_fingerprint import ( build_business_fingerprint, build_content_fingerprint, @@ -53,6 +70,47 @@ from app.services.shipping_notice.context_fields.runtime import canonical_mail_c from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_parser +def _discard_resolved_worker_field_conflicts( + conflicts: list[dict[str, Any]], + *, + decisions: list[dict[str, Any]], + blocked_fields: list[str], +) -> list[dict[str, Any]]: + """移除已由最终动态裁决解决的 Worker 早期字段证据缺失阻断。 + + Worker 可能在派生前先报告 ``evidence_missing``;Candidate 必须以 + persist_dynamic_order 的最终 Decision/blocked_fields 为准。仅移除字段级、 + 字段完整性归属的早期缺证冲突:真实跨来源冲突、非字段完整性冲突,以及最终 + 仍处于 blocked_fields 的必填或建单关键字段,一律保留。 + + Args: + conflicts: Worker 原始阻断冲突。 + decisions: 动态 Schema 最终字段裁决。 + blocked_fields: 派生后最终仍阻断流程的字段编码。 + + Returns: + 仍应投影到 Candidate 的阻断冲突。 + """ + unresolved = {str(code).strip() for code in blocked_fields if str(code or '').strip()} + resolved_fields = { + str(item.get('field_code') or '').strip() + for item in decisions + if isinstance(item, dict) + and item.get('status') in {'accepted', 'corroborated', 'derived'} + and str(item.get('field_code') or '').strip() not in unresolved + } + return [ + item for item in conflicts + if not ( + str(item.get('field') or '').strip() in resolved_fields + and str(item.get('reason') or '') == 'evidence_missing' + and str(item.get('owning_gate_code') or '') in { + 'field_completeness', 'order_field_extraction', + } + ) + ] + + def _runtime_session_for_run(run: Any) -> ChatSession | SimpleNamespace: """读取 Run 的 UI 会话;历史会话已清理时使用冻结身份继续持久化业务结果。 @@ -419,6 +477,11 @@ def persist_order_extraction_result( }, frozen_evidence_text_by_document=frozen_evidence_text_by_document, ) + blocking_conflicts = _discard_resolved_worker_field_conflicts( + blocking_conflicts, + decisions=list(dynamic.get('decisions') or []), + blocked_fields=list(dynamic.get('blocked_fields') or []), + ) if run_id is not None: dynamic['extraction'].run_id = int(run_id) layout_evidence_issues = [ @@ -856,67 +919,103 @@ def persist_order_extraction_result( ), ) - auto_candidate_nos = [row.candidate_no for row in auto_candidates] - create_result: dict[str, Any] | None = None - if auto_candidate_nos: - idem = f"extract:{current_snapshot[:48]}" - create_result = create_shipping_batch_from_candidates( - user_id=int(session.user_id), - conversation_id=session.session_id, - intake_nos=intake_nos, - candidate_nos=auto_candidate_nos, - create_idempotency_key=idem, - ) - # 建批事务已在启动编排器前绑定 Task 与已接受 Extraction;此处只完成本轮提交收口。 - db.session.commit() - else: - # [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。 - if not pending: - now = datetime.utcnow() - for intake in intakes: - intake.parse_status = 'consumed' - intake.consumed_at = now - intake.order_extraction_status = 'completed' - intake.updated_at = now - db.session.commit() - - create_data = (create_result or {}).get('data') - create_data = create_data if isinstance(create_data, dict) else {} - created = list(create_data.get('tasks') or []) - opened_existing = list( - (create_result or {}).get('opened_existing') - or create_data.get('opened_existing') - or [] - ) - for item in (create_result or {}).get('reconciliation_pending') or []: - if not isinstance(item, dict): + # [STEP 4] open_existing 是既有任务的安全跳转/字段对账,不是新建单路径。 + # 它必须在此单独收口,禁止借已删除批次编排器实现,也不得触发新单或自动推进。 + opened_existing: list[dict[str, Any]] = [] + for candidate in auto_candidates: + if ( + candidate.duplicate_resolution != 'open_existing' + or candidate.consumed_task_id is not None + or candidate.validation_status != 'ready' + ): continue - reconciliation = ( - item.get('reconciliation') - if isinstance(item.get('reconciliation'), dict) - else {} + target_no = str(candidate.duplicate_target_task_no or '').strip().upper() + if not target_no: + continue + target = ( + db.session.query(ShippingNotice) + .filter_by(task_no=target_no, user_id=int(session.user_id)) + .with_for_update() + .first() ) - pending.append({ - 'candidate_no': item.get('candidate_no'), - 'task_no': item.get('task_no'), - 'reasons': [ - str(reconciliation.get('reason') or 'open_existing_reconciliation_required') - ], - 'reconciliation': reconciliation, + if target is None: + continue + reconciliation: dict[str, Any] | None = None + duplicate_status = str(candidate.duplicate_status or '').strip() + if duplicate_status == 'exact_file': + from app.services.shipping_notice.open_existing_reservation_backfill import ( + backfill_exact_file_open_existing_reservations, + ) + + structured = ( + candidate.structured_result_json + if isinstance(candidate.structured_result_json, dict) + else {} + ) + extraction = ( + structured.get('extraction') + if isinstance(structured.get('extraction'), dict) + else {} + ) + reconciliation = backfill_exact_file_open_existing_reservations( + task=target, + candidate=candidate, + candidate_summary=( + structured.get('business_summary') + if isinstance(structured.get('business_summary'), dict) + else {} + ), + duplicate_status=duplicate_status, + duplicate_matches=[{'task_no': target.task_no}], + verified_reservation_evidence=list( + extraction.get('verified_reservation_evidence') or [] + ), + ) + # 对账服务仍以既有任务的动态字段及旧安全态为唯一依据;其内会在字段 + # 已安全补齐后推进到 parse_review,不能在这里二次推导或覆盖阶段。 + if ( + reconciliation.get('status') != 'applied' + and reconciliation.get('reason') not in { + 'duplicate_status_not_exact_file', + 'target_already_complete', + 'target_task_not_safe', + } + ): + candidate.selected = False + pending_item = { + 'candidate_no': candidate.candidate_no, + 'task_no': target.task_no, + 'reasons': [str(reconciliation.get('reason') or 'open_existing_reconciliation_required')], + 'reconciliation': reconciliation, + } + pending.append(pending_item) + pending_by_intake[int(candidate.intake_id)].append(pending_item) + continue + candidate.consumed_task_id = int(target.id) + candidate.updated_at = datetime.utcnow() + opened_existing.append({ + 'candidate_no': candidate.candidate_no, + 'task_no': target.task_no, + **({'reconciliation': reconciliation} if reconciliation is not None else {}), }) - created_count = len(created) + + # Candidate 只进入 Review Case/STP;禁止旧抽取链绕过确认直接创建批次或 Task。 + if not pending: + now = datetime.utcnow() + for intake in intakes: + intake.parse_status = 'consumed' + intake.consumed_at = now + intake.order_extraction_status = 'completed' + intake.updated_at = now + db.session.commit() + + created: list[dict[str, Any]] = [] + created_count = 0 opened_existing_count = len(opened_existing) - created_with_missing_fields_count = sum( - 1 - for candidate in auto_candidates - if candidate.duplicate_resolution != 'open_existing' and candidate.missing_fields_json - ) - # 下层响应缺失任务明细属于契约异常;摘要只能陈述已持久化并返回的 Task,不能回退到 Candidate 数。 - created_with_missing_fields_count = min(created_with_missing_fields_count, created_count) + created_with_missing_fields_count = 0 result = { 'status': 'ok', 'request_id': request_id, - 'batch_no': create_result.get('batch_no') if create_result else None, 'created': created, 'opened_existing': opened_existing, 'pending_orders': pending, @@ -1014,7 +1113,6 @@ def submit_order_extraction_run_result( result = { 'status': 'ok', 'request_id': str(run.run_no), - 'batch_no': None, 'created': [{'task_no': task_no} for task_no in task_nos], 'opened_existing': [], 'pending_orders': [{'candidate_no': item.candidate_no} for item in pending], @@ -1060,7 +1158,6 @@ def submit_order_extraction_run_result( result = { 'status': 'ok', 'request_id': str(run.run_no), - 'batch_no': None, 'created': [], 'opened_existing': [], 'pending_orders': [], @@ -1258,7 +1355,6 @@ def submit_order_extraction_unit_result( result = { 'status': 'ok', 'request_id': str(run.run_no), - 'batch_no': None, 'created': [{'task_no': task_no} for task_no in task_nos], 'opened_existing': [], 'pending_orders': [], @@ -1271,8 +1367,7 @@ def submit_order_extraction_unit_result( 'idempotent_replay': True, 'unit_id': int(unit.id), } - from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit - ensure_review_case_for_unit(run=run, unit=unit) + reconcile_review_case_after_unit(run=run, unit=unit) return result session = _runtime_session_for_run(run) diff --git a/backend/app/services/shipping_notice/order_extraction_route_contract.py b/backend/app/services/shipping_notice/order_extraction_route_contract.py index 612ff0b7..32d79d1c 100644 --- a/backend/app/services/shipping_notice/order_extraction_route_contract.py +++ b/backend/app/services/shipping_notice/order_extraction_route_contract.py @@ -105,6 +105,11 @@ STABLE_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({ 'no_special_profile_feature', 'generic_extraction_disabled', 'generic_gate_blocked', + 'coordinate_evidence_unavailable', + # Runtime Parse Strategy:当前文档的坐标/行结构判断无法唯一裁决时固定进入 Review。 + 'PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION', + 'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS', + 'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION', 'llm_review_disabled', 'extraction_emergency_stop', 'rejected', diff --git a/backend/app/services/shipping_notice/order_extraction_run_service.py b/backend/app/services/shipping_notice/order_extraction_run_service.py index a0ff4891..7dee2a91 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/order_extraction_run_service.py 用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。 依赖:Agent/ChatSession、ShippingOrderIntake/Document、已发布订单 Schema、SQLAlchemy 事务、 - order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress、 + order_extraction.submit_order_extraction_unit_result、 workflow_ledger_service(物化后幂等建 WorkflowItem)、process_gate_bridge(Execution 创建)、 error_explainability_contract(Run 失败可解释性投影)、 conversation_processing_projection(会话多任务投影)、audit_service。 @@ -34,7 +34,7 @@ from typing import Any from flask import current_app from sqlalchemy.exc import IntegrityError -from sqlalchemy import and_, or_ +from sqlalchemy import and_, func, or_, select from app import db from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError @@ -852,6 +852,7 @@ def _build_snapshot( parse_email_allocation_text, ) from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract + from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan table_contract = compile_table_header_contract(dict(schema_version.definition_json or {})) generic_config = ( @@ -918,7 +919,7 @@ def _build_snapshot( ) if isinstance(email_supplement, dict): email_supplement['document_id'] = int(document.id) - documents_by_intake[document.intake_id].append({ + document_snapshot = { 'document_id': document.id, 'document_type': document.document_type, 'attachment_key': document.attachment_key, @@ -933,7 +934,15 @@ def _build_snapshot( 'layout_snapshot': layout_snapshot, 'layout_schema_candidates': layout_schema_candidates, 'email_supplement': email_supplement, - }) + } + # 自动标注候选只在冻结 Schema/Layout 身份下编译为 Parse Plan;Worker 不得 + # 直接消费 layout_schema_candidates。 + document_snapshot['generic_parse_plan'] = compile_generic_parse_plan( + candidates=layout_schema_candidates, + schema_checksum=str(schema_version.checksum or ''), + layout_snapshot=layout_snapshot if isinstance(layout_snapshot, dict) else {}, + ) + documents_by_intake[document.intake_id].append(document_snapshot) incomplete = [ intake.intake_no for intake in intakes @@ -1366,6 +1375,7 @@ def materialize_order_extraction_run_inputs( from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract + from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan table_contract = compile_table_header_contract(dict(contract)) document_ids = _run_snapshot_document_ids(run) if document_ids: @@ -1411,6 +1421,11 @@ def materialize_order_extraction_run_inputs( candidates = [{'mapping_status': 'failed', 'issues': ['layout_schema_mapping_invalid']}] item['layout_snapshot'] = layout_snapshot item['layout_schema_candidates'] = candidates + item['generic_parse_plan'] = compile_generic_parse_plan( + candidates=candidates, + schema_checksum=str(schema.get('checksum') or ''), + layout_snapshot=layout_snapshot if isinstance(layout_snapshot, dict) else {}, + ) changed = True if changed: from sqlalchemy.orm.attributes import flag_modified @@ -2442,7 +2457,7 @@ def submit_order_extraction( """ from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.shipping_processing_projection import ( - project_conversation_processing_items, + project_conversation_processing_summary, ) normalized_submission = str(submission_id or '').strip() @@ -2466,17 +2481,11 @@ def submit_order_extraction( ) can_append, block_reason = evaluate_can_append(existing) existing_task_no = str(getattr(existing, 'user_task_no', None) or '').strip() or None - unified = project_conversation_processing_items( + unified = project_conversation_processing_summary( user_id=user.id, conversation_id=existing.conversation_id, focused_task_no=existing_task_no, recent_task_no=existing_task_no, - recent_decision=decision, - recent_append_count=( - int(existing_row.appended_intake_count) - if existing_row is not None and decision == 'appended' - else None - ), ) return { 'decision': decision, @@ -2497,7 +2506,6 @@ def submit_order_extraction( existing.input_frozen_at.isoformat() + 'Z' if existing.input_frozen_at else None ), 'processing': unified.get('conversation_processing'), - 'work_items': unified.get('work_items') or [], } # [STEP 2] 解析可追加目标。 @@ -2776,16 +2784,14 @@ def submit_order_extraction( persisted_task_no = str(getattr(run, 'user_task_no', None) or '').strip() or None from app.services.shipping_notice.shipping_processing_projection import ( - project_conversation_processing_items, + project_conversation_processing_summary, ) - unified = project_conversation_processing_items( + unified = project_conversation_processing_summary( user_id=user.id, conversation_id=run.conversation_id, focused_task_no=persisted_task_no, recent_task_no=persisted_task_no, - recent_decision=decision, - recent_append_count=appended_count if decision == 'appended' else None, ) return { 'decision': decision, @@ -2803,7 +2809,6 @@ def submit_order_extraction( run.input_frozen_at.isoformat() + 'Z' if run.input_frozen_at else None ), 'processing': unified.get('conversation_processing'), - 'work_items': unified.get('work_items') or [], } @@ -2826,7 +2831,7 @@ def focus_conversation_task( _latest_focused_task_no, ) from app.services.shipping_notice.shipping_processing_projection import ( - project_conversation_processing_items, + project_conversation_processing_summary, ) normalized_task = str(task_no or '').strip() @@ -2863,7 +2868,7 @@ def focus_conversation_task( after={'focused_task_no': normalized_task, 'run_no': run.run_no}, metadata={'user_task_no': normalized_task}, ) - unified = project_conversation_processing_items( + unified = project_conversation_processing_summary( user_id=user_id, conversation_id=run.conversation_id, focused_task_no=normalized_task, @@ -2871,7 +2876,6 @@ def focus_conversation_task( return { 'focused_task_no': normalized_task, 'processing': unified.get('conversation_processing'), - 'work_items': unified.get('work_items') or [], } @@ -2891,7 +2895,7 @@ def mark_conversation_task_viewed( """ from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.shipping_processing_projection import ( - project_conversation_processing_items, + project_conversation_processing_summary, ) normalized_task = str(task_no or '').strip() @@ -2927,7 +2931,7 @@ def mark_conversation_task_viewed( after={'seen_at': run.seen_at.isoformat() + 'Z', 'user_task_no': normalized_task}, metadata={'user_task_no': normalized_task}, ) - unified = project_conversation_processing_items( + unified = project_conversation_processing_summary( user_id=user_id, conversation_id=run.conversation_id, focused_task_no=normalized_task, @@ -2935,7 +2939,6 @@ def mark_conversation_task_viewed( return { 'user_task_no': normalized_task, 'processing': unified.get('conversation_processing'), - 'work_items': unified.get('work_items') or [], } @@ -3289,6 +3292,75 @@ def list_order_extraction_runs( } +def list_order_extraction_run_summaries( + *, + user_id: int, + conversation_id: str | None = None, + limit: int = 50, + status: str | None = None, + page: int | None = None, + page_size: int | None = None, +) -> list[dict[str, Any]] | dict[str, Any]: + """ + 为会话恢复和任务中心读取固定成本 Run 摘要,禁止加载冻结输入快照。 + + 核心逻辑:列表端只需定位最新 Run 与展示摘要,故用标量列投影直接绕过 ORM 实体; + `input_snapshot_json` / `request_snapshot_json` 只能由单 Run 详情路径按需读取。 + + Args: + user_id: 当前用户主键。 + conversation_id: 可选会话过滤。 + limit: 非分页模式的条数上限。 + status: 可选业务状态过滤。 + page: 可选分页页码。 + page_size: 可选分页大小。 + + Returns: + 非分页:摘要字典列表;分页:{items, total, page, page_size}。 + """ + normalized_status = str(status or '').strip() or None + if normalized_status and normalized_status not in { + 'queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled', + }: + raise ValidationError('status is invalid') + + filters = [ShippingOrderProcessingRun.user_id == user_id] + if conversation_id: + filters.append(ShippingOrderProcessingRun.conversation_id == conversation_id) + if normalized_status: + filters.append(ShippingOrderProcessingRun.status == normalized_status) + columns = ( + ShippingOrderProcessingRun.run_no, + ShippingOrderProcessingRun.user_task_no, + ShippingOrderProcessingRun.owner_agent_id, + ShippingOrderProcessingRun.conversation_id, + ShippingOrderProcessingRun.status, + ShippingOrderProcessingRun.phase, + ShippingOrderProcessingRun.progress_summary_json, + ShippingOrderProcessingRun.progress_version, + ShippingOrderProcessingRun.last_activity_at, + ShippingOrderProcessingRun.created_at, + ShippingOrderProcessingRun.updated_at, + ) + statement = select(*columns).where(*filters).order_by(ShippingOrderProcessingRun.created_at.desc()) + if page is None and page_size is None: + return list(db.session.execute( + statement.limit(min(max(int(limit or 50), 1), 100)), + ).mappings()) + safe_page = max(1, int(page or 1)) + safe_page_size = min(100, max(1, int(page_size or 20))) + total = db.session.scalar(select(func.count()).select_from(ShippingOrderProcessingRun).where(*filters)) or 0 + rows = list(db.session.execute( + statement.offset((safe_page - 1) * safe_page_size).limit(safe_page_size), + ).mappings()) + return { + 'items': rows, + 'total': int(total), + 'page': safe_page, + 'page_size': safe_page_size, + } + + def _reparse_difference_summary(run: ShippingOrderProcessingRun) -> dict[str, Any] | None: """返回新版与来源 Run 的脱敏规则差异计数,禁止比较或暴露邮件正文和 Provider 输出。""" source = run.reparse_source @@ -3546,6 +3618,7 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str, 'primary_notice': workspace_projection.get('primary_notice'), 'user_visible_stage': workspace_projection.get('user_visible_stage'), 'health_tips': workspace_projection.get('health_tips') or [], + 'lifecycle_progress': workspace_projection.get('lifecycle_progress') or {}, 'cancellation': workspace_projection.get('cancellation'), 'progress_version': workspace_projection.get('progress_version'), 'elapsed_seconds': workspace_projection.get('elapsed_seconds'), @@ -3561,6 +3634,35 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str, } +def serialize_order_extraction_run_list_item(run: Any) -> dict[str, Any]: + """序列化标量 Run 列表行;不得访问 ORM 冻结快照或工作台投影。""" + row = run if hasattr(run, 'get') else run._mapping + progress_summary = row.get('progress_summary_json') if isinstance(row.get('progress_summary_json'), dict) else {} + return { + 'run_no': row['run_no'], + 'user_task_no': row['user_task_no'], + 'agent_id': row['owner_agent_id'], + 'conversation_id': row['conversation_id'], + 'status': str(row['status'] or 'queued'), + 'phase': str(row['phase'] or row['status'] or 'queued'), + 'summary': { + 'total_documents': int(progress_summary.get('total_documents') or 0), + 'pending_documents': int(progress_summary.get('pending_documents') or 0), + 'processing_documents': int(progress_summary.get('processing_documents') or 0), + 'completed_documents': int(progress_summary.get('completed_documents') or 0), + 'review_required_documents': int(progress_summary.get('review_required_documents') or 0), + 'failed_documents': int(progress_summary.get('failed_documents') or 0), + 'cancelled_documents': int(progress_summary.get('cancelled_documents') or 0), + 'candidate_count': int(progress_summary.get('candidate_count') or 0), + 'opened_existing_documents': int(progress_summary.get('opened_existing_documents') or 0), + }, + 'progress_version': int(row['progress_version'] or 0), + 'last_activity_at': row['last_activity_at'].isoformat() + 'Z' if row['last_activity_at'] else None, + 'created_at': row['created_at'].isoformat() + 'Z' if row['created_at'] else None, + 'updated_at': row['updated_at'].isoformat() + 'Z' if row['updated_at'] else None, + } + + def serialize_order_extraction_message_state(run: ShippingOrderProcessingRun) -> dict[str, Any]: """把服务端 Run 事实投影为聊天状态卡;历史恢复和实时持久化必须共用同一映射。""" from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state @@ -4359,10 +4461,11 @@ def progress_ready_extraction_unit( orders: list[dict[str, Any]], ) -> dict[str, Any]: """ - 单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 STP 触发下游 auto_progress。 + 单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 Review Case/STP 正式链触发下游。 - 核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit;建批路径由编排器 - 调用 progress_workflow.auto_progress;若仅打开既有任务则不重复推进。 + 核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit。自动建单与自动推进 + 由 submit 内的 Review Case/STP 正式链异步协调,禁止此处再以已删除的 batch_no 或 + 结果数组推断并直接调用旧 auto_progress,避免重复推进。 Args: run: 所属抽取 Run。 @@ -4376,21 +4479,6 @@ def progress_ready_extraction_unit( mark_order_extraction_persistence_started(run) result = submit_order_extraction_unit_result(run=run, unit=unit, orders=orders) - # 建批编排器会异步调用同一 auto_progress;此处仅为无编排器的已创建任务兜底同步推进。 - created = list(result.get('created') or []) - if created and not result.get('batch_no') and not result.get('idempotent_replay'): - from app.services.shipping_notice.progress_workflow import auto_progress - for item in created: - task_no = str(item.get('task_no') or '').strip() - if not task_no: - continue - try: - auto_progress({'task_id': task_no, 'source': 'system'}) - except Exception: - current_app.logger.exception( - 'STP auto_progress failed after unit persist run=%s unit=%s task=%s', - run.run_no, getattr(unit, 'id', None), task_no, - ) return result diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index a521fc61..d3a1a077 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -25,7 +25,18 @@ from app.services.shipping_notice.order_extraction_runtime_snapshot import ( from app.services.shipping_notice.document_layout.html_table import parse_html_grid from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract -from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows +from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + coordinate_profile_character_candidates, + reconstruct_coordinate_profile_rows, reconstruct_coordinate_profile_rows_with_strategy, + reconstruction_exclusion_regions, +) +from app.services.shipping_notice.document_layout.coordinate_transform import ( + apply_coordinate_transform_to_region, +) +from app.services.shipping_notice.document_layout.runtime_parse_strategy import ( + resolve_runtime_parse_strategy, + select_runtime_region_ids, +) from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields from app.services.shipping_notice.document_layout.order_profile_matcher import ( ProfileMatchResult, @@ -44,6 +55,10 @@ from app.services.shipping_notice.order_extraction_route_contract import ( from app.services.shipping_notice.tool_common import generic_extraction_enabled, profile_auto_selection_enabled from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value +from app.services.shipping_notice.reservation_region import ( + apply_reservation_region_candidates, + extract_reservation_from_vendor_comments_pages, +) @dataclass(frozen=True) @@ -278,6 +293,8 @@ def _frozen_order_profile(raw: dict[str, Any]) -> OrderCoordinateProfile: table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, ) @@ -312,6 +329,8 @@ def _coordinate_profile_rows( *, raw_profile: dict[str, Any], raw_table: dict[str, Any], layout: dict[str, Any], contract: Any, schema_fields: dict[str, dict[str, Any]], document_id: int | None = None, initial_carry: dict[str, Any] | None = None, + coordinate_transform: dict[str, Any] | None = None, + row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] = 'fixed_subrows', ) -> list[dict[str, Any]] | None: """ 用模板表区和整页字符生成带字段坐标的紧凑行候选。 @@ -324,6 +343,7 @@ def _coordinate_profile_rows( schema_fields: field_id/code 对应的冻结 Schema 字段。 document_id: 当前 Unit 文档 ID;提供时生成稳定 token/evidence 引用。 initial_carry: 跨页固定子行的已解析字段。 + coordinate_transform: 共同 matcher 对当前唯一 Profile 已确认的平移;不在本函数重算。 Returns: 规范化字段行;坐标前置条件缺失时返回 None。 @@ -351,12 +371,13 @@ def _coordinate_profile_rows( if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0: return None rows: list[dict[str, Any]] = [] + runtime_region_ids = set(select_runtime_region_ids( + table_regions=[region.model_dump() for region in profile.table_regions], page_no=page_no, + )) for region in profile.table_regions: - if region.page_scope == 'first_page' and page_no != 1: - continue - if region.page_scope == 'continuation_pages' and page_no <= 1: - continue - if region.page_scope == 'exact_page' and page_no != region.page_no: + # 标注页优先;续页仅回退到稳定的基础表区。是否真正属于明细页仍由当前页 + # 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。 + if region.region_id not in runtime_region_ids: continue # A continuation page may carry column headers only; it is not a data layout. if not region.line_layouts: @@ -364,41 +385,42 @@ def _coordinate_profile_rows( relative_region = _coordinate_region_mapping(region.region) if relative_region is None: return None - region_bbox = { - 'x0': relative_region['x0'] * page_bbox['x1'], - 'y0': relative_region['y0'] * page_bbox['y1'], - 'x1': relative_region['x1'] * page_bbox['x1'], - 'y1': relative_region['y1'] * page_bbox['y1'], - } + reference_page_frame = profile.reference_page_frames.get(page_no) + reconstruction_page_bbox = ( + { + 'x0': 0, 'y0': 0, + 'x1': reference_page_frame.width, 'y1': reference_page_frame.height, + } + if reference_page_frame is not None else page_bbox + ) raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None - if not is_virtual_page and raw_bbox is not None and not _coordinate_regions_overlap(raw_bbox, region_bbox): - continue - # [STEP] 横向边界服从模板;纵向取模板样例区与真实物理表的并集。模板 y 区间只描述 - # 一条样例版式,不能截掉其后重复明细;MinerU 框过短时仍由模板区保住 continuation。 - evidence_bbox = dict(region_bbox) - if raw_bbox is not None: - evidence_bbox['y0'] = min(region_bbox['y0'], float(raw_bbox.get('y0', region_bbox['y0']))) - evidence_bbox['y1'] = max(region_bbox['y1'], float(raw_bbox.get('y1', region_bbox['y1']))) - if isinstance(page_characters, list): - characters = [ - item for item in page_characters - if isinstance(item, dict) and _coordinate_character_in_region(item, evidence_bbox) - ] - else: - # 历史快照没有整页字符时保留表内字符兼容;新快照必须优先整页证据。 - characters = tables.get(table_id) + characters, _candidate_page_bbox = coordinate_profile_character_candidates( + table_region=region.region.model_dump(), page_size=page_size, + reference_page_frame=( + reference_page_frame.model_dump() if reference_page_frame is not None else None + ), + page_characters=page_characters if isinstance(page_characters, list) else None, + table_characters=tables.get(table_id) if isinstance(tables.get(table_id), list) else None, + raw_table_bbox=raw_bbox, table_id=table_id, page_no=page_no, + coordinate_transform=coordinate_transform, + allow_table_fallback=(not is_virtual_page and page_no == int(raw_table.get('page_no') or 1)), + ) if not isinstance(characters, list): return None carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {} for reconstructed in reconstruct_coordinate_profile_rows( - characters=[item for item in characters if isinstance(item, dict)], table_bbox=page_bbox, + characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_page_bbox, line_layouts=[item.model_dump() for item in region.line_layouts], table_region=relative_region, termination_rules=[item.model_dump() for item in region.termination_rules], - exclusion_regions=[item.model_dump() for item in region.exclusion_regions], + exclusion_regions=reconstruction_exclusion_regions( + region.model_dump(), + ), initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0), line_start_field_code=region.line_start_field_code, - row_reconstruction_mode=region.row_reconstruction_mode, + row_reconstruction_mode=row_reconstruction_mode, + coordinate_transform=coordinate_transform, + schema_field_metadata=list(schema_fields.values()), ): values: list[dict[str, Any]] = [] issues = list(reconstructed.issues) @@ -442,6 +464,47 @@ def _coordinate_profile_rows( return rows +def _selected_coordinate_transform( + *, profile_match: dict[str, Any], raw_profile: dict[str, Any], +) -> dict[str, Any] | None: + """仅为显式 anchor_frame 模板转交 matcher 的已选变换。 + + 普通 legacy 模板的绝对字段坐标已由其发布盲测验证;matcher 为提高身份匹配 + 鲁棒性推导的临时位移不得改变这类模板的正式取值区域。 + """ + if str(profile_match.get('status') or '') not in {'unique_match', 'selected_by_score'}: + return None + definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {} + coordinate_model = definition.get('coordinate_model') if isinstance(definition.get('coordinate_model'), dict) else {} + if str(coordinate_model.get('type') or 'legacy') != 'anchor_frame': + return None + identity = ( + str(raw_profile.get('profile_code') or ''), + int(raw_profile.get('version') or 0), + str(raw_profile.get('checksum') or ''), + ) + for candidate in profile_match.get('candidates') or []: + if not isinstance(candidate, dict): + continue + candidate_identity = ( + str(candidate.get('profile_code') or ''), + int(candidate.get('version') or 0), + str(candidate.get('checksum') or profile_match.get('checksum') or ''), + ) + if candidate_identity[:2] != identity[:2]: + continue + transform = candidate.get('coordinate_transform') + return transform if isinstance(transform, dict) else None + return None + + +def _translate_coordinate_region( + region: dict[str, float], *, coordinate_transform: dict[str, Any] | None, +) -> dict[str, float] | None: + """在裁剪页级 glyph 前应用 matcher 已确认的统一坐标变换,非法声明 fail-closed。""" + return apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform) + + def _coordinate_region_mapping(value: Any) -> dict[str, float] | None: """将模板相对区域统一为坐标字典,供绝对裁剪与行重建共同使用。 @@ -481,6 +544,69 @@ def _coordinate_regions_overlap(left: dict[str, Any], right: dict[str, Any]) -> return False +def _physical_table_targets_profile_region( + *, raw_table: dict[str, Any], table_regions: list[dict[str, Any]], page_size: dict[str, Any] | None, + reference_page_frame: dict[str, Any] | None = None, + coordinate_transform: dict[str, Any] | None = None, +) -> bool: + """判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。 + + 同页的页脚汇总、签章等 MinerU 物理表不属于订单明细模板,不能因其无法重建 + 而阻断已成功的目标表。虚拟页、缺失 bbox 或页尺寸异常时维持既有整页坐标回退, + 避免表检测遗漏被错误跳过。 + """ + page_no = int(raw_table.get('page_no') or 1) + if str(raw_table.get('table_id') or '') == f'page-{page_no}': + return True + raw_bbox = raw_table.get('bbox') + if not isinstance(raw_bbox, dict) or not isinstance(page_size, dict): + return True + try: + page_width, page_height = float(page_size['width']), float(page_size['height']) + projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else page_width + projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else page_height + except (KeyError, TypeError, ValueError): + return True + if page_width <= 0 or page_height <= 0 or projection_width <= 0 or projection_height <= 0: + return True + active_region_ids = set(select_runtime_region_ids( + table_regions=table_regions, page_no=page_no, + )) + active_regions = [ + region for region in table_regions + if isinstance(region, dict) + and str(region.get('region_id') or '') in active_region_ids + and isinstance(region.get('region'), dict) + and region.get('line_layouts') + ] + if not active_regions: + return True + for region in active_regions: + projected = apply_coordinate_transform_to_region( + region['region'], coordinate_transform=coordinate_transform, + ) + if projected is None: + continue + absolute_region = { + 'x0': projected['x0'] * projection_width, 'y0': projected['y0'] * projection_height, + 'x1': projected['x1'] * projection_width, 'y1': projected['y1'] * projection_height, + } + if _coordinate_regions_overlap(raw_bbox, absolute_region): + return True + return False + + +def _virtual_page_without_rows_is_nonblocking( + *, raw_table: dict[str, Any], fixed_rows: list[dict[str, Any]] | None, + adaptive_rows: list[dict[str, Any]] | None, dynamic_rows: list[dict[str, Any]] | None = None, +) -> bool: + """空虚拟页只作为漏检表格的补偿候选,不能把已有目标表成功覆盖为失败。""" + page_no = int(raw_table.get('page_no') or 1) + if str(raw_table.get('table_id') or '') != f'page-{page_no}': + return False + return not (fixed_rows or []) and not (adaptive_rows or []) and not (dynamic_rows or []) + + def _coordinate_character_in_region(character: dict[str, Any], region: dict[str, float]) -> bool: """按字符中心点裁剪模板表区,避免边缘字形重叠把页头或相邻表带入。""" bbox = character.get('bbox') if isinstance(character.get('bbox'), dict) else None @@ -685,13 +811,30 @@ def _profile_table_candidates( if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version and str(item.get('checksum') or '') == match.checksum ] + # 只有唯一选中的模板显式标注了 Reservation 专区,才补齐全文坐标并开启 + # Vendor Comments→Terms 跨页扫描;其他候选模板不得改变未标注模板的读取范围。 + selected_reservation_region = ( + (profiles[0].get('definition') or {}).get('reservation_id_region') + if len(profiles) == 1 and isinstance(profiles[0], dict) else None + ) + if isinstance(selected_reservation_region, dict) and document_model is not None: + layout = ensure_on_demand_coordinate_evidence( + document=document_model, layout=layout, page_nos=None, + table_by_page={int(item.get('page_no') or 1): item for item in raw_tables}, + ) if match_only: + reservation_region = ( + _reservation_region_candidates(raw_profile=profiles[0], layout=layout) + if len(profiles) == 1 else {'candidates': [], 'reason': None} + ) return { 'matched': True, 'blocking': False, 'tables': [], 'issues': [], 'match': profile_match, + 'reservation_region_candidates': reservation_region['candidates'], + 'reservation_region_reason': reservation_region['reason'], } result_tables: list[dict[str, Any]] = [] issues: list[str] = [] @@ -734,6 +877,28 @@ def _profile_table_candidates( # MinerU HTML is intentionally neither required nor parsed on this path. try: profile = _frozen_coordinate_profile(raw_profile) + coordinate_transform = _selected_coordinate_transform( + profile_match=profile_match, raw_profile=raw_profile, + ) + profile_table_regions = [ + item.model_dump() for item in profile.table_regions + if callable(getattr(item, 'model_dump', None)) + ] + evidence_pages = ( + (layout.get('coordinate_evidence') or {}).get('pages') or {} + ) + page_size = evidence_pages.get(str(raw_table.get('page_no') or 1)) + reference_page_frame = profile.reference_page_frames.get(int(raw_table.get('page_no') or 1)) + if not _physical_table_targets_profile_region( + raw_table=raw_table, + table_regions=profile_table_regions, + page_size=page_size if isinstance(page_size, dict) else None, + reference_page_frame=( + reference_page_frame.model_dump() if reference_page_frame is not None else None + ), + coordinate_transform=coordinate_transform, + ): + continue carry = None parent_table_id = str(raw_table.get('continuation_of') or '') if parent_table_id: @@ -745,17 +910,51 @@ def _profile_table_candidates( ): carry = candidate break - coordinate_rows = _coordinate_profile_rows( + fixed_rows = _coordinate_profile_rows( raw_profile=raw_profile, raw_table=raw_table, layout=layout, contract=contract, schema_fields=schema_fields, document_id=int(unit.document_id), initial_carry=carry, + coordinate_transform=coordinate_transform, + row_reconstruction_mode='fixed_subrows', + ) + adaptive_rows = _coordinate_profile_rows( + raw_profile=raw_profile, raw_table=raw_table, layout=layout, + contract=contract, schema_fields=schema_fields, + document_id=int(unit.document_id), initial_carry=None, + coordinate_transform=coordinate_transform, + row_reconstruction_mode='adaptive_record_columns', + ) + dynamic_rows = _coordinate_profile_rows( + raw_profile=raw_profile, raw_table=raw_table, layout=layout, + contract=contract, schema_fields=schema_fields, + document_id=int(unit.document_id), initial_carry=None, + coordinate_transform=coordinate_transform, + row_reconstruction_mode='dynamic_x_columns', ) except (TypeError, ValueError): issues.append('order_profile_snapshot_invalid') continue - if coordinate_rows is None: + if fixed_rows is None or adaptive_rows is None or dynamic_rows is None: issues.append('order_profile_coordinate_reconstruction_unavailable') continue + if _virtual_page_without_rows_is_nonblocking( + raw_table=raw_table, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, + dynamic_rows=dynamic_rows, + ): + continue + strategy = resolve_runtime_parse_strategy( + page_glyphs=(layout.get('coordinate_evidence') or {}).get('page_glyphs') or {}, + fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, + dynamic_rows=dynamic_rows, + ) + if strategy.status != 'selected' or strategy.row_mode is None: + issues.extend(strategy.reason_codes) + continue + coordinate_rows = ( + fixed_rows if strategy.row_mode == 'fixed_subrows' + else adaptive_rows if strategy.row_mode == 'adaptive_record_columns' + else dynamic_rows + ) if coordinate_rows: complete_rows = [] for row in coordinate_rows: @@ -763,7 +962,7 @@ def _profile_table_candidates( if ( region is not None and region.continuation_rule.allow_cross_page - and region.row_reconstruction_mode == 'fixed_subrows' + and strategy.row_mode == 'fixed_subrows' and row.get('_coordinate_row_count', 0) < len(region.line_layouts) ): cross_page_carries[(str(raw_profile.get('profile_code') or ''), table_id)] = { @@ -790,6 +989,7 @@ def _profile_table_candidates( issues.append('order_profile_multiple_matches') continue raw_profile, parsed = matches[0] + reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout) result_tables.append({ 'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'), 'profile_code': str(raw_profile.get('profile_code') or ''), @@ -799,6 +999,13 @@ def _profile_table_candidates( 'page_no': int(raw_table.get('page_no') or 1), 'auto_create_approved': bool(raw_profile.get('auto_create_approved')), 'rows': parsed, + 'reservation_region_candidates': reservation_region['candidates'], + 'reservation_region_reason': reservation_region['reason'], + 'runtime_parse_strategy': { + 'page_nos': list(strategy.page_nos), + 'row_mode': strategy.row_mode, + 'reason_codes': list(strategy.reason_codes), + }, }) return { 'matched': matched_any, @@ -1400,8 +1607,12 @@ def _extract_generic_evidence_result( from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate candidates = document.get('layout_schema_candidates') if isinstance(document.get('layout_schema_candidates'), list) else [] + parse_plan = document.get('generic_parse_plan') if isinstance(document.get('generic_parse_plan'), dict) else None gate = evaluate_generic_extraction_gate( candidates=candidates, + parse_plan=parse_plan, + layout_snapshot=document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}, + require_parse_plan=True, definition=definition, schema=schema, intake=intake, @@ -1471,16 +1682,30 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult decision = adapter_result.decision # [STEP 2] 公共建单:任何 adapter 只能交付 table/证据,不能自行裁决生命周期。 if adapter_result.table is not None: + reservation_candidates = ( + adapter_result.table.get('reservation_region_candidates') + if isinstance(adapter_result.table, dict) else None + ) + if not isinstance(reservation_candidates, list): + reservation_candidates = profile_result.get('reservation_region_candidates') + reservation_region_reason = ( + adapter_result.table.get('reservation_region_reason') + if isinstance(adapter_result.table, dict) else None + ) or profile_result.get('reservation_region_reason') orders, reason_code = _build_approved_profile_order_result( unit=unit, intake=intake, schema=schema, definition=definition, table=adapter_result.table, confirmed_order_fields=adapter_result.confirmed_order_fields, allow_manual_review=False, + reservation_region_candidates=reservation_candidates if isinstance(reservation_candidates, list) else None, + reservation_region_reason=str(reservation_region_reason or '') or None, ) if orders is None and adapter_result.allow_manual_row_review and reason_code == 'row_needs_review': orders, review_reason = _build_approved_profile_order_result( unit=unit, intake=intake, schema=schema, definition=definition, table=adapter_result.table, confirmed_order_fields=adapter_result.confirmed_order_fields, allow_manual_review=True, + reservation_region_candidates=reservation_candidates if isinstance(reservation_candidates, list) else None, + reservation_region_reason=str(reservation_region_reason or '') or None, ) if orders is not None: decision['fallback_reason_codes'] = ['row_needs_review'] @@ -1491,8 +1716,21 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult if adapter_result.attach_formal_evidence: order['_hxops_formal_evidence'] = (adapter_result.evidence or {}).get('formal_evidence_summary') order['_hxops_value_source_identity'] = (adapter_result.evidence or {}).get('value_source_identity') + _normalize_profile_order_observations( + orders, + default_value_source=adapter_name, + coordinate_transform=_selected_coordinate_transform( + profile_match=match, + raw_profile=selected_profile, + ) if adapter_name == 'coordinate_ocr' and isinstance(selected_profile, dict) else None, + ) decision['parsed_table_count'] = 1 decision['route_type'] = 'profile_deterministic' + if any(order.get('reservation_region_status') == 'needs_review' for order in orders): + decision['fallback_reason_codes'] = ['reservation_region_needs_review'] + return _apply_stp_route_adjudication( + decision, execution_mode='review_required', orders=orders, + ) if decision.get('fallback_reason_codes'): return _apply_stp_route_adjudication( decision, execution_mode='review_required', orders=orders, @@ -1561,6 +1799,8 @@ def _route_reason_for_issue(issue: str) -> str: 'order_profile_snapshot_field_mismatch': 'profile_schema_mismatch', 'order_profile_multiple_matches': 'profile_ambiguous', 'order_profile_coordinate_reconstruction_unavailable': 'coordinate_evidence_unavailable', + 'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS': 'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS', + 'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION': 'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION', } # 第零层:on-demand 坐标恢复失败码直接收敛为证据不可用,不经过 fallback 误报为 drift。 if str(issue).startswith('coordinate_evidence_'): @@ -1575,13 +1815,34 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfile: profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0), document_match=definition.get('document_match'), table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, ) +def _reservation_region_candidates(*, raw_profile: dict[str, Any], layout: dict[str, Any]) -> dict[str, Any]: + """仅对已标注专区的模板,跨页读取 Vendor Comments 到首次 Terms 标题间的候选。""" + definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {} + configured = definition.get('reservation_id_region') + if not isinstance(configured, dict): + return {'candidates': [], 'reason': None} + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} + pages = [ + (int(page_no), glyphs) + for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and isinstance(glyphs, list) + ] + candidates, reason = extract_reservation_from_vendor_comments_pages(pages) + return {'candidates': candidates, 'reason': reason} + + def _build_approved_profile_order_result( *, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any], table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None, allow_manual_review: bool = False, + reservation_region_candidates: list[dict[str, Any]] | None = None, + reservation_region_reason: str | None = None, ) -> tuple[list[dict[str, Any]] | None, str | None]: """ 把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。 @@ -1719,6 +1980,66 @@ def _build_approved_profile_order_result( } if source_missing_fields['header']['field_ids'] or source_missing_fields['lines']: base_order['source_missing_fields'] = source_missing_fields + # Reservation 专用区域可同时生成整单默认值和指定行覆盖值。有效值的行优先 + # 回退由 Schema Runtime 的 compute_effective_reservation_id 统一处理,无须复制 Header。 + reservation_scope = { + str(item.get('scope') or ''): item for item in fields + if str(item.get('field_code') or '') == 'reservation_id' + } + candidates = reservation_region_candidates or list(table.get('reservation_region_candidates') or []) + reservation_region_reason = reservation_region_reason or str(table.get('reservation_region_reason') or '') or None + if reservation_region_reason: + base_order['reservation_region_status'] = 'needs_review' + base_order['reservation_region_review_reasons'] = [reservation_region_reason] + if candidates: + header_target = reservation_scope.get('header') + line_target = reservation_scope.get('line') + applied = apply_reservation_region_candidates( + candidates=candidates, + header_field_id=str(header_target.get('field_id') or '') if header_target else None, + line_field_id=str(line_target.get('field_id') or '') if line_target else None, + line_count=len(line_groups), + ) + if applied.header_value and header_target: + header_evidence = next((item for item in candidates if item.get('scope') == 'header'), {}) + header_fields.append({'field_id': str(header_target.get('field_id') or ''), 'observations': [{ + 'value': applied.header_value, 'document_id': int(unit.document_id), + 'quote': str(header_evidence.get('raw_text') or '')[:1000], 'confidence': 1.0, + }]}) + header_id = str(header_target.get('field_id') or '') + source_missing_fields['header']['field_ids'] = [ + field_id for field_id in source_missing_fields['header']['field_ids'] if field_id != header_id + ] + header_code = str(header_target.get('field_code') or '') + source_missing_fields['header']['field_codes'] = [ + field_code for field_code in source_missing_fields['header']['field_codes'] if field_code != header_code + ] + if line_target: + for line_no, value in applied.line_values.items(): + line_evidence = next(( + item for item in candidates + if item.get('scope') == 'line' and item.get('line_no') == line_no and item.get('value') == value + ), {}) + line_groups[line_no - 1].setdefault('fields', []).append({'field_id': str(line_target.get('field_id') or ''), 'observations': [{ + 'value': value, 'document_id': int(unit.document_id), + 'quote': str(line_evidence.get('raw_text') or '')[:1000], 'confidence': 1.0, + }]}) + line_id = str(line_target.get('field_id') or '') + line_code = str(line_target.get('field_code') or '') + for missing in source_missing_fields['lines']: + if isinstance(missing, dict) and int(missing.get('line_index') or -1) == line_no - 1: + missing['field_ids'] = [field_id for field_id in missing['field_ids'] if field_id != line_id] + missing['field_codes'] = [field_code for field_code in missing['field_codes'] if field_code != line_code] + source_missing_fields['lines'] = [ + item for item in source_missing_fields['lines'] + if item.get('field_ids') or item.get('field_codes') + ] + if not source_missing_fields['header']['field_ids'] and not source_missing_fields['lines']: + base_order.pop('source_missing_fields', None) + if applied.needs_review: + base_order['reservation_region_candidates'] = candidates + base_order['reservation_region_status'] = 'needs_review' + base_order['reservation_region_review_reasons'] = list(applied.review_reasons) if not has_review_rows: base_order['_hxops_acceptance'] = 'approved_deterministic_profile_v1' # 当前业务约束:一份 PDF 只能形成一个 PO;检测到多个 PO 必须整体拒识并转人工复核。 @@ -1757,6 +2078,67 @@ def _build_approved_profile_order( return orders[0] if orders and len(orders) == 1 else None +def _normalize_profile_order_observations( + orders: list[dict[str, Any]], + *, + default_value_source: str, + coordinate_transform: dict[str, Any] | None, +) -> None: + """将 Profile adapter 的字段产物统一为可追溯 Observation 合同。 + + 坐标模板、XFA datasets 的内部字段形态不同,但进入 Candidate Gate 前必须具有相同 + 的来源、证据引用和几何变换声明。这里不补造缺失的坐标或值;仅为已有字段级 + layout/datasets evidence 投影稳定顶层引用,缺证据仍由后续资格门禁拦截。 + """ + source_aliases = { + 'pdf_coordinate': 'native_pdf', + 'native_glyph': 'native_pdf', + 'ocr_coordinate': 'ocr', + 'ocr_glyph': 'ocr', + 'acroform_widget': 'acroform_widget', + 'xfa_dataset': 'xfa_dataset', + 'coordinate_ocr': 'native_pdf', + } + default_source = source_aliases.get(default_value_source, default_value_source or 'unknown') + transform_ref: dict[str, Any] | None = None + if default_source in {'native_pdf', 'ocr', 'acroform_widget'}: + transform_ref = ( + {'kind': 'legacy_absolute'} + if coordinate_transform is None + else { + 'kind': 'coordinate_transform', + 'status': coordinate_transform.get('status'), + 'matrix': list(coordinate_transform.get('matrix') or []), + 'anchor_count': coordinate_transform.get('anchor_count'), + 'residual': coordinate_transform.get('residual'), + } + ) + for order in orders: + if not isinstance(order, dict): + continue + groups = [order.get('header_fields') or []] + groups.extend( + line.get('fields') or [] + for line in order.get('lines') or [] + if isinstance(line, dict) + ) + for fields in groups: + for field in fields if isinstance(fields, list) else []: + if not isinstance(field, dict): + continue + for observation in field.get('observations') or []: + if not isinstance(observation, dict): + continue + evidence = observation.get('layout_evidence') + evidence = evidence if isinstance(evidence, dict) else {} + raw_source = observation.get('value_source') or evidence.get('source') or default_value_source + observation['value_source'] = source_aliases.get(str(raw_source or ''), default_source) + if 'evidence_ref' not in observation and evidence.get('evidence_ref') is not None: + observation['evidence_ref'] = evidence.get('evidence_ref') + if transform_ref is not None: + observation['transform_ref'] = transform_ref + + def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, Any]]: """读取唯一匹配坐标模板的 confirmed 订单字段;无页级证据或歧义时返回空锁集。""" snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} @@ -1806,6 +2188,11 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An candidates = extract_order_fields( profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields, coordinate_evidence=layout.get('coordinate_evidence') or {}, + allow_fixed_region_confirmation=True, + coordinate_transform=_selected_coordinate_transform( + profile_match=match.model_dump(mode='json') if hasattr(match, 'model_dump') else match, + raw_profile=raw, + ), ) return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed'] diff --git a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py index 13e2a498..3f9c4c96 100644 --- a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -39,6 +39,141 @@ from app.services.shipping_notice.progress_feature_flags import ( ACTIVE_UNIT_STATUSES = {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'} IN_FLIGHT_UNIT_STATUSES = {'routing', 'matching_profile', 'extracting', 'merging_supplement'} +# Run/ProgressEvent 的内部事件统一收敛为工作台可见步骤;用户态不暴露 Worker 状态名。 +_LIFECYCLE_EVENT_STEP_CODES = { + 'plan_created': 'document_queued', + 'document_queued': 'document_queued', + 'layout_parsing_started': 'layout_parsing_started', + 'layout_parsing_completed': 'layout_parsing_completed', + 'profile_matching': 'profile_matching', + 'profile_candidates_scored': 'profile_matching', + 'profile_auto_selected': 'profile_matched', + 'profile_matched': 'profile_matched', + 'table_reconstructed': 'table_reconstructed', + 'order_fields_extracted': 'order_fields_extracted', + 'email_supplement_merged': 'email_supplement_merged', + 'candidate_ready': 'review_ready', + 'review_required': 'review_required', +} + +# 这些事件本身就是一个业务动作已经完成的事实。ProgressEvent 的 status 为了 +# 兼容 Run/Unit 的实时状态,部分仍会记录为 running,不能据此把已完成步骤漏掉。 +_LIFECYCLE_COMPLETION_EVENT_CODES = frozenset({ + 'layout_parsing_completed', + 'profile_auto_selected', + 'profile_matched', + 'table_reconstructed', + 'order_fields_extracted', + 'email_supplement_merged', + 'candidate_ready', +}) +_LIFECYCLE_UNIT_STEP_CODES = { + 'pending': 'document_queued', + 'routing': 'profile_matching', + 'matching_profile': 'profile_matching', + 'extracting': 'order_fields_extracted', + 'merging_supplement': 'email_supplement_merged', + 'candidate_ready': 'review_ready', + 'review_required': 'review_required', +} + + +def _build_lifecycle_progress( + run: ShippingOrderProcessingRun, + *, + units: list[ShippingOrderProcessingUnit], + effective_status: str, + current_activity: dict[str, Any] | None, + health_tips: list[dict[str, Any]], +) -> dict[str, Any]: + """ + 构建复核工作台消费的用户态生命周期进度。 + + 核心逻辑:复用当前 Run 的事件、状态、最后活动和健康提示,映射为五阶段中的 + 接收解析/订单复核及阶段内步骤;不返回正文、Provider、Job 或堆栈信息。 + """ + event_rows = [] + if getattr(run, 'id', None) is not None: + event_rows = ( + ShippingOrderExtractionProgressEvent.query + .filter_by(run_id=run.id, visibility='workspace') + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.asc(), ShippingOrderExtractionProgressEvent.id.asc()) + .all() + ) + completed: list[str] = [] + seen: set[str] = set() + for event in event_rows: + event_code = str(event.event_code or '').strip() + if ( + str(event.status or '').lower() != 'completed' + and event_code not in _LIFECYCLE_COMPLETION_EVENT_CODES + ): + continue + step = _LIFECYCLE_EVENT_STEP_CODES.get(event_code) + if step and step not in seen: + seen.add(step) + completed.append(step) + + raw_event = str((current_activity or {}).get('event_code') or '').strip() + current_step = _LIFECYCLE_EVENT_STEP_CODES.get(raw_event) + if raw_event in _LIFECYCLE_COMPLETION_EVENT_CODES: + active_unit = next((unit for unit in units if unit.status in ACTIVE_UNIT_STATUSES), None) + current_step = _LIFECYCLE_UNIT_STEP_CODES.get(str(active_unit.status or '')) if active_unit else None + if ( + effective_status in {'queued', 'processing'} + and current_step == 'layout_parsing_started' + and not any(unit.status in IN_FLIGHT_UNIT_STATUSES for unit in units) + ): + current_step = 'document_queued' + if not current_step: + current_step = 'document_queued' if effective_status in {'queued', 'processing'} else None + if current_step and current_step not in completed and effective_status in {'queued', 'processing'}: + # 当前运行中的步骤不能同时标记已完成;保留历史完成步骤顺序。 + completed = [step for step in completed if step != current_step] + + lifecycle_stage = 'intake_parse' + if current_step in {'review_ready', 'review_required'} or effective_status == 'review_required': + lifecycle_stage = 'order_review' + if effective_status in {'completed'}: + lifecycle_stage = 'order_review' + lifecycle_status = { + 'queued': 'running', + 'processing': 'running', + 'review_required': 'waiting', + 'failed': 'failed', + 'cancelled': 'cancelled', + 'completed': 'completed', + 'partially_completed': 'waiting', + }.get(effective_status, 'waiting') + health_status = 'failed' if lifecycle_status == 'failed' else ('attention' if health_tips else 'normal') + last_activity_at = (current_activity or {}).get('last_activity_at') or ( + run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None + ) + blocking_reason_i18n_key = None + if lifecycle_status == 'failed': + blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.failed' + elif lifecycle_status == 'cancelled': + blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.cancelled' + elif effective_status == 'review_required': + blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.review_required' + elif health_tips: + tip_code = str(health_tips[0].get('code') or '').strip() + if tip_code: + blocking_reason_i18n_key = f'chat.shippingProcessing.progress.lifecycleReason.{tip_code}' + return { + 'lifecycle_stage': lifecycle_stage, + 'lifecycle_status': lifecycle_status, + 'current_step_code': current_step, + 'current_step_i18n_key': ( + f'chat.shippingProcessing.progress.step.{current_step}' if current_step else None + ), + 'completed_step_codes': completed, + 'last_activity_at': last_activity_at, + 'health_status': health_status, + 'blocking_reason_i18n_key': blocking_reason_i18n_key, + 'primary_action': None, + } + # 候选待处理原因中偏「冲突/歧义」的码;其余有 missing_fields 或待补语义的归入待补信息。 _CANDIDATE_CONFLICT_REASON_CODES = frozenset({ 'email_supplement_conflict', @@ -536,6 +671,47 @@ def _latest_progress_events(run: ShippingOrderProcessingRun) -> tuple[dict[tuple return events, current +def serialize_lifecycle_progress( + run: ShippingOrderProcessingRun, + *, + units: list[ShippingOrderProcessingUnit] | None = None, + effective_status: str | None = None, + current_event: ShippingOrderExtractionProgressEvent | None = None, + health_tips: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + """构建轻量 Run 进度,供复核首屏读取,避免加载完整工作台文件与处理项投影。""" + resolved_units = units if units is not None else ( + list(run.extraction_plan.units or []) if run.extraction_plan is not None else [] + ) + resolved_status = effective_status or _effective_run_status(run, units=resolved_units) + if current_event is None and getattr(run, 'id', None) is not None: + _, current_event = _latest_progress_events(run) + current_activity: dict[str, Any] | None = None + if resolved_status in {'queued', 'processing'}: + if str(run.phase or '') == 'waiting_layout': + current_activity = {'event_code': 'layout_parsing_started'} + elif current_event is not None: + current_activity = {'event_code': current_event.event_code} + else: + active_unit = next((unit for unit in resolved_units if unit.status in ACTIVE_UNIT_STATUSES), None) + current_activity = { + 'event_code': ('document_queued' if run.status == 'queued' else active_unit.status) + if active_unit is not None else 'document_queued', + } + if current_activity is not None and run.last_activity_at is not None: + current_activity['last_activity_at'] = run.last_activity_at.isoformat() + 'Z' + resolved_tips = health_tips if health_tips is not None else ( + _health_tips_for_run(run, resolved_units) if progress_ui_v3_enabled() else [] + ) + return _build_lifecycle_progress( + run, + units=resolved_units, + effective_status=resolved_status, + current_activity=current_activity, + health_tips=resolved_tips, + ) + + def _latest_layout_document_events(run: ShippingOrderProcessingRun) -> dict[tuple[int, str], ShippingOrderExtractionProgressEvent]: """按 PDF 收集版面解析事件;该阶段早于 Unit 创建,不能复用 Unit 事件映射。""" events: dict[tuple[int, str], ShippingOrderExtractionProgressEvent] = {} @@ -1108,9 +1284,11 @@ def _run_available_actions( if ( str(run.status or '') in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} ): - from app.services.shipping_notice.order_review_disposition_service import has_reparseable_batch_documents + from app.services.shipping_notice.order_review_disposition_service import ( + has_reparseable_batch_documents_readonly, + ) - if has_reparseable_batch_documents(user_id=int(run.user_id), run=run): + if has_reparseable_batch_documents_readonly(user_id=int(run.user_id), run=run): actions.append('reparse_batch') if run.status == 'failed' or any(unit.status == 'failed' for unit in units) or 'technical_failure' in categories: if 'retry_failed_attachments' not in actions: @@ -1390,7 +1568,9 @@ def _email_supplement_projection( 1 for order in orders if isinstance(order, dict) for conflict in order.get('conflicts') or [] if isinstance(conflict, dict) - if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous' + if str(conflict.get('reason') or '').strip() in { + 'supplement_relation_ambiguous', 'supplement_field_conflict', + } ) status = 'conflict' if conflict_count > 0 else 'merged' if relation_codes else 'none' @@ -1666,6 +1846,14 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]: else (run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None) ), } + health_tips = _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else [] + lifecycle_progress = serialize_lifecycle_progress( + run, + units=units, + effective_status=effective_status, + current_event=current_event, + health_tips=health_tips, + ) return { 'effective_status': effective_status, 'summary': { @@ -1694,7 +1882,8 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]: ), 'user_visible_stage': 'failed' if effective_status == 'failed' else _run_user_visible_stage(run, units), # 回滚进度 UI v3 时不下发健康提示,避免前端展示灰度未启用的细化提醒。 - 'health_tips': _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else [], + 'health_tips': health_tips, + 'lifecycle_progress': lifecycle_progress, 'cancellation': _cancellation_projection(run), 'progress_version': int(run.progress_version or 0), 'elapsed_seconds': _elapsed_seconds(started_at=run.started_at or run.created_at, finished_at=run.finished_at, now=now), diff --git a/backend/app/services/shipping_notice/order_field_purposes.py b/backend/app/services/shipping_notice/order_field_purposes.py index b7d31056..7cae906b 100644 --- a/backend/app/services/shipping_notice/order_field_purposes.py +++ b/backend/app/services/shipping_notice/order_field_purposes.py @@ -12,7 +12,7 @@ from typing import Any from app import db from app.models import ShippingOrderSnapshot, ShippingNotice -from app.services.shipping_notice.export import order_field_id_values +from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values _PURPOSE_BY_CAPABILITY = { @@ -25,7 +25,8 @@ _PURPOSE_BY_CAPABILITY = { def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | None = None) -> dict[str, str]: """读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。""" - snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + source_notice = _source_notice_for_order_facts(task) + snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于履约的冻结订单快照') rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule') diff --git a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py index 396a8ed5..a25bf053 100644 --- a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py +++ b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py @@ -22,11 +22,24 @@ def owns_definition(definition_or_mode: dict[str, Any] | str | None) -> bool: def owns_layout(layout: dict[str, Any] | None) -> bool: - """只按冻结 datasets capability 选择末端值源,不按 PDF provider 分流。""" + """仅在 Layout 明确证明为受支持的 XFA hybrid 文档时选择 datasets 值源。 + + ``xfa_capability`` 可能因历史复用、诊断失败或派生快照而存在,不能单独 + 作为 PDF 类型判断依据;必须同时满足结构分析已完成、文档类型为当前支持 + 的 XFA kind,且 XFA 功能开关开启。 + """ + from app.services.shipping_notice.document_layout.xfa_contract import XFA_SUPPORTED_DOCUMENT_KINDS + capability = layout.get('xfa_capability') if isinstance(layout, dict) and isinstance(layout.get('xfa_capability'), dict) else {} + document_kind = str( + capability.get('document_kind') + or (layout.get('document_kind') if isinstance(layout, dict) else '') + or '', + ).strip() return bool( xfa_enabled() and isinstance(layout, dict) + and document_kind in XFA_SUPPORTED_DOCUMENT_KINDS and (capability.get('structure_analysis_ready') or capability.get('dataset_structure_fingerprint')) ) @@ -1330,13 +1343,42 @@ def blind_candidate(*, profile: Any, sample: Any) -> dict[str, Any]: metrics = build_xfa_validation_metrics(definition=definition, extraction=extraction, cross_check_summary=validation.cross_check_summary, schema_field_ids=field_ids) rows = [{str(field['field_code']): quality_service._json_value(field.get('value')) for field in row.get('fields') or [] if isinstance(field, dict) and field.get('field_code')} for row in extraction.rows] datasets_candidate = {'order_fields': [{'field_code': item.field_code, 'value': quality_service._json_value(item.normalized_value), 'status': 'confirmed' if item.normalized_value not in (None, '') and not item.issues else 'failed', 'field_id': item.field_id, 'scope': 'header', 'page_no': 1, 'issues': list(item.issues)} for item in extraction.header_fields], 'rows': [row for row in rows if row]} + # Reservation 专用证据区不是 XFA 的拆分映射:它和坐标模板盲测共用同一解析器。 + # 视觉候选中的整单值与指定行覆盖值应参与最终 blind candidate,避免盲测与正式 + # 公共建单路径出现不同结果。 + visual_reservation_headers = [ + item for item in visual_candidate.get('order_fields') or [] + if isinstance(item, dict) and item.get('field_code') == 'reservation_id' + ] + if visual_reservation_headers: + datasets_candidate['order_fields'] = [ + item for item in datasets_candidate['order_fields'] + if not (item.get('field_code') == 'reservation_id' and item.get('scope') == 'header') + ] + visual_reservation_headers + for index, visual_row in enumerate(visual_candidate.get('rows') or []): + if index >= len(datasets_candidate['rows']) or not isinstance(visual_row, dict): + continue + if visual_row.get('reservation_id') not in (None, ''): + datasets_candidate['rows'][index]['reservation_id'] = visual_row['reservation_id'] ocr_comparison = _blind_candidate_cross_check( visual_candidate=visual_candidate, datasets_candidate=datasets_candidate, ) reason_codes = list(extraction.reason_codes or []) + list(validation.reason_codes or []) if ocr_comparison['status'] == 'mismatched': reason_codes.append('ocr_datasets_mismatch') - return {'document_id': document.id, 'table_id': visual_table_id, **datasets_candidate, 'extraction_status': extraction.status, 'reason_codes': reason_codes, 'line_row_count': len(rows), 'visual_coverage_rate': float(metrics.get('visual_coverage_rate') or 0.0), 'mirror_consistency_rate': float(metrics.get('mirror_consistency_rate') or 0.0), 'evidence_retention_rate': float(metrics.get('evidence_retention_rate') or 0.0), 'cross_checks': dict(validation.cross_check_summary or {}), 'ocr_datasets_cross_check': ocr_comparison} + return { + 'document_id': document.id, 'table_id': visual_table_id, **datasets_candidate, + 'extraction_status': extraction.status, 'reason_codes': reason_codes, + 'line_row_count': len(rows), 'visual_coverage_rate': float(metrics.get('visual_coverage_rate') or 0.0), + 'mirror_consistency_rate': float(metrics.get('mirror_consistency_rate') or 0.0), + 'evidence_retention_rate': float(metrics.get('evidence_retention_rate') or 0.0), + 'cross_checks': dict(validation.cross_check_summary or {}), + 'ocr_datasets_cross_check': ocr_comparison, + **({ + 'reservation_region_status': visual_candidate['reservation_region_status'], + 'reservation_region_review_reasons': visual_candidate.get('reservation_region_review_reasons') or [], + } if visual_candidate.get('reservation_region_status') == 'needs_review' else {}), + } def blind_gate_failures(*, candidate: dict[str, Any], sample_id: int) -> tuple[list[str], dict[str, float]]: 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 index 767971cc..3e21cfdd 100644 --- a/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py +++ b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py @@ -138,6 +138,8 @@ def _customer_step_for_case( site_id=None, actor_id=None, reason=confirm_reason, + # 保存校验入口需将客户确认、Draft 校验与后续 Gate/STP 写入作为同一事务提交。 + commit=False, ) except Exception as exc: # noqa: BLE001 _LOGGER.warning( @@ -179,6 +181,33 @@ def _customer_step_for_case( } +def auto_confirm_unique_customer_for_review_case( + *, + case: ShippingOrderReviewCase, + trigger: str, +) -> dict[str, Any]: + """ + 将当前 Case 的唯一 Shadow 客户候选落为 Bill-to 已确认事实。 + + 用途与触发时机:保存订单并校验、恢复协调等入口在读取建单资格前调用; + 仅 ``unique_candidate`` 能自动确认,其他匹配状态保持人工处置。 + + Args: + case: 当前文件 Stream 的可编辑订单复核 Case。 + trigger: 调用来源,写入客户确认审计。 + + Returns: + 客户步骤摘要;``auto_confirmed`` 时附带标准客户主键,其他状态不伪造确认事实。 + """ + status, metadata = _customer_step_for_case(case=case, trigger=trigger) + if status == 'auto_confirmed': + db.session.flush() + return { + 'status': status, + **(dict(metadata) if isinstance(metadata, dict) else {}), + } + + def reconcile_single_case_for_auto_progress( *, case_no: Any = None, diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index e86d24c8..7ce8d332 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -58,7 +58,6 @@ from app.services.shipping_notice.batch_create_idempotency import ( assert_no_exact_duplicate_notices, normalize_create_idempotency_key, ) -from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary @@ -883,7 +882,7 @@ def _persist_wave_lines_for_task( Args: case: 复核 Case。 - task: 本波次新建 Task。 + task: 本波次新建的 Notice。 line_keys: 本波次完整行键。 wave_no: 波次序号(从 1 起)。 revision_id: 可选确认修订 ID。 @@ -1357,9 +1356,8 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) # [BE-06] Notice 创建及挂接后的消费/客户绑定失败须 fail-closed 回滚。 try: - shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user_id)) task = ShippingNotice( - task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), user_id=int(user_id), + task_no=generate_task_no(), user_id=int(user_id), conversation_id=case.run.conversation_id, source_type='review_confirmation', source_file_name=document.filename, source_file_type=asset.mime_type if asset else None, source_content_hash=document.content_hash, source_asset_id=document.asset_id, source_intake_id=int(intake.id), source_candidate_id=int(candidate.id), @@ -1595,13 +1593,19 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool: return False if not getattr(task, 'current_order_extraction_id', None): return False - return not bool( - getattr(task, 'inventory_snapshot_id', None) - or getattr(task, 'inventory_lines_json', None) - or getattr(task, 'match_status', None) - or getattr(task, 'export_file_path', None) - or getattr(task, 'upload_status', None) - ) + inventory_snapshot_id = getattr(task, 'inventory_snapshot_id', None) + inventory_lines = getattr(task, 'inventory_lines_json', None) + match_status = getattr(task, 'match_status', None) + export_file_path = getattr(task, 'export_file_path', None) + upload_status = getattr(task, 'upload_status', None) + # 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等 + # 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。 + has_inventory = isinstance(inventory_snapshot_id, int) and not isinstance(inventory_snapshot_id, bool) + has_inventory = has_inventory or isinstance(inventory_lines, (list, dict)) and bool(inventory_lines) + has_match = isinstance(match_status, str) and bool(match_status.strip()) + has_export = isinstance(export_file_path, str) and bool(export_file_path.strip()) + has_upload = isinstance(upload_status, str) and bool(upload_status.strip()) + return not (has_inventory or has_match or has_export or has_upload) def resolve_confirm_outcome(progress: dict[str, Any] | None) -> str: diff --git a/backend/app/services/shipping_notice/order_review_disposition_service.py b/backend/app/services/shipping_notice/order_review_disposition_service.py index d7ee626b..7c1fbab2 100644 --- a/backend/app/services/shipping_notice/order_review_disposition_service.py +++ b/backend/app/services/shipping_notice/order_review_disposition_service.py @@ -6,7 +6,8 @@ backend/app/services/shipping_notice/order_review_disposition_service.py workflow_ledger_service、order_task_service.resolve_order_task_for_candidate。 逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft, 禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果, -成功后才由 Run 终态钩子替代旧 Case;创建后继 Run 时显式传入 Case 对应 OT(非 Run 根号)。 +成功后才由 Run 终态钩子替代旧 Case,并在 Stream 原子切换成功后补触发新版 Case 的统一自动推进; +创建后继 Run 时显式传入 Case 对应 OT(非 Run 根号)。 每次关键处置同时写 CaseEvent + 统一 ShippingAuditEvent; 质量异常原因码 `other` 时备注必填。被拒绝操作(无效原因、终态冲突、替代状态不满足、 WorkflowItem 已关闭等)在抛错前独立 commit 拒绝审计,避免 API 回滚吞掉留痕。由 workspace shipping_notice API 调用。 @@ -91,8 +92,8 @@ def _case_document_identity(*, case: ShippingOrderReviewCase, documents_by_id: d return f'document:{document_id}' -def select_current_batch_reparse_cases( - *, user_id: int, run: ShippingOrderProcessingRun, +def _select_current_batch_reparse_cases( + *, user_id: int, run: ShippingOrderProcessingRun, for_update: bool, ) -> tuple[ShippingOrderProcessingRun, list[ShippingOrderReviewCase]]: """ 从批次 Run 谱系为每个原 PDF 选择最新 Review Case。 @@ -111,24 +112,26 @@ def select_current_batch_reparse_cases( ShippingOrderReviewStream.owner_user_id == int(user_id), ShippingOrderProcessingRun.conversation_id == str(run.conversation_id), ) - .with_for_update() - .all() ) + if for_update: + stream_cases = stream_cases.with_for_update() + stream_cases = stream_cases.all() if stream_cases: root = _run_lineage_root(run=run) return root, sorted(stream_cases, key=lambda item: int(item.document_id)) root = _run_lineage_root(run=run) runs = _lineage_runs(root=root, user_id=user_id) run_ids = [int(item.id) for item in runs] - cases = ( + cases_query = ( ShippingOrderReviewCase.query .filter( ShippingOrderReviewCase.owner_user_id == int(user_id), ShippingOrderReviewCase.run_id.in_(run_ids), ) - .with_for_update() - .all() ) + if for_update: + cases_query = cases_query.with_for_update() + cases = cases_query.all() document_ids = {int(case.document_id) for case in cases if int(case.document_id or 0) > 0} documents_by_id = { int(document.id): document @@ -144,6 +147,13 @@ def select_current_batch_reparse_cases( return root, [selected[key] for key in sorted(selected)] +def select_current_batch_reparse_cases( + *, user_id: int, run: ShippingOrderProcessingRun, +) -> tuple[ShippingOrderProcessingRun, list[ShippingOrderReviewCase]]: + """为批次重解析写命令选择当前 Case,并锁定参与决策的行。""" + return _select_current_batch_reparse_cases(user_id=user_id, run=run, for_update=True) + + def has_reparseable_batch_documents(*, user_id: int, run: ShippingOrderProcessingRun) -> bool: """供投影判断批次操作可见性;确认/履约与非订单文件不作为可重解析目标。""" _root, cases = select_current_batch_reparse_cases(user_id=user_id, run=run) @@ -154,6 +164,21 @@ def has_reparseable_batch_documents(*, user_id: int, run: ShippingOrderProcessin ) +def has_reparseable_batch_documents_readonly( + *, user_id: int, run: ShippingOrderProcessingRun, +) -> bool: + """为 GET 投影无锁判断批次重解析资格,禁止复用写命令的锁定选择器。""" + _root, cases = _select_current_batch_reparse_cases( + user_id=user_id, run=run, for_update=False, + ) + return any( + str(case.status or '').strip().lower() + in {'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending'} + and case.confirmed_task_id is None + for case in cases + ) + + def reparse_batch_documents( *, user_id: int, run_no: str, reason: str, comment: str | None = None, ) -> dict[str, Any]: @@ -1015,7 +1040,17 @@ def reparse_case_document( def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: bool) -> None: - """在新版 Run 终态收口旧 Case:成功替代,失败恢复原草稿的原生命周期。""" + """ + 在新版 Run 终态收口旧 Case,并在成功切换当前版本后恢复自动推进。 + + 核心逻辑:重解析结果落库时新版 Case 尚不是 Stream 当前版本,协调器会安全跳过; + 因此只在 ``activate_review_case`` 已确认切换成功后调用单 Case 协调器。这样复用 + 客户确认、Draft 校验、Gate 与 STP 幂等链路,且不会让晚到分支覆盖已确认版本。 + + Args: + run: 已到终态的重解析后继 Run。 + succeeded: 新版 Run 是否成功到达可复核终态。 + """ marker = (run.input_snapshot_json or {}).get('review_reparse') if not isinstance(marker, dict) or not run.reparse_of_run_id: return @@ -1042,10 +1077,21 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo # Run 已到终态但没有可复核新版本时,不可废弃旧草稿。 return from app.services.shipping_notice.review_stream_service import activate_review_case - activate_review_case( + stream = activate_review_case( case=replacement_case, trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded', ) + # [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进。激活被并发确认或 + # 晚到分支拒绝时,保持该草稿只读,不得错误建单或进入库存准备。 + if int(stream.current_case_id or 0) == int(replacement_case.id): + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_single_case_for_auto_progress, + ) + reconcile_single_case_for_auto_progress( + case=replacement_case, + trigger='document_reparse_succeeded', + refresh_validation=True, + ) _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={ 'successor_run_no': run.run_no, 'replacement_case_no': replacement_case.case_no, diff --git a/backend/app/services/shipping_notice/order_review_evidence_view.py b/backend/app/services/shipping_notice/order_review_evidence_view.py index c91391b7..e15d6671 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_view.py +++ b/backend/app/services/shipping_notice/order_review_evidence_view.py @@ -29,9 +29,6 @@ from app.services.shipping_notice.order_review_llm_contract import ( 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, ) @@ -659,35 +656,6 @@ def build_review_evidence_view(case) -> dict[str, Any]: ) 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) 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 6620b177..2e4d7a1d 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 @@ -17,6 +17,8 @@ from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ShippingOrderCandidate, ShippingOrderReviewCase from app.services.shipping_notice.candidate_qualification_service import ( + current_open_candidate_conflicts, + field_evidence_gap_is_non_blocking, recalculate_candidate_qualification, resolve_review_case_customer_resolved, ) @@ -34,12 +36,12 @@ 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:' -_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'}) +_EVIDENCE_GAP_REASONS = frozenset({ + 'evidence_missing', + 'pdf_evidence_missing', + # 历史正文补充冲突缺失双方值和证据,必须显示重新识别入口,不能成为空面板阻断。 + 'supplement_conflict_evidence_insufficient', +}) def _conflict_key(*, field: str, line_index: Any) -> str: @@ -51,6 +53,12 @@ def _conflict_key(*, field: str, line_index: Any) -> str: return f'{idx}:{str(field or "").strip()}' +def _stored_conflict_key(item: dict[str, Any]) -> str: + """读取新旧 Candidate 冲突的稳定键,新 Finding 优先使用其冻结 conflict_key。""" + explicit = str(item.get('conflict_key') or '').strip() + return explicit or _conflict_key(field=item.get('field'), line_index=item.get('line_index')) + + def _candidate_for_case(case: ShippingOrderReviewCase) -> ShippingOrderCandidate | None: if not case.candidate_id: return None @@ -156,6 +164,36 @@ def _option_display( } +def _finding_source_options(item: dict[str, Any]) -> list[dict[str, Any]]: + """将统一 Finding 的 source 快照投影为复核选项,避免依赖已丢失的 Observation 索引。""" + options: list[dict[str, Any]] = [] + seen: set[str] = set() + for source in item.get('sources') or []: + if not isinstance(source, dict): + continue + raw_value = source.get('raw_value') + if raw_value in (None, ''): + continue + key = str(raw_value) + if key in seen: + continue + seen.add(key) + source_type = str(source.get('source_type') or '').strip() + evidence_role = 'primary_pdf' if source_type == 'pdf' else _evidence_role_for_source_type(source_type) + options.append({ + 'value_key': key, + 'display_value': raw_value, + 'sources': [source_type] if source_type else [], + 'source_type': source_type or None, + 'source_types': [source_type] if source_type else [], + 'evidence_role': evidence_role, + 'evidence_rank': None, + 'evidence_ref': source.get('evidence_ref'), + 'document_id': source.get('document_id'), + }) + return options + + def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None: """按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。""" draft = case.current_draft @@ -223,91 +261,6 @@ def _finding_scope(case: ShippingOrderReviewCase, *, field_code: str, line_index return 'unscoped' -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_candidate_findings(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """ 将 Candidate 的值冲突与证据缺失分区投影,并按稳定 Finding 身份去重。 @@ -323,6 +276,11 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu evidence_issues: list[dict[str, Any]] = [] seen: set[tuple[str, str]] = set() raw_conflicts = list(candidate.conflicts_json or []) + open_conflict_keys = { + _stored_conflict_key(item) + for item in current_open_candidate_conflicts(candidate) + if isinstance(item, dict) + } adjudication = _adjudication_blob(candidate) observations = _observations_index(adjudication) for item in raw_conflicts: @@ -340,12 +298,22 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu line_index = -1 value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')] reason = str(item.get('reason') or 'field_conflict') + # 资格层仍认为该 Finding 阻断时,投影不得静默丢弃;即使候选值不完整, + # 也必须给用户一个可解释的 Review 入口,保持 UI/Gate 同源。 + is_current_open_blocking = _stored_conflict_key(item) in open_conflict_keys is_evidence_gap = reason in _EVIDENCE_GAP_REASONS - # 只有多个候选值不一致才属于「字段冲突待裁决」。 - if len(value_keys) < 2 and not is_evidence_gap: + if is_evidence_gap and field_evidence_gap_is_non_blocking(candidate, item): continue + # 只有多个候选值不一致才属于「字段冲突待裁决」。 + if len(value_keys) < 2 and not is_evidence_gap and not is_current_open_blocking: + continue + if is_current_open_blocking and len(value_keys) < 2: + reason = str(reason or 'field_conflict') + recovery_action = str(item.get('recovery_action') or 'review_current_evidence').strip() or 'review_current_evidence' + else: + recovery_action = str(item.get('recovery_action') or '').strip() or None observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid] - options = [ + options = _finding_source_options(item) or [ _option_display( field=field, value_key=key, @@ -356,15 +324,16 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu ] line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None finding = { - 'conflict_key': _conflict_key(field=field, line_index=line_index), + 'conflict_key': _stored_conflict_key(item), 'field_code': field, 'line_index': line_index if line_index >= 0 else None, 'line_key': line_key, - 'scope': _finding_scope(case, field_code=field, line_index=line_index), + 'scope': str(item.get('scope') or _finding_scope(case, field_code=field, line_index=line_index)), 'severity': str(item.get('severity') or 'blocking'), 'reason': reason, 'options': options, 'observation_ids': observation_ids, + 'recovery_action': recovery_action, } # 同一 scope/field/reason 只能有一个开放 Finding;重复来源合并为一张卡。 finding_identity = (finding['conflict_key'], reason) @@ -372,7 +341,6 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu continue seen.add(finding_identity) (evidence_issues if is_evidence_gap else value_conflicts).append(finding) - value_conflicts.extend(_project_vc_candidate_conflicts(case=case, candidate=candidate)) return value_conflicts, evidence_issues @@ -388,56 +356,6 @@ def project_review_case_evidence_issues(case: ShippingOrderReviewCase) -> list[d return evidence_issues -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, @@ -480,174 +398,66 @@ def resolve_review_case_field_conflict( ) 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 mode = str(resolution or '').strip().lower() - 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}, - ) + conflicts = list(candidate.conflicts_json or []) + target_idx = -1 + target: dict[str, Any] | None = None + for idx, item in enumerate(conflicts): + if isinstance(item, dict) and _stored_conflict_key(item) == 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(value) for value in (target.get('values') or []) if value 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') + options = _finding_source_options(target) + option = options[int(option_index)] if options else _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_index(_adjudication_blob(candidate)), + ) + 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: - 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}, - ) - # 解析历史可能保留同一稳定键的重复记录;一次人工裁决必须原子清空该 Finding 身份。 - conflicts = [ - item for item in conflicts - if not ( - isinstance(item, dict) - and _conflict_key(field=item.get('field'), line_index=item.get('line_index')) == raw_key - ) - ] - 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() + raise ValidationError('Invalid conflict resolution', code='SHIPPING.INVALID_CONFLICT_RESOLUTION', details={'resolution': resolution}) + conflicts = [item for item in conflicts if not (isinstance(item, dict) and _stored_conflict_key(item) == raw_key)] + 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 []) + adjudication['decisions'] = [ + {**decision, 'status': 'selected', 'value': chosen_display, 'resolution_method': 'manual_review'} + if isinstance(decision, dict) + and str(decision.get('field') or '') == field_code + and (line_index < 0 or int(decision.get('line_index') or -1) == line_index) + else decision + for decision in 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' @@ -688,16 +498,6 @@ 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] 按冲突类型分别处理 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) recalculate_candidate_qualification( 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 c4275b88..e02e7409 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 @@ -7,8 +7,8 @@ services/shipping_notice/order_review_fulfillment_decision_service.py line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、 order_review_resume_service。 逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions; - 订单级聚合计数供侧栏主卡;旧 create_fulfillment_wave 仍走 confirm(BE-8 兼容); - OT 后自动 wave 另服务;履约「料号」= Schema part_number(内部料号),禁止 reservation 回填。 + 订单级聚合计数供侧栏主卡;OT 后波次由确认服务统一创建;履约「料号」= + Schema part_number(内部料号),禁止 reservation 回填。 """ from __future__ import annotations @@ -417,28 +417,43 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None: - """短缺放行后重投影并提交正式任务当前技术 Gate,不改写库存事实。""" + """ + 短缺放行后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。 + + 核心逻辑:Gate 重投影不改写库存事实;复用既有 auto-fulfill Job,由 Job 再判断 + 是否恰好只有一条开放且可履约的明细。多条明细不会自动合并,仍由用户勾选创建 wave。 + """ task_id = getattr(case, 'confirmed_task_id', None) if task_id is None: return task = db.session.get(ShippingNotice, int(task_id)) - execution_id = getattr(task, 'active_process_execution_id', None) if task is not None else None - if execution_id is None: + if task is None: return - from app.models import ShippingProcessExecution - execution = db.session.get(ShippingProcessExecution, int(execution_id)) - if execution is None or int(getattr(execution, 'task_id', 0) or 0) != int(task_id): - return - from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=actor_id) - # 放行是库存充分性 Gate 的受控业务事实;重投影后由统一编排器重新读取当前 - # Gate 并仅入队一个技术动作,避免 API 事务中直接生成 Excel 或绕过 Worker。 - from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + execution_id = getattr(task, 'active_process_execution_id', None) + if execution_id is not None: + from app.models import ShippingProcessExecution + execution = db.session.get(ShippingProcessExecution, int(execution_id)) + if execution is not None and int(getattr(execution, 'task_id', 0) or 0) == int(task_id): + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=actor_id) + # 放行是库存充分性 Gate 的受控业务事实;重投影后由统一编排器重新读取当前 + # Gate 并仅入队一个技术动作,避免 API 事务中直接生成 Excel 或绕过 Worker。 + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress - submit_auto_progress( - task=task, + submit_auto_progress( + task=task, + trigger='inventory_shortage_released', + operator_id=actor_id, + commit=False, + ) + # 单条自动履约必须在提交后由 Worker 创建独立 Notice,不能在 API 事务内同步生成 Excel。 + 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_shortage_released', - operator_id=actor_id, commit=False, ) @@ -802,9 +817,23 @@ def project_review_case_line_decisions( for key, draft_line in draft_lines.items(): proj = projections.get(key) or {} decision = by_key.get(key) + # 正式 OT 的库存数量以当前行匹配事实为准;草稿 validation_result 只保留 + # 解析阶段投影,不能因为其中没有 available_qty 就错误阻断人工出单。 + fact = match_facts.get(key) + fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {} + fulfill_proj = dict(proj) + if isinstance(fact, dict): + if fact.get('available_qty') is not None: + fulfill_proj['available_qty'] = fact.get('available_qty') + if fact.get('match_result'): + fulfill_proj['match_result'] = fact.get('match_result') + if fact.get('inventory_status'): + fulfill_proj['inventory_status'] = fact.get('inventory_status') + if fact.get('inventory_source_code'): + fulfill_proj['inventory_source_code'] = fact.get('inventory_source_code') can_fulfill, _block, rq, aq = _assess_line_fulfill_complete( draft_line, - proj, + fulfill_proj, schema_fields=schema_fields, ) required = str(rq) if rq is not None else ( @@ -829,8 +858,6 @@ def project_review_case_line_decisions( getattr(decision, 'decision_source', None) if decision is not None else None ) decision_snap = dict(decision.snapshot_json or {}) if decision is not None else {} - fact = match_facts.get(key) - fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {} auto_failed = bool( decision_snap.get('auto_fulfill_failed') or (fact or {}).get('auto_fulfill_failed') @@ -1252,156 +1279,6 @@ def decide_review_line_fulfillment( return attach_resume_outcome(payload, resume) -def create_fulfillment_wave( - *, - user_id: int, - case_no: str, - line_keys: list[str], - expected_draft_version: Any, - idempotency_key: str | None, - reason: str | None = None, -) -> dict[str, Any]: - """ - 为选中的完整明细行创建履约波次 Task。 - - 核心逻辑:仅接受已标记 fulfill_complete_line_now 且未入 Task 的行; - 建波次前强制 validate_draft 刷新库存事实并再次校验充足/Reservation; - 数量必须等于草稿整行;调用确认服务并传入 line_keys 过滤。 - - Args: - user_id: 操作人。 - case_no: Case 编号。 - line_keys: 本波次完整行键列表。 - expected_draft_version: 草稿版本。 - idempotency_key: 建单幂等键。 - reason: 可选备注。 - - Returns: - 确认结果 + line_fulfillment 投影。 - """ - keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] - if not keys: - raise ValidationError( - 'line_keys required', - code='SHIPPING.REVIEW_LINE_WAVE_EMPTY', - ) - if len(keys) != len(set(keys)): - raise ValidationError( - 'Duplicate line_keys', - code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE', - ) - - case = _load_writable_case(user_id=user_id, case_no=case_no) - # [STEP 1] 建波次前重跑草稿校验,消费最新库存/预留/路由投影。 - from app.services.shipping_notice.order_review_draft_service import validate_draft - - validate_draft( - user_id=int(user_id), - case_no=str(case_no), - expected_draft_version=expected_draft_version, - ) - 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') - - from app.services.shipping_notice.order_review_workbench_projection import ( - schema_fields_from_case, - ) - - draft_lines = _draft_line_map(case) - projections = _line_projection_map(case) - schema_fields = schema_fields_from_case(case) - for key in keys: - if key not in draft_lines: - raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND') - decision = _active_decision(case, key) - if decision is None or decision.decision_code != DECISION_FULFILL: - raise ConflictError( - 'Line must be marked fulfill_complete_line_now', - code='SHIPPING.REVIEW_LINE_NOT_READY_FOR_WAVE', - details={'line_key': key}, - ) - if decision.line_status in {'task_created', 'fulfilled'}: - raise ConflictError( - 'Line already in a task wave', - code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK', - details={'line_key': key}, - ) - req, _avail = _assert_line_can_fulfill_complete( - line_key=key, - draft_line=draft_lines[key], - proj=projections.get(key) or {}, - schema_fields=schema_fields, - ) - # 禁止拆分:决定中的 required_qty 必须等于草稿整行数量 - if decision.required_qty and _parse_qty(decision.required_qty) != req: - raise ValidationError( - 'Quantity split is not allowed', - code='SHIPPING.REVIEW_LINE_QTY_SPLIT_FORBIDDEN', - details={'line_key': key}, - ) - - from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case - - # validate_draft 可能抬升草稿版本;以当前草稿版本确认。 - current_version = int(case.current_draft.draft_version) if case.current_draft else expected_draft_version - result = confirm_review_case( - user_id=int(user_id), - case_no=str(case_no), - expected_draft_version=current_version, - idempotency_key=idempotency_key, - confirm_note=reason, - line_keys=keys, - ) - - # [STEP 2] 标记决定为 task_created - from sqlalchemy import func - - 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() - if task_no: - task_row = ShippingNotice.query.filter_by(task_no=task_no).first() - if task_row is not None: - task_id = int(task_row.id) - if task_id is None and isinstance(result, dict) and result.get('case'): - raw_task_id = result['case'].get('confirmed_task_id') - if raw_task_id is not None: - task_id = int(raw_task_id) - # 确认服务已写入 wave_lines;复用其波次号,避免二次递增。 - wave_no = ( - db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no)) - .filter(ShippingOrderReviewWaveLine.review_case_id == int(case.id)) - .scalar() - ) - next_wave = int(wave_no or 0) - if next_wave <= 0: - prior = ( - db.session.query(func.max(ShippingOrderReviewLineDecision.wave_no)) - .filter(ShippingOrderReviewLineDecision.review_case_id == int(case.id)) - .scalar() - ) - next_wave = int(prior or 0) + 1 - for key in keys: - decision = _active_decision(case, key) - if decision is None: - continue - decision.line_status = 'task_created' - decision.task_id = int(task_id) if task_id else decision.task_id - decision.wave_no = next_wave - decision.updated_at = datetime.utcnow() - db.session.flush() - - from app.services.shipping_notice.order_review_projection import serialize_review_case - - result = dict(result or {}) - result['line_fulfillment'] = project_review_case_line_decisions(case) - result['case'] = serialize_review_case(case) - result['wave_no'] = next_wave - return result - - def close_remaining_fulfillment( *, user_id: int, diff --git a/backend/app/services/shipping_notice/order_review_profile_match_service.py b/backend/app/services/shipping_notice/order_review_profile_match_service.py index f4e85ed7..3e4a76eb 100644 --- a/backend/app/services/shipping_notice/order_review_profile_match_service.py +++ b/backend/app/services/shipping_notice/order_review_profile_match_service.py @@ -134,12 +134,31 @@ def _sanitize_candidates(raw: list[Any], *, display_map: dict[tuple[str, int], s 'missing_required_anchor_ids': [ str(c) for c in (item.get('missing_required_anchor_ids') or []) if c ][:12], + 'coordinate_transform': _sanitize_coordinate_transform(item.get('coordinate_transform')), }) if len(out) >= 5: break return out +def _sanitize_coordinate_transform(value: Any) -> dict[str, Any] | None: + """投影受限坐标变换审计摘要;禁止泄露原始正文和完整坐标。""" + if not isinstance(value, dict): + return None + status = str(value.get('status') or '').strip() + if not status: + return None + result: dict[str, Any] = {'status': status} + for key in ('translate_x', 'translate_y'): + raw = value.get(key) + try: + result[key] = round(float(raw), 6) if raw is not None else None + except (TypeError, ValueError): + result[key] = None + result['reason_codes'] = [str(code) for code in (value.get('reason_codes') or []) if str(code).strip()][:12] + return result + + def project_review_case_profile_match(case: ShippingOrderReviewCase) -> dict[str, Any]: """ 投影建单前文档模板匹配摘要。 diff --git a/backend/app/services/shipping_notice/order_review_progress_bridge.py b/backend/app/services/shipping_notice/order_review_progress_bridge.py index 0f9b3055..1015a54f 100644 --- a/backend/app/services/shipping_notice/order_review_progress_bridge.py +++ b/backend/app/services/shipping_notice/order_review_progress_bridge.py @@ -117,6 +117,32 @@ def record_review_progress_event( # [STEP 3] 兑现或丢弃 Savepoint,隔离主业务事务。 if wrote: + # Review Gate 变化必须推动同一订单工作项的版本,即使 OT 的 stage/status + # 没变化;否则工作台单调合并会继续保留旧 primary_action。 + task_no = str(getattr(run, 'user_task_no', None) or '').strip() + from app.models import ShippingOrderTask + order_task = ( + ShippingOrderTask.query.filter_by(task_no=task_no).first() + if task_no else None + ) + if order_task is None and getattr(run, 'id', None) is not None: + order_task = ( + ShippingOrderTask.query + .filter_by(extraction_run_id=int(run.id)) + .order_by(ShippingOrderTask.id.desc()) + .first() + ) + if order_task is not None: + from app.services.shipping_notice.order_task_service import sync_order_task_processing_state + sync_order_task_processing_state( + order_task, + force_progress_bump=True, + actor_type='system', + actor_id='review_progress', + reason_code='review_gate_changed', + source='order_review_progress_bridge', + correlation_id=str(case.case_no or '')[:128] or None, + ) if nested.is_active: nested.commit() return True diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index 0b33037f..ea557252 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -40,13 +40,22 @@ from __future__ import annotations from typing import Any +from sqlalchemy.orm import Load + from app import db from app.models import ( + Job, ShippingOrderCandidate, ShippingOrderExtraction, ShippingOrderProcessingRun, ShippingOrderReviewCase, + ShippingOrderReviewDraft, ShippingOrderReviewStream, + ShippingOrderIntake, + ShippingNotice, + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, ) @@ -535,6 +544,52 @@ def _document_filename(run: ShippingOrderProcessingRun, document_id: int) -> str return None +def _document_intake_for_retry( + run: ShippingOrderProcessingRun, + document_id: int, + *, + intakes_by_no: dict[str, ShippingOrderIntake] | None = None, +) -> ShippingOrderIntake | None: + """按冻结文档归属定位当前 Intake,避免工作台按文件名或会话猜测 SNI。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + for intake_snapshot in snapshot.get('intakes') or []: + if not isinstance(intake_snapshot, dict): + continue + for document in intake_snapshot.get('documents') or []: + if not isinstance(document, dict) or int(document.get('document_id') or 0) != int(document_id): + continue + intake_no = str(intake_snapshot.get('intake_no') or '').strip().upper() + if intake_no: + if intakes_by_no is not None: + return intakes_by_no.get(intake_no) + return ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none() + return None + + +def _intake_retry_projection( + case: ShippingOrderReviewCase, + run: ShippingOrderProcessingRun, + candidate: ShippingOrderCandidate | None, + *, + intake: ShippingOrderIntake | None = None, + intakes_by_no: dict[str, ShippingOrderIntake] | None = None, +) -> tuple[str | None, bool]: + """返回当前 Case 唯一的 Intake 重试目标与服务端授权结果。""" + if intake is None: + intake = _document_intake_for_retry( + run, + int(case.document_id), + intakes_by_no=intakes_by_no, + ) + retry_authorized = bool( + intake is not None + and str(intake.parse_status or '').strip().lower() == 'parse_failed' + and candidate is None + and not case.confirmed_task_id + ) + return (intake.intake_no if retry_authorized else None, retry_authorized) + + def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]: """由后端 Case 状态与 WorkflowItem 生命周期决定可用动作,前端不可自行推导确认资格。""" from app.services.shipping_notice.tool_common import llm_review_enabled @@ -651,6 +706,7 @@ def serialize_review_case( run = case.run draft = case.current_draft candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None + intake_no, intake_retry_authorized = _intake_retry_projection(case, run, candidate) schema_fields = _schema_fields(run) header_fields = [item for item in schema_fields if item.get('scope') == 'header'] line_fields = [item for item in schema_fields if item.get('scope') == 'line'] @@ -678,7 +734,13 @@ def serialize_review_case( 'issues': list(draft.issue_summary_json or []), 'validation': dict(draft.validation_result_json or {}), 'build_eligibility': { - 'can_build': bool((draft.validation_result_json or {}).get('can_build')), + # 未校验不是业务阻断;保留 None 让前端展示“尚未校验”,避免 + # 把缺失的布尔值投影成 can_build=false。 + 'can_build': ( + bool((draft.validation_result_json or {}).get('can_build')) + if str((draft.validation_result_json or {}).get('status') or '').strip() != 'not_validated' + else None + ), 'can_auto_create': bool((draft.validation_result_json or {}).get('can_auto_create')), 'status': str((draft.validation_result_json or {}).get('status') or 'needs_review'), 'gates': dict((draft.validation_result_json or {}).get('gates') or {}), @@ -912,6 +974,16 @@ def serialize_review_case( # task_missing:无恢复 API 时明确 view + contact_admin;防御性剥离残留 confirm。 available_actions = list(bundle['available_actions']) if bundle else [a for a in _allowed_actions(case) if a != 'confirm'] + if intake_retry_authorized: + available_actions = ['retry_parse'] + elif ( + candidate is None + and not case.confirmed_task_id + and (intake := _document_intake_for_retry(run, int(case.document_id))) is not None + and str(intake.parse_status or '').strip().lower() in {'parsing', 'queued', 'cancelled'} + ): + # parsing / cancelled 等状态只可等待或查看;不得把草稿动作误投影为解析恢复。 + available_actions = [] # 兼容兜底:task_missing 仍然优先固定视图动作。 if formal_ot.get('task_missing'): available_actions = ['view', 'contact_admin'] @@ -976,6 +1048,7 @@ def serialize_review_case( 'draft': projected_draft, 'llm_suggestions': llm_suggestions, 'available_actions': available_actions, + 'intake_no': intake_no, 'formal_editable_field_ids': ( list_editable_formal_field_ids( schema_fields, @@ -999,9 +1072,33 @@ def _serialize_review_case_summary( case: ShippingOrderReviewCase, *, run: ShippingOrderProcessingRun, + candidates_by_id: dict[int, ShippingOrderCandidate] | None = None, + intakes_by_no: dict[str, ShippingOrderIntake] | None = None, + drafts_by_id: dict[int, ShippingOrderReviewDraft] | None = None, ) -> dict[str, Any]: """为工作台文件队列投影单 Case 的只读识别与生命周期摘要。""" - candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None + draft = ( + drafts_by_id.get(int(case.current_draft_id)) + if drafts_by_id is not None and case.current_draft_id + else case.current_draft + ) + candidate = ( + candidates_by_id.get(int(case.candidate_id)) + if candidates_by_id is not None and case.candidate_id + else (db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None) + ) + intake = _document_intake_for_retry( + run, + int(case.document_id), + intakes_by_no=intakes_by_no, + ) + intake_no, intake_retry_authorized = _intake_retry_projection( + case, + run, + candidate, + intake=intake, + intakes_by_no=intakes_by_no, + ) # 空 Review Case 只是解析异常/人工处置容器,不能显示为已进入订单复核。 # 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。 lifecycle_stage = 'intake_parse' @@ -1042,9 +1139,23 @@ def _serialize_review_case_summary( 'document_id': int(case.document_id), 'file_name': _document_filename(run, int(case.document_id)), 'status': case.status, - 'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None, - 'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0, - 'available_actions': _allowed_actions(case), + 'draft_version': int(draft.draft_version) if draft is not None else None, + 'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0, + # Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。 + # 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。 + 'available_actions': ( + ['retry_parse'] + if intake_retry_authorized + else ( + [] + if intake is not None + and str(intake.parse_status or '').strip().lower() in {'parsing', 'queued', 'cancelled'} + and candidate is None + and not case.confirmed_task_id + else _allowed_actions(case) + ) + ), + 'intake_no': intake_no, # 后端按 Case/正式任务裁决,禁止工作台仅为当前项从草稿拼接 PO 或阶段。 'po_number': str(candidate.po_number or '').strip() or None if candidate is not None else None, 'lifecycle_stage': lifecycle_stage, @@ -1058,6 +1169,8 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]: """返回当前有效 Case 的轻量列表;superseded 版本仅保留在历史/审计中。""" # Run 是执行审计容器,不拥有“当前复核版本”语义。历史数据即使遗留开放状态, # 也只能由文件 Stream 的 current_case_id 决定是否出现在 Run 详情。 + from app.services.shipping_notice.order_extraction_workspace_projection import serialize_lifecycle_progress + cases = ( db.session.query(ShippingOrderReviewCase) .join( @@ -1086,6 +1199,8 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]: 'superseded_by_run_no': superseding_run.run_no if superseding_run is not None else None, 'summary': counts, 'items': items, + # 复核首屏只需 Run 级进度;禁止为此读取完整文件、候选与处理项投影。 + 'lifecycle_progress': serialize_lifecycle_progress(run), } @@ -1101,16 +1216,162 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, .join(ShippingOrderProcessingRun, ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id) .filter(ShippingOrderProcessingRun.conversation_id == conversation_id) .filter(ShippingOrderReviewCase.status != 'superseded') + .options( + Load(ShippingOrderReviewCase).load_only( + ShippingOrderReviewCase.id, + ShippingOrderReviewCase.stream_id, + ShippingOrderReviewCase.revision_no, + ShippingOrderReviewCase.case_no, + ShippingOrderReviewCase.run_id, + ShippingOrderReviewCase.document_id, + ShippingOrderReviewCase.candidate_id, + ShippingOrderReviewCase.current_draft_id, + ShippingOrderReviewCase.confirmed_task_id, + ShippingOrderReviewCase.status, + ShippingOrderReviewCase.disposition, + ), + Load(ShippingOrderProcessingRun).load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.run_no, + ShippingOrderProcessingRun.conversation_id, + ShippingOrderProcessingRun.user_id, + ShippingOrderProcessingRun.schema_version_id, + ShippingOrderProcessingRun.input_snapshot_json, + ), + ) ) if owner_ids: query = query.filter(ShippingOrderReviewStream.owner_user_id.in_(owner_ids)) rows = query.order_by(ShippingOrderReviewStream.updated_at.desc(), ShippingOrderReviewStream.id.desc()).all() - items = [{ - **_serialize_review_case_summary(case, run=run), - 'stream_id': int(stream.id), - 'stream_state': stream.state, - 'source_run_no': run.run_no, - } for stream, case, run in rows] + case_ids = [int(case.id) for _, case, _ in rows] + candidate_ids = [int(case.candidate_id) for _, case, _ in rows if case.candidate_id] + draft_ids = [int(case.current_draft_id) for _, case, _ in rows if case.current_draft_id] + task_ids = [int(case.confirmed_task_id) for _, case, _ in rows if case.confirmed_task_id] + candidates_by_id = { + int(candidate.id): candidate + for candidate in ShippingOrderCandidate.query.filter(ShippingOrderCandidate.id.in_(candidate_ids)).all() + } if candidate_ids else {} + drafts_by_id = { + int(draft.id): draft + for draft in ShippingOrderReviewDraft.query.filter(ShippingOrderReviewDraft.id.in_(draft_ids)).all() + } if draft_ids else {} + _tasks_by_id = { + int(task.id): task + for task in ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all() + } if task_ids else {} + intake_nos = { + str(intake_snapshot.get('intake_no') or '').strip().upper() + for _, case, run in rows + for intake_snapshot in (run.input_snapshot_json or {}).get('intakes', []) + if isinstance(intake_snapshot, dict) + for document in intake_snapshot.get('documents') or [] + if isinstance(document, dict) and int(document.get('document_id') or 0) == int(case.document_id) + } + intakes_by_no = { + str(intake.intake_no).strip().upper(): intake + for intake in ShippingOrderIntake.query.filter(ShippingOrderIntake.intake_no.in_(intake_nos)).all() + } if intake_nos else {} + + # 队列是会话级聚合:将逐 Case 的 STP 读取收敛为一次批量查询,并复用既有投影缓存契约。 + from app.services.shipping_notice.order_stp_auto_create_service import build_stp_idempotency_key + + stp_prefixes = { + f"stp-auto:{run.run_no}:doc-{int(case.document_id)}:" + for _, case, run in rows + if case.document_id is not None + } + stp_refs = { + build_stp_idempotency_key( + run_no=run.run_no, + document_id=int(case.document_id), + draft_version=int(drafts_by_id[int(case.current_draft_id)].draft_version), + ) + for _, case, run in rows + if case.current_draft_id and int(case.current_draft_id) in drafts_by_id + } + jobs_by_ref: dict[str, list[Job]] = {ref: [] for ref in stp_refs} + jobs_by_prefix: dict[str, list[Job]] = {prefix: [] for prefix in stp_prefixes} + if stp_prefixes: + from sqlalchemy import or_ + from app.services.shipping_notice.order_stp_auto_create_service import SHIPPING_STP_JOB_DOMAIN + from app.jobs.types import JobType + + jobs = ( + Job.query.filter( + Job.domain == SHIPPING_STP_JOB_DOMAIN, + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + or_(*(Job.business_ref.like(f'{prefix}%') for prefix in stp_prefixes)), + ).order_by(Job.id.desc()).all() + ) + for job in jobs: + ref = str(job.business_ref or '').strip() + jobs_by_ref.setdefault(ref, []).append(job) + prefix = next((item for item in stp_prefixes if ref.startswith(item)), None) + if prefix: + jobs_by_prefix[prefix].append(job) + + executions_by_case_id: dict[int, ShippingProcessExecution] = {} + gates_by_execution_id: dict[int, list[ShippingProcessGate]] = {} + latest_attempt_by_id: dict[int, ShippingProcessGateAttempt] = {} + if case_ids: + executions = ( + ShippingProcessExecution.query.filter( + ShippingProcessExecution.review_case_id.in_(case_ids), + ShippingProcessExecution.status != 'superseded', + ).order_by(ShippingProcessExecution.id.desc()).all() + ) + execution_ids = [int(execution.id) for execution in executions] + for execution in executions: + if execution.review_case_id is not None: + executions_by_case_id.setdefault(int(execution.review_case_id), execution) + if execution_ids: + gates = ShippingProcessGate.query.filter( + ShippingProcessGate.execution_id.in_(execution_ids), + ).order_by( + ShippingProcessGate.execution_id.asc(), + ShippingProcessGate.sequence_no.asc(), + ).all() + for gate in gates: + gates_by_execution_id.setdefault(int(gate.execution_id), []).append(gate) + latest_attempt_ids = [ + int(gate.latest_attempt_id) + for gate in gates + if gate.latest_attempt_id is not None + ] + if latest_attempt_ids: + latest_attempt_by_id = { + int(attempt.id): attempt + for attempt in ShippingProcessGateAttempt.query.filter( + ShippingProcessGateAttempt.id.in_(latest_attempt_ids), + ).all() + } + + previous_cache = db.session.info.get('shipping_conversation_projection_read_cache') + cache = dict(previous_cache) if isinstance(previous_cache, dict) else {} + cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **jobs_by_ref} + cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **jobs_by_prefix} + cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **executions_by_case_id} + cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **gates_by_execution_id} + cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **latest_attempt_by_id} + db.session.info['shipping_conversation_projection_read_cache'] = cache + try: + items = [{ + **_serialize_review_case_summary( + case, + run=run, + candidates_by_id=candidates_by_id, + intakes_by_no=intakes_by_no, + drafts_by_id=drafts_by_id, + ), + 'stream_id': int(stream.id), + 'stream_state': stream.state, + 'source_run_no': run.run_no, + } for stream, case, run in rows] + finally: + if previous_cache is None: + db.session.info.pop('shipping_conversation_projection_read_cache', None) + else: + db.session.info['shipping_conversation_projection_read_cache'] = previous_cache counts = { 'total': len(items), 'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')), diff --git a/backend/app/services/shipping_notice/order_review_reservation_service.py b/backend/app/services/shipping_notice/order_review_reservation_service.py index 7b04fe21..f103b81f 100644 --- a/backend/app/services/shipping_notice/order_review_reservation_service.py +++ b/backend/app/services/shipping_notice/order_review_reservation_service.py @@ -114,22 +114,31 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, effective = str(proj.get('effective_reservation_id') or '').strip() or None line_key = str(proj.get('line_key') or '').strip() or None block_reason = str(proj.get('block_reason') or '').strip() or None - reservation_blocked = ( - not effective - or (block_reason and 'reservation' in block_reason.lower()) - or any( - int(item.get('line_index') or -1) == idx - for item in issues + line_reservation_issue = next( + ( + item for item in issues if item.get('line_index') is not None - ) + and int(item.get('line_index')) == idx + and str(item.get('code') or item.get('reason_code') or '') in _RESERVATION_ISSUE_CODES + ), + None, + ) + reservation_block_reason = ( + str((line_reservation_issue or {}).get('code') or (line_reservation_issue or {}).get('reason_code') or '').strip() + or ('effective_reservation_missing' if not effective else None) + or (block_reason if block_reason and 'reservation' in block_reason.lower() else None) + ) + reservation_blocked = ( + reservation_block_reason is not None ) lines_out.append({ 'line_index': idx, 'line_key': line_key, 'effective_reservation_id': effective, 'can_build': bool(proj.get('can_build', True)), - 'block_reason': block_reason, - 'needs_attention': reservation_blocked and not bool(proj.get('can_build', True)), + # Reservation 面板只展示自身 Gate 原因,不能泄漏库存路由 block_reason。 + 'block_reason': reservation_block_reason, + 'needs_attention': reservation_blocked, }) # 无 line_projections 时仍从草稿行展示当前值,便于编辑入口。 diff --git a/backend/app/services/shipping_notice/order_review_resume_service.py b/backend/app/services/shipping_notice/order_review_resume_service.py index 979b89fe..bcf9eb43 100644 --- a/backend/app/services/shipping_notice/order_review_resume_service.py +++ b/backend/app/services/shipping_notice/order_review_resume_service.py @@ -129,6 +129,7 @@ def resume_after_review_change( change_type: str | None = None, skip_validate: bool = False, allow_auto_create: bool = True, + expected_draft_version: int | None = None, ) -> dict[str, Any]: """ 建单前统一恢复:重校验 → Gate 同步 → 资格重算 → 可选 auto_gate 建单。 @@ -141,6 +142,7 @@ def resume_after_review_change( change_type: 可选失效规则键(process_gate_dependency)。 skip_validate: True 时跳过 validate_draft(调用方刚校验过)。 allow_auto_create: False 时只重算资格,不自动建单(例如仅预览)。 + expected_draft_version: 可选乐观锁版本;显式保存校验时必须传入。 Returns: resume_outcome 字典(含 gate_recalculated / auto_gate_allowed / task_created 等)。 @@ -177,12 +179,27 @@ def resume_after_review_change( 'case': serialize_review_case(case), } + # [STEP 1.5] 唯一 Shadow 候选必须先写成 Bill-to confirmed,再读取建单资格。 + # 否则保存校验会把“唯一候选待确认”误判为“客户未识别”。不在此处 commit, + # 保证客户确认、Draft 校验与后续 Gate/STP 决策属于同一事务。 + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + auto_confirm_unique_customer_for_review_case, + ) + customer_auto_confirmation = auto_confirm_unique_customer_for_review_case( + case=case, + trigger=trigger_code, + ) + # [STEP 2] 显式全量校验(同步建单前 Gate)。 if not skip_validate: validate_draft( user_id=int(user_id), case_no=str(case.case_no), - expected_draft_version=int(case.current_draft.draft_version), + expected_draft_version=( + int(expected_draft_version) + if expected_draft_version is not None + else int(case.current_draft.draft_version) + ), ) db.session.flush() case = _reload_case(user_id=user_id, case_no=case_no) @@ -216,6 +233,7 @@ def resume_after_review_change( 'auto_gate_allowed': snap['auto_gate_allowed'], 'qualification_status': snap['qualification_status'], 'failed_gates': snap['failed_gates'], + 'customer_auto_confirmation': customer_auto_confirmation, }, source='order_review_resume', strict=True, @@ -238,6 +256,7 @@ def resume_after_review_change( ), 'case': serialize_review_case(case), 'invalidated_gates': invalidated, + 'customer_auto_confirmation': customer_auto_confirmation, } # [STEP 5] 可建单但不允许 auto_gate:等待人工确认建单。 @@ -276,6 +295,7 @@ def resume_after_review_change( ), 'case': serialize_review_case(case), 'invalidated_gates': invalidated, + 'customer_auto_confirmation': customer_auto_confirmation, } # [STEP 6] auto_gate:入队 STP 幂等 Job(queued);Worker 再执行 confirm。 diff --git a/backend/app/services/shipping_notice/order_review_service.py b/backend/app/services/shipping_notice/order_review_service.py index 9e56a087..dda4cfa4 100644 --- a/backend/app/services/shipping_notice/order_review_service.py +++ b/backend/app/services/shipping_notice/order_review_service.py @@ -17,6 +17,7 @@ from __future__ import annotations import uuid from typing import Any +from sqlalchemy.orm import load_only from sqlalchemy.orm.attributes import flag_modified from app import db @@ -429,13 +430,32 @@ def get_review_queue_visible_to_user( is_admin: bool = False, ) -> list[ShippingOrderProcessingRun]: """按当前 Run 定位会话;Stream 当前版本决定队列,Run 替代标记不再过滤文件。""" - anchor = get_review_run_visible_to_user(run_no, user_id, is_admin=is_admin) + # 队列仅需要会话与 owner 范围;不要为授权读取解码 Run 的审计/执行大 JSON。 + anchor = ( + ShippingOrderProcessingRun.query.options( + load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.user_id, + ShippingOrderProcessingRun.conversation_id, + ), + ) + .filter_by(run_no=run_no) + .first() + ) + if anchor is None or (not is_admin and int(anchor.user_id) != int(user_id)): + raise NotFoundError('Order extraction run not found', code='SHIPPING.REVIEW_RUN_NOT_FOUND') query = ShippingOrderProcessingRun.query.filter( ShippingOrderProcessingRun.conversation_id == anchor.conversation_id, ) if not is_admin: query = query.filter(ShippingOrderProcessingRun.user_id == int(user_id)) - return query.order_by( + return query.options( + load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.user_id, + ShippingOrderProcessingRun.conversation_id, + ), + ).order_by( ShippingOrderProcessingRun.created_at.asc(), ShippingOrderProcessingRun.id.asc(), ).all() diff --git a/backend/app/services/shipping_notice/order_review_workbench_projection.py b/backend/app/services/shipping_notice/order_review_workbench_projection.py index 26d91736..f287239c 100644 --- a/backend/app/services/shipping_notice/order_review_workbench_projection.py +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -441,12 +441,22 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str } task_no = str(getattr(task, 'task_no', None) or '').strip().upper() or None - upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + verified_upload_success = has_verified_upload_success(task) + upload_status = getattr(task, 'upload_status', None) + upload_status = upload_status.strip().lower() if isinstance(upload_status, str) else '' + export_file_path = getattr(task, 'export_file_path', None) + match_status = getattr(task, 'match_status', None) + inventory_lines = getattr(task, 'inventory_lines_json', None) + has_export = isinstance(export_file_path, str) and bool(export_file_path.strip()) + has_match = isinstance(match_status, str) and bool(match_status.strip()) + has_inventory = isinstance(inventory_lines, (list, dict)) and bool(inventory_lines) progress_state = ( - 'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} - else 'export_ready' if getattr(task, 'export_file_path', None) - else 'matched' if getattr(task, 'match_status', None) - else 'inventory_ready' if getattr(task, 'inventory_lines_json', None) + 'uploaded' if verified_upload_success + else 'export_ready' if has_export + else 'matched' if has_match + else 'inventory_ready' if has_inventory else 'not_started' ) active = find_active_shipping_notice_run_job(task_no=task_no or '') @@ -633,9 +643,14 @@ def project_stage_for_task( map_notice_to_processing_status_stage, ) - upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + # 业务完成不能仅信任 Notice 的历史聚合字段。复核工作台必须与批次投影 + # 复用同一成功谓词,否则同一任务会在不同入口出现“已完成/待上传”分叉。 + verified_upload_success = has_verified_upload_success(task) + raw_upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() progress_state = ( - 'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} + 'uploaded' if verified_upload_success else 'export_ready' if getattr(task, 'export_file_path', None) else 'matched' if getattr(task, 'match_status', None) else 'inventory_ready' if getattr(task, 'inventory_lines_json', None) @@ -656,10 +671,12 @@ def project_stage_for_task( 'stage_node': None, } - # 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在 - # freight_uploading,不能用过期阶段覆盖已经完成的履约状态。 - if progress_state in {'uploaded', 'closed', 'completed'}: + # 成功回调会先更新 Notice 聚合事实;旧 OT.stage 可能仍停在 + # freight_uploading,只有三层成功事实齐备时才能覆盖为 completed。 + if progress_state == 'uploaded': return _with_label('completed', source='notice_terminal') + if raw_upload_status in {'uploaded', 'succeeded', 'success'}: + return _with_label('freight_uploading', source='upload_success_unverified') # [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。 order_task = None @@ -678,6 +695,8 @@ def project_stage_for_task( order_task = None ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() if order_task else '' if ot_stage and ot_stage in SHIPPING_PROCESSING_STAGES: + if ot_stage == 'completed' and not verified_upload_success: + return _with_label('freight_uploading', source='upload_success_unverified') # [STEP 1b] 正式 OT 已创建但 stage 仍停在 order_creating:业务上已进入获取库存。 # Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。 if ot_stage == 'order_creating': 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 73dccf3e..02d42447 100644 --- a/backend/app/services/shipping_notice/order_schema/field_rules.py +++ b/backend/app/services/shipping_notice/order_schema/field_rules.py @@ -225,6 +225,11 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any: for pattern in ( '%Y-%m-%d', '%Y/%m/%d', '%Y.%m.%d', '%Y%m%d', '%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y', + # Purchase orders also commonly use a two-digit year (for + # example ``06/16/26``). ``strptime`` applies the standard + # POSIX pivot for ``%y``; the normalized result is still an + # ISO date, so downstream validators receive one type. + '%m/%d/%y', '%m-%d-%y', '%m.%d.%y', '%d-%b-%Y', '%d-%B-%Y', ): try: diff --git a/backend/app/services/shipping_notice/order_schema/runtime.py b/backend/app/services/shipping_notice/order_schema/runtime.py index 40c8836c..3ff40227 100644 --- a/backend/app/services/shipping_notice/order_schema/runtime.py +++ b/backend/app/services/shipping_notice/order_schema/runtime.py @@ -1187,19 +1187,6 @@ def persist_dynamic_order( documents, schema_definition=version.definition_json or {}, layout_candidates_by_document=layout_candidates_by_document, ) - for issue in table_issues: - blocked.extend(str(code) for code in issue['field_codes']) - for code in issue.get('field_codes') or []: - findings.append({ - 'finding_code': 'layout_table_evidence_blocked', - 'owning_gate_code': 'layout_parsing', - 'severity': 'blocking', - 'field_code': str(code), - 'decision_id': None, - 'reason_code': str(issue.get('reason') or 'layout_evidence_unavailable'), - 'user_visible': True, - 'blocks_current_action': True, - }) groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [ (None, None, 'header', raw_order.get('header_fields') or [], header) ] @@ -1383,6 +1370,41 @@ def persist_dynamic_order( owning_gate_code='field_completeness', )) + # 表格候选未被整表接受只代表结构化坐标质量不足。若当前字段已有已接受的 + # 可验证证据,不能用表格诊断覆盖该字段事实;否则关键字段仍须保守阻断。 + accepted_field_codes = { + str(decision.get('field_code') or '') + for decision in decisions + if str(decision.get('status') or '') in {'accepted', 'corroborated', 'derived'} + } + for issue in table_issues: + blocking_codes = [ + str(code) + for code in issue['field_codes'] + if str(code) not in accepted_field_codes + and field_may_block_process( + next( + ( + config for config in all_configs.values() + if str(config.get('field_code') or '') == str(code) + ), + None, + ) + ) + ] + blocked.extend(blocking_codes) + for code in issue.get('field_codes') or []: + findings.append({ + 'finding_code': 'layout_table_evidence_blocked', + 'owning_gate_code': 'layout_parsing', + 'severity': 'blocking' if str(code) in blocking_codes else 'diagnostic', + 'field_code': str(code), + 'decision_id': None, + 'reason_code': str(issue.get('reason') or 'layout_evidence_unavailable'), + 'user_visible': str(code) in blocking_codes, + 'blocks_current_action': str(code) in blocking_codes, + }) + # 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。 system_line_projections: list[dict[str, Any]] = [] for line, projection in zip(extraction.lines, line_projections): 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 af98c29f..16c3bbf8 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,9 +29,6 @@ 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, @@ -214,47 +211,6 @@ def _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, @@ -322,6 +278,13 @@ def find_active_stp_job(*, business_ref: str) -> Job | None: key = str(business_ref or '').strip() if not key: return None + cache = db.session.info.get('shipping_conversation_projection_read_cache') + if isinstance(cache, dict): + jobs = cache.get('stp_jobs_by_ref', {}).get(key, []) + return next( + (job for job in jobs if str(job.status or '').strip().lower() in {'queued', 'running'}), + None, + ) return ( Job.query .filter( @@ -348,6 +311,10 @@ def find_latest_stp_job(*, business_ref: str) -> Job | None: key = str(business_ref or '').strip() if not key: return None + cache = db.session.info.get('shipping_conversation_projection_read_cache') + if isinstance(cache, dict): + jobs = cache.get('stp_jobs_by_ref', {}).get(key, []) + return jobs[0] if jobs else None return ( Job.query .filter( @@ -459,40 +426,6 @@ 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')) diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index 1c23a346..ddc5d92c 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -9,6 +9,7 @@ from __future__ import annotations import copy from typing import Any +from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value from app.services.shipping_notice.po_number import normalize_atomic_po_number @@ -50,6 +51,135 @@ def _schema_field_values(row: dict[str, Any], field_codes: set[str]) -> set[str] } +def _canonical_field_value(value: Any, config: dict[str, Any]) -> Any: + """返回冻结 Schema 下用于跨来源比较的字段规范值,保留调用方持有的原始证据值。 + + 核心逻辑:正文补充合并不能把金额、小数位、日期等显示格式差异误判为业务冲突; + 统一复用订单 Schema 的标准化器,遇到非法值仍向上抛出既有校验异常而非放行。 + + Args: + value: PDF Observation 或邮件正文行中的原始值。 + config: 该 field_code 对应的冻结 Schema 配置。 + + Returns: + 可进行语义相等比较的规范值。 + """ + return normalize_order_field_value(value, config) + + +def _canonical_values(fields: Any, code: str, codes: dict[str, str], config: dict[str, Any]) -> set[Any]: + """收集字段 Observation 的规范值集合,禁止以显示文本代替业务等价判断。""" + if not isinstance(fields, list): + return set() + return { + _canonical_field_value(observation.get('value'), config) + for field in fields if isinstance(field, dict) + if codes.get(str(field.get('field_id') or '')) == code + for observation in field.get('observations') or [] if isinstance(observation, dict) + if observation.get('value') not in (None, '') + } + + +def _field_observations(fields: Any, code: str, codes: dict[str, str]) -> list[dict[str, Any]]: + """返回字段的原始 Observation,供冲突 Finding 保留 PDF 侧可追溯证据。""" + if not isinstance(fields, list): + return [] + return [ + observation + for field in fields if isinstance(field, dict) + if codes.get(str(field.get('field_id') or '')) == code + for observation in field.get('observations') or [] if isinstance(observation, dict) + if observation.get('value') not in (None, '') + ] + + +def _supplement_field_conflict( + *, + field_code: str, + config: dict[str, Any], + line_index: int, + pdf_observations: list[dict[str, Any]], + email_value: Any, + email_evidence: dict[str, Any], + email_document_id: int, + schema_version: str, +) -> dict[str, Any]: + """构造可展示、可裁决的正文补充字段冲突 Finding。 + + 核心逻辑:Candidate Gate、复核面板和进度统计必须消费同一事实;因此不能只保存 + field/reason,而要冻结双方原值、Schema 规范值、文档和 evidence_ref。 + """ + pdf = pdf_observations[0] if pdf_observations else {} + pdf_raw = pdf.get('value') + email_raw = email_value + return { + 'conflict_key': f'{line_index}:{field_code}', + 'severity': 'blocking', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'unresolved', + 'field': field_code, + 'scope': 'header' if line_index < 0 else 'line', + 'line_index': line_index if line_index >= 0 else None, + 'values': [str(pdf_raw), str(email_raw)], + 'sources': [ + { + 'source_type': 'pdf', + 'raw_value': str(pdf_raw), + 'canonical_value': str(_canonical_field_value(pdf_raw, config)), + 'document_id': pdf.get('document_id'), + 'evidence_ref': dict(pdf.get('evidence_ref') or {}), + }, + { + 'source_type': 'email_body', + 'raw_value': str(email_raw), + 'canonical_value': str(_canonical_field_value(email_raw, config)), + 'document_id': email_document_id or None, + 'evidence_ref': dict(email_evidence or {}), + }, + ], + 'rule_version': schema_version or 'shipping-order-schema.unknown', + } + + +def _supplement_multi_value_conflict( + *, + field_code: str, + config: dict[str, Any], + values: set[str], + selected_rows: list[dict[str, Any]], + line_index: int, + email_document_id: int, + schema_version: str, +) -> dict[str, Any]: + """构造邮件正文内部多值的完整 Finding,禁止保留不可展示的旧简略冲突。""" + ordered_values = sorted(values) + sources: list[dict[str, Any]] = [] + for row in selected_rows: + raw_value = str(row.get(field_code) or '').strip() + if not raw_value: + continue + evidence = row.get('evidence', {}).get(field_code, {}) if isinstance(row.get('evidence'), dict) else {} + sources.append({ + 'source_type': 'email_body', + 'raw_value': raw_value, + 'canonical_value': str(_canonical_field_value(raw_value, config)), + 'document_id': email_document_id or None, + 'evidence_ref': dict(evidence or {}), + }) + return { + 'conflict_key': f'{line_index}:{field_code}', + 'severity': 'blocking', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'unresolved', + 'field': field_code, + 'scope': 'header' if line_index < 0 else 'line', + 'line_index': line_index if line_index >= 0 else None, + 'values': ordered_values, + 'sources': sources, + 'rule_version': schema_version or 'shipping-order-schema.unknown', + } + + def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]: """按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。""" configs = { @@ -59,6 +189,7 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta } ids = {code: str(item.get('field_id') or '') for code, item in configs.items() if item.get('field_id')} part_codes = {'part_number', 'customer_part_number'} & set(configs) + schema_version = str(schema_definition.get('version') or '') merged: list[dict[str, Any]] = [] for raw in orders: order = copy.deepcopy(raw) @@ -107,52 +238,81 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta continue for source_row in selected: row_part_values = _schema_field_values(source_row, part_codes) - target_lines = [line for line in order.get('lines') or [] if isinstance(line, dict)] + indexed_target_lines = [ + (index, line) + for index, line in enumerate(order.get('lines') or []) + if isinstance(line, dict) + ] if relation != 'po_fallback': # 精确料号命中(含 PN/AMPN × 内部/客户料号四种组合)只写入交集行。 - target_lines = [ - line for line in target_lines + indexed_target_lines = [ + (index, line) for index, line in indexed_target_lines if row_part_values & ( _values(line.get('fields'), 'part_number', {v: k for k, v in ids.items()}) | _values(line.get('fields'), 'customer_part_number', {v: k for k, v in ids.items()}) ) ] - if not target_lines: + if not indexed_target_lines: order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'}) continue + target_lines = [line for _, line in indexed_target_lines] for target_code, config in configs.items(): - values = { - str(item.get(target_code) or '').strip() - for item in selected - if str(item.get(target_code) or '').strip() - } - if len(values) > 1: - order.setdefault('conflicts', []).append({ - 'severity': 'blocking', 'reason': 'supplement_field_conflict', - 'field': target_code, - }) - continue - value = next(iter(values), '') - field_id = ids.get(target_code) - if not value or not field_id: - continue - target_groups = order.get('header_fields') if config.get('scope') == 'header' else [line.setdefault('fields', []) for line in target_lines] - for fields in ([target_groups] if config.get('scope') == 'header' else target_groups): + target_groups = ( + [(-1, order.get('header_fields'))] + if config.get('scope') == 'header' + else [(index, line.setdefault('fields', [])) for index, line in indexed_target_lines] + ) + for line_index, fields in target_groups: if not isinstance(fields, list): continue - existing_values = _values(fields, target_code, {v: k for k, v in ids.items()}) + value_by_canonical: dict[Any, tuple[str, dict[str, Any]]] = {} + comparable_rows = selected if line_index < 0 or relation == 'po_fallback' else [source_row] + for item in comparable_rows: + raw_value = str(item.get(target_code) or '').strip() + if raw_value: + value_by_canonical.setdefault( + _canonical_field_value(raw_value, config), + (raw_value, item), + ) + values = {raw_value for raw_value, _ in value_by_canonical.values()} + if len(value_by_canonical) > 1: + conflict = _supplement_multi_value_conflict( + field_code=target_code, + config=config, + values=values, + selected_rows=comparable_rows, + line_index=line_index, + email_document_id=int(supplement.get('document_id') or 0), + schema_version=schema_version, + ) + if conflict not in order.setdefault('conflicts', []): + order['conflicts'].append(conflict) + continue + value, value_source_row = next(iter(value_by_canonical.values()), ('', {})) + field_id = ids.get(target_code) + if not value or not field_id: + continue + existing_values = _canonical_values( + fields, target_code, {v: k for k, v in ids.items()}, config, + ) if existing_values: # PDF 是主证据,但正文给出不同的唯一 Schema 值也不能被静默忽略: # 保留 PDF 值,强制进入 Review 由人工裁决。 - if existing_values != {value.strip().upper()}: - conflict = { - 'severity': 'blocking', 'reason': 'supplement_field_conflict', - 'field': target_code, - } + if existing_values != {_canonical_field_value(value, config)}: + conflict = _supplement_field_conflict( + field_code=target_code, + config=config, + line_index=line_index, + pdf_observations=_field_observations(fields, target_code, {v: k for k, v in ids.items()}), + email_value=value, + email_evidence=value_source_row.get('evidence', {}).get(target_code, {}), + email_document_id=int(supplement.get('document_id') or 0), + schema_version=schema_version, + ) if conflict not in order.setdefault('conflicts', []): order['conflicts'].append(conflict) continue - _inject(fields, field_id, value, source_row.get('evidence', {}).get(target_code, {}), int(supplement.get('document_id') or 0)) + _inject(fields, field_id, value, value_source_row.get('evidence', {}).get(target_code, {}), int(supplement.get('document_id') or 0)) # 来源方和分配实体是证据字段;没有对应 Schema 字段时仍写入内部订单元数据。 order.setdefault('_hxops_email_supplement_evidence', []).append({ 'source_from_party': source_row.get('source_from_party'), diff --git a/backend/app/services/shipping_notice/order_task_service.py b/backend/app/services/shipping_notice/order_task_service.py index ea0fb9de..62021249 100644 --- a/backend/app/services/shipping_notice/order_task_service.py +++ b/backend/app/services/shipping_notice/order_task_service.py @@ -46,6 +46,7 @@ def sync_order_task_processing_state( stage: str | None = None, status: str | None = None, bump_progress: bool = True, + force_progress_bump: bool = False, actor_type: str = 'system', actor_id: str | int | None = None, reason_code: str | None = None, @@ -69,6 +70,7 @@ def sync_order_task_processing_state( stage: 统一 ShippingProcessingStage;None 表示不改。 status: OT 投影 status;None 表示不改。 bump_progress: 是否递增乐观并发版本。 + force_progress_bump: 仅业务事实变化但 stage/status 不变时,是否强制推进版本。 actor_type/actor_id: 操作主体(默认 system)。 reason_code/reason: 变更原因(码 + 可选说明)。 request_id/operation_id/correlation_id: 请求与幂等关联键。 @@ -93,8 +95,9 @@ def sync_order_task_processing_state( if next_status is not None and before_status != next_status: order_task.status = next_status changed = True - if changed and bump_progress: + if (changed or force_progress_bump) and bump_progress: order_task.progress_version = before_version + 1 + changed = True if changed: order_task.updated_at = datetime.utcnow() db.session.flush() @@ -958,7 +961,10 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional 'shipping_notice_id': row.shipping_notice_id, 'candidate_id': row.candidate_id, } - row.shipping_notice_id = int(notice_id) + # 兼容字段只在首张 Notice 尚未建立时回填,后续分批 Notice 以 + # ShippingNotice.order_task_id 的多对一关系为权威,禁止覆盖首条指针。 + if row.shipping_notice_id is None: + row.shipping_notice_id = int(notice_id) row.updated_at = datetime.utcnow() from app.models import ShippingNotice @@ -979,7 +985,7 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional reason_code='notice_created', before=before, after={ - 'shipping_notice_id': int(notice_id), + 'shipping_notice_id': row.shipping_notice_id, 'candidate_id': row.candidate_id, 'notice_task_no': str(getattr(notice, 'task_no', None) or '') or None, }, diff --git a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py index 6e9e4202..099016f7 100644 --- a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py +++ b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py @@ -22,11 +22,15 @@ from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingNotice, + ShippingOrderTask, ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderReviewWaveIdempotency, ShippingOrderReviewWaveLine, + ShippingOrderSnapshot, ) +from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot +from app.services.shipping_notice.tool_common import generate_task_no from app.services.shipping_notice.order_review_fulfillment_decision_service import ( DECISION_FULFILL, _STATUS_BY_DECISION, @@ -71,7 +75,8 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE', details={'line_key': line.get('line_key'), 'match_result': line.get('match_result')}, ) - if line.get('is_shortage'): + is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_inventory_shortage' + if line.get('is_shortage') and not is_released_shortage: raise ConflictError( 'Line has inventory shortage', code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', @@ -79,7 +84,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] ) req = _parse_qty(line.get('required_qty')) avail = _parse_qty(line.get('available_qty')) - if req is None or avail is None or avail < req: + if req is None or (avail is None and not is_released_shortage) or (avail is not None and avail < req and not is_released_shortage): raise ConflictError( 'Line cannot fulfill complete quantity with current inventory facts', code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', @@ -164,7 +169,7 @@ def create_post_ot_fulfillment_wave( idempotency_key: 可选幂等键(独立表强约束)。 Returns: - wave_no / task_no / accepted_line_keys / skipped_line_keys / line_fulfillment / + wave_no / task_no / notice_no / accepted_line_keys / skipped_line_keys / line_fulfillment / idempotency_row_id / idempotent_replay。 """ keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] @@ -256,6 +261,7 @@ def create_post_ot_fulfillment_wave( accepted.append(key) wave_no = None + notice = None if accepted: max_wave = ( db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no)) @@ -266,9 +272,67 @@ def create_post_ot_fulfillment_wave( from app.services.shipping_notice.order_review_confirmation_service import ( _persist_wave_lines_for_task, ) + from app.services.shipping_notice.export import _source_notice_for_order_facts + + source_notice = _source_notice_for_order_facts(task) + snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) + snapshot_line_ids = { + int(snapshot.lines[int((by_key[key] or {}).get('line_index'))].id) + for key in accepted + if snapshot is not None + and (by_key[key] or {}).get('line_index') is not None + and 0 <= int((by_key[key] or {}).get('line_index')) < len(snapshot.lines) + } + if len(snapshot_line_ids) != len(accepted): + raise ConflictError( + 'Selected review lines do not map to frozen order lines', + code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING', + ) + order_task = db.session.get(ShippingOrderTask, int(task.order_task_id)) if task.order_task_id else None + if order_task is None: + raise ConflictError( + 'Formal notice is not linked to an order task', + code='SHIPPING.REVIEW_POST_OT_WAVE_ORDER_TASK_REQUIRED', + ) + # [STEP 1c] 每个履约波次都是独立 Notice,直接继承客户快照; + # 对外发货通知单号只能随该 Notice 的首个 Excel 在同一事务中分配。 + if task.customer_id is None: + raise ConflictError( + 'Formal notice customer is required before creating a fulfillment wave', + code='SHIPPING.REVIEW_POST_OT_WAVE_CUSTOMER_REQUIRED', + ) + notice = ShippingNotice( + task_no=generate_task_no(), + order_task_id=int(order_task.id), + customer_id=task.customer_id, + customer_name_snapshot=task.customer_name_snapshot, + customer_short_code_snapshot=task.customer_short_code_snapshot, + user_id=task.user_id, + conversation_id=task.conversation_id, + source_type='post_ot_fulfillment_wave', + inventory_source_code=task.inventory_source_code, + inventory_connector_type=task.inventory_connector_type, + inventory_warehouse_id=task.inventory_warehouse_id, + inventory_source_status=task.inventory_source_status, + inventory_source_method=task.inventory_source_method, + inventory_source_config_version=task.inventory_source_config_version, + inventory_routing_fingerprint=task.inventory_routing_fingerprint, + inventory_snapshot_id=task.inventory_snapshot_id, + customer_resolution_status=task.customer_resolution_status, + customer_resolution_method=task.customer_resolution_method, + customer_identity_fingerprint=task.customer_identity_fingerprint, + customer_confirmed_by=task.customer_confirmed_by, + customer_confirmed_at=task.customer_confirmed_at, + ) + db.session.add(notice) + db.session.flush() + notice.customer_resolution_status = 'confirmed' + replace_notice_lines_from_snapshot( + notice_id=int(notice.id), snapshot=snapshot, snapshot_line_ids=snapshot_line_ids, + ) _persist_wave_lines_for_task( case=case, - task=task, + task=notice, line_keys=accepted, wave_no=wave_no, revision_id=None, @@ -282,6 +346,18 @@ def create_post_ot_fulfillment_wave( current = _active_decision(case, key) if current is not None and current.line_status in {'task_created', 'fulfilled'}: continue + # [STEP 2a] 短缺放行的补录库存字段必须保留在活动审计决定中, + # 不能被通用 fulfill 决定覆盖,否则独立 Excel 将丢失放行字段来源。 + if ( + key in accepted + and current is not None + and current.decision_code == 'release_inventory_shortage' + ): + current.line_status = 'task_created' + current.task_id = int(notice.id) + current.wave_no = int(wave_no) if wave_no is not None else None + current.updated_at = now + continue if current is not None: current.is_active = False current.updated_at = now @@ -301,7 +377,7 @@ def create_post_ot_fulfillment_wave( available_qty=avail, reservation_id=line.get('reservation_id'), part_number=line.get('part_number'), - task_id=int(task.id), + task_id=int(notice.id) if key in accepted else int(task.id), wave_no=wave_no if key in accepted else ( int(current.wave_no) if current is not None and current.wave_no is not None else None ), @@ -342,8 +418,8 @@ def create_post_ot_fulfillment_wave( review_case_no=str(case.case_no), run_no=str(case.run.run_no) if case.run is not None else None, task_no=str(task.task_no), - before_json={'line_keys': keys}, - after_json={ + before={'line_keys': keys}, + after={ 'wave_no': wave_no, 'accepted_line_keys': accepted, 'skipped_line_keys': skipped, @@ -354,10 +430,11 @@ def create_post_ot_fulfillment_wave( result = { 'case_no': case.case_no, - 'task_no': task.task_no, - 'task_id': int(task.id), + 'task_no': notice.task_no if notice is not None else task.task_no, + 'task_id': int(notice.id) if notice is not None else int(task.id), 'review_case_id': int(case.id), 'wave_no': wave_no, + 'notice_no': notice.task_no if notice is not None else None, 'accepted_line_keys': accepted, 'skipped_line_keys': skipped, 'decision_source': source, @@ -371,8 +448,8 @@ def create_post_ot_fulfillment_wave( idem_row = ShippingOrderReviewWaveIdempotency( idempotency_key=persist_key, review_case_id=int(case.id), - task_id=int(task.id), - task_no=str(task.task_no), + task_id=int(notice.id) if notice is not None else int(task.id), + task_no=str(notice.task_no if notice is not None else task.task_no), wave_no=wave_no, decision_source=source, line_keys_json=_stable_line_keys(keys), @@ -396,7 +473,10 @@ def create_post_ot_fulfillment_wave( def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: """ - 列出可自动/人工完整履约的行(ready+matched+非短缺+未关闭+未终态)。 + 列出可自动/人工履约的行(ready+matched+未关闭+未终态)。 + + 核心逻辑:库存充足行可直接入 wave;库存不足行只有在已留下 + ``release_inventory_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。 Args: case: 复核 Case。 @@ -415,7 +495,8 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: continue if str(item.get('match_result') or '') != 'matched': continue - if item.get('is_shortage'): + decision_code = str((item.get('decision') or {}).get('decision_code') or '') + if item.get('is_shortage') and decision_code != 'release_inventory_shortage': continue if item.get('user_line_status') == 'auto_fulfill_failed': continue @@ -423,7 +504,10 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: continue req = _parse_qty(item.get('required_qty')) avail = _parse_qty(item.get('available_qty')) - if req is None or avail is None or avail < req: + is_released_shortage = decision_code == 'release_inventory_shortage' + if req is None or (avail is None and not is_released_shortage) or ( + avail is not None and avail < req and not is_released_shortage + ): continue out.append(str(item.get('line_key') or '')) return [k for k in out if k] diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index 951fdb08..f91842f8 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -1164,10 +1164,8 @@ def sync_fulfillment_gates_from_task( idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}:{shortage_reason or "ok"}', force=True, ) - if not sufficiency_ok: - return - - # [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离 + # [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离。 + # 库存不足仍停在 Gate 16,但滚动履约可为已满足/已审计放行行生成下一份 Excel。 excel_error = excel_gate_error(task) excel_ready = excel_error is None apply_gate_outcome( diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 67577492..7826e66b 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -316,7 +316,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'gate_code': 'freight_upload_rpa', 'sequence_no': 19, 'label': '货代上传 RPA', - 'ui_placement': {'target_surface': 'upload_complete', 'target_anchor': 'freight_upload'}, + 'ui_placement': {'target_surface': 'freight_upload', 'target_anchor': 'freight_upload'}, 'responsible_party': 'worker', 'implementation_status': 'implemented', 'recoverable': True, @@ -330,7 +330,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'gate_code': 'manual_upload_handoff', 'sequence_no': 20, 'label': '人工上传交接', - 'ui_placement': {'target_surface': 'upload_complete', 'target_anchor': 'manual_upload'}, + 'ui_placement': {'target_surface': 'freight_upload', 'target_anchor': 'manual_upload'}, 'responsible_party': 'owner', 'implementation_status': 'implemented', 'recoverable': True, @@ -366,6 +366,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'recheck_freeze_readiness', 'retry_task_creation', 'retry_inventory_preparation', + 'reload_inventory_result', 'poll_inventory_preparation', 'retry_inventory_field_mapping', 'retry_inventory_matching', @@ -380,7 +381,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'poll_freight_upload_rpa', 'retry_freight_upload_rpa', 'regenerate_manual_upload_todo', - # 仅驱动前端打开人工上传凭据登记;不得通过普通 Gate POST 直接确认。 + # 仅驱动前端打开人工上传确认;不得通过普通 Gate POST 直接确认。 'mark_manual_uploaded', }) @@ -419,9 +420,9 @@ for _code, _ui_handler in { 'open_shortage_review': {'ui_handler': 'shortage_review'}, }.items(): PROCESS_GATE_ACTION_PRESENTATION[_code].update(_ui_handler) -# 人工上传凭据登记由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。 +# 人工上传确认由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。 PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['dispatch'] = 'dialog' -PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_evidence' +PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_confirmation' for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}: PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery' for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}: @@ -468,11 +469,17 @@ def is_business_user_action(action_code: str | None) -> bool: return bool(code) and code in PROCESS_GATE_BUSINESS_USER_ACTION_CODES -def inventory_preparation_primary_action(status: str | None) -> str | None: +def inventory_preparation_primary_action( + status: str | None, + blocking_reason_code: str | None = None, +) -> str | None: """裁决库存准备 Gate 面向业务用户的主动作。""" normalized_status = str(status or '').strip().lower() + normalized_reason = str(blocking_reason_code or '').strip().lower() if normalized_status == 'waiting_external': return 'poll_inventory_preparation' + if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}: + return 'reload_inventory_result' if normalized_status in {'blocked_manual', 'blocked_retryable'}: return 'retry_inventory_preparation' return None @@ -706,7 +713,7 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = { 'upload_rpa_failed': 'freight_upload_rpa', 'upload_rpa_login_failed': 'freight_upload_rpa', 'upload_platform_rejected': 'freight_upload_rpa', - 'upload_result_unknown': 'manual_upload_handoff', + 'upload_result_unknown': 'freight_upload_rpa', } # Candidate Qualification / 旧自动建单门禁键 → 唯一 owning_gate(禁止平行用户投影)。 @@ -817,6 +824,8 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool: return True if action == 'retry_inventory_matching' and code == 'inventory_sufficiency': return True + if action == 'reload_inventory_result' and code == 'inventory_preparation': + return True navigation_owners = { 'open_order_review': {'order_freeze_readiness', 'order_field_extraction'}, 'open_profile_review': {'document_profile_routing'}, diff --git a/backend/app/services/shipping_notice/process_gate_dependency.py b/backend/app/services/shipping_notice/process_gate_dependency.py index 6ad2744c..283dc814 100644 --- a/backend/app/services/shipping_notice/process_gate_dependency.py +++ b/backend/app/services/shipping_notice/process_gate_dependency.py @@ -158,7 +158,8 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = { 'inventory_field_mapping': ('inventory_preparation',), 'inventory_matching': ('inventory_field_mapping',), 'inventory_sufficiency': ('inventory_matching',), - 'excel_readiness': ('inventory_sufficiency',), + # 滚动导出仅要求已完成库存匹配;库存不足仍由 inventory_sufficiency 独立阻断未导出行。 + 'excel_readiness': ('inventory_matching',), 'artifact_generation': ('excel_readiness',), 'freight_upload_rpa': ('artifact_generation',), 'manual_upload_handoff': ('freight_upload_rpa',), diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index 95239e0b..5adb1c89 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -181,6 +181,7 @@ def _dispatch_action( 'retry_duplicate_detection': _handle_recheck_task_gates, 'retry_task_creation': _handle_retry_task_creation, 'retry_inventory_preparation': _handle_retry_inventory_preparation, + 'reload_inventory_result': _handle_reload_inventory_result, 'poll_inventory_preparation': _handle_retry_inventory_preparation, 'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping, 'retry_inventory_matching': _handle_retry_inventory_matching, @@ -860,6 +861,58 @@ def _handle_retry_inventory_preparation( return outcome +def _handle_reload_inventory_result( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """ + 重读已产生的库存快照,不重新触发库存 RPA。 + + 核心逻辑:仅复用既有快照查询、身份校验、挂接和库存加载;未命中时保留当前 + RPA 超时阻断,让用户明确选择“重新获取库存”或上传库存文件。 + """ + from app.models import ShippingNotice + from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot + from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + from app.services.shipping_notice.process_gate_bridge import ( + inventory_preparation_reason_code, + sync_fulfillment_gates_from_task, + ) + + task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + if task is None: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'inventory_preparation_failed', + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False}, + } + response = _try_reuse_inventory_snapshot( + task, + task_rpa_inventory_source(task) or {}, + mode='reload_result', + ) + if response is None: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': inventory_preparation_reason_code(task), + 'effective_result_json': {'findings': [], 'snapshot_found': False}, + 'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False}, + } + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=payload.get('actor_user_id'), + ) + return _tool_outcome( + action_code='reload_inventory_result', + response=response, + blocking_reason_code=inventory_preparation_reason_code(task), + ) + + def _handle_retry_inventory_field_mapping( *, execution: ShippingProcessExecution, @@ -1130,42 +1183,35 @@ def _handle_regenerate_excel( gate: ShippingProcessGate, payload: dict[str, Any], ) -> dict[str, Any]: - """重新生成 Excel Artifact;上传 Gate 的跨阶段恢复先精确作废旧产物。""" + """仅在尚未生成 Excel 时重试首次生成,已有 Artifact 时拒绝重生。""" + from app.models import ShippingExportArtifact, ShippingNotice from app.services.shipping_notice.fulfillment_workflow import generate_excel from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action - recovery_definition = recovery_plan_for_action( - current_gate=gate.gate_code, - action_code='regenerate_excel_artifact', + task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + existing = ( + ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first() + if task is not None and task.id is not None else None ) - invalidation = None - if recovery_definition is not None: - from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only - - invalidation = invalidate_excel_regeneration_only( - execution=execution, - attempt_id=payload.get('attempt_id'), - actor_id=payload.get('actor_user_id'), - ) + if existing is not None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'notice_excel_already_generated', + 'blocking_reason_json': {'message': '同一发货通知单只能生成一个 Excel;请创建新的发货通知单'}, + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'regenerate_excel_artifact', 'rejected': True}, + } response = generate_excel(_task_payload(execution, payload)) outcome = _tool_outcome( action_code='regenerate_excel_artifact', response=response, blocking_reason_code='artifact_generation_failed', ) - if invalidation is not None: - outcome['output_snapshot']['invalidation'] = invalidation - sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) - if recovery_definition is not None and gate.gate_code == 'manual_upload_handoff' and outcome['outcome'] == 'passed': - # Gate 20 是恢复动作的授权载体,不是 Excel 生成的业务终点。新 Artifact - # 生成后仍须回到人工上传交接;否则 complete_gate_attempt 会把 Gate 20 误写为 passed。 - outcome.update({ - 'outcome': 'blocked_manual', - 'blocking_reason_code': 'manual_upload_pending', - 'blocking_reason_json': {'message': '新的发货 Excel 已生成,请登记人工上传凭据'}, - 'effective_result_json': {'findings': [], 'regenerated': True}, - }) + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=payload.get('actor_user_id'), + ) return outcome diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 1762d599..673cbf70 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -77,20 +77,15 @@ def _projection_primary_next_action(*, gate_code: str, status: str) -> str | Non return str(value) if value else None -# 库存 RPA / 准备失败原因:统一由业务用户触发「重新获取库存」(retry_inventory_preparation)。 -# 与 error_explainability_contract.EXPLAINABILITY_REASON_META 中 inventory_file_empty 等 -# 的 prescribed action 保持一致;这些原因在 process_gate_contract 中分类为 retryable_tech, -# 但因 inventory_preparation 的 responsible_party='worker',历史投影会按「worker/retry_ 技术 -# 动作屏蔽」规则将其从业务按钮隐藏,导致用户只能看到被降级的人工上传入口。 +# 库存准备失败由业务用户显式处理;RPA 超时/耗尽优先重读已落盘结果,其他失败才重试 RPA。 def _resolve_recovery_next_action( *, blocking: dict[str, Any] | None, full: dict[str, Any], execution: Any, ) -> tuple[str | None, bool]: """ 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 - [STEP 1] 库存 RPA 失败(inventory_preparation Gate + retryable_tech 原因码)统一下发 - ``retry_inventory_preparation``(重新获取库存),绕过历史「worker/retry_ 技术动作屏蔽」 - 分支,使业务用户在库存 RPA 失败时可直接重试,而非被降级为人工上传入口。 + [STEP 1] 库存 RPA 超时/耗尽先下发 ``reload_inventory_result``,只重读已有结果; + 其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。 [STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。 [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留 RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。 @@ -102,9 +97,9 @@ def _resolve_recovery_next_action( status = str((blocking or {}).get('status') or '').strip().lower() has_formal_task = bool(execution and getattr(execution, 'task_id', None)) - # [STEP 1] 库存准备失败统一允许业务用户手动重新获取库存;人工上传是辅助输入入口。 + # [STEP 1] RPA 超时/耗尽时先重读已有结果,其他库存准备失败仍允许重新运行 RPA。 if blocking_gate_code == 'inventory_preparation': - inventory_action = inventory_preparation_primary_action(status) + inventory_action = inventory_preparation_primary_action(status, normalized_reason) if inventory_action: return inventory_action, False @@ -234,26 +229,30 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo gate: 门禁行。 include_diagnostics: False 时仅保留用户可见 blocking Finding。 """ - legacy_readonly = str(gate.gate_code or '').strip() not in PROCESS_GATE_CODE_SET - definition = ( - {'label': '历史 AutoProgress 记录', 'responsible_party': 'system', 'recoverable': False} - if legacy_readonly else _projection_gate_definition(gate.gate_code) - ) + definition = _projection_gate_definition(gate.gate_code) latest = None if gate.latest_attempt_id: - latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id)) + from app import db + + cache = db.session.info.get('shipping_conversation_projection_read_cache') + latest = ( + cache.get('latest_attempt_by_id', {}).get(int(gate.latest_attempt_id)) + if isinstance(cache, dict) else None + ) + if latest is None: + latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id)) findings = _findings_from_gate(gate) if not include_diagnostics: findings = [ item for item in findings if item.get('severity') == 'blocking' and item.get('user_visible', True) ] - allowed_actions = [str(gate.next_action_code)] if not legacy_readonly and ( + allowed_actions = [str(gate.next_action_code)] if ( gate.next_action_code and is_business_user_action(str(gate.next_action_code)) ) else [] # 将 RecoveryPlan 目标绑定到当前 Gate 对象,避免 Case/UI 包装层只透传主动作时丢失恢复按钮。 from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS - recovery_targets = [] if legacy_readonly else [ + recovery_targets = [ { 'action_code': action_code, 'target_gate': plan.get('target_gate'), @@ -266,7 +265,6 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo ] return { 'gate_code': gate.gate_code, - 'legacy_readonly': legacy_readonly, 'sequence_no': int(gate.sequence_no), 'label': definition.get('label'), 'implementation_status': definition.get('implementation_status'), @@ -316,23 +314,31 @@ def serialize_process_execution( Returns: 含当前门禁、主动作与全部门禁轨道的字典。 """ + from app import db + + cache = db.session.info.get('shipping_conversation_projection_read_cache') gates = ( - ShippingProcessGate.query - .filter_by(execution_id=int(execution.id)) - .order_by(ShippingProcessGate.sequence_no.asc()) - .all() + cache.get('gates_by_execution_id', {}).get(int(execution.id), []) + if isinstance(cache, dict) else [] ) + if not gates: + gates = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id)) + .order_by(ShippingProcessGate.sequence_no.asc()) + .all() + ) serialized = [ serialize_process_gate(gate, include_diagnostics=include_diagnostics) for gate in gates + if str(gate.gate_code or '').strip() in PROCESS_GATE_CODE_SET ] current = next( (item for item in serialized if item.get('gate_code') == execution.current_gate_code), None, ) - legacy_readonly = any(item.get('legacy_readonly') for item in serialized) recovery_targets: list[dict[str, Any]] = [] - if execution.current_gate_code and not legacy_readonly: + if execution.current_gate_code in PROCESS_GATE_CODE_SET: # RecoveryPlan 合同是服务端唯一动作来源;Projection 只读输出,客户端不能改写 target Gate。 from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS @@ -345,14 +351,18 @@ def serialize_process_execution( 'invalidates': list(definition.get('invalidates') or ()), 'permission': definition.get('permission'), }) - active_recovery_plans = ShippingProcessRecoveryPlan.query.filter( - ShippingProcessRecoveryPlan.execution_id == int(execution.id), - ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}), - ).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all() + active_recovery_plans = ( + cache.get('active_recovery_plans_by_execution_id', {}).get(int(execution.id), []) + if isinstance(cache, dict) else None + ) + if active_recovery_plans is None: + active_recovery_plans = ShippingProcessRecoveryPlan.query.filter( + ShippingProcessRecoveryPlan.execution_id == int(execution.id), + ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}), + ).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all() return { 'execution_no': execution.execution_no, - 'status': 'legacy_readonly' if legacy_readonly else execution.status, - 'legacy_readonly': legacy_readonly, + 'status': execution.status, 'current_gate_code': execution.current_gate_code, 'last_passed_gate_code': execution.last_passed_gate_code, 'primary_next_action_code': execution.primary_next_action_code, @@ -497,45 +507,6 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, current_blocking_gate、reason、next_action、diagnostic_hint、technical_auto_only。 """ full = serialize_process_execution(execution, include_diagnostics=False) - # 完成态的正式 Execution 会清空 current_gate_code;空值表示没有待处理 Gate, - # 不能被误判为已下线的 APX 历史执行。只有存在实际 Gate 编号且不在正式契约内时, - # 才进入 legacy_readonly 兼容投影。 - current_gate_code = str(getattr(execution, 'current_gate_code', '') or '').strip() - legacy_readonly = bool(full.get('legacy_readonly')) or ( - bool(current_gate_code) and current_gate_code not in PROCESS_GATE_CODE_SET - ) - if legacy_readonly: - refs = _execution_navigation_refs(execution) - return { - 'execution_no': full.get('execution_no'), - 'status': 'legacy_readonly', - 'legacy_readonly': True, - 'execution_status': None, - 'current_gate': full.get('current_gate'), - 'current_blocking_gate': None, - 'recovery_targets': [], - 'active_recovery_plans': [], - 'blocking_reason_code': 'shipping_apx_runtime_disabled', - 'blocking_message': '历史自动推进记录仅供审计查看', - 'failure_detail': None, - 'explainability': None, - 'next_action_code': None, - 'primary_action': None, - 'allowed_actions': [], - 'action_presentation': [], - 'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}], - 'technical_auto_only': True, - 'owner_type': 'system', - 'responsible_party': 'system', - 'diagnostic_hint': None, - **refs, - 'navigation': None, - 'gates_track': [ - {'gate_code': item.get('gate_code'), 'label': item.get('label'), - 'status': item.get('status'), 'sequence_no': item.get('sequence_no')} - for item in (full.get('gates') or []) - ], - } current = full.get('current_gate') blocking = None if ( @@ -577,7 +548,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, break reason_code = (blocking or {}).get('blocking_reason_code') # [STEP] 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 - # 库存 RPA 失败统一下发「重新获取库存」,不再因 worker 责任方被技术动作屏蔽。 + # 库存 RPA 超时/耗尽优先下发「重新读取库存结果」,不触发新的 RPA 请求。 next_action, technical_auto_only = _resolve_recovery_next_action( blocking=blocking, full=full, @@ -610,20 +581,23 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, target for target in recovery_targets if str(target.get('action_code') or '').strip() == 'retry_inventory_preparation' ] - # [AUTHORITY] 上传阶段的 Excel 重生仅在旧 Artifact 仍是未上传 ready 状态时授权; - # 已有成功/未知外部结果或活动 RecoveryPlan 时,后端不下发按钮。 - if any(str(target.get('action_code') or '').strip() == 'regenerate_excel_artifact' for target in recovery_targets): - if not _excel_regeneration_allowed( - execution=execution, - active_recovery_plans=list(full.get('active_recovery_plans') or []), - ): - recovery_targets = [ - target for target in recovery_targets - if str(target.get('action_code') or '').strip() != 'regenerate_excel_artifact' - ] + # 一个 Notice 只能有一个 Excel;错误导出需要创建新的 Notice,而非替代旧 Artifact。 + recovery_targets = [ + target for target in recovery_targets + if str(target.get('action_code') or '').strip() != 'regenerate_excel_artifact' + ] if blocking: if next_action and is_business_user_action(str(next_action)): allowed_actions.append(str(next_action)) + # 超时或耗尽后默认重读已有结果;保留显式 RPA 重试作为备用操作, + # 让用户在确实没有迟到结果时自行决定是否发起新一轮抓取。 + if ( + str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation' + and str(reason_code or '').strip().lower() + in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'} + and 'retry_inventory_preparation' not in allowed_actions + ): + allowed_actions.append('retry_inventory_preparation') # Gate 20 的人工凭据登记是主动作;货代 RPA 仍允许由用户显式重试。 # 该可选动作来自 Gate 契约,不能由前端根据自动上传开关自行补出。 if ( diff --git a/backend/app/services/shipping_notice/process_gate_recovery_service.py b/backend/app/services/shipping_notice/process_gate_recovery_service.py index ae95fb2b..56a7674b 100644 --- a/backend/app/services/shipping_notice/process_gate_recovery_service.py +++ b/backend/app/services/shipping_notice/process_gate_recovery_service.py @@ -114,7 +114,7 @@ def _primary_recovery_action( ) -> str | None: """按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。""" if gate.gate_code == 'inventory_preparation': - return inventory_preparation_primary_action(gate.status) + return inventory_preparation_primary_action(gate.status, gate.blocking_reason_code) # 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。 if gate.gate_code == 'inventory_matching' and execution.task_id: return 'retry_inventory_matching' @@ -236,11 +236,11 @@ def request_gate_action( details={'action_code': action}, ) - # Gate 20 的确认必须走 mark-manual-uploaded:该 API 强制校验截图/PDF 凭据与货代回执号。 - # 禁止复用普通 Gate POST,避免调用方绕过人工上传证据门槛。 + # Gate 20 的确认必须走 Notice 上传确认 API:该 API 按 business_no 与唯一 Artifact + # 校验当前履约事实,禁止普通 Gate POST 绕过该边界。 if action == 'mark_manual_uploaded': raise ValidationError( - 'Manual upload confirmation requires evidence registration', + 'Manual upload confirmation must use the shipping notice endpoint', code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', details={'action_code': action, 'gate_code': gate.gate_code}, ) diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index 13c33896..a593bf99 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -305,15 +305,13 @@ def ensure_execution_for_workflow_version( .order_by(ShippingProcessExecution.id.desc()) .first() ) - # APX 六 Gate 与正式 20-Gate 不能共用同一 Execution。历史数据可能仍按 - # task_id 被查到;此时必须新建正式链,禁止把 20-Gate 行写进 APX sequence。 if existing is not None: existing_codes = { str(row.gate_code or '').strip() for row in ShippingProcessGate.query.filter_by(execution_id=int(existing.id)).all() } if existing_codes and not existing_codes.issubset(PROCESS_GATE_CODE_SET): - existing = None + raise RuntimeError('shipping_process_execution_contract_invalid') if existing is not None: if review_case_id and existing.review_case_id is None: existing.review_case_id = int(review_case_id) diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index ca366a70..2116c5b2 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -45,7 +45,6 @@ _WRITE_ACTION_CODES = frozenset({ 'open_shortage_review', 'upload_inventory_file', 'retry_inventory_preparation', - 'retry', 'retry_parse', 'retry_failed_documents', 'regenerate_excel', @@ -79,8 +78,10 @@ _POST_CREATE_STAGES = frozenset({ _ACTION_CODE_ALIASES: dict[str, str] = { 'open_review': 'open_order_review', 'open_order_processing': 'open_order_review', - 'retry_parse': 'retry', - 'retry_failed_documents': 'retry', + # 解析恢复保留其对象边界;不得再塌缩成泛化 retry,否则前端无法判定 + # 应重投 Intake、重跑 Run,还是提交当前 Gate。 + 'retry_parse': 'retry_parse', + 'retry_failed_documents': 'retry_failed_documents', 'open_fulfillment': 'view_result', 'view_details': 'view_result', 'wait_manual_upload': 'open_manual_upload', @@ -90,6 +91,7 @@ _ACTION_CODE_ALIASES: dict[str, str] = { 'rematch': 'open_inventory_match_review', 'match_inventory': 'open_inventory_match_review', 'generate_excel': 'regenerate_excel', + 'confirm_inventory_source': 'open_inventory_source_review', # 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由 # Gate API 使用原始 action_code 校验,legacy projection 只负责展示语义。 'regenerate_excel_artifact': 'regenerate_excel', @@ -97,13 +99,27 @@ _ACTION_CODE_ALIASES: dict[str, str] = { 'reparse_batch': 'reparse_batch', } +# 具有独立对象边界的动作。它们不是泛化 retry,必须保留原始码,避免丢失 +# 重解析、草稿裁决等业务能力。 +_OBJECT_EXECUTABLE_ACTION_CODES = frozenset({ + 'retry_parse', + 'retry_failed_documents', + 'retry_failed_attachments', + 'reparse', + 'reparse_batch', + 'create_draft', + 'edit_draft', + 'reconcile_and_progress', +}) +# Retry Decision 是旧任务恢复协调器的内部语义。投影只把可确定的决策翻译成 +# 已注册的精确 Gate 动作;绝不再下发字面量 retry。 def normalize_action_code(code: str | None) -> str | None: """ - 将原始动作码规范为 SHIPPING_PROCESSING_ACTION_INTENTS 可识别的契约码。 + 将原始动作码规范为正式 Gate 或具备独立对象边界的业务动作码。 Args: - code: Gate / legacy available_actions 原始码。 + code: Gate 或独立业务动作原始码。 Returns: 契约动作码;无法映射时返回 None(禁止泄漏未知码)。 @@ -112,6 +128,16 @@ def normalize_action_code(code: str | None) -> str | None: if not raw: return None mapped = _ACTION_CODE_ALIASES.get(raw, raw) + # 字面量 retry 没有对象/阶段边界,禁止从历史 payload 重新授权为 UI 动作。 + if mapped == 'retry': + return None + if mapped in _OBJECT_EXECUTABLE_ACTION_CODES: + return mapped + # Gate 合同是正式动作码全集;这里仅作契约校验,不改变原始动作码。 + from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_ACTION_CODES + + if mapped in PROCESS_GATE_ACTION_CODES: + return mapped if mapped in SHIPPING_PROCESSING_ACTION_INTENTS and mapped != 'none': return mapped return None @@ -167,7 +193,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: 【触发时机】写状态机回写 OT、投影组装 order_task 工作项。 - 核心逻辑:上传完成 → completed;上传中/待上传 → freight_uploading; + 核心逻辑:仅可审计的上传成功 → completed;上传中、待登记及历史无证据上传 + → freight_uploading; 导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching; matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。 领域映射唯一来源,禁止写状态机反向依赖投影私有函数。 @@ -185,8 +212,16 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: review = str(getattr(notice, 'review_status', None) or '').strip().lower() match = str(getattr(notice, 'match_status', None) or '').strip().lower() lifecycle = str(getattr(notice, 'lifecycle_status', None) or '').strip().lower() - if upload_st in {'uploaded', 'succeeded', 'success'} or lifecycle in {'archived', 'deleted'}: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + verified_upload_success = has_verified_upload_success(notice) + if lifecycle in {'voided', 'archived', 'deleted'}: + return ('cancelled', 'cancelled') + if verified_upload_success: ps = 'uploaded' + elif upload_st in {'uploaded', 'succeeded', 'success'}: + # 历史聚合字段或单一回执不构成业务完成。保留在上传工作面,等待核对。 + ps = 'waiting_upload' elif upload_st in {'uploading', 'pending', 'failed'} or pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}: ps = 'waiting_upload' if upload_st != 'failed' else 'upload_failed' elif export_path: @@ -356,23 +391,24 @@ def derive_available_actions( status: str, stage: str, gate: dict[str, Any] | None, - legacy_actions: list[str] | None = None, + authorized_actions: list[str] | None = None, excel_ready: bool = False, shipping_notice_no: str | None = None, ) -> list[str]: """ - 由 Gate / Artifact 等业务事实推导 available_actions,禁止仅凭 stage 猜测可下载。 + 由持久化 Gate / Artifact 等业务事实推导 available_actions,禁止仅凭 stage + 或未落库的 Gate 片段猜测可操作入口。 核心逻辑:Gate next_action 优先;download_excel 仅当 excel_ready; regenerate_excel 仅当处于 excel_generating 且非 automating 且 Excel 未就绪; - open_manual_upload 仅当 Gate 或 legacy 明确给出;completed → view_result; + open_manual_upload 仅当 Gate 或已授权动作明确给出;completed → view_result; 建单前剔除匹配/Excel/上传等履约动作(fail-closed)。 Args: status: 统一 status。 stage: 统一 stage。 - gate: current_gate 摘要。 - legacy_actions: 可选旧会话卡动作,仅保留可映射项。 + gate: current_gate 摘要;仅正式 Process Gate code 可授权动作。 + authorized_actions: 调用方已裁决的精确对象动作,不能由状态推断。 excel_ready: 是否存在 ready 的发货 Excel Artifact。 shipping_notice_no: 正式 Notice 任务号;空表示建单前。 @@ -384,7 +420,14 @@ def derive_available_actions( post_create = _is_post_create(stage=stage_norm, shipping_notice_no=shipping_notice_no) actions: list[str] = [] seen: set[str] = set() - gate_action = _gate_next_action(gate) + # current_gate 可能来自旧 Case/任务快照。只有 process_gate_contract 注册的 + # 正式 Gate 才能授权动作;历史码即使携带 next_action_code 也必须 fail-closed。 + gate_code = str( + (gate or {}).get('gate_code') or (gate or {}).get('gateCode') or '' + ).strip().lower() if isinstance(gate, dict) else '' + from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET + gate_declared = gate_code in PROCESS_GATE_CODE_SET + gate_action = _gate_next_action(gate) if gate_declared else None def _push(raw: str | None) -> None: code = normalize_action_code(raw) @@ -403,13 +446,8 @@ def derive_available_actions( _push(gate_action) - # [BE-04] 仅技术失败允许默认 retry;业务 blocked 只保留 Gate next_action。 - if status_norm == 'failed' and 'retry' not in seen: - _push('retry') - elif status_norm == 'blocked' and gate_action in { - 'retry', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments', - }: - _push('retry') + # 技术失败只能由当前 Gate 或 Retry Decision 下发精确恢复动作。禁止在 + # available_actions 注入字面量 retry,避免跨阶段错误重跑抽取。 if status_norm == 'completed': _push('view_result') elif ( @@ -425,13 +463,14 @@ def derive_available_actions( if excel_ready: _push('download_excel') - for item in legacy_actions or []: - mapped = normalize_action_code(item) - # [BE-07] legacy 只补充只读类动作,禁止用旧卡覆盖 Gate 写意图。 - if mapped in {'view_result', 'view_record', 'refresh', 'download_excel'}: - _push(mapped) - elif mapped == 'open_manual_upload': - _push(mapped) + for item in authorized_actions or []: + code = normalize_action_code(item) + # Gate 片段已声明当前节点时,它是唯一写动作裁决者。调用方携带的对象级 + # 授权只可补足完全无 Gate 的解析处置;即使 Gate 尚未证明已持久化,也不得 + # 用历史动作绕过它并把 match_inventory 等带入 Excel/上传节点。 + if gate_declared and code not in {'view_result', 'view_record', 'refresh', 'download_excel'}: + continue + _push(code) if not actions: actions = ['view_result'] if status_norm in {'completed', 'failed', 'cancelled'} else [] @@ -441,9 +480,10 @@ def derive_available_actions( def reconcile_processing_projection_facts( payload: dict[str, Any], *, - legacy_actions: list[str] | None = None, + authorized_actions: list[str] | None = None, invalidated_from_stage: str | None = None, excel_ready: bool = False, + verified_upload_success: bool | None = None, ) -> dict[str, Any]: """ 在投影输出前强制 status/stage/gate/action 不变量,并写入 stage_nodes。 @@ -457,7 +497,7 @@ def reconcile_processing_projection_facts( Args: payload: 即将返回的 ShippingProcessingProjection dict(snake_case)。 - legacy_actions: 可选旧动作列表。 + authorized_actions: 调用方已裁决的精确对象动作。 invalidated_from_stage: 可选失效起点 stage。 excel_ready: 是否存在 ready Excel Artifact。 @@ -518,6 +558,17 @@ def reconcile_processing_projection_facts( status = 'automating' stage_idx = shipping_processing_stage_index(stage) + # 完成由上传成功谓词单独裁决。正式 OT 的历史 completed/uploaded 不能因为 + # 旧字段、归档或技术流程结束而越过人工核对;取消态不在此规则内改写。 + if verified_upload_success is True: + status = 'completed' + stage = 'completed' + gate = None + gate_action = None + elif verified_upload_success is False and status == 'completed': + status = 'waiting_human' + stage = 'freight_uploading' + # [BE-03] Extraction Run 完成误标为全流程 completed:早期 stage 时回退 status。 if status == 'completed' and stage and stage != 'completed': if stage_idx is not None and stage_idx <= waiting_idx: @@ -570,7 +621,7 @@ def reconcile_processing_projection_facts( status=status, stage=stage, gate=gate, - legacy_actions=legacy_actions if legacy_actions is not None else list( + authorized_actions=authorized_actions if authorized_actions is not None else list( payload.get('available_actions') or [] ), excel_ready=excel_ready, @@ -628,10 +679,10 @@ def apply_user_projection_fields( 【AI 触发时机】:任何需要向前端返回 OrderTask/Conversation 投影的末端出口, 在 reconcile_processing_projection_facts 之后、record_projection_inconsistency 之后调用。 - 核心逻辑(决策 F3:新增字段不替换旧枚举,Retry Decision 优先 + legacy 兜底): - [STEP 1] 保存旧枚举到 legacy_status / legacy_stage / legacy_current_gate,避免旧前端 break。 + 核心逻辑:以正式 Process Gate 与领域事实生成唯一用户态 DTO。 + [STEP 1] 读取当前投影 status / stage / current_gate 作为计算输入,不输出兼容镜像。 [STEP 2] 读取 pending_reason / review_status / inventory_source_status 原始字段。 - [STEP 3] 计算 Retry Decision(仅 notice 存在时,失败/不存在则 legacy 兜底)。 + [STEP 3] 按正式 Gate 与领域终态裁决用户状态。 [STEP 4] 按冻结优先级计算 user_status(completed/cancelled/failed → retryable → waiting_human → running)。 [STEP 5] 仅在投影内部计算可重试语义,用于生成唯一 primary_action;不再输出旧 retryable 布尔字段。 [STEP 6] 计算 blocking_reason:{code, i18n_key, details} 或 None。 @@ -644,7 +695,7 @@ def apply_user_projection_fields( order_task: 可选 ShippingOrderTask 实体(用于 facts 与 legacy pending_reason)。 Returns: - 就地修改后的 payload(含新增 6 字段与 3 个 legacy_* 备份)。 + 就地修改后的 payload(含用户态字段;不保留旧字段备份)。 """ from app.services.shipping_notice.constants import ( RS_SHORTAGE_REVIEW as REVIEW_STATUS_SHORTAGE_REVIEW, @@ -656,10 +707,7 @@ def apply_user_projection_fields( _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') + # ===== [STEP 1] 读取当前投影输入 ===== old_status = str(payload.get('status') or '').strip().lower() old_stage = str(payload.get('stage') or '').strip().lower() source_type = str(payload.get('source_type') or '').strip().lower() or None @@ -699,49 +747,31 @@ def apply_user_projection_fields( 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 优先级) ===== + # ===== [STEP 3] 按正式 Gate 与领域终态计算 user_status ===== notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else '' - _rd_has_completed_process = notice_upload_status in {'uploaded', 'succeeded', 'success'} + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + # 读取路径也必须遵守三层上传成功事实;否则 retry 决策或旧 status=completed + # 会在这一步将前序 reconcile 的货代上传态重新提升为完成。 + verified_upload_success = bool(notice is not None and has_verified_upload_success(notice)) + unverified_upload_terminal = bool( + notice is not None + and not verified_upload_success + and ( + old_status == 'completed' + or old_stage == 'completed' + or notice_upload_status in {'uploaded', 'succeeded', 'success'} + ) + ) def _compute_user_status() -> str: - # [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision - # 只描述任务调度,不能覆盖正式 Gate 已到达的 Excel/上传阻断。 + # 当前 Gate 是唯一可执行状态源,不能由旧 Retry Decision 覆盖。 gate_status = str((old_gate or {}).get('status') or '').strip().lower() if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}: return 'retryable' if gate_status == 'blocked_manual': return 'waiting_human' + if unverified_upload_terminal: + return 'waiting_human' # 1) 终态短路:old_status completed/cancelled/failed if old_status == 'completed': return 'completed' @@ -749,20 +779,7 @@ def apply_user_projection_fields( 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 { @@ -771,16 +788,19 @@ def apply_user_projection_fields( _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() + if unverified_upload_terminal: + payload['status'] = 'waiting_human' + payload['stage'] = 'freight_uploading' + old_status = 'waiting_human' + old_stage = 'freight_uploading' + # ===== [不变] user_stage 计算(保持不动) ===== user_stage = _USER_STAGE_TO_CODE.get(old_stage) if user_stage is None: @@ -808,8 +828,6 @@ def apply_user_projection_fields( return False if user_status == 'retryable': return True - if user_status == 'failed' and rd_retryable: - return True return False retryable = _compute_retryable() @@ -885,12 +903,6 @@ def apply_user_projection_fields( 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': {}, - } gate_reason = str((old_gate or {}).get('blocking_reason_code') or '').strip() if gate_reason and gate_reason in _REASON_TO_I18N_KEY: return { @@ -905,12 +917,6 @@ def apply_user_projection_fields( 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': 'technical_failure_present', 'i18n_key': _REASON_TO_I18N_KEY['technical_failure_present'], @@ -918,16 +924,10 @@ def apply_user_projection_fields( } # 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}, + 'details': {'status': old_status, 'stage': old_stage}, } return None @@ -935,7 +935,6 @@ def apply_user_projection_fields( # ===== [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', 'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', 'retry_inventory_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', 'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', @@ -947,7 +946,6 @@ def apply_user_projection_fields( 'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review', } _ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = { - 'retry': 'chat.shippingProcessing.action.retry', 'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', 'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', 'open_order_review': 'chat.shippingProcessing.action.open_order_review', @@ -967,15 +965,6 @@ def apply_user_projection_fields( 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 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: # [BE-10] Gate action 是当前阶段唯一主动作来源;旧 stage 的 # match_inventory/regenerate_excel 仅作兼容回退。 @@ -983,7 +972,7 @@ def apply_user_projection_fields( gate_action_alias = { 'regenerate_excel_artifact': 'regenerate_excel', }.get(gate_action, gate_action) - if gate_action_alias in SHIPPING_PROCESSING_ACTION_INTENTS and user_status in { + if gate_action_alias and user_status in { 'retryable', 'waiting_human', 'running', }: return { @@ -994,11 +983,7 @@ def apply_user_projection_fields( # 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 分派 + # waiting_human 仅按 Gate/领域阻断映射精确业务入口。 if user_status == 'waiting_human': if bcode in {'inventory_shortage', 'inventory_multi_file_conflict', 'inventory_source_conflict'}: code = 'open_inventory_match_review' @@ -1028,27 +1013,7 @@ def apply_user_projection_fields( }: code = 'open_order_review' return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - # 1h. available_actions 含 reconcile_and_progress → 统一对账恢复入口兜底 - available_actions = payload.get('available_actions') - 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 + # Gate 未明确授权时不由阶段、状态或旧 actions 补造 CTA。 return None primary_action = _compute_primary_action() @@ -1076,7 +1041,7 @@ def apply_user_projection_fields( 'excel_readiness': 5, 'artifact_generation': 6, 'manual_upload_handoff': 7, - 'upload_receipt_recorded': 8, + 'manual_upload_handoff': 8, } current_order = gate_order.get(gate_code) facts['inventory_milestones'] = { diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index 6d23d569..93abf8c2 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -281,12 +281,16 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = ( 'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate', + 'open_inventory_source_review', 'open_inventory_match_review', 'open_shortage_review', 'upload_inventory_file', 'retry_inventory_preparation', 'retry_inventory_matching', - 'retry', + 'retry_parse', + 'retry_failed_documents', + 'retry_failed_attachments', + 'reparse', 'reparse_batch', 'refresh', 'regenerate_excel', diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index a4e483de..6dae0c38 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -254,6 +254,10 @@ def run_task_auto_progress( 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}") + # 新 Notice 以自身 customer_id 为唯一客户事实;在创建任何 Gate/Job 前 fail-closed。 + customer_gate = customer_gate_tool_response(task, operation='auto_progress') + if customer_gate is not None: + return customer_gate # P0-3:旧 facade 不再直接跨 Gate 调用库存/匹配/Excel。所有触发统一只提交 # 当前正式 Gate;Worker 在事实落库后才创建下一个 Job。 diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index f4115b59..363f91fb 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -1,14 +1,13 @@ """ services/shipping_notice/query_service.py -用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 -依赖:ShippingCase、ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、 - ShippingReservation、ShippingOrderReviewCase、ShippingOrderProcessingRun、 +用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 +依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、 + ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、 ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、 order_review_projection(任务中心 STP retry 动作投影)。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; - co8 起 shipping_batches 已删除,批次 list API 返回空、按 batch_no 查询返回 None; - tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉; + tools.py 通过 TaskProjection 委托序列化与任务解析,写路径逐步下沉; SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event, 以及统一 shipping_processing_status / progress_version / order_task_no(BE-02), 并注入 review_run_no 供任务中心深链订单处理工作台(UI-04); @@ -35,7 +34,6 @@ from app import db from app.core.errors import ValidationError from app.models import ( FileAsset, - ShippingCase, ShippingExportArtifact, ShippingExportArtifactLine, ShippingInventoryVerification, @@ -47,14 +45,16 @@ from app.models import ( ShippingOrderProcessingRunIntake, ShippingOrderLine, ShippingOrderReviewCase, + ShippingOrderSnapshot, ShippingOrderReviewStream, ShippingOrderSubmission, ShippingReservation, ShippingNotice, + ShippingNoticeLine, + ShippingNoticeLineInventoryMatch, ShippingTaskEvent, ShippingUploadAttempt, ) -from app.services.shipping_notice.batch_legacy_removed import SHIPPING_BATCHES_REMOVED_MESSAGE from app.services.shipping_notice.constants import ( CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_PARSE_REVIEW, @@ -85,6 +85,7 @@ from app.services.shipping_notice.task_order_field_editor import ( current_line_field_values_or_empty, current_order_field_display_or_empty, ) +from app.services.shipping_notice.po_number import normalize_po_number EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @@ -132,12 +133,11 @@ _REVIEW_CASE_STATUS_TODO: dict[str, str] = { } -def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[str, str]]: - """裁决建单前 Review Case 的生命周期查看入口。 +def _review_case_lifecycle_projection(case: ShippingOrderReviewCase) -> dict[str, Any]: + """复用统一生命周期投影裁决 Review Case 的当前阶段与入口。 - 只有关联当前有效订单 Candidate 的 Case 才能进入订单生命周期工作台;空 Case、 - 已替代 Candidate 与拒绝/过期 Candidate 仍是解析或处置对象,不能因待办列表存在 - 而获得订单复核、库存准备或通知完成入口。 + 当前有效 Candidate 才能进入订单复核;空、过期或被替代 Candidate 仍属于接收解析。 + 此处只组装已有事实并调用 ``project_lifecycle``,不新增状态机或前端专用阶段。 """ candidate = ( db.session.get(ShippingOrderCandidate, int(case.candidate_id)) @@ -146,11 +146,23 @@ def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[s ) from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate - if not is_current_reviewable_candidate(candidate): - return [] - from app.services.shipping_notice.lifecycle_projection import lifecycle_entries + from app.services.shipping_notice.lifecycle_projection import project_lifecycle - return lifecycle_entries(lifecycle_stage='order_review', has_candidate_context=True) + has_candidate_context = is_current_reviewable_candidate(candidate) + if has_candidate_context: + return project_lifecycle( + current_gate=None, + blocking_reason=None, + has_candidate_context=True, + processing_stage='waiting_review', + ) + return project_lifecycle( + current_gate=None, + blocking_reason=None, + has_candidate_context=False, + has_intake_parse_context=False, + processing_stage='document_parsing', + ) class TaskProjection(str, Enum): @@ -162,13 +174,6 @@ class TaskProjection(str, Enum): DETAIL = "detail" -class BatchProjection(str, Enum): - """批次读模型投影:工作台全量 / Tool 精简。""" - - SUMMARY = "summary" - TOOL = "tool" - - def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]: """为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。""" verifications = ShippingInventoryVerification.query.filter_by(task_id=task.id).order_by( @@ -219,64 +224,22 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any] } -def _task_batch_no(task: ShippingNotice) -> str | None: - """shipping_batches 已删除;任务不再挂 batch_no。""" - del task - return None - - -def task_sort_key(task: ShippingNotice) -> tuple[int, str]: - """批次内任务排序键:batch_index 优先,其次 created_at。""" - return ( - task.batch_index if task.batch_index is not None else 10**9, - task.created_at.isoformat() if task.created_at else "", - ) - - -def sort_batch_tasks(tasks: list[ShippingNotice]) -> list[ShippingNotice]: - """按 batch_index、created_at 对批次任务列表排序(返回新列表)。""" - return sorted(tasks, key=task_sort_key) - - def get_task_by_ref(task_ref: str) -> ShippingNotice | None: - """按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。""" + """按 task_no、business_no 或数字主键精确查找 Notice。""" value = str(task_ref or "").strip() if not value: return None task = ShippingNotice.query.filter_by(task_no=value).first() if task: return task - case = db.session.query(ShippingCase).filter_by(business_no=value.upper()).first() - if case is not None: - visited: set[int] = set() - while case.id not in visited: - visited.add(int(case.id)) - replacement = ( - db.session.query(ShippingCase) - .filter_by(replaces_case_id=case.id) - .order_by(ShippingCase.id.desc()) - .first() - ) - if replacement is None: - break - case = replacement - return ( - db.session.query(ShippingNotice) - .filter_by(shipping_case_id=case.id) - .order_by(ShippingNotice.document_version.desc(), ShippingNotice.id.desc()) - .first() - ) + task = ShippingNotice.query.filter_by(business_no=value.upper()).first() + if task: + return task if value.isdigit(): return db.session.get(ShippingNotice, int(value)) return None -def get_batch_by_no(batch_no: str) -> None: - """按 batch_no 查找批次;shipping_batches 已删除,固定返回 None。""" - del batch_no - return None - - def resolve_order_extraction_ui_target( *, user_id: int, @@ -286,15 +249,15 @@ def resolve_order_extraction_ui_target( """ 按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。 - 核心逻辑:先查当前用户、当前会话、指定 Intake 直接消费的新 Batch;没有新 Batch 时, - 再沿 Candidate.consumed_task_id 查找打开的既有 Task。禁止回退到“用户最近批次”,避免并发会话串单。 + 核心逻辑:沿 Candidate.consumed_task_id 查找当前用户的既有 Task。 + 禁止回退到“用户最近任务”,避免并发会话串单。 Args: user_id: 当前聊天用户 ID。 conversation_id: 当前 HXOPS ChatSession.session_id。 intake_nos: 本轮 agent_runtime_context.refs.intake_nos。 Returns: - `(batch, task)`;新建批次时 batch 非空,只有 open_existing 时 task 非空。 + `(None, task)`;`shipping_batches` 已删除,任务是唯一恢复锚点。 """ normalized = sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()}) session_id = str(conversation_id or '').strip() @@ -328,12 +291,6 @@ def resolve_order_extraction_ui_target( return None, task -def get_task_in_batch(batch_no: str, task_no: str) -> ShippingNotice | None: - """查找属于指定批次的任务;shipping_batches 已删除,固定返回 None。""" - del batch_no, task_no - return None - - def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str] | None: """解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。""" if not task or not task.export_file_path: @@ -366,102 +323,6 @@ def task_export_error_message(task: ShippingNotice | None) -> str: return "" -def list_sorted_batch_tasks(batch: Any) -> list[ShippingNotice]: - """shipping_batches 已删除;保留签名供过渡调用方,固定返回空列表。""" - del batch - return [] - - -def list_batch_task_summaries(batch: Any) -> list[dict[str, Any]]: - """shipping_batches 已删除;固定返回空列表。""" - del batch - return [] - - -def compute_batch_process_summary(tasks: list[ShippingNotice]) -> dict[str, int]: - """批次进度汇总(Tool / 工作台 / 写回 batch.process_summary_json 共用公式)。""" - total = len(tasks) - completed = sum(1 for item in tasks if _is_task_completed(item)) - failed = sum(1 for item in tasks if _is_task_failed(item)) - running = sum(1 for item in tasks if _is_task_active(item)) - pending = max(0, total - completed - failed - running - sum(1 for item in tasks if _is_task_needs_human(item))) - focus = next( - ( - item for item in sort_batch_tasks(tasks) - if not _is_task_completed(item) and not _is_task_failed(item) - ), - None, - ) - return { - "total": total, - "completed": completed, - "failed": failed, - "running": running, - "pending": pending, - "current_index": int(focus.batch_index or 0) if focus else (total if total else 0), - "current_task_no": focus.task_no if focus else None, - } - - -def _is_task_completed(task: ShippingNotice) -> bool: - """判断任务是否已进入完成态,用于会话级聚合统计。""" - upload_status = str(getattr(task, "upload_status", None) or "").strip().lower() - return upload_status in {"uploaded", "succeeded", "success"} or bool( - str(getattr(task, "freight_ref_no", None) or "").strip() - ) - - -def _is_task_failed(task: ShippingNotice) -> bool: - """判断任务是否失败或上传失败,用于会话级异常优先展示。""" - return ( - str(getattr(task, "review_status", None) or "").strip().lower() == "rejected" - or str(getattr(task, "upload_status", None) or "").strip().lower() == "failed" - ) - - -def _is_task_needs_human(task: ShippingNotice) -> bool: - """判断任务是否停在人工门;失败态不重复计入人工门。""" - if _is_task_failed(task) or _is_task_completed(task): - return False - return bool(getattr(task, "review_status", None) or getattr(task, "pending_human_reason", None)) - - -def _is_task_active(task: ShippingNotice) -> bool: - """判断任务是否仍处于自动执行或等待外部系统返回的状态。""" - if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task): - return False - lifecycle = str(getattr(task, "lifecycle_status", "active") or "active").strip().lower() - if lifecycle != "active": - return False - return bool( - getattr(task, "current_step", None) - or getattr(task, "inventory_snapshot_id", None) - or getattr(task, "export_file_path", None) - or getattr(task, "upload_status", None) - ) - - -def compute_conversation_workspace_summary(batches: list[Any]) -> dict[str, int]: - """按会话聚合多个批次的状态计数,供 Agent 会话级工作台展示。""" - tasks: list[ShippingNotice] = [] - for batch in batches: - tasks.extend(list(getattr(batch, "tasks", None) or [])) - completed = sum(1 for task in tasks if _is_task_completed(task)) - failed = sum(1 for task in tasks if _is_task_failed(task)) - needs_human = sum(1 for task in tasks if _is_task_needs_human(task)) - running = sum(1 for task in tasks if _is_task_active(task)) - pending = max(0, len(tasks) - completed - failed - needs_human - running) - return { - "batch_count": len(batches), - "total": len(tasks), - "completed": completed, - "running": running, - "failed": failed, - "needs_human": needs_human, - "pending": pending, - } - - def extract_task_no_from_text(text: str) -> str | None: """从自然语言文本中提取 SN 技术号或客户业务号。""" raw = str(text or "") @@ -521,9 +382,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: header = current_header_field_values_or_empty(task) payload: dict[str, Any] = { "task_no": task.task_no, - "shipping_case_id": task.shipping_case_id, - "case_no": task.shipping_case.case_no if task.shipping_case else None, - "business_no": task.shipping_case.business_no if task.shipping_case else None, + "business_no": task.business_no, "current_step": task.current_step, "review_status": task.review_status, "match_status": task.match_status, @@ -532,9 +391,9 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: "customer_code": header.get('customer_code'), "customer_resolution_status": task.customer_resolution_status, "customer_resolution_method": task.customer_resolution_method, - "customer_id": task.shipping_case.customer_id if task.shipping_case else None, - "customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None, - "customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None, + "customer_id": task.customer_id, + "customer_name_snapshot": task.customer_name_snapshot, + "customer_short_code_snapshot": task.customer_short_code_snapshot, "ship_to": header.get('ship_to') or header.get('ship_to_address'), "po_number": header.get('po_number'), "required_date": header.get('required_date'), @@ -671,21 +530,16 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str data = { "id": task.id, "task_no": task.task_no, - "shipping_case_id": task.shipping_case_id, - "case_no": task.shipping_case.case_no if task.shipping_case else None, - "business_no": task.shipping_case.business_no if task.shipping_case else None, - "batch_no": _task_batch_no(task), + "business_no": task.business_no, "source_type": task.source_type, "source_file_name": task.source_file_name, "source_file_type": task.source_file_type, - "batch_index": task.batch_index, - "batch_total": task.batch_total, "customer_name": header.get('customer_name') or header.get('bill_to_customer'), "customer_resolution_status": task.customer_resolution_status, "customer_resolution_method": task.customer_resolution_method, - "customer_id": task.shipping_case.customer_id if task.shipping_case else None, - "customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None, - "customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None, + "customer_id": task.customer_id, + "customer_name_snapshot": task.customer_name_snapshot, + "customer_short_code_snapshot": task.customer_short_code_snapshot, "current_step": task.current_step, "review_status": task.review_status, "match_status": task.match_status, @@ -747,7 +601,6 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str "po_number": header.get('po_number'), "required_date": header.get('required_date'), "step_payload": step_payload, - "upload_receipt": task.upload_receipt_json or {}, "export_version": task.export_version, "idempotency_key": task.idempotency_key, "lines": current_line_field_values_or_empty(task), @@ -790,41 +643,6 @@ def serialize_task_for_tool(task: ShippingNotice) -> dict[str, Any]: return serialize_task(task, TaskProjection.TOOL) -def serialize_batch(batch: Any, projection: BatchProjection) -> dict[str, Any]: - """shipping_batches 已删除;禁止序列化批次对象。""" - del batch, projection - raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE) - - -def serialize_batch_for_tool(batch: Any | None) -> dict[str, Any] | None: - """Tool 批次 data 投影;shipping_batches 已删除。""" - del batch - return None - - -def serialize_batch_summary(batch: Any) -> dict[str, Any]: - """shipping_batches 已删除;禁止序列化批次摘要。""" - del batch - raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE) - - -def serialize_conversation_batch_workspace(batch: Any) -> dict[str, Any]: - """shipping_batches 已删除;禁止构建会话批次工作台。""" - del batch - raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE) - - -def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]: - """返回一个 Agent 会话下用户可见的所有发货批次与聚合摘要(co8 起固定空集)。""" - value = str(conversation_id or "").strip() - del user_id - return { - "conversation_id": value, - "summary": compute_conversation_workspace_summary([]), - "batches": [], - } - - def task_todo_category(task: ShippingNotice) -> str: """ 由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。 @@ -875,7 +693,6 @@ def _todo_category_from_task_row( ui = resolve_task_ui_state_from_fields( review_status=getattr(row, "review_status", None), pending_human_reason=getattr(row, "pending_human_reason", None), - shipping_case_id=getattr(row, "shipping_case_id", None), customer_resolution_status=getattr(row, "customer_resolution_status", None), order_snapshot_id=getattr(row, "order_snapshot_id", None), inventory_lines_json=getattr(row, "inventory_lines_json", None), @@ -971,6 +788,41 @@ def _artifact_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None: } +def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: + """ + 投影发货通知列表需要的项次、料号、数量与当前库存事实。 + + 核心逻辑:Notice 行定义“本通知包含哪些业务行”;当前库存只读取同 Notice、 + `is_current=true` 的匹配事实。未找到匹配事实时明确返回 null,禁止由前端估算库存。 + """ + if task.id is None: + return [] + matches_by_line_key = { + str(item.line_key): item + for item in ShippingNoticeLineInventoryMatch.query.filter( + ShippingNoticeLineInventoryMatch.task_id == int(task.id), + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ).all() + if item.line_key + } + rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by( + ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(), + ).all() + return [{ + 'line_no': (item.field_values_json or {}).get('line_no') or item.position, + 'part_number': item.part_number, + 'customer_part_number': (item.field_values_json or {}).get('customer_part_number'), + 'reservation_id': item.reservation_id, + 'shipment_qty': str(item.required_qty) if item.required_qty is not None else None, + 'available_qty': matches_by_line_key.get(str(item.line_key or '')).available_qty + if matches_by_line_key.get(str(item.line_key or '')) is not None else None, + 'shortage_qty': matches_by_line_key.get(str(item.line_key or '')).shortage_qty + if matches_by_line_key.get(str(item.line_key or '')) is not None else None, + 'inventory_status': matches_by_line_key.get(str(item.line_key or '')).inventory_status + if matches_by_line_key.get(str(item.line_key or '')) is not None else None, + } for item in rows] + + def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]) -> None: """ 将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。 @@ -1062,6 +914,7 @@ def _enrich_task_center_fields( data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin) data["recent_event"] = _latest_task_event_summary(task) data["artifact_summary"] = _artifact_summary_for_task(task) + data['notice_line_summary'] = _notice_line_summary_for_task(task) # [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。 from app.services.shipping_notice.ui_state import build_task_ui_state @@ -1112,46 +965,15 @@ def serialize_task_detail( ) -def get_batch_for_user(batch_no: str, user_id: int) -> None: - """按 batch_no 查找批次;shipping_batches 已删除,固定返回 None。""" - del batch_no, user_id - return None - - -def list_batches_for_user( - user_id: int, - *, - limit: int = 100, -) -> list[dict[str, Any]]: - """列出用户可见批次摘要;shipping_batches 已删除,固定返回空列表。""" - del user_id, limit - return [] - - -def list_tasks_for_batch(batch_no: str, user_id: int) -> list[dict[str, Any]]: - """列出批次下任务;shipping_batches 已删除,固定返回空列表。""" - del batch_no, user_id - return [] - - -def get_focus_task_for_batch(batch_no: str, user_id: int) -> ShippingNotice | None: - """获取批次 focus 任务;shipping_batches 已删除,固定返回 None。""" - del batch_no, user_id - return None - - def list_tasks_for_user( user_id: int, *, - batch_no: str | None = None, limit: int = 100, ) -> list[dict[str, Any]]: - """列出用户可见任务摘要,可按批次或工作台用户态状态过滤。""" + """列出用户可见任务摘要。""" q = ShippingNotice.query.filter( (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)) ) - if batch_no: - return [] rows = q.order_by(desc(ShippingNotice.created_at)).limit(max(1, min(limit, 500))).all() return [ serialize_task_summary(c, viewer_user_id=user_id) @@ -1164,7 +986,6 @@ def list_tasks_page_for_user( *, page: int = 1, page_size: int = 20, - batch_no: str | None = None, lifecycle_status: str | None = None, ) -> dict[str, Any]: """ @@ -1178,8 +999,6 @@ def list_tasks_page_for_user( q = ShippingNotice.query.filter( (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)) ) - if batch_no: - return {"items": [], "page": normalized_page, "page_size": normalized_page_size, "total": 0} if lifecycle_status: normalized_lifecycle = str(lifecycle_status).strip().lower() if normalized_lifecycle == 'deleted': @@ -1263,20 +1082,103 @@ def get_task_visible_to_user( return task +def list_freight_notice_groups_for_task( + task: ShippingNotice, + *, + user_id: int, + is_admin: bool = False, +) -> dict[str, Any]: + """ + 按当前 Notice 所属客户 PO 返回货代上传的 Notice 聚合行。 + + 核心逻辑:一个 business_no 就是一张独立发货 Excel;同一 PO 后续补货产生的 + Notice 必须作为另一组返回。查询只取当前用户可见的 active Notice,且强制排除尚未 + 分配 business_no 的历史/中间对象,前端不得由 PDF 草稿行猜测分组。 + + Args: + task: 当前订单工作台已授权读取的正式 Notice。 + user_id: 当前用户;非管理员仅返回其创建的 Notice。 + is_admin: 管理员只读可见范围。 + + Returns: + 包含 PO 及一行一个 business_no 的货代上传聚合投影。 + """ + po_number = _notice_po_number(task) + if not po_number: + return {'po_number': None, 'items': [], 'reason': 'po_missing'} + + candidates = ShippingNotice.query.filter( + ShippingNotice.deleted_at.is_(None), + ShippingNotice.lifecycle_status == 'active', + ShippingNotice.business_no.isnot(None), + ) + if not is_admin: + candidates = candidates.filter(ShippingNotice.user_id == int(user_id)) + + items: list[dict[str, Any]] = [] + for notice in candidates.order_by(ShippingNotice.created_at.asc(), ShippingNotice.id.asc()).all(): + if _notice_po_number(notice) != po_number: + continue + business_no = str(notice.business_no or '').strip() + if not business_no: + continue + # [STEP] 主区单条菜单只消费服务端已裁决的 Notice 动作,禁止按 upload_status 猜测。 + from app.services.shipping_notice.ui_state import build_task_ui_state + actions = (build_task_ui_state(notice).get('actions') or {}) + available_actions = [ + str(action.get('code')).strip() + for action in [actions.get('primary'), *(actions.get('secondary') or [])] + if isinstance(action, dict) and action.get('enabled') is True and str(action.get('code') or '').strip() + ] + items.append({ + 'business_no': business_no, + 'po_number': po_number, + 'upload_status': notice.upload_status, + 'export_file_name': notice.export_file_name, + 'available_actions': available_actions, + 'lines': _notice_line_summary_for_task(notice), + }) + return { + 'po_number': po_number, + 'items': items, + 'reason': None if items else 'no_business_notice', + } + + +def _notice_po_number(notice: ShippingNotice) -> str: + """读取 Notice 的正式客户 PO;动态 Schema、冻结快照和兼容投影按稳定顺序回退。""" + header = current_header_field_values_or_empty(notice) + for field_code in ('customer_po_number', 'po_number'): + normalized = normalize_po_number(header.get(field_code)) + if normalized: + return normalized + + snapshot = None + if notice.order_snapshot_id: + snapshot = db.session.get(ShippingOrderSnapshot, notice.order_snapshot_id) + if snapshot: + for value in (snapshot.customer_po_number, (snapshot.header_values_json or {}).get('po_number')): + normalized = normalize_po_number(value) + if normalized: + return normalized + + candidate = ( + db.session.get(ShippingOrderCandidate, notice.source_candidate_id) + if notice.source_candidate_id else None + ) + normalized = normalize_po_number(getattr(candidate, 'po_number', None)) + return normalized + + def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool: - """待办列表客户关键字过滤:匹配 case 快照、来源文件名或当前订单头客户名。""" + """待办列表客户关键字过滤:匹配 Notice 快照、来源文件名或当前订单头客户名。""" needle = str(customer or "").strip().lower() if not needle: return True - case = task.shipping_case candidates: list[str] = [] - if case is not None: - for value in ( - getattr(case, "customer_name_snapshot", None), - getattr(case, "customer_short_code_snapshot", None), - ): - if value: - candidates.append(str(value)) + for value in (task.customer_name_snapshot, task.customer_short_code_snapshot): + if value: + candidates.append(str(value)) if task.source_file_name: candidates.append(str(task.source_file_name)) header = current_header_field_values_or_empty(task) @@ -1341,7 +1243,19 @@ def serialize_review_case_todo( del is_admin run = db.session.get(ShippingOrderProcessingRun, case.run_id) if case.run_id else None document = db.session.get(ShippingOrderDocument, case.document_id) if case.document_id else None - lifecycle_entries = _review_case_lifecycle_entries(case) + lifecycle = _review_case_lifecycle_projection(case) + lifecycle_stage = str(lifecycle.get('lifecycle_stage') or 'unclassified') + lifecycle_entries = list(lifecycle.get('lifecycle_entries') or []) + from app.services.shipping_notice.lifecycle_projection import LIFECYCLE_STAGES + stage_index = next( + (index for index, item in enumerate(LIFECYCLE_STAGES) + if item.get('code') == lifecycle_stage), + 0, + ) + stage_definition = next( + (item for item in LIFECYCLE_STAGES if item['code'] == lifecycle_stage), + {'code': lifecycle_stage, 'label': '状态待同步'}, + ) source_name = None if document is not None: source_name = str(getattr(document, "filename", None) or "").strip() or None @@ -1399,18 +1313,19 @@ def serialize_review_case_todo( "updated_at": case.updated_at.isoformat() if case.updated_at else None, "created_at": case.created_at.isoformat() if case.created_at else None, "ui_state": { - "stage": {"code": "order_review", "label": "订单复核", "index": 2, "total": 4}, - # [AUTHORITY] 任务中心、批次中心和工作台均消费该入口;禁止前端按 Case - # 状态或待办类别补造订单复核权限。 - "lifecycle_stage": "order_review" if lifecycle_entries else None, + "stage": {**stage_definition, "index": stage_index + 1, "total": len(LIFECYCLE_STAGES)}, + # [AUTHORITY] 任务中心、批次中心和工作台均消费统一生命周期投影; + # 前端不得按 Case 状态或待办类别补造订单复核权限。 + "lifecycle_stage": lifecycle_stage, "lifecycle_entries": lifecycle_entries, - "checkpoint": {"code": "order_review", "kind": str(CheckpointKind.MUST_HUMAN), "label": "订单复核"}, + "intake_parse_authorized": lifecycle_stage == "intake_parse", + "checkpoint": {"code": lifecycle_stage, "kind": str(CheckpointKind.MUST_HUMAN), "label": stage_definition['label']}, "todo": {"title": current_todo, "message": current_todo}, "actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []}, "reason": {"code": f"review_case_{case.status}", "message": current_todo}, "lifecycle_status": "active", "process_gate": None, - "checkpoint_code": "order_review", + "checkpoint_code": lifecycle_stage, "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), "summary": { "title": "待人工复核", @@ -1732,11 +1647,7 @@ def _task_todo_category_sql_expr(): (reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")), ( db.and_( - ShippingNotice.shipping_case_id.isnot(None), - db.or_( - ShippingNotice.customer_resolution_status.is_(None), - ShippingNotice.customer_resolution_status != "confirmed", - ), + ShippingNotice.customer_resolution_status.in_(("pending", "needs_review", "failed", "unresolved")), ), literal("exception"), ), @@ -1841,10 +1752,10 @@ def _todo_tasks_base_query( if task_no: q = q.filter(ShippingNotice.task_no == str(task_no).strip()) if customer_needle: - q = q.outerjoin(ShippingCase, ShippingCase.id == ShippingNotice.shipping_case_id).filter( + q = q.filter( db.or_( - ShippingCase.customer_name_snapshot.ilike(customer_like), - ShippingCase.customer_short_code_snapshot.ilike(customer_like), + ShippingNotice.customer_name_snapshot.ilike(customer_like), + ShippingNotice.customer_short_code_snapshot.ilike(customer_like), ShippingNotice.source_file_name.ilike(customer_like), ) ) diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 63c3bf20..08953eab 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -36,7 +36,6 @@ def enqueue_shipping_notice_job( *, task_no: str, created_by_id: int | None = None, - batch_no: str | None = None, commit: bool = True, ) -> tuple[bool, str]: """ @@ -48,7 +47,6 @@ def enqueue_shipping_notice_job( Args: task_no: 发货任务号。 created_by_id: 创建人。 - batch_no: 可选批次号。 commit: False 时与业务同事务提交;此时 sync 模式返回 queued_sync_pending:。 Returns: @@ -63,7 +61,6 @@ def enqueue_shipping_notice_job( JobType.SHIPPING_NOTICE_RUN, { 'task_no': normalized_task_no, - 'batch_no': str(batch_no or '').strip().upper() or None, }, domain=SHIPPING_NOTICE_JOB_DOMAIN, business_ref=normalized_task_no, @@ -124,7 +121,6 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: JobType.SHIPPING_NOTICE_RUN, { 'task_no': task_no, - 'batch_no': (job.payload_json or {}).get('batch_no') if job and job.payload_json else None, }, domain=SHIPPING_NOTICE_JOB_DOMAIN, business_ref=task_no, @@ -225,11 +221,11 @@ def claim_next_shipping_notice_job() -> Job | None: JobType.SHIPPING_DOCUMENT_LAYOUT, JobType.SHIPPING_PROCESS_GATE, JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS, - JobType.SHIPPING_AUTO_PROGRESS, JobType.SHIPPING_PDF_AUTOMARK, JobType.SHIPPING_STP_AUTO_CREATE, JobType.SHIPPING_LINE_AUTO_FULFILL, JobType.SHIPPING_POST_OT_WAVE_PROGRESS, + JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS, ], ) diff --git a/backend/app/services/shipping_notice/reconciliation_projector.py b/backend/app/services/shipping_notice/reconciliation_projector.py index e4ee45c6..9f741b0f 100644 --- a/backend/app/services/shipping_notice/reconciliation_projector.py +++ b/backend/app/services/shipping_notice/reconciliation_projector.py @@ -566,12 +566,20 @@ def _project_case_formal_gate_summary( # 纯投影契约测试与离线诊断没有 Flask application context;此时没有可读 # 的持久化 Execution,保持原有 Case 派生事实即可。 return None + from app import db + + cache = db.session.info.get('shipping_conversation_projection_read_cache') execution = ( - ShippingProcessExecution.query.filter_by(review_case_id=int(case_id)) - .filter(ShippingProcessExecution.status != 'superseded') - .order_by(ShippingProcessExecution.id.desc()) - .first() + cache.get('execution_by_case_id', {}).get(int(case_id)) + if isinstance(cache, dict) else None ) + if execution is None: + execution = ( + ShippingProcessExecution.query.filter_by(review_case_id=int(case_id)) + .filter(ShippingProcessExecution.status != 'superseded') + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) if execution is None: return None from app.services.shipping_notice.process_gate_projection import project_user_gate_summary @@ -588,8 +596,8 @@ def _project_case_formal_gate_facts( 将正式 Gate 摘要归一化为 Case bundle 的三项用户事实。 正式 Execution 存在时,Gate 事实必须覆盖 Case 的历史阻断: - 只有已入队/运行或等待外部回执才表示系统正在推进;建单前的订单冻结 - 校验仍需用户从编辑区提交,不能因 ``pending`` 误显示为系统处理中。 + 已落库的正式 Gate 表示流程已进入该节点;建单前的订单冻结校验仍需用户 + 从编辑区提交,是唯一不能因 ``pending`` 显示为系统处理中的例外。 """ if not isinstance(summary, dict): return None @@ -634,10 +642,10 @@ def _project_case_formal_gate_facts( blocking_reason = BlockingReason(code=None, i18n_key=None, details=None) user_status: UserStatus = 'running' elif gate_status == 'pending': - # pending 仅表示尚未进入该 Gate,不能伪装为系统已在推进。保留当前 - # Case 的可编辑 idle 语义,直到 Gate 实际入队或运行。 + # Execution 已持久化后 pending 是该 Gate 的初始系统推进态;不能回退到 + # Case 草稿的 idle 语义,否则五阶段会把已进入下游节点的文件错误标为空闲。 blocking_reason = BlockingReason(code=None, i18n_key=None, details=None) - user_status = 'idle' + user_status = 'running' elif gate_status == 'blocked_manual': user_status: UserStatus = 'waiting_human' elif gate_status in {'blocked_retryable', 'invalidated'}: @@ -805,24 +813,24 @@ def project_case_primary_action( return {'code': 'open_order_review', 'variant': 'warning', 'label_key': 'shipping.actions.open_order_review'} - # 1f: 草稿编辑和保存校验分别属于主编辑区与底栏,不得升级为当前任务 CTA。 - if user_status == 'waiting_human': - return None - - # 1g: idle → 有 create_draft 优先(首次打开草稿面板 CTA) - if user_status == 'idle': + # 1f: 已授权草稿操作是文件列表的下一项业务操作。点击只导航到该文件的 + # 复核上下文;validate 仍由工作台底栏执行,不能提升为列表 CTA。 + if user_status in {'waiting_human', 'idle'}: if 'create_draft' in actions: - return None + return {'code': 'create_draft', 'variant': 'primary', + 'label_key': 'shipping.actions.create_draft'} if 'edit_draft' in actions: - return None + return {'code': 'edit_draft', 'variant': 'primary', + 'label_key': 'shipping.actions.edit_draft'} - # 1h: running/queued → 次优先 view(但 edit_draft 仍然允许) + # 1g: running/queued → 次优先 view(但 edit_draft 仍然允许) if user_status == 'running' and 'edit_draft' in actions: return None - # 1i: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个命中的动作码 + # 1h: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个业务动作;view 是只读 + # 查询能力,阶段导航由五阶段入口承担,不能伪装成文件当前业务 CTA。 for code in _PRIMARY_ACTION_ORDER: - if code in {'edit_draft', 'create_draft', 'validate'}: + if code in {'edit_draft', 'create_draft', 'validate', 'view'}: continue if code in actions: variant = 'default' @@ -913,31 +921,46 @@ def _project_fine_grained_pre_stp_blocking( _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)}:" + cache = db.session.info.get('shipping_conversation_projection_read_cache') + prefix_jobs = ( + cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, []) + if isinstance(cache, dict) else None + ) 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}%"), + next( + (job for job in prefix_jobs if str(job.status or '').strip().lower() in {'queued', 'running'}), + None, + ) if prefix_jobs is not None else ( + 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() ) - .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}%"), + next( + (job for job in prefix_jobs if str(job.status or '').strip().lower() in {'failed', 'dead'}), + None, + ) if prefix_jobs is not None else ( + 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() ) - .order_by(Job.id.desc()) - .first() ) if latest_failed is not None: rj = ( @@ -1036,16 +1059,24 @@ def _project_fine_grained_pre_stp_blocking( 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)}:" + cache = db.session.info.get('shipping_conversation_projection_read_cache') + prefix_jobs = ( + cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, []) + if isinstance(cache, dict) else None + ) 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}%"), + next((job for job in prefix_jobs if str(job.status or '').strip().lower() == 'queued'), None) + if prefix_jobs is not None else ( + 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() ) - .order_by(Job.id.desc()) - .first() ) _worker_unavailable_hit = False diff --git a/backend/app/services/shipping_notice/reconciliation_service.py b/backend/app/services/shipping_notice/reconciliation_service.py index 84259674..f0da259f 100644 --- a/backend/app/services/shipping_notice/reconciliation_service.py +++ b/backend/app/services/shipping_notice/reconciliation_service.py @@ -426,13 +426,11 @@ def reconcile_and_progress( 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 裁决后调用。 + 【AI 触发时机】:用户点击「处理重复任务」走自动化恢复,或前端 + duplicate_decision_required 裁决后调用。 核心执行顺序(Q11 短事务锁 + Q1 五级归属 + Q3 复用 Candidate 裁决 + Q2 写回绑定): 1. 加载 Case(FOR UPDATE 短锁);查可见性;构建 request_snapshot(参数一致性校验) @@ -447,14 +445,9 @@ def reconcile_and_progress( 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 审计 - → 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY, - 否则返回 outcome=ownership_anomaly_rejected。 + BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计 + → 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY, + 否则返回 outcome=ownership_anomaly_rejected。 Args: user_id: 操作人。 @@ -464,8 +457,6 @@ def reconcile_and_progress( 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() 方法)。 @@ -493,61 +484,6 @@ def reconcile_and_progress( 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 @@ -579,12 +515,6 @@ def reconcile_and_progress( '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) @@ -757,8 +687,6 @@ def reconcile_and_progress( '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, diff --git a/backend/app/services/shipping_notice/recovery_invalidation_service.py b/backend/app/services/shipping_notice/recovery_invalidation_service.py index 1e387503..46153535 100644 --- a/backend/app/services/shipping_notice/recovery_invalidation_service.py +++ b/backend/app/services/shipping_notice/recovery_invalidation_service.py @@ -133,7 +133,7 @@ def invalidate_excel_regeneration_only( ).with_for_update().all() for artifact in artifacts: uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).with_for_update().all() - # 成功上传或已登记货代回执是不可逆外部事实,不能用 Excel 重生覆盖。 + # 成功上传或已有外部上传参考是不可逆外部事实,不能用 Excel 重生覆盖。 if artifact.status == 'uploading' or any( upload.status == 'succeeded' or str(upload.freight_ref_no or '').strip() for upload in uploads diff --git a/backend/app/services/shipping_notice/reference_context.py b/backend/app/services/shipping_notice/reference_context.py index e35af0b9..efd049fe 100644 --- a/backend/app/services/shipping_notice/reference_context.py +++ b/backend/app/services/shipping_notice/reference_context.py @@ -1,7 +1,7 @@ """ backend/app/services/shipping_notice/reference_context.py -用途:从发货通知批次/任务/事件构建 shipping_notice 专用 reference_context。 +用途:从发货通知任务/事件构建 shipping_notice 专用 reference_context。 依赖:models.ShippingNotice/ShippingTaskEvent、agent_runtime_context.reference。 逻辑:runtime_context 在调用 Dify 前经本模块提炼当前 focus、最近动作、最近失败和候选对象,避免把全量事件流水直接暴露给 Runtime。 """ @@ -59,7 +59,7 @@ def _task_recency_key(task: ShippingNotice) -> tuple[datetime, int]: return updated_at, int(getattr(task, "id", 0) or 0) -def _collect_batch_tasks(batch: Any | None, focus_task: ShippingNotice | None) -> list[ShippingNotice]: +def _collect_focus_task(focus_task: ShippingNotice | None) -> list[ShippingNotice]: """ 汇总当前 reference_context 可见的任务集合。 @@ -72,9 +72,9 @@ def _collect_batch_tasks(batch: Any | None, focus_task: ShippingNotice | None) - def _recent_events(tasks: list[ShippingNotice]) -> list[ShippingTaskEvent]: """ - 查询最近关键事件。 + 查询当前任务最近关键事件。 - 核心逻辑:只取当前批次/任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。 + 核心逻辑:只取当前任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。 """ task_ids = [int(task.id) for task in tasks if getattr(task, "id", None) is not None] if not task_ids: @@ -210,7 +210,6 @@ def _candidate_refs(tasks: list[ShippingNotice], focus_task_no: str) -> list[dic def _build_recent_activity_summary( *, - batch: Any | None, focus_task_no: str, last_action_summary: str, last_failed_summary: str, @@ -226,8 +225,6 @@ def _build_recent_activity_summary( pieces.append(last_action_summary) if focus_task_no: pieces.append(f"当前 focus 为 {focus_task_no}") - elif _clean_text(getattr(batch, "batch_no", None)): - pieces.append(f"当前批次为 {_clean_text(batch.batch_no).upper()}") if last_failed_summary: pieces.append(last_failed_summary) if len(candidates) > 1: @@ -243,7 +240,6 @@ def _build_recent_activity_summary( def build_shipping_reference_context( *, - batch: Any | None, focus_task: ShippingNotice | None, ) -> dict[str, Any]: """ @@ -252,20 +248,17 @@ def build_shipping_reference_context( 【AI 触发时机】:当用户在 HXOPS 已做确认、重匹配、切票等动作后,又在对话里说“继续”“刚才那个”“上一个失败的”时, Dify 需要优先读取这份上下文理解当前现场,但不能直接据此推进业务状态。 - 核心逻辑:读取 batch.current_focus_task_no、任务状态和最近少量事件,提炼 focus_object / last_action_target / + 核心逻辑:读取当前任务状态和最近少量事件,提炼 focus_object / last_action_target / last_failed_target / candidates / recent_activity_summary 五类短期线索;不输出全量任务详情或完整事件日志。 Args: - batch: 当前批次;可为空。 focus_task: 当前焦点任务;可为空。 Returns: shipping_notice 领域的 reference_context;没有有效线索时返回空 dict。 """ - tasks = _collect_batch_tasks(batch, focus_task) + tasks = _collect_focus_task(focus_task) focus_task_no = _task_no(focus_task) - if not focus_task_no and batch and _clean_text(getattr(batch, "current_focus_task_no", None)): - focus_task_no = _clean_text(batch.current_focus_task_no).upper() if not tasks and not focus_task_no: return {} @@ -278,7 +271,6 @@ def build_shipping_reference_context( focus_object = build_object_ref("task", focus_task_no) if focus_task_no else {} recent_activity_summary = _build_recent_activity_summary( - batch=batch, focus_task_no=focus_task_no, last_action_summary=last_action_summary, last_failed_summary=last_failed_summary, diff --git a/backend/app/services/shipping_notice/reservation_region.py b/backend/app/services/shipping_notice/reservation_region.py new file mode 100644 index 00000000..62984a02 --- /dev/null +++ b/backend/app/services/shipping_notice/reservation_region.py @@ -0,0 +1,160 @@ +""" +Reservation ID 专用证据区域解析器。 + +用途:从管理员圈选的 Vendor Comments 区域提取 Reservation ID 和可选行号。 +依赖:reservation_id 的统一格式校验。 +逻辑:只消费区域文字,不依赖客户名称、固定坐标或旧的三来源映射;无行号仅标记为未归属,最终由 Schema scope 决定表头写入或明细复核。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any + +from app.services.shipping_notice.document_layout.coordinate_region_text import visual_text_lines +from app.services.shipping_notice.reservation_id import validated_reservation_id + + +_ID_RE = re.compile(r"(? list[ReservationRegionCandidate]: + """从区域原文提取候选;有行号归明细,无行号归订单头。""" + candidates: list[ReservationRegionCandidate] = [] + for raw_line in (str(text or '').splitlines() or [str(text or '')]): + line = raw_line.strip() + # A selected comments area can also contain customer numbers, quantities, + # and dates. Only a value on a Reservation-labelled line is evidence. + if not line or not _RESERVATION_LABEL_RE.search(line): + continue + ids = [validated_reservation_id(m.group(1)) for m in _ID_RE.finditer(line)] + ids = [value for value in ids if value] + if not ids: + continue + line_match = _LINE_RE.search(line) + line_no = None + if line_match: + line_no = int(line_match.group(1) or line_match.group(2)) + scope = 'line' if line_no is not None else 'header' + status = 'mapped' if line_no is not None else 'header' + for value in dict.fromkeys(ids): + candidates.append(ReservationRegionCandidate(value, line_no, scope, line, status)) + return candidates + + +def extract_reservation_from_region_text(text: str) -> list[dict[str, object]]: + """返回 API/预览可直接序列化的统一候选 DTO。""" + return [ + { + 'value': item.value, + 'line_no': item.line_no, + 'scope': item.scope, + 'raw_text': item.raw_text, + 'status': item.status, + } + for item in extract_reservation_from_region(text) + ] + + +def extract_reservation_from_vendor_comments_pages( + pages: list[tuple[int, list[dict[str, Any]]]], +) -> tuple[list[dict[str, object]], str | None]: + """从跨页 Vendor Comments 区块提取 Reservation;仅首个 Terms 标题前的文字有效。 + + 核心逻辑:Reservation 专区已启用时,页面坐标只是提供稳定阅读顺序,不能作为固定 + 页码或矩形取值依据。缺少起止锚点时返回稳定原因,由调用方转人工复核。 + """ + started = False + window_lines: list[str] = [] + for _page_no, glyphs in sorted(pages, key=lambda item: item[0]): + for line in visual_text_lines(glyphs): + if not started: + if _VENDOR_COMMENTS_HEADING_RE.fullmatch(line): + started = True + continue + if _TERMS_AND_CONDITIONS_HEADING_RE.fullmatch(line): + return extract_reservation_from_region_text('\n'.join(window_lines)), None + window_lines.append(line) + if not started: + return [], 'vendor_comments_anchor_missing' + return [], 'terms_and_conditions_anchor_missing' + + +def apply_reservation_region_candidates( + *, candidates: list[dict[str, object]], header_field_id: str | None, + line_field_id: str | None, line_count: int, +) -> ReservationRegionApplication: + """按固定契约将专用区域候选归属到订单头和逻辑明细行。 + + 无行号 Reservation 是整单事实,最多接受一个不同值;带行号的值仅在 + Schema 启用明细 Reservation 字段时写入对应逻辑行。冲突、越界行号或 + 多个不同整单值必须转人工复核,不能静默猜测。 + """ + _ = header_field_id + header_values: list[str] = [] + line_values_by_no: dict[int, list[str]] = {} + reasons: list[str] = [] + for item in candidates: + if not isinstance(item, dict): + continue + value = str(item.get('value') or '') + if not value: + continue + if item.get('scope') == 'header': + header_values.append(value) + continue + if item.get('scope') != 'line' or item.get('line_no') is None: + continue + try: + line_no = int(item['line_no']) + except (TypeError, ValueError): + reasons.append('line_out_of_range') + continue + if line_no < 1 or line_no > line_count: + reasons.append('line_out_of_range') + continue + if line_field_id: + line_values_by_no.setdefault(line_no, []).append(value) + else: + reasons.append('line_field_unavailable') + + unique_headers = list(dict.fromkeys(header_values)) + if len(unique_headers) > 1: + reasons.append('conflicting_header_value') + resolved_lines: dict[int, str] = {} + for line_no, values in line_values_by_no.items(): + unique_values = list(dict.fromkeys(values)) + if len(unique_values) > 1: + reasons.append('conflicting_line_value') + continue + resolved_lines[line_no] = unique_values[0] + return ReservationRegionApplication( + header_value=unique_headers[0] if len(unique_headers) == 1 else None, + line_values=resolved_lines, + needs_review=bool(reasons), + review_reasons=tuple(dict.fromkeys(reasons)), + ) diff --git a/backend/app/services/shipping_notice/reservation_service.py b/backend/app/services/shipping_notice/reservation_service.py index 5586b2fa..372b92ed 100644 --- a/backend/app/services/shipping_notice/reservation_service.py +++ b/backend/app/services/shipping_notice/reservation_service.py @@ -180,6 +180,7 @@ def reserve_available_for_artifact( artifact: ShippingExportArtifact, verification: ShippingInventoryVerification, released_snapshot_line_ids: set[int] | None = None, + selected_snapshot_line_ids: set[int] | None = None, ) -> list[ShippingReservation]: """ 锁定本轮可用或已审计短缺放行的预约单,并写入 Artifact 行。 @@ -193,6 +194,7 @@ def reserve_available_for_artifact( artifact: 已落库但尚未提交的导出 Artifact。 verification: 当前库存核验轮次。 released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。 + selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时不得占用集合外行。 Returns: 本次被 Artifact 占用的预约单。 @@ -226,7 +228,12 @@ def reserve_available_for_artifact( ) if not rows: raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY') - selected = [item for item in rows if item.id in verification_lines] + selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())} + selected = [ + item for item in rows + if item.id in verification_lines + and (not selected_ids or int(item.snapshot_line_id) in selected_ids) + ] if not selected: raise ConflictError('Current verification has no available reservations', code='SHIPPING.ROLLING_EXPORT_NOT_READY') for reservation in selected: @@ -244,6 +251,7 @@ def current_available_snapshot_line_ids( task: ShippingNotice, *, released_snapshot_line_ids: set[int] | None = None, + selected_snapshot_line_ids: set[int] | None = None, ) -> tuple[ShippingInventoryVerification, set[int]]: """ 取得最新核验中可导出的冻结订单行。 @@ -254,6 +262,7 @@ def current_available_snapshot_line_ids( Args: task: 当前正式发货任务。 released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。 + selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时仅返回该集合。 Returns: (最新核验轮次, 本次可导出的冻结订单行 ID)。 @@ -288,7 +297,11 @@ def current_available_snapshot_line_ids( ShippingReservation.id.in_(reservation_ids), ShippingReservation.status.in_({'available', 'pending'}), ).all() if reservation_ids else [] - line_ids = {item.snapshot_line_id for item in reservations} + selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())} + line_ids = { + item.snapshot_line_id for item in reservations + if not selected_ids or int(item.snapshot_line_id) in selected_ids + } if not line_ids: raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY') return verification, line_ids diff --git a/backend/app/services/shipping_notice/runtime_context.py b/backend/app/services/shipping_notice/runtime_context.py index d9c1466e..7c1d1a03 100644 --- a/backend/app/services/shipping_notice/runtime_context.py +++ b/backend/app/services/shipping_notice/runtime_context.py @@ -34,20 +34,6 @@ def _clean_text(value: Any) -> str: return str(value or "").strip() -def _batch_no(batch: Any | None, task: ShippingNotice | None) -> str: - """ - 获取当前上下文的批次号。 - - 核心逻辑:shipping_batches 已删除;仅保留显式传入 batch 对象的兼容读取。 - - Returns: - 批次号;无法识别时返回空字符串。 - """ - if batch and _clean_text(getattr(batch, "batch_no", None)): - return _clean_text(batch.batch_no).upper() - return "" - - def _task_no(task: ShippingNotice | None) -> str: """ 获取当前上下文的任务号。 @@ -66,7 +52,6 @@ def _task_no(task: ShippingNotice | None) -> str: def _build_refs( *, task: ShippingNotice | None, - batch: Any | None, run_purpose: str | None, intake_nos: list[str] | None = None, capability: str | None = None, @@ -76,11 +61,10 @@ def _build_refs( """ 构建新版 agent_runtime_context.refs。 - 核心逻辑:使用稳定业务字段名 task_no/batch_no/run_purpose/file_name,区别于旧 hxops_context 的 task/batch。 + 核心逻辑:使用稳定业务字段名 task_no/run_purpose/file_name。 Args: task: 当前任务。 - batch: 当前批次。 run_purpose: 本次 Dify run 的目的。 intake_nos: 点击发送时锁定的 Intake 编号集合。 capability: 当前固定画布能力,如 order_extraction。 @@ -90,13 +74,10 @@ def _build_refs( """ refs: dict[str, str] = {} task_no = _task_no(task) - batch_no = _batch_no(batch, task) file_name = _clean_text(getattr(task, "source_file_name", None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: refs["task_no"] = task_no - if batch_no: - refs["batch_no"] = batch_no if normalized_run_purpose: refs["run_purpose"] = normalized_run_purpose if file_name: @@ -115,7 +96,7 @@ def _build_refs( return refs -def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[str, Any]: +def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]: """ 构建发货通知运行态提示。 @@ -123,7 +104,6 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st Args: task: 当前任务。 - batch: 当前批次。 Returns: 状态提示字典。 @@ -132,8 +112,6 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st task_no = _task_no(task) if task_no: state_hint["focus_task_no"] = task_no - elif batch and _clean_text(getattr(batch, "current_focus_task_no", None)): - state_hint["focus_task_no"] = _clean_text(batch.current_focus_task_no).upper() if task is not None: for attr, key in ( @@ -147,26 +125,21 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st if value: state_hint[key] = value - batch_no = _batch_no(batch, task) - if batch_no: - state_hint["batch_no"] = batch_no return state_hint def _build_summary( *, task: ShippingNotice | None, - batch: Any | None, run_purpose: str | None, ) -> str: """ 构建给 Dify 阅读的短摘要。 - 核心逻辑:用自然语言说明当前 run 的任务、批次、文件和状态,避免 Dify 依赖 conversation memory 猜现场。 + 核心逻辑:用自然语言说明当前 run 的任务、文件和状态,避免 Dify 依赖 conversation memory 猜现场。 Args: task: 当前任务。 - batch: 当前批次。 run_purpose: 本次 Dify run 的目的。 Returns: @@ -174,14 +147,11 @@ def _build_summary( """ pieces: list[str] = [] task_no = _task_no(task) - batch_no = _batch_no(batch, task) file_name = _clean_text(getattr(task, "source_file_name", None)) current_step = _clean_text(getattr(task, "current_step", None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: pieces.append(f"当前任务 {task_no}") - if batch_no: - pieces.append(f"属于批次 {batch_no}") if file_name: pieces.append(f"来源文件 {file_name}") if normalized_run_purpose: @@ -189,7 +159,7 @@ def _build_summary( if current_step: pieces.append(f"当前步骤 {current_step}") if not pieces: - return "当前为货代发货通知 Agent 会话,尚未解析出明确任务或批次锚点。" + return "当前为货代发货通知 Agent 会话,尚未解析出明确任务锚点。" return ",".join(pieces) + "。" @@ -197,7 +167,6 @@ def build_shipping_runtime_context( *, session_id: str, task: ShippingNotice | None = None, - batch: Any | None = None, trigger_source: str | None = None, request_id: str | None = None, locale: str | None = None, @@ -211,13 +180,12 @@ def build_shipping_runtime_context( """ 构建货代发货通知 Agent 的 agent_runtime_context。 - 核心逻辑:以 HXOPS DB 中的 task/batch 为事实源,生成 refs/domain.state_hint/reference_context snapshot, + 核心逻辑:以 HXOPS DB 中的 task 为事实源,生成 refs/domain.state_hint/reference_context snapshot, 供 Dify 每次 run 显式识别现场。 Args: session_id: HXOPS 本地 ChatSession.session_id。 task: 当前显式任务;禁止在本函数内按会话猜测。 - batch: 当前批次。 trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。 request_id: 本次请求 ID。 locale: 用户语言。 @@ -233,14 +201,11 @@ def build_shipping_runtime_context( """ domain = { "type": SHIPPING_NOTICE_AGENT_CODE, - "summary": _build_summary(task=task, batch=batch, run_purpose=run_purpose), - "state_hint": _build_state_hint(task, batch), + "summary": _build_summary(task=task, run_purpose=run_purpose), + "state_hint": _build_state_hint(task), "available_actions_hint": [], } - reference_context = build_shipping_reference_context( - batch=batch, - focus_task=task, - ) + reference_context = build_shipping_reference_context(focus_task=task) return build_agent_runtime_context( agent_code=SHIPPING_NOTICE_AGENT_CODE, scope=scope, @@ -250,7 +215,6 @@ def build_shipping_runtime_context( locale=locale, refs=_build_refs( task=task, - batch=batch, run_purpose=run_purpose, intake_nos=intake_nos, capability=capability, diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 14ccc1c0..66b14348 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -14,29 +14,39 @@ services/shipping_notice/shipping_processing_projection.py 写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准(BE-07,禁止 Notice 覆盖); 已挂正式 Notice 时 stage/stage_label_key 与 Case.current_stage 同源(project_stage_for_task); **只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);已建 Notice 时填 shipping_notice_no; - work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing; + work_items 构建后由 _conversation_processing_from_work_items 构建正式 conversation_processing; 不投影会话级批量恢复动作;失败必须由用户在当前 Gate 选择具体动作。 """ from __future__ import annotations import logging +from dataclasses import dataclass from datetime import datetime from typing import Any +from sqlalchemy.orm import load_only, selectinload + from app import db from app.core.errors import NotFoundError, ValidationError from app.models import ( FileAsset, + Job, ShippingNotice, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderProcessingRun, ShippingOrderProcessingRunIntake, + ShippingOrderProcessingPlan, ShippingOrderProcessingUnit, ShippingOrderReviewCase, + ShippingOrderReviewDraft, ShippingOrderReviewStream, + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, + ShippingProcessRecoveryPlan, ShippingOrderSubmission, ShippingOrderTask, ) @@ -48,8 +58,11 @@ from app.services.shipping_notice.processing_projection_invariants import ( from app.services.shipping_notice.processing_ownership import ( record_projection_inconsistency_audit, ) +from app.services.shipping_notice.reconciliation_projector import ( + project_case_primary_action, +) from app.services.shipping_notice.lifecycle_projection import ( - LIFECYCLE_STAGE_RANGES, + LIFECYCLE_STAGE_CODES, project_lifecycle, ) from app.services.shipping_notice.query_service import resolve_task_export_download @@ -63,6 +76,269 @@ from app.services.shipping_notice.progress_audit_contract import ( logger = logging.getLogger(__name__) + +@dataclass(frozen=True) +class _ConversationProjectionLoadContext: + """会话投影的一次性只读预取结果,避免 EML 附件按 Intake 重复查询。""" + + documents_by_intake_id: dict[int, list[ShippingOrderDocument]] + intakes_by_no: dict[str, ShippingOrderIntake] + prefetched_gate_attempts: list[ShippingProcessGateAttempt] + read_cache: dict[str, Any] + + +_CONVERSATION_PROJECTION_READ_CACHE_KEY = 'shipping_conversation_projection_read_cache' + + +def _conversation_projection_read_cache() -> dict[str, Any] | None: + """返回当前会话投影的临时只读缓存;单项投影不启用该缓存。""" + cached = db.session.info.get(_CONVERSATION_PROJECTION_READ_CACHE_KEY) + return cached if isinstance(cached, dict) else None + + +def _conversation_projection_load_context( + intakes: list[ShippingOrderIntake], +) -> _ConversationProjectionLoadContext: + """批量加载会话 Intake 的业务附件,供同一请求内所有 EML 聚合复用。""" + intake_ids = [int(intake.id) for intake in intakes] + documents_by_intake_id: dict[int, list[ShippingOrderDocument]] = { + intake_id: [] for intake_id in intake_ids + } + if intake_ids: + documents = ( + ShippingOrderDocument.query.filter( + ShippingOrderDocument.intake_id.in_(intake_ids), + ShippingOrderDocument.document_type != 'email_body', + ) + .order_by( + ShippingOrderDocument.intake_id.asc(), + ShippingOrderDocument.id.asc(), + ) + .all() + ) + for document in documents: + documents_by_intake_id.setdefault(int(document.intake_id), []).append(document) + document_ids = [ + int(document.id) + for documents in documents_by_intake_id.values() + for document in documents + ] + prefetched_gate_attempts: list[ShippingProcessGateAttempt] = [] + read_cache: dict[str, Any] = { + 'current_case_by_document_id': {}, + 'run_links_by_intake_id': {}, + 'runs_by_id': {}, + 'stp_jobs_by_ref': {}, + 'stp_jobs_by_prefix': {}, + 'execution_by_case_id': {}, + 'gates_by_execution_id': {}, + 'latest_attempt_by_id': {}, + 'active_recovery_plans_by_execution_id': {}, + 'parse_jobs_by_id': {}, + 'candidate_count_by_intake_id': {}, + 'candidate_by_id': {}, + 'reparseable_batch_by_run_id': {}, + 'reparseable_batch_for_conversation': None, + } + if document_ids: + cases = ( + ShippingOrderReviewCase.query.filter( + ShippingOrderReviewCase.document_id.in_(document_ids), + ) + .options( + selectinload(ShippingOrderReviewCase.current_draft), + selectinload(ShippingOrderReviewCase.run).selectinload( + ShippingOrderProcessingRun.extraction_plan, + ).selectinload(ShippingOrderProcessingPlan.units), + ) + .all() + ) + case_ids = [int(case.id) for case in cases] + current_case_ids = { + int(case_id) + for (case_id,) in db.session.query( + ShippingOrderReviewStream.current_case_id, + ).filter( + ShippingOrderReviewStream.document_id.in_(document_ids), + ShippingOrderReviewStream.current_case_id.isnot(None), + ).all() + } + read_cache['current_case_by_document_id'] = { + int(case.document_id): case + for case in cases + if int(case.id) in current_case_ids + } + for case in cases: + if case.run is not None: + read_cache['runs_by_id'][int(case.run.id)] = case.run + if case_ids: + executions = ( + ShippingProcessExecution.query.filter( + ShippingProcessExecution.review_case_id.in_(case_ids), + ShippingProcessExecution.status != 'superseded', + ) + .order_by(ShippingProcessExecution.id.desc()) + .options(selectinload(ShippingProcessExecution.gates).selectinload( + ShippingProcessGate.attempts, + )) + .all() + ) + for execution in executions: + read_cache['execution_by_case_id'].setdefault( + int(execution.review_case_id), execution, + ) + read_cache['gates_by_execution_id'][int(execution.id)] = list( + getattr(execution, 'gates', []) or [], + ) + execution_ids = [int(execution.id) for execution in executions] + if execution_ids: + latest_attempt_ids = [ + int(attempt_id) + for (attempt_id,) in db.session.query( + ShippingProcessGate.latest_attempt_id, + ).filter( + ShippingProcessGate.execution_id.in_(execution_ids), + ShippingProcessGate.latest_attempt_id.isnot(None), + ).all() + ] + if latest_attempt_ids: + # serialize_process_gate 使用 session.get(latest_attempt_id)。保留这些 + # 实体引用可使同一次投影命中 identity map,避免每个 Gate 再查一次。 + prefetched_gate_attempts = ShippingProcessGateAttempt.query.filter( + ShippingProcessGateAttempt.id.in_(latest_attempt_ids), + ).all() + read_cache['latest_attempt_by_id'] = { + int(attempt.id): attempt for attempt in prefetched_gate_attempts + } + recovery_plans = ShippingProcessRecoveryPlan.query.filter( + ShippingProcessRecoveryPlan.execution_id.in_(execution_ids), + ShippingProcessRecoveryPlan.status.in_({ + 'planned', 'invalidating', 'queued', 'running', + 'waiting_external', 'waiting_manual', + }), + ).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all() + for plan in recovery_plans: + read_cache['active_recovery_plans_by_execution_id'].setdefault( + int(plan.execution_id), [], + ).append(plan) + # 读取所有当前 Case 的 STP Job 一次;后续 Case bundle 以幂等键从缓存裁决。 + stp_prefixes = { + f"stp-auto:{case.run.run_no}:doc-{int(case.document_id)}:" + for case in cases + if case.run is not None and case.document_id is not None + } + if stp_prefixes: + from sqlalchemy import or_ + from app.jobs.types import JobType + + jobs = Job.query.filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + or_(*(Job.business_ref.like(f'{prefix}%') for prefix in stp_prefixes)), + ).order_by(Job.id.desc()).all() + for job in jobs: + ref = str(job.business_ref or '').strip() + read_cache['stp_jobs_by_ref'].setdefault(ref, []).append(job) + prefix = next((item for item in stp_prefixes if ref.startswith(item)), None) + if prefix: + read_cache['stp_jobs_by_prefix'].setdefault(prefix, []).append(job) + if intake_ids: + asset_ids = [int(intake.asset_id) for intake in intakes if intake.asset_id] + if asset_ids: + FileAsset.query.filter(FileAsset.id.in_(asset_ids)).all() + parse_job_ids = [int(intake.parse_job_id) for intake in intakes if intake.parse_job_id] + if parse_job_ids: + read_cache['parse_jobs_by_id'] = { + int(job.id): job for job in Job.query.filter(Job.id.in_(parse_job_ids)).all() + } + candidates = ShippingOrderCandidate.query.filter( + ShippingOrderCandidate.intake_id.in_(intake_ids), + ).all() + read_cache['candidate_by_id'] = {int(candidate.id): candidate for candidate in candidates} + for candidate in candidates: + if ( + bool(candidate.is_current_version) + and str(candidate.candidate_status or '').strip().lower() in {'provisional', 'accepted'} + ): + intake_id = int(candidate.intake_id) + read_cache['candidate_count_by_intake_id'][intake_id] = ( + int(read_cache['candidate_count_by_intake_id'].get(intake_id, 0)) + 1 + ) + links = ( + ShippingOrderProcessingRunIntake.query.join( + ShippingOrderProcessingRun, + ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id, + ) + .filter(ShippingOrderProcessingRunIntake.intake_id.in_(intake_ids)) + .order_by( + ShippingOrderProcessingRun.created_at.desc(), + ShippingOrderProcessingRunIntake.created_at.desc(), + ) + .all() + ) + for link in links: + read_cache['run_links_by_intake_id'].setdefault( + int(link.intake_id), [], + ).append(link) + run = db.session.get(ShippingOrderProcessingRun, int(link.run_id)) + if run is not None: + read_cache['runs_by_id'].setdefault(int(run.id), run) + if intakes: + # 与写命令的选取语义一致:会话已有 Stream 时,Stream.current_case 才是 + # 每份 PDF 的当前版本事实。这里仅用于 GET 授权摘要,绝不加行锁。 + conversation_stream_cases = ( + db.session.query(ShippingOrderReviewCase) + .join( + ShippingOrderReviewStream, + ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, + ) + .join( + ShippingOrderProcessingRun, + ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id, + ) + .filter( + ShippingOrderReviewStream.owner_user_id == int(intakes[0].user_id), + ShippingOrderProcessingRun.conversation_id == str(intakes[0].conversation_id), + ) + .all() + ) + if conversation_stream_cases: + read_cache['reparseable_batch_for_conversation'] = any( + str(case.status or '').strip().lower() + in {'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending'} + and case.confirmed_task_id is None + for case in conversation_stream_cases + ) + return _ConversationProjectionLoadContext( + documents_by_intake_id=documents_by_intake_id, + intakes_by_no={str(intake.intake_no): intake for intake in intakes}, + prefetched_gate_attempts=prefetched_gate_attempts, + read_cache=read_cache, + ) + + +def _has_reparseable_batch_documents_for_projection( + *, run: ShippingOrderProcessingRun, + load_context: _ConversationProjectionLoadContext | None = None, +) -> bool: + """投影读取批次资格:优先会话预取,回退时也只能执行无锁只读查询。""" + cache = load_context.read_cache if load_context is not None else _conversation_projection_read_cache() + if isinstance(cache, dict): + conversation_cached = cache.get('reparseable_batch_for_conversation') + if conversation_cached is not None: + return bool(conversation_cached) + cached = cache.get('reparseable_batch_by_run_id', {}).get(int(run.id)) + if cached is not None: + return bool(cached) + from app.services.shipping_notice.order_review_disposition_service import ( + has_reparseable_batch_documents_readonly, + ) + + result = has_reparseable_batch_documents_readonly(user_id=int(run.user_id), run=run) + if isinstance(cache, dict): + cache.setdefault('reparseable_batch_by_run_id', {})[int(run.id)] = result + return result + # Intake 仍处于「材料解析」身份、页面应展示 order_intake 的 parse_status。 _INTAKE_ORDER_INTAKE_PARSE_STATUSES = frozenset({ 'created', @@ -343,7 +619,11 @@ def _intake_parse_attempt_count(intake: ShippingOrderIntake) -> int: return 0 from app.models import Job - job = db.session.get(Job, job_id) + cache = _conversation_projection_read_cache() + job = ( + cache['parse_jobs_by_id'].get(job_id) + if cache is not None else db.session.get(Job, job_id) + ) if job is None: return 0 return max(0, int(getattr(job, 'attempts', 0) or 0)) @@ -400,7 +680,7 @@ def _intake_current_gate( return None -def _intake_available_actions(intake: ShippingOrderIntake) -> list[str]: +def _intake_authorized_actions(intake: ShippingOrderIntake) -> list[str]: """Intake 级可用动作(最小集)。""" parse_status = str(intake.parse_status or '').strip().lower() actions = ['view_details'] @@ -413,6 +693,7 @@ def _intake_source_summary( intake: ShippingOrderIntake, *, asset: FileAsset | None, + load_context: _ConversationProjectionLoadContext | None = None, ) -> dict[str, Any]: """ 构建 Intake 的 source_summary。 @@ -431,28 +712,43 @@ def _intake_source_summary( if isinstance(structured.get('business_summary'), dict) else {} ) + prefetched_documents = ( + load_context.documents_by_intake_id.get(int(intake.id)) + if load_context is not None else None + ) document_filters = [ShippingOrderDocument.intake_id == int(intake.id)] # EML 正文是邮件上下文而非可处理文件。父卡数量必须与后续展开附件同源, # 否则会出现“3 个文件、只有 2 个(甚至 0 个)叶子”的假象。 if str(intake.source_type or '').strip().lower() == 'eml': document_filters.append(ShippingOrderDocument.document_type != 'email_body') - document_count = db.session.query(ShippingOrderDocument.id).filter( - *document_filters, - ).count() - parsed_document_count = db.session.query(ShippingOrderDocument.id).filter( - *document_filters, - ShippingOrderDocument.parse_status == 'parsed', - ).count() + if prefetched_documents is not None: + document_count = len(prefetched_documents) + parsed_document_count = sum( + str(document.parse_status or '').strip().lower() == 'parsed' + for document in prefetched_documents + ) + else: + document_count = db.session.query(ShippingOrderDocument.id).filter( + *document_filters, + ).count() + parsed_document_count = db.session.query(ShippingOrderDocument.id).filter( + *document_filters, + ShippingOrderDocument.parse_status == 'parsed', + ).count() from app.models import ShippingOrderCandidate + cache = _conversation_projection_read_cache() candidate_count = ( - db.session.query(ShippingOrderCandidate.id) - .filter( - ShippingOrderCandidate.intake_id == int(intake.id), - ShippingOrderCandidate.is_current_version.is_(True), - ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')), + cache['candidate_count_by_intake_id'].get(int(intake.id), 0) + if cache is not None else ( + db.session.query(ShippingOrderCandidate.id) + .filter( + ShippingOrderCandidate.intake_id == int(intake.id), + ShippingOrderCandidate.is_current_version.is_(True), + ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')), + ) + .count() ) - .count() ) subject = str(email.get('subject') or '').strip() or None filename = None @@ -483,6 +779,7 @@ def project_intake_work_item( *, submission: ShippingOrderSubmission | None = None, asset: FileAsset | None = None, + load_context: _ConversationProjectionLoadContext | None = None, ) -> dict[str, Any]: """ 将尚未建 OT(或仍在解析)的 Intake 投影为 ShippingProcessingProjection。 @@ -513,7 +810,7 @@ def project_intake_work_item( getattr(intake, 'updated_at', None) or getattr(intake, 'created_at', None) ) - legacy_actions = _intake_available_actions(intake) + authorized_actions = _intake_authorized_actions(intake) intake_status = _intake_processing_status(intake) intake_stage = _intake_processing_stage(intake) extraction_status = str( @@ -576,11 +873,13 @@ def project_intake_work_item( 'progress_version': progress_version, 'last_activity_at': _iso(last_activity) or '', 'current_gate': _intake_current_gate(intake, asset=asset), - 'available_actions': legacy_actions, - 'source_summary': _intake_source_summary(intake, asset=asset), + 'available_actions': authorized_actions, + 'source_summary': _intake_source_summary( + intake, asset=asset, load_context=load_context, + ), 'child_order_tasks': [], }, - legacy_actions=legacy_actions, + authorized_actions=authorized_actions, ) # Intake 与 OT 同样是 Processing Projection 的输出边界。补齐用户态字段后, # 会话卡无需从 legacy status 再次猜测“处理中/待人工”。 @@ -602,6 +901,7 @@ def project_intake_work_item( intake=intake, order_task_children=[], unit_by_document_id=unit_by_document_id, + load_context=load_context, ) aggregate_states = [ str(child.get('user_status') or child.get('status') or '').strip().lower() @@ -677,31 +977,45 @@ def _latest_intake_run_unit_outcomes( intake: ShippingOrderIntake, ) -> dict[int, ShippingOrderProcessingUnit]: """按文件读取 Intake 最新冻结 Unit 裁决,兼容部分重解析的跨 Run 谱系。""" + cache = _conversation_projection_read_cache() links = ( - ShippingOrderProcessingRunIntake.query.join( - ShippingOrderProcessingRun, - ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id, + cache['run_links_by_intake_id'].get(int(intake.id), []) + if cache is not None else ( + ShippingOrderProcessingRunIntake.query.join( + ShippingOrderProcessingRun, + ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id, + ) + .filter(ShippingOrderProcessingRunIntake.intake_id == int(intake.id)) + .order_by( + ShippingOrderProcessingRun.created_at.desc(), + ShippingOrderProcessingRunIntake.created_at.desc(), + ) + .all() ) - .filter(ShippingOrderProcessingRunIntake.intake_id == int(intake.id)) - .order_by( - ShippingOrderProcessingRun.created_at.desc(), - ShippingOrderProcessingRunIntake.created_at.desc(), - ) - .all() ) outcomes: dict[int, ShippingOrderProcessingUnit] = {} for link in links: - run = db.session.get(ShippingOrderProcessingRun, int(link.run_id)) + run = ( + cache['runs_by_id'].get(int(link.run_id)) + if cache is not None else db.session.get( + ShippingOrderProcessingRun, int(link.run_id), + ) + ) plan = run.extraction_plan if run is not None else None if plan is None: continue units = ( - ShippingOrderProcessingUnit.query.filter( - ShippingOrderProcessingUnit.plan_id == int(plan.id), - ShippingOrderProcessingUnit.intake_id == int(intake.id), + [ + unit for unit in (getattr(plan, 'units', []) or []) + if int(unit.intake_id) == int(intake.id) + ] if cache is not None else ( + ShippingOrderProcessingUnit.query.filter( + ShippingOrderProcessingUnit.plan_id == int(plan.id), + ShippingOrderProcessingUnit.intake_id == int(intake.id), + ) + .order_by(ShippingOrderProcessingUnit.position.asc()) + .all() ) - .order_by(ShippingOrderProcessingUnit.position.asc()) - .all() ) # 部分重解析 Run 只包含被选中的 PDF。不能因它是全局最新 Run 就丢掉 # 兄弟文件在前一 Run 的开放 Case/失败裁决;按 document_id 首次命中才是真实最新事实。 @@ -975,6 +1289,10 @@ def _current_open_case_for_order_task(order_task: ShippingOrderTask | None) -> S document_id = getattr(candidate, 'primary_document_id', None) if candidate is not None else None if document_id is None: return None + cache = _conversation_projection_read_cache() + if cache is not None: + case = cache['current_case_by_document_id'].get(int(document_id)) + return case if case is not None and str(case.status or '') in {'unreviewed', 'draft', 'ready'} and case.confirmed_task_id is None else None return ( ShippingOrderReviewCase.query.join( ShippingOrderReviewStream, @@ -1033,11 +1351,15 @@ def _order_task_current_gate( project_user_gate_summary, ) + cache = _conversation_projection_read_cache() execution = ( - ShippingProcessExecution.query.filter_by(review_case_id=int(open_case.id)) - .filter(ShippingProcessExecution.status != 'superseded') - .order_by(ShippingProcessExecution.id.desc()) - .first() + cache['execution_by_case_id'].get(int(open_case.id)) + if cache is not None else ( + ShippingProcessExecution.query.filter_by(review_case_id=int(open_case.id)) + .filter(ShippingProcessExecution.status != 'superseded') + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) ) if execution is not None: summary = project_user_gate_summary(execution) @@ -1228,7 +1550,7 @@ def _project_order_task_work_item( user_task_no = str(getattr(order_task, 'task_no', None) or '').strip() if not user_task_no: return None - legacy_actions = list((task_row or {}).get('available_actions') or []) + authorized_actions = list((task_row or {}).get('available_actions') or []) documents = [] snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} for intake_row in snapshot.get('intakes') or []: @@ -1280,19 +1602,34 @@ def _project_order_task_work_item( str(run.status or ''), stage=stage, ) - # 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为 - # automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。 + # 完成只接受三层可审计成功事实。旧 OT/process_status/upload_status 可能遗留 + # completed/uploaded;缺少成功 Attempt 时必须停在货代上传,不能进入完成统计。 + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + verified_upload_success = bool( + notice_for_stage is not None and has_verified_upload_success(notice_for_stage) + ) notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else '' notice_upload_status = str(getattr(notice_for_stage, 'upload_status', None) or '').strip().lower() if notice_for_stage is not None else '' notice_lifecycle = str(getattr(notice_for_stage, 'lifecycle_status', None) or '').strip().lower() if notice_for_stage is not None else '' - if ( - notice_process_status in {'uploaded', 'closed', 'completed'} - or notice_upload_status in {'uploaded', 'succeeded', 'success'} - or notice_lifecycle in {'voided', 'archived', 'deleted'} - ): + if verified_upload_success: status = 'completed' stage = 'completed' stage_label_key = 'completed' + elif notice_for_stage is not None and ( + status == 'completed' + or stage == 'completed' + or notice_process_status in {'uploaded', 'closed', 'completed'} + or notice_upload_status in {'uploaded', 'succeeded', 'success'} + ): + status = 'waiting_human' + stage = 'freight_uploading' + stage_label_key = 'freight_uploading' + elif notice_lifecycle in {'voided', 'archived', 'deleted'}: + status = 'cancelled' + # 取消/归档是终态而非完成态;保留最后业务工作面便于解释和审计回看。 + stage = 'freight_uploading' + stage_label_key = 'freight_uploading' # [BE-03] OT 上残留的 completed + 早期 stage 组合在输出前再折叠。 if status == 'completed' and stage != 'completed': status = derivation_status_for_extraction_run('completed', stage=stage) @@ -1382,6 +1719,7 @@ def _project_order_task_work_item( 'intake_no': _first_intake_no_for_run(run), 'status': status, 'stage': stage, + 'verified_upload_success': verified_upload_success if notice_for_stage is not None else None, # 与 Case.current_stage.label_key 同源;前端禁止用 stage 码直接当用户文案。 'stage_label_key': stage_label_key or ( 'waiting_system_start' if stage == 'order_creating' else stage @@ -1399,7 +1737,7 @@ def _project_order_task_work_item( 'current_gate': current_gate, # Gate 执行上下文与当前轻量节点分离,前端不得从 OT / 文件名猜写入目标。 'process_gate': process_gate, - 'available_actions': legacy_actions, + 'available_actions': authorized_actions, 'source_summary': _order_task_source_summary( run, order_task, @@ -1410,15 +1748,15 @@ def _project_order_task_work_item( _child_order_tasks_for_run(run, root_task_no=root_task_no) if is_root else [] ), }, - legacy_actions=legacy_actions, + authorized_actions=authorized_actions, invalidated_from_stage=invalidated_from_stage, excel_ready=excel_ready, + verified_upload_success=verified_upload_success if notice_for_stage is not None else None, ) # [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。 record_projection_inconsistency_audit(payload) payload.pop('projection_inconsistency_code', None) - # [T8 用户态 Projection 6 字段] 新增 status/stage/current_gate/blocking_reason/primary_action/facts, - # 同时保存旧枚举到 legacy_status/stage/current_gate,保证旧客户端兼容。 + # [T8 用户态 Projection] 由正式 Gate 与领域事实生成唯一用户态合同。 payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task) # [Phase 3] 当 work_item 关联真实 open_case(未确认 Case 或 candidate_id 回链 Case)→ @@ -1452,12 +1790,10 @@ def _project_order_task_work_item( if pre_ot_stp: payload['stage'] = 'order_creating' payload['stage_label_key'] = 'order_creating' - payload['legacy_stage'] = 'order_creating' for child in payload.get('aggregate_children') or []: if isinstance(child, dict): child['stage'] = 'order_creating' child['stage_label_key'] = 'order_creating' - child['legacy_stage'] = 'order_creating' # 五字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions if isinstance(bundle.get('user_status'), str): payload['user_status'] = bundle['user_status'] @@ -1504,7 +1840,6 @@ def _project_order_task_work_item( if pre_ot_stp: payload['user_stage'] = 'pre_ot_stp' payload['user_current_gate_code'] = 'task_creation' - payload['legacy_status'] = payload.get('status') payload['status'] = 'failed' for child in payload.get('aggregate_children') or []: if isinstance(child, dict): @@ -1512,7 +1847,6 @@ def _project_order_task_work_item( child['user_current_gate_code'] = 'task_creation' child['stage'] = 'order_creating' child['stage_label_key'] = 'order_creating' - child['legacy_stage'] = 'order_creating' child['current_gate'] = dict(payload.get('current_gate') or {}) except Exception: # noqa: BLE001 # Review bundle 是当前用户动作的权威来源;读取失败时不得静默回退到 @@ -1588,12 +1922,10 @@ def _project_order_task_work_item( if str(payload.get('user_stage') or '').strip().lower() == 'pre_ot_stp': payload['stage'] = 'order_creating' payload['stage_label_key'] = 'order_creating' - payload['legacy_stage'] = 'order_creating' for child in payload.get('aggregate_children') or []: if isinstance(child, dict) and str(child.get('user_stage') or '').strip().lower() == 'pre_ot_stp': child['stage'] = 'order_creating' child['stage_label_key'] = 'order_creating' - child['legacy_stage'] = 'order_creating' return payload @@ -1677,8 +2009,14 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str: item: order_task 工作项 dict。 Returns: - needs_action | processing | completed 之一。 + needs_action | processing | completed | history 之一。 """ + is_unverified_upload_terminal = ( + item.get('verified_upload_success') is False + and str(item.get('user_status') or item.get('status') or '').strip().lower() == 'completed' + ) + if is_unverified_upload_terminal: + return 'needs_action' user_group = str(item.get('user_group') or '').strip().lower() if user_group in {'failed', 'waiting_human'}: return 'needs_action' @@ -1693,12 +2031,18 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str: 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'}: + if user_status in {'cancelled', 'archived', 'voided', 'deleted'}: + return 'history' + if user_status == 'completed': 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 in {'cancelled', 'archived', 'voided', 'deleted'} or stage in { + 'cancelled', 'archived', 'voided', 'deleted', + }: + return 'history' if status == 'completed' or stage == 'completed': return 'completed' return 'processing' @@ -1717,6 +2061,8 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> 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 item.get('verified_upload_success') is False and user_status == 'completed': + return 'pending_review' if user_status == 'waiting_human': return 'pending_review' if user_status == 'retryable': @@ -1761,11 +2107,27 @@ def _eml_aggregate_user_group( return 'processing' +def _intake_parse_case_primary_action(*, reparse_authorized: bool) -> dict[str, Any] | None: + """裁决无有效 Candidate 的 Review Case 在接收解析阶段的文件主动作。 + + 阶段按钮只负责打开工作台;文件行主动作必须是服务端已经授权的重解析命令。 + 摘要和详情投影共用本函数,防止首屏将导航动作提升为主 CTA。 + """ + if not reparse_authorized: + return None + return { + 'code': 'reparse', + 'variant': 'primary', + 'label_key': 'shipping.actions.reparse', + } + + def _eml_aggregate_document_children( *, intake: ShippingOrderIntake | None, order_task_children: list[dict[str, Any]], unit_by_document_id: dict[int, ShippingOrderProcessingUnit] | None = None, + load_context: _ConversationProjectionLoadContext | None = None, ) -> list[dict[str, Any]]: """以 EML Intake 的真实业务附件构建展开叶子,并仅叠加已存在 OT 的领域裁决。 @@ -1788,12 +2150,16 @@ def _eml_aggregate_document_children( ] documents = ( - ShippingOrderDocument.query.filter( - ShippingOrderDocument.intake_id == int(intake.id), - ShippingOrderDocument.document_type != 'email_body', + load_context.documents_by_intake_id.get(int(intake.id), []) + if load_context is not None + else ( + ShippingOrderDocument.query.filter( + ShippingOrderDocument.intake_id == int(intake.id), + ShippingOrderDocument.document_type != 'email_body', + ) + .order_by(ShippingOrderDocument.id.asc()) + .all() ) - .order_by(ShippingOrderDocument.id.asc()) - .all() ) if not documents: return [ @@ -1824,7 +2190,13 @@ def _eml_aggregate_document_children( # Unit 是附件级最终事实。Run 只是兄弟 Unit 的执行容器,绝不能因某一份 # PDF 失败覆盖同 Run 其它 review_required 附件的人工复核入口。 unit_run = getattr(getattr(unit, 'plan', None), 'run', None) if unit is not None else None - unit_failed = unit_status == 'failed' + # Run 已终止失败时,尚未同步的 Unit.review_required 是陈旧中间态, + # 不能把失败文件误投影为待人工;后续重解析 Run 仍按最新谱系覆盖。 + unit_run_failed = str( + getattr(unit_run, 'status', '') or '', + ).strip().lower() == 'failed' + unit_failed = unit_status == 'failed' or unit_run_failed + unit_reparse_authorized = unit_status == 'failed' failure_reason_code = ( str( getattr(unit_run, 'error_code', None) @@ -1841,15 +2213,23 @@ def _eml_aggregate_document_children( # Case 是候选落库后的正式人工阶段事实;Unit 保留 candidate_ready 不能让 # EML 聚合退回「接收解析」。当前 Case 可来自局部重解析后的新 Unit, # 故必须按原 Document 的 Stream 指针查找,不能按旧 unit_id 反查。 + cache = _conversation_projection_read_cache() review_case = ( - ShippingOrderReviewCase.query.join( - ShippingOrderReviewStream, - ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, - ).filter( - ShippingOrderReviewStream.document_id == int(document.id), - ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming')), - ).one_or_none() + cache['current_case_by_document_id'].get(int(document.id)) + if cache is not None else ( + ShippingOrderReviewCase.query.join( + ShippingOrderReviewStream, + ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, + ).filter( + ShippingOrderReviewStream.document_id == int(document.id), + ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming')), + ).one_or_none() + ) ) + if review_case is not None and str(review_case.status or '') not in { + 'unreviewed', 'draft', 'ready', 'confirming', + }: + review_case = None review_required = review_required or review_case is not None review_bundle: dict[str, Any] | None = None if review_case is not None: @@ -1904,22 +2284,16 @@ def _eml_aggregate_document_children( 'details': {}, } if 'reparse' in review_actions: - review_primary = { - 'code': 'reparse', - 'variant': 'primary', - 'label_key': 'shipping.actions.reparse', - } + review_primary = _intake_parse_case_primary_action( + reparse_authorized=True, + ) else: - # 防御性兜底:Case 未授予 reparse 时只保留其正式裁决动作, - # 不从接收解析状态反推或构造重解析权限。 - action_code = str(explained.get('next_action') or 'open_order_review').strip() - review_primary = { - 'code': action_code, - 'variant': 'primary', - 'label_key': f'shipping.actions.{action_code}', - } - review_actions = [action_code] - elif unit_failed: + # 没有当前有效 Candidate 时,Case 仍属于解析处置阶段。 + # 不能把 explainability 的 next_action(尤其是 open_order_review) + # 当成订单复核授权,否则会渲染出按钮但在工作台被前置阶段守卫拒绝。 + review_primary = None + review_actions = [] + elif unit_reparse_authorized: # 尚未形成 Case 的失败附件只能由后端授权对所属 Run 发起重解析。 # 前端仅消费这份 reparse 动作及下发的 Run 身份,绝不按失败状态补造。 review_primary = { @@ -1929,9 +2303,12 @@ def _eml_aggregate_document_children( } review_actions = ['reparse'] run = ( - db.session.get(ShippingOrderProcessingRun, int(review_case.run_id)) - if review_case is not None - else unit_run + ( + cache['runs_by_id'].get(int(review_case.run_id)) + if cache is not None else db.session.get( + ShippingOrderProcessingRun, int(review_case.run_id), + ) + ) if review_case is not None else unit_run ) leaf = { 'work_item_type': 'document', @@ -1953,7 +2330,7 @@ def _eml_aggregate_document_children( 'progress_version': int(getattr(intake, 'progress_version', None) or 1), 'last_activity_at': _iso(document.updated_at) or _iso(intake.updated_at) or '', 'current_gate': review_gate if review_case is not None else None, - 'available_actions': review_actions if (review_case is not None or unit_failed) else [], + 'available_actions': review_actions if (review_case is not None or unit_reparse_authorized) else [], 'blocking_reason': ( {'code': failure_reason_code, 'details': {}} if unit_failed else @@ -1969,7 +2346,7 @@ def _eml_aggregate_document_children( # 附件只有明确授予 reparse 时才展示当前阶段,不能由前端按失败态猜测。 'intake_parse_authorized': bool( (review_case is not None and not has_current_candidate) - or (unit_failed and 'reparse' in review_actions) + or (unit_reparse_authorized and 'reparse' in review_actions) ), 'child_order_tasks': [], } @@ -1990,32 +2367,16 @@ def _eml_aggregate_document_children( has_current_candidate ) leaf['source_summary'] = summary - # 有/无预建 OT 的 EML 附件都在这里汇合。批次中心的文件级主动作只能 - # 是生命周期入口;create/edit/validate 是 Case 内部处置,必须在工作台内 - # 呈现。只保留正式 Process Gate 的主动作;Case 内部码(例如 - # order_review_build)即使带 next_action 也不能夺走批次入口。 - leaf_case_no = str(leaf.get('case_no') or '').strip() - leaf_gate = leaf.get('current_gate') if isinstance(leaf.get('current_gate'), dict) else {} - leaf_primary = leaf.get('primary_action') if isinstance(leaf.get('primary_action'), dict) else {} - from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET - - has_formal_gate = str(leaf_gate.get('gate_code') or '').strip() in PROCESS_GATE_CODE_SET - if ( - leaf_case_no - and not has_formal_gate - and str(leaf_primary.get('code') or '').strip() in {'create_draft', 'edit_draft', 'validate'} - ): - leaf['primary_action'] = { - 'code': 'open_order_review', - 'variant': 'primary', - 'label_key': 'shipping.actions.open_order_review', - } + # 文件主动作保留 Case / Gate 已裁决的真实动作码。生命周期导航由 + # ui_state.lifecycle_entries 单独表达,不能为消除重复而篡改业务动作。 result.append(_with_processing_ui_state(leaf)) return result def _aggregate_eml_order_task_work_items( work_items: list[dict[str, Any]], + *, + load_context: _ConversationProjectionLoadContext | None = None, ) -> list[dict[str, Any]]: """ 按 Intake 聚合同一 EML 的多个 order_task 工作项。 @@ -2056,7 +2417,11 @@ def _aggregate_eml_order_task_work_items( result = list(passthrough) for intake_no, children in grouped.items(): # EML 的计数、状态及展开明细必须基于同一组业务附件,而不是仅基于已创建 OT。 - intake = ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none() + intake = ( + load_context.intakes_by_no.get(intake_no) + if load_context is not None + else ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none() + ) aggregate_children = _eml_aggregate_document_children( intake=intake, order_task_children=children, @@ -2064,6 +2429,7 @@ def _aggregate_eml_order_task_work_items( _latest_intake_run_unit_outcomes(intake) if intake is not None else None ), + load_context=load_context, ) states = [_state(item) for item in aggregate_children] upload_states = [_upload_state(item) for item in aggregate_children] @@ -2166,13 +2532,11 @@ def _aggregate_eml_order_task_work_items( candidate_runs = ShippingOrderProcessingRun.query.filter( ShippingOrderProcessingRun.run_no.in_(candidate_run_nos), ).all() - from app.services.shipping_notice.order_review_disposition_service import ( - has_reparseable_batch_documents, - ) - if any( str(run.status or '') in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} - and has_reparseable_batch_documents(user_id=int(run.user_id), run=run) + and _has_reparseable_batch_documents_for_projection( + run=run, load_context=load_context, + ) for run in candidate_runs ) and 'reparse_batch' not in aggregate['available_actions']: aggregate['available_actions'].append('reparse_batch') @@ -2334,16 +2698,10 @@ def _conversation_task_row_from_work_item( 'document_id': source_document_id, 'filename': filename, }) - user_group = str(item.get('user_group') or '').strip().lower() - if not user_group: - user_status = str(item.get('user_status') or item.get('status') or '').strip().lower() - user_group = ( - 'failed' if user_status in {'failed', 'retryable'} - else 'waiting_human' if user_status in {'waiting_human', 'waiting_review'} - else 'completed' if user_status == 'completed' - else 'cancelled' if user_status == 'cancelled' - else 'processing' - ) + # status_groups 与文件统计必须消费同一用户态裁决。尤其是旧载荷的 + # completed + verified_upload_success=False,顶层已降级为待处理,不能在 + # status_groups 又显示为 completed。 + user_group = _batch_user_group(item) return { 'user_task_no': user_task_no, 'submission_ordinal': None, @@ -2403,10 +2761,9 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: current_gate=( item.get('current_gate') if isinstance(item.get('current_gate'), dict) - else {'gate_code': item.get('user_current_gate_code')} + else None ), blocking_reason=item.get('blocking_reason') if isinstance(item.get('blocking_reason'), dict) else None, - legacy_stage=str(item.get('user_stage') or item.get('stage') or ''), # root_order_task_no 只是导航身份;必须有当前 Candidate 或正式通知事实才开放入口。 has_candidate_context=bool( int(source_summary.get('candidate_count') or 0) > 0 @@ -2415,6 +2772,8 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: ), # 空 Candidate 的接收解析只认后端持久化 Case 显式授予的上下文。 has_intake_parse_context=bool(item.get('intake_parse_authorized')), + verified_upload_success=bool(item.get('verified_upload_success')), + processing_stage=str(item.get('user_stage') or item.get('stage') or '').strip() or None, ) lifecycle_stage = lifecycle['lifecycle_stage'] if primary is not None: @@ -2472,6 +2831,30 @@ def _with_processing_ui_state(item: dict[str, Any]) -> dict[str, Any]: return projected +def _strip_legacy_action_fields_for_response(value: Any) -> Any: + """在 API 边界移除已下线的顶层动作镜像。 + + 内部投影仍可用 ``primary_action`` / ``available_actions`` 选择 EML 当前代表项, + 但对外唯一动作合同是 ``ui_state``。在最终序列化前剥离镜像,防止新旧合同再次被 + 客户端混用;递归处理 EML 子附件和会话状态组。 + + Args: + value: 已完成全部聚合的公开 DTO 片段。 + + Returns: + 不含旧顶层动作字段、其余结构不变的公开 DTO。 + """ + if isinstance(value, list): + return [_strip_legacy_action_fields_for_response(item) for item in value] + if not isinstance(value, dict): + return value + return { + key: _strip_legacy_action_fields_for_response(item) + for key, item in value.items() + if key not in {'primary_action', 'available_actions'} + } + + def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) -> str | None: """将已授权动作映射到工作台展示面;未知动作不生成导航目标。""" code = str(action_code or '').strip().lower() @@ -2491,24 +2874,25 @@ def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) - 'download_excel', 'open_manual_upload', 'wait_manual_upload', 'mark_manual_uploaded', 'retry_freight_upload_rpa', 'retry_upload', }: - return 'upload_complete' + return 'freight_upload' # 历史 Review 投影的 view 与 view_result 同为只读查看入口;必须由后端附带 # 当前已裁决的工作台目标,前端不得因缺失目标误判为“前置阶段未完成”。 return lifecycle_stage if code in {'view', 'view_result', 'view_record'} else None def _lifecycle_stage_from_item(item: dict[str, Any]) -> str | None: - """批次统计使用与任务详情相同的共享生命周期裁决,不维护独立映射。""" + """批次统计复用共享裁决器,并优先映射项目已写入的文件阶段事实。""" return project_lifecycle( current_gate=( item.get('current_gate') if isinstance(item.get('current_gate'), dict) - else {'gate_code': item.get('user_current_gate_code')} + else None ), blocking_reason=item.get('blocking_reason') if isinstance(item.get('blocking_reason'), dict) else None, - legacy_stage=str(item.get('user_stage') or item.get('stage') or ''), has_candidate_context=bool(item.get('has_formal_ot') or item.get('shipping_notice_no')), has_intake_parse_context=bool(item.get('intake_parse_authorized')), + verified_upload_success=bool(item.get('verified_upload_success')), + processing_stage=str(item.get('user_stage') or item.get('stage') or '').strip() or None, )['lifecycle_stage'] @@ -2516,7 +2900,7 @@ def _current_file_representatives(work_items: list[dict[str, Any]]) -> list[dict """为批次投影选择每个业务文件唯一的当前代表项。 核心逻辑:EML 聚合根不参与文件口径;同一文件的旧 Run、旧 OT 或历史失败 - 投影只保留最新活动项。四阶段、文件统计、未分类统计必须共用本函数,避免一个 + 投影只保留最新活动项。五阶段、文件统计、未分类统计必须共用本函数,避免一个 PDF 同时被计入多个阶段或多个状态组。 Args: @@ -2690,13 +3074,9 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> candidate_runs = ShippingOrderProcessingRun.query.filter( ShippingOrderProcessingRun.run_no.in_(candidate_run_nos), ).all() - from app.services.shipping_notice.order_review_disposition_service import ( - has_reparseable_batch_documents, - ) - if any( str(run.status or '') in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} - and has_reparseable_batch_documents(user_id=int(run.user_id), run=run) + and _has_reparseable_batch_documents_for_projection(run=run) for run in candidate_runs ) and 'reparse_batch' not in clone['available_actions']: clone['available_actions'].append('reparse_batch') @@ -2705,11 +3085,11 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> return displayed -def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]: - """从最终用户态工作项构建批次四阶段主进度。 +def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]: + """从最终用户态工作项构建批次五阶段主进度。 业务阶段映射和状态优先级只在后端维护;15 个技术节点仍附着在单项诊断字段, - 绝不要求前端通过 stage 索引再计算四阶段。 + 绝不要求前端通过 stage 索引再计算业务阶段。 """ ranked_items = sorted( _current_file_representatives(work_items), @@ -2733,17 +3113,21 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, 'failed': 0, 'blocking_reason': None, } - for code, _ in LIFECYCLE_STAGE_RANGES + for code in LIFECYCLE_STAGE_CODES } for item in ranked_items: lifecycle_stage = _lifecycle_stage_from_item(item) if lifecycle_stage is None: continue + # 历史取消/归档只能保留在 history/status_groups,既不推动任一工作面, + # 也不得作为「通知完成」的分子或分母。 + item_group = _batch_user_group(item) + if item_group in {'cancelled', 'archived'}: + continue summary = stage_summaries[lifecycle_stage] summary['total'] += 1 - # 四阶段与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run + # 生命周期与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run # 兼容投影中残留为 running,不能把后端已裁决为“待处理”的文件再显示为处理中。 - item_group = _batch_user_group(item) if item_group == 'completed': summary['completed'] += 1 continue @@ -2763,7 +3147,7 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, } or None nodes: list[dict[str, Any]] = [] - for code, _ in LIFECYCLE_STAGE_RANGES: + for code in LIFECYCLE_STAGE_CODES: summary = stage_summaries[code] # 卡片状态只由本阶段聚合事实计算,禁止由其他阶段的优先文件反向影响。 status = ( @@ -2782,7 +3166,7 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, def _unclassified_summary(work_items: list[dict[str, Any]]) -> dict[str, int]: - """统计无法归入四阶段的业务文件,避免批次摘要与文件清单口径不一致。""" + """统计无法归入业务生命周期的文件,避免批次摘要与文件清单口径不一致。""" return { 'count': sum( 1 for item in _current_file_representatives(work_items) @@ -2823,7 +3207,7 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An 优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造 人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。 """ - # 批次主状态与文件计数、四阶段必须消费同一份“每文件唯一当前代表项”。 + # 批次主状态与文件计数、五阶段必须消费同一份“每文件唯一当前代表项”。 # 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成 # “数字是当前、按钮却指向历史”的第二裁决源。 ranked = sorted( @@ -2861,27 +3245,23 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An def _batch_user_group(item: dict[str, Any]) -> str: - """归一批次统计使用的互斥用户分组,优先消费领域投影已裁决的 user_group。""" + """返回领域投影已经裁决的唯一用户分组,缺失时保持未分类。""" group = str(item.get('user_group') or '').strip().lower() - if group in {'failed', 'waiting_human', 'processing', 'completed'}: + if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'}: return group - status = str(item.get('user_status') or item.get('status') or '').strip().lower() - if status in {'failed', 'retryable'}: - return 'failed' - if status in {'waiting_human', 'waiting_review', 'idle'}: - return 'waiting_human' - if status in {'completed', 'cancelled'}: - return 'completed' - return 'processing' + return 'unclassified' def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]: """按唯一当前业务文件统计互斥状态组,EML 容器永不计数。""" + # 已取消/归档文件保留在历史列表,但不构成当前任务完成率的分母或分子。 groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0} for item in _current_file_representatives(work_items): group = _batch_user_group(item) summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {} filename = str(summary.get('filename') or '').strip().lower() + if group not in groups: + continue if not filename.endswith('.eml') and (filename or int(summary.get('document_id') or 0)): groups[group] += 1 return { @@ -2900,7 +3280,7 @@ def _conversation_processing_from_work_items( recent_task_no: str | None = None, ) -> dict[str, Any]: """ - 由最终 work_items 重建 conversation_processing 兼容块(含兄弟 OT)。 + 由最终 work_items 构建完整详情投影。 核心逻辑:仅消费 order_task 项;按 status/stage 分组;文件总数优先按 source_summary.document_id 去重,避免异常兄弟 OT 重复累计同一 PDF; @@ -2914,12 +3294,9 @@ def _conversation_processing_from_work_items( Returns: 与 project_conversation_processing 同形的 dict。 """ - # 文件清单必须与批次统计、四阶段和 CTA 使用相同的当前文件代表项,同时 + # 文件清单必须与批次统计、五阶段和 CTA 使用相同的当前文件代表项,同时 # 保留 EML 父卡,避免附件失去邮件归属或在多个状态组重复出现。 display_work_items = _display_work_items_from_current_files(work_items) - needs_action: list[dict[str, Any]] = [] - processing: list[dict[str, Any]] = [] - completed: list[dict[str, Any]] = [] all_rows: list[dict[str, Any]] = [] focused = str(focused_task_no or '').strip() or None recent = str(recent_task_no or '').strip() or None @@ -2933,25 +3310,30 @@ def _conversation_processing_from_work_items( all_rows.append(row) if recent and row['user_task_no'] == recent: row['recently_created'] = True - bucket = row['group'] - if bucket == 'needs_action': - needs_action.append(row) - elif bucket == 'completed': - completed.append(row) - else: - processing.append(row) - def _sort_key(entry: dict[str, Any]) -> str: return str(entry.get('last_activity_at') or entry.get('created_at') or '') - needs_action.sort(key=_sort_key, reverse=True) - processing.sort(key=_sort_key, reverse=True) - completed.sort(key=_sort_key, reverse=True) - total = len(needs_action) + len(processing) + len(completed) + status_groups = { + 'failed': [row for row in all_rows if row.get('user_group') == 'failed'], + 'waiting_human': [row for row in all_rows if row.get('user_group') == 'waiting_human'], + 'processing': [row for row in all_rows if row.get('user_group') == 'processing'], + 'completed': [row for row in all_rows if row.get('user_group') == 'completed'], + 'cancelled': [row for row in all_rows if row.get('user_group') == 'cancelled'], + 'archived': [row for row in all_rows if row.get('user_group') == 'archived'], + } + for rows in status_groups.values(): + rows.sort(key=_sort_key, reverse=True) + total = sum(len(rows) for rows in status_groups.values()) # [STEP 2] 会话文件数是业务 PDF 去重数,不是各任务 Run 文档数的简单求和。 + # 仅以当前且仍活跃的业务文件兜底;取消/归档的历史文档不能因 + # source_summary 仍保留 document_id 而重新进入完成率分母。 + active_file_items = [ + item for item in _current_file_representatives(work_items) + if _batch_user_group(item) in {'failed', 'waiting_human', 'processing', 'completed'} + ] document_ids = { int(summary.get('document_id')) - for item in work_items + for item in active_file_items if isinstance(item, dict) and str(item.get('work_item_type') or '') == 'order_task' for child in (item.get('aggregate_children') or [item]) if isinstance(child, dict) @@ -2962,40 +3344,520 @@ def _conversation_processing_from_work_items( total_files = file_counts['total_files'] or ( len(document_ids) if document_ids - else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed) + else sum(int(row.get('file_count') or 0) for key, rows in status_groups.items() + if key in {'failed', 'waiting_human', 'processing', 'completed'} for row in rows) ) + lifecycle_nodes = _batch_lifecycle_nodes(work_items) return { 'projection_version': 1, 'summary': { 'total_tasks': total, 'total_files': total_files, - 'processing': len(processing), - 'needs_action': len(needs_action), - 'completed': len(completed), - 'history': 0, + 'processing': len(status_groups['processing']), + 'needs_action': len(status_groups['failed']) + len(status_groups['waiting_human']), + 'completed': len(status_groups['completed']), + 'history': len(status_groups['cancelled']) + len(status_groups['archived']), **file_counts, }, 'focused_task_no': focused, 'recent_task_no': recent, - 'needs_action': needs_action, - 'processing': processing, - 'completed': completed, - 'history': [], - 'status_groups': { - 'failed': [row for row in all_rows if row.get('user_group') == 'failed'], - 'waiting_human': [row for row in all_rows if row.get('user_group') == 'waiting_human'], - 'processing': [row for row in all_rows if row.get('user_group') == 'processing'], - 'completed': [row for row in all_rows if row.get('user_group') == 'completed'], - 'cancelled': [row for row in all_rows if row.get('user_group') == 'cancelled'], - 'archived': [row for row in all_rows if row.get('user_group') == 'archived'], - }, - 'four_stage_nodes': _batch_four_stage_nodes(work_items), + 'status_groups': status_groups, + # 新客户端只消费 lifecycle_nodes;旧字段在一个发布周期内原样兼容,避免 + # 会话卡、批次中心和嵌入式消费者在灰度期间看到不同阶段数。 + 'lifecycle_nodes': lifecycle_nodes, 'unclassified_summary': _unclassified_summary(work_items), 'ui_state': _batch_ui_state_from_items(work_items), 'output_artifacts': _batch_output_artifacts(work_items), } +def project_conversation_processing_summary( + *, + user_id: int, + conversation_id: str, + agent_id: int | None = None, + focused_task_no: str | None = None, + recent_task_no: str | None = None, +) -> dict[str, Any]: + """返回会话首屏的轻量进度读模型。 + + 首屏只需要后端已裁决的状态→EML→PDF树、统计和已授权动作标识;完整 + work_items、Gate 执行上下文与旧四组镜像属于详情读模型,必须按需通过 + work-item 接口读取。摘要仅批量读取正式 Gate 的最小状态列,绝不加载 + Attempt、Run JSON 或详情上下文,避免同一任务在首屏响应中重复传输三次。 + """ + del agent_id + normalized = str(conversation_id or '').strip() + if not normalized: + raise ValidationError('conversation_id is required') + + # 首屏严禁加载 Run JSON 快照、Plan/Unit 或 Gate Attempt;它们只属于详情读取。 + # 摘要只读取状态树和操作裁决所需列;正文、解析结果和重复检测 JSON + # 属于详情读模型,禁止在首屏查询中触发 ORM 反序列化。 + intakes = ShippingOrderIntake.query.options(load_only( + ShippingOrderIntake.id, + ShippingOrderIntake.intake_no, + ShippingOrderIntake.asset_id, + ShippingOrderIntake.source_type, + ShippingOrderIntake.updated_at, + )).filter( + ShippingOrderIntake.user_id == int(user_id), + ShippingOrderIntake.conversation_id == normalized, + ShippingOrderIntake.purpose == 'shipping_notice', + ).order_by(ShippingOrderIntake.updated_at.desc(), ShippingOrderIntake.id.desc()).all() + intake_ids = [int(row.id) for row in intakes] + documents_by_intake: dict[int, list[ShippingOrderDocument]] = {item_id: [] for item_id in intake_ids} + if intake_ids: + for document in ShippingOrderDocument.query.options(load_only( + ShippingOrderDocument.id, + ShippingOrderDocument.intake_id, + ShippingOrderDocument.filename, + ShippingOrderDocument.parse_status, + ShippingOrderDocument.classification, + ShippingOrderDocument.order_extraction_status, + ShippingOrderDocument.order_extraction_error_code, + )).filter( + ShippingOrderDocument.intake_id.in_(intake_ids), + ShippingOrderDocument.document_type != 'email_body', + ).order_by(ShippingOrderDocument.intake_id.asc(), ShippingOrderDocument.id.asc()).all(): + documents_by_intake.setdefault(int(document.intake_id), []).append(document) + asset_ids = [int(item.asset_id) for item in intakes if item.asset_id] + assets = { + int(asset.id): asset + for asset in (FileAsset.query.options(load_only( + FileAsset.id, + FileAsset.original_filename, + )).filter(FileAsset.id.in_(asset_ids)).all() if asset_ids else []) + } + candidates = ShippingOrderCandidate.query.options(load_only( + ShippingOrderCandidate.id, + ShippingOrderCandidate.primary_document_id, + ShippingOrderCandidate.order_extraction_run_id, + ShippingOrderCandidate.po_number, + )).filter( + ShippingOrderCandidate.intake_id.in_(intake_ids) if intake_ids else False, + ShippingOrderCandidate.is_current_version.is_(True), + ).all() + candidate_by_document_id = { + int(candidate.primary_document_id): candidate + for candidate in candidates + if candidate.primary_document_id is not None + } + candidate_ids = [int(candidate.id) for candidate in candidates] + tasks_by_candidate_id = { + int(task.candidate_id): task + for task in ShippingOrderTask.query.options(load_only( + ShippingOrderTask.id, + ShippingOrderTask.candidate_id, + ShippingOrderTask.shipping_notice_id, + ShippingOrderTask.task_no, + ShippingOrderTask.extraction_run_id, + ShippingOrderTask.status, + ShippingOrderTask.stage, + ShippingOrderTask.error_code, + ShippingOrderTask.updated_at, + )).filter( + ShippingOrderTask.user_id == int(user_id), + ShippingOrderTask.conversation_id == normalized, + ShippingOrderTask.candidate_id.in_(candidate_ids) if candidate_ids else False, + ).order_by(ShippingOrderTask.updated_at.desc(), ShippingOrderTask.id.desc()).all() + if task.candidate_id is not None + } + # 正式 Notice / Execution / 当前 Gate 是建单后业务阶段的唯一真相。摘要以 + # 固定三次批量查询取得最小列,不触碰 Gate Attempt、详情 JSON 或关系加载。 + task_ids = [int(task.id) for task in tasks_by_candidate_id.values()] + direct_notice_ids = { + int(task.shipping_notice_id) + for task in tasks_by_candidate_id.values() + if task.shipping_notice_id is not None + } + notices_by_id: dict[int, ShippingNotice] = {} + notices_by_order_task_id: dict[int, ShippingNotice] = {} + if task_ids: + for notice in ShippingNotice.query.options(load_only( + ShippingNotice.id, + ShippingNotice.order_task_id, + ShippingNotice.active_process_execution_id, + )).filter(ShippingNotice.order_task_id.in_(task_ids)).all(): + notices_by_id[int(notice.id)] = notice + if notice.order_task_id is not None: + notices_by_order_task_id[int(notice.order_task_id)] = notice + missing_direct_notice_ids = direct_notice_ids.difference(notices_by_id) + if missing_direct_notice_ids: + for notice in ShippingNotice.query.options(load_only( + ShippingNotice.id, + ShippingNotice.order_task_id, + ShippingNotice.active_process_execution_id, + )).filter(ShippingNotice.id.in_(missing_direct_notice_ids)).all(): + notices_by_id[int(notice.id)] = notice + if notice.order_task_id is not None: + notices_by_order_task_id.setdefault(int(notice.order_task_id), notice) + notice_ids = list(notices_by_id) + executions_by_id: dict[int, ShippingProcessExecution] = {} + latest_execution_by_notice_id: dict[int, ShippingProcessExecution] = {} + if notice_ids: + for execution in ShippingProcessExecution.query.options(load_only( + ShippingProcessExecution.id, + ShippingProcessExecution.task_id, + ShippingProcessExecution.status, + ShippingProcessExecution.current_gate_code, + )).filter( + ShippingProcessExecution.task_id.in_(notice_ids), + ShippingProcessExecution.status != 'superseded', + ).order_by(ShippingProcessExecution.id.desc()).all(): + executions_by_id[int(execution.id)] = execution + if execution.task_id is not None: + latest_execution_by_notice_id.setdefault(int(execution.task_id), execution) + current_gate_codes = { + str(execution.current_gate_code).strip() + for execution in executions_by_id.values() + if str(execution.current_gate_code or '').strip() + } + gates_by_execution_and_code: dict[tuple[int, str], ShippingProcessGate] = {} + if executions_by_id and current_gate_codes: + for gate in ShippingProcessGate.query.options(load_only( + ShippingProcessGate.execution_id, + ShippingProcessGate.gate_code, + ShippingProcessGate.status, + ShippingProcessGate.blocking_reason_code, + ShippingProcessGate.next_action_code, + )).filter( + ShippingProcessGate.execution_id.in_(list(executions_by_id)), + ShippingProcessGate.gate_code.in_(current_gate_codes), + ).all(): + gates_by_execution_and_code[(int(gate.execution_id), str(gate.gate_code))] = gate + + def _current_gate_for_task(task: ShippingOrderTask | None) -> dict[str, str] | None: + """返回摘要所需的正式当前 Gate;只消费当前 Execution 的最小持久化列。""" + if task is None: + return None + notice = ( + notices_by_id.get(int(task.shipping_notice_id)) + if task.shipping_notice_id is not None + else notices_by_order_task_id.get(int(task.id)) + ) + if notice is None: + return None + execution = ( + executions_by_id.get(int(notice.active_process_execution_id)) + if notice.active_process_execution_id is not None + else latest_execution_by_notice_id.get(int(notice.id)) + ) + if execution is None: + return None + gate_code = str(execution.current_gate_code or '').strip() + gate = gates_by_execution_and_code.get((int(execution.id), gate_code)) if gate_code else None + if gate is None: + return None + return { + 'gate_code': str(gate.gate_code), + 'status': str(gate.status), + 'blocking_reason_code': str(gate.blocking_reason_code or '').strip(), + 'next_action_code': str(gate.next_action_code or '').strip(), + } + document_ids = [ + int(document.id) + for documents in documents_by_intake.values() + for document in documents + ] + current_case_by_document_id = { + int(case.document_id): case + for case in ShippingOrderReviewCase.query.join( + ShippingOrderReviewStream, + ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, + ).options(load_only( + ShippingOrderReviewCase.id, + ShippingOrderReviewCase.document_id, + ShippingOrderReviewCase.run_id, + ShippingOrderReviewCase.case_no, + ShippingOrderReviewCase.status, + ShippingOrderReviewCase.current_draft_id, + ShippingOrderReviewCase.confirmed_task_id, + )).filter( + ShippingOrderReviewStream.document_id.in_(document_ids) if document_ids else False, + ).all() + } + run_ids = { + int(run_id) + for candidate in candidates + for run_id in ( + getattr(candidate, 'order_extraction_run_id', None), + getattr(tasks_by_candidate_id.get(int(candidate.id)), 'extraction_run_id', None), + ) + if run_id is not None + } + run_ids.update( + int(case.run_id) + for case in current_case_by_document_id.values() + if case.run_id is not None + ) + runs_by_id = { + int(run.id): run + for run in ( + ShippingOrderProcessingRun.query.options(load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.run_no, + )).filter( + ShippingOrderProcessingRun.id.in_(run_ids), + ).all() + if run_ids else [] + ) + } + + def _status( + document: ShippingOrderDocument, + task: ShippingOrderTask | None, + case: ShippingOrderReviewCase | None, + current_gate: dict[str, str] | None, + ) -> tuple[str, str, str | None]: + gate_status = str((current_gate or {}).get('status') or '').strip().lower() + gate_code = str((current_gate or {}).get('gate_code') or '').strip().lower() + gate_reason = str((current_gate or {}).get('blocking_reason_code') or '').strip() or None + if gate_status == 'blocked_manual': + return 'waiting_human', gate_code, gate_reason + if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}: + return 'failed', gate_code, gate_reason or 'processing_failed' + if gate_status in {'queued', 'running', 'waiting_external', 'pending'}: + return 'running', gate_code, gate_reason + if gate_status == 'cancelled': + return 'cancelled', gate_code, gate_reason + case_status = str(getattr(case, 'status', None) or '').strip().lower() + if case is not None and case.confirmed_task_id is None and case_status in { + 'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending', + }: + return 'waiting_human', 'waiting_review', f'review_case_{case_status}' + raw = str(task.status if task is not None else document.order_extraction_status or '').strip().lower() + stage = str(task.stage if task is not None else '').strip().lower() or ( + 'document_parsing' if str(document.parse_status or '').strip().lower() != 'parsed' else 'candidate_creating' + ) + if raw in {'failed', 'parse_failed', 'technical_retrying'}: + return 'failed', stage, str(task.error_code if task is not None else document.order_extraction_error_code or 'processing_failed') + if raw in {'review_required', 'waiting_review', 'pending_review', 'waiting_human'}: + return 'waiting_human', 'waiting_review' if stage == 'candidate_creating' else stage, 'waiting_review' + if raw in {'completed', 'uploaded'}: + return 'completed', 'completed', None + if raw in {'cancelled', 'archived'}: + return raw, raw, None + return 'running', stage, None + + def _leaf( + document: ShippingOrderDocument, + task: ShippingOrderTask | None, + case: ShippingOrderReviewCase | None, + ) -> dict[str, Any]: + current_gate = _current_gate_for_task(task) + user_status, stage, reason = _status(document, task, case, current_gate) + group = 'processing' if user_status == 'running' else user_status + task_no = str(task.task_no).strip() if task is not None else None + candidate = candidate_by_document_id.get(int(document.id)) + candidate_po = str(getattr(candidate, 'po_number', None) or '').strip() if candidate is not None else '' + # 摘要只信任 Candidate 的规范化 PO 列;结构化抽取 JSON 仅在详情接口按需读取。 + # 候选存在不等于关键字段已完成解析;没有 PO 时仍停留在接收解析阶段。 + if not candidate_po and stage in {'waiting_review', 'order_review'}: + stage = 'candidate_creating' + case_status = str(getattr(case, 'status', None) or '').strip().lower() + terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'} + extraction_failed = str(document.order_extraction_status or '').strip().lower() in { + 'failed', 'parse_failed', 'technical_retrying', + } + task_no = str(task.task_no).strip() if task is not None else None + available_actions: list[str] = [] + primary_action: dict[str, Any] | None = None + intake_parse_authorized = False + gate_action = str((current_gate or {}).get('next_action_code') or '').strip() + if gate_action: + available_actions = [gate_action] + primary_action = {'code': gate_action, 'variant': 'primary'} + elif extraction_failed and case is None: + # Intake 解析失败的恢复入口只指向既有 retry API;不猜测 Case/订单入口。 + available_actions = ['retry_parse'] + primary_action = { + 'code': 'retry_parse', + 'variant': 'primary', + 'label_key': 'shipping.actions.retry_parse', + } + intake_parse_authorized = True + elif case is not None and not terminal_case: + if candidate is not None: + # 当前 Candidate 已生成后,Case 进入订单复核;仅用已批量读取的 + # current_draft_id 恢复权威业务动作,避免摘要路径逐文件加载 Case 详情。 + available_actions = ['edit_draft' if case.current_draft_id else 'create_draft'] + primary_action = project_case_primary_action( + user_status, + {'code': reason, 'i18n_key': None, 'details': None}, + available_actions, + user_stage='order_review', + ) + else: + # 无有效 Candidate 的 Case 仍在接收解析处置;阶段按钮只负责导航, + # 文件主动作必须是服务端已经授权的重解析命令。 + available_actions = ['reparse'] + primary_action = _intake_parse_case_primary_action( + reparse_authorized=True, + ) + elif task is not None or candidate_by_document_id.get(int(document.id)) is not None: + # Candidate 已形成但 Case 尚未物化时,仍保留进入订单生命周期的安全入口; + # 详情页会显示当前事实并在服务端决定是否可继续编辑。 + available_actions = ['open_order_review'] + primary_action = { + 'code': 'open_order_review', + 'variant': 'primary', + 'label_key': 'shipping.actions.open_order_review', + } + elif task_no and user_status not in {'completed', 'cancelled', 'archived'}: + # 有正式 OT 但暂时没有可执行 Gate 时,至少保留进入生命周期工作台入口。 + available_actions = ['open_order_review'] + primary_action = { + 'code': 'open_order_review', + 'variant': 'primary', + 'label_key': 'shipping.actions.open_order_review', + } + leaf = { + 'work_item_type': 'order_task', + 'work_item_no': f'DOCUMENT:{document.id}', + 'source_type': 'direct_pdf', + 'root_order_task_no': task_no, + 'run_no': ( + # Case 是接收解析工作台的稳定对象;深链必须使用同一 Case 的 Run, + # 不能因其尚未物化 Candidate/OT 而丢失 run_no。 + str(getattr(runs_by_id.get(int(case.run_id)), 'run_no', '') or '').strip() + if case is not None and getattr(case, 'run_id', None) in runs_by_id + else str(getattr(runs_by_id.get(int(task.extraction_run_id)), 'run_no', '') or '').strip() + if task is not None and getattr(task, 'extraction_run_id', None) in runs_by_id + else str(getattr(runs_by_id.get(int(candidate.order_extraction_run_id)), 'run_no', '') or '').strip() + if candidate is not None and getattr(candidate, 'order_extraction_run_id', None) in runs_by_id + else None + ), + 'intake_no': str(getattr(document, 'intake_id', None) or '').strip() or None, + 'case_no': str(getattr(case, 'case_no', None) or '').strip() or None, + 'status': 'processing' if user_status == 'running' else user_status, + 'stage': stage, + 'user_status': user_status, + 'user_stage': stage, + 'user_group': group, + 'source_summary': { + 'document_id': int(document.id), + 'filename': str(document.filename or '').strip() or None, + 'document_count': 1, + 'parsed_document_count': int(str(document.parse_status or '').strip().lower() == 'parsed'), + 'candidate_count': 1 if candidate is not None or task is not None or case is not None else 0, + 'po_number': candidate_po or None, + }, + 'current_gate': current_gate, + 'blocking_reason': {'code': reason} if reason else None, + 'primary_action': primary_action, + 'available_actions': available_actions, + 'intake_parse_authorized': intake_parse_authorized, + } + return _with_processing_ui_state(leaf) + + groups: dict[str, list[dict[str, Any]]] = {key: [] for key in ( + 'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', + )} + for intake in intakes: + intake_documents = documents_by_intake.get(int(intake.id), []) + leaves = [] + tasks: list[ShippingOrderTask] = [] + for document in intake_documents: + candidate = candidate_by_document_id.get(int(document.id)) + task = tasks_by_candidate_id.get(int(candidate.id)) if candidate is not None else None + case = current_case_by_document_id.get(int(document.id)) + # 邮件的 unknown/supporting 附件若没有 Candidate、Review Case 或 OT, + # 只是原始邮件的支撑材料,不是可进入五阶段的业务文件。 + classification = str(document.classification or '').strip().lower() + if classification in {'unknown', 'supporting'} and candidate is None and case is None and task is None: + continue + if task is not None: + tasks.append(task) + leaves.append(_leaf(document, task, case)) + if not leaves: + continue + states = [str(leaf['user_status']) for leaf in leaves] + group = next((key for key in ('failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived') if key in states), 'processing') + source_type = str(intake.source_type or '').strip().lower() or 'direct_pdf' + asset = assets.get(int(intake.asset_id)) if intake.asset_id else None + title = str(getattr(asset, 'original_filename', None) or '').strip() or str(intake.intake_no) + is_eml = source_type == 'eml' + primary_task = tasks[0] if tasks else None + task_no = str(primary_task.task_no).strip() if primary_task is not None else f'INTAKE:{intake.intake_no}' + groups[group].append({ + 'user_task_no': task_no, + 'title': title, + 'display_kind': 'multi_document_task' if len(leaves) > 1 else 'single_document_task', + 'group': 'needs_action' if group in {'failed', 'waiting_human'} else ('history' if group in {'cancelled', 'archived'} else group), + 'status_label': 'pending_review' if group == 'waiting_human' else ('processing' if group == 'processing' else group), + 'file_count': len(leaves), + 'run_no': next((str(leaf.get('run_no') or '').strip() for leaf in leaves if leaf.get('run_no')), None), + 'case_no': next((str(leaf.get('case_no') or '').strip() for leaf in leaves if leaf.get('case_no')), None), + 'last_activity_at': _iso(intake.updated_at) or '', + 'available_actions': list( + dict.fromkeys( + action + for leaf in leaves + for action in (leaf.get('available_actions') or []) + ), + ), + 'user_status': 'running' if group == 'processing' else group, + 'user_stage': leaves[0]['user_stage'], + 'user_group': group, + 'aggregate_summary': {'intake_no': str(intake.intake_no), 'total': len(leaves)}, + 'aggregate_children': leaves if is_eml else leaves, + 'ui_state': _processing_ui_state_from_item({ + 'user_status': 'running' if group == 'processing' else group, + 'user_stage': leaves[0]['user_stage'], + 'source_summary': {'candidate_count': sum( + int((leaf.get('source_summary') or {}).get('candidate_count') or 0) + for leaf in leaves + )}, + 'primary_action': next((leaf.get('primary_action') for leaf in leaves if leaf.get('primary_action')), None), + 'available_actions': list(dict.fromkeys( + action for leaf in leaves for action in (leaf.get('available_actions') or []) + )), + 'intake_parse_authorized': any(leaf.get('intake_parse_authorized') for leaf in leaves), + }), + }) + # [AUTHORITY] 首屏摘要与详情投影一样,以同一批文件叶子的互斥用户分组 + # 生成总数和四个状态数。此前这里只返回 total_files,前端却按 *_files + # 渲染批次概览,造成“总文件有数、四个状态全为 0”的合同断裂。 + summary_file_counts = _batch_file_counts([ + row + for rows in groups.values() + for row in rows + ]) + summary_projection = { + 'projection_version': 2, + 'summary': { + 'total_tasks': sum(len(rows) for rows in groups.values()), + **summary_file_counts, + 'processing': len(groups['processing']), + 'needs_action': len(groups['failed']) + len(groups['waiting_human']), + 'completed': len(groups['completed']), + 'history': len(groups['cancelled']) + len(groups['archived']), + }, + 'focused_task_no': str(focused_task_no or '').strip() or None, + 'recent_task_no': str(recent_task_no or '').strip() or None, + 'status_groups': groups, + 'lifecycle_nodes': _batch_lifecycle_nodes([ + {'aggregate_children': task.get('aggregate_children') or []} + for rows in groups.values() + for task in rows + ]), + # 摘要与详情必须使用同一批文件的状态裁决;不能把全量待人工的会话硬编码为 idle, + # 否则聊天摘要会回退显示为“系统处理中”。 + 'ui_state': _batch_ui_state_from_items([ + row + for rows in groups.values() + for row in rows + ]), + 'output_artifacts': [], + } + return { + 'conversation_id': normalized, + 'projection_mode': 'summary', + 'conversation_processing': summary_projection, + } + + def project_conversation_processing_items( *, user_id: int, @@ -3045,6 +3907,23 @@ def project_conversation_processing_items( ) work_items: list[dict[str, Any]] = [] + # 会话缓存必须在 OT 投影前建立:OT 的 Gate/Case bundle 与 Intake 叶子共用 + # 同一批 Review、Run、Plan、Unit、Attempt、Job 事实,不能等到列表后半段才预取。 + intakes = ( + ShippingOrderIntake.query.filter( + ShippingOrderIntake.user_id == int(user_id), + ShippingOrderIntake.conversation_id == normalized, + ShippingOrderIntake.purpose == 'shipping_notice', + ) + .order_by( + ShippingOrderIntake.updated_at.desc(), + ShippingOrderIntake.created_at.desc(), + ) + .all() + ) + load_context = _conversation_projection_load_context(intakes) + previous_read_cache = db.session.info.get(_CONVERSATION_PROJECTION_READ_CACHE_KEY) + db.session.info[_CONVERSATION_PROJECTION_READ_CACHE_KEY] = load_context.read_cache # STEP 1a:会话内 OT 实体列表。代表 Run 只服务于这些真实 OT, # 必须先取得其编号,避免刚上传/仅 Intake 会话扫描全部历史 Run。 order_tasks = ( @@ -3061,21 +3940,16 @@ def project_conversation_processing_items( for task in order_tasks if str(task.task_no or '').strip() ] - # [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 漂移。 - legacy_seed_runs: list[ShippingOrderProcessingRun] = [] + # STEP 1a:正式读模型只选择未被替代且属于当前 OT 的 Run。代表项选择规则归本模块 + # 所有,禁止依赖已经下线的 conversation_processing_projection 私有常量。 + representative_runs: list[ShippingOrderProcessingRun] = [] if order_task_nos: - from app.services.shipping_notice.conversation_processing_projection import ( - _RIGHT_PANEL_RUN_STATUSES, - ) - legacy_seed_runs = ( + representative_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.in_(order_task_nos), - ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)), ) .order_by( ShippingOrderProcessingRun.last_activity_at.desc().nullslast(), @@ -3084,7 +3958,7 @@ def project_conversation_processing_items( .all() ) latest_by_task: dict[str, ShippingOrderProcessingRun] = {} - for seed_run in legacy_seed_runs: + for seed_run in representative_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 @@ -3135,7 +4009,7 @@ def project_conversation_processing_items( task_no = str(order_task.task_no or '').strip() if not task_no: continue - # 选 Run 优先级:A) 旧投影等价代表 → B) OT 自身 extraction_run_id → C) 原 fallback + # 选 Run 优先级:A) 当前 OT 的最新正式代表 → 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)) @@ -3193,7 +4067,7 @@ def project_conversation_processing_items( invalidated_from_stage = None if not stage_label_key and stage == 'order_creating': stage_label_key = 'waiting_system_start' - legacy_actions_min: list[str] = [] + authorized_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 @@ -3224,7 +4098,7 @@ def project_conversation_processing_items( getattr(order_task, 'updated_at', None) ) or '', 'current_gate': None, - 'available_actions': legacy_actions_min, + 'available_actions': authorized_actions_min, 'source_summary': { 'filename': None, 'document_count': 0, @@ -3232,7 +4106,7 @@ def project_conversation_processing_items( }, 'child_order_tasks': [], }, - legacy_actions=legacy_actions_min, + authorized_actions=authorized_actions_min, invalidated_from_stage=invalidated_from_stage, excel_ready=excel_ready, ) @@ -3257,71 +4131,77 @@ def project_conversation_processing_items( and str(item.get('intake_no') or '').strip() ) } - intakes = ( - ShippingOrderIntake.query.filter( - ShippingOrderIntake.user_id == int(user_id), - ShippingOrderIntake.conversation_id == normalized, - ShippingOrderIntake.purpose == 'shipping_notice', - ) - .order_by( - ShippingOrderIntake.updated_at.desc(), - ShippingOrderIntake.created_at.desc(), - ) - .all() - ) - submission_cache: dict[int, ShippingOrderSubmission | None] = {} - asset_cache: dict[int, FileAsset | None] = {} - for intake in intakes: - if not _should_emit_intake_work_item( - intake, - linked_intake_ids=linked_intake_ids, - represented_eml_intake_nos=represented_eml_intake_nos, - ): - continue - submission = None - if intake.order_submission_id: - sid = int(intake.order_submission_id) - if sid not in submission_cache: - submission_cache[sid] = db.session.get(ShippingOrderSubmission, sid) - submission = submission_cache[sid] - asset = None - if intake.asset_id: - aid = int(intake.asset_id) - if aid not in asset_cache: - asset_cache[aid] = db.session.get(FileAsset, aid) - asset = asset_cache[aid] - work_items.append( - project_intake_work_item(intake, submission=submission, asset=asset) - ) + try: + submission_cache: dict[int, ShippingOrderSubmission | None] = {} + asset_cache: dict[int, FileAsset | None] = {} + for intake in intakes: + if not _should_emit_intake_work_item( + intake, + linked_intake_ids=linked_intake_ids, + represented_eml_intake_nos=represented_eml_intake_nos, + ): + continue + submission = None + if intake.order_submission_id: + sid = int(intake.order_submission_id) + if sid not in submission_cache: + submission_cache[sid] = db.session.get(ShippingOrderSubmission, sid) + submission = submission_cache[sid] + asset = None + if intake.asset_id: + aid = int(intake.asset_id) + if aid not in asset_cache: + asset_cache[aid] = db.session.get(FileAsset, aid) + asset = asset_cache[aid] + work_items.append( + project_intake_work_item( + intake, + submission=submission, + asset=asset, + load_context=load_context, + ) + ) - # 同一 EML Intake 只作为一个用户工作项返回。聚合必须发生在 work_items 返回前, - # 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。 - work_items = _aggregate_eml_order_task_work_items(work_items) - # [AUTHORITY] 顶层 work_items 与 conversation_processing.status_groups 必须使用 - # 同一份“当前文件代表项”展示 DTO。否则前端兼容消费者若从顶层 work_items - # 读取,会重新看到历史 Run/旧失败项,绕过批次统计已经完成的互斥裁决。 - # 该函数保留 EML 父容器,只裁掉其历史附件,不能以叶子项直接替换父卡。 - work_items = _display_work_items_from_current_files(work_items) - work_items = [_with_processing_ui_state(item) for item in work_items] + # 同一 EML Intake 只作为一个用户工作项返回。聚合必须发生在 work_items 返回前, + # 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。 + work_items = _aggregate_eml_order_task_work_items( + work_items, + load_context=load_context, + ) + # [AUTHORITY] 顶层 work_items 与 conversation_processing.status_groups 必须使用 + # 同一份“当前文件代表项”展示 DTO。否则前端兼容消费者若从顶层 work_items + # 读取,会重新看到历史 Run/旧失败项,绕过批次统计已经完成的互斥裁决。 + # 该函数保留 EML 父容器,只裁掉其历史附件,不能以叶子项直接替换父卡。 + work_items = _display_work_items_from_current_files(work_items) + work_items = [_with_processing_ui_state(item) for item in work_items] - recent_override = str(recent_task_no or '').strip() or None - rebuilt = _conversation_processing_from_work_items( - work_items, - focused_task_no=focused_override, - recent_task_no=recent_override, - ) - # 写路径元数据:保留提交决策与追加计数,供前端卡片提示。 - if recent_decision is not None: - rebuilt['recent_decision'] = recent_decision - if recent_append_count is not None: - rebuilt['recent_append_count'] = recent_append_count + recent_override = str(recent_task_no or '').strip() or None + rebuilt = _conversation_processing_from_work_items( + work_items, + focused_task_no=focused_override, + recent_task_no=recent_override, + ) + # 写路径元数据:保留提交决策与追加计数,供前端卡片提示。 + if recent_decision is not None: + rebuilt['recent_decision'] = recent_decision + if recent_append_count is not None: + rebuilt['recent_append_count'] = recent_append_count - return { - 'conversation_id': normalized, - 'work_items': work_items, - 'conversation_processing': rebuilt, - 'conversation_allowed_actions': [], - } + # 内部聚合依赖顶层动作中间表示;仅在响应边界剥离,既不会破坏当前文件 + # 代表项/EML 聚合,也不会再次暴露两套前端动作合同。 + public_work_items = _strip_legacy_action_fields_for_response(work_items) + public_rebuilt = _strip_legacy_action_fields_for_response(rebuilt) + return { + 'conversation_id': normalized, + 'work_items': public_work_items, + 'conversation_processing': public_rebuilt, + 'conversation_allowed_actions': [], + } + finally: + if previous_read_cache is None: + db.session.info.pop(_CONVERSATION_PROJECTION_READ_CACHE_KEY, None) + else: + db.session.info[_CONVERSATION_PROJECTION_READ_CACHE_KEY] = previous_read_cache def get_shipping_processing_work_item( diff --git a/backend/app/services/shipping_notice/shipping_turn_context.py b/backend/app/services/shipping_notice/shipping_turn_context.py index cc0dbe70..b3e50341 100644 --- a/backend/app/services/shipping_notice/shipping_turn_context.py +++ b/backend/app/services/shipping_notice/shipping_turn_context.py @@ -1,7 +1,7 @@ """ services/shipping_notice/shipping_turn_context.py -用途:货代 Chat Turn 领域上下文解析(task_no / batch_no 等 refs 键名约定)。 +用途:货代 Chat Turn 领域上下文解析(task_no refs 键名约定)。 依赖:turn_context.TurnContext。 逻辑:chat_action_handlers 通过本模块解析货代专属锚点;平台 turn_context 不感知这些键名。 """ @@ -14,12 +14,9 @@ from app.services.chat.turn_context import TurnContext # 与 agent_runtime_context.refs 及前端 shipping 上下文对齐的键名约定。 SHIPPING_REF_TASK_NO = "task_no" -SHIPPING_REF_BATCH_NO = "batch_no" _TASK_PAYLOAD_KEYS = ("task_no", "taskNo", "task_id", "taskId") _TASK_REF_KEYS = (SHIPPING_REF_TASK_NO, "taskNo", "task_id", "taskId") -_BATCH_PAYLOAD_KEYS = ("batch_no", "batchNo") -_BATCH_REF_KEYS = (SHIPPING_REF_BATCH_NO, "batchNo") def _first_non_empty(values: tuple[str, ...]) -> str: @@ -57,19 +54,3 @@ def resolve_shipping_task_no(ctx: TurnContext) -> str: from_refs = _first_non_empty(tuple(ctx.refs.get(key, "") for key in _TASK_REF_KEYS)).upper() return from_refs - -def resolve_shipping_batch_no(ctx: TurnContext) -> str: - """ - 从 action payload 或 session refs 解析货代批次编号。 - - Args: - ctx: 当前 Chat Turn 上下文。 - - Returns: - batch_no 文本;无法解析时返回空串。 - """ - payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} - from_payload = _read_payload_str(payload, *_BATCH_PAYLOAD_KEYS) - if from_payload: - return from_payload - return _first_non_empty(tuple(ctx.refs.get(key, "") for key in _BATCH_REF_KEYS)) diff --git a/backend/app/services/shipping_notice/shipping_turn_helpers.py b/backend/app/services/shipping_notice/shipping_turn_helpers.py index 4b55073b..5bd031ba 100644 --- a/backend/app/services/shipping_notice/shipping_turn_helpers.py +++ b/backend/app/services/shipping_notice/shipping_turn_helpers.py @@ -3,7 +3,7 @@ services/shipping_notice/shipping_turn_helpers.py 用途:货代 Chat Turn handler 共用的 SSE 事件构造与 UI State 回写。 依赖:action_schema.TurnEvent、ui_state、query_service。 -逻辑:chat_action_handlers 与 chat_action_extended_handlers 复用本模块,避免重复 yield 逻辑。 +逻辑:Chat Turn handler 复用本模块,避免重复 yield 逻辑。 """ from __future__ import annotations @@ -11,8 +11,7 @@ from __future__ import annotations from typing import Any, Iterator from app.services.chat.action_schema import TurnEvent -from app.services.shipping_notice.query_service import get_batch_for_user -from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state +from app.services.shipping_notice.ui_state import build_task_ui_state def stream_text_events( @@ -46,43 +45,18 @@ def stream_text_events( def shipping_task_ui_state_event(task) -> TurnEvent: """单票任务 ui_state.updated 事件。""" ui_state = build_task_ui_state(task) - batch_no = None return TurnEvent( event="ui_state.updated", data={ "domain": "shipping", "task_no": task.task_no, - "batch_no": batch_no, "payload": { "task_no": task.task_no, - "batch_no": batch_no, "ui_state": ui_state, }, }, ) -def shipping_batch_ui_state_event(batch_no: str, user_id: int) -> TurnEvent | None: - """批次级 ui_state.updated 事件。""" - batch = get_batch_for_user(batch_no, user_id) - if batch is None: - return None - batch_state = build_batch_ui_state(batch) - focus_task_no = str(batch_state.get("current_focus_task_no") or "").strip() - return TurnEvent( - event="ui_state.updated", - data={ - "domain": "shipping", - "batch_no": batch_no, - "task_no": focus_task_no or None, - "payload": { - "batch_no": batch_no, - "batch_ui_state": batch_state, - "task_no": focus_task_no or None, - }, - }, - ) - - def tool_result_message(result: dict[str, Any]) -> str: return str(result.get("message") or "").strip() diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index 3f7dd962..8b4f550e 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -147,7 +147,6 @@ def resolve_task_ui_state_from_fields( *, review_status: str | None, pending_human_reason: str | None, - shipping_case_id: int | None, customer_resolution_status: str | None, order_snapshot_id: int | None, inventory_lines_json: Any, @@ -188,7 +187,7 @@ def resolve_task_ui_state_from_fields( if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED: return _task_ui_state(CP_NOTICE_TEXT_EXTRACTION_FAILED) - if shipping_case_id is not None and customer_resolution_status != "confirmed": + if str(customer_resolution_status or "").strip().lower() in {"pending", "needs_review", "failed", "unresolved"}: return _task_ui_state(CP_CUSTOMER_REVIEW) # [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。 @@ -254,7 +253,6 @@ def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState: return resolve_task_ui_state_from_fields( review_status=task.review_status, pending_human_reason=task.pending_human_reason, - shipping_case_id=task.shipping_case_id, customer_resolution_status=task.customer_resolution_status, order_snapshot_id=task.order_snapshot_id, inventory_lines_json=task.inventory_lines_json, diff --git a/backend/app/services/shipping_notice/task_candidate_reconciliation.py b/backend/app/services/shipping_notice/task_candidate_reconciliation.py index 78c7885d..3496cf91 100644 --- a/backend/app/services/shipping_notice/task_candidate_reconciliation.py +++ b/backend/app/services/shipping_notice/task_candidate_reconciliation.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/task_candidate_reconciliation.py 用途:将 Candidate 订单行对账到既有 Task(字段级自动补齐 / 冲突落库)。 依赖:po_number、reservation_id、动态订单 FieldValue、task_field_conflict_service、state_machine。 -逻辑:batch_from_intakes / open_existing 路径调用;仅安全态任务可自动补齐。 +逻辑:open_existing 对账路径调用;仅安全态任务可自动补齐。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/task_disposition_service.py b/backend/app/services/shipping_notice/task_disposition_service.py index 1af2d521..985aa41e 100644 --- a/backend/app/services/shipping_notice/task_disposition_service.py +++ b/backend/app/services/shipping_notice/task_disposition_service.py @@ -3,7 +3,7 @@ services/shipping_notice/task_disposition_service.py 用途:集中处理发货任务的回收站、作废与归档生命周期,避免混用业务阶段和生命周期。 依赖:ShippingNotice / ShippingTaskEvent、fulfillment_audit.record_fulfillment_audit、 - SQLAlchemy 行锁、ShippingCase 生命周期事实。 + SQLAlchemy 行锁、ShippingNotice 生命周期事实。 逻辑:workspace 批量处置 API 通过本模块锁定任务、重算资格;TaskEvent 与 ShippingAuditEvent 双写稳定 reason_code;编排与回调阶段读取本模块的 active 判定以阻断副作用。 """ @@ -14,8 +14,6 @@ from dataclasses import dataclass from datetime import datetime from typing import Any, Literal -from sqlalchemy.orm import joinedload - from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( @@ -99,7 +97,7 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice: if not normalized_task_no: raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED') task = ( - ShippingNotice.query.options(joinedload(ShippingNotice.shipping_case)) + ShippingNotice.query .filter(ShippingNotice.task_no == normalized_task_no) .with_for_update() .first() @@ -110,11 +108,10 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice: def _has_external_fulfillment(task: ShippingNotice) -> bool: - """识别已提交、正在提交或已有货代回执的任务;这些任务不可在平台单方作废。""" + """识别已提交、正在提交或已有外部上传参考的任务;这些任务不可在平台单方作废。""" upload_status = str(task.upload_status or '').strip().lower() return bool( task.freight_ref_no - or task.upload_receipt_json or upload_status in _EXTERNAL_UPLOAD_STATUSES ) @@ -285,7 +282,8 @@ def move_task_to_recycle_bin( # [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。 has_internal_business_record = bool( - task.shipping_case_id + task.business_no + or task.customer_id or task.source_candidate_id or task.match_status or task.export_file_path @@ -421,7 +419,8 @@ def purge_task_permanently( # [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。 blocking_counts = { - 'shipping_case': int(bool(task.shipping_case_id)), + 'business_number': int(bool(task.business_no)), + 'customer': int(bool(task.customer_id)), 'source_asset': int(bool(task.source_asset_id)), 'source_intake': int(bool(task.source_intake_id)), 'source_candidate': int(bool(task.source_candidate_id)), diff --git a/backend/app/services/shipping_notice/task_retry_decision_service.py b/backend/app/services/shipping_notice/task_retry_decision_service.py deleted file mode 100644 index c2134420..00000000 --- a/backend/app/services/shipping_notice/task_retry_decision_service.py +++ /dev/null @@ -1,1036 +0,0 @@ -""" -services/shipping_notice/task_retry_decision_service.py - -用途:正式 OT「重试」统一决策与执行入口(任务级 / 行级 / 对话级 / auto-progress 兼容)。 -依赖:inventory_source_gate、inventory_workflow、fulfillment_workflow.match_inventory、 - progress_workflow.auto_progress、fulfillment_audit、ShippingNotice / - ShippingNoticeLineInventoryMatch。 -逻辑:用户只表达重试意图;本服务按最新事实选择 resolve_source / fetch_inventory / - rematch / needs_human / noop / failed,或非库存阶段委托 auto_progress; - 禁止对话级与任务级分叉实现;幂等键与审计字段一并返回。 -""" - -from __future__ import annotations - -import logging -from typing import Any, Literal - -from app import db -from app.core.errors import AppError, NotFoundError, ValidationError -from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch - -_LOGGER = logging.getLogger(__name__) - -Scope = Literal['task', 'line'] - -ACTION_RESOLVE_SOURCE = 'resolve_source' -ACTION_FETCH_INVENTORY = 'fetch_inventory' -ACTION_REMATCH = 'rematch' -ACTION_NEEDS_HUMAN = 'needs_human' -ACTION_NOOP = 'noop' -ACTION_FAILED = 'failed' -ACTION_AUTO_PROGRESS = 'auto_progress' - -STATUS_RUNNING = 'running' -STATUS_NEEDS_HUMAN = 'needs_human' -STATUS_COMPLETED = 'completed' -STATUS_FAILED = 'failed' - -PH_RPA_PENDING = 'rpa_pending' -PH_UPLOAD_PENDING = 'upload_rpa_pending' -PH_UPLOAD_FAILED = 'upload_rpa_failed' - - -def _request_formal_gate_action( - *, - task: ShippingNotice, - action_code: str, - user_id: int, - idempotency_key: str, - trigger: str, - line_key: str | None = None, -) -> dict[str, Any]: - """将外部重试意图提交给正式 20-Gate Recovery/ProcessGate 编排。 - - 外部入口只负责定位当前正式 Gate 和动作;库存准备、匹配等旧函数仅允许 - 由 ``process_gate_executor`` 通过内部分派标记调用。 - """ - from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate - from app.services.shipping_notice.process_gate_recovery_service import request_gate_action - from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version - from app.models import ShippingProcessExecution, ShippingProcessGate - - execution = None - current_id = getattr(task, 'active_process_execution_id', None) - if current_id: - execution = ShippingProcessExecution.query.filter_by(id=int(current_id)).with_for_update().first() - if execution is not None and str(execution.status or '').strip().lower() == 'superseded': - execution = None - if execution is None: - execution = ensure_execution_for_workflow_version( - task_id=int(task.id), actor_type='user', actor_id=int(user_id), - start_gate_code=determine_formal_start_gate(task), - ) - task.active_process_execution_id = int(execution.id) - db.session.flush() - gate = ShippingProcessGate.query.filter_by( - execution_id=int(execution.id), gate_code=str(execution.current_gate_code or '').strip(), - ).first() - if gate is None: - raise ValidationError('Current formal process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') - - requested = str(action_code or '').strip() - if requested == 'retry_inventory_from_matching' and gate.gate_code != 'inventory_sufficiency': - requested = 'retry_inventory_matching' - payload: dict[str, Any] = {'trigger': trigger} - if line_key: - payload['line_key'] = str(line_key) - result = request_gate_action( - execution_no=str(execution.execution_no), gate_code=str(gate.gate_code), - action_code=requested, expected_gate_version=int(gate.evaluation_version), - idempotency_key=str(idempotency_key), actor_type='user', actor_id=int(user_id), - payload=payload, - ) - return { - 'status': 'running' if result.get('dispatch') in {'async_job', 'sync'} else 'failed', - 'action': action_code, - 'task_id': task.task_no, - 'job_id': result.get('job_id'), - 'attempt_id': (result.get('attempt') or {}).get('id'), - 'execution_no': result.get('execution_no'), - 'gate_code': result.get('gate_code'), - 'message': '已提交正式 20-Gate 恢复动作', - } - - -def retry_task_with_decision( - *, - task_no: str, - user_id: int, - scope: Scope = 'task', - line_key: str | None = None, - reason: str | None = None, - trigger: str = 'user_retry', - continue_auto_progress: bool = False, -) -> dict[str, Any]: - """ - 统一重试决策并执行。 - - 核心逻辑:加锁读取任务事实 → 决策树 → 执行既有库存/推进处理器 → 写审计 → 返回统一结果。 - - Args: - task_no: 正式任务号。 - user_id: 操作人。 - scope: task=整单;line=单行。 - line_key: scope=line 时必填。 - reason: 用户/系统原因。 - trigger: 调用方标识(user_retry / conversation_retry / system_auto_progress)。 - continue_auto_progress: True 时库存节点通过后继续 auto_progress(兼容调度入口)。 - - Returns: - 含 action/status/retryable/decision_version/snapshot_id/job_id/idempotency_key 等。 - - Raises: - ValidationError / NotFoundError / AppError。 - """ - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - from app.services.shipping_notice.query_service import get_task_for_user - - normalized_task = str(task_no or '').strip() - if not normalized_task: - raise ValidationError('task_no is required') - scope_norm: Scope = 'line' if str(scope or '').strip().lower() == 'line' else 'task' - line = str(line_key or '').strip() or None - if scope_norm == 'line' and not line: - raise ValidationError('line_key is required for line scope') - - task = get_task_for_user(normalized_task, int(user_id)) - if task is None: - raise NotFoundError('Not found') - - decision_version = int(getattr(task, 'order_data_version', None) or 1) - # 题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, - action=action, - decision_version=decision_version, - line_key=line, - ) - - # [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 []) - ) - 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, - user_id=int(user_id), - decided=decided, - continue_auto_progress=bool(continue_auto_progress), - decision_version=decision_version, - idempotency_key=idempotency_key, - line_key=line, - trigger=trigger, - ) - _audit_decision( - task=task, - user_id=int(user_id), - scope=scope_norm, - line_key=line, - trigger=trigger, - reason=reason, - result=executed, - ) - try: - db.session.commit() - except Exception: # noqa: BLE001 - db.session.rollback() - _LOGGER.exception('task retry decision commit failed task_no=%s', normalized_task) - raise - return executed - - -def decide_retry_action_only( - task: ShippingNotice, - *, - scope: Scope = 'task', - line_key: str | None = None, -) -> dict[str, Any]: - """ - 只读决策(供投影 / 测试);不执行副作用。 - - Returns: - ``{action, reason_code, retryable, ...}``。 - """ - return _decide(task, scope=scope, line_key=line_key) - - -def _decide( - task: ShippingNotice, - *, - scope: Scope, - line_key: str | None, - latest_active: dict[str, Any] | None = None, -) -> dict[str, Any]: - """按冻结优先级计算 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 - - 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) - ) - - lifecycle_status = str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() - upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() - if lifecycle_status in {'voided', 'archived', 'deleted'} or upload_status in {'uploaded', 'succeeded', 'success'}: - return { - 'action': ACTION_NOOP, - 'status': STATUS_COMPLETED, - 'retryable': False, - 'reason_code': 'already_completed', - } - # 库存 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, - 'retryable': False, - 'reason_code': 'already_running', - } - latest_statuses = { - str(item.get('status') or '').strip().lower() - for item in (active.get('latest_attempts') or {}).values() - } - if scope != 'line' and pending == PH_RPA_PENDING and latest_statuses <= {'', 'not_started'}: - return { - 'action': ACTION_NOOP, - 'status': STATUS_RUNNING, - 'retryable': False, - 'reason_code': 'already_running', - } - if pending == PH_UPLOAD_FAILED: - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': 'upload_rpa_failed', - } - - if scope == 'line' and line_key: - 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', ''}: - # 多候选 / 客户未指定:不得自动选源进 RPA。 - codes = _frozen_or_candidate_codes(task) - if status == 'conflicted': - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': 'inventory_source_candidates_need_human', - } - # resolve_source:单一候选或歧义已人工消除 → 可通过重试自动推进 - return { - 'action': ACTION_RESOLVE_SOURCE, - 'status': STATUS_RUNNING, - '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': True, - 'reason_code': 'inventory_snapshot_missing', - } - - # 有快照/明细但匹配未完成或失败 → rematch;短缺 → needs_human。 - match_hint = _task_match_hint(task) - if match_hint.get('needs_human'): - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - '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': True, - 'reason_code': 'inventory_match_incomplete', - } - - # 非库存阻断:委托现有 auto_progress 推进后续阶段。 - return { - 'action': ACTION_AUTO_PROGRESS, - 'status': STATUS_RUNNING, - 'retryable': False, - 'reason_code': None, - } - - -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': True, - 'reason_code': 'inventory_source_unstable', - } - - row = ( - ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task.id), line_key=str(line_key)) - .order_by(ShippingNoticeLineInventoryMatch.id.desc()) - .first() - ) - fact = { - 'match_result': getattr(row, 'match_result', None) if row else None, - 'inventory_status': getattr(row, 'inventory_status', None) if row else 'preparing', - 'available_qty': getattr(row, 'available_qty', None) if row else None, - 'required_qty': getattr(row, 'required_qty', None) if row else None, - 'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None) if row else None, - 'inventory_source_code': getattr(row, 'inventory_source_code', None) if row else None, - 'matched_at': getattr(row, 'matched_at', None) if row else None, - '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, - required_qty=fact.get('required_qty'), - stored_line_status=None, - decision_source=None, - can_fulfill_complete_line=False, - inventory_rpa_running=line_running_flag, - ) - user_status = str(view.get('user_line_status') or '') - if user_status == 'source_conflict': - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': 'inventory_shortage' if user_status == 'shortage' else 'inventory_source_conflict', - } - if user_status == 'shortage': - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': 'inventory_shortage', - } - if not project_line_retryable( - inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []), - user_line_status=user_status, - inventory_rpa_running=line_running_flag, - ): - return { - 'action': ACTION_NOOP, - 'status': STATUS_COMPLETED, - 'retryable': False, - 'reason_code': 'already_completed', - } - 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': 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': 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, - user_id: int, - decided: dict[str, Any], - continue_auto_progress: bool, - 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 ( - adjudicate_and_apply_inventory_source, - ensure_inventory_source_review_state, - ) - - action = str(decided.get('action') or ACTION_NOOP) - # 所有重试动作(含库存匹配 REMATCH)共用同一触发来源;不能只在 FETCH 分支内初始化。 - trigger_norm = str(trigger or '').strip().lower() or 'user_retry' - base_kwargs = { - 'task': task, - 'decision_version': decision_version, - 'idempotency_key': idempotency_key, - 'snapshot_id': getattr(task, 'inventory_snapshot_id', None), - 'source_code': str(getattr(task, 'inventory_source_code', None) or '') or None, - } - - if action == ACTION_NOOP: - return _result_payload( - action=ACTION_NOOP, - status=str(decided.get('status') or STATUS_COMPLETED), - retryable=False, - reason_code=str(decided.get('reason_code') or 'already_completed'), - message='无需重试', - **base_kwargs, - ) - - if action == ACTION_NEEDS_HUMAN: - return _result_payload( - action=ACTION_NEEDS_HUMAN, - status=STATUS_NEEDS_HUMAN, - retryable=False, - reason_code=str(decided.get('reason_code') or 'needs_human'), - message='当前需要人工处理', - **base_kwargs, - ) - - try: - if action == ACTION_RESOLVE_SOURCE: - adjudicate_and_apply_inventory_source(task) - ensure_inventory_source_review_state(task) - db.session.flush() - from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable - if not is_inventory_source_stable(task): - return _result_payload( - action=ACTION_NEEDS_HUMAN, - status=STATUS_NEEDS_HUMAN, - retryable=False, - reason_code='inventory_source_candidates_need_human', - message='库存源未稳定,需要人工确认', - **base_kwargs, - ) - # 源已稳定:继续获取库存。 - action = ACTION_FETCH_INVENTORY - - if action == ACTION_FETCH_INVENTORY: - # 库存 RPA 的正式前置事实是订单快照。历史任务可能已完成解析但未成功冻结, - # 会话重试必须先补做一次冻结;冻结门禁失败时返回 needs_human,禁止伪造 Trigger。 - if not getattr(task, 'order_snapshot_id', None) and isinstance(task, ShippingNotice): - try: - from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot - - freeze_order_snapshot( - task, - actor_id=int(user_id), - expected_order_data_version=decision_version, - freeze_mode='manual', - ) - db.session.flush() - except AppError as freeze_err: - return _result_payload( - action=ACTION_NEEDS_HUMAN, - status=STATUS_NEEDS_HUMAN, - retryable=False, - reason_code=str(getattr(freeze_err, 'code', None) or 'order_freeze_not_ready'), - message='订单快照尚未冻结,无法进入库存 RPA。', - **base_kwargs, - ) - formal = _request_formal_gate_action( - task=task, - action_code='retry_inventory_preparation', - user_id=int(user_id), - idempotency_key=idempotency_key, - trigger=trigger_norm, - line_key=line_key, - ) - return _map_tool_result(formal, action=ACTION_FETCH_INVENTORY, base_kwargs=base_kwargs, message='已提交库存获取') - - if action == ACTION_REMATCH: - # 题5B:有 line_key → 调用新 match_inventory_line 只对目标行匹配,避免整单重算覆盖其他行; - # 否则(例如 scope=task 且缺快照或整单重算)仍走原 match_inventory。 - norm_line_key = str(line_key or '').strip() - formal = _request_formal_gate_action( - task=task, - action_code='retry_inventory_from_matching', - user_id=int(user_id), - idempotency_key=idempotency_key, - trigger=trigger_norm, - line_key=norm_line_key or None, - ) - return _map_tool_result(formal, action=ACTION_REMATCH, base_kwargs=base_kwargs, message='已提交库存匹配') - - # ACTION_AUTO_PROGRESS 或 continue - return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs) - except AppError as err: - # 下游 flush/写库失败会使 PostgreSQL 事务进入 aborted;必须先清理, - # 才能让调用方继续写本次失败决策审计。 - db.session.rollback() - return _result_payload( - action=ACTION_FAILED, - status=STATUS_FAILED, - retryable=False, - reason_code=str(getattr(err, 'code', None) or 'SHIPPING.RETRY_FAILED'), - message=str(getattr(err, 'message', None) or err), - **base_kwargs, - ) - except Exception as exc: # noqa: BLE001 - _LOGGER.exception('task retry execute failed task_no=%s action=%s', task.task_no, action) - # 同上:避免后续 _audit_decision 查询审计哈希链时触发 - # InFailedSqlTransaction,掩盖真正的业务失败。 - db.session.rollback() - return _result_payload( - action=ACTION_FAILED, - status=STATUS_FAILED, - retryable=False, - reason_code='SHIPPING.RETRY_FAILED', - message=str(exc)[:500], - **base_kwargs, - ) - - -def _run_auto_progress( - task: ShippingNotice, - *, - user_id: int, - base_kwargs: dict[str, Any], -) -> dict[str, Any]: - """委托现有 auto_progress 推进非库存/后续阶段。""" - from app.services.shipping_notice import tools as shipping_tools - - result = shipping_tools.auto_progress({ - 'task_id': task.task_no, - 'source': 'workspace_api', - 'operator_id': int(user_id), - 'actor_id': int(user_id), - '_trusted_user_id': int(user_id), - 'trigger': 'task_retry_decision', - }) - return _map_tool_result( - result, - action=ACTION_AUTO_PROGRESS, - base_kwargs=base_kwargs, - message='已提交自动推进', - ) - - -def _map_tool_result( - tool_result: dict[str, Any] | None, - *, - action: str, - base_kwargs: dict[str, Any], - message: str, -) -> dict[str, Any]: - """将既有 tool 响应映射为统一 Retry 结果。""" - status_raw = str((tool_result or {}).get('status') or '').strip().lower() - if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload', 'blocked_manual'}: - return _result_payload( - action=ACTION_NEEDS_HUMAN, - status=STATUS_NEEDS_HUMAN, - retryable=False, - reason_code=str( - (tool_result or {}).get('error_code') - or (tool_result or {}).get('reason_code') - or (tool_result or {}).get('blocking_reason_code') - or 'needs_human' - ), - message=str((tool_result or {}).get('message') or '当前需要人工处理'), - job_id=(tool_result or {}).get('job_id'), - **base_kwargs, - ) - if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed', 'blocked_retryable'}: - return _result_payload( - action=ACTION_FAILED, - status=STATUS_FAILED, - retryable=False, - reason_code=str( - (tool_result or {}).get('error_code') - or (tool_result or {}).get('reason_code') - or (tool_result or {}).get('blocking_reason_code') - or status_raw - ), - message=str((tool_result or {}).get('message') or '自动处理失败'), - job_id=(tool_result or {}).get('job_id'), - **base_kwargs, - ) - if status_raw in {'ok', 'completed', 'succeeded'}: - return _result_payload( - action=action, - status=STATUS_COMPLETED, - retryable=False, - reason_code=None, - message=str((tool_result or {}).get('message') or message), - job_id=(tool_result or {}).get('job_id'), - **base_kwargs, - ) - # running / queued / processing - return _result_payload( - action=action, - status=STATUS_RUNNING, - retryable=False, - reason_code=None, - message=str((tool_result or {}).get('message') or message), - job_id=(tool_result or {}).get('job_id'), - **base_kwargs, - ) - - -def _result_payload( - *, - task: ShippingNotice, - action: str, - status: str, - retryable: bool, - reason_code: str | None, - decision_version: int, - idempotency_key: str, - message: str, - snapshot_id: Any = None, - source_code: str | None = None, - job_id: Any = None, - idempotent_replay: bool = False, -) -> dict[str, Any]: - """组装统一响应。""" - return { - 'task_no': task.task_no, - 'idempotent_replay': bool(idempotent_replay), - 'action': action, - 'stage': None, - 'status': status, - 'retryable': bool(retryable), - 'job_id': job_id, - 'reason_code': reason_code, - 'message': message, - 'decision_version': int(decision_version), - 'snapshot_id': int(snapshot_id) if snapshot_id not in (None, '') else None, - 'source_code': source_code, - 'idempotency_key': idempotency_key, - } - - -def _build_idempotency_key( - *, - task: ShippingNotice, - action: str, - decision_version: int, - line_key: str | None, -) -> str: - """按冻结约定生成业务幂等键。""" - task_no = str(task.task_no) - source = str(getattr(task, 'inventory_source_code', None) or 'NA').strip().upper() or 'NA' - snapshot = getattr(task, 'inventory_snapshot_id', None) or 'none' - if action == ACTION_FETCH_INVENTORY: - key = f'inventory-fetch:{task_no}:{source}:v{decision_version}' - elif action == ACTION_REMATCH: - key = f'inventory-match:{task_no}:{snapshot}:v{decision_version}' - elif action == ACTION_RESOLVE_SOURCE: - key = f'inventory-source:{task_no}:v{decision_version}' - else: - key = f'auto-progress:{task_no}:v{decision_version}' - if line_key: - key = f'{key}:line:{line_key}' - return key - - -def _is_inventory_rpa_active(task: ShippingNotice) -> bool: - """库存 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 ( - Job, - 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 - query = ( - ShippingTaskInventoryRpaAttempt.query - .filter(ShippingTaskInventoryRpaAttempt.task_no == task_no) - .order_by( - ShippingTaskInventoryRpaAttempt.source_code.asc(), - ShippingTaskInventoryRpaAttempt.attempt_no.desc(), - ShippingTaskInventoryRpaAttempt.id.desc(), - ) - ) - # 轻量调用方可能只提供 first();正式 ORM 使用 all() 做一次批量读取。 - rows = query.all() if hasattr(query, 'all') else [query.first()] - rows = [row for row in rows if row is not None] - latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {} - for row in rows: - key = str(getattr(row, 'source_code', None) or '').strip().upper() or None - if not key and len(required_frozen_sources) == 1: - key = required_frozen_sources[0] - 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(getattr(att, 'attempt_no', 0) or 0), - 'run_no': str(getattr(att, 'run_no', '') or '') or None, - 'status': st, - 'error_code': str(getattr(att, 'error_code', '') or '') or None, - 'error_message': str(getattr(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, - ) - .join(Job, Job.id == ShippingProcessGateAttempt.job_id) - .filter(ShippingProcessGateAttempt.status.in_(('queued', 'running'))) - .filter(Job.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]: - """读取冻结/候选库存源编码。""" - try: - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - return list(task_frozen_inventory_source_codes(task) or []) - except Exception: # noqa: BLE001 - return [] - - -def _task_match_hint(task: ShippingNotice) -> dict[str, Any]: - """根据行匹配事实判断是否需 rematch 或人工。""" - rows = ( - ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task.id)) - .order_by(ShippingNoticeLineInventoryMatch.id.desc()) - .limit(200) - .all() - ) - if not rows: - # 有库存明细但无匹配行 → 需要匹配。 - if getattr(task, 'inventory_lines_json', None) or getattr(task, 'inventory_snapshot_id', None): - return {'needs_rematch': True} - return {} - needs_rematch = False - for row in rows: - result = str(getattr(row, 'match_result', None) or '').strip().lower() - status = str(getattr(row, 'inventory_status', None) or '').strip().lower() - if result in {'not_found'} or status in {'source_conflict'}: - # 短缺/冲突:人工。 - return {'needs_human': True, 'reason_code': 'inventory_shortage' if result == 'not_found' else 'inventory_source_conflict'} - if result in {'mapping_failed', 'result_missing', 'preparing', ''} or status in {'mapping_failed', 'preparing'}: - needs_rematch = True - if needs_rematch: - return {'needs_rematch': True} - return {} - - -def _audit_decision( - *, - task: ShippingNotice, - user_id: int, - scope: Scope, - line_key: str | None, - trigger: str, - reason: str | None, - result: dict[str, Any], -) -> None: - """写对象级重试决策审计。""" - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - - action = str(result.get('action') or ACTION_NOOP) - event_type = { - ACTION_RESOLVE_SOURCE: 'inventory_source_resolved', - ACTION_FETCH_INVENTORY: 'inventory_rpa_triggered', - ACTION_REMATCH: 'inventory_matching_started', - ACTION_AUTO_PROGRESS: 'auto_progress_retried', - ACTION_NEEDS_HUMAN: 'auto_progress_retried', - ACTION_NOOP: 'auto_progress_retried', - ACTION_FAILED: 'auto_progress_retried', - }.get(action, 'auto_progress_retried') - record_fulfillment_audit( - event_type=event_type, - aggregate_type='shipping_task', - aggregate_id=str(task.task_no), - action='retry', - actor_id=int(user_id), - task_no=str(task.task_no), - conversation_id=str(getattr(task, 'conversation_id', None) or '') or None, - 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 'failure', - error_code=str(result.get('reason_code') or '') if result.get('status') == STATUS_FAILED else None, - metadata={ - 'scope': scope, - 'line_key': line_key, - 'trigger': trigger, - 'previous_stage': None, - 'next_stage': result.get('stage'), - 'action': action, - 'decision_version': result.get('decision_version'), - 'snapshot_id': result.get('snapshot_id'), - 'job_id': result.get('job_id'), - 'idempotency_key': result.get('idempotency_key'), - 'status': result.get('status'), - }, - source='api', - strict=False, - ) diff --git a/backend/app/services/shipping_notice/task_supersession_service.py b/backend/app/services/shipping_notice/task_supersession_service.py index 59815325..59a90aa4 100644 --- a/backend/app/services/shipping_notice/task_supersession_service.py +++ b/backend/app/services/shipping_notice/task_supersession_service.py @@ -18,7 +18,7 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID') if not task_is_active(old): return - external = bool(old.freight_ref_no or old.upload_receipt_json or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'}) + external = bool(old.freight_ref_no or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'}) if external: existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none() if existing is None: diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 0b6a1d74..3d9da679 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -21,7 +21,6 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ValidationError from app.models import ShippingNotice -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed from app.services.shipping_notice.constants import CP_TASK_EXISTS from app.services.shipping_notice.decision_workflow import submit_decision from app.services.shipping_notice.task_order_field_editor import ( @@ -37,12 +36,9 @@ from app.services.shipping_notice.reservation_gate import task_reservation_gate_ from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.query_service import ( TaskProjection, - compute_batch_process_summary, extract_task_no_from_text, get_task_by_ref, - list_sorted_batch_tasks, resolve_task_from_payload, - serialize_batch_for_tool, serialize_task as qs_serialize_task, serialize_task_for_tool, ) @@ -53,16 +49,8 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta from app.services.shipping_notice.inventory_workflow import ensure_inventory from app.services.shipping_notice.batch_create_idempotency import ( acquire_notice_create_locks, - assert_idempotent_batch_content_matches, assert_no_exact_duplicate_notices, - build_existing_batch_tool_response, - compute_notice_items_content_fingerprint, - dedupe_notice_items_by_content_hash, - find_batch_by_create_idempotency, - handle_batch_create_integrity_error, - normalize_create_idempotency_key, ) -from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.candidate_qualification_service import ( assert_customer_confirmed_before_task_create, resolve_confirmed_bill_to_customer_id, @@ -95,46 +83,6 @@ def start_task_orchestrator(task_no: str | None) -> bool: return _start(task_no) -def recompute_batch_summary(batch: Any | None) -> None: - """写路径:shipping_batches 已删除(co8),保留空操作供历史调用方兼容。""" - del batch - - -def sync_batch_after_task_change(task: ShippingNotice | None) -> None: - """任务状态变更后刷新所属批次;shipping_batches 已删除,无操作。""" - del task - - -def create_batch(payload: dict[str, Any]) -> tuple[Any, bool]: - """ - 创建或复用发货批次壳(不含 notice 解析)。 - 【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED(co8e9f0a1b2c)。 - """ - del payload - raise_shipping_batches_removed(action='tools.create_batch') - - -def _create_single_task_batch(payload: dict[str, Any]) -> Any: - """为单票任务创建标准批次容器;shipping_batches 已删除。""" - del payload - raise_shipping_batches_removed(action='tools.create_single_task_batch') - - -def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: - """ - 一次创建批次,并为每个 notice_item 创建任务;默认将字段解析延后到 Dify 画布。 - 【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED(co8e9f0a1b2c)。 - """ - del payload - raise_shipping_batches_removed(action='tools.create_batch_tasks') - - def create_task(payload: dict[str, Any]) -> dict[str, Any]: """ 创建单个发货任务,或复用当前会话里已存在的进行中任务。 @@ -191,35 +139,27 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: checkpoint=CP_TASK_EXISTS, ) - shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id")) # [STEP] 单票建单同样要求客户已确认,禁止创建后进入 customer_review。 customer_id = _parse_optional_customer_id(payload.get("customer_id")) assert_customer_confirmed_before_task_create( - shipping_case=shipping_case, customer_id=customer_id, ) task = ShippingNotice( task_no=generate_task_no(), - shipping_case_id=shipping_case.id, + customer_id=customer_id, user_id=payload.get("user_id"), conversation_id=str(payload.get("conversation_id") or "").strip() or None, source_type=str(payload.get("source_type") or "manual"), batch_index=1, batch_total=1, raw_content=str(payload.get("raw_content") or "").strip() or None, - customer_resolution_status=( - 'confirmed' if shipping_case.customer_id is not None else 'pending' - ), - customer_resolution_method=( - 'inherited' if shipping_case.customer_id is not None else None - ), + customer_resolution_status='pending', ) db.session.add(task) log_task_event(task, "task_created", {"source_type": task.source_type}) db.session.flush() _bind_confirmed_customer_after_task_create( task, - shipping_case=shipping_case, customer_id=customer_id, candidate=None, actor_id=payload.get("user_id"), @@ -252,7 +192,6 @@ def _parse_optional_customer_id(raw: Any) -> int | None: def _bind_confirmed_customer_after_task_create( task: ShippingNotice, *, - shipping_case: Any, customer_id: int | None, candidate: ShippingOrderCandidate | None, actor_id: Any, @@ -260,12 +199,8 @@ def _bind_confirmed_customer_after_task_create( """ 创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。 - 核心逻辑:业务单已有客户则标记 inherited;否则用显式 customer_id 或候选 Bill-to 确认。 + 核心逻辑:用显式 customer_id 或候选 Bill-to 直接确认当前 Notice。 """ - if getattr(shipping_case, 'customer_id', None) is not None: - task.customer_resolution_status = 'confirmed' - task.customer_resolution_method = task.customer_resolution_method or 'inherited' - return bind_id = customer_id or resolve_confirmed_bill_to_customer_id(candidate=candidate) if bind_id is None: raise ConflictError( @@ -793,7 +728,6 @@ def replace_task_notice( extra={"warnings": cleaned_warnings}, ) log_task_event(task, "notice_replace_extract_failed", {"warnings": cleaned_warnings}) - sync_batch_after_task_change(task) db.session.commit() return tool_response( status="needs_human", @@ -834,7 +768,6 @@ def replace_task_notice( "warnings": cleaned_warnings, }, ) - sync_batch_after_task_change(task) db.session.commit() orchestrator_started = start_task_orchestrator(task.task_no) return tool_response( @@ -1046,7 +979,6 @@ def _commit_notice_edit( before_export_file_name=before_export_file_name, before_order_data_version=before_order_data_version, ) - sync_batch_after_task_change(task) db.session.commit() return tool_response( status="ok", @@ -1450,7 +1382,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]: metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)}, source=event_source, ) - sync_batch_after_task_change(task) db.session.commit() from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index efbab8f3..ea584f61 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -19,7 +19,6 @@ from flask import current_app from app import db from app.models import ShippingNotice, ShippingTaskEvent -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK @@ -267,12 +266,6 @@ def _clean_event_value(value: Any) -> str: return str(value or "").strip() -def _task_batch_no(task: ShippingNotice | None) -> str: - """从任务关系中提取批次号。""" - batch = getattr(task, "batch", None) - return _clean_event_value(getattr(batch, "batch_no", None)) - - def build_task_action_event_detail( task: ShippingNotice, *, @@ -284,7 +277,7 @@ def build_task_action_event_detail( """ 构建任务动作类事件详情。 - 核心逻辑:统一补齐 action/source/target/batch/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。 + 核心逻辑:统一补齐 action/source/target/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。 Args: task: 动作作用的目标任务。 @@ -301,7 +294,6 @@ def build_task_action_event_detail( "source": _clean_event_value(source), "target_type": "task", "target_id": _clean_event_value(getattr(task, "task_no", None)), - "batch_no": _task_batch_no(task), "conversation_id": _clean_event_value(getattr(task, "conversation_id", None)), } normalized_comment = _clean_event_value(comment) @@ -588,21 +580,3 @@ def log_task_action_event( ) -def switch_batch_focus( - batch: Any, - task: ShippingNotice, - *, - source: str, - event_type: str = "focus_switched", - comment: str | None = None, - emit_when_unchanged: bool = True, - extra: dict[str, Any] | None = None, -) -> bool: - """ - 切换批次焦点任务并写入标准事件。 - - Raises: - ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。 - """ - del batch, task, source, event_type, comment, emit_when_unchanged, extra - raise_shipping_batches_removed() diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index bb5d6b7e..f2699515 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -93,7 +93,7 @@ def tool_response( Args: stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。 forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。 - extra: 需要保留在顶层的兼容字段,例如 batch_no。 + extra: 需要保留在顶层的额外业务字段。 """ from app.services.shipping_notice.state_machine import resolve_task_ui_state diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 52cd0a18..62efdde8 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -17,9 +17,7 @@ from app.services.shipping_notice import ( from app.services.shipping_notice import customer_identity_gate -# 任务 / 批次 / 决策 -create_batch = task_workflow.create_batch -create_batch_tasks = task_workflow.create_batch_tasks +# 任务 / 决策 create_task = task_workflow.create_task auto_progress = task_workflow.auto_progress submit_decision = task_workflow.submit_decision diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 587f8a26..2a2b3e53 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -1,16 +1,15 @@ """ services/shipping_notice/ui_state.py -用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 +用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、 process_gate_projection(统一 Gate 用户摘要)、 order_review_workbench_projection.apply_post_ot_gate_rules。 逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions, - 再补充四阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、 + 再补充五阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、 stp_facts、progress_nodes); 若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影; Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办); - 批次 UI 仅作会话上传集合摘要,不作为履约写操作面。 """ from __future__ import annotations @@ -18,7 +17,6 @@ from __future__ import annotations from typing import Any from app.models import ShippingNotice -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed from app.services.shipping_notice.constants import ( CP_COMPLETED, CP_CUSTOMER_REVIEW, @@ -53,13 +51,7 @@ from app.services.shipping_notice.lifecycle_projection import ( LIFECYCLE_STAGES, project_lifecycle, ) -from app.services.shipping_notice.query_service import ( - compute_batch_process_summary, - list_sorted_batch_tasks, - resolve_task_export_download, - serialize_batch_summary, - serialize_task_summary, -) +from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary from app.services.shipping_notice.state_machine import ( CheckpointKind, resolve_task_ui_state, @@ -71,41 +63,10 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = ( {"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"}, {"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"}, {"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "通知准备"}, - {"id": "shipping-stage-4", "code": "upload_complete", "label": "通知完成"}, + {"id": "shipping-stage-4", "code": "freight_upload", "label": "货代上传"}, + {"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"}, ) -_CURRENT_STEP_INDEX_MAP: dict[str, int] = { - "step1_notice_submit": 0, - "step2_parse_confirm": 1, - "step3_inventory_prepare": 2, - "step2_inventory_prepare": 2, - "step4_align_confirm": 3, - "step5_match_inventory": 4, - "step3_inventory_match": 4, - "step4_shortage_review": 4, - "step6_generate_file": 5, - "step5_export_excel": 5, - "step7_upload_freight": 6, - "step6_upload_freight": 6, - "step7_finish": 6, -} - -_TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"} -_BLOCKED_CHECKPOINTS = { - CP_PARSE_REVIEW, - CP_RSV_REQ, - CP_INVENTORY_SOURCE_REVIEW, - CP_ORDER_FREEZE, - RS_SHORTAGE_REVIEW, - CP_NOTICE_TEXT_EXTRACTION_FAILED, - CP_UPLOAD_REQ, - CP_UPLOAD_FAILED, - CP_UPLOAD_RESULT_UNKNOWN, - CP_CUSTOMER_REVIEW, - CP_EXPORT_READY, - CP_EXPORT_GENERATED, -} - _REVIEW_ENTRY_CHECKPOINTS = { CP_PARSE_REVIEW, CP_RSV_REQ, @@ -131,45 +92,17 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = { CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"), CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"), CP_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"), - CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"), - CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"), + CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), + CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), } -# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。 -_STAGE_CHECKPOINT_CODES: dict[str, str] = { - CP_PARSE_REVIEW: "order_review", - CP_RSV_REQ: "order_review", - CP_CUSTOMER_REVIEW: "order_review", - CP_ORDER_FREEZE: "order_review", - CP_INVENTORY_SOURCE_REVIEW: "fulfillment_prep", - CP_INVENTORY_PENDING: "fulfillment_prep", - CP_READY_MATCH: "fulfillment_prep", - RS_SHORTAGE_REVIEW: "fulfillment_prep", - CP_READY_EXPORT: "fulfillment_prep", - CP_EXPORT_READY: "fulfillment_prep", - CP_EXPORT_GENERATED: "fulfillment_prep", - CP_WAITING_UPLOAD: "upload_complete", - CP_UPLOAD_REQ: "fulfillment_prep", - CP_UPLOAD_FAILED: "upload_complete", - CP_UPLOAD_RESULT_UNKNOWN: "upload_complete", - CP_UPLOADED: "upload_complete", - CP_COMPLETED: "upload_complete", - CP_REJECTED: "order_review", -} - - def _task_lifecycle( *, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None, ) -> dict[str, Any]: - """以共享裁决器投影正式任务生命周期;旧 checkpoint 仅作无 Gate 的兼容兜底。""" + """以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。""" gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate') - legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or '')) - if legacy_stage is None: - legacy_stage = 'upload_complete' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None - if legacy_stage is None: - # 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。 - legacy_index = _derive_current_step_index(task) - legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete')[legacy_index] + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + return project_lifecycle( current_gate=gate if isinstance(gate, dict) else None, blocking_reason=( @@ -177,16 +110,18 @@ def _task_lifecycle( if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code') else None ), - legacy_stage=legacy_stage, # ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。 has_candidate_context=True, + verified_upload_success=has_verified_upload_success(task), ) def _business_stage(lifecycle: dict[str, Any]) -> dict[str, Any]: - """将共享生命周期结果包装为任务详情既有的阶段 DTO。""" - stage_code = str(lifecycle.get('lifecycle_stage') or 'intake_parse') - index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), 0) + """将共享生命周期结果包装为任务详情阶段 DTO;无正式事实时不猜阶段。""" + stage_code = str(lifecycle.get('lifecycle_stage') or '') + index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), None) + if index is None: + return {'code': 'unclassified', 'label': '状态待同步', 'index': 0, 'total': len(LIFECYCLE_STAGES)} return {**LIFECYCLE_STAGES[index], 'index': index + 1, 'total': len(LIFECYCLE_STAGES)} @@ -247,47 +182,6 @@ def _unified_actions(*, process_gate: dict[str, Any] | None) -> dict[str, Any]: return {"primary": primary, "secondary": secondary} -def _derive_current_step_index(task: ShippingNotice) -> int: - """ - 根据任务领域事实推导四阶段流程当前索引。 - - 核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。 - """ - current_step = str(task.current_step or "").strip() - if current_step in _CURRENT_STEP_INDEX_MAP: - legacy_index = _CURRENT_STEP_INDEX_MAP[current_step] - return 0 if legacy_index <= 0 else 1 if legacy_index == 1 else 3 if legacy_index >= 6 else 2 - - review_status = str(task.review_status or "").strip() - pending_reason = str(task.pending_human_reason or "").strip() - match_status = str(task.match_status or "").strip() - upload_status = str(getattr(task, "upload_status", None) or "").strip().lower() - has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip()) - - if upload_status in {"uploaded", "succeeded", "success"} or str(getattr(task, "lifecycle_status", "") or "").lower() in {"archived", "deleted"}: - return 3 - if upload_status in {"pending", "uploading", "failed"} or has_export: - return 2 - if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}: - return 2 - if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE: - return 2 - if task.inventory_lines_json or match_status: - return 2 - if pending_reason in { - PH_RPA_PENDING, - PH_INV_UNAVAIL, - PH_RPA_EXHAUSTED, - }: - return 2 - if review_status in { - RS_PARSE_REVIEW, - PH_RSV_REQ, - } or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}: - return 1 - return 0 - - def build_shipping_workflow_steps( task: ShippingNotice, checkpoint: str | None, @@ -295,7 +189,7 @@ def build_shipping_workflow_steps( lifecycle_stage: str | None = None, ) -> list[dict[str, str]]: """ - 构造四阶段流程状态。 + 构造五阶段流程状态。 Returns: list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。 @@ -304,32 +198,22 @@ def build_shipping_workflow_steps( (index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage), None, ) - # 正式 Gate 已存在时,四阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。 - current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task) - pending_reason = str(task.pending_human_reason or "").strip() - checkpoint_value = str(checkpoint or "").strip() + # 五阶段只使用共享生命周期裁决;缺少正式事实时全部保持 pending。 + current_index = lifecycle_index steps: list[dict[str, str]] = [] for index, step in enumerate(WORKFLOW_STEPS): - if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}: + # ``upload_complete`` 已由唯一成功谓词裁决。历史 Task.upload_status 不能让 + # 流程条伪装为完成,否则会与 lifecycle_entries 和批次完成率分叉。 + if lifecycle_stage == "upload_complete": status = "completed" + elif current_index is None: + status = "pending" elif index < current_index: status = "completed" elif index == current_index: status = "current" else: status = "pending" - inventory_blocked = index == 2 and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED} - parse_blocked = index == 1 and ( - checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_NOTICE_TEXT_EXTRACTION_FAILED} - or pending_reason in {"low_confidence", PH_RSV_REQ} - ) - prep_blocked = index == 2 and ( - checkpoint_value in {CP_INVENTORY_SOURCE_REVIEW, RS_SHORTAGE_REVIEW} - or pending_reason in {PH_INVENTORY_SOURCE_UNRESOLVED, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_SHORTAGE} - ) - upload_blocked = index == 3 and str(getattr(task, "upload_status", None) or "").strip().lower() == "failed" - if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked or prep_blocked or upload_blocked): - status = "blocked" steps.append({**step, "status": status}) return steps @@ -586,9 +470,9 @@ def _build_task_summary( RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。", CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。", CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。", - CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", - CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", - CP_WAITING_UPLOAD: "待人工上传登记:请下载 Excel,在货代平台上传后于本系统登记凭据。", + CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", + CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", + CP_WAITING_UPLOAD: "待人工上传确认:请下载 Excel,在货代平台上传后于本系统确认已上传。", CP_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。", CP_REJECTED: "任务已驳回,无需继续处理。", CP_UPLOADED: "任务已完成上传。", @@ -664,7 +548,7 @@ def _build_stage_context( stp_facts: dict[str, Any] | None, process_gate: dict[str, Any] | None, ) -> dict[str, Any]: - """构造四阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。 + """构造五阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。 通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成 只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。 @@ -834,13 +718,17 @@ def _build_stage_context( ShippingExportArtifact.task_id == task.id, ).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all() latest_attempt = attempts[0] if attempts else None + succeeded_attempt = next( + (item for item in attempts if str(getattr(item, 'status', '') or '').lower() == 'succeeded'), + None, + ) latest_status = str(getattr(latest_attempt, 'status', '') or '').lower() upload_outcome = ( 'succeeded' if latest_status == 'succeeded' else 'failed' if latest_status in {'failed', 'timed_out'} else 'unknown' if latest_status == 'unknown' else 'running' if latest_status in {'pending', 'running'} else - 'awaiting_manual' if lifecycle_stage == 'upload_complete' else + 'awaiting_manual' if lifecycle_stage == 'freight_upload' else 'not_started' ) return { @@ -869,6 +757,15 @@ def _build_stage_context( }, 'upload': { 'outcome': upload_outcome, + # 成功工作面只能消费该不可变成功事实,而非“最近一条 Attempt”。后者可能 + # 是迟到失败或人工核对记录,不能反向定义完成证据。 + 'succeeded_attempt': ({ + 'id': succeeded_attempt.id, + 'status': succeeded_attempt.status, + 'mode': succeeded_attempt.mode, + 'freight_ref_no': succeeded_attempt.freight_ref_no, + 'finished_at': succeeded_attempt.finished_at.isoformat() if succeeded_attempt.finished_at else None, + } if succeeded_attempt is not None else None), 'latest_attempt': ({ 'id': latest_attempt.id, 'status': latest_attempt.status, @@ -930,7 +827,7 @@ def build_task_ui_state( 'enabled': True, # Artifact 已验证是下载授权的唯一来源;它直接声明展示位置, # 不依赖旧 checkpoint 或 action code 位置映射。 - 'target_surface': 'upload_complete', + 'target_surface': 'freight_upload', 'target_anchor': 'excel_artifact', }, default_kind='view') action_codes = { @@ -967,7 +864,6 @@ def build_task_ui_state( } return { "task_no": task.task_no, - "batch_no": None, "stage": stage, "lifecycle_stage": stage["code"], "lifecycle_entries": lifecycle['lifecycle_entries'], @@ -1034,12 +930,3 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] ) -def build_batch_ui_state(batch: Any) -> dict[str, Any]: - """ - 构建批次级会话上传集合摘要(非履约写操作面)。 - - Raises: - ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。 - """ - del batch - raise_shipping_batches_removed() diff --git a/backend/app/services/shipping_notice/upload_attempt_service.py b/backend/app/services/shipping_notice/upload_attempt_service.py index fece748e..f9cbd227 100644 --- a/backend/app/services/shipping_notice/upload_attempt_service.py +++ b/backend/app/services/shipping_notice/upload_attempt_service.py @@ -1,8 +1,8 @@ """ services/shipping_notice/upload_attempt_service.py -用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工回执证据。 -依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、FileAsset、任务状态机。 +用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认。 +依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。 逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,Task 字段仅保留聚合投影。 """ @@ -21,7 +21,6 @@ from app.models import ( ShippingNotice, ShippingUploadAttempt, ) -from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced def current_upload_artifact(task: ShippingNotice, artifact_id: int | None = None) -> ShippingExportArtifact: @@ -80,6 +79,39 @@ def _aggregate_task_upload_status(task: ShippingNotice) -> None: task.upload_status = 'pending' +def has_verified_upload_success(task: ShippingNotice) -> bool: + """判断任务是否具备可审计的货代上传成功事实。 + + 业务完成必须同时满足 Task 聚合、全部预约单和成功 Attempt 三层事实;历史字段、 + 单独外部参考或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次 + 已完成分组与停止轮询共用的唯一成功谓词。 + """ + try: + from flask import has_app_context + if not has_app_context(): + return False + except Exception: # pragma: no cover - standalone/domain tests without Flask + return False + # 完成率只统计当前有效任务。已作废/归档的历史成功事实必须保留审计, + # 但不能再投影为「通知完成」或进入完成分母/分子。 + if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in { + 'voided', 'archived', 'deleted', 'cancelled', + }: + return False + if getattr(task, 'id', None) is None or str(task.upload_status or '').strip().lower() != 'uploaded': + return False + reservations = ShippingReservation.query.filter_by(task_id=task.id).all() + if not reservations or any(row.status != 'uploaded' for row in reservations): + return False + return db.session.query(ShippingUploadAttempt.id).join( + ShippingExportArtifact, + ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id, + ).filter( + ShippingExportArtifact.task_id == task.id, + ShippingUploadAttempt.status == 'succeeded', + ).first() is not None + + def complete_attempt( attempt: ShippingUploadAttempt, *, success: bool, callback_id: str, freight_ref_no: str | None = None, error_message: str | None = None, @@ -149,41 +181,36 @@ def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploa return attempt -def record_manual_upload(task: ShippingNotice, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt: - """登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。""" - asset_no = str(evidence_asset_no or '').strip() - receipt_no = str(freight_ref_no or '').strip() - if not asset_no or not receipt_no: - raise ValidationError( - 'Manual upload receipt number and evidence are required', - code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED', - details={'reason_code': 'close_blocked_missing_receipt'}, - ) +def record_manual_upload(task: ShippingNotice, *, artifact_id: int | None, operator_id: int) -> ShippingUploadAttempt: + """ + 确认指定 Excel 已由人工上传;仅记录目标 Artifact 与服务端操作人,不再采集回执或截图/PDF。 + + Args: + task: 目标发货通知任务,必须处于可履约状态。 + artifact_id: 当前通知单唯一待上传 Excel 的 Artifact 主键;为空时服务端选择唯一可上传 Artifact。 + operator_id: 服务端会话中的操作人主键,禁止由客户端伪造。 + + Returns: + ShippingUploadAttempt: 已成功的人工上传确认尝试。 + + Raises: + ConflictError: 任务或 Artifact 不再允许上传时抛出。 + """ 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 if not task_is_active(task): raise ConflictError('Inactive task cannot be manually uploaded', code='SHIPPING.TASK_LIFECYCLE_CONFLICT') assert_task_not_supersession_blocked(task) artifact = current_upload_artifact(task, artifact_id) - asset = get_asset_for_user(asset_no, operator_id) - if asset.upload_status != 'ready' or asset.deleted_at is not None: - raise ValidationError( - 'Manual upload evidence is unavailable', - code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED', - details={'reason_code': 'close_blocked_missing_receipt'}, - ) attempt = ShippingUploadAttempt( artifact_id=artifact.id, attempt_no=ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() + 1, mode='manual', idempotency_key=f'manual:{artifact.id}:{uuid.uuid4().hex}', - status='running', started_at=datetime.utcnow(), evidence_asset_id=asset.id, operator_id=operator_id, + status='running', started_at=datetime.utcnow(), operator_id=operator_id, ) db.session.add(attempt) db.session.flush() - mark_asset_referenced(asset) - return complete_attempt( - attempt, success=True, callback_id=f'manual:{attempt.id}', freight_ref_no=receipt_no, - ) + return complete_attempt(attempt, success=True, callback_id=f'manual:{attempt.id}') def void_rejected_artifact(task: ShippingNotice, *, artifact_id: int, operator_id: int, reason: str) -> ShippingExportArtifact: diff --git a/backend/migrations/versions/hm6n7o8p9q0r_remove_legacy_shipping_apx_runtime.py b/backend/migrations/versions/hm6n7o8p9q0r_remove_legacy_shipping_apx_runtime.py new file mode 100644 index 00000000..6928bfa6 --- /dev/null +++ b/backend/migrations/versions/hm6n7o8p9q0r_remove_legacy_shipping_apx_runtime.py @@ -0,0 +1,67 @@ +"""移除已下线 APX 自动推进运行时。 + +用途:收口遗留 APX Execution/Job 并删除仅服务旧六门禁运行时的唯一索引。 +依赖:shipping_process_executions、shipping_process_gates、jobs。 +逻辑:正式 20-Gate 是唯一运行态;迁移只终止 APX 记录,绝不改写正式 Execution、STP、Excel 或 RPA Job。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'hm6n7o8p9q0r' +down_revision = 'hk5l6m7n8o9p' +branch_labels = None +depends_on = None + + +def _indexes(table: str) -> set[str]: + """读取索引名,保证不同环境重复升级安全。""" + return {str(item.get('name') or '') for item in sa.inspect(op.get_bind()).get_indexes(table)} + + +def upgrade() -> None: + """终态化 APX 旧运行记录,再删除旧类型唯一索引。""" + bind = op.get_bind() + bind.execute(sa.text(""" + UPDATE jobs + SET status = 'cancelled', finished_at = COALESCE(finished_at, CURRENT_TIMESTAMP), + message = 'legacy APX auto-progress runtime removed' + WHERE domain = 'shipping_notice' + AND job_type = 'shipping_auto_progress' + AND status IN ('queued', 'running', 'active') + """)) + bind.execute(sa.text(""" + UPDATE shipping_process_gates + SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP + WHERE execution_id IN ( + SELECT id FROM shipping_process_executions WHERE execution_no LIKE 'APX-%' + ) + AND status IN ('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated') + """)) + bind.execute(sa.text(""" + UPDATE shipping_process_executions + SET status = 'superseded', updated_at = CURRENT_TIMESTAMP + WHERE execution_no LIKE 'APX-%' + AND status IN ('active', 'blocked', 'waiting_external') + """)) + if 'uq_jobs_shipping_auto_progress_one_active_task' in _indexes('jobs'): + op.drop_index('uq_jobs_shipping_auto_progress_one_active_task', table_name='jobs') + + +def downgrade() -> None: + """仅恢复旧索引定义;已终态化的 APX 记录不应被自动复活。""" + if 'uq_jobs_shipping_auto_progress_one_active_task' not in _indexes('jobs'): + 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" + ), + ) diff --git a/backend/migrations/versions/hn7o8p9q0r1s_add_notice_business_number.py b/backend/migrations/versions/hn7o8p9q0r1s_add_notice_business_number.py new file mode 100644 index 00000000..144af933 --- /dev/null +++ b/backend/migrations/versions/hn7o8p9q0r1s_add_notice_business_number.py @@ -0,0 +1,64 @@ +"""为 ShippingNotice 增加独立发货通知业务编号。 + +用途:支持同一 PO 多个发货通知单各自拥有 business_no。 +依赖:shipping_notices、shipping_cases、shipping_business_sequences。 +逻辑:新增可空字段并从旧 Case 回填仅能唯一映射的历史 Notice;无法唯一映射的记录保留空值等待业务迁移。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = 'hn7o8p9q0r1s' +down_revision = 'hm6n7o8p9q0r' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增 Notice 编号字段并安全回填一对一历史映射。""" + inspector = sa.inspect(op.get_bind()) + columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + with op.batch_alter_table('shipping_notices') as batch: + if 'business_no' not in columns: + batch.add_column(sa.Column('business_no', sa.String(length=32), nullable=True)) + if 'business_date' not in columns: + batch.add_column(sa.Column('business_date', sa.Date(), nullable=True)) + if 'business_sequence_value' not in columns: + batch.add_column(sa.Column('business_sequence_value', sa.Integer(), nullable=True)) + if 'business_numbering_rule_version' not in columns: + batch.add_column(sa.Column('business_numbering_rule_version', sa.String(length=32), nullable=True)) + indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')} + if 'ix_shipping_notices_business_no' not in indexes: + batch.create_index('ix_shipping_notices_business_no', ['business_no'], unique=False) + uniques = {item['name'] for item in inspector.get_unique_constraints('shipping_notices')} + if 'uq_shipping_notices_business_no' not in uniques: + batch.create_unique_constraint('uq_shipping_notices_business_no', ['business_no']) + + bind = op.get_bind() + bind.execute(sa.text(""" + UPDATE shipping_notices AS n + SET business_no = c.business_no, + business_date = c.business_date, + business_sequence_value = c.sequence_value, + business_numbering_rule_version = c.numbering_rule_version + FROM shipping_cases AS c + WHERE n.shipping_case_id = c.id + AND c.business_no IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM shipping_notices AS other + WHERE other.business_no = c.business_no AND other.id <> n.id + ) + """)) + + +def downgrade() -> None: + """移除 Notice 独立编号字段;旧 Case 编号仍保留。""" + with op.batch_alter_table('shipping_notices') as batch: + batch.drop_constraint('uq_shipping_notices_business_no', type_='unique') + batch.drop_index('ix_shipping_notices_business_no') + batch.drop_column('business_numbering_rule_version') + batch.drop_column('business_sequence_value') + batch.drop_column('business_date') + batch.drop_column('business_no') diff --git a/backend/migrations/versions/ho8p9q0r1s2t_notice_customer_facts.py b/backend/migrations/versions/ho8p9q0r1s2t_notice_customer_facts.py new file mode 100644 index 00000000..fdfb0f5f --- /dev/null +++ b/backend/migrations/versions/ho8p9q0r1s2t_notice_customer_facts.py @@ -0,0 +1,60 @@ +"""将客户身份事实迁移到 ShippingNotice。 + +用途:支持 Notice 在不依赖 ShippingCase 的情况下完成客户确认、业务编号和履约。 +依赖:shipping_notices、shipping_customers、shipping_cases。 +逻辑:新增 Notice 客户字段并从历史 Case 回填;旧 Case 外键暂留只读兼容。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'ho8p9q0r1s2t' +down_revision = 'hn7o8p9q0r1s' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增 Notice 客户字段并回填历史 Case 客户事实。""" + inspector = sa.inspect(op.get_bind()) + columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + with op.batch_alter_table('shipping_notices') as batch: + if 'customer_id' not in columns: + batch.add_column(sa.Column('customer_id', sa.Integer(), nullable=True)) + if 'customer_name_snapshot' not in columns: + batch.add_column(sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True)) + if 'customer_short_code_snapshot' not in columns: + batch.add_column(sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True)) + indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')} + if 'ix_shipping_notices_customer_id' not in indexes: + batch.create_index('ix_shipping_notices_customer_id', ['customer_id'], unique=False) + foreign_keys = {item.get('name') for item in inspector.get_foreign_keys('shipping_notices')} + if 'fk_shipping_notices_customer_id' not in foreign_keys: + batch.create_foreign_key( + 'fk_shipping_notices_customer_id', 'shipping_customers', ['customer_id'], ['id'], + ) + + bind = op.get_bind() + bind.execute(sa.text(""" + UPDATE shipping_notices AS n + SET customer_id = c.customer_id, + customer_name_snapshot = c.customer_name_snapshot, + customer_short_code_snapshot = c.customer_short_code_snapshot + FROM shipping_cases AS c + WHERE n.shipping_case_id = c.id + AND n.customer_id IS NULL + AND c.customer_id IS NOT NULL + """)) + + +def downgrade() -> None: + """回滚 Notice 客户字段;历史 Case 字段不受影响。""" + with op.batch_alter_table('shipping_notices') as batch: + batch.drop_constraint('fk_shipping_notices_customer_id', type_='foreignkey') + batch.drop_index('ix_shipping_notices_customer_id') + batch.drop_column('customer_short_code_snapshot') + batch.drop_column('customer_name_snapshot') + batch.drop_column('customer_id') diff --git a/backend/migrations/versions/hp9q0r1s2t3u_remove_shipping_case.py b/backend/migrations/versions/hp9q0r1s2t3u_remove_shipping_case.py new file mode 100644 index 00000000..6dc81b31 --- /dev/null +++ b/backend/migrations/versions/hp9q0r1s2t3u_remove_shipping_case.py @@ -0,0 +1,105 @@ +"""物理移除已废弃的 ShippingCase 聚合层。 + +用途:在历史 Notice 已自持客户与 business_no 后,删除 shipping_cases 表及 Notice 外键。 +依赖:shipping_notices、shipping_customers、shipping_business_sequences。 +逻辑:先检查残留客户/编号事实,再断开 Notice 旧外键并删除历史聚合表;不影响 Review Case 或收料 RPA。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'hp9q0r1s2t3u' +down_revision = 'ho8p9q0r1s2t' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """校验 Notice 已完成迁移后删除 Case 表和兼容字段。""" + bind = op.get_bind() + inspector = sa.inspect(bind) + if not inspector.has_table('shipping_cases'): + return + + # 历史库可能错误标记为已执行 hn/ho,但物理表仍缺少其应新增的列。 + # 最终删表迁移必须先自愈这些可由旧 Case 无损恢复的事实,不能引用缺失列。 + notice_columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + missing_columns = [ + ('business_no', sa.String(length=32)), + ('business_date', sa.Date()), + ('business_sequence_value', sa.Integer()), + ('business_numbering_rule_version', sa.String(length=32)), + ('customer_id', sa.Integer()), + ('customer_name_snapshot', sa.String(length=200)), + ('customer_short_code_snapshot', sa.String(length=6)), + ] + missing_notice_fields = {name for name, _ in missing_columns if name not in notice_columns} + with op.batch_alter_table('shipping_notices') as batch: + for name, column_type in missing_columns: + if name in missing_notice_fields: + batch.add_column(sa.Column(name, column_type, nullable=True)) + + # 重新读取反射信息,确保修复后的 PostgreSQL/SQLite 结构都用于后续约束和校验。 + inspector = sa.inspect(bind) + notice_columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + case_columns = {item['name'] for item in inspector.get_columns('shipping_cases')} + copied_fields = [ + ('business_no', 'business_no'), + ('business_date', 'business_date'), + ('business_sequence_value', 'sequence_value'), + ('business_numbering_rule_version', 'numbering_rule_version'), + ('customer_id', 'customer_id'), + ('customer_name_snapshot', 'customer_name_snapshot'), + ('customer_short_code_snapshot', 'customer_short_code_snapshot'), + ] + assignments = [ + f"{notice_field} = COALESCE(n.{notice_field}, c.{case_field})" + for notice_field, case_field in copied_fields + if notice_field in missing_notice_fields and case_field in case_columns + ] + if assignments: + bind.execute(sa.text(f""" + UPDATE shipping_notices AS n + SET {', '.join(assignments)} + FROM shipping_cases AS c + WHERE c.id = n.shipping_case_id + """)) + + # Notice 是最终事实;旧 Case 若仍有未迁移编号或客户,拒绝静默丢失。 + residual = bind.execute(sa.text(""" + SELECT COUNT(*) + FROM shipping_notices AS n + JOIN shipping_cases AS c ON c.id = n.shipping_case_id + WHERE (c.business_no IS NOT NULL AND n.business_no IS NULL) + OR (c.customer_id IS NOT NULL AND n.customer_id IS NULL) + """)).scalar_one() + if int(residual or 0): + raise RuntimeError( + f'shipping_case migration incomplete: {int(residual)} Notice rows still miss copied facts' + ) + + notice_indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')} + notice_fks = inspector.get_foreign_keys('shipping_notices') + with op.batch_alter_table('shipping_notices') as batch: + for fk in notice_fks: + referred = str(fk.get('referred_table') or '') + columns = set(fk.get('constrained_columns') or []) + if referred == 'shipping_cases' and 'shipping_case_id' in columns: + if fk.get('name'): + batch.drop_constraint(fk['name'], type_='foreignkey') + if 'ix_shipping_notices_shipping_case_id' in notice_indexes: + batch.drop_index('ix_shipping_notices_shipping_case_id') + if 'shipping_case_id' in notice_columns: + batch.drop_column('shipping_case_id') + + # PostgreSQL 的 UNIQUE 约束拥有同名底层索引,不能先以 index 操作删除; + # DROP TABLE 会一并清理 Case 表上的普通索引和约束索引。 + op.drop_table('shipping_cases') + + +def downgrade() -> None: + """不自动恢复已删除的历史 Case 数据。""" + raise RuntimeError('ShippingCase removal migration is irreversible') diff --git a/backend/scripts/audit_apx_runtime_state.py b/backend/scripts/audit_apx_runtime_state.py deleted file mode 100644 index dd9bc930..00000000 --- a/backend/scripts/audit_apx_runtime_state.py +++ /dev/null @@ -1,25 +0,0 @@ -""" -只读清点目标数据库中的 APX 运行态。 - -用法:在目标环境加载现有环境变量后执行 `python scripts/audit_apx_runtime_state.py`。 -本脚本只执行查询并输出 JSON,不迁移、不取消、不删除任何记录。 -""" - -from __future__ import annotations - -import json - -from app import create_app -from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state - - -def main() -> None: - """加载生产配置并输出 APX 只读清点结果。""" - app = create_app() - with app.app_context(): - print(json.dumps(audit_apx_runtime_state(), ensure_ascii=False, indent=2, sort_keys=True)) - - -if __name__ == '__main__': - main() - diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index fd2a67b1..2fe061df 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -251,7 +251,7 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction db.session.flush() extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) - customer = getattr(getattr(task, 'shipping_case', None), 'customer', None) + customer = getattr(task, 'customer', None) if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by( extraction_id=extraction.id, role='bill_to', ).one_or_none() is None: diff --git a/backend/tests/jobs/test_runner.py b/backend/tests/jobs/test_runner.py index 6cf11607..7d917e9c 100644 --- a/backend/tests/jobs/test_runner.py +++ b/backend/tests/jobs/test_runner.py @@ -36,7 +36,7 @@ def test_handler_error_rolls_back_before_mark_failed(monkeypatch): class _Db: session = _Session() - job = {'id': 939, 'job_type': 'shipping_auto_progress', 'attempts': 1, 'payload': {}} + job = {'id': 939, 'job_type': 'shipping_process_gate', 'attempts': 1, 'payload': {}} monkeypatch.setattr(runner.store, 'claim_next', lambda **_kwargs: job) monkeypatch.setattr(runner, 'get_handler', lambda _job_type: lambda *_args: (_ for _ in ()).throw(RuntimeError('db failed'))) monkeypatch.setattr(runner.store, 'mark_failed', lambda *_args, **_kwargs: (events.append('mark_failed'), (_ for _ in ()).throw(StopIteration))) diff --git a/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py b/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py index 5448d3e3..08e34f3e 100644 --- a/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py +++ b/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py @@ -16,7 +16,7 @@ from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingBusinessSequence, - ShippingCase, + ShippingNotice, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -74,14 +74,14 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app): @pytest.mark.parametrize('reference_kind', [ - 'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', + 'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', ]) def test_business_and_audit_references_block_delete(app, reference_kind: str): """每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。""" with app.app_context(): customer = _customer() - if reference_kind == 'case': - db.session.add(ShippingCase(case_no='CASE-LIFECYCLE', customer_id=customer.id)) + if reference_kind == 'notice': + db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id)) elif reference_kind == 'sequence': db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16))) elif reference_kind == 'external_ref': @@ -194,14 +194,14 @@ def test_delete_unused_customer_cascades_configurable_identity_evidence(app): @pytest.mark.parametrize('reference_kind', [ - 'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', + 'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', ]) def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str): """永久删除必须复用完整生命周期统计,任一业务或审计引用均返回冲突。""" with app.app_context(): customer = _customer('BLK') - if reference_kind == 'case': - db.session.add(ShippingCase(case_no='CASE-DELETE-BLOCK', customer_id=customer.id)) + if reference_kind == 'notice': + db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id)) elif reference_kind == 'sequence': db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16))) elif reference_kind == 'external_ref': @@ -267,13 +267,13 @@ def test_delete_blocks_reference_created_after_preview(app): preview = get_customer_lifecycle_impact(customer.id) assert preview['can_delete'] is True - db.session.add(ShippingCase(case_no='CASE-DELETE-RACE', customer_id=customer.id)) + db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id)) db.session.commit() with pytest.raises(ConflictError) as exc_info: delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None) assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED' - assert exc_info.value.details['blockers']['business_cases'] == 1 + assert exc_info.value.details['blockers']['shipping_notices'] == 1 assert db.session.get(ShippingCustomer, customer.id) is not None diff --git a/backend/tests/services/admin/test_shipping_customer_merge_service.py b/backend/tests/services/admin/test_shipping_customer_merge_service.py index a4d308b8..0d311e3f 100644 --- a/backend/tests/services/admin/test_shipping_customer_merge_service.py +++ b/backend/tests/services/admin/test_shipping_customer_merge_service.py @@ -16,7 +16,7 @@ from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( ShippingBusinessSequence, - ShippingCase, + ShippingNotice, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -71,8 +71,8 @@ def test_merge_moves_future_configuration_and_preserves_history(app): normalized_value='same@example.com', status='approved', source='manual', ), ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'), - ShippingCase( - case_no='CASE-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601', + ShippingNotice( + task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601', customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code, ), ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1), @@ -82,7 +82,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app): target_id = target.id preview = get_customer_merge_impact(source_id, target_id) - assert preview['historical_references']['business_cases'] == 1 + assert preview['historical_references']['shipping_notices'] == 1 # 合并预检同时展示旧识别证据与阶段一可配置证据的迁移统计。 assert preview['migrate'] == { 'identifiers': 1, 'duplicate_identifiers': 1, 'identity_evidences': 0, @@ -105,10 +105,10 @@ def test_merge_moves_future_configuration_and_preserves_history(app): assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source_id).count() == 0 assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2 assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1 - historical_case = db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-HISTORY').one() - assert historical_case.customer_id == source_id - assert historical_case.business_no == 'SRC26071601' - assert historical_case.customer_short_code_snapshot == 'SRC' + historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one() + assert historical_notice.customer_id == source_id + assert historical_notice.business_no == 'SRC26071601' + assert historical_notice.customer_short_code_snapshot == 'SRC' assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1 merge = db.session.get(ShippingCustomerMerge, result['merge_id']) assert merge is not None and merge.source_customer_id_snapshot == source_id diff --git a/backend/tests/services/admin/test_shipping_customer_service.py b/backend/tests/services/admin/test_shipping_customer_service.py index fdb722c4..cf69f314 100644 --- a/backend/tests/services/admin/test_shipping_customer_service.py +++ b/backend/tests/services/admin/test_shipping_customer_service.py @@ -13,7 +13,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ValidationError -from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent +from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice from app.services.admin.shipping_customer_service import ( create_customer, create_identifier, @@ -219,7 +219,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app): """列表返回业务单和识别证据数量,避免管理端逐客户补查。""" with app.app_context(): customer = _create_customer() - db.session.add(ShippingCase(case_no='CASE-COUNT-1', customer_id=customer['id'])) + db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id'])) db.session.add(ShippingCustomerIdentifier( customer_id=customer['id'], identifier_type='name_alias', @@ -231,5 +231,5 @@ def test_customer_list_returns_preaggregated_reference_counts(app): db.session.commit() result = list_customers({'page': 1, 'page_size': 20}) - assert result['items'][0]['case_count'] == 1 + assert result['items'][0]['notice_count'] == 1 assert result['items'][0]['identifier_count'] == 1 diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py index 52795c17..68695869 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -1,8 +1,8 @@ """ tests/services/shipping_notice/test_reconciliation_phase34_contract.py -用途:Phase 3 统一 Projection 四事实 + Phase 4 管理端 replay 权限 + - BRANCH F ownership_anomaly rollback 的合同测试。 +用途:Phase 3 统一 Projection 四事实 + Phase 4 BRANCH F + ownership_anomaly rollback 的合同测试。 依赖:recovery_contract、reconciliation_projector、 reconciliation_service.reconcile_and_progress(mock 掉 DB 层仅验证纯函数矩阵)。 逻辑: @@ -14,9 +14,6 @@ tests/services/shipping_notice/test_reconciliation_phase34_contract.py 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 降级情形,Review Case 不含旧流程字段)。 @@ -287,7 +284,7 @@ def test_pending_order_freeze_readiness_waits_for_the_user_to_submit_validation( # ============================================================ -# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询) +# [P4] BRANCH F 归属异常(通过 monkeypatch 替换锁 DB 查询) # ============================================================ def _mock_case_for_p4(case_no='CASE-2608-0042'): @@ -372,72 +369,6 @@ def _install_minimal_mocks(monkeypatch, case=None, app=None): 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 降级(Review Case 不含旧流程字段) # ============================================================ diff --git a/backend/tests/test_admin_shipping_customers.py b/backend/tests/test_admin_shipping_customers.py index 44c3f945..d0ff6695 100644 --- a/backend/tests/test_admin_shipping_customers.py +++ b/backend/tests/test_admin_shipping_customers.py @@ -11,7 +11,6 @@ from __future__ import annotations from app import db from app.models import ( FileAsset, - ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingIdentityDefinition, @@ -328,7 +327,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers( customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active') db.session.add(customer) db.session.flush() - db.session.add(ShippingCase(case_no='CASE-DELETE-API', customer_id=customer.id)) + db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id)) db.session.commit() customer_id = customer.id @@ -364,7 +363,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history( customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias', normalized_value='SOURCEALIAS', status='approved', source='manual', ), - ShippingCase(case_no='CASE-MERGE-API', customer_id=source.id, business_no='SRC26071601'), + ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'), ]) db.session.commit() source_id = source.id @@ -397,7 +396,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history( with app.app_context(): assert db.session.get(ShippingCustomer, source_id).status == 'merged' assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1 - assert db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-API').one().customer_id == source_id + assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client): @@ -517,11 +516,10 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli _create_users() wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active') correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active') - case = ShippingCase(case_no='CASE-CORRECTION-API', numbering_status='pending') - db.session.add_all([wrong, correct, case]) + db.session.add_all([wrong, correct]) db.session.flush() task = ShippingNotice( - task_no='SN-CORRECTION-API', shipping_case_id=case.id, + task_no='SN-CORRECTION-API', source_type='manual', customer_resolution_status='pending', ) db.session.add(task) @@ -529,7 +527,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli from app.services.shipping_notice.customer_identity_gate import confirm_task_customer confirm_task_customer(task, customer_id=wrong.id, actor_id=None) - old_business_no = task.shipping_case.business_no + old_business_no = task.business_no correct_id = correct.id forbidden = client.post( @@ -549,7 +547,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli assert payload['old_business_no'] == old_business_no assert payload['new_business_no'].startswith('NEW') with app.app_context(): - old_case = ShippingCase.query.filter_by(business_no=old_business_no).one() - replacement = ShippingCase.query.filter_by(replaces_case_id=old_case.id).one() - assert old_case.status == 'voided' + old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one() + replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one() + assert old_notice.lifecycle_status == 'voided' assert replacement.business_no == payload['new_business_no'] diff --git a/backend/tests/test_agent_registry_handlers.py b/backend/tests/test_agent_registry_handlers.py index 376e7641..11601d41 100644 --- a/backend/tests/test_agent_registry_handlers.py +++ b/backend/tests/test_agent_registry_handlers.py @@ -26,7 +26,6 @@ def test_shipping_handler_builds_ui_state_event(app): external_conversation_id=None, request_id='req-1', shipping_task_id='SN-TEST-001', - shipping_batch_no='SB-TEST', ) event = handler.build_ui_state_event(ctx) assert event is None or event.get('event') == 'shipping_ui_state' diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py index ae90ef11..c46bdf6e 100644 --- a/backend/tests/test_chat_turn_runtime.py +++ b/backend/tests/test_chat_turn_runtime.py @@ -63,21 +63,11 @@ def _create_task_for_user(user_id: int) -> str: return task.task_no -def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch): +def test_chat_turn_rejects_legacy_fulfillment_action(app, client): user = _create_user() agent = _create_shipping_agent() task_no = _create_task_for_user(user.id) - monkeypatch.setattr( - "app.services.shipping_notice.chat_action_handlers.submit_decision", - lambda payload: { - "status": "ok", - "message": "已确认,请继续下一步。", - "task_id": task_no, - "data": {}, - }, - ) - res = client.post( "/api/chat/turns/stream", headers={ @@ -99,14 +89,8 @@ def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch) events = _parse_sse_events(res.get_data(as_text=True)) event_names = [item.get("event") for item in events] assert "run.started" in event_names - assert "step.started" in event_names - assert "message.completed" in event_names or "message_end" in event_names - assert "run.completed" in event_names - - logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all() - assert len(logs) == 1 - assert logs[0].query == "确认" - assert "已确认" in logs[0].answer + assert "run.failed" in event_names + assert "run.completed" not in event_names def test_chat_turn_unknown_action_returns_failed(app, client): @@ -154,11 +138,11 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client): assert any(item.get("event") == "run.failed" for item in events) -def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_path): +def test_chat_turn_multipart_upload_rejects_removed_batch_action(app, client, tmp_path): """ - multipart 上传时 agent_id 应从 form 字段解析;create_batch_from_notices 已下线为 410。 + multipart 上传时 agent_id 应从 form 字段解析;旧建批 action 不再注册。 - 关键断言:form 带 agent_id 时 run 能启动;建批动作固定 BATCHES_REMOVED(非 agent 解析失败)。 + 关键断言:form 带 agent_id 时 run 能启动;旧 action 作为未知 action 失败。 """ from io import BytesIO @@ -191,8 +175,7 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_pa assert "run.failed" in event_names assert "run.completed" not in event_names failed = next(item for item in events if item.get("event") == "run.failed") - # 关键断言:SSE run.failed 顶层带业务 code(非嵌套 data)。 - assert failed.get("code") == "SHIPPING.BATCHES_REMOVED" + assert failed.get("code") == "RESOURCE.NOT_FOUND" def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, client, monkeypatch): @@ -239,102 +222,3 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie assert all('schema_preview' not in payload for payload in assistant_payloads) -@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c') -def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path): - """shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。""" - from io import BytesIO - - user = _create_user() - agent = _create_shipping_agent() - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) - captured: dict = {} - - def fake_create(**kwargs): - captured.update(kwargs) - return { - "status": "ok", - "batch_no": "SB-CHAT-IDEM-001", - "data": { - "tasks": [{"task_id": "SN-CHAT-IDEM-001"}], - "focus_task": {"task_no": "SN-CHAT-IDEM-001"}, - }, - } - - monkeypatch.setattr( - "app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items", - fake_create, - ) - - res = client.post( - "/api/chat/turns/stream", - headers={"X-Username": user.username, "X-Role": user.role}, - data={ - "agent_id": str(agent.id), - "input": json.dumps( - { - "type": "upload_followup", - "display_text": "上传发货通知:notice.txt", - "action_type": "shipping.create_batch_from_notices", - "payload": {"idempotency_key": "chat-idem-001"}, - }, - ensure_ascii=False, - ), - "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"), - }, - content_type="multipart/form-data", - ) - assert res.status_code == 200 - res.get_data(as_text=True) - assert captured.get("create_idempotency_key") == "chat-idem-001" - notice_items = captured.get("notice_items") or [] - assert notice_items - assert notice_items[0].get("source_content_hash") - - -@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c') -def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path): - """相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。""" - from io import BytesIO - - user = _create_user() - agent = _create_shipping_agent() - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) - orchestrator_calls: list[str] = [] - monkeypatch.setattr( - "app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator", - lambda batch_no: orchestrator_calls.append(batch_no) or True, - ) - - payload_input = { - "type": "upload_followup", - "display_text": "上传发货通知:notice.txt", - "action_type": "shipping.create_batch_from_notices", - "payload": {"idempotency_key": "chat-replay-integration-001"}, - } - headers = {"X-Username": user.username, "X-Role": user.role} - raw = "客户:ACME\nA001 x 10".encode("utf-8") - - def _post_turn(): - return client.post( - "/api/chat/turns/stream", - headers=headers, - data={ - "agent_id": str(agent.id), - "input": json.dumps(payload_input, ensure_ascii=False), - "files": (BytesIO(raw), "notice.txt"), - }, - content_type="multipart/form-data", - ) - - first = _post_turn() - assert first.status_code == 200 - first_events = _parse_sse_events(first.get_data(as_text=True)) - assert "run.failed" not in [item.get("event") for item in first_events] - - second = _post_turn() - assert second.status_code == 200 - second_events = _parse_sse_events(second.get_data(as_text=True)) - completed = [item for item in second_events if item.get("event") == "message.completed"] - assert completed - assert "已恢复此前创建的批次" in str(completed[-1].get("content", "")) - assert len(orchestrator_calls) == 1 diff --git a/backend/tests/test_email_supplement_merge.py b/backend/tests/test_email_supplement_merge.py index f359251b..2dca8f2a 100644 --- a/backend/tests/test_email_supplement_merge.py +++ b/backend/tests/test_email_supplement_merge.py @@ -6,6 +6,8 @@ from __future__ import annotations +import pytest + from app.services.shipping_notice.email_allocation_table_parser import ( parse_email_allocation_tables, parse_email_allocation_text, @@ -87,6 +89,19 @@ def test_email_supplement_external_reservation_id_alias_merges_real_mail_header( assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn' +def test_email_supplement_uses_schema_alias_order_for_duplicate_source_headers(): + """同字段的两个邮件列按 Schema aliases 顺序取值,不能整表拒绝。""" + supplement = parse_email_allocation_tables( + content_hash='h' * 64, + schema_definition=SCHEMA, + html_tables=['''
PO#MPNSource Typehub code
4518738152D4-A08AR12000002FIRST-SOURCESECOND-HUB
'''], + ) + + assert supplement['issues'] == [] + assert supplement['rows'][0]['inventory_source_hint'] == 'FIRST-SOURCE' + assert supplement['rows'][0]['evidence']['inventory_source_hint']['column_index'] == 2 + + def test_email_supplement_ampn_alias_matches_customer_part_number(): """邮件 AMPN 应能与订单客户料号交叉关联并补入预约号。""" order = _order() @@ -139,7 +154,41 @@ def test_email_supplement_conflicting_schema_field_does_not_overwrite_pdf_or_pic orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA, )[0] assert not any(item['field_id'] == 'reservation' for item in merged['lines'][0]['fields']) - assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts'] + finding = next(item for item in merged['conflicts'] if item.get('field') == 'reservation_id') + assert finding['resolution_status'] == 'unresolved' + assert finding['scope'] == 'line' + assert finding['line_index'] == 0 + assert finding['conflict_key'] == '0:reservation_id' + assert finding['values'] == ['33874', '33875'] + assert [source['source_type'] for source in finding['sources']] == ['email_body', 'email_body'] + + +@pytest.mark.pure_unit +def test_email_supplement_does_not_cross_compare_values_from_different_part_lines(): + """同 PO 的不同料号可有不同单价,补充合并只能比较同一目标行的关联正文行。""" + schema = { + 'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ], + } + order = _order() + order['lines'][0]['fields'].append({'field_id': 'unit-price', 'observations': [{'value': '10.00'}]}) + order['lines'].append({'fields': [ + {'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]}, + {'field_id': 'qty', 'observations': [{'value': 1}]}, + {'field_id': 'unit-price', 'observations': [{'value': '20.00'}]}, + ]}) + result = merge_email_supplements( + orders=[order], + supplements_by_intake={1: {'document_id': 304, 'rows': [ + {'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '10.00', 'evidence': {}}, + {'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000003', 'unit_price': '20.00', 'evidence': {}}, + ]}}, + schema_definition=schema, + )[0] + + assert not any(item.get('field') == 'unit_price' for item in result['conflicts']) def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review(): @@ -166,6 +215,110 @@ def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review(): assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts'] +@pytest.mark.pure_unit +def test_email_supplement_treats_decimal_format_variants_as_the_same_value(): + """PDF 与邮件的金额仅格式不同,必须按 Schema decimal 语义比较而非制造冲突。""" + schema = { + 'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ], + } + order = _order() + order['lines'][0]['fields'].append({ + 'field_id': 'unit-price', 'observations': [{'value': '1731.6'}], + }) + supplement = { + 'document_id': 44, + 'rows': [{ + 'customer_po_number': '4518738152', + 'part_number': 'D4-A08AR12000002', + 'unit_price': '1,731.60', + 'evidence': {}, + }], + } + + merged = merge_email_supplements( + orders=[order], supplements_by_intake={1: supplement}, schema_definition=schema, + )[0] + + assert _value(merged['lines'][0]['fields'], 'unit-price') == '1731.6' + assert not any(item.get('field') == 'unit_price' for item in merged['conflicts']) + + +@pytest.mark.pure_unit +def test_email_supplement_decimal_difference_creates_a_complete_unresolved_finding(): + """真实金额不一致必须保留双方原值、规范值和邮件单元格证据,供复核直接裁决。""" + schema = { + 'version': 'shipping-order-schema.v9', + 'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ], + } + order = _order() + order['lines'][0]['fields'].append({ + 'field_id': 'unit-price', 'observations': [{ + 'value': '1731.60', 'document_id': 305, 'evidence_ref': {'page_no': 1, 'cell_id': 'pdf-unit-price'}, + }], + }) + supplement = { + 'document_id': 304, + 'rows': [{ + 'customer_po_number': '4518738152', + 'part_number': 'D4-A08AR12000002', + 'unit_price': '1732.00', + 'evidence': {'unit_price': {'table_index': 0, 'row_index': 5, 'column_index': 4, 'cell_id': 'email-unit-price'}}, + }], + } + + merged = merge_email_supplements( + orders=[order], supplements_by_intake={1: supplement}, schema_definition=schema, + )[0] + + finding = next(item for item in merged['conflicts'] if item.get('field') == 'unit_price') + assert finding['conflict_key'] == '0:unit_price' + assert finding['severity'] == 'blocking' + assert finding['resolution_status'] == 'unresolved' + assert finding['scope'] == 'line' + assert finding['line_index'] == 0 + assert finding['values'] == ['1731.60', '1732.00'] + assert finding['sources'] == [ + { + 'source_type': 'pdf', 'raw_value': '1731.60', 'canonical_value': '1731.60', + 'document_id': 305, 'evidence_ref': {'page_no': 1, 'cell_id': 'pdf-unit-price'}, + }, + { + 'source_type': 'email_body', 'raw_value': '1732.00', 'canonical_value': '1732.00', + 'document_id': 304, + 'evidence_ref': {'table_index': 0, 'row_index': 5, 'column_index': 4, 'cell_id': 'email-unit-price'}, + }, + ] + assert finding['rule_version'] == 'shipping-order-schema.v9' + + +@pytest.mark.pure_unit +def test_email_supplement_duplicate_email_decimal_formats_do_not_create_a_conflict(): + """同一邮件补充行的等价金额格式必须按 decimal 归并,不能产生正文内部冲突。""" + schema = { + 'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ], + } + result = merge_email_supplements( + orders=[_order()], + supplements_by_intake={1: {'document_id': 304, 'rows': [ + {'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '1731.6', 'evidence': {}}, + {'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '1,731.60', 'evidence': {}}, + ]}}, + schema_definition=schema, + )[0] + + assert _value(result['lines'][0]['fields'], 'unit-price') == '1731.6' + assert not any(item.get('field') == 'unit_price' for item in result['conflicts']) + + def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_numbers(): """邮件 PN/AMPN 均可与订单内部/客户料号交叉匹配,不依赖字段名称相同。""" scenarios = [ diff --git a/backend/tests/test_legacy_supplement_conflict_reassessment.py b/backend/tests/test_legacy_supplement_conflict_reassessment.py new file mode 100644 index 00000000..83c27d2f --- /dev/null +++ b/backend/tests/test_legacy_supplement_conflict_reassessment.py @@ -0,0 +1,108 @@ +""" +tests/test_legacy_supplement_conflict_reassessment.py + +用途:验证旧补充冲突不会被静默放行,而会升级为有稳定键的证据不足 Finding。 +依赖:legacy_supplement_conflict_reassessment_service、pytest。 +逻辑:纯函数层覆盖旧结构升级、非旧 Finding 保留以及重复旧记录收敛。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.legacy_supplement_conflict_reassessment_service import ( + reassess_legacy_supplement_conflicts_from_frozen_order, + upgrade_legacy_supplement_conflicts, +) +from tests.test_email_supplement_merge import SCHEMA, _order + + +@pytest.mark.pure_unit +def test_upgrade_legacy_supplement_conflict_keeps_blocking_but_makes_recovery_visible(): + """旧 `{field, reason}` 不能被直接清除,须变为可展示的证据不足 Finding。""" + upgraded, count = upgrade_legacy_supplement_conflicts([{ + 'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price', + }]) + + assert count == 1 + assert upgraded == [{ + 'conflict_key': '-1:unit_price', 'severity': 'blocking', + 'reason': 'supplement_conflict_evidence_insufficient', 'resolution_status': 'unresolved', + 'field': 'unit_price', 'scope': 'unscoped', 'line_index': None, + 'values': [], 'sources': [], 'rule_version': 'legacy-supplement-conflict.v1', + 'legacy_reason': 'supplement_field_conflict', 'recovery_action': 'reparse_current_pdf', + }] + + +@pytest.mark.pure_unit +def test_upgrade_legacy_supplement_conflict_does_not_touch_complete_current_finding(): + """已有新 Finding 的证据与裁决状态不可被历史迁移覆盖。""" + current = { + 'conflict_key': '0:unit_price', 'severity': 'blocking', + 'reason': 'supplement_field_conflict', 'resolution_status': 'unresolved', + 'field': 'unit_price', 'values': ['1', '2'], 'sources': [{'source_type': 'pdf'}], + } + upgraded, count = upgrade_legacy_supplement_conflicts([current]) + assert count == 0 + assert upgraded == [current] + + +@pytest.mark.pure_unit +def test_upgrade_legacy_supplement_conflict_collapses_duplicate_legacy_identity(): + """同字段重复旧阻断升级后只有一项,避免一次操作产生多个不可裁决卡片。""" + upgraded, count = upgrade_legacy_supplement_conflicts([ + {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price'}, + {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price'}, + ]) + assert count == 2 + assert len(upgraded) == 1 + + +@pytest.mark.pure_unit +def test_reassess_legacy_conflict_from_frozen_order_clears_decimal_format_false_positive(): + """冻结证据可恢复时,1731.6 与 1,731.60 必须按当前 decimal 规则清除旧假冲突。""" + schema = {'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ]} + order = _order() + order['lines'][0]['fields'].append({ + 'field_id': 'unit-price', 'observations': [{'value': '1731.6'}], + }) + conflicts, status, count = reassess_legacy_supplement_conflicts_from_frozen_order( + candidate_conflicts=[{'reason': 'supplement_field_conflict', 'field': 'unit_price'}], + frozen_order=order, + supplements_by_intake={1: {'document_id': 304, 'rows': [{ + 'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', + 'unit_price': '1,731.60', 'evidence': {}, + }]}}, + schema_definition=schema, + ) + assert status == 'rebuilt' + assert count == 1 + assert conflicts == [] + + +@pytest.mark.pure_unit +def test_reassess_legacy_conflict_from_frozen_order_rebuilds_real_conflict_with_evidence(): + """冻结证据可恢复时,真实金额差异必须变为当前完整 Finding,而不是笼统旧阻断。""" + schema = {'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ]} + order = _order() + order['lines'][0]['fields'].append({'field_id': 'unit-price', 'observations': [{ + 'value': '10.00', 'document_id': 305, 'evidence_ref': {'page_no': 1}, + }]}) + conflicts, status, _ = reassess_legacy_supplement_conflicts_from_frozen_order( + candidate_conflicts=[{'reason': 'supplement_field_conflict', 'field': 'unit_price'}], + frozen_order=order, + supplements_by_intake={1: {'document_id': 304, 'rows': [{ + 'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', + 'unit_price': '11.00', 'evidence': {'unit_price': {'row_index': 1}}, + }]}}, + schema_definition=schema, + ) + assert status == 'rebuilt' + assert conflicts[0]['conflict_key'] == '0:unit_price' + assert [source['document_id'] for source in conflicts[0]['sources']] == [305, 304] diff --git a/backend/tests/test_order_document_profile_creation_service.py b/backend/tests/test_order_document_profile_creation_service.py index 0ded8915..fe09beeb 100644 --- a/backend/tests/test_order_document_profile_creation_service.py +++ b/backend/tests/test_order_document_profile_creation_service.py @@ -55,6 +55,8 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi assert created['profile_code'] != 'CLIENT_SUPPLIED_CODE' assert created['draft_revision']['revision_no'] == 1 assert created['edit_lease']['browser_session_id'] == 'wizard-tab-a' + # 主表身份必须同时冻结在 Profile 定义和两类共同视觉样本上。 + assert created['definition']['main_table_id'] == 'sample-table' assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1 assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1 assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1 @@ -115,6 +117,27 @@ def test_public_identity_signature_owns_coordinate_run_lifecycle(app, monkeypatc assert signature['run_type'] == 'layout_signature' +def test_runtime_adapter_does_not_route_plain_pdf_by_stale_xfa_capability(monkeypatch): + """关键断言:普通 PDF 的残留 XFA capability 不得改变正式值源路由。""" + from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset + + monkeypatch.setattr(xfa_dataset, 'xfa_enabled', lambda: True) + stale_plain_pdf_layout = { + 'document_kind': 'plain_pdf', + 'xfa_capability': {'structure_analysis_ready': True}, + } + assert xfa_dataset.owns_layout(stale_plain_pdf_layout) is False + + supported_xfa_layout = { + 'document_kind': 'xfa_hybrid', + 'xfa_capability': { + 'document_kind': 'xfa_hybrid', + 'structure_analysis_ready': True, + }, + } + assert xfa_dataset.owns_layout(supported_xfa_layout) is True + + def test_wizard_xfa_mode_creates_visual_main_table_draft_before_dataset_mapping(app, monkeypatch): """关键断言:XFA 向导只冻结视觉主表;datasets 选择留给编辑映射,发布仍 fail-closed。""" from hashlib import sha256 diff --git a/backend/tests/test_order_document_profile_publish_check_service.py b/backend/tests/test_order_document_profile_publish_check_service.py index 18f52ea0..ae2a7bfa 100644 --- a/backend/tests/test_order_document_profile_publish_check_service.py +++ b/backend/tests/test_order_document_profile_publish_check_service.py @@ -46,7 +46,11 @@ def _signature_run(profile: dict) -> ShippingOrderDocumentProfileValidationRun: profile_id=profile['id'], revision_no=profile['draft_revision']['revision_no'], definition_checksum=profile['draft_revision']['definition_checksum'], schema_version_id=profile['schema_version_id'], run_type='layout_signature', status='passed', - summary_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'}, + summary_json={ + 'signature_checksum': 'sig-checksum', + 'matcher_policy_version': 'profile-layout-matcher', + 'evidence_contract_version': validation_service.LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION, + }, result_snapshot_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'}, operation_id='signature-validation', ) @@ -160,6 +164,37 @@ def test_report_blocks_when_signature_missing(app, monkeypatch): assert 'signature_required' in keys or 'overlap_validation_required' in keys +def test_report_ignores_submitted_pre_hydration_signature(app, monkeypatch): + """页面提交旧签名 ID 时,发布检查必须忽略它并通过统一入口重建当前签名。""" + with app.app_context(): + monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None) + schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-legacy-signature-create') + lease = _lease(draft['id']); run = _passing_run(draft) + legacy = _signature_run(draft) + legacy.summary_json = { + key: value for key, value in legacy.summary_json.items() + if key != 'evidence_contract_version' + } + db.session.commit() + fresh = _signature_run(draft) + overlap = _overlap_run(draft) + calls: list[int] = [] + + def _resolve(profile, _revision, **_kwargs): + calls.append(profile.id) + return fresh + + monkeypatch.setattr(validation_service, 'resolve_profile_identity_signature', _resolve) + monkeypatch.setattr(validation_service, 'run_cross_template_overlap', lambda *args, **kwargs: {'id': overlap.id, 'status': 'passed', 'stored_status': 'passed'}) + report = checks.create_report( + draft['id'], data={'validation_run_id': run.id, 'matching_signature_run_id': legacy.id, 'overlap_validation_run_id': overlap.id}, + actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-legacy-signature-report', + ) + + assert calls == [draft['id']] + assert report['matching_signature_run_id'] == fresh.id + + def test_report_blocks_when_overlap_failed(app, monkeypatch): """关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。""" with app.app_context(): @@ -202,8 +237,8 @@ def test_report_invalidates_when_signature_cleared(app, monkeypatch): assert refreshed['status'] == 'invalidated' -def test_consume_report_blocks_editor_self_approval(app, monkeypatch): - """职责分离:最近映射编辑者不得消费自己的发布检查报告。""" +def test_consume_report_allows_editor_self_approval(app, monkeypatch): + """业务规则:管理员可确认发布自己编辑的订单模板草稿。""" with app.app_context(): monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None) monkeypatch.setattr( @@ -244,15 +279,9 @@ def test_consume_report_blocks_editor_self_approval(app, monkeypatch): operation_id='pc-sod-report', ) keys = [str(item['key']) for item in report['warning_items']] - with pytest.raises(ValidationError) as error: - checks.consume_report( - draft['id'], - report['report_no'], - data={'confirmed_warning_keys': keys}, - actor_id=editor.id, - browser_session_id='publish-check-tab', - lease_token=lease['lease_token'], - operation_id='pc-sod-consume', - ) - assert error.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID' - assert (error.value.details or {}).get('key') == 'editor_cannot_approve_own_version' + published = checks.consume_report( + draft['id'], report['report_no'], data={'confirmed_warning_keys': keys}, + actor_id=editor.id, browser_session_id='publish-check-tab', + lease_token=lease['lease_token'], operation_id='pc-sod-consume', + ) + assert published['status'] == 'published' diff --git a/backend/tests/test_order_document_profile_validation_service.py b/backend/tests/test_order_document_profile_validation_service.py index 83ffb906..e4e39292 100644 --- a/backend/tests/test_order_document_profile_validation_service.py +++ b/backend/tests/test_order_document_profile_validation_service.py @@ -85,6 +85,71 @@ def test_frozen_sample_layout_survives_source_document_retention_cleanup(monkeyp assert validation_service._load_sample_layout(sample) == frozen_layout +def test_frozen_sample_layout_hydrates_coordinate_evidence_reference(monkeypatch): + """压缩 Layout 仍须通过其 FileAsset 引用恢复坐标证据,供签名和发布校验使用。""" + sample = SimpleNamespace(document_id=992, layout_version_id=772) + frozen_layout = {'status': 'ready', 'coordinate_evidence_ref': {'asset_no': 'evidence-asset'}} + document = SimpleNamespace(id=992) + hydrated_layout = { + **frozen_layout, + 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 100}}}, + } + + def _get(model, identity): + if model.__name__ == 'ShippingDocumentLayoutVersion' and identity == 772: + return SimpleNamespace(payload_json=frozen_layout) + if model.__name__ == 'ShippingOrderDocument' and identity == 992: + return document + return None + + monkeypatch.setattr(validation_service.db.session, 'get', _get) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.lifecycle._hydrate_coordinate_evidence', + lambda *, payload, document: hydrated_layout, + ) + + assert validation_service._load_sample_layout(sample) == hydrated_layout + + +def test_profile_identity_signature_rejects_pre_hydration_signature(monkeypatch): + """旧证据契约生成的签名不能在修复后继续参与发布唯一性校验。""" + profile = SimpleNamespace( + id=93, + matching_signature_run_id=94, + matching_signature_checksum='old-signature', + matching_signature_version='order-profile-layout-signature', + ) + revision = SimpleNamespace(definition_checksum='definition-checksum') + legacy_run = SimpleNamespace( + profile_id=93, + run_type='layout_signature', + status='passed', + definition_checksum='definition-checksum', + summary_json={}, + result_snapshot_json={'signature_checksum': 'old-signature'}, + ) + monkeypatch.setattr(validation_service.db.session, 'get', lambda *_args: legacy_run) + + with pytest.raises(Exception) as error: + validation_service.resolve_profile_identity_signature(profile, revision, auto_run=False) + + assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE' + + +def test_match_thresholds_preserve_explicit_zero_score_and_margin(): + """模板允许唯一命中不设分数/间距下限时,发布校验不得把 0 覆盖为默认门槛。""" + thresholds = validation_service._match_thresholds({ + 'document_match': { + 'minimum_score': 0.0, + 'minimum_margin': 0.0, + 'scoring_thresholds': {'evidence_coverage_minimum': 0.7}, + }, + }) + + assert thresholds['minimum_score'] == 0.0 + assert thresholds['minimum_margin'] == 0.0 + + def test_failed_current_sample_run_remains_queryable(app): """关键断言:运行时样本证据不可用也必须保存 failed 摘要,方便后续审计而非吞掉失败。""" with app.app_context(): diff --git a/backend/tests/test_order_extraction_pdf_po_split.py b/backend/tests/test_order_extraction_pdf_po_split.py index b9a86f17..d72342ae 100644 --- a/backend/tests/test_order_extraction_pdf_po_split.py +++ b/backend/tests/test_order_extraction_pdf_po_split.py @@ -8,7 +8,10 @@ from __future__ import annotations from types import SimpleNamespace -from app.services.shipping_notice.order_extraction_workflow import _build_approved_profile_order_result +from app.services.shipping_notice.order_extraction_workflow import ( + _build_approved_profile_order_result, + _reservation_region_candidates, +) SCHEMA = {'schema_version_id': 1, 'checksum': 'schema'} @@ -18,6 +21,14 @@ DEFINITION = {'fields': [ {'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'required': True}, ]} +RESERVATION_DEFINITION = { + 'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1}, + 'fields': DEFINITION['fields'] + [ + {'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header'}, + {'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line'}, + ], +} + def _row(po: str, part: str) -> dict: return {'status': 'parsed', 'issues': [], 'fields': [ @@ -27,6 +38,32 @@ def _row(po: str, part: str) -> dict: ]} +def _page_glyphs(*lines: str) -> list[dict]: + """构造跨页 Reservation 路由回归所需的最小坐标文字。""" + glyphs = [] + for row_index, line in enumerate(lines): + for column_index, char in enumerate(line): + glyphs.append({ + 'text': char, + 'bbox': {'x0': column_index * 8, 'x1': column_index * 8 + 6, 'y0': row_index * 16, 'y1': row_index * 16 + 12}, + 'source_index': len(glyphs), + 'boundary_before': 'space' if char == ' ' else 'none', + }) + return glyphs + + +def _two_page_layout() -> dict: + return { + 'coordinate_evidence': { + 'pages': {'1': {'width': 800, 'height': 600}, '2': {'width': 800, 'height': 600}}, + 'page_glyphs': { + '1': _page_glyphs('Vendor Comments:', 'Reservation#33008'), + '2': _page_glyphs('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999'), + }, + }, + } + + def test_approved_pdf_rejects_multiple_pos_in_one_pdf(): """同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。""" orders, reason = _build_approved_profile_order_result( @@ -47,3 +84,75 @@ def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven(): ) assert reason is None assert len(orders or []) == 1 + + +def test_approved_pdf_writes_unnumbered_reservation_to_header_and_line_value_to_its_row(): + """同一证据区可同时提供整单默认 Reservation 与指定行覆盖值。""" + orders, reason = _build_approved_profile_order_result( + unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, + definition=RESERVATION_DEFINITION, + table={'rows': [_row('PO-1', 'P-1'), _row('PO-1', 'P-2')]}, + reservation_region_candidates=[ + {'value': '33008', 'scope': 'header', 'line_no': None, 'raw_text': 'Reservation#33008'}, + {'value': '3000098851', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098851 for line#1'}, + ], + ) + + assert reason is None + order = (orders or [])[0] + assert any( + item['field_id'] == 'header-reservation' and item['observations'][0]['value'] == '33008' + for item in order['header_fields'] + ) + assert any( + item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == '3000098851' + for item in order['lines'][0]['fields'] + ) + assert not any(item['field_id'] == 'line-reservation' for item in order['lines'][1]['fields']) + + +def test_approved_pdf_marks_conflicting_reservation_region_for_review(): + """同一逻辑行的不同 Reservation 不得被任意选择。""" + orders, reason = _build_approved_profile_order_result( + unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, + definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]}, + reservation_region_candidates=[ + {'value': '3000098851', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098851 for line#1'}, + {'value': '3000098852', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098852 for line#1'}, + ], + ) + + assert reason is None + assert (orders or [])[0]['reservation_region_status'] == 'needs_review' + + +def test_enabled_reservation_region_reads_vendor_comments_across_pages(): + """已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。""" + result = _reservation_region_candidates( + raw_profile={'definition': RESERVATION_DEFINITION}, layout=_two_page_layout(), + ) + + assert result['reason'] is None + assert [item['value'] for item in result['candidates']] == ['33008', '3000098851'] + + +def test_profile_without_reservation_region_does_not_scan_vendor_comments(): + """未标注专区的模板必须保持既有行为,不得扫描正文中的 Reservation。""" + result = _reservation_region_candidates( + raw_profile={'definition': DEFINITION}, layout=_two_page_layout(), + ) + + assert result == {'candidates': [], 'reason': None} + + +def test_enabled_reservation_region_requires_review_when_terms_heading_is_missing(): + """专区缺少结束锚点时,不得把未封闭文本区的值当成可自动建单证据。""" + orders, reason = _build_approved_profile_order_result( + unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, + definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]}, + reservation_region_reason='terms_and_conditions_anchor_missing', + ) + + assert reason is None + assert (orders or [])[0]['reservation_region_status'] == 'needs_review' + assert (orders or [])[0]['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing'] diff --git a/backend/tests/test_post_ot_fulfillment_wave_p0.py b/backend/tests/test_post_ot_fulfillment_wave_p0.py index 36578fe0..378e28c0 100644 --- a/backend/tests/test_post_ot_fulfillment_wave_p0.py +++ b/backend/tests/test_post_ot_fulfillment_wave_p0.py @@ -8,6 +8,8 @@ tests/test_post_ot_fulfillment_wave_p0.py from __future__ import annotations +import ast +import inspect from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -16,6 +18,99 @@ import pytest from app.core.errors import ConflictError +def test_create_post_ot_wave_uses_standard_fulfillment_audit_snapshot_keywords(): + """履约波次审计必须使用统一的 before/after 状态摘要参数。""" + from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc + + function_node = ast.parse(inspect.getsource(svc.create_post_ot_fulfillment_wave)).body[0] + audit_calls = [ + node + for node in ast.walk(function_node) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == 'record_fulfillment_audit' + ] + + assert len(audit_calls) == 1 + keyword_names = {keyword.arg for keyword in audit_calls[0].keywords} + assert {'before', 'after'} <= keyword_names + assert not {'before_json', 'after_json'} & keyword_names + + +def test_released_shortage_line_is_eligible_for_post_ot_wave(): + """短缺放行仅完成审批,后续必须允许该行进入独立发货通知波次。""" + from app.services.shipping_notice.post_ot_fulfillment_wave_service import _assert_fact_allows_fulfill + + required, available = _assert_fact_allows_fulfill({ + 'line_key': 'L-RELEASED', + 'inventory_status': 'ready', + 'match_result': 'matched', + 'is_shortage': True, + 'required_qty': '3', + 'available_qty': '0', + 'decision': {'decision_code': 'release_inventory_shortage'}, + }) + + assert str(required) == '3' + assert str(available) == '0' + + +def test_list_eligible_post_ot_lines_keeps_released_shortage_only(): + """库存不足明细必须先有放行审计决定,才能成为 wave 候选。""" + from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc + + case = SimpleNamespace(id=1) + with patch.object(svc, 'project_review_case_line_decisions', return_value={'lines': [ + { + 'line_key': 'released', 'line_status': 'released_shortage', + 'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True, + 'required_qty': '3', 'available_qty': '0', + 'decision': {'decision_code': 'release_inventory_shortage'}, + }, + { + 'line_key': 'unreleased', 'line_status': 'pending_decision', + 'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True, + 'required_qty': '3', 'available_qty': '0', + 'decision': None, + }, + ]}): + assert svc.list_eligible_post_ot_line_keys(case) == ['released'] + + +def test_post_ot_wave_creates_a_distinct_notice_with_only_selected_lines(app): + """波次必须产生独立 Notice,且其 NoticeLine 只能包含本次勾选项次。""" + from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot + + selected = [SimpleNamespace( + id=101, position=0, line_no='10', part_number='PN-10', + reservation_id='RES-10', qty='2', field_values_json={}, + )] + snapshot = SimpleNamespace(lines=[ + *selected, + SimpleNamespace( + id=102, position=1, line_no='20', part_number='PN-20', + reservation_id='RES-20', qty='3', field_values_json={}, + ), + ]) + added: list = [] + + with app.app_context(): + with ( + patch('app.services.shipping_notice.notice_line_service.db.session.query') as query, + patch('app.services.shipping_notice.notice_line_service.db.session.add_all', side_effect=added.extend), + patch('app.services.shipping_notice.notice_line_service.db.session.flush'), + ): + query.return_value.filter_by.return_value.delete.return_value = 0 + count = replace_notice_lines_from_snapshot( + notice_id=9, + snapshot=snapshot, + snapshot_line_ids={101}, + ) + + assert count == 1 + assert [(row.notice_id, row.snapshot_line_id, row.line_key) for row in added] == [(9, 101, '10')] + + def test_create_post_ot_wave_idempotent_replay_returns_original(app): """同 key 且参数一致必须返回原 wave,不二次建波。""" from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc @@ -143,7 +238,12 @@ def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app): with app.app_context(): with ( patch.object(coord, 'line_auto_fulfill_enabled', return_value=True), - patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']), + patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']), + patch.object( + coord, + 'project_review_case_line_decisions', + return_value={'lines': [{'line_key': 'L1', 'line_status': 'ready_to_fulfill'}]}, + ), patch.object(coord, 'create_post_ot_fulfillment_wave', side_effect=_boom), patch.object(coord.db.session, 'rollback', side_effect=lambda: calls.append('rollback')), patch.object(coord.db.session, 'flush', side_effect=lambda: calls.append('flush')), @@ -159,6 +259,32 @@ def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app): schedule_mock.assert_not_called() +def test_coordinate_auto_fulfill_requires_manual_selection_for_multiple_lines(app): + """多条开放明细不得由系统自动合并为同一张发货通知单。""" + from app.services.shipping_notice import line_auto_fulfill_coordinator as coord + + case = SimpleNamespace(id=3, case_no='RC-MULTI', confirmed_task_id=8) + with app.app_context(): + with ( + patch.object(coord, 'line_auto_fulfill_enabled', return_value=True), + patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1', 'L2']), + patch.object( + coord, + 'project_review_case_line_decisions', + return_value={'lines': [ + {'line_key': 'L1', 'line_status': 'released_shortage'}, + {'line_key': 'L2', 'line_status': 'ready_to_fulfill'}, + ]}, + ), + patch.object(coord, 'create_post_ot_fulfillment_wave') as create_mock, + ): + out = coord.coordinate_post_ot_auto_fulfill(case=case, trigger='inventory_shortage_released') + + assert out['status'] == 'idle' + assert out['reason'] == 'manual_wave_selection_required' + create_mock.assert_not_called() + + def test_mark_auto_fulfill_failed_does_not_create_wait_inventory(app): """无活动决定时只写匹配事实 detail,不新建 wait_inventory 决定。""" from app.services.shipping_notice import line_auto_fulfill_coordinator as coord @@ -250,3 +376,30 @@ def test_post_ot_api_does_not_call_confirm_auto_progress(app, monkeypatch): assert calls['confirm'] == 0 assert out['post_ot_wave'] is True assert out['wave_progress']['wave_no'] == 3 + + +def test_post_ot_api_rejects_pre_ot_wave_without_legacy_fallback(app, monkeypatch): + """无正式 OT 时必须拒绝,不能回落到历史建波/自动推进链路。""" + from app.api.workspace import shipping_notice as api + from app.core.errors import ValidationError + + with app.app_context(): + with app.test_request_context( + '/api/workspace/shipping-notice/order-review-cases/RC-9/line-fulfillment/wave', + method='POST', + json={'line_keys': ['L1'], 'idempotency_key': 'k1'}, + ): + monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=1)) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_draft_service.soft_load_review_case_for_audit', + lambda **_k: SimpleNamespace(id=1, case_no='RC-9'), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot', + lambda _c: {'has_formal_ot': False}, + ) + + with pytest.raises(ValidationError, match='formal order task') as exc: + api.workspace_create_shipping_order_review_fulfillment_wave('RC-9') + + assert exc.value.code == 'SHIPPING.FORMAL_OT_REQUIRED' diff --git a/backend/tests/test_shipping_auto_progress_controller_phase1.py b/backend/tests/test_shipping_auto_progress_controller_phase1.py index d65ce9de..caef0a9b 100644 --- a/backend/tests/test_shipping_auto_progress_controller_phase1.py +++ b/backend/tests/test_shipping_auto_progress_controller_phase1.py @@ -206,6 +206,62 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app): ensure_mock.assert_called_once() +def test_unique_customer_candidate_can_be_confirmed_before_draft_validation(app): + """保存校验前,唯一 Shadow 候选必须先落为 Bill-to 已确认事实。""" + from app.services.shipping_notice import order_review_auto_progress_coordinator as coord + + case = SimpleNamespace(case_no='SORC-UNIQUE-CUSTOMER', candidate_id=31) + with patch.object( + coord, + '_customer_step_for_case', + return_value=('auto_confirmed', {'customer_id': 5555}), + ) as step_mock: + result = coord.auto_confirm_unique_customer_for_review_case( + case=case, + trigger='draft_validated', + ) + + step_mock.assert_called_once_with(case=case, trigger='draft_validated') + assert result == {'status': 'auto_confirmed', 'customer_id': 5555} + + +def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(app): + """唯一客户自动确认只 flush,不能在 Draft 校验前单独提交事务。""" + from app.services.shipping_notice import order_review_auto_progress_coordinator as coord + + case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31) + candidate = SimpleNamespace(id=31) + shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555) + extraction = SimpleNamespace(id=101) + shadow_model = SimpleNamespace( + query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)), + ) + match_model = SimpleNamespace( + query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))), + ) + with patch.object(coord.db.session, 'get', return_value=candidate), patch.object( + coord, + 'ShippingCustomerShadowResolution', + shadow_model, + ), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object( + coord, + '_resolve_extraction_for_case', + return_value=extraction, + ), patch.object( + coord, + 'ShippingOrderCustomerMatch', + match_model, + ), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object( + coord, + 'record_fulfillment_audit', + ): + status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated') + + assert status == 'auto_confirmed' + assert metadata == {'customer_id': 5555, 'extraction_id': 101} + assert confirm_mock.call_args.kwargs['commit'] is False + + def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app): """合同 4:恢复扫描只收敛超时事实,不能在失败后自动补建 STP Job。""" from app.services.shipping_notice import shipping_recovery_sweeper_service as sw diff --git a/backend/tests/test_shipping_auto_progress_p0_3.py b/backend/tests/test_shipping_auto_progress_p0_3.py index 1b150a59..1bc54951 100644 --- a/backend/tests/test_shipping_auto_progress_p0_3.py +++ b/backend/tests/test_shipping_auto_progress_p0_3.py @@ -21,9 +21,7 @@ from app.models import ( ShippingProcessGateAttempt, ) from app.services.shipping_notice.auto_progress_controller import ( - AUTO_PROGRESS_GATE_CODES, determine_formal_start_gate, - run_auto_progress_job, submit_auto_progress, ) from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through @@ -80,38 +78,21 @@ def test_submit_creates_formal_execution_for_task_without_case(app): assert len(gate_codes) == 20 assert gate_codes[0] == 'document_materialization' assert gate_codes[-1] == 'manual_upload_handoff' - assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0 assert Job.query.filter_by(id=first['job_id']).one().job_type == 'shipping_process_gate' -def test_submit_reuses_formal_case_execution_and_supersedes_duplicate_apx(app): - """同一 Task 已有正式 Case Execution 时不得保留第二条 APX 活动链。""" +def test_submit_reuses_formal_case_execution(app): + """同一 Task 已有正式 Case Execution 时必须复用该 20-Gate 链。""" task = _task_with_candidate() formal = ensure_execution_for_workflow_version(review_case_id=901, task_id=int(task.id)) - duplicate = ShippingProcessExecution( - execution_no='APX-DUPLICATE', task_id=int(task.id), - candidate_set_id=task.active_inventory_candidate_set_id, - execution_revision=1, status='blocked', current_gate_code=AUTO_PROGRESS_GATE_CODES[0], - lock_version=1, - ) - db.session.add(duplicate) - db.session.flush() - for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1): - db.session.add(ShippingProcessGate( - execution_id=int(duplicate.id), gate_code=gate_code, sequence_no=sequence_no, - status='pending', evaluation_version=1, lock_version=1, - )) - task.active_process_execution_id = int(duplicate.id) + task.active_process_execution_id = int(formal.id) db.session.commit() result = submit_auto_progress(task=task, trigger='user_retry') db.session.refresh(task) - db.session.refresh(duplicate) assert result['execution_id'] == formal.id assert task.active_process_execution_id == formal.id - assert duplicate.status == 'superseded' - assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0 def test_formal_execution_queues_one_gate_attempt_job(app): @@ -202,66 +183,3 @@ def test_active_stp_job_without_retry_metadata_is_reused(app): assert result['retry_of_job_id'] is None -def test_legacy_shipping_auto_progress_job_is_terminal_readonly(app): - """历史 APX Job 被 Worker 领取时只能终止,不能再执行六 Gate 状态机。""" - task = _task_with_candidate() - legacy = ShippingProcessExecution( - execution_no='APX-READONLY', task_id=int(task.id), status='active', - candidate_set_id=int(task.active_inventory_candidate_set_id), - current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1, - ) - db.session.add(legacy) - db.session.flush() - gate = ShippingProcessGate( - execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0], - sequence_no=1, status='running', evaluation_version=1, lock_version=1, - ) - db.session.add(gate) - db.session.flush() - task.active_process_execution_id = int(legacy.id) - job = Job( - domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id), - execution_id=int(legacy.id), gate_id=int(gate.id), status='running', - candidate_set_id=int(task.active_inventory_candidate_set_id), - payload_json={'fencing_token': 'legacy-token'}, fencing_token='legacy-token', max_attempts=1, - ) - db.session.add(job) - db.session.commit() - - result = run_auto_progress_job(job_id=int(job.id), worker_id='test-worker') - - db.session.refresh(job) - db.session.refresh(gate) - assert result['status'] == 'legacy_readonly' - assert job.status == 'cancelled' - assert gate.status == 'cancelled' - - -def test_active_legacy_apx_job_does_not_block_formal_submission(app): - """历史 APX 活动 Job 不得被正式 20-Gate 提交入口复用或阻塞。""" - task = _task_with_candidate() - legacy = ShippingProcessExecution( - execution_no='APX-NONBLOCKING', task_id=int(task.id), status='active', - candidate_set_id=int(task.active_inventory_candidate_set_id), - current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1, - ) - db.session.add(legacy) - db.session.flush() - gate = ShippingProcessGate( - execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0], - sequence_no=1, status='queued', evaluation_version=1, lock_version=1, - ) - db.session.add(gate) - db.session.flush() - task.active_process_execution_id = int(legacy.id) - db.session.add(Job( - domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id), - execution_id=int(legacy.id), gate_id=int(gate.id), candidate_set_id=int(task.active_inventory_candidate_set_id), - status='queued', payload_json={}, fencing_token='legacy-token', max_attempts=1, - )) - db.session.commit() - - result = submit_auto_progress(task=task, trigger='review_confirmed') - - assert result['status'] == 'queued' - assert db.session.get(Job, result['job_id']).job_type == 'shipping_process_gate' diff --git a/backend/tests/test_shipping_business_numbering.py b/backend/tests/test_shipping_business_numbering.py index 708a0bf6..56a782b7 100644 --- a/backend/tests/test_shipping_business_numbering.py +++ b/backend/tests/test_shipping_business_numbering.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_business_numbering.py -用途:验证货代业务编号格式、上海日期、两位流水上限及业务单版本继承。 -依赖:ShippingCase/Customer/Sequence、business_numbering_service、customer_identity_gate。 -逻辑:直接调用领域服务,覆盖幂等、01-99、修订共享与强制新建独立编号。 +用途:验证货代业务编号格式、上海日期、两位流水上限及 Notice 独立编号。 +依赖:ShippingNotice/Customer/Sequence、business_numbering_service、customer_identity_gate。 +逻辑:直接调用领域服务,覆盖幂等、01-99 与替代 Notice 独立编号。 """ from datetime import datetime, timezone @@ -12,9 +12,9 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent +from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingTaskEvent from app.services.shipping_notice.business_numbering_service import ( - assign_business_number, + assign_notice_business_number, format_business_no, shanghai_business_date, ) @@ -22,25 +22,23 @@ from app.services.shipping_notice.customer_identity_gate import confirm_task_cus from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref -def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"): - """创建待客户确认的业务单、任务和启用客户。""" +def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"): + """创建待客户确认的 Notice 和启用客户。""" customer = ShippingCustomer( standard_name=f"编号测试客户 {short_code}", short_code=short_code, status="active", ) - case = ShippingCase(case_no=f"CASE-{task_no}", numbering_status="pending") - db.session.add_all([customer, case]) + db.session.add(customer) db.session.flush() task = ShippingNotice( task_no=task_no, - shipping_case_id=case.id, customer_resolution_status="pending", source_type="manual", ) db.session.add(task) db.session.commit() - return task, case, customer + return task, customer def test_number_format_and_shanghai_date_boundary(app): @@ -55,53 +53,89 @@ def test_number_format_and_shanghai_date_boundary(app): def test_confirmation_assigns_idempotent_business_number(app): """重复确认同一客户不得重复占用流水,正式编号保持不变。""" with app.app_context(): - task, case, customer = _seed_case() + task, customer = _seed_notice() first = confirm_task_customer(task, customer_id=customer.id, actor_id=None) - first_no = first.shipping_case.business_no + first_no = first.business_no second = confirm_task_customer(first, customer_id=customer.id, actor_id=None) assert first_no - assert second.shipping_case.business_no == first_no + assert second.business_no == first_no assert ShippingBusinessSequence.query.one().current_value == 1 - assert second.shipping_case.customer_short_code_snapshot == "WYC" + assert second.customer_short_code_snapshot == "WYC" assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1 -def test_revision_inherits_and_force_case_uses_next_sequence(app): - """同一业务单修订继承编号,独立业务单确认同客户时占用下一流水。""" +def test_each_notice_gets_a_distinct_business_number_for_same_customer(app): + """同一客户 PO 的不同发货通知必须各自占用独立业务流水。""" with app.app_context(): - task, case, customer = _seed_case() + customer = ShippingCustomer( + standard_name='通知单波次客户', short_code='WVC', status='active', + ) + db.session.add(customer) + db.session.flush() + first = ShippingNotice(task_no='SN-NOTICE-NO-1', customer_resolution_status='confirmed') + second = ShippingNotice(task_no='SN-NOTICE-NO-2', customer_resolution_status='confirmed') + db.session.add_all([first, second]) + db.session.flush() + first.customer_id = customer.id + second.customer_id = customer.id + db.session.flush() + + first_no = assign_notice_business_number(first) + second_no = assign_notice_business_number(second) + + assert first_no != second_no + assert first.business_no == first_no + assert second.business_no == second_no + + +def test_notice_confirms_customer_and_assigns_number_without_shipping_case(app): + """新 Notice 必须自持客户快照与编号,不能要求 ShippingCase 作为前置容器。""" + with app.app_context(): + customer = ShippingCustomer( + standard_name='Notice 自持客户', short_code='NHC', status='active', + ) + task = ShippingNotice( + task_no='SN-NOTICE-SELF-CUSTOMER', + customer_resolution_status='pending', + source_type='manual', + ) + db.session.add_all([customer, task]) + db.session.commit() + + confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=7) + + assert confirmed.customer_id == customer.id + assert confirmed.customer_name_snapshot == 'Notice 自持客户' + assert confirmed.customer_short_code_snapshot == 'NHC' + assert confirmed.business_no + assert confirmed.customer_resolution_status == 'confirmed' + + +def test_replacement_notice_uses_next_sequence(app): + """替代 Notice 保留原号审计并为新 Notice 分配下一业务号。""" + with app.app_context(): + task, customer = _seed_notice() confirm_task_customer(task, customer_id=customer.id, actor_id=None) revision = ShippingNotice( task_no="SN-NUMBER-REV", - shipping_case_id=case.id, supersedes_task_id=task.id, - customer_resolution_status="confirmed", - source_type="manual", - ) - forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending") - db.session.add_all([revision, forced_case]) - db.session.flush() - forced_task = ShippingNotice( - task_no="SN-NUMBER-FORCED", - shipping_case_id=forced_case.id, customer_resolution_status="pending", source_type="manual", ) - db.session.add(forced_task) + db.session.add(revision) db.session.commit() - confirm_task_customer(forced_task, customer_id=customer.id, actor_id=None) - assert revision.shipping_case.business_no == case.business_no - assert forced_task.shipping_case.business_no[:-2] == case.business_no[:-2] - assert case.business_no.endswith("01") - assert forced_task.shipping_case.business_no.endswith("02") + confirm_task_customer(revision, customer_id=customer.id, actor_id=None) + assert revision.business_no[:-2] == task.business_no[:-2] + assert task.business_no.endswith("01") + assert revision.business_no.endswith("02") def test_daily_sequence_blocks_one_hundredth_case(app): """客户当日已有 99 笔时,第 100 笔必须阻断且不写业务号。""" with app.app_context(): - task, case, customer = _seed_case() + task, customer = _seed_notice() business_date = shanghai_business_date() db.session.add(ShippingBusinessSequence( business_type="shipping_notice", @@ -110,19 +144,19 @@ def test_daily_sequence_blocks_one_hundredth_case(app): current_value=99, )) db.session.commit() - case.customer_id = customer.id + task.customer_id = customer.id with pytest.raises(ConflictError) as exc_info: - assign_business_number(case) + assign_notice_business_number(task) assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED" - assert case.business_no is None + assert task.business_no is None assert ShippingBusinessSequence.query.one().current_value == 99 def test_numbering_failure_rolls_back_customer_confirmation(app): """流水耗尽导致确认失败时,业务单客户和任务确认状态不得半落库。""" with app.app_context(): - task, case, customer = _seed_case() + task, customer = _seed_notice() db.session.add(ShippingBusinessSequence( business_type="shipping_notice", customer_id=customer.id, @@ -135,43 +169,41 @@ def test_numbering_failure_rolls_back_customer_confirmation(app): confirm_task_customer(task, customer_id=customer.id, actor_id=None) db.session.rollback() db.session.expire_all() - persisted_case = db.session.get(ShippingCase, case.id) persisted_task = db.session.get(ShippingNotice, task.id) - assert persisted_case.customer_id is None - assert persisted_case.business_no is None + assert persisted_task.customer_id is None + assert persisted_task.business_no is None assert persisted_task.customer_resolution_status == "pending" -def test_business_number_query_returns_latest_revision(app): - """使用正式业务号查询时应返回同业务单最新修订任务。""" +def test_business_number_query_returns_exact_notice(app): + """使用正式业务号查询时必须返回该 Notice,不能跳到替代版本。""" with app.app_context(): - task, case, customer = _seed_case() + task, customer = _seed_notice() confirm_task_customer(task, customer_id=customer.id, actor_id=None) revision = ShippingNotice( task_no="SN-NUMBER-QUERY-REV", - shipping_case_id=case.id, supersedes_task_id=task.id, document_version=2, - customer_resolution_status="confirmed", + customer_resolution_status="pending", source_type="manual", ) db.session.add(revision) db.session.commit() - resolved = get_task_by_ref(case.business_no) - assert resolved.id == revision.id - assert extract_task_no_from_text(f"请继续处理 {case.business_no}") == case.business_no + resolved = get_task_by_ref(task.business_no) + assert resolved.id == task.id + assert extract_task_no_from_text(f"请继续处理 {task.business_no}") == task.business_no def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app): """客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。""" with app.app_context(): - task, case, customer = _seed_case() - case.customer_id = customer.id + task, customer = _seed_notice() + task.customer_id = customer.id customer.short_code = "W1" # 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。 with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info: - assign_business_number(case) + assign_notice_business_number(task) assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID" - assert case.business_no is None + assert task.business_no is None db.session.rollback() diff --git a/backend/tests/test_shipping_candidate_qualification.py b/backend/tests/test_shipping_candidate_qualification.py index ddf51852..42605672 100644 --- a/backend/tests/test_shipping_candidate_qualification.py +++ b/backend/tests/test_shipping_candidate_qualification.py @@ -10,6 +10,8 @@ from __future__ import annotations from types import SimpleNamespace +import pytest + from app.services.shipping_notice.candidate_qualification_service import ( evaluate_candidate_qualification, resolve_review_case_customer_resolved, @@ -111,6 +113,104 @@ def test_layout_table_review_diagnostic_does_not_block_auto_create(monkeypatch): assert 'blocking_conflict' not in reason_codes +@pytest.mark.pure_unit +def test_derived_field_evidence_gap_does_not_block_candidate_qualification(monkeypatch): + """派生已解决的字段不能继续被历史 evidence_missing 阻断。""" + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled', + lambda: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy', + lambda: {'enabled': True}, + ) + candidate = _eligible_candidate( + conflicts_json=[{ + 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }], + structured_result_json={ + 'customer': {'resolution_status': 'user_confirmed'}, + 'extraction': {'field_adjudication': { + 'blocked_fields': [], + 'decisions': [{'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived'}], + }}, + }, + ) + + result = evaluate_candidate_qualification( + candidate=candidate, + fields_complete=True, + customer_resolved=True, + schema_auto_create_enabled=True, + ) + + assert result['gates']['field_conflicts_resolved'] is True + assert result['can_auto_create'] is True + + +@pytest.mark.pure_unit +def test_resolved_blocking_finding_does_not_block_candidate_qualification(monkeypatch): + """标准 Finding 已记录人工裁决时,资格 Gate 只能阻断 unresolved 项。""" + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled', + lambda: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy', + lambda: {'enabled': True}, + ) + candidate = _eligible_candidate(conflicts_json=[{ + 'conflict_key': '0:unit_price', + 'field': 'unit_price', + 'severity': 'blocking', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'resolved', + 'values': ['1731.60', '1732.00'], + }]) + + result = evaluate_candidate_qualification( + candidate=candidate, + fields_complete=True, + customer_resolved=True, + schema_auto_create_enabled=True, + ) + + assert result['gates']['field_conflicts_resolved'] is True + assert result['can_auto_create'] is True + + +@pytest.mark.pure_unit +def test_non_blocking_standard_finding_does_not_block_candidate_qualification(monkeypatch): + """统一 Finding 的 severity 不是 blocking 时不得被资格 Gate 误拦截。""" + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled', + lambda: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy', + lambda: {'enabled': True}, + ) + candidate = _eligible_candidate(conflicts_json=[{ + 'conflict_key': '0:unit_price', + 'field': 'unit_price', + 'severity': 'review_required', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'unresolved', + 'values': ['1731.60', '1732.00'], + }]) + + result = evaluate_candidate_qualification( + candidate=candidate, + fields_complete=True, + customer_resolved=True, + schema_auto_create_enabled=True, + ) + + assert result['gates']['field_conflicts_resolved'] is True + assert result['can_auto_create'] is True + + def test_llm_candidate_can_pass_unified_gates(monkeypatch): """LLM Candidate 具备分类/字段置信度与证据时可通过统一门禁 → eligible。""" monkeypatch.setattr( @@ -244,7 +344,9 @@ def test_generic_candidate_failure_has_concrete_reason_codes(monkeypatch): assert result['can_auto_create'] is False assert 'evidence_missing' in result['blocking_reason_codes'] assert 'field_conflict' in result['blocking_reason_codes'] - assert 'required_field_missing' in result['blocking_reason_codes'] + # Candidate Qualification 在字段合并后运行,必须使用最终字段完整性原因码; + # `required_field_missing` 仅保留给解析/复核草稿阶段。 + assert 'final_required_field_missing' in result['blocking_reason_codes'] assert 'duplicate_unresolved' in result['blocking_reason_codes'] or 'duplicate_resolved' in result['failed_gates'] assert any(code.startswith('customer_') for code in result['blocking_reason_codes']) diff --git a/backend/tests/test_shipping_chat_action_handlers.py b/backend/tests/test_shipping_chat_action_handlers.py index 9ede091e..81623ef3 100644 --- a/backend/tests/test_shipping_chat_action_handlers.py +++ b/backend/tests/test_shipping_chat_action_handlers.py @@ -15,6 +15,9 @@ def test_legacy_fulfillment_chat_actions_are_not_registered(): action_types = set(list_action_types()) assert { + "shipping.create_batch_from_notices", + "shipping.create_batch_from_intakes", + "shipping.switch_batch_focus", "shipping.freeze_order", "shipping.generate_excel", "shipping.retry_upload", @@ -36,4 +39,6 @@ def test_legacy_workspace_fulfillment_routes_are_not_registered(app): '/api/workspace/shipping-tasks//match-inventory', '/api/workspace/shipping-tasks//generate-excel', '/api/workspace/shipping-tasks//retry-upload', + '/api/workspace/shipping-tasks//retry', + '/api/workspace/shipping-tasks//lines//retry', }.isdisjoint(routes) diff --git a/backend/tests/test_shipping_conversation_processing_api.py b/backend/tests/test_shipping_conversation_processing_api.py index 57e1797e..e44a4068 100644 --- a/backend/tests/test_shipping_conversation_processing_api.py +++ b/backend/tests/test_shipping_conversation_processing_api.py @@ -11,6 +11,7 @@ from __future__ import annotations from app import db from app.core.auth.jwt import issue_local_access_token from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun +from sqlalchemy import event from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_task_service import ( allocate_user_task_no_for_run, @@ -99,6 +100,10 @@ def test_workspace_shipping_processing_and_focus_viewed_api(app, client): ) assert focus.status_code == 200, focus.get_json() assert focus.get_json()['data']['focused_task_no'] == user_task_no + assert 'work_items' not in focus.get_json()['data'] + assert set(focus.get_json()['data']['processing']['status_groups']) == { + 'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', + } viewed = client.post( f'/api/workspace/shipping-notice/conversation-tasks/{user_task_no}/viewed', @@ -106,3 +111,122 @@ def test_workspace_shipping_processing_and_focus_viewed_api(app, client): headers=headers, ) assert viewed.status_code == 200, viewed.get_json() + assert 'work_items' not in viewed.get_json()['data'] + + +def test_workspace_shipping_processing_summary_omits_detail_and_legacy_mirrors(app, client): + """首屏会话摘要只返回状态→EML→PDF权威分组,详情必须按需读取。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='API-SUMMARY') + 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, + ) + db.session.commit() + token = issue_local_access_token(user) + session_id = session.session_id + assert run.id is not None + + response = client.get( + f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary', + headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 200, response.get_json() + data = response.get_json()['data'] + assert data['conversation_id'] == session_id + assert data['projection_mode'] == 'summary' + assert 'work_items' not in data + projection = data['conversation_processing'] + assert set(projection['status_groups']) == { + 'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', + } + assert 'needs_action' not in projection + assert 'history' not in projection + for tasks in projection['status_groups'].values(): + for task in tasks: + assert 'process_gate' not in task + assert 'objects' not in task + # PDF 叶子是首屏“状态→EML→PDF”树的一部分;但叶子同样不携带详情 Gate。 + for child in task.get('aggregate_children') or []: + assert 'process_gate' not in child + + +def test_workspace_shipping_processing_summary_does_not_read_run_snapshots(app, client): + """首屏摘要不得查询 processing run,避免 JSON 快照解码重新进入轮询路径。""" + with app.app_context(): + user, _agent, session, _intake, _document = _seed_run_input(suffix='API-SUMMARY-FAST') + token = issue_local_access_token(user) + session_id = session.session_id + run_selects: list[str] = [] + + def capture_run_selects(_conn, _cursor, statement, _parameters, _context, _executemany): + if 'shipping_order_processing_runs' in statement.lower(): + run_selects.append(statement) + + event.listen(db.engine, 'before_cursor_execute', capture_run_selects) + try: + response = client.get( + f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary', + headers={'Authorization': f'Bearer {token}'}, + ) + finally: + event.remove(db.engine, 'before_cursor_execute', capture_run_selects) + + assert response.status_code == 200, response.get_json() + assert run_selects == [] + + +def test_workspace_shipping_processing_summary_keeps_lightweight_action_entries(app, client): + """摘要不加载重型详情,但必须保留后端裁决的最小操作入口。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='API-SUMMARY-ACTIONS') + 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, + ) + run_no = run.run_no + db.session.commit() + token = issue_local_access_token(user) + session_id = session.session_id + document.parse_status = 'parsed' + document.order_extraction_status = 'review_required' + candidate = ShippingOrderCandidate( + candidate_no=f'SNC-API-SUMMARY-ACTIONS-{run.id}', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key=f'key-api-summary-actions-{run.id}', + order_extraction_run_id=run.id, + is_current_version=True, + candidate_status='provisional', + structured_result_json={}, + ) + db.session.add(candidate) + db.session.flush() + db.session.commit() + + response = client.get( + f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary', + headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 200, response.get_json() + projection = response.get_json()['data']['conversation_processing'] + assert [node['code'] for node in projection['lifecycle_nodes']] == [ + 'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete', + ] + tasks = projection['status_groups']['waiting_human'] + assert len(tasks) == 1 + leaf = tasks[0]['aggregate_children'][0] + assert leaf['run_no'] == run_no + assert leaf['source_summary']['po_number'] is None + assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse' + assert leaf['ui_state']['primary_action']['code'] == 'open_order_review' + assert leaf['ui_state']['primary_action']['target_surface'] == 'order_lifecycle_workbench' + assert leaf['ui_state']['primary_action']['target_lifecycle_stage'] == 'intake_parse' diff --git a/backend/tests/test_shipping_coordinate_table_reconstruction.py b/backend/tests/test_shipping_coordinate_table_reconstruction.py index 450b433a..648495cc 100644 --- a/backend/tests/test_shipping_coordinate_table_reconstruction.py +++ b/backend/tests/test_shipping_coordinate_table_reconstruction.py @@ -12,13 +12,18 @@ from pydantic import ValidationError from app.services.shipping_notice.document_layout.contracts import LayoutBBox from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + coordinate_profile_character_candidates, _text_in_region, + _text_in_horizontal_region, + reconstruction_exclusion_regions, reconstruct_coordinate_profile_rows, + reconstruct_coordinate_profile_rows_with_strategy, reconstruct_table_from_positioned_text, resolve_line_start_field_code, suggest_header_layouts, suggest_header_regions, suggest_multi_subrow_layouts, + derive_incomplete_table_bbox, ) from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter from app.services.shipping_notice.document_layout.order_profile import TableRegionProfile @@ -64,6 +69,87 @@ def _adaptive_layouts() -> list[dict]: ] +def test_coordinate_profile_character_candidates_share_page_first_union_contract(): + """三条解析链路应得到同一套整页优先、纵向并集字符候选。""" + page_characters = [ + {'text': 'H', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}, + {'text': 'D', 'bbox': {'x0': 10, 'y0': 160, 'x1': 20, 'y1': 170}}, + {'text': 'X', 'bbox': {'x0': 300, 'y0': 160, 'x1': 310, 'y1': 170}}, + ] + table_characters = [{'text': 'legacy', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}] + characters, page_bbox = coordinate_profile_character_candidates( + table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5}, + page_size={'width': 400, 'height': 400}, page_characters=page_characters, + table_characters=table_characters, + raw_table_bbox={'x0': 0, 'y0': 120, 'x1': 200, 'y1': 180}, + table_id='table-1', page_no=1, + ) + assert page_bbox == {'x0': 0.0, 'y0': 0.0, 'x1': 400.0, 'y1': 400.0} + assert [item['text'] for item in characters or []] == ['H', 'D'] + + +def test_coordinate_profile_character_candidates_use_annotation_page_frame_on_taller_runtime_page(): + """分页训练表区在未分页长页中必须保持原始 PDF 点坐标,不能按新页高拉伸。""" + characters, page_bbox = coordinate_profile_character_candidates( + table_region={'x0': .0, 'y0': .2, 'x1': 1.0, 'y1': .3}, + reference_page_frame={'width': 200, 'height': 100}, + page_size={'width': 200, 'height': 200}, + page_characters=[ + {'text': 'line', 'bbox': {'x0': 10, 'y0': 21, 'x1': 30, 'y1': 29}}, + {'text': 'wrong', 'bbox': {'x0': 10, 'y0': 41, 'x1': 35, 'y1': 49}}, + ], + table_characters=None, table_id='page-1', page_no=1, + ) + + # 关键断言:训练页 .2-.3 对应 y=20..30,而不是长页 y=40..60。 + assert page_bbox == {'x0': 0.0, 'y0': 0.0, 'x1': 200.0, 'y1': 200.0} + assert [item['text'] for item in characters or []] == ['line'] + + +def test_coordinate_profile_character_candidates_fallback_when_page_crop_is_empty(): + """空的页级裁剪不能覆盖仍可用的当前表字符证据。""" + characters, _ = coordinate_profile_character_candidates( + table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5}, + page_size={'width': 100, 'height': 100}, + page_characters=[{'text': 'header', 'bbox': {'x0': 80, 'y0': 80, 'x1': 90, 'y1': 90}}], + table_characters=[{'text': '10', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}], + table_id='table-1', page_no=1, + ) + assert [item['text'] for item in characters or []] == ['10'] + + +def test_coordinate_profile_character_candidates_do_not_reuse_table_on_other_page(): + """续页没有自己的页级候选时,不能重复消费首页表字符。""" + characters, _ = coordinate_profile_character_candidates( + table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5}, + page_size={'width': 100, 'height': 100}, + page_characters=[], + table_characters=[{'text': '10', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}], + table_id='table-1', page_no=2, allow_table_fallback=False, + ) + assert characters is None + + +def test_reconstruction_exclusions_do_not_treat_header_layouts_as_deleted_text(): + """表头框是语义/预览证据,默认不得在明细起行前删除相交字符。""" + exclusions = reconstruction_exclusion_regions({ + 'exclusion_regions': [{'x0': .1, 'y0': .1, 'x1': .2, 'y1': .2}], + 'header_layouts': [{'region': {'x0': .0, 'y0': .2, 'x1': 1, 'y1': .4}}], + }) + + assert exclusions == [{'x0': .1, 'y0': .1, 'x1': .2, 'y1': .2}] + + +def test_horizontal_region_keeps_a_character_that_intersects_its_right_edge(): + """字段边界切过字形时必须保留该字,避免料号末尾标点被静默截断。""" + glyphs = [ + (0, PositionedCharacter(text='A', bbox=LayoutBBox(x0=80, y0=20, x1=84, y1=30))), + (1, PositionedCharacter(text='-', bbox=LayoutBBox(x0=99.9, y0=20, x1=103, y1=30))), + ] + + assert _text_in_horizontal_region(glyphs, LayoutBBox(x0=80, y0=10, x1=100, y1=40)) == 'A -' + + def test_table_region_text_prefers_explicit_pdf_space_boundary(): """明细自由文本列应恢复 PDF 原始词边界,同时不依赖降低全局几何阈值。""" glyphs = [ @@ -217,6 +303,72 @@ def test_subrow_suggestion_uses_one_record_for_vertical_samples(): assert suggestions[0].y1 < suggestions[1].y0 +def test_incomplete_table_bbox_expands_from_page_rows_until_summary(): + """表格框只覆盖表头时,页级坐标可恢复唯一明细区,但不包含合计行。""" + characters = _glyphs( + [('Item', 10), ('Material', 65), ('Quantity', 150)], + [('Description', 10), ('Delivery Date', 120)], + [('10', 10), ('PART-A', 65), ('3.000', 150)], + [('FRAME', 65), ('PCS', 150)], + [('898.72', 120), ('2,696.16', 165)], + [('TOTAL AMOUNT', 65)], + ) + + expanded = derive_incomplete_table_bbox( + characters=characters, + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48}, + ) + + assert expanded == {'x0': 0.0, 'y0': 0.0, 'x1': 200.0, 'y1': 90.0} + + +def test_incomplete_table_bbox_does_not_expand_without_line_anchor(): + """没有可靠明细起行锚点时,不能把页面下方普通文本扩大成表格。""" + characters = _glyphs( + [('Item', 10), ('Material', 65), ('Quantity', 150)], + [('Description', 10), ('Delivery Date', 120)], + [('notes', 10), ('ordinary text', 65)], + [('TOTAL AMOUNT', 65)], + ) + + assert derive_incomplete_table_bbox( + characters=characters, + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48}, + ) is None + + +def test_profile_reconstruction_uses_page_evidence_when_table_glyphs_are_header_only(monkeypatch): + """Profile 重建入口必须把页级派生框传给同一行重建器。""" + from app.services.shipping_notice import order_document_profile_service as service + + page_glyphs = _glyphs( + [('Item', 10), ('Material', 65), ('Quantity', 150)], + [('Description', 10), ('Delivery Date', 120)], + [('10', 10), ('PART-A', 65), ('3.000', 150)], + [('FRAME', 65), ('PCS', 150)], + [('898.72', 120), ('2,696.16', 165)], + [('TOTAL', 65)], + ) + layout = { + 'status': 'ready', + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48}}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 120}}, + 'page_glyphs': {'1': page_glyphs}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + 'tables': {'table-1': page_glyphs[:30]}, + }, + } + monkeypatch.setattr(service.db.session, 'get', lambda _model, _id: SimpleNamespace(id=77)) + + result = service.suggest_coordinate_reconstruction( + {'document_id': 77, 'table_id': 'table-1'}, actor_id=None, layout_snapshot=layout, + ) + + assert result['table_bbox_source'] == 'page_coordinate_derived' + assert len(result['subrow_layouts']) == 3 + + def test_coordinate_profile_rows_merge_only_declared_physical_layouts(): """v2 主行必须有行号,续行按 row_offset 合并,合计或额外文本不得混入明细。""" rows = reconstruct_coordinate_profile_rows( @@ -241,6 +393,114 @@ def test_coordinate_profile_rows_merge_only_declared_physical_layouts(): assert rows[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'} +def test_coordinate_profile_rows_require_multi_field_signature_for_new_records(): + """孤立数字不能启动明细;同一视觉行的业务字段组合才可启动。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('0', 10)], + [('20', 10), ('PART-A', 65), ('5', 160)], + ), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}}, + {'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}}, + {'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer', 'validator_keys': ['positive_integer']}, + ], + ) + + # 关键断言:表头/噪声中的孤立 0 不得成为第 1 条明细,真实组合只产生 1 条。 + assert [row.fields for row in rows] == [{ + 'customer_po_line_no': '20', 'part_number': 'PART-A', 'qty': '5', + }] + + +def test_coordinate_profile_rows_can_start_without_line_number_when_business_fields_agree(): + """客户行号缺失时,料号与数量等独立业务字段可在任意列位置联合起行。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('PART-A', 10), ('5', 160)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .75, 'y1': 1}}, + {'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + line_start_field_code='customer_po_line_no', + schema_field_metadata=[ + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer', 'validator_keys': ['positive_integer']}, + ], + ) + + # 关键断言:起行不依赖列序或必须存在的行号字段。 + assert [row.fields for row in rows] == [{'part_number': 'PART-A', 'qty': '5'}] + + +def test_coordinate_profile_rows_ignore_non_line_schema_fields_for_record_start(): + """明细起行只消费 Schema scope=line,header 字段不能提供联合起行证据。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('Vendor', 10), ('PART-A', 65)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .75, 'y1': 1}}, + {'field_code': 'vendor', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + line_start_field_code='customer_po_line_no', + schema_field_metadata=[ + {'field_code': 'vendor', 'scope': 'header', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + # 只有一个 line 字段有效;header 字段不能把该视觉行提升为明细。 + assert rows == [] + + +def test_adaptive_record_start_uses_only_schema_line_fields_without_business_name_whitelist(): + """自适应模式同样按 Schema line 字段联合起行,不能把表头文本当行号。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('0rd', 10), ('Shipping In', 65)], [('20', 10), ('PART-A', 65)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + line_start_field_code='customer_po_line_no', + row_reconstruction_mode='adaptive_record_columns', + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert [row.fields for row in rows] == [{ + 'customer_po_line_no': '20', 'customer_part_number': 'PART-A', + }] + + +def test_schema_string_line_anchor_rejects_header_text(): + """string 类型起行字段仍须满足通用行号形态,不能接受表头文本。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('0rd', 10), ('PART-A', 65)], [('B', 10), ('PART-B', 65)], [('20', 10), ('PART-C', 65)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}}, + {'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + line_start_field_code='customer_po_line_no', + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert [row.fields for row in rows] == [{ + 'customer_po_line_no': '20', 'part_number': 'PART-C', + }] + + def test_line_number_can_be_used_as_a_configured_coordinate_anchor(): """用户选择项次字段时,坐标模板可用 line_no 启动明细。""" rows = reconstruct_coordinate_profile_rows( @@ -277,6 +537,73 @@ def test_coordinate_profile_row_layout_repeats_across_the_table(): ] +def test_coordinate_profile_rows_apply_selected_anchor_frame_translation_to_all_regions(): + """锚点框架选中的平移必须同时投影主表、物理行和每个字段区。""" + baseline_layout = { + 'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, + 'line_layouts': [{ + 'layout_id': 'main', 'row_offset': 0, + 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .35}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .25, 'x1': .25, 'y1': .35}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .25, 'x1': .55, 'y1': .35}}, + {'field_code': 'qty', 'region': {'x0': .55, 'y0': .25, 'x1': .75, 'y1': .35}}, + {'field_code': 'unit_price', 'region': {'x0': .75, 'y0': .25, 'x1': 1, 'y1': .35}}, + ], + }], + } + shifted = reconstruct_coordinate_profile_rows( + characters=_glyphs([('00010', 10), ('PART-A', 65), ('2', 135), ('10.50', 175)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, + coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .20}, + **baseline_layout, + ) + + # Without the selected transform these glyphs sit outside all baseline Y regions. + assert shifted[0].fields == { + 'customer_po_line_no': '00010', 'customer_part_number': 'PART-A', + 'qty': '2', 'unit_price': '10.50', + } + + +def test_coordinate_profile_rows_apply_shared_affine_matrix_to_all_regions(): + """订单行必须消费订单头相同的矩阵变换,禁止仅支持旧 translate 键。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('00010', 10), ('PART-A', 65)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, + table_region={'x0': 0, 'y0': .10, 'x1': 1, 'y1': .20}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .10, 'x1': 1, 'y1': .20}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .10, 'x1': .25, 'y1': .20}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .10, 'x1': 1, 'y1': .20}}, + ]}], + coordinate_transform={ + 'status': 'applied', 'matrix': [1.0, 0.0, 0.0, 0.0, 1.0, .10], + 'anchor_ids': ['title'], 'reason_codes': [], + }, + ) + + # 关键断言:仅矩阵键存在时,行字段仍以同一运行时坐标系读取。 + assert [row.fields for row in rows] == [{'customer_po_line_no': '00010', 'customer_part_number': 'PART-A'}] + + +def test_coordinate_profile_rows_reject_invalid_selected_anchor_frame_transform(): + """非 matcher 认可的变换不得悄悄回退为绝对坐标取值。""" + kwargs = { + 'characters': _glyphs([('00010', 10), ('PART-A', 65)]), + 'table_bbox': {'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, + 'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, + 'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .20, 'x1': .25, 'y1': .40}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .20, 'x1': 1, 'y1': .40}}, + ]}], + } + + assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={'status': 'pending'}) == [] + assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={ + 'status': 'applied', 'translate_x': 0, 'translate_y': .9, + }) == [] + + def test_coordinate_profile_preview_can_expose_unanchored_main_row_for_review(): """仅预览模式在缺少有效起行值时保留字段证据,正式重建仍严格过滤。""" kwargs = { @@ -585,6 +912,133 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l }, ] + +def test_dynamic_x_columns_recovers_a_shifted_record_hidden_by_static_header_exclusion(): + """表头随单头高度移动时,动态候选须以起行/列校验恢复被旧表头框遮住的首条明细。""" + rows, strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=_glyphs( + [('LN', 10), ('Quantity', 50), ('Part Number', 120)], + [('1', 10), ('113', 50), ('PART-A', 120)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 60}, + table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': .9}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .5, 'x1': .15, 'y1': .7}}, + {'field_code': 'qty', 'region': {'x0': .15, 'y0': .5, 'x1': .4, 'y1': .7}}, + {'field_code': 'part_number', 'region': {'x0': .4, 'y0': .5, 'x1': 1, 'y1': .7}}, + ], + }], + exclusion_regions=[{'x0': 0, 'y0': .2, 'x1': 1, 'y1': .75}], + dynamic_exclusion_regions=[], + line_start_field_code='customer_po_line_no', + ) + + assert strategy.status == 'selected' + assert strategy.row_mode == 'dynamic_x_columns' + assert [row.fields for row in rows] == [ + {'customer_po_line_no': '1', 'qty': '113', 'part_number': 'PART-A'}, + ] + + +def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor(): + """动态行整体上移时,跨视觉行字段须随同一锚点平移而非复用首行前缀。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('1', 10), ('113', 50), ('WTP-D4-', 120)], + [('A08AR12000001', 120)], + [('D4-A08AR12000001', 120)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 120}, + table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .50, 'x1': 1, 'y1': .95}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .15, 'y1': .80}}, + {'field_code': 'qty', 'region': {'x0': .15, 'y0': .70, 'x1': .4, 'y1': .80}}, + {'field_code': 'customer_part_number', 'region': {'x0': .4, 'y0': .70, 'x1': 1, 'y1': .90}}, + {'field_code': 'part_number', 'region': {'x0': .4, 'y0': .92, 'x1': 1, 'y1': 1}}, + ], + }], + line_start_field_code='customer_po_line_no', + row_reconstruction_mode='dynamic_x_columns', + ) + + assert [row.fields for row in rows] == [{ + 'customer_po_line_no': '1', 'qty': '113', + 'customer_part_number': 'WTP-D4-A08AR12000001', + 'part_number': 'D4-A08AR12000001', + }] + + +def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor(): + """固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('1', 10), ('CUSTOMER-1', 60)], [('VENDOR-1', 60)], + [('2', 10), ('CUSTOMER-2', 60)], [('VENDOR-2', 60)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 140}, + table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .50, 'x1': 1, 'y1': .95}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .60, 'x1': .2, 'y1': .70}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .60, 'x1': 1, 'y1': .68}}, + {'field_code': 'part_number', 'region': {'x0': .25, 'y0': .70, 'x1': 1, 'y1': .78}}, + ], + }], + line_start_field_code='customer_po_line_no', + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert [row.fields for row in rows] == [ + {'customer_po_line_no': '1', 'customer_part_number': 'CUSTOMER-1', 'part_number': 'VENDOR-1'}, + {'customer_po_line_no': '2', 'customer_part_number': 'CUSTOMER-2', 'part_number': 'VENDOR-2'}, + ] + + +def test_coordinate_profile_strategy_prefers_fixed_for_wrapped_part_fields(): + """跨视觉行字段必须使用字段框完整值,不能被 adaptive 前缀覆盖。""" + schema = [ + {'field_code': code, 'scope': 'line', 'enabled': True, 'data_type': 'string'} + for code in ('customer_po_line_no', 'customer_part_number', 'part_number') + ] + rows, strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=_glyphs( + [('1', 10), ('WTP-B3-', 55)], + [('A08AR11000001', 55)], + [('B3-A08AR11000001', 55)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 70}, + table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .95}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .95}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .4}}, + {'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .7, 'y1': .65}}, + {'field_code': 'part_number', 'region': {'x0': .2, 'y0': .65, 'x1': .7, 'y1': .9}}, + ], + }], + schema_field_metadata=schema, + line_start_field_code='customer_po_line_no', + ) + + assert strategy.status == 'selected' + assert strategy.row_mode == 'fixed_subrows' + assert rows[0].fields['customer_part_number'] == 'WTP-B3-A08AR11000001' + assert rows[0].fields['part_number'] == 'B3-A08AR11000001' + assert rows[0].issues == [] + deleted = reconstruct_coordinate_profile_rows( characters=_glyphs( [('10', 10), ('B3-A08AR10000018-A7', 120)], @@ -850,6 +1304,7 @@ def test_profile_order_carries_coordinate_field_evidence_into_observation(): 'page_no': 1, 'table_id': 'table-1', 'value_bbox': {'x0': 10, 'y0': 20, 'x1': 40, 'y1': 30}, 'glyph_indices': [5, 6, 7], 'token_ids': ['g5', 'g6', 'g7'], + 'evidence_ref': 'layout:9:p1:table-1:part-id', 'bbox_text': 'PART-A', 'quote_source': 'glyph_region', 'source': 'pdf_coordinate', 'has_value_coordinate': True, 'coordinate_status': 'candidate', 'highlight_quality': 'candidate', @@ -860,13 +1315,51 @@ def test_profile_order_carries_coordinate_field_evidence_into_observation(): schema={'schema_version_id': 1, 'checksum': 'a' * 64}, definition=definition, table=table, ) + from app.services.shipping_notice.order_extraction_workflow import _normalize_profile_order_observations + + _normalize_profile_order_observations( + [order], default_value_source='coordinate_ocr', coordinate_transform=None, + ) observation = order['lines'][0]['fields'][0]['observations'][0] assert observation['value'] == 'PART-A' + # 统一 Observation 合同:坐标路径也必须显式声明最终值源,而不是只藏在 layout_evidence。 + assert observation['value_source'] == 'native_pdf' + assert observation['evidence_ref'] == 'layout:9:p1:table-1:part-id' + assert observation['transform_ref'] == {'kind': 'legacy_absolute'} assert observation['layout_evidence']['page_no'] == 1 assert observation['layout_evidence']['value_bbox'] == {'x0': 10, 'y0': 20, 'x1': 40, 'y1': 30} assert observation['layout_evidence']['token_ids'] == ['g5', 'g6', 'g7'] +def test_profile_observation_preserves_ocr_source_and_applied_transform(): + """OCR 证据与受限变换必须在统一 Observation 中可审计,不能伪装为原生 PDF。""" + from app.services.shipping_notice.order_extraction_workflow import _normalize_profile_order_observations + + order = { + 'header_fields': [], + 'lines': [{'fields': [{'field_id': 'part-id', 'observations': [{ + 'value': 'PART-A', 'document_id': 9, + 'layout_evidence': {'source': 'ocr_coordinate', 'evidence_ref': 'layout:9:p1:t1:c1'}, + }]}]}], + } + transform = { + 'status': 'applied', 'matrix': [1.01, 0, .02, 0, .99, .01], + 'anchor_count': 3, 'residual': .002, + } + + _normalize_profile_order_observations( + [order], default_value_source='coordinate_ocr', coordinate_transform=transform, + ) + + observation = order['lines'][0]['fields'][0]['observations'][0] + assert observation['value_source'] == 'ocr' + assert observation['evidence_ref'] == 'layout:9:p1:t1:c1' + assert observation['transform_ref'] == { + 'kind': 'coordinate_transform', 'status': 'applied', + 'matrix': [1.01, 0, .02, 0, .99, .01], 'anchor_count': 3, 'residual': .002, + } + + def test_coordinate_reconstruction_uses_x_y_and_continuation_rules(): """行号、料号、数量按 x/y 重建;无行号的下一视觉行只能是续行。""" result = _reconstruct(_glyphs( diff --git a/backend/tests/test_shipping_customer_auto_resolution.py b/backend/tests/test_shipping_customer_auto_resolution.py index cd811c40..23543943 100644 --- a/backend/tests/test_shipping_customer_auto_resolution.py +++ b/backend/tests/test_shipping_customer_auto_resolution.py @@ -2,7 +2,7 @@ backend/tests/test_shipping_customer_auto_resolution.py 用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。 -依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice/Case、customer_auto_resolution。 +依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。 逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。 """ @@ -14,7 +14,6 @@ from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( FileAsset, - ShippingCase, ShippingCustomer, ShippingCustomerShadowResolution, ShippingIdentityDefinition, @@ -122,11 +121,10 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"): candidate_key="document:1", validation_status="ready", selected=True, structured_result_json={"business_summary": {"customer_name": "unstable name"}}, ) - case = ShippingCase(case_no=f"AUTO-CASE-{user.id}", numbering_status="pending") - db.session.add_all([candidate, case]) + db.session.add(candidate) db.session.flush() task = ShippingNotice( - task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id, + task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id, user_id=user.id, source_type="email_attachment", customer_resolution_status="pending", ) @@ -216,8 +214,8 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): assert result["rule_version"] == AUTO_RESOLUTION_VERSION assert task.customer_resolution_status == "confirmed" assert task.customer_resolution_method == "auto_rule" - assert task.shipping_case.customer_id == customer.id - assert task.shipping_case.business_no.startswith("WYC") + assert task.customer_id == customer.id + assert task.business_no.startswith("WYC") assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1 event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one() assert event.detail_json['rule_set']['checksum'] @@ -240,13 +238,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False disabled = try_auto_confirm_task_customer(task) assert disabled["status"] == "disabled" - assert task.shipping_case.business_no is None + assert task.business_no is None _allow_auto_confirmation(app) unmatched = try_auto_confirm_task_customer(task) assert unmatched["status"] == "unmatched" assert task.customer_resolution_status == "pending" - assert task.shipping_case.business_no is None + assert task.business_no is None def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): @@ -261,7 +259,7 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): assert result["status"] == "ambiguous" assert len(result["candidate_customer_ids"]) == 2 assert task.customer_resolution_status == "pending" - assert task.shipping_case.business_no is None + assert task.business_no is None def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): @@ -271,7 +269,6 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() task_id = task.id - case_id = task.shipping_case_id result = try_auto_confirm_task_customer(task) assert result["status"] == "auto_confirmed" @@ -279,10 +276,9 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): db.session.expire_all() persisted_task = db.session.get(ShippingNotice, task_id) - persisted_case = db.session.get(ShippingCase, case_id) assert persisted_task.customer_resolution_status == "pending" - assert persisted_case.customer_id is None - assert persisted_case.business_no is None + assert persisted_task.customer_id is None + assert persisted_task.business_no is None assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 @@ -300,7 +296,7 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic assert result["status"] == "insufficient_labeled_samples" assert result["quality_gate"]["labeled_sample_count"] == 0 assert task.customer_resolution_status == "pending" - assert task.shipping_case.business_no is None + assert task.business_no is None def test_business_evidence_never_auto_confirms(app): @@ -405,61 +401,48 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app assert result["quality_gate"]["labeled_sample_count"] == 1 assert result["quality_gate"]["accuracy"] == 0 assert task.customer_resolution_status == "pending" - assert task.shipping_case.business_no is None + assert task.business_no is None -def test_numbered_customer_correction_voids_old_number_and_replaces_case(app): - """客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。""" +def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app): + """客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。""" with app.app_context(): wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active") correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active") - case = ShippingCase(case_no="CASE-CORRECTION", numbering_status="pending") - db.session.add_all([wrong, correct, case]) + db.session.add_all([wrong, correct]) db.session.flush() first = ShippingNotice( - task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1, - source_type="manual", customer_resolution_status="pending", - ) - db.session.add(first) - db.session.flush() - latest = ShippingNotice( - task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2, - supersedes_task_id=first.id, source_type="manual", upload_status="pending", - customer_resolution_status="pending", inventory_source_code="DSV", + task_no="SN-CORRECTION-V1", document_version=1, + source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV", inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}], match_status="fulfillable", line_results_json=[{"sku": "A"}], export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx", ) - db.session.add(latest) + db.session.add(first) db.session.commit() confirm_task_customer(first, customer_id=wrong.id, actor_id=None) - old_case_id = case.id - old_business_no = case.business_no + old_business_no = first.business_no result = correct_numbered_task_customer( - latest, + first, customer_id=correct.id, reason="自动识别客户错误", actor_id=None, ) - old_case = db.session.get(ShippingCase, old_case_id) - replacement = db.session.get(ShippingCase, result["new_case_id"]) - assert old_case.business_no == old_business_no - assert old_case.status == "voided" - assert old_case.numbering_status == "voided" - assert replacement.replaces_case_id == old_case.id + replacement = db.session.get(ShippingNotice, result["new_notice_id"]) + assert first.business_no == old_business_no + assert first.lifecycle_status == "voided" + assert replacement.supersedes_task_id == first.id assert replacement.business_no.startswith("NEW") assert replacement.business_no != old_business_no - assert latest.shipping_case_id == replacement.id - assert first.shipping_case_id == replacement.id - assert latest.customer_resolution_method == "admin_correction" - assert latest.inventory_source_status is None - assert latest.inventory_lines_json is None - assert latest.export_file_path is None - assert latest.source_type == "manual" - assert get_task_by_ref(old_business_no).id == latest.id - assert get_task_by_ref(replacement.business_no).id == latest.id + assert replacement.customer_resolution_method == "admin_correction" + assert replacement.inventory_source_status is None + assert replacement.inventory_lines_json is None + assert replacement.export_file_path is None + assert replacement.source_type == "manual" + assert get_task_by_ref(old_business_no).id == first.id + assert get_task_by_ref(replacement.business_no).id == replacement.id assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2 metrics = get_auto_resolution_metrics() assert metrics["corrected_task_count"] == 2 @@ -471,11 +454,10 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a with app.app_context(): wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active") correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active") - case = ShippingCase(case_no="CASE-CORRECTION-BLOCK", numbering_status="pending") - db.session.add_all([wrong, correct, case]) + db.session.add_all([wrong, correct]) db.session.flush() task = ShippingNotice( - task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id, + task_no="SN-CORRECTION-BLOCK", source_type="manual", customer_resolution_status="pending", ) db.session.add(task) @@ -493,4 +475,4 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None) assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED" db.session.rollback() - assert db.session.query(ShippingCase).count() == 1 + assert db.session.query(ShippingNotice).count() == 1 diff --git a/backend/tests/test_shipping_customer_identity_gate.py b/backend/tests/test_shipping_customer_identity_gate.py index b5813c90..410338ae 100644 --- a/backend/tests/test_shipping_customer_identity_gate.py +++ b/backend/tests/test_shipping_customer_identity_gate.py @@ -3,7 +3,7 @@ backend/tests/test_shipping_customer_identity_gate.py 用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。 依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。 -逻辑:构造 pending 或缺失业务单的任务逐入口断言无副作用;确认后验证业务单/修订同步。 +逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。 """ from __future__ import annotations @@ -15,7 +15,7 @@ from werkzeug.datastructures import FileStorage from app import db from app.core.errors import AppError -from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent, User +from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User from app.services.shipping_notice.customer_identity_gate import ( assert_customer_identity_gate, confirm_task_customer, @@ -31,7 +31,7 @@ from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.task_workflow import retry_task -def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]: +def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]: """创建待确认任务、启用客户和任务用户。""" sequence = db.session.query(User).count() user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user') @@ -39,14 +39,9 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCusto customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active') db.session.add_all([user, customer]) db.session.flush() - case = ShippingCase(case_no=f'CASE-GATE-{user.id}') if with_case else None - if case: - db.session.add(case) - db.session.flush() task = ShippingNotice( task_no=f'SN-GATE-{user.id}', user_id=user.id, - shipping_case_id=case.id if case else None, - customer_resolution_status='pending' if case else None, + customer_resolution_status='pending' if customer_pending else None, lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}], inventory_source_status='user_confirmed', inventory_source_code='DSV', ) @@ -111,12 +106,12 @@ def test_pending_customer_blocks_retry_before_clearing_review_state(app): assert task.error_message == '标准客户尚未确认' -def test_confirm_customer_syncs_revision_chain_and_assigns_number(app): - """客户确认同步同业务单全部任务,并在同事务生成正式业务号。""" +def test_confirm_customer_does_not_assign_notice_number_before_excel(app): + """客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。""" with app.app_context(): task, customer, user = _seed_task() revision = ShippingNotice( - task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id, + task_no='SN-GATE-REV', user_id=user.id, supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending', ) db.session.add(revision) @@ -124,24 +119,60 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app): updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) db.session.refresh(revision) - case = db.session.get(ShippingCase, task.shipping_case_id) assert updated.customer_resolution_status == 'confirmed' - assert revision.customer_resolution_status == 'confirmed' + assert revision.customer_resolution_status == 'pending' assert updated.customer_resolution_method == 'manual' - assert case.customer_id == customer.id - assert case.customer_name_snapshot == customer.standard_name - assert case.customer_short_code_snapshot == customer.short_code - assert case.business_no.startswith(customer.short_code) - assert len(case.business_no) == len(customer.short_code) + 8 - assert case.sequence_value == 1 - assert case.numbering_status == 'assigned' + assert updated.customer_id == customer.id + assert updated.customer_name_snapshot == customer.standard_name + assert updated.customer_short_code_snapshot == customer.short_code + assert updated.business_no is None + assert updated.business_date is None + assert updated.business_sequence_value is None assert customer_identity_is_confirmed(updated) is True - assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 2 - assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 2 + assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1 + assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0 -def test_inactive_customer_reblocks_and_missing_case_is_blocked(app): - """已确认客户停用后重新阻断;缺少业务单的任务也必须阻断。""" +def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch): + """PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。""" + with app.app_context(): + task, customer, user = _seed_task() + original_query = db.session.query + lock_arguments: list[dict] = [] + + class NoticeQuerySpy: + """保留真实 Query 行为,仅记录客户确认路径的行锁参数。""" + + def __init__(self, query): + self._query = query + + def filter(self, *criteria): + self._query = self._query.filter(*criteria) + return self + + def with_for_update(self, **kwargs): + lock_arguments.append(kwargs) + self._query = self._query.with_for_update(**kwargs) + return self + + def one(self): + return self._query.one() + + def traced_query(*entities, **kwargs): + query = original_query(*entities, **kwargs) + if len(entities) == 1 and entities[0] is ShippingNotice: + return NoticeQuerySpy(query) + return query + + monkeypatch.setattr(db.session, 'query', traced_query) + + confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) + + assert lock_arguments == [{'of': ShippingNotice}] + + +def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): + """已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。""" with app.app_context(): task, customer, user = _seed_task() confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) @@ -151,11 +182,11 @@ def test_inactive_customer_reblocks_and_missing_case_is_blocked(app): assert_customer_identity_gate(task, operation='match_inventory') assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' - missing_case, _other_customer, _other_user = _seed_task(with_case=False) - with pytest.raises(AppError) as missing_case_error: - assert_customer_identity_gate(missing_case, operation='match_inventory') - assert missing_case_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' - assert customer_identity_is_confirmed(missing_case) is False + unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False) + with pytest.raises(AppError) as unconfirmed_error: + assert_customer_identity_gate(unconfirmed, operation='match_inventory') + assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' + assert customer_identity_is_confirmed(unconfirmed) is False def test_workspace_customer_search_and_confirmation_api(app, client): diff --git a/backend/tests/test_shipping_customer_migrations.py b/backend/tests/test_shipping_customer_migrations.py index 883463c2..59109963 100644 --- a/backend/tests/test_shipping_customer_migrations.py +++ b/backend/tests/test_shipping_customer_migrations.py @@ -95,3 +95,113 @@ def test_shipping_customer_migrations_upgrade_and_downgrade(): finally: for module, original_op in zip(modules, original_ops, strict=True): module.op = original_op + + +def _shipping_case_removal_schema(engine: sa.Engine, *, migrated: bool) -> None: + """构造最终删表迁移所需的最小 Notice/Case 历史结构。""" + metadata = sa.MetaData() + sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_cases', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('business_no', sa.String(32), nullable=True), + ) + sa.Table( + 'shipping_notices', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('task_no', sa.String(64), nullable=False), + sa.Column('shipping_case_id', sa.Integer(), sa.ForeignKey('shipping_cases.id'), nullable=True), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('business_no', sa.String(32), nullable=True), + ) + metadata.create_all(engine) + with engine.begin() as connection: + connection.execute(sa.text("INSERT INTO shipping_cases (id, customer_id, business_no) VALUES (1, 7, 'CUS26082301')")) + if migrated: + connection.execute(sa.text( + "INSERT INTO shipping_notices (id, task_no, shipping_case_id, customer_id, business_no) " + "VALUES (1, 'SN-MIGRATED', 1, 7, 'CUS26082301')" + )) + else: + connection.execute(sa.text( + "INSERT INTO shipping_notices (id, task_no, shipping_case_id, customer_id, business_no) " + "VALUES (1, 'SN-UNMIGRATED', 1, NULL, NULL)" + )) + + +def test_shipping_case_removal_migration_requires_notice_facts_and_drops_legacy_table(): + """最终迁移只能删除已回填 Notice 的 Case;未回填事实必须显式失败。""" + module = importlib.import_module('migrations.versions.hp9q0r1s2t3u_remove_shipping_case') + for migrated in (True, False): + engine = sa.create_engine('sqlite:///:memory:') + _shipping_case_removal_schema(engine, migrated=migrated) + with engine.begin() as connection: + original_op = module.op + module.op = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True})) + try: + if migrated: + module.upgrade() + inspector = sa.inspect(connection) + assert 'shipping_cases' not in inspector.get_table_names() + assert 'shipping_case_id' not in {item['name'] for item in inspector.get_columns('shipping_notices')} + else: + with pytest.raises(RuntimeError, match='migration incomplete'): + module.upgrade() + finally: + module.op = original_op + + +def test_shipping_case_removal_repairs_fact_columns_skipped_by_inconsistent_revision(): + """版本表已越过前置迁移但 Notice 仍为旧结构时,最终迁移应先恢复事实列再删 Case。""" + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_cases', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('business_no', sa.String(32), nullable=True), + sa.Column('business_date', sa.Date(), nullable=True), + sa.Column('sequence_value', sa.Integer(), nullable=True), + sa.Column('numbering_rule_version', sa.String(32), nullable=True), + sa.Column('customer_name_snapshot', sa.String(200), nullable=True), + sa.Column('customer_short_code_snapshot', sa.String(6), nullable=True), + ) + sa.Table( + 'shipping_notices', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('task_no', sa.String(64), nullable=False), + sa.Column('shipping_case_id', sa.Integer(), sa.ForeignKey('shipping_cases.id'), nullable=True), + ) + metadata.create_all(engine) + with engine.begin() as connection: + connection.execute(sa.text("INSERT INTO shipping_customers (id) VALUES (7)")) + connection.execute(sa.text( + "INSERT INTO shipping_cases " + "(id, customer_id, business_no, business_date, sequence_value, numbering_rule_version, " + "customer_name_snapshot, customer_short_code_snapshot) " + "VALUES (1, 7, 'CUS26082301', '2026-08-23', 1, 'V1', 'Customer', 'CUS')" + )) + connection.execute(sa.text( + "INSERT INTO shipping_notices (id, task_no, shipping_case_id) " + "VALUES (1, 'SN-LEGACY', 1)" + )) + + module = importlib.import_module('migrations.versions.hp9q0r1s2t3u_remove_shipping_case') + with engine.begin() as connection: + original_op = module.op + module.op = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True})) + try: + module.upgrade() + inspector = sa.inspect(connection) + columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + assert {'business_no', 'customer_id', 'business_date', 'business_sequence_value'} <= columns + row = connection.execute(sa.text( + "SELECT business_no, customer_id, business_sequence_value " + "FROM shipping_notices WHERE id = 1" + )).one() + assert row == ('CUS26082301', 7, 1) + assert 'shipping_cases' not in inspector.get_table_names() + finally: + module.op = original_op diff --git a/backend/tests/test_shipping_customer_shadow_resolution.py b/backend/tests/test_shipping_customer_shadow_resolution.py index ad776bbe..fb458911 100644 --- a/backend/tests/test_shipping_customer_shadow_resolution.py +++ b/backend/tests/test_shipping_customer_shadow_resolution.py @@ -14,7 +14,7 @@ import pytest from app import db from app.models import ( - FileAsset, ShippingCase, ShippingCustomer, ShippingCustomerShadowMatch, + FileAsset, ShippingCustomer, ShippingCustomerShadowMatch, ShippingCustomerShadowResolution, ShippingCustomerSite, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderSchema, @@ -154,9 +154,6 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app): ) _intake, candidate = _seed_candidate(sender='spoof@example.net') _attach_value(candidate, version, field, 'buyer@wyc.example.com') - case = ShippingCase(case_no='CASE-SHADOW') - db.session.add(case) - resolution = refresh_candidate_shadow_resolution(candidate) assert resolution.status == 'unique_candidate' @@ -164,7 +161,6 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app): assert resolution.identity_rule_set_id == rule_set['id'] assert resolution.evidence_json[0]['context_field_id'] == field.id assert resolution.evidence_json[0]['source']['kind'] == 'field_value' - assert case.customer_id is None and case.business_no is None def test_schema_uuid_drift_keeps_stable_customer_identity_rule_matching(app): diff --git a/backend/tests/test_shipping_document_layout_lifecycle.py b/backend/tests/test_shipping_document_layout_lifecycle.py index 0feb87eb..db506b0b 100644 --- a/backend/tests/test_shipping_document_layout_lifecycle.py +++ b/backend/tests/test_shipping_document_layout_lifecycle.py @@ -93,6 +93,25 @@ def test_layout_snapshot_checksum_and_idempotent_current_version(app): assert current_layout_snapshot(document)['marker'] == 'v1' +def test_ready_pdf_layout_requires_coordinate_evidence_asset(app, monkeypatch): + """关键断言:PDF 坐标证据资产保存失败时,布局不得伪装为 ready。""" + with app.app_context(): + document = _document() + monkeypatch.setattr(layout_lifecycle, '_persist_coordinate_evidence_asset', lambda **_: None) + snapshot = { + **_snapshot(), + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '
x
'}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 100}}, + 'page_glyphs': {'1': [{'text': 'x'}]}, + 'tables': {'table-1': [{'text': 'x'}]}, + }, + } + version = record_inline_layout_snapshot(document, snapshot) + assert version.status == 'failed' + assert 'shipping_document_layout_coordinate_evidence_persist_failed' in version.issues_json + + def test_inline_derived_xfa_layout_localizes_structure_analysis_identity(app): """坐标补证派生 Layout 必须克隆 XFA Analysis,样本可安全冻结到新版本。""" with app.app_context(): @@ -504,6 +523,8 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate'] assert 'tables' not in pending.payload_json['coordinate_evidence'] assert 'page_glyphs' not in pending.payload_json['coordinate_evidence'] + assert pending.payload_json['matching_features']['version'] == 'v1' + assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2] assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json @@ -569,6 +590,66 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map assert 'tables' not in restored['coordinate_evidence'] +def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app): + """冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。""" + with app.app_context(): + document = _document() + current = record_inline_layout_snapshot(document, { + **_snapshot(), + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 200}}, + 'page_glyphs': {'1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, + 'tables': {'table-1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + }) + db.session.flush() + document.current_layout_version = current + frozen_layout = { + **_snapshot(), + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}], + 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}}, + } + + restored = ensure_on_demand_coordinate_evidence( + document=document, layout=frozen_layout, page_nos={1}, + ) + + # 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。 + assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H' + assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H' + + +def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app): + """同页同时存在时,当前 Layout 是最新事实,不能被旧 Run 快照坐标覆盖。""" + with app.app_context(): + document = _document() + current = record_inline_layout_snapshot(document, { + **_snapshot(), + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 200}}, + 'page_glyphs': {'1': [{'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + }) + document.current_layout_version = current + stale_run_layout = { + **_snapshot(), + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 200}}, + 'page_glyphs': {'1': [{'text': 'STALE', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, + 'sources': {'pages': {'1': 'ocr_coordinate'}}, + }, + } + + restored = ensure_on_demand_coordinate_evidence( + document=document, layout=stale_run_layout, page_nos={1}, + ) + + assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT' + assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate' + + def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch): """同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。""" with app.app_context(): @@ -612,6 +693,35 @@ def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypat } +def test_on_demand_evidence_leaves_coordinates_missing_when_native_and_ocr_fail(app, monkeypatch): + """原 PDF 无字符且 OCR 不可用时不得伪造坐标,调用方必须转 Review。""" + with app.app_context(): + document = _document() + layout = { + **_snapshot(), + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 80}}], + 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}}, + } + page = SimpleNamespace(page_no=1, width=100, height=200, image=None, characters=[]) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + lambda _content: [page], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines', + lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError('ocr unavailable')), + ) + + restored = ensure_on_demand_coordinate_evidence( + document=document, layout=layout, page_nos={1}, + ) + + assert not restored['coordinate_evidence'].get('page_glyphs') + + def test_layout_document_budget_creates_unsupported_audit_versions(app): """超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。""" app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True diff --git a/backend/tests/test_shipping_document_layout_native_pdf.py b/backend/tests/test_shipping_document_layout_native_pdf.py index 822a018d..d3d8170c 100644 --- a/backend/tests/test_shipping_document_layout_native_pdf.py +++ b/backend/tests/test_shipping_document_layout_native_pdf.py @@ -115,6 +115,53 @@ def test_attach_native_pdf_page_images_renders_only_missing_pages(): assert attached[1].characters is chars_b +def test_extract_native_pdf_pages_closes_pdfium_handles_before_returning(): + """PDFium 句柄必须在数据复制后显式关闭,不能留给 weakref finalizer 在进程退出时回收。""" + closed: list[str] = [] + + class FakeTextPage: + def count_chars(self): + return 0 + + def close(self): + closed.append('text') + + class FakePage: + def get_size(self): + return 200, 100 + + def get_textpage(self): + return FakeTextPage() + + def get_rotation(self): + return 0 + + def close(self): + closed.append('page') + + class FakeDocument: + def __init__(self, _content): + self.page = FakePage() + + def __len__(self): + return 1 + + def __getitem__(self, _index): + return self.page + + def close(self): + closed.append('document') + + with patch( + 'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument', + FakeDocument, + ): + pages = extract_native_pdf_pages(b'%PDF', render_images=False) + + assert len(pages) == 1 + assert closed == ['text', 'page', 'document'] + + def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph(): """PDFium 空格即使没有 bbox,也必须成为下一可见字符的可靠边界并保留原始序号。""" class FakeTextPage: @@ -135,6 +182,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph(): assert loose is True return (10 + index * 4, 80, 13 + index * 4, 88) + def close(self): + """模拟 PDFium text page 的显式释放接口。""" + class FakePage: """模拟无需渲染的单页 PDF。""" @@ -150,6 +200,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph(): """样本不旋转。""" return 0 + def close(self): + """模拟 PDFium page 的显式释放接口。""" + class FakeDocument: """模拟 PDFium 文档的页数和索引访问。""" @@ -164,6 +217,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph(): """返回唯一页面。""" return FakePage() + def close(self): + """模拟 PDFium document 的显式释放接口。""" + with patch( 'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument', FakeDocument, @@ -242,6 +298,35 @@ def test_native_pdf_text_fallback_accepts_po_header_synonyms_without_false_page_ assert 'PURCHASE' not in tables[0]['html'] +def test_native_pdf_text_fallback_skips_separator_between_header_and_first_data_row(): + """表头下的起始横线不能截断无框采购订单的首条明细。""" + characters = [] + for y, entries in [ + (10, [('Item', 10), ('Material', 55), ('Qty', 135)]), + (22, [('________________________________________', 10)]), + (34, [('00010', 10), ('PART-A', 55), ('2', 135)]), + (46, [('________________________________________', 10)]), + (58, [('Total:', 90), ('2', 135)]), + ]: + for value, x0 in entries: + for index, char in enumerate(value): + characters.append(PositionedCharacter( + text=char, source_index=len(characters), + bbox=LayoutBBox(x0=x0 + index * 4, y0=y, x1=x0 + index * 4 + 3, y1=y + 8), + )) + page = NativePdfPage( + page_no=1, width=180, height=100, rotation=0, characters=characters, + image=np.full((200, 360), 255, dtype=np.uint8), + ) + + tables = build_native_pdf_text_table_fallbacks(b'%PDF', native_pages=[page]) + + # 起始横线后仍须保留首条业务数据;合计行和表尾横线不属于候选表。 + assert len(tables) == 1 + assert '00010' in tables[0]['html'] + assert 'Total:' not in tables[0]['html'] + + def test_native_pdf_unique_text_builds_traceable_needs_review_layout(): """唯一文本可形成 cell/token 引用,但人工真值延期时整体仍必须 needs_review。""" mineru = _candidate('
PartQty
') diff --git a/backend/tests/test_shipping_document_layout_runtime.py b/backend/tests/test_shipping_document_layout_runtime.py index 4f95781b..9a0b0c46 100644 --- a/backend/tests/test_shipping_document_layout_runtime.py +++ b/backend/tests/test_shipping_document_layout_runtime.py @@ -65,6 +65,7 @@ def test_runtime_persists_compact_text_and_table_snapshot_without_raw_response(a app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False, ) with app.app_context(), patch( 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', @@ -107,6 +108,7 @@ def test_runtime_reuses_native_pdf_pages_across_fallback_layout_and_evidence(app app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False, ) native_pages = [object()] timings: dict[str, int] = {} @@ -157,6 +159,7 @@ def test_runtime_empty_mineru_tables_use_pdfium_provider_fallback(app): app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False, ) empty_candidate = _candidate().model_copy(update={'pages': [ _candidate().pages[0].model_copy(update={'tables': []}), diff --git a/backend/tests/test_shipping_document_profile_quality.py b/backend/tests/test_shipping_document_profile_quality.py index 79231f52..b734085e 100644 --- a/backend/tests/test_shipping_document_profile_quality.py +++ b/backend/tests/test_shipping_document_profile_quality.py @@ -30,6 +30,16 @@ from app.models import ( ) from app.services.shipping_notice import document_profile_quality_service as quality from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot +from app.services.file_assets import storage as file_asset_storage_module + + +@pytest.fixture(autouse=True) +def _memory_file_asset_storage(monkeypatch): + """测试外置坐标证据使用内存对象,保持 FileAsset/MinIO 契约而不依赖服务。""" + objects: dict[str, bytes] = {} + monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'upload_bytes', lambda *, storage_key, data, content_type: objects.__setitem__(storage_key, bytes(data))) + monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'get_bytes', lambda storage_key: objects[storage_key]) + monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None)) @pytest.mark.parametrize( @@ -52,8 +62,8 @@ def test_blind_test_order_field_comparison_rejects_different_values(): ) -def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_source(): - """盲测仅在模板显式启用自适应模式时改用整页字符,默认表格模式必须保持不变。""" +def test_quality_region_uses_page_glyphs_for_every_reconstruction_mode(): + """盲测与预览/正式解析必须从当前页同一字符事实开始重建。""" evidence = { 'tables': {'table-1': [{'text': 'TABLE'}]}, 'page_glyphs': {'1': [{'text': 'PAGE'}]}, @@ -62,13 +72,36 @@ def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_sourc assert quality._region_characters_for_quality( region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'), evidence=evidence, raw_table=raw_table, table_id='table-1', - ) == [{'text': 'TABLE'}] + ) == [{'text': 'PAGE'}] assert quality._region_characters_for_quality( region=SimpleNamespace(row_reconstruction_mode='adaptive_record_columns'), evidence=evidence, raw_table=raw_table, table_id='table-1', ) == [{'text': 'PAGE'}] +def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages(): + """关键断言:第二页只有合同正文时,不能重复重建第一页的订单明细。""" + evidence = { + 'tables': {'table-1': [{'text': 'TABLE'}]}, + 'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'TERMS'}]}, + } + region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False)) + raw_table = {'table_id': 'table-1', 'page_no': 1} + assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}] + assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None + + +def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region(): + """关键断言:显式跨页区域只能使用后续页自己的 page glyphs。""" + evidence = { + 'tables': {'table-1': [{'text': 'PAGE-1'}]}, + 'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'PAGE-2'}]}, + } + region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=True)) + raw_table = {'table_id': 'table-1', 'page_no': 1} + assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) == [{'text': 'PAGE-2'}] + + def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingOrderDocument]]: """创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。""" user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin') @@ -244,10 +277,8 @@ def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(a ) executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id) assert executed['latest_run']['status'] == 'passed', executed['latest_run'] - with pytest.raises(Exception) as self_approval: - quality.approve_suite(suite_id=suite['id'], actor_id=user.id) - assert getattr(self_approval.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY' - approved = quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id) + # 业务规则:具备管理员权限即可批准,不再要求必须由其他管理员批准。 + approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id) assert approved['status'] == 'approved' assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) qualification = quality.qualification_summary(profile) @@ -334,6 +365,7 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app): layout_version = documents[1].current_layout_version payload = dict(layout_version.payload_json) + payload.pop('coordinate_evidence_ref', None) payload['coordinate_evidence'] = {'tables': {}, 'pages': {}, 'page_glyphs': {}} layout_version.payload_json = payload db.session.commit() @@ -344,7 +376,6 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app): if item['document_id'] == documents[1].id ) assert candidate['review_mode'] == 'preparing' - assert candidate['confirmable'] is False assert candidate['layout_issue_codes'] == ['coordinate_evidence_missing'] @@ -365,27 +396,6 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch): db.session.commit() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) - def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None): - """模拟从原始 PDF 恢复整页字符,验证盲测不依赖 MinerU table_id。""" - assert page_nos is None - recovered = dict(layout) - recovered['coordinate_evidence'] = { - 'pages': {'1': {'width': 200, 'height': 60}}, - 'page_glyphs': {'1': [ - {'text': char, 'bbox': { - 'x0': x0 + char_index * 5, 'y0': 20, - 'x1': x0 + char_index * 5 + 4, 'y1': 30, - }} - for text, x0 in [('PN-1', 30), ('3', 150)] - for char_index, char in enumerate(text) - ]}, - 'sources': {'pages': {'1': 'pdf_coordinate'}}, - 'tables': {}, - } - return recovered - - monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates) - available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples'] candidate_option = next(item for item in available if item['document_id'] == document.id) assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID @@ -393,11 +403,13 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch): assert candidate_option['confirmable'] is False assert candidate_option['layout_issue_codes'] == ['mineru_cell_coordinates_missing'] - candidate = quality.preview_independent_sample( - suite_id=suite['id'], document_id=document.id, - table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id, - ) - assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': '3'}] + with pytest.raises(Exception) as diagnostic_preview: + quality.preview_independent_sample( + suite_id=suite['id'], document_id=document.id, + table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id, + ) + assert getattr(diagnostic_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID' + candidate = {'rows': []} with pytest.raises(Exception) as bypassed_review: quality.add_sample( suite_id=suite['id'], document_id=document.id, @@ -405,7 +417,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch): expected_rows=candidate['rows'], actor_id=user.id, ) assert getattr(bypassed_review.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID' - assert candidate['confirmable'] is False + assert diagnostic_preview.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID' with pytest.raises(Exception) as diagnostic_confirmation: quality.confirm_sample_reviews( suite_id=suite['id'], document_id=document.id, @@ -414,7 +426,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch): layout_version_id=current_version.id, layout_payload_checksum=current_version.payload_checksum, actor_id=user.id, ) - assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE' + assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID' def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch): @@ -431,29 +443,6 @@ def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch): db.session.commit() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) - def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None): - """模拟正在预热时直接从原 PDF 恢复整页坐标,空布局不得阻断复核。""" - assert layout == {'status': 'pending', 'tables': [], 'issues': []} - assert page_nos is None - return { - **layout, - 'coordinate_evidence': { - 'pages': {'1': {'width': 200, 'height': 60}}, - 'page_glyphs': {'1': [ - {'text': char, 'bbox': { - 'x0': x0 + char_index * 5, 'y0': 20, - 'x1': x0 + char_index * 5 + 4, 'y1': 30, - }} - for text, x0 in [('PN-1', 30), ('3', 150)] - for char_index, char in enumerate(text) - ]}, - 'sources': {'pages': {'1': 'pdf_coordinate'}}, - 'tables': {}, - }, - } - - monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates) - available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples'] candidate_option = next(item for item in available if item['document_id'] == document.id) assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID @@ -484,26 +473,6 @@ def test_document_candidate_identity_expires_after_background_layout_completion( for item in available ) - def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None): - """文档级复核使用整页证据,不依赖后台刚生成的表格身份。""" - assert page_nos is None - recovered = dict(layout) - recovered['coordinate_evidence'] = { - 'pages': {'1': {'width': 200, 'height': 60}}, - 'page_glyphs': {'1': [ - {'text': char, 'bbox': { - 'x0': x0 + char_index * 5, 'y0': 20, - 'x1': x0 + char_index * 5 + 4, 'y1': 30, - }} - for text, x0 in [('PN-1', 30), ('3', 150)] - for char_index, char in enumerate(text) - ]}, - 'sources': {'pages': {'1': 'pdf_coordinate'}}, - 'tables': {}, - } - return recovered - - monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates) with pytest.raises(Exception) as stale_preview: quality.preview_independent_sample( suite_id=suite['id'], document_id=document.id, @@ -600,8 +569,9 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid record_inline_layout_snapshot(document, { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', 'tables': [{'table_id': 'table-1', 'page_no': 1}], - 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}}, + 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, }) + db.session.flush() db.session.commit() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) for document in documents: @@ -671,7 +641,7 @@ def test_coordinate_blind_preview_skips_header_only_regions(app): record_inline_layout_snapshot(document, { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', 'tables': [{'table_id': 'table-1', 'page_no': 1}], - 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}}, + 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, }) db.session.commit() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) @@ -680,6 +650,56 @@ def test_coordinate_blind_preview_skips_header_only_regions(app): assert candidate['rows'] == [] +def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app): + """盲测候选必须和编辑器预览一样排除表头视觉区域。""" + with app.app_context(): + profile, user, documents = _published_profile_with_samples() + profile.definition_json = { + 'document_match': {'required_anchors': []}, + 'table_regions': [{ + 'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1, + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'header_layouts': [{ + 'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, + 'field_regions': [], + }], + 'line_layouts': [{ + 'layout_id': 'main', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': 1}, + 'field_regions': [ + {'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, + {'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', + 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, + ], + }], + }], 'order_field_layouts': [], + } + glyphs = [ + {'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 10, 'x1': 23 + index * 4, 'y1': 20}} + for index, char in enumerate('Item') + ] + [ + {'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}} + for index, char in enumerate('20') + ] + [ + {'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}} + for index, char in enumerate('PART-A') + ] + record_inline_layout_snapshot(documents[1], { + 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', + 'tables': [{'table_id': 'table-1', 'page_no': 1}], + 'coordinate_evidence': { + 'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + }) + db.session.commit() + candidate = quality._candidate_for_sample( + profile=profile, document_id=documents[1].id, table_id='table-1', + ) + assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}] + + def test_profile_checksum_change_invalidates_approved_quality_credential(app): """关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。""" with app.app_context(): diff --git a/backend/tests/test_shipping_excel_template.py b/backend/tests/test_shipping_excel_template.py index bf7d9055..3d89d9d1 100644 --- a/backend/tests/test_shipping_excel_template.py +++ b/backend/tests/test_shipping_excel_template.py @@ -19,7 +19,7 @@ from app import db from app.models import ( ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, - ShippingCase, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ) from app.services.shipping_notice import excel_template @@ -152,12 +152,10 @@ def _workbook_upload() -> FileStorage: def test_filename_pattern_supports_business_number_and_split_business_variables(): """业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。""" - shipping_case = ShippingCase( - case_no='CASE-FILENAME', business_no='WYC26060201', customer_short_code_snapshot='WYC', - business_date=date(2026, 6, 2), sequence_value=1, + task = ShippingNotice( + task_no='TASK-FILENAME', inventory_source_code='DBS', business_no='WYC26060201', + customer_short_code_snapshot='WYC', business_date=date(2026, 6, 2), business_sequence_value=1, ) - task = ShippingNotice(task_no='TASK-FILENAME', inventory_source_code='DBS') - task.shipping_case = shipping_case template = ShippingExcelTemplate( template_code='FILENAME', display_name='Filename', definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'}, @@ -333,8 +331,15 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): ShippingOrderFieldValue(extraction_id=extraction.id, field_id=po_number.id, value_text='16754796', decision_id=po_decision.id), ShippingOrderFieldValue(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, value_text='PN-1', decision_id=line_decision.id), ]) + confirmed_customer = ShippingCustomer( + standard_name='Export ACME', short_code='EAC', status='active', + ) + db.session.add(confirmed_customer) + db.session.flush() task = ShippingNotice( task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB', + customer_id=confirmed_customer.id, + customer_resolution_status='confirmed', # 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。 inventory_warehouse_id=None, inventory_lines_json=[{ _inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9', @@ -348,6 +353,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): lines=[(1, part.id, 'PN-1', 1, '1000000001')], ) + assert task.business_no is None path, filename, artifact = generate_shipment_excel(task) db.session.commit() @@ -363,10 +369,13 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): assert artifact.order_schema_version_id == version.id assert artifact.inventory_parsing_profile_id == parsing.id assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0 + assert task.business_no is not None + assert task.business_no.startswith('EAC') - # 已存在待上传 Artifact 时仍保持原有幂等保护,和 Warehouse ID 无关。 - with pytest.raises(ValueError, match='当前任务存在待上传的发货 Excel'): + # 一个 Notice 已有 Excel 后必须创建新 Notice,禁止同号追加第二个 Artifact。 + with pytest.raises(ConflictError) as second_export: generate_shipment_excel(task) + assert second_export.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED' def test_header_mapping_rejects_line_order_field(app): @@ -401,17 +410,13 @@ def test_export_date_system_fact_uses_business_timezone(app): assert isinstance(value, date) -def test_excel_pull_request_number_uses_export_date_without_changing_case_number(app): - """Excel Pull Request Number 必须采用导出日期,且业务单主编号保持原值。""" +def test_excel_pull_request_number_uses_notice_business_number(app): + """Excel Pull Request Number 直接使用 Notice business_no,不因导出日期重编号。""" with app.app_context(): - shipping_case = ShippingCase( - case_no='CASE-EXCEL-NO', business_no='IVMX26080801', sequence_value=1, - ) - task = ShippingNotice(task_no='TASK-EXCEL-NO') - task.shipping_case = shipping_case + task = ShippingNotice(task_no='TASK-EXCEL-NO', business_no='IVMX26080801', business_sequence_value=1) - assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26081101' - assert shipping_case.business_no == 'IVMX26080801' + assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26080801' + assert task.business_no == 'IVMX26080801' def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app): diff --git a/backend/tests/test_shipping_generic_order_gate.py b/backend/tests/test_shipping_generic_order_gate.py index 254183d8..5e944dab 100644 --- a/backend/tests/test_shipping_generic_order_gate.py +++ b/backend/tests/test_shipping_generic_order_gate.py @@ -12,11 +12,15 @@ from decimal import Decimal from types import SimpleNamespace from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate +from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan from app.services.shipping_notice.order_extraction_workflow import ( _apply_stp_route_adjudication, _coordinate_profile_rows, + _physical_table_targets_profile_region, _profile_table_candidates, _route_reason_for_issue, + _selected_coordinate_transform, + _virtual_page_without_rows_is_nonblocking, _should_attempt_generic_extraction, route_deterministic_unit, ) @@ -37,6 +41,37 @@ def _field(code: str, *, scope: str = 'line', required: bool = False, collection } +def test_physical_table_outside_profile_region_is_not_a_parse_target(): + """页脚等非目标物理表不得进入模板明细重建并污染已成功的订单表。""" + regions = [{ + 'region_id': 'order-lines', 'page_scope': 'exact_page', 'page_no': 1, + 'region': {'x0': .02, 'y0': .40, 'x1': .94, 'y1': .46}, + 'line_layouts': [{}], + }] + page = {'width': 612, 'height': 792} + + assert _physical_table_targets_profile_region( + raw_table={'table_id': 'order-lines', 'page_no': 1, 'bbox': {'x0': 15, 'y0': 235, 'x1': 570, 'y1': 345}}, + table_regions=regions, page_size=page, + ) is True + assert _physical_table_targets_profile_region( + raw_table={'table_id': 'footer-summary', 'page_no': 1, 'bbox': {'x0': 16, 'y0': 659, 'x1': 569, 'y1': 721}}, + table_regions=regions, page_size=page, + ) is False + + +def test_empty_virtual_page_does_not_block_a_successful_target_table(): + """无物理表的续页仅用于补漏;没有行时不得覆盖已成功的目标表。""" + assert _virtual_page_without_rows_is_nonblocking( + raw_table={'table_id': 'page-2', 'page_no': 2}, + fixed_rows=[], adaptive_rows=[], + ) is True + assert _virtual_page_without_rows_is_nonblocking( + raw_table={'table_id': 'page-2', 'page_no': 2}, + fixed_rows=[{'status': 'needs_review', 'issues': ['field_invalid']}], adaptive_rows=[], + ) is False + + def _good_candidate() -> dict: return { 'page_no': 1, @@ -66,6 +101,19 @@ def _good_candidate() -> dict: } +def _frozen_generic_document(candidate: dict) -> dict: + """构造与生产 Run 一致的冻结候选和 Parse Plan,禁止测试直接旁路生产边界。""" + layout = {'status': 'ready', 'tables': [], 'layout_candidate': {}} + return { + 'document_id': 55, + 'layout_snapshot': layout, + 'layout_schema_candidates': [candidate], + 'generic_parse_plan': compile_generic_parse_plan( + candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout, + ), + } + + def test_gate_passes_clean_candidate(): """完整映射且无未解释行时 gate 通过。""" definition = {'fields': [_field('part_number', required=True), _field('qty', required=True)]} @@ -326,6 +374,43 @@ def test_should_attempt_generic_extraction_allows_no_special_profile_feature(): ) is True +def test_legacy_profile_does_not_apply_matcher_inferred_coordinate_transform(): + """已发布 legacy 模板的正式字段解析必须沿用盲测验证过的绝对坐标。""" + inferred = { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': .03, + 'anchor_ids': ['title'], 'reason_codes': [], + } + transform = _selected_coordinate_transform( + raw_profile={ + 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'definition': {'coordinate_model': {'type': 'legacy'}}, + }, + profile_match={ + 'status': 'unique_match', 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'candidates': [{ + 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'coordinate_transform': inferred, + }], + }, + ) + + # 关键断言:自动推断的位移只服务于匹配,不得改变 legacy 模板的正式字段坐标。 + assert transform is None + assert _selected_coordinate_transform( + raw_profile={ + 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'definition': {'coordinate_model': {'type': 'anchor_frame'}}, + }, + profile_match={ + 'status': 'unique_match', 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'candidates': [{ + 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'coordinate_transform': inferred, + }], + }, + ) == inferred + + def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkeypatch): """自适应模板的完整业务行不得按子布局数量误判跨页,成功匹配必须上送路由审计。""" profile = { @@ -405,7 +490,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey assert result['match']['status'] == 'unique_match' assert result['match']['profile_code'] == 'ODP-PRODUCTION' # 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。 - assert seen_table_ids == ['native-text-table-p1-1'] + assert seen_table_ids == ['native-text-table-p1-1', 'native-text-table-p1-1'] def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): @@ -415,6 +500,7 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): region=SimpleNamespace(model_dump=lambda: {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}), termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False), line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines', + model_dump=lambda: {'region_id': 'lines', 'page_scope': 'all_pages', 'line_layouts': [{}]}, ) monkeypatch.setattr( 'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile', @@ -442,6 +528,43 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): assert seen['characters'][0]['text'] == 'Terms' +def test_coordinate_profile_rows_forward_selected_match_transform_without_recomputing(monkeypatch): + """工作流只能转交共同 matcher 的已选变换,不能由表格或订单值重新推断。""" + region = SimpleNamespace( + page_scope='all_pages', page_no=None, line_layouts=[SimpleNamespace(model_dump=lambda: {})], + region=SimpleNamespace(model_dump=lambda: {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.5}), + termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False), + line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines', + model_dump=lambda: {'region_id': 'lines', 'page_scope': 'all_pages'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile', + lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]), + ) + seen = {} + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workflow.reconstruct_coordinate_profile_rows', + lambda **kwargs: (seen.update(coordinate_transform=kwargs.get('coordinate_transform')) or []), + ) + transform = { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': .03, + 'anchor_ids': ['title'], 'reason_codes': [], + } + + rows = _coordinate_profile_rows( + raw_profile={}, raw_table={'table_id': 'order-table', 'page_no': 1}, + layout={'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': [{'text': 'x', 'bbox': {'x0': 30, 'y0': 30, 'x1': 31, 'y1': 31}}]}, + 'tables': {}, + }}, + contract=SimpleNamespace(fields_by_code={}), schema_fields={}, coordinate_transform=transform, + ) + + assert rows == [] + assert seen['coordinate_transform'] == transform + + def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkeypatch): """固定子行以模板表区为权威,须读取 MinerU 框外续行并跳过同页无关表。""" region = SimpleNamespace( @@ -559,11 +682,7 @@ def test_route_deterministic_unit_uses_generic_when_enabled(monkeypatch): 'order_document_profiles': [], 'intakes': [{ 'intake_no': 'SNI-001', - 'documents': [{ - 'document_id': 55, - 'layout_snapshot': {'status': 'ready', 'tables': []}, - 'layout_schema_candidates': [candidate], - }], + 'documents': [_frozen_generic_document(candidate)], }], }, ) @@ -609,11 +728,7 @@ def test_template_parse_failure_falls_back_to_generic(monkeypatch): 'order_document_profiles': [{'schema_version_id': 1}], 'intakes': [{ 'intake_no': 'SNI-001', - 'documents': [{ - 'document_id': 55, - 'layout_snapshot': {'status': 'ready', 'tables': []}, - 'layout_schema_candidates': [candidate], - }], + 'documents': [_frozen_generic_document(candidate)], }], }, ) diff --git a/backend/tests/test_shipping_generic_parse_plan.py b/backend/tests/test_shipping_generic_parse_plan.py new file mode 100644 index 00000000..7d1d3020 --- /dev/null +++ b/backend/tests/test_shipping_generic_parse_plan.py @@ -0,0 +1,95 @@ +""" +tests/test_shipping_generic_parse_plan.py + +用途:验证自动标注候选必须先冻结为 Parse Plan,且 Plan 不能跨 Schema/Layout/候选复用。 +依赖:generic_parse_plan、generic_order_gate。 +逻辑:覆盖生产通用解析的身份门禁;任一输入漂移均 fail-closed 到 Review。 +""" + +from types import SimpleNamespace + +from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate +from app.services.shipping_notice.generic_parse_plan import ( + compile_generic_parse_plan, + validate_generic_parse_plan, +) + + +def _candidate() -> dict: + return { + 'page_no': 1, 'table_id': 'table-1', 'mapping_status': 'candidate', + 'columns': [{'column_index': 0, 'field_id': 'part', 'field_code': 'part_number', 'status': 'mapped'}], + 'rows': [{'row_index': 1, 'role': 'data', 'fields': [{ + 'field_id': 'part', 'field_code': 'part_number', 'value': 'ABC', + 'cell_id': 'cell-1', 'evidence_ref': 'layout:1:cell-1', + }]}], + 'row_role_summary': {'data': 1}, 'unmapped_nonempty_column_indices': [], + } + + +def _definition() -> dict: + return {'fields': [{ + 'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, + 'required': True, 'value_type': 'string', 'aliases': ['Part'], + }]} + + +def _evaluate(*, plan, candidates, layout): + return evaluate_generic_extraction_gate( + candidates=candidates, parse_plan=plan, require_parse_plan=True, layout_snapshot=layout, + definition=_definition(), schema={'schema_version_id': 1, 'checksum': 'a' * 64}, + intake={'intake_no': 'SNI-1'}, unit=SimpleNamespace(document_id=1), + ) + + +def test_frozen_parse_plan_allows_clean_generic_deterministic_candidate(): + """自动标注经 Plan 冻结、证据绑定和 Gate 后才可进入确定性解析。""" + candidate = _candidate() + layout = {'layout_candidate': {'pages': [{'page_no': 1}]}} + plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout) + + result = _evaluate(plan=plan, candidates=[candidate], layout=layout) + + assert result.passed is True + + +def test_missing_parse_plan_blocks_production_generic_route(): + """候选本身再完整,未冻结 Plan 也不得作为生产事实。""" + result = _evaluate(plan=None, candidates=[_candidate()], layout={'layout_candidate': {}}) + + assert result.passed is False + assert 'generic_parse_plan_missing' in result.gate_reason_codes + + +def test_parse_plan_blocks_runtime_candidate_drift(): + """冻结后运行时候选变化均不得以旧 Plan 自动建单。""" + candidate = _candidate() + layout = {'layout_candidate': {'pages': [{'page_no': 1}]}} + plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout) + changed_candidate = _candidate() + changed_candidate['rows'][0]['fields'][0]['value'] = 'CHANGED' + + result = _evaluate(plan=plan, candidates=[changed_candidate], layout=layout) + + assert result.passed is False + assert 'generic_parse_plan_runtime_candidate_changed' in result.gate_reason_codes + + +def test_parse_plan_blocks_schema_or_layout_drift(): + """冻结 Plan 不能跨 Schema 或 Layout 复用,防止自动标注结果污染其他文档。""" + candidate = _candidate() + layout = {'layout_candidate': {'pages': [{'page_no': 1}]}} + plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout) + + schema_changed = validate_generic_parse_plan( + plan=plan, schema_checksum='b' * 64, layout_snapshot=layout, runtime_candidates=[candidate], + ) + layout_changed = validate_generic_parse_plan( + plan=plan, schema_checksum='a' * 64, + layout_snapshot={'layout_candidate': {'pages': [{'page_no': 2}]}}, runtime_candidates=[candidate], + ) + + assert schema_changed.passed is False + assert 'generic_parse_plan_schema_changed' in schema_changed.reason_codes + assert layout_changed.passed is False + assert 'generic_parse_plan_layout_changed' in layout_changed.reason_codes diff --git a/backend/tests/test_shipping_notice_business_case.py b/backend/tests/test_shipping_notice_business_case.py index 926913bb..66e9d5f0 100644 --- a/backend/tests/test_shipping_notice_business_case.py +++ b/backend/tests/test_shipping_notice_business_case.py @@ -1,25 +1,23 @@ """ backend/tests/test_shipping_notice_business_case.py -用途:验证货代业务单聚合在普通建单、修订和强制新建场景下的归属规则。 -依赖:app fixture、ShippingNotice/ShippingCase、business_case_service。 -逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。 +用途:验证 Notice 建单和替代关系不依赖 ShippingCase。 +依赖:app fixture、ShippingNotice、task_workflow。 +逻辑:直接调用领域服务并断言 Notice 独立事实,不触发解析和库存副作用。 """ +from app import db import pytest -from app import db from app.core.errors import ConflictError -from app.models import ShippingCase, ShippingCustomer, ShippingNotice -from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task -from app.services.shipping_notice.task_workflow import create_batch_tasks, create_task +from app.models import ShippingCustomer, ShippingNotice +from app.services.shipping_notice.task_workflow import create_task -def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int | None = None) -> ShippingNotice: - """构造最小货代任务,供业务单关系断言使用。""" +def _task(task_no: str, *, supersedes_task_id: int | None = None) -> ShippingNotice: + """构造最小 Notice,供替代关系断言使用。""" return ShippingNotice( task_no=task_no, - shipping_case_id=case_id, supersedes_task_id=supersedes_task_id, source_type='manual', ) @@ -33,76 +31,32 @@ def _active_customer(*, short_code: str = 'CASE') -> ShippingCustomer: return customer -def test_normal_and_force_create_use_different_cases(app): - """普通建单和强制新建必须各自创建独立业务单。""" +def test_notices_are_independent_without_business_case(app): + """不同 Notice 无需中间聚合实体,业务事实由自身保存。""" with app.app_context(): - normal = resolve_shipping_case_for_new_task(created_by_id=None) - forced = resolve_shipping_case_for_new_task( - duplicate_resolution_type='force_create', - created_by_id=None, - ) - assert normal.id != forced.id - assert normal.business_no is None - assert forced.business_no is None + first = _task('SN-NOTICE-INDEPENDENT-1') + second = _task('SN-NOTICE-INDEPENDENT-2') + db.session.add_all([first, second]) + db.session.commit() + assert first.id != second.id + assert first.business_no is None + assert second.business_no is None -def test_revision_inherits_existing_parent_case(app): - """修订任务必须继承父任务已有业务单,不能创建新业务单。""" +def test_replacement_links_to_parent_notice(app): + """替代 Notice 仅链接原 Notice,不继承或依赖 Case。""" with app.app_context(): - case = resolve_shipping_case_for_new_task(created_by_id=None) - parent = _task('SN-CASE-PARENT-1', case_id=case.id) + parent = _task('SN-NOTICE-PARENT-1') db.session.add(parent) db.session.flush() - - resolved = resolve_shipping_case_for_new_task( - supersedes_task_id=parent.id, - duplicate_resolution_type='revision', - ) - assert resolved.id == case.id - assert ShippingCase.query.count() == 1 + replacement = _task('SN-NOTICE-REPLACEMENT-1', supersedes_task_id=parent.id) + db.session.add(replacement) + db.session.commit() + assert replacement.supersedes_task_id == parent.id -def test_revision_rejects_parent_without_business_case(app): - """修订父任务缺少业务单时必须阻断,禁止隐式补建。""" - with app.app_context(): - parent = _task('SN-CASE-LEGACY-1') - db.session.add(parent) - db.session.flush() - - with pytest.raises(ConflictError) as exc_info: - resolve_shipping_case_for_new_task( - supersedes_task_id=parent.id, - duplicate_resolution_type='revision', - ) - assert exc_info.value.code == 'SHIPPING_NOTICE.REVISION_CASE_MISSING' - assert ShippingCase.query.count() == 0 - - -def test_revision_chain_reuses_root_case(app): - """连续修订版本必须沿用同一业务单聚合。""" - with app.app_context(): - case = resolve_shipping_case_for_new_task(created_by_id=None) - parent = _task('SN-CASE-CHAIN-1', case_id=case.id) - db.session.add(parent) - db.session.flush() - revision_case = resolve_shipping_case_for_new_task( - supersedes_task_id=parent.id, - duplicate_resolution_type='revision', - ) - revision = _task('SN-CASE-CHAIN-2', case_id=revision_case.id, supersedes_task_id=parent.id) - db.session.add(revision) - db.session.flush() - - next_case = resolve_shipping_case_for_new_task( - supersedes_task_id=revision.id, - duplicate_resolution_type='revision', - ) - assert next_case.id == case.id - assert ShippingCase.query.count() == 1 - - -def test_create_task_assigns_case_and_serializes_it(app): - """真实单票建单路径必须创建业务单并在 Tool 投影中返回关联信息。""" +def test_create_task_assigns_notice_customer_and_serializes_it(app): + """真实单票建单路径直接写 Notice 客户事实,不创建 ShippingCase。""" with app.app_context(): customer = _active_customer(short_code='CRT') result = create_task({ @@ -111,11 +65,9 @@ def test_create_task_assigns_case_and_serializes_it(app): 'customer_id': customer.id, }) task = ShippingNotice.query.filter_by(task_no=result['task_id']).one() - assert task.shipping_case_id is not None assert task.customer_resolution_status == 'confirmed' - assert result['data']['shipping_case_id'] == task.shipping_case_id - assert result['data']['case_no'] == task.shipping_case.case_no - assert task.shipping_case.customer_id == customer.id + assert task.customer_id == customer.id + assert result['data']['customer_id'] == customer.id def test_create_task_rejects_without_customer(app): @@ -126,59 +78,3 @@ def test_create_task_rejects_without_customer(app): assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK' -@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c') -def test_batch_revision_inherits_parent_case(app): - """真实批量建单路径中的 revision 必须继承父任务业务单。""" - with app.app_context(): - customer = _active_customer(short_code='REV') - case = resolve_shipping_case_for_new_task(created_by_id=None) - case.customer_id = customer.id - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = customer.short_code - parent = _task('SN-CASE-BATCH-PARENT', case_id=case.id) - parent.customer_resolution_status = 'confirmed' - db.session.add(parent) - db.session.commit() - - result = create_batch_tasks({ - 'notice_items': [{ - 'source_type': 'manual', - 'raw_text': 'revision notice', - 'document_version': 2, - 'supersedes_task_id': parent.id, - 'duplicate_resolution_type': 'revision', - }], - 'defer_parse': True, - }) - task = ShippingNotice.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one() - assert task.shipping_case_id == case.id - assert task.supersedes_task_id == parent.id - assert task.customer_resolution_status == 'confirmed' - assert ShippingCase.query.count() == 1 - - -@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c') -def test_batch_force_create_uses_new_case(app): - """真实批量建单路径中的 force_create 必须创建独立业务单。""" - with app.app_context(): - customer = _active_customer(short_code='FRC') - original_case = resolve_shipping_case_for_new_task(created_by_id=None) - original = _task('SN-CASE-FORCE-SOURCE', case_id=original_case.id) - db.session.add(original) - db.session.commit() - - result = create_batch_tasks({ - 'notice_items': [{ - 'source_type': 'manual', - 'raw_text': 'forced notice', - 'duplicate_source_task_id': original.id, - 'duplicate_resolution_type': 'force_create', - 'customer_id': customer.id, - }], - 'defer_parse': True, - }) - task = ShippingNotice.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one() - assert task.shipping_case_id != original_case.id - assert task.duplicate_source_task_id == original.id - assert task.customer_resolution_status == 'confirmed' - assert ShippingCase.query.count() == 2 diff --git a/backend/tests/test_shipping_notice_intakes_lifecycle.py b/backend/tests/test_shipping_notice_intakes_lifecycle.py index 7d2b2c04..73334d52 100644 --- a/backend/tests/test_shipping_notice_intakes_lifecycle.py +++ b/backend/tests/test_shipping_notice_intakes_lifecycle.py @@ -101,6 +101,62 @@ def test_intake_status_exposes_layout_lifecycle_without_blocking_terminal_fallba assert completed['layout_status'] == 'completed' assert completed['layout_summary']['failed'] == 1 + +def test_active_intake_list_omits_heavy_candidate_review_details(app, shipping_user): + """活跃列表保留恢复所需字段,但不得传输审核证据与裁决历史。""" + from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation + + with app.app_context(): + asset, intake = _seed_parsed_intake( + shipping_user.id, + intake_no='SNI-LIGHT-LIST-001', + hash_value='light-list-hash', + ) + intake.conversation_id = 'conversation-light-list' + document = ShippingOrderDocument( + intake_id=intake.id, + asset_id=asset.id, + document_type='attachment', + attachment_key='order.pdf', + filename='order.pdf', + content_hash='light-list-document-hash', + classification='order_notice', + parse_status='parsed', + ) + db.session.add(document) + db.session.flush() + db.session.add(ShippingOrderCandidate( + candidate_no='SNC-LIGHT-LIST-001', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key='light-list-candidate', + structured_result_json={ + 'business_summary': {'po_number': 'PO-LIGHT-001'}, + 'extraction': { + 'field_adjudication': {'observation_history': ['large-history']}, + 'customer_matches': [{'customer': 'large-match'}], + }, + }, + evidence_json=[{'text': 'large-evidence'}], + selected=True, + validation_status='ready', + )) + db.session.commit() + + rows = list_active_intakes_for_conversation( + user_id=shipping_user.id, + conversation_id='conversation-light-list', + ) + + assert len(rows) == 1 + candidate = rows[0]['candidates'][0] + assert candidate['candidate_no'] == 'SNC-LIGHT-LIST-001' + assert candidate['po_number'] == 'PO-LIGHT-001' + assert candidate['selected'] is True + assert 'evidence' not in candidate + assert 'field_adjudication' not in candidate + assert 'customer_matches' not in candidate + def test_candidate_review_duplicate_api_and_access_guards(app, client): """Candidate API 应支持修订、刷新和决策,并阻止越权或已消费候选修改。""" from app.core.auth.jwt import issue_local_access_token diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 71217e83..7ff68aa7 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -13,7 +13,7 @@ import pytest from app import db from app.models import ( - ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource, + ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink, ShippingOrderCustomerMatch, @@ -101,7 +101,7 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None: """为直接构造的 RPA 回调任务补齐已确认客户。 - 核心逻辑:测试不经建单工作流时,显式创建 business case 与激活客户, + 核心逻辑:测试不经建单工作流时,显式绑定激活客户, 使回调测试只验证 RPA 契约,而不绕过客户身份门禁。 """ customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none() @@ -111,47 +111,17 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None: ) db.session.add(customer) db.session.flush() - case = ShippingCase( - case_no=f'CASE-{task.task_no}', customer=customer, - customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code, - ) - task.shipping_case = case + task.customer = customer + task.customer_name_snapshot = customer.standard_name + task.customer_short_code_snapshot = customer.short_code task.customer_resolution_status = 'confirmed' task.customer_resolution_method = 'test_fixture' - db.session.add_all([case, task]) + db.session.add(task) db.session.flush() # 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。 task._test_customer_confirmed = True -@pytest.fixture(autouse=True) -def _confirmed_customer_for_rpa_flows(app, monkeypatch): - """为本模块新建的业务单绑定测试客户,使用例聚焦客户门禁之后的 RPA 行为。""" - from app.services.shipping_notice import task_workflow - - original = task_workflow.resolve_shipping_case_for_new_task - - def _resolve_confirmed_case(**kwargs): - case = original(**kwargs) - if case.customer_id is not None: - return case - customer = db.session.query(ShippingCustomer).filter_by(short_code="RPA").one_or_none() - if customer is None: - customer = ShippingCustomer( - standard_name="RPA 流程测试客户", - short_code="RPA", - status="active", - ) - db.session.add(customer) - db.session.flush() - case.customer_id = customer.id - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = customer.short_code - return case - - monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case) - - @pytest.fixture(autouse=True) def _freeze_test_rpa_batch_callback_contract(monkeypatch): """兼容旧测试调用:仅在测试边界补齐 v2 envelope,不改变生产回调校验。""" diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index f9567eba..04e0749d 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -41,7 +41,10 @@ from app.models import ( ) from app.services.chat.log_service import merge_chat_log_payload from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary -from app.services.shipping_notice.order_extraction import persist_order_extraction_result +from app.services.shipping_notice.order_extraction import ( + _discard_resolved_worker_field_conflicts, + persist_order_extraction_result, +) from app.services.shipping_notice.order_extraction_merge import merge_unit_orders from app.services.shipping_notice.open_existing_reservation_backfill import ( backfill_exact_file_open_existing_reservations, @@ -84,6 +87,9 @@ def _ensure_order_schema() -> dict[str, str]: configs.append({ 'field_id': field['id'], 'display_name': code, 'required': required, 'aliases': [], 'business_purpose': business_purposes.get(code, 'general'), + # Reservation 是自动建单的流程匹配键;证据不足必须阻断 STP,不能仅作为诊断。 + 'auto_create_key_field': code == 'reservation_id', + 'minimum_confidence': 0.85 if code == 'reservation_id' else None, 'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [], 'evidence_policy': { 'required': True, 'source_precedence': ['attachment_text', 'backend_table', 'dify_llm'], @@ -115,6 +121,111 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it() assert assessment['missing_process_fields'] == ['reservation_id'] +def test_candidate_discards_early_optional_line_evidence_conflict_after_derivation(app): + """派生补齐可选 line_no 后,Candidate 不得保留 Worker 的早期 PDF 证据阻断。""" + with app.app_context(): + order_schema_service.initialize_schema({'display_name': '派生字段测试'}, actor_id=None) + customer_line = order_schema_service.save_field( + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + line_no = order_schema_service.save_field( + {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + part = order_schema_service.save_field( + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + qty = order_schema_service.save_field( + {'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None, + ) + draft = order_schema_service.create_draft({}, actor_id=None) + + def config(field: dict, *, required: bool, normalizer: str, validators: list[str], comparator: str) -> dict: + return { + 'field_id': field['id'], 'display_name': field['field_code'], 'required': required, + 'auto_create_key_field': False, 'aliases': [], 'business_purpose': 'general', + 'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_text'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': comparator, + } + + saved = order_schema_service.save_draft(draft['id'], { + 'fields': [ + config(customer_line, required=False, normalizer='trim', validators=[], comparator='normalized_text'), + config(line_no, required=False, normalizer='trim', validators=[], comparator='normalized_text'), + config(part, required=True, normalizer='uppercase_trim', validators=['non_empty'], comparator='normalized_text'), + config(qty, required=True, normalizer='decimal', validators=['positive_decimal'], comparator='decimal'), + ], + 'derivation_rules': [{ + 'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', 'enabled': True, + 'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no', + 'strategy': 'copy_if_empty', 'scope': 'line', + }], + 'expected_lock_version': draft['lock_version'], + }) + published = order_schema_service.publish( + draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], + ) + _user, _session, intake, document, _runtime_context = _seed_extraction_input() + document.extracted_text = 'Customer PO Line 00010 SKU SKU-A QTY 10' + db.session.commit() + + result = _persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [{ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'source_intake_no': intake.intake_no, 'primary_document_id': document.id, + 'classification': 'shipping_request', 'classification_confidence': 0.99, + 'header_fields': [], + 'lines': [{'fields': [ + {'field_id': customer_line['id'], 'observations': [{ + 'value': '00010', 'document_id': document.id, 'quote': 'Customer PO Line 00010', 'confidence': 0.99, + }]}, + {'field_id': part['id'], 'observations': [{ + 'value': 'SKU-A', 'document_id': document.id, 'quote': 'SKU SKU-A', 'confidence': 0.99, + }]}, + {'field_id': qty['id'], 'observations': [{ + 'value': 10, 'document_id': document.id, 'quote': 'QTY 10', 'confidence': 0.99, + }]}, + ]}], + 'conflicts': [{ + 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }], + }]}) + + candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() + decisions = candidate.structured_result_json['extraction']['field_adjudication']['decisions'] + assert any( + item.get('field_code') == 'line_no' and item.get('reason_code') == 'derived' + for item in decisions + ) + assert not any( + item.get('field') == 'line_no' and item.get('reason') == 'evidence_missing' + for item in candidate.conflicts_json + ) + assert 'blocking_conflict' not in result['pending_orders'][0]['reasons'] + + +def test_candidate_keeps_early_field_conflict_when_final_schema_still_blocks_field(): + """最终 Schema 仍阻断的必填/关键字段,不得被已接受的旧 Decision 静默放行。""" + conflicts = _discard_resolved_worker_field_conflicts( + [{ + 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }], + decisions=[{ + 'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived', + }], + blocked_fields=['line_no'], + ) + + assert conflicts == [{ + 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }] + + def test_candidate_validation_projects_customer_po_number_to_legacy_candidate_field(): """当前动态 Schema 的客户 PO 必须投影到 Candidate 兼容字段,供履约链路读取。""" assessment = assess_candidate_business_summary({ @@ -837,7 +948,7 @@ def test_persist_order_extraction_result_keeps_provider_orders_provisional_and_r assert result['pending_count'] == 2 assert result['non_shipping_count'] == 0 assert result['created_with_missing_fields_count'] == 0 - assert result['batch_no'] is None + assert 'batch_no' not in result candidates = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).all() assert len(candidates) == 2 assert len({item.candidate_key for item in candidates}) == 2 @@ -1032,10 +1143,6 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', lambda **_kwargs: dict(duplicate_result), ) - monkeypatch.setattr( - 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_candidate', - lambda **_kwargs: dict(duplicate_result), - ) context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context}) result = _persist_test_orders({ @@ -1133,8 +1240,8 @@ def test_persist_order_extraction_result_unassigned_pending_keeps_documents_part assert document.order_extraction_status == 'partially_completed' -def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_review(app): - """同文件最新 Candidate 按 PO/SKU/qty 唯一命中时,只补旧任务空 Reservation 并保留人工复核。""" +def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app): + """同文件唯一命中补齐 Reservation 后,既有任务进入解析复核而非继续停在缺字段态。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() existing = ShippingNotice( @@ -1195,7 +1302,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev assert values['part_number'] == 'P123456' assert values['qty'] == 24 assert values['reservation_id'] == '1000140351' - assert existing.review_status == 'rsv_req' + # Reservation 已补齐,状态机必须退出 rsv_req;仍保留解析复核,禁止自动确认或推进。 + assert existing.review_status == 'parse_review' assert existing.pending_human_reason == 'low_confidence' assert 'process_field_gate' not in (existing.step_payload_json or {}) assert existing.error_message is None @@ -1281,7 +1389,11 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app): assert result['pending_count'] == 1 assert 'blocking_conflict' in result['pending_orders'][0]['reasons'] candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() - assert any(item['reason'] == 'cross_source_conflict' for item in candidate.conflicts_json) + # 当前裁决以受信表格/PDF 值为准;仍必须作为关键字段冲突阻断 STP。 + assert any( + item['field'] == 'reservation_id' and item['reason'] == 'pdf_preferred' + for item in candidate.conflicts_json + ) adjudication = candidate.structured_result_json['extraction']['field_adjudication'] reservation_observations = [ item for item in adjudication['observations'] diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index d610f7be..3e7b88ee 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -19,37 +19,11 @@ from app.services.shipping_notice.query_service import ( resolve_task_from_payload, serialize_task, task_export_error_message, - task_sort_key, + list_freight_notice_groups_for_task, ) from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT -def test_chat_match_result_payload_uses_unified_actions_only(): - """Chat 匹配结果不得再把旧 action_buttons 作为按钮来源。""" - from app.services.shipping_notice.chat_action_handlers import _match_result_payload - - payload = _match_result_payload( - "SN-ACTIONS-ONLY", - { - "data": { - "match_status": "shortage", - "line_results": [], - "shortage": {"lines": []}, - }, - "action_buttons": [{"id": "legacy_retry"}], - "ui_state": { - "actions": { - "primary": {"code": "open_shortage_review", "enabled": True}, - "secondary": [], - }, - }, - }, - ) - - assert payload["actions"]["primary"]["code"] == "open_shortage_review" - assert "action_buttons" not in payload - - def test_get_task_by_ref_supports_task_no_and_numeric_id(app): """task_no 与数字主键均应能解析到同一任务。""" with app.app_context(): @@ -327,6 +301,116 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app): assert "can_handle" not in no_viewer +def test_serialize_task_summary_projects_only_current_notice_line_facts(app): + """同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。""" + with app.app_context(): + from app import db + from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch + from app.services.shipping_notice.query_service import serialize_task_summary + + first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11) + second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11) + db.session.add_all([first, second]); db.session.flush() + db.session.add_all([ + ShippingNoticeLine( + notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST', + reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'}, + ), + ShippingNoticeLine( + notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND', + reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'}, + ), + ShippingNoticeLineInventoryMatch( + task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready', + available_qty='20', shortage_qty='0', is_current=True, + ), + ShippingNoticeLineInventoryMatch( + task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready', + available_qty='9', shortage_qty='0', is_current=True, + ), + ]) + db.session.commit() + + data = serialize_task_summary(first, viewer_user_id=11) + + assert data['business_no'] == 'WVC26082301' + assert data['notice_line_summary'] == [{ + 'line_no': '00010', 'part_number': 'PART-FIRST', 'customer_part_number': None, + 'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20', + 'shortage_qty': '0', 'inventory_status': 'ready', + }] + + +def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app): + """货代上传聚合必须按同 PO 的 business_no 拆组,并排除无业务号及他人 Notice。""" + with app.app_context(): + from app import db + from app.models import ShippingNoticeLine + from app.services.shipping_notice import query_service + + def with_po(task_no, business_no, user_id): + return ShippingNotice(task_no=task_no, business_no=business_no, source_type='manual', user_id=user_id) + + first = with_po('SN-GROUP-1', 'WYC26082401', 11) + second = with_po('SN-GROUP-2', 'WYC26082402', 11) + no_business = with_po('SN-GROUP-3', None, 11) + other = with_po('SN-GROUP-4', 'WYC26082499', 99) + db.session.add_all([first, second, no_business, other]); db.session.flush() + db.session.add_all([ + ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}), + ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}), + ]) + db.session.commit() + + original_header_reader = query_service.current_header_field_values_or_empty + # customer_po_number 是当前动态 Schema 的正式 PO 字段;聚合必须不依赖旧兼容投影。 + query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-GROUP'} + try: + result = list_freight_notice_groups_for_task(first, user_id=11) + finally: + query_service.current_header_field_values_or_empty = original_header_reader + assert result['po_number'] == 'PO-GROUP' + assert [item['business_no'] for item in result['items']] == ['WYC26082401', 'WYC26082402'] + # 单条菜单必须消费服务端授权投影,前端不得按上传状态自行猜测可执行动作。 + assert 'available_actions' in result['items'][0] + assert result['items'][0]['lines'][0]['part_number'] == 'PART-A' + assert result['items'][1]['lines'][0]['part_number'] == 'PART-B' + + +def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app): + """当前 Extraction 不可读时,货代上传聚合仍必须以冻结快照中的客户 PO 对齐同一发货批次。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderSnapshot + from app.services.shipping_notice import query_service + + first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11) + second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11) + db.session.add_all([first, second]); db.session.flush() + for task in (first, second): + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=task.id, + schema_version_id=1, + order_data_version=1, + header_values_json={}, + customer_po_number='ZNB-16754796', + ) + db.session.add(snapshot); db.session.flush() + task.order_snapshot_id = snapshot.id + db.session.commit() + + original_header_reader = query_service.current_header_field_values_or_empty + query_service.current_header_field_values_or_empty = lambda _task: {} + try: + result = list_freight_notice_groups_for_task(first, user_id=11) + finally: + query_service.current_header_field_values_or_empty = original_header_reader + + assert result['po_number'] == '16754796' + assert [item['business_no'] for item in result['items']] == ['WYC26082411', 'WYC26082412'] + + def test_list_my_todos_and_count_buckets(app): """list_my_todos 按 bucket 分类;count 徽标与 pending 一致。""" with app.app_context(): @@ -434,7 +518,7 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app): assert hit['ui_state']['summary']['entry_surface'] == 'review_workbench' assert hit['ui_state']['lifecycle_stage'] == 'order_review' assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [ - 'available', 'current', 'unavailable', 'unavailable', + 'available', 'current', 'unavailable', 'unavailable', 'unavailable', ] counts = count_my_todos(user.id) @@ -485,8 +569,8 @@ def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_stil assert original.case_no not in review_case_nos -def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app): - """历史空 Review Case 可以处置,但不能被待办页默认授权进入订单生命周期。""" +def test_open_review_case_without_current_candidate_enters_intake_parse(app): + """无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。""" with app.app_context(): from app import db from app.services.shipping_notice.order_review_service import ensure_run_review_cases @@ -503,7 +587,8 @@ def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app): pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50) hit = next(item for item in pending['items'] if item.get('review_case_no') == case.case_no) - assert hit['ui_state']['lifecycle_stage'] is None + assert hit['ui_state']['lifecycle_stage'] == 'intake_parse' + assert hit['ui_state']['intake_parse_authorized'] is True assert hit['ui_state']['lifecycle_entries'] == [] @@ -708,7 +793,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app): row = SimpleNamespace( review_status=task.review_status, pending_human_reason=task.pending_human_reason, - shipping_case_id=task.shipping_case_id, customer_resolution_status=task.customer_resolution_status, order_snapshot_id=task.order_snapshot_id, current_order_extraction_id=task.current_order_extraction_id, diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py index e90f2f72..f6617e61 100644 --- a/backend/tests/test_shipping_notice_reservation_id.py +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -4,6 +4,25 @@ from app.services.shipping_notice.reservation_id import ( normalize_reservation_id, validated_reservation_id, ) +from app.services.shipping_notice.reservation_region import ( + apply_reservation_region_candidates, + extract_reservation_from_region_text, + extract_reservation_from_vendor_comments_pages, +) + + +def _glyph_lines(*lines: str) -> list[dict]: + """构造按视觉阅读顺序排列的最小页面文字证据。""" + glyphs = [] + for row_index, line in enumerate(lines): + for column_index, char in enumerate(line): + glyphs.append({ + 'text': char, + 'bbox': {'x0': column_index * 8, 'x1': column_index * 8 + 6, 'y0': row_index * 16, 'y1': row_index * 16 + 12}, + 'source_index': len(glyphs), + 'boundary_before': 'space' if char == ' ' else 'none', + }) + return glyphs def test_match_numeric_reservation_id(): @@ -37,6 +56,91 @@ def test_reservation_contract_only_accepts_five_or_ten_digits(): assert not is_valid_reservation_id("12345678901", numeric_only=True) +def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present(): + """专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。""" + assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{ + 'value': '3000098851', 'line_no': 1, 'scope': 'line', + 'raw_text': 'Reservation#3000098851 for line#1', 'status': 'mapped', + }] + + +def test_reservation_region_assigns_reservation_without_line_to_header(): + """无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。""" + assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{ + 'value': '33008', 'line_no': None, 'scope': 'header', + 'raw_text': 'MDW hub order.Reservation#33008', 'status': 'header', + }] + + +def test_reservation_region_ignores_unrelated_numeric_noise(): + """备注区的普通客户号、数量等数字没有 Reservation 标签时不得被误写入订单。""" + assert extract_reservation_from_region_text("End Customer: D1\nQuantity: 1000143920") == [] + + +def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading(): + """专区启用后跨页累计 Vendor Comments,首次 Terms 标题后的值必须被排除。""" + candidates, reason = extract_reservation_from_vendor_comments_pages([ + (1, _glyph_lines('Vendor Comments:', 'Reservation#33008')), + (2, _glyph_lines('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999')), + ]) + + assert reason is None + assert [item['value'] for item in candidates] == ['33008', '3000098851'] + + +def test_vendor_comments_window_requires_start_and_end_headings(): + """缺少任一边界时不能把全文中的 Reservation 当作专区证据。""" + candidates, reason = extract_reservation_from_vendor_comments_pages([ + (1, _glyph_lines('Reservation#33008')), + ]) + + assert candidates == [] + assert reason == 'vendor_comments_anchor_missing' + + +def test_reservation_region_applies_header_and_line_override_together(): + """整单值是默认值,指定行的 Reservation 仅覆盖对应明细。""" + applied = apply_reservation_region_candidates( + candidates=extract_reservation_from_region_text( + "MDW hub order.Reservation#33008\nReservation#3000098851 for line#1" + ), + header_field_id='header-reservation', + line_field_id='line-reservation', + line_count=2, + ) + + assert applied.header_value == '33008' + assert applied.line_values == {1: '3000098851'} + assert applied.needs_review is False + + +def test_reservation_region_marks_only_conflicts_and_invalid_line_references_for_review(): + """重复同一值可去重;同一行冲突或越界才阻断自动建单。""" + applied = apply_reservation_region_candidates( + candidates=extract_reservation_from_region_text( + "Reservation#3000098851 for line#1\nReservation#3000098852 for line#1\n" + "Reservation#3000098853 for line#3" + ), + header_field_id='header-reservation', + line_field_id='line-reservation', + line_count=2, + ) + + assert applied.needs_review is True + assert set(applied.review_reasons) == {'conflicting_line_value', 'line_out_of_range'} + + +def test_reservation_region_requires_review_when_numbered_value_has_no_line_target(): + """Schema 未启用行级字段时,不能静默丢弃带行号的覆盖值。""" + applied = apply_reservation_region_candidates( + candidates=extract_reservation_from_region_text("Reservation#3000098851 for line#1"), + header_field_id='header-reservation', line_field_id=None, line_count=1, + ) + + assert applied.needs_review is True + assert applied.review_reasons == ('line_field_unavailable',) + + def test_reservation_gate_blocks_empty_and_malformed_order_lines(): """空订单或畸形行都不能被视为 Reservation 门禁通过。""" from app.services.shipping_notice.reservation_gate import reservation_gate_issues diff --git a/backend/tests/test_shipping_notice_state_machine.py b/backend/tests/test_shipping_notice_state_machine.py index 3c6eaefe..db8cb73a 100644 --- a/backend/tests/test_shipping_notice_state_machine.py +++ b/backend/tests/test_shipping_notice_state_machine.py @@ -79,7 +79,6 @@ def test_resolve_with_mocked_simple_namespace_attributes() -> None: upload_status="uploaded", review_status=None, pending_human_reason=None, - shipping_case_id=None, customer_resolution_status=None, order_snapshot_id=None, inventory_lines_json=None, diff --git a/backend/tests/test_shipping_notice_stp_acceptance.py b/backend/tests/test_shipping_notice_stp_acceptance.py index 399f8b69..75138bef 100644 --- a/backend/tests/test_shipping_notice_stp_acceptance.py +++ b/backend/tests/test_shipping_notice_stp_acceptance.py @@ -290,28 +290,6 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon }) -def test_export_ready_ui_state_entry_is_task_workbench(app) -> None: - """场景:Excel 待人工上传登记待办深链入口为任务处理工作台。""" - with app.app_context(): - task = ShippingNotice( - task_no="SN-STP-ENTRY", - source_type="manual", - export_file_path="/tmp/x.xlsx", - export_file_name="x.xlsx", - ) - state = build_task_ui_state(task) - assert state["checkpoint"]["kind"] == "wait_manual_upload" - assert state["summary"]["entry_surface"] == "task_workbench" - button_ids = [ - item.get("code") - for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])] - if item - ] - assert "mark_manual_uploaded" in button_ids - assert "download_excel" in button_ids - assert "action_buttons" not in state - - def test_my_todos_owner_can_handle_admin_view_only(app) -> None: """场景:跨会话待办 + 权限 — 创建者 can_handle,管理员看他人任务只读。""" with app.app_context(): diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index e51b98f0..fa52d7c7 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -14,7 +14,7 @@ import pytest from app import db from app.models import ( ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule, - ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice, + ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot, ShippingOrderSnapshotLine, @@ -107,34 +107,6 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation db.session.flush() -@pytest.fixture(autouse=True) -def _confirmed_customer_for_legacy_tool_flows(app, monkeypatch): - """为本模块创建的业务单绑定测试客户,使既有用例继续聚焦客户 Gate 之后的流程。""" - from app.services.shipping_notice import task_workflow - - original = task_workflow.resolve_shipping_case_for_new_task - - def _resolve_confirmed_case(**kwargs): - case = original(**kwargs) - if case.customer_id is not None: - return case - customer = db.session.query(ShippingCustomer).filter_by(short_code="TST").one_or_none() - if customer is None: - customer = ShippingCustomer( - standard_name="Tool 流程测试客户", - short_code="TST", - status="active", - ) - db.session.add(customer) - db.session.flush() - case.customer_id = customer.id - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = customer.short_code - return case - - monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case) - - def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client): with app.app_context(): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret" @@ -703,79 +675,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa assert len(list(trigger.glob("inventory_export_*.json"))) == 1 -@pytest.mark.auto_rpa -def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, tmp_path, monkeypatch): - from datetime import datetime, timedelta - - from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks - from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING - - headers = _tool_headers(app) - trigger = tmp_path / "inventory_triggers" - trigger.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 - monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", - lambda: None, - ) - - create_res = client.post( - "/api/shipping-notice/tools/create_batch", - headers=headers, - json={"conversation_id": "conv-rpa-batch-retry"}, - ) - batch_no = create_res.get_json()["batch_no"] - task_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={ - "batch_no": batch_no, - "conversation_id": "conv-rpa-batch-retry", - "source_type": "manual", - }, - ) - task_id = task_res.get_json()["task_id"] - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) - task.pending_human_reason = PH_RPA_PENDING - task.step_payload_json = { - "rpa_inventory_source": { - "source_code": "DSV360_AWSDU", - "connector_type": "dsv360", - "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", - "entry_url": "https://s360.dbschenker.com/", - "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, - } - } - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - db.session.add( - ShippingTaskEvent( - task_id=task.id, - event_type="inventory_rpa_triggered", - detail_json={"attempt": 1}, - created_at=datetime.utcnow() - timedelta(seconds=5), - ) - ) - db.session.commit() - - with app.app_context(): - result = retry_batch_pending_tasks(batch_no) - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - assert result["started"] == 1 - assert result["skipped"] == 0 - assert task.pending_human_reason == PH_RPA_EXHAUSTED - assert task.pending_human_reason == PH_RPA_EXHAUSTED - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1 - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1 - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_exhausted").count() == 1 - assert len(list(trigger.glob("inventory_export_*.json"))) == 0 - - def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client): headers = _tool_headers(app) diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index 3559f5d5..bf85defe 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -77,18 +77,18 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback() "primary_action": { "code": "mark_manual_uploaded", "label": "登记人工上传", - "target_surface": "upload_complete", + "target_surface": "freight_upload", }, "action_presentation": [{ "code": "download_excel", "label": "下载发货 Excel", - "target_surface": "upload_complete", + "target_surface": "freight_upload", "target_anchor": "excel_artifact", }], }, ) - assert state["primary"]["target_surface"] == "upload_complete" - assert state["secondary"][0]["target_surface"] == "upload_complete" + assert state["primary"]["target_surface"] == "freight_upload" + assert state["secondary"][0]["target_surface"] == "freight_upload" assert state["secondary"][0]["target_anchor"] == "excel_artifact" @@ -121,8 +121,8 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None: assert "stage_context" in detailed_state -def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None: - """没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。""" +def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: + """旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。""" with app.app_context(): task = ShippingNotice( task_no="SN-UI-STAGE-ACTIONS", @@ -131,15 +131,15 @@ def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(ap source_type="manual", ) state = build_task_ui_state(task) - assert state["stage"]["code"] == "order_review" - assert state["stage"]["index"] == 2 - assert state["stage"]["total"] == 4 + assert state["stage"]["code"] == "unclassified" + assert state["stage"]["index"] == 0 + assert state["stage"]["total"] == 5 assert state["actions"]["primary"] is None assert state["actions"]["secondary"] == [] -def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None: - """正式工作台的四个入口必须由后端下发,页面不能按阶段顺序自行生成。""" +def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None: + """正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。""" with app.app_context(): task = ShippingNotice( task_no="SN-UI-LIFECYCLE-ENTRIES", @@ -148,13 +148,8 @@ def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> Non source_type="manual", ) state = build_task_ui_state(task) - assert state["lifecycle_stage"] == "order_review" - assert state["lifecycle_entries"] == [ - {"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"}, - {"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"}, - {"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, - {"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, - ] + assert state["lifecycle_stage"] == "unclassified" + assert state["lifecycle_entries"] == [] def test_task_ui_state_ignores_superseded_process_execution(app) -> None: @@ -208,12 +203,12 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None: assert state['stage']['code'] == 'fulfillment_prep' assert state['current_step']['code'] == 'fulfillment_prep' assert [entry['state'] for entry in state['lifecycle_entries']] == [ - 'available', 'available', 'current', 'unavailable', + 'available', 'available', 'current', 'unavailable', 'unavailable', ] def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None: - """正式人工上传 Gate 必须裁决为通知完成,不受旧复核字段影响。""" + """正式人工上传 Gate 必须停留货代上传,不受旧复核字段影响。""" with app.app_context(): from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version @@ -235,16 +230,16 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No state = build_task_ui_state(task) - assert state['lifecycle_stage'] == 'upload_complete' + assert state['lifecycle_stage'] == 'freight_upload' assert state['lifecycle_authority'] == 'process_gate' - assert state['stage']['code'] == 'upload_complete' + assert state['stage']['code'] == 'freight_upload' assert [entry['state'] for entry in state['lifecycle_entries']] == [ - 'available', 'available', 'available', 'current', + 'available', 'available', 'available', 'current', 'unavailable', ] -def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None: - """库存匹配/上传结果只映射四个业务阶段。""" +def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> None: + """库存和上传历史字段不能再替代正式 Gate 生成生命周期。""" with app.app_context(): fulfillment = ShippingNotice( task_no="SN-UI-FULFILLMENT", @@ -257,11 +252,11 @@ def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages( source_type="manual", upload_status="uploaded", ) - assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep" + assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified" upload_state = build_task_ui_state(upload, include_stage_context=True) - assert upload_state["stage"]["code"] == "upload_complete" + assert upload_state["stage"]["code"] == "unclassified" # 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。 - assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual" + assert upload_state["stage_context"]["upload"]["outcome"] == "not_started" def test_entry_surface_parse_review_is_review_workbench(app) -> None: diff --git a/backend/tests/test_shipping_order_auto_freeze_execution.py b/backend/tests/test_shipping_order_auto_freeze_execution.py deleted file mode 100644 index 2eacd8ec..00000000 --- a/backend/tests/test_shipping_order_auto_freeze_execution.py +++ /dev/null @@ -1,55 +0,0 @@ -""" -tests/test_shipping_order_auto_freeze_execution.py - -用途:锁定自动冻结候选范围不得扩大到 Run 内其它已消费任务。 -依赖:order_auto_freeze_execution._freeze_created_tasks。 -逻辑:未传入本轮 eligible candidate_nos 时不得扫描全 Run consumed 集合。 -""" - -from __future__ import annotations - -from types import SimpleNamespace -from unittest.mock import MagicMock, patch - -from app.services.shipping_notice.order_auto_freeze_execution import _freeze_created_tasks - - -def test_freeze_created_tasks_requires_eligible_candidate_nos(): - """空 eligible 集合必须直接返回,禁止扩大冻结范围。""" - run = SimpleNamespace(id=1) - with patch( - 'app.services.shipping_notice.order_auto_freeze_execution.ShippingOrderCandidate' - ) as candidate_model: - frozen, blocked = _freeze_created_tasks(run=run, policy={'enabled': True}, candidate_nos=[]) - assert frozen == [] - assert blocked == [] - candidate_model.query.filter_by.assert_not_called() - - -def test_freeze_created_tasks_filters_accepted_selected_and_eligible_nos(): - """冻结查询必须约束 accepted + selected 且限定本轮 candidate_nos。""" - run = SimpleNamespace(id=42) - query = MagicMock() - query.filter_by.return_value = query - query.filter.return_value = query - query.order_by.return_value = query - query.all.return_value = [] - - with patch( - 'app.services.shipping_notice.order_auto_freeze_execution.ShippingOrderCandidate' - ) as candidate_model: - candidate_model.query = query - frozen, blocked = _freeze_created_tasks( - run=run, - policy={'enabled': True}, - candidate_nos=['CAND-A', 'CAND-B'], - ) - assert frozen == [] - assert blocked == [] - query.filter_by.assert_called_once_with( - order_extraction_run_id=42, - is_current_version=True, - candidate_status='accepted', - selected=True, - ) - assert query.filter.call_count == 2 diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index d08894cf..a124d7c6 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -122,6 +122,85 @@ def _coordinate_definition() -> dict: } +def test_reservation_region_requires_header_and_allows_optional_line_scope_schema(): + """无行号值必须有 Header 落点;启用 Line 后同一区域还可承载行级 Reservation。""" + schema = SimpleNamespace(definition_json={'fields': [{ + 'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header', + 'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'], + }, { + 'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'], + }, { + 'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'], + }, { + 'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'], + }]}) + definition = _coordinate_definition() + definition['reservation_id_region'] = { + 'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .3}, + 'page_scope': 'exact_page', 'page_no': 1, + } + + normalized = service._normalize_definition(definition, schema_version=schema) + + assert normalized['reservation_id_region']['page_no'] == 1 + + +def test_reference_page_frames_are_preserved_by_coordinate_definition_normalization(): + """模板规范化必须保留标注页物理尺寸,不能只保存浏览器百分比坐标。""" + schema = SimpleNamespace(definition_json={'fields': [ + { + 'field_id': 'line-field', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'], + }, + { + 'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'], + }, + ]}) + definition = _coordinate_definition() + definition['reference_page_frames'] = { + '1': {'width': 609, 'height': 791, 'origin': 'pdf_top_left', 'box': 'cropbox'}, + } + + normalized = service._normalize_definition(definition, schema_version=schema) + + assert normalized['reference_page_frames']['1']['width'] == 609.0 + assert normalized['reference_page_frames']['1']['height'] == 791.0 + assert normalized['coordinate_model']['type'] == 'legacy' + + +def test_reference_page_frames_read_annotation_coordinate_evidence(): + """参考页框必须来自冻结 Layout 的 PDF 坐标证据,而不是前端提交。""" + frames = service._reference_page_frames({ + 'coordinate_evidence': {'pages': {'1': {'width': 609, 'height': 791}}}, + }) + + assert frames == { + '1': {'width': 609.0, 'height': 791.0, 'origin': 'pdf_top_left', 'box': 'cropbox'}, + } + + +def test_reservation_region_rejects_schema_without_header_scope(): + """无行号 Reservation 需要稳定 Header 落点,只有 Line 字段时不得保存。""" + schema = SimpleNamespace(definition_json={'fields': [{ + 'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'], + }]}) + definition = _coordinate_definition() + definition['reservation_id_region'] = { + 'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .3}, + 'page_scope': 'exact_page', 'page_no': 1, + } + + with pytest.raises(Exception) as caught: + service._normalize_definition(definition, schema_version=schema) + + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID' + + def test_visual_sample_preview_reads_common_ocr_value_before_xfa_path_is_selected(app, monkeypatch): """XFA 草稿未选 datasets path 时,仍从共同 PDF 坐标证据显示 PO 样本值。""" glyphs = [ @@ -365,6 +444,45 @@ def test_preview_page_region_text_uses_unique_xfa_widget_when_coordinate_text_is assert result['status'] == 'needs_review' +def test_preview_page_region_text_does_not_use_partial_xfa_widget_value(app, monkeypatch): + """局部框与大 Widget 仅相交时,不能把整段 /V 当作框内视觉样本。""" + document = SimpleNamespace(id=112, asset_id=501, filename='hybrid.pdf') + layout = { + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': []}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + } + monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document) + monkeypatch.setattr(service, '_document_layout', lambda _document: layout) + monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout) + monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False) + monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [ + SimpleNamespace( + page_no=1, + normalized_bbox={'x0': .40, 'y0': .10, 'x1': .80, 'y1': .60}, + value='TEMP-S000218922 FRAME MPN:D4-A08AR12000001 Customer', + ), + ], raising=False) + monkeypatch.setattr(service, '_read_rendered_preview_crop_text', lambda _image: 'D4-A08AR12000001', raising=False) + + with app.app_context(): + result = service.read_preview_page_region_text( + 1, + data={ + 'document_id': 112, + 'region': {'x0': .50, 'y0': .30, 'x1': .70, 'y1': .40}, + 'rendered_image_base64': 'data:image/png;base64,iVBORw0KGgo=', + }, + page_no=1, + actor_id=1, + ) + + assert result['text'] == 'D4-A08AR12000001' + assert result['source'] == 'xfa_rendered_ocr' + + def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch): """任意视觉框命中多个带值 Widget 时不得将其中之一冒充样本值。""" document = SimpleNamespace(id=110, asset_id=501, filename='hybrid.pdf') @@ -392,6 +510,39 @@ def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch assert result['source'] == 'acroform_widget_ambiguous' +def test_preview_page_region_text_reads_xfa_canvas_crop_when_server_rendering_has_no_value(app, monkeypatch): + """XFA 可见值必须从管理员当前 PDF.js 画布裁剪图回读,不能以服务端 PDFium 空结果丢弃标注。""" + document = SimpleNamespace(id=111, asset_id=501, filename='hybrid.pdf') + layout = { + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': []}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + } + monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document) + monkeypatch.setattr(service, '_document_layout', lambda _document: layout) + monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout) + monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None) + monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: []) + monkeypatch.setattr(service, '_read_rendered_preview_crop_text', lambda _image: 'HC07', raising=False) + + with app.app_context(): + result = service.read_preview_page_region_text( + 1, + data={ + 'document_id': 111, + 'region': {'x0': .40, 'y0': .15, 'x1': .75, 'y1': .35}, + 'rendered_image_base64': 'data:image/png;base64,iVBORw0KGgo=', + }, + page_no=1, + actor_id=1, + ) + + assert result['text'] == 'HC07' + assert result['source'] == 'xfa_rendered_ocr' + + def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field(app, monkeypatch): """共同视觉预览忽略旧浏览器重复提交的已绑定未绑定布局,仍返回 PO 样本值。""" glyphs = [ @@ -626,10 +777,16 @@ def test_template_sample_status_accepts_materialized_document_with_failed_layout status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id) # 上传成功只取决于样本文档已物化;失败 Layout 留到预览复核阶段按需恢复或报错。 - assert status == { - 'intake_no': 'SNI-LAYOUT-STATUS', 'parse_status': 'parsed', 'document_count': 1, - 'document_ids': [document.id], 'error_code': None, - } + assert status['intake_no'] == 'SNI-LAYOUT-STATUS' + assert status['parse_status'] == 'parsed' + assert status['document_count'] == 1 + assert status['document_ids'] == [document.id] + assert status['error_code'] is None + # 文档物化成功与 Layout 失败分开呈现,前端不可把上传成功误当成可自动标注。 + assert status['layout_status'] == 'failed' + assert status['evidence_status'] == 'pending' + assert status['automark_ready'] is False + assert status['sample_readiness'] == [] def test_template_sample_status_accepts_materialized_document_without_modeling_table(app): @@ -663,10 +820,15 @@ def test_template_sample_status_accepts_materialized_document_without_modeling_t status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id) # Layout 预热结果不是上传门禁,不能把可读 PDF 误报为上传失败。 - assert status == { - 'intake_no': 'SNI-EMPTY-TABLE-STATUS', 'parse_status': 'parsed', 'document_count': 1, - 'document_ids': [document.id], 'error_code': None, - } + assert status['intake_no'] == 'SNI-EMPTY-TABLE-STATUS' + assert status['parse_status'] == 'parsed' + assert status['document_count'] == 1 + assert status['document_ids'] == [document.id] + assert status['error_code'] is None + assert status['layout_status'] == 'ready' + assert status['evidence_status'] == 'pending' + assert status['automark_ready'] is False + assert status['sample_readiness'] == [] def test_template_sample_status_keeps_file_materialization_failure_fail_closed(app): @@ -691,10 +853,91 @@ def test_template_sample_status_keeps_file_materialization_failure_fail_closed(a status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id) # 文件本身未能物化时必须保持失败,不能借上传/Layout 解耦绕过。 - assert status == { - 'intake_no': 'SNI-MATERIALIZATION-FAILED', 'parse_status': 'failed', 'document_count': 0, - 'document_ids': [], 'error_code': 'SHIPPING_NOTICE_INTAKE_PARSE_FAILED', - } + assert status['intake_no'] == 'SNI-MATERIALIZATION-FAILED' + assert status['parse_status'] == 'failed' + assert status['document_count'] == 0 + assert status['document_ids'] == [] + assert status['error_code'] == 'SHIPPING_NOTICE_INTAKE_PARSE_FAILED' + assert status['layout_status'] == 'pending' + assert status['evidence_status'] == 'pending' + assert status['automark_ready'] is False + assert status['sample_readiness'] == [] + + +def test_refresh_profile_sample_readiness_freezes_ready_annotation_evidence(app): + """ready Layout 与唯一主表齐备时,统一服务必须回填样本的完整冻结身份。""" + with app.app_context(): + schema = _schema_version() + draft = service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation') + profile = db.session.get(ShippingOrderDocumentProfile, draft['id']) + + state = service.refresh_profile_sample_readiness(profile=profile, sample=sample) + db.session.commit() + frozen = db.session.get(ShippingOrderDocumentProfileSample, sample.id) + + # 同一服务既供轮询使用也供入队使用,冻结后的 Job 必须取得当前 Layout 的完整身份。 + assert state['automark_ready'] is True + assert state['evidence_status'] == 'frozen' + assert frozen.layout_version_id is not None + assert frozen.layout_payload_checksum is not None + assert frozen.source_content_hash == 's' * 64 + assert frozen.evidence_frozen_at is not None + + +def test_profile_sample_readiness_rejects_current_layout_content_identity_mismatch(app): + """当前 Layout 的来源内容身份异常时不得冻结或入队,避免旧坐标混入新样本。""" + with app.app_context(): + schema = _schema_version() + draft = service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation') + profile = db.session.get(ShippingOrderDocumentProfile, draft['id']) + document = db.session.get(ShippingOrderDocument, sample.document_id) + version = db.session.get(ShippingDocumentLayoutVersion, document.current_layout_version_id) + version.source_content_hash = 'x' * 64 + db.session.flush() + + state = service.refresh_profile_sample_readiness(profile=profile, sample=sample) + with pytest.raises(Exception) as caught: + service.require_profile_sample_automark_ready(profile=profile, sample=sample) + + # 关键断言:Layout 可见并不足够,Document 与 Layout 的不可变内容身份不一致必须失败关闭。 + assert state['automark_ready'] is False + assert state['evidence_status'] == 'stale' + assert state['reason_code'] == 'layout_content_hash_mismatch' + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE' + + +def test_profile_sample_readiness_requires_manual_main_table_selection_for_multiple_tables(app): + """未绑定主表而 Layout 存在多个表时不得猜测第一张表,必须返回人工选择门禁。""" + with app.app_context(): + from app.services.shipping_notice.document_layout.lifecycle import canonical_layout_payload + + schema = _schema_version() + draft = service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation') + profile = db.session.get(ShippingOrderDocumentProfile, draft['id']) + document = db.session.get(ShippingOrderDocument, sample.document_id) + version = db.session.get(ShippingDocumentLayoutVersion, document.current_layout_version_id) + payload = dict(version.payload_json) + tables = [dict(item) for item in payload['tables']] + tables.append({**tables[0], 'table_id': 'second-table'}) + payload['tables'] = tables + checksum, _ = canonical_layout_payload(payload) + version.payload_json = payload + version.payload_checksum = checksum + sample.table_id = None + db.session.flush() + + state = service.refresh_profile_sample_readiness(profile=profile, sample=sample) + with pytest.raises(Exception) as caught: + service.require_profile_sample_automark_ready(profile=profile, sample=sample) + + # 关键断言:多表选择不是自动标注的可推断信息,禁止以位置或顺序猜测。 + assert state['automark_ready'] is False + assert state['main_table_status'] == 'ambiguous' + assert state['reason_code'] == 'main_table_ambiguous' + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS' def test_draft_unbound_order_field_layout_does_not_require_schema_scope(app): @@ -860,6 +1103,36 @@ def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app): ] +def test_order_field_layout_rejects_address_bound_to_number_anchor(app): + """关键断言:地址字段不能保存为订单编号的 Number 标签,避免错误锚点进入运行时。""" + with app.app_context(): + schema = _schema_version() + schema.definition_json['fields'].append({ + 'field_id': 'ship-to-address', 'field_code': 'ship_to_address', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }) + definition = _coordinate_definition() + definition['order_field_layouts'] = [{ + 'layout_id': 'ship_to_address_layout', 'field_id': '', 'field_code': 'ship_to_address', + 'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1, + 'anchor': {'anchor_id': 'order_field_1_1_anchor', 'text': 'Number'}, + 'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, + 'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False, + 'minimum_evidence_level': 'coordinate', + }] + + with pytest.raises(Exception) as caught: + service.save_draft({ + 'profile_code': 'SHIP_TO_NUMBER', 'display_name': 'Ship to number mismatch', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID' + assert getattr(caught.value, 'details', {}).get('reason') == 'order_field_anchor_semantic_mismatch' + assert getattr(caught.value, 'details', {}).get('field_code') == 'ship_to_address' + + def test_order_field_layout_rejects_line_field_and_unbounded_value_only_mode(app): """订单字段不得借用明细字段;无锚点坐标回退必须限制在单页。""" with app.app_context(): @@ -2027,6 +2300,86 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke assert preview['source_row_indices'] == [[], [0]] +def test_profile_region_preview_does_not_promote_unanchored_header_to_data(app, monkeypatch): + """页级证据没有有效起行锚点时,预览必须保持无明细并进入 Review 语义。""" + with app.app_context(): + schema = _schema_version() + profile = SimpleNamespace(profile_code='STRICT_PREVIEW', version=1, schema_version=schema) + document = SimpleNamespace(id=308) + definition = _coordinate_definition() + definition['table_regions'][0]['line_layouts'][0]['field_regions'] = [{ + 'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }] + layout = { + 'tables': [{'table_id': 'header-only', 'page_no': 1}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 100}}, + 'tables': {'header-only': [ + {'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}}, + ]}, + 'page_glyphs': {'1': [ + {'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}}, + ]}, + }, + } + monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document) + monkeypatch.setattr(service, '_document_layout', lambda _document: layout) + monkeypatch.setattr( + db.session, 'get', + lambda model, _identity: profile if model is ShippingOrderDocumentProfile else None, + ) + preview = service.preview_profile_region( + 22, data={'document_id': 308, 'table_id': 'header-only', 'definition': definition}, actor_id=1, + ) + + assert preview['rows'] == [['customer_po_line_no']] + assert preview['row_roles'] == ['header'] + assert preview['status'] == 'needs_review' + + +def test_profile_region_preview_excludes_configured_header_regions_from_line_rows(app, monkeypatch): + """已配置的表头区域不得作为坐标明细行;真实起行值仍必须保留。""" + with app.app_context(): + schema = _schema_version() + profile = SimpleNamespace(profile_code='HEADER_BOUNDARY', version=1, schema_version=schema) + document = SimpleNamespace(id=309) + definition = _coordinate_definition() + table = definition['table_regions'][0] + table['header_layouts'] = [{ + 'layout_id': 'header_1', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .2}, + 'field_regions': [], + }] + table['line_layouts'][0]['field_regions'] = [{ + 'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': .21, 'x1': .3, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }] + table['line_layouts'][0]['region'] = {'x0': 0, 'y0': .2, 'x1': 1, 'y1': 1} + layout = { + 'tables': [{'table_id': 'header-and-data', 'page_no': 1}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 100}}, + 'tables': {'header-and-data': [ + {'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}}, + {'text': 'Vendor', 'source_index': 1, 'bbox': {'x0': 30, 'y0': 5, 'x1': 45, 'y1': 10}}, + {'text': '10', 'source_index': 2, 'bbox': {'x0': 5, 'y0': 30, 'x1': 15, 'y1': 40}}, + ]}, + }, + } + monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document) + monkeypatch.setattr(service, '_document_layout', lambda _document: layout) + monkeypatch.setattr(db.session, 'get', lambda model, _identity: profile if model is ShippingOrderDocumentProfile else None) + preview = service.preview_profile_region( + 23, data={'document_id': 309, 'table_id': 'header-and-data', 'definition': definition}, actor_id=1, + ) + + assert preview['rows'] == [['customer_po_line_no'], ['10']] + assert preview['source_row_indices'] == [[], [0]] + + def test_profile_region_preview_uses_schema_field_order(app, monkeypatch): """局部候选字段必须按绑定 Schema 顺序返回,不受字段标注先后影响。""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index a732e56b..5d93848d 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -14,6 +14,7 @@ from decimal import Decimal from unittest.mock import patch import pytest +from sqlalchemy import event from sqlalchemy.orm.attributes import flag_modified from app import db @@ -64,6 +65,7 @@ from app.jobs.queue import fail_job from app.services.shipping_notice.order_extraction import ( submit_order_extraction_run_result, submit_order_extraction_unit_result, + reconcile_review_case_after_unit, ) from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit from app.services.shipping_notice.order_extraction_plan import ( @@ -934,9 +936,13 @@ def test_run_v3_freezes_layout_schema_candidate_and_policy_versions(app): ) frozen_document = run.input_snapshot_json['intakes'][0]['documents'][0] candidates = frozen_document['layout_schema_candidates'] + parse_plan = frozen_document['generic_parse_plan'] assert run.input_snapshot_json['snapshot_version'] == 3 assert candidates[0]['mapping_status'] == 'candidate' assert candidates[0]['rows'][0]['fields'][0]['cell_id'] + assert parse_plan['status'] == 'qualified' + assert parse_plan['schema_checksum'] == run.input_snapshot_json['schema']['checksum'] + assert parse_plan['candidate_checksum'] assert 'layout_table_not_accepted' in candidates[0]['issues'] # 关键断言:策略版本写入快照,且不再暴露 Dify Workflow 清单。 assert run.input_snapshot_json['policy_versions']['route_strategy_version'] == ROUTE_STRATEGY_VERSION @@ -1105,7 +1111,6 @@ def test_second_pdf_unit_can_persist_after_first_unit_consumes_shared_intake(app db.session.refresh(intake) assert intake.parse_status == 'consumed' assert intake.consumed_task_id is None - assert intake.consumed_batch_id is None result = submit_order_extraction_unit_result(run=run, unit=second_unit, orders=[]) @@ -1904,6 +1909,75 @@ def test_run_api_create_get_list_and_user_isolation(app, client): assert hidden.get_json()['error']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND' +def test_run_list_returns_lightweight_summaries_without_full_workspace_projection(app, client, monkeypatch): + """会话恢复列表不得为每个 Run 构建文档、Case、Gate 等完整工作台投影。""" + with app.app_context(): + owner, agent, session, intake, _document = _seed_run_input(suffix='LIGHT-LIST') + run, _ = create_order_extraction_run( + user=owner, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + token = issue_local_access_token(owner) + run_no = run.run_no + conversation_id = session.session_id + + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection.serialize_workspace_run', + lambda _run: (_ for _ in ()).throw(AssertionError('list must not build workspace projection')), + ) + response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs?conversation_id={conversation_id}&limit=20', + headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 200 + item = next(row for row in response.get_json()['data']['items'] if row['run_no'] == run_no) + assert item['status'] == 'queued' + assert item['summary']['total_documents'] == 0 + for forbidden in ('documents', 'handling_items', 'available_actions', 'result', 'selection_plan'): + assert forbidden not in item + + +def test_run_list_does_not_select_large_input_snapshots(app, client): + """会话恢复列表只读摘要列,不能因 upload_batch_id 再取冻结输入快照。""" + with app.app_context(): + owner, agent, session, intake, _document = _seed_run_input(suffix='LIST-SCALAR') + run, _ = create_order_extraction_run( + user=owner, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + snapshot = dict(run.input_snapshot_json) + snapshot['large_regression_payload'] = 'x' * 1_000_000 + run.input_snapshot_json = snapshot + db.session.commit() + token = issue_local_access_token(owner) + conversation_id = session.session_id + + statements: list[str] = [] + + def capture_statement(_conn, _cursor, statement, _parameters, _context, _executemany): + if 'shipping_order_processing_runs' in statement: + statements.append(statement.lower()) + + with app.app_context(): + event.listen(db.engine, 'before_cursor_execute', capture_statement) + try: + response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs?conversation_id={conversation_id}&limit=20', + headers={'Authorization': f'Bearer {token}'}, + ) + finally: + event.remove(db.engine, 'before_cursor_execute', capture_statement) + + assert response.status_code == 200 + assert statements + assert all('input_snapshot_json' not in statement for statement in statements) + + def test_run_api_requires_upload_batch_id(app, client): """发送端缺少服务端上传批次时必须拒绝,不能回退为全会话 Intake 选择。""" with app.app_context(): @@ -2170,6 +2244,9 @@ def test_run_documents_and_summary_keep_partial_success_isolated_per_pdf(app, cl headers={'Authorization': f'Bearer {owner_token}'}, ) assert run_response.status_code == 200 + # 关键断言:重型 Run 投影必须返回可与浏览器 HAR 对齐的分段耗时,便于定位慢查询。 + assert 'run_lookup' in run_response.headers.get('Server-Timing', '') + assert 'workspace_projection' in run_response.headers.get('Server-Timing', '') run_payload = run_response.get_json()['data'] assert run_payload['summary'] == { 'total_documents': 3, @@ -2343,6 +2420,89 @@ def test_run_summary_omits_legacy_progress_projection(app): assert 'progress' not in payload +def test_run_summary_exposes_user_lifecycle_progress_from_current_activity(app): + """Run 摘要必须提供五阶段用户态进度与当前步骤,供复核台首屏直接展示。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='LIFECYCLE-PROGRESS') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + run.status = 'processing' + run.phase = 'deterministic_parsing' + run.progress_version = 4 + run.last_activity_at = datetime.utcnow() + db.session.commit() + + payload = serialize_order_extraction_run(run) + progress = payload['lifecycle_progress'] + + assert progress['lifecycle_stage'] == 'intake_parse' + assert progress['lifecycle_status'] == 'running' + assert progress['current_step_code'] == 'document_queued' + assert progress['current_step_i18n_key'] == 'chat.shippingProcessing.progress.step.document_queued' + assert isinstance(progress['completed_step_codes'], list) + assert progress['last_activity_at'] + assert progress['health_status'] == 'normal' + assert 'input_snapshot' not in str(progress) + assert 'provider' not in str(progress).lower() + + +def test_run_summary_lifecycle_progress_maps_completed_events_and_current_step(app): + """事件事实映射为稳定用户步骤,并保留已完成步骤顺序。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='LIFECYCLE-EVENTS') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(run, target_status='processing') + ensure_order_extraction_plan(run) + unit = run.extraction_plan.units[0] + unit.status = 'extracting' + unit.started_at = datetime.utcnow() + unit.last_activity_at = datetime.utcnow() + latest_sequence = ( + db.session.query(ShippingOrderExtractionProgressEvent.sequence_no) + .filter_by(run_id=run.id) + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc()) + .first() + ) + sequence_base = int(latest_sequence[0]) if latest_sequence else 0 + for sequence, code in enumerate(('layout_parsing_completed', 'profile_matching'), start=1): + db.session.add(ShippingOrderExtractionProgressEvent( + run_id=run.id, + unit_id=unit.id, + document_id=document.id, + sequence_no=sequence_base + sequence, + event_code=code, + # 真实写入契约把该完成事实保留为 running,投影仍必须识别为已完成。 + status='running', + visibility='workspace', + summary_json={}, + idempotency_key=f'lifecycle-events-{sequence}', + )) + db.session.commit() + + progress = serialize_order_extraction_run(run)['lifecycle_progress'] + assert progress['current_step_code'] == 'profile_matching' + assert progress['completed_step_codes'] == ['layout_parsing_completed'] + + +def test_run_summary_lifecycle_progress_marks_failed_without_worker_details(app): + """失败 Run 只显示稳定失败态和脱敏字段,不泄漏内部错误正文。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='LIFECYCLE-FAILED') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(run, target_status='processing') + transition_order_extraction_run(run, target_status='failed', error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED', error_message='secret worker trace') + payload = serialize_order_extraction_run(run) + progress = payload['lifecycle_progress'] + assert progress['lifecycle_status'] == 'failed' + assert progress['health_status'] == 'failed' + assert 'secret worker trace' not in str(progress) + + def test_user_run_summary_never_exposes_worker_error_text(app): """Workspace status cards expose a stable error code, never Provider or Worker details.""" with app.app_context(): @@ -2442,46 +2602,6 @@ def test_run_seen_api_keeps_cross_user_isolation(app, client): assert hidden.status_code == 404 -def test_chat_sessions_aggregate_only_new_unseen_order_extraction_attention(app): - """侧栏只聚合同用户同Agent的新提醒,并把失败优先级提升到 error。""" - from app.api.chat import _order_extraction_attention_by_conversation - - with app.app_context(): - owner, agent, session, intake, _document = _seed_run_input(suffix='SESSION-ATTENTION') - ignored_agent = Agent( - name='Other owner', agent_code='generic', runtime_provider='dify', dify_app_id='other-owner', - dify_api_key='key', is_active=True, - ) - db.session.add(ignored_agent) - db.session.flush() - run, _ = create_order_extraction_run( - user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - transition_order_extraction_run(run, target_status='processing') - transition_order_extraction_run(run, target_status='failed', error_message='provider unavailable') - historical = ShippingOrderProcessingRun( - run_no='SNER-HISTORICAL-SESSION', user_id=owner.id, owner_agent_id=agent.id, - conversation_id=session.session_id, schema_version_id=run.schema_version_id, - input_snapshot_hash='e' * 64, input_snapshot_json={}, idempotency_key='f' * 64, - status='completed', phase='completed', finished_at=datetime.utcnow(), - ) - other_owner_run = ShippingOrderProcessingRun( - run_no='SNER-OTHER-OWNER', user_id=owner.id, owner_agent_id=ignored_agent.id, - conversation_id=session.session_id, schema_version_id=run.schema_version_id, - input_snapshot_hash='g' * 64, input_snapshot_json={}, idempotency_key='h' * 64, - status='completed', phase='completed', finished_at=datetime.utcnow(), attention_generated_at=datetime.utcnow(), - ) - db.session.add_all([historical, other_owner_run]) - db.session.commit() - aggregate = _order_extraction_attention_by_conversation( - user_id=owner.id, - agent_id=agent.id, - conversation_ids={session.session_id}, - ) - - assert aggregate == {session.session_id: (1, 'error')} - - def test_final_order_extraction_job_failure_marks_queued_run_failed(app): """Job 重试耗尽时必须收口 Run,避免聊天页永久显示处理中。""" with app.app_context(): @@ -2677,114 +2797,6 @@ def test_terminal_transition_updates_persisted_chat_state(app): ] -def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, client): - """终态后晚到的旧卡必须在历史 GET 时按 Run 事实纠正,不能永久显示运行中。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-HISTORY') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') - transition_order_extraction_run( - run, - target_status='failed', - error_code='TEST.FAILED', - error_message='failed before card persisted', - ) - db.session.add(ChatLog( - user_id=user.id, - agent_id=agent.id, - session_id=session.session_id, - conversation_id=session.session_id, - query='', - answer='', - message_type='text', - payload={ - 'formId': f'shipping-order-extraction-run:{run.run_no}', - 'order_extraction_run_no': run.run_no, - 'shipping_order_extraction_state': {'status': 'extracting', 'terminal': False}, - }, - )) - db.session.commit() - token = issue_local_access_token(user) - session_id = session.session_id - agent_id = agent.id - - response = client.get( - f'/api/chat/messages?conversation_id={session_id}&agent_id={agent_id}', - headers={'Authorization': f'Bearer {token}'}, - ) - - assert response.status_code == 200 - state = response.get_json()[-1]['payload']['shipping_order_extraction_state'] - assert state['status'] == 'failed' - assert state['terminal'] is True - assert state['availableActions'] == [ - 'view_details', 'refresh_status', 'retry_failed_attachments', - ] - assert 'failed before card persisted' not in str(response.get_json()) - - -def test_chat_history_does_not_project_user_run_anchor_as_duplicate_state_card(app, client): - """同一 Run 的上传记录与状态记录共存时,历史回放只能出现一张助手状态卡。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-DEDUPLICATE') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') - transition_order_extraction_run(run, target_status='failed', error_message='failed once') - db.session.add_all([ - ChatLog( - user_id=user.id, - agent_id=agent.id, - session_id=session.session_id, - conversation_id=session.session_id, - query='上传附件', - answer='', - message_type='text', - payload={ - 'formId': f'shipping-order-extraction-user:{run.run_no}', - 'order_extraction_run_no': run.run_no, - }, - ), - ChatLog( - user_id=user.id, - agent_id=agent.id, - session_id=session.session_id, - conversation_id=session.session_id, - query='', - answer='', - message_type='text', - payload={ - 'formId': f'shipping-order-extraction-run:{run.run_no}', - 'order_extraction_run_no': run.run_no, - }, - ), - ]) - db.session.commit() - token = issue_local_access_token(user) - run_no = run.run_no - session_id = session.session_id - agent_id = agent.id - - response = client.get( - f'/api/chat/messages?conversation_id={session_id}&agent_id={agent_id}', - headers={'Authorization': f'Bearer {token}'}, - ) - - assert response.status_code == 200 - messages = response.get_json() - state_cards = [ - item for item in messages - if item['role'] == 'assistant' - and item.get('payload', {}).get('order_extraction_run_no') == run_no - ] - assert len(state_cards) == 1 - assert state_cards[0]['payload']['shipping_order_extraction_state']['status'] == 'failed' - assert [item['role'] for item in messages] == ['user', 'assistant'] - - def test_failed_run_retry_api_returns_queued_run(app, client): """用户点击重新识别后 API 返回 202,并原位恢复同一 Run。""" with app.app_context(): @@ -2860,7 +2872,6 @@ def test_terminal_run_reparse_reuses_orphaned_consumed_intake(app, client): transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) intake.parse_status = 'consumed' intake.consumed_at = datetime.utcnow() - intake.consumed_batch_id = None intake.consumed_task_id = None db.session.commit() token = issue_local_access_token(user) @@ -2886,7 +2897,6 @@ def test_reparse_submission_accepts_orphaned_consumed_intake(app): transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) intake.parse_status = 'consumed' intake.consumed_at = datetime.utcnow() - intake.consumed_batch_id = None intake.consumed_task_id = None db.session.commit() replacement, _ = reparse_order_extraction_run( @@ -2909,7 +2919,6 @@ def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app): transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) intake.parse_status = 'consumed' intake.consumed_at = datetime.utcnow() - intake.consumed_batch_id = None intake.consumed_task_id = None db.session.commit() replacement, _ = reparse_order_extraction_run( @@ -2925,6 +2934,23 @@ def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app): assert ShippingOrderCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0 +def test_unit_replay_reconciles_review_case_after_ensure(monkeypatch): + """Unit 幂等回放创建/恢复 Case 后必须进入统一自动校验协调器。""" + calls = [] + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_service.ensure_review_case_for_unit', + lambda **kwargs: calls.append(('ensure', kwargs)) or object(), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_stp_auto_create_service.maybe_stp_auto_create_for_run', + lambda **kwargs: calls.append(('reconcile', kwargs)) or [{'validate_status': 'validated'}], + ) + + reconcile_review_case_after_unit(run='run', unit='unit') + + assert [item[0] for item in calls] == ['ensure', 'reconcile'] + + def test_unit_submission_survives_deleted_chat_session(app): """后台 Run 不得因 UI 会话历史已清理而回滚 Candidate/Review Case 持久化。""" with app.app_context(): @@ -3415,26 +3441,6 @@ def test_failed_reparse_restores_source_candidate_version(app): assert source.superseded_by_run_id is None -def test_only_current_version_candidate_can_be_consumed(app): - """旧版本 Candidate 即使被直接提交,也必须被建单入口拒绝。""" - from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates - - with app.app_context(): - user, _agent, _session, intake, document = _seed_run_input(suffix='SUPERSEDED') - candidate = ShippingOrderCandidate( - candidate_no='SNC-SUPERSEDED', intake_id=intake.id, primary_document_id=document.id, - candidate_key='old-version', selected=True, is_current_version=False, validation_status='ready', - ) - db.session.add(candidate) - db.session.commit() - with pytest.raises(ValidationError) as caught: - create_shipping_batch_from_candidates( - user_id=user.id, intake_nos=[intake.intake_no], candidate_nos=[candidate.candidate_no], - create_idempotency_key='test-current-version-gate', conversation_id=None, - ) - assert caught.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_FOUND' - - def test_order_extraction_health_reports_backlog_latency_and_safe_errors(app): """管理员健康汇总应识别积压/失败并只返回安全运行元数据。""" from app.services.shipping_notice.order_extraction_run_service import get_order_extraction_run_health diff --git a/backend/tests/test_shipping_order_field_extraction.py b/backend/tests/test_shipping_order_field_extraction.py index 83d10717..706cd505 100644 --- a/backend/tests/test_shipping_order_field_extraction.py +++ b/backend/tests/test_shipping_order_field_extraction.py @@ -37,7 +37,9 @@ def _glyphs(*lines: tuple[str, float, float]) -> list[dict]: return result -def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfile: +def _profile( + *, layout: dict, page_scope: str = 'first_page', reference_page_frames: dict[str, dict] | None = None, +) -> OrderCoordinateProfile: """构造包含一个独立 header 字段的最小合法 v2 Profile。""" return OrderCoordinateProfile.model_validate({ 'profile_code': 'ORDER-FIELD-TEST', 'version': 1, @@ -48,6 +50,7 @@ def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinate 'scope': 'header', 'page_scope': page_scope, **layout, }], + 'reference_page_frames': reference_page_frames or {}, }) @@ -60,15 +63,38 @@ def _schema(**overrides: object) -> dict[str, dict]: }} -def _evidence(*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate') -> dict: +def _evidence( + *, pages: dict[str, list[dict]], source: str = 'pdf_coordinate', page_size: tuple[float, float] = (200, 200), +) -> dict: """构造冻结页级证据;故意不提供 tables,证明订单字段不依赖明细区。""" return { - 'pages': {page: {'width': 200, 'height': 200} for page in pages}, + 'pages': {page: {'width': page_size[0], 'height': page_size[1]} for page in pages}, 'page_glyphs': pages, 'sources': {'pages': {page: source for page in pages}}, } +def test_fixed_order_field_uses_annotation_page_frame_when_runtime_page_is_taller(): + """同内容由分页页变为长页时,固定字段仍须读取标注页的 PDF 点坐标。""" + profile = _profile( + layout={'fallback_value_region': {'x0': .10, 'y0': .20, 'x1': .90, 'y1': .30}}, + reference_page_frames={'1': {'width': 200, 'height': 100}}, + ) + + result = extract_order_fields( + profile=profile, + schema_fields=_schema(), + coordinate_evidence=_evidence( + pages={'1': _glyphs(('45001', 40, 21))}, page_size=(200, 200), + ), + allow_fixed_region_confirmation=True, + )[0] + + # 关键断言:不能把训练页 y=20..30 重投影到长页 y=40..60。 + assert result.status == 'confirmed' + assert result.value == '45001' + + def test_visual_row_prefers_explicit_pdf_space_boundary_over_geometry_threshold(): """真实词间距低于旧阈值时,PDF 文本流的明确空格仍应恢复,不能输出粘连地址。""" row = [ @@ -140,6 +166,55 @@ def test_anchor_relative_value_is_confirmed_with_native_page_coordinates(): assert result.source == 'pdf_coordinate' +def test_anchor_frame_transform_moves_order_number_anchor_and_value_together(): + """共同 matcher 的纵向平移必须同时投影订单号标签和值框。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'po', 'text': 'PO NO', + 'region': {'x0': .05, 'y0': .1, 'x1': .25, 'y1': .14}, + 'position_locked': True, + }, + 'absolute_value_region': {'x0': .2, 'y0': .1, 'x1': .9, 'y1': .14}, + 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields( + profile=profile, + schema_fields=_schema(), + coordinate_evidence=_evidence(pages={'1': _glyphs(('PO NO 45001', 20, 40))}), + coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .1}, + )[0] + assert result.status == 'confirmed' + assert result.value == '45001' + + +def test_coordinate_transform_applies_affine_matrix_to_order_header_regions(): + """订单头必须与订单行共享 matcher 已验证的仿射矩阵,而非只读取旧平移键。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'po', 'text': 'PO NO', + 'region': {'x0': .10, 'y0': .10, 'x1': .30, 'y1': .14}, + 'position_locked': True, + }, + 'absolute_value_region': {'x0': .20, 'y0': .10, 'x1': .80, 'y1': .14}, + 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields( + profile=profile, + schema_fields=_schema(), + coordinate_evidence=_evidence(pages={'1': _glyphs(('PO NO 45001', 30, 40))}), + coordinate_transform={ + 'status': 'applied', + 'matrix': [1.0, 0.0, .05, 0.0, 1.0, .10], + 'anchor_ids': ['po'], + 'reason_codes': [], + }, + )[0] + + # 关键断言:仅 matrix 存在时也必须与共同 matcher 的坐标系一致。 + assert result.status == 'confirmed' + assert result.value == '45001' + + def test_right_of_anchor_keeps_saved_value_width_when_actual_anchor_text_is_narrower(): """值框只命中 USD 首字符时,应补齐同一连续词而非误报未读取到值。""" profile = _profile(layout={ @@ -301,6 +376,25 @@ def test_anchor_reference_region_and_exact_mode_reject_unrelated_label_occurrenc assert result.value == '45001' +def test_unique_anchor_outside_saved_reference_region_is_still_readable(): + """同版式样本唯一命中标签时,旧参考框不得阻断盲测/正式读取。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'ship_to', 'text': 'Ship to', 'match_mode': 'exact', + 'region': {'x0': .55, 'y0': .10, 'x1': .63, 'y1': .12}, + 'position_locked': True, + }, + 'value_region': {'x0': .8, 'y0': 0, 'x1': 4.0, 'y1': 1.0}, + 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('Ship to:ACME', 20, 20))}, + ))[0] + + assert result.status == 'confirmed' + assert result.value == 'ACME' + + def test_legacy_placeholder_anchor_uses_its_reference_region_as_review_only_evidence(): """历史手工默认标签不能丢值,但只能按原标注框降级为人工复核。""" profile = _profile(layout={ @@ -390,6 +484,24 @@ def test_fallback_and_ocr_never_become_confirmed(): assert ocr_result.status == 'needs_review' +def test_profile_confirmed_fixed_region_is_confirmed_with_native_coordinates(): + """唯一确认模板中的无标签固定区域可作为原生 PDF 正式字段证据。""" + profile = _profile(layout={ + 'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2}, + }) + + result = extract_order_fields( + profile=profile, + schema_fields=_schema(), + coordinate_evidence=_evidence(pages={'1': _glyphs(('45001', 30, 20))}), + allow_fixed_region_confirmation=True, + )[0] + + # 关键断言:此放宽仅由已确认的模板调用方显式开启,原生坐标和字段校验仍是必要条件。 + assert result.status == 'confirmed' + assert result.issues == [] + + def test_multiline_stops_at_next_label_and_type_failure_requires_review(): """地址值在下一个标签前截断;日期格式无效不能绕过 Schema validator。""" address = _profile(layout={ @@ -429,6 +541,21 @@ def test_common_purchase_order_slash_date_is_normalized(): assert result.value.isoformat() == '2026-06-20' +def test_common_purchase_order_short_slash_date_is_normalized(): + """采购单常见两位年份日期应按冻结 date Schema 归一化。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'date', 'text': 'DATE'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema( + field_code='order_date', value_type='date', validator_keys=['iso_date'], + ), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/16/26', 20, 20))}))[0] + + # 关键断言:视觉样本的两位年份转换为统一 ISO 日期,而不是未读取。 + assert result.status == 'confirmed' + assert result.value.isoformat() == '2026-06-16' + + def test_date_does_not_extend_beyond_value_frame(): """值框边界是标注预览的唯一证据,日期也不得跨框补全。""" profile = _profile(layout={ @@ -498,6 +625,27 @@ def test_absolute_value_region_uses_canvas_boundary_instead_of_anchor_projection assert result.value == '66 Hou-Kang Street' +def test_absolute_single_line_value_region_moves_with_its_unique_anchor(): + """单头整体上移时,绝对客户值框必须跟随已唯一命中的自身标签。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'bill_to', 'text': 'BILL TO', + 'region': {'x0': .10, 'y0': .30, 'x1': .30, 'y1': .35}, + }, + 'absolute_value_region': {'x0': .10, 'y0': .38, 'x1': .90, 'y1': .44}, + 'value_mode': 'single_line', + }) + result = extract_order_fields( + profile=profile, schema_fields=_schema(field_code='bill_to_customer'), + coordinate_evidence=_evidence(pages={'1': _glyphs( + ('BILL TO', 20, 40), ('Hyve Solutions Corporation', 20, 56), ('44201 Nobel Drive', 20, 72), + )}), + )[0] + + assert result.status == 'confirmed' + assert result.value == 'Hyve Solutions Corporation' + + def test_tight_value_region_keeps_edge_glyphs_without_reading_adjacent_text(): """紧贴 USD 字符盒的右侧值框应容忍渲染误差,但不能吞入相邻字段。""" profile = _profile(layout={ diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index 21d654ac..2dfd134a 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -1,6 +1,10 @@ """验证订单坐标模板匹配:版面签名、七维评分与解析校验门禁。""" -from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles +from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile +from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _resolve_coordinate_transform, + match_frozen_coordinate_profiles, +) from app.services.shipping_notice.document_layout.order_profile_signature import ( MATCHER_POLICY_ID, build_layout_signature, @@ -86,6 +90,210 @@ def _with_signature(profile: dict, layout: dict) -> dict: return enriched +def _anchor_frame_profile(code: str = 'PO_ANCHOR_FRAME') -> dict: + """构造声明锚点坐标框架的最小 Profile,供平移门禁回归使用。""" + profile = _profile(code) + profile['definition']['coordinate_model'] = { + 'type': 'anchor_frame', + 'anchors': [{ + 'anchor_id': 'title', 'text': 'PURCHASE ORDER', 'match_mode': 'exact', + 'minimum_evidence_level': 'coordinate', + 'region': {'x0': .185, 'y0': .05, 'x1': .26, 'y1': .0857142857}, + }], + 'max_translate_x': .02, + 'max_translate_y': .05, + } + return profile + + +def _layout_with_frame_anchor(*, anchor_y: float = .05, table_y: float = .25) -> dict: + """构造标题与主表同步平移的坐标 Layout,模拟正文高度改变而非结构变更。""" + layout = _layout(bbox={'x0': .05, 'y0': table_y, 'x1': .95, 'y1': .95}) + text = 'PURCHASE ORDER' + anchor_glyphs = [ + { + 'text': char, + 'bbox': {'x0': 10 + index * 5, 'y0': anchor_y * 280, 'x1': 14 + index * 5, 'y1': anchor_y * 280 + 10}, + 'boundary_before': 'space' if index and text[index - 1] == ' ' else 'none', + } + for index, char in enumerate(text) + if char != ' ' + ] + header = layout['coordinate_evidence']['tables']['table-1'] + for glyph in header: + glyph['bbox']['y0'] += (table_y - .25) * 280 + glyph['bbox']['y1'] += (table_y - .25) * 280 + plant_text = 'PLANT NAME: FACTORY A' + plant_glyphs = [ + {'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}} + for index, char in enumerate(plant_text) + ] + layout['coordinate_evidence']['page_glyphs']['1'] = [ + *plant_glyphs, + *anchor_glyphs, + *header, + ] + return layout + + +def test_anchor_frame_matches_bounded_vertical_translation_without_changing_legacy_profiles(): + """同一结构整体下移时仅启用锚点框架的 Profile 可命中,legacy 仍按原规则失败关闭。""" + baseline = _layout_with_frame_anchor() + shifted = _layout_with_frame_anchor(anchor_y=.095, table_y=.295) + framed = _with_signature(_anchor_frame_profile(), baseline) + legacy = _with_signature(_profile('PO_LEGACY'), baseline) + + framed_result = match_frozen_coordinate_profiles(profiles=[framed], layout=shifted) + legacy_result = match_frozen_coordinate_profiles(profiles=[legacy], layout=shifted) + + # 关键断言:变换来自唯一静态锚点,并且 legacy Profile 未因新能力改变行为。 + assert framed_result.status == 'unique_match' + assert framed_result.candidates[0].coordinate_transform == { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.045, + 'anchor_ids': ['title'], 'reason_codes': [], + } + assert legacy_result.candidates[0].coordinate_transform is None + + +def test_legacy_profile_automatically_uses_unique_document_match_label_for_bounded_translation(): + """新管理台不配置坐标模型时,唯一的模板身份标签仍可自动校正小幅整体平移。""" + definition = _profile('PO_AUTO_FRAME')['definition'] + definition['document_match']['required_anchors'][0].update({ + 'label_region': {'x0': .05, 'y0': .02, 'x1': .265, 'y1': .10}, + 'value_region': {'x0': .42, 'y0': .02, 'x1': .85, 'y1': .10}, + }) + profile = OrderCoordinateProfile.model_validate(definition) + pages = {'1': {'width': 200, 'height': 280}} + glyphs = {'1': [ + {'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 25.8, 'x1': 13 + index * 4, 'y1': 35.8}} + for index, char in enumerate('PLANT NAME:') + ]} + + transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs) + + assert reasons == [] + assert transform == { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.05, + 'anchor_ids': ['plant_name'], 'reason_codes': [], + } + + +def test_affine_anchor_frame_requires_explicit_opt_in_and_three_stable_anchors(): + """仿射只允许显式治理的多锚点 Profile 使用,默认平移模板不改变行为。""" + definition = _anchor_frame_profile()['definition'] + definition['coordinate_model'].update({ + 'transform_mode': 'affine', + 'anchors': [ + {'anchor_id': 'a', 'text': 'A', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .10, 'x1': .14, 'y1': .14}}, + {'anchor_id': 'b', 'text': 'B', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .10, 'x1': .64, 'y1': .14}}, + {'anchor_id': 'c', 'text': 'C', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .60, 'x1': .14, 'y1': .64}}, + ], + 'max_scale_delta': .05, + 'max_rotation_degrees': 3.0, + 'max_residual': .005, + }) + profile = OrderCoordinateProfile.model_validate(definition) + pages = {'1': {'width': 1000, 'height': 1000}} + # x 轴放大 2%,y 轴放大 1%,并整体右移 1%、下移 2%。 + glyphs = {'1': [ + {'text': 'A', 'bbox': {'x0': 122.4, 'y0': 131.2, 'x1': 142.4, 'y1': 151.2}}, + {'text': 'B', 'bbox': {'x0': 632.4, 'y0': 131.2, 'x1': 652.4, 'y1': 151.2}}, + {'text': 'C', 'bbox': {'x0': 122.4, 'y0': 636.2, 'x1': 142.4, 'y1': 656.2}}, + ]} + + transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs) + + # 关键断言:仿射矩阵仅由三个唯一锚点证明,且带可审计残差。 + assert reasons == [] + assert transform['matrix'] == [1.02, 0.0, .01, 0.0, 1.01, .02] + assert transform['anchor_ids'] == ['a', 'b', 'c'] + assert transform['residual'] == 0.0 + + +def test_affine_anchor_frame_rejects_degenerate_or_high_residual_evidence(): + """共线锚点和超残差锚点不允许形成看似可信的仿射坐标系。""" + definition = _anchor_frame_profile()['definition'] + definition['coordinate_model'].update({ + 'transform_mode': 'affine', + 'anchors': [ + {'anchor_id': 'a', 'text': 'A', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .10, 'x1': .14, 'y1': .14}}, + {'anchor_id': 'b', 'text': 'B', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .10, 'x1': .64, 'y1': .14}}, + {'anchor_id': 'c', 'text': 'C', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .60, 'x1': .14, 'y1': .64}}, + {'anchor_id': 'd', 'text': 'D', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .60, 'x1': .64, 'y1': .64}}, + ], + 'max_scale_delta': .05, + 'max_rotation_degrees': 3.0, + 'max_residual': .003, + }) + profile = OrderCoordinateProfile.model_validate(definition) + pages = {'1': {'width': 1000, 'height': 1000}} + # A/B/C 都符合平移;D 额外偏离 2%,残差必须阻断而不是被最小二乘掩盖。 + glyphs = {'1': [ + {'text': 'A', 'bbox': {'x0': 110, 'y0': 120, 'x1': 130, 'y1': 140}}, + {'text': 'B', 'bbox': {'x0': 610, 'y0': 120, 'x1': 630, 'y1': 140}}, + {'text': 'C', 'bbox': {'x0': 110, 'y0': 620, 'x1': 130, 'y1': 640}}, + {'text': 'D', 'bbox': {'x0': 630, 'y0': 620, 'x1': 650, 'y1': 640}}, + ]} + + transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs) + + assert transform is None + assert reasons == ['profile_anchor_frame_affine_residual_out_of_range'] + + +def test_anchor_frame_fails_closed_when_anchor_is_missing_ambiguous_or_out_of_range(): + """锚点框架不得因缺锚、重锚或超界平移降级猜测,均须成为模板硬失败。""" + baseline = _layout_with_frame_anchor() + profile = _with_signature(_anchor_frame_profile(), baseline) + missing = _layout() + ambiguous = _layout_with_frame_anchor(anchor_y=.08, table_y=.28) + ambiguous['coordinate_evidence']['page_glyphs']['1'].extend( + _layout_with_frame_anchor(anchor_y=.115)['coordinate_evidence']['page_glyphs']['1'][21:34], + ) + out_of_range = _layout_with_frame_anchor(anchor_y=.14, table_y=.34) + + for layout, reason in ( + (missing, 'profile_anchor_frame_anchor_missing'), + (ambiguous, 'profile_anchor_frame_anchor_ambiguous'), + (out_of_range, 'profile_anchor_frame_transform_out_of_range'), + ): + result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout) + assert result.candidates[0].hard_match is False + assert reason in result.candidates[0].reason_codes + + +def test_anchor_frame_matches_static_anchor_embedded_in_a_pdf_line(): + """PDF 原生字符常把多个标签拼成一行;锚点应返回自身字符框而非整行框。""" + baseline = _layout_with_frame_anchor() + title = baseline['coordinate_evidence']['page_glyphs']['1'][21:34] + prefix = [{'text': 'X', 'bbox': {'x0': 0, 'y0': 14, 'x1': 5, 'y1': 24}}] + suffix = [{'text': 'X', 'bbox': {'x0': 80, 'y0': 14, 'x1': 85, 'y1': 24}}] + for glyph in title: + glyph['bbox']['y0'] += 10 + glyph['bbox']['y1'] += 10 + prefix[0]['bbox']['y0'] += 10 + prefix[0]['bbox']['y1'] += 10 + suffix[0]['bbox']['y0'] += 10 + suffix[0]['bbox']['y1'] += 10 + baseline['coordinate_evidence']['page_glyphs']['1'] = [ + *baseline['coordinate_evidence']['page_glyphs']['1'][:21], + *prefix, + *title, + *suffix, + *baseline['coordinate_evidence']['page_glyphs']['1'][34:], + ] + profile = _with_signature(_anchor_frame_profile(), baseline) + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=baseline) + + # 关键断言:行内静态锚点仍唯一命中,且自身 bbox 不受前后文本扩大影响。 + assert result.status == 'unique_match' + assert result.candidates[0].coordinate_transform == { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.035714, + 'anchor_ids': ['title'], 'reason_codes': [], + } + + def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values(): """工厂标签和值关系不受订单号、料号、数量变化影响。""" layout = _layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X') @@ -120,6 +328,114 @@ def test_profile_matcher_enforces_required_anchor_and_evidence_availability(): assert match_frozen_coordinate_profiles(profiles=[profile], layout={'tables': []}).status == 'evidence_insufficient' +def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_compacted(): + """字符坐标被压缩后,模板匹配仍须使用压缩前持久化的结构特征。""" + complete_layout = _layout() + profile = _profile('PO_A') + profile['definition']['document_match']['required_anchors'] = [] + profile = _with_signature(profile, complete_layout) + compacted_layout = { + 'tables': complete_layout['tables'], + 'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']}, + 'matching_features': { + 'version': 'v1', + 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, + 'tables': [{ + 'table_id': 'table-1', 'page_no': 1, + 'bbox': [0.05, 0.25, 0.95, 0.95], + 'header_candidates': [{ + 'header_tokens': ['item', 'no', 'qty'], + 'column_centers': [0.1225, 0.2825, 0.4225], + 'column_width_ratios': [0.1611, 0.0722, 0.1167], + }], + }], + 'static_text_centers': {}, + }, + } + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout) + + assert result.status == 'unique_match' + candidate = result.candidates[0] + assert candidate.dimension_states['header_semantic_position'] == 'matched' + assert candidate.dimension_states['column_topology'] == 'matched' + + +def test_profile_matcher_selects_semantic_header_candidate_not_data_row_from_compacted_projection(): + """压缩投影含数据行候选时,必须用语义与列几何选真实表头,不能只比列数。""" + complete_layout = _layout() + profile = _profile('PO_A') + profile['definition']['document_match']['required_anchors'] = [] + profile = _with_signature(profile, complete_layout) + compacted_layout = { + 'tables': complete_layout['tables'], + 'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']}, + 'matching_features': { + 'version': 'v1', + 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, + 'tables': [{ + 'bbox': [0.05, 0.25, 0.95, 0.95], + 'header_candidates': [ + { + 'header_tokens': ['ab-100', 'ea', '10'], + 'column_centers': [0.1225, 0.2825, 0.4225], + 'column_width_ratios': [0.1611, 0.0722, 0.1167], + }, + { + 'header_tokens': ['item', 'no', 'qty'], + 'column_centers': [0.1225, 0.2825, 0.4225], + 'column_width_ratios': [0.1611, 0.0722, 0.1167], + }, + ], + }], + }, + } + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout) + + assert result.status == 'unique_match' + assert result.candidates[0].dimension_states['header_semantic_position'] == 'matched' + + +def test_profile_matcher_rejects_incomplete_compacted_projection_as_evidence_insufficient(): + """没有候选表头事实的压缩投影不得仅凭页面和表框自动命中。""" + complete_layout = _layout() + profile = _profile('PO_A') + profile['definition']['document_match']['required_anchors'] = [] + profile = _with_signature(profile, complete_layout) + compacted_layout = { + 'tables': complete_layout['tables'], + 'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']}, + 'matching_features': { + 'version': 'v1', + 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, + 'tables': [{'bbox': [0.05, 0.25, 0.95, 0.95]}], + }, + } + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout) + + assert result.status == 'evidence_insufficient' + + +def test_profile_matcher_prefers_current_glyphs_to_persisted_projection(): + """当前 Layout 有完整 glyph 时,错误持久化投影不得覆盖实时证据。""" + layout = _layout() + profile = _with_signature(_profile('PO_A'), layout) + layout['matching_features'] = { + 'version': 'v1', + 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, + 'tables': [{'bbox': [0.05, 0.25, 0.95, 0.95], 'header_candidates': [{ + 'header_tokens': ['unrelated'], 'column_centers': [.8], 'column_width_ratios': [.1], + }]}], + } + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout) + + assert result.status == 'unique_match' + assert result.candidates[0].dimension_states['column_topology'] == 'matched' + + def test_profile_matcher_reports_only_missing_anchor_identifiers(): """缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。""" profile = _profile('PO_A') diff --git a/backend/tests/test_shipping_order_review_field_conflict.py b/backend/tests/test_shipping_order_review_field_conflict.py index 3e9b357b..e94920cf 100644 --- a/backend/tests/test_shipping_order_review_field_conflict.py +++ b/backend/tests/test_shipping_order_review_field_conflict.py @@ -11,6 +11,8 @@ from __future__ import annotations from types import SimpleNamespace from unittest.mock import patch +import pytest + from app.services.shipping_notice.order_review_field_conflict_service import ( project_review_case_evidence_issues, project_review_case_field_conflicts, @@ -94,6 +96,140 @@ def test_project_review_case_field_conflicts_empty_without_candidate(): assert project_review_case_field_conflicts(case) == [] +def test_project_review_case_keeps_open_legacy_single_value_conflict_visible(monkeypatch): + """资格层仍阻断的遗留单值 Finding 不得被投影静默丢弃。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'conflict_key': '0:unit_price', + 'field': 'unit_price', + 'line_index': 0, + 'severity': 'blocking', + 'reason': 'field_conflict', + 'values': ['1731.60'], + }], + structured_result_json={}, + ) + case = SimpleNamespace( + candidate_id=1, + current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]), + ) + from app.services.shipping_notice import order_review_field_conflict_service as svc + + monkeypatch.setattr(svc, '_candidate_for_case', lambda _case: candidate) + monkeypatch.setattr(svc, 'current_open_candidate_conflicts', lambda _candidate: list(candidate.conflicts_json)) + + items = project_review_case_field_conflicts(case) + + assert len(items) == 1 + assert items[0]['field_code'] == 'unit_price' + assert items[0]['conflict_key'] == '0:unit_price' + + +@pytest.mark.pure_unit +def test_project_review_case_field_conflicts_uses_complete_finding_source_evidence(): + """正文补充真冲突必须直接展示 PDF/邮件值与来源,不能因缺 Observation 而消失。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'conflict_key': '0:unit_price', + 'field': 'unit_price', + 'line_index': 0, + 'scope': 'line', + 'severity': 'blocking', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'unresolved', + 'values': ['1731.60', '1732.00'], + 'sources': [ + {'source_type': 'pdf', 'raw_value': '1731.60', 'document_id': 305, 'evidence_ref': {'page_no': 1}}, + {'source_type': 'email_body', 'raw_value': '1732.00', 'document_id': 304, 'evidence_ref': {'row_index': 5}}, + ], + }], + structured_result_json={}, + ) + case = SimpleNamespace( + candidate_id=1, + current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]), + ) + + from app.services.shipping_notice import order_review_field_conflict_service as svc + + original = svc._candidate_for_case + svc._candidate_for_case = lambda _case: candidate + try: + items = project_review_case_field_conflicts(case) + finally: + svc._candidate_for_case = original + + assert len(items) == 1 + assert items[0]['conflict_key'] == '0:unit_price' + assert [option['display_value'] for option in items[0]['options']] == ['1731.60', '1732.00'] + assert [option['evidence_role'] for option in items[0]['options']] == ['primary_pdf', 'context'] + assert [option['document_id'] for option in items[0]['options']] == [305, 304] + + +@pytest.mark.pure_unit +def test_project_review_case_finding_with_pdf_source_is_marked_primary_pdf(): + """补充合并的 PDF 来源未附原始 source_type 时,面板仍须标识其为主 PDF。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'conflict_key': '0:unit_price', 'field': 'unit_price', 'line_index': 0, + 'severity': 'blocking', 'reason': 'supplement_field_conflict', + 'values': ['1', '2'], + 'sources': [ + {'source_type': 'pdf', 'raw_value': '1', 'document_id': 305, 'evidence_ref': {}}, + {'source_type': 'email_body', 'raw_value': '2', 'document_id': 304, 'evidence_ref': {}}, + ], + }], + structured_result_json={}, + ) + case = SimpleNamespace( + candidate_id=1, + current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]), + ) + from app.services.shipping_notice import order_review_field_conflict_service as svc + + original = svc._candidate_for_case + svc._candidate_for_case = lambda _case: candidate + try: + items = project_review_case_field_conflicts(case) + finally: + svc._candidate_for_case = original + + assert items[0]['options'][0]['evidence_role'] == 'primary_pdf' + + +@pytest.mark.pure_unit +def test_project_review_case_legacy_supplement_evidence_gap_is_visible_not_a_blank_panel(): + """历史补充冲突证据不足必须投影为可见证据问题,不能静默阻断资格。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'conflict_key': '-1:unit_price', + 'field': 'unit_price', + 'severity': 'blocking', + 'reason': 'supplement_conflict_evidence_insufficient', + 'resolution_status': 'unresolved', + 'scope': 'unscoped', + 'recovery_action': 'reparse_current_pdf', + }], + structured_result_json={}, + ) + case = SimpleNamespace(current_draft=None) + from app.services.shipping_notice import order_review_field_conflict_service as svc + + original = svc._candidate_for_case + svc._candidate_for_case = lambda _case: candidate + try: + conflicts, evidence_issues = svc._project_review_case_candidate_findings(case) + finally: + svc._candidate_for_case = original + assert conflicts == [] + assert evidence_issues == [{ + 'conflict_key': '-1:unit_price', 'field_code': 'unit_price', 'line_index': None, + 'line_key': None, 'scope': 'unscoped', 'severity': 'blocking', + 'reason': 'supplement_conflict_evidence_insufficient', 'options': [], + 'observation_ids': [], 'recovery_action': 'reparse_current_pdf', + }] + + def test_project_review_findings_deduplicate_evidence_gaps_and_keep_them_out_of_value_conflicts(): """同键证据缺失只能保留一项,并与多值字段冲突分区展示。""" candidate = SimpleNamespace( @@ -155,6 +291,34 @@ def test_project_review_findings_deduplicate_evidence_gaps_and_keep_them_out_of_ assert [item['scope'] for item in evidence_issues] == ['unscoped', 'line'] +def test_project_review_findings_omits_optional_line_no_evidence_gap(): + """line_no 非必填且可派生时,历史证据缺失不得继续显示为待确认。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'field': 'line_no', + 'severity': 'blocking', + 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }], + structured_result_json={ + 'extraction': {'field_adjudication': { + 'blocked_fields': [], + 'decisions': [{'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived'}], + }}, + }, + ) + case = SimpleNamespace(candidate_id=1, current_draft=SimpleNamespace(lines_json=[])) + + from app.services.shipping_notice import order_review_field_conflict_service as svc + + original = svc._candidate_for_case + svc._candidate_for_case = lambda _case: candidate + try: + assert project_review_case_evidence_issues(case) == [] + finally: + svc._candidate_for_case = original + + def test_sync_review_gates_replaces_stale_missing_field_gate_with_field_conflict(): """草稿字段已齐全时,Gate 必须通过完整性并把最新证据冲突归属到字段冲突门禁。""" case = SimpleNamespace( diff --git a/backend/tests/test_shipping_order_review_resume_service.py b/backend/tests/test_shipping_order_review_resume_service.py index 5cf21b10..56ac2cf2 100644 --- a/backend/tests/test_shipping_order_review_resume_service.py +++ b/backend/tests/test_shipping_order_review_resume_service.py @@ -101,3 +101,110 @@ def test_resume_waiting_manual_confirm_when_auto_gate_false(monkeypatch): assert result['auto_gate_allowed'] is False assert result['task_created'] is False assert case.status == 'ready' + + +@pytest.mark.pure_unit +def test_resume_enqueues_auto_create_when_draft_validation_is_eligible(monkeypatch): + """保存并校验在所有 Gate 通过时必须入队 STP,而非停在 ready。""" + case = _case(can_build=True, can_auto_create=True, validation_status='ready') + monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case) + monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None) + monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: []) + monkeypatch.setattr(svc, 'record_fulfillment_audit', lambda **_kw: None) + monkeypatch.setattr(svc.db.session, 'flush', lambda: None) + monkeypatch.setattr(svc.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_projection.serialize_review_case', + lambda _c: {'case_no': case.case_no, 'status': case.status}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case', + lambda **_kw: {'status': 'queued', 'job_id': 91, 'idempotency_key': 'stp-91'}, + ) + + result = svc.resume_after_review_change( + user_id=7, + case_no=case.case_no, + trigger='draft_validated', + skip_validate=True, + allow_auto_create=True, + ) + + assert result['outcome'] == 'auto_create_enqueued' + assert result['auto_gate_allowed'] is True + assert result['stp_enqueue'] == {'status': 'queued', 'job_id': 91, 'idempotency_key': 'stp-91'} + + +def test_resume_auto_confirms_unique_customer_before_validating(monkeypatch): + """保存校验时必须先确认唯一客户候选,再执行 Draft 校验。""" + case = _case(can_build=True, can_auto_create=False, validation_status='ready') + calls = [] + monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case) + monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None) + monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: []) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.auto_confirm_unique_customer_for_review_case', + lambda **_kw: calls.append('customer') or {'status': 'auto_confirmed', 'customer_id': 5555}, + ) + monkeypatch.setattr( + svc, + 'validate_draft', + lambda **_kw: calls.append('validate') or {'status': 'ready'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit', + lambda **_kw: None, + ) + monkeypatch.setattr(svc.db.session, 'flush', lambda: None) + monkeypatch.setattr(svc.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_projection.serialize_review_case', + lambda _c: {'case_no': case.case_no}, + ) + + svc.resume_after_review_change( + user_id=7, + case_no=case.case_no, + trigger='draft_validated', + skip_validate=False, + ) + + assert calls == ['customer', 'validate'] + + +def test_validate_draft_api_delegates_versioned_validation_to_resume_coordinator(app, monkeypatch): + """保存校验 API 不可绕过协调器,必须传递乐观锁版本。""" + from app.api.workspace import shipping_notice as api + from app.services.shipping_notice import order_review_resume_service + + user = SimpleNamespace(id=7) + calls = [] + + def fake_resume(**kwargs): + calls.append(kwargs) + return { + 'case': {'case_no': kwargs['case_no']}, + 'outcome': 'blocked', + 'gate_recalculated': True, + } + + monkeypatch.setattr(api, '_require_user', lambda: user) + monkeypatch.setattr(order_review_resume_service, 'resume_after_review_change', fake_resume) + with app.test_request_context( + '/shipping-notice/order-review-cases/CASE-API/draft/validate', + method='POST', + json={'expected_draft_version': 12}, + ): + response, status = api.workspace_validate_shipping_order_review_draft('CASE-API') + + assert status == 200 + assert response.get_json()['data']['case'] == {'case_no': 'CASE-API'} + assert calls == [{ + 'user_id': 7, + 'case_no': 'CASE-API', + 'trigger': 'draft_validated', + 'change_type': None, + 'skip_validate': False, + 'allow_auto_create': True, + 'expected_draft_version': 12, + }] diff --git a/backend/tests/test_shipping_order_review_service.py b/backend/tests/test_shipping_order_review_service.py index bc475d68..452ce7b8 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -24,13 +24,17 @@ from app.models import ( ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderCandidate, + ShippingOrderCustomerMatch, + ShippingOrderExtraction, ShippingOrderProcessingRun, ShippingOrderReviewCase, ShippingOrderReviewStream, ShippingOrderReviewCaseEvent, ShippingOrderReviewConfirmedRevision, ShippingOrderReviewWaveLine, + ShippingOrderSchemaVersion, ShippingNotice, + ShippingCustomer, User, ) from app.services.shipping_notice.order_review_projection import ( @@ -294,7 +298,7 @@ def test_review_queue_projects_each_case_po_and_lifecycle_stage(app): assert item['po_number'] == 'PO-QUEUE-001' assert item['lifecycle_stage'] == 'order_review' assert [entry['state'] for entry in item['lifecycle_entries']] == [ - 'available', 'current', 'unavailable', 'unavailable', + 'available', 'current', 'unavailable', 'unavailable', 'unavailable', ] @@ -334,7 +338,7 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app): assert item['po_number'] == 'PO-QUEUE-002' assert item['lifecycle_stage'] == 'fulfillment_prep' assert [entry['state'] for entry in item['lifecycle_entries']] == [ - 'available', 'available', 'current', 'unavailable', + 'available', 'available', 'current', 'unavailable', 'unavailable', ] @@ -401,6 +405,32 @@ def _materialized_run(*, user, agent, session, intake): return run +def test_review_case_summary_exposes_only_failed_intake_retry_authorization(app): + """当前阶段卡只消费服务端 parse_failed 的 SNI 编号与 retry_parse 授权。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-INTAKE-RETRY') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + case = ensure_run_review_cases(run=run)[0] + intake.parse_status = 'parse_failed' + db.session.commit() + + failed = serialize_review_run(run)['items'][0] + # 关键断言:失败节点提供原 SNI 和 retry_parse;不需要重新上传或前端猜测。 + assert failed['intake_no'] == intake.intake_no + assert failed['available_actions'] == ['retry_parse'] + + intake.parse_status = 'parsing' + db.session.commit() + parsing = serialize_review_run(run)['items'][0] + # 关键断言:运行中只能等待 Worker 超时回收,不能显示冲突重试动作。 + assert parsing['available_actions'] == [] + + intake.parse_status = 'cancelled' + db.session.commit() + cancelled = serialize_review_run(run)['items'][0] + assert cancelled['available_actions'] == [] + + def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'reservation-id') -> None: """ 为 Review 就绪路径测试注入行级 catch-all 库存源规则。 @@ -419,6 +449,51 @@ def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'res db.session.commit() +def _seed_confirmed_bill_to_for_candidate(*, candidate, run, intake, user) -> None: + """ + 为机器 Candidate 补齐可继承的 Bill-to 确认事实。 + + 核心逻辑:确认服务只从 Candidate 关联的来源 Extraction 复制已确认客户;不能以 + Candidate 摘要中的状态替代冻结所需的可审计客户事实。 + """ + customer = ShippingCustomer( + standard_name='Review Test Customer', + short_code='REV', + ) + db.session.add(customer) + db.session.flush() + extraction = ShippingOrderExtraction( + run_id=int(run.id), + intake_id=int(intake.id), + schema_version_id=int(run.schema_version_id), + input_snapshot_hash=str(run.input_snapshot_hash or ''), + input_snapshot_json={'source': 'review_test_customer_confirmation'}, + status='accepted', + normalized_result_json={}, + validation_result_json={}, + created_by_id=int(user.id), + ) + db.session.add(extraction) + db.session.flush() + candidate.order_extraction_id = int(extraction.id) + db.session.add(ShippingOrderCustomerMatch( + extraction_id=int(extraction.id), + role='bill_to', + raw_name=customer.standard_name, + normalized_name='REVIEW TEST CUSTOMER', + status='confirmed', + customer_id=int(customer.id), + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + identity_fingerprint='f' * 64, + identity_rule_version='order-customer-fingerprint.v1', + identity_components_json={'role': 'bill_to'}, + resolution_method='manual', + confirmation_reason='测试确认', + confirmed_by_id=int(user.id), + )) + + def test_reservation_summary_reads_current_draft_value_before_async_validation(): """合法预约号已保存但校验 Job 未落投影时,右栏不得误报缺失。""" case = SimpleNamespace( @@ -516,6 +591,42 @@ def test_reservation_summary_reads_machine_value_before_async_validation(): assert result['lines'][0]['effective_reservation_id'] == '33874' +def test_reservation_summary_does_not_leak_inventory_block_reason(): + """Reservation 面板不得展示同一明细的库存路由阻断原因。""" + case = SimpleNamespace( + run=SimpleNamespace(input_snapshot_json={ + 'schema': {'definition': {'fields': [{ + 'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', + }]}}}, + ), + current_draft=SimpleNamespace( + validation_result_json={ + 'status': 'needs_review', + 'line_projections': [{ + 'line_key': 'line-1', + 'effective_reservation_id': None, + 'can_build': False, + 'block_reason': 'no_inventory_source_candidates', + }], + 'issues': [{ + 'code': 'effective_reservation_missing', + 'line_index': 0, + 'owning_gate_code': 'reservation_validation', + 'severity': 'blocking', + }], + }, + lines_json=[], + ), + ) + + result = project_review_case_reservation(case) + + # 关键断言:库存路由码只能留在库存 Gate,Reservation 行应显示自身缺失原因。 + assert result['lines'][0]['block_reason'] == 'effective_reservation_missing' + assert result['lines'][0]['block_reason'] != 'no_inventory_source_candidates' + assert result['lines'][0]['needs_attention'] is True + + def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candidate_readonly(app): """同一 PDF 重入只保留一个 Case/Draft,草稿复制机器快照但不改写 Candidate。""" with app.app_context(): @@ -634,7 +745,7 @@ def test_candidate_gate_reconciliation_supersedes_active_legacy_attempt(app): gate_code='document_materialization', trigger_type='system_requeue', actor_type='system', actor_id='test', idempotency_key='candidate-supersedes-active-attempt', - input_snapshot={'action_code': 'retry_with_latest_rules'}, + input_snapshot={'action_code': 'rematerialize_document'}, ) mark_attempt_running(attempt_id=attempt.id, worker_id='test') from app.services.shipping_notice.process_gate_bridge import reconcile_extraction_gates_for_review_case @@ -951,11 +1062,20 @@ def test_review_read_api_returns_safe_owner_scoped_projection(app): token = issue_local_access_token(user) headers = {'Authorization': f'Bearer {token}'} run_response = client.get(f'/api/workspace/shipping-notice/order-extraction-runs/{run.run_no}/review', headers=headers) + queue_response = client.get(f'/api/workspace/shipping-notice/order-review-queue/{run.run_no}', headers=headers) case_response = client.get(f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}', headers=headers) # 关键断言:列表和详情仅给 owner 返回 Case/Draft 安全投影,不输出原始文本或对象存储信息。 assert run_response.status_code == 200 + assert queue_response.status_code == 200 assert case_response.status_code == 200 + # 关键断言:慢切换读取必须返回查找/投影边界,供浏览器 HAR 精确定位,不泄露业务内容。 + assert 'review_lookup' in run_response.headers.get('Server-Timing', '') + assert 'review_projection' in run_response.headers.get('Server-Timing', '') + assert 'queue_lookup' in queue_response.headers.get('Server-Timing', '') + assert 'queue_projection' in queue_response.headers.get('Server-Timing', '') + assert 'case_lookup' in case_response.headers.get('Server-Timing', '') + assert 'case_projection' in case_response.headers.get('Server-Timing', '') assert case.case_no in str(run_response.get_json()) body = case_response.get_json() assert 'extracted_text' not in str(body) @@ -1768,6 +1888,63 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a raise AssertionError('superseded case must not be reparsed') +def test_successful_document_reparse_reconciles_only_activated_replacement_case(app, monkeypatch): + """PDF 重识别成功切换当前版本后,必须补触发新版 Case 的统一自动推进。""" + with app.app_context(): + from app.services.shipping_notice import order_review_disposition_service as disposition + + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-PROGRESS') + source = _materialized_run(user=user, agent=agent, session=session, intake=intake) + source_case = ensure_run_review_cases(run=source)[0] + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={}) + replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other') + ensure_order_extraction_plan(replacement) + for unit in replacement.extraction_plan.units: + unit.status = 'candidate_ready' + replacement_case = ensure_run_review_cases(run=replacement)[0] + reconciled = [] + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.' + 'reconcile_single_case_for_auto_progress', + lambda **kwargs: reconciled.append(kwargs) or {'enqueue_status': 'queued'}, + ) + + finalize_document_reparse(run=replacement, succeeded=True) + + assert reconciled == [{ + 'case': replacement_case, + 'trigger': 'document_reparse_succeeded', + 'refresh_validation': True, + }] + + +def test_document_reparse_does_not_reconcile_when_stream_activation_is_rejected(app, monkeypatch): + """Stream 冲突或已确认旧版本拒绝切换时,不得推进晚到的新版草稿。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-CONFLICT') + source = _materialized_run(user=user, agent=agent, session=session, intake=intake) + source_case = ensure_run_review_cases(run=source)[0] + mark_review_stream_confirmed(case=source_case) + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={}) + replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other') + ensure_order_extraction_plan(replacement) + for unit in replacement.extraction_plan.units: + unit.status = 'candidate_ready' + ensure_run_review_cases(run=replacement) + reconciled = [] + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.' + 'reconcile_single_case_for_auto_progress', + lambda **kwargs: reconciled.append(kwargs), + ) + + finalize_document_reparse(run=replacement, succeeded=True) + + assert reconciled == [] + + def test_run_auto_progress_ignores_legacy_open_case_that_is_not_stream_current(app): """Run 级协调只能处理文件 Stream 当前 Case,不能重启残留旧版本。""" with app.app_context(): @@ -1925,6 +2102,8 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] unit.result_json = {'orders': [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-CONFIRM'}]}], 'lines': [{'fields': [ {'field_id': 'part-id', 'observations': [{'value': 'A001'}]}, @@ -1941,6 +2120,12 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app): }, ) db.session.add(machine) + _seed_confirmed_bill_to_for_candidate( + candidate=machine, + run=run, + intake=intake, + user=user, + ) db.session.commit() case = ensure_run_review_cases(run=run)[0] # 确认建单要求 Candidate 已绑定 OT(BE-01);测试显式物化。 @@ -2016,17 +2201,26 @@ def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutati schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [ {'field_id': 'part-id', 'observations': [{'value': 'A002'}]}, {'field_id': 'qty-id', 'observations': [{'value': '3'}]}, {'field_id': 'reservation-id', 'observations': [{'value': '3000092918'}]}, ]}]}]} - db.session.add(ShippingOrderCandidate( + machine = ShippingOrderCandidate( candidate_no='CAND-REVIEW-CONFIRM-REPLAY', intake_id=intake.id, primary_document_id=document.id, candidate_key='machine-confirm-replay', order_extraction_run_id=run.id, structured_result_json={'customer': {'resolution_status': 'confirmed'}}, - )) + ) + db.session.add(machine) + _seed_confirmed_bill_to_for_candidate( + candidate=machine, + run=run, + intake=intake, + user=user, + ) db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() @@ -2312,6 +2506,8 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] # 行 A 完整;行 B 缺 qty → 整单 needs_review,但 A 应可先行。 unit.result_json = {'orders': [{'header_fields': [], 'lines': [ @@ -2325,11 +2521,18 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): {'field_id': 'reservation-id', 'observations': [{'value': '3000092902'}]}, ]}, ]}]} - db.session.add(ShippingOrderCandidate( + machine = ShippingOrderCandidate( candidate_no='CAND-REVIEW-MULTI-WAVE', intake_id=intake.id, primary_document_id=document.id, candidate_key='machine-multi-wave', order_extraction_run_id=run.id, structured_result_json={'customer': {'resolution_status': 'confirmed'}}, - )) + ) + db.session.add(machine) + _seed_confirmed_bill_to_for_candidate( + candidate=machine, + run=run, + intake=intake, + user=user, + ) db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() @@ -2456,3 +2659,17 @@ def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app): ) assert exc.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE' del agent, session, intake +def test_unvalidated_draft_is_not_projected_as_build_blocked(app): + """未执行校验的 Draft 必须保持 not_validated,不能伪造成 can_build=false。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='UNVALIDATED-PROJECTION') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + unit = run.extraction_plan.units[0] + case = ensure_review_case_for_unit(run=run, unit=unit) + db.session.flush() + + detail = serialize_review_case(case) + eligibility = detail['draft']['build_eligibility'] + + assert eligibility['status'] == 'not_validated' + assert eligibility['can_build'] is None diff --git a/backend/tests/test_shipping_order_schema_runtime.py b/backend/tests/test_shipping_order_schema_runtime.py index 6b8497d6..41a5e576 100644 --- a/backend/tests/test_shipping_order_schema_runtime.py +++ b/backend/tests/test_shipping_order_schema_runtime.py @@ -1279,6 +1279,85 @@ def test_optional_non_key_field_evidence_missing_is_diagnostic_only(app): assert diagnostic[0].get('user_visible') is False +def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app): + """表格诊断命中可选列时,只能保留诊断,不能把它写入 blocked_fields。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + line_no = service.save_field({'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + line_no_cfg = _config(line_no['id'], '行号', value_type='string') + line_no_cfg.update({'required': False, 'auto_create_key_field': False}) + published = _save_and_publish(draft, [ + line_no_cfg, + _config(part['id'], '内部料号', value_type='string'), + ]) + intake_id, documents, actor_id = _seed_documents() + document = documents[1] + document.extracted_text = 'Part No: ABC-123' + + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], + 'lines': [{'fields': [{'field_id': part['id'], 'observations': [{ + 'value': 'ABC-123', 'document_id': document.id, 'quote': 'Part No: ABC-123', + }]}]}], + }, + intake_id=intake_id, snapshot_hash='q' * 64, documents=documents, actor_id=actor_id, + layout_candidates_by_document={ + int(document.id): [{'reason': 'layout_table_needs_review', 'field_codes': ['line_no']}], + }, + ) + + # 关键断言:可选行号的坐标问题不影响自动建单资格,但审计诊断必须保留。 + assert 'line_no' not in (result.get('blocked_fields') or []) + finding = next(item for item in result['findings'] if item.get('field_code') == 'line_no') + assert finding['severity'] == 'diagnostic' + assert finding['blocks_current_action'] is False + + +def test_accepted_key_field_is_not_blocked_by_unaccepted_table_mapping(app): + """关键字段已有当前可验证证据时,整表坐标诊断不能覆盖字段事实。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + unit_price = service.save_field({'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + price_cfg = _config(unit_price['id'], '单价', value_type='decimal') + price_cfg.update({'auto_create_key_field': True, 'minimum_confidence': 0.9}) + published = _save_and_publish(draft, [price_cfg]) + intake_id, documents, actor_id = _seed_documents() + document = documents[1] + document.extracted_text = 'Unit Price 898.72' + + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], + 'lines': [{'fields': [{'field_id': unit_price['id'], 'observations': [{ + 'value': '898.72', 'document_id': document.id, + 'quote': 'Unit Price 898.72', 'confidence': 1.0, + }]}]}], + }, + intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id, + layout_candidates_by_document={ + int(document.id): [{ + 'mapping_status': 'candidate', + 'rows': [{'role': 'data', 'fields': [{ + 'field_id': unit_price['id'], 'value': '898.72', + 'cell_id': 'price-cell', 'evidence_ref': 'layout:price-cell', + }]}], + }], + }, + ) + + # 关键断言:表格映射未被接受仍保留诊断,但已接受的单价证据不得被重新阻断。 + assert 'unit_price' not in (result.get('blocked_fields') or []) + finding = next(item for item in result['findings'] if item.get('field_code') == 'unit_price') + assert finding['severity'] == 'diagnostic' + assert finding['blocks_current_action'] is False + + def test_key_field_quality_issue_still_blocks(app): """auto_create_key_field 字段证据不足必须进入 blocked_fields(即使 required=false)。""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_task_progress_audit.py b/backend/tests/test_shipping_order_task_progress_audit.py index 587056b6..9e379e5e 100644 --- a/backend/tests/test_shipping_order_task_progress_audit.py +++ b/backend/tests/test_shipping_order_task_progress_audit.py @@ -19,11 +19,13 @@ from app.services.shipping_notice.progress_audit_contract import ( def test_order_task_progress_audit_event_types_frozen(): - """契约冻结:OT 进度三类事件码齐全。""" + """契约冻结:OT 进度及投影一致性事件码齐全。""" assert ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES == frozenset({ 'order_task_created', 'order_task_updated', 'order_task_progress_changed', + 'shipping_processing_projection_inconsistent', + 'shipping_processing_task_ownership_mismatch', }) @@ -114,3 +116,29 @@ def test_sync_order_task_processing_state_noop_skips_audit(app): ).count() assert after_count == before_count assert int(ot.progress_version or 1) == version + + +def test_sync_order_task_processing_state_can_bump_for_review_projection(app): + """Review Gate 变化即使不改 stage/status,也必须推进 Projection 版本。""" + with app.app_context(): + ot = _seed_user_and_task('OT-PROGRESS-AUDIT-3') + version = int(ot.progress_version or 1) + sync_order_task_processing_state( + ot, + force_progress_bump=True, + reason_code='review_gate_changed', + source='test_review_projection', + ) + db.session.commit() + + assert int(ot.progress_version or 1) == version + 1 + event = ( + ShippingAuditEvent.query.filter_by( + event_type='order_task_progress_changed', + aggregate_id=ot.task_no, + ) + .order_by(ShippingAuditEvent.id.desc()) + .first() + ) + assert event is not None + assert event.reason_code == 'review_gate_changed' diff --git a/backend/tests/test_shipping_order_task_status_consistency.py b/backend/tests/test_shipping_order_task_status_consistency.py index 79816896..dbc0c086 100644 --- a/backend/tests/test_shipping_order_task_status_consistency.py +++ b/backend/tests/test_shipping_order_task_status_consistency.py @@ -186,7 +186,7 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): notice_before = ShippingNotice.query.count() with patch( - 'app.services.shipping_notice.order_review_confirmation_service.resolve_shipping_case_for_new_task', + 'app.services.shipping_notice.order_task_service.link_notice_to_order_task', side_effect=ConflictError('simulated notice create failure', code='SHIPPING.SIMULATED_NOTICE_FAIL'), ): with pytest.raises(ConflictError) as exc_info: diff --git a/backend/tests/test_shipping_pdf_automark.py b/backend/tests/test_shipping_pdf_automark.py index 1137592a..44b88cf0 100644 --- a/backend/tests/test_shipping_pdf_automark.py +++ b/backend/tests/test_shipping_pdf_automark.py @@ -105,7 +105,7 @@ def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_change from app.services.shipping_notice import order_document_profile_pdf_automark_service as service profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'}) - annotation = SimpleNamespace(table_id='table-1', layout_version_id=88, layout_payload_checksum='a' * 64) + annotation = SimpleNamespace(id=71, document_id=77, table_id='table-1') document = SimpleNamespace( id=77, current_layout_version_id=88, @@ -125,12 +125,22 @@ def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_change 'get', lambda model, _ident: document if model is service.ShippingOrderDocument else None, ) + from app.services.shipping_notice import order_document_profile_service as profile_service + monkeypatch.setattr( + profile_service, + 'require_profile_sample_automark_ready', + lambda **_kwargs: (_ for _ in ()).throw(ValidationError( + 'Profile sample layout is stale', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE', + )), + ) monkeypatch.setattr(service, 'enqueue', lambda *_args, **_kwargs: 9001) with pytest.raises(ValidationError) as caught: enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1) - assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID' + # Layout 身份不一致必须使用可操作的 stale 错误码,不能退化为泛化配置错误。 + assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE' def test_execute_automark_rejects_job_after_document_layout_reparse(monkeypatch): @@ -591,6 +601,33 @@ def test_automark_exposes_acroform_widget_as_independent_visual_candidate(): assert 'value_binding' not in widget_candidate['binding'] +def test_automark_merges_same_field_same_geometry_sources(): + """关键断言:同字段同页同坐标的 PDF 与 Widget 候选只生成一个画布框。""" + from app.services.shipping_notice import order_document_profile_pdf_automark_service as service + + candidates = [ + { + 'candidate_id': 'pdf-1', 'candidate_kind': 'field_binding', + 'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': { + 'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4}, + }}, + 'evidence_sources': ['pdf_coordinate'], 'needs_review': True, + }, + { + 'candidate_id': 'widget-1', 'candidate_kind': 'field_binding', + 'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': { + 'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4}, + }}, + 'evidence_sources': ['acroform_widget'], 'needs_review': True, + }, + ] + + merged = service._merge_duplicate_field_binding_candidates(candidates) + + assert len(merged) == 1 + assert merged[0]['evidence_sources'] == ['pdf_coordinate', 'acroform_widget'] + + def test_automark_keeps_unmatched_acroform_widget_as_unbound_visual_candidate(monkeypatch): """Widget 技术名未匹配 Schema 时仍可供人工框选,禁止自动猜业务字段。""" from app.services.shipping_notice import order_document_profile_pdf_automark_service as service @@ -717,7 +754,11 @@ def test_automark_enriches_widget_table_candidate_with_coordinate_header_text(): coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []} widget_geometry = { 'table_region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .8}, - 'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .25, 1]}], + # 动态 XFA 的表头控件有展示值时,Widget 聚类会把表头带误判为候选行。 + 'subrow_layouts': [{ + 'row_offset': 0, 'column_boundaries': [0, .25, 1], + 'region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .2}, + }], 'header_regions': [], 'status': 'needs_review', } with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch( @@ -741,6 +782,8 @@ def test_automark_enriches_widget_table_candidate_with_coordinate_header_text(): assert field['field_code'] == 'line_no' assert field['region'] == {'x0': .1, 'y0': .15, 'x1': .3, 'y1': .2} assert field['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate'] + # 已确认的表头带不得同时作为可保存的 Widget 明细行。 + assert widget_candidate['payload']['subrow_layouts'] == [] def test_automark_marks_opencv_and_native_structure_conflict_for_review(): diff --git a/backend/tests/test_shipping_process_gate_contract.py b/backend/tests/test_shipping_process_gate_contract.py index c6f36258..30b4d005 100644 --- a/backend/tests/test_shipping_process_gate_contract.py +++ b/backend/tests/test_shipping_process_gate_contract.py @@ -82,6 +82,16 @@ def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate(): ) is True +def test_inventory_preparation_allows_reload_existing_result_without_rpa(): + """RPA 超时后可重读已有库存结果;该动作仅属于库存准备 Gate。""" + assert action_belongs_to_gate( + gate_code='inventory_preparation', action_code='reload_inventory_result', + ) is True + assert action_belongs_to_gate( + gate_code='inventory_matching', action_code='reload_inventory_result', + ) is False + + def test_inventory_sufficiency_actions_keep_business_specific_labels(): """库存缺口恢复必须保留精确业务动作,禁止客户端降级为统一“重试”。""" assert action_presentation('open_shortage_review') == { @@ -106,13 +116,13 @@ def test_fulfillment_action_presentation_declares_lifecycle_surface(): )['target_surface'] == 'fulfillment_prep' assert action_presentation( 'retry_freight_upload_rpa', gate_code='freight_upload_rpa', - )['target_surface'] == 'upload_complete' + )['target_surface'] == 'freight_upload' assert action_presentation( 'regenerate_manual_upload_todo', gate_code='manual_upload_handoff', - )['target_surface'] == 'upload_complete' + )['target_surface'] == 'freight_upload' assert action_presentation( 'mark_manual_uploaded', gate_code='manual_upload_handoff', - )['target_surface'] == 'upload_complete' + )['target_surface'] == 'freight_upload' def test_manual_upload_handoff_authorizes_excel_regeneration_at_artifact_anchor(): @@ -140,7 +150,7 @@ def test_gate_action_presentation_declares_ui_dispatch_without_frontend_action_c 'label_key': 'workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded', 'kind': 'current_gate', 'dispatch': 'dialog', - 'ui_handler': 'manual_upload_evidence', + 'ui_handler': 'manual_upload_confirmation', } assert action_presentation('confirm_customer') == { 'code': 'confirm_customer', @@ -187,61 +197,6 @@ def test_field_quality_block_eligibility(): assert field_quality_may_block(required=False, auto_create_key_field=False) is False -def test_projection_marks_apx_gate_as_readonly_without_executable_actions(app, monkeypatch): - """APX 历史 Gate 只可审计展示,不能再投影为可恢复业务 Gate。""" - from types import SimpleNamespace - from app.services.shipping_notice import process_gate_projection as projection - - gate = SimpleNamespace( - id=1, gate_code='inventory_candidates_calculated', sequence_no=1, - status='pending', evaluation_version=1, input_fingerprint=None, - blocking_reason_code=None, blocking_reason_json=None, - recommendation_json=None, effective_result_json={}, findings_json=None, - next_action_code=None, passed_at=None, invalidated_at=None, - latest_attempt_id=None, - ) - monkeypatch.setattr( - projection.ShippingProcessGateAttempt.query, - 'get', - lambda _id: None, - raising=False, - ) - payload = projection.serialize_process_gate(gate, include_diagnostics=False) - assert payload['gate_code'] == 'inventory_candidates_calculated' - assert payload['legacy_readonly'] is True - assert payload['allowed_actions'] == [] - assert payload['recovery_targets'] == [] - assert len(PROCESS_GATE_DEFINITIONS) == 20 - - -def test_user_gate_summary_marks_apx_execution_readonly(app, monkeypatch): - """APX Execution 不能向用户下发主动作或恢复目标。""" - from types import SimpleNamespace - from app.services.shipping_notice import process_gate_projection as projection - - execution = SimpleNamespace( - id=1, execution_no='APX-1', status='blocked', current_gate_code='inventory_candidates_calculated', - last_passed_gate_code=None, primary_next_action_code=None, responsible_party='system', - lock_version=1, review_case_id=None, task_id=1, updated_at=None, - ) - gate = SimpleNamespace( - id=1, gate_code='inventory_candidates_calculated', sequence_no=1, status='blocked_retryable', - evaluation_version=1, input_fingerprint=None, blocking_reason_code='inventory_candidates_required', - blocking_reason_json=None, recommendation_json=None, effective_result_json={}, - next_action_code=None, passed_at=None, invalidated_at=None, latest_attempt_id=None, - ) - query = projection.ShippingProcessGate.query - monkeypatch.setattr(query, 'filter_by', lambda **_kwargs: query) - monkeypatch.setattr(query, 'order_by', lambda *_args: query) - monkeypatch.setattr(query, 'all', lambda: [gate]) - monkeypatch.setattr(projection.ShippingProcessGateAttempt.query, 'get', lambda _id: None, raising=False) - summary = projection.project_user_gate_summary(execution) - assert summary['status'] == 'legacy_readonly' - assert summary['legacy_readonly'] is True - assert summary['next_action_code'] is None - assert summary['allowed_actions'] == [] - - def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technical(app, monkeypatch): """库存匹配技术重试被隐藏时,跨阶段 RecoveryPlan 仍必须保留人工复核入口。""" from types import SimpleNamespace @@ -488,6 +443,43 @@ def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch): assert summary['allowed_actions'] == ['retry_inventory_preparation'] +def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch): + """RPA 超时先重读已落盘结果,不能把主按钮直接指向新的 RPA 请求。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='EXE-INVENTORY-TIMEOUT', status='blocked', + current_gate_code='inventory_preparation', + primary_next_action_code='retry_inventory_preparation', + responsible_party='worker', lock_version=1, review_case_id=None, task_id=99, + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-INVENTORY-TIMEOUT', 'status': 'blocked', + 'primary_next_action_code': 'retry_inventory_preparation', + 'responsible_party': 'worker', 'recovery_targets': [], + 'active_recovery_plans': [], 'gates': [], + 'current_gate': { + 'gate_code': 'inventory_preparation', 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_rpa_timeout', + 'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 3, + }, + }, + ) + + summary = projection.project_user_gate_summary(execution) + + assert summary['next_action_code'] == 'reload_inventory_result' + assert summary['primary_action']['code'] == 'reload_inventory_result' + assert summary['allowed_actions'] == [ + 'reload_inventory_result', + 'retry_inventory_preparation', + ] + + def test_user_gate_summary_exposes_manual_gate_evidence_and_rpa_retry(app, monkeypatch): """Gate 20 保持凭据登记主动作,并显式下发可选 RPA 重试。""" from types import SimpleNamespace @@ -558,12 +550,12 @@ def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action( 'mark_manual_uploaded', 'retry_freight_upload_rpa', ] - assert summary['primary_action']['target_surface'] == 'upload_complete' + assert summary['primary_action']['target_surface'] == 'freight_upload' assert summary['primary_action']['target_anchor'] == 'manual_upload' -def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, monkeypatch): - """跨 Gate Excel 恢复必须采用 RecoveryPlan 的位置,不能继承 Gate 20 的上传位置。""" +def test_manual_upload_handoff_hides_excel_regeneration_for_single_notice(app, monkeypatch): + """同一 Notice 只能有一个 Excel,上传阶段不得投影重生入口。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection @@ -588,16 +580,10 @@ def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, m }, }, ) - monkeypatch.setattr(projection, '_excel_regeneration_allowed', lambda **_: True) - summary = projection.project_user_gate_summary(execution) - regeneration = next( - item for item in summary['action_presentation'] - if item['code'] == 'regenerate_excel_artifact' - ) - assert regeneration['target_surface'] == 'fulfillment_prep' - assert regeneration['target_anchor'] == 'excel_artifact' + assert 'regenerate_excel_artifact' not in summary['allowed_actions'] + assert all(item['code'] != 'regenerate_excel_artifact' for item in summary['action_presentation']) def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, monkeypatch): diff --git a/backend/tests/test_shipping_process_gate_recovery_action_contract.py b/backend/tests/test_shipping_process_gate_recovery_action_contract.py index 9a00ee8f..7f7dc663 100644 --- a/backend/tests/test_shipping_process_gate_recovery_action_contract.py +++ b/backend/tests/test_shipping_process_gate_recovery_action_contract.py @@ -1,10 +1,9 @@ """ tests/test_shipping_process_gate_recovery_action_contract.py -用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 失败统一下发 -「重新获取库存」(retry_inventory_preparation),不再因 inventory_preparation -Gate 的 responsible_party='worker' 被历史「worker/retry_ 技术动作屏蔽」规则 -降级为人工上传入口 (upload_inventory_file)。 +用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 超时/耗尽优先下发 +「重新读取库存结果」(reload_inventory_result),其他失败下发「重新获取库存」 +(retry_inventory_preparation),不再被历史 worker 技术动作屏蔽规则降级为人工上传入口。 依赖:process_gate_projection._resolve_recovery_next_action。 逻辑:pure_unit 纯单测(不建 Flask/DB);以阻断原因码 / Gate 状态为输入, @@ -59,12 +58,10 @@ def test_inventory_file_empty_blocked_manual_resolves_to_retry(): @pytest.mark.parametrize('reason', [ 'inventory_file_empty', 'inventory_preparation_failed', - 'inventory_rpa_timeout', 'inventory_rpa_login_failed', 'inventory_rpa_export_failed', 'inventory_file_identity_mismatch', 'inventory_file_missing', - 'inventory_rpa_exhausted', ]) def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason): """全部库存 RPA 失败原因(无论 blocked_manual / blocked_retryable)均下发「重新获取库存」。""" @@ -79,14 +76,15 @@ def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason): @pytest.mark.pure_unit -def test_inventory_rpa_exhausted_falls_back_to_manual_upload(): - """历史耗尽码仍允许用户手动重新获取库存。""" +@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted']) +def test_inventory_rpa_timeout_or_exhausted_prefers_reload_existing_result(reason): + """超时或耗尽先重读已有结果,不能直接新开 RPA Attempt。""" full, blocking = _mk( {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', - 'blocking_reason_code': 'inventory_rpa_exhausted'}, + 'blocking_reason_code': reason}, ) action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) - assert action == 'retry_inventory_preparation' + assert action == 'reload_inventory_result' @pytest.mark.pure_unit @@ -225,6 +223,84 @@ def test_inventory_preparation_waiting_keeps_refresh_action(): assert action == 'poll_inventory_preparation' +def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, monkeypatch): + """重新读取库存结果只复用快照,不能触发新的库存 RPA。""" + from app.models import ShippingNotice + from app.services.shipping_notice import process_gate_executor as executor + + task = SimpleNamespace(task_no='SN-RELOAD-1') + execution = SimpleNamespace(task_id=7) + calls: list[tuple[str, object]] = [] + monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', + lambda _task: {'source_code': 'DSV360_AWSDU'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot', + lambda received_task, source, *, mode: calls.append((mode, (received_task, source))) or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa', + lambda *_args, **_kwargs: pytest.fail('reload must not trigger RPA'), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_rpa_timeout', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_kwargs: calls.append(('sync', _kwargs)), + ) + + with app.app_context(): + outcome = executor._handle_reload_inventory_result( + execution=execution, + gate=SimpleNamespace(gate_code='inventory_preparation'), + payload={'actor_user_id': 3}, + ) + + assert outcome['outcome'] == 'passed' + assert calls[0][0] == 'reload_result' + assert calls[1][0] == 'sync' + + +def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app, monkeypatch): + """无可复用快照时保持超时阻断,不能隐式改为重新触发 RPA。""" + from app.models import ShippingNotice + from app.services.shipping_notice import process_gate_executor as executor + + task = SimpleNamespace(task_no='SN-RELOAD-MISSING') + execution = SimpleNamespace(task_id=7) + monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', + lambda _task: {'source_code': 'DSV360_AWSDU'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot', + lambda *_args, **_kwargs: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa', + lambda *_args, **_kwargs: pytest.fail('reload must not trigger RPA'), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_rpa_timeout', + ) + + with app.app_context(): + outcome = executor._handle_reload_inventory_result( + execution=execution, + gate=SimpleNamespace(gate_code='inventory_preparation'), + payload={}, + ) + + assert outcome['outcome'] == 'blocked_retryable' + assert outcome['blocking_reason_code'] == 'inventory_rpa_timeout' + + @pytest.mark.pure_unit def test_no_blocking_returns_no_action(): """无当前阻断时不下发给任何主恢复动作。""" diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 5ef1baf3..d2481cf2 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -998,41 +998,6 @@ def test_legacy_workspace_forwarding_audit_is_structured(app): } -def test_apx_runtime_audit_is_read_only_and_counts_active_states(app): - """APX 清点只读统计运行中记录,不修改历史 Execution/Job。""" - from app import db - from app.models import Job, ShippingNotice, ShippingProcessExecution - from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state - - task = ShippingNotice(task_no='SN-APX-AUDIT') - db.session.add(task) - db.session.flush() - active = ShippingProcessExecution( - execution_no='APX-20260811-ACTIVE', task_id=task.id, status='active', - current_gate_code='inventory_snapshots_ready', - ) - historical = ShippingProcessExecution( - execution_no='APX-20260811-HIST', task_id=task.id, status='completed', - current_gate_code='inventory_matched', - ) - db.session.add_all([active, historical]) - db.session.flush() - job = Job( - domain='shipping_notice', job_type='shipping_auto_progress', task_id=task.id, - execution_id=active.id, status='queued', business_ref='APX-20260811-ACTIVE', - ) - db.session.add(job) - db.session.commit() - - result = audit_apx_runtime_state() - - assert result['execution']['active_count'] == 1 - assert result['execution']['historical_count'] == 1 - assert result['job']['active_count'] == 1 - assert ShippingProcessExecution.query.filter_by(id=active.id).one().status == 'active' - assert Job.query.filter_by(id=job.id).one().status == 'queued' - - def test_inventory_mapping_is_versioned_and_immutable_by_shape(): """Mapping 必须按文件+版本唯一,旧版本通过 superseded_by_id 留谱系。""" assert 'uq_shipping_inventory_mapping_file_version' in _unique_names(ShippingInventoryMapping) @@ -1117,71 +1082,48 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan(): assert plan.completed_at is not None -def test_excel_regeneration_completion_preserves_manual_upload_gate(): - """跨 Gate Excel 重生完成后,当前 Gate 20 必须继续等待人工上传且计划可关闭。""" - from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt - - class Plan: - status = 'queued' - action_code = 'regenerate_excel_artifact' - resume_after_gate = 'manual_upload_handoff' - started_at = None - completed_at = None - failure_code = None - failure_detail_json = None - - plan = Plan() - complete_recovery_plan_for_attempt( - plan=plan, - outcome='blocked_manual', - business_result_code='manual_upload_pending', - ) - - assert plan.status == 'succeeded' - assert plan.completed_at is not None - - -def test_manual_upload_excel_regeneration_returns_to_manual_handoff(monkeypatch): - """Gate 20 触发 Excel 重生后,执行器必须作废旧产物并保持人工上传阻断。""" +def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch): + """已有 Excel 时不能在同一 Notice 重生,必须创建新的 Notice。""" from types import SimpleNamespace + from app.models import ShippingExportArtifact, ShippingNotice from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel - invalidated = {} + task = SimpleNamespace(id=1, task_no='SN-ONE-EXCEL') + monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) monkeypatch.setattr( - 'app.services.shipping_notice.recovery_invalidation_service.invalidate_excel_regeneration_only', - lambda **kwargs: invalidated.update(kwargs) or {'artifacts': [10], 'uploads': [11]}, + ShippingExportArtifact, + 'query', + SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=10))), ) monkeypatch.setattr( 'app.services.shipping_notice.fulfillment_workflow.generate_excel', - lambda _payload: {'status': 'ok'}, - ) - monkeypatch.setattr( - 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', - lambda **_: None, - ) - monkeypatch.setattr( - 'app.services.shipping_notice.process_gate_executor._task_payload', - lambda _execution, _payload: {'_orchestrator_internal_dispatch': True}, + lambda _payload: pytest.fail('existing Artifact must not be regenerated'), ) outcome = _handle_regenerate_excel( execution=SimpleNamespace(execution_no='SPE-EXCEL-HANDOFF', task_id=1), gate=SimpleNamespace(gate_code='manual_upload_handoff'), - payload={'attempt_id': 3, 'actor_user_id': 9}, + payload={'actor_user_id': 9}, ) - assert invalidated['attempt_id'] == 3 assert outcome['outcome'] == 'blocked_manual' - assert outcome['blocking_reason_code'] == 'manual_upload_pending' - assert outcome['output_snapshot']['invalidation']['artifacts'] == [10] + assert outcome['blocking_reason_code'] == 'notice_excel_already_generated' def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch): """Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。""" from types import SimpleNamespace + from app.models import ShippingExportArtifact, ShippingNotice from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel synced = [] + task = SimpleNamespace(id=1, task_no='SN-FIRST-EXCEL') + monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr( + ShippingExportArtifact, + 'query', + SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: None)), + ) monkeypatch.setattr( 'app.services.shipping_notice.fulfillment_workflow.generate_excel', lambda _payload: {'status': 'failed', 'message': 'template unavailable'}, diff --git a/backend/tests/test_shipping_processing_projection_invariants.py b/backend/tests/test_shipping_processing_projection_invariants.py index a081089d..4ce0ce9d 100644 --- a/backend/tests/test_shipping_processing_projection_invariants.py +++ b/backend/tests/test_shipping_processing_projection_invariants.py @@ -108,7 +108,7 @@ def test_inventory_shortage_gate_projects_a_user_visible_blocking_reason(): def test_normalize_unknown_action_codes(): """未知 / 别名动作码映射到契约或丢弃。""" - assert normalize_action_code('retry_failed_documents') == 'retry' + assert normalize_action_code('retry_failed_documents') == 'retry_failed_documents' assert normalize_action_code('open_fulfillment') == 'view_result' assert normalize_action_code('not_a_real_action') is None @@ -165,7 +165,10 @@ def test_download_excel_requires_excel_ready_fact(): with_ready = derive_available_actions( status='blocked', stage='freight_uploading', - gate={'next_action_code': 'wait_manual_upload'}, + gate={ + 'gate_code': 'manual_upload_handoff', + 'next_action_code': 'wait_manual_upload', + }, excel_ready=True, ) assert 'download_excel' in with_ready @@ -223,9 +226,11 @@ def test_map_notice_to_processing_status_stage_domain_mapping(): ) uploaded = SimpleNamespace( + id=None, current_step='', upload_status='uploaded', export_file_path=None, ) - assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed') + # 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。 + assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading') waiting = SimpleNamespace( current_step='', upload_status='pending', export_file_path='/x.xlsx', @@ -254,8 +259,8 @@ def test_map_notice_unknown_status_fail_closed(): assert map_notice_to_processing_status_stage(unknown) == ('blocked', 'waiting_review') -def test_derive_available_actions_blocked_without_retry_gate(): - """BE-04: business blocked without retry Gate must not append retry.""" +def test_derive_available_actions_without_gate_fails_closed(): + """BE-04: no Gate and no object authorization must not invent an action.""" from app.services.shipping_notice.processing_projection_invariants import ( derive_available_actions, ) @@ -270,12 +275,11 @@ def test_derive_available_actions_blocked_without_retry_gate(): }, excel_ready=False, ) - assert 'retry' not in actions - assert 'open_inventory_source_review' in actions + assert actions == [] -def test_derive_available_actions_failed_adds_retry(): - """BE-04: technical failed should allow retry by default.""" +def test_derive_available_actions_failed_without_gate_does_not_add_retry(): + """BE-04: failed status alone cannot authorize a generic retry.""" from app.services.shipping_notice.processing_projection_invariants import ( derive_available_actions, ) @@ -286,7 +290,7 @@ def test_derive_available_actions_failed_adds_retry(): gate=None, excel_ready=False, ) - assert 'retry' in actions + assert actions == ['view_result'] def test_retryable_projection_uses_technical_failure_reason_mapping(): @@ -475,8 +479,8 @@ def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action(): assert payload['available_actions'] == ['retry_inventory_preparation'] -def test_waiting_human_reconcile_action_uses_projected_available_actions(): - """人工阻断存在统一对账动作时,主动作必须从当前投影动作列表中安全选取。""" +def test_waiting_human_reconcile_action_uses_gate_action(): + """人工阻断的统一对账动作必须由正式 Gate 明确下发。""" payload = apply_user_projection_fields({ 'status': 'waiting_review', 'stage': 'inventory_matching', @@ -484,11 +488,12 @@ def test_waiting_human_reconcile_action_uses_projected_available_actions(): 'gate_code': 'inventory_candidates_calculated', 'status': 'blocked', 'blocking_reason_code': 'inventory_candidates_required', + 'next_action_code': 'reconcile_and_progress', }, - 'available_actions': ['reconcile_and_progress', 'view_details'], + 'available_actions': ['view_details'], }) - # 关键断言:该分支不得因未定义局部变量返回 500,且必须选中统一恢复入口。 + # 关键断言:只能选中 Gate 明示的统一恢复入口。 assert payload['user_status'] == 'waiting_human' assert payload['primary_action']['code'] == 'reconcile_and_progress' diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index a098e04f..02ff2c1d 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -27,6 +27,10 @@ from app.models import ( ShippingOrderCandidate, ShippingOrderProcessingUnit, ShippingOrderSubmission, + ShippingOrderTask, + ShippingNotice, + ShippingProcessExecution, + ShippingProcessGate, User, ) from app.services.file_assets.service import upload_file_asset @@ -34,10 +38,13 @@ from app.services.shipping_notice.intake_service import create_shipping_notice_i from app.services.shipping_notice.progress_audit_contract import ( DIRECT_PDF_ALLOWED_STAGES, ) +from app.services.shipping_notice.reconciliation_projector import ( + project_case_primary_action, +) from app.services.shipping_notice.shipping_processing_projection import ( _aggregate_eml_order_task_work_items, _batch_file_counts, - _batch_four_stage_nodes, + _batch_lifecycle_nodes, _batch_ui_state_from_items, _conversation_processing_from_work_items, _display_work_items_from_current_files, @@ -45,6 +52,7 @@ from app.services.shipping_notice.shipping_processing_projection import ( _processing_ui_state_from_item, _project_order_task_work_item, map_run_status_to_processing_status, + project_conversation_processing_summary, map_run_to_processing_stage, project_conversation_processing_items, project_intake_work_item, @@ -94,28 +102,58 @@ def test_map_run_status_to_processing_status() -> None: assert map_run_status_to_processing_status('unknown') == 'processing' +def test_waiting_human_case_promotes_authorized_create_draft_as_primary_action() -> None: + """待人工的无草稿文件必须下发创建草稿,作为文件行唯一业务入口。""" + action = project_case_primary_action( + 'waiting_human', + {'code': None, 'i18n_key': None, 'details': None}, + ['view', 'create_draft', 'validate'], + 'order_review', + ) + + # 已授权的下一项业务操作不能被裁决为空,否则文件行没有可执行入口。 + assert action == { + 'code': 'create_draft', + 'variant': 'primary', + 'label_key': 'shipping.actions.create_draft', + } + + +def test_waiting_human_case_promotes_authorized_edit_draft_as_primary_action() -> None: + """待人工的已有草稿文件必须下发编辑草稿,而不是重复阶段导航。""" + action = project_case_primary_action( + 'waiting_human', + {'code': None, 'i18n_key': None, 'details': None}, + ['view', 'edit_draft', 'validate'], + 'order_review', + ) + + # 编辑草稿是当前文件的业务入口,validate 仍留在工作台底栏执行。 + assert action == { + 'code': 'edit_draft', + 'variant': 'primary', + 'label_key': 'shipping.actions.edit_draft', + } + + @pytest.mark.parametrize( - ('stage', 'expected_lifecycle_stage'), + ('gate_code', 'expected_lifecycle_stage'), [ ('inventory_preparation', 'fulfillment_prep'), - ('inventory_candidates_calculated', 'fulfillment_prep'), - ('inventory_candidates_frozen', 'fulfillment_prep'), - ('inventory_snapshots_ready', 'fulfillment_prep'), - ('inventory_matched', 'fulfillment_prep'), - ('excel_generated', 'fulfillment_prep'), - ('upload_receipt_recorded', 'upload_complete'), + ('inventory_matching', 'fulfillment_prep'), + ('artifact_generation', 'fulfillment_prep'), + ('freight_upload_rpa', 'freight_upload'), ], ) -def test_batch_four_stage_nodes_maps_auto_progress_gate_stages( - stage: str, +def test_batch_lifecycle_nodes_maps_formal_gate_stages( + gate_code: str, expected_lifecycle_stage: str, ) -> None: - """自动推进 Gate 的真实阶段码必须归入对应四阶段,不能回退到接收解析。""" - nodes = _batch_four_stage_nodes([{ - 'stage': stage, - 'user_stage': stage, + """正式 Gate 必须归入对应五阶段,不能依赖历史技术阶段码。""" + nodes = _batch_lifecycle_nodes([{ 'status': 'running', 'user_status': 'running', + 'current_gate': {'gate_code': gate_code}, }]) summaries = {node['code']: node['summary']['total'] for node in nodes} @@ -126,28 +164,19 @@ def test_batch_four_stage_nodes_maps_auto_progress_gate_stages( @pytest.mark.parametrize( ('item', 'expected_lifecycle_stage'), [ - ({'user_stage': 'inventory_match'}, 'fulfillment_prep'), - ({'user_stage': 'freight_upload'}, 'upload_complete'), - ({'user_stage': 'customer_resolving'}, 'order_review'), - ({'user_stage': 'duplicate_checking'}, 'order_review'), - ({'user_stage': 'waiting_human_review'}, 'order_review'), - # Case bundle 已归一化为业务阶段时,批次摘要与生命周期入口必须直接识别, - # 不能错误落入 unclassified 并禁用订单复核入口。 - ({'user_stage': 'order_review'}, 'order_review'), # 正式 Gate 是当前业务位置,必须覆盖尚未同步的历史技术 stage。 ({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'fulfillment_prep'), - ({'stage': 'document_parsing', 'user_current_gate_code': 'inventory_matching'}, 'fulfillment_prep'), # 无 Gate 时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段。 ({'blocking_reason': {'code': 'inventory_file_missing'}}, 'fulfillment_prep'), ({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'), ], ) -def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases( +def test_batch_lifecycle_nodes_uses_formal_gate_or_owning_reason( item: dict[str, object], expected_lifecycle_stage: str, ) -> None: - """批次四阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。""" - nodes = _batch_four_stage_nodes([{ + """批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。""" + nodes = _batch_lifecycle_nodes([{ **item, 'status': 'waiting_human', 'user_status': 'waiting_human', @@ -158,6 +187,42 @@ def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliase assert summaries['intake_parse'] == (1 if expected_lifecycle_stage == 'intake_parse' else 0) +def test_batch_lifecycle_nodes_without_formal_fact_is_unclassified() -> None: + """未知旧阶段保持未分类,不能凭空映射到某个业务工作面。""" + nodes = _batch_lifecycle_nodes([{ + 'status': 'waiting_human', + 'user_status': 'waiting_human', + 'user_stage': 'inventory_match', + }]) + + assert all(node['summary']['total'] == 0 for node in nodes) + + +@pytest.mark.parametrize( + ('user_stage', 'expected_lifecycle_stage'), + [ + ('candidate_creating', 'intake_parse'), + ('waiting_review', 'order_review'), + ('inventory_preparation', 'fulfillment_prep'), + ('manual_upload_handoff', 'freight_upload'), + ], +) +def test_batch_lifecycle_nodes_maps_persisted_processing_stages( + user_stage: str, + expected_lifecycle_stage: str, +) -> None: + """无 Gate 的当前文件仍须按已写入阶段完整归入五阶段,不能静默丢失。""" + nodes = _batch_lifecycle_nodes([{ + 'status': 'waiting_human', + 'user_status': 'waiting_human', + 'user_stage': user_stage, + }]) + + summaries = {node['code']: node['summary']['total'] for node in nodes} + assert summaries[expected_lifecycle_stage] == 1 + assert sum(summaries.values()) == 1 + + def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> None: """通知准备未完成时通知完成必须由后端裁决为不可进入,不能由前端自行限制。""" fulfillment_state = _processing_ui_state_from_item({ @@ -177,6 +242,7 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N {'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'order_review', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'fulfillment_prep', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, + {'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, ] assert fulfillment_state['primary_action']['execution_mode'] == 'navigate' @@ -201,40 +267,6 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N 'target_lifecycle_stage': 'fulfillment_prep', }] - legacy_view_state = _processing_ui_state_from_item({ - 'user_status': 'waiting_human', - 'user_stage': 'waiting_review', - 'source_summary': {'candidate_count': 1}, - 'run_no': 'SNER-LIFECYCLE-VIEW', - 'case_no': 'SNRC-LIFECYCLE-VIEW', - 'root_order_task_no': 'OT-LIFECYCLE-VIEW', - # 历史 Review 投影仍可能下发 view;它与 view_result 一样只是后端已授权的查看入口。 - 'available_actions': ['view'], - }) - assert legacy_view_state['secondary_actions'] == [{ - 'code': 'view', - 'enabled': True, - 'execution_mode': 'navigate', - 'target_surface': 'order_lifecycle_workbench', - 'target_lifecycle_stage': 'order_review', - }] - - review_state = _processing_ui_state_from_item({ - 'user_status': 'waiting_human', - 'user_stage': 'waiting_review', - 'source_summary': {'candidate_count': 1}, - 'run_no': 'SNER-REVIEW', - 'case_no': 'SNRC-REVIEW', - 'root_order_task_no': 'OT-REVIEW', - 'available_actions': [], - }) - assert review_state['lifecycle_entries'] == [ - {'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, - {'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, - {'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, - {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, - ] - def test_processing_ui_state_exposes_shared_gate_authority() -> None: """批次投影须标明正式 Gate 裁决,不能让旧 technical stage 覆盖库存准备阶段。""" @@ -358,6 +390,33 @@ def test_failed_run_overrides_stale_unit_review_stage_for_eml_leaf(app) -> None: assert leaves[0]['primary_action'] is None +def test_eml_leaf_preserves_case_business_action_instead_of_replacing_it_with_navigation(app) -> None: + """EML 文件行必须保留 Case 裁决的真实动作,五阶段入口已单独承担导航。""" + from tests.test_shipping_order_extraction_runs import _seed_run_input + + with app.app_context(): + _user, _agent, _session, intake, document = _seed_run_input(suffix='EML-KEEP-ACTION') + + leaves = _eml_aggregate_document_children( + intake=intake, + order_task_children=[{ + 'work_item_type': 'order_task', + 'work_item_no': 'DOCUMENT:KEEP-ACTION', + 'case_no': 'SORC-KEEP-ACTION', + 'current_gate': {'gate_code': 'order_review_build'}, + 'primary_action': { + 'code': 'create_draft', + 'variant': 'primary', + 'label_key': 'shipping.actions.create_draft', + }, + 'available_actions': ['create_draft'], + 'source_summary': {'document_id': document.id}, + }], + ) + + assert leaves[0]['primary_action']['code'] == 'create_draft' + + def test_intake_candidate_context_ignores_superseded_candidate(app) -> None: """历史 Candidate 只能审计,不能重新打开当前文件的生命周期入口。""" with app.app_context(): @@ -478,42 +537,47 @@ def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(ap def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_summary() -> None: - """四阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。""" + """五阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。""" projection = _conversation_processing_from_work_items([ { - 'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW', - 'root_order_task_no': 'OT-REVIEW', 'source_type': 'direct_pdf', - 'source_summary': {'document_id': 1, 'filename': 'review.pdf'}, - 'user_status': 'waiting_human', 'user_stage': 'waiting_review', + 'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW', + 'root_order_task_no': 'OT-REVIEW', 'source_type': 'direct_pdf', + 'source_summary': {'document_id': 1, 'filename': 'review.pdf'}, + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', 'user_stage': 'order_review', + 'current_gate': {'gate_code': 'field_completeness', 'status': 'blocked'}, 'blocking_reason': {'code': 'order_review_required'}, 'available_actions': [], }, { 'work_item_type': 'order_task', 'work_item_no': 'OT-UNKNOWN', - 'root_order_task_no': 'OT-UNKNOWN', 'source_type': 'direct_pdf', - 'source_summary': {'document_id': 2, 'filename': 'unknown.pdf'}, - 'user_status': 'running', 'user_stage': 'unmapped_legacy_stage', + 'root_order_task_no': 'OT-UNKNOWN', 'source_type': 'direct_pdf', + 'source_summary': {'document_id': 2, 'filename': 'unknown.pdf'}, + 'user_group': 'unclassified', + 'user_status': 'running', 'user_stage': 'unmapped_legacy_stage', 'available_actions': [], }, ]) - nodes = {node['code']: node for node in projection['four_stage_nodes']} + nodes = {node['code']: node for node in projection['lifecycle_nodes']} assert nodes['order_review']['status'] == 'blocked' assert nodes['intake_parse']['status'] == 'pending' assert projection['unclassified_summary'] == {'count': 1} -def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None: - """同一 EML 的两份订单 PDF 应在四阶段摘要中计为两项,而非一张父卡。""" - nodes = _batch_four_stage_nodes([{ +def test_batch_lifecycle_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None: + """同一 EML 的两份订单 PDF 应在五阶段摘要中计为两项,而非一张父卡。""" + nodes = _batch_lifecycle_nodes([{ 'work_item_type': 'order_task', 'work_item_no': 'INTAKE:SNI-DOUBLE', 'source_type': 'eml', + 'user_group': 'waiting_human', 'user_status': 'waiting_human', 'user_stage': 'order_review', 'aggregate_children': [ { 'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-1', + 'user_group': 'waiting_human', 'user_status': 'waiting_human', 'user_stage': 'order_review', 'current_gate': {'gate_code': 'field_completeness'}, 'blocking_reason': {'code': 'required_field_missing'}, @@ -521,6 +585,7 @@ def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_roo }, { 'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-2', + 'user_group': 'waiting_human', 'user_status': 'waiting_human', 'user_stage': 'order_review', 'current_gate': {'gate_code': 'field_completeness'}, 'blocking_reason': {'code': 'required_field_missing'}, @@ -535,19 +600,21 @@ def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_roo assert order_review['summary']['needs_action'] == 2 -def test_batch_four_stage_nodes_deduplicates_a_document_to_its_latest_projection() -> None: +def test_batch_lifecycle_nodes_deduplicates_a_document_to_its_latest_projection() -> None: """同一 PDF 的历史失败投影不能与当前通知准备投影重复计数或覆盖当前阶段。""" - nodes = _batch_four_stage_nodes([ - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-OLD', - 'user_status': 'failed', 'user_stage': 'document_parsing', + nodes = _batch_lifecycle_nodes([ + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-OLD', + 'user_group': 'failed', + 'user_status': 'failed', 'user_stage': 'document_parsing', 'last_activity_at': '2026-08-15T09:00:00Z', 'blocking_reason': {'code': 'intake_parse_failed'}, 'source_summary': {'document_id': 401, 'filename': 'same.pdf'}, }, - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT', - 'user_status': 'waiting_human', 'user_stage': 'inventory_matching', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT', + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', 'user_stage': 'inventory_matching', 'last_activity_at': '2026-08-15T10:00:00Z', 'blocking_reason': {'code': 'inventory_match_failed'}, 'source_summary': {'document_id': 401, 'filename': 'same.pdf'}, @@ -565,15 +632,17 @@ def test_batch_four_stage_nodes_deduplicates_a_document_to_its_latest_projection def test_batch_file_counts_uses_the_same_current_file_representative_as_stage_summary() -> None: """同一 PDF 的历史失败项不能同时计入失败和当前处理中的文件数量。""" work_items = [ - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-OLD', - 'user_status': 'failed', 'user_stage': 'document_parsing', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-OLD', + 'user_group': 'failed', + 'user_status': 'failed', 'user_stage': 'document_parsing', 'last_activity_at': '2026-08-15T09:00:00Z', 'source_summary': {'document_id': 501, 'filename': 'same.pdf'}, }, - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT', - 'user_status': 'waiting_human', 'user_stage': 'inventory_matching', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT', + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', 'user_stage': 'inventory_matching', 'last_activity_at': '2026-08-15T10:00:00Z', 'source_summary': {'document_id': 501, 'filename': 'same.pdf'}, }, @@ -593,15 +662,16 @@ def test_batch_stage_summary_uses_the_same_user_group_as_file_counts() -> None: work_items = [{ 'work_item_type': 'order_task', 'work_item_no': 'OT-GROUP-OVERRIDES-STATUS', - 'user_group': 'waiting_human', - 'user_status': 'running', - 'user_stage': 'inventory_matching', + 'user_group': 'waiting_human', + 'user_status': 'running', + 'user_stage': 'inventory_matching', + 'current_gate': {'gate_code': 'inventory_matching', 'status': 'blocked'}, 'source_summary': {'document_id': 502, 'filename': 'waiting.pdf'}, }] assert _batch_file_counts(work_items)['waiting_human_files'] == 1 fulfillment = next( - node for node in _batch_four_stage_nodes(work_items) + node for node in _batch_lifecycle_nodes(work_items) if node['code'] == 'fulfillment_prep' ) assert fulfillment['summary']['needs_action'] == 1 @@ -632,6 +702,35 @@ def test_conversation_status_groups_use_the_same_current_file_representative() - ] +@pytest.mark.parametrize('terminal_status', ['cancelled', 'archived']) +def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metrics( + app, + terminal_status: str, +) -> None: + """取消或归档仅保留历史,不得进入会话完成、文件完成或第五阶段统计。""" + with app.app_context(): + work_items = [{ + 'work_item_type': 'order_task', + 'work_item_no': f'OT-{terminal_status.upper()}', + 'user_group': terminal_status, + 'user_status': terminal_status, + 'user_stage': 'freight_uploading', + 'status': terminal_status, + 'stage': terminal_status, + 'source_summary': {'document_id': 570, 'filename': 'history.pdf'}, + }] + projection = _conversation_processing_from_work_items(work_items) + assert projection['summary']['completed'] == 0 + assert projection['summary']['history'] == 1 + assert projection['summary']['total_files'] == 0 + assert projection['summary']['completed_files'] == 0 + assert projection['status_groups']['completed'] == [] + assert [row['user_task_no'] for row in projection['status_groups'][terminal_status]] == [ + f'OT-{terminal_status.upper()}', + ] + assert all(node['summary']['total'] == 0 for node in projection['lifecycle_nodes']) + + def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> None: """历史失败项不得在互斥统计后仍抢走批次当前按钮。""" work_items = [ @@ -667,17 +766,19 @@ def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> def test_batch_file_counts_deduplicates_reparse_versions_by_content_hash() -> None: """重解析产生新 document_id 时,内容哈希相同的 PDF 仍只计当前一项。""" work_items = [ - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-V1', - 'user_status': 'failed', 'user_stage': 'document_parsing', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-V1', + 'user_group': 'failed', + 'user_status': 'failed', 'user_stage': 'document_parsing', 'last_activity_at': '2026-08-15T09:00:00Z', 'source_summary': { 'document_id': 601, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64, }, }, - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-V2', - 'user_status': 'waiting_human', 'user_stage': 'order_review', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-V2', + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', 'user_stage': 'order_review', 'last_activity_at': '2026-08-15T10:00:00Z', 'source_summary': { 'document_id': 602, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64, @@ -694,6 +795,7 @@ def test_batch_file_counts_prefers_content_hash_over_different_root_document_ids work_items = [ { 'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V1', + 'user_group': 'failed', 'user_status': 'failed', 'user_stage': 'document_parsing', 'last_activity_at': '2026-08-15T09:00:00Z', 'source_summary': { @@ -703,6 +805,7 @@ def test_batch_file_counts_prefers_content_hash_over_different_root_document_ids }, { 'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V2', + 'user_group': 'waiting_human', 'user_status': 'waiting_human', 'user_stage': 'order_review', 'last_activity_at': '2026-08-15T10:00:00Z', 'source_summary': { @@ -997,8 +1100,139 @@ def test_eml_order_intake_uses_latest_run_unit_review_outcome_without_order_task assert all(child['user_status'] == 'waiting_human' for child in item['aggregate_children']) +def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_counts(app) -> None: + """未知支撑附件没有 Candidate、Case、OT 时不得进入五阶段或业务文件统计。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, primary_document = _seed_run_input( + suffix='SUMMARY-SUPPORTING-ATTACHMENT', + ) + intake.source_type = 'eml' + supporting_document = ShippingOrderDocument( + intake_id=intake.id, + document_type='attachment', + attachment_key='po-info.xlsx', + filename='PO_INFO.xlsx', + content_hash='s' * 64, + classification='unknown', + parse_status='empty', + order_extraction_status='completed', + ) + db.session.add(supporting_document) + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + leaves = [ + child + for rows in payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + ] + + # 关键断言:仅验证支撑附件已被排除;主业务文档的当前阶段可随解析状态演进。 + assert int(primary_document.id) in { + int(child['source_summary']['document_id']) for child in leaves + } + assert int(supporting_document.id) not in { + int(child['source_summary']['document_id']) for child in leaves + } + + +def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app) -> None: + """首屏摘要必须下发四个文件状态数,避免概览总数与状态数来自不同合同。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-FILE-STATUS-COUNTS', + ) + intake.source_type = 'eml' + document.order_extraction_status = 'failed' + document.order_extraction_error_code = 'processing_failed' + db.session.commit() + + summary = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + )['conversation_processing']['summary'] + + # 关键断言:总文件与四个互斥状态数同源,批次概览不能因缺字段降为全 0。 + assert summary['total_files'] == 1 + assert summary['failed_files'] == 1 + assert summary['waiting_human_files'] == 0 + assert summary['processing_files'] == 0 + assert summary['completed_files'] == 0 + + +def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None: + """摘要必须以正式库存 Gate 覆盖旧 OT completed,不能误显示为货代上传。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-FORMAL-GATE-OVERRIDE', + ) + candidate = ShippingOrderCandidate( + candidate_no='CAND-SUMMARY-GATE', intake_id=intake.id, + primary_document_id=document.id, candidate_key='summary-gate', + candidate_status='accepted', po_number='PO-SUMMARY-GATE', + ) + db.session.add(candidate) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-SUMMARY-GATE', user_id=user.id, conversation_id=session.session_id, + intake_id=intake.id, candidate_id=candidate.id, status='completed', stage='completed', + ) + db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-SUMMARY-GATE', user_id=user.id, conversation_id=session.session_id, + order_task_id=order_task.id, + ) + db.session.add(notice) + db.session.flush() + order_task.shipping_notice_id = notice.id + execution = ShippingProcessExecution( + execution_no='SPE-SUMMARY-GATE', task_id=notice.id, status='blocked', + current_gate_code='inventory_preparation', lock_version=1, + ) + db.session.add(execution) + db.session.flush() + notice.active_process_execution_id = execution.id + db.session.add(ShippingProcessGate( + execution_id=execution.id, gate_code='inventory_preparation', sequence_no=11, + status='blocked_manual', evaluation_version=1, lock_version=1, + blocking_reason_code='inventory_rpa_timeout', + next_action_code='retry_inventory_preparation', + )) + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + leaves = [ + child + for rows in payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + ] + leaf = next(child for child in leaves if child['source_summary']['document_id'] == document.id) + + # 关键断言:正式 Gate 是阶段与用户状态真相,旧 OT completed 只能作为兼容字段。 + assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert leaf['user_status'] == 'waiting_human' + assert leaf['blocking_reason']['code'] == 'inventory_rpa_timeout' + # 摘要批次状态必须复用同一待人工叶子裁决,聊天卡不得显示成系统处理中。 + assert payload['conversation_processing']['ui_state']['status'] == 'waiting_human' + + def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -> None: - """待人工附件已有 Review Case 时,叶子 ui_state 必须给出进入订单处理动作。""" + """接收解析 Case 在详情与首屏摘要中均以重解析作为文件主动作。""" with app.app_context(): from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import _materialized_run @@ -1031,10 +1265,113 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) - {'code': 'intake_parse', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'order_review', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, + {'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, ] assert leaf['intake_parse_authorized'] is True + summary_payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + summary_leaf = next( + child + for rows in summary_payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + if child['source_summary']['document_id'] == unit.document_id + ) + + # 首屏摘要不得把阶段导航 open_order_review 冒充为业务主动作; + # 否则前端隐藏导航后,用户将失去真实的重解析入口。 + assert summary_leaf['ui_state']['primary_action']['code'] == 'reparse' + + +def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> None: + """首屏摘要有有效 Candidate 的当前 Case 必须保留复核业务动作。""" + with app.app_context(): + from app.services.shipping_notice.order_review_service import ensure_run_review_cases + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-CANDIDATE-EDIT-DRAFT', + ) + intake.source_type = 'eml' + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + candidate = ShippingOrderCandidate( + candidate_no='CAND-SUMMARY-EDIT-DRAFT', intake_id=intake.id, + primary_document_id=document.id, candidate_key='summary-edit-draft', + order_extraction_run_id=run.id, is_current_version=True, + candidate_status='accepted', po_number='PO-SUMMARY-EDIT-DRAFT', + ) + db.session.add(candidate) + db.session.flush() + review_case = ensure_run_review_cases(run=run)[0] + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + summary_leaf = next( + child + for rows in payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + if child['source_summary']['document_id'] == document.id + ) + + assert summary_leaf['case_no'] == review_case.case_no + # Draft 已存在时,文件行只能暴露当前订单复核的业务动作,不能回退成接收解析重试。 + assert summary_leaf['ui_state']['primary_action']['code'] == 'edit_draft' + assert 'edit_draft' in summary_leaf['available_actions'] + assert 'reparse' not in summary_leaf['available_actions'] + + +def test_summary_leaf_uses_current_review_case_run_for_intake_parse_navigation(app) -> None: + """摘要投影的接收解析深链必须把同一 Case 的 Run 一并下发。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit + + user, agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-CASE-RUN-ANCHOR', + ) + intake.source_type = 'eml' + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + unit = run.extraction_plan.units[0] + unit.status = 'review_required' + unit.reason_code = 'coordinate_evidence_unavailable' + run.status = 'review_required' + run.phase = 'review_required' + review_case = ensure_review_case_for_unit(run=run, unit=unit) + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + rows = [ + row + for group in payload['conversation_processing']['status_groups'].values() + for row in group + ] + task = next(row for row in rows if row['user_task_no'] == f'INTAKE:{intake.intake_no}') + leaf = next( + child for child in task['aggregate_children'] + if child['source_summary']['document_id'] == document.id + ) + + assert leaf['case_no'] == review_case.case_no + assert leaf['run_no'] == run.run_no + assert leaf['ui_state']['lifecycle_entries'][0] == { + 'code': 'intake_parse', + 'state': 'current', + 'target_surface': 'order_lifecycle_workbench', + } + def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None: """同一 Run 的失败 PDF 只能影响自身;两个待复核 PDF 仍必须保留后端裁决的入口。""" @@ -1172,7 +1509,7 @@ def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document def test_conversation_projection_is_the_complete_batch_display_source(app) -> None: - """会话投影一次下发分组、EML 子文件、四阶段及 UI 动作,前端无需二次裁决。""" + """会话投影一次下发分组、EML 子文件、五阶段及 UI 动作,前端无需二次裁决。""" with app.app_context(): items = _aggregate_eml_order_task_work_items([ { @@ -1183,10 +1520,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No 'source_summary': { 'document_id': 101, 'document_count': 1, 'filename': 'a.pdf', 'email_subject': 'FWD: Shanghai shipping notice', - }, - 'status': 'failed', 'stage': 'waiting_review', - 'user_status': 'failed', 'user_stage': 'waiting_review', - 'available_actions': ['retry_parse'], + }, + 'status': 'failed', 'stage': 'waiting_review', + 'user_group': 'failed', + 'user_status': 'failed', 'user_stage': 'waiting_review', + 'current_gate': {'gate_code': 'field_completeness'}, + 'available_actions': ['retry_parse'], 'primary_action': {'code': 'retry_parse'}, 'blocking_reason': {'code': 'intake_parse_failed'}, 'facts': {'upload_state': 'not_created'}, @@ -1199,10 +1538,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No 'source_summary': { 'document_id': 102, 'document_count': 1, 'filename': 'b.pdf', 'email_subject': 'FWD: Shanghai shipping notice', - }, - 'status': 'processing', 'stage': 'document_parsing', - 'user_status': 'running', 'user_stage': 'document_parsing', - 'available_actions': [], 'facts': {'upload_state': 'not_created'}, + }, + 'status': 'processing', 'stage': 'document_parsing', + 'user_group': 'processing', + 'user_status': 'running', 'user_stage': 'document_parsing', + 'current_gate': {'gate_code': 'document_parsing'}, + 'available_actions': [], 'facts': {'upload_state': 'not_created'}, }, ]) @@ -1216,7 +1557,7 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No assert failed[0]['ui_state']['primary_action'] == {'code': 'retry_parse'} assert projection['ui_state']['primary_action'] == {'code': 'retry_parse'} assert projection['summary']['total_files'] == 2 - assert projection['four_stage_nodes'][1] == { + assert projection['lifecycle_nodes'][1] == { 'code': 'order_review', 'label_key': 'order_review', 'status': 'blocked', 'summary': { 'total': 1, @@ -1260,7 +1601,8 @@ def test_eml_aggregate_action_uses_the_same_priority_as_its_status(app) -> None: 'last_activity_at': '2026-08-14T00:00:00Z', 'source_summary': {'document_id': 201, 'document_count': 1, 'filename': 'waiting.pdf'}, 'status': 'waiting_human', 'stage': 'waiting_review', - 'user_status': 'waiting_human', 'user_stage': 'waiting_review', + 'user_status': 'waiting_human', 'user_stage': 'order_review', + 'current_gate': {'gate_code': 'order_review', 'status': 'blocked'}, 'blocking_reason': {'code': 'customer_confirmation_required'}, 'primary_action': {'code': 'confirm_customer'}, 'available_actions': ['confirm_customer'], 'facts': {'upload_state': 'not_created'}, @@ -1597,6 +1939,66 @@ def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, s ) +def test_conversation_projection_prefetches_eml_attachments_once(app, shipping_user): + """同一会话多个 EML 应一次加载附件集合,避免按邮件重复查询 Document。""" + with app.app_context(): + conversation_id = f'conv-stage4-eml-prefetch-{uuid.uuid4().hex[:8]}' + intakes = [] + with patch('app.services.shipping_notice.intake_service.enqueue', return_value=9404): + for index in range(2): + created = create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=_upload_ready_asset( + shipping_user.id, + filename=f'mail-{index}.eml', + content=b'From: a@b.c\nSubject: PO\n\nbody', + ), + upload_batch_id=str(uuid.uuid4()), + conversation_id=conversation_id, + ) + intake = ShippingOrderIntake.query.filter_by( + intake_no=created['intake_no'], + ).one() + intake.source_type = 'eml' + intake.parse_status = 'consumed' + intake.order_extraction_status = 'partially_completed' + intakes.append(intake) + for index, intake in enumerate(intakes): + db.session.add_all([ + ShippingOrderDocument( + intake_id=int(intake.id), document_type='email_body', + attachment_key='__email_body__', filename=f'mail-{index}.eml', + content_hash=f'body-{index}', classification='email_context', + parse_status='parsed', + ), + ShippingOrderDocument( + intake_id=int(intake.id), document_type='attachment', + attachment_key=f'po-{index}.pdf', filename=f'po-{index}.pdf', + content_hash=f'attachment-{index}', classification='order', + parse_status='parsed', order_extraction_status='not_started', + ), + ]) + db.session.commit() + + document_selects: list[str] = [] + + def _capture_document_selects(_conn, _cursor, statement, _parameters, _context, _executemany): + if re.search(r'\bfrom\s+shipping_order_documents\b', statement, re.IGNORECASE): + document_selects.append(statement) + + event.listen(db.engine, 'before_cursor_execute', _capture_document_selects) + try: + payload = project_conversation_processing_items( + user_id=shipping_user.id, + conversation_id=conversation_id, + ) + finally: + event.remove(db.engine, 'before_cursor_execute', _capture_document_selects) + + assert payload['conversation_processing']['summary']['total_files'] == 2 + assert len(document_selects) <= 1 + + def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, shipping_user): """ order_task 投影须填充 current_gate / candidate_count / po_number,禁止全空摘要。 @@ -1682,6 +2084,7 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship assert item['source_summary']['filename'] == document.filename + def test_order_task_projection_uses_stream_current_case_for_gate_and_deep_link(app, shipping_user): """同一文件旧开放 Case 残留时,OT Gate 与深链只能取 Stream 当前 Case。""" del shipping_user @@ -1816,6 +2219,47 @@ def test_eml_aggregate_keeps_run_authorized_batch_reparse_action(app, shipping_u assert 'reparse_batch' in displayed[0]['available_actions'] +def test_conversation_projection_reparseability_read_path_does_not_lock(app, shipping_user): + """会话 GET 判断批次动作时只能读,不得发出 FOR UPDATE。""" + del shipping_user + with app.app_context(): + from app.services.shipping_notice.order_review_service import ensure_run_review_cases + from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, _agent, session, intake, _document = _seed_run_input(suffix='EML-BATCH-READ-ONLY') + run = _materialized_run(user=user, agent=_agent, session=session, intake=intake) + ensure_run_review_cases(run=run) + transition_order_extraction_run(run, target_status='processing') + transition_order_extraction_run(run, target_status='review_required', result={}) + db.session.commit() + + statements: list[str] = [] + + def _capture(_conn, _cursor, statement, _parameters, _context, _executemany): + statements.append(statement) + + event.listen(db.engine, 'before_cursor_execute', _capture) + try: + with patch( + 'app.services.shipping_notice.order_review_disposition_service.select_current_batch_reparse_cases', + side_effect=AssertionError('GET projection must not enter the locked write selector'), + ): + _aggregate_eml_order_task_work_items([{ + 'work_item_type': 'order_task', 'work_item_no': 'OT-EML-READ-ONLY', + 'source_type': 'eml', 'intake_no': intake.intake_no, 'run_no': run.run_no, + 'status': 'review_required', 'stage': 'order_review', 'user_status': 'waiting_human', + 'user_stage': 'order_review', 'user_group': 'waiting_human', 'last_activity_at': '', + 'available_actions': ['open_order_review'], 'facts': {'upload_state': 'not_created'}, + 'source_summary': {'document_id': None, 'filename': 'mail.eml'}, + }]) + finally: + event.remove(db.engine, 'before_cursor_execute', _capture) + + assert not any('FOR UPDATE' in statement.upper() for statement in statements) + + def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_user): """ BE-07:投影 stage/status 以 OT 已写入值为准,禁止读路径用 Notice 覆盖。 @@ -1868,16 +2312,16 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u assert synced['status'] == 'automating' assert synced['stage'] == 'freight_uploading' - # 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。 + # 历史 Notice.upload_status 不构成成功证据;未补齐 Attempt/预约单时仍须停在货代上传。 notice.upload_status = 'uploaded' order_task.status = 'automating' order_task.stage = 'freight_uploading' db.session.commit() - completed = _project_order_task_work_item(run) - assert completed['status'] == 'completed' - assert completed['stage'] == 'completed' - assert completed['user_status'] == 'completed' - assert all(node['status'] == 'passed' for node in completed['stage_nodes']) + unverified = _project_order_task_work_item(run) + assert unverified['status'] == 'waiting_human' + assert unverified['stage'] == 'freight_uploading' + assert unverified['user_status'] == 'waiting_human' + assert unverified['verified_upload_success'] is False def test_conversation_processing_rebuild_prefers_work_item_user_status(app): diff --git a/backend/tests/test_shipping_review_confirm_auto_progress.py b/backend/tests/test_shipping_review_confirm_auto_progress.py index fb77a23a..baf98cf8 100644 --- a/backend/tests/test_shipping_review_confirm_auto_progress.py +++ b/backend/tests/test_shipping_review_confirm_auto_progress.py @@ -71,11 +71,12 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk summary = projection._project_post_confirm_auto_progress(case) - # 关键断言:刷新后可据此恢复琥珀色重试入口,且保留成功 Job 身份。 + # 关键断言:刷新后保留失败事实,但不恢复已下线的泛化 retry 入口; + # 用户必须回到当前 Gate 选择具体业务动作。 assert summary is not None assert summary['task_no'] == 'SN-STUCK-1' - assert summary['needs_retry'] is True - assert summary['status'] == 'needs_retry' + assert summary['needs_retry'] is False + assert summary['status'] == 'failed' assert summary['job_id'] == 55 assert summary['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced' diff --git a/backend/tests/test_shipping_review_line_fulfillment_decision.py b/backend/tests/test_shipping_review_line_fulfillment_decision.py index 368a644d..c6fa734e 100644 --- a/backend/tests/test_shipping_review_line_fulfillment_decision.py +++ b/backend/tests/test_shipping_review_line_fulfillment_decision.py @@ -202,17 +202,18 @@ def test_shortage_release_keeps_first_export_line_override(): ) == {0: {'6': 'ODM-001'}} -def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_inventory_fact(app, monkeypatch): - """短缺放行重投影后必须入队 Excel 产物 Gate,且不得改写库存缺口事实。""" +def test_shortage_release_syncs_gate_and_enqueues_auto_fulfill_without_mutating_inventory_fact(app, monkeypatch): + """短缺放行只同步 Gate,并由 Worker 决定是否创建单条 Notice/Excel。""" from types import SimpleNamespace from app.services.shipping_notice import order_review_fulfillment_decision_service as svc - task = SimpleNamespace(id=12, active_process_execution_id=34) + task = SimpleNamespace(id=12, task_no='SN-12', active_process_execution_id=34) case = SimpleNamespace(confirmed_task_id=12) execution = SimpleNamespace(id=34, task_id=12) synced = [] queued = [] + auto_fulfill_jobs = [] monkeypatch.setattr(svc.db.session, 'get', lambda model, key: task if key == 12 else execution) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', @@ -222,6 +223,10 @@ def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_ 'app.services.shipping_notice.auto_progress_controller.submit_auto_progress', lambda **kwargs: queued.append(kwargs), ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job', + lambda **kwargs: auto_fulfill_jobs.append(kwargs), + ) with app.app_context(): _sync_confirmed_task_fulfillment_gates(case=case, actor_id=7) @@ -233,6 +238,11 @@ def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_ 'operator_id': 7, 'commit': False, }] + assert auto_fulfill_jobs == [{ + 'task_no': 'SN-12', + 'trigger': 'inventory_shortage_released', + 'commit': False, + }] def test_shortage_release_rejects_missing_template_inventory_override(): @@ -554,70 +564,6 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch): assert result['decision']['id'] == 42 -def test_create_wave_revalidates_inventory(app, monkeypatch): - """建波次前 validate_draft 后仍库存不足则拒绝。""" - from types import SimpleNamespace - - from app.services.shipping_notice import order_review_fulfillment_decision_service as svc - - draft = SimpleNamespace( - draft_version=2, - lines_json=[{ - 'line_key': 'L1', - 'qty': '10', - 'reservation_id': 'R1', - 'part_number': 'PN1', - }], - validation_result_json={ - 'line_projections': [{ - 'line_key': 'L1', - 'available_qty': '1', - 'effective_reservation_id': 'R1', - }], - }, - ) - case = SimpleNamespace( - id=1, - case_no='CASE-1', - status='ready', - current_draft=draft, - run=SimpleNamespace(run_no='RUN-1'), - ) - decision = SimpleNamespace( - decision_code=DECISION_FULFILL, - line_status='ready_to_fulfill', - required_qty='10', - is_active=True, - ) - - monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case) - monkeypatch.setattr(svc, '_get_soft_loader', lambda: lambda **kwargs: case) - monkeypatch.setattr(svc, '_active_decision', lambda *a, **k: decision) - - called = {'validate': False} - - def _fake_validate(**kwargs): - called['validate'] = True - return {'status': 'ready'} - - monkeypatch.setattr( - 'app.services.shipping_notice.order_review_draft_service.validate_draft', - _fake_validate, - ) - - with app.app_context(): - with pytest.raises(ConflictError) as exc: - svc.create_fulfillment_wave( - user_id=1, - case_no='CASE-1', - line_keys=['L1'], - expected_draft_version=2, - idempotency_key='wave-1', - ) - assert called['validate'] is True - assert exc.value.code == 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY' - - def test_project_empty_case_without_draft(app): """无草稿行时投影应返回空列表。""" from types import SimpleNamespace diff --git a/backend/tests/test_shipping_review_wave_line_concurrency.py b/backend/tests/test_shipping_review_wave_line_concurrency.py index 1bb96764..4d0dc002 100644 --- a/backend/tests/test_shipping_review_wave_line_concurrency.py +++ b/backend/tests/test_shipping_review_wave_line_concurrency.py @@ -36,7 +36,6 @@ def test_wave_line_unique_constraint_blocks_second_insert(app): from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan from app.services.shipping_notice.order_review_service import ensure_run_review_cases - from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.tool_common import generate_task_no user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-UQ') @@ -46,19 +45,19 @@ def test_wave_line_unique_constraint_blocks_second_insert(app): ensure_order_extraction_plan(run) db.session.commit() unit = run.extraction_plan.units[0] + unit.status = 'candidate_ready' unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]} db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() - shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id)) task1 = ShippingNotice( - task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), + task_no=generate_task_no(), user_id=int(user.id), source_type='review_confirmation', source_file_name=document.filename, source_content_hash=document.content_hash, ) task2 = ShippingNotice( - task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), + task_no=generate_task_no(), user_id=int(user.id), source_type='review_confirmation', source_file_name=document.filename, source_content_hash=document.content_hash, ) @@ -93,7 +92,6 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan from app.services.shipping_notice.order_review_service import ensure_run_review_cases - from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.tool_common import generate_task_no user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-RACE') @@ -103,17 +101,17 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): ensure_order_extraction_plan(run) db.session.commit() unit = run.extraction_plan.units[0] + unit.status = 'candidate_ready' unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]} db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() case_id = int(case.id) - shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id)) tasks = [] for _ in range(2): task = ShippingNotice( - task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), + task_no=generate_task_no(), user_id=int(user.id), source_type='review_confirmation', source_file_name=document.filename, source_content_hash=document.content_hash, ) diff --git a/backend/tests/test_shipping_review_workbench_stage_layering.py b/backend/tests/test_shipping_review_workbench_stage_layering.py index ff64fae9..90607427 100644 --- a/backend/tests/test_shipping_review_workbench_stage_layering.py +++ b/backend/tests/test_shipping_review_workbench_stage_layering.py @@ -106,6 +106,30 @@ def test_completed_checks_include_formal_ot_milestone(): assert 'order_review_completed' in codes +def test_completed_checks_do_not_mark_open_legacy_conflict_as_resolved(): + """遗留阻断 Finding 已投影为开放冲突时,不得再显示冲突已解决。""" + checks = project_completed_checks( + case=SimpleNamespace(updated_at=None), + process_gate={ + 'gates_track': [ + {'gate_code': 'field_conflict_resolution', 'status': 'passed'}, + ], + }, + customer_resolution=None, + duplicate=None, + field_conflicts=[{ + 'conflict_key': '0:unit_price', + 'field_code': 'unit_price', + 'status': 'open', + }], + field_completeness=None, + profile_match=None, + formal_ot={'has_formal_ot': False}, + ) + + assert 'field_conflicts_resolved' not in {item['code'] for item in checks} + + def test_post_ot_clears_pre_ot_blocking_gate(): """正式 OT 后建单前 Gate 不得成为当前阻断。""" summary = apply_post_ot_gate_rules( @@ -235,6 +259,7 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating(): current_step=None, stage_nodes_json=None, step_payload_json=None, + upload_status=None, ) stage = project_stage_for_task(task) assert stage['code'] == 'order_creating' @@ -242,8 +267,8 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating(): assert stage['source'] == 'domain_facts' -def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage(): - """人工上传已完成时,旧 OT freight_uploading 阶段不能覆盖 Notice 终态。""" +def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(): + """历史 Notice.upload_status 无成功 Attempt 时不得绕过货代上传核对。""" task = SimpleNamespace( id=1, order_task_id=9, @@ -253,8 +278,8 @@ def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage(): step_payload_json=None, ) stage = project_stage_for_task(task) - assert stage['code'] == 'completed' - assert stage['source'] == 'notice_terminal' + assert stage['code'] == 'freight_uploading' + assert stage['source'] == 'upload_success_unverified' def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch): diff --git a/backend/tests/test_shipping_rolling_fulfillment.py b/backend/tests/test_shipping_rolling_fulfillment.py index 46840be0..2d1251db 100644 --- a/backend/tests/test_shipping_rolling_fulfillment.py +++ b/backend/tests/test_shipping_rolling_fulfillment.py @@ -26,6 +26,7 @@ from app.services.shipping_notice.reservation_service import ( ensure_task_reservations, record_inventory_verification, ) +from app.services.shipping_notice.fulfillment_workflow import excel_gate_error from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot @@ -77,6 +78,53 @@ def test_shortage_release_makes_only_its_snapshot_line_exportable(app): assert line_ids == {released_line.id} +def test_partial_inventory_allows_excel_for_the_available_lines(app): + """关键断言:部分短缺不阻断已完整满足行的滚动 Excel 导出资格。""" + with app.app_context(): + task, user = _build_accepted_order(suffix='partial-excel-gate') + snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + available_line = snapshot.lines[0] + shortage_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681', + qty=Decimal('3'), field_values_json={}, + ) + snapshot.lines.append(shortage_line) + db.session.flush() + record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[ + {'reservation_id': available_line.reservation_id, 'part_number': available_line.part_number, 'required_qty': available_line.qty, 'available_qty': available_line.qty, 'line_status': 'ok'}, + {'reservation_id': shortage_line.reservation_id, 'part_number': shortage_line.part_number, 'required_qty': shortage_line.qty, 'available_qty': '0', 'line_status': 'shortage'}, + ]) + + assert excel_gate_error(task) is None + + +def test_selected_notice_only_returns_its_frozen_lines(app): + """独立发货通知只能取得用户选择的满足行,不能捎带同 PO 其他可用行。""" + with app.app_context(): + task, user = _build_accepted_order(suffix='selected-notice-lines') + snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + first_line = snapshot.lines[0] + second_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681', + qty=Decimal('3'), field_values_json={}, + ) + snapshot.lines.append(second_line) + db.session.flush() + record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[ + {'reservation_id': first_line.reservation_id, 'part_number': first_line.part_number, 'required_qty': first_line.qty, 'available_qty': first_line.qty, 'line_status': 'ok'}, + {'reservation_id': second_line.reservation_id, 'part_number': second_line.part_number, 'required_qty': second_line.qty, 'available_qty': second_line.qty, 'line_status': 'ok'}, + ]) + + _verification, line_ids = current_available_snapshot_line_ids( + task, + selected_snapshot_line_ids={first_line.id}, + ) + + assert line_ids == {first_line.id} + + + + def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app): """关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。""" with app.app_context(): diff --git a/backend/tests/test_shipping_runtime_parse_strategy.py b/backend/tests/test_shipping_runtime_parse_strategy.py new file mode 100644 index 00000000..c573bf60 --- /dev/null +++ b/backend/tests/test_shipping_runtime_parse_strategy.py @@ -0,0 +1,165 @@ +"""验证订单模板运行时策略仅基于当前文档证据作出可审计的受控选择。""" + +from app.services.shipping_notice.document_layout.runtime_parse_strategy import ( + resolve_runtime_parse_strategy, + select_runtime_region_ids, +) + + +def _row(*, line_no: str, part_no: str, issues: list[str] | None = None) -> dict: + """构造最小重建行,关键料号与项次用于验证策略不得静默改写业务结果。""" + return { + 'status': 'parsed' if not issues else 'needs_review', + 'issues': issues or [], + 'fields': [ + {'field_code': 'customer_po_line_no', 'value': line_no}, + {'field_code': 'part_number', 'value': part_no}, + ], + } + + +def test_runtime_strategy_uses_every_page_with_coordinate_evidence(): + """模板画在首页时,运行时仍须计划检查所有有页级坐标的页面以避免静默漏续页。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}], '2': [{}], '3': []}, + fixed_rows=[], adaptive_rows=[], + ) + + # 页面计划仍完整保留;没有任何可用明细行时整体必须 Review,不能伪造成功。 + assert result.status == 'needs_review' + assert result.page_nos == (1, 2) + + +def test_runtime_strategy_selects_adaptive_only_when_fixed_has_no_valid_rows(): + """固定子行无有效行而自适应能完整重建时,系统才自动切换而非要求人工猜策略。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='10', part_no='PART-A', issues=['row_incomplete'])], + adaptive_rows=[_row(line_no='10', part_no='PART-A')], + ) + + assert result.status == 'selected' + assert result.row_mode == 'adaptive_record_columns' + assert result.reason_codes == ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',) + + +def test_runtime_strategy_selects_dynamic_x_columns_when_existing_modes_have_no_valid_rows(): + """固定与自适应均无行时,才允许使用同一 Schema 校验过的动态 Y 候选。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[], adaptive_rows=[], + dynamic_rows=[_row(line_no='10', part_no='PART-A')], + ) + + assert result.status == 'selected' + assert result.row_mode == 'dynamic_x_columns' + assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',) + + +def test_runtime_strategy_requires_review_when_dynamic_conflicts_with_existing_valid_row(): + """动态结果与既有有效行冲突时不得静默保留旧模式,必须进入 Review。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='10', part_no='PART-A')], adaptive_rows=[], + dynamic_rows=[_row(line_no='10', part_no='PART-B')], + ) + + assert result.status == 'needs_review' + assert result.row_mode is None + assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) + + +def test_runtime_strategy_selects_dynamic_when_it_safely_covers_more_valid_records(): + """动态候选完整覆盖旧模式且额外恢复有效起行记录时,才能取代不完整结果。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='20', part_no='PART-B')], adaptive_rows=[], + dynamic_rows=[ + _row(line_no='10', part_no='PART-A'), + _row(line_no='20', part_no='PART-B'), + ], + ) + + assert result.status == 'selected' + assert result.row_mode == 'dynamic_x_columns' + assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',) + + +def test_runtime_strategy_requires_review_when_two_valid_modes_disagree_on_business_rows(): + """两种有效重建结果的关键项次或料号不一致时不得按分数强选,必须转既有 Review。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='10', part_no='PART-A')], + adaptive_rows=[_row(line_no='10', part_no='PART-B')], + ) + + assert result.status == 'needs_review' + assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) + + +def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value(): + """同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。""" + fixed = _row(line_no='10', part_no='PART-A') + fixed['fields'].append({'field_code': 'quantity', 'value': '12'}) + adaptive = _row(line_no='10', part_no='PART-A') + adaptive['fields'].append({'field_code': 'quantity', 'value': '10'}) + + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive], + ) + + assert result.status == 'needs_review' + assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) + + +def test_runtime_strategy_prefers_complete_fixed_rows_when_overlap_matches(): + """固定模式多识别一个字段时不得把同一条明细误判为策略冲突。""" + fixed = _row(line_no='10', part_no='PART-A') + fixed['fields'].append({'field_code': 'uom', 'value': 'EA'}) + adaptive = _row(line_no='10', part_no='PART-A') + + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive], + ) + + assert result.status == 'selected' + assert result.row_mode == 'fixed_subrows' + + +def test_runtime_strategy_still_reviews_when_field_values_conflict(): + """字段值冲突仍必须进入 Review,不能用字段数量掩盖识别差异。""" + fixed = _row(line_no='10', part_no='PART-A') + fixed['fields'].append({'field_code': 'uom', 'value': 'EA'}) + adaptive = _row(line_no='10', part_no='PART-A') + adaptive['fields'].append({'field_code': 'uom', 'value': 'PCS'}) + + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive], + ) + + assert result.status == 'needs_review' + assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) + + +def test_runtime_strategy_reuses_base_region_on_continuation_page_without_duplicate_page_regions(): + """标注页只用于定位同页表区;没有专属标注的续页复用基础表区,不能重复消费其他页布局。""" + regions = [ + {'region_id': 'page_one', 'page_scope': 'exact_page', 'page_no': 1}, + {'region_id': 'page_two', 'page_scope': 'exact_page', 'page_no': 2}, + ] + + assert select_runtime_region_ids(table_regions=regions, page_no=1) == ('page_one',) + assert select_runtime_region_ids(table_regions=regions, page_no=2) == ('page_two',) + assert select_runtime_region_ids(table_regions=regions, page_no=3) == ('page_one',) + + +def test_runtime_region_selection_prefers_legacy_continuation_region_before_base_region(): + """已发布模板的续页专属框仍优先于首页基准框,避免升级后错用另一种行布局。""" + regions = [ + {'region_id': 'page_one', 'page_scope': 'first_page'}, + {'region_id': 'continuation', 'page_scope': 'continuation_pages'}, + {'region_id': 'all_pages', 'page_scope': 'all_pages'}, + ] + + assert select_runtime_region_ids(table_regions=regions, page_no=1) == ('page_one',) + assert select_runtime_region_ids(table_regions=regions, page_no=2) == ('continuation',) diff --git a/backend/tests/test_shipping_stp_auto_create_enqueue.py b/backend/tests/test_shipping_stp_auto_create_enqueue.py index 4a10776c..9eae82d1 100644 --- a/backend/tests/test_shipping_stp_auto_create_enqueue.py +++ b/backend/tests/test_shipping_stp_auto_create_enqueue.py @@ -244,17 +244,23 @@ def test_stp_handler_accepts_worker_contract_and_finishes_owned_attempt(app): payload={'case_no': 'SORC-STP-HANDLER', 'draft_version': 3, 'job_id': 906}, job_id=906, ) - finish_mock.assert_called_once_with( - 906, - result={'ok': True, 'message': 'done', 'task_no': 'SN-1'}, - message='done', - owned_attempt=2, - ) + finish_mock.assert_called_once() + args, kwargs = finish_mock.call_args + assert args == (906,) + assert kwargs['message'] == 'done' + assert kwargs['owned_attempt'] == 2 + assert kwargs['result'] == { + 'ok': True, + 'message': 'done', + 'task_no': 'SN-1', + 'contract_version': 'shipping-recovery-v1-phase1', + 'status': 'ok', + } fail_mock.assert_not_called() -def test_stp_handler_uses_fail_job_contract_for_business_failure(app): - """业务失败必须使用 fail_job(error/result/retryable/owned_attempt),不得传旧参数名。""" +def test_stp_handler_marks_business_failure_blocked_manual(app): + """业务失败必须停止自动重试并提供人工复核入口。""" from app.jobs.context import JobContext from app.jobs.handlers import shipping_stp_auto_create as handler @@ -279,13 +285,15 @@ def test_stp_handler_uses_fail_job_contract_for_business_failure(app): ) as fail_mock: handler.handle_shipping_stp_auto_create(ctx, {'job_id': 907}) - fail_mock.assert_called_once_with( - 907, - error='not eligible', - result=result, - retryable=True, - owned_attempt=1, - ) + fail_mock.assert_called_once() + args, kwargs = fail_mock.call_args + assert args == (907,) + assert kwargs['error'] == 'not eligible' + assert kwargs['retryable'] is False + assert kwargs['owned_attempt'] == 1 + assert kwargs['result']['blocking_reason'] == 'SHIPPING.STP_NOT_ELIGIBLE' + assert kwargs['result']['next_action'] == 'open_order_review' + assert kwargs['result']['contract_version'] == 'shipping-recovery-v1-phase1' finish_mock.assert_not_called() diff --git a/backend/tests/test_shipping_stp_match_completed_gate.py b/backend/tests/test_shipping_stp_match_completed_gate.py index 782108d5..122fd621 100644 --- a/backend/tests/test_shipping_stp_match_completed_gate.py +++ b/backend/tests/test_shipping_stp_match_completed_gate.py @@ -8,35 +8,54 @@ tests/test_shipping_stp_match_completed_gate.py from __future__ import annotations -from types import SimpleNamespace - +from app import db +from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch from app.services.shipping_notice.fulfillment_workflow import match_completed -def test_match_completed_rejects_partial(): +def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingNotice: + """写入正式行匹配事实,供 Excel 门禁读取。""" + task = ShippingNotice(task_no=task_no, source_type='manual') + db.session.add(task) + db.session.flush() + db.session.add_all([ + ShippingNoticeLineInventoryMatch( + task_id=task.id, + line_key=f'L{index}', + match_result=row['match_result'], + inventory_status='ready', + shortage_qty=row.get('shortage_qty', '0'), + is_current=True, + ) + for index, row in enumerate(rows, start=1) + ]) + db.session.flush() + return task + + +def test_match_completed_rejects_partial(app): """partial 即使存在 ok 行也不得进入 Excel。""" - task = SimpleNamespace( - match_status='partial', - line_results_json=[ - {'line_status': 'ok'}, - {'line_status': 'shortage'}, - ], - ) - assert match_completed(task) is False + with app.app_context(): + task = _task_with_current_matches( + task_no='SN-MATCH-PARTIAL', + rows=[{'match_result': 'matched'}, {'match_result': 'not_found', 'shortage_qty': '1'}], + ) + assert match_completed(task) is False -def test_match_completed_requires_all_ok_fulfillable(): +def test_match_completed_requires_all_ok_fulfillable(app): """fulfillable 且全部 ok 才允许制单。""" - ok = SimpleNamespace( - match_status='fulfillable', - line_results_json=[{'line_status': 'ok'}, {'disposition': 'ok'}], - ) - mixed = SimpleNamespace( - match_status='fulfillable', - line_results_json=[{'line_status': 'ok'}, {'line_status': 'not_found'}], - ) - assert match_completed(ok) is True - assert match_completed(mixed) is False + with app.app_context(): + ok = _task_with_current_matches( + task_no='SN-MATCH-OK', + rows=[{'match_result': 'matched'}, {'match_result': 'matched'}], + ) + mixed = _task_with_current_matches( + task_no='SN-MATCH-MIXED', + rows=[{'match_result': 'matched'}, {'match_result': 'not_found'}], + ) + assert match_completed(ok) is True + assert match_completed(mixed) is False def test_match_step_progress_partial_is_needs_human_not_100(): diff --git a/backend/tests/test_shipping_stp_phase3_auto_create.py b/backend/tests/test_shipping_stp_phase3_auto_create.py index 0c777d92..b80f7cf5 100644 --- a/backend/tests/test_shipping_stp_phase3_auto_create.py +++ b/backend/tests/test_shipping_stp_phase3_auto_create.py @@ -10,6 +10,8 @@ from __future__ import annotations from types import SimpleNamespace +from app import db +from app.models import ShippingNotice from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable from app.services.shipping_notice.order_stp_auto_create_service import _draft_has_manual_edits from app.services.shipping_notice.stp_inventory_freeze import ( @@ -86,38 +88,25 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch): }, ) - task = SimpleNamespace( - inventory_source_status=None, - inventory_source_code=None, - inventory_connector_type=None, - inventory_warehouse_id=None, - inventory_source_method=None, - inventory_source_config_version=None, - inventory_routing_fingerprint=None, - step_payload_json={}, - destination_code=None, - destination_city=None, - destination_country=None, - warehouse_hint=None, - inventory_source_confirmed_by=None, - inventory_source_confirmed_at=None, - current_order_extraction_id=None, - ) - result = freeze_stp_inventory_candidates_on_task( - task, - line_projections=[{ - 'line_key': 'L1', - 'candidate_inventory_source_codes': ['DBS_DUB'], - 'selection_mode': 'rule', - 'routing_status': 'resolved', - 'matched_rule_ids': [1], - }], - ) - assert result.status == 'resolved' - assert task.inventory_source_status == 'resolved' - assert task.inventory_source_code == 'DBS_DUB' - assert task_frozen_inventory_source_codes(task) == ['DBS_DUB'] - assert is_inventory_source_stable(task) is True + with app.app_context(): + task = ShippingNotice(task_no='SN-STP-FREEZE-ONE', source_type='manual') + db.session.add(task) + db.session.flush() + result = freeze_stp_inventory_candidates_on_task( + task, + line_projections=[{ + 'line_key': 'L1', + 'candidate_inventory_source_codes': ['DBS_DUB'], + 'selection_mode': 'rule', + 'routing_status': 'resolved', + 'matched_rule_ids': [1], + }], + ) + assert result.status == 'resolved' + assert task.inventory_source_status == 'resolved' + assert task.inventory_source_code == 'DBS_DUB' + assert task_frozen_inventory_source_codes(task) == ['DBS_DUB'] + assert is_inventory_source_stable(task) is True def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch): @@ -143,35 +132,22 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch monkeypatch.setattr(gate_mod, 'inventory_sources_runtime_version', lambda: 'cfg-v2') monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source) - task = SimpleNamespace( - inventory_source_status=None, - inventory_source_code=None, - inventory_connector_type=None, - inventory_warehouse_id=None, - inventory_source_method=None, - inventory_source_config_version=None, - inventory_routing_fingerprint=None, - step_payload_json={}, - destination_code=None, - destination_city=None, - destination_country=None, - warehouse_hint=None, - inventory_source_confirmed_by=None, - inventory_source_confirmed_at=None, - current_order_extraction_id=None, - ) - result = freeze_stp_inventory_candidates_on_task( - task, - line_projections=[{ - 'line_key': 'L1', - 'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'], - 'selection_mode': 'rule', - 'routing_status': 'ambiguous', - 'matched_rule_ids': [9], - }], - ) - assert result.status == 'candidates_frozen' - assert task.inventory_source_status == 'candidates_frozen' - assert not task.inventory_source_code - assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] - assert is_inventory_source_stable(task) is True + with app.app_context(): + task = ShippingNotice(task_no='SN-STP-FREEZE-MANY', source_type='manual') + db.session.add(task) + db.session.flush() + result = freeze_stp_inventory_candidates_on_task( + task, + line_projections=[{ + 'line_key': 'L1', + 'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'], + 'selection_mode': 'rule', + 'routing_status': 'ambiguous', + 'matched_rule_ids': [9], + }], + ) + assert result.status == 'candidates_frozen' + assert task.inventory_source_status == 'candidates_frozen' + assert not task.inventory_source_code + assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] + assert is_inventory_source_stable(task) is True diff --git a/backend/tests/test_shipping_task_disposition.py b/backend/tests/test_shipping_task_disposition.py index 1f65b2ab..45d19ad6 100644 --- a/backend/tests/test_shipping_task_disposition.py +++ b/backend/tests/test_shipping_task_disposition.py @@ -4,7 +4,6 @@ from app import db from app.core.errors import ConflictError from app.models import ( ShippingAuditEvent, - ShippingCase, ShippingNotice, ShippingTaskEvent, ShippingTaskPurgeAudit, @@ -62,11 +61,8 @@ def test_plain_created_task_can_be_deleted_and_restored(app): def test_internal_business_task_is_voided_before_recycle_bin(app): """已有业务单的任务不能伪装为纯删除,必须留下作废事实和原因。""" with app.app_context(): - case = ShippingCase(case_no='SC-DISPOSITION-001') - task = _task('SN-DISPOSITION-VOID-001') - db.session.add_all([case, task]) - db.session.flush() - task.shipping_case_id = case.id + task = _task('SN-DISPOSITION-VOID-001', business_no='SN260823001') + db.session.add(task) db.session.commit() outcome = move_task_to_recycle_bin(task, actor_id=1, reason='重复建单') @@ -210,11 +206,9 @@ def test_workspace_voided_filter_includes_voided_recycle_bin_task(app, client): """已作废视图必须可审计“作废并删除”的任务,不能被 deleted_at 条件意外排除。""" headers, user_id = _headers_for_user(app, 'disposition-voided-list') with app.app_context(): - case = ShippingCase(case_no='SC-DISPOSITION-LIST-VOIDED') - task = _task('SN-DISPOSITION-LIST-VOIDED', user_id=user_id) - db.session.add_all([case, task]) + task = _task('SN-DISPOSITION-LIST-VOIDED', user_id=user_id, business_no='SN260823002') + db.session.add(task) db.session.flush() - task.shipping_case_id = case.id move_task_to_recycle_bin(task, actor_id=user_id, reason='测试作废') db.session.commit() @@ -254,11 +248,8 @@ def test_admin_can_purge_only_pure_deleted_task_and_audit_is_retained(app, clien def test_purge_blocks_task_with_business_reference(app): """已有业务单的回收站任务即使被手工篡改为 active,也必须阻断永久删除。""" with app.app_context(): - case = ShippingCase(case_no='SC-DISPOSITION-PURGE-BLOCK') - task = _task('SN-DISPOSITION-PURGE-BLOCK') - db.session.add_all([case, task]) - db.session.flush() - task.shipping_case_id = case.id + task = _task('SN-DISPOSITION-PURGE-BLOCK', business_no='SN260823003') + db.session.add(task) task.deleted_at = __import__('datetime').datetime.utcnow() db.session.commit() diff --git a/backend/tests/test_shipping_task_supersession.py b/backend/tests/test_shipping_task_supersession.py index 4ac92d72..ae3438db 100644 --- a/backend/tests/test_shipping_task_supersession.py +++ b/backend/tests/test_shipping_task_supersession.py @@ -30,8 +30,8 @@ def test_unuploaded_resend_voids_old_task_and_keeps_new_active(app): assert new.lifecycle_status == 'active' -def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(app): - """关键断言:已上传旧版必须先有撤销回执,后继版才恢复活动状态。""" +def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app): + """关键断言:已上传旧版须登记外部撤销确认;不要求回执号或文件。""" with app.app_context(): old, new, user = _tasks(uploaded=True) establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend') @@ -39,7 +39,11 @@ def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(a assert new.lifecycle_status == 'blocked' with pytest.raises(ConflictError): assert_task_not_supersession_blocked(new) - complete_freight_cancellation(cancellation_id=row.id, actor_id=user.id, freight_receipt_no='CANCEL-1', receipt_asset_id=1) + complete_freight_cancellation( + cancellation_id=row.id, + actor_id=user.id, + note='已在货代平台确认撤销', + ) assert row.status == 'cancelled' assert old.lifecycle_status == 'voided' assert new.lifecycle_status == 'active' diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index 9d94167e..95a495fd 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -18,7 +18,11 @@ from app.models import ( ShippingUploadAttempt, ) from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success -from app.services.shipping_notice.upload_attempt_service import complete_attempt, mark_attempt_result_unknown, start_rpa_attempt, void_rejected_artifact +from app.services.shipping_notice.export import assert_notice_has_no_export_artifact +from app.services.shipping_notice.upload_attempt_service import ( + complete_attempt, has_verified_upload_success, mark_attempt_result_unknown, + record_manual_upload, start_rpa_attempt, void_rejected_artifact, +) from app.services.shipping_notice.state_machine import resolve_task_ui_state @@ -64,10 +68,136 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app): assert ShippingUploadAttempt.query.count() == 1 assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' + # 三层成功事实齐全后,才允许任务进入业务「通知完成」。 + assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True with pytest.raises(ConflictError): start_rpa_attempt(task, artifact_id=artifact.id) +def test_notice_with_existing_excel_cannot_generate_another_artifact(app): + """一个发货通知单已有 Excel 后必须创建新 Notice,不能追加第二个 Artifact。""" + with app.app_context(): + task, _artifact, _reservation = _ready_artifact() + + with pytest.raises(ConflictError) as exc_info: + assert_notice_has_no_export_artifact(task) + + assert exc_info.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED' + + +def test_batch_notice_confirmation_isolates_each_business_number(app, monkeypatch): + """批量通知单确认中一张被阻断时,其他通知单仍独立提交成功。""" + from types import SimpleNamespace + + from app.api.workspace import shipping_notice as api + + with app.app_context(), app.test_request_context( + '/api/workspace/shipping-notices/batch/confirm-uploaded', + method='POST', + json={'business_nos': ['WVC26082301', 'WVC26082302']}, + ): + commits: list[str] = [] + monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=7)) + monkeypatch.setattr( + api, + '_confirm_notice_uploaded', + lambda *, business_no, user_id: ( + {'status': 'ok'} if business_no.endswith('01') + else (_ for _ in ()).throw(ConflictError('already uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')) + ), + ) + monkeypatch.setattr(api.db.session, 'commit', lambda: commits.append('commit')) + monkeypatch.setattr(api.db.session, 'rollback', lambda: commits.append('rollback')) + + response = api.workspace_batch_confirm_shipping_notices_uploaded() + body = response[0].get_json()['data'] + + assert [item['status'] for item in body['results']] == ['confirmed', 'blocked'] + assert commits == ['commit', 'rollback'] + + +def test_business_no_rpa_batch_isolates_each_notice(app, monkeypatch): + """批量 RPA 必须只接受 business_no,并让已受理通知独立提交。""" + from types import SimpleNamespace + + from app.api.workspace import shipping_notice as api + + with app.app_context(), app.test_request_context( + '/api/workspace/shipping-notices/batch/rpa-upload', + method='POST', + json={'business_nos': ['WVC26082301', 'WVC26082302']}, + ): + commits: list[str] = [] + monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=7)) + monkeypatch.setattr( + api, + '_start_notice_rpa_upload', + lambda *, business_no, user_id: ( + {'status': 'running'} if business_no.endswith('01') + else (_ for _ in ()).throw(ConflictError('unknown result', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN')) + ), + ) + monkeypatch.setattr(api.db.session, 'commit', lambda: commits.append('commit')) + monkeypatch.setattr(api.db.session, 'rollback', lambda: commits.append('rollback')) + + response = api.workspace_batch_start_shipping_notice_rpa_upload() + body = response[0].get_json()['data'] + + assert [item['status'] for item in body['results']] == ['accepted', 'blocked'] + assert [item['business_no'] for item in body['results']] == ['WVC26082301', 'WVC26082302'] + assert commits == ['commit', 'rollback'] + + +def test_business_no_loader_rejects_task_no_alias(app, monkeypatch): + """新货代入口不得把内部 task_no 或旧 Case 编号当作 business_no 接收。""" + from app.api.workspace import shipping_notice as api + + with app.app_context(), app.test_request_context('/api/workspace/shipping-notices/SN-1/export'): + task = ShippingNotice(task_no='SN-1', business_no='WVC26082301', user_id=7) + monkeypatch.setattr(api, 'get_task_for_user', lambda reference, user_id: task) + + with pytest.raises(Exception) as exc_info: + api._load_business_notice_for_user(business_no='SN-1', user_id=7) + + assert getattr(exc_info.value, 'code', None) == 'RESOURCE.NOT_FOUND' + + +def test_upload_success_updates_only_its_notice(app): + """一张独立 Notice 上传成功只终态化其自身,不影响同 PO 的其他 Notice。""" + with app.app_context(): + task, artifact, _reservation = _ready_artifact() + other = ShippingNotice(task_no='TASK-UPLOAD-OTHER', order_task_id=task.order_task_id) + db.session.add(other); db.session.flush() + attempt = start_rpa_attempt(task, artifact_id=artifact.id) + + complete_attempt(attempt, success=True, callback_id='callback-notice', freight_ref_no='F-2') + + assert db.session.get(ShippingNotice, task.id).upload_status == 'uploaded' + assert db.session.get(ShippingNotice, other.id).upload_status is None + + +def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app): + """历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。""" + with app.app_context(): + task, _artifact, _reservation = _ready_artifact() + task.upload_status = 'uploaded' + db.session.flush() + + assert has_verified_upload_success(task) is False + + +def test_archived_upload_success_is_not_counted_as_completed(app): + """归档任务保留上传审计,但不能再计入当前通知完成统计。""" + with app.app_context(): + task, artifact, _reservation = _ready_artifact() + attempt = start_rpa_attempt(task, artifact_id=artifact.id) + complete_attempt(attempt, success=True, callback_id='callback-archived', freight_ref_no='REF-ARCHIVED') + task.lifecycle_status = 'archived' + db.session.flush() + + assert has_verified_upload_success(task) is False + + def test_failed_attempt_does_not_complete_reservation(app): """RPA 失败仅释放 Artifact 重试状态,不能把预约单错误标记为上传完成。""" with app.app_context(): @@ -78,6 +208,24 @@ def test_failed_attempt_does_not_complete_reservation(app): assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready' +def test_manual_upload_confirmation_requires_no_receipt_or_file_evidence(app): + """人工确认只记录操作者和目标 Excel,不要求货代回执或截图/PDF。""" + with app.app_context(): + task, artifact, reservation = _ready_artifact() + + attempt = record_manual_upload( + task, + artifact_id=artifact.id, + operator_id=7, + ) + + assert attempt.mode == 'manual' + assert attempt.evidence_asset_id is None + assert attempt.freight_ref_no is None + assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' + assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' + + def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app): """共享目录投递失败要落为失败 Attempt,不能遗留 uploading Artifact 阻断下一轮。""" with app.app_context(): @@ -173,7 +321,7 @@ def test_upload_callback_success_parsing_does_not_treat_false_text_as_success(): def test_rpa_report_upload_success_without_evidence_rejected(app): - """success=True 但缺少 success_evidence 时必须 fail-closed 拒绝。""" + """RPA success=True 但缺少受信 Worker 证据时必须 fail-closed 拒绝。""" with app.app_context(): from unittest.mock import patch @@ -197,7 +345,7 @@ def test_rpa_report_upload_success_without_evidence_rejected(app): def test_rpa_report_upload_success_without_reference_allowed(app): - """DSV 绿 DOM 成功时 reference 可为空;须带 success_evidence.kind 且证据资产落库。""" + """DSV 受信成功证据可不带 reference,并持久化内部审计资产。""" with app.app_context(): from unittest.mock import patch @@ -232,13 +380,9 @@ def test_rpa_report_upload_success_without_reference_allowed(app): 'observed_at': '2026-08-05T03:00:00Z', 'page_url': 'https://dsv.example/history', 'dom_snippet': '', - 'dom_sha256': ( - __import__('hashlib') - .sha256( - b'' - ) - .hexdigest() - ), + 'dom_sha256': __import__('hashlib').sha256( + b'' + ).hexdigest(), }, }) assert result['status'] == 'ok' @@ -246,13 +390,12 @@ def test_rpa_report_upload_success_without_reference_allowed(app): refreshed = db.session.get(ShippingUploadAttempt, attempt.id) assert refreshed is not None evidence = refreshed.success_evidence_json or {} - assert evidence.get('dom_sha256') assert evidence.get('page_url') assert refreshed.evidence_asset_id == 4242 -def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app): - """DOM 校验通过但证据资产落库失败时,不得标记上传成功。""" +def test_rpa_report_upload_success_requires_internal_audit_asset(app): + """自动 RPA 成功仍保存内部审计资产;人工确认路径不受此规则影响。""" with app.app_context(): from unittest.mock import patch @@ -261,12 +404,16 @@ def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app): task, artifact, reservation = _ready_artifact() attempt = start_rpa_attempt(task, artifact_id=artifact.id) db.session.commit() + def _persist(*, task, attempt, success_evidence): + attempt.evidence_asset_id = 4242 + return 4242 + with patch( 'app.services.shipping_notice.fulfillment_workflow.customer_gate_tool_response', return_value=None, ), patch( 'app.services.shipping_notice.fulfillment_workflow._persist_rpa_success_evidence_asset', - return_value=None, + side_effect=_persist, ): result = rpa_report_upload({ 'task_id': task.task_no, @@ -283,60 +430,43 @@ def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app): 'dom_sha256': __import__('hashlib').sha256(b'
').hexdigest(), }, }) - assert result['status'] == 'failed' - assert result.get('data', {}).get('upload_evidence_persist_failed') is True - assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' - assert db.session.get(ShippingUploadAttempt, attempt.id).status != 'succeeded' + assert result['status'] == 'ok' + assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' + assert db.session.get(ShippingUploadAttempt, attempt.id).evidence_asset_id == 4242 -def test_normalize_rpa_success_evidence_rejects_missing_dom_or_bad_hash(): - """缺少 page_url/dom 或哈希不匹配时必须拒绝。""" +def test_normalize_rpa_success_evidence_requires_minimal_status_summary(): + """受信 RPA 成功证据必须具备可核验的站点、时间、文件和页面定位。""" from app.services.shipping_notice.fulfillment_workflow import _normalize_rpa_success_evidence - import hashlib - - snippet = '
' - digest = hashlib.sha256(snippet.encode('utf-8')).hexdigest() base = { 'kind': 'green_success_dom', 'selector': '#ok', 'filename': 'test.xlsx', 'observed_at': '2026-08-05T03:00:00Z', 'page_url': 'https://example.test/upload', - 'dom_snippet': snippet, - 'dom_sha256': digest, } + base.update({'dom_snippet': '
', 'dom_sha256': __import__('hashlib').sha256(b'
').hexdigest()}) assert _normalize_rpa_success_evidence({'success_evidence': base}) is not None - # 关键断言:缺 page_url / 缺 snippet / 哈希错误一律 None。 + # 关键断言:缺页面定位、选择器、时间或文件名一律拒绝。 bad_url = dict(base, page_url='') assert _normalize_rpa_success_evidence({'success_evidence': bad_url}) is None - bad_snip = dict(base, dom_snippet='') - assert _normalize_rpa_success_evidence({'success_evidence': bad_snip}) is None - bad_hash = dict(base, dom_sha256='0' * 64) - assert _normalize_rpa_success_evidence({'success_evidence': bad_hash}) is None + assert _normalize_rpa_success_evidence({'success_evidence': dict(base, selector='')}) is None + assert _normalize_rpa_success_evidence({'success_evidence': dict(base, observed_at='')}) is None + assert _normalize_rpa_success_evidence({'success_evidence': dict(base, filename='')}) is None -def test_normalize_rpa_success_evidence_requires_dom_contract(): - """缺 page_url / dom_snippet / 哈希不一致时必须拒绝成功证据。""" - import hashlib - +def test_normalize_rpa_success_evidence_rejects_bad_dom_contract(): + """RPA 内部回调仍需 DOM 哈希自洽;这不适用于人工上传确认。""" from app.services.shipping_notice.fulfillment_workflow import _normalize_rpa_success_evidence - snippet = '' - digest = hashlib.sha256(snippet.encode('utf-8')).hexdigest() base = { 'kind': 'dsv_history_green_dom', 'selector': 'em.ok', 'filename': 'test.xlsx', 'observed_at': '2026-08-05T03:00:00Z', 'page_url': 'https://dsv.example/history', - 'dom_snippet': snippet, - 'dom_sha256': digest, + 'dom_snippet': '', + 'dom_sha256': '0' * 64, + 'screenshot_base64': 'legacy-only', } - assert _normalize_rpa_success_evidence({'success_evidence': base}) is not None - # 关键断言:缺 page_url / 缺 snippet / 哈希不匹配均 fail-closed。 - missing_url = dict(base, page_url='') - assert _normalize_rpa_success_evidence({'success_evidence': missing_url}) is None - missing_dom = dict(base, dom_snippet='') - assert _normalize_rpa_success_evidence({'success_evidence': missing_dom}) is None - bad_hash = dict(base, dom_sha256='0' * 64) - assert _normalize_rpa_success_evidence({'success_evidence': bad_hash}) is None + assert _normalize_rpa_success_evidence({'success_evidence': base}) is None diff --git a/backend/tests/test_shipping_vendor_comments_phase2.py b/backend/tests/test_shipping_vendor_comments_phase2.py deleted file mode 100644 index 97a46f7f..00000000 --- a/backend/tests/test_shipping_vendor_comments_phase2.py +++ /dev/null @@ -1,444 +0,0 @@ -""" -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_shipping_workbench_action_contract.py b/backend/tests/test_shipping_workbench_action_contract.py index a92e35b0..61918544 100644 --- a/backend/tests/test_shipping_workbench_action_contract.py +++ b/backend/tests/test_shipping_workbench_action_contract.py @@ -31,7 +31,6 @@ _TABLE: list[tuple[str, str, str, str]] = [ ('confirm_customer', 'confirm_customer', 'pre_create', 'open_customer_dialog'), ('resolve_field_conflicts', 'resolve_field_conflicts', 'pre_create', 'focus_field_conflicts'), ('adjudicate_duplicate', 'adjudicate_duplicate', 'pre_create', 'focus_duplicate_panel'), - ('open_inventory_source_review', 'open_inventory_source_review', 'pre_create', 'open_inventory_candidates'), ('confirm_inventory_source', 'open_inventory_source_review', 'post_create', 'todo'), ('match_inventory', 'open_inventory_match_review', 'post_create', 'todo'), ('rematch', 'open_inventory_match_review', 'post_create', 'todo'), @@ -42,8 +41,7 @@ _TABLE: list[tuple[str, str, str, str]] = [ ('download_excel', 'download_excel', 'post_create', 'download'), ('mark_manual_uploaded', 'open_manual_upload', 'post_create', 'todo'), ('open_manual_upload', 'open_manual_upload', 'post_create', 'todo'), - ('retry', 'retry', 'any', 'retry'), - ('retry_parse', 'retry', 'pre_create', 'retry'), + ('retry_parse', 'retry_parse', 'pre_create', 'retry'), ('refresh', 'refresh', 'any', 'refresh_strip'), ('view_result', 'view_result', 'terminal', 'view_result'), ('open_fulfillment', 'view_result', 'terminal', 'view_result'), @@ -101,13 +99,13 @@ def test_post_create_projection_keeps_fulfillment_write_chain(): status='blocked', stage='inventory_matching', gate={ - 'gate_code': 'inventory_match', + 'gate_code': 'inventory_matching', 'status': 'blocked', 'next_action_code': 'match_inventory', 'blocking_reason_code': 'inventory_shortage', 'attempt_no': 1, }, - legacy_actions=['download_excel'], + authorized_actions=['download_excel'], excel_ready=True, shipping_notice_no='SN-100', ) @@ -175,7 +173,7 @@ def test_pre_create_keeps_inventory_source_review_but_strips_match(): 'blocking_reason_code': 'require_manual_review', 'attempt_no': 1, }, - legacy_actions=['match_inventory', 'generate_excel'], + authorized_actions=['match_inventory', 'generate_excel'], excel_ready=False, shipping_notice_no=None, ) diff --git a/backend/tests/test_shipping_workspace_legacy_audit.py b/backend/tests/test_shipping_workspace_legacy_audit.py deleted file mode 100644 index 91d82c61..00000000 --- a/backend/tests/test_shipping_workspace_legacy_audit.py +++ /dev/null @@ -1,92 +0,0 @@ -""" -tests/test_shipping_workspace_legacy_audit.py - -用途:证明旧工作台写入口(retry / confirm-inventory-source)具备审计四要素。 -依赖:Flask app/client fixture、ShippingTaskEvent、ShippingAuditEvent。 -逻辑:模拟工作台 JWT 用户调用旧路由,断言操作人、时间、内容与前后快照均落库。 -""" -from __future__ import annotations - -from app import db -from app.core.auth.jwt import issue_local_access_token -from app.models import ( - ShippingAuditEvent, - ShippingCase, - ShippingCustomer, - ShippingNotice, - ShippingTaskEvent, - User, -) - - -def _workspace_headers(app, username: str = 'legacy-audit-user') -> tuple[dict[str, str], int]: - """签发工作台用户头,并返回 headers 与 user_id。""" - with app.app_context(): - user = User.query.filter_by(username=username).first() - if user is None: - user = User(username=username, email=f'{username}@example.com', role='user') - db.session.add(user) - db.session.commit() - token = issue_local_access_token(user) - return { - 'Authorization': f'Bearer {token}', - 'Content-Type': 'application/json', - }, int(user.id) - - -def test_workspace_retry_records_actor_and_snapshots(app, client): - """retry 须写入 TaskEvent + ShippingAuditEvent,含操作人与前后快照。""" - headers, user_id = _workspace_headers(app, 'legacy-audit-retry') - with app.app_context(): - customer = ShippingCustomer(standard_name='Legacy Audit Co', short_code='LGA', status='active') - case = ShippingCase(case_no='SC-LEGACY-AUDIT-RETRY', customer=customer) - task = ShippingNotice( - task_no='SN-LEGACY-AUDIT-RETRY', - user_id=user_id, - shipping_case=case, - source_type='manual', - review_status='parse_review', - pending_human_reason='low_confidence', - error_message='timeout', - customer_resolution_status='confirmed', - raw_content='客户:ACME\nA001 x 1', - ) - db.session.add_all([customer, case, task]) - db.session.commit() - - res = client.post( - '/api/workspace/shipping-tasks/SN-LEGACY-AUDIT-RETRY/retry', - headers=headers, - json={'comment': '人工重试'}, - ) - assert res.status_code == 200 - envelope = res.get_json() - assert envelope['success'] is True - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no='SN-LEGACY-AUDIT-RETRY').one() - event = ( - ShippingTaskEvent.query.filter_by(task_id=task.id, event_type='task_retry_requested') - .order_by(ShippingTaskEvent.id.desc()) - .first() - ) - # 关键断言:旧 retry 入口不再匿名,且前后状态可对比。 - assert event is not None - assert event.actor_id == user_id - assert event.created_at is not None - assert event.before_json.get('status') == 'failed' - assert event.after_json.get('status') in {'created', 'parsed'} - audit = ( - ShippingAuditEvent.query.filter_by( - aggregate_type='shipping_task', - aggregate_id='SN-LEGACY-AUDIT-RETRY', - action='retry_task', - ) - .order_by(ShippingAuditEvent.id.desc()) - .first() - ) - assert audit is not None - assert int(audit.actor_id or 0) == user_id - assert audit.before_snapshot_json is not None - assert audit.after_snapshot_json is not None - assert audit.created_at is not None diff --git a/backend/tests/test_shipping_xfa_formal_extraction_route.py b/backend/tests/test_shipping_xfa_formal_extraction_route.py index 19d24a2e..f4a6ded0 100644 --- a/backend/tests/test_shipping_xfa_formal_extraction_route.py +++ b/backend/tests/test_shipping_xfa_formal_extraction_route.py @@ -553,6 +553,12 @@ def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes): assert str(values['price_unit']) == expected['lines'][0]['price_unit'] assert Decimal(str(values['amount'])) == Decimal(expected['lines'][0]['amount']) assert str(values['delivery_date']) == expected['lines'][0]['delivery_date'] + # XFA 仍以 datasets 为正式值源,并把冻结字段 evidence 暴露为统一 Observation 引用。 + material_observation = route.orders[0]['lines'][0]['fields'][0]['observations'][0] + assert material_observation['value_source'] == 'xfa_dataset' + assert isinstance(material_observation['evidence_ref'], dict) + assert material_observation['evidence_ref']['source'] == 'xfa_dataset' + assert 'transform_ref' not in material_observation blob = json.dumps(route.decision, ensure_ascii=False, default=str) assert '' not in blob assert 'datasets_xml' not in blob diff --git a/backend/tests/test_shipping_xfa_publish_separation_of_duties.py b/backend/tests/test_shipping_xfa_publish_separation_of_duties.py index 27c24466..7e16090c 100644 --- a/backend/tests/test_shipping_xfa_publish_separation_of_duties.py +++ b/backend/tests/test_shipping_xfa_publish_separation_of_duties.py @@ -1,7 +1,7 @@ """ tests/test_shipping_xfa_publish_separation_of_duties.py -用途:阶段 6 发布职责分离契约——编辑人不得批准自己的 Revision。 +用途:验证发布确认不再额外限制草稿创建人。 依赖:publish_check_service 已有 consume 阻断键;本文件固化原因码与审计事件集合。 逻辑:纯单元断言职责分离键与编辑审计事件白名单稳定。 """ @@ -17,19 +17,13 @@ from app.services.shipping_notice import order_document_profile_publish_check_se pytestmark = pytest.mark.pure_unit -def test_editor_self_approval_reason_key_is_stable(): - """关键断言:职责分离失败键稳定为 editor_cannot_approve_own_version。""" +def test_editor_self_approval_gate_is_removed(): + """关键断言:消费流程不再包含自己编辑不得发布的门禁。""" source = inspect.getsource(checks.consume_report) - assert 'editor_cannot_approve_own_version' in source - assert '_find_last_profile_editor_id' in source + assert 'editor_cannot_approve_own_version' not in source + assert '_find_last_profile_editor_id' not in source -def test_editor_audit_events_cover_mapping_and_split(): - """关键断言:查找最近编辑者覆盖末端映射与拆分编辑审计事件。""" - source = inspect.getsource(checks._find_last_profile_editor_id) - for event in ( - 'xfa_mapping_saved', - 'xfa_split_rule_suggested', - 'xfa_segment_mapping_updated', - ): - assert event in source +def test_publish_check_service_has_no_editor_separation_helper(): + """关键断言:发布检查服务不再保留历史编辑者查询辅助函数。""" + assert not hasattr(checks, '_find_last_profile_editor_id') diff --git a/backend/tests/test_shipping_xfa_split_rule_contract.py b/backend/tests/test_shipping_xfa_split_rule_contract.py index faccc465..73097851 100644 --- a/backend/tests/test_shipping_xfa_split_rule_contract.py +++ b/backend/tests/test_shipping_xfa_split_rule_contract.py @@ -97,6 +97,18 @@ def test_matcher_whitelist_and_regex_limits(): XfaSplitMatcher(type='regex', pattern=r'(a+)+$') +def test_position_matcher_accepts_restricted_prefix_post_processor(): + """位置选行后可正式执行标签后取值,不能依赖 UI stages[]。""" + matcher = XfaSplitMatcher( + type='position', + line_index=3, + post_processors=[{'type': 'prefix', 'value': 'MPN', 'separators': [':', ':']}], + ) + + assert matcher.post_processors[0].type == 'prefix' + assert matcher.post_processors[0].value == 'MPN' + + def test_rule_set_accepts_rule_id_alias(): """历史 rule_id 字段可解析为 rule_set_id。""" rule_set = XfaSplitRuleSet( diff --git a/backend/tests/test_shipping_xfa_split_rule_engine.py b/backend/tests/test_shipping_xfa_split_rule_engine.py index 9024b7f1..7a758aa4 100644 --- a/backend/tests/test_shipping_xfa_split_rule_engine.py +++ b/backend/tests/test_shipping_xfa_split_rule_engine.py @@ -254,3 +254,32 @@ def test_line_breaks_config_is_honored(): assert 'A' in claimeds unmatched = {item.normalized_text for item in result.evidence_only_segments if item.rule_id == 'unmatched'} assert unmatched == {'B', 'C'} + + +def test_position_rule_applies_prefix_post_processor_to_selected_line(): + """先按行定位,再取标签后内容,保证 XFA 正式规则与预览一致。""" + rule_set = XfaSplitRuleSet( + rule_set_id='mpn-v1', + rule_version=1, + source_path_id='path-x', + source_scope='line', + rules=[ + XfaSplitRule( + rule_id='r-mpn', + matcher=XfaSplitMatcher( + type='position', line_index=3, + post_processors=[{'type': 'prefix', 'value': 'MPN', 'separators': [':', ':']}], + ), + segment=XfaSplitSegment( + segment_id=new_segment_id(), segment_code='part_number', display_name='MPN', + handling='mapped', target_field_id='f-part', target_field_code='part_number', + ), + ), + ], + ) + + result = execute_split_rule_set(raw_value='TEMP-S000218922\nFRAME\nMPN:D4-A08AR12000001', rule_set=rule_set) + + assert result.mapped_fields == {'part_number': 'D4-A08AR12000001'} + assert result.segments[0].raw_text == 'MPN:D4-A08AR12000001' + assert result.segments[0].normalized_text == 'D4-A08AR12000001' diff --git a/backend/tests/test_task_retry_decision_service.py b/backend/tests/test_task_retry_decision_service.py deleted file mode 100644 index ce5d8074..00000000 --- a/backend/tests/test_task_retry_decision_service.py +++ /dev/null @@ -1,292 +0,0 @@ -""" -tests/test_task_retry_decision_service.py - -用途:锁定统一重试决策树的只读分支(noop / fetch)与行级 retryable。 -依赖:task_retry_decision_service、line_inventory_match_projection。 -逻辑:不启全量 Flask;验证决策优先级。 -""" - -from __future__ import annotations - -from types import SimpleNamespace - -from app.services.shipping_notice.line_inventory_match_projection import project_line_retryable -from app.services.shipping_notice.task_retry_decision_service import ( - ACTION_FETCH_INVENTORY, - ACTION_NOOP, - ACTION_REMATCH, - ACTION_AUTO_PROGRESS, - ACTION_FAILED, - _execute, - decide_retry_action_only, - _is_inventory_rpa_active, -) - - -def _task(**kwargs): - defaults = { - 'task_no': 'OT-1', - 'id': 1, - 'upload_status': None, - 'pending_human_reason': None, - 'inventory_lines_json': None, - 'inventory_snapshot_id': None, - 'inventory_source_status': 'resolved', - 'inventory_source_code': 'DSB_SLC', - 'inventory_source_confirmed_by': None, - 'order_data_version': 3, - } - defaults.update(kwargs) - return SimpleNamespace(**defaults) - - -def test_project_line_retryable_hides_shortage_and_running(): - assert project_line_retryable( - inventory_allowed_actions=['retry_inventory_preparation'], - user_line_status='shortage', - ) is False - assert project_line_retryable( - inventory_allowed_actions=['retry_inventory_preparation'], - user_line_status='inventory_file_missing', - inventory_rpa_running=True, - ) is False - assert project_line_retryable( - inventory_allowed_actions=['retry_inventory_preparation'], - user_line_status='inventory_file_missing', - ) is True - - -def test_decide_completed_is_noop(): - task = _task(upload_status='uploaded') - decided = decide_retry_action_only(task, scope='task') - assert decided['action'] == ACTION_NOOP - assert decided['reason_code'] == 'already_completed' - - -def test_decide_missing_snapshot_fetch(monkeypatch): - task = _task(inventory_snapshot_id=None, inventory_lines_json=None) - monkeypatch.setattr( - 'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable', - lambda _t: True, - ) - decided = decide_retry_action_only(task, scope='task') - assert decided['action'] == ACTION_FETCH_INVENTORY - - -def test_decide_rpa_pending_already_running(): - task = _task(pending_human_reason='rpa_pending') - decided = decide_retry_action_only(task, scope='task') - assert decided['action'] == ACTION_NOOP - assert decided['reason_code'] == 'already_running' - - -def test_fulfillable_task_without_excel_continues_auto_progress(monkeypatch): - """库存已完全匹配但 Excel 尚未生成时,任务级重试必须推进后续 Gate。""" - task = _task( - inventory_snapshot_id=7, - inventory_lines_json=[{'part_number': 'PN-1'}], - ) - monkeypatch.setattr( - 'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable', - lambda _t: True, - ) - monkeypatch.setattr( - 'app.services.shipping_notice.task_retry_decision_service._task_match_hint', - lambda _t: {}, - ) - - decided = decide_retry_action_only(task, scope='task') - - assert decided['action'] == ACTION_AUTO_PROGRESS - - -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 - - -def test_execute_rolls_back_before_returning_unexpected_failure(monkeypatch): - """下游数据库失败后,返回失败结果前必须清理 Session,供审计链继续写入。""" - task = _task(task_no='OT-ROLLBACK') - rollback_calls = [] - monkeypatch.setattr( - 'app.services.shipping_notice.task_retry_decision_service.db.session.rollback', - lambda: rollback_calls.append(True), - ) - monkeypatch.setattr( - 'app.services.shipping_notice.tools.auto_progress', - lambda _payload: (_ for _ in ()).throw(RuntimeError('database write failed')), - ) - - result = _execute( - task=task, - user_id=7, - decided={'action': ACTION_AUTO_PROGRESS}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='auto-progress:OT-ROLLBACK:v3', - line_key=None, - ) - - # 关键断言:审计在 _execute 返回后才写,故必须已恢复可用事务。 - assert rollback_calls == [True] - assert result['action'] == ACTION_FAILED - assert result['status'] == 'failed' - - -def test_execute_fetch_retry_rpa_submits_formal_gate_action(monkeypatch): - """正式 retry_rpa 必须提交正式 Gate Action。""" - task = _task(task_no='OT-TRIGGER-DIRECT', inventory_snapshot_id=None, inventory_lines_json=None) - captured: dict[str, object] = {} - monkeypatch.setattr( - 'app.services.shipping_notice.task_retry_decision_service._request_formal_gate_action', - lambda **kwargs: captured.update(kwargs) or {'status': 'running'}, - ) - - result = _execute( - task=task, - user_id=7, - decided={'action': ACTION_FETCH_INVENTORY}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='inventory-fetch:OT-TRIGGER-DIRECT:DSB_SLC:v3', - line_key=None, - trigger='conversation_retry', - ) - - assert result['status'] == 'running' - assert captured['action_code'] == 'retry_inventory_preparation' - - -def test_execute_rematch_submits_formal_gate_action(monkeypatch): - """库存匹配节点重试必须提交正式 Gate Action。""" - task = _task(task_no='OT-REMATCH', inventory_snapshot_id=9, inventory_lines_json=[]) - captured: dict[str, object] = {} - monkeypatch.setattr( - 'app.services.shipping_notice.task_retry_decision_service._request_formal_gate_action', - lambda **kwargs: captured.update(kwargs) or {'status': 'running'}, - ) - - result = _execute( - task=task, - user_id=7, - decided={'action': ACTION_REMATCH}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='inventory-rematch:OT-REMATCH:v3', - line_key=None, - trigger='user_retry', - ) - - assert result['status'] == 'running' - assert captured['action_code'] == 'retry_inventory_from_matching' - - -def test_execute_fetch_uses_formal_gate_action_instead_of_legacy_inventory(monkeypatch): - """外部 retry_rpa 必须提交正式 Gate Action,不能直接执行旧库存函数。""" - task = _task(task_no='OT-FORMAL-RETRY', inventory_snapshot_id=None, inventory_lines_json=None) - captured: dict[str, object] = {} - - import app.services.shipping_notice.task_retry_decision_service as service - import app.services.shipping_notice.inventory_workflow as inventory_workflow - - monkeypatch.setattr(inventory_workflow, 'ensure_inventory', lambda _payload: (_ for _ in ()).throw( - AssertionError('legacy inventory workflow must not be called by external retry') - )) - monkeypatch.setattr( - service, - '_request_formal_gate_action', - lambda **kwargs: captured.update(kwargs) or {'status': 'running', 'action': 'fetch_inventory'}, - raising=False, - ) - - result = service._execute( - task=task, - user_id=7, - decided={'action': ACTION_FETCH_INVENTORY}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='formal-retry:OT-FORMAL-RETRY:v3', - line_key=None, - trigger='user_retry', - ) - - assert result['status'] == 'running' - assert captured['action_code'] == 'retry_inventory_preparation' - - -def test_execute_rematch_uses_formal_gate_action_instead_of_legacy_match(monkeypatch): - """外部 rematch 必须提交正式 Gate Action,不能直接执行旧匹配函数。""" - task = _task(task_no='OT-FORMAL-REMATCH', inventory_snapshot_id=9, inventory_lines_json=[]) - captured: dict[str, object] = {} - - import app.services.shipping_notice.task_retry_decision_service as service - import app.services.shipping_notice.tools as shipping_tools - - monkeypatch.setattr(shipping_tools, 'match_inventory', lambda _payload: (_ for _ in ()).throw( - AssertionError('legacy match workflow must not be called by external retry') - )) - monkeypatch.setattr( - service, - '_request_formal_gate_action', - lambda **kwargs: captured.update(kwargs) or {'status': 'running', 'action': 'rematch'}, - raising=False, - ) - - result = service._execute( - task=task, - user_id=7, - decided={'action': ACTION_REMATCH}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='formal-rematch:OT-FORMAL-REMATCH:v3', - line_key=None, - trigger='user_retry', - ) - - assert result['status'] == 'running' - assert captured['action_code'] == 'retry_inventory_from_matching' diff --git a/backend/tests/test_tasks_0304_chat_fix.py b/backend/tests/test_tasks_0304_chat_fix.py index 1fee59d9..a2fb2fcf 100644 --- a/backend/tests/test_tasks_0304_chat_fix.py +++ b/backend/tests/test_tasks_0304_chat_fix.py @@ -1,6 +1,7 @@ import pytest +from flask import g from app import create_app, db -from app.models import Agent, User +from app.models import Agent, ChatSession, User @pytest.fixture def client(): @@ -97,3 +98,60 @@ def test_chat_url_logic(client): res = client.get('/api/chat/sessions', headers=headers, json={'agent_id': agent_id}) assert res.status_code == 403 assert res.get_json()['error'] == 'Permission denied for this agent' + + +def test_chat_completions_stream_reads_session_snapshot_after_commit(client, monkeypatch): + """ + 提交会话后消费 SSE 时使用标量快照,避免已脱离 Session 的 ORM 实例被延迟刷新。 + + 关键断言:生成器在请求返回后仍能产出 session_created 事件,而不会抛出 + DetachedInstanceError。 + """ + with client.application.app_context(): + user = User(username='stream-user', role='admin', email='stream-user@example.com') + agent = Agent(name='Stream Agent', dify_api_key='test-key', api_base_url='http://dify.invalid') + db.session.add_all([user, agent]) + db.session.commit() + user_id = user.id + agent_id = agent.id + + monkeypatch.setattr( + 'app.services.chat.executors.stream_chat_via_executor', + lambda _context: iter(['data: {"event": "message_end"}\n\n']), + ) + from app.api.chat import completions + + captured_session = None + original_ensure_chat_session = completions._ensure_chat_session + + def capture_ensured_session(*args, **kwargs): + nonlocal captured_session + captured_session = original_ensure_chat_session(*args, **kwargs) + return captured_session + + monkeypatch.setattr(completions, '_ensure_chat_session', capture_ensured_session) + + def get_current_user(): + current_user = db.session.get(User, user_id) + g.current_user = current_user + return current_user + + monkeypatch.setattr('app.core.decorators._get_current_user', get_current_user) + + with client.application.test_request_context( + '/api/chat/completions', + method='POST', + json={'agent_id': agent_id, 'query': '测试流式会话'}, + ): + response = client.application.view_functions['chat.chat_completions']() + # 模拟生产环境:流式处理中的事务令 ORM 属性过期,随后请求 scoped Session 被清理。 + assert captured_session is not None + db.session.expire(captured_session) + db.session.remove() + body = ''.join(response.response).encode() + + assert response.status_code == 200 + assert b'"event": "session_created"' in body + assert b'DetachedInstanceError' not in body + with client.application.app_context(): + assert ChatSession.query.filter_by(user_id=user_id, agent_id=agent_id).count() == 1 diff --git a/backend/tests/test_worker_shipping.py b/backend/tests/test_worker_shipping.py index c7ea8036..2660eff6 100644 --- a/backend/tests/test_worker_shipping.py +++ b/backend/tests/test_worker_shipping.py @@ -53,6 +53,22 @@ def test_shipping_worker_claims_unified_pdf_automark_jobs(monkeypatch): assert JobType.SHIPPING_PDF_AUTOMARK in received['job_types'] +def test_shipping_worker_claims_review_revalidate_jobs(monkeypatch): + """Review Revalidate Job 必须进入 shipping worker 领取白名单,不能永久 queued。""" + received: dict[str, object] = {} + + def claim_next_job(**kwargs): + received.update(kwargs) + return None + + monkeypatch.setattr('app.jobs.queue.claim_next_job', claim_next_job) + + queue_service.claim_next_shipping_notice_job() + + # 关键断言:字段变更后的异步校验任务必须由 shipping worker 领取。 + assert JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS in received['job_types'] + + def test_route_runtime_diagnostic_identifies_loaded_workflow_without_document_content(): """路由审计必须可定位 Worker 代码身份,且不得采集文档或字段内容。""" from app.jobs.handlers import shipping_order_extraction as handler diff --git a/docs/demand.md b/docs/demand.md index 8bb4e3f9..bdf845cc 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -13,7 +13,10 @@ ### 当前业务阶段基线(2026-08) -业务人员只看到四个阶段:`接收解析 → 订单复核 → 通知准备 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;上传或登记回执后进入通知完成。`ui_state` 是唯一前端读模型,按钮由后端统一返回。阶段四的进入不等于上传成功:必须有服务端确认的上传 Attempt 和回执事实;同一 Gate 的全局处理按钮只在右侧“当前处理”出现一次。 +业务人员只看到五个阶段:`接收解析 → 订单复核 → 通知准备 → 货代上传 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`freight_upload`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;下载 Excel、RPA 上传、人工确认、失败重试和未知结果核对属于货代上传。`ui_state` 是唯一前端读模型,按钮由后端统一返回。 + +- **完成口径**:只有 `upload_status=uploaded`、全部预约单均为 `uploaded`、且存在关联 Artifact 的 `ShippingUploadAttempt.status=succeeded` 三项事实同时成立,才进入「通知完成」并计入任务/批次完成率。PDF 候选成功、技术 `completed`、回执文本、取消或归档均不得替代成功事实。 +- **恢复口径**:上传失败、RPA 运行中、人工待登记和历史无成功 Attempt 的 `uploaded` 都停在「货代上传」。未知结果必须先查询货代侧或登记核对证据,禁止自动重试;取消/归档是终态但不计为通知完成。同一 Gate 的全局处理按钮只在右侧“当前处理”出现一次。 - **模式**:直通处理(STP)+ 例外工作台。可信 PDF 自动建 Task 并推进至「Excel 已生成,待人工上传」;解析不确定进入人工复核;建单后异常优先在对话侧 Process Gate 轻量处理,复杂数据进复核工作台。 - **双工作台架构(2026-08-02 冻结)**:对话工作台 = 主入口/主状态/主进度/轻量操作;复核工作台 = 深度编辑与证据处理;Task 工作台 = 仅备用深链(非主导航)。后端工作流始终后台运行,前端只消费状态投影。权威线框见 [review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。 @@ -88,7 +91,7 @@ - **业务需要**:PDF 进入系统至待人工上传的任一业务门禁失败后,应只恢复该门禁(或按精确依赖失效下游),复用输入未变化的上游结果,避免整单重跑或误用失效匹配/Excel。 - **Phase 0**:库存源路由已可在不重识别 PDF 的前提下按最新已发布规则重算;人工决定优先,须显式采用规则建议或保留人工结果。 - **Phase 1**:冻结 20 个门禁编码、状态、恢复动作、失效图与审计事件(见 [process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md));后续阶段再接线模型/API/UI。 -- **中断恢复(2026-08)**:建单前统一恢复协调器(`order_review_resume_service`)在客户确认、重复/冲突裁决、Reservation 重校验、草稿校验、行级履约决定后重算资格;**Gate 通过 / 建单资格 / auto_gate** 三层分离;符合 auto_gate 则幂等自动建单并推进。支持完整明细行先行履约波次(禁止拆分数量);技术 Gate 对业务用户 fail-closed。 +- **中断恢复(2026-08)**:建单前统一恢复协调器(`order_review_resume_service`)在客户确认、重复/冲突裁决、Reservation 重校验、草稿校验、行级履约决定后重算资格;**Gate 通过 / 建单资格 / auto_gate** 三层分离;符合 auto_gate 则幂等自动建单并推进。支持完整明细行先行履约波次(禁止拆分数量);短缺放行后仅当恰有一条开放可履约明细时自动创建 Notice 与其 Excel,多条仍由用户勾选合并,暂不支持批次放行;技术 Gate 对业务用户 fail-closed。 - **Phase 1.5**:字段仅在 `required` 或 `auto_create_key_field` 时因质量问题阻断;可选非关键字段证据不足只诊断不阻断;用户端同一时间最多一个阻断原因;自动冻结资格类原因唯一归属 `order_freeze_readiness`;禁止旧五门禁平行用户投影。 - **权限**:任务所有者与管理员可发起恢复与人工决定;其他人员默认只读,除非另行授予恢复权限;未授权用户不可见。 @@ -96,7 +99,7 @@ - 管理员在受控低清 PDF 画布上配置表头、明细物理行和字段区域,不输入坐标数字;翻页按页加载,离开未保存草稿必须确认。 - 表头行与明细行分别配置。表头识别只能给出当前冻结 Schema 的唯一精确别名建议,不能覆盖人工字段绑定;字段缺失、重复或不确定时保持未映射。 -- 订单级字段作为独立标注域:管理员可用标签锚点、相对值区、多行停止标签和受控规范化配置 Header 字段;不得把账款/送货客户、地址、PO 等标为明细表头或物理行字段。发布前盲测须验证每个订单字段的人工真值与页级字符坐标证据,`confirmed` 字段不可被 Dify 覆盖。 +- 订单级字段作为独立标注域:管理员可用标签锚点、相对值区、多行停止标签和受控规范化配置 Header 字段;对于 PDF 本身无真实标签的稳定字段,可配置单页固定值区,但只在模板唯一匹配、原生 PDF 坐标完整且字段校验通过的正式运行或盲测回放中确认为 `confirmed`。不得把账款/送货客户、地址、PO 等标为明细表头或物理行字段。发布前盲测须验证每个订单字段的人工真值与页级字符坐标证据,`confirmed` 字段不可被 Dify 覆盖。 - 字段规则版本必须保留:文档模板绑定稳定 `field_id` 与创建时 Schema 快照。新增或调整 Schema 版本不得清空既有模板绑定;仅发生字段语义、作用域、类型或证据能力等破坏性变化时,才要求受影响字段显式迁移和重新盲测。 ## 采购合同全面审核补充需求 @@ -223,7 +226,7 @@ ### 3.x 货代发货任务删除与回收站 - **核心目标**:任务列表支持批量删除、归档和回收站恢复;“删除”优先保留可追溯业务事实,而非直接物理删除。 -- **外部一致性门禁**:上传中、已上传、有货代参考号或上传回执的任务只能归档;HXOPS 不得在未接入外部作废能力时单方作废或删除。 +- **外部一致性门禁**:上传中、已上传或已有外部上传参考的任务只能归档;HXOPS 不得在未接入外部作废能力时单方作废或删除。 - **永久删除**:仅管理员可从回收站永久清除无任何业务、解析、库存、导出、修订、重复、外部上传或审计引用的纯误建任务;清除保留独立快照审计。 - **Dify 边界**:本功能不新增、不修改 Dify Tool 或画布节点。Dify 配置无需调整;任务处置由 HXOPS 工作台 API 和后端生命周期门禁处理。 @@ -237,7 +240,8 @@ - **发布与依赖**:识别规则集须草稿/发布/退役并保留不可变审计快照;被启用规则引用的订单字段不可退役或从发布 Schema 移除。 - **Dify 边界**:不新增或修改 Dify Tool/画布;Dify 仅按现有动态契约回传 Header Observation,配置由业务管理员手工核对,HXOPS 后端负责最终裁决、匹配和确认。 -- **双编号**:`ShippingTask.task_no` 继续作为创建即生成且永不修改的内部技术编号;客户确认后生成面向业务的 `business_no`,队列、文件目录、RPA、外键和内部 API 仍使用 `task_no`。 +- **双编号与操作边界**:`ShippingNotice.task_no` 是创建即生成且永不修改的内部技术追踪键;客户确认后为每张发货通知单生成唯一 `business_no`。货代下载、人工确认、RPA 上传、重试、批量操作、文件名与对外 API 均以 `business_no` 为唯一维度;`task_no` 不得作为货代操作参数。 +- **PO 与通知单**:一个 PO 可按不同库存到位批次创建多个 `ShippingNotice`;每张 Notice 冻结本次项次、料号、数量和预约单,并且只生成一个 Excel。后续库存到位必须创建新的 Notice 和新的 `business_no`,不得向已有 Notice 追加 Excel。 - **业务编号格式**:固定为 `{customer_short_code}{YYMMDD}{sequence_2}`,不使用分隔符;例如客户简码 `WYC` 在 2026-07-15 的第 1 票为 `WYC26071501`。 - **客户简码格式**:由管理员维护,全局唯一,固定为 `2-6` 位大写英文字母(`^[A-Z]{2,6}$`);完整业务编号满足 `^[A-Z]{2,6}\d{8}$`。 - **日期与容量**:日期严格按 `Asia/Shanghai` 计算;流水按“客户 + 上海业务日期”独立从 `01` 递增至 `99`,第 100 票必须阻断并提示容量耗尽,禁止归零、覆盖或随机补号。 @@ -286,6 +290,8 @@ - 历史口径曾写“一封 EML = 一个 Intake”;该语义保留为 EML Intake 规则,并扩展直接 PDF Intake。上传阶段只做快览:读取邮件头、正文白名单 HTML 表格快照和附件目录,不抽取附件全文、不创建附件 Document/派生资产、不调度 MinerU/OCR。订单抽取已切换为独立 Run:点击发送直接创建后台作业并轮询 Run/投影状态,不再把 `shipping_intake_nos` 发送给普通 Chatflow;普通无附件问答仍走聊天 SSE。 - 一个附件可包含多个订单,一个订单也可跨正文/多个附件;按实际业务订单生成 Candidate,不按附件数量机械拆分。EML 多 PDF 时每个 PDF 独立 Candidate,禁止跨 PDF 拼行。 - 正文与附件由 HXOPS 的确定性关系规则关联并统一裁决;**有主 PDF 时当前值按 PDF 优先**(见上节);`part_number`/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。订单抽取主链不调用 Dify。 +- 邮件正文补充字段冲突必须可解释并可恢复:新 Finding 固定携带字段/行、双方原值与规范化值、文档/证据引用、严重度和处理状态;金额等字段按 Schema 语义比较,明细按精确 `PO + MPN` 对齐。历史无双方证据的旧冲突不得按空 Case 投影放行,管理员重评估冻结输入后仅清除格式等价假冲突;无法恢复证据时保持阻断并引导重新识别当前 PDF。 +- Draft「保存并校验」必须由后端统一恢复协调器完成资格、Gate 和幂等自动建单入队;前端只显示 `resume_outcome`,不自行推导流程。入队/已排队/运行中均须明确提示,Worker 实际状态以后端处理投影为准。 - 判重以 Candidate 为业务粒度:附件 hash 判断相同文件,业务身份指纹判断同一订单,内容指纹区分完全重复与订单修订。 - 迁移前高置信 Candidate 可自动创建 Batch/Task;订单人工复核目标态切换后,任何 PDF 均必须由对应 Review Case 使用指定草稿版本确认,才可创建 Task。Reservation ID 缺失仍是硬门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。 - 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。 @@ -293,6 +299,8 @@ - 订单附件结构化必须支持版本化订单坐标 Profile v2。模板真相为静态文档锚点、表区相对坐标、独立表头布局、明细物理行布局、字段区域到稳定 `field_id + field_code` 的绑定、注册解析器、跨页/终止规则;表头文字只能用于建议、校准和匹配,不能决定最终字段。已发布版本不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile,不能只保存当前 Profile ID。 - **XFA 客户采购订单(PO)统一解析(2026-08-18)**:普通 PDF 与 XFA 共用同一编辑、自动标注、保存、验证、发布和运行时解析主链。`/XFA datasets + 拆分规则`是 XFA 的首选正式值源;datasets 缺失、受限、Profile/结构不匹配、规则或对账失败时,必须继续进入普通 PDF 共用的 PDFium 原生坐标/OCR 证据链。AcroForm Widget 同时作为统一画布的视觉绑定和自动标注证据。每个 observation 记录 `value_source` 与坐标/引文证据;PDF 证据不得伪装为 datasets。回退结果可创建候选供人工复核,但固定 `needs_review`、禁止 CQ/STP 自动建单;低置信、证据不足或冲突同样不得静默建单。Dify 不参与解析主链。 - **XFA 统一视觉标注、字段拆分与精确解析**:页面画框、自动标注 Job、保存、验证、发布与普通 PDF 使用同一入口和 DTO;服务端仅按已持久化 Profile 能力选择 datasets 或 PDF 证据适配器。XFA `value_binding.type=xfa_dataset` 保持为首选配置,不把 OCR 固化成主映射;确认后的 `visual_binding` 用于定位、复核和审计。拆分优先级固定 `prefix > regex > position > unmatched`,冲突进入 `needs_review`;正则优先 RE2。 +- **XFA 可见值回读补偿(2026-08-25)**:Hybrid XFA 的可见值可能仅由浏览器 PDF.js 外观层绘制,服务端 PDFium/OCR/Widget 因而可为空。工作台依次尝试原生坐标、服务端 OCR、唯一 Widget 与受控浏览器 XFA 画布裁剪 OCR;仍为空时保留管理员已框选的值框并明确提示回读失败,继续允许绑定 datasets。裁剪图不持久化、不进入审计正文、不替代 datasets 正式值。 +- **PDF 订单解析证据链收口(2026-08-21)**:原 PDF 是不可变事实;固定 `matching_features.v1` 仅提供稳定版式匹配输入,坐标统一按当前 Layout、快照补缺、原 PDF、OCR 的顺序按需恢复。Profile 只负责版式,Schema 是唯一字段契约,订单头/订单行共用受限几何变换和字段证据。关键证据缺失、模板歧义/漂移、变换异常、XFA/OCR 冲突均必须进入 Review;自动标注仅辅助 Draft,生产通用解析必须冻结 Parse Plan,Dify 不参与主链或自动建单。 - **XFA 字段拆分映射(历史增量,已由统一方案接管)**:早期曾落地多阶段 `stages[]` 流水线与独立 XFA 映射页。统一方案冻结后,拆分语义以 `prefix > regex > position > unmatched` 为准,工作台并入统一画框编辑器;历史契约文档 [xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md) 仅作迁移对照,不再作为新开发权威。 - 业务管理员必须通过受控样本页面维护订单坐标 Profile:可配置相对区域、静态锚点、独立表头/明细布局和注册解析器;不得编辑 HTML、原始 bbox、JSON、正则、脚本、Prompt 或结构指纹。草稿更新使用乐观锁;每个明细字段区域必须绑定 Schema 允许的 `pdf_coordinate`/`ocr_coordinate` 来源和最低证据等级;不可变版本可复制为新草稿或退役。 - Profile 治理必须保存模板模式、训练样本计数和不含锚点正文的匹配策略摘要;训练/标注样本、盲测样本及其增删、草稿保存、区域/字段绑定变化、测试执行/批准、发布和退役均追加审计。样本文档被训练或盲测引用后不得删除;审计不得保存 PDF、HTML、对象存储地址、正文或凭据。 @@ -327,6 +335,7 @@ - 首次发送无需先创建聊天消息:Run 创建事务会创建本地 ChatSession 并原子绑定尚未归属会话的 Intake,前端使用返回的 `conversation_id` 更新路由。 - 订单识别状态卡必须可在刷新/重新进入会话后按 Run 列表恢复;活动态只显示不确定进度,不按固定轮询频率重复写 ChatLog,只有业务状态变化才原位持久化。 - 订单抽取进度必须来自 HXOPS 持久化的 Run / PDF Unit / Progress Event 数据库事实;用户卡片只展示 `summary/current_activity/available_actions` 及按 PDF 归并结果,不再消费 Dify 节点事件、Workflow 阶段或浏览器 SSE。浏览器继续使用自适应短轮询,页面刷新、重新登录和 Worker 重启后均可恢复同一事实视图。 +- **生命周期工作台进度(2026-08-23)**:复核工作台在 Run 正在解析、重解析或尚未产生 Case 的窗口也必须常驻显示五阶段导航及当前阶段内步骤;步骤只由 `Run / Unit / Progress Event` 的后端投影裁决。任何会触发后端异步自动推进的动作(包括重新解析、重新识别客户后门禁通过、库存/RPA/Excel 恢复)复用同一真实投影;仅打开客户选择或其他同步人工编辑不显示伪造“处理中”。门禁未通过展示稳定阻断原因,失败、取消、排队或长时间无活动在紧凑当前步骤提示中说明原因;不新增 SSE、进度表、状态机、独立状态卡或前端计时猜测。 - **处理进度细化与全链路审计(2026-07-29)**: - 用户可见阶段必须覆盖排队、版面预处理、路由、模板匹配、提取、正文合并、候选生成、人工复核、技术重试、失败、正在取消、已取消、完成;禁止把多种内部态压缩为单一“自动处理中”,禁止虚假百分比或 ETA。 - 普通用户可刷新自己的 Run、取消自己创建的活跃 Run/Unit;管理员可取消任意活跃项但代取消必须填写原因。整批取消为主操作;已完成 PDF 结果保留;仅失败项可重试且保留 Attempt/审计历史。`review_required` 不得显示为技术失败。 @@ -398,9 +407,9 @@ 本节是发货通知后续阶段的冻结业务契约;与本文件此前关于订单真相、制单条件或单份 Excel 的描述不一致时,以本节为准。 -- 履约策略固定为 `SHIP_AVAILABLE_ROLLING`:每轮有效库存核验中,只要至少一个预约单满足,即可由用户确认生成本轮 Excel;系统必须将该任务中全部“满足且未被有效 Excel 占用”的预约单一并写入该 Excel,缺货项继续等待下一轮库存。 +- 履约策略固定为 `SHIP_AVAILABLE_ROLLING`:自动链仅在全部未分配项次满足时创建一张独立发货通知和 Excel;任一项不足即中断。人工可多选“库存满足”或“已审计放行”的完整项次,每次生成一张独立通知与同号 Excel;缺货项继续等待补货或后续放行。 - **试点容量与恢复(阶段 7)**:批量通知文件数、单文件大小、EML 附件数量/单附件大小/总大小均须由环境变量限制,超限在解析和建单前返回明确业务错误;试点先以 3–5 个高频模板逐个完成独立盲测,再根据管理员健康接口记录的 P50/P95、失败率、积压与 RPA 耗时确定正式 SLA。Worker 重启恢复、同文件幂等重试和备份恢复演练均须留存环境、时间、操作者、结果与问题记录;演练失败不得启用自动建单或自动上传。 -- 一个附件可形成一个业务任务,但一个任务可形成多份按时间顺序的 Excel Artifact。全部缺货时不得产生空 Excel;已成功上传的预约单永久不得再次制单;仅当任务全部当前有效预约单均上传成功时才完成。 +- 一个附件可形成一个业务任务;一个 PO 可按库存批次创建多个独立发货通知单,但每张 Notice 只能形成一份 Excel Artifact。全部缺货时不得产生空 Excel;已成功上传的预约单永久不得再次制单;仅当该 Notice 的全部预约单均上传成功时才完成。 - `FieldValue` 仅是解析阶段的 Observation/Decision 投影;人工复核和客户绑定完成后冻结 `OrderSnapshot` 及其行作为库存、制单、上传的正式业务真相。冻结快照不可编辑,后续客户修订必须形成新快照版本。 - **字段分层与履约门禁**:平台系统事实由代码和数据库固定;货代订单字段由「系统标准字段资产(锁定 57 项)+ 扩展字段资产」组成,Schema 版本按需采用并以稳定 `field_id` 冻结。标准目录不是全部必填。当前固定策略 `SHIP_AVAILABLE_ROLLING_V1` 只要求 Line 的 `reservation_id:string`、`part_number:string`、`qty:decimal > 0` 以及已人工确认的 Bill-to 客户;`uom` 暂不强制且不做单位换算。`inventory_source_hint` 仅是可选 Line 路由线索。履约策略本轮不改造管理 UI,但策略绑定只能消费标准字段,不得把扩展字段绑到核心履约能力。 - **Reservation 全局唯一(阶段 1)**:`reservation_id` 单列全局唯一,同一 PO 内也不得重复。PO 比较只去除首尾空格并统一大写,保留前导零和中间字符;不同 PO 必须阻断为重复订单。相同 PO 但料号或数量变化仅返回包含前后差异的人工修订候选,存在有效 Excel Artifact 或已上传时直接阻断;PO 不属于首次履约最小字段,但 Reservation 已注册后若后续记录缺 PO 必须阻断,不能以空 PO 判断修订。 @@ -409,7 +418,7 @@ - 预约单以全局注册表管理,而非以历史订单行文本去重。唯一预约单在任一时刻只能处于 `pending`、`available`、`artifact_reserved`、`uploaded` 或 `external_change_required` 之一,并只允许归属一个有效 Artifact。 - Excel 文件名允许由已发布 Excel 模板的版本化命名规则定义;没有模板规则时可使用受控环境变量默认规则。后端必须校验规则、生成最终文件名并在 Artifact 冻结规则来源/版本、文件名和流水;前端、Dify 或普通用户不得提交任意文件名。 - Dify 仅生成候选 Observation,不能创建 Task、冻结 Snapshot、选择库存、生成 Excel 或触发上传。任何关键字段含未人工确认的 LLM fallback Observation 时,必须转人工复核并阻断自动冻结。 -- 人工上传是 RPA 的受控降级,必须上传截图或回执文件;没有外部成功证据不得将预约单标记为已上传。 +- 人工上传是 RPA 的受控降级:业务人员仅按 `business_no` 确认已上传,不上传截图、回执或 PDF;服务端仍通过该 Notice 的受控 Attempt 与状态机记录成功事实。 - 上传以 Excel Artifact 为边界:每次 RPA 或人工操作均创建独立 Attempt,trigger 和回调必须携带 `artifact_id`、`attempt_id` 与幂等 `callback_id`。相同回调只生效一次;网络失败只能重试原 Artifact,只有货代明确拒绝并经授权才可作废 Artifact、释放未上传预约单;Task 上传字段仅为 Artifact/Attempt 的聚合投影。 ### 3.1 本期范围 diff --git a/docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html b/docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html index 52c83252..d0f966f5 100644 --- a/docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html +++ b/docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html @@ -12,14 +12,19 @@ @@ -33,11 +38,18 @@ +
+
评审对话走查(演示)
+ + + + +
仓
仓库管理人员在途仓调拨 Agent
-
AI
在途仓自动调拨Chat 首页 · 仅展示摘要与入口
/chat/:agentId
+
AI
在途仓自动调拨Chat 首页 · 仅展示摘要与入口
调拨中心
@@ -45,20 +57,20 @@ - - diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue index fb2b35f4..8832c7af 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileBlindTestPage.vue @@ -178,7 +178,8 @@ function stopUploadPolling(): void { async function pollUploadedSample(intakeNo: string): Promise { try { const result = await getOrderProfileSampleStatus(intakeNo); - if (result.parse_status === 'parsed' && result.document_count > 0) { + // 与样本列表的可见条件一致:文档物化且 Layout ready 后才进入候选列表。 + if (result.parse_status === 'parsed' && result.document_count > 0 && result.layout_status === 'ready') { await loadAvailableSamples(true); const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id)); if (selected) { @@ -192,7 +193,7 @@ async function pollUploadedSample(intakeNo: string): Promise { } return; } - if (['failed', 'error'].includes(result.parse_status)) { + if (['failed', 'error'].includes(result.parse_status) || result.layout_status === 'failed') { await loadAvailableSamples(true); const selected = availableSamples.value.find((item) => (result.document_ids || []).includes(item.document_id)); if (selected) { diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue index d63aead0..a49a8d5d 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue @@ -21,6 +21,7 @@ import { BusinessError } from "@/shared/api/client"; import { useMessage } from "@/shared/composables/useMessage"; import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api"; import { + authorizeOrderProfilePreviewPages, authorizeOrderProfilePdfPreview, addOrderProfileTrainingSample, listOrderDocumentProfiles, @@ -29,6 +30,7 @@ import { enqueueOrderProfilePdfAutomark, generateOrderProfileOcrCoordinateEvidence, getOrderProfilePdfAutomarkJob, + getOrderProfileSampleStatus, getOrderProfileSampleTables, listOrderProfileValidationRuns, listOrderProfileBoundSamples, @@ -47,13 +49,15 @@ import type { OrderFieldValuePreview, OrderProfileCanvasRegion, OrderProfileDocumentMatchAnchor, + OrderCoordinateProfileDefinition, OrderProfileFieldRegion, OrderProfileRelativeRegion, OrderProfileBoundSample, OrderFieldLayoutSuggestion, - OrderProfileRowReconstructionMode, ShippingOrderDocumentProfile, + OrderProfileSampleIntake, OrderProfileValidationRun, + OrderProfilePreviewPages, } from "@/features/admin/types/shipping-order-document-profile.types"; import { asVisualProfileDefinition, @@ -69,6 +73,10 @@ import XfaDatasetTree from "./components/XfaDatasetTree.vue"; import XfaSplitRulePanel from "./components/XfaSplitRulePanel.vue"; import { useOrderProfileValueAdapter } from "./composables/useOrderProfileValueAdapter"; import { + filterRegionsAfterRemoval, + resolveSelectedOrderAnchorId, + resolveMainTableIdForPageChange, + shouldKeepUnreadableOrderField, resolveSharedCanvasDocument, resolveDeskAdapter, resolveValueAdapterKey, @@ -81,16 +89,23 @@ import { suggestFieldCodeFromHeaders, toOrderProfileAnchorId, buildOrderProfileRecognitionResults, + buildOrderProfileCanvasLineFieldValues, selectCurrentDatasetsValidationEvidence, groupUniqueOrderProfileLineFields, + restoreFormalBindingFieldCodes, + reconcileAutomarkOrderFieldRegions, normalizeOrderProfileRelativeRegion, buildAutomarkSuggestedRegions, normalizeAutomarkFieldCandidates, + restoreReservationIdRegion, + preferredAutomarkTableSource, selectAutomarkReconstruction, summarizeAutomarkTableCandidates, toOrderProfileHeaderFieldRegion, resolveCoordinateFieldScope, isOrderProfileVisualFieldEligible, + buildAutomarkSuggestionSummary, + type AutomarkSuggestionContext, } from "./orderProfileForm.utils"; const { t } = useI18n(); @@ -116,8 +131,11 @@ const samples = ref< const schemas = ref([]); const active = ref(null); const boundSamples = ref([]); -/** 坐标 PDF 与 XFA 共用原 PDF + PDF.js 画布;PDFium 页图仅留给后端证据生成。 */ +/** 自动标注前必须由服务端确认当前 annotation 样本的 Layout/主表/证据三项均已就绪。 */ +const automarkSampleReadiness = ref(null); +/** 普通 PDF 使用 PDFium 页图;显式 XFA 模板才申请原 PDF 交给 PDF.js 渲染动态外观。 */ const pdfPreviewGrant = ref<{ document_id: number; preview_token: string; expires_in_seconds: number } | null>(null); +const previewPages = ref(null); const pdfPageCount = ref(1); const pageNo = ref(1); const sampleTables = ref< @@ -137,8 +155,10 @@ const orderFieldValueState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle' const orderFieldValueError = ref(''); const selectedVisualSampleValue = ref(null); const selectedVisualSampleState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle'); +const visualSampleCache = new Map(); +const VISUAL_SAMPLE_TIMEOUT_MS = 10000; /** 当前选区视觉样本的实际证据来源;仅供管理员交叉复核,不能替代 datasets 正式值。 */ -const selectedVisualSampleSource = ref<'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget' | null>(null); +const selectedVisualSampleSource = ref<'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget' | 'xfa_rendered_ocr' | null>(null); const previewError = ref(""); const headerSuggestions = ref< Array<{ @@ -151,7 +171,14 @@ const headerSuggestions = ref< }> >([]); const orderFieldSuggestions = ref([]); -const pendingSuggestion = ref<{ id: string; checksum: string; summary: Record; regions: OrderProfileCanvasRegion[] } | null>(null); +/** 待确认候选冻结任务身份;翻页只能改变画布视图,不能改变接受请求的审计身份。 */ +const pendingSuggestion = ref<{ + id: string; + checksum: string; + context: AutomarkSuggestionContext; + summary: Record; + regions: OrderProfileCanvasRegion[]; +} | null>(null); const automarkTableCandidates = ref>([]); const automarkTableCandidateSummaries = ref>([]); const selectedAutomarkTableSource = ref(''); @@ -165,6 +192,7 @@ const documentCanvas = ref<{ zoomIn: () => void; zoomOut: () => void; resetZoom: () => void; + captureRegion: (region: OrderProfileRelativeRegion) => string | null; } | null>(null); const previewState = ref<"idle" | "updating" | "ready" | "failed">("idle"); const canvasUnavailable = ref(false); @@ -173,6 +201,12 @@ const leaveConfirmOpen = ref(false); let resolveRouteLeave: ((allowed: boolean) => void) | null = null; const suggestingRegions = ref(false); const suggestionProgress = ref(""); +type AutomarkStage = 'idle' | 'checking' | 'queued' | 'analyzing' | 'building' | 'review' | 'failed' | 'complete'; +const automarkStage = ref('idle'); +const automarkStagePercent: Record = { + idle: 0, checking: 15, queued: 30, analyzing: 55, building: 75, review: 100, failed: 100, complete: 100, +}; +const automarkProgressPercent = computed(() => automarkStagePercent[automarkStage.value]); const creationKind = ref(null); const pendingDocumentAnchorLabel = ref(null); const pendingOrderFieldAnchor = ref(null); @@ -217,7 +251,7 @@ const valueAdapterDesk = reactive(useOrderProfileValueAdapter({ const deskAnnotationContext = computed(() => ({ ...resolveSharedCanvasDocument({ documentId: form.documentId, - mainTableId: String((active.value?.definition as { main_table_id?: string } | undefined)?.main_table_id || ''), + mainTableId: mainTableId.value, sampleTableId: form.tableId, }), pageNo: pageNo.value, @@ -254,6 +288,10 @@ const xfaConfigReadonly = computed(() => ( * XFA 后台仍可走 automark Job,但 UI 不再使用专用 OCR 底栏。 */ async function onDeskCanvasSuggest(): Promise { + if (!automarkSampleReadiness.value?.automark_ready) { + message.warning(automarkReadinessMessage(automarkSampleReadiness.value?.automark_reason_code)); + return; + } void suggestRegions(); } @@ -268,6 +306,12 @@ function onDeskCanvasCreate(region: OrderProfileRelativeRegion): void { * 画布选中:统一视觉 adapter 负责写回其末端取值定义。 */ function onDeskCanvasSelect(id: string): void { + if (id === 'reservation_id_region') { + reservationIdRegionSelected.value = true; + selectedId.value = null; + return; + } + reservationIdRegionSelected.value = false; canvasActions.value.select(id); const region = regions.value.find((item) => item.id === id); if (hasValueSourceMapping.value && region && ['order_field', 'header_field', 'field'].includes(region.kind)) { @@ -301,6 +345,10 @@ function onDeskCanvasEnd(): void { * 画布几何变更。 */ function onDeskCanvasChange(id: string, region: OrderProfileRelativeRegion): void { + if (id === 'reservation_id_region') { + updateReservationIdRegion(region); + return; + } canvasActions.value.change(id, region); } @@ -329,6 +377,11 @@ function onDeskCanvasDuplicate(): void { * 画布删除选中框。 */ function onDeskCanvasDelete(): void { + if (reservationIdRegionSelected.value) { + clearReservationIdRegion(); + reservationIdRegionSelected.value = false; + return; + } canvasActions.value.remove(); } @@ -353,8 +406,12 @@ let leaseRenewing = false; let autosaveFailures = 0; let localChangeVersion = 0; let previewTimer: number | null = null; +/** 预览请求代次;旧的异步响应不得覆盖较新的 Profile 定义或样本选择。 */ +let previewRequest = 0; let orderFieldValueTimer: number | null = null; let pendingGestureId: string | null = null; +let activeGestureId: string | null = null; +let activeGestureMoved = false; let pendingFormEdit: OrderProfileCanvasRegion[] | null = null; let pendingFieldBinding: { fieldCode: string | null; fieldLayoutId: string; scope: 'header' | 'line' } | null = null; let restoringProfile = false; @@ -367,13 +424,16 @@ const form = reactive({ tableId: "", changeNote: "", }); +/** 冻结的模板主表身份;与当前 PDF 页用于预览的表身份严格分离。 */ +const mainTableId = ref(''); +/** 管理员选择候选表后,须经二次确认才允许覆盖冻结主表。 */ +const pendingMainTableRepairId = ref(''); +const mainTableRepairConfirmOpen = ref(false); const regions = ref([]); /** 已提交版面重解析时禁用重复请求;不修改草稿或样本绑定。 */ const reparsingLayout = ref(false); -/** 每个明细表区的重建策略与页范围独立保存,避免画布重开/保存时回退为默认固定子行。 */ +/** 每个明细表区仅保留视觉证据来源;页范围与行重建由运行时自动决策。 */ const tableRegionSettings = reactive>({}); /** 文档匹配锚点独立于字段坐标;必须以固定标签和固定值关系区分模板。 */ @@ -384,6 +444,25 @@ const documentMatch = reactive({ minimumMargin: 0.15, }); const documentMatchDirty = ref(false); +/** 已冻结主表无法重建明细时,管理员可从受控候选中明确恢复。 */ +const repairingMainTable = ref(false); +/** Reservation ID 专用证据区域;管理员只标记这一处,不配置来源/拆分 JSON。 */ +const reservationIdRegion = ref<{ + region: OrderProfileRelativeRegion; + page_scope: 'exact_page'; + page_no: number; +} | null>(null); +const reservationIdRegionDirty = ref(false); +const reservationIdRegionSelected = ref(false); +/** Reservation 区域的服务端统一解析结果;只用于标注时核验,正式解析仍在后端执行。 */ +const reservationIdCandidates = ref>([]); +const reservationIdCandidateState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle'); /** * 共同画布的字段选项只决定视觉定位;coordinate 末端值源仍必须由 Schema 显式授权 * pdf_coordinate。XFA 的正式取值来自 datasets,不能因未授权 PDF 文本而在画布中消失。 @@ -430,15 +509,8 @@ const pageRegions = computed(() => regions.value.filter((item) => item.pageNo === pageNo.value), ); const activePageHasLines = computed(() => pageRegions.value.some((item) => item.kind === 'line')); -const activeTableRegionSetting = computed(() => tableRegionSettings[pageNo.value] || { - rowReconstructionMode: 'fixed_subrows' as const, - pageScope: 'exact_page' as const, - visualEvidenceSource: null, -}); const ensureTableRegionSetting = (targetPageNo: number) => { tableRegionSettings[targetPageNo] ||= { - rowReconstructionMode: 'fixed_subrows', - pageScope: 'exact_page', visualEvidenceSource: null, }; return tableRegionSettings[targetPageNo]; @@ -474,7 +546,10 @@ const visualCanvas = computed(() => { actions: coordinateCanvasActions.value, documentReady: Boolean(form.documentId && form.tableId), preview: pdfPreviewGrant.value, - previewPagePath: `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/pdf-preview`, + grant: previewPages.value?.pages.find((item) => item.page_no === pageNo.value) || null, + previewPagePath: valueAdapterKey.value === 'xfa_dataset' + ? `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/pdf-preview` + : `/api/admin/shipping-notice/order-document-profiles/${active.value?.id || 0}/preview-pages`, regions: pageRegions.value, selectedRegionId: selectedId.value, creationKind: creationKind.value, @@ -538,7 +613,7 @@ const draftSaveAdapter = computed(() => ( applySavedDraft: async (saved) => valueAdapterDesk.applySavedDraft(saved as ShippingOrderDocumentProfile), }, coordinate_ocr: { - hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value, + hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value || reservationIdRegionDirty.value, skipUnchangedManualSave: false, canSave: issues.value.length === 0, canValidate: issues.value.length === 0, @@ -551,11 +626,69 @@ const draftSaveAdapter = computed(() => ( )); const deskCanvasDocumentReady = computed(() => visualCanvas.value.documentReady); const deskCanvasPreview = computed(() => visualCanvas.value.preview); +const deskCanvasGrant = computed(() => visualCanvas.value.grant); const deskCanvasPreviewPagePath = computed(() => visualCanvas.value.previewPagePath); -const deskCanvasRegions = computed(() => visualCanvas.value.regions); -const deskSelectedRegionId = computed(() => visualCanvas.value.selectedRegionId); +/** + * 把待确认候选投影为只读预览层;正式 regions 始终保持不变,接受建议后才落盘。 + * 同 ID 的旧自动区域由候选替换,避免用户同时看到两套重叠框。 + */ +const deskCanvasRegions = computed(() => { + const current = visualCanvas.value.regions; + const reservationRegion = reservationIdRegion.value && reservationIdRegion.value.page_no === pageNo.value + ? [{ + id: 'reservation_id_region', + kind: 'reservation_id_region' as const, + label: 'Reservation ID 区域', + region: { ...reservationIdRegion.value.region }, + pageNo: reservationIdRegion.value.page_no, + }] + : []; + const pending = pendingSuggestion.value; + if (!pending) return [...current, ...reservationRegion]; + const pendingIds = new Set(pending.regions.map((region) => region.id)); + const previewRegions = pending.regions + .filter((region) => region.pageNo === pageNo.value) + .map((region) => ({ ...region, isPreview: true })); + return [ + ...current.filter((region) => !pendingIds.has(region.id)), + ...reservationRegion, + ...previewRegions, + ]; +}); +const deskSelectedRegionId = computed(() => ( + reservationIdRegionSelected.value ? 'reservation_id_region' : visualCanvas.value.selectedRegionId +)); const deskCreationKind = computed(() => visualCanvas.value.creationKind); -const deskAutoSuggestDisabled = computed(() => visualCanvas.value.autoSuggestDisabled); +const automarkReadinessMessage = (reasonCode?: string | null): string => { + const keyByReason: Record = { + layout_not_ready: 'autoSuggestLayoutNotReady', + main_table_missing: 'autoSuggestMainTableRequired', + main_table_ambiguous: 'autoSuggestMainTableAmbiguous', + layout_content_hash_mismatch: 'autoSuggestLayoutStale', + layout_checksum_mismatch: 'autoSuggestLayoutStale', + document_missing: 'autoSuggestSampleMissing', + }; + return t(`admin.shippingOrderProfiles.workbench.${keyByReason[reasonCode || ''] || 'autoSuggestEvidencePending'}`); +}; +/** 刷新当前 annotation 文档对应 Intake;服务端会在此处幂等补齐可安全冻结的证据。 */ +const refreshAutomarkSampleReadiness = async (): Promise => { + const intakeNo = samples.value.find((item) => item.document_id === form.documentId)?.intake_no; + if (!intakeNo) { + automarkSampleReadiness.value = null; + return null; + } + const status = await getOrderProfileSampleStatus(intakeNo); + const currentProfileState = status.sample_readiness?.find( + (item) => item.profile_id === active.value?.id && item.document_id === form.documentId, + ); + automarkSampleReadiness.value = currentProfileState + ? { ...status, ...currentProfileState, sample_readiness: [currentProfileState] } + : { ...status, automark_ready: false, automark_reason_code: 'document_missing' }; + return automarkSampleReadiness.value; +}; +const deskAutoSuggestDisabled = computed(() => ( + visualCanvas.value.autoSuggestDisabled || !automarkSampleReadiness.value?.automark_ready +)); const deskPageNo = computed(() => visualCanvas.value.pageNo); const deskPageCount = computed(() => visualCanvas.value.pageCount); const deskSaveDisabled = computed(() => visualCanvas.value.saveDisabled); @@ -571,10 +704,15 @@ const deskUndoDisabled = computed(() => visualCanvas.value.undoDisabled); const deskRedoDisabled = computed(() => visualCanvas.value.redoDisabled); const deskDuplicateDisabled = computed(() => visualCanvas.value.duplicateDisabled); const deskDeleteDisabled = computed(() => visualCanvas.value.deleteDisabled); -const deskHasSelection = computed(() => visualCanvas.value.hasSelection); -const deskSelectedKindLabel = computed(() => visualCanvas.value.selectedKindLabel); -const deskSelectedGeometry = computed(() => visualCanvas.value.selectedGeometry); -const deskActivePageHasLines = computed(() => visualCanvas.value.activePageHasLines); +const deskHasSelection = computed(() => visualCanvas.value.hasSelection || reservationIdRegionSelected.value); +const deskSelectedKindLabel = computed(() => ( + reservationIdRegionSelected.value ? 'Reservation ID 证据区域' : visualCanvas.value.selectedKindLabel +)); +const deskSelectedGeometry = computed(() => { + if (!reservationIdRegionSelected.value || !reservationIdRegion.value) return visualCanvas.value.selectedGeometry; + const r = reservationIdRegion.value.region; + return `P${reservationIdRegion.value.page_no} · ${r.x0.toFixed(3)}, ${r.y0.toFixed(3)} - ${r.x1.toFixed(3)}, ${r.y1.toFixed(3)}`; +}); const deskHeaderRecognitionResults = computed(() => visualCanvas.value.headerRecognitionResults); const deskLineRecognitionResults = computed(() => visualCanvas.value.lineRecognitionResults); const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly); @@ -589,6 +727,15 @@ const onDeskRejectSuggestion = () => visualCanvas.value.rejectSuggestion(); const deskPendingSuggestionCount = computed(() => ( pendingSuggestion.value?.regions.length || 0 )); +const pendingSuggestionPageNo = computed(() => pendingSuggestion.value?.context.pageNo || null); +const pendingSuggestionIsOffCanvasPage = computed(() => ( + pendingSuggestionPageNo.value !== null && pendingSuggestionPageNo.value !== pageNo.value +)); +/** 返回待确认候选的冻结页面;不限制管理员先浏览其他页面。 */ +const returnToPendingSuggestionPage = (): void => { + const targetPageNo = pendingSuggestionPageNo.value; + if (targetPageNo !== null) void selectPage(targetPageNo); +}; const hasAutomarkTableChoice = computed(() => automarkTableCandidates.value.length > 1); const automarkTableChoiceRequired = computed(() => hasAutomarkTableChoice.value && !selectedAutomarkTableSource.value); const automarkFieldChoiceRequired = computed(() => automarkFieldConflicts.value.some((item) => !selectedAutomarkFieldSources[item.field_id])); @@ -598,16 +745,6 @@ const deskSaveButtonDisabled = computed(() => ( const updateDeskPageCount = (count: number): void => { visualCanvas.value.setRenderedPageCount(count); }; -const deskTableRegionSetting = computed(() => ( - activeTableRegionSetting.value -)); -const deskTableConfigReadonly = computed(() => ( - compactEditor.value || saveState.value === 'readonly' -)); -const updateActiveTableRegionSetting = () => { - checkpoint(); - schedulePreview(); -}; const selectedRegion = computed( () => pageRegions.value.find((item) => item.id === selectedId.value) || null, ); @@ -651,6 +788,7 @@ const selectedRegionSampleSourceLabel = computed(() => { pdf_coordinate: t('admin.shippingOrderProfiles.workbench.visualEvidenceSources.pdf_coordinate'), ocr_coordinate: t('admin.shippingOrderProfiles.workbench.visualEvidenceSources.ocr_coordinate'), acroform_widget: t('admin.shippingOrderProfiles.workbench.visualEvidenceSources.acroform_widget'), + xfa_rendered_ocr: t('admin.shippingOrderProfiles.workbench.visualEvidenceSources.xfa_rendered_ocr'), }; return labels[source]; }); @@ -675,6 +813,7 @@ const selectedRegionKindLabel = computed(() => { order_anchor: 'orderAnchor', order_field: 'orderField', header_field: 'header', header: 'header', line: 'line', field: 'field', exclusion: 'exclusion', document_anchor_label: 'documentMatchAnchorLabel', document_anchor_value: 'documentMatchAnchorValue', + reservation_id_region: 'drawReservationIdRegionShortcut', }; const translationKey = translationKeys[kind]; return t(`admin.shippingOrderProfiles.workbench.${translationKey}`); @@ -688,9 +827,25 @@ const recognitionResults = computed(() => buildOrderProfileRecognitionResults( hasValueSourceMapping.value ? selectCurrentDatasetsValidationEvidence(validationRuns.value, active.value?.structure_fingerprint) : null, + reservationIdCandidates.value, )); const headerRecognitionResults = computed(() => recognitionResults.value.header); const lineRecognitionResults = computed(() => recognitionResults.value.line); +/** 仅在当前主表没有任何逻辑明细、且样本文档存在其它表时提供恢复入口。 */ +const mainTableRepairCandidates = computed(() => sampleTables.value.filter((item) => ( + item.table_id !== mainTableId.value +))); +const canRepairMainTable = computed(() => ( + !hasValueSourceMapping.value + && previewState.value === 'ready' + && !lineRecognitionResults.value.length + && mainTableRepairCandidates.value.length > 0 + && saveState.value !== 'readonly' +)); +const canvasLineFieldValues = computed(() => buildOrderProfileCanvasLineFieldValues( + pageRegions.value, + preview.value, +)); /** * 识别结果点击:统一视觉 adapter 选择其对应标注。 @@ -820,6 +975,57 @@ const canonicalSuggestionJson = (value: unknown): string => { }; /** 为每次本地变更编号,阻止飞行保存的旧响应清除后续编辑。 */ const markLocalChange = () => { localChangeVersion += 1; }; +/** 保存 Reservation ID 专用区域,并纳入普通 Profile 草稿自动保存。 */ +const updateReservationIdRegion = (region: OrderProfileRelativeRegion): void => { + reservationIdRegion.value = { region: { ...region }, page_scope: 'exact_page', page_no: pageNo.value }; + reservationIdRegionDirty.value = true; + markLocalChange(); + scheduleAutosave(); +}; +const clearReservationIdRegion = (): void => { + reservationIdRegion.value = null; + reservationIdRegionDirty.value = true; + markLocalChange(); + scheduleAutosave(); +}; +/** + * 读取当前圈选区域的 Reservation 候选。 + * 核心逻辑:编辑器预览调用与正式解析相同的后端固定解析器,前端不自行推断行归属。 + */ +const refreshReservationIdCandidates = async (): Promise => { + const configured = reservationIdRegion.value; + if (!active.value || !form.documentId || !configured) { + reservationIdCandidates.value = []; + reservationIdCandidateState.value = 'idle'; + return; + } + reservationIdCandidateState.value = 'loading'; + try { + const result = await readOrderProfilePreviewPageRegionText( + active.value.id, + form.documentId, + configured.page_no, + configured.region, + undefined, + 'reservation_id_region', + ); + reservationIdCandidates.value = result.reservation_candidates || []; + reservationIdCandidateState.value = 'ready'; + } catch { + reservationIdCandidates.value = []; + reservationIdCandidateState.value = 'failed'; + } +}; +watch( + () => { + const configured = reservationIdRegion.value; + return configured + ? `${active.value?.id || 0}:${form.documentId}:${configured.page_no}:${JSON.stringify(configured.region)}` + : ''; + }, + () => { void refreshReservationIdCandidates(); }, + { immediate: true }, +); /** 对区域变更建立一个可恢复检查点,并清空分叉后的 redo 历史。 */ const checkpoint = () => { history.value.push(snapshot()); @@ -928,6 +1134,14 @@ const redo = () => { scheduleAutosave(); }; /** 添加一种标注区域;真实坐标由画布拖动调整,避免管理员输入数字。 */ +/** + * 将画布框选区域加入当前草稿。 + * 核心逻辑:订单字段值框可绑定当前明确选中的订单字段标签,也可在没有稳定标签时作为固定区域保存; + * 禁止静默继承页面上其他订单锚点。 + * @param kind - 用户当前选择的画布工具类型。 + * @param drawnRegion - 本次拖拽得到的归一化区域。 + * @param selectedText - 已识别的区域文本,仅供需要文本的区域使用。 + */ const addRegion = ( kind: OrderProfileCanvasRegion["kind"], drawnRegion?: OrderProfileRelativeRegion, @@ -939,10 +1153,10 @@ const addRegion = ( pageRegions.value.filter((item) => item.kind === effectiveKind).length + 1; const selectedLayout = selectedRegion.value?.kind === "line" ? selectedRegion.value : null; - const selectedOrderAnchor = - selectedRegion.value?.kind === "order_anchor" - ? selectedRegion.value - : pageRegions.value.find((item) => item.kind === "order_anchor") || null; + const selectedOrderAnchorId = resolveSelectedOrderAnchorId(selectedRegion.value); + const selectedOrderAnchor = selectedOrderAnchorId + ? pageRegions.value.find((item) => item.id === selectedOrderAnchorId) || null + : null; const existingHeaderField = effectiveKind === "header_field" && drawnRegion ? pageRegions.value.find( @@ -1037,7 +1251,10 @@ const startDrawing = (kind: OrderProfileCanvasRegion["kind"]) => { const readDocumentAnchorText = async (region: OrderProfileRelativeRegion): Promise => { if (!active.value || !form.documentId) return null; try { - const result = await readOrderProfilePreviewPageRegionText(active.value.id, form.documentId, pageNo.value, region); + const result = await readOrderProfilePreviewPageRegionText( + active.value.id, form.documentId, pageNo.value, region, undefined, undefined, + documentCanvas.value?.captureRegion(region), + ); return result.text.trim() || null; } catch (error) { fail(error); @@ -1048,6 +1265,10 @@ const readDocumentAnchorText = async (region: OrderProfileRelativeRegion): Promi const createDrawnRegion = async (region: OrderProfileRelativeRegion) => { const kind = creationKind.value; creationKind.value = null; + if (kind === 'reservation_id_region') { + updateReservationIdRegion(region); + return; + } if (kind === 'document_anchor_label') { const label = await readDocumentAnchorText(region); if (!label) { @@ -1123,22 +1344,25 @@ const createDrawnRegion = async (region: OrderProfileRelativeRegion) => { } if (kind === 'order_field' && pendingOrderFieldAnchor.value) { const value = await readDocumentAnchorText(region); - if (!value) { + if (!shouldKeepUnreadableOrderField(valueAdapterKey.value, kind, Boolean(value))) { documentAnchorNotice.value = t('admin.shippingOrderProfiles.workbench.documentMatchAnchorTextMissing'); creationKind.value = 'order_field'; return; } const anchor = pendingOrderFieldAnchor.value; const valueRegion: OrderProfileCanvasRegion = { - id: anchor.orderFieldId!, kind, label: value, region, parentId: anchor.id, + id: anchor.orderFieldId!, kind, region, parentId: anchor.id, // The Schema selector uses null for its explicit "unbound" option. Do not // leave this undefined, otherwise a newly drawn value box can retain the // previous selected address field in the browser control. - fieldCode: null, orderFieldId: anchor.orderFieldId, valueMode: 'single_line', suggestedValue: value, pageNo: pageNo.value, + fieldCode: null, orderFieldId: anchor.orderFieldId, valueMode: 'single_line', suggestedValue: value, + label: value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable'), pageNo: pageNo.value, }; regions.value.push(valueRegion); pendingOrderFieldAnchor.value = null; - documentAnchorNotice.value = ''; + documentAnchorNotice.value = value + ? '' + : t('admin.shippingOrderProfiles.workbench.xfaVisualReadbackUnavailable'); selectedId.value = valueRegion.id; markLocalChange(); schedulePreview(); @@ -1186,16 +1410,12 @@ const removeSelected = () => { if (!selectedRegion.value) return; checkpoint(); const removedId = selectedRegion.value.id; - const removesSharedAnchor = selectedRegion.value.kind === "order_anchor"; const documentAnchorId = ['document_anchor_label', 'document_anchor_value'].includes(selectedRegion.value.kind) ? selectedRegion.value.parentId : null; // Removing a shared label removes dependent value boxes; removing one value box // preserves the label and any sibling customer/address field. - regions.value = regions.value.filter( - (item) => item.id !== removedId && item.parentId !== removedId && - (!removesSharedAnchor || item.parentId !== removedId) && item.parentId !== documentAnchorId, - ); + regions.value = filterRegionsAfterRemoval(regions.value, removedId, documentAnchorId || null); if (documentAnchorId) { documentMatch.requiredAnchors = documentMatch.requiredAnchors.filter((item) => item.anchor_id !== documentAnchorId); documentMatch.optionalAnchors = documentMatch.optionalAnchors.filter((item) => item.anchor_id !== documentAnchorId); @@ -1207,10 +1427,17 @@ const removeSelected = () => { /** 标记一次画布手势,只有实际产生几何变化时才创建撤销检查点。 */ const beginRegionGesture = (id: string) => { pendingGestureId = id; + activeGestureId = id; + activeGestureMoved = false; }; /** 结束画布手势;未移动的单击不会被误认为未保存编辑。 */ const endRegionGesture = () => { + const gestureId = activeGestureId; pendingGestureId = null; + activeGestureId = null; + const moved = activeGestureMoved; + activeGestureMoved = false; + if (moved && gestureId && selectedId.value === gestureId) void refreshSelectedVisualSampleValue(); }; /** 处理画布拖动产生的相对区域;一次手势只创建一个撤销检查点。 */ const updateRegion = (id: string, region: OrderProfileRelativeRegion) => { @@ -1226,6 +1453,7 @@ const updateRegion = (id: string, region: OrderProfileRelativeRegion) => { checkpoint(); pendingGestureId = null; } + activeGestureMoved = activeGestureId === id || activeGestureMoved; const normalized = normalizedCanvasRegion(region); if (!normalized) return; item.region = normalized; @@ -1332,11 +1560,13 @@ const definition = () => { ); return { region_id: `main_lines_page_${regionPageNo}`, - page_scope: regionSettings.pageScope, - page_no: regionSettings.pageScope === 'exact_page' ? regionPageNo : null, + // 仅为旧 schema 提供兼容形状;运行时会自动选择适用页范围。 + page_scope: 'exact_page' as const, + page_no: regionPageNo, region: tableRegion, line_start_field_code: resolveLineStartFieldCode(mainLineFieldCodes), - row_reconstruction_mode: regionSettings.rowReconstructionMode, + // 仅为旧 schema 提供兼容形状;运行时固定/自适应策略并行评估。 + row_reconstruction_mode: 'fixed_subrows' as const, // 仅冻结管理员确认的视觉几何来源,正式字段值仍由 coordinate/XFA datasets // adapter 在运行时按各自受控契约取得。 visual_evidence_source: regionSettings.visualEvidenceSource, @@ -1377,7 +1607,12 @@ const definition = () => { })), }; }); - return { + const visualDefinition: OrderCoordinateProfileDefinition = { + // 主表身份由创建向导冻结;编辑器保存时随定义原样携带,不能退化为只存 sample.table_id。 + main_table_id: resolveMainTableIdForPageChange({ + frozenMainTableId: mainTableId.value, + pagePreviewTableId: form.tableId, + }), document_match: { document_type: "purchase_order" as const, page_pattern: "one_or_more" as const, @@ -1481,6 +1716,12 @@ const definition = () => { }; }), }; + return { + ...visualDefinition, + ...(reservationIdRegion.value + ? { reservation_id_region: { ...reservationIdRegion.value } } + : {}), + }; }; /** * 保存当前草稿定义并附带当前标签租约。 @@ -1513,7 +1754,11 @@ const save = async (automatic = false) => { schema_version_id: form.schemaId, definition: adapterPayload.definition, sample_document_id: form.documentId, - sample_table_id: form.tableId, + // sample_table_id 与 definition.main_table_id 是同一份冻结身份;当前页预览表不能参与保存。 + sample_table_id: resolveMainTableIdForPageChange({ + frozenMainTableId: mainTableId.value, + pagePreviewTableId: form.tableId, + }), change_note: form.changeNote, }; if (!existingProfile) throw new Error('A draft must be created by the wizard before editing.'); @@ -1540,11 +1785,14 @@ const save = async (automatic = false) => { history.value = []; future.value = []; documentMatchDirty.value = false; + reservationIdRegionDirty.value = false; } saveState.value = 'saved'; autosaveFailures = 0; if (!automatic) message.success(t("admin.shippingOrderProfiles.updated")); profiles.value = profiles.value.map((item) => item.id === savedProfile.id ? savedProfile : item); + // 保存主表后后端会冻结当前 Layout 身份;立即同步门禁,避免管理员必须重开编辑页。 + await refreshAutomarkSampleReadiness(); await refreshOrderFieldSuggestionValues(); if (localChangeVersion !== savingChangeVersion) scheduleAutosave(); return true; @@ -1581,16 +1829,27 @@ const suggestRegions = async () => { if (suggestingRegions.value || !active.value) return; const { documentId, tableId, pageNo: targetPageNo } = deskAnnotationContext.value; if (!documentId) { + automarkStage.value = 'failed'; suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"); message.error(t("admin.shippingOrderProfiles.workbench.autoSuggestFailed")); return; } if (!tableId) return; suggestingRegions.value = true; + automarkStage.value = 'checking'; suggestionProgress.value = t( "admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates", ); try { + // 入队前使用当前服务端状态:它会幂等补齐样本证据,不能相信进入编辑页时的旧快照。 + const readiness = await refreshAutomarkSampleReadiness(); + if (!readiness?.automark_ready) { + automarkStage.value = 'failed'; + suggestionProgress.value = automarkReadinessMessage(readiness?.automark_reason_code); + message.warning(suggestionProgress.value); + return; + } + automarkStage.value = 'queued'; suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing"); const queued = await enqueueOrderProfilePdfAutomark(active.value.id, { document_id: documentId, @@ -1602,6 +1861,8 @@ const suggestRegions = async () => { let job; for (;;) { job = await getOrderProfilePdfAutomarkJob(active.value.id, queued.job_id); + if (String(job.status) === 'queued') automarkStage.value = 'queued'; + else if (['running', 'pending'].includes(String(job.status || ''))) automarkStage.value = 'analyzing'; if (!['queued', 'running', 'pending'].includes(String(job.status || ''))) break; await new Promise((resolve) => { window.setTimeout(resolve, 500); }); } @@ -1638,14 +1899,14 @@ const suggestRegions = async () => { .filter((item) => item.field_id && item.sources.length > 1) : []; for (const key of Object.keys(selectedAutomarkFieldSources)) delete selectedAutomarkFieldSources[key]; - selectedAutomarkTableSource.value = automarkTableCandidates.value.length === 1 - ? automarkTableCandidates.value[0]!.source : ''; + selectedAutomarkTableSource.value = preferredAutomarkTableSource(automarkTableCandidates.value); // 新一轮自动标记不能沿用上一轮已确认来源;单一路候选仍保留其来源以便 // 草稿版本可追溯,多路候选则必须等待用户选择。 - ensureTableRegionSetting(pageNo.value).visualEvidenceSource = selectedAutomarkTableSource.value + ensureTableRegionSetting(targetPageNo).visualEvidenceSource = selectedAutomarkTableSource.value ? selectedAutomarkTableSource.value as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry' : null; if (visualCanvas.value.applyAutomarkCandidates(candidates)) { + automarkStage.value = 'complete'; suggestionProgress.value = candidates.length ? t("admin.shippingOrderProfiles.workbench.autoSuggestComplete") : t("admin.shippingOrderProfiles.workbench.autoSuggestNoRows"); @@ -1673,6 +1934,7 @@ const suggestRegions = async () => { const orderFields = { order_field_candidates: normalizeAutomarkFieldCandidates(selectedFieldCandidates) }; orderFieldSuggestions.value = orderFields.order_field_candidates; if (!suggestion && !orderFields.order_field_candidates.length && !automarkFieldConflicts.value.length) { + automarkStage.value = 'complete'; suggestionProgress.value = t( "admin.shippingOrderProfiles.workbench.autoSuggestNoRows", ); @@ -1681,26 +1943,32 @@ const suggestRegions = async () => { suggestionProgress.value = t( "admin.shippingOrderProfiles.workbench.autoSuggestApplying", ); + automarkStage.value = 'building'; const suggestedRegions = buildAutomarkSuggestedRegions({ reconstruction: suggestion, orderFieldCandidates: orderFields.order_field_candidates, - pageNo: pageNo.value, + pageNo: targetPageNo, unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }), lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }), }); - const summary = { - algorithm_version: 'coordinate-suggest-v1', kind: 'page_regions', page_no: pageNo.value, - document_id: documentId, table_id: form.tableId, automark_job_id: job.job_id, - region_count: suggestedRegions.length, - region_kinds: suggestedRegions.map((item) => item.kind), - evidence_source_required: hasParallelTableCandidates, - selected_evidence_source: hasParallelTableCandidates ? null : (selectedAutomarkTableSource.value || null), - selected_field_evidence_sources: { ...selectedAutomarkFieldSources }, + const context: AutomarkSuggestionContext = { + documentId, + tableId, + pageNo: targetPageNo, + automarkJobId: job.job_id, }; + const summary = buildAutomarkSuggestionSummary(context, { + regionCount: suggestedRegions.length, + regionKinds: suggestedRegions.map((item) => item.kind), + evidenceSourceRequired: hasParallelTableCandidates, + // 多来源仍要求人工接受;预选 PDF 只避免下拉框显示已选但摘要为空。 + selectedEvidenceSource: selectedAutomarkTableSource.value || null, + selectedFieldEvidenceSources: { ...selectedAutomarkFieldSources }, + }); const serialized = canonicalSuggestionJson(summary); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized)); const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join(''); - pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions: suggestedRegions }; + pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context, summary, regions: suggestedRegions }; message.success( t("admin.shippingOrderProfiles.workbench.suggestionReadyForDecision"), ); @@ -1708,11 +1976,26 @@ const suggestRegions = async () => { suggestionProgress.value = hasParallelTableCandidates ? t("admin.shippingOrderProfiles.workbench.autoSuggestMultiEvidenceReview") : t("admin.shippingOrderProfiles.workbench.autoSuggestComplete"); + automarkStage.value = hasParallelTableCandidates ? 'review' : 'complete'; } catch (error) { - suggestionProgress.value = - error instanceof BusinessError - ? error.message - : t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"); + if (error instanceof BusinessError) { + const reasonByCode: Record = { + 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_NOT_READY': 'layout_not_ready', + 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_REQUIRED': 'main_table_missing', + 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS': 'main_table_ambiguous', + 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE': 'layout_checksum_mismatch', + 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND': 'document_missing', + }; + const reason = reasonByCode[error.code]; + if (reason) { + suggestionProgress.value = automarkReadinessMessage(reason); + message.warning(suggestionProgress.value); + return; + } + } + suggestionProgress.value = error instanceof BusinessError + ? error.message : t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"); + automarkStage.value = 'failed'; fail(error); } finally { suggestingRegions.value = false; @@ -1722,28 +2005,31 @@ const suggestRegions = async () => { /** 用户选择 native/OCR 表格候选后,重新生成待确认建议并刷新其审计摘要。 */ const chooseAutomarkTableSource = async (source: string) => { selectedAutomarkTableSource.value = source; - ensureTableRegionSetting(pageNo.value).visualEvidenceSource = source as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry'; + const pending = pendingSuggestion.value; + if (!pending) return; + ensureTableRegionSetting(pending.context.pageNo).visualEvidenceSource = source as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry'; const candidate = automarkTableCandidates.value.find((item) => item.source === source); - if (!candidate || !pendingSuggestion.value) return; + if (!candidate) return; const regions = buildAutomarkSuggestedRegions({ reconstruction: candidate.reconstruction, orderFieldCandidates: orderFieldSuggestions.value, - pageNo: pageNo.value, + pageNo: pending.context.pageNo, unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }), lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }), }); - const summary = { ...pendingSuggestion.value.summary, selected_evidence_source: source, region_count: regions.length, region_kinds: regions.map((item) => item.kind) }; + const summary = { ...pending.summary, selected_evidence_source: source, region_count: regions.length, region_kinds: regions.map((item) => item.kind) }; const serialized = canonicalSuggestionJson(summary); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized)); const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join(''); - pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions }; + pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context: pending.context, summary, regions }; schedulePreview(); }; /** 选择冲突字段的视觉来源;只将该来源的框加入待确认画布,不影响 XFA datasets 正式值源。 */ const chooseAutomarkFieldSource = async (fieldId: string, source: string) => { selectedAutomarkFieldSources[fieldId] = source; - if (!pendingSuggestion.value) return; + const pending = pendingSuggestion.value; + if (!pending) return; const selectedCandidates = automarkCandidates.value.filter((item) => { if (item.candidate_kind !== 'field_binding' || !item.binding || typeof item.binding !== 'object') return true; const currentFieldId = String((item.binding as Record).field_id || ''); @@ -1759,12 +2045,12 @@ const chooseAutomarkFieldSource = async (fieldId: string, source: string) => { const regions = buildAutomarkSuggestedRegions({ reconstruction: selectedTable, orderFieldCandidates: orderFieldSuggestions.value, - pageNo: pageNo.value, + pageNo: pending.context.pageNo, unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }), lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }), }); const summary = { - ...pendingSuggestion.value.summary, + ...pending.summary, selected_field_evidence_sources: { ...selectedAutomarkFieldSources }, region_count: regions.length, region_kinds: regions.map((item) => item.kind), @@ -1772,7 +2058,7 @@ const chooseAutomarkFieldSource = async (fieldId: string, source: string) => { const serialized = canonicalSuggestionJson(summary); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized)); const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join(''); - pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions }; + pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context: pending.context, summary, regions }; schedulePreview(); }; /** @@ -1809,6 +2095,9 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted suggestionPages.has(region.pageNo) && (region.id.startsWith(`header_${region.pageNo}_`) || region.id.startsWith(`line_${region.pageNo}_`)); + const replaceableAutoRegionIds = new Set( + regions.value.filter(isReplaceableAutoTableRegion).map((region) => region.id), + ); // A new suggestion is a complete table layout for its page. Replace its // previous generated header/line frames before appending it, otherwise a // changed suggestion ID leaves geometrically overlapping regions behind. @@ -1816,7 +2105,22 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted (region) => !isReplaceableAutoTableRegion(region), ); const existingIds = new Set(regions.value.map((region) => region.id)); - const acceptedRegions = item.regions.filter((region) => !existingIds.has(region.id)).map((region) => ({ ...region, fieldCode: decision === 'accepted_adjusted' && region.id === firstSuggestedField?.id ? replacementFieldCode : region.fieldCode })); + const formalBindingLayoutIds = new Set( + (valueAdapterDesk.definition?.bindings || []) + .filter((binding) => Boolean(binding.value_binding?.path_id?.trim())) + .map((binding) => String(binding.field_layout_id || '').trim()), + ); + const reconciledSuggestedRegions = reconcileAutomarkOrderFieldRegions( + regions.value, + item.regions, + ); + const acceptedRegions = restoreFormalBindingFieldCodes( + regions.value, + reconciledSuggestedRegions.filter((region) => ( + !existingIds.has(region.id) || replaceableAutoRegionIds.has(region.id) + )), + formalBindingLayoutIds, + ).map((region) => ({ ...region, fieldCode: decision === 'accepted_adjusted' && region.id === firstSuggestedField?.id ? replacementFieldCode : region.fieldCode })); const suggestedLines = acceptedRegions.filter((region) => region.kind === 'line'); if (suggestedLines.length) { const fieldParentIds = new Set( @@ -1841,6 +2145,7 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted selectedId.value = item.regions.find((region) => region.fieldCode)?.id || item.regions[0]?.id || null; } pendingSuggestion.value = null; + automarkStage.value = decision === 'rejected' ? 'idle' : 'complete'; suggestionAdjustmentField.value = ''; } catch (error) { fail(error); } }; @@ -1888,14 +2193,17 @@ const refreshOrderFieldSuggestionValues = async () => { /** * 读取当前选中非单头框的视觉样本值。 * - * 明细/表头框与单头字段共用受控 region-text API;后端按 native、OCR、唯一 Widget - * 顺序回读,结果仅用于工作台显示,不能写入 datasets binding 或正式抽取值。 + * 所有值框共用受控 region-text API;后端按 native、OCR、唯一 Widget、浏览器 XFA + * 渲染裁剪 OCR 顺序回读,结果仅用于工作台显示,不能写入 datasets binding 或正式抽取值。 */ let selectedVisualSampleRequest = 0; +let selectedVisualSampleAbortController: AbortController | null = null; const refreshSelectedVisualSampleValue = async () => { const request = ++selectedVisualSampleRequest; + selectedVisualSampleAbortController?.abort(); + selectedVisualSampleAbortController = null; const region = selectedRegion.value; - if (!active.value || !form.documentId || !region || region.kind === 'order_field' || !['header_field', 'field'].includes(region.kind)) { + if (!active.value || !form.documentId || !region || !['order_field', 'header_field', 'field'].includes(region.kind)) { selectedVisualSampleValue.value = null; selectedVisualSampleState.value = 'idle'; selectedVisualSampleSource.value = null; @@ -1904,29 +2212,62 @@ const refreshSelectedVisualSampleValue = async () => { selectedVisualSampleValue.value = null; selectedVisualSampleState.value = 'loading'; selectedVisualSampleSource.value = null; + const abortController = new AbortController(); + selectedVisualSampleAbortController = abortController; + let timeoutId: number | null = null; + const { x0, y0, x1, y1 } = region.region; + const cacheKey = `${form.documentId}:${region.pageNo}:${x0}:${y0}:${x1}:${y1}`; + const cached = visualSampleCache.get(cacheKey); + if (cached) { + selectedVisualSampleAbortController = null; + selectedVisualSampleValue.value = cached.text; + selectedVisualSampleSource.value = cached.source; + selectedVisualSampleState.value = 'ready'; + return; + } try { - const result = await readOrderProfilePreviewPageRegionText( - active.value.id, form.documentId, region.pageNo, region.region, - ); + const result = await Promise.race([ + readOrderProfilePreviewPageRegionText( + active.value.id, form.documentId, region.pageNo, region.region, + abortController.signal, + undefined, + documentCanvas.value?.captureRegion(region.region), + ), + new Promise((_, reject) => { + timeoutId = window.setTimeout(() => { + abortController.abort(); + reject(new Error('visual_sample_timeout')); + }, VISUAL_SAMPLE_TIMEOUT_MS); + }), + ]); if (request !== selectedVisualSampleRequest) return; selectedVisualSampleValue.value = result.text || null; - selectedVisualSampleSource.value = result.source === 'pdf_coordinate' || result.source === 'ocr_coordinate' || result.source === 'acroform_widget' + selectedVisualSampleSource.value = result.source === 'pdf_coordinate' || result.source === 'ocr_coordinate' || result.source === 'acroform_widget' || result.source === 'xfa_rendered_ocr' ? result.source : null; + visualSampleCache.set(cacheKey, { + text: selectedVisualSampleValue.value, + source: selectedVisualSampleSource.value, + }); selectedVisualSampleState.value = 'ready'; - } catch { + } catch (error) { + if (error instanceof DOMException && error.name === 'AbortError') return; if (request === selectedVisualSampleRequest) { selectedVisualSampleValue.value = null; selectedVisualSampleSource.value = null; selectedVisualSampleState.value = 'failed'; } + } finally { + if (timeoutId !== null) window.clearTimeout(timeoutId); + if (selectedVisualSampleAbortController === abortController) { + selectedVisualSampleAbortController = null; + } } }; watch( () => { const region = selectedRegion.value; if (!region) return ''; - const { x0, y0, x1, y1 } = region.region; - return `${region.id}:${region.kind}:${region.pageNo}:${x0}:${y0}:${x1}:${y1}`; + return `${region.id}:${region.kind}:${region.pageNo}`; }, () => { void refreshSelectedVisualSampleValue(); }, { immediate: true }, @@ -1944,6 +2285,7 @@ const scheduleOrderFieldSuggestionValues = () => { /** 在后台刷新区域预览,保留原有坐标/OCR 准备行为;结果不再占用标注画布下方空间。 */ const schedulePreview = () => { if (previewTimer) window.clearTimeout(previewTimer); + const request = ++previewRequest; if (!active.value || !form.documentId || !form.tableId) return; // XFA 行正式值只能来自 datasets 当前样本验证;不调用坐标 preview-region, // 因为它可能把视觉表头/OCR 文字投影为“已读取”的明细值。 @@ -1955,44 +2297,62 @@ const schedulePreview = () => { } previewState.value = "updating"; previewError.value = ""; + const profileId = active.value.id; + const documentId = form.documentId; + const tableId = form.tableId; + const currentDefinition = definition(); previewTimer = window.setTimeout(async () => { try { - preview.value = await previewOrderProfileRegion( - active.value!.id, - form.documentId, - form.tableId, - definition(), + const nextPreview = await previewOrderProfileRegion( + profileId, + documentId, + tableId, + currentDefinition, ); + if (request !== previewRequest) return; + preview.value = nextPreview; previewState.value = "ready"; } catch (error) { + if (request !== previewRequest) return; if (error instanceof BusinessError && error.code === "SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE") { try { - await generateOrderProfileOcrCoordinateEvidence(form.documentId, form.tableId); - preview.value = await previewOrderProfileRegion(active.value!.id, form.documentId, form.tableId, definition()); + await generateOrderProfileOcrCoordinateEvidence(documentId, tableId); + const retryPreview = await previewOrderProfileRegion(profileId, documentId, tableId, currentDefinition); + if (request !== previewRequest) return; + preview.value = retryPreview; previewState.value = "ready"; return; } catch (retryError) { error = retryError; } } + if (request !== previewRequest) return; previewState.value = "failed"; previewError.value = error instanceof BusinessError ? error.message : t("admin.shippingOrderProfiles.workbench.previewFailed"); } }, 400); }; -/** 签发当前绑定样本的原 PDF 单用途画布令牌;坐标 PDF 与 XFA 共用 PDF.js 渲染。 */ +/** + * 签发当前样本的受控画布预览。 + * 核心逻辑:普通坐标 PDF 使用服务端 PDFium PNG,保证内嵌繁体字形一致;只有显式 + * XFA datasets 模板才保留 PDF.js 原 PDF 渲染,以显示动态表单外观。 + */ const loadPages = async () => { if (!active.value || !form.documentId) return; try { - pdfPreviewGrant.value = await authorizeOrderProfilePdfPreview( - active.value.id, - form.documentId, - ); + if (valueAdapterKey.value === 'xfa_dataset') { + previewPages.value = null; + pdfPreviewGrant.value = await authorizeOrderProfilePdfPreview(active.value.id, form.documentId); + } else { + pdfPreviewGrant.value = null; + previewPages.value = await authorizeOrderProfilePreviewPages(active.value.id, form.documentId); + } pageNo.value = 1; - pdfPageCount.value = 1; + pdfPageCount.value = previewPages.value?.page_count || 1; canvasUnavailable.value = false; } catch { pdfPreviewGrant.value = null; + previewPages.value = null; pdfPageCount.value = 1; canvasUnavailable.value = true; } @@ -2005,6 +2365,7 @@ const reprocessCurrentSampleLayout = async (): Promise => { await reparseOrderProfileSampleLayout(form.documentId); message.success(t('admin.shippingOrderProfiles.blindTest.layoutReparseStarted')); await loadSampleTables(); + await refreshAutomarkSampleReadiness(); await loadPages(); await refreshOrderFieldSuggestionValues(); } catch (error) { @@ -2019,12 +2380,61 @@ const selectPage = async (nextPageNo: number) => { if (nextPageNo === pageNo.value) return; pageNo.value = nextPageNo; selectedId.value = null; - const pageTable = sampleTables.value.find( - (item) => item.page_no === nextPageNo, - ); - form.tableId = pageTable?.table_id || ""; + // 翻页只改变当前页预览表,模板主表仍由 mainTableId 单独冻结。 + const pageTable = sampleTables.value.find((item) => item.page_no === nextPageNo); + form.tableId = pageTable?.table_id || ''; await refreshOrderFieldSuggestionValues(); }; + +/** + * 明确恢复草稿的视觉主表。 + * 核心逻辑:仅接受同一 annotation 文档的候选;先用当前绑定验证目标能重建 data 行, + * 再通过既有租约/Revision 保存事务同步 definition 与 annotation sample,绝不静默换表。 + */ +const repairMainTable = async (tableId: string): Promise => { + if (!active.value || !form.documentId || repairingMainTable.value) return; + const candidate = sampleTables.value.find((item) => item.table_id === tableId); + if (!candidate) return; + repairingMainTable.value = true; + try { + const candidateDefinition = definition(); + candidateDefinition.main_table_id = candidate.table_id; + const preview = await previewOrderProfileRegion(active.value.id, form.documentId, candidate.table_id, candidateDefinition); + if (!preview.row_roles.some((role) => role === 'data')) { + message.error(t('admin.shippingOrderProfiles.workbench.mainTableRepairNoData')); + return; + } + const previousMainTableId = mainTableId.value; + const previousPreviewTableId = form.tableId; + mainTableId.value = candidate.table_id; + form.tableId = candidate.table_id; + markLocalChange(); + const saved = await save(false); + if (saved) { + message.success(t('admin.shippingOrderProfiles.workbench.mainTableRepaired')); + } else { + // 保存失败时不能让本地状态伪装成已恢复,避免后续自动保存再次写入未确认的主表。 + mainTableId.value = previousMainTableId; + form.tableId = previousPreviewTableId; + } + } catch (error) { + fail(error); + } finally { + repairingMainTable.value = false; + } +}; +/** 打开受控恢复确认;选择候选本身绝不写入草稿。 */ +const requestMainTableRepair = (tableId: string): void => { + if (!tableId) return; + pendingMainTableRepairId.value = tableId; + mainTableRepairConfirmOpen.value = true; +}; +/** 确认后才执行预检和原子保存。 */ +const confirmMainTableRepair = (): void => { + const tableId = pendingMainTableRepairId.value; + pendingMainTableRepairId.value = ''; + if (tableId) void repairMainTable(tableId); +}; /** 请求当前或全部表头的只读精确别名建议;结果不自动修改人工字段绑定。 */ const suggestHeaders = async (currentOnly: boolean) => { if (!active.value || !form.documentId || !form.tableId) return; @@ -2075,8 +2485,17 @@ const loadSampleTables = async () => { column_count: item.column_count, rows: item.rows, })); - form.tableId = sampleTables.value[0]?.table_id || ""; - pageNo.value = sampleTables.value[0]?.page_no || 1; + // Keep the server-bound annotation table when refreshing the table list. + // Falling back to the first parsed table selects the order-header table on + // documents that contain multiple physical tables, which leaves the line + // recognition panel empty even though the frozen profile has line rows. + const annotationTableId = boundSamples.value.find( + (item) => item.sample_role === 'annotation' && item.document_id === form.documentId, + )?.table_id || ''; + const selectedTable = sampleTables.value.find((item) => item.table_id === annotationTableId) + || sampleTables.value[0]; + form.tableId = selectedTable?.table_id || ""; + pageNo.value = selectedTable?.page_no || 1; } catch (error) { fail(error); } @@ -2128,12 +2547,11 @@ const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => { /** 从 v2 定义恢复区域,供草稿重开后继续在画布上编辑。 */ const restoreRegions = (profile: ShippingOrderDocumentProfile) => { const definition = asVisualProfileDefinition(profile.definition); + mainTableId.value = String(definition.main_table_id || ''); for (const key of Object.keys(tableRegionSettings)) delete tableRegionSettings[Number(key)]; for (const table of definition.table_regions) { const regionPageNo = restoreOrderProfileRegionPageNo(table); tableRegionSettings[regionPageNo] = { - rowReconstructionMode: table.row_reconstruction_mode || 'fixed_subrows', - pageScope: table.page_scope, visualEvidenceSource: table.visual_evidence_source || null, }; } @@ -2338,6 +2756,10 @@ const edit = async (profile: ShippingOrderDocumentProfile) => { form.schemaId = profile.schema_version_id; form.changeNote = profile.change_note || ""; xfaDirty.value = false; + reservationIdRegion.value = restoreReservationIdRegion((profile.definition as { + reservation_id_region?: unknown; + }).reservation_id_region); + reservationIdRegionDirty.value = false; const definition = asVisualProfileDefinition(profile.definition); documentMatch.requiredAnchors = (definition.document_match.required_anchors || []).map((item) => ({ ...item })); documentMatch.optionalAnchors = (definition.document_match.optional_anchors || []).map((item) => ({ ...item })); @@ -2372,14 +2794,18 @@ const edit = async (profile: ShippingOrderDocumentProfile) => { // main_table_id 优先,其次才兼容历史 annotation sample 的 table_id。 // XFA datasets 不参与该选择,只在最后保存/取值时消费其 adapter 证据。 const visualTableId = String( - (profile.definition as { main_table_id?: string }).main_table_id + mainTableId.value || annotationSample?.table_id || '', ); if (visualTableId && sampleTables.value.some((item) => item.table_id === visualTableId)) { + // 历史草稿没有 definition.main_table_id 时,以已绑定 annotation sample 一次性补齐内存冻结值。 + // 后续翻页只会修改 form.tableId,不能再影响这个身份。 + mainTableId.value = visualTableId; form.tableId = visualTableId; pageNo.value = sampleTables.value.find((item) => item.table_id === visualTableId)?.page_no || pageNo.value; } + await refreshAutomarkSampleReadiness(); await loadPages(); } catch (error) { fail(error); @@ -2501,10 +2927,12 @@ watch( () => { form.tableId = ""; pdfPreviewGrant.value = null; + previewPages.value = null; pdfPageCount.value = 1; canvasUnavailable.value = false; if (restoringProfile) return; void loadSampleTables(); + void refreshAutomarkSampleReadiness(); if (active.value) void loadPages(); }, ); @@ -2605,6 +3033,10 @@ onMounted(async () => { } }); onBeforeUnmount(() => { + ++previewRequest; + ++selectedVisualSampleRequest; + selectedVisualSampleAbortController?.abort(); + selectedVisualSampleAbortController = null; if (previewTimer) window.clearTimeout(previewTimer); if (autosaveTimer) window.clearTimeout(autosaveTimer); if (retryTimer) window.clearTimeout(retryTimer); @@ -2687,11 +3119,60 @@ onBeforeUnmount(() => { {{ t('admin.shippingOrderProfiles.blindTest.reprocessLayout') }}
+
+
+
+ {{ pendingSuggestion ? t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') : t('admin.shippingOrderProfiles.workbench.autoSuggestRunning') }} +

{{ suggestionProgress || t('admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates') }}

+
+ {{ pendingSuggestion.regions.length }} {{ t('admin.shippingOrderProfiles.workbench.suggestionPreviewBadge') }} +
+
+ +
+
+
+ {{ t('admin.shippingOrderProfiles.workbench.suggestionOnPage', { page: pendingSuggestionPageNo }) }} + +
+
+ +
+ + {{ t('admin.shippingOrderProfiles.workbench.autoSuggestCandidateSummary', { source: summary.source, rows: summary.rowCount, columns: summary.columnCount }) }} + {{ t('admin.shippingOrderProfiles.workbench.autoSuggestCandidateConflict') }} + +
+
+
+ +
+
+ + + + +
+
+
{ :pending-suggestion-count="deskPendingSuggestionCount" :order-field-values="deskOrderFieldValues" :order-field-value-state="deskOrderFieldValueState" + :line-field-values="canvasLineFieldValues" :empty-hint="deskEmptyHint" :load-error="deskLoadError" @undo="onDeskCanvasUndo" @@ -2732,36 +3214,6 @@ onBeforeUnmount(() => { @load-failed="onDeskCanvasLoadFailed" @retry="onDeskCanvasRetry" /> -
- {{ t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') }} - {{ pendingSuggestion.regions.length }} - - - - -
@@ -2781,48 +3233,44 @@ onBeforeUnmount(() => {

{{ documentAnchorNotice }}

-
- {{ t('admin.shippingOrderProfiles.workbench.tableRegionSettings') }} - -

{{ t(`admin.shippingOrderProfiles.workbench.rowReconstructionHints.${deskTableRegionSetting.rowReconstructionMode}`) }}

- -

- {{ t('admin.shippingOrderProfiles.xfaDesk.tableSettingsHint') }} -

+
+ Reservation ID 证据区域 +

只需圈选包含 Reservation ID 的备注区域;系统统一解析:无行号写订单头,带行号写对应明细。

+ + + 已标记第 {{ reservationIdRegion.page_no }} 页区域;解析结果由预览/复核统一返回。 +

正在识别 Reservation ID…

+

区域预览失败;保存后可在盲测/复核中再次确认。

+
+ +
{{ t('admin.shippingOrderProfiles.workbench.selectedRegion') }} @@ -3085,6 +3533,15 @@ onBeforeUnmount(() => { {{ t(`admin.shippingOrderProfiles.workbench.evidenceStatus.${item.status}`) }}

{{ t('admin.shippingOrderProfiles.workbench.noRecognitionResults') }}

+
+

{{ t('admin.shippingOrderProfiles.workbench.mainTableRepairHint') }}

+ +
@@ -3172,6 +3629,16 @@ onBeforeUnmount(() => {
+ @@ -3533,6 +4000,48 @@ onBeforeUnmount(() => { padding: 0.85rem; background: #f8fafc; } +.reservation-region-config { + border-bottom: 1px solid #cbd5e1; + display: grid; + gap: 0.45rem; + padding: 0.85rem; + background: #f8fafc; +} +.reservation-region-config p, +.reservation-region-config small { + margin: 0; + color: #64748b; + font-size: 0.72rem; + line-height: 1.45; +} +.reservation-region-config button { + width: fit-content; +} +.reservation-region-config__status { + margin: 0; +} +.reservation-region-config__candidates { + display: grid; + gap: 0.35rem; + margin: 0; + padding: 0; + list-style: none; +} +.reservation-region-config__candidates li { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: 0.35rem; + color: #475569; + font-size: 0.72rem; +} +.reservation-region-config__candidates code { + color: #0f172a; + font: 700 0.72rem/1.3 ui-monospace, SFMono-Regular, Menlo, monospace; +} +.reservation-region-config__review { + color: #b45309; +} .table-region-editor { display: grid; gap: 0.55rem; @@ -3697,8 +4206,26 @@ onBeforeUnmount(() => { .editor-desk > main { min-height: 0; } .editor-workbench .config { max-height: calc(100vh - 5rem); overflow-y: auto; } .editor-bottom-drawer { max-width: none; border-top: 1px solid #334155; background: #f8fafc; } -.suggestion-decision { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; border-top: 1px solid #7dd3fc; background: #ecfeff; padding: .65rem .9rem; color: #155e75; } -.suggestion-decision span { border-radius: 999px; background: #bae6fd; padding: .15rem .4rem; font-size: .72rem; }.suggestion-decision button,.suggestion-decision .select-field { border: 1px solid #0891b2; border-radius: .35rem; background: #fff; padding: .35rem .55rem; color: #0e7490; font-size: .75rem; } +.automark-status-panel { position: sticky; top: .5rem; z-index: 6; display: grid; gap: .65rem; margin: 0 0 .75rem; border: 1px solid #7dd3fc; border-radius: .45rem; background: #f0f9ff; padding: .75rem .9rem; color: #164e63; box-shadow: 0 8px 20px rgb(14 116 144 / .12); } +.automark-status-panel__heading { display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; } +.automark-status-panel__heading strong { display: block; color: #0c4a6e; font-size: .82rem; } +.automark-status-panel__heading p { margin: .2rem 0 0; color: #475569; font-size: .75rem; } +.automark-status-panel__count { flex: 0 0 auto; border-radius: 999px; background: #bae6fd; padding: .2rem .5rem; font-size: .7rem; font-weight: 700; } +.automark-progress { height: .35rem; overflow: hidden; border-radius: 999px; background: #dbeafe; } +.automark-progress span { display: block; height: 100%; border-radius: inherit; background: #0284c7; transition: width .25s ease; } +.automark-status-panel__body { display: grid; gap: .6rem; } +.automark-candidate-page-notice { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .45rem; border: 1px solid #bae6fd; border-radius: .35rem; background: #fff; padding: .45rem .55rem; color: #0c4a6e; font-size: .75rem; } +.automark-choice-block { display: grid; gap: .45rem; } +.automark-choice-block label { display: flex; flex-wrap: wrap; align-items: center; gap: .45rem; color: #334155; font-size: .74rem; font-weight: 700; } +.automark-choice-block--fields { grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); } +.automark-status-panel__actions { display: flex; flex-wrap: wrap; align-items: center; gap: .45rem; } +.automark-status-panel__actions .select-field { min-width: 12rem; } +@media (max-width: 640px) { + .automark-status-panel { top: 0; } + .automark-status-panel__actions { align-items: stretch; } + .automark-status-panel__actions > * { flex: 1 1 100%; } + .automark-status-panel__actions .select-field { min-width: 0; } +} .suggestion-evidence-summary { display: flex; flex-wrap: wrap; gap: .35rem; width: 100%; font-size: .72rem; } .suggestion-evidence-summary span { background: #e0f2fe; color: #075985; } .suggestion-evidence-summary span.is-conflict { background: #fee2e2; color: #991b1b; } diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/canvasActions.utils.spec.ts b/frontend/src/features/admin/modules/shipping-order-document-profiles/canvasActions.utils.spec.ts index 4efe90d2..8db34679 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/canvasActions.utils.spec.ts +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/canvasActions.utils.spec.ts @@ -6,13 +6,66 @@ */ import { describe, expect, it, vi } from 'vitest'; import { + filterRegionsAfterRemoval, + resolveSelectedOrderAnchorId, resolveCanvasActions, resolveDeskAdapter, + resolveMainTableIdForPageChange, resolveSharedCanvasDocument, resolveValueAdapterKey, + shouldKeepUnreadableOrderField, type OrderProfileCanvasActions, } from './canvasActions.utils'; +describe('filterRegionsAfterRemoval', () => { + it('deletes only the selected ordinary top-level region', () => { + const regions = [ + { id: 'green-1', kind: 'header_field', label: 'A', region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1 }, + { id: 'green-2', kind: 'header_field', label: 'B', region: { x0: 0, y0: .2, x1: .1, y1: .3 }, pageNo: 1 }, + ] as any; + + expect(filterRegionsAfterRemoval(regions, 'green-1')).toEqual([regions[1]]); + }); + + it('keeps ordinary top-level regions while deleting a document-anchor family', () => { + const regions = [ + { id: 'green-1', kind: 'header_field', label: 'A', region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1 }, + { id: 'anchor-label', kind: 'document_anchor_label', label: 'Label', parentId: 'anchor-1', region: { x0: 0, y0: .2, x1: .1, y1: .3 }, pageNo: 1 }, + { id: 'anchor-value', kind: 'document_anchor_value', label: 'Value', parentId: 'anchor-1', region: { x0: 0, y0: .3, x1: .1, y1: .4 }, pageNo: 1 }, + ] as any; + + expect(filterRegionsAfterRemoval(regions, 'anchor-label', 'anchor-1').map((item) => item.id)).toEqual(['green-1']); + }); +}); + +describe('resolveSelectedOrderAnchorId', () => { + it('only returns an explicitly selected order anchor', () => { + const selectedAnchor = { + id: 'ship_to_anchor', kind: 'order_anchor', label: 'Ship to', + region: { x0: 0, y0: 0, x1: .1, y1: .1 }, pageNo: 1, + } as any; + const selectedValue = { + id: 'ship_to_value', kind: 'order_field', parentId: 'ship_to_anchor', + label: 'Example', region: { x0: 0, y0: .1, x1: .1, y1: .2 }, pageNo: 1, + } as any; + + expect(resolveSelectedOrderAnchorId(selectedAnchor)).toBe('ship_to_anchor'); + expect(resolveSelectedOrderAnchorId(selectedValue)).toBeNull(); + expect(resolveSelectedOrderAnchorId(null)).toBeNull(); + }); +}); + +describe('shouldKeepUnreadableOrderField', () => { + it('keeps an XFA value box when visual readback remains unavailable', () => { + // OCR/Widget 回读失败必须可诊断,但不能让管理员已框选的 XFA 值框消失。 + expect(shouldKeepUnreadableOrderField('xfa_dataset', 'order_field', false)).toBe(true); + }); + + it('keeps the ordinary-PDF empty-value guard unchanged', () => { + expect(shouldKeepUnreadableOrderField('coordinate_ocr', 'order_field', false)).toBe(false); + }); +}); + function actions(): OrderProfileCanvasActions { return { create: vi.fn(), select: vi.fn(), dragStart: vi.fn(), dragEnd: vi.fn(), change: vi.fn(), @@ -98,3 +151,12 @@ describe('resolveCanvasActions', () => { expect(resolveValueAdapterKey({ template_mode: 'coordinate' } as any)).toBe('coordinate_ocr'); }); }); + +describe('resolveMainTableIdForPageChange', () => { + it('keeps the frozen main table when PDF navigation selects another table on the same page', () => { + expect(resolveMainTableIdForPageChange({ + frozenMainTableId: 'order-lines-table', + pagePreviewTableId: 'total-amount-table', + })).toBe('order-lines-table'); + }); +}); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/canvasActions.utils.ts b/frontend/src/features/admin/modules/shipping-order-document-profiles/canvasActions.utils.ts index 99d467e6..9ebdd330 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/canvasActions.utils.ts +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/canvasActions.utils.ts @@ -24,6 +24,58 @@ export interface OrderProfileCanvasActions { draw(kind: OrderProfileCanvasRegion['kind']): void; } +/** + * 计算删除画布区域后的区域集合。 + * 普通区域只删除自身及其直接子区域;文档锚点仅在明确传入锚点 ID 时级联删除。 + */ +export function filterRegionsAfterRemoval( + regions: OrderProfileCanvasRegion[], + removedId: string, + documentAnchorId: string | null = null, +): OrderProfileCanvasRegion[] { + return regions.filter((item) => ( + item.id !== removedId + && item.parentId !== removedId + && (documentAnchorId === null || item.parentId !== documentAnchorId) + )); +} + +/** + * 返回当前明确选中的订单字段标签 ID。 + * 核心逻辑:订单字段值框只能继承用户当前选中的标签,绝不回退到页面第一个标签。 + * @param selectedRegion - 当前画布选区;非订单字段标签或未选中时返回 null。 + * @returns 可作为订单字段父节点的标签 ID,或 null。 + */ +export function resolveSelectedOrderAnchorId( + selectedRegion: Pick | null, +): string | null { + return selectedRegion?.kind === 'order_anchor' ? selectedRegion.id : null; +} + +/** + * 保持模板主表身份与 PDF 页内预览表分离。 + * 核心逻辑:翻页是画布导航,不能把同页第一张表(例如合计区)写回已冻结的主表身份。 + */ +export function resolveMainTableIdForPageChange(options: { + frozenMainTableId: string; + pagePreviewTableId: string; +}): string { + return options.frozenMainTableId || options.pagePreviewTableId; +} + +/** + * 判断 XFA 视觉回读为空时是否应保留用户刚圈选的值框。 + * 核心逻辑:空回读是待诊断的视觉证据失败,不得吞掉管理员已经完成的 XFA 位置标注; + * 普通 PDF 仍维持原有的空文本拒绝规则。 + */ +export function shouldKeepUnreadableOrderField( + adapterKey: string, + kind: OrderProfileCanvasRegion['kind'] | null, + hasVisualText: boolean, +): boolean { + return hasVisualText || (adapterKey === 'xfa_dataset' && kind === 'order_field'); +} + /** * 共享 Editor 消费的视觉画布状态。 * @@ -35,6 +87,7 @@ export interface OrderProfileVisualCanvasAdapter { actions: OrderProfileCanvasActions; documentReady: boolean; preview: { document_id: number; preview_token: string; expires_in_seconds: number } | null; + grant: { page_no: number; preview_token: string } | null; previewPagePath: string; regions: OrderProfileCanvasRegion[]; selectedRegionId: string | null; @@ -130,7 +183,7 @@ export function resolveDeskAdapter(options: { /** * 返回唯一由 Editor 消费的 PDF 画布文档上下文。 * 核心逻辑:所有 Profile 先使用共同冻结的 annotation document + main_table_id; - * 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDF.js 渲染始终 + * 历史草稿缺失 main_table_id 时才回退样本 table_id。预览授权、页码和 PDFium/PDF.js 渲染始终 * 由共享 Editor 持有,值源 adapter 不得参与上下文选择。 * @param options.documentId - 共同 annotation 文档身份。 * @param options.mainTableId - definition 中冻结的共同视觉主表。 diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts index f3eba770..52944946 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts @@ -82,4 +82,52 @@ describe('OrderProfileDocumentCanvas PDF preview', () => { expect(wrapper.find('.canvas-stage').attributes('style')).toContain('width: 750px'); expect(wrapper.find('.region').attributes('style')).toContain('left: 50%'); }); + + it('uses the server-rendered PNG page for an ordinary PDF instead of PDF.js', async () => { + const wrapper = mount(OrderProfileDocumentCanvas, { + props: { + profileId: 71, + grant: { page_no: 1, preview_token: 'page-token' }, + previewPagePath: '/api/admin/shipping-notice/order-document-profiles/71/preview-pages', + regions: [], pageNo: 1, pageCount: 1, + }, + global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] }, + }); + await flushPromises(); + + // 普通 PDF 底图由后端 PDFium 输出,避免前端 PDF.js 对特定繁体内嵌字体的渲染差异。 + expect(getDocumentMock).not.toHaveBeenCalled(); + expect(wrapper.find('img').exists()).toBe(true); + expect(fetch).toHaveBeenCalledWith( + '/api/admin/shipping-notice/order-document-profiles/71/preview-pages/1?preview_token=page-token', + expect.objectContaining({ cache: 'no-store' }), + ); + }); + + it('captures the selected XFA appearance from the unscaled PDF.js canvas', async () => { + const drawImage = vi.fn(); + const toDataURL = vi.fn(() => 'data:image/png;base64,canvas-crop'); + const nativeCreateElement = document.createElement.bind(document); + vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => { + const element = nativeCreateElement(tagName) as HTMLCanvasElement; + if (tagName === 'canvas') { + Object.defineProperty(element, 'getContext', { value: vi.fn(() => ({ drawImage })) }); + Object.defineProperty(element, 'toDataURL', { value: toDataURL }); + } + return element; + }); + const wrapper = mount(OrderProfileDocumentCanvas, { + props: { profileId: 71, pdfPreview: { preview_token: 'single-use-token' }, regions: [], pageNo: 1, pageCount: 1 }, + global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] }, + }); + await flushPromises(); + await flushPromises(); + const source = wrapper.find('canvas.pdf-page').element as HTMLCanvasElement; + Object.defineProperties(source, { width: { value: 600 }, height: { value: 800 } }); + + expect((wrapper.vm as { captureRegion: (region: object) => string | null }).captureRegion({ x0: .1, y0: .2, x1: .4, y1: .5 })) + .toBe('data:image/png;base64,canvas-crop'); + // 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。 + expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240); + }); }); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue index c759d534..e4b0f399 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue @@ -8,7 +8,7 @@ - - - - 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 deleted file mode 100644 index d2a730d5..00000000 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue +++ /dev/null @@ -1,431 +0,0 @@ - - - - - - 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 deleted file mode 100644 index 6a14c10c..00000000 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue +++ /dev/null @@ -1,544 +0,0 @@ - - - - - - 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 deleted file mode 100644 index 951d7514..00000000 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue +++ /dev/null @@ -1,393 +0,0 @@ - - - - - - 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 deleted file mode 100644 index b084a50d..00000000 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue +++ /dev/null @@ -1,921 +0,0 @@ - - - - - - diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts index d3a8353b..dcae59d6 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts @@ -546,6 +546,28 @@ describe('XfaSplitRulePanel', () => { ]); }); + it('keeps advanced processing attached to a position matcher rule', async () => { + const ruleSet = makePipelineRuleSet({ + rules: [{ + ...makePipelineRuleSet().rules[0], + matcher: { type: 'position', line_index: 3 }, + }], + }); + const wrapper = mountPanel({ + definition: { ...baseDefinition, split_rules: [ruleSet] }, + }); + const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理')); + await advancedButton!.trigger('click'); + const addAdvanced = wrapper.find('.xfa-split__add-stage-select'); + await addAdvanced.setValue('extract_prefix'); + await addAdvanced.trigger('change'); + const emitted = wrapper.emitted('update:split-rules'); + const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules; + expect(last?.[0]?.rules[0]?.stages.map((stage) => stage.type)).toEqual([ + 'split_lines', 'select_line', 'extract_prefix', + ]); + }); + it('adds a rule after mounting when autoAddRule is enabled', () => { const wrapper = mountPanel({ autoAddRule: true, @@ -577,6 +599,73 @@ describe('XfaSplitRulePanel', () => { expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() })); }); + it('sends formal matcher post-processors instead of UI-only pipeline fields to preview', async () => { + previewMock.mockResolvedValue({ + preview: { status: 'ok', mapped_fields: {}, segments: [], evidence_only_segments: [], diagnostics: [] }, + }); + const wrapper = mountPanel({ + definition: { + ...baseDefinition, + split_rules: [makePipelineRuleSet({ + strategy: 'pipeline', + rules: [{ + ...makePipelineRuleSet().rules[0], + order: 3, + matcher: { type: 'position', line_index: 3 }, + stages: [ + { stage_id: 'split', type: 'split_lines', line_breaks: ['\\n'] }, + { stage_id: 'line', type: 'select_line', line_index: 3 }, + { stage_id: 'mpn', type: 'extract_prefix', value: 'MPN', separators: [':', ':'] }, + ], + }], + })], + }, + }); + + await exposedActions(wrapper).runPreview(); + await flushPromises(); + + expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({ + rule_set: expect.objectContaining({ + rules: [expect.objectContaining({ + matcher: expect.objectContaining({ + type: 'position', + line_index: 3, + post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'], case_sensitive: false }], + }), + })], + }), + })); + const request = previewMock.mock.calls[0]?.[1] as { rule_set: Record }; + expect(request.rule_set).not.toHaveProperty('strategy'); + expect(request.rule_set.rules[0]).not.toHaveProperty('order'); + expect(request.rule_set.rules[0]).not.toHaveProperty('stages'); + }); + + it('reprojects saved formal post-processors into the advanced editor', async () => { + const wrapper = mountPanel({ + definition: { + ...baseDefinition, + split_rules: [makePipelineRuleSet({ + rules: [{ + ...makePipelineRuleSet().rules[0], + stages: [], + matcher: { + type: 'position', + line_index: 3, + post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'] }], + }, + }], + })], + }, + }); + + const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理')); + await advancedButton!.trigger('click'); + + expect(wrapper.findAll('input').some((input) => input.element.value === 'MPN')).toBe(true); + }); + it('ignores exposed edit actions when canEdit is false', () => { const wrapper = mountPanel({ canEdit: false }); exposedActions(wrapper).addRule(); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue index 667cc195..511e03dd 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue @@ -2,8 +2,8 @@ features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue 用途:XFA 字段拆分规则编辑——matcher 优先(prefix/regex/position),兼容历史 stages[] 投影。 依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表。 - 逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 保留供 UI 与兼容预览; - 确认前须预览当前 rule_set 哈希;预览直接返回完整识别值。 + 逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 仅保留编辑态; + 预览和确认统一投影为正式 matcher DTO,确认前须校验同一正式 DTO 哈希。 --> diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts index 33f929ef..0ce28300 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts @@ -17,10 +17,12 @@ const i18n = createI18n({ messages: { 'zh-CN': { chat: { + shippingNoticeRetryParse: '重试解析', shippingOrderReview: { lifecycle: { navigation: '订单生命周期阶段', current: '当前可处理', + processing: '处理中', completed: '已完成,可查看', blocked: '前置未完成', }, @@ -33,18 +35,43 @@ const i18n = createI18n({ const stages: ReviewLifecycleStageItem[] = [ { code: 'order_review', label: '订单复核', state: 'completed' }, { code: 'fulfillment_prep', label: '通知准备', state: 'current' }, + { code: 'freight_upload', label: '货代上传', state: 'blocked', reason: '请先完成通知准备' }, { code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' }, ]; /** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */ function mountNavigation() { return mount(ReviewLifecycleStageNavigation, { - props: { stages, activeCode: 'fulfillment_prep' }, + props: { stages, activeCode: 'fulfillment_prep', processingCode: 'fulfillment_prep' }, global: { plugins: [i18n] }, }); } describe('ReviewLifecycleStageNavigation', () => { + it('only exposes retry_parse on the current intake stage when the server authorizes it', async () => { + const wrapper = mount(ReviewLifecycleStageNavigation, { + props: { + stages: [ + { code: 'intake_parse', label: '接收解析', state: 'current' }, + ...stages, + ], + activeCode: 'intake_parse', + availableActions: ['retry_parse'], + retrying: false, + }, + global: { plugins: [i18n] }, + }); + + // 关键断言:重试入口必须位于已发送文件的当前阶段卡,且完全由后端动作授权。 + const retry = wrapper.get('[data-testid="review-lifecycle-stage-retry-parse"]'); + expect(retry.text()).toContain('重试解析'); + await retry.trigger('click'); + expect(wrapper.emitted('retry-parse')).toEqual([[]]); + + await wrapper.setProps({ availableActions: [] }); + expect(wrapper.find('[data-testid="review-lifecycle-stage-retry-parse"]').exists()).toBe(false); + }); + it('renders intake_parse as the first lifecycle stage', () => { const wrapper = mount(ReviewLifecycleStageNavigation, { props: { @@ -63,9 +90,10 @@ describe('ReviewLifecycleStageNavigation', () => { 'review-lifecycle-stage-intake_parse', 'review-lifecycle-stage-order_review', 'review-lifecycle-stage-fulfillment_prep', + 'review-lifecycle-stage-freight_upload', 'review-lifecycle-stage-upload_complete', ]); - expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-4'); + expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-5'); }); it('allows opening a completed stage for inspection', async () => { @@ -75,6 +103,14 @@ describe('ReviewLifecycleStageNavigation', () => { expect(wrapper.emitted('select')).toEqual([['order_review']]); }); + it('shows a spinner and processing label on the active stage while automation runs', () => { + const wrapper = mountNavigation(); + const stage = wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]'); + expect(stage.attributes('data-processing')).toBe('1'); + expect(stage.text()).toContain('处理中'); + expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(true); + }); + it('disables a future stage and does not emit a selection', async () => { const wrapper = mountNavigation(); const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]'); diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue index d1ae0717..ed6eb2da 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue @@ -1,13 +1,13 @@