diff --git a/backend/app/api/chat/__init__.py b/backend/app/api/chat/__init__.py index e3cf8b3a..89728b3e 100644 --- a/backend/app/api/chat/__init__.py +++ b/backend/app/api/chat/__init__.py @@ -13,8 +13,24 @@ chat_bp = Blueprint('chat', __name__) # 子模块导入时在同一 Blueprint 上注册原有 URL。 from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401 +from .shared import ( # noqa: E402, F401 + CHAT_USER_ATTACHMENT_LIMIT, + CHAT_USER_ATTACHMENT_MAX_SIZE, + CHAT_USER_ATTACHMENT_SOURCES, + CHAT_USER_ATTACHMENT_TYPES, + _merge_user_attachments_from_terminal_event, + _normalize_user_attachments, +) from app.api.chat_turns import register_chat_turn_routes # noqa: E402 register_chat_turn_routes(chat_bp) -__all__ = ['chat_bp'] +__all__ = [ + 'chat_bp', + 'CHAT_USER_ATTACHMENT_LIMIT', + 'CHAT_USER_ATTACHMENT_MAX_SIZE', + 'CHAT_USER_ATTACHMENT_SOURCES', + 'CHAT_USER_ATTACHMENT_TYPES', + '_merge_user_attachments_from_terminal_event', + '_normalize_user_attachments', +] diff --git a/backend/app/api/chat/sessions.py b/backend/app/api/chat/sessions.py index fa55ebac..a46ab083 100644 --- a/backend/app/api/chat/sessions.py +++ b/backend/app/api/chat/sessions.py @@ -8,6 +8,7 @@ api/chat/sessions.py from __future__ import annotations from .shared import * # noqa: F403 +from .shared import _normalize_user_attachments from . import chat_bp from .core import ( _chat_logs_for_session, @@ -194,19 +195,32 @@ def get_chat_messages(): messages = [] agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic' for log in logs: - if log.query: - messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)}) + raw_payload = log.payload if isinstance(log.payload, dict) else {} + user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments')) + assistant_payload = { + key: value + for key, value in raw_payload.items() + if key != 'user_attachments' + } + if log.query or user_attachments: + user_msg = { + 'role': 'user', + 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code), + } + if user_attachments: + user_msg['attachments'] = user_attachments + messages.append(user_msg) if ( not log.answer and not log.message_type - and not log.payload + and not assistant_payload ): continue if ( log.query and log.answer == log.query and (not log.message_type or log.message_type == 'text') - and not log.payload + and not assistant_payload ): continue assistant_msg = { @@ -220,8 +234,8 @@ def get_chat_messages(): assistant_msg['run_id'] = log.run_id if log.message_type: assistant_msg['type'] = log.message_type - if log.payload: - assistant_msg['payload'] = log.payload + if assistant_payload: + assistant_msg['payload'] = assistant_payload messages.append(assistant_msg) return jsonify(messages) diff --git a/backend/app/api/chat/shared.py b/backend/app/api/chat/shared.py index 64fdb848..faf3c128 100644 --- a/backend/app/api/chat/shared.py +++ b/backend/app/api/chat/shared.py @@ -12,6 +12,7 @@ import ntpath import posixpath import tempfile import os +import re import subprocess import uuid import json @@ -41,6 +42,95 @@ from app.core.errors import ( ) SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice' +# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。 +CHAT_USER_ATTACHMENT_LIMIT = 20 +CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024 +CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'} +CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'} + + +def _normalize_user_attachments(value) -> list[dict]: + """ + 校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。 + + 核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。 + + Args: + value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。 + + Returns: + 可安全写入 JSON 的附件快照列表;非法项目被忽略。 + """ + if not isinstance(value, list): + return [] + normalized: list[dict] = [] + for item in value[:CHAT_USER_ATTACHMENT_LIMIT]: + if not isinstance(item, dict): + continue + raw_name = str(item.get('name') or '') + basename = re.split(r'[\\/]+', raw_name)[-1] + name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255] + attachment_type = str(item.get('type') or '').strip().lower() + source = str(item.get('source') or '').strip().lower() + if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES: + continue + snapshot = { + 'name': name, + 'type': attachment_type, + 'source': source, + } + extension = str(item.get('extension') or '').strip().lower() + if re.fullmatch(r'[a-z0-9]{1,16}', extension): + snapshot['extension'] = extension + try: + size = int(item.get('size')) if item.get('size') is not None else None + except (TypeError, ValueError): + size = None + if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE: + snapshot['size'] = size + normalized.append(snapshot) + return normalized + + +def _merge_user_attachments_from_terminal_event( + event_data: dict, + *, + user_id: int, + agent_id: int, + session_id: str, + user_attachments: list[dict], +) -> bool: + """ + 在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。 + + Args: + event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。 + user_id: 当前用户 ID。 + agent_id: 当前 Agent ID。 + session_id: 当前 HXOPS 本地会话 ID。 + user_attachments: 已完成白名单校验的附件快照。 + + Returns: + 找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。 + """ + if not user_attachments: + return False + try: + chat_log_id = int(event_data.get('chat_log_id') or 0) + except (TypeError, ValueError): + return False + if chat_log_id <= 0: + return False + from app.services.chat.log_service import merge_chat_log_payload + return merge_chat_log_payload( + chat_log_id=chat_log_id, + user_id=int(user_id or 0), + agent_id=int(agent_id or 0), + session_id=session_id, + payload_patch={'user_attachments': user_attachments}, + ) + + PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip() diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 44041498..4b69c224 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -256,15 +256,6 @@ def tool_match_inventory(): resume_gate_code='inventory_matching', )) -@shipping_notice_bp.route('/tools/submit_decision', methods=['POST']) -def tool_submit_decision(): - """ - 提交人工决策。 - 【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。 - """ - return jsonify(shipping_tools.submit_decision(_payload())) - - @shipping_notice_bp.route('/tools/confirm_customer', methods=['POST']) def tool_confirm_customer(): """ diff --git a/backend/app/api/user/auth_support.py b/backend/app/api/user/auth_support.py index f47704f7..f5bec47a 100644 --- a/backend/app/api/user/auth_support.py +++ b/backend/app/api/user/auth_support.py @@ -16,7 +16,7 @@ from app.services.agent_category import serialize_agent_list_item, sort_agent_ro from app.services.agent_registry.serialization import serialize_registry_fields from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field -from app.core.auth.jwt import get_current_user as _auth_current_user +from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError from sqlalchemy import and_, or_, inspect, insert from datetime import datetime, timedelta diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 7ea88a80..4249ef79 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -26,8 +26,8 @@ from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNot from app.services.shipping_notice.chat_actions import build_chat_actions_payload from app.services.shipping_notice.constants import ( AUTO_CHAIN_FALLBACK, - CP_EXPORT_GENERATED, - CP_NOTICE_TEXT_EXTRACTION_FAILED, + POSITION_EXPORT_GENERATED, + POSITION_NOTICE_TEXT_EXTRACTION_FAILED, ) from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership from app.services.shipping_notice.query_service import ( @@ -410,7 +410,7 @@ def workspace_create_shipping_task_from_notice(): task_no=task_id, ) if not intake.accepted: - return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED}) + return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'position': POSITION_NOTICE_TEXT_EXTRACTION_FAILED}) from app.models import ShippingOrderTask from app.models import ShippingOrderIntake task = ShippingOrderTask.query.filter_by(task_no=task_id).first() @@ -462,7 +462,7 @@ def workspace_shipping_task_detail(task_no: str): 返回指定任务的详情快照与内嵌 UI State。 核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到 - checkpoint / actions / steps,减少前端二次推导与竞态刷新。 + position / user_mode / actions / steps,减少前端二次推导与竞态刷新。 """ user = _require_user() is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' @@ -470,8 +470,8 @@ def workspace_shipping_task_detail(task_no: str): task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin) if not task: raise NotFoundError('Not found') - # [PERF] view=workbench 供订单生命周期工作台首屏裁剪:剔除复核编辑器重字段, - # 响应体与序列化耗时显著下降;缺省/非法值一律回退 full,保持兼容。 + # [PERF] view=workbench:跳过 DETAIL 重投影,仅身份壳 + ui_state enrich; + # 缺省/非法值一律回退 full,保持兼容。 view = str(request.args.get('view', 'full') or 'full').strip().lower() if view not in ('full', 'workbench'): view = 'full' @@ -2331,12 +2331,36 @@ def workspace_confirm_shipping_order_review_case(case_no: str): 'message': '无需调度自动推进,或任务已离开待推进态', } else: + # [STEP] 仅下发 position / user_mode;禁止 checkpoint 别名。 + position = progress.get('position') + user_mode = progress.get('user_mode') + if not position or not user_mode: + try: + from app.models import ShippingOrderTask + from app.services.shipping_notice.progress_workflow import ( + _entry_position, + _entry_user_mode, + ) + + ot = ( + db.session.query(ShippingOrderTask) + .filter( + ShippingOrderTask.task_no == str(result.get('task_no') or '').strip().upper() + ) + .first() + ) + if ot is not None: + position = position or _entry_position(ot) + user_mode = user_mode or _entry_user_mode(ot) + except Exception: + pass result['auto_progress_started'] = bool(progress.get('auto_progress_started')) result['auto_progress'] = { 'status': progress.get('status'), 'message': progress.get('message'), 'enqueue_result': progress.get('enqueue_result'), - 'checkpoint': progress.get('checkpoint'), + 'position': position, + 'user_mode': user_mode, } result['confirm_outcome'] = resolve_confirm_outcome( { 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 987f87e8..00a33702 100644 --- a/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py +++ b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py @@ -67,7 +67,7 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non gen = generate_excel({ 'task_id': task.task_no, 'wave_no': wave_no, - 'line_keys': list(frozen.get('line_keys') or []), + 'snapshot_line_ids': list(frozen.get('snapshot_line_ids') or []), 'post_ot_wave': True, '_orchestrator_internal_dispatch': True, }) diff --git a/backend/app/jobs/queue.py b/backend/app/jobs/queue.py index 1d081717..5cc4faef 100644 --- a/backend/app/jobs/queue.py +++ b/backend/app/jobs/queue.py @@ -23,7 +23,7 @@ from sqlalchemy.exc import IntegrityError, OperationalError from sqlalchemy.orm import Session from app import db -from app.core.errors import ValidationError +from app.core.errors import AppError, NotFoundError, ValidationError from app.jobs.types import JobType from app.models import Job @@ -43,6 +43,19 @@ def _orm_session() -> Session: return db.session() +def _is_retryable_exc(exc: BaseException) -> bool: + """按异常类型分级判断任务失败是否可重试(通用裁定,不区分业务域)。 + + 业务 NotFound / AppError.retryable=False(含 ValidationError)视为不可再排队; + 仅瞬时基础设施异常(503 ServiceUnavailable 或未归类异常)才允许重试。 + """ + if isinstance(exc, NotFoundError): + return False + if isinstance(exc, AppError): + return bool(getattr(exc, 'retryable', False)) + return True + + def _ensure_outer_dbapi_transaction(session: Session) -> None: """ 确保 begin_nested() 不会成为数据库最外层事务。 @@ -582,7 +595,7 @@ def recover_stale_jobs( sibling: Job | None = None rowcount = 0 - if str(domain or '') != 'shipping_notice' and snap_attempts < max_attempts: + if snap_attempts < max_attempts: if _subject_to_parse_queued_unique(str(job.job_type or "")): try: sibling = _resolve_safe_supersede_sibling( @@ -1054,12 +1067,12 @@ def process_next_job( return True, job_type_value except Exception as exc: db.session.rollback() - # 发货通知失败必须停在当前 Gate,不能由通用 runner 隐式重新入队。 - # 其它领域维持既有技术重试策略。 + # 失败收口的可重试性由异常类型分级裁定,不按业务域一刀切; + # handler 已自行 fail_job 收敛的绝不应进入此处,此处仅兜底 handler 逃逸的异常。 fail_job( job_id, error=str(exc), - retryable=(str(domain or '').strip() != 'shipping_notice'), + retryable=_is_retryable_exc(exc), owned_attempt=owned_attempt, ) raise diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index a5276e6c..5864abeb 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -70,7 +70,6 @@ from app.models.shipping_order_schema import ( ShippingOrderSchemaVersion, ShippingSchemaFamily, ) -from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch from app.models.shipping_order_snapshot import ( ShippingOrderReviewEvent, ShippingOrderSnapshot, @@ -253,7 +252,6 @@ __all__ = [ 'ShippingOrderFieldObservation', 'ShippingOrderFieldDecision', 'ShippingOrderFieldValue', - 'ShippingOrderCustomerMatch', 'ShippingOrderSnapshot', 'ShippingOrderSnapshotLine', 'ShippingOrderReviewEvent', diff --git a/backend/app/models/shipping_customer_resolution.py b/backend/app/models/shipping_customer_resolution.py index 2af97322..2795b6a6 100644 --- a/backend/app/models/shipping_customer_resolution.py +++ b/backend/app/models/shipping_customer_resolution.py @@ -1,9 +1,10 @@ """ backend/app/models/shipping_customer_resolution.py -用途:保存订单候选的客户影子识别结果与人工标签。 +用途:保存订单候选的正式客户识别结果、识别证据与人工标签。 依赖:ShippingOrderCandidate、ShippingOrderIntake、ShippingCustomer、User。 -逻辑:订单候选抽取后幂等刷新本表;阶段 3 仅用于质量观测,禁止据此绑定业务单或生成编号。 +逻辑:订单候选抽取后幂等刷新识别证据和候选;确认字段独立保存最终客户, + 不得以订单中的任一字段(例如 bill_to)充当客户身份真相。 """ from __future__ import annotations @@ -11,19 +12,19 @@ from __future__ import annotations from datetime import datetime from typing import List, Optional -from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint +from sqlalchemy import CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base class ShippingCustomerShadowResolution(Base): - """每个订单候选唯一一条影子识别快照,可追加管理员真值标签。""" + """每个订单候选唯一一条正式客户识别快照,可追加确认和质量标签。""" __tablename__ = 'shipping_customer_shadow_resolutions' __table_args__ = ( CheckConstraint( - "status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed')", + "status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')", name='ck_shipping_customer_shadow_status', ), Index('ix_shipping_customer_shadow_status_created', 'status', 'created_at'), @@ -56,6 +57,12 @@ class ShippingCustomerShadowResolution(Base): resolution_context_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) top_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) top_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True) + # 客户确认是识别结果的独立事实;不得覆盖 evidence_json 或原始身份指纹。 + confirmed_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) + confirmation_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + confirmation_reason: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) manual_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) labeled_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) labeled_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) diff --git a/backend/app/models/shipping_order_customer_match.py b/backend/app/models/shipping_order_customer_match.py deleted file mode 100644 index 87844363..00000000 --- a/backend/app/models/shipping_order_customer_match.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -backend/app/models/shipping_order_customer_match.py - -用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。 -依赖:ShippingOrderExtraction、ShippingCustomer、users。 -逻辑:动态订单字段保留原文客户名称;本表按角色保存规则版本化身份指纹、候选、确认客户及名称/简称快照,供冻结和导出读取。 -""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any, Optional - -from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint -from sqlalchemy.orm import Mapped, mapped_column, relationship - -from app.models.base import Base - - -class ShippingOrderCustomerMatch(Base): - """一次订单解析中的角色化客户匹配;每个解析记录的每种客户角色仅保留一条当前结果。""" - - __tablename__ = 'shipping_order_customer_matches' - __table_args__ = ( - UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'), - CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'), - CheckConstraint( - "status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')", - name='ck_shipping_order_customer_matches_status', - ), - Index('ix_shipping_order_customer_matches_customer_role', 'customer_id', 'role'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - extraction_id: Mapped[int] = mapped_column( - ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False, index=True, - ) - role: Mapped[str] = mapped_column(String(16), nullable=False) - raw_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) - source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) - identity_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - identity_components_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched') - customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) - site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), 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) - candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list) - resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - confirmation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) - confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - updated_at: Mapped[datetime] = mapped_column( - DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, - ) - - extraction = relationship('ShippingOrderExtraction') - customer = relationship('ShippingCustomer') - site = relationship('ShippingCustomerSite') diff --git a/backend/app/services/agent_registry/handlers/shipping_notice.py b/backend/app/services/agent_registry/handlers/shipping_notice.py index 09fe96a9..fb65ce32 100644 --- a/backend/app/services/agent_registry/handlers/shipping_notice.py +++ b/backend/app/services/agent_registry/handlers/shipping_notice.py @@ -89,10 +89,10 @@ 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 {} - checkpoint = ui_state.get('checkpoint') return json.dumps({ 'task_no': event.get('task_no'), - 'checkpoint': checkpoint, + 'position': ui_state.get('position'), + 'user_mode': ui_state.get('user_mode'), 'updated_at': ui_state.get('updated_at'), }, ensure_ascii=False, sort_keys=True) diff --git a/backend/app/services/file_assets/service.py b/backend/app/services/file_assets/service.py index 1de7c862..2e700c0d 100644 --- a/backend/app/services/file_assets/service.py +++ b/backend/app/services/file_assets/service.py @@ -381,11 +381,12 @@ def create_derived_file_asset_from_bytes( expires_at=expires_at, ) - # [STEP] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务 + # [STEP] 幂等插入派生资产:先查后建规避常见唯一约束冲突;冲突时回读已有行。 + # 不使用 begin_nested SAVEPOINT:被 SAVEPOINT 语义包住的 INSERT 在同一 Session + # 内创建多个派生资产时,其行对后续 autoflush 的 UPDATE 不可见,会触发 StaleDataError。 try: - with db.session.begin_nested(): - db.session.add(asset) - db.session.flush() + db.session.add(asset) + db.session.flush() except IntegrityError: raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash) if raced is not None: diff --git a/backend/app/services/in_transit_transfer/concurrency.py b/backend/app/services/in_transit_transfer/concurrency.py index 09438f5c..3f727c77 100644 --- a/backend/app/services/in_transit_transfer/concurrency.py +++ b/backend/app/services/in_transit_transfer/concurrency.py @@ -9,9 +9,9 @@ from __future__ import annotations # 一期冻结并发参数(与规格 §10 一致)。 -SOURCE_CONCURRENCY = 2 -ERP_QUERY_CONCURRENCY = 2 -ERP_WRITE_CONCURRENCY = 1 +SOURCE_CONCURRENCY = 3 +ERP_QUERY_CONCURRENCY = 3 +ERP_WRITE_CONCURRENCY = 3 def assert_single_writer(run_count: int) -> None: diff --git a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py index eb24344d..37dfb9a0 100644 --- a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py +++ b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py @@ -2,7 +2,7 @@ services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py 用途:OT 后行级自动履约补偿轮询(每 15 分钟)——补齐 matching/ot_created 事件丢失。 -依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_line_keys。 +依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_snapshot_line_ids。 逻辑:platform_api_path=shipping-post-ot-auto-fulfill-compensation;flag 关闭时 no-op; 仅扫描有正式 OT 且存在 eligible 行的 Case,复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。 """ @@ -18,7 +18,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import ( ) from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( - list_eligible_post_ot_line_keys, + list_eligible_post_ot_snapshot_line_ids, ) ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] @@ -63,7 +63,7 @@ def run_post_ot_auto_fulfill_compensation(*, limit: int = 50) -> dict[str, Any]: if scanned >= safe_limit: break scanned += 1 - eligible = list_eligible_post_ot_line_keys(case) + eligible = list_eligible_post_ot_snapshot_line_ids(case) if not eligible: skipped += 1 continue diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index f66dfd61..c1ff5278 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -2,9 +2,11 @@ services/shipping_notice/auto_progress_controller.py 用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。 -依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务。 +依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务; + process_gate_job_service.cancel_inventory_external_wait_polls(显式 retry_rpa 终止轮询)。 逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job - 在同一数据库事务落库。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 + 在同一数据库事务落库。显式 inventory_mode=retry_rpa 时覆盖 waiting_external 残留 poll, + 强制入队 retry_inventory_preparation。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 """ from __future__ import annotations @@ -18,18 +20,18 @@ from flask import current_app from app import db from app.jobs.queue import enqueue from app.jobs.types import JobType -from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt +from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate from app.services.shipping_notice.tool_common import log_task_event _ACTIVE_JOB_STATUSES = ('queued', 'running') -_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'}) +_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled'}) def audit_legacy_forwarded_entrypoint( - *, task: ShippingNotice, action_code: str, actor_id: int | None = None, + *, task: ShippingOrderTask, action_code: str, actor_id: int | None = None, request_id: str | None = None, ) -> None: """记录旧工作台入口已转发至正式 Gate Orchestrator 的审计事实。""" @@ -51,9 +53,9 @@ def _utc_now() -> datetime: return datetime.utcnow() -def _task_is_cancelled(task: ShippingNotice) -> bool: +def _task_is_cancelled(task: ShippingOrderTask) -> bool: """根据生命周期事实判断任务是否不可再推进,旧 Job 不得将其复活。""" - return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES + return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES or str(getattr(task, 'status', '') or '').strip().lower() == 'cancelled' def _recover_stale_active_job(job: Job) -> bool: @@ -90,6 +92,17 @@ def _recover_stale_active_job(job: Job) -> bool: gate.status = 'blocked_manual' gate.blocking_reason_code = 'technical_failure_present' gate.updated_at = now + # [FIX] 同一事务内重算 Execution 指针并回写 OT.stage,避免 Gate 已被判为 + # blocked_manual 而 execution.status / OT.stage 仍停在上一机械阶段(如 automating)。 + execution_id = getattr(gate, 'execution_id', None) + execution = ( + db.session.get(ShippingProcessExecution, int(execution_id)) + if execution_id is not None else None + ) + if execution is not None: + from app.services.shipping_notice.process_gate_service import _refresh_execution_pointers + + _refresh_execution_pointers(execution) db.session.flush() return True @@ -111,7 +124,7 @@ def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool: def determine_formal_start_gate( - task: ShippingNotice, + task: ShippingOrderTask, *, candidate_set: Any | None = None, ) -> str: @@ -126,7 +139,8 @@ def determine_formal_start_gate( return 'order_freeze_readiness' # 仅当服务端已明确记录 pending/failed 时阻断客户确认;None 保留给历史 # Task-only 兼容构造,不能把缺失的可选字段误当成失败事实。 - customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower() + from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts + customer_status = str((customer_confirmation_facts(task) or {}).get('status') or '').strip().lower() if customer_status in {'pending', 'needs_review', 'failed', 'unresolved'}: return 'customer_resolution' # 字段冲突是独立的正式 Gate,必须先于候选冻结和库存准备处理。 @@ -139,7 +153,7 @@ def determine_formal_start_gate( def _create_formal_execution_for_task( - task: ShippingNotice, + task: ShippingOrderTask, *, candidate_set_id: int | None, ) -> ShippingProcessExecution: @@ -178,7 +192,7 @@ def _supersede_duplicate_execution( ) -def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution: +def _active_execution_for_task(task: ShippingOrderTask, *, candidate_set_id: int | None) -> ShippingProcessExecution: """ 锁定并取得当前唯一活动 Execution。 @@ -235,7 +249,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | return _create_formal_execution_for_task(task, candidate_set_id=candidate_set_id) -def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None: +def supersede_auto_progress_for_candidate_refreeze(task: ShippingOrderTask) -> None: """ 在 CandidateSet 指针切换后取消旧 Job/未完成 Gate,防止旧版本副作用污染新链。 @@ -309,9 +323,37 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi return None, None +def _auto_retry_blocked( + trigger: str | None, + has_failed_worker_attempt: bool, + resume_gate_code: str | None = None, +) -> bool: + """[禁止自动重试] 裁决:已存在失败 Worker Attempt 时是否拒绝再入队。 + + 核心逻辑:防止自动/后台 trigger 在外部依赖持续故障时无人值守空转重试; + 但用户显式重试(user_retry / user_manual)或带 resume_gate_code 的显式定向推进 + (如匹配工具调 run_task_auto_progress,其 trigger 为 tool_api_match_inventory_line + 而非 user_retry)应放行,否则点"重新匹配库存"会因 has_failed_worker_attempt + 被误拦、报"自动推进已无待处理 Gate"。 + + Args: + trigger: 触发类型(auto / user_retry / user_manual / worker_takeover / ...)。 + has_failed_worker_attempt: 当前 Gate 是否已有带 job_id 的失败 Attempt。 + resume_gate_code: 显式定向推进的目标 Gate;有值即视为用户/工具主动恢复,不拦。 + + Returns: + True 表示应禁止自动再入队;False 表示放行。 + """ + user_initiated = str(trigger or '').strip() in {'user_retry', 'user_manual'} + explicit_resume = bool(str(resume_gate_code or '').strip()) + return bool(has_failed_worker_attempt) and not user_initiated and not explicit_resume + + def submit_auto_progress( - *, task: ShippingNotice, trigger: str, operator_id: int | None = None, + *, task: ShippingOrderTask, trigger: str, operator_id: int | None = None, resume_gate_code: str | None = None, commit: bool = True, + inventory_mode: str = 'auto', + line_scope_key: str | None = None, recovery_plan_id: int | None = None, recovery_attempt_id: int | None = None, resume_after_gate: str | None = None, @@ -319,14 +361,12 @@ def submit_auto_progress( """ 接收任何自动/用户触发并安全入队当前 Gate。 - 普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。 + 入口只接受 ShippingOrderTask;Execution 与 Gate 始终按 OT 任务身份推进。 """ - # ShippingNotice.shipping_case 使用 joined eager load,会产生 LEFT OUTER JOIN; - # PostgreSQL 禁止对外连接可空侧执行无目标 FOR UPDATE,因此仅锁主表。 locked_task = ( - ShippingNotice.query + ShippingOrderTask.query .filter_by(id=int(task.id)) - .with_for_update(of=ShippingNotice) + .with_for_update(of=ShippingOrderTask) .first() ) if locked_task is None: @@ -373,14 +413,23 @@ def submit_auto_progress( from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job from app.services.shipping_notice.process_gate_service import queue_gate_attempt - sync_fulfillment_gates_from_task( - execution=execution, - actor_type='system', - actor_id=operator_id, + explicit_inventory_retry = ( + str(inventory_mode or '').strip() == 'retry_rpa' + and str(resume_gate_code or '').strip() == 'inventory_preparation' ) - db.session.flush() + if not explicit_inventory_retry: + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=operator_id, + ) + db.session.flush() execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one() - current_gate = str(execution.current_gate_code or '').strip() or None + current_gate = ( + 'inventory_preparation' + if explicit_inventory_retry + else str(execution.current_gate_code or '').strip() or None + ) gate = ( ShippingProcessGate.query .filter_by(execution_id=int(execution.id), gate_code=current_gate) @@ -388,6 +437,53 @@ def submit_auto_progress( .first() if current_gate else None ) + if explicit_inventory_retry and gate is not None: + # [ROOT CAUSE] 显式 retry_rpa(含行级改源后重抓)必须覆盖残留的 + # poll_inventory_preparation / waiting_external。否则只会再入队只读 poll: + # poll 遇到失败 Preparation 会直接收口,既不建新 RPA Attempt 也不写 trigger。 + # passed / waiting_external / failed_terminal 一律放开为 blocked_retryable。 + from app.services.shipping_notice.process_gate_job_service import ( + cancel_inventory_external_wait_polls, + ) + + cancel_inventory_external_wait_polls( + gate_id=int(gate.id), + reason='显式库存重抓:终止外部等待轮询', + ) + # 活动 Attempt 不得被复用;否则 queue_gate_attempt 会因 BUSY 失败, + # 或 active_attempt 早退把「强制重抓」吞成「继续轮询」。 + for stale in ( + ShippingProcessGateAttempt.query + .filter( + ShippingProcessGateAttempt.gate_id == int(gate.id), + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ) + .all() + ): + stale.status = 'failed' + stale.error_code = 'superseded_by_explicit_retry' + stale.error_summary = '被显式库存重抓取代' + stale.finished_at = _utc_now() + if stale.job_id: + stale_job = db.session.get(Job, int(stale.job_id)) + if stale_job is not None and str(stale_job.status or '') in _ACTIVE_JOB_STATUSES: + stale_job.status = 'cancelled' + stale_job.finished_at = _utc_now() + stale_job.message = '显式库存重抓:取消残留活动 Job' + gate.status = 'blocked_retryable' + gate.passed_at = None + gate.blocking_reason_code = 'inventory_rpa_retry_requested' + gate.next_action_code = 'retry_inventory_preparation' + gate.evaluation_version = int(gate.evaluation_version) + 1 + gate.lock_version = int(gate.lock_version) + 1 + gate.updated_at = _utc_now() + execution.current_gate_code = 'inventory_preparation' + # 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate + # 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。 + execution.responsible_party = 'worker' + execution.primary_next_action_code = 'retry_inventory_preparation' + execution.updated_at = _utc_now() + db.session.flush() active_attempt = ( ShippingProcessGateAttempt.query .filter( @@ -398,7 +494,7 @@ def submit_auto_progress( .first() if gate is not None else None ) - if active_attempt is not None and active_attempt.job_id: + if active_attempt is not None and active_attempt.job_id and not explicit_inventory_retry: if commit: db.session.commit() return { @@ -410,6 +506,22 @@ def submit_auto_progress( 'reused': True, } action_code = str(getattr(gate, 'next_action_code', '') or '').strip() + # [禁止自动重试] 门禁一旦存在“Worker 真实执行失败”的 Attempt(failed 且 job_id 非空), + # 本次自动投递即属重试:任何 trigger(回调/聊天/批处理)都不得再入队,重试必须由 + # 用户在当前 Gate 显式发起;否则外部依赖持续故障时,回调/轮询会形成无人值守的 + # “失败→重试→再失败”空转环。仅存量内联投影 Attempt(job_id 为空)或无 Attempt + # 的首次投递不受影响,编排初始触发保持不变。 + has_failed_worker_attempt = ( + gate is not None + and db.session.query(ShippingProcessGateAttempt.id) + .filter( + ShippingProcessGateAttempt.gate_id == int(gate.id), + ShippingProcessGateAttempt.status == 'failed', + ShippingProcessGateAttempt.job_id.isnot(None), + ) + .first() + is not None + ) # 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的 # system/worker Gate 才可自动创建 Attempt 并入队。 # 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。 @@ -418,6 +530,7 @@ def submit_auto_progress( if ( gate is not None and action_code + and not _auto_retry_blocked(trigger, has_failed_worker_attempt, resume_gate_code) and action_belongs_to_gate(gate_code=str(gate.gate_code), action_code=action_code) and not is_navigation_action(action_code) and is_technical_gate_party(execution.responsible_party) @@ -439,6 +552,8 @@ def submit_auto_progress( 'candidate_set_id': candidate_set_id, 'fencing_token': uuid.uuid4().hex, 'trigger': trigger, + 'inventory_mode': inventory_mode, + 'line_scope_key': line_scope_key, 'recovery_plan_id': recovery_plan_id, 'recovery_attempt_id': recovery_attempt_id, 'resume_after_gate': resume_after_gate, diff --git a/backend/app/services/shipping_notice/chat_actions.py b/backend/app/services/shipping_notice/chat_actions.py index 44368a67..b456a676 100644 --- a/backend/app/services/shipping_notice/chat_actions.py +++ b/backend/app/services/shipping_notice/chat_actions.py @@ -2,11 +2,17 @@ services/shipping_notice/chat_actions.py 用途:发货通知聊天只读状态适配。 -依赖:state_machine(checkpoint 与内部状态迁移)、ui_state。 +依赖:state_machine(位置/用户模式与内部状态迁移)、ui_state。 逻辑:Chat 不再拥有动作目录或写入口;仅输出 Gate 已裁决的只读 UI State。 """ -from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, checkpoint_for_task, resolve_task_ui_state, validate_registry +from app.services.shipping_notice.state_machine import ( + TaskTransition, + apply_task_transition, + position_for_task, + resolve_task_ui_state, + validate_registry, +) from app.services.shipping_notice.ui_state import build_task_ui_state @@ -14,19 +20,20 @@ def build_chat_actions_payload(task) -> dict: """ 构建聊天气泡侧动作按钮兼容 payload。 - 核心逻辑:复用统一 UI State 读模型,抽取聊天侧 checkpoint/summary/process_gate; + 核心逻辑:复用统一 UI State 读模型,抽取聊天侧 position/user_mode/summary/process_gate; 业务动作只从 ui_state.actions 返回,Chat 不再暴露旧 action_buttons。 Args: task: ShippingNotice 模型实例。 Returns: - 包含 task_no、checkpoint、process_gate、actions 与摘要的字典。 + 包含 task_no、position、user_mode、process_gate、actions 与摘要的字典。 """ state = build_task_ui_state(task) return { "task_no": state.get("task_no"), - "checkpoint": state.get("checkpoint"), + "position": state.get("position"), + "user_mode": state.get("user_mode"), "stage": state.get("stage"), "todo": state.get("todo"), "actions": state.get("actions"), @@ -41,7 +48,7 @@ __all__ = [ "TaskTransition", "apply_task_transition", "build_chat_actions_payload", - "checkpoint_for_task", + "position_for_task", "resolve_task_ui_state", "validate_registry", ] diff --git a/backend/app/services/shipping_notice/constants.py b/backend/app/services/shipping_notice/constants.py index 23b84e52..e3d2bfaa 100644 --- a/backend/app/services/shipping_notice/constants.py +++ b/backend/app/services/shipping_notice/constants.py @@ -1,10 +1,10 @@ """ services/shipping_notice/constants.py -用途:发货通知 API 字段名、checkpoint / review_status / pending_human_reason 的规范常量; +用途:发货通知 API 字段名、位置标签 POSITION_* / review_status / pending_human_reason 的规范常量; 并再导出错误可解释性分层原因码集合,供 Tool/Workspace 与门禁投影对齐。 -依赖:error_explainability_contract(分层原因码冻结集);state_machine.py 引用 CP_*/PH_*/RS_*。 -逻辑:tools.py、tool_response、workspace API 统一读本模块,避免 checkpoint id 漂移; +依赖:error_explainability_contract(分层原因码冻结集);state_machine / ui_state 引用 POSITION_*/PH_*/RS_*。 +逻辑:tools.py、tool_response、workspace API 统一读本模块,避免位置标签漂移; 细粒度 reason_code 以 error_explainability_contract 为准,本文件仅再导出。 """ @@ -36,28 +36,27 @@ from app.services.shipping_notice.error_explainability_contract import ( # Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑 AUTO_CHAIN_FALLBACK = "auto_chain_fallback" -# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py) -CP_UPLOAD_REQ = "upload_req" -CP_PARSE_OK = "parse_ok" -CP_PARSE_REVIEW = "parse_review" -CP_CUSTOMER_REVIEW = "customer_review" -CP_TASK_EXISTS = "task_exists" -CP_RSV_REQ = "rsv_req" -CP_UPLOAD_FAILED = "upload_failed" -CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" -CP_WAITING_UPLOAD = "waiting_upload" -CP_REJECTED = "rejected" -# Derived UI checkpoints (no separate pending_human_reason; from domain facts) -CP_INVENTORY_PENDING = "inventory_pending" -CP_READY_MATCH = "ready_to_match" -CP_READY_EXPORT = "ready_to_export" -CP_EXPORT_READY = "export_ready" -CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed" -CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review" -CP_ORDER_FREEZE = "order_freeze" -CP_EXPORT_GENERATED = "export_generated" -CP_UPLOADED = "uploaded" -CP_COMPLETED = "completed" +# 位置标签(原 CheckPoint 字面量;非状态机。derive_position / 文案表共用) +POSITION_UPLOAD_REQ = "upload_req" +POSITION_PARSE_OK = "parse_ok" # 转瞬态;新逻辑勿依赖 +POSITION_PARSE_REVIEW = "parse_review" +POSITION_CUSTOMER_REVIEW = "customer_review" +POSITION_TASK_EXISTS = "task_exists" # 信息态;新逻辑勿依赖 +POSITION_RSV_REQ = "rsv_req" +POSITION_UPLOAD_FAILED = "upload_failed" +POSITION_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" +POSITION_WAITING_UPLOAD = "waiting_upload" +POSITION_REJECTED = "rejected" +POSITION_INVENTORY_PENDING = "inventory_pending" +POSITION_READY_MATCH = "ready_to_match" +POSITION_READY_EXPORT = "ready_to_export" +POSITION_EXPORT_READY = "export_ready" +POSITION_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed" +POSITION_INVENTORY_SOURCE_REVIEW = "inventory_source_review" +POSITION_ORDER_FREEZE = "order_freeze" +POSITION_EXPORT_GENERATED = "export_generated" +POSITION_UPLOADED = "uploaded" +POSITION_COMPLETED = "completed" # review_status RS_PARSE_REVIEW = "parse_review" @@ -68,13 +67,13 @@ RS_CONFIRMED = "confirmed" # pending_human_reason (internal; shortened) PH_LOW_CONF = "low_confidence" -PH_RSV_REQ = CP_RSV_REQ +PH_RSV_REQ = POSITION_RSV_REQ PH_SHORTAGE = "shortage" PH_RPA_EXHAUSTED = "rpa_exhausted" PH_RPA_PENDING = "rpa_pending" PH_INV_UNAVAIL = "inv_unavail" PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved" -PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED +PH_NOTICE_TEXT_EXTRACTION_FAILED = POSITION_NOTICE_TEXT_EXTRACTION_FAILED PH_UPLOAD_RPA_FAILED = "upload_rpa_failed" PH_UPLOAD_RPA_PENDING = "upload_rpa_pending" PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" @@ -82,26 +81,26 @@ PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" # 错误可解释性契约再导出(阶段 0 冻结;接线见 error_explainability_contract / 契约文档) __all__ = ( 'AUTO_CHAIN_FALLBACK', - 'CP_UPLOAD_REQ', - 'CP_PARSE_OK', - 'CP_PARSE_REVIEW', - 'CP_CUSTOMER_REVIEW', - 'CP_TASK_EXISTS', - 'CP_RSV_REQ', - 'CP_UPLOAD_FAILED', - 'CP_UPLOAD_RESULT_UNKNOWN', - 'CP_WAITING_UPLOAD', - 'CP_REJECTED', - 'CP_INVENTORY_PENDING', - 'CP_READY_MATCH', - 'CP_READY_EXPORT', - 'CP_EXPORT_READY', - 'CP_NOTICE_TEXT_EXTRACTION_FAILED', - 'CP_INVENTORY_SOURCE_REVIEW', - 'CP_ORDER_FREEZE', - 'CP_EXPORT_GENERATED', - 'CP_UPLOADED', - 'CP_COMPLETED', + 'POSITION_UPLOAD_REQ', + 'POSITION_PARSE_OK', + 'POSITION_PARSE_REVIEW', + 'POSITION_CUSTOMER_REVIEW', + 'POSITION_TASK_EXISTS', + 'POSITION_RSV_REQ', + 'POSITION_UPLOAD_FAILED', + 'POSITION_UPLOAD_RESULT_UNKNOWN', + 'POSITION_WAITING_UPLOAD', + 'POSITION_REJECTED', + 'POSITION_INVENTORY_PENDING', + 'POSITION_READY_MATCH', + 'POSITION_READY_EXPORT', + 'POSITION_EXPORT_READY', + 'POSITION_NOTICE_TEXT_EXTRACTION_FAILED', + 'POSITION_INVENTORY_SOURCE_REVIEW', + 'POSITION_ORDER_FREEZE', + 'POSITION_EXPORT_GENERATED', + 'POSITION_UPLOADED', + 'POSITION_COMPLETED', 'RS_PARSE_REVIEW', 'RS_SHORTAGE_REVIEW', 'RS_RSV_REQ', diff --git a/backend/app/services/shipping_notice/customer_identity_gate.py b/backend/app/services/shipping_notice/customer_identity_gate.py index 23fd6d4a..da66174a 100644 --- a/backend/app/services/shipping_notice/customer_identity_gate.py +++ b/backend/app/services/shipping_notice/customer_identity_gate.py @@ -171,7 +171,7 @@ def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict task=task, message='标准客户尚未确认,请先选择正式客户后再继续。', data=serialize_task_for_tool(task), - checkpoint='customer_review', + position='customer_review', stop_agent_turn=True, forbidden_next_tools=[ 'ensure_inventory', 'parse_inventory', 'match_inventory', @@ -204,7 +204,7 @@ def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]: task=task, message='请选择标准客户。', data=serialize_task_for_tool(task), - checkpoint='customer_review', + position='customer_review', stop_agent_turn=True, ) updated = confirm_task_customer( diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py deleted file mode 100644 index dd070fd8..00000000 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ /dev/null @@ -1,517 +0,0 @@ -""" -services/shipping_notice/decision_workflow.py - -用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。 -依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、 - tool_common(操作人/生命周期快照)、fulfillment_audit。 -逻辑:由 task_workflow / workspace API 转调;决策事件必须带操作人与前后快照, - reject/close/confirm 同步写入 ShippingAuditEvent。 -""" - -from __future__ import annotations - -from typing import Any - -from app import db -from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun, ShippingTaskInventoryLink -from app.services.shipping_notice.constants import ( - CP_INVENTORY_SOURCE_REVIEW, - CP_PARSE_OK, - PH_INVENTORY_SOURCE_UNRESOLVED, - PH_LOW_CONF, - PH_RPA_PENDING, - PH_SHORTAGE, - RS_PARSE_REVIEW, - RS_SHORTAGE_REVIEW, -) -from app.services.shipping_notice.fulfillment_workflow import match_completed -from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction -from app.services.shipping_notice.inventory_source_gate import ( - is_inventory_source_stable, - adjudicate_and_apply_inventory_source, - ensure_inventory_source_review_state, -) -from app.services.shipping_notice.i18n import resolve_lang, t -from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool -from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state -from app.services.shipping_notice.tool_common import ( - log_task_action_event, - log_task_event, - merge_tool_payload, - payload_wants_auto_chain_fallback, - resolve_workspace_actor_id, - task_lifecycle_audit_snapshot, - prepend_tool_message, -) -from app.services.shipping_notice.tool_response import tool_response - - -def start_task_orchestrator(task_no: str | None) -> bool: - """延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。""" - from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start - - return _start(task_no) - - -def _reset_inventory_state_for_forced_rpa(task) -> None: - """ - 清理旧库存派生结果,让 retry_rpa 成为真正的“重新获取库存”。 - 【AI 触发时机】:用户明确要求重新获取库存时由 submit_decision 内部调用。 - """ - task.inventory_lines_json = None - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.export_file_path = None - task.export_file_name = None - task.freight_ref_no = None - task.upload_status = None - task.upload_mode = None - - -def _request_formal_gate_action(**kwargs): - """决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。 - - 核心逻辑:请求正式 Gate 恢复前先清除任务级解析/复核阻断残留 - (review_status / pending_human_reason / error_message / upload 错误), - 避免旧阻断事实污染重启后的 Gate 投影。写入由被调用方的事务统一提交。 - """ - task = kwargs.get('task') - if task is not None: - task.upload_error_message = None - task.upload_receipt_json = None - task.review_status = None - task.pending_human_reason = None - task.error_message = None - - from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request - - return _request(**kwargs) - - -def _prepare_task_for_inventory_reupload(task) -> None: - """ - 解除任务当前库存快照并清理派生结果,等待用户重新选择正式库存文件。 - - 【AI 触发时机】:用户明确选择“重新上传库存”时由 submit_decision 内部调用。 - 历史库存快照与 link 保留审计,但当前 active link 会停用,且不会进入字段推断链路。 - """ - if task.id is not None: - for link in ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all(): - link.is_active = False - _reset_inventory_state_for_forced_rpa(task) - apply_task_transition(task, TaskTransition.INV_UNAVAIL) - - -def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: - """ - 提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。 - 【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。 - -核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、正式 Gate - Recovery 或重解析等分支;工作台入口须注入 operator_id 以保证审计非匿名。 - Args: - payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。 - - Returns: - dict[str, Any]: Tool 标准响应,返回决策后的任务阶段和下一步动作。 - """ - task = resolve_task_from_payload(payload) - if not task: - return tool_response( - status="failed", - message=t("workflow.decision.task_not_found", lang="zh"), - ) - - decision = str(payload.get("decision") or "").strip().lower() - comment = str(payload.get("comment") or "").strip() - lang = resolve_lang(payload) - event_source = str(payload.get("event_source") or "").strip() or "decision_workflow" - actor_id = resolve_workspace_actor_id(payload) - before_snapshot = task_lifecycle_audit_snapshot(task) - - # Published parsing profiles are the only production mapping contract. - # Reject legacy task-level mapping decisions instead of reopening a manual - # mapping path that could override the source's configured profile. - if decision in {"confirm_inventory_mapping", "correct_inventory_mapping"}: - return tool_response( - status="failed", - task_id=task.task_no, - message="库存字段映射已由库存站点的已发布解析方案管理;请在库存映射中调整方案后重新获取库存。", - data=serialize_task_for_tool(task), - ) - - if decision == "reparse_inventory": - _prepare_task_for_inventory_reupload(task) - log_task_action_event( - task, - "inventory_reupload_requested", - action="reparse_inventory", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=task_lifecycle_audit_snapshot(task), - ) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。", - data=serialize_task_for_tool(task), - checkpoint="upload_req", - stop_agent_turn=True, - ) - - # [STEP 1] 先处理终止型决策。 - # reject / close 会直接结束当前任务,不再继续进入库存或出货链路。 - if decision == "reject": - apply_task_transition(task, TaskTransition.REJECTED) - after_snapshot = task_lifecycle_audit_snapshot(task) - log_task_action_event( - task, - "decision_rejected", - action="reject", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=after_snapshot, - ) - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - record_fulfillment_audit( - event_type='task_decision', - aggregate_type='shipping_task', - aggregate_id=task.task_no, - action='reject', - actor_type='user' if actor_id is not None else 'system', - actor_id=actor_id, - task_no=task.task_no, - conversation_id=task.conversation_id, - before=before_snapshot or {'status': 'active'}, - after=after_snapshot or {'status': 'rejected'}, - metadata={'decision': 'reject'}, - source=event_source, - ) - db.session.commit() - return tool_response( - status="ok", - task_id=task.task_no, - message=t("workflow.decision.rejected", lang=lang), - data=serialize_task_for_tool(task), - ) - - if decision in {"close", "closed"}: - apply_task_transition(task, TaskTransition.CLOSED) - after_snapshot = task_lifecycle_audit_snapshot(task) - log_task_action_event( - task, - "decision_closed", - action="close", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=after_snapshot, - ) - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - record_fulfillment_audit( - event_type='task_decision', - aggregate_type='shipping_task', - aggregate_id=task.task_no, - action='close', - actor_type='user' if actor_id is not None else 'system', - actor_id=actor_id, - task_no=task.task_no, - conversation_id=task.conversation_id, - before=before_snapshot or {'status': 'active'}, - after=after_snapshot or {'status': 'closed'}, - metadata={'decision': 'close'}, - source=event_source, - ) - db.session.commit() - return tool_response( - status="ok", - task_id=task.task_no, - message=t("workflow.decision.closed", lang=lang), - data=serialize_task_for_tool(task), - ) - - # [STEP 2] 处理“确认继续”类决策。 - # confirm 既可能表示确认解析,也可能表示确认已匹配结果,因此要结合当前状态分支判断。 - if decision in {"confirm", "confirmed", "confirm_parse"}: - if task.review_status == RS_SHORTAGE_REVIEW or task.pending_human_reason == PH_SHORTAGE: - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.shortage_confirm_blocked", lang=lang), - data=serialize_task_for_tool(task), - ) - - if ( - decision == "confirm_parse" - or task.review_status == RS_PARSE_REVIEW - or task.pending_human_reason == PH_LOW_CONF - or not match_completed(task) - ): - parse_validation = ( - (task.step_payload_json or {}).get("parse_validation") - if isinstance(task.step_payload_json, dict) - else None - ) - blocking_issues = [ - item - for item in (parse_validation.get("issues") if isinstance(parse_validation, dict) else []) or [] - if isinstance(item, dict) and item.get("severity") == "blocking" - ] - if blocking_issues: - return tool_response( - status="needs_human", - task=task, - message="解析结果仍包含不合法的关键字段,请修正后再确认。", - data={**serialize_task_for_tool(task), "parse_validation": parse_validation}, - checkpoint=task.review_status or "parse_review", - stop_agent_turn=True, - forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"], - ) - is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF - # 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。 - if ( - not is_low_confidence_parse_confirm - and ( - task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED - or not is_inventory_source_stable(task) - ) - ): - ui = resolve_task_ui_state(task) - return tool_response( - status="needs_human", - task=task, - message="库存源尚未确定,请先完成库存源确认。", - data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, - stop_agent_turn=True, - ) - apply_task_transition(task, TaskTransition.CONFIRM_PARSE) - task.match_status = None - task.shortage_json = None - task.line_results_json = None - after_snapshot = task_lifecycle_audit_snapshot(task) - log_task_action_event( - task, - "parse_confirmed", - action="confirm", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=after_snapshot, - ) - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - record_fulfillment_audit( - event_type='task_decision', - aggregate_type='shipping_task', - aggregate_id=task.task_no, - action='confirm_parse', - actor_type='user' if actor_id is not None else 'system', - actor_id=actor_id, - task_no=task.task_no, - conversation_id=task.conversation_id, - before=before_snapshot, - after=after_snapshot, - metadata={'decision': decision}, - source=event_source, - ) - db.session.commit() - if not is_inventory_source_stable(task): - adjudication = ensure_inventory_source_review_state(task) - db.session.commit() - return tool_response( - status="ok", - task=task, - message="解析内容已确认,请继续选择正式库存源。", - data={ - **serialize_task_for_tool(task), - "inventory_source_candidates": adjudication.candidates, - "inventory_source_status": adjudication.status, - "inventory_source_reason": adjudication.reason, - "destination_candidates": adjudication.destination_candidates, - }, - checkpoint=CP_INVENTORY_SOURCE_REVIEW, - stop_agent_turn=True, - ) - if not task.inventory_lines_json: - orchestrator_started = start_task_orchestrator(task.task_no) - return tool_response( - status="running" if orchestrator_started else "ok", - task=task, - message=t("workflow.decision.parse_confirmed_running", lang=lang), - data=serialize_task_for_tool(task), - checkpoint=CP_PARSE_OK, - next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang), - forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], - ) - return tool_response( - status="ok", - task=task, - message=t("workflow.decision.parse_confirmed_next", lang=lang), - data=serialize_task_for_tool(task), - checkpoint=CP_PARSE_OK, - next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang), - forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], - ) - - if match_completed(task): - apply_task_transition(task, TaskTransition.CONFIRM_MATCHED) - after_snapshot = task_lifecycle_audit_snapshot(task) - log_task_action_event( - task, - "decision_confirmed", - action="confirm", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=after_snapshot, - ) - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - record_fulfillment_audit( - event_type='task_decision', - aggregate_type='shipping_task', - aggregate_id=task.task_no, - action='confirm_matched', - actor_type='user' if actor_id is not None else 'system', - actor_id=actor_id, - task_no=task.task_no, - conversation_id=task.conversation_id, - before=before_snapshot, - after=after_snapshot, - metadata={'decision': decision}, - source=event_source, - ) - db.session.commit() - return tool_response( - status="ok", - task_id=task.task_no, - message=t("workflow.decision.matched_confirmed", lang=lang), - data=serialize_task_for_tool(task), - ) - - if task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json: - orchestrator_started = start_task_orchestrator(task.task_no) - return tool_response( - status="running" if orchestrator_started else "ok", - task=task, - message=t("workflow.decision.inventory_preparing", lang=lang), - data=serialize_task_for_tool(task), - ) - - if task.inventory_lines_json: - orchestrator_started = start_task_orchestrator(task.task_no) - return tool_response( - status="running" if orchestrator_started else "ok", - task=task, - message=t("workflow.decision.fulfillment_running", lang=lang), - data=serialize_task_for_tool(task), - ) - - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.confirm_invalid_state", lang=lang), - data=serialize_task_for_tool(task), - ) - - # [STEP 3] 处理重算型决策。 - # retry_rpa / rematch 都是在当前任务基础上回退或重放局部链路, - # 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。 - if decision == "retry_rpa": - _reset_inventory_state_for_forced_rpa(task) - log_task_event( - task, - "decision_retry_rpa", - {"comment": comment, "force_refresh": True}, - actor_id=actor_id, - source=event_source, - before=before_snapshot, - after=task_lifecycle_audit_snapshot(task), - ) - db.session.flush() - return _request_formal_gate_action( - task=task, - action_code='retry_inventory_preparation', - user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0), - idempotency_key=str(payload.get('idempotency_key') or f'decision-retry-rpa:{task.task_no}:{task.order_data_version}'), - trigger=event_source, - ) - - if decision == "rematch": - apply_task_transition(task, TaskTransition.REMATCH_REQUESTED) - task.match_status = None - task.shortage_json = None - task.line_results_json = None - log_task_action_event( - task, - "decision_rematch", - action="rematch", - source=event_source, - comment=comment, - actor_id=actor_id, - before=before_snapshot, - after=task_lifecycle_audit_snapshot(task), - ) - # flush 即可:状态清理与正式 Gate Action 入队同属一次连续写入,避免中间态落库。 - db.session.flush() - return _request_formal_gate_action( - task=task, - action_code='retry_inventory_from_matching', - user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0), - idempotency_key=str(payload.get('idempotency_key') or f'decision-rematch:{task.task_no}:{task.order_data_version}'), - trigger=event_source, - ) - - # [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。 - if decision == "reparse": - candidate = ( - db.session.get(ShippingOrderCandidate, int(task.source_candidate_id)) - if task.source_candidate_id else None - ) - source_run_id = candidate.order_extraction_run_id if candidate is not None else None - if source_run_id: - from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run - - run = db.session.get(ShippingOrderProcessingRun, source_run_id) - if run is not None: - replacement, reused = reparse_order_extraction_run( - user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None, - ) - log_task_action_event( - task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment, - extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused}, - actor_id=actor_id, - before=before_snapshot, - after=task_lifecycle_audit_snapshot(task), - ) - db.session.commit() - return tool_response( - status="needs_human", task=task, - message="已使用当前发布规则重新识别原始发货通知,请等待新版结果后审核。", - data={**serialize_task_for_tool(task), "order_extraction_run_no": replacement.run_no}, - checkpoint=task.review_status or "parse_review", stop_agent_turn=True, - forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], - ) - return tool_response( - status="needs_human", - task=task, - message="当前任务无法追溯到可重新识别的原始 Run,请重新上传发货通知。", - data=serialize_task_for_tool(task), - checkpoint=task.review_status or "parse_review", - stop_agent_turn=True, - forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], - ) - - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.unknown", lang=lang).format(decision=decision), - ) 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 e6fc1a96..99c7007c 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 @@ -177,6 +177,7 @@ def reconstruct_coordinate_profile_rows_with_strategy( dynamic_rows = reconstruct_coordinate_profile_rows( characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, table_region=table_region, termination_rules=termination_rules, + # dynamic 不执行普通排除过滤,但其专用排除区仍授权删除标记。 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, @@ -567,6 +568,7 @@ def reconstruct_coordinate_profile_rows( _absolute_relative_region(bbox, item) for item in (exclusion_regions or []) if isinstance(item, dict) ] + marker_authorization_exclusions = exclusions # 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其 # “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions, # 从而保留管理员配置的普通排除区。 @@ -583,10 +585,10 @@ def reconstruct_coordinate_profile_rows( continue band_indices = {glyph_index for glyph_index, _glyph in band} marker_indices.update(band_indices) - if exclusions and any( + if marker_authorization_exclusions and any( _inside_region(glyph.bbox, region) for _glyph_index, glyph in band - for region in exclusions + for region in marker_authorization_exclusions ): authorized_marker_indices.update(band_indices) # [STEP 2] 普通排除区内容与未授权删除文字都不参与字段重建;已授权删除标记保留到行状态判定。 @@ -604,7 +606,8 @@ 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( + return _resolve_shifted_part_number_candidates( + rows=_reconstruct_dynamic_x_columns_profile_rows( glyphs=glyphs, table_bbox=bbox, ordered_layouts=ordered_layouts, @@ -612,9 +615,13 @@ def reconstruct_coordinate_profile_rows( include_deleted=include_deleted, line_start_field_code=start_field_code, schema_fields=schema_fields, + ), + glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox, + line_start_field_code=start_field_code, ) if row_reconstruction_mode == 'adaptive_record_columns': - return _reconstruct_adaptive_record_columns_profile_rows( + return _resolve_shifted_part_number_candidates( + rows=_reconstruct_adaptive_record_columns_profile_rows( glyphs=glyphs, table_bbox=bbox, ordered_layouts=ordered_layouts, @@ -622,6 +629,9 @@ def reconstruct_coordinate_profile_rows( include_deleted=include_deleted, line_start_field_code=start_field_code, schema_fields=schema_fields, + ), + glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox, + line_start_field_code=start_field_code, ) relative_y_rows = _reconstruct_relative_y_profile_rows( @@ -636,7 +646,10 @@ def reconstruct_coordinate_profile_rows( schema_fields=schema_fields, ) if relative_y_rows is not None: - return relative_y_rows + return _resolve_shifted_part_number_candidates( + rows=relative_y_rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox, + line_start_field_code=start_field_code, + ) def values_for( band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any], @@ -730,7 +743,11 @@ def reconstruct_coordinate_profile_rows( current_issues.extend(continuation_issues) next_offset += 1 flush() - return results if include_deleted else [row for row in results if row.role != 'deleted'] + rows = results if include_deleted else [row for row in results if row.role != 'deleted'] + return _resolve_shifted_part_number_candidates( + rows=rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox, + line_start_field_code=start_field_code, + ) def _project_coordinate_profile_regions( @@ -960,12 +977,23 @@ def _reconstruct_dynamic_x_columns_profile_rows( delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center values: dict[str, str] = {} issues: list[str] = [] + deleted = any( + _DELETED_PATTERN.fullmatch(re.sub( + r'\s+', '', ''.join( + glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0) + ), + )) + for _row_index, band in record + ) for field in fields: code = str(field['field_code']) saved = _absolute_relative_region(table_bbox, field['region']) + # [STEP 3] 整体上移可把宽字段框推过页面顶端;截断页外部分, + # 保持 LayoutBBox 的非负原点和正面积契约。 + shifted_y0 = max(0.0, saved.y0 + delta_y) region = LayoutBBox( - x0=saved.x0, y0=saved.y0 + delta_y, - x1=saved.x1, y1=saved.y1 + delta_y, + x0=saved.x0, y0=shifted_y0, + x1=saved.x1, y1=max(shifted_y0 + 1e-6, saved.y1 + delta_y), ) selected_bands = [ band for _row_index, band in record @@ -990,7 +1018,7 @@ def _reconstruct_dynamic_x_columns_profile_rows( results.append(CoordinateProfileLogicalRow( fields=values, source_row_indices=[row_index for row_index, _band in record], - role='data', issues=issues, + role='deleted' if deleted else 'data', issues=issues, )) return results if include_deleted else [row for row in results if row.role != 'deleted'] @@ -1157,6 +1185,19 @@ def _reconstruct_relative_y_profile_rows( start_region = _absolute_relative_region(table_bbox, start_field['region']) expected_anchor_center = (start_region.y0 + start_region.y1) / 2 results: list[CoordinateProfileLogicalRow] = [] + sample_record = usable_bands[anchors[0]:anchors[1] if len(anchors) > 1 else len(usable_bands)] + expected_indices = _calibrate_field_band_indices( + fields=fields, sample_record=sample_record, table_bbox=table_bbox, + ) + multiline_fields = { + id(field) for field in fields + if sum( + _regions_overlap_vertically( + _absolute_relative_region(table_bbox, field['region']), _band_bbox(band), + ) + for _row_index, band in sample_record + ) > 1 + } for anchor_index, start in enumerate(anchors): end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands) record = usable_bands[start:end] @@ -1176,23 +1217,56 @@ def _reconstruct_relative_y_profile_rows( 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 - raw = _text_in_multiline_region( - intersecting, region, - compact=code in {'part_number', 'customer_part_number', 'aws_part_number'}, - ) + if id(field) not in multiline_fields: + intersecting = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + raw = _text_in_horizontal_region(intersecting[0], region) if intersecting else '' + if code == 'part_number': + expected_index = expected_indices.get(id(field), 0) + candidates: list[tuple[float, int, str]] = [] + for candidate_index in range(expected_index, len(record)): + candidate_raw = _text_in_horizontal_region(record[candidate_index][1], region) + if _is_structured_part_identifier(candidate_raw): + compact_candidate = re.sub(r'\s+', '', candidate_raw) + candidates.append(( + _profile_field_band_score( + raw=candidate_raw, field_code=code, + extractor_key=str(field.get('extractor_key') or 'direct'), + ), + candidate_index, candidate_raw, + )) + if re.search(r'\d', compact_candidate): + candidates[-1] = (candidates[-1][0] + .5, *candidates[-1][1:]) + candidates.sort(key=lambda item: (-item[0], item[1])) + if len(candidates) == 1: + raw = candidates[0][2] + elif len(candidates) > 1: + best = candidates[0] + if best[0] > candidates[1][0] + .25: + raw = best[2] + else: + issues.append(f'coordinate_profile_field_band_ambiguous:{code}') + raw = '' + else: + # 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 + 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( @@ -1890,6 +1964,112 @@ def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str) return score +def _is_structured_part_identifier(raw: str) -> bool: + """仅将带数字或连接符的料号作为纠偏证据,普通描述词保持原框位。""" + value = str(raw or '').strip() + compact = re.sub(r'\s+', '', value) + return bool( + not re.match(r'^(?:revision|rev)\s*:', value, re.IGNORECASE) + and + re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', compact) + and re.search(r'\d|[._:/-]', compact) + ) + + +def _resolve_shifted_part_number_candidates( + *, rows: list[CoordinateProfileLogicalRow], + glyphs: list[tuple[int, PositionedCharacter]], + ordered_layouts: list[dict[str, Any]], + table_bbox: LayoutBBox, + line_start_field_code: str, +) -> list[CoordinateProfileLogicalRow]: + """在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。 + + 固定/自适应/动态三种重建都可能先把描述折行绑定到内部料号框;这里复核当前 + 逻辑记录的后续候选,唯一高置信候选才替换,多个候选则保留 Review,避免改变 + 没有折行的其他模板。 + """ + part_fields = [ + field for layout in ordered_layouts + for field in (layout.get('field_regions') or []) + if isinstance(field, dict) and str(field.get('field_code') or '') == 'part_number' + and isinstance(field.get('region'), dict) + ] + if not part_fields: + return rows + part_start_offset = min( + offset for offset, layout in enumerate(ordered_layouts) + if any(field in (layout.get('field_regions') or []) for field in part_fields) + ) + # 主行内的料号没有“预期下一子行”这一语义。只纠正被标在后续子行的字段, + # 避免跨到价格、日期或表尾文本中寻找候选,保持已有单行模板的解析边界。 + if part_start_offset == 0: + return rows + bands = _group_visual_rows(glyphs) + main_fields = ordered_layouts[0].get('field_regions') or [] + start_field = next( + ( + field for field in main_fields + if isinstance(field, dict) + and str(field.get('field_code') or '') == line_start_field_code + and isinstance(field.get('region'), dict) + ), + None, + ) + start_region = ( + _absolute_relative_region(table_bbox, start_field['region']) + if start_field is not None else None + ) + + for row_position, row in enumerate(rows): + current = str(row.fields.get('part_number') or '').strip() + if not current or not row.source_row_indices: + continue + record_start = min(row.source_row_indices) + record_end = ( + min(min(next_row.source_row_indices) for next_row in rows[row_position + 1:]) + if row_position + 1 < len(rows) else len(bands) + ) + candidates: list[tuple[float, int, str]] = [] + # 从该记录中 part_number 的预期子行开始重扫;当前值本身若只是折行描述, + # 会被跳过,后续唯一结构化候选才可替换。不能按 source_row_indices 末端起步, + # 因为自适应重建可能已把后续候选 band 一并吸收到当前行。 + expected_index = record_start + part_start_offset + scan_start = expected_index + for index in range(scan_start, record_end): + # 末条记录也必须以视觉上的下一起行锚点截断;后续解析策略可能因 + # 表尾规则不产出该行,但不能让它泄漏进当前记录的料号候选池。 + if index > record_start and start_region is not None: + start_raw = _text_in_horizontal_region(bands[index], start_region) + if is_valid_line_start_value(start_raw): + break + for field in part_fields: + region = _absolute_relative_region(table_bbox, field['region']) + raw = _text_in_horizontal_region(bands[index], region) + if raw.strip() == current: + continue + if not _is_structured_part_identifier(raw): + continue + score = _profile_field_band_score( + raw=raw, field_code='part_number', + extractor_key=str(field.get('extractor_key') or 'direct'), + ) + score -= abs(index - expected_index) * .5 + if re.search(r'\d', re.sub(r'\s+', '', raw)): + score += .5 + candidates.append((score, index, raw)) + candidates.sort(key=lambda item: (-item[0], item[1])) + if len(candidates) == 1: + row.fields['part_number'] = candidates[0][2] + elif len(candidates) > 1: + if candidates[0][0] > candidates[1][0] + .25: + row.fields['part_number'] = candidates[0][2] + else: + row.fields.pop('part_number', None) + row.issues.append('coordinate_profile_field_band_ambiguous:part_number') + return rows + + def _text_in_region( band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, ) -> str: diff --git a/backend/app/services/shipping_notice/document_layout/field_split_core.py b/backend/app/services/shipping_notice/document_layout/field_split_core.py index 71d27929..6a06b316 100644 --- a/backend/app/services/shipping_notice/document_layout/field_split_core.py +++ b/backend/app/services/shipping_notice/document_layout/field_split_core.py @@ -380,6 +380,8 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any]) segment.pop('handling', None) segment.pop('target_field_id', None) segment.pop('target_field_code', None) + # segment_id 是段记录标识而非拆分逻辑(matcher/normalization/relation),不得进入内容指纹。 + segment.pop('segment_id', None) return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')) diff --git a/backend/app/services/shipping_notice/document_layout/html_table.py b/backend/app/services/shipping_notice/document_layout/html_table.py index cfd86fb3..8f54df54 100644 --- a/backend/app/services/shipping_notice/document_layout/html_table.py +++ b/backend/app/services/shipping_notice/document_layout/html_table.py @@ -464,10 +464,13 @@ def _map_data_row( if _is_repeated_header(grid, row_index=row_index, columns=columns, contract=contract): return HtmlMappedRow(row_index=row_index, role='repeated_header') joined = ' '.join(normalized) - if 'item deleted' in joined or 'deleted item' in joined or '项目已删除' in joined or '項目已刪除' in joined: + # 删除标记是业务内容关键词,不区分大小写;normalize_table_header 保留表头大小写。 + marker_joined = joined.lower() + if 'item deleted' in marker_joined or 'deleted item' in marker_joined or '项目已删除' in joined or '項目已刪除' in joined: return HtmlMappedRow(row_index=row_index, role='deleted') first = next((item for item in normalized if item), '') - if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first): + # 合计标记同样是业务内容关键词,按小写匹配 'Total'/'TOTAL'/'Subtotal' 等常见大小写。 + if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first.lower()): return HtmlMappedRow(row_index=row_index, role='summary') if _has_explicit_zero_quantity(row, columns=columns): return HtmlMappedRow(row_index=row_index, role='deleted') @@ -581,7 +584,8 @@ def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool: if not texts: return False markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'} - return all(text in markers for text in texts) + # 删除标记占整行的内容为业务关键词,按小写匹配,避免大小写差异漏判。 + return all(text.lower() in markers for text in texts) def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]: diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_extractors.py b/backend/app/services/shipping_notice/document_layout/order_profile_extractors.py index 784bdaf9..9d913ae2 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_extractors.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_extractors.py @@ -32,6 +32,10 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str if field_code == 'reservation_id': value = validated_reservation_id(text) return {field_code: value} if value else {} + if field_code == 'uom': + # 单位剔除数字(如 '0 PCS' → 'PCS'),避免相邻数量字段数字串入单位。 + stripped = re.sub(r'\d+', '', text).strip() + return {field_code: stripped} if stripped else {} return {field_code: text} if extractor_key == 'temp_internal_parts': resolved = resolve_composite_part_numbers(text) 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 11d12dc3..c9b81372 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 @@ -1383,6 +1383,28 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float: _HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+') +def _band_headers_match_signature( + *, band_tokens: list[str], signature: dict[str, Any] | None, +) -> bool: + """判断冻结表头带读到的 token 是否足以代表签名表头。 + + 只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”, + 直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行) + 需要回退到表体顶部的结构搜索。 + """ + expected = [ + str(token).casefold() + for pattern in (signature or {}).get('table_patterns') or [] + if isinstance(pattern, dict) + for token in pattern.get('header_tokens') or [] + ] + if not expected or not band_tokens: + return False + observed = [str(token).casefold() for token in band_tokens] + matched = sum(1 for token in expected if token in observed) + return matched / len(expected) >= 0.5 + + def _observe_primary_table_header( *, glyph_tables: dict[str, Any], @@ -1391,7 +1413,13 @@ def _observe_primary_table_header( primary_bbox: list[float] | None, signature: dict[str, Any] | None, ) -> tuple[list[str], list[float], list[float]]: - """仅从实际主表 bbox 顶部观测表头,与签名生成保持同一证据口径。""" + """从实际主表顶部观测表头,与签名生成保持同一证据口径。 + + 先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为, + 不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到 + 错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑), + 从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。 + """ if not primary_bbox or len(primary_bbox) != 4: return [], [], [] glyphs = page_glyphs.get('1') or page_glyphs.get(1) @@ -1419,11 +1447,28 @@ def _observe_primary_table_header( item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False) if _usable_observed_header_token(str(item.get('text') or '')) ][:32] - 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] + band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans] + band_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] - return tokens, centers, widths + band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans] + # 固定带有效 → 直接沿用(对正常模板零影响)。 + if _band_headers_match_signature(band_tokens=band_tokens, signature=signature): + return band_tokens, band_centers, band_widths + # 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。 + candidates = [{ + 'bbox': primary_bbox, + 'header_candidates': _observe_header_candidates( + glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox, + ), + }] + selected = _select_persisted_header_candidate(candidates=candidates, signature=signature) + if selected is not None: + header, _ = selected + return ( + [str(token).casefold() for token in header['header_tokens']], + header['column_centers'], header['column_width_ratios'], + ) + return band_tokens, band_centers, band_widths def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None: 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 6625a69d..26a26c88 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 @@ -14,6 +14,15 @@ from typing import Any from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile +from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + LayoutBBox, + _absolute_relative_region, + _group_visual_rows, + _inside_horizontal_region, + _table_glyphs, + _text_in_horizontal_region, + coordinate_profile_character_candidates, +) _NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$') @@ -84,12 +93,14 @@ def validate_profile_parse_candidate( fields=header_bound, glyphs=glyphs, page=page, ) - # [STEP 2] Line 字段覆盖 + # [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报) line_fields = [ field for table in profile.table_regions for layout in table.line_layouts for field in layout.field_regions if field.scope == 'line' ] - line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page) + line_coverage = _line_region_coverage_shift_tolerant( + profile=profile, glyphs=glyphs, page=page, layout=layout, + ) # [STEP 3] 明细行数启发式 line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page) @@ -207,6 +218,176 @@ def _field_validation_region(field: Any) -> dict[str, Any] | None: return None +def _line_region_coverage_shift_tolerant( + *, + profile: OrderCoordinateProfile, + glyphs: list[dict[str, Any]], + page: dict[str, Any], + layout: dict[str, Any], +) -> dict[str, Any]: + """按行重建同源的位移容忍字符窗口与视觉行横向重叠,统计 line 字段覆盖率。 + + 核心逻辑:legacy 模板把字段区冻结在标注样本的绝对页坐标,但实际物理表可能整体 + 纵向位移;若沿用冻结区域做严格中心包含读取,位移后的字段会读空,导致 + ``profile_parse_line_coverage_insufficient`` 误报。行重建 ``values_for`` 是把字段 + 区域按横向边界投影到所在视觉行(只做 x 重叠、y 来自真实行带),与是否位移无关。 + 此处对齐同一套语义:先按当前表区定位物理表,构造位移容忍的字符窗口,再按视觉行 + 做横向重叠覆盖;定位不到物理表时回退到冻结区域严格读取。 + + Args: + profile: 当前候选 Profile(含 table_regions)。 + glyphs: 当前页冻结坐标字符。 + page: 当前页尺寸。 + layout: 冻结 layout,含 coordinate_evidence 的 tables/page_glyphs。 + + Returns: + {coverage_ratio, empty_region_count, total_region_count}。 + """ + if not profile.table_regions: + return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0} + line_fields = [ + field for table in profile.table_regions for layout_item in table.line_layouts + for field in layout_item.field_regions if field.scope == 'line' + ] + if not line_fields: + return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0} + + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + # 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。 + primary_region = next( + (table for table in profile.table_regions if table.line_layouts), None, + ) + raw_table = _locate_overlapping_raw_table( + primary_region=primary_region, layout=layout, page=page, profile=profile, + ) + width, height = float(page['width']), float(page['height']) + table_region = primary_region.region.model_dump() if primary_region is not None else None + reference_page_frame = _reference_page_frame_mapping(profile, page) + reconstruction_page_bbox = { + 'x0': 0.0, 'y0': 0.0, + 'x1': float(reference_page_frame['width']) if reference_page_frame is not None else width, + 'y1': float(reference_page_frame['height']) if reference_page_frame is not None else height, + } + # 位移容忍字符窗口:表区横向始终有效,纵向扩展至定位到的物理表框。 + characters, _ = coordinate_profile_character_candidates( + table_region=table_region or {}, + page_size=page, reference_page_frame=reference_page_frame, + page_characters=glyphs if isinstance(glyphs, list) else None, + table_characters=( + page_glyph_tables.get(raw_table.get('table_id')) + if raw_table is not None and isinstance(page_glyph_tables.get(raw_table.get('table_id')), list) + else None + ), + raw_table_bbox=(raw_table.get('bbox') if raw_table is not None else None), + table_id=(raw_table.get('table_id') if raw_table is not None else None), + page_no=1, coordinate_transform=None, allow_table_fallback=True, + ) + if not isinstance(characters, list) or not characters: + return _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page) + + page_bbox = _LayoutBBox_from_dict(reconstruction_page_bbox) + glyphs_in_table = _table_glyphs(characters, page_bbox) + visual_rows = _group_visual_rows(glyphs_in_table) + non_empty = 0 + measurable = 0 + for field in line_fields: + relative = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region + if not isinstance(relative, dict): + continue + measurable += 1 + absolute = _absolute_relative_region(page_bbox, relative) + if _region_is_covered(visual_rows=visual_rows, region=absolute): + non_empty += 1 + total = measurable + return { + 'coverage_ratio': non_empty / total if total else 1.0, + 'empty_region_count': total - non_empty, + 'total_region_count': total, + } + + +def _reference_page_frame_mapping(profile: OrderCoordinateProfile, page: dict[str, Any]) -> dict[str, Any] | None: + """读取 Profile 冻结的首页参考页框;缺失时返回 None(由调用方回退到页面尺寸)。""" + reference = profile.reference_page_frames.get(1) + if reference is None: + return None + return reference.model_dump() if hasattr(reference, 'model_dump') else reference + + +def _LayoutBBox_from_dict(value: dict[str, Any]) -> Any: + """将页面框 dict 包装为 LayoutBBox,供重建辅助函数读取绝对坐标。""" + if isinstance(value, LayoutBBox): + return value + return LayoutBBox.model_validate(value) + + +def _locate_overlapping_raw_table( + *, + primary_region: Any, + layout: dict[str, Any], + page: dict[str, Any], + profile: OrderCoordinateProfile, +) -> dict[str, Any] | None: + """在 layout.tables 中找出与主表区纵向交叠且位于当前页、重叠面积最大的物理表。 + + 命中不到物理表(例如整页字符回退、虚拟页)时返回 None,由调用方维持冻结严格读取, + 避免把无物理表的场景误判为已定位到明细表。 + """ + if primary_region is None: + return None + reference_page_frame = _reference_page_frame_mapping(profile, page) + width, height = float(page['width']), float(page['height']) + projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else width + projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else height + if projection_width <= 0 or projection_height <= 0: + return None + relative = primary_region.region.model_dump() if hasattr(primary_region.region, 'model_dump') else primary_region.region + if not isinstance(relative, dict): + return None + try: + absolute_region = { + 'x0': float(relative['x0']) * projection_width, + 'y0': float(relative['y0']) * projection_height, + 'x1': float(relative['x1']) * projection_width, + 'y1': float(relative['y1']) * projection_height, + } + except (KeyError, TypeError, ValueError): + return None + best: dict[str, Any] | None = None + best_overlap = 0.0 + for raw_table in layout.get('tables') or []: + if not isinstance(raw_table, dict) or int(raw_table.get('page_no') or 1) != 1: + continue + bbox = raw_table.get('bbox') + if not isinstance(bbox, dict): + continue + overlap_x = ( + min(float(bbox.get('x1', 0)), absolute_region['x1']) + - max(float(bbox.get('x0', 0)), absolute_region['x0']) + ) + overlap_y = ( + min(float(bbox.get('y1', 0)), absolute_region['y1']) + - max(float(bbox.get('y0', 0)), absolute_region['y0']) + ) + if overlap_x <= 0 or overlap_y <= 0: + continue + overlap_area = overlap_x * overlap_y + if overlap_area > best_overlap: + best_overlap = overlap_area + best = raw_table + return best + + +def _region_is_covered(visual_rows: list[list[tuple[int, Any]]], region: Any) -> bool: + """判断任一视觉行在字段横向边界内是否出现非空文字,忽略冻结纵向位置。""" + for band in visual_rows: + selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)] + if _text_in_horizontal_region(selected, region).strip(): + return True + return False + + def _estimate_line_count( *, profile: OrderCoordinateProfile, diff --git a/backend/app/services/shipping_notice/duplicate_detection.py b/backend/app/services/shipping_notice/duplicate_detection.py index e8e12c3b..df6820d2 100644 --- a/backend/app/services/shipping_notice/duplicate_detection.py +++ b/backend/app/services/shipping_notice/duplicate_detection.py @@ -48,7 +48,7 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str upload = 'uploaded' except Exception: upload = None - if upload in {'uploaded', 'succeeded', 'success'}: + if upload == 'uploaded': return 'completed' return 'active' diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index 2c274ce8..2e11c9b1 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -4,6 +4,8 @@ services/shipping_notice/export.py 用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。 依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。 逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板; + 导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配; + Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败; 在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。 订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。 """ @@ -195,6 +197,34 @@ def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bo ) +def _unique_notice_warehouse_id(notice_lines: list[Any]) -> str | None: + """ + 从表头可写的 Notice 行推导唯一 Warehouse ID。 + + 核心逻辑:PVMI 等模板把 Warehouse ID 写在 Header;多行须同库位才可写入表头, + 多库位冲突时失败,避免把某一行的库位误写到整单表头。 + + Args: + notice_lines: 本 Notice 的 ``ShippingNoticeLine`` 列表。 + + Returns: + 唯一非空库位码;全部为空时返回 None。 + + Raises: + ValueError: 多行存在多个不同库位。 + """ + warehouses = { + str(getattr(line, 'inventory_warehouse_id', None) or '').strip().upper() + for line in (notice_lines or []) + if str(getattr(line, 'inventory_warehouse_id', None) or '').strip() + } + if len(warehouses) > 1: + raise ValueError('多库位发货通知不能把 Warehouse ID 映射为表头') + if len(warehouses) == 1: + return next(iter(warehouses)) + return None + + def _format_value(value: Any, formatter: str) -> Any: """应用发布契约允许的确定性格式化器。""" if value is None: @@ -286,6 +316,50 @@ def _match_text(value: Any) -> str: return str(value).strip().casefold() +def _narrow_inventory_lines_by_wanted_match_keys( + inventory_lines: list[dict[str, Any]], + *, + inventory_field_keys: list[str], + wanted_keys: set[tuple[str, ...]], +) -> list[dict[str, Any]]: + """ + 仅保留与本单导出行 match_keys 命中的库存行。 + + 核心逻辑:导出前按 reservation/part 等键裁剪候选,避免上万行全量快照进入 + 逐行模板匹配;键集合为空时返回空列表(由后续匹配/放行逻辑裁决)。 + + Args: + inventory_lines: 活动库存快照行。 + inventory_field_keys: 与 match_keys 对齐的库存字段键(通常为字段目录 ID)。 + wanted_keys: 本单导出行规范化后的键元组集合。 + + Returns: + 子集库存行;无候选时为空列表。 + """ + if not inventory_lines or not inventory_field_keys or not wanted_keys: + return [] + return [ + row for row in inventory_lines + if tuple(_match_text(row.get(field)) for field in inventory_field_keys) in wanted_keys + ] + + +def _wanted_order_match_keys( + order_lines: list[dict[str, Any]], + *, + order_field_ids: list[str], +) -> set[tuple[str, ...]]: + """从本单导出行收集完整 match_keys 元组(缺任一键的行跳过)。""" + wanted: set[tuple[str, ...]] = set() + if not order_lines or not order_field_ids: + return wanted + for order_line in order_lines: + key = tuple(_match_text(order_line.get(field_id)) for field_id in order_field_ids) + if all(key): + wanted.add(key) + return wanted + + def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]: """返回模板直接引用的库存字段 ID,用于多命中一致性验证。""" raw_ids = { @@ -625,8 +699,38 @@ def generate_shipment_excel( line_values.append(row) from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution - # [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。 + # [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part) + # 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。 inventory_lines = resolve_inventory_lines_for_execution(source_notice) + if (line_inventory_fields or header_inventory_fields) and match_keys and line_values: + from app.models import ShippingInventoryField + + match_field_ids = { + int(item.get('inventory_field_id')) + for item in match_keys + if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit() + } + catalog = { + str(item.id): str(item.id) + for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all() + } if match_field_ids else {} + order_field_ids: list[str] = [] + inventory_field_keys: list[str] = [] + for item in match_keys: + if not isinstance(item, dict): + continue + inv_key = catalog.get(str(item.get('inventory_field_id') or '').strip()) + if not inv_key: + continue + order_field_ids.append(str(item.get('order_field_id') or '')) + inventory_field_keys.append(inv_key) + if order_field_ids and inventory_field_keys: + wanted_keys = _wanted_order_match_keys(line_values, order_field_ids=order_field_ids) + inventory_lines = _narrow_inventory_lines_by_wanted_match_keys( + inventory_lines, + inventory_field_keys=inventory_field_keys, + wanted_keys=wanted_keys, + ) release_overrides_by_line = _release_overrides_for_export_lines( line_values=line_values, release_overrides_by_source_line=release_overrides_by_source_line, @@ -679,26 +783,36 @@ def generate_shipment_excel( } for sheet, start_row in data_start_rows.items(): _clear_template_data_rows(wb[sheet], start_row) + # [STEP] Notice 行一次加载:明细写各行库位;Header warehouse 仅在模板需要时解析。 + notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by( + ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(), + ).all() + header_warehouse_id: str | None = None + header_warehouse_resolved = False for mapping in mappings: ws = wb[mapping['sheet']] start_row = int(mapping['start_row']) column = int(mapping['target_column']) if mapping['row_mode'] == 'header': + # PVMI Header 允许 system_fact:warehouse_id;值取本 Notice 唯一库位。 + mapping_warehouse_id = None if _template_requires_system_warehouse_id([mapping]): - raise ValueError('Warehouse ID 仅可作为发货通知行字段导出,模板不得将其映射为表头') + if not header_warehouse_resolved: + header_warehouse_id = _unique_notice_warehouse_id(notice_lines) + header_warehouse_resolved = True + if not header_warehouse_id: + raise ValueError('缺少 Warehouse ID,无法写入发货 Excel 表头') + mapping_warehouse_id = header_warehouse_id ws.cell(start_row, column).value = _mapping_value( mapping, task=task, order_values=header_values, inventory_values=header_inventory, excel_business_no=excel_business_no, export_date=export_date, notice_line_no=None, - notice_line_warehouse_id=None, + notice_line_warehouse_id=mapping_warehouse_id, field_id_by_code=field_id_by_code, ) continue row_count = max(len(line_values), 1) - notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by( - ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(), - ).all() for index in range(row_count): order_line = line_values[index] if index < len(line_values) else {} inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {} diff --git a/backend/app/services/shipping_notice/field_impact_analysis.py b/backend/app/services/shipping_notice/field_impact_analysis.py index 32753e86..3e74806c 100644 --- a/backend/app/services/shipping_notice/field_impact_analysis.py +++ b/backend/app/services/shipping_notice/field_impact_analysis.py @@ -317,3 +317,60 @@ def analyze_unadopt_impact(*, previous_field_ids: set[str], next_field_ids: set[ 'warnings': warnings, 'can_publish': not blocked, } + + +def _definition_field_code_map(definition: dict[str, Any] | None) -> dict[str, str]: + """提取版本定义中 field_id → field_code 映射,用于字段语义键跨版本一致性校验。""" + if not isinstance(definition, dict): + return {} + result: dict[str, str] = {} + for item in (definition.get('fields') or []): + if not isinstance(item, dict): + continue + field_id = str(item.get('field_id') or '').strip() + field_code = str(item.get('field_code') or '').strip() + if field_id and field_code: + result[field_id] = field_code + return result + + +def analyze_published_field_code_changes( + previous_definition: dict[str, Any] | None, + next_definition: dict[str, Any] | None, +) -> dict[str, Any]: + """ + 已发布 field_code 不可变门禁:同一 field_id 不应在下一发布版本中更换 field_code。 + + 核心逻辑:只比较上一已发布版本与当前草稿「同一 field_id」的 field_code 是否变化; + 同一 field_code 漂移到新 field_id(废弃旧字段 + 新建)属于合法路径,不阻断。 + 仅在语义键被重命名时阻断,要求走「退役 + 新建」而非原地改名,保证 field_code 是 + 跨版本稳定引用锚点(供身份识别 resolver 等按语义键匹配)。 + + Args: + previous_definition: 上一已发布版本 definition;无则视为首次发布,不校验。 + next_definition: 即将发布的草稿 definition。 + + Returns: + 含 blocked、changed(field_id / previous_field_code / next_field_code)与 + changed_field_ids 的字典;changed 为空时 can_publish=True。 + """ + if previous_definition is None: + return {'blocked': False, 'changed': [], 'changed_field_ids': [], 'can_publish': True} + previous_map = _definition_field_code_map(previous_definition) + next_map = _definition_field_code_map(next_definition) + changed: list[dict[str, Any]] = [] + for field_id in sorted(set(previous_map) & set(next_map)): + previous_code = previous_map[field_id] + next_code = next_map[field_id] + if previous_code != next_code: + changed.append({ + 'field_id': field_id, + 'previous_field_code': previous_code, + 'next_field_code': next_code, + }) + return { + 'blocked': bool(changed), + 'changed': changed, + 'changed_field_ids': [item['field_id'] for item in changed], + 'can_publish': not changed, + } diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index f365281f..e116e82c 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -1,15 +1,16 @@ """ services/shipping_notice/fulfillment_workflow.py -用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与自动串联编排。 +用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与下游衔接入口。 依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、 inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、rpa.write_upload_trigger、 tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、 order_task_stage_machine。 -逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match; +逻辑:tools.py 门面 re-export;匹配成功后 Gate 路径禁止 try_auto_chain 内嵌 generate/upload, + 由 ProcessGate complete→enqueue 独立 artifact/freight Attempt;遗留非 Gate 路径仅 + submit auto_progress(artifact_generation); 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 成功须带受信回调中的白名单状态信息;不保存截图、DOM 文件或证据资产; @@ -29,7 +30,7 @@ from flask import current_app from app import db from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch, ShippingOrderTask -from app.services.shipping_notice.constants import CP_UPLOADED +from app.services.shipping_notice.constants import POSITION_UPLOADED from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values from app.services.shipping_notice.inventory_file_store import ( active_inventory_file_for_task, @@ -61,7 +62,6 @@ from app.services.shipping_notice.upload_attempt_service import ( complete_attempt, has_verified_upload_success, latest_export_artifact, - latest_upload_attempt, record_manual_upload, start_rpa_attempt, ) @@ -140,11 +140,9 @@ def _export_file_name(task: ShippingNotice) -> str | None: def _upload_status(task: ShippingNotice) -> str | None: - attempt = latest_upload_attempt(task) - if attempt is not None: - return str(attempt.status or '').strip().lower() or None - artifact = _current_export_artifact(task) - return str(artifact.status or '').strip().lower() if artifact is not None else None + """Notice 面 upload_status:经统一投影,成功只返回 uploaded。""" + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status + return project_notice_upload_status(task) def _cfg_bool(key: str, default: bool = False) -> bool: @@ -360,7 +358,7 @@ def _reservation_gate_response( **serialize_task_for_tool(task), "reservation_id_required": detail, }, - checkpoint="rsv_req", + position="rsv_req", stop_agent_turn=True, forbidden_next_tools=forbidden_next_tools, ) @@ -886,7 +884,7 @@ def excel_gate_error(task: ShippingNotice) -> str | None: ) if latest_preparation is not None and str(latest_preparation.status or '').strip().lower() == 'failed': return 'workflow.fulfillment.inventory_preparation_failed' - if _upload_status(task) in {"uploaded", "succeeded", "success"} and _export_file_path(task): + if _upload_status(task) == 'uploaded' and _export_file_path(task): return None # 滚动履约允许先导出当前完整满足/已审计放行的行;剩余短缺行继续保留在库存满足性 Gate。 if not match_completed(task) and not exportable_snapshot_line_ids(task): @@ -913,75 +911,51 @@ def try_auto_chain_after_match( payload: dict[str, Any] | None = None, ) -> dict[str, Any]: """ - 匹配成功后自动串联 Excel 导出;AUTO_UPLOAD 开启时继续触发货代上传 RPA。 + 匹配成功后的下游衔接入口(履约编排)。 - 核心逻辑:match_result 为 ok 后默认自动生成 Excel; - SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true 时调用 upload_to_freight(mode=auto); - 关闭时停在 wait_manual_upload 待人工登记。 + 核心逻辑: + - Gate Attempt 路径(``_orchestrator_internal_dispatch=True``):**直接返回**匹配结果, + 禁止同 Attempt 内嵌 ``generate_excel`` / ``upload_to_freight``;由 + ``complete_gate_attempt → _enqueue_auto_progress_after_gate_pass`` 入队独立 + ``artifact_generation`` / freight Attempt。 + - 非 Gate 遗留路径(deprecated):仅 ``run_task_auto_progress(resume_gate_code= + artifact_generation)`` 提交下一 Attempt,仍禁止直跑 generate。 Args: - task: 当前 ShippingNotice。 + task: 当前 ShippingNotice / OT。 match_result: match_inventory 的 Tool 响应。 - payload: 原始请求体,用于读取 auto_chain_fallback 与 lang 等字段。 + payload: 原始请求体;Gate 路径须含 ``_orchestrator_internal_dispatch``。 Returns: - dict[str, Any]: 串联后的 Tool 响应;未触发串联时原样返回 match_result。 + dict[str, Any]: 未触发下游时原样返回 match_result;遗留路径返回 auto_progress 响应。 """ if match_result.get("status") != "ok": return match_result + + # [STEP] Gate Attempt 内禁止跨门禁产物副作用(编排分离契约)。 + if isinstance(payload, dict) and payload.get('_orchestrator_internal_dispatch'): + return match_result + if not should_auto_chain_after_match(payload): return match_result - result = match_result - from app.services.shipping_notice.tool_common import merge_tool_payload - from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state + # [DEPRECATED] 非 Gate 聊天/Tool 兼容:只提交 artifact Attempt,不直跑 Excel。 + from app.services.shipping_notice.progress_workflow import run_task_auto_progress - tool_payload = merge_tool_payload(task, payload) - - # [STEP 1] 低风险:存在可导出行时自动生成下一份滚动 Excel。 - if _auto_generate_excel_enabled(): - db.session.refresh(task) - if _current_export_artifact(task) is None and excel_gate_error(task) is None: - gen = generate_excel(tool_payload) - if gen.get("status") != "ok": - return gen - result = prepend_tool_message(gen, str(result.get("message") or "")) - # Excel 生成可能刚刚把 OT 物化为正式 Notice;后续上传必须使用 Notice 编号。 - from app.services.shipping_notice.query_service import resolve_task_from_payload as _resolve_task - refreshed = _resolve_task({'task_no': task.task_no}) - if refreshed is not None: - task = refreshed - tool_payload = merge_tool_payload(task, payload) - - # [STEP 2] Excel 就绪后:开启 AUTO_UPLOAD 则触发货代 RPA,否则停待人工上传。 - db.session.refresh(task) - ui = resolve_task_ui_state(task) - excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or ( - _export_file_path(task) and _upload_status(task) != 'uploaded' + trigger = str((payload or {}).get('source') or (payload or {}).get('trigger') or 'legacy_auto_chain').strip() + actor_raw = (payload or {}).get('operator_id') or (payload or {}).get('actor_id') or (payload or {}).get('_trusted_user_id') + try: + operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != 'system' else None + except (TypeError, ValueError): + operator_id = None + return run_task_auto_progress( + str(task.task_no), + trigger=trigger, + expected_version=None, + idempotency_key=str((payload or {}).get('idempotency_key') or '').strip() or None, + resume_gate_code='artifact_generation', + operator_id=operator_id, ) - if excel_ready and _auto_upload_enabled(): - upload_result = upload_to_freight({ - **tool_payload, - 'task_id': task.task_no, - 'mode': 'auto', - }) - return prepend_tool_message(upload_result, str(result.get('message') or '')) - if excel_ready: - return tool_response( - status="ok", - task=task, - message=str( - result.get("message") - or "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。" - ), - data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, - stop_agent_turn=True, - forbidden_next_tools=["upload_to_freight"], - ) - - return result - def _order_extraction_gate_response( task: ShippingNotice, @@ -1078,7 +1052,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, ), 'primary_action': build_inventory_candidate_primary_action(), }, - checkpoint='inventory_source_review', + position='inventory_source_review', stop_agent_turn=True, ) # ownership & gates @@ -1123,11 +1097,38 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, task, legacy_payload_lines=parse_inventory_lines(payload), ) if not inventory_lines: - # 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义) + # 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义); + # 保留 Gate 内部调度标记,并尽量带上该行 source_codes,避免回退成整单 RPA。 inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_no': target_line_no} + if payload.get('_orchestrator_internal_dispatch'): + inv_payload['_orchestrator_internal_dispatch'] = True + scoped_codes = [ + str(code).strip().upper() + for code in (payload.get('source_codes') or []) + if str(code).strip() + ] + if not scoped_codes: + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + candidate_line = next( + ( + line for line in get_active_candidate_lines(task) + if int(getattr(line, 'line_no', 0) or 0) == target_line_no + ), + None, + ) + scoped_codes = [ + str(code).strip().upper() + for code in (getattr(candidate_line, 'source_codes_json', None) or []) + if str(code).strip() + ] if candidate_line is not None else [] + if scoped_codes: + inv_payload['source_codes'] = scoped_codes lang_suffix = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() if lang_suffix: inv_payload["lang"] = lang_suffix + for key in ('operator_id', 'actor_user_id', 'mode'): + if payload.get(key) is not None: + inv_payload[key] = payload.get(key) return ensure_inventory(inv_payload) if not is_inventory_source_stable(task): return tool_response( @@ -1135,7 +1136,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, task=task, message="库存源尚未确定,无法执行行级库存匹配。", data=serialize_task_for_tool(task), - checkpoint="inventory_source_review", + position="inventory_source_review", stop_agent_turn=True, ) from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes @@ -1294,7 +1295,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, task_id=task.task_no, message=match_summary, data=serialize_task_for_tool(task), - checkpoint=f'line_no:{target_line_no}:rematch:ok', + position=f'line_no:{target_line_no}:rematch:ok', ) return try_auto_chain_after_match(task, match_result, payload=payload) apply_task_transition(task, TaskTransition.MATCH_SHORTAGE) @@ -1324,7 +1325,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, task=task, message=match_summary, data=serialize_task_for_tool(task), - checkpoint=f'shortage_review:line_no:{target_line_no}', + position=f'shortage_review:line_no:{target_line_no}', stop_agent_turn=True, forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], ) @@ -1655,7 +1656,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task=task, message="库存源尚未确定,无法执行库存匹配。", data=serialize_task_for_tool(task), - checkpoint="inventory_source_review", + position="inventory_source_review", stop_agent_turn=True, ) @@ -1799,7 +1800,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task=task, message=match_summary, data=serialize_task_for_tool(task), - checkpoint="shortage_review", + position="shortage_review", stop_agent_turn=True, forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], ) @@ -2323,7 +2324,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: task_id=task.task_no, message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no), data=serialize_task_for_tool(task), - checkpoint=CP_UPLOADED if has_verified_upload_success(task) else None, + position=POSITION_UPLOADED if has_verified_upload_success(task) else None, ) @@ -2374,7 +2375,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: 可选 freight_ref_no、error_message。 Returns: - dict[str, Any]: 成功时 checkpoint=uploaded;失败时 needs_human 并附带 error_message。 + dict[str, Any]: 成功时 position=uploaded;失败时 needs_human 并附带 error_message。 """ lang = resolve_lang(payload) try: @@ -2499,7 +2500,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: task_id=task.task_no, message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang), data=serialize_task_for_tool(task), - checkpoint=CP_UPLOADED if has_verified_upload_success(task) else None, + position=POSITION_UPLOADED if has_verified_upload_success(task) else None, ) if completed.status == 'unknown': @@ -2556,7 +2557,7 @@ def run_auto_progress_fulfillment_steps( 核心逻辑:自动匹配与生成 Excel;AUTO_UPLOAD 开启时触发 upload_to_freight(mode=auto); 关闭时停在 wait_manual_upload 待人工登记。 """ - from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state + from app.services.shipping_notice.state_machine import resolve_task_ui_state # [STEP 1] 若允许自动匹配且当前尚未完成匹配,则先进入 match_inventory。 if _auto_match_enabled() and not match_completed(task): @@ -2573,10 +2574,8 @@ def run_auto_progress_fulfillment_steps( steps.append("生成发货 Excel") # [STEP 3] Excel 就绪后按开关触发货代 RPA,或停待人工上传。 - ui = resolve_task_ui_state(task) - excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or ( - _export_file_path(task) and _upload_status(task) != 'uploaded' - ) + # excel_ready 只读领域产物事实,禁止 UserMode/resolve_task_ui_state 裁决。 + excel_ready = bool(_export_file_path(task)) and _upload_status(task) != 'uploaded' if excel_ready and _auto_upload_enabled(): steps.append("触发货代上传 RPA") return upload_to_freight({ @@ -2591,7 +2590,7 @@ def run_auto_progress_fulfillment_steps( task=task, message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, + position=resolve_task_ui_state(task).position, stop_agent_turn=True, forbidden_next_tools=["upload_to_freight"], ) diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py index aa96cf8a..bffe2e20 100644 --- a/backend/app/services/shipping_notice/i18n.py +++ b/backend/app/services/shipping_notice/i18n.py @@ -113,6 +113,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.fulfillment.reservation_required": "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。订单缺少 Reservation ID:{count} 行。请重新解析发货通知后再匹配。", "workflow.gate.field_conflict_blocked": "存在 {count} 条未解决的订单字段冲突,请先复核并解决后再继续库存/匹配/导出。", "workflow.fulfillment.excel_gate_unmatched": "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。", + "workflow.fulfillment.inventory_preparation_failed": "库存准备失败。请人工重试或上传库存文件后再继续。", "workflow.fulfillment.excel_exists": "发货 Excel 已生成:{file}", "workflow.fulfillment.match_first": "match_inventory(须先完成库存上传与字段对齐确认)", "workflow.fulfillment.generate_running": "正在生成发货 Excel", @@ -238,6 +239,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.fulfillment.reservation_required": "The current matching rule requires Reservation ID on the order side. {count} order lines are missing Reservation ID. Please re-parse the shipping notice before matching again.", "workflow.gate.field_conflict_blocked": "There are {count} unresolved order field conflicts. Resolve them before inventory, matching, or export.", "workflow.fulfillment.excel_gate_unmatched": "Inventory matching is not complete yet. Please upload inventory, confirm field alignment, and call match_inventory first.", + "workflow.fulfillment.inventory_preparation_failed": "Inventory preparation failed. Retry manually or upload an inventory file before continuing.", "workflow.fulfillment.excel_exists": "Shipment Excel already exists: {file}", "workflow.fulfillment.match_first": "match_inventory (inventory upload and field alignment confirmation are required first)", "workflow.fulfillment.generate_running": "Generating shipment Excel.", @@ -363,6 +365,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.fulfillment.reservation_required": "กฎการจับคู่ปัจจุบันกำหนดให้ฝั่งคำสั่งซื้อมี Reservation ID ขณะนี้มี {count} รายการที่ขาด Reservation ID โปรดแยกใบแจ้งส่งสินค้าใหม่ก่อนแล้วค่อยจับคู่", "workflow.gate.field_conflict_blocked": "มีข้อขัดแย้งของฟิลด์คำสั่งซื้อที่ยังไม่แก้ {count} รายการ กรุณาตรวจสอบก่อนดำเนินการสต็อก/จับคู่/ส่งออก", "workflow.fulfillment.excel_gate_unmatched": "ยังจับคู่สต็อกไม่เสร็จ โปรดอัปโหลดสต็อก ยืนยันการจับคู่คอลัมน์ แล้วเรียก match_inventory ก่อน", + "workflow.fulfillment.inventory_preparation_failed": "การเตรียมสต็อกล้มเหลว โปรดลองด้วยตนเองหรืออัปโหลดไฟล์สต็อกก่อนดำเนินการต่อ", "workflow.fulfillment.excel_exists": "สร้างไฟล์ Shipment Excel แล้ว: {file}", "workflow.fulfillment.match_first": "match_inventory (ต้องอัปโหลดสต็อกและยืนยันการจับคู่คอลัมน์ก่อน)", "workflow.fulfillment.generate_running": "กำลังสร้าง Shipment Excel", diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index a31e0541..d404cdec 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -3,7 +3,9 @@ services/shipping_notice/inventory_file_store.py 用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。 依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。 -逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。 +逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT); + fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution: + 冻结候选 OT 读 prepare 合并行,单源读 active Link 文件;禁止用 Notice.id 漏读 OT Link。 """ from __future__ import annotations @@ -141,8 +143,20 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None: def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None: - """读取任务当前 active link 指向的库存快照。""" - task_id = getattr(task, 'id', None) + """ + 读取任务当前 active link 指向的库存快照。 + + 核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入 + ``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。 + + Args: + task: OT 或已绑定 ``order_task_id`` 的正式 Notice。 + + Returns: + 当前有效库存文件;无 active Link 时返回 None。 + """ + # [STEP] Link 归属 OT:Notice.id 与 OT.id 不同,禁止误用 Notice 主键查 Link。 + task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) if task_id is None: return None link = ( @@ -214,15 +228,35 @@ def resolve_inventory_lines_for_execution( legacy_payload_lines: list[dict[str, Any]] | None = None, ) -> list[dict[str, Any]]: """ - 解析库存匹配与导出的统一运行输入,活动库存 Link 为唯一事实源。 + 解析库存匹配与导出的统一运行输入。 + + 核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源 + ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File; + 否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。 Args: - task: 当前正式发货通知。 + task: 当前正式发货通知 / OT。 legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。 Returns: 本次执行使用的库存行;不会回写任务或通知单的库存行缓存。 """ + # [STEP 1] STP 冻结候选:匹配输入来自各源快照合并,不读被污染的单文件缓存。 + from app.services.shipping_notice.stp_inventory_freeze import ( + task_frozen_inventory_source_codes, + ) + from app.services.shipping_notice.stp_line_inventory_match import ( + prepare_candidate_inventory_lines, + ) + + if len(task_frozen_inventory_source_codes(task)) >= 1: + prep = prepare_candidate_inventory_lines(task) + if prep.get('status') == 'ready': + rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)] + if rows: + return rows + + # [STEP 2] 单源 / 无冻结:活动 Link 文件是行事实。 if active_inventory_file_for_task(task) is not None: return active_inventory_lines_for_task(task) if isinstance(legacy_payload_lines, list): diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/inventory_mapping_workflow.py index 9ecb4491..9d7640d6 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py +++ b/backend/app/services/shipping_notice/inventory_mapping_workflow.py @@ -3,7 +3,8 @@ services/shipping_notice/inventory_mapping_workflow.py 用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。 依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。 -逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析。 +逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析; + 快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。 """ from __future__ import annotations @@ -13,6 +14,7 @@ from typing import Any from app import db from app.models import ShippingNotice from app.services.shipping_notice.inventory_file_store import ( + _can_relink_inventory, active_inventory_file_for_task, apply_inventory_parse_result_to_linked_tasks, start_inventory_file_linked_tasks, @@ -36,9 +38,14 @@ def inventory_loaded_response( field_mapping: dict[str, str] | None = None, mapping_source: str | None = None, commit: bool = True, + persist_lines: bool = True, ) -> dict[str, Any]: """ - 写入已经确定性解析的正式库存,并将关联任务推进到待匹配状态。 + 将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。 + + 核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库) + 写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态, + 禁止覆盖共享 File 上已有行缓存。 Args: task: 当前正式发货任务。 @@ -50,13 +57,18 @@ def inventory_loaded_response( field_mapping: published Profile 的字段映射快照。 mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。 commit: False 时仅 flush,供批量回调维持外层事务边界。 + persist_lines: False 时不写 File.inventory_lines_json(复用路径)。 Returns: Tool 标准响应;成功后任务可直接进入库存匹配。 """ inv_file = active_inventory_file_for_task(task) + if inv_file is None: + raise ValueError('OT 库存解析结果必须先绑定到有效库存文件') + + # [STEP] 首次落库写 File;复用只推进状态,避免共享快照被 OT 私有/合并行覆盖。 linked_tasks: list[ShippingNotice] = [] - if inv_file: + if persist_lines: linked_tasks = apply_inventory_parse_result_to_linked_tasks( inv_file, inventory_lines, @@ -65,7 +77,11 @@ def inventory_loaded_response( mapping_confirmed=True, ) else: - raise ValueError('OT 库存解析结果必须先绑定到有效库存文件') + linked_tasks = [ + link.task + for link in (inv_file.links or []) + if link.is_active and link.task and _can_relink_inventory(link.task) + ] # [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态, # 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新 @@ -124,6 +140,7 @@ def inventory_loaded_response( "column_meta": column_meta, "inventory_file_no": inv_file.inventory_file_no if inv_file else None, "linked_task_nos": [item.task_no for item in linked_tasks], + "persist_lines": bool(persist_lines), }, ) if commit: @@ -141,5 +158,6 @@ def inventory_loaded_response( "inventory_row_count": len(inventory_lines), "field_alignment": field_alignment, "warnings": warnings or [], + "persist_lines": bool(persist_lines), }, ) diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 57890dec..15acc0fc 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -21,7 +21,7 @@ from typing import Any from app import db from app.core.errors import AppError, ServiceUnavailableError from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask, ShippingTaskEvent -from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING +from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file from app.services.shipping_notice.inventory_snapshot_store import ( find_latest_ready_snapshot, @@ -190,12 +190,14 @@ def _try_reuse_inventory_snapshot( except (OSError, ValueError, AppError): lines, column_meta = [], {} if lines: + # 复用:行缓存已由 read_inventory_file_lines 保证;只 Link + 推进,不覆盖 File。 return inventory_loaded_response( task, lines, column_meta=column_meta, source="snapshot_reuse", event_type="inventory_snapshot_reused", + persist_lines=False, ) db.session.commit() @@ -338,7 +340,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor task=task, message=_workflow_error(task), data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, + position=POSITION_UPLOAD_REQ, ) @@ -835,7 +837,7 @@ def _validate_rpa_callback_gate(task: ShippingNotice) -> dict[str, Any] | None: "order_missing_preview": reservation_issues[:5], }, }, - checkpoint="rsv_req", + position="rsv_req", stop_agent_turn=True, ) @@ -1114,12 +1116,19 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[ return None -def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retry: bool = True) -> dict[str, Any]: +def ensure_inventory_via_rpa( + task: ShippingNotice, + *, + mode: str, + allow_auto_retry: bool = True, + source_codes: list[str] | None = None, +) -> dict[str, Any]: """触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。 Args: allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。 poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。 + source_codes: 可选行级库存源;有值时只为这些源准备/触发 RPA,不跑整单冻结源。 """ from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response manual_retry_round = mode == "retry_rpa" @@ -1158,7 +1167,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr "order_missing_preview": reservation_issues[:5], }, }, - checkpoint="rsv_req", + position="rsv_req", stop_agent_turn=True, ) @@ -1176,7 +1185,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr task=task, message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", data=serialize_task_for_tool(task), - checkpoint=CP_INVENTORY_SOURCE_REVIEW, + position=POSITION_INVENTORY_SOURCE_REVIEW, stop_agent_turn=True, ) @@ -1189,7 +1198,12 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr if mode in {'auto', 'retry_rpa'}: from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared - prepared = ensure_all_required_sources_prepared(task, mode=mode, allow_auto_retry=allow_auto_retry) + prepared = ensure_all_required_sources_prepared( + task, + mode=mode, + allow_auto_retry=allow_auto_retry, + source_codes=source_codes, + ) db.session.flush() if prepared.pending_source_codes: apply_task_transition(task, TaskTransition.RPA_PENDING) @@ -1299,7 +1313,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr task=task, message=_workflow_error(task), data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, + position=POSITION_UPLOAD_REQ, ) # [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。 @@ -1403,7 +1417,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retr task=task, message=f"{human_message}。请上传货代库存 Excel。" if human_message != RPA_WORKER_OFFLINE_MESSAGE else human_message, data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, + position=POSITION_UPLOAD_REQ, ) @@ -1563,7 +1577,7 @@ def _handle_rpa_inventory_skipped( task=task, message=message, data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, + position=POSITION_UPLOAD_REQ, ) diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py index 014f53c4..d84d0305 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -4,6 +4,7 @@ services/shipping_notice/inventory_source_gate.py 用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。 依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。 逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备); + apply 仅冻结 resolved/ambiguous/candidates_frozen;unresolved 不得写入全源 CandidateSet; 解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。 """ @@ -101,10 +102,16 @@ def apply_inventory_source_adjudication( """ 将裁决结果冻结为 CandidateSet;无候选时由 Gate 保存阻断事实。 + 核心逻辑:仅 resolved / ambiguous / candidates_frozen 且候选非空时冻结; + unresolved/conflicted/invalid 即使误带候选也不得冻结(防全源兜底污染)。 + Args: execution_id: 可选;传给 ``freeze_candidates_for_task``,使重冻结不撤销当前 正在执行的门禁链(否则会误 supersede 活动 Execution)。 """ + status = str(adjudication.status or '').strip().lower() + if status not in {'resolved', 'ambiguous', 'candidates_frozen'}: + return if any(str(item.get('source_code') or '').strip() for item in (adjudication.candidates or []) if isinstance(item, dict)): freeze_candidates_for_task( task, adjudication=adjudication, execution_id=execution_id, @@ -191,8 +198,8 @@ def transition_task_to_inventory_source_review( """ 将任务持久化到库存源规则重算检查点,并写入候选裁决信息。 - 核心逻辑:保留 checkpoint 作为内部恢复事实,但不产生人工选源按钮; - 解析复核必须在进入本检查点前完成,不保存延后复核标记。 + 核心逻辑:写入 INVENTORY_SOURCE_REVIEW 过渡与 stage,但不产生人工选源按钮; + 解析复核必须在进入本阶段前完成,不保存延后复核标记。 """ from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition diff --git a/backend/app/services/shipping_notice/inventory_source_rules.py b/backend/app/services/shipping_notice/inventory_source_rules.py index 218c613c..44e34072 100644 --- a/backend/app/services/shipping_notice/inventory_source_rules.py +++ b/backend/app/services/shipping_notice/inventory_source_rules.py @@ -4,7 +4,8 @@ services/shipping_notice/inventory_source_rules.py 用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。 依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。 逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行; - 本模块仍负责任务级裁决与快照消歧(履约阶段);Warehouse 由 Source/匹配决定。 + 行级一致的 ambiguous/resolved/conflicted 可上收为任务裁决;unresolved 禁止兜底全部启用源; + Warehouse 由 Source/匹配决定。 """ from __future__ import annotations @@ -111,7 +112,12 @@ def _from_source(*, status: str, source: dict[str, Any], method: str, context: d def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySourceAdjudication: - """将规则引擎候选集转换为可执行或待人工确认的裁决。""" + """ + 将规则引擎候选集转换为可执行或待人工确认的裁决。 + + 核心逻辑:只保留规则给出且当前仍可用的 Source;unresolved/空候选时 candidates + 必须为空,禁止回退到全部启用库存源(否则会错误触发全源 RPA)。 + """ sources = [item for code in result.source_codes if (item := get_database_inventory_source(code))] evidence = [{'rule_ids': list(result.matched_rule_ids), **result.evidence}] if result.status == 'resolved' and len(sources) == 1: @@ -120,7 +126,7 @@ def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySo status=result.status, config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context), - candidates=[_candidate(item) for item in (sources or list_database_inventory_sources())], + candidates=[_candidate(item) for item in sources], evidence=evidence, reason='routing_rule_' + result.status, ) @@ -235,19 +241,41 @@ def resolve_ambiguous_source_from_ready_snapshots( def adjudicate_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication: - """先评估任务级规则,再在所有订单行一致时接受行级规则结果。""" + """ + 先评估任务级规则,再在订单行一致时接受行级规则结果。 + + 核心逻辑:任务级有结论直接用;否则要求各行非 unresolved 且 + (status, source_codes) 一致(含 ambiguous 多候选)才采纳行级结果。 + 仅「各行 resolved 到不同单源」时合并为 ambiguous;不得把 unresolved 扩成全源。 + """ context = extract_routing_context(task) task_result = evaluate_inventory_source_rules(task=task) if task_result.status != 'unresolved': return _result_to_adjudication(task_result, context) line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in _task_routing_lines(task)] - resolved_codes = {item.source_codes[0] for item in line_results if item.status == 'resolved' and len(item.source_codes) == 1} - if len(resolved_codes) == 1 and all(item.status == 'resolved' for item in line_results): - return _result_to_adjudication(next(item for item in line_results if item.status == 'resolved'), context) - if len(resolved_codes) > 1: + # [STEP] 各行一致的非 unresolved(含 ambiguous)直接采纳,修复 PREFIX 多候选被丢弃。 + if line_results and all(item.status != 'unresolved' for item in line_results): + first = line_results[0] + if all( + item.status == first.status and item.source_codes == first.source_codes + for item in line_results + ): + return _result_to_adjudication(first, context) + resolved_codes = { + item.source_codes[0] + for item in line_results + if item.status == 'resolved' and len(item.source_codes) == 1 + } + if len(resolved_codes) > 1 and all(item.status == 'resolved' for item in line_results): return InventorySourceAdjudication( - 'ambiguous', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context), - candidates=[_candidate(item) for item in list_database_inventory_sources() if item['source_code'] in resolved_codes], + 'ambiguous', + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[ + _candidate(item) + for item in list_database_inventory_sources() + if item['source_code'] in resolved_codes + ], reason='line_rules_resolve_different_sources', ) return _result_to_adjudication(task_result, context) diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index 1c4f12e9..30608a44 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -2,8 +2,11 @@ services/shipping_notice/inventory_workflow.py 用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。 -依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、动态订单字段。 -逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除。 +依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、 + inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。 +逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除; + payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓); + STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File。 """ from __future__ import annotations @@ -15,7 +18,7 @@ from app import db from app.core.errors import AppError from app.models import ShippingOrderTask from app.services.shipping_notice.constants import ( - CP_INVENTORY_SOURCE_REVIEW, + POSITION_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_task_inventory_upload @@ -52,6 +55,107 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non return None +def _link_ready_candidate_prep_or_block( + task: ShippingOrderTask, + prep: dict[str, Any], + *, + lang: str, +) -> dict[str, Any] | None: + """ + STP 候选库存 ready 后,确保 OT 已绑定有效库存文件再允许写回解析结果。 + + 核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded + 快照并 ``link_snapshot_to_task``(与单源 reuse 对齐)。绑定失败返回 needs_human, + 禁止抛出「未绑定库存文件」ValueError 把 Gate Job 打成 technical_failure。 + + Args: + task: 已冻结候选源的订单任务。 + prep: ``prepare_candidate_inventory_lines`` 的 ready 结果。 + lang: 文案语言。 + + Returns: + None 表示可继续 ``inventory_loaded_response(persist_lines=False)``;dict 为 tool_response 阻断结果。 + """ + from app.models import ShippingInventoryFile + from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + + # [STEP 1] 已绑定则无需重复 link。 + if active_inventory_file_for_task(task) is not None: + return None + + # [STEP 2] 从候选准备证据解析待绑定快照编号。 + file_no = '' + for item in list(prep.get('evidence') or []): + if not isinstance(item, dict): + continue + if str(item.get('status') or '').strip().lower() != 'loaded': + continue + file_no = str(item.get('inventory_file_no') or '').strip() + if file_no: + break + if not file_no: + for row in list(prep.get('lines') or []): + if not isinstance(row, dict): + continue + file_no = str(row.get('__inventory_file_no') or '').strip() + if file_no: + break + + inv_file = ( + ShippingInventoryFile.query.filter_by(inventory_file_no=file_no).first() + if file_no + else None + ) + link = None + if inv_file is not None: + link = link_snapshot_to_task( + task, + inv_file, + reason='stp_candidate_prep', + role='owner', + audit_payload={ + 'candidate_set_id': prep.get('candidate_set_id'), + 'loaded_source_codes': list(prep.get('loaded_source_codes') or []), + }, + ) + if link is not None: + db.session.flush() + return None + + # [STEP 3] 无法绑定:软阻断,留给人工重试/上传,勿让 Gate Job 因 ValueError 失败。 + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + set_task_step_progress( + task, + step_key='step3_inventory_prepare', + step_title='获取库存', + status='needs_human', + message=t('workflow.inventory.unavailable', lang=lang), + progress_percent=0, + detail=t('workflow.inventory.unavailable', lang=lang), + ) + log_task_event( + task, + 'inventory_candidate_link_failed', + { + 'inventory_file_no': file_no or None, + 'loaded_source_codes': list(prep.get('loaded_source_codes') or []), + 'candidate_set_id': prep.get('candidate_set_id'), + }, + ) + db.session.commit() + return tool_response( + status='needs_human', + task=task, + message=t('workflow.inventory.unavailable', lang=lang), + data={ + **serialize_task_for_tool(task), + 'blocking_reason': {'code': 'inventory_file_missing'}, + 'inventory_file_no': file_no or None, + }, + ) + + def _reservation_gate_response(task: ShippingOrderTask, *, lang: str) -> dict[str, Any] | None: """ 库存入口统一检查订单侧 Reservation ID。 @@ -74,7 +178,7 @@ def _reservation_gate_response(task: ShippingOrderTask, *, lang: str) -> dict[st "order_missing_preview": reservation_issues[:5], }, }, - checkpoint="rsv_req", + position="rsv_req", stop_agent_turn=True, forbidden_next_tools=[ "ensure_inventory", @@ -102,7 +206,7 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, task=task, message='订单解析已确认后必须先冻结订单快照,才能进入库存链路。', data={**serialize_task_for_tool(task), 'error_code': 'SHIPPING.ORDER_SNAPSHOT_REQUIRED'}, - checkpoint='order_freeze', + position='order_freeze', stop_agent_turn=True, forbidden_next_tools=['ensure_inventory', 'parse_inventory', 'match_inventory', 'generate_shipment_excel'], ) @@ -143,9 +247,9 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, data={ **serialize_task_for_tool(task), "error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED", - "checkpoint": CP_INVENTORY_SOURCE_REVIEW, + "position": POSITION_INVENTORY_SOURCE_REVIEW, }, - checkpoint=CP_INVENTORY_SOURCE_REVIEW, + position=POSITION_INVENTORY_SOURCE_REVIEW, stop_agent_turn=True, forbidden_next_tools=["ensure_inventory", "match_inventory", "generate_shipment_excel"], ) @@ -160,7 +264,7 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, task=task, message="库存源尚未确定,请先完成订单解析阶段的库存源确认。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, + position=ui.position or POSITION_INVENTORY_SOURCE_REVIEW, stop_agent_turn=True, ) return None @@ -291,6 +395,14 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: resume_gate_code='inventory_preparation', operator_id=operator_id, inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto', + line_scope_key=( + str( + payload.get('line_scope_key') + if payload.get('line_scope_key') is not None + else payload.get('snapshot_line_id') + or '' + ).strip() or None + ), ) lang = resolve_lang(payload) task = resolve_task_from_payload(payload) @@ -308,6 +420,11 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # 只读轮询开关:poll_inventory_preparation 查询路径传 False——轮询只消费 RPA Attempt 事实, # 禁止在查询中自动新建 Attempt;重试必须由用户显式动作(mode='retry_rpa')发起。 allow_auto_retry = bool(payload.get('allow_auto_retry', True)) + scoped_source_codes = [ + str(code).strip().upper() + for code in (payload.get('source_codes') or []) + if str(code).strip() + ] or None inventory_lines = parse_inventory_lines(payload) if inventory_lines: return inventory_loaded_response( @@ -321,7 +438,9 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: if mode == "retry_rpa": from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa - return ensure_inventory_via_rpa(task, mode=mode) + return ensure_inventory_via_rpa( + task, mode=mode, source_codes=scoped_source_codes, + ) if mode == "auto": from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot @@ -367,7 +486,12 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: from app.services.shipping_notice.per_source_rpa_service import ( ensure_all_required_sources_prepared, ) - probe = ensure_all_required_sources_prepared(task, mode=mode, allow_auto_retry=allow_auto_retry) + probe = ensure_all_required_sources_prepared( + task, + mode=mode, + allow_auto_retry=allow_auto_retry, + source_codes=scoped_source_codes, + ) if probe.pending_source_codes: apply_task_transition(task, TaskTransition.RPA_PENDING) task.error_message = None @@ -447,14 +571,17 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: 'missing_source_codes': prep.get('missing_source_codes') or [], }, ) - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response - + # [STEP] ready 快照复用:先 Link,再只推进状态;不把合并行写进共享 File。 + link_block = _link_ready_candidate_prep_or_block(task, prep, lang=lang) + if link_block is not None: + return link_block return inventory_loaded_response( task, list(prep.get('lines') or []), column_meta={'source': 'stp_candidate_prep'}, source='stp_candidate_prep', event_type='inventory_candidates_prepared', + persist_lines=False, ) reused = _try_reuse_inventory_snapshot( @@ -469,7 +596,12 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # 否则任务会错误停在人审且没有可执行的恢复动作。 from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa - return ensure_inventory_via_rpa(task, mode=mode, allow_auto_retry=allow_auto_retry) + return ensure_inventory_via_rpa( + task, + mode=mode, + allow_auto_retry=allow_auto_retry, + source_codes=scoped_source_codes, + ) # [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。 # 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。 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 973b9d34..be7ff00b 100644 --- a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py +++ b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py @@ -24,7 +24,7 @@ from app.services.shipping_notice.line_inventory_match_persistence import resolv from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( create_post_ot_fulfillment_wave, - list_eligible_post_ot_line_keys, + list_eligible_post_ot_snapshot_line_ids, ) from app.services.shipping_notice.order_review_fulfillment_decision_service import ( project_review_case_line_decisions, @@ -35,7 +35,7 @@ from app.services.shipping_notice.post_ot_wave_progress_service import schedule_ def _mark_auto_fulfill_failed( case: ShippingOrderReviewCase, *, - line_keys: list[str], + snapshot_line_ids: list[str], error_code: str, message: str, ) -> None: @@ -46,12 +46,18 @@ def _mark_auto_fulfill_failed( """ now = datetime.utcnow() formal_task_id = getattr(case, 'confirmed_task_id', None) - for key in line_keys: + projection = project_review_case_line_decisions(case) + draft_id_by_snapshot_id = { + str(item.get('snapshot_line_id')): str(item.get('draft_line_id') or '').strip() + for item in list(projection.get('lines') or []) + if isinstance(item, dict) and item.get('snapshot_line_id') is not None + } + for key in snapshot_line_ids: key_s = str(key) if formal_task_id is not None: fact = ( ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(formal_task_id), line_key=key_s, is_current=True) + .filter_by(task_id=int(formal_task_id), snapshot_line_id=int(key_s), is_current=True) .first() ) if fact is not None: @@ -67,9 +73,12 @@ def _mark_auto_fulfill_failed( fact.detail_json = detail fact.updated_at = now + draft_line_id = draft_id_by_snapshot_id.get(key_s) + if not draft_line_id: + continue row = ( ShippingOrderReviewLineDecision.query - .filter_by(review_case_id=int(case.id), line_key=key_s, is_active=True) + .filter_by(review_case_id=int(case.id), draft_line_id=draft_line_id, is_active=True) .first() ) if row is None: @@ -116,10 +125,10 @@ def coordinate_post_ot_auto_fulfill( 'case_no': case.case_no, } - eligible = list_eligible_post_ot_line_keys(case) + eligible = list_eligible_post_ot_snapshot_line_ids(case) projection = project_review_case_line_decisions(case) unassigned = [ - str(item.get('line_key') or '') + str(item.get('snapshot_line_id') or '') for item in list(projection.get('lines') or []) if str(item.get('line_status') or '') not in {'task_created', 'fulfilled', 'closed_unfulfillable'} ] @@ -129,7 +138,7 @@ def coordinate_post_ot_auto_fulfill( 'reason': 'no_eligible_lines', 'trigger': trigger, 'case_no': case.case_no, - 'accepted_line_keys': [], + 'accepted_snapshot_line_ids': [], } # [STEP] 自动制单只处理唯一开放明细。多条明细必须由用户勾选后合并, # 绝不静默替用户决定 Notice 的合并范围。 @@ -139,7 +148,7 @@ def coordinate_post_ot_auto_fulfill( 'reason': 'manual_wave_selection_required', 'trigger': trigger, 'case_no': case.case_no, - 'accepted_line_keys': [], + 'accepted_snapshot_line_ids': [], } idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}' @@ -147,7 +156,7 @@ def coordinate_post_ot_auto_fulfill( # [STEP 1] 整波创建(失败则整波回滚) result = create_post_ot_fulfillment_wave( case_no=str(case.case_no), - line_keys=eligible, + snapshot_line_ids=[int(item) for item in eligible], decision_source='system', actor_user_id=None, reason=f'auto_fulfill:{trigger}', @@ -157,7 +166,7 @@ def coordinate_post_ot_auto_fulfill( progress = schedule_post_ot_wave_progress( task_no=str(result.get('task_no') or ''), wave_no=result.get('wave_no'), - line_keys=list(result.get('accepted_line_keys') or eligible), + snapshot_line_ids=[int(item) for item in (result.get('accepted_snapshot_line_ids') or eligible)], review_case_id=int(result.get('review_case_id') or case.id), idempotency_row_id=result.get('idempotency_row_id'), request_idempotency_key=str(result.get('idempotency_key') or idem_key), @@ -170,7 +179,7 @@ def coordinate_post_ot_auto_fulfill( 'case_no': case.case_no, 'wave_progress': progress, **{k: result.get(k) for k in ( - 'task_no', 'wave_no', 'accepted_line_keys', 'skipped_line_keys', + 'task_no', 'wave_no', 'accepted_snapshot_line_ids', 'skipped_snapshot_line_ids', 'idempotency_row_id', 'idempotent_replay', )}, } @@ -185,7 +194,7 @@ def coordinate_post_ot_auto_fulfill( if refreshed is not None: _mark_auto_fulfill_failed( refreshed, - line_keys=eligible, + snapshot_line_ids=eligible, error_code=getattr(exc, 'code', None) or 'SHIPPING.AUTO_FULFILL_FAILED', message=str(exc)[:1000], ) @@ -195,7 +204,7 @@ def coordinate_post_ot_auto_fulfill( 'trigger': trigger, 'case_no': case_no_hint, 'error': str(exc)[:500], - 'eligible_line_keys': eligible, + 'eligible_snapshot_line_ids': eligible, } diff --git a/backend/app/services/shipping_notice/line_inventory_match_projection.py b/backend/app/services/shipping_notice/line_inventory_match_projection.py index 2255d78f..8be910ae 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_projection.py +++ b/backend/app/services/shipping_notice/line_inventory_match_projection.py @@ -6,7 +6,8 @@ services/shipping_notice/line_inventory_match_projection.py 逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用; ready+not_found→available=0;result_missing 不得转 0; inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮); - line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail。 + line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail; + load_current_match_facts_by_task 在同一 HTTP 请求内按 task_id memo。 """ from __future__ import annotations @@ -415,12 +416,32 @@ def resolve_allowed_actions( def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, Any]]: - """加载 OT 当前行匹配事实,键为冻结订单行 ID。""" + """ + 加载 OT 当前行匹配事实,键为冻结订单行 ID。 + + 同一 HTTP 请求内按 task_id memo,避免 SUMMARY / ui_state / stage_context 重复查库。 + """ if task_id is None: return {} + key = int(task_id) + try: + from flask import g, has_app_context, has_request_context + if has_app_context() and has_request_context(): + cache = getattr(g, '_shipping_match_facts_by_task', None) + if cache is None: + cache = {} + g._shipping_match_facts_by_task = cache + cached = cache.get(key) + if cached is not None: + return cached + else: + cache = None + except Exception: + cache = None + rows = ( ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task_id), is_current=True) + .filter_by(task_id=key, is_current=True) .all() ) out: dict[int, dict[str, Any]] = {} @@ -428,6 +449,8 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, if row.snapshot_line_id is None: continue out[int(row.snapshot_line_id)] = serialize_match_fact(row) + if cache is not None: + cache[key] = out return out @@ -470,6 +493,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'unit': row.unit, 'matching_rule_version': row.matching_rule_version, 'inventory_source_code': row.inventory_source_code, + 'allowed_source_codes_snapshot': list(getattr(row, 'allowed_source_codes_snapshot', None) or []), 'inventory_file_no': getattr(row, 'matched_file_no', None), 'inventory_file_sha256': ( dict(row.detail_json or {}).get('file_sha256') diff --git a/backend/app/services/shipping_notice/match.py b/backend/app/services/shipping_notice/match.py index ff274131..4f16a86c 100644 --- a/backend/app/services/shipping_notice/match.py +++ b/backend/app/services/shipping_notice/match.py @@ -15,7 +15,7 @@ def _norm(value: Any) -> str: return str(value or "").strip() -def _line_key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: +def _match_identity(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: """按配置字段列表构造确定性匹配键;任一字段为空时该行不可匹配。""" values = tuple(_norm(row.get(field)).casefold() for field in fields) return values if values and all(values) else None @@ -27,7 +27,7 @@ def _aggregate_inventory( """按用户配置的库存匹配字段组合汇总唯一数量字段。""" totals: dict[tuple[str, ...], float] = {} for row in inventory_lines: - key = _line_key(row, match_fields) + key = _match_identity(row, match_fields) if key is None: continue try: @@ -70,7 +70,7 @@ def match_notice_lines( # [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。 total_lines = len(notice_lines) for index, line in enumerate(notice_lines, start=1): - order_key = _line_key(line, order_fields) + order_key = _match_identity(line, order_fields) try: required = float(line.get("__required_qty") or 0) except (TypeError, ValueError): diff --git a/backend/app/services/shipping_notice/openapi_spec.py b/backend/app/services/shipping_notice/openapi_spec.py index f2bb3f97..fbdac2cb 100644 --- a/backend/app/services/shipping_notice/openapi_spec.py +++ b/backend/app/services/shipping_notice/openapi_spec.py @@ -51,7 +51,7 @@ def _post_op( "200": { "description": ( "Tool response (status: ok|running|needs_human|failed). " - "May include checkpoint; business buttons are exposed only by ui_state.actions." + "May include position; business buttons are exposed only by ui_state.actions." ), "content": { "application/json": { @@ -86,7 +86,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "paths": { "/tools/get_task_status": _post_op( "get_task_status", - "查询任务当前状态;响应含库存连接器独立字段与候选结构", + "查询任务当前状态;响应含库存源状态与候选结构", { "task_id": task_id, "conversation_id": _str_prop("Dify 会话 ID"), @@ -94,8 +94,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: }, required=["task_id", "shipping_chat_capability_token"], description=( - "返回 inventory_source_code、inventory_connector_type、" - "inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|" + "返回 inventory_source_code、inventory_warehouse_id、" + "inventory_source_status(unresolved|ambiguous|resolved|" "candidates_frozen|invalid|conflicted)、inventory_source_method、" "inventory_source_config_version、inventory_routing_fingerprint、" "以及 step_payload.inventory_source_resolution.candidates。" diff --git a/backend/app/services/shipping_notice/order_customer_matching.py b/backend/app/services/shipping_notice/order_customer_matching.py deleted file mode 100644 index 2e4f32fc..00000000 --- a/backend/app/services/shipping_notice/order_customer_matching.py +++ /dev/null @@ -1,289 +0,0 @@ -""" -backend/app/services/shipping_notice/order_customer_matching.py - -用途:将订单解析出的 Bill-to / Ship-to 名称和外部编码匹配到客户及送货站点主数据。 -依赖:ShippingCustomer、外部编码、客户站点/标识、ShippingOrderCustomerMatch、客户名称规范化。 -逻辑:外部编码优先于名称;Bill-to 匹配标准客户,Ship-to 匹配客户站点,唯一命中保存简称快照。 -""" - -from __future__ import annotations - -import hashlib -import json -from datetime import datetime -from typing import Any - -from app import db -from app.core.errors import NotFoundError, ValidationError -from app.models import ( - ShippingCustomer, - ShippingCustomerExternalRef, - ShippingCustomerIdentifier, - ShippingCustomerSite, - ShippingCustomerSiteIdentifier, - ShippingOrderCustomerMatch, - ShippingOrderExtraction, -) -from app.services.shipping_notice.customer_normalization import normalize_customer_name - -ROLE_FIELDS = { - 'bill_to': {'name': 'bill_to_customer', 'code': 'bill_to_customer_code', 'source': 'bill_to_source_system'}, - 'ship_to': {'name': 'ship_to_customer', 'code': 'ship_to_code', 'source': 'ship_to_source_system'}, -} -IDENTITY_RULE_VERSION = 'order-customer-fingerprint.v1' - - -def _normalized_code(value: Any) -> str: - """规范外部客户/站点编码,保留业务符号并统一大小写。""" - return str(value or '').strip().upper() - - -def _identity_fingerprint(*, role: str, raw_name: str, external_code: str, source_system: str) -> tuple[str, dict[str, str]]: - """用订单原文标准化值和固定规则版本生成稳定身份指纹,不写回或替换原始字段。""" - components = { - 'role': role, - 'normalized_name': normalize_customer_name(raw_name) if raw_name else '', - 'external_code': _normalized_code(external_code), - 'source_system': _normalized_code(source_system), - } - encoded = json.dumps( - {'rule_version': IDENTITY_RULE_VERSION, 'components': components}, - ensure_ascii=True, sort_keys=True, separators=(',', ':'), - ).encode('utf-8') - return hashlib.sha256(encoded).hexdigest(), components - - -def _customer_candidates(raw_name: str) -> list[dict[str, Any]]: - """按标准名称和 approved 名称别名返回稳定去重的启用客户候选。""" - normalized = normalize_customer_name(raw_name) - if not normalized: - return [] - customers = db.session.query(ShippingCustomer).filter_by(status='active').all() - matched: dict[int, dict[str, Any]] = {} - for customer in customers: - if normalize_customer_name(customer.standard_name) == normalized: - matched[customer.id] = { - 'customer_id': customer.id, - 'standard_name': customer.standard_name, - 'short_code': customer.short_code, - 'matched_by': ['standard_name'], - } - aliases = db.session.query(ShippingCustomerIdentifier).filter_by( - identifier_type='name_alias', normalized_value=normalized, status='approved', - ).all() - active_by_id = {customer.id: customer for customer in customers} - for alias in aliases: - customer = active_by_id.get(int(alias.customer_id)) - if customer is None: - continue - candidate = matched.setdefault(customer.id, { - 'customer_id': customer.id, - 'standard_name': customer.standard_name, - 'short_code': customer.short_code, - 'matched_by': [], - }) - if 'name_alias' not in candidate['matched_by']: - candidate['matched_by'].append('name_alias') - return sorted(matched.values(), key=lambda item: (item['standard_name'], item['customer_id'])) - - -def _bill_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]: - """优先按来源系统和外部客户编码匹配 Bill-to,再回退名称匹配。""" - code = _normalized_code(external_code) - source = _normalized_code(source_system) - if code and source: - refs = db.session.query(ShippingCustomerExternalRef).filter_by( - source_system=source, legacy_customer_key=code, - ).all() - candidates = [] - for ref in refs: - customer = db.session.get(ShippingCustomer, int(ref.customer_id)) - if customer and customer.status == 'active': - candidates.append({ - 'customer_id': customer.id, 'standard_name': customer.standard_name, - 'short_code': customer.short_code, 'site_id': None, 'site_name': None, - 'site_code': None, 'matched_by': ['external_customer_code'], - }) - if candidates: - return candidates - return [{**item, 'site_id': None, 'site_name': None, 'site_code': None} for item in _customer_candidates(raw_name)] - - -def _ship_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]: - """优先按 Ship-to Code 匹配启用站点,再按站点名称或已审核别名匹配。""" - code = _normalized_code(external_code) - source = _normalized_code(source_system) - sites = db.session.query(ShippingCustomerSite).filter_by(status='active').all() - matched: dict[int, dict[str, Any]] = {} - matched_site_ids: dict[int, str] = {} - if code: - identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by( - identifier_type='external_code', source_system=source, normalized_value=code, status='approved', - ).all() - for identifier in identifiers: - matched_site_ids[int(identifier.site_id)] = 'external_site_code' - for site in sites: - if _normalized_code(site.site_code) == code: - matched_site_ids[site.id] = 'site_code' - if not matched_site_ids: - normalized = normalize_customer_name(raw_name) if raw_name else '' - for site in sites: - if normalized and normalize_customer_name(site.site_name) == normalized: - matched_site_ids[site.id] = 'site_name' - if normalized: - identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by( - identifier_type='name_alias', source_system='', normalized_value=normalized, status='approved', - ).all() - for identifier in identifiers: - matched_site_ids[int(identifier.site_id)] = 'site_name_alias' - by_id = {site.id: site for site in sites} - for site_id, matched_by in matched_site_ids.items(): - site = by_id.get(site_id) - customer = db.session.get(ShippingCustomer, int(site.customer_id)) if site else None - if site is None or customer is None or customer.status != 'active': - continue - matched[site.id] = { - 'customer_id': customer.id, 'standard_name': customer.standard_name, - 'short_code': customer.short_code, 'site_id': site.id, 'site_name': site.site_name, - 'site_code': site.site_code, 'matched_by': [matched_by], - } - return sorted(matched.values(), key=lambda item: (item['standard_name'], item['site_name'], item['site_id'])) - - -def refresh_order_customer_matches( - extraction: ShippingOrderExtraction, - header: dict[str, Any], -) -> list[dict[str, Any]]: - """ - 根据订单头原文幂等刷新 Bill-to / Ship-to 客户匹配结果。 - - Args: - extraction: 已持久化的动态订单解析记录。 - header: 已通过证据裁决的订单头字段投影。 - Returns: - 两种角色的匹配摘要;客户简称只来自客户主数据快照。 - """ - results: list[dict[str, Any]] = [] - for role, fields in ROLE_FIELDS.items(): - raw_name = str(header.get(fields['name']) or '').strip() - external_code = _normalized_code(header.get(fields['code'])) - source_system = _normalized_code(header.get(fields['source'])) - fingerprint, components = _identity_fingerprint( - role=role, raw_name=raw_name, external_code=external_code, source_system=source_system, - ) - candidates = ( - _bill_to_candidates(raw_name, external_code, source_system) - if role == 'bill_to' - else _ship_to_candidates(raw_name, external_code, source_system) - ) - row = db.session.query(ShippingOrderCustomerMatch).filter_by( - extraction_id=extraction.id, role=role, - ).one_or_none() - if row is None: - row = ShippingOrderCustomerMatch(extraction_id=extraction.id, role=role) - db.session.add(row) - row.raw_name = raw_name or None - row.normalized_name = normalize_customer_name(raw_name) if raw_name else None - row.source_system = source_system or None - row.external_code = external_code or None - row.identity_fingerprint = fingerprint - row.identity_rule_version = IDENTITY_RULE_VERSION - row.identity_components_json = components - row.candidates_json = candidates - if len(candidates) == 1: - candidate = candidates[0] - row.status = 'unique_candidate' - row.customer_id = int(candidate['customer_id']) - row.site_id = int(candidate['site_id']) if candidate.get('site_id') else None - row.customer_name_snapshot = str(candidate['standard_name']) - row.customer_short_code_snapshot = str(candidate['short_code']) - row.resolution_method = str(candidate['matched_by'][0]) - else: - row.status = 'ambiguous' if candidates else 'unmatched' - row.customer_id = None - row.site_id = None - row.customer_name_snapshot = None - row.customer_short_code_snapshot = None - row.resolution_method = None - row.confirmed_by_id = None - row.confirmed_at = None - row.confirmation_reason = None - row.updated_at = datetime.utcnow() - db.session.flush() - results.append(serialize_order_customer_match(row)) - return results - - -def confirm_order_customer_match( - extraction_id: int, - *, - role: str, - customer_id: int, - site_id: int | None = None, - actor_id: int | None, - reason: str, - commit: bool = True, -) -> dict[str, Any]: - """ - 人工确认某个订单客户角色;必须写入理由并保留冻结时可复核的指纹。 - - Args: - commit: True 时立即 db.session.commit();False 时仅 flush,由调用方统一控制事务 - (用于同事务内追加 reconcile / Job 入队等后续步骤)。 - """ - if role not in ROLE_FIELDS: - raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID') - row = db.session.query(ShippingOrderCustomerMatch).filter_by( - extraction_id=extraction_id, role=role, - ).one_or_none() - if row is None: - raise NotFoundError('Order customer match not found', code='SHIPPING.ORDER_CUSTOMER_MATCH_NOT_FOUND') - reason_value = str(reason or '').strip() - if not reason_value: - raise ValidationError('Customer confirmation reason is required', code='SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED') - customer = db.session.get(ShippingCustomer, int(customer_id)) - if customer is None: - raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') - if customer.status != 'active': - raise ValidationError('Inactive customer cannot be used', code='SHIPPING.CUSTOMER_INACTIVE') - selected_site = None - if role == 'ship_to': - selected_site = db.session.get(ShippingCustomerSite, int(site_id)) if site_id is not None else None - if selected_site is None or selected_site.customer_id != customer.id or selected_site.status != 'active': - raise ValidationError('Active Ship-to site is required', code='SHIPPING.ORDER_CUSTOMER_SITE_INVALID') - row.status = 'confirmed' - row.customer_id = customer.id - row.site_id = selected_site.id if selected_site else None - row.customer_name_snapshot = customer.standard_name - row.customer_short_code_snapshot = customer.short_code - row.resolution_method = 'manual' - row.confirmation_reason = reason_value - row.confirmed_by_id = actor_id - row.confirmed_at = datetime.utcnow() - if commit: - db.session.commit() - else: - db.session.flush() - return serialize_order_customer_match(row) - - -def serialize_order_customer_match(row: ShippingOrderCustomerMatch) -> dict[str, Any]: - """输出前端可直接展示的角色匹配摘要,不暴露内部 ORM 状态。""" - return { - 'id': row.id, - 'extraction_id': row.extraction_id, - 'role': row.role, - 'raw_name': row.raw_name, - 'status': row.status, - 'customer_id': row.customer_id, - 'site_id': row.site_id, - 'source_system': row.source_system, - 'external_code': row.external_code, - 'identity_fingerprint': row.identity_fingerprint, - 'identity_rule_version': row.identity_rule_version, - 'standard_name': row.customer_name_snapshot, - 'short_code': row.customer_short_code_snapshot, - 'candidates': list(row.candidates_json or []), - 'resolution_method': row.resolution_method, - 'confirmation_reason': row.confirmation_reason, - } 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 bf39a6f1..6b444c0f 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -1,10 +1,10 @@ """ backend/app/services/shipping_notice/order_document_profile_service.py -??????????? Profile ?????????? Run ????? -???ShippingOrderDocumentProfile?????????? Schema ???document_layout.order_profile ???? -??????????? field_code ???? field_id?????????? Schema ?????????? - ???????????????????????? CASCADE ???? 500? + Profile Run +ShippingOrderDocumentProfile Schema document_layout.order_profile + field_code field_id Schema + CASCADE 500? """ from __future__ import annotations @@ -85,7 +85,7 @@ PDF_PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-pdf-preview:' def _definition_hash(definition: dict[str, Any]) -> str: - """?? v2 ??????????????????????? 7 ?????""" + """ v2 7 """ encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() return hashlib.sha256(encoded).hexdigest() @@ -102,7 +102,7 @@ def _profile_template_mode(profile: ShippingOrderDocumentProfile) -> str: def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> bool: - """???????????????????????????????????""" + """""" required = ( sample.layout_version_id, sample.source_content_hash, @@ -116,7 +116,7 @@ def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> def _sample_payload(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any]: - """????????????????????????""" + """""" return { 'id': sample.id, 'document_id': sample.document_id, @@ -139,7 +139,7 @@ def _sample_payload(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any def _profile_frozen_evidence_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: - """???????????????????????????????""" + """""" samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all() total_count = len(samples) ready_count = sum(1 for item in samples if _sample_frozen_evidence_ready(item)) @@ -200,16 +200,16 @@ def _match_summary(definition: dict[str, Any]) -> dict[str, Any]: def _normalize_profile_customer_scope(customer_ids: Any) -> list[int] | None: """ - ????????????????????????????????? + Args: - customer_ids: ????????????????? + customer_ids: Returns: - ???????? ID ????????? None? + ID None? Raises: - ValidationError: ?? ID ??????? + ValidationError: ID """ if customer_ids is None: return None @@ -248,7 +248,7 @@ def _audit( revision_no: int | None = None, detail: dict[str, Any] | None = None, ) -> None: - """?? Profile ?????detail ???????????? checksum ???????""" + """ Profile detail checksum """ db.session.add(ShippingOrderDocumentProfileAudit( profile_id=profile_id, document_id=document_id, event_type=event_type, actor_id=actor_id, request_id=str(request_id or '').strip() or None, @@ -259,14 +259,14 @@ def _audit( def _refresh_training_sample_count(profile: ShippingOrderDocumentProfile) -> None: - """?? Profile ????????????????????????""" + """ Profile """ profile.training_sample_count = ShippingOrderDocumentProfileSample.query.filter_by( profile_id=profile.id, sample_role='training', ).count() def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]: - """??????????????????????????????????""" + """""" adapter_summary = get_value_adapter(definition).definition_audit_summary(definition) if adapter_summary is not None: return adapter_summary @@ -300,7 +300,7 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]: def _bound_sample_document(profile_id: int, document_id: int) -> ShippingOrderDocument: - """?????? Profile ???????????? ID ???????""" + """ Profile ID """ sample = ShippingOrderDocumentProfileSample.query.filter_by( profile_id=int(profile_id), document_id=int(document_id), ).first() @@ -362,12 +362,12 @@ def _release_profile_sample_asset_if_unreferenced(profile_id: int, document_id: def _preview_grant_store() -> Any: - """?????????????? Redis????????????????""" + """ Redis""" return preview_grant_store() def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]: - """???? Schema ????????????????? field_code?""" + """ Schema field_code?""" definition = version.definition_json if isinstance(version.definition_json, dict) else {} result: dict[str, dict[str, Any]] = {} for raw in definition.get('fields') or []: @@ -385,7 +385,7 @@ def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, A def _schema_profile_fields(version: ShippingOrderSchemaVersion) -> dict[tuple[str, str], dict[str, Any]]: - """? ``(scope, field_code)`` ?? Profile ???????????????????""" + """? ``(scope, field_code)`` Profile """ definition = version.definition_json if isinstance(version.definition_json, dict) else {} result: dict[str, dict[str, Any]] = {} for index, raw in enumerate(definition.get('fields') or []): @@ -425,7 +425,7 @@ def _schema_profile_fields(version: ShippingOrderSchemaVersion) -> dict[tuple[st def _require_schema_version(raw_id: Any) -> ShippingOrderSchemaVersion: - """????? published/retired Schema??????? Profile ?????""" + """ published/retired Schema Profile """ try: version_id = int(raw_id) except (TypeError, ValueError) as exc: @@ -449,13 +449,13 @@ def _normalize_definition( preferred_template_mode: str | None = None, ) -> dict[str, Any]: """ - ?? v2 ????????? ID???? HTML ??/?????? + v2 ID HTML / Args: - raw: ???????????????????????????? - schema_version: ????????????????? + raw: + schema_version: Returns: - ????? v2 ????????????? Schema ???????? + v2 Schema """ if not isinstance(raw, dict): raise ValidationError( @@ -800,7 +800,7 @@ def _normalize_visual_definition_for_preview( def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordinateProfile: - """???????????????? v1 ???? Profile ??????? v2?""" + """ v1 Profile v2?""" definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} return OrderCoordinateProfile( profile_code=profile.profile_code, @@ -815,7 +815,7 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: - """????????? Profile ?? DTO?""" + """ Profile DTO?""" schema = profile.schema_version source_profile = profile.source_profile compatibility = None @@ -874,7 +874,7 @@ def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: def list_profiles() -> list[dict[str, Any]]: - """?????????????? Profile?""" + """ Profile?""" return [payload(item) for item in ShippingOrderDocumentProfile.query.order_by( ShippingOrderDocumentProfile.profile_code.asc(), ShippingOrderDocumentProfile.version.desc(), @@ -882,7 +882,7 @@ def list_profiles() -> list[dict[str, Any]]: def list_profile_samples(profile_id: int) -> list[dict[str, Any]]: - """??????????????????????????""" + """""" profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -892,7 +892,7 @@ def list_profile_samples(profile_id: int) -> list[dict[str, Any]]: def resolve_profile_sample_table_id(profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample) -> str: - """???????????????????????????????????""" + """""" explicit = str(sample.table_id or '').strip() if explicit: return explicit @@ -920,7 +920,7 @@ def resolve_profile_sample_table_id(profile: ShippingOrderDocumentProfile, sampl def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]: - """???????????????????????? token?????????""" + """ token""" if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') try: @@ -965,7 +965,7 @@ def list_preview_pages(profile_id: int, *, document_id: int, actor_id: int | Non def render_preview_page(*, token: str, page_no: int, actor_id: int | None) -> bytes: - """?????????????? PNG????? PDF?HTML?????????""" + """ PNG PDF?HTML""" store = _preview_grant_store() raw_grant = store.getdel(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token)}') try: @@ -1056,7 +1056,7 @@ def read_pdf_preview(*, token: str, actor_id: int | None) -> bytes: def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, actor_id: int | None) -> dict[str, Any]: - """???????????????? bbox?token ID?HTML ????????""" + """ bbox?token ID?HTML """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') try: @@ -1085,15 +1085,15 @@ def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, act def read_preview_page_region_text( profile_id: int, *, data: dict[str, Any], page_no: int, actor_id: int | None, ) -> dict[str, Any]: - """????????????????????????-?????? + """- Args: - profile_id: ?????????????????? - data: ??? document_id ????? region??????????????? - page_no: ????????? - actor_id: ?????????????????? + profile_id: + data: document_id region + page_no: + actor_id: Returns: - ????????????????????????????????? + """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') @@ -1182,7 +1182,7 @@ def _read_rendered_preview_crop_text(rendered_image_base64: Any) -> str: def preview_profile_region( profile_id: int, *, data: dict[str, Any], actor_id: int | None, ) -> dict[str, Any]: - """?????????? v2 ?????????????????????""" + """ v2 """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') try: @@ -1288,7 +1288,7 @@ def preview_profile_region( ) if not isinstance(region_characters, list): continue - # ??????????????????????????? Schema ??? + # Schema for line_layout in sorted(table_region.line_layouts, key=lambda item: item.row_offset): for field_region in line_layout.field_regions: ordered_codes = [field_region.field_code] + [ @@ -1311,16 +1311,16 @@ def preview_profile_region( termination_rules=[item.model_dump() for item in table_region.termination_rules], exclusion_regions=reconstruction_exclusions, dynamic_exclusion_regions=reconstruction_exclusions, - # ????????????????????????????????? + # include_deleted=not strict, line_start_field_code=table_region.line_start_field_code, schema_field_metadata=schema_field_metadata, ) rows.extend(reconstructed_rows) - # ?????????????????????????????? + # if strict: rows = [row for row in rows if not getattr(row, 'issues', None)] - # ?????????????? target_fields ??????????????? + # target_fields for row in rows: for field_code in row.fields: if field_code not in seen_field_codes: @@ -1328,12 +1328,12 @@ def preview_profile_region( involved_field_codes.append(field_code) schema_field_codes = list(_schema_fields(profile.schema_version)) field_codes = [code for code in schema_field_codes if code in seen_field_codes] - # ??????????? Schema ?????????????? Schema ????? + # Schema Schema field_codes.extend(code for code in involved_field_codes if code not in schema_field_codes) result = { 'table_id': table_id, 'row_count': len(rows) + (1 if field_codes else 0), 'column_count': len(field_codes), 'rows': ([field_codes] if field_codes else []) + [[row.fields.get(code, '') for code in field_codes] for row in rows], - # ???????????????????????? rows ????? + # rows 'field_codes': field_codes, 'row_roles': (['header'] if field_codes else []) + [row.role for row in rows], 'source_row_indices': ([[]] if field_codes else []) + [row.source_row_indices for row in rows], @@ -1350,10 +1350,10 @@ def suggest_profile_header( profile_id: int, *, data: dict[str, Any], actor_id: int | None, ) -> dict[str, Any]: """ - ??????????????????????????????? Schema ????? + Schema - ????????????????? Profile?????????????????? - ?? Profile ?? Schema ?????? PDF/OCR ???????? + Profile + Profile Schema PDF/OCR """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') @@ -1422,7 +1422,7 @@ def suggest_profile_header( def generate_profile_ocr_evidence( profile_id: int, *, document_id: Any, table_id: Any, actor_id: int | None, ) -> dict[str, Any]: - """??????? PDF ??? OCR ?????????????????????""" + """ PDF OCR """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') try: @@ -1442,9 +1442,9 @@ def generate_profile_ocr_evidence( def _matching_signature_status(profile: ShippingOrderDocumentProfile) -> str: """ - ?????????missing / valid / stale? + missing / valid / stale? - ? run_id ? checksum ?? missing???????? valid ? missing? + ? run_id ? checksum missing valid ? missing? """ if not profile.matching_signature_run_id or not profile.matching_signature_checksum: return 'missing' @@ -1459,16 +1459,16 @@ def clear_matching_signature_refs( reason: str = 'definition_or_sample_changed', ) -> bool: """ - ?? Profile ?????????? ValidationRun ??? + Profile ValidationRun Args: - profile: ?? Profile ??? - actor_id: ?????? - operation_id: ????? ID? - reason: ?????? + profile: Profile + actor_id: + operation_id: ID? + reason: Returns: - ?????????? + """ if not profile.matching_signature_run_id and not profile.matching_signature_checksum: return False @@ -1493,7 +1493,7 @@ def clear_matching_signature_refs( def add_profile_sample( profile_id: int, *, document_id: Any, table_id: Any, sample_role: Any, actor_id: int | None, ) -> list[dict[str, Any]]: - """????????????????????????????""" + """""" profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -1537,7 +1537,7 @@ def add_profile_sample( def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | None) -> list[dict[str, Any]]: - """?????????????????????????????""" + """""" profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -1561,7 +1561,7 @@ def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | No def _document_layout(document: ShippingOrderDocument) -> dict[str, Any]: - """?????? Profile ? ready MinerU ??????????/??????""" + """ Profile ? ready MinerU /""" from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot layout = current_layout_snapshot(document) or {} @@ -1599,7 +1599,7 @@ def _reference_page_frames(layout: dict[str, Any]) -> dict[str, dict[str, Any]]: def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDocumentLayoutVersion: - """????????? ready Layout ???????????????????????""" + """ ready Layout """ version = document.current_layout_version if ( version is None @@ -1776,7 +1776,7 @@ def require_profile_sample_automark_ready( def _layout_page_count(payload: dict[str, Any]) -> int | None: - """????????????? payload ?? pages?????????????""" + """ payload pages""" pages = payload.get('pages') if isinstance(pages, list) and pages: return len([item for item in pages if isinstance(item, dict)]) @@ -1792,7 +1792,7 @@ def _layout_page_count(payload: dict[str, Any]) -> int | None: def _layout_table_identity_snapshot(payload: dict[str, Any], table_id: str | None) -> dict[str, Any] | None: - """???????????????????????????????""" + """""" safe_table_id = str(table_id or '').strip() if not safe_table_id: return None @@ -1819,7 +1819,7 @@ def _profile_sample_coordinate_pages( profile: ShippingOrderDocumentProfile, *, sample: ShippingOrderDocumentProfileSample, layout_payload: dict[str, Any], ) -> set[int]: - """????? definition ????????????""" + """ definition """ definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} pages: set[int] = set() for anchor in (definition.get('document_match') or {}).get('required_anchors') or []: @@ -1835,7 +1835,7 @@ def _profile_sample_coordinate_pages( def _layout_has_page_coordinate_evidence(payload: dict[str, Any], *, page_nos: set[int]) -> bool: - """?? layout ??????????????? table glyph??""" + """ layout table glyph""" evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {} pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} @@ -1850,7 +1850,7 @@ def _layout_has_page_coordinate_evidence(payload: dict[str, Any], *, page_nos: s def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, frozen_at: datetime) -> int: - """????????????? Layout/Schema/Parser ??????????????""" + """ Layout/Schema/Parser """ from app.services.shipping_notice.document_layout.lifecycle import ( canonical_layout_payload, ensure_inline_xfa_structure_analysis_identity, @@ -1955,9 +1955,9 @@ def _freeze_value_adapter_evidence( def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int: """ - ???????????????? TTL ????? + TTL - ? PDF ??? annotation/training ???? mark_asset_referenced? + ? PDF annotation/training mark_asset_referenced? """ from app.services.file_assets.service import mark_asset_referenced @@ -1981,7 +1981,7 @@ def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int: def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[str, Any]]: - """????????????????????????????????????""" + """""" evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} characters = tables.get(table_id) if isinstance(tables.get(table_id), list) else [] @@ -1989,7 +1989,7 @@ def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[s def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tuple[list[dict[str, Any]], str | None]: - """??????????????????????????????????""" + """""" evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no)) source = (evidence.get('sources') or {}).get('pages', {}).get(str(page_no)) @@ -2090,7 +2090,7 @@ def _read_page_ocr_coordinate_evidence( def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str, float], list[dict[str, Any]]]]: - """??????????????????????????????""" + """""" rows: list[list[dict[str, Any]]] = [] for glyph in sorted(glyphs, key=lambda item: (float((item.get('bbox') or {}).get('y0', 0)), float((item.get('bbox') or {}).get('x0', 0)))): bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None @@ -2131,14 +2131,14 @@ def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str, def _anchor_text_key(value: str) -> str: - """???????????????????????????""" + """""" return re.sub(r'[^\w]+', '', value, flags=re.UNICODE).casefold() def _inline_anchor_and_value_regions( *, text: str, line_bbox: dict[str, float], glyphs: list[dict[str, Any]], label: str, width: float, height: float, ) -> tuple[dict[str, float], dict[str, float], str]: - """??? bbox ?????????????????????????""" + """ bbox """ label_key = _anchor_text_key(label) consumed: list[dict[str, Any]] = [] consumed_start = 0 @@ -2218,7 +2218,7 @@ def _inline_anchor_and_value_regions( def _inline_value_text(*, text: str, label: str) -> str: - """????????????????????????????? PDF?""" + """ PDF?""" start = text.casefold().find(label.casefold()) suffix = text[start + len(label):] if start >= 0 else '' suffix = suffix.lstrip(':? ').strip() @@ -2230,10 +2230,10 @@ def _generic_order_label_candidates( *, lines: list[tuple[str, dict[str, float], list[dict[str, Any]]]], width: float, height: float, table_start_y: float | None, known_anchor_keys: set[str], bound_line_indexes: set[int], source: str, ) -> list[dict[str, Any]]: - """????? Schema ??? ``LABEL: value`` ????????????""" + """ Schema ``LABEL: value`` """ candidates: list[dict[str, Any]] = [] for line_index, (text, bbox, glyphs) in enumerate(lines): - # ?????????????????? QUALITY/SHIPMENT ??????????? + # QUALITY/SHIPMENT if table_start_y is not None and bbox['y0'] >= table_start_y - height * .18: continue match = re.match(r'^\s*([^:?]{2,42}?)[?:]', text) @@ -2259,14 +2259,14 @@ def _generic_order_label_candidates( def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """ - ??????? v2 ?????????????????? + v2 Args: - data: ???????Schema?????????? ``page_nos``?????????? ``page_no``? - actor_id: ????? ID???????????????????????? + data: Schema ``page_nos`` ``page_no``? + actor_id: ID Returns: - ??????????????????????????????????? needs_review? + needs_review? """ try: document_id = int(data.get('document_id')) @@ -2302,7 +2302,7 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} known_pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} page_nos = sorted(set(page_nos) | {int(item) for item in known_pages if str(item).isdigit() and int(item) > 0}) - # [STEP 1] ???????????????????????????????????? + # [STEP 1] selected_layouts = [ item for item in profile.order_field_layouts if any( @@ -2313,7 +2313,7 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> ) ] selected_profile = profile.model_copy(update={'order_field_layouts': selected_layouts}) - # [STEP 2] ?????????????? all_pages ?????????????????? + # [STEP 2] all_pages for selected_page in page_nos: layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=selected_page) fields_by_id = { @@ -2479,10 +2479,10 @@ def suggest_order_field_layouts( record_audit: bool = True, ) -> dict[str, Any]: """ - ??? Schema ? Header ??????????????????????? + Schema ? Header + + PDF/OCR Schema - ????? PDF/OCR ??????????????? Schema ?????????? - ?????????????? """ try: document_id = int(data.get('document_id')) @@ -2565,18 +2565,18 @@ def generate_ocr_coordinate_evidence( persist: bool = True, ) -> dict[str, Any]: """ - ??? PDF ?????????????????????????????? OCR? + PDF OCR? Args: - document_id: ?????? ID????????? PDF ??? - table_id: ??????? MinerU ?? ID????????? - actor_id: ???????? ID????????? + document_id: ID PDF + table_id: MinerU ID + actor_id: ID force_ocr: True 时即使表内存在部分原生字符也重读渲染外观层;仅用于 视觉行/字段证据不足的受控回退,结果仍标为 ocr_coordinate 且 needs_review。 persist: False 时仅返回内存快照,供统一 automark 的多证据融合;禁止改变 Document 当前 Layout 或令冻结样本失效。 Returns: - ??????? ID?source ? pdf ? ocr??????????? + ID?source ? pdf ? ocr """ document = db.session.get(ShippingOrderDocument, int(document_id)) if document is None or not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'): @@ -2655,13 +2655,13 @@ def generate_ocr_coordinate_evidence( def _native_characters_in_table(*, characters: list[Any], table_bbox: dict[str, Any]) -> list[dict[str, Any]]: """ - ??????????????? PDF ???????????????? + PDF Args: - characters: PDFium ??????????? - table_bbox: MinerU ???????????? + characters: PDFium + table_bbox: MinerU Returns: - ??????????????????????????? OCR ??? + OCR """ try: x0, y0 = float(table_bbox['x0']), float(table_bbox['y0']) @@ -2681,7 +2681,7 @@ def _native_characters_in_table(*, characters: list[Any], table_bbox: dict[str, def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) -> list[dict[str, Any]]: - """? OCR ??????????????????OCR ????????????""" + """? OCR OCR """ bbox = table_bbox result: list[dict[str, Any]] = [] source_index = 0 @@ -2703,7 +2703,7 @@ def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) -> def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]: - """? OCR ????????????????????????? cell ?????""" + """? OCR cell """ result: list[dict[str, Any]] = [] source_index = 0 for line in lines: @@ -2724,7 +2724,7 @@ def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]: def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict[str, Any]]: - """??????????????????????????????""" + """""" if actor_id is None: return [] safe_limit = max(1, min(int(limit), 100)) @@ -2748,7 +2748,7 @@ def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict if layout.get('status') != 'ready' or not tables: continue content_hash = str(document.content_hash or '').strip().lower() - # ??????????????????/??????????? + # / if content_hash and content_hash in seen_content_hashes: continue intake = db.session.get(ShippingOrderIntake, document.intake_id) @@ -2785,7 +2785,7 @@ def list_sample_documents(*, actor_id: int | None, limit: int = 50) -> list[dict def delete_sample_intake(intake_no: str, *, actor_id: int | None) -> None: - """???????????????????????????????????""" + """""" if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') intake = ShippingOrderIntake.query.filter_by( @@ -2848,7 +2848,7 @@ def delete_sample_intake(intake_no: str, *, actor_id: int | None) -> None: def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, Any]: - """?????????? PDF/EML ?????? Intake???????????""" + """ PDF/EML Intake""" if actor_id is None: raise ValidationError( 'Profile sample requires an administrator identity', @@ -2866,7 +2866,7 @@ def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, An def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[str, Any]: - """?????????????Intake ???????????????""" + """Intake """ if actor_id is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') intake = ShippingOrderIntake.query.filter_by( @@ -2913,7 +2913,7 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st status = 'parsed' error_code = None else: - # ???? PDF Document??????? EML / Layout? + # PDF Document EML / Layout? status = 'parsing' error_code = None ready_values = [bool(item.get('automark_ready')) for item in readiness] @@ -2943,7 +2943,7 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st def get_sample_tables(document_id: int) -> dict[str, Any]: - """?????????????????? cell ?????? bbox?????? HTML?""" + """ cell bbox HTML?""" document = db.session.get(ShippingOrderDocument, int(document_id)) if document is None: raise NotFoundError( @@ -3064,13 +3064,13 @@ def suggest_coordinate_reconstruction( data: dict[str, Any], *, actor_id: int | None, layout_snapshot: dict[str, Any] | None = None, ) -> dict[str, Any]: """ - ??????????????????????????? + Args: - data: document_id?table_id???????? row_offset??? row_offset ??????? - actor_id: ????? ID???????????????? + data: document_id?table_id row_offset row_offset + actor_id: ID Returns: - ???????????????????????????????????? + """ try: document_id = int(data.get('document_id')) @@ -3240,9 +3240,9 @@ def create_draft_from_sample( operation_id: str | None = None, enforce_lease: bool = False, ) -> dict[str, Any]: """ - ??????? v2 ?????? Profile ??? + v2 Profile - ?????????????????????? HTML??????????? + HTML """ try: document_id = int(data.get('document_id')) @@ -3259,7 +3259,7 @@ def create_draft_from_sample( layout = _document_layout(document) if not isinstance(data.get('definition'), dict): raise ValidationError('Coordinate template definition is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') - # ???????????????????? table/document ??????????? + # table/document if not any(isinstance(item, dict) for item in layout.get('tables') or []): raise ValidationError('Selected sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') saved = save_draft({ @@ -3295,21 +3295,21 @@ def save_draft( enforce_lease: bool = False, commit: bool = True, ) -> dict[str, Any]: """ - ?????????????????????? Revision? + Revision? Args: - data: ????????? Profile ????????? - actor_id: ???????? - profile_id: ?????????????? - browser_session_id: ?????????????????? - lease_token: ????????????????? - operation_id: ????? Revision ???????? - change_source: ????????????? restore? - enforce_lease: ? True ??????????????? - commit: ? False ??????????????????????????? + data: Profile + actor_id: + profile_id: + browser_session_id: + lease_token: + operation_id: Revision + change_source: restore? + enforce_lease: ? True + commit: ? False Returns: - ??????????? Profile DTO????? Revision ??? + Profile DTO Revision """ operation = str(operation_id or secrets.token_hex(16)).strip() profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile_id else None @@ -3521,7 +3521,7 @@ def save_draft( ) db.session.add(profile) else: - # ?????????????????????? Revision??????????????? + # Revision if ( profile.structure_fingerprint != definition_checksum or previous_display_name != next_display_name @@ -3619,7 +3619,7 @@ def save_draft( profile_id=profile.id, definition_checksum=profile.structure_fingerprint, ).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first() revision = retry_revision - # ?????????????????????? Revision??????????????? + # Revision has_effective_change = ( previous_definition is None or previous_definition != definition @@ -3628,7 +3628,7 @@ def save_draft( or change_source == 'restore' or latest_revision is None ) - # definition ????????????? ValidationRun ?? stale + # definition ValidationRun stale if previous_definition is not None and previous_definition != definition: clear_matching_signature_refs( profile, actor_id=actor_id, operation_id=operation, reason='definition_changed', @@ -3655,7 +3655,7 @@ def save_draft( elif revision is None: revision = latest_revision if revision is None: - # ?????????????????????????????? + # raise ValidationError('Draft revision could not be created', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') _audit(profile_id=profile.id, event_type='draft_saved', actor_id=actor_id, operation_id=operation, browser_session_id=str(browser_session_id or '').strip() or None, revision_no=revision.revision_no, detail={ @@ -3683,17 +3683,17 @@ def _resolve_annotation_document( required: bool, ) -> ShippingOrderDocument | None: """ - ?? XFA ???????/????? + XFA / Args: - profile: ???? Profile? - data: ?????? sample_document_id? + profile: Profile? + data: sample_document_id? Returns: - ShippingOrderDocument ??? + ShippingOrderDocument Raises: - NotFoundError / ValidationError: ????????? Profile? + NotFoundError / ValidationError: Profile? """ document_id = data.get('sample_document_id') if document_id not in (None, ''): @@ -3736,7 +3736,7 @@ def _resolve_annotation_document( def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: - """??????????????????????????????????????""" + """""" source = db.session.get(ShippingOrderDocumentProfile, profile_id) if source is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -3773,7 +3773,7 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: profile_id=source.id, sample_role='annotation', ).all() for sample in annotation_samples: - # ??????? annotation ???? PDF?????????????????????? + # annotation PDF db.session.add(ShippingOrderDocumentProfileSample( profile_id=clone.id, document_id=sample.document_id, @@ -3814,7 +3814,7 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: def create_schema_migration_draft( profile_id: int, *, target_schema_version_id: int, resolutions: dict[str, Any], actor_id: int | None, ) -> dict[str, Any]: - """???? Profile ???????????????????????""" + """ Profile """ source = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if source is None or source.status != 'published': raise ValidationError( @@ -4063,7 +4063,7 @@ def create_schema_migration_draft( def publish( profile_id: int, *, actor_id: int | None, expected_lock_version: Any, commit: bool = True, ) -> dict[str, Any]: - """????????????????commit=False ???????????????""" + """commit=False """ try: profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile is None: @@ -4099,7 +4099,7 @@ def publish( 'All draft order field layouts must be bound before publish', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) - # ?????????/????????????????? manual_confirmation ??? + # / manual_confirmation from app.services.shipping_notice.document_profile_quality_service import ( assert_profile_publishable, ensure_manual_confirmation_qualification, @@ -4195,7 +4195,7 @@ def publish( def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]: - """????????????? Run ??????????""" + """ Run """ profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -4213,10 +4213,10 @@ def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]: def delete_draft(profile_id: int) -> None: """ - ???????????????/??????????/??????????? + // - ?????checksum ?????? profile ???? suites?? suites/auto_freeze - ? profile_id ?? DB CASCADE??????????????? IntegrityError 500? + checksum profile suites suites/auto_freeze + ? profile_id DB CASCADE IntegrityError 500? """ profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile is None: @@ -4226,11 +4226,11 @@ def delete_draft(profile_id: int) -> None: 'Only draft order document profile can be deleted', code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED', ) - # [STEP 1] ?????????quality_suite_id ? CASCADE???? suite ??? + # [STEP 1] quality_suite_id ? CASCADE suite ShippingDocumentProfileAutoFreezeQualification.query.filter_by( profile_id=profile.id, ).delete(synchronize_session=False) - # [STEP 2] ??? Profile ????????? superseded??samples/runs ? ORM cascade + # [STEP 2] Profile supersededsamples/runs ? ORM cascade suites = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).all() for suite in suites: db.session.delete(suite) @@ -4248,13 +4248,13 @@ def delete_draft(profile_id: int) -> None: from app.services.file_assets.service import release_asset_reference release_asset_reference(asset) - # [STEP 4] ???? Profile ????????? DB CASCADE? + # [STEP 4] Profile DB CASCADE? db.session.delete(profile) db.session.commit() def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any]]: - """???? Schema ??? Profile ?????????? field_id ?????""" + """ Schema Profile field_id """ target_schema = db.session.get(ShippingOrderSchemaVersion, int(schema_version_id)) if target_schema is None or target_schema.status != 'published': return [] @@ -4334,7 +4334,7 @@ def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any def _require_sample_document(document_id: int) -> ShippingOrderDocument: - """? ID ??????????? NotFoundError?""" + """? ID NotFoundError?""" document = db.session.get(ShippingOrderDocument, int(document_id)) if document is None: raise NotFoundError( 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 65fa9f46..37a52a2b 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -4506,12 +4506,18 @@ def sync_order_extraction_run_after_job_recovery(job: Any) -> None: Args: job: 已由 `recover_stale_jobs` 条件更新成功并刷新的 Job。 """ + from app.services.shipping_notice.order_review_workbench_projection import ( + project_job_status_outcome, + ) run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first() if run is None or run.status in {'completed', 'partially_completed', 'review_required', 'cancelled'}: return if job.status == 'queued' and run.status == 'processing': transition_order_extraction_run(run, target_status='queued', phase='timeout_retry_queued') - elif job.status in {'failed', 'dead', 'cancelled'} and run.status in {'queued', 'processing'}: + elif ( + project_job_status_outcome(getattr(job, 'status', None)) == 'failed' + or str(getattr(job, 'status', None) or '').strip().lower() == 'cancelled' + ) and run.status in {'queued', 'processing'}: if run.status == 'queued': transition_order_extraction_run(run, target_status='processing', phase='timeout_failing') transition_order_extraction_run( diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index 80b541f7..15f65e2a 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -1280,7 +1280,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A candidate.consumed_task_id = int(task.id) candidate.updated_at = datetime.utcnow() # The review Case is the explicit human confirmation for this PDF. Do not - # recreate a low-confidence parse checkpoint on the newly materialized Task. + # recreate a low-confidence parse_review disposition on the newly materialized Task. # [STEP] 确认只固化订单信息(订单字段/客户/订单快照)。库存源候选的裁决/冻结 # 退到确认后 OT 进入的正式 inventory_source_routing Gate 处理,不在确认流程内 # 提前冻结库存候选,因此也不再在确认处设置 OT 的 notification_preparation 阶段。 diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index 879ad00c..21e5c55f 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -12,6 +12,7 @@ backend/app/services/shipping_notice/order_review_projection.py order_review_fulfillment_decision_service.project_review_case_line_decisions / build_inventory_issue_fallback、 order_review_workbench_projection(正式 OT / completed_checks / field_completeness)、 + lifecycle_projection.project_lifecycle(队列摘要五阶段;禁止 build_task_ui_state)、 order_task_service.resolve_order_task_for_candidate、 schema_edit_policy.list_editable_formal_field_ids、 workflow_ledger_service.find_item_by_current_case、ShippingNotice(确认后推进态)。 @@ -33,6 +34,7 @@ backend/app/services/shipping_notice/order_review_projection.py 普通路径不再投影 confirm(自动建单走 STP;无 manual_create_fallback); 不返回会话级批量恢复动作;失败由当前 Gate 的具体动作恢复。 WorkflowItem 已关闭时 available_actions 仅保留 view; + 会话队列摘要对正式 OT 仅用 project_lifecycle(OT.stage),禁止逐条 build_task_ui_state; 不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。 """ @@ -57,6 +59,7 @@ from app.models import ( ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, + ShippingTaskInventoryRpaAttempt, ) @@ -66,6 +69,30 @@ def _safe_filename(value: Any) -> str | None: return name[:255] or None +def _inventory_rpa_is_running(task: Any) -> bool: + """仅依据正式 OT 的库存 RPA Attempt 判断库存获取是否运行中。 + + 自动推进 Job(shipping_notice_run)的 queued/running 只表示阶段推进, + 不代表库存 RPA 已创建或正在执行;两者必须隔离,避免把明细行伪装成 acquiring_inventory。 + """ + task_no = str(getattr(task, 'task_no', None) or '').strip() + if not task_no: + return False + try: + return ( + ShippingTaskInventoryRpaAttempt.query + .filter( + ShippingTaskInventoryRpaAttempt.task_no == task_no, + ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + ) + .first() + is not None + ) + except Exception: # noqa: BLE001 + # 纯投影/无数据库测试对象不得把未知状态误判为运行中。 + return False + + def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[str, Any] | None: """ 投影已绑定正式 OT 的任务号与自动推进态(与 automation 同源 Job 判定)。 @@ -273,6 +300,9 @@ def _project_case_automation_status( } # [STEP 2] 建单前:查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。 + from app.services.shipping_notice.order_review_workbench_projection import ( + project_job_status_outcome, + ) job = None latest = None draft = getattr(case, 'current_draft', None) @@ -325,7 +355,7 @@ def _project_case_automation_status( 'can_build': can_build, 'job_id': int(job.id), } - if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}: + if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'failed': # 旧 Job(改造前写入)可能没有 retryable;缺失时按失败即停止处理。 result = latest.result_json if isinstance(latest.result_json, dict) else {} raw_retryable = result.get('retryable') @@ -356,7 +386,7 @@ def _project_case_automation_status( 'error_code': result.get('error_code') or blocking_reason, 'retry_of_job_id': int(latest.id), } - if latest is not None and str(latest.status or '').strip().lower() in {'succeeded', 'success', 'completed'}: + if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'succeeded': return { 'status': 'completed', 'retryable': False, @@ -933,10 +963,8 @@ def serialize_review_case( # [STEP] 行履约投影依赖 automation / labels;Case 兜底仅无行投影且系统失败。 # waiting_to_start / waiting = 尚未真正跑库存 RPA,禁止当成 running 清空行动作。 - auto_status = str((automation or {}).get('status') or '').strip().lower() - inventory_rpa_running = auto_status in { - 'processing', 'queued', 'automating', 'running', - } + # 库存 RPA 运行态必须来自逐源 Attempt;阶段自动推进 Job 与库存 RPA 解耦。 + inventory_rpa_running = _inventory_rpa_is_running(formal_ot.get('task')) source_labels: dict[str, str] = {} if isinstance(validation_snapshot, dict): raw_labels = validation_snapshot.get('inventory_source_labels') or {} @@ -1015,6 +1043,38 @@ def serialize_review_case( } +def _queue_current_gate_hint(case: ShippingOrderReviewCase) -> dict[str, Any] | None: + """ + 从会话级批量缓存取当前 Gate 码,供队列 lifecycle 在 OT.stage 为旧 step 码时兜底。 + + Args: + case: 当前复核 Case。 + + Returns: + ``{'gate_code': ...}`` 或 None(无 Execution / 缓存未就绪时)。 + """ + cache = db.session.info.get('shipping_conversation_projection_read_cache') + if not isinstance(cache, dict) or getattr(case, 'id', None) is None: + return None + execution = (cache.get('execution_by_case_id') or {}).get(int(case.id)) + if execution is None: + return None + gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower() + if gate_code: + return {'gate_code': gate_code} + gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or [] + for gate in gates: + status = str(getattr(gate, 'status', '') or '').strip().lower() + if status not in { + 'blocked_manual', 'blocked_retryable', 'waiting_external', 'running', 'pending', + }: + continue + code = str(getattr(gate, 'gate_code', '') or '').strip().lower() + if code: + return {'gate_code': code} + return None + + def _serialize_review_case_summary( case: ShippingOrderReviewCase, *, @@ -1023,7 +1083,11 @@ def _serialize_review_case_summary( intakes_by_no: dict[str, ShippingOrderIntake] | None = None, drafts_by_id: dict[int, ShippingOrderReviewDraft] | None = None, ) -> dict[str, Any]: - """为工作台文件队列投影单 Case 的只读识别与生命周期摘要。""" + """为工作台文件队列投影单 Case 的只读识别与生命周期摘要。 + + 正式 OT 的五阶段:优先 OT.stage → project_lifecycle;旧 step* stage 不在映射表时 + 用批量缓存的 current Gate 兜底。禁止调用 build_task_ui_state。 + """ draft = ( drafts_by_id.get(int(case.current_draft_id)) if drafts_by_id is not None and case.current_draft_id @@ -1059,17 +1123,25 @@ def _serialize_review_case_summary( intake_parse_authorized = False candidate_is_reviewable = False if case.confirmed_task_id: + from app.services.shipping_notice.lifecycle_projection import project_lifecycle from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot - from app.services.shipping_notice.ui_state import build_task_ui_state + # 队列摘要只需五阶段 lifecycle;禁止走 build_task_ui_state(会拉 Gate/summary/ + # 动作全量,会话多 OT 时 N 倍放大到数秒)。正式 OT 已存在即开放候选上下文入口。 + # OT.stage 若仍是历史 step* 码,project_lifecycle 会忽略它并改用 current_gate 兜底。 formal_ot = resolve_formal_ot(case) if formal_ot.get('has_formal_ot'): task = formal_ot['task'] confirmed_task_no = str(getattr(task, 'task_no', None) or '').strip() or None has_formal_ot = True - task_ui_state = build_task_ui_state(task) - lifecycle_stage = str(task_ui_state.get('lifecycle_stage') or lifecycle_stage) - lifecycle_entries = list(task_ui_state.get('lifecycle_entries') or []) + lifecycle = project_lifecycle( + current_gate=_queue_current_gate_hint(case), + blocking_reason=None, + has_candidate_context=True, + processing_stage=getattr(task, 'stage', None), + ) + lifecycle_stage = str(lifecycle.get('lifecycle_stage') or lifecycle_stage) + lifecycle_entries = list(lifecycle.get('lifecycle_entries') or []) else: from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate 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 fdb21bb0..a0506d34 100644 --- a/backend/app/services/shipping_notice/order_review_workbench_projection.py +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -3,13 +3,14 @@ backend/app/services/shipping_notice/order_review_workbench_projection.py 用途:复核工作台 Case 投影的阶段分层辅助——正式 OT 判定、用户态 profile_match、 field_completeness、completed_checks、OT 当前阶段与 automation 责任方; - 以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐。 + 以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐; + 另提供 Job.status → 单一 outcome 投影(project_job_status_outcome)。 依赖:ShippingNotice、ShippingOrderReviewCase、Job、order_review_draft_service._current_value、 process_gate_contract、processing_projection_invariants、queue_service 域常量。 逻辑:由 order_review_projection.serialize_review_case / shipping_processing_projection / order_review_fulfillment_decision_service 调用;不新建状态模型; project_stage_for_task 与 project_post_ot_automation_from_job 为 Case/Progress 同源; - 禁止前端自行拼接里程碑。 + Job 成功/失败同义词只在本模块翻译,调用方只判 succeeded/failed。 """ from __future__ import annotations @@ -20,6 +21,37 @@ from typing import Any from app import db from app.models import ShippingNotice, ShippingOrderReviewCase, ShippingOrderTask +# Job 库内成功/失败词 → 单一 outcome;仅本模块持有 synonym 袋,禁止外溢。 +JOB_FAILURE_STATUS_TOKENS: frozenset[str] = frozenset({'failed', 'dead'}) +JOB_SUCCESS_STATUS_TOKENS: frozenset[str] = frozenset({'succeeded', 'success', 'completed'}) + + +def project_job_status_outcome(raw_status: str | None) -> str: + """将 Job.status 库内词投影为单一 outcome。 + + 核心逻辑:failed/dead → failed;succeeded/success/completed → succeeded; + queued / running|processing 原样归类。调用方只允许 ``== 'failed'`` / ``== 'succeeded'``。 + + Args: + raw_status: Job.status 原值。 + + Returns: + failed | succeeded | queued | running | 其它小写透传 | 空串。 + """ + status = str(raw_status or '').strip().lower() + if not status: + return '' + if status in JOB_FAILURE_STATUS_TOKENS: + return 'failed' + if status in JOB_SUCCESS_STATUS_TOKENS: + return 'succeeded' + if status == 'queued': + return 'queued' + if status in {'running', 'processing'}: + return 'running' + return status + + # 正式 OT 创建后不得再作为「当前人工阻断」的建单前 Gate。 _PRE_OT_BLOCKING_GATE_CODES: frozenset[str] = frozenset({ 'document_materialization', @@ -547,11 +579,11 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str **_job_fields(active), } - # [STEP 2] 最近 Job:failed/dead,或 success 但 OT 未推进。 + # [STEP 2] 最近 Job:failed,或 succeeded 但 OT 未推进。 if latest is not None: - latest_status = str(latest.status or '').strip().lower() + latest_outcome = project_job_status_outcome(getattr(latest, 'status', None)) fields = _job_fields(latest) - if latest_status in {'failed', 'dead'}: + if latest_outcome == 'failed': exhausted = _attempts_exhausted(latest) return { 'status': 'manual_fallback' if exhausted else 'failed', @@ -562,7 +594,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str 'reason_code': fields.get('error_code') or 'auto_progress_job_failed', **fields, } - if latest_status in {'succeeded', 'success', 'completed'}: + if latest_outcome == 'succeeded': # Job 标成功但 OT 仍 created:业务故障,不得伪装 waiting / 抹掉 job_id。 if progress_state in {'', 'not_started'}: exhausted = _attempts_exhausted(latest) @@ -663,7 +695,6 @@ def project_stage_for_task( from app.services.shipping_notice.upload_attempt_service import ( has_verified_upload_success, latest_export_artifact, - latest_upload_attempt, ) # 业务完成不能仅信任 Notice 的历史聚合字段。复核工作台必须与批次投影 @@ -672,7 +703,6 @@ def project_stage_for_task( if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None): owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task verified_upload_success = has_verified_upload_success(task) - raw_upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip().lower() if isinstance(owner, ShippingOrderTask): from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task @@ -707,7 +737,8 @@ def project_stage_for_task( # freight_uploading,只有三层成功事实齐备时才能覆盖为 completed。 if progress_state == 'uploaded': return _with_label('completed', source='notice_terminal') - if raw_upload_status in {'uploaded', 'succeeded', 'success'}: + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status + if project_notice_upload_status(task) == 'uploaded': return _with_label('freight_uploading', source='upload_success_unverified') # [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。 diff --git a/backend/app/services/shipping_notice/order_schema/derivation_engine.py b/backend/app/services/shipping_notice/order_schema/derivation_engine.py deleted file mode 100644 index 2ccc7613..00000000 --- a/backend/app/services/shipping_notice/order_schema/derivation_engine.py +++ /dev/null @@ -1,105 +0,0 @@ -""" -services/shipping_notice/order_schema/derivation_engine.py - -用途:执行 Schema 级字段派生规则(首期 copy_if_empty),供模拟与运行时共用。 -依赖:field_rules(规则归一化与 line_no 格式)、统一 ValidationError。 -逻辑:仅处理启用中的 line→line 规则;目标非空/来源空/格式非法时记录跳过原因; - 不写库;调用方负责持久化与审计。 -""" - -from __future__ import annotations - -from typing import Any - -from app.services.shipping_notice.order_schema.field_rules import ( - derivation_rules_checksum, - is_valid_line_no_value, - normalize_derivation_rules, -) - - -def apply_derivation_rules_to_lines( - lines: list[dict[str, Any]], - rules: list[dict[str, Any]] | None, - *, - locked_targets: set[tuple[int, str]] | None = None, -) -> dict[str, Any]: - """ - 对明细行集合执行派生规则,返回派生后行与逐行结果摘要。 - - 核心逻辑:仅启用规则生效;copy_if_empty 仅在目标为空时复制来源; - 目标已锁定(人工覆盖)时跳过;来源缺失或目标格式非法时跳过。 - - Args: - lines: 明细字段字典列表(按行可变副本由本函数新建)。 - rules: Schema definition_json.derivation_rules 或草稿规则。 - locked_targets: 可选 ``{(line_index, field_code)}`` 人工锁定集合。 - - Returns: - ``{lines, results, rules_checksum, derived_count, skipped_count}``; - ``results`` 每项含 line_index、rule_id、status(derived|skipped)、skip_reason、 - source/target 前后值。 - """ - normalized = normalize_derivation_rules(rules, adopted_line_field_codes=None) - checksum = derivation_rules_checksum(normalized) - enabled = [rule for rule in normalized if rule.get('enabled')] - output_lines = [dict(line) for line in lines] - results: list[dict[str, Any]] = [] - locks = locked_targets or set() - - for line_index, line in enumerate(output_lines): - for rule in enabled: - source_code = str(rule['source_field_code']) - target_code = str(rule['target_field_code']) - rule_id = str(rule['rule_id']) - before_target = line.get(target_code) - before_source = line.get(source_code) - entry: dict[str, Any] = { - 'line_index': line_index, - 'rule_id': rule_id, - 'source_field_code': source_code, - 'target_field_code': target_code, - 'strategy': rule['strategy'], - 'before_source': before_source, - 'before_target': before_target, - 'after_target': before_target, - 'status': 'skipped', - 'skip_reason': None, - } - if (line_index, target_code) in locks: - entry['skip_reason'] = 'manual_override_locked' - results.append(entry) - continue - if before_target not in (None, ''): - entry['skip_reason'] = 'target_not_empty' - results.append(entry) - continue - if before_source in (None, ''): - entry['skip_reason'] = 'source_empty' - results.append(entry) - continue - source_text = str(before_source).strip() - if target_code == 'line_no' and not is_valid_line_no_value(source_text): - entry['skip_reason'] = 'source_format_invalid' - results.append(entry) - continue - if rule['strategy'] != 'copy_if_empty': - entry['skip_reason'] = 'unsupported_strategy' - results.append(entry) - continue - line[target_code] = source_text - entry['after_target'] = source_text - entry['status'] = 'derived' - entry['skip_reason'] = None - results.append(entry) - - derived_count = sum(1 for item in results if item['status'] == 'derived') - skipped_count = sum(1 for item in results if item['status'] == 'skipped') - return { - 'lines': output_lines, - 'results': results, - 'rules': normalized, - 'rules_checksum': checksum, - 'derived_count': derived_count, - 'skipped_count': skipped_count, - } 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 02d42447..bc302e51 100644 --- a/backend/app/services/shipping_notice/order_schema/field_rules.py +++ b/backend/app/services/shipping_notice/order_schema/field_rules.py @@ -1,18 +1,15 @@ """ backend/app/services/shipping_notice/order_schema/field_rules.py -用途:执行冻结订单 Schema 的通用字段归一化、validator,以及 Schema 级字段派生规则契约校验。 +用途:执行冻结订单 Schema 的通用字段归一化和 validator。 依赖:标准库 Decimal/date、reservation_id 安全校验、统一 ValidationError。 逻辑:运行时传入完整字段配置;本模块不查询数据库,也不允许配置绕过 Reservation ID 安全规则; Header/Line Reservation 均可选,有效值由行优先回退头计算; - 单价等字段必须已经由显式视觉框或拆分规则提供单值;derivation_rules 仅允许 line→line。 + 单价等字段必须已经由显式视觉框或拆分规则提供单值;订单项次由系统按单据内顺序生成。 """ from __future__ import annotations -import hashlib -import json -import re from datetime import date, datetime from decimal import Decimal, InvalidOperation from typing import Any @@ -20,11 +17,7 @@ from typing import Any from app.core.errors import ValidationError from app.services.shipping_notice.reservation_id import validated_reservation_id -# Phase 0/1 派生规则契约常量。 -DERIVATION_STRATEGIES = frozenset({'copy_if_empty'}) -DERIVATION_ALLOWED_TARGETS = frozenset({'line_no'}) -DERIVATION_LINE_NO_PATTERN = re.compile(r'^\d{1,6}$') -DEFAULT_DERIVATION_RULE_ID = 'R-LINE-NO-FROM-CUSTOMER-PO' +# 硬切换后不再提供 Schema 派生规则;订单项次由系统按单据顺序生成。 def compute_effective_reservation_id( @@ -52,155 +45,6 @@ def compute_effective_reservation_id( ) -def default_derivation_rules() -> list[dict[str, Any]]: - """ - 返回新草稿默认派生规则(关闭状态)。 - - 核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False, - 避免未评审规则自动改写内部项次。 - - Returns: - 可写入 definition_json.derivation_rules 的规则列表。 - """ - return [{ - 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': False, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }] - - -def derivation_rules_checksum(rules: list[dict[str, Any]]) -> str: - """ - 计算派生规则稳定校验和,供发布冻结与审计引用。 - - Args: - rules: 已归一化的派生规则列表。 - - Returns: - SHA-256 hex 摘要。 - """ - payload = json.dumps(rules, ensure_ascii=False, sort_keys=True, separators=(',', ':')) - return hashlib.sha256(payload.encode('utf-8')).hexdigest() - - -def normalize_derivation_rules( - value: Any, - *, - adopted_line_field_codes: set[str] | None = None, -) -> list[dict[str, Any]]: - """ - 归一化并校验 Schema definition_json.derivation_rules。 - - 核心逻辑:仅允许 line→line;首期策略仅 copy_if_empty;目标仅 line_no; - 禁止自引用;同一启用目标只允许一条规则;来源/目标须属于已采用明细字段(若提供)。 - - Args: - value: 原始 derivation_rules(None 时返回默认关闭预置)。 - adopted_line_field_codes: 当前草稿已采用的明细 field_code 集合;None 表示跳过采用检查。 - - Returns: - 归一化后的规则列表。 - - Raises: - ValidationError: 结构、策略、循环或竞争冲突。 - """ - if value is None: - return default_derivation_rules() - if not isinstance(value, list): - raise ValidationError( - 'derivation_rules must be a list', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - ) - normalized: list[dict[str, Any]] = [] - enabled_targets: set[str] = set() - for index, raw in enumerate(value): - if not isinstance(raw, dict): - raise ValidationError( - 'derivation rule must be an object', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'index': index}, - ) - rule_id = str(raw.get('rule_id') or '').strip() or f'R-DERIVE-{index + 1}' - enabled = raw.get('enabled', False) - if not isinstance(enabled, bool): - raise ValidationError( - 'derivation rule enabled must be boolean', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id}, - ) - source = str(raw.get('source_field_code') or '').strip() - target = str(raw.get('target_field_code') or '').strip() - strategy = str(raw.get('strategy') or '').strip() - scope = str(raw.get('scope') or 'line').strip() - if scope != 'line': - raise ValidationError( - 'derivation rules only allow line scope', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id}, - ) - if strategy not in DERIVATION_STRATEGIES: - raise ValidationError( - 'unsupported derivation strategy', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id, 'strategy': strategy}, - ) - if target not in DERIVATION_ALLOWED_TARGETS: - raise ValidationError( - 'derivation target is not allowed in this phase', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id, 'target_field_code': target}, - ) - if not source or source == target: - raise ValidationError( - 'derivation source/target must differ and be non-empty', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id}, - ) - if adopted_line_field_codes is not None: - missing = {code for code in (source, target) if code not in adopted_line_field_codes} - if missing: - raise ValidationError( - 'derivation fields must be adopted line fields', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'rule_id': rule_id, 'missing_field_codes': sorted(missing)}, - ) - if enabled and target in enabled_targets: - raise ValidationError( - 'only one enabled derivation rule is allowed per target', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID', - details={'target_field_code': target}, - ) - if enabled: - enabled_targets.add(target) - normalized.append({ - 'rule_id': rule_id, - 'enabled': enabled, - 'source_field_code': source, - 'target_field_code': target, - 'strategy': strategy, - 'scope': scope, - }) - return normalized - - -def is_valid_line_no_value(value: Any) -> bool: - """ - 校验内部项次格式:1–6 位数字,保留前导零。 - - Args: - value: 候选内部项次。 - - Returns: - 是否符合契约。 - """ - if value in (None, ''): - return False - return bool(DERIVATION_LINE_NO_PATTERN.fullmatch(str(value).strip())) - - def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any: """按冻结字段类型解析候选值,同时保留原始文本大小写。 @@ -267,8 +111,6 @@ def validate_order_field_value(value: Any, config: dict[str, Any]) -> bool: field_code = str(config.get('field_code') or '') if field_code == 'reservation_id' and value not in (None, '') and not validated_reservation_id(value): return False - if field_code == 'line_no' and value not in (None, '') and not is_valid_line_no_value(value): - return False for key in config.get('validator_keys') or []: if key == 'non_empty' and value in (None, ''): return False diff --git a/backend/app/services/shipping_notice/order_schema/runtime.py b/backend/app/services/shipping_notice/order_schema/runtime.py index 3ff40227..25b5115f 100644 --- a/backend/app/services/shipping_notice/order_schema/runtime.py +++ b/backend/app/services/shipping_notice/order_schema/runtime.py @@ -3,15 +3,15 @@ backend/app/services/shipping_notice/order_schema/runtime.py 用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。 依赖:订单 Schema 动态模型、standard_field_registry、ShippingOrderDocument、registry、 - derivation_engine、audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)、 + audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)、 pdf_priority_adjudication(阶段 2 PDF 优先冲突裁决)。 -逻辑:提交时先验证原文证据和字段规则并投影;再执行 Schema 派生并落库 FieldValue; +逻辑:提交时先验证原文证据和字段规则并投影;内部项次由系统按行顺序生成; Observation.source_type 按主 PDF / 其他 PDF / Excel / Word / 正文区分; 跨来源冲突时先尝试 PDF_PRIORITY_FIELD_POLICIES,未命中再回退 prefer_attachment/email; Decision.selected_observation_id 对齐最终选中 Observation,禁止固定取第一条; 仅 required 或 auto_create_key_field 字段可进入 blocked_fields; 可选非关键字段证据不足只生成 diagnostic Finding,不阻断建单; - 必填门禁仅在派生后按最终投影判定; + 必填门禁按最终投影判定; published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。 """ @@ -43,13 +43,11 @@ from app.services.shipping_notice.context_fields.runtime import ( canonical_mail_context, persist_deterministic_context_fields, ) -from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches from app.services.shipping_notice.order_schema.field_rules import ( compute_effective_reservation_id, normalize_order_field_value, validate_order_field_value, ) -from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.pdf_priority_adjudication import choose_pdf_priority_value @@ -413,11 +411,19 @@ def _verified_email_supplement_observation( def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool: - """只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。""" + """ + 只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。 + + anchor_bbox 仅锚点定位字段携带;模板固定值区字段(无锚点标签)由解析器合法返回 + None,其冻结 value_bbox + 字符索引已是完整取值证据,不得因缺锚点丢弃观测, + 否则账款客户/地址等固定区头字段永远无法落库,下游客户识别将空转。 + """ + anchor_bbox = raw.get('anchor_bbox') return ( str(raw.get('source') or '') == 'pdf_coordinate' and isinstance(raw.get('page_no'), int) and raw['page_no'] >= 1 - and isinstance(raw.get('anchor_bbox'), dict) and isinstance(raw.get('value_bbox'), dict) + and (anchor_bbox is None or isinstance(anchor_bbox, dict)) + and isinstance(raw.get('value_bbox'), dict) and isinstance(raw.get('glyph_indices'), list) and bool(raw['glyph_indices']) ) @@ -946,7 +952,7 @@ def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) - return result -def _persist_derived_line_field( +'''# Disabled legacy derivation helpers intentionally retained as inert source text. *, extraction: ShippingOrderExtraction, line: ShippingOrderLine, @@ -1034,7 +1040,6 @@ def _persist_derived_line_field( 'value': payload, 'reason_code': 'derived', 'rule_id': rule_id, - 'derivation_rules_checksum': rules_checksum, 'observation_ids': [], 'confidence': 1.0, } @@ -1104,6 +1109,7 @@ def _derivation_evidence_refs( return refs +''' def persist_dynamic_order( *, raw_order: dict[str, Any], @@ -1132,9 +1138,12 @@ def persist_dynamic_order( str(item['field_id']): item for item in (version.definition_json or {}).get('fields') or [] if item.get('enabled', True) } + # line_no 是系统生成且只读的订单项次,不是解析出来的业务字段:不进 llm 字段裁决, + # 不落 FieldValue/Decision,只在 ShippingOrderLine.line_no 与 system_line_projections 体现。 configs = { field_id: item for field_id, item in all_configs.items() if item.get('collection_mode', 'llm_extraction') == 'llm_extraction' + and str(item.get('field_code') or '').strip() != 'line_no' } context_configs = [ item for item in all_configs.values() @@ -1196,7 +1205,8 @@ def persist_dynamic_order( line = ShippingOrderLine( extraction_id=extraction.id, position=position, - line_key=str(uuid.uuid4()), + line_no=position + 1, + draft_line_id=str(uuid.uuid4()), ) db.session.add(line) db.session.flush() @@ -1282,79 +1292,19 @@ def persist_dynamic_order( owning_gate_code='order_field_extraction', )) - # [STEP 3] Schema 派生规则:仅补齐空目标;成功后落库 FieldValue,供冻结/Excel 读取。 - derivation_outcome = apply_derivation_rules_to_lines( - line_projections, - (version.definition_json or {}).get('derivation_rules'), - ) - line_projections = derivation_outcome['lines'] + # [STEP 3] 内部项次由系统按解析行顺序生成;不读取或执行任何派生规则。 field_lineage: list[dict[str, Any]] = [] - for item in derivation_outcome['results']: - line_index = int(item['line_index']) - line_obj = extraction.lines[line_index] if line_index < len(extraction.lines) else None - lineage_row = { - 'line_key': line_obj.line_key if line_obj is not None else None, - 'field_code': item['target_field_code'], - 'value_source': 'derived' if item['status'] == 'derived' else 'skipped', - 'rule_id': item['rule_id'], - 'rule_checksum': derivation_outcome['rules_checksum'], - 'skip_reason': item.get('skip_reason'), - 'before_value': item.get('before_target'), - 'after_value': item.get('after_target'), - 'source_field_code': item.get('source_field_code'), - 'source_value': item.get('before_source'), - } - field_lineage.append(lineage_row) - if item['status'] == 'derived' and line_obj is not None: - target_config = _config_by_line_field_code(all_configs, str(item['target_field_code'])) - if target_config is not None and item.get('after_target') not in (None, ''): - decisions.append(_persist_derived_line_field( - extraction=extraction, - line=line_obj, - config=target_config, - value=item.get('after_target'), - rule_id=str(item['rule_id']), - rules_checksum=str(derivation_outcome['rules_checksum']), - )) - event_type = 'FIELD_DERIVED' if item['status'] == 'derived' else 'FIELD_DERIVATION_SKIPPED' - evidence_refs = _derivation_evidence_refs( - extraction_id=int(extraction.id), - line_id=int(line_obj.id) if line_obj is not None else None, - source_field_code=str(item.get('source_field_code') or '') or None, - all_configs=all_configs, - ) - append_shipping_audit_event( - event_type=event_type, - aggregate_type='shipping_order_extraction', - aggregate_id=str(extraction.id), - intake_no=getattr(intake, 'intake_no', None), - actor_type='system', - actor_id='derivation_engine', - action='derive_line_field', - result='success' if item['status'] == 'derived' else 'ignored', - reason_code=item.get('skip_reason'), - evidence_refs=evidence_refs or None, - metadata={ - 'rule_id': item['rule_id'], - 'derivation_rules_checksum': derivation_outcome['rules_checksum'], - 'field_code': item['target_field_code'], - 'line_key': lineage_row['line_key'], - 'source_field_code': item.get('source_field_code'), - 'skip_reason': item.get('skip_reason'), - 'schema_version_id': version.id, - }, - before={'previous_value': item.get('before_target'), 'value_source': 'machine'}, - after={ - 'new_value': item.get('after_target'), - 'value_source': 'derived' if item['status'] == 'derived' else 'skipped', - }, - ) - # [STEP 4] 关键字段完整性仅在派生之后按最终投影检查,避免派生刚补齐的必填项仍被误拦。 + # [STEP 4] 关键字段完整性按最终投影检查。 for config in all_configs.values(): if not field_may_block_process(config): continue code = str(config['field_code']) + # line_no 是系统生成且只读的订单项次(写入 ShippingOrderLine.line_no,并经 + # system_line_projections 输出);业务行投影不重复携带它,因此不得用“required + # 但业务投影缺失”把这一系统字段误判为缺失阻断。 + if code == 'line_no': + continue missing = False if config['scope'] == 'header' and code not in header: missing = True @@ -1405,11 +1355,12 @@ def persist_dynamic_order( 'blocks_current_action': str(code) in blocking_codes, }) - # 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。 + # 行级辅助投影:输出草稿身份、系统项次与有效 Reservation。 system_line_projections: list[dict[str, Any]] = [] for line, projection in zip(extraction.lines, line_projections): system_line_projections.append({ - 'line_key': line.line_key, + 'draft_line_id': line.draft_line_id, + 'line_no': int(line.line_no), 'effective_reservation_id': compute_effective_reservation_id( line_reservation_id=projection.get('reservation_id'), header_reservation_id=header.get('reservation_id'), @@ -1437,7 +1388,6 @@ def persist_dynamic_order( 'header': header, 'lines': line_projections, 'field_lineage': field_lineage, - 'derivation_rules_checksum': derivation_outcome['rules_checksum'], } extraction.validation_result_json = { 'blocked_fields': blocked_unique, @@ -1447,19 +1397,16 @@ def persist_dynamic_order( extraction.status = 'needs_review' if blocked_unique else 'accepted' extraction.updated_at = datetime.utcnow() db.session.flush() - customer_matches = refresh_order_customer_matches(extraction, header) return { 'extraction': extraction, 'header': header, 'lines': line_projections, 'system_line_projections': system_line_projections, 'field_lineage': field_lineage, - 'derivation_rules_checksum': derivation_outcome['rules_checksum'], 'blocked_fields': blocked_unique, 'findings': deduped_findings, 'observations': observations, 'decisions': decisions, - 'customer_matches': customer_matches, 'auto_create_key_field_thresholds': { str(item['field_code']): float(item['minimum_confidence']) for item in all_configs.values() diff --git a/backend/app/services/shipping_notice/order_schema/service.py b/backend/app/services/shipping_notice/order_schema/service.py index f6ade775..95ae4a3e 100644 --- a/backend/app/services/shipping_notice/order_schema/service.py +++ b/backend/app/services/shipping_notice/order_schema/service.py @@ -3,8 +3,8 @@ backend/app/services/shipping_notice/order_schema/service.py 用途:管理唯一发货订单 Schema 的版本采用/发布与追加式配置审计;字段资产生命周期委托 field_asset_service。 依赖:db、订单 Schema 模型、standard_field_registry、field_asset_service、field_rules、registry、统一 AppError。 -逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy、derivation_rules、 - task_edit_policy);乐观锁阻止覆盖;发布冻结快照并追加审计事件。 +逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy、task_edit_policy); + 乐观锁阻止覆盖;发布冻结快照并追加审计事件。 """ from __future__ import annotations @@ -68,12 +68,6 @@ from app.services.shipping_notice.order_schema.registry import ( from app.services.shipping_notice.order_schema.compatibility import compare_profile_schema from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.order_schema.diff import compare_definitions -from app.services.shipping_notice.order_schema.field_rules import ( - default_derivation_rules, - derivation_rules_checksum, - normalize_derivation_rules, -) -from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines from app.services.shipping_notice.audit_service import append_shipping_audit_event SCHEMA_CODE = DEFAULT_SCHEMA_FAMILY_CODE @@ -836,7 +830,7 @@ def get_extraction_audit(extraction_id: int) -> dict[str, Any]: 'raw_llm_output': _copy_json(extraction.raw_llm_output_json), 'normalized_result': _copy_json(extraction.normalized_result_json), 'validation_result': _copy_json(extraction.validation_result_json), - 'lines': [{'id': row.id, 'position': row.position, 'line_key': row.line_key} for row in lines], + 'lines': [{'id': row.id, 'position': row.position, 'draft_line_id': row.draft_line_id} for row in lines], 'observations': [ identity(row.field_id) | { 'id': row.id, 'line_id': row.line_id, 'source_document_id': row.source_document_id, @@ -1018,12 +1012,6 @@ def create_draft( definition if source else None, fallback=schema.auto_creation_policy_json, ) - # [STEP] 派生规则:复制来源时归一化;全新草稿预置关闭状态的默认规则。 - definition['derivation_rules'] = normalize_derivation_rules( - definition.get('derivation_rules') if source else None, - adopted_line_field_codes=None, - ) - definition['derivation_rules_checksum'] = derivation_rules_checksum(definition['derivation_rules']) version = ShippingOrderSchemaVersion( schema_id=schema.id, version=next_version, @@ -1123,6 +1111,23 @@ def save_draft( raise ValidationError('fields must be a list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') before = _definition(version) ensure_standard_assets_seeded(actor_id=actor_id) + # line_no 是系统项次字段:调用方无需提交配置,服务端始终将其纳入 Schema。 + line_no_asset = ShippingOrderField.query.filter_by( + field_code='line_no', scope='line', asset_kind='system_standard', status='active', + ).one() + if not any( + isinstance(item, dict) and str(item.get('field_id') or '') == str(line_no_asset.id) + for item in configs + ): + configs = [*configs, { + 'field_id': str(line_no_asset.id), + 'enabled': True, + 'display_name': line_no_asset.display_name_default or '内部项次', + 'required': True, + 'normalizer_key': 'integer', + 'comparator_key': 'integer', + 'validator_keys': ['positive_integer'], + }] seen: set[str] = set() enabled_purposes: set[str] = set() normalized_fields: list[dict[str, Any]] = [] @@ -1241,34 +1246,36 @@ def save_draft( 'on_revalidation_failure': sanitized['on_revalidation_failure'], } normalized_fields.append(field_entry) + # line_no 是订单项次系统字段:Schema 必须包含且启用为必填,但不得开放人工编辑或派生配置。 + line_no_entries = [item for item in normalized_fields if item.get('field_code') == 'line_no' and item.get('scope') == 'line'] + if len(line_no_entries) != 1: + raise ValidationError( + 'line_no is required exactly once in schema fields', + code='SHIPPING.ORDER_SCHEMA_LINE_NO_REQUIRED', + ) + line_no_entry = line_no_entries[0] + line_no_entry['enabled'] = True + line_no_entry['required'] = True + line_no_entry['auto_create_key_field'] = False + line_no_entry['aliases'] = [] + line_no_entry['extraction_instruction'] = None + line_no_entry['task_edit_policy'] = { + 'editable': False, + 'editable_until': None, + 'change_effect': 'none', + 'on_revalidation_failure': 'block', + } if 'auto_creation_policy' in data: auto_creation_policy = _auto_creation_policy(data.get('auto_creation_policy')) else: auto_creation_policy = _resolve_auto_creation_policy_for_definition( before, fallback=version.schema.auto_creation_policy_json, ) - adopted_line_codes = { - str(item.get('field_code')) - for item in normalized_fields - if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line' - } - # 保存时未传 derivation_rules 则保留草稿既有规则;缺省时回退关闭预置。 - raw_derivation_rules = data['derivation_rules'] if 'derivation_rules' in data else before.get('derivation_rules') - derivation_rules = normalize_derivation_rules( - raw_derivation_rules if raw_derivation_rules is not None else default_derivation_rules(), - adopted_line_field_codes=adopted_line_codes if any( - rule.get('enabled') for rule in ( - raw_derivation_rules if isinstance(raw_derivation_rules, list) else default_derivation_rules() - ) - ) else None, - ) after = { 'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields, 'auto_creation_policy': auto_creation_policy, - 'derivation_rules': derivation_rules, - 'derivation_rules_checksum': derivation_rules_checksum(derivation_rules), } compile_table_header_contract(after) version.definition_json = after @@ -1334,21 +1341,6 @@ def publish( enabled_configs = _enabled_fields(definition) if not enabled_configs: raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') - # [STEP] 发布前再次归一化派生规则;启用中的规则要求来源/目标已采用。 - adopted_line_codes = { - str(item.get('field_code')) - for item in enabled_configs - if item.get('scope') == 'line' and item.get('field_code') - } - derivation_rules = normalize_derivation_rules( - definition.get('derivation_rules'), - adopted_line_field_codes=adopted_line_codes if any( - isinstance(rule, dict) and rule.get('enabled') - for rule in (definition.get('derivation_rules') or []) - ) else None, - ) - definition['derivation_rules'] = derivation_rules - definition['derivation_rules_checksum'] = derivation_rules_checksum(derivation_rules) version.definition_json = definition included_field_ids = {str(config.get('field_id')) for config in enabled_configs} previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first() @@ -1470,134 +1462,11 @@ def simulate_derivation( actor_id: int | None, request_id: str | None = None, ) -> dict[str, Any]: - """ - 对草稿或已发布 Schema 版本的派生规则做只读样本模拟。 - - 核心逻辑:优先使用请求体 derivation_rules,否则读版本 definition; - lines 可直接提交,或通过 sample_ref=`extraction:` 从历史 Extraction 加载明细投影; - 模拟前仅对历史 Extraction 样本剔除规则目标字段,避免已派生结果恒跳过; - 手工 JSON 保留目标字段以真实评估 copy_if_empty; - 写入 DERIVATION_SIMULATED 审计(不 commit),不改订单。 - - Args: - version_id: Schema 版本 ID。 - data: 含 lines 或 sample_ref(extraction:)、可选 derivation_rules。 - actor_id: 管理员 ID。 - request_id: 请求追踪 ID。 - - Returns: - 模拟结果摘要与逐行结果。 - - Raises: - ValidationError: lines / sample_ref 非法。 - NotFoundError: 版本或 Extraction 不存在。 - """ - from app.models import ShippingOrderExtraction - - _, version = _resolve_schema_for_version(version_id) - sample_ref = str(data.get('sample_ref') or '').strip() or None - raw_lines = data.get('lines') - sample_source: dict[str, Any] | None = None - - # [STEP] 支持可追溯样本:extraction: → normalized_result_json.lines - # 历史样本可能已含派生后的目标字段;模拟前剔除规则目标,避免 copy_if_empty 恒跳过。 - if sample_ref and sample_ref.startswith('extraction:'): - try: - extraction_id = int(sample_ref.split(':', 1)[1]) - except (TypeError, ValueError) as exc: - raise ValidationError( - 'sample_ref extraction id is invalid', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_INVALID', - ) from exc - extraction = db.session.get(ShippingOrderExtraction, extraction_id) - if extraction is None: - raise NotFoundError( - 'Derivation sample extraction not found', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_NOT_FOUND', - ) - normalized = extraction.normalized_result_json if isinstance(extraction.normalized_result_json, dict) else {} - loaded = list(normalized.get('lines') or []) - if not loaded or any(not isinstance(item, dict) for item in loaded): - raise ValidationError( - 'extraction sample has no usable line projections', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_EMPTY', - ) - raw_lines = loaded - sample_source = { - 'kind': 'extraction', - 'extraction_id': int(extraction.id), - 'schema_version_id': int(extraction.schema_version_id), - 'intake_id': int(extraction.intake_id), - 'status': extraction.status, - 'targets_stripped_for_simulate': True, - } - - if not isinstance(raw_lines, list) or any(not isinstance(item, dict) for item in raw_lines): - raise ValidationError( - 'lines must be a list of objects (or provide sample_ref=extraction:)', - code='SHIPPING.ORDER_SCHEMA_DERIVATION_SIMULATE_INVALID', - ) - definition = _definition(version) - rules = data.get('derivation_rules') if 'derivation_rules' in data else definition.get('derivation_rules') - normalized_rules = normalize_derivation_rules(rules if isinstance(rules, list) else None) - # 仅历史 Extraction 样本剔除目标字段;手工 JSON 保留原值以真实评估 copy_if_empty。 - strip_targets = bool(sample_source and sample_source.get('targets_stripped_for_simulate')) - if strip_targets: - target_codes = { - str(rule.get('target_field_code') or '') - for rule in normalized_rules - if rule.get('target_field_code') - } - simulate_lines = [] - for line in raw_lines: - cleaned = dict(line) - for code in target_codes: - cleaned.pop(code, None) - simulate_lines.append(cleaned) - else: - simulate_lines = [dict(line) for line in raw_lines] - outcome = apply_derivation_rules_to_lines(simulate_lines, normalized_rules) - append_shipping_audit_event( - event_type='DERIVATION_SIMULATED', - aggregate_type='shipping_order_schema_version', - aggregate_id=str(version.id), - actor_type='admin', - actor_id=actor_id, - request_id=request_id, - action='simulate_derivation', - result='success', - metadata={ - 'schema_version': version.version, - 'schema_version_status': version.status, - 'derivation_rules_checksum': outcome['rules_checksum'], - 'derived_count': outcome['derived_count'], - 'skipped_count': outcome['skipped_count'], - 'sample_ref': sample_ref, - 'sample_source': sample_source, - 'line_count': len(raw_lines), - }, - after={ - 'derivation_rules_checksum': outcome['rules_checksum'], - 'derived_count': outcome['derived_count'], - 'skipped_count': outcome['skipped_count'], - 'sample_ref': sample_ref, - }, + """派生规则已硬切换下线;项次由系统生成,接口统一返回业务错误。""" + raise ValidationError( + 'Schema derivation is disabled; line_no is system-generated', + code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED', ) - # 不在此 commit:由路由层统一提交,便于与样本读取等审计同事务。 - return { - 'schema_version_id': version.id, - 'schema_version': version.version, - 'schema_version_status': version.status, - 'rules_checksum': outcome['rules_checksum'], - 'rules': outcome['rules'], - 'derived_count': outcome['derived_count'], - 'skipped_count': outcome['skipped_count'], - 'results': outcome['results'], - 'lines_after': outcome['lines'], - 'sample_ref': sample_ref, - 'sample_source': sample_source, - 'mutates_orders': False, - } def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]: @@ -1637,4 +1506,4 @@ def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]: }) if len(items) >= capped: break - return {'items': items} \ No newline at end of file + return {'items': items} diff --git a/backend/app/services/shipping_notice/order_schema/table_contract.py b/backend/app/services/shipping_notice/order_schema/table_contract.py index 17426ac1..3ac40619 100644 --- a/backend/app/services/shipping_notice/order_schema/table_contract.py +++ b/backend/app/services/shipping_notice/order_schema/table_contract.py @@ -18,7 +18,7 @@ from app.core.errors import ValidationError TABLE_FIELD_CODES = frozenset({ - 'line_no', 'reservation_id', 'part_number', 'product_revision', 'customer_part_number', + 'reservation_id', 'part_number', 'product_revision', 'customer_part_number', 'customer_po_line_no', 'product_feature', 'qty', 'uom', 'reference_qty', 'reference_uom', 'pricing_qty', 'pricing_uom', 'required_date', 'requested_receipt_date', 'unit_price', 'line_amount_before_tax', 'line_tax_amount', 'line_amount_with_tax', 'tax_category', 'tax_rate', @@ -36,10 +36,16 @@ class TableHeaderContract: def normalize_table_header(value: Any) -> str: - """以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。""" - # Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are - # distinct configured labels, so a permissive match cannot silently bind a column. + """以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。 + + Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are + distinct configured labels, so a permissive match cannot silently bind a column. + 额外把 camelCase 相邻词拆出空格(``manufacturerPN`` -> ``manufacturer PN``), + 使真实邮件/PDF 表头 ``manufacturerPN`` 能命中 Schema 的 ``Manufacturer PN`` 别名。 + """ text = unicodedata.normalize('NFKC', str(value or '')).strip() + # 在「小写/数字 后紧接大写」的边界插入空格,处理无分隔符的驼峰表头。 + text = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", ' ', text) text = re.sub(r"[^\w\u4e00-\u9fff]+", ' ', text, flags=re.UNICODE) return re.sub(r'[_\s]+', ' ', text).strip() 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 16c3bbf8..67335308 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 @@ -474,10 +474,16 @@ def ensure_stp_auto_create_for_case( ), } - # [STEP] failed/dead 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。 + # [STEP] failed 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。 + from app.services.shipping_notice.order_review_workbench_projection import ( + project_job_status_outcome, + ) latest = find_latest_stp_job(business_ref=idempotency_key) retry_of_job_id = None - if latest is not None and str(latest.status or '') in {'failed', 'dead', 'cancelled'}: + latest_status = str(getattr(latest, 'status', None) or '').strip().lower() if latest is not None else '' + if latest is not None and ( + project_job_status_outcome(latest_status) == 'failed' or latest_status == 'cancelled' + ): retry_of_job_id = int(latest.id) elif force_retry and latest is not None: retry_of_job_id = int(latest.id) diff --git a/backend/app/services/shipping_notice/post_ot_wave_progress_service.py b/backend/app/services/shipping_notice/post_ot_wave_progress_service.py index 122d6ae3..ea8e3fae 100644 --- a/backend/app/services/shipping_notice/post_ot_wave_progress_service.py +++ b/backend/app/services/shipping_notice/post_ot_wave_progress_service.py @@ -34,7 +34,7 @@ def schedule_post_ot_wave_progress( *, task_no: str, wave_no: int | None, - line_keys: list[str], + snapshot_line_ids: list[int], review_case_id: int | None = None, idempotency_row_id: int | None = None, request_idempotency_key: str | None = None, @@ -49,7 +49,7 @@ def schedule_post_ot_wave_progress( Args: task_no: 正式 OT 编号。 wave_no: 本波次号;可为 None(仅跳过行时)。 - line_keys: 本波行键。 + snapshot_line_ids: 本波冻结订单行 ID。 review_case_id: 复核 Case id。 idempotency_row_id: wave 幂等行 id(用于回写 progress_*)。 request_idempotency_key: 原始 wave 请求幂等键。 @@ -61,7 +61,7 @@ def schedule_post_ot_wave_progress( """ _ = created_by_id normalized = str(task_no or '').strip().upper() - keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] + ids = [int(k) for k in (snapshot_line_ids or [])] if not normalized: return { 'auto_progress_started': False, @@ -69,7 +69,7 @@ def schedule_post_ot_wave_progress( 'reason': 'missing_task_no', 'wave_no': wave_no, } - if wave_no is None and not keys: + if wave_no is None and not ids: return { 'auto_progress_started': False, 'status': 'skipped', @@ -105,7 +105,7 @@ def schedule_post_ot_wave_progress( { 'task_no': normalized, 'wave_no': int(wave_no) if wave_no is not None else None, - 'line_keys': keys, + 'snapshot_line_ids': ids, 'review_case_id': int(review_case_id) if review_case_id is not None else None, 'idempotency_row_id': int(idempotency_row_id) if idempotency_row_id is not None else None, 'progress_idempotency_key': progress_key, @@ -143,7 +143,7 @@ def schedule_post_ot_wave_progress( 'progress_status': 'scheduled' if job_id is not None else 'failed', 'progress_job_id': int(job_id) if job_id is not None else None, 'progress_idempotency_key': progress_key, - 'line_keys': keys, + 'snapshot_line_ids': ids, } diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index c1caa52b..048ed292 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -10,7 +10,9 @@ services/shipping_notice/process_gate_bridge.py co8 后仅按 review_case_id / task_id 创建 Execution,不再依赖 WorkflowItem; 复核草稿经 sync_review_gate_for_case 同步客户/Reservation/库存路由等 findings.details; 确认建单后 sync_execution_after_review_confirm:多波次不覆盖首波 Task 绑定; - 禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code。 + 禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code; + 建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_inventory_preparation + 供 ensure_inventory(复用未过期快照或触发 RPA)。 """ from __future__ import annotations @@ -21,6 +23,7 @@ import logging from datetime import datetime from typing import Any +from app import db from app.models import ( ShippingOrderReviewCase, ShippingOrderCandidate, @@ -964,6 +967,7 @@ def sync_fulfillment_gates_from_task( 按 ShippingNotice 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。 核心逻辑:将库存、匹配、上传等领域事实投影为 Gate 结果; + 建单后尚无库存行时不投影假失败,只露出 retry_inventory_preparation 供自动取数; RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断 manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。 由 auto_progress 与 Gate 恢复执行器在履约动作后调用。 @@ -1183,6 +1187,35 @@ def sync_fulfillment_gates_from_task( force=True, ) return + # [STEP 2B] 建单后尚无库存事实(derived=created)时,禁止把「未取数」投影成 + # inventory_file_empty 失败。应保留 pending 并露出 Worker 动作,由 + # submit_auto_progress → ensure_inventory:先复用未过期快照,否则触发 RPA。 + if not has_inventory_lines and status == 'created': + prep_gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id), gate_code='inventory_preparation') + .first() + ) + if prep_gate is not None and str(prep_gate.status or '').strip().lower() in { + 'pending', 'queued', 'running', + }: + if not str(prep_gate.next_action_code or '').strip(): + from app.services.shipping_notice.process_gate_contract import ( + primary_next_action_for_gate, + ) + prep_gate.next_action_code = ( + primary_next_action_for_gate( + gate_code='inventory_preparation', + status='blocked_retryable', + ) + or 'retry_inventory_preparation' + ) + prep_gate.updated_at = datetime.utcnow() + from app.services.shipping_notice.process_gate_service import ( + _refresh_execution_pointers, + ) + _refresh_execution_pointers(execution) + return # 库存准备的成功事实只能是已验证并绑定的库存行。下游状态可能因历史脏数据、 # 并发投影或错误侧路动作残留,绝不能反向证明库存文件已经准备完成。 inv_prep_passed = has_inventory_lines diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 30cd8b6d..d02ba303 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -3,12 +3,14 @@ services/shipping_notice/process_gate_contract.py 用途:冻结货代发货通知全链路业务门禁(Gate)契约:编码、状态、恢复动作、 阻断原因、责任方、Finding 严重级别、原因码唯一归属与字段阻断资格; + 以及 Gate→粗分类/位置/待办(derive_*); 作为 Execution/Gate/Attempt 与前后端类型的唯一代码源。 依赖:无外部 IO;被 process_gate_dependency、领域服务、API、前端类型与文档引用; 细粒度错误可解释性分层码见 error_explainability_contract。 逻辑:本模块只冻结名称与规则,不执行业务;后续阶段接线时禁止前端或 Job 私自发明门禁码; 同一根因只允许一个 owning_gate 产生用户阻断 Finding; - 单源不可用明细(source_disabled 等)不得写入本模块 owning_gate,避免与行级阻断混层。 + 单源不可用明细(source_disabled 等)不得写入本模块 owning_gate,避免与行级阻断混层; + derive_user_mode / derive_position / derive_todo_category 供进度早停、待办与摘要消费。 """ from __future__ import annotations @@ -1306,6 +1308,89 @@ def user_mode_for_blocking_reason(reason_code: str | None) -> str | None: return BLOCKING_REASON_TO_USER_MODE.get(str(reason_code).strip()) +# review_status 人工复核处置 → must_human(在 auto_continue 默认之前) +_REVIEW_STATUS_MUST_HUMAN: Final[frozenset[str]] = frozenset({ + 'parse_review', + 'rsv_req', + 'quality_issue', + 'customer_review', + 'shortage_review', +}) + + +def derive_user_mode( + *, + user_status: str | None, + gate_code: str | None, + review_status: str | None, + lifecycle_stage: str | None, +) -> str: + """ + 粗分类(auto_continue / must_human / wait_manual_upload / complete)。 + + 用途:从 Gate user_status/gate_code 与 review_status 推导用户模式;不投影领域标量。 + 核心逻辑:rejected→complete;复核处置(parse_review/rsv_req/quality_issue/ + customer_review/shortage_review)→must_human;再按 Gate/user_status 分支。 + """ + rs = str(review_status or '').strip() + if rs == 'rejected': + return 'complete' + if rs in _REVIEW_STATUS_MUST_HUMAN: + return 'must_human' + if str(user_status or '').strip() == 'completed': + return 'complete' + code = str(gate_code or '').strip() + stage = str(lifecycle_stage or '').strip() + status = str(user_status or '').strip() + if code == 'manual_upload_handoff' or ( + stage in {'freight_upload', 'upload_complete'} and status == 'waiting_human' + ): + return 'wait_manual_upload' + if status == 'waiting_human': + return 'must_human' + return 'auto_continue' + + +def derive_position(*, gate_code: str | None, review_status: str | None) -> str | None: + """ + 位置标签(与 POSITION_* / 文案表 key 对齐),供待办/用户态/阶段摘要消费。 + + 用途:复核处置优先读 review_status;履约位置读 current_gate_code。 + """ + rs = str(review_status or '').strip() + if rs in {'rejected', 'parse_review', 'rsv_req', 'quality_issue', 'customer_review'}: + return rs + mapping = { + 'order_field_extraction': 'parse_review', + 'customer_resolution': 'customer_review', + 'reservation_validation': 'rsv_req', + 'inventory_preparation': 'inventory_pending', + 'inventory_matching': 'ready_to_match', + 'inventory_sufficiency': 'shortage_review', + 'order_freeze_readiness': 'order_freeze', + 'excel_readiness': 'ready_to_export', + 'artifact_generation': 'export_ready', + 'freight_upload_rpa': 'upload_failed', + 'manual_upload_handoff': 'waiting_upload', + } + return mapping.get(str(gate_code or '').strip()) + + +def derive_todo_category(*, user_mode: str, position: str | None = None) -> str: + """ + 待办分类(review / exception / manual_upload / done / in_progress)。 + + 用途:由 user_mode + position 推导待办分类(Gate-first 唯一口径)。 + """ + if user_mode == 'wait_manual_upload': + return 'manual_upload' + if user_mode == 'complete': + return 'done' + if user_mode == 'must_human': + return 'review' if position in {'parse_review', 'rsv_req', 'customer_review'} else 'exception' + return 'in_progress' + + # ============================================================ # 阶段能力集(Stage Capabilities)——一期:通知准备阶段 # 能力可用性 = 阶段 + Excel 未生成 + 预条件(数据在场),不由门禁通过与否决定。 diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index d91cf3ed..4da9c9a9 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -4,11 +4,13 @@ services/shipping_notice/process_gate_executor.py 用途:将门禁恢复动作码路由到真实业务执行器(同步适配或异步履约)。 依赖:process_gate_service、order_review_draft_service、freeze_readiness_service、 inventory_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、 - document_layout.lifecycle、process_gate_contract、process_gate_bridge。 + document_layout.lifecycle、process_gate_contract、process_gate_bridge、 + inventory_candidate_projection、recovery_invalidation_service。 逻辑:由 Gate Job Handler 或同步恢复路径调用;禁止客户端传入目标状态; 库存源 adopt/keep/reroute 委托 Draft 服务;技术重试委托既有 Run/版面路径; co8 后文档/Run 解析仅经 review_case_id / task_id,不再读 WorkflowItem; - 人工入口动作返回 navigation 提示,保持 blocked_manual。 + 人工入口动作返回 navigation 提示,保持 blocked_manual; + 行级库存重抓按 snapshot_line_id → candidate.source_codes_json 收窄 RPA/失效。 """ from __future__ import annotations @@ -76,6 +78,13 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({ 'regenerate_manual_upload_todo', }) +# 库存准备:仅这些已有动作码强制 mode=retry_rpa(跳过快照复用、新建 Attempt)。 +# poll / 首次自动投递不得落入此集合;禁止「人工入口一律 retry_rpa」。 +_FORCE_INVENTORY_RPA_ACTION_CODES: frozenset[str] = frozenset({ + 'retry_inventory_preparation', + 'retry_inventory_from_preparation', +}) + # 人工入口:前端应导航,不把业务状态改为 passed。 _NAVIGATION_ACTIONS: frozenset[str] = frozenset({ 'open_order_review', @@ -356,6 +365,71 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any]) } +def _resolve_line_inventory_scope( + task: ShippingOrderTask | ShippingNotice | None, + *, + line_scope_key: Any = None, +) -> dict[str, Any] | None: + """ + 由 snapshot_line_id / line_scope_key 解析行级库存作用域。 + + 核心逻辑:snapshot_line_id → SnapshotLine.line_no → CandidateLine.source_codes_json。 + Gate 直调 ensure_inventory 时绕过 progress_workflow,必须在此收窄源范围。 + + Args: + task: 当前 OT / 兼容 Notice owner。 + line_scope_key: 前端 snapshot_line_id 或已规范化的行 scope。 + + Returns: + {snapshot_line_id, line_no, source_codes};无法解析时 None。 + """ + if task is None: + return None + raw = line_scope_key + if raw is None: + return None + try: + scoped_line_id = int(raw) + except (TypeError, ValueError): + return None + if scoped_line_id <= 0 or not getattr(task, 'order_snapshot_id', None): + return None + + from app.models import ShippingOrderSnapshot + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + scoped_line = next( + ( + line for line in (getattr(snapshot, 'lines', None) or []) + if int(getattr(line, 'id', 0) or 0) == scoped_line_id + ), + None, + ) + if scoped_line is None: + return None + line_no = int(getattr(scoped_line, 'line_no', 0) or 0) + candidate_line = next( + ( + line for line in get_active_candidate_lines(task) + if int(getattr(line, 'line_no', 0) or 0) == line_no + ), + None, + ) + source_codes = [ + str(code).strip().upper() + for code in (getattr(candidate_line, 'source_codes_json', None) or []) + if str(code).strip() + ] if candidate_line is not None else [] + if not source_codes: + return None + return { + 'snapshot_line_id': scoped_line_id, + 'line_no': line_no, + 'source_codes': source_codes, + } + + def _tool_outcome( *, action_code: str, @@ -745,7 +819,19 @@ def _handle_retry_inventory_preparation( """ 重试/轮询库存准备。 - 核心逻辑:调用 ensure_inventory 后按任务事实推导细粒度阻断码,再同步履约门禁。 + 核心逻辑:按已有动作码映射 ensure_inventory mode(retry_inventory_preparation → + retry_rpa;poll → auto + allow_auto_retry=False;首次 gate_attempt_passed 保持 auto); + 若携带 line_scope_key/snapshot_line_id,则按该行 candidate.source_codes_json 收窄 + RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory 后按任务事实推导 + 细粒度阻断码,再同步履约门禁。 + + Args: + execution: 当前 ProcessExecution。 + gate: 当前库存准备 Gate。 + payload: 须含 action_code;可选 actor_user_id / line_scope_key / snapshot_line_id。 + + Returns: + Gate Attempt outcome 字典(outcome / blocking_reason_code / effective_result_json 等)。 """ from app.models import ShippingNotice from app.services.shipping_notice.inventory_workflow import ensure_inventory @@ -831,6 +917,14 @@ def _handle_retry_inventory_preparation( str(payload.get('trigger') or '') == 'gate_attempt_passed' and not is_manual_rpa_retry ) + line_scope = _resolve_line_inventory_scope( + task, + line_scope_key=( + payload.get('line_scope_key') + if payload.get('line_scope_key') is not None + else payload.get('snapshot_line_id') + ), + ) if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: # 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实, # 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。 @@ -854,6 +948,8 @@ def _handle_retry_inventory_preparation( action_code=str(payload.get('action_code')), attempt_id=payload.get('attempt_id'), actor_id=actor_id, + source_codes=(line_scope or {}).get('source_codes'), + snapshot_line_id=(line_scope or {}).get('snapshot_line_id'), ) preparation_round = create_inventory_preparation_round( task=task, @@ -870,10 +966,17 @@ def _handle_retry_inventory_preparation( if payload.get('line_scope_key') is not None else payload.get('snapshot_line_id') ) - # 只有用户显式重试强制生成新 Attempt;首次自动投递应先尝试复用有效快照。 - if payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: + if line_scope is not None: + # 行级重抓:只把该行 candidate.source_codes_json 交给 ensure_inventory / RPA。 + inventory_payload['source_codes'] = list(line_scope['source_codes']) + inventory_payload['snapshot_line_id'] = int(line_scope['snapshot_line_id']) + # [STEP] 按已有动作码映射 ensure_inventory mode(零新动作码)。 + # 禁止「人工入口一律 retry_rpa」:仅显式强制 RPA 码写 retry_rpa;poll 只读轮询; + # 首次 gate_attempt_passed 自动投递保持默认 auto(先复用快照)。 + action_code = str(payload.get('action_code') or '').strip() + if action_code in _FORCE_INVENTORY_RPA_ACTION_CODES and not is_initial_auto_dispatch: inventory_payload['mode'] = 'retry_rpa' - if str(payload.get('action_code') or '') == 'poll_inventory_preparation': + if action_code == 'poll_inventory_preparation': # [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试, # 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。 inventory_payload['allow_auto_retry'] = False @@ -1219,7 +1322,12 @@ def _handle_retry_inventory_from_field_mapping( gate: ShippingProcessGate, payload: dict[str, Any], ) -> dict[str, Any]: - """从库存字段映射恢复:失效匹配下游后只重跑映射,不创建库存准备轮次。""" + """ + 从库存字段映射恢复:失效匹配下游后重跑映射;映射通过后仍同 Attempt 嵌套匹配。 + + Follow-up P1:映射 Attempt 应收口后仅 enqueue ``inventory_matching`` Attempt, + 禁止在本函数内直接调用 ``_handle_retry_inventory_matching``(跨 Gate 嵌套债务)。 + """ from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream invalidate_inventory_downstream( @@ -1257,12 +1365,29 @@ def _handle_retry_inventory_matching( ``sync_fulfillment_gates_from_task`` 已将缺口写入 inventory_sufficiency; 当前 inventory_matching Attempt 必须以 passed 收口,否则会覆盖正确的 满足性 Gate 归属并再次显示“进入库存匹配处理”。 + 行级点击(line_scope_key/snapshot_line_id)走 match_inventory_line,并在回退 + ensure_inventory 时携带该行 source_codes。 """ - from app.models import ShippingNotice - from app.services.shipping_notice.fulfillment_workflow import match_inventory + from app.services.shipping_notice.fulfillment_workflow import match_inventory, match_inventory_line from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - response = match_inventory(_task_payload(execution, payload)) + task = _resolve_order_task(execution) + match_payload = _task_payload(execution, payload) + line_scope = _resolve_line_inventory_scope( + task, + line_scope_key=( + payload.get('line_scope_key') + if payload.get('line_scope_key') is not None + else payload.get('snapshot_line_id') + ), + ) + if line_scope is not None: + match_payload['source_codes'] = list(line_scope['source_codes']) + match_payload['snapshot_line_id'] = int(line_scope['snapshot_line_id']) + match_payload['line_scope_key'] = int(line_scope['snapshot_line_id']) + response = match_inventory_line(match_payload, line_no=int(line_scope['line_no'])) + else: + response = match_inventory(match_payload) sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) task = _resolve_order_task(execution) from app.services.shipping_notice.fulfillment_workflow import ( diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index b673cc77..695b5336 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -41,6 +41,18 @@ def _auto_match_enabled() -> bool: from app.services.shipping_notice.tool_common import auto_match_enabled return bool(auto_match_enabled()) + + +def _auto_generate_excel_enabled() -> bool: + """是否自动入队 artifact_generation Attempt(SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED)。 + + 关闭时匹配通过后停在「重新生成 Excel」人工入口,禁止静默投递 regenerate Job。 + """ + from app.services.shipping_notice.tool_common import auto_generate_excel_enabled + + return bool(auto_generate_excel_enabled()) + + from app.services.shipping_notice.process_gate_dependency import compute_invalidated_gates from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text @@ -1017,6 +1029,10 @@ def _enqueue_auto_progress_after_gate_pass( next_gate.next_action_code in {'retry_inventory_matching'} and not _auto_match_enabled() ) + or ( + next_gate.next_action_code == 'regenerate_excel_artifact' + and not _auto_generate_excel_enabled() + ) or str(next_gate.next_action_code).startswith('open_') ): return diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 2116c5b2..17b115cc 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -205,12 +205,32 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: Returns: (ShippingProcessingStatus, ShippingProcessingStage)。 """ - step = str(getattr(notice, 'current_step', None) or '').strip().lower() - upload_st = str(getattr(notice, 'upload_status', None) or '').strip().lower() - export_path = str(getattr(notice, 'export_file_path', None) or '').strip() - pending = str(getattr(notice, 'pending_human_reason', None) or '').strip().lower() - review = str(getattr(notice, 'review_status', None) or '').strip().lower() - match = str(getattr(notice, 'match_status', None) or '').strip().lower() + owner = notice + if not hasattr(notice, 'current_step') and getattr(notice, 'order_task_id', None): + try: + from app import db + from app.models import ShippingOrderTask + owner = db.session.get(ShippingOrderTask, int(notice.order_task_id)) or notice + except Exception: # noqa: BLE001 + owner = notice + step = str(getattr(owner, 'current_step', None) or '').strip().lower() + pending = str(getattr(owner, 'pending_human_reason', None) or '').strip().lower() + review = str(getattr(owner, 'review_status', None) or '').strip().lower() + match = '' + export_path = '' + projected_upload = None + try: + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match = str(aggregate_match_status_for_task(int(owner.id)) or '').strip().lower() if owner.id else '' + from app.services.shipping_notice.upload_attempt_service import ( + latest_export_artifact, + project_notice_upload_status, + ) + artifact = latest_export_artifact(owner) + export_path = str(getattr(artifact, 'file_path', None) or '').strip() + projected_upload = project_notice_upload_status(owner) + except Exception: # noqa: BLE001 + pass lifecycle = str(getattr(notice, 'lifecycle_status', None) or '').strip().lower() from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success @@ -219,17 +239,17 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: return ('cancelled', 'cancelled') if verified_upload_success: ps = 'uploaded' - elif upload_st in {'uploaded', 'succeeded', 'success'}: - # 历史聚合字段或单一回执不构成业务完成。保留在上传工作面,等待核对。 + elif projected_upload == 'uploaded': + # 有 Notice 面成功投影但未过三层验证:留在上传工作面核对。 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 projected_upload in {'uploading', 'pending', 'failed', 'unknown'} or pending in { + 'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown', + }: + ps = 'waiting_upload' if projected_upload != 'failed' else 'upload_failed' elif export_path: ps = 'matched' elif match: ps = 'matched' - elif getattr(notice, 'inventory_lines_json', None): - ps = 'inventory_ready' elif pending or review: ps = 'pending_review' else: @@ -237,7 +257,7 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: if ps in {'uploaded', 'closed', 'completed'}: return ('completed', 'completed') - if ps in {'waiting_upload', 'upload_failed', 'uploading'} or upload_st == 'uploading': + if ps in {'waiting_upload', 'upload_failed', 'uploading'} or projected_upload == 'uploading': return ('automating', 'freight_uploading') if 'upload' in step or step.startswith('step7'): return ('automating', 'freight_uploading') @@ -512,7 +532,7 @@ def reconcile_processing_projection_facts( stage_idx = shipping_processing_stage_index(stage) waiting_idx = shipping_processing_stage_index('waiting_review') or 8 - # 关键事实无法读取时 fail-closed:不能继续沿用旧 checkpoint 或写动作。 + # 关键事实无法读取时 fail-closed:不能继续沿用遗留位置投影或写动作。 if payload.get('projection_data_inconsistent'): payload['status'] = 'waiting_human' payload['stage'] = 'waiting_review' @@ -740,15 +760,25 @@ def apply_user_projection_fields( pending_reason: str | None = None review_status_raw: str | None = None inventory_source_status_raw: str | None = None - if notice is not None: - pending_reason = str(getattr(notice, 'pending_human_reason', None) or '').strip() or None - review_status_raw = str(getattr(notice, 'review_status', None) or '').strip() or None - inventory_source_status_raw = str(getattr(notice, 'inventory_source_status', None) or '').strip() or None - if order_task is not None and not pending_reason: + if order_task is None and notice is not None and getattr(notice, 'order_task_id', None): + try: + from app import db + from app.models import ShippingOrderTask + order_task = db.session.get(ShippingOrderTask, int(notice.order_task_id)) + except Exception: # noqa: BLE001 + order_task = None + if order_task is not None: pending_reason = str(getattr(order_task, 'pending_human_reason', None) or '').strip() or None + review_status_raw = str(getattr(order_task, 'review_status', None) or '').strip() or None # ===== [STEP 3] 按正式 Gate 与领域终态计算 user_status ===== - notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else '' + projected_upload = None + if order_task is not None and notice is not None: + try: + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status + projected_upload = project_notice_upload_status(notice) + except Exception: # noqa: BLE001 + projected_upload = None from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success # 读取路径也必须遵守三层上传成功事实;否则 retry 决策或旧 status=completed @@ -760,7 +790,7 @@ def apply_user_projection_fields( and ( old_status == 'completed' or old_stage == 'completed' - or notice_upload_status in {'uploaded', 'succeeded', 'success'} + or projected_upload == 'uploaded' ) ) def _compute_user_status() -> str: @@ -1018,6 +1048,41 @@ def apply_user_projection_fields( primary_action = _compute_primary_action() + # ===== [STEP 8: flatten C→A] 复用唯一裁决 C(process_gate),不再二次推导 drift ===== + # 契约 §2.1/§2.2:primary_action.code / blocking_reason.code 唯一来源是 C(project_user_gate_summary)。 + # A(本函数)只把 C 已裁决的规范化码包成 ui_state DTO;禁止再走别名(D1: regenerate_excel_artifact→ + # regenerate_excel)或坍缩(D2: inventory_preparation_failed→technical_failure_present)覆盖 C。 + # 条件化:仅当 _project_order_task_work_item 已写入 payload['process_gate'](正式 OT 有 Execution)时 + # 消费 C;Intake/min 投影路径(shipping_processing_projection.py:983/:4695)无 process_gate,保留现有推导。 + # 该实现与前端右卡仅读 A(§2.4)同批上线,保证右卡/对话流/批次进度中心同源;此处不改 user_status + # (那是 A 独有的六值展示分组枚举,C/B 均不产出,留在 A)。 + _process_gate = payload.get('process_gate') if isinstance(payload.get('process_gate'), dict) else None + if _process_gate is not None: + # D1: primary_action.code 取 C 规范码(去 A 的 regenerate_excel_artifact→regenerate_excel 别名)。 + _c_primary_code = str((_process_gate.get('primary_action') or {}).get('code') or '').strip() + if not _c_primary_code: + _c_primary_code = str(_process_gate.get('next_action_code') or '').strip() + if _c_primary_code: + _a_primary_code = str((primary_action or {}).get('code') or '').strip() + if _a_primary_code != _c_primary_code: + primary_action = { + 'code': _c_primary_code, + 'i18n_key': _resolve_action_i18n_key(_c_primary_code), + 'parameters': {}, + } + # D2: blocking_reason.code 取 C 已裁决的具体码,不再坍缩为 technical_failure_present。 + _c_reason_code = str(_process_gate.get('blocking_reason_code') or '').strip() + if _c_reason_code and isinstance(blocking_reason, dict): + _a_reason_code = str(blocking_reason.get('code') or '').strip() + if _a_reason_code != _c_reason_code: + blocking_reason = { + 'code': _c_reason_code, + 'i18n_key': _REASON_TO_I18N_KEY.get(_c_reason_code) or ( + (blocking_reason or {}).get('i18n_key') + ), + 'details': dict((blocking_reason or {}).get('details') or {}), + } + # ===== [不变] facts 子事实计算(保持不动) ===== facts: dict[str, Any] = { 'inventory_source_status': inventory_source_status_raw or 'unresolved', @@ -1055,25 +1120,13 @@ def apply_user_projection_fields( if isinstance(cand, list): facts['candidate_source_codes'] = [str(c or '').strip().upper() for c in cand if str(c or '').strip()] if notice is not None: - step_payload = getattr(notice, 'step_payload_json', None) - if isinstance(step_payload, dict): - prep = step_payload.get('candidate_inventory_prep') - if isinstance(prep, dict): - facts['prepared_source_codes'] = list(prep.get('loaded_source_codes') or []) - facts['pending_source_codes'] = list(prep.get('missing_source_codes') or []) - resolutions = step_payload.get('line_inventory_resolutions') - if isinstance(resolutions, list): - facts['line_resolutions'] = resolutions[:] - fms = step_payload.get('forced_match_source_code') - if fms: - facts['forced_match_source_code'] = str(fms).strip().upper() - # 正式 OT 优先从 CandidateSet/LineMatch Projection 读取库存事实;旧 - # step_payload 仅作为尚未形成正式候选集的历史任务兼容回退。 + # 正式 OT 的库存事实只从 CandidateSet、Preparation/Link/File、LineMatch 与 Gate + # 读取;step_payload_json 不再作为库存运行事实或恢复动作来源。 try: from app.services.shipping_notice.inventory_candidate_projection import ( project_inventory_candidate_facts, ) - candidate_facts = project_inventory_candidate_facts(notice) + candidate_facts = project_inventory_candidate_facts(order_task) if candidate_facts.get('current_set') is not None: facts['candidate_set_id'] = candidate_facts.get('candidate_set_id') facts['candidate_set_version'] = candidate_facts.get('candidate_set_version') @@ -1096,7 +1149,7 @@ def apply_user_projection_fields( # P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。 try: from app.models import ShippingTaskInventoryRpaAttempt - attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(notice, 'task_no', '') or '')).all() + attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all() facts['rpa_attempts'] = [{ 'source_code': a.source_code, 'attempt_no': a.attempt_no, 'source_run_no': a.source_run_no, 'status': a.status, @@ -1107,11 +1160,17 @@ def apply_user_projection_fields( } for a in attempts] except Exception: facts['rpa_attempts'] = [] - if getattr(notice, 'export_artifact_id', None): - facts['export_state'] = 'created' - if getattr(notice, 'upload_status', None): - us = str(getattr(notice, 'upload_status') or '').strip().lower() - facts['upload_state'] = us if us else 'not_created' + try: + from app.services.shipping_notice.upload_attempt_service import ( + latest_export_artifact, + project_facts_upload_state, + ) + artifact = latest_export_artifact(order_task or notice) + if artifact is not None: + facts['export_state'] = str(getattr(artifact, 'status', None) or 'created') + facts['upload_state'] = project_facts_upload_state(order_task or notice) + except Exception: # noqa: BLE001 + pass if getattr(notice, 'wecom_sent_at', None): facts['switch_state'] = 'sent' diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index 93abf8c2..799aa1dd 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -523,8 +523,6 @@ PROCESS_GATE_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ LINE_DERIVATION_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ 'FIELD_DERIVED', 'FIELD_DERIVATION_SKIPPED', - 'LINE_NO_OVERRIDDEN', - 'LINE_NO_RESTORED', 'DERIVATION_SIMULATED', 'DERIVATION_RULES_CHANGED', 'ORDER_FROZEN', @@ -823,7 +821,6 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ 'validation_blocking_count', 'validation_warning_count', 'field_id', - 'line_key', 'previous_value', 'new_value', 'value_source', @@ -858,10 +855,8 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ # 字段派生 / 覆盖 / 导出血缘(脱敏摘要,禁止邮件/PDF 正文)。 'rule_id', 'rule_checksum', - 'derivation_rules_checksum', 'skip_reason', 'override_reason_code', - 'export_sequence', 'export_artifact_no', 'template_version', 'field_code', @@ -874,7 +869,8 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ 'suggestion_pending', 'idempotency_key', 'action_semantics', - 'line_keys', + 'draft_line_ids', + 'snapshot_line_ids', 'routing_status', # Process Gate 恢复摘要(禁止正文、规则 SQL、对象存储 URL)。 'gate_code', diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index 6dae0c38..c312255b 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -3,10 +3,13 @@ services/shipping_notice/progress_workflow.py 用途:承接发货通知任务的自动推进提交,包括解析确认检查、正式库存准备与履约侧串联。 依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、 - state_machine(CheckpointKind)、tool_response、process_gate_bridge。 + process_gate_contract.derive_user_mode、ui_state._process_gate_user_summary_for_task、 + state_machine(双读回退)、tool_response、process_gate_bridge。 逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;P0-3 起正式入口只提交 当前最早未通过 Gate,Worker 负责单 Gate 执行与下一 Job 的事务性入队;历史私有实现暂保留 - 供兼容调用方,但不得再由本 facade 直接跨 Gate 调度。 + 供兼容调用方,但不得再由本 facade 直接跨 Gate 调度; + 早停粗分类优先 Gate derive_user_mode,无 Execution 时回退 resolve_task_ui_state; + inventory_preparation 的 retryable_tech 阻断不早停,交给 ensure_inventory(复用快照或 RPA)。 """ from __future__ import annotations @@ -19,7 +22,7 @@ from app.services.shipping_notice import fulfillment_workflow from app import db from app.models.shipping_process_gate import ShippingProcessGateAttempt from app.services.shipping_notice.constants import ( - CP_INVENTORY_SOURCE_REVIEW, + POSITION_INVENTORY_SOURCE_REVIEW, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, PH_RSV_REQ, @@ -32,12 +35,86 @@ from app.services.shipping_notice.inventory_source_gate import ( ) from app.services.shipping_notice.inventory_workflow import ensure_inventory as _legacy_ensure_inventory from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool -from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state +from app.services.shipping_notice.state_machine import resolve_task_ui_state from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response +def _entry_user_mode(task) -> str: + """ + 自动推进入口早停:从 Gate 推导用户处置模式。 + + 无活动 Execution 时回退 resolve_task_ui_state.user_mode。 + inventory_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker + 继续走 ensure_inventory(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。 + """ + from app.services.shipping_notice.process_gate_contract import ( + derive_user_mode, + user_mode_for_blocking_reason, + ) + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task + + gate = _process_gate_user_summary_for_task(task) + if not isinstance(gate, dict) or not gate: + return str(resolve_task_ui_state(task).user_mode) + gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {} + if not isinstance(gate_view, dict): + gate_view = {} + status = str(gate_view.get('status') or '').strip().lower() + summary_status = str(gate.get('status') or gate.get('gate_status') or '').strip().lower() + gate_code = str(gate.get('current_gate_code') or gate_view.get('gate_code') or '').strip() + reason_code = str( + gate_view.get('blocking_reason_code') + or gate.get('blocking_reason_code') + or '' + ).strip() + # [STEP] 库存准备可自动恢复:候选已冻结但尚无快照时,sync 可能先投影 + # blocked_retryable + inventory_file_empty;契约上属 retryable_tech,应由 + # submit_auto_progress 入队 ensure_inventory,而不是入口 must_human 停机。 + if ( + gate_code == 'inventory_preparation' + and status == 'blocked_retryable' + and user_mode_for_blocking_reason(reason_code) == 'retryable_tech' + ): + return 'auto_continue' + if summary_status in {'completed', 'done'}: + user_status = 'completed' + elif status in {'blocked_manual', 'blocked_retryable'} or summary_status == 'blocked': + user_status = 'waiting_human' + elif status == 'failed_terminal' or summary_status == 'failed': + user_status = 'failed' + else: + user_status = 'running' + return derive_user_mode( + user_status=user_status, + gate_code=gate_code or None, + review_status=getattr(task, 'review_status', None), + lifecycle_stage=gate.get('lifecycle_stage'), + ) + + +def _entry_position(task) -> str | None: + """ + 工具响应下发位置标签:优先 Gate derive_position,否则 resolve_task_ui_state。 + """ + from app.services.shipping_notice.process_gate_contract import derive_position + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task + + gate = _process_gate_user_summary_for_task(task) + if isinstance(gate, dict) and gate: + gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {} + if not isinstance(gate_view, dict): + gate_view = {} + pos = derive_position( + gate_code=gate.get('current_gate_code') or gate_view.get('gate_code'), + review_status=getattr(task, 'review_status', None), + ) + if pos: + return pos + return resolve_task_ui_state(task).position + + # --------------------------------------------------------------------------- # T5: 唯一 AutoProgress Orchestrator 入口 facade # --------------------------------------------------------------------------- @@ -56,7 +133,7 @@ from app.services.shipping_notice.customer_identity_gate import customer_gate_to _RESUME_GATE_CODE_LEGACY_ENTRY = { # inventory_preparation → 调 inventory_workflow.ensure_inventory 逻辑(复用旧实现) 'inventory_preparation': 'ensure_inventory', - # inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key) + # inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key=订单项次) 'inventory_matching': 'match_inventory', # None 或 'auto' → 走完整 auto_progress 串联链(解析→库存→匹配→导出→上传) 'auto': 'auto_progress_full', @@ -130,8 +207,12 @@ def _dispatch_legacy_orchestration( resume_after_gate: str | None = None, ) -> dict[str, Any]: """ - resume_gate_code → 旧实现分派(短期复用稳定实现,后续逐步把每个 Gate 原子步骤迁入本 facade)。 - 长期目标:每个 Gate 只在本函数内跑原子 run_one_gate_step();旧实现会逐步下线。 + [DEPRECATED / P0-3 后不可达主路径] resume_gate_code → 旧跨 Gate 串联实现。 + + 正式开心路径已改为 ProcessGate:``submit_auto_progress`` / + ``complete_gate_attempt → _enqueue_auto_progress_after_gate_pass`` 只入队下一 Gate + Attempt;匹配成功不得在此函数内嵌 ``generate_excel`` / ``upload_to_freight``。 + 本函数体暂保留供兼容调用方与测试打桩,不得再作为新编排入口扩展。 """ entry = _RESUME_GATE_CODE_LEGACY_ENTRY.get(resume_gate_code, 'auto_progress_full') base_payload: dict[str, Any] = { @@ -150,7 +231,49 @@ def _dispatch_legacy_orchestration( ) frozen_sources = task_frozen_inventory_source_codes(task) if frozen_sources and len(frozen_sources) >= 1: - prepare_result = ensure_all_required_sources_prepared(task, mode=inventory_mode) + scoped_source_codes: list[str] | None = None + scope_key = str(line_scope_key or '').strip() + if scope_key: + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + + try: + scoped_line_id = int(scope_key) + except (TypeError, ValueError): + scoped_line_id = 0 + from app.models import ShippingOrderSnapshot + + snapshot = ( + db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + if getattr(task, 'order_snapshot_id', None) else None + ) + scoped_line = next( + ( + line for line in (getattr(snapshot, 'lines', None) or []) + if int(getattr(line, 'id', 0) or 0) == scoped_line_id + ), + None, + ) + if scoped_line is not None: + candidate_lines = get_active_candidate_lines(task) + candidate_line = next( + ( + line for line in candidate_lines + if int(getattr(line, 'line_no', 0) or 0) == int(getattr(scoped_line, 'line_no', 0) or 0) + ), + None, + ) + scoped_sources = [ + str(code).strip().upper() + for code in (getattr(candidate_line, 'source_codes_json', None) or []) + if str(code).strip() + ] if candidate_line is not None else [] + if scoped_sources: + frozen_sources = scoped_sources + scoped_source_codes = scoped_sources + + prepare_result = ensure_all_required_sources_prepared( + task, mode=inventory_mode, source_codes=scoped_source_codes, + ) if prepare_result.all_prepared: return _legacy_ensure_inventory({**base_payload, '_prepared_sources': prepare_result.prepared_source_codes, '_orchestrator_internal_dispatch': True}) return tool_response( @@ -178,7 +301,7 @@ def _dispatch_legacy_orchestration( if norm_line_scope: return fulfillment_workflow.match_inventory_line( {**base_payload, '_orchestrator_internal_dispatch': True}, - line_key=norm_line_scope, + line_no=int(norm_line_scope), ) return fulfillment_workflow.match_inventory({**base_payload, '_orchestrator_internal_dispatch': True}) return _auto_progress_full(task, base_payload, trigger=trigger, operator_id=operator_id) @@ -265,6 +388,8 @@ def run_task_auto_progress( submitted = submit_auto_progress( task=task, trigger=trigger, operator_id=operator_id, resume_gate_code=resume_gate_code, commit=True, + inventory_mode=inventory_mode, + line_scope_key=line_scope_key, recovery_plan_id=recovery_plan_id, recovery_attempt_id=recovery_attempt_id, resume_after_gate=resume_after_gate, @@ -377,7 +502,8 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: 【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。 亦由 STP 直通建单、人工复核确认后系统入口复用(同一函数,禁止平行链路)。 - 核心逻辑:先按 checkpoint_kind 处理早停;WAIT_MANUAL_UPLOAD 在 AUTO_UPLOAD 开启时 + 核心逻辑:先按 Gate derive_user_mode 处理早停(无 Execution 回退 user_mode); + WAIT_MANUAL_UPLOAD / wait_manual_upload 在 AUTO_UPLOAD 开启时 不早停、落入履约链触发货代 RPA;关闭时才对齐 manual_upload_pending 并禁止自动上传。 再检查解析门禁与客户/库存源,库存就绪后委托 fulfillment_workflow 同一编排链。 Args: @@ -411,21 +537,22 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: # 正式 20-Gate 编排仍由后续分支负责;这里仅返回用户可执行的当前结果。 early_task = resolve_task_from_payload({'task_no': task_no}) if task_no else None if early_task is not None: - early_ui = resolve_task_ui_state(early_task) - if early_ui.checkpoint_kind == CheckpointKind.MUST_HUMAN: + early_mode = _entry_user_mode(early_task) + early_position = _entry_position(early_task) + if early_mode == 'must_human': return tool_response( status='needs_human', task=early_task, message='当前任务需要人工处理,已暂停自动推进。', data=serialize_task_for_tool(early_task), - checkpoint=early_ui.checkpoint, + position=early_position, stop_agent_turn=True, ) - if early_ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD and not fulfillment_workflow.is_auto_upload_enabled(): + if early_mode == 'wait_manual_upload' and not fulfillment_workflow.is_auto_upload_enabled(): return tool_response( status='ok', task=early_task, message='Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。', data=serialize_task_for_tool(early_task), - checkpoint=early_ui.checkpoint, + position=early_position, stop_agent_turn=True, forbidden_next_tools=['upload_to_freight'], ) @@ -491,25 +618,26 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: steps: list[str] = [] - # [STEP 0] STP 检查点早停:必须人工、待人工上传登记或已完成时不产生新副作用。 - ui_early = resolve_task_ui_state(task) - if ui_early.checkpoint_kind == CheckpointKind.MUST_HUMAN: + # [STEP 0] Gate 粗分类早停:必须人工、待人工上传登记或已完成时不产生新副作用。 + early_mode = _entry_user_mode(task) + early_position = _entry_position(task) + if early_mode == 'must_human': return tool_response( status="needs_human", task=task, message="当前任务需要人工处理,已暂停自动推进。", data=serialize_task_for_tool(task), - checkpoint=ui_early.checkpoint, + position=early_position, stop_agent_turn=True, ) - if ui_early.checkpoint_kind == CheckpointKind.COMPLETE: + if early_mode == 'complete': return tool_response( status="ok", task=task, message="任务已结束,无需自动推进。", data=serialize_task_for_tool(task), ) - if ui_early.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD: + if early_mode == 'wait_manual_upload': pending = str(getattr(task, 'pending_human_reason', '') or '').strip() # RPA 已触发/失败:只对齐细粒度投影,不再重复编排。 if pending in {'upload_rpa_pending', 'upload_rpa_failed'}: @@ -539,7 +667,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: else '货代上传 RPA 失败,请在对话侧恢复或改人工登记。' ), data=serialize_task_for_tool(task), - checkpoint=ui_early.checkpoint, + position=early_position, stop_agent_turn=True, ) # AUTO_UPLOAD 开启:与 fulfillment 链统一,继续向下触发上传,禁止在此早停。 @@ -569,7 +697,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: task=task, message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", data=serialize_task_for_tool(task), - checkpoint=ui_early.checkpoint, + position=early_position, stop_agent_turn=True, forbidden_next_tools=["upload_to_freight"], ) @@ -583,29 +711,34 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: threshold = 0.7 confidence = None try: - confidence = float(task.parse_confidence) if task.parse_confidence is not None else None + parse_validation = (task.step_payload_json or {}).get('parse_validation') if isinstance(getattr(task, 'step_payload_json', None), dict) else None + raw_confidence = parse_validation.get('confidence') if isinstance(parse_validation, dict) else None + confidence = float(raw_confidence) if raw_confidence is not None else None except (TypeError, ValueError): confidence = None - if task.review_status == RS_RSV_REQ or task.pending_human_reason == PH_RSV_REQ: + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + blocking_reason = task_blocking_reason(task) + if task.review_status == RS_RSV_REQ or blocking_reason == PH_RSV_REQ: ui = resolve_task_ui_state(task) return tool_response( status="needs_human", task=task, message="订单仍缺少后续处理必需字段,请先补充后再继续。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, + position=ui.position, stop_agent_turn=True, forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"], ) - if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF: + if task.review_status == RS_PARSE_REVIEW or blocking_reason == PH_LOW_CONF: ui = resolve_task_ui_state(task) return tool_response( status="needs_human", task=task, message="发货通知解析需要人工确认后才能自动推进。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, + position=ui.position, stop_agent_turn=True, ) if confidence is not None and confidence < threshold: @@ -615,7 +748,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: task=task, message=f"解析置信度 {confidence:.2f} 低于阈值 {threshold:.2f},请人工确认后再自动推进。", data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, + position=ui.position, stop_agent_turn=True, ) @@ -623,7 +756,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: if customer_gate is not None: return customer_gate - if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task): + if blocking_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task): adjudication = ensure_inventory_source_review_state(task) db.session.commit() if not is_inventory_source_stable(task): @@ -639,12 +772,13 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: "inventory_source_reason": adjudication.reason, "destination_candidates": adjudication.destination_candidates, }, - checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW, + position=ui.position or POSITION_INVENTORY_SOURCE_REVIEW, stop_agent_turn=True, ) # [STEP 2] 保证库存已经就绪(仅复用已有库存快照;不得隐式触发库存 RPA)。 - if not task.inventory_lines_json: + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + if not has_ready_inventory_file_for_task(task): lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"} if lang: @@ -660,7 +794,9 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: else: steps.append("载入库存") - # [STEP 3] 库存就绪后进入履约侧自动推进(与 try_auto_chain 同一语义:可含货代 RPA)。 + # [STEP 3] 库存就绪后进入履约侧自动推进。 + # [DEPRECATED] 旧语义曾与 try_auto_chain 同 Attempt 串联 generate±upload; + # P0-3 / 编排分离后正式路径为独立 Gate Attempt,本 legacy 体仅兼容残留入口。 fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps) # [STEP 4] 将履约真相同步到 Process Gate(inventory_preparation→manual_upload_handoff)。 diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 527912ac..843410e0 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -10,13 +10,17 @@ services/shipping_notice/query_service.py 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), + 直接序列化 ShippingOrderTask 时 order_task_no 取自身 task_no(禁止经 order_task_id 冲 null), 并注入 review_run_no 供任务中心深链订单处理工作台(UI-04); list_my_todos / count_my_todos 合并建单前 Review Case、未建 OT Intake 与 Task 待办; serialize_review_case_todo 在 STP failed/manual_fallback 时投影 retry_stp_auto_create; - 客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与 Task(客户快照/来源文件名); - 待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT, - 仅水合当前页(禁止 500 截断冒充总数); + 客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与确认客户/来源文档; + 待办 todo_category 优先 Gate derive_*(单任务 / enrich / 行级);无 Execution 回退 position/user_mode; + SQL CASE 仍为粗筛近似(双读过渡,与 Gate 可能短暂漂移); + list 用 UNION ALL + COUNT/OFFSET/LIMIT,仅水合当前页(禁止 500 截断冒充总数); + fetch_gate_positions 批量读 Execution.current_gate_code,供 Gate 推导待办避免 N+1; DETAIL 另投影 parse_validation / process_field_gate / source_candidate 与履约时间线(Reservation/Artifact); + view=workbench 跳过 SUMMARY/DETAIL 重投影,仅身份壳 + enrich(ui_state),禁止算完再删; co8 起 WorkflowItem 账本已下线,不再附加 workflow_item 投影(BE-06); 订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。 """ @@ -29,6 +33,7 @@ from pathlib import Path from typing import Any from sqlalchemy import String, asc, case, cast, desc, exists, func, literal, select, union_all +from sqlalchemy.orm import aliased from app import db from app.core.errors import ValidationError @@ -37,6 +42,7 @@ from app.models import ( ShippingExportArtifact, ShippingExportArtifactLine, ShippingInventoryVerification, + ShippingInventoryFile, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, @@ -46,19 +52,23 @@ from app.models import ( ShippingOrderLine, ShippingOrderReviewCase, ShippingOrderSnapshot, + ShippingOrderSnapshotLine, ShippingOrderReviewStream, ShippingOrderSubmission, ShippingReservation, ShippingNotice, + ShippingOrderTask, + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingProcessExecution, + ShippingProcessGate, + ShippingTaskInventoryLink, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, ShippingTaskEvent, ShippingUploadAttempt, ) from app.services.shipping_notice.constants import ( - CP_NOTICE_TEXT_EXTRACTION_FAILED, - CP_PARSE_REVIEW, - CP_RSV_REQ, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, @@ -75,10 +85,10 @@ from app.services.shipping_notice.constants import ( RS_RSV_REQ, RS_SHORTAGE_REVIEW, ) +from app.services.shipping_notice.upload_attempt_service import latest_export_artifact from app.services.shipping_notice.state_machine import ( - CheckpointKind, + UserMode, resolve_task_ui_state, - resolve_task_ui_state_from_fields, ) from app.services.shipping_notice.task_order_field_editor import ( current_header_field_values_or_empty, @@ -92,13 +102,14 @@ EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml. _TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE) _BUSINESS_NO_RE = re.compile(r"(? ShippingOrderCandidate | None: + """ + 定位同一文件当前可复核 Candidate,不依赖单个 Case 的 ``candidate_id``。 + + 触发时机:Review Case 的生命周期投影需要裁决「是否已进入订单复核」时,遇到 + 重解析时序(doc67)——Stream.current_case 可能仍是空的旧 Case(``candidate_id=None``), + 而真正带可复核 Candidate 的是同文档另一 Case。若只读当前 Case 的 candidate_id, + 会把「PO + 订单明细已识别、仅被阻塞需人工复核」的文档误压回「接收解析」。 + + 核心逻辑:先按 document_id 遍历同文档已回链 Candidate 的 Case,找到满足 + ``is_current_reviewable_candidate`` 的 Candidate;回退时按主文档直查。空、过期或 + 被替代 Candidate 一律不开放候选上下文。 + + Args: + document_id: Review Case 的源文档 ID。 + + Returns: + 当前可复核 Candidate;无有效候选时返回 None。 + """ + from app.services.shipping_notice.candidate_service import ( + is_current_reviewable_candidate, + ) + + if document_id is None: + return None + for sibling in ( + ShippingOrderReviewCase.query + .filter( + ShippingOrderReviewCase.document_id == int(document_id), + ShippingOrderReviewCase.candidate_id.isnot(None), + ) + .order_by(ShippingOrderReviewCase.id.desc()) + .all() + ): + candidate = db.session.get(ShippingOrderCandidate, int(sibling.candidate_id)) + if is_current_reviewable_candidate(candidate): + return candidate + candidate = ( + ShippingOrderCandidate.query + .filter(ShippingOrderCandidate.primary_document_id == int(document_id)) + .order_by(ShippingOrderCandidate.id.desc()) + .first() + ) + return candidate if is_current_reviewable_candidate(candidate) else None + + def _review_case_lifecycle_projection(case: ShippingOrderReviewCase) -> dict[str, Any]: """复用统一生命周期投影裁决 Review Case 的当前阶段与入口。 当前有效 Candidate 才能进入订单复核;空、过期或被替代 Candidate 仍属于接收解析。 此处只组装已有事实并调用 ``project_lifecycle``,不新增状态机或前端专用阶段。 + 候选上下文按「文件」粒度裁决:当前 Case 落到空旧 Case(``candidate_id=None``) + 时,回退定位该文件真实可复核 Candidate,避免已识别+阻塞文档被压回接收解析。 """ candidate = ( db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id is not None else None ) - from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate + from app.services.shipping_notice.candidate_service import ( + is_current_reviewable_candidate, + ) from app.services.shipping_notice.lifecycle_projection import project_lifecycle has_candidate_context = is_current_reviewable_candidate(candidate) + if not has_candidate_context: + # doc67 类重解析时序:Stream.current_case 可能是空旧 Case,真实可复核 + # Candidate 在同文档另一 Case。按文件粒度回退定位,禁止把已解析+阻塞 + # 文档误投影为「接收解析」。 + candidate = _current_reviewable_candidate_for_document( + getattr(case, 'document_id', None), + ) + has_candidate_context = candidate is not None if has_candidate_context: return project_lifecycle( current_gate=None, @@ -176,19 +247,22 @@ class TaskProjection(str, Enum): def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]: """为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。""" - verifications = ShippingInventoryVerification.query.filter_by(task_id=task.id).order_by( + inventory_task_id = int(getattr(task, 'order_task_id', None) or task.id) + verifications = ShippingInventoryVerification.query.filter_by(task_id=inventory_task_id).order_by( ShippingInventoryVerification.created_at, ShippingInventoryVerification.id, ).all() - artifacts = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by( - ShippingExportArtifact.created_at, ShippingExportArtifact.id, - ).all() + artifacts = [] + if isinstance(task, ShippingNotice): + artifacts = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by( + ShippingExportArtifact.created_at, ShippingExportArtifact.id, + ).all() artifact_ids = [item.id for item in artifacts] artifact_lines = ShippingExportArtifactLine.query.filter( ShippingExportArtifactLine.artifact_id.in_(artifact_ids), ).all() if artifact_ids else [] reservation_ids = { item.id: item.reservation_id - for item in ShippingReservation.query.filter(ShippingReservation.task_id == task.id).all() + for item in ShippingReservation.query.filter(ShippingReservation.task_id == inventory_task_id).all() } reservations_by_artifact: dict[int, list[str]] = {} for line in artifact_lines: @@ -224,11 +298,14 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any] } -def get_task_by_ref(task_ref: str) -> ShippingNotice | None: - """按 task_no、business_no 或数字主键精确查找 Notice。""" +def get_task_by_ref(task_ref: str) -> ShippingOrderTask | ShippingNotice | None: + """按 OT task_no 查找订单任务;业务编号/Notice 主键仅用于正式通知专用查询。""" value = str(task_ref or "").strip() if not value: return None + task = ShippingOrderTask.query.filter_by(task_no=value).first() + if task: + return task task = ShippingNotice.query.filter_by(task_no=value).first() if task: return task @@ -236,7 +313,7 @@ def get_task_by_ref(task_ref: str) -> ShippingNotice | None: if task: return task if value.isdigit(): - return db.session.get(ShippingNotice, int(value)) + return db.session.get(ShippingOrderTask, int(value)) or db.session.get(ShippingNotice, int(value)) return None @@ -279,13 +356,13 @@ def resolve_order_extraction_ui_target( # co8 起 Intake.consumed_batch_id 已删除;仅通过 Candidate→Task 反查已有任务。 task = ( - db.session.query(ShippingNotice) - .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingNotice.id) + db.session.query(ShippingOrderTask) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) .filter( ShippingOrderCandidate.intake_id.in_([int(item.id) for item in intakes]), - ShippingNotice.user_id == int(user_id), + ShippingOrderTask.user_id == int(user_id), ) - .order_by(ShippingOrderCandidate.id.asc(), ShippingNotice.id.asc()) + .order_by(ShippingOrderCandidate.id.asc(), ShippingOrderTask.id.asc()) .first() ) return None, task @@ -293,7 +370,7 @@ def resolve_order_extraction_ui_target( def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str] | None: """解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。""" - if not task or not task.export_file_path: + if not task or isinstance(task, ShippingOrderTask) or getattr(task, 'id', None) is None: return None from app.models import ShippingExportArtifact # 已人工/RPA 上传完成的 Artifact 仍是用户可下载的最终 Excel; @@ -301,7 +378,6 @@ def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str artifact = ShippingExportArtifact.query.filter( ShippingExportArtifact.task_id == task.id, ShippingExportArtifact.status.in_({'ready', 'uploaded'}), - ShippingExportArtifact.file_path == task.export_file_path, ).order_by( ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(), ).first() @@ -315,7 +391,7 @@ def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str def task_export_error_message(task: ShippingNotice | None) -> str: """导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。""" - if not task or task.id is None or not task.export_file_path: + if not task or task.id is None: return "export file not found" resolved = resolve_task_export_download(task) if resolved is None: @@ -334,7 +410,7 @@ def resolve_task_from_payload( payload: dict[str, Any], *, allow_conversation_fallback: bool = True, -) -> ShippingNotice | None: +) -> ShippingOrderTask | ShippingNotice | None: """ 按 task_id/task_no、文本内嵌 SN- 或 conversation_id 解析任务(只读)。 @@ -362,9 +438,9 @@ def resolve_task_from_payload( conv_id = str(payload.get("conversation_id") or "").strip() if conv_id: candidates = ( - ShippingNotice.query.filter_by(conversation_id=conv_id) - .filter(ShippingNotice.lifecycle_status == "active") - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query.filter_by(conversation_id=conv_id) + .filter(ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled'})) + .order_by(ShippingOrderTask.id.desc()) .limit(2) .all() ) @@ -375,39 +451,81 @@ def resolve_task_from_payload( def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: """Tool data 基础字段(裁剪前)。""" + if isinstance(task, ShippingOrderTask): + header, lines, _field_display = _order_values_for_projection(task) + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + match_facts = list(load_current_match_facts_by_task(task.id).values()) + customer = _order_task_customer_projection(task) + inventory = _order_task_inventory_projection(task) + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + shortage = {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]} + return { + 'task_no': task.task_no, + 'order_task_no': task.task_no, + 'current_step': task.stage, + 'stage': task.stage, + 'status': task.status, + 'customer_name': header.get('customer_name'), + 'customer_code': header.get('customer_code'), + 'customer_resolution_status': customer['status'], + 'customer_resolution_method': customer['resolution_method'], + 'customer_id': customer['customer_id'], + 'customer_name_snapshot': customer['customer_name_snapshot'], + 'customer_short_code_snapshot': customer['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'), + 'lines': lines, + 'shortage': shortage, + 'line_results': match_facts, + 'pending_human_reason': task_blocking_reason(task), + 'error_message': task.error_message, + 'conversation_id': task.conversation_id, + 'step_payload': task.step_payload_json or {}, + **inventory, + 'inventory_snapshot': _serialize_inventory_snapshot(task), + } from app.services.shipping_notice.notice_upload import max_notice_chars from app.services.shipping_notice.rpa import rpa_runtime_mode - step_payload = task.step_payload_json or {} - header = current_header_field_values_or_empty(task) + workflow_owner = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if getattr(task, 'order_task_id', None) else task + ) + match_projection = _current_match_projection(workflow_owner) + artifact, upload_attempt = _latest_export_upload_facts(task) + step_payload = getattr(workflow_owner, 'step_payload_json', None) or {} + header = current_header_field_values_or_empty(workflow_owner) + customer_projection = _order_task_customer_projection(workflow_owner) if isinstance(workflow_owner, ShippingOrderTask) else {} payload: dict[str, Any] = { "task_no": task.task_no, - "business_no": task.business_no, - "current_step": task.current_step, - "review_status": task.review_status, - "match_status": task.match_status, - "pending_human_reason": task.pending_human_reason, - "customer_name": header.get('customer_name') or header.get('bill_to_customer'), + "business_no": getattr(task, 'business_no', None), + "current_step": getattr(workflow_owner, 'current_step', None) or getattr(workflow_owner, 'stage', None), + "review_status": getattr(workflow_owner, 'review_status', None), + "match_status": match_projection['match_status'], + "pending_human_reason": getattr(workflow_owner, 'pending_human_reason', None), + "customer_name": header.get('customer_name'), "customer_code": header.get('customer_code'), - "customer_resolution_status": task.customer_resolution_status, - "customer_resolution_method": task.customer_resolution_method, - "customer_id": task.customer_id, - "customer_name_snapshot": task.customer_name_snapshot, - "customer_short_code_snapshot": task.customer_short_code_snapshot, + "customer_resolution_status": customer_projection.get('status'), + "customer_resolution_method": customer_projection.get('resolution_method'), + "customer_id": customer_projection.get('customer_id'), + "customer_name_snapshot": customer_projection.get('customer_name_snapshot'), + "customer_short_code_snapshot": customer_projection.get('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'), - "lines": current_line_field_values_or_empty(task), - "shortage": task.shortage_json, - "line_results": task.line_results_json, - "export_file_name": task.export_file_name, - "freight_ref_no": task.freight_ref_no, - "error_message": task.error_message, + "lines": current_line_field_values_or_empty(workflow_owner), + "shortage": match_projection['shortage'], + "line_results": match_projection['line_results'], + "export_file_name": getattr(artifact, 'file_name', None), + "freight_ref_no": getattr(upload_attempt, 'freight_ref_no', None), + "error_message": getattr(workflow_owner, 'error_message', None), "conversation_id": task.conversation_id, - "step_payload": step_payload, + "step_payload": getattr(workflow_owner, 'step_payload_json', None) or {}, "rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None), } - raw_content = str(task.raw_content or "").strip() + raw_content = str(getattr(workflow_owner, 'raw_content', None) or "").strip() lines = payload["lines"] from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link @@ -421,6 +539,84 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: return payload +def _current_match_projection(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: + """从关联 OT 的行级 Match 生成通知准备读模型,禁止读取 Notice 聚合缓存。""" + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) + rows = list(load_current_match_facts_by_task(task_id).values()) + shortage_rows = [ + row for row in rows + if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'} + or str(row.get('match_result') or '').strip().lower() != 'matched' + ] + return { + 'match_status': 'unfulfillable' if shortage_rows else ('fulfillable' if rows else None), + 'shortage': {'lines': shortage_rows}, + 'line_results': rows, + } +def _latest_export_upload_facts(task: ShippingNotice) -> tuple[Any | None, Any | None]: + """读取最新导出 Artifact 与上传 Attempt,作为正式 Notice 的只读运行投影。""" + artifact = latest_export_artifact(task) + attempt = ( + ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)) + .order_by(ShippingUploadAttempt.attempt_no.desc(), ShippingUploadAttempt.id.desc()).first() + if artifact is not None else None + ) + return artifact, attempt + + +def _snapshot_order_values(snapshot: ShippingOrderSnapshot) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, list[dict[str, Any]]]]: + """按冻结时的 Schema 还原订单头、订单行及展示契约,禁止回读可变 Extraction。""" + fields = list((getattr(snapshot.schema_version, 'definition_json', None) or {}).get('fields') or []) + header_configs = [item for item in fields if item.get('scope') == 'header'] + line_configs = [item for item in fields if item.get('scope') == 'line'] + + def _display(config: dict[str, Any]) -> dict[str, Any]: + return { + 'field_code': str(config.get('field_code') or ''), + 'display_name': str(config.get('display_name') or config.get('field_code') or ''), + 'scope': str(config.get('scope') or ''), + 'value_type': str(config.get('value_type') or 'string'), + 'sequence': int(config.get('sequence') or 0), + } + + header_values = dict(snapshot.header_values_json or {}) + header = { + str(config.get('field_code') or ''): header_values.get(str(config.get('field_id') or '')) + for config in header_configs + if str(config.get('field_code') or '') + } + lines = [ + { + str(config.get('field_code') or ''): dict(line.field_values_json or {}).get(str(config.get('field_id') or '')) + for config in line_configs + if str(config.get('field_code') or '') + } + for line in sorted(snapshot.lines, key=lambda item: (int(item.position), int(item.id))) + ] + return header, lines, { + 'header_fields': [_display(config) for config in header_configs], + 'line_fields': [_display(config) for config in line_configs], + } + + +def _order_values_for_projection(task: ShippingOrderTask | ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, list[dict[str, Any]]]]: + """冻结后统一读取 Snapshot;冻结前才允许读取当前已接受的 Extraction。""" + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None + if snapshot is not None: + return _snapshot_order_values(snapshot) + return ( + current_header_field_values_or_empty(owner), + current_line_field_values_or_empty(owner), + current_order_field_display_or_empty(owner), + ) + + def _serialize_inventory_snapshot(task: ShippingNotice) -> dict[str, Any] | None: """工作台任务摘要中的库存快照投影。""" from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link @@ -428,6 +624,47 @@ def _serialize_inventory_snapshot(task: ShippingNotice) -> dict[str, Any] | None return serialize_inventory_snapshot_link(task) +def _order_task_customer_projection(task: ShippingOrderTask) -> dict[str, Any]: + """从正式客户识别结果读取 OT 客户确认事实。""" + from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts + + facts = customer_resolution_facts(task) + customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None + resolution = facts['resolution'] + return { + 'customer_id': facts['customer_id'], + 'customer_name_snapshot': getattr(customer, 'standard_name', None), + 'customer_short_code_snapshot': getattr(customer, 'short_code', None), + 'status': facts['status'], + 'resolution_method': getattr(resolution, 'confirmation_method', None), + } + + +def _order_task_inventory_projection(task: ShippingOrderTask) -> dict[str, Any]: + """从 CandidateSet 与行级 Match 读取 OT 库存路由投影,禁止读 OT 旧列。""" + from app.services.shipping_notice.inventory_candidate_projection import project_inventory_candidate_facts + + facts = project_inventory_candidate_facts(task) + sources = list(facts.get('sources') or []) + source_codes = [str(item.get('source_code') or '').strip().upper() for item in sources] + source_codes = [item for item in source_codes if item] + single_source = source_codes[0] if len(source_codes) == 1 else None + versions = { + str(item.get('source_config_version') or '').strip() + for item in sources if str(item.get('source_config_version') or '').strip() + } + return { + 'inventory_source_code': single_source, + 'inventory_source_status': 'candidates_frozen' if facts.get('current_set') else 'unresolved', + 'inventory_source_method': 'candidate_set' if facts.get('current_set') else None, + 'inventory_source_config_version': next(iter(versions)) if len(versions) == 1 else None, + 'inventory_routing_fingerprint': ( + (facts.get('current_set') or {}).get('input_fingerprint') + if isinstance(facts.get('current_set'), dict) else None + ), + } + + def _task_version_chain_fields(task: ShippingNotice) -> dict[str, Any]: """ 组装任务版本链与重复决策投影字段。 @@ -450,6 +687,7 @@ def _task_version_chain_fields(task: ShippingNotice) -> dict[str, Any]: src = db.session.get(ShippingNotice, int(task.duplicate_source_task_id)) if src is not None: duplicate_source_task_no = src.task_no + candidate = db.session.get(ShippingOrderCandidate, task.source_candidate_id) if getattr(task, 'source_candidate_id', None) else None return { 'document_version': int(task.document_version or 1), 'supersedes_task_no': supersedes_task_no, @@ -457,8 +695,8 @@ def _task_version_chain_fields(task: ShippingNotice) -> dict[str, Any]: 'duplicate_source_task_no': duplicate_source_task_no, 'duplicate_resolution_type': task.duplicate_resolution_type, 'duplicate_override_reason': task.duplicate_override_reason, - 'business_fingerprint': task.business_fingerprint, - 'fingerprint_version': task.fingerprint_version, + 'business_fingerprint': getattr(candidate, 'business_fingerprint', None), + 'fingerprint_version': getattr(candidate, 'fingerprint_version', None), } @@ -485,7 +723,7 @@ def _serialize_source_candidate_projection(task: ShippingNotice) -> dict[str, An 并投影当前字段裁决与不可变 Observation 历史; Candidate 已清理或不存在时返回 None,不阻断 Task Detail。 """ - if not task.source_candidate_id: + if not getattr(task, 'source_candidate_id', None): return None candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id)) if candidate is None: @@ -518,6 +756,11 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str """按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。""" from app.services.shipping_notice.rpa import rpa_runtime_mode + workflow_owner = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if getattr(task, 'order_task_id', None) else task + ) + if projection == TaskProjection.TOOL: from app.services.shipping_notice.user_facing_status import strip_internal_task_fields @@ -525,55 +768,139 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str if projection == TaskProjection.TOOL_INTERNAL: return _task_tool_payload(task) if projection == TaskProjection.SUMMARY: - step_payload = task.step_payload_json or {} - header = current_header_field_values_or_empty(task) + if isinstance(task, ShippingOrderTask): + header, _lines, _field_display = _order_values_for_projection(task) + customer = _order_task_customer_projection(task) + inventory = _order_task_inventory_projection(task) + from app.services.shipping_notice.task_disposition_service import task_disposition_capability + disposition_capabilities = { + action: { + 'allowed': result.allowed, + 'code': result.code, + 'reason': result.reason, + } + for action in ('delete', 'void', 'archive', 'restore') + for result in (task_disposition_capability(task, action),) + } + step_payload = task.step_payload_json or {} + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + match_facts = list(load_current_match_facts_by_task(task.id).values()) + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + has_shortage = any( + str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'} + or str(row.get('match_result') or '').strip().lower() != 'matched' + for row in match_facts + ) + return { + 'id': task.id, + 'task_no': task.task_no, + 'order_task_no': task.task_no, + 'source_type': task.source_type, + 'customer_name': header.get('customer_name'), + 'customer_id': customer['customer_id'], + 'customer_name_snapshot': customer['customer_name_snapshot'], + 'customer_short_code_snapshot': customer['customer_short_code_snapshot'], + 'current_step': task.stage, + 'stage': task.stage, + 'status': task.status, + 'lifecycle_status': str(getattr(task, 'lifecycle_status', 'active') or 'active'), + 'deleted_at': task.deleted_at.isoformat() if getattr(task, 'deleted_at', None) else None, + 'voided_at': task.voided_at.isoformat() if getattr(task, 'voided_at', None) else None, + 'void_reason': getattr(task, 'void_reason', None), + 'archived_at': task.archived_at.isoformat() if getattr(task, 'archived_at', None) else None, + 'match_status': ('unfulfillable' if has_shortage else ('fulfillable' if match_facts else None)), + 'pending_human_reason': task_blocking_reason(task), + 'error_message': task.error_message, + 'conversation_id': task.conversation_id, + 'step_payload': step_payload, + 'destination_code': header.get('destination_code'), + 'destination_city': header.get('destination_city'), + 'destination_country': header.get('destination_country'), + 'warehouse_hint': header.get('warehouse_hint'), + **inventory, + 'inventory_snapshot': _serialize_inventory_snapshot(task), + 'shortage': {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}, + 'line_results': match_facts, + 'order_snapshot_id': getattr(workflow_owner, 'order_snapshot_id', None), + 'progress_version': task.progress_version, + 'created_at': task.created_at.isoformat() if task.created_at else None, + 'updated_at': task.updated_at.isoformat() if task.updated_at else None, + 'disposition_capabilities': disposition_capabilities, + } + workflow_payload = getattr(workflow_owner, 'step_payload_json', None) or {} + step_payload = workflow_payload + header = current_header_field_values_or_empty(workflow_owner) + from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + inventory_facts = active_inventory_runtime_facts(workflow_owner) + source_codes = task_frozen_inventory_source_codes(workflow_owner) + routing = (getattr(inventory_facts.get('candidate_set'), 'routing_rule_version_json', None) or {}) + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + match_task_id = getattr(workflow_owner, 'id', None) or task.id + match_facts = list(load_current_match_facts_by_task(match_task_id).values()) + match_status_projection = ( + 'unfulfillable' if any( + str(row.get('match_result') or '').strip().lower() != 'matched' + or str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'} + for row in match_facts + ) else ('fulfillable' if match_facts else None) + ) + artifact, upload_attempt = _latest_export_upload_facts(task) + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status + upload_status_projection = project_notice_upload_status(task) + customer_projection = _order_task_customer_projection(workflow_owner) if isinstance(workflow_owner, ShippingOrderTask) else {} + source_candidate = db.session.get(ShippingOrderCandidate, workflow_owner.candidate_id) if isinstance(workflow_owner, ShippingOrderTask) and workflow_owner.candidate_id else None + source_document = db.session.get(ShippingOrderDocument, source_candidate.primary_document_id) if source_candidate and source_candidate.primary_document_id else None data = { "id": task.id, "task_no": task.task_no, "business_no": task.business_no, "source_type": task.source_type, - "source_file_name": task.source_file_name, - "source_file_type": task.source_file_type, - "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.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, - "upload_status": task.upload_status, - "upload_mode": task.upload_mode, - "upload_attempt": task.upload_attempt, - "pending_human_reason": task.pending_human_reason, - "error_message": task.error_message or task.upload_error_message, + "source_file_name": getattr(source_document, 'filename', None), + "source_file_type": getattr(workflow_owner, 'source_type', None), + "customer_name": header.get('customer_name'), + "customer_resolution_status": customer_projection.get('status'), + "customer_resolution_method": customer_projection.get('resolution_method'), + "customer_id": customer_projection.get('customer_id'), + "customer_name_snapshot": customer_projection.get('customer_name_snapshot'), + "customer_short_code_snapshot": customer_projection.get('customer_short_code_snapshot'), + "current_step": getattr(workflow_owner, 'current_step', None) or getattr(workflow_owner, 'stage', None), + "review_status": getattr(workflow_owner, 'review_status', None), + "match_status": match_status_projection, + "upload_status": upload_status_projection, + "upload_mode": getattr(upload_attempt, 'mode', None), + "upload_attempt": getattr(upload_attempt, 'attempt_no', None), + "pending_human_reason": getattr(workflow_owner, 'pending_human_reason', None), + "error_message": getattr(workflow_owner, 'error_message', None) or getattr(upload_attempt, 'error_message', None), "lifecycle_status": str(getattr(task, 'lifecycle_status', 'active') or 'active'), "deleted_at": task.deleted_at.isoformat() if getattr(task, 'deleted_at', None) else None, "voided_at": task.voided_at.isoformat() if getattr(task, 'voided_at', None) else None, "void_reason": getattr(task, 'void_reason', None), "archived_at": task.archived_at.isoformat() if getattr(task, 'archived_at', None) else None, "conversation_id": task.conversation_id, - "export_file_name": task.export_file_name, - "freight_ref_no": task.freight_ref_no, + "export_file_name": getattr(artifact, 'file_name', None), + "freight_ref_no": getattr(upload_attempt, 'freight_ref_no', None), + "export_version": getattr(artifact, 'id', None), + "idempotency_key": getattr(upload_attempt, 'idempotency_key', None), "step_payload": step_payload, "rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None), "rpa_inventory_source": step_payload.get("rpa_inventory_source") if isinstance(step_payload, dict) else None, "inventory_source_resolution": step_payload.get("inventory_source_resolution") if isinstance(step_payload, dict) else None, - "destination_code": task.destination_code, - "destination_city": task.destination_city, - "destination_country": task.destination_country, - "warehouse_hint": task.warehouse_hint, - "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": _serialize_inventory_snapshot(task), - "shortage": task.shortage_json, - "line_results": task.line_results_json or [], + "destination_code": header.get('destination_code'), + "destination_city": header.get('destination_city'), + "destination_country": header.get('destination_country'), + "warehouse_hint": header.get('warehouse_hint'), + "inventory_source_code": source_codes[0] if len(source_codes) == 1 else None, + "inventory_warehouse_id": (_serialize_inventory_snapshot(workflow_owner) or {}).get("warehouse_id"), + "inventory_source_status": 'resolved' if len(source_codes) == 1 else ('candidates_frozen' if source_codes else 'unresolved'), + "inventory_source_method": routing.get('adjudication_method'), + "inventory_source_config_version": inventory_facts.get('source_config_version'), + "inventory_routing_fingerprint": routing.get('routing_fingerprint'), + "inventory_snapshot": _serialize_inventory_snapshot(workflow_owner), + "shortage": {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}, + "line_results": match_facts, "created_at": task.created_at.isoformat() if task.created_at else None, "updated_at": task.updated_at.isoformat() if task.updated_at else None, } @@ -591,33 +918,58 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str } return data if projection == TaskProjection.DETAIL: - step_payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - header = current_header_field_values_or_empty(task) - order_field_display = current_order_field_display_or_empty(task) + if isinstance(task, ShippingOrderTask): + from app.services.shipping_notice.task_disposition_service import task_disposition_capability + data = serialize_task(task, TaskProjection.SUMMARY) + header, lines, field_display = _order_values_for_projection(task) + data.update({ + 'lines': lines, + 'order_header': header, + 'order_header_fields': field_display['header_fields'], + 'order_line_fields': field_display['line_fields'], + 'order_snapshot_id': task.order_snapshot_id, + 'order_data_version': int(task.order_data_version or 1), + 'parse_validation': _dict_or_none((task.step_payload_json or {}).get('parse_validation')), + 'process_field_gate': _dict_or_none((task.step_payload_json or {}).get('process_field_gate')), + }) + data['disposition_capabilities'] = data.get('disposition_capabilities') or { + action: { + 'allowed': result.allowed, + 'code': result.code, + 'reason': result.reason, + } + for action in ('delete', 'void', 'archive', 'restore') + for result in (task_disposition_capability(task, action),) + } + return data + step_payload = getattr(workflow_owner, 'step_payload_json', None) if isinstance(getattr(workflow_owner, 'step_payload_json', None), dict) else {} + header = current_header_field_values_or_empty(workflow_owner) + order_field_display = current_order_field_display_or_empty(workflow_owner) data = serialize_task(task, TaskProjection.SUMMARY) + match_projection = _current_match_projection(task) data.update({ "customer_code": header.get('customer_code'), "ship_to": header.get('ship_to') or header.get('ship_to_address'), "po_number": header.get('po_number'), "required_date": header.get('required_date'), "step_payload": step_payload, - "export_version": task.export_version, - "idempotency_key": task.idempotency_key, - "lines": current_line_field_values_or_empty(task), + "export_version": getattr(_latest_export_upload_facts(task)[0], 'id', None), + "idempotency_key": getattr(_latest_export_upload_facts(task)[1], 'idempotency_key', None), + "lines": current_line_field_values_or_empty(workflow_owner), "order_header": header, "order_header_fields": order_field_display['header_fields'], "order_line_fields": order_field_display['line_fields'], - "shortage": task.shortage_json, - "line_results": task.line_results_json or [], - "parse_confidence": task.parse_confidence, - "error_message": task.error_message, + "shortage": match_projection['shortage'], + "line_results": match_projection['line_results'], + "parse_confidence": getattr(workflow_owner, 'parse_confidence', None), + "error_message": getattr(workflow_owner, 'error_message', None), # [STEP] 稳定顶层投影解析门禁与来源 Candidate 审计,供工作台持久只读展示。 "parse_validation": _dict_or_none(step_payload.get("parse_validation")), "process_field_gate": _dict_or_none(step_payload.get("process_field_gate")), "source_candidate": _serialize_source_candidate_projection(task), # 工作台据此隐藏冻结按钮;是否可冻结仍由写路径重算,不能信任前端状态。 - "order_snapshot_id": task.order_snapshot_id, - "order_data_version": int(task.order_data_version or 1), + "order_snapshot_id": getattr(workflow_owner, 'order_snapshot_id', None), + "order_data_version": int(getattr(workflow_owner, 'order_data_version', 1) or 1), "field_conflicts": _serialize_open_field_conflicts(task), **_fulfillment_timeline(task), "events": [ @@ -631,7 +983,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str "after_json": e.after_json, "created_at": e.created_at.isoformat() if e.created_at else None, } - for e in sorted(task.events or [], key=lambda x: x.created_at or "") + for e in sorted(getattr(task, 'events', None) or [], key=lambda x: x.created_at or "") ], }) return data @@ -643,30 +995,153 @@ def serialize_task_for_tool(task: ShippingNotice) -> dict[str, Any]: return serialize_task(task, TaskProjection.TOOL) -def task_todo_category(task: ShippingNotice) -> str: +def fetch_gate_positions(task_ids: list[int]) -> dict[int, dict[str, Any]]: """ - 由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。 + 一次查询批量任务当前 gate 位置,供待办/列表映射 position(避免 N+1)。 - 核心逻辑:wait_manual_upload→manual_upload(含 Excel 导出后待登记); - complete→done;must_human 且属复核入口→review,其余 must_human→exception; - auto_continue→in_progress。 - 筛选 manual_upload 时 SQL 侧亦覆盖 waiting_upload / 有导出文件的任务。 + 核心逻辑:``ShippingProcessExecution.task_id IN (...)``;同 task 多 Execution 时 + 后写入覆盖前写入(调用方若需 active-only 可再滤 status)。 + + Args: + task_ids: OT 主键列表。 + + Returns: + ``{task_id: {'current_gate_code', 'status'}}``;无命中的 id 不出现。 + """ + from app.models import ShippingProcessExecution + + ids = [int(i) for i in task_ids if i is not None] + if not ids: + return {} + rows = ShippingProcessExecution.query.filter(ShippingProcessExecution.task_id.in_(ids)).all() + return { + int(getattr(r, 'task_id', 0)): { + 'current_gate_code': getattr(r, 'current_gate_code', None), + 'status': getattr(r, 'status', None), + } + for r in rows + if getattr(r, 'task_id', None) is not None + } + + +def _user_status_from_gate_pos(gate_pos: dict[str, Any] | None) -> str: + """ + 将 Execution / Gate 摘要 status 粗映射为 derive_user_mode 的 user_status。 + + 核心逻辑:blocked* → waiting_human;completed/done → completed;failed* → failed;其余 running。 + """ + if not isinstance(gate_pos, dict): + return 'running' + status = str(gate_pos.get('status') or '').strip().lower() + if status in {'blocked_manual', 'blocked_retryable', 'blocked'}: + return 'waiting_human' + if status in {'completed', 'done'}: + return 'completed' + if status in {'failed_terminal', 'failed'}: + return 'failed' + return 'running' + + +def _todo_category_from_gate( + gate_pos: dict[str, Any] | None, + review_status: Any, + *, + lifecycle_stage: str | None = None, +) -> str: + """ + 从 Gate 位置推导 todo_category(替代 user_mode 路径)。 + + 核心逻辑:derive_user_mode + derive_position → derive_todo_category。 + + Args: + gate_pos: ``{'current_gate_code', 'status'}``;可为 None(仅靠 review_status)。 + review_status: 任务复核处置。 + lifecycle_stage: 可选生命周期,供 wait_manual_upload 判定。 Returns: review | exception | manual_upload | in_progress | done """ + from app.services.shipping_notice.process_gate_contract import ( + derive_position, + derive_todo_category, + derive_user_mode, + ) + + pos_payload = gate_pos if isinstance(gate_pos, dict) else {} + user_mode = derive_user_mode( + user_status=_user_status_from_gate_pos(pos_payload), + gate_code=pos_payload.get('current_gate_code'), + review_status=review_status, + lifecycle_stage=lifecycle_stage, + ) + position = derive_position( + gate_code=pos_payload.get('current_gate_code'), + review_status=review_status, + ) + return derive_todo_category(user_mode=user_mode, position=position) + + +def _todo_category_from_process_gate( + process_gate: dict[str, Any] | None, + review_status: Any, +) -> str | None: + """ + 从用户 Gate 摘要推导 todo_category;无 current_gate_code 时返回 None 供回退。 + + 核心逻辑:优先 current_blocking_gate.status,否则摘要 status / current_gate。 + """ + if not isinstance(process_gate, dict) or not process_gate.get('current_gate_code'): + return None + gate_view = process_gate.get('current_blocking_gate') or process_gate.get('current_gate') or {} + if not isinstance(gate_view, dict): + gate_view = {} + status = ( + gate_view.get('status') + or process_gate.get('status') + or process_gate.get('gate_status') + ) + return _todo_category_from_gate( + { + 'current_gate_code': process_gate.get('current_gate_code') or gate_view.get('gate_code'), + 'status': status, + }, + review_status, + lifecycle_stage=process_gate.get('lifecycle_stage'), + ) + + +def task_todo_category(task: ShippingNotice) -> str: + """ + 推导待办分类(服务端唯一口径):优先 Gate,无 Execution 回退 position/user_mode。 + + 核心逻辑:wait_manual_upload→manual_upload;complete→done; + must_human 且属复核入口→review,其余 must_human→exception; + auto_continue→in_progress。 + SQL CASE 仍为粗筛近似。 + + Returns: + review | exception | manual_upload | in_progress | done + """ + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task + + gated = _todo_category_from_process_gate( + _process_gate_user_summary_for_task(task), + getattr(task, 'review_status', None), + ) + if gated is not None: + return gated ui = resolve_task_ui_state(task) - return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind) + return _todo_category_from_ui(ui.position, ui.user_mode) -def _todo_category_from_ui(checkpoint: str | None, kind: CheckpointKind) -> str: - """将 checkpoint_kind(及复核入口集合)映射为 todo_category。""" - if kind == CheckpointKind.WAIT_MANUAL_UPLOAD: +def _todo_category_from_ui(position: str | None, kind: UserMode) -> str: + """将 user_mode(及复核入口位置集合)映射为 todo_category(无 Gate 时回退)。""" + if kind == UserMode.WAIT_MANUAL_UPLOAD: return "manual_upload" - if kind == CheckpointKind.COMPLETE: + if kind == UserMode.COMPLETE: return "done" - if kind == CheckpointKind.MUST_HUMAN: - if str(checkpoint or "") in _REVIEW_TODO_CHECKPOINTS: + if kind == UserMode.MUST_HUMAN: + if str(position or "") in _REVIEW_TODO_POSITIONS: return "review" return "exception" return "in_progress" @@ -676,32 +1151,33 @@ def _todo_category_from_task_row( row: Any, *, extractions_with_lines: set[int], + gate_pos: dict[str, Any] | None = None, ) -> str: """ 用轻量任务行计算 todo_category,避免索引阶段全量 ORM + 订单行 N+1。 - 核心逻辑:委托 resolve_task_ui_state_from_fields;has_dynamic_order_lines 查批量集合。 + 核心逻辑:若调用方已批量取 gate_pos 则走 Gate;否则仅凭 review_status 薄回退。 """ - extraction_id = getattr(row, "current_order_extraction_id", None) - has_lines = ( - extraction_id is not None - and int(extraction_id) in extractions_with_lines + del extractions_with_lines # 领域行事实不再参与位置裁决 + if gate_pos is not None and gate_pos.get('current_gate_code'): + return _todo_category_from_gate( + gate_pos, + getattr(row, 'review_status', None), + ) + from app.services.shipping_notice.process_gate_contract import ( + derive_position, + derive_todo_category, + derive_user_mode, ) - upload_status = str(getattr(row, "upload_status", None) or "").strip().lower() - if upload_status in {"uploaded", "succeeded", "success"}: - return "done" - ui = resolve_task_ui_state_from_fields( - review_status=getattr(row, "review_status", None), - pending_human_reason=getattr(row, "pending_human_reason", 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), - match_status=getattr(row, "match_status", None), - export_file_path=getattr(row, "export_file_path", None), - has_dynamic_order_lines=has_lines, - upload_req_options=[], + review_status = getattr(row, 'review_status', None) + position = derive_position(gate_code=None, review_status=review_status) + user_mode = derive_user_mode( + user_status=None, + gate_code=None, + review_status=review_status, + lifecycle_stage=None, ) - return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind) + return derive_todo_category(user_mode=user_mode, position=position) def _extractions_with_accepted_lines(extraction_ids: set[int]) -> set[int]: @@ -755,7 +1231,7 @@ def _latest_task_event_summary(task: ShippingNotice) -> dict[str, Any] | None: 核心逻辑:按 created_at/id 降序取一条,投影 event_type / created_at / detail。 """ - if task.id is None: + if isinstance(task, ShippingOrderTask) or task.id is None: return None event = ( ShippingTaskEvent.query.filter_by(task_id=task.id) @@ -776,10 +1252,11 @@ def _artifact_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None: """ 投影任务导出 Artifact 摘要(Excel 文件名/路径);无导出时返回 None。 - 核心逻辑:优先读任务上的 export_file_*;有路径或文件名即视为有摘要。 + 核心逻辑:只读取 ShippingExportArtifact;Notice 不保存导出文件投影。 """ - file_name = str(task.export_file_name or "").strip() or None - file_path = str(task.export_file_path or "").strip() or None + artifact = latest_export_artifact(task) + file_name = str(getattr(artifact, 'file_name', '') or "").strip() or None + file_path = str(getattr(artifact, 'file_path', '') or "").strip() or None if not file_name and not file_path: return None return { @@ -792,47 +1269,62 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: """ 投影发货通知列表需要的项次、料号、数量与当前库存事实。 - 核心逻辑:Notice 行定义“本通知包含哪些业务行”;项次(line_no)经 - order_line_no_resolver 统一解析(字段真实值 → 客户 PO 行号 → 展示序号), - 并附 line_no_source 标注,禁止前端按 position 或序号自行推导业务项次。 + 核心逻辑:Notice 行定义“本通知包含哪些业务行”;项次直接读取 + ShippingNoticeLine.line_no。该值在通知创建时按本通知从 1 开始编号, + 不允许由订单字段、客户 PO 行号或展示序号派生。 当前库存只读取同 Notice、`is_current=true` 的匹配事实;未找到匹配事实时明确 返回 null,禁止由前端估算库存。 """ if task.id is None: return [] - matches_by_line_key = { - str(item.line_key): item + if isinstance(task, ShippingOrderTask): + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if task.order_snapshot_id else None + return [{ + 'line_no': int(line.line_no), + 'part_number': line.part_number, + 'customer_part_number': (line.field_values_json or {}).get('customer_part_number'), + 'reservation_id': line.reservation_id, + 'shipment_qty': str(line.qty) if line.qty is not None else None, + 'available_qty': None, + 'shortage_qty': None, + 'inventory_status': None, + } for line in (getattr(snapshot, 'lines', None) or [])] + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) if getattr(task, 'order_task_id', None) else None + snapshot = db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id)) if owner and owner.order_snapshot_id else None + if snapshot is not None: + matches_by_snapshot_line_id = { + int(item.snapshot_line_id): item + for item in ShippingNoticeLineInventoryMatch.query.filter( + ShippingNoticeLineInventoryMatch.task_id == int(owner.id), + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ).all() + if item.snapshot_line_id is not None + } + # Snapshot 仅提供订单冻结事实;正式通知的项次、料号、发运数量和预约号 + # 必须来自本 Notice 的 ShippingNoticeLine,避免不同通知波次串行。 + matches_by_snapshot_line_id = { + int(item.snapshot_line_id): item for item in ShippingNoticeLineInventoryMatch.query.filter( ShippingNoticeLineInventoryMatch.task_id == int(task.id), ShippingNoticeLineInventoryMatch.is_current.is_(True), ).all() - if item.line_key + if item.snapshot_line_id is not None } rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by( ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(), ).all() - from app.services.shipping_notice.order_line_no_resolver import ( - notice_line_field_id_map, - resolve_order_line_no_projection, - ) - - field_id_by_code = notice_line_field_id_map(task) return [{ - **resolve_order_line_no_projection( - field_values=item.field_values_json, - field_id_by_code=field_id_by_code, - fallback_sequence=(int(item.position) + 1) if item.position is not None else None, - ), + 'line_no': int(item.line_no), '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, + 'available_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).available_qty + if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, + 'shortage_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).shortage_qty + if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, + 'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).inventory_status + if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, } for item in rows] @@ -840,14 +1332,17 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any] """ 将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。 - 核心逻辑:优先 Notice.order_task_id → ShippingOrderTask;有 OT 时用领域事实 - 映射为 shipping_processing_status(与 shipping_processing_projection 同源), + 核心逻辑:实体本身若是 ShippingOrderTask,直接以自身为 OT(禁止再经 + order_task_id 反查——OT 无该字段,否则会把 SUMMARY 已写入的 order_task_no + 冲成 null,导致工作台右卡 work-item 投影永不启动);Notice 则经 + order_task_id → ShippingOrderTask。有 OT 时用领域事实映射为 + shipping_processing_status(与 shipping_processing_projection 同源), 并注入 shipping_processing_stage / progress_version / order_task_no; 另附带 review_run_no / owner_agent_id / conversation_id(经 OT.extraction_run), 供任务中心「进入订单处理」深链。 Args: - task: ShippingNotice(正式发货任务)。 + task: ShippingNotice 或 ShippingOrderTask。 data: 就地写入的序列化字典。 """ from app.models import ShippingOrderProcessingRun, ShippingOrderTask @@ -855,20 +1350,17 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any] _notice_domain_progress_stage, ) - order_task = None - order_task_id = getattr(task, 'order_task_id', None) - if order_task_id is not None: - order_task = db.session.get(ShippingOrderTask, int(order_task_id)) - if order_task is None: - # 回退:OT.shipping_notice_id → Notice(双向挂接未齐时)。 - order_task = ( - db.session.query(ShippingOrderTask) - .filter(ShippingOrderTask.shipping_notice_id == int(task.id)) - .order_by(ShippingOrderTask.id.asc()) - .first() - ) - - status, stage = _notice_domain_progress_stage(task) + # [STEP 1] 解析权威 OT:OT 实体即自身;Notice 经 order_task_id 反查。 + order_task: ShippingOrderTask | None = None + if isinstance(task, ShippingOrderTask): + order_task = task + status = str(getattr(task, 'status', '') or '').strip() or 'processing' + stage = str(getattr(task, 'stage', '') or '').strip() or None + else: + order_task_id = getattr(task, 'order_task_id', None) + if order_task_id is not None: + order_task = db.session.get(ShippingOrderTask, int(order_task_id)) + status, stage = _notice_domain_progress_stage(task) data['shipping_processing_status'] = status data['shipping_processing_stage'] = ( str(getattr(order_task, 'stage', None) or '').strip() or stage @@ -878,6 +1370,7 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any] or getattr(task, 'progress_version', None) or 1 ) + # [STEP 2] order_task_no 必须恒为 OT 编号;OT 自序列化时不得落成 null。 data['order_task_no'] = ( str(getattr(order_task, 'task_no', None) or '').strip() or None ) @@ -936,13 +1429,19 @@ def _enrich_task_center_fields( ui_state = build_task_ui_state(task, include_stage_context=include_stage_context) data["ui_state"] = ui_state - # [PERF] todo_category 与 ui_state 同源(均由 resolve_task_ui_state 推导):直接在 - # 已构建的 ui_state 上推导,避免 task_todo_category 在请求内对同一任务再算一次 - # resolve_task_ui_state(每次含 has_dynamic_order_lines 的取数),削减重复查询。 - data["todo_category"] = _todo_category_from_ui( - ui_state.get("checkpoint_code"), - CheckpointKind(str(ui_state.get("checkpoint_kind"))), + # [PERF] 优先复用 ui_state.process_gate(build_task_ui_state 已查 Execution); + # 无 Gate 时回退 position/user_mode,避免再跑一次 resolve_task_ui_state。 + gated = _todo_category_from_process_gate( + ui_state.get("process_gate") if isinstance(ui_state, dict) else None, + ui_state.get("review_status") if isinstance(ui_state, dict) else getattr(task, 'review_status', None), ) + if gated is not None: + data["todo_category"] = gated + else: + data["todo_category"] = _todo_category_from_ui( + ui_state.get("position") if isinstance(ui_state, dict) else None, + UserMode(str((ui_state or {}).get("user_mode") or UserMode.AUTO_CONTINUE)), + ) _inject_unified_processing_fields(task, data) # [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。 data['workflow_item'] = None @@ -969,6 +1468,46 @@ def serialize_task_summary( ) +def _serialize_task_workbench_shell(task: ShippingNotice) -> dict[str, Any]: + """ + 订单生命周期工作台身份壳:不跑 SUMMARY/DETAIL 重投影。 + + 核心逻辑:工作台只消费 task_no / business_no / export_artifacts 等身份字段, + 以及 enrich 写入的 ui_state(含 stage_context)与行摘要;禁止先算 DETAIL 再 pop。 + + Args: + task: ShippingNotice 或 ShippingOrderTask。 + + Returns: + 供 ``_enrich_task_center_fields`` 就地补全的最小字典。 + """ + created_at = getattr(task, 'created_at', None) + updated_at = getattr(task, 'updated_at', None) + stage = getattr(task, 'stage', None) or getattr(task, 'current_step', None) + data: dict[str, Any] = { + 'id': getattr(task, 'id', None), + 'task_no': task.task_no, + 'source_type': getattr(task, 'source_type', None), + 'status': getattr(task, 'status', None), + 'stage': stage, + 'current_step': getattr(task, 'current_step', None) or stage, + 'progress_version': getattr(task, 'progress_version', None), + 'conversation_id': getattr(task, 'conversation_id', None), + 'created_at': created_at.isoformat() if created_at else None, + 'updated_at': updated_at.isoformat() if updated_at else None, + } + if isinstance(task, ShippingOrderTask): + data['order_task_no'] = task.task_no + data['order_snapshot_id'] = getattr(task, 'order_snapshot_id', None) + data['order_data_version'] = int(getattr(task, 'order_data_version', 1) or 1) + data['business_no'] = None + return data + data['business_no'] = getattr(task, 'business_no', None) + # Notice 人工上传弹窗仍读 export_artifacts;比整份 DETAIL 轻一个数量级。 + data.update(_fulfillment_timeline(task)) + return data + + def serialize_task_detail( task: ShippingNotice, *, @@ -986,20 +1525,14 @@ def serialize_task_detail( is_admin: 是否管理员视图。 include_stage_context: 是否让内嵌 ui_state 附带 stage_context(避免调用方重复 build)。 view: 投影视图。``full`` 返回完整详情(含复核编辑器数据);``workbench`` 为 - 订单生命周期工作台首屏裁剪版:工作台只消费 ui_state + 进度/产物/行摘要, - 不读取行明细/订单头/事件/字段冲突等复核编辑器重字段。把这些字段从响应剔除, - 避免每次进入工作台都拉取 67KB 级详情(对应 /shipping-tasks/:task_no 的大响应)。 + 订单生命周期工作台首屏投影:只建身份壳再 enrich(ui_state / 行摘要 / 产物), + **不**进入 SUMMARY/DETAIL 重投影,避免先算 lines/header/match 再剔除。 """ - data = serialize_task(task, TaskProjection.DETAIL) + # [PERF] workbench:算之前就轻;禁止 DETAIL 后再 pop。 if view == 'workbench': - # [PERF] 工作台首屏不消费以下复核编辑器字段,剔除后显著缩小响应体与序列化耗时。 - # 仅剔除编辑重字段;ui_state(含 stage_context)、notice_line_summary、 - # artifact_summary、_fulfillment_timeline(export_artifacts) 与进度字段原样保留。 - for key in ( - 'lines', 'order_header', 'order_header_fields', 'order_line_fields', - 'events', 'field_conflicts', - ): - data.pop(key, None) + data = _serialize_task_workbench_shell(task) + else: + data = serialize_task(task, TaskProjection.DETAIL) return _enrich_task_center_fields( task, data, viewer_user_id=viewer_user_id, is_admin=is_admin, include_stage_context=include_stage_context, @@ -1012,10 +1545,33 @@ def list_tasks_for_user( limit: int = 100, ) -> list[dict[str, Any]]: """列出用户可见任务摘要。""" - q = ShippingNotice.query.filter( - (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)) - ) - rows = q.order_by(desc(ShippingNotice.created_at)).limit(max(1, min(limit, 500))).all() + safe_limit = max(1, min(limit, 500)) + notice_refs = ShippingNotice.query.filter( + (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)), + ShippingNotice.deleted_at.is_(None), + ).with_entities( + literal('shipping_notice').label('kind'), ShippingNotice.id.label('entity_id'), + ShippingNotice.created_at.label('sort_at'), ShippingNotice.task_no.label('sort_ref'), + ).statement + ot_refs = ShippingOrderTask.query.filter( + ShippingOrderTask.user_id == int(user_id), + ShippingOrderTask.deleted_at.is_(None), + ).with_entities( + literal('order_task').label('kind'), ShippingOrderTask.id.label('entity_id'), + ShippingOrderTask.created_at.label('sort_at'), ShippingOrderTask.task_no.label('sort_ref'), + ).statement + combined = union_all(notice_refs, ot_refs).subquery('task_refs') + refs = db.session.execute( + select(combined.c.kind, combined.c.entity_id) + .order_by(desc(combined.c.sort_at), desc(combined.c.sort_ref), desc(combined.c.entity_id)) + .limit(safe_limit) + ).all() + notice_ids = [int(entity_id) for kind, entity_id in refs if kind == 'shipping_notice'] + ot_ids = [int(entity_id) for kind, entity_id in refs if kind == 'order_task'] + notices_by_id = {int(row.id): row for row in ShippingNotice.query.filter(ShippingNotice.id.in_(notice_ids)).all()} if notice_ids else {} + ots_by_id = {int(row.id): row for row in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(ot_ids)).all()} if ot_ids else {} + rows = [notices_by_id.get(int(entity_id)) if kind == 'shipping_notice' else ots_by_id.get(int(entity_id)) for kind, entity_id in refs] + rows = [row for row in rows if row is not None] return [ serialize_task_summary(c, viewer_user_id=user_id) for c in rows @@ -1037,36 +1593,60 @@ def list_tasks_page_for_user( """ normalized_page = max(1, int(page)) normalized_page_size = max(1, min(int(page_size), 100)) - q = ShippingNotice.query.filter( + notice_q = ShippingNotice.query.filter( (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)) ) - if lifecycle_status: - normalized_lifecycle = str(lifecycle_status).strip().lower() - if normalized_lifecycle == 'deleted': - q = q.filter(ShippingNotice.deleted_at.is_not(None)) - elif normalized_lifecycle == 'active': - q = q.filter( - ShippingNotice.deleted_at.is_(None), - ShippingNotice.lifecycle_status == 'active', - db.or_( - ShippingNotice.upload_status.is_(None), - db.func.lower(ShippingNotice.upload_status).notin_(('uploaded', 'succeeded', 'success')), - ), - ) - elif normalized_lifecycle == 'voided': - # 作废后移入回收站的任务仍须出现在“已作废”视图,便于业务审计与追溯。 - q = q.filter(ShippingNotice.lifecycle_status == normalized_lifecycle) - else: - q = q.filter(ShippingNotice.deleted_at.is_(None), ShippingNotice.lifecycle_status == normalized_lifecycle) + ot_q = ShippingOrderTask.query.filter(ShippingOrderTask.user_id == int(user_id)) + normalized_lifecycle = str(lifecycle_status or 'active').strip().lower() + if normalized_lifecycle == 'deleted': + notice_q = notice_q.filter(ShippingNotice.deleted_at.is_not(None)) + ot_q = ot_q.filter(ShippingOrderTask.deleted_at.is_not(None)) + elif normalized_lifecycle == 'active': + notice_upload_success = exists(select(1).select_from(ShippingUploadAttempt).join( + ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id, + ).where( + ShippingExportArtifact.task_id == ShippingNotice.id, + ShippingUploadAttempt.status == 'succeeded', + )) + notice_q = notice_q.filter( + ShippingNotice.deleted_at.is_(None), + ShippingNotice.lifecycle_status == 'active', + ~notice_upload_success, + ) + ot_q = ot_q.filter( + ShippingOrderTask.deleted_at.is_(None), + ShippingOrderTask.lifecycle_status == 'active', + ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled', 'canceled'}), + ) else: - q = q.filter(ShippingNotice.deleted_at.is_(None), ShippingNotice.lifecycle_status == 'active') - total = q.order_by(None).count() - rows = ( - q.order_by(desc(ShippingNotice.created_at)) - .offset((normalized_page - 1) * normalized_page_size) - .limit(normalized_page_size) - .all() - ) + notice_q = notice_q.filter(ShippingNotice.lifecycle_status == normalized_lifecycle) + ot_q = ot_q.filter(ShippingOrderTask.lifecycle_status == normalized_lifecycle) + + union_stmt = union_all( + notice_q.with_entities( + literal('shipping_notice').label('kind'), ShippingNotice.id.label('entity_id'), + func.coalesce(ShippingNotice.created_at, ShippingNotice.updated_at).label('sort_at'), + ShippingNotice.task_no.label('sort_ref'), + ).statement, + ot_q.with_entities( + literal('order_task').label('kind'), ShippingOrderTask.id.label('entity_id'), + func.coalesce(ShippingOrderTask.created_at, ShippingOrderTask.updated_at).label('sort_at'), + ShippingOrderTask.task_no.label('sort_ref'), + ).statement, + ).subquery('task_union') + total = int(db.session.execute(select(func.count()).select_from(union_stmt)).scalar_one() or 0) + offset = (normalized_page - 1) * normalized_page_size + page_refs = db.session.execute( + select(union_stmt.c.kind, union_stmt.c.entity_id) + .order_by(desc(union_stmt.c.sort_at), desc(union_stmt.c.sort_ref), desc(union_stmt.c.entity_id)) + .offset(offset).limit(normalized_page_size) + ).all() if offset < total else [] + notice_ids = [int(entity_id) for kind, entity_id in page_refs if kind == 'shipping_notice'] + ot_ids = [int(entity_id) for kind, entity_id in page_refs if kind == 'order_task'] + notices_by_id = {int(row.id): row for row in ShippingNotice.query.filter(ShippingNotice.id.in_(notice_ids)).all()} if notice_ids else {} + ots_by_id = {int(row.id): row for row in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(ot_ids)).all()} if ot_ids else {} + rows = [notices_by_id.get(int(entity_id)) if kind == 'shipping_notice' else ots_by_id.get(int(entity_id)) for kind, entity_id in page_refs] + rows = [row for row in rows if row is not None] return { "items": [ serialize_task_summary(item, viewer_user_id=user_id) @@ -1078,7 +1658,7 @@ def list_tasks_page_for_user( } -def get_task_for_user(task_no: str, user_id: int) -> ShippingNotice | None: +def get_task_for_user(task_no: str, user_id: int) -> ShippingOrderTask | ShippingNotice | None: """ 按 task_no 查找任务并校验写路径归属(严格创建者)。 @@ -1098,7 +1678,7 @@ def get_task_visible_to_user( user_id: int, *, is_admin: bool = False, -) -> ShippingNotice | None: +) -> ShippingOrderTask | ShippingNotice | None: """ 按 task_no 查找当前用户可见的任务(创建者或管理员只读)。 @@ -1170,17 +1750,31 @@ def list_freight_notice_groups_for_task( # [STEP] upload_mode/upload_attempt 从 ShippingUploadAttempt 权威事实解析。 # denormalized Notice.upload_mode 恒为 None,不能作为「人工/RPA」展示来源。 upload_mode, upload_attempt = _task_upload_attempt_facts(notice.id) + latest_attempt = ( + ShippingUploadAttempt.query + .join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id) + .filter(ShippingExportArtifact.task_id == int(notice.id)) + .order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()) + .first() + ) + artifact = ( + ShippingExportArtifact.query + .filter(ShippingExportArtifact.task_id == int(notice.id)) + .order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()) + .first() + ) + from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status items.append({ 'business_no': business_no, 'po_number': po_number, - 'upload_status': notice.upload_status, + # Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。 + 'upload_status': project_notice_upload_status(notice), 'upload_mode': upload_mode, 'upload_attempt': upload_attempt, - 'upload_error_code': notice.upload_error_code, + 'upload_error_code': getattr(latest_attempt, 'error_code', None), # 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。 - 'upload_error_message': (notice.upload_error_message or notice.error_message or '')[:500] or None, - 'pending_human_reason': notice.pending_human_reason, - 'export_file_name': notice.export_file_name, + 'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None, + 'export_file_name': getattr(artifact, 'file_name', None), 'available_actions': available_actions, 'lines': _notice_line_summary_for_task(notice), }) @@ -1231,9 +1825,11 @@ def _notice_po_number(notice: ShippingNotice) -> str: if normalized: return normalized + owner = db.session.get(ShippingOrderTask, notice.order_task_id) if notice.order_task_id else None snapshot = None - if notice.order_snapshot_id: - snapshot = db.session.get(ShippingOrderSnapshot, notice.order_snapshot_id) + snapshot_id = getattr(owner, 'order_snapshot_id', None) + if snapshot_id: + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot: for value in (snapshot.customer_po_number, (snapshot.header_values_json or {}).get('po_number')): normalized = normalize_po_number(value) @@ -1249,18 +1845,25 @@ def _notice_po_number(notice: ShippingNotice) -> str: def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool: - """待办列表客户关键字过滤:匹配 Notice 快照、来源文件名或当前订单头客户名。""" + """待办列表客户关键字过滤:匹配确认客户快照、来源文档或当前订单头证据。""" needle = str(customer or "").strip().lower() if not needle: return True candidates: list[str] = [] - 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)) + owner = task if isinstance(task, ShippingOrderTask) else ( + db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else None + ) + if owner is not None: + customer = _order_task_customer_projection(owner) + for value in (customer['customer_name_snapshot'], customer['customer_short_code_snapshot']): + if value: + candidates.append(str(value)) + docs = db.session.query(ShippingOrderDocument.filename).join( + ShippingOrderCandidate, ShippingOrderCandidate.primary_document_id == ShippingOrderDocument.id, + ).filter(ShippingOrderCandidate.id == owner.candidate_id).all() if owner.candidate_id else [] + candidates.extend(str(row[0]) for row in docs if row[0]) header = current_header_field_values_or_empty(task) - for key in ("customer_name", "bill_to_customer", "ship_to_customer", "customer_code"): + for key in ("customer_name", "ship_to_customer", "customer_code"): value = header.get(key) if value: candidates.append(str(value)) @@ -1268,7 +1871,7 @@ def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool: def _visible_tasks_query_for_todos(user_id: int, *, is_admin: bool = False): - """构造「我的待办」可见任务基础查询(活跃生命周期)。""" + """构造正式 ShippingNotice 的待办查询;OT 由 `_visible_order_tasks_query_for_todos` 提供。""" q = ShippingNotice.query.filter( ShippingNotice.deleted_at.is_(None), ShippingNotice.lifecycle_status == "active", @@ -1279,6 +1882,173 @@ def _visible_tasks_query_for_todos(user_id: int, *, is_admin: bool = False): return q +def _visible_order_tasks_query_for_todos(user_id: int, *, is_admin: bool = False): + """构造库存准备前 OT 待办查询;OT 是正式 Notice 创建前唯一可见根实体。""" + query = ShippingOrderTask.query.filter( + ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled', 'canceled'}), + ~exists( + select(1).select_from(ShippingNotice).where( + ShippingNotice.order_task_id == ShippingOrderTask.id, + ) + ), + ) + if not is_admin: + query = query.filter(ShippingOrderTask.user_id == int(user_id)) + return query + + +def _latest_process_execution_field_sql(task_id_column, field_name: str): + """ + 最新非 superseded Execution 的指定列(scalar subquery),供待办 SQL Gate-first。 + + Args: + task_id_column: OT 主键列表达式(Notice.order_task_id 或 OrderTask.id)。 + field_name: ``current_gate_code`` 或 ``status``。 + """ + column = getattr(ShippingProcessExecution, field_name) + return ( + select(column) + .where( + ShippingProcessExecution.task_id == task_id_column, + ShippingProcessExecution.status != 'superseded', + ) + .order_by(ShippingProcessExecution.id.desc()) + .limit(1) + .scalar_subquery() + ) + + +def _gate_todo_category_sql_whens(task_id_column): + """ + Gate 优先的 todo_category CASE when 列表(对齐 derive_todo_category)。 + + 核心逻辑:复核 gate→review;人工上传 handoff→manual_upload; + 短缺/失败类 gate→exception;准备/匹配运行中→in_progress。 + """ + gate_code = _latest_process_execution_field_sql(task_id_column, 'current_gate_code') + gate_exec_status = _latest_process_execution_field_sql(task_id_column, 'status') + return [ + ( + gate_code.in_(('order_field_extraction', 'customer_resolution', 'reservation_validation')), + literal('review'), + ), + ( + gate_code.in_(('manual_upload_handoff',)), + literal('manual_upload'), + ), + ( + db.and_( + gate_code.in_(('artifact_generation',)), + gate_exec_status.in_(('blocked', 'completed')), + ), + literal('manual_upload'), + ), + ( + db.and_( + gate_code.in_( + ( + 'inventory_sufficiency', + 'freight_upload_rpa', + 'inventory_source_routing', + 'excel_readiness', + ) + ), + gate_exec_status.in_(('blocked', 'failed')), + ), + literal('exception'), + ), + ( + gate_code.in_( + ( + 'inventory_preparation', + 'inventory_matching', + 'inventory_field_mapping', + 'order_freeze_readiness', + 'artifact_generation', + ) + ), + literal('in_progress'), + ), + ] + + +def _order_task_todo_category_sql_expr(): + """按 Gate 优先、再领域事实投影 OT 待办,禁止读取库存 JSON 投影。""" + stage = db.func.lower(db.func.coalesce(ShippingOrderTask.stage, "")) + reason = db.func.lower(db.func.coalesce(ShippingOrderTask.pending_human_reason, "")) + ready_file = exists( + select(1) + .select_from(ShippingTaskInventoryLink) + .join(ShippingInventoryFile, ShippingInventoryFile.id == ShippingTaskInventoryLink.inventory_file_id) + .where( + ShippingTaskInventoryLink.task_id == ShippingOrderTask.id, + ShippingTaskInventoryLink.is_active.is_(True), + ShippingTaskInventoryLink.invalidated_at.is_(None), + ShippingInventoryFile.snapshot_status == 'ready', + ShippingInventoryFile.invalidated_at.is_(None), + ShippingInventoryFile.line_count > 0, + ) + ) + incomplete_match = exists( + select(1) + .select_from(ShippingOrderSnapshotLine) + .where( + ShippingOrderSnapshotLine.snapshot_id == ShippingOrderTask.order_snapshot_id, + ~exists( + select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id, + ShippingNoticeLineInventoryMatch.snapshot_line_id == ShippingOrderSnapshotLine.id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.match_result != 'preparing', + ) + ), + ) + ) + has_shortage = exists( + select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + db.or_( + ShippingNoticeLineInventoryMatch.match_result != 'matched', + db.and_( + ShippingNoticeLineInventoryMatch.shortage_qty.isnot(None), + ShippingNoticeLineInventoryMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')), + ), + ), + ) + ) + manual_gate = exists( + select(1) + .select_from(ShippingProcessExecution) + .join(ShippingProcessGate, ShippingProcessGate.execution_id == ShippingProcessExecution.id) + .where( + ShippingProcessExecution.task_id == ShippingOrderTask.id, + ShippingProcessExecution.status.notin_(('completed', 'cancelled', 'superseded')), + ShippingProcessGate.status.in_(('blocked_manual', 'failed_terminal')), + ) + ) + return case( + *_gate_todo_category_sql_whens(ShippingOrderTask.id), + ( + db.or_( + reason.in_((PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_INVENTORY_SOURCE_UNRESOLVED, PH_SHORTAGE)), + manual_gate, + db.and_(ShippingOrderTask.order_snapshot_id.isnot(None), ~incomplete_match, has_shortage), + ), + literal("exception"), + ), + ( + db.and_( + ShippingOrderTask.order_snapshot_id.isnot(None), + ready_file, + incomplete_match, + ), + literal("in_progress"), + ), + (stage.in_(("inventory_source_resolving", "notification_preparation", "inventory_fetching", "inventory_matching", "order_creating")), literal("in_progress")), + else_=literal("in_progress"), + ) + def _visible_open_review_cases_query(user_id: int, *, is_admin: bool = False): """ 构造建单前开放 Review Case 查询(尚未确认建单)。 @@ -1397,19 +2167,18 @@ def serialize_review_case_todo( "lifecycle_stage": lifecycle_stage, "lifecycle_entries": lifecycle_entries, "intake_parse_authorized": lifecycle_stage == "intake_parse", - "checkpoint": {"code": lifecycle_stage, "kind": str(CheckpointKind.MUST_HUMAN), "label": stage_definition['label']}, + "position": lifecycle_stage, + "user_mode": str(UserMode.MUST_HUMAN), "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": lifecycle_stage, - "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), "summary": { "title": "待人工复核", "message": current_todo, "stage": "待人工复核", - "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), + "user_mode": str(UserMode.MUST_HUMAN), "current_todo": current_todo, "pause_reason": current_todo, "pause_reason_code": ( @@ -1563,24 +2332,21 @@ def serialize_intake_todo( # Intake 尚未有当前有效订单 Candidate;只能进入对话查看解析,不能进入生命周期工作台。 "lifecycle_stage": "intake_parse", "lifecycle_entries": [], - "checkpoint": {"code": "order_field_extraction", "kind": str( - CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE - ), "label": "订单解析"}, + "position": "order_field_extraction", + "user_mode": str( + UserMode.MUST_HUMAN if failed else UserMode.AUTO_CONTINUE + ), "todo": {"title": title, "message": message}, "actions": {"primary": ({"code": "retry_parse", "label": "重新解析", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if failed else None), "secondary": []}, "reason": ({"code": str(intake.error_code or "intake_parse_failed"), "message": message} if failed else None), "lifecycle_status": "active", "process_gate": None, - "checkpoint_code": "order_field_extraction", - "checkpoint_kind": str( - CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE - ), "summary": { "title": title, "message": message, "stage": title, - "checkpoint_kind": str( - CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE + "user_mode": str( + UserMode.MUST_HUMAN if failed else UserMode.AUTO_CONTINUE ), "current_todo": title, "pause_reason": message if failed else None, @@ -1609,17 +2375,30 @@ def _todo_category_sql_filter(allowed: frozenset[str]): 核心逻辑:与 task_todo_category 对齐的保守 OR;精确分类由 _task_todo_category_sql_expr 完成。 """ + workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_pending_reason = select(ShippingOrderTask.pending_human_reason).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_current_step = select(ShippingOrderTask.current_step).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_customer_pending = exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ShippingCustomerShadowResolution.status != 'confirmed', + ) + ) + artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) + upload_success = _verified_upload_success_sql_expr() + upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(('pending', 'running', 'failed', 'unknown')))) clauses = [] if "manual_upload" in allowed: # wait_manual_upload:waiting_upload / 已有导出文件且未 uploaded。 clauses.append( db.or_( - ShippingNotice.upload_status.in_(("pending", "uploading", "failed")), + upload_pending, db.and_( - ShippingNotice.export_file_path.isnot(None), + artifact_exists, db.or_( - ShippingNotice.upload_status.is_(None), - db.func.lower(ShippingNotice.upload_status).notin_(("uploaded", "succeeded", "success")), + ~upload_success, ), ShippingNotice.lifecycle_status == "active", ), @@ -1629,27 +2408,31 @@ def _todo_category_sql_filter(allowed: frozenset[str]): # 已上传/关闭/驳回终态(不含待人工上传登记)。 clauses.append( db.or_( - ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")), - ShippingNotice.review_status == RS_REJECTED, + upload_success, + workflow_review_status == RS_REJECTED, ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")), ) ) if "review" in allowed: clauses.append( db.or_( - ShippingNotice.review_status.isnot(None), - ShippingNotice.pending_human_reason.isnot(None), + workflow_review_status.isnot(None), + workflow_pending_reason.isnot(None), ) ) if "exception" in allowed: - clauses.append(ShippingNotice.pending_human_reason.isnot(None)) + clauses.append(workflow_pending_reason.isnot(None)) if "in_progress" in allowed: clauses.append( db.or_( - ShippingNotice.current_step.isnot(None), - ShippingNotice.inventory_snapshot_id.isnot(None), - ShippingNotice.export_file_path.isnot(None), - ShippingNotice.upload_status.isnot(None), + workflow_current_step.isnot(None), + exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + )), + artifact_exists, + upload_pending, ) ) if not clauses: @@ -1667,7 +2450,9 @@ def _task_has_dynamic_order_lines_sql(): select(1) .select_from(ShippingOrderExtraction) .where( - ShippingOrderExtraction.id == ShippingNotice.current_order_extraction_id, + ShippingOrderExtraction.id == select(ShippingOrderTask.current_order_extraction_id).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery(), ShippingOrderExtraction.status == "accepted", exists( select(1) @@ -1696,81 +2481,108 @@ def _sql_str_blank(column): def _task_todo_category_sql_expr(): """ - 将 resolve_task_ui_state_from_fields 同序映射为 todo_category SQL CASE。 + 待办 todo_category 的 SQL CASE:Gate 优先,再 review_status / 领域标量回退。 - 核心逻辑:分支顺序与状态机一致;直接产出 review|exception|manual_upload|in_progress|done, - 供 UNION 分页与徽标 COUNT 在数据库内过滤,避免轻量全量索引。 + 核心逻辑:不再与 resolve_task_ui_state「同序」;与 ORM + ``task_todo_category`` / ``derive_todo_category`` 对齐,供 UNION 分页与徽标 COUNT。 """ has_lines = _task_has_dynamic_order_lines_sql() - reason = ShippingNotice.pending_human_reason - upload_status = db.func.lower(db.func.coalesce(ShippingNotice.upload_status, "")) - match_status = db.func.lower(db.func.coalesce(ShippingNotice.match_status, "")) + reason = select(ShippingOrderTask.pending_human_reason).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery() + review_status = select(ShippingOrderTask.review_status).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery() + snapshot_id = select(ShippingOrderTask.order_snapshot_id).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery() + customer_pending = exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ShippingCustomerShadowResolution.status != 'confirmed', + ) + ) + artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(("ready", "uploading", "uploaded")))) + upload_success = _verified_upload_success_sql_expr() + upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(("pending", "running", "failed", "unknown")))) + match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + )) return case( - (upload_status.in_(("uploaded", "succeeded", "success")), literal("done")), + (upload_success, literal("done")), (ShippingNotice.lifecycle_status.in_(("archived", "deleted")), literal("done")), ( db.or_( - ShippingNotice.review_status == RS_REJECTED, + review_status == RS_REJECTED, ), literal("done"), ), + # [STEP] Gate-first(经 order_task_id 关联最新 Execution) + *_gate_todo_category_sql_whens(ShippingNotice.order_task_id), ( - db.or_(reason == PH_RSV_REQ, ShippingNotice.review_status == RS_RSV_REQ), + db.or_(reason == PH_RSV_REQ, review_status == RS_RSV_REQ), literal("review"), ), ( - db.or_(reason == PH_LOW_CONF, ShippingNotice.review_status == RS_PARSE_REVIEW), + db.or_(reason == PH_LOW_CONF, review_status == RS_PARSE_REVIEW), literal("review"), ), (reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")), ( db.and_( - ShippingNotice.customer_resolution_status.in_(("pending", "needs_review", "failed", "unresolved")), + customer_pending, ), literal("exception"), ), ( - db.and_(ShippingNotice.order_snapshot_id.is_(None), has_lines), + db.and_(snapshot_id.is_(None), has_lines), literal("in_progress"), ), (reason == PH_RPA_EXHAUSTED, literal("exception")), # Excel 已生成即进入待人工上传登记,不依赖历史 match_status 是否补写。 - (ShippingNotice.export_file_path.isnot(None), literal("manual_upload")), + (artifact_exists, literal("manual_upload")), ( db.and_( - _sql_str_blank(ShippingNotice.review_status), + _sql_str_blank(review_status), _sql_str_blank(reason), - _sql_json_falsy(ShippingNotice.inventory_lines_json), + ~exists().where( + ShippingTaskInventoryLink.task_id == ShippingNotice.order_task_id, + ShippingTaskInventoryLink.is_active.is_(True), + ShippingTaskInventoryLink.invalidated_at.is_(None), + ), ), literal("in_progress"), ), ( db.and_( - _sql_str_blank(ShippingNotice.review_status), + _sql_str_blank(review_status), _sql_str_blank(reason), - _sql_str_blank(ShippingNotice.match_status), + ~match_exists, has_lines, ), literal("in_progress"), ), ( db.and_( - match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), - ShippingNotice.export_file_path.isnot(None), + match_exists, + artifact_exists, ), literal("manual_upload"), ), - (match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), literal("in_progress")), + (match_exists, literal("in_progress")), (reason == PH_INV_UNAVAIL, literal("exception")), (reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")), ( - db.or_(reason == PH_SHORTAGE, ShippingNotice.review_status == RS_SHORTAGE_REVIEW), + db.or_(reason == PH_SHORTAGE, review_status == RS_SHORTAGE_REVIEW), literal("exception"), ), ( db.or_( reason == PH_UPLOAD_RPA_FAILED, - upload_status == "failed", + exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status == "failed")), ), literal("exception"), ), @@ -1778,11 +2590,10 @@ def _task_todo_category_sql_expr(): (reason == PH_RPA_PENDING, literal("exception")), (reason == PH_UPLOAD_RPA_PENDING, literal("exception")), # Excel 后待人工上传登记。 - (upload_status.in_(("pending", "uploading")), literal("manual_upload")), + (upload_pending, literal("manual_upload")), else_=literal("in_progress"), ) - def _todo_sort_key_from_dt(value: Any, ref: str) -> tuple[str, str]: """待办排序键:updated_at 降序 + 稳定引用(测试/调试辅助)。""" if hasattr(value, "isoformat"): @@ -1811,6 +2622,30 @@ def _apply_review_case_customer_filter(cases_q, *, customer_needle: str, custome ) +def _verified_upload_success_sql_expr(): + """以当前 Excel Artifact 已上传这一唯一事实判定 Notice 已完成。""" + artifact = aliased(ShippingExportArtifact) + current_artifact_id = ( + select(artifact.id) + .where( + artifact.task_id == ShippingNotice.id, + artifact.status.in_(("ready", "uploading", "uploaded")), + ) + .order_by(artifact.created_at.desc(), artifact.id.desc()) + .limit(1) + .correlate(ShippingNotice) + .scalar_subquery() + ) + return exists( + select(1) + .select_from(ShippingExportArtifact) + .where( + ShippingExportArtifact.id == current_artifact_id, + ShippingExportArtifact.status == "uploaded", + ) + ) + + def _todo_tasks_base_query( user_id: int, *, @@ -1827,40 +2662,75 @@ def _todo_tasks_base_query( 核心逻辑:可见性 / 客户 / bucket 粗筛后,用 _task_todo_category_sql_expr().in_(allowed)。 """ q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin) + workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_pending_reason = select(ShippingOrderTask.pending_human_reason).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_current_step = select(ShippingOrderTask.current_step).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + workflow_customer_pending = exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .where(ShippingOrderTask.id == ShippingNotice.order_task_id, + ShippingCustomerShadowResolution.status != 'confirmed') + ) + artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) + upload_success = _verified_upload_success_sql_expr() + upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(('pending', 'running', 'failed', 'unknown')))) + match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) if task_no: q = q.filter(ShippingNotice.task_no == str(task_no).strip()) if customer_needle: q = q.filter( db.or_( - ShippingNotice.customer_name_snapshot.ilike(customer_like), - ShippingNotice.customer_short_code_snapshot.ilike(customer_like), - ShippingNotice.source_file_name.ilike(customer_like), + exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id) + .join(ShippingCustomer, ShippingCustomer.id == ShippingCustomerShadowResolution.confirmed_customer_id) + .where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ShippingCustomerShadowResolution.status == 'confirmed', + db.or_( + ShippingCustomer.standard_name.ilike(customer_like), + ShippingCustomer.short_code.ilike(customer_like), + ), + ) + ), + exists( + select(1).select_from(ShippingOrderDocument) + # Candidate 使用 primary_document_id 关联来源文档;不能读取已移除的 document_id 投影。 + .join(ShippingOrderCandidate, ShippingOrderCandidate.primary_document_id == ShippingOrderDocument.id) + .join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingOrderCandidate.id) + .where(ShippingOrderTask.id == ShippingNotice.order_task_id, ShippingOrderDocument.filename.ilike(customer_like)) + ), ) ) + category_clause = _todo_category_sql_filter(allowed) if category_clause is not None: q = q.filter(category_clause) if normalized_bucket in {"pending", "processing"}: q = q.filter( db.or_( - ShippingNotice.pending_human_reason.isnot(None), - ShippingNotice.review_status.isnot(None), - ShippingNotice.export_file_path.isnot(None), - ShippingNotice.current_step.isnot(None), - ShippingNotice.inventory_snapshot_id.isnot(None), - ShippingNotice.upload_status.isnot(None), + workflow_pending_reason.isnot(None), + workflow_review_status.isnot(None), + artifact_exists, + workflow_current_step.isnot(None), + exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( + ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + )), + upload_pending, ) ) elif normalized_bucket == "done": # Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。 q = q.filter( db.or_( - ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")), - ShippingNotice.review_status == RS_REJECTED, + upload_success, + workflow_review_status == RS_REJECTED, ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")), db.and_( - ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), - ShippingNotice.export_file_path.isnot(None), + match_exists, + artifact_exists, ), ) ) @@ -1972,6 +2842,37 @@ def list_my_todos( ) ) + # 库存准备尚未创建正式 Notice 时,待办必须来自 OT,否则失败任务会从任务中心消失。 + ot_allowed = frozenset(cat for cat in task_allowed if cat in {"exception", "in_progress"}) + if ot_allowed: + ot_q = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin) + if task_no: + ot_q = ot_q.filter(ShippingOrderTask.task_no == str(task_no).strip()) + if customer_needle: + ot_q = ot_q.filter( + exists( + select(1).select_from(ShippingCustomerShadowResolution) + .join(ShippingCustomer, ShippingCustomer.id == ShippingCustomerShadowResolution.confirmed_customer_id) + .where( + ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id, + ShippingCustomerShadowResolution.status == 'confirmed', + db.or_( + ShippingCustomer.standard_name.ilike(customer_like), + ShippingCustomer.short_code.ilike(customer_like), + ), + ) + ) + ) + ot_q = ot_q.filter(_order_task_todo_category_sql_expr().in_(tuple(sorted(ot_allowed)))) + branches.append( + ot_q.with_entities( + literal("order_task").label("kind"), + ShippingOrderTask.id.label("entity_id"), + func.coalesce(ShippingOrderTask.updated_at, ShippingOrderTask.created_at).label("sort_at"), + ShippingOrderTask.task_no.label("sort_ref"), + ) + ) + if not branches: return { "items": [], @@ -2004,7 +2905,8 @@ def list_my_todos( # [STEP 3] 仅水合当前页 ORM 并按 UNION 顺序序列化。 page_case_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "review_case"] page_intake_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "order_intake"] - page_task_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "task"] + page_notice_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "task"] + page_order_task_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "order_task"] cases_by_id: dict[int, ShippingOrderReviewCase] = {} if page_case_ids: for case in ShippingOrderReviewCase.query.filter( @@ -2017,10 +2919,14 @@ def list_my_todos( ShippingOrderIntake.id.in_(page_intake_ids), ).all(): intakes_by_id[int(intake.id)] = intake - tasks_by_id: dict[int, ShippingNotice] = {} - if page_task_ids: - for task in ShippingNotice.query.filter(ShippingNotice.id.in_(page_task_ids)).all(): - tasks_by_id[int(task.id)] = task + notices_by_id: dict[int, ShippingNotice] = {} + if page_notice_ids: + for notice in ShippingNotice.query.filter(ShippingNotice.id.in_(page_notice_ids)).all(): + notices_by_id[int(notice.id)] = notice + order_tasks_by_id: dict[int, ShippingOrderTask] = {} + if page_order_task_ids: + for task in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(page_order_task_ids)).all(): + order_tasks_by_id[int(task.id)] = task page_rows: list[dict[str, Any]] = [] for kind, entity_id in page_refs: @@ -2045,12 +2951,13 @@ def list_my_todos( ) ) continue - task = tasks_by_id.get(entity_id_int) - if task is None: - continue - page_rows.append( - serialize_task_summary(task, viewer_user_id=user_id, is_admin=is_admin) - ) + notice = notices_by_id.get(entity_id_int) + if kind == "order_task": + order_task = order_tasks_by_id.get(entity_id_int) + if order_task is not None: + page_rows.append(serialize_task_summary(order_task, viewer_user_id=user_id, is_admin=is_admin)) + elif notice is not None: + page_rows.append(serialize_task_summary(notice, viewer_user_id=user_id, is_admin=is_admin)) return { "items": page_rows, @@ -2069,23 +2976,31 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]: Returns: {pending, processing, done, total_pending_badge} """ + workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() + artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) + upload_success = _verified_upload_success_sql_expr() + match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) pending = _visible_open_review_cases_query(user_id, is_admin=is_admin).count() pending += _visible_orphan_intakes_query(user_id, is_admin=is_admin).count() category_expr = _task_todo_category_sql_expr() active = _active_todo_tasks_scope(user_id, is_admin=is_admin) task_pending_cats = tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})) pending += active.filter(category_expr.in_(task_pending_cats)).count() + ot_active = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin) + ot_category = _order_task_todo_category_sql_expr() + pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse", "manual_upload"})))).count() processing = active.filter(category_expr == "in_progress").count() + processing += ot_active.filter(ot_category == "in_progress").count() done = ( _visible_tasks_query_for_todos(user_id, is_admin=is_admin) .filter( db.or_( - ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")), - ShippingNotice.review_status == RS_REJECTED, + upload_success, + workflow_review_status == RS_REJECTED, ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")), db.and_( - ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), - ShippingNotice.export_file_path.isnot(None), + match_exists, + artifact_exists, ), ) ) diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 08953eab..22973069 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -92,10 +92,13 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool: if not task_is_active(task): return False - pending_reason = str(task.pending_human_reason or '').strip() + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + pending_reason = str(task_blocking_reason(task) or '').strip() + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + return ( pending_reason == PH_RPA_PENDING - and not task.inventory_lines_json + and not has_ready_inventory_file_for_task(task) ) or pending_reason == PH_UPLOAD_RPA_PENDING @@ -107,7 +110,8 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: from app.services.shipping_notice.query_service import get_task_by_ref task = get_task_by_ref(task_no) - if task and str(task.pending_human_reason or '').strip() == PH_RPA_PENDING: + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + if task and str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING: from app.services.shipping_notice.inventory_rpa_workflow import next_inventory_rpa_recheck_at scheduled_at = next_inventory_rpa_recheck_at(task) diff --git a/backend/app/services/shipping_notice/reconcile_queries.py b/backend/app/services/shipping_notice/reconcile_queries.py index 1c8b10c2..d541d961 100644 --- a/backend/app/services/shipping_notice/reconcile_queries.py +++ b/backend/app/services/shipping_notice/reconcile_queries.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/reconcile_queries.py 用途:Phase 2 对账只读查询层 — 按 Q1 五级 L1-L3 归属链判断 Case → Task 的绑定关系。 依赖:models.ShippingOrderReviewCase / ShippingOrderCandidate / ShippingOrderDocument - / ShippingNotice(=OrderTask)、business_fingerprint.build_business_fingerprint、 + / ShippingOrderTask、business_fingerprint.build_business_fingerprint、 duplicate_detection.classify_task_lifecycle、recovery_contract(类型契约)。 逻辑:由 reconciliation_service.reconcile_existing_task() 调用;全部为只读查询, 不做任何 DB 写入;返回统一 ReconcileMatchResult 结构(match_level / task_no / @@ -19,8 +19,8 @@ from typing import Any from app import db from app.models import ( FileAsset, - ShippingNotice, ShippingOrderCandidate, + ShippingOrderTask, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderProcessingUnit, @@ -61,7 +61,7 @@ def _no_match(*, reason: str, case_no: str) -> ReconcileMatchResult: def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMatchResult | None: """ - L1:Case.confirmed_task_id → 直接查 ShippingNotice 拿到 task_no。 + L1:Case.confirmed_task_id → 直接查 ShippingOrderTask 拿到 task_no。 【AI 触发时机】:对账入口必须先执行本步骤,避免 L2/L3 瞎匹配覆盖掉人工确认的绑定。 """ steps: list[dict[str, Any]] = [] @@ -70,7 +70,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa # 1a. confirmed_task_id 有值且指向存在的 Task task_id = getattr(case, 'confirmed_task_id', None) if task_id is not None: - task = db.session.get(ShippingNotice, int(task_id)) + task = db.session.get(ShippingOrderTask, int(task_id)) if task is not None and task.task_no: steps.append({'step': 'L1a-confirmed_task_id', 'passed': True, 'evidence': {'task_id': int(task_id), 'task_no': str(task.task_no)}}) @@ -83,15 +83,15 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa lifecycle=classify_task_lifecycle(task)), ) steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, - 'reason': 'confirmed_task_id 指向的 ShippingNotice 不存在或无 task_no', + 'reason': 'confirmed_task_id 指向的 ShippingOrderTask 不存在或无 task_no', 'evidence': {'task_id': int(task_id)}}) else: steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, 'reason': 'confirmed_task_id is None'}) - # 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingNotice 校验存在性 + # 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingOrderTask 校验存在性 confirmed_task_no = str(getattr(case, 'confirmed_task_no', '') or '').strip() if confirmed_task_no: - task = ShippingNotice.query.filter_by(task_no=confirmed_task_no).first() + task = ShippingOrderTask.query.filter_by(task_no=confirmed_task_no).first() if task is not None: steps.append({'step': 'L1b-confirmed_task_no', 'passed': True, 'evidence': {'task_no': confirmed_task_no, 'task_id': int(task.id)}}) @@ -104,7 +104,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa lifecycle=classify_task_lifecycle(task)), ) steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, - 'reason': 'confirmed_task_no 反向查无 ShippingNotice', + 'reason': 'confirmed_task_no 反向查无 ShippingOrderTask', 'evidence': {'task_no': confirmed_task_no}}) else: steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, 'reason': 'confirmed_task_no 为空'}) @@ -141,7 +141,7 @@ def _step_l1cde_downstream_links( ) -> ReconcileMatchResult | None: """ L1c: Candidate → 已有 OrderTask(Candidate.fulfilled_task_id 或 wave_lines → Task)。 - L1d: Document → ShippingNotice.source_document_id / document_id 外键。 + L1d: Document → Candidate.primary_document_id → ShippingOrderTask 外键。 L1e: Candidate + Document + PO + customer_code + fingerprint 联合匹配(过渡到 L2)。 """ steps: list[dict[str, Any]] = [] @@ -151,7 +151,7 @@ def _step_l1cde_downstream_links( if candidate is not None: fulfilled_task_id = getattr(candidate, 'fulfilled_task_id', None) if fulfilled_task_id is not None: - task = db.session.get(ShippingNotice, int(fulfilled_task_id)) + task = db.session.get(ShippingOrderTask, int(fulfilled_task_id)) if task is not None and task.task_no: steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': True, 'evidence': {'candidate_id': int(candidate.id), @@ -183,7 +183,7 @@ def _step_l1cde_downstream_links( ) wave_task_ids = [int(r.task_id) for r in wave_task_id_rows if r.task_id is not None] if len(wave_task_ids) == 1: - task = db.session.get(ShippingNotice, wave_task_ids[0]) + task = db.session.get(ShippingOrderTask, wave_task_ids[0]) if task is not None and task.task_no: steps.append({'step': 'L1c-wave_line_task', 'passed': True, 'evidence': {'task_id': wave_task_ids[0], 'task_no': str(task.task_no)}}) @@ -204,14 +204,14 @@ def _step_l1cde_downstream_links( steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False, 'reason': 'Case 没有 Candidate'}) steps.append({'step': 'L1c-wave_line_task', 'passed': False, 'reason': 'Case 没有 Candidate'}) - # -------- L1d:Document 外键链:Unit → Intake → Notice(ShippingNotice.source_document_id / document_id)-------- + # -------- L1d:Document 外键链:Unit → Intake → Candidate → OT -------- document_id = int(case.document_id) - # 路径 A:ShippingNotice.source_document_id == document_id(PDF 级直接关联) + # 路径 A:Candidate.primary_document_id == document_id(PDF 级直接关联) doc_task_a = ( - ShippingNotice.query - .filter((ShippingNotice.source_document_id == document_id) | - (ShippingNotice.document_id == document_id)) - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderCandidate.primary_document_id == document_id) + .order_by(ShippingOrderTask.id.desc()) .limit(5) .all() ) @@ -240,15 +240,19 @@ def _step_l1cde_downstream_links( intake = db.session.get(ShippingOrderIntake, int(unit.intake_id)) asset_id = getattr(intake, 'asset_id', None) if intake is not None else None if asset_id is not None: - # FileAsset.content_hash == ShippingNotice.source_content_hash(文件哈希级) + # FileAsset.content_hash == Intake/Document.content_hash(文件哈希级) asset = db.session.get(FileAsset, int(asset_id)) content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower() if content_hash: file_tasks = ( - ShippingNotice.query - .filter_by(user_id=int(case.owner_user_id), source_content_hash=content_hash) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderTask.intake_id) + .filter( + ShippingOrderTask.user_id == int(case.owner_user_id), + ShippingOrderIntake.asset_id == int(asset_id), + ) + .filter(ShippingOrderTask.lifecycle_status == 'active') + .order_by(ShippingOrderTask.id.desc()) .limit(5) .all() ) @@ -400,11 +404,12 @@ def _step_l2_structural_match( if (payload['business_fingerprint'] and payload['fingerprint_strength'] in {'strong', 'medium'}): same_fp_tasks = ( - ShippingNotice.query - .filter(ShippingNotice.user_id == int(case.owner_user_id), - ShippingNotice.business_fingerprint == payload['business_fingerprint']) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderTask.user_id == int(case.owner_user_id), + ShippingOrderCandidate.business_fingerprint == payload['business_fingerprint']) + .filter(ShippingOrderTask.lifecycle_status == 'active') + .order_by(ShippingOrderTask.id.desc()) .limit(5) .all() ) @@ -435,21 +440,21 @@ def _step_l2_structural_match( # L2b:同用户 + PO 精确一致 + customer_code 精确一致 if payload['po_numbers'] and payload['customer_code']: - # ShippingNotice 头字段 JSON:查 structured_result_json.business_summary.po_numbers / customer_code + # Candidate 结构化摘要:查 structured_result_json.business_summary.po_numbers / customer_code # 因 ORM 层无强列,退化为查 source_content_po_numbers 的 Candidate → Task 反向 same_customer_tasks = ( - ShippingNotice.query - .filter_by(user_id=int(case.owner_user_id)) - .filter(ShippingNotice.customer_code == payload['customer_code'] - if hasattr(ShippingNotice, 'customer_code') else True) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderTask.user_id == int(case.owner_user_id)) + .filter(ShippingOrderTask.lifecycle_status == 'active') + .order_by(ShippingOrderTask.id.desc()) .limit(20) .all() ) - po_matched: list[ShippingNotice] = [] + po_matched: list[ShippingOrderTask] = [] for task in same_customer_tasks: - structured = getattr(task, 'structured_result_json', None) if hasattr(ShippingNotice, 'structured_result_json') else None + candidate_row = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(task.id)).order_by(ShippingOrderCandidate.id.desc()).first() + structured = getattr(candidate_row, 'structured_result_json', None) if candidate_row is not None else None summary = structured.get('business_summary') if isinstance(structured, dict) else None task_pos: set[str] = set() if isinstance(summary, dict): @@ -460,7 +465,7 @@ def _step_l2_structural_match( po_matched.append(task) if len(po_matched) == 1: task = po_matched[0] - steps.append({'step': 'L2b-po_customer_match', 'passed': True, + steps.append({'step': 'L2b-po_customer_identity', 'passed': True, 'evidence': {'customer_code': payload['customer_code'], 'pos_matched': sorted(set(payload['po_numbers']) & {str(x).strip().upper() for x in @@ -474,11 +479,11 @@ def _step_l2_structural_match( confidence=ReconcileConfidence.PROBABLE, evidence=evidence, ) - steps.append({'step': 'L2b-po_customer_match', 'passed': False, + steps.append({'step': 'L2b-po_customer_identity', 'passed': False, 'reason': f'PO+客码匹配 {len(po_matched)} 个(不唯一)', 'evidence': {'matched_count': len(po_matched)}}) else: - steps.append({'step': 'L2b-po_customer_match', 'passed': False, + steps.append({'step': 'L2b-po_customer_identity', 'passed': False, 'reason': 'PO 或 customer_code 缺失,无法联合匹配', 'evidence': {'pos_count': len(payload['po_numbers']), 'customer_code_empty': not bool(payload['customer_code'])}}) @@ -487,11 +492,11 @@ def _step_l2_structural_match( # 在 L1d 步骤中已筛选 content_hash 但超过 1 个的情形,这里统一转为 L3 ambiguous document_id = int(case.document_id) doc_tasks_multi = ( - ShippingNotice.query - .filter((ShippingNotice.source_document_id == document_id) | - (ShippingNotice.document_id == document_id)) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderCandidate.primary_document_id == document_id) + .filter(ShippingOrderTask.lifecycle_status == 'active') + .order_by(ShippingOrderTask.id.desc()) .limit(5) .all() ) diff --git a/backend/app/services/shipping_notice/reconciliation_projector.py b/backend/app/services/shipping_notice/reconciliation_projector.py index 9f741b0f..3f59c2b9 100644 --- a/backend/app/services/shipping_notice/reconciliation_projector.py +++ b/backend/app/services/shipping_notice/reconciliation_projector.py @@ -25,8 +25,8 @@ backend/app/services/shipping_notice/reconciliation_projector.py 从 automation.reason_code / blocking_reason 拆出 {code, i18n_key, details} 与 invariants._REASON_TO_I18N_KEY 一致映射。 ⑤ project_case_user_status(case, automation) - 返回七值归一化 completed / cancelled / waiting_human / retryable / - failed / running / idle(与 shipping-processing user_status 同域)。 + 返回 F2 六值 completed / cancelled / waiting_human / retryable / + failed / running(与 USER_FACING_TASK_STATUSES 同域;禁止 idle)。 ⑥ project_case_primary_action(user_status, blocking_reason, available_actions, user_stage) 完整复刻 invariants._compute_primary_action 逻辑(1a~1i)。 ⑦ 总入口 project_review_case_projection_bundle(...) @@ -51,7 +51,7 @@ from app.models import ( UserStatus = Literal[ 'completed', 'cancelled', 'waiting_human', - 'retryable', 'failed', 'running', 'idle', + 'retryable', 'failed', 'running', ] @@ -142,7 +142,11 @@ def project_case_automation_status( job_id / error_code / reason_code / blocking_reason / next_action 的字典(与详情页 automation 同构)。 """ - from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot + from app.services.shipping_notice.order_review_workbench_projection import ( + JOB_FAILURE_STATUS_TOKENS, + project_job_status_outcome, + resolve_formal_ot, + ) from app.services.shipping_notice.order_stp_auto_create_service import ( build_stp_idempotency_key, find_active_stp_job, @@ -281,7 +285,7 @@ def project_case_automation_status( 'can_build': can_build, 'job_id': int(job.id), } - if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}: + if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'failed': result = latest.result_json if isinstance(latest.result_json, dict) else {} raw_retryable = result.get('retryable') if raw_retryable is None: @@ -313,9 +317,7 @@ def project_case_automation_status( 'error_code': result.get('error_code') or blocking_reason_raw, 'retry_of_job_id': int(latest.id), } - if latest is not None and str(latest.status or '').strip().lower() in { - 'succeeded', 'success', 'completed', - }: + if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'succeeded': return { 'status': 'completed', 'retryable': False, @@ -707,7 +709,7 @@ def project_case_blocking_reason(automation: dict[str, Any] | None) -> BlockingR # ============================================================ -# [5] user_status(七值归一化) +# [5] user_status(F2 六值;默认人工等待 = waiting_human,禁止 idle) # ============================================================ def project_case_user_status( @@ -715,11 +717,12 @@ def project_case_user_status( automation: dict[str, Any] | None, ) -> UserStatus: """ - 与 shipping-processing invariants 的 user_status 七值同域映射。 + 与 USER_FACING_TASK_STATUSES / shipping-processing user_status 同域(F2 六值)。 + Case 草稿待处置默认 waiting_human;禁止再输出 idle。 """ auto_status = str((automation or {}).get('status') or '').strip().lower() case_status = str(case.status or '').strip().lower() - if auto_status in {'completed', 'success'}: + if auto_status == 'completed': return 'completed' if case_status in {'cancelled', 'superseded', 'non_order'}: return 'cancelled' @@ -734,7 +737,7 @@ def project_case_user_status( return 'waiting_human' if auto_status in {'waiting_to_start'}: return 'running' # waiting = 尚未运行,但系统已负责 - return 'idle' + return 'waiting_human' # ============================================================ @@ -815,7 +818,7 @@ def project_case_primary_action( # 1f: 已授权草稿操作是文件列表的下一项业务操作。点击只导航到该文件的 # 复核上下文;validate 仍由工作台底栏执行,不能提升为列表 CTA。 - if user_status in {'waiting_human', 'idle'}: + if user_status == 'waiting_human': if 'create_draft' in actions: return {'code': 'create_draft', 'variant': 'primary', 'label_key': 'shipping.actions.create_draft'} @@ -861,6 +864,10 @@ def _project_fine_grained_pre_stp_blocking( from app.extensions import db from app.models import Job from app.jobs.types import JobType + from app.services.shipping_notice.order_review_workbench_projection import ( + JOB_FAILURE_STATUS_TOKENS, + project_job_status_outcome, + ) from app.services.shipping_notice.order_stp_auto_create_service import ( build_stp_idempotency_key, ) @@ -948,14 +955,17 @@ def _project_fine_grained_pre_stp_blocking( else: latest_failed = ( next( - (job for job in prefix_jobs if str(job.status or '').strip().lower() in {'failed', 'dead'}), + ( + job for job in prefix_jobs + if project_job_status_outcome(getattr(job, 'status', None)) == 'failed' + ), 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.status.in_(tuple(JOB_FAILURE_STATUS_TOKENS)), Job.business_ref.like(f"{business_ref_prefix}%"), ) .order_by(Job.id.desc()) @@ -1189,10 +1199,17 @@ def project_review_case_projection_bundle( # [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case # 草稿状态重算 order_review_build/idle,会覆盖批次投影已读取的 # field_completeness / required_field_missing,造成同一文件前后端状态冲突。 + # 但该裁决权只适用于已确认(post-OT)的正式 Gate;未确认(unreviewed/draft/ready + # 且无 confirmed_task_id)的 Case 仍停留在建单前,其当前 Gate / 用户态必须由 + # Case 派生事实(order_review_build / waiting_human)裁决,不得被正式 Gate 的 + # reservation_validation / running 反向覆盖。 formal_gate_facts = _project_case_formal_gate_facts( _project_case_formal_gate_summary(case), ) - if formal_gate_facts is not None: + if ( + formal_gate_facts is not None + and str(case.status or '').strip().lower() == 'confirmed' + ): current_gate, blocking_reason, user_status = formal_gate_facts # [STEP 6] primary_action # 建单前 STP 已失败时,主操作的阶段必须随失败事实停在 pre_ot_stp; diff --git a/backend/app/services/shipping_notice/reconciliation_service.py b/backend/app/services/shipping_notice/reconciliation_service.py index f0da259f..c7f5e5bf 100644 --- a/backend/app/services/shipping_notice/reconciliation_service.py +++ b/backend/app/services/shipping_notice/reconciliation_service.py @@ -34,6 +34,7 @@ from app.jobs.types import JobType from app.models import ( Job, ShippingNotice, + ShippingOrderTask, ShippingOrderCandidate, ShippingOrderReviewCase, ShippingOrderReviewCaseEvent, @@ -326,14 +327,15 @@ def _write_reconcile_audit_and_event( def _write_back_case_task_binding( *, case: ShippingOrderReviewCase, - task: ShippingNotice, + task: ShippingOrderTask, actor_type: str, ) -> None: """ Q2:L2 命中后必须写回正式关联,避免下次恢复仍撞重复检查。 1. Case.confirmed_task_id / confirmed_task_no 2. Candidate.fulfilled_task_id(若存在当前 Candidate) - 3. Document → Task 外键(ShippingNotice.source_document_id 如空则补) + 3. 来源文档继续由 Case.document_id / Candidate.primary_document_id 承载; + OT 只保存 intake/candidate 指针,不写入已移除的 source_document_id 投影。 """ case.confirmed_task_id = int(task.id) # confirmed_task_no 通常为 property,但实际存字段若可写则同步 @@ -350,12 +352,6 @@ def _write_back_case_task_binding( cand.fulfilled_task_id = int(task.id) except Exception: # noqa: BLE001 — 模型无列则降级 pass - # Document → Task 外键 - if not getattr(task, 'source_document_id', None) and getattr(case, 'document_id', None): - try: - task.source_document_id = int(case.document_id) - except Exception: # noqa: BLE001 - pass # ============================================================ @@ -537,8 +533,8 @@ def reconcile_and_progress( mlvl: str = match_result['match_level'] confidence: str = match_result['confidence'] matched_task_no: str | None = match_result.get('task_no') - matched_task: ShippingNotice | None = ( - ShippingNotice.query.filter_by(task_no=matched_task_no).first() + matched_task: ShippingOrderTask | None = ( + ShippingOrderTask.query.filter_by(task_no=matched_task_no).first() if matched_task_no else None ) @@ -775,12 +771,23 @@ def assert_case_not_blocked_manual(*, case_no: str, case: ShippingOrderReviewCas return rj = latest.result_json if isinstance(latest.result_json, dict) else {} retryable_flag = bool(rj.get('retryable', True)) + error_code = str(rj.get('error_code') or '').strip() blocking_reason_raw = rj.get('blocking_reason') blocking_reason = ( {'code': str(blocking_reason_raw)} if isinstance(blocking_reason_raw, str) and blocking_reason_raw else blocking_reason_raw if isinstance(blocking_reason_raw, dict) else None ) + # 兼容修复前已落库的技术异常:旧结果被错误写成 retryable=false, + # 但 SHIPPING.STP_AUTO_CREATE_UNEXPECTED 本身不是业务裁决原因,普通 + # retry 应创建新的 Job,而不是强制用户走 reconcile-and-progress。 + effective_error_code = error_code or ( + blocking_reason.get('code') + if isinstance(blocking_reason, dict) + else str(blocking_reason or '').strip() + ) + if not retryable_flag and effective_error_code == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED': + return if should_general_retry_be_removed(retryable_flag=retryable_flag, blocking_reason=blocking_reason): raise ConflictError( 'Case blocked on manual adjudication; use reconcile-and-progress instead of retry-stp-auto-create', diff --git a/backend/app/services/shipping_notice/recovery_invalidation_service.py b/backend/app/services/shipping_notice/recovery_invalidation_service.py index eece70f1..ce987717 100644 --- a/backend/app/services/shipping_notice/recovery_invalidation_service.py +++ b/backend/app/services/shipping_notice/recovery_invalidation_service.py @@ -4,11 +4,13 @@ services/shipping_notice/recovery_invalidation_service.py 用途:按恢复动作精确失效库存下游事实及正式 Gate。 依赖:ShippingProcessExecution/Gate、库存快照链接、行级 Match、Verification、Artifact、UploadAttempt。 逻辑:只标记失效,不删除、不覆盖历史事实;所有变更在调用方事务内完成。 + 行级 scope(source_codes)时:只失效对应源链接与未发通知行的匹配,禁止触碰已有 Notice Artifact。 """ from __future__ import annotations from datetime import datetime +from sqlalchemy import false from app import db from app.models import ( @@ -19,21 +21,72 @@ from app.models import ( ShippingProcessExecution, ShippingTaskInventoryLink, ShippingUploadAttempt, + ShippingNotice, ) from app.services.shipping_notice.process_gate_service import invalidate_downstream_gates +def _noticed_snapshot_line_ids(task_id: int) -> set[int]: + """ + 返回该 OT 下已写入正式发货通知行的 snapshot_line_id 集合。 + + 核心逻辑:ShippingNoticeLine 是「已产生发货通知」的权威事实;行级重抓不得改写这些行。 + """ + from app.models.shipping_notice_line import ShippingNoticeLine + + rows = ( + db.session.query(ShippingNoticeLine.snapshot_line_id) + .join(ShippingNotice, ShippingNotice.id == ShippingNoticeLine.notice_id) + .filter(ShippingNotice.order_task_id == int(task_id)) + .all() + ) + return {int(row[0]) for row in rows if row[0] is not None} + + +def _match_row_source_codes(row: ShippingNoticeLineInventoryMatch) -> set[str]: + """从匹配事实抽取规范化库存源集合,供行级失效过滤。""" + codes: set[str] = set() + primary = str(getattr(row, 'inventory_source_code', '') or '').strip().upper() + if primary: + codes.add(primary) + for raw in list(getattr(row, 'allowed_source_codes_snapshot', None) or []): + code = str(raw or '').strip().upper() + if code: + codes.add(code) + return codes + + def invalidate_inventory_downstream( *, execution: ShippingProcessExecution, action_code: str, attempt_id: int | None = None, actor_id: int | str | None = None, + source_codes: list[str] | None = None, + snapshot_line_id: int | None = None, ) -> dict[str, list[int] | list[str]]: - """失效库存恢复受影响事实,并返回可审计的对象 ID。""" + """ + 失效库存恢复受影响事实,并返回可审计的对象 ID。 + + 核心逻辑:整单恢复保持原行为;若传入 source_codes(行级重抓),则: + - 只停用对应源的库存链接; + - 只作废「未产生发货通知」且命中该源/该行的匹配事实; + - 禁止 supersede 已有 Notice 的 Artifact/Upload。 + + Args: + execution: 当前 ProcessExecution。 + action_code: 恢复动作码,决定失效深度。 + attempt_id: 可选 Gate Attempt ID。 + actor_id: 可选操作人。 + source_codes: 行级库存源;有值即进入行级收窄模式。 + snapshot_line_id: 可选被点击的冻结行 ID,用于精确命中该行匹配事实。 + + Returns: + 各类被失效对象 ID 列表。 + """ task_id = int(execution.task_id or 0) if not task_id: return {'gates': [], 'links': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []} now = datetime.utcnow() - from app.models import ShippingNotice - task = db.session.get(ShippingNotice, task_id) + from app.models import ShippingOrderTask + task = db.session.get(ShippingOrderTask, task_id) result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []} change_type = { 'retry_inventory_preparation': 'inventory_file_changed', @@ -42,26 +95,43 @@ def invalidate_inventory_downstream( 'retry_inventory_from_matching': 'inventory_matching_changed', }.get(action_code, 'inventory_matching_changed') result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id) + scoped_codes = { + str(code).strip().upper() + for code in (source_codes or []) + if str(code).strip() + } + line_scoped = bool(scoped_codes) + protected_line_ids = _noticed_snapshot_line_ids(task_id) if line_scoped else set() + scoped_snapshot_line_id = int(snapshot_line_id) if snapshot_line_id is not None else None if action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}: links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all() for link in links: + link_code = str(getattr(link, 'matched_source_code', '') or '').strip().upper() + if line_scoped and link_code and link_code not in scoped_codes: + continue + if line_scoped and not link_code: + # 无源码的历史链接在行级重抓时不误伤;整单路径仍会停用。 + continue link.is_active = False link.invalidated_at = now link.invalidated_by_attempt_id = attempt_id link.invalidation_reason = action_code result['links'].append(int(link.id)) - active_file_ids = [ + affected_file_ids = [ int(link.inventory_file_id) for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all() - if link.inventory_file_id + if link.inventory_file_id and ( + not line_scoped + or str(getattr(link, 'matched_source_code', '') or '').strip().upper() in scoped_codes + ) ] if action_code in { 'retry_inventory_preparation', 'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', - } and active_file_ids: + } and affected_file_ids: mappings = ShippingInventoryMapping.query.filter( - ShippingInventoryMapping.inventory_file_id.in_(active_file_ids), + ShippingInventoryMapping.inventory_file_id.in_(affected_file_ids), ShippingInventoryMapping.status == 'active', ).with_for_update().all() for mapping in mappings: @@ -69,47 +139,40 @@ def invalidate_inventory_downstream( result['mappings'].append(int(mapping.id)) matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all() for row in matches: + row_line_id = int(getattr(row, 'snapshot_line_id', 0) or 0) + if line_scoped and row_line_id in protected_line_ids: + continue + if line_scoped: + row_codes = _match_row_source_codes(row) + hit_scoped_line = scoped_snapshot_line_id is not None and row_line_id == scoped_snapshot_line_id + hit_scoped_source = bool(row_codes.intersection(scoped_codes)) + if not hit_scoped_line and not hit_scoped_source: + continue row.is_current = False row.invalidated_at = now row.invalidated_by_attempt_id = attempt_id row.invalidation_reason = action_code result['matches'].append(int(row.id)) - verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() - for verification in verifications: - verification.status = 'superseded' - result['verifications'].append(int(verification.id)) - artifacts = ShippingExportArtifact.query.filter( - ShippingExportArtifact.task_id == task_id, - ShippingExportArtifact.status.in_({'ready', 'uploading'}), - ).with_for_update().all() - for artifact in artifacts: - artifact.status = 'superseded' - result['artifacts'].append(int(artifact.id)) - uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter( - ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}), + if not line_scoped: + verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() + for verification in verifications: + verification.status = 'superseded' + result['verifications'].append(int(verification.id)) + notice_ids = [int(row.id) for row in ShippingNotice.query.filter_by(order_task_id=task_id).all()] + artifacts = ShippingExportArtifact.query.filter( + ShippingExportArtifact.task_id.in_(notice_ids) if notice_ids else false(), + ShippingExportArtifact.status.in_({'ready', 'uploading'}), ).with_for_update().all() - for upload in uploads: - upload.invalidated_at = now - upload.invalidation_reason = action_code - result['uploads'].append(int(upload.id)) - if task is not None and action_code in { - 'retry_inventory_preparation', - 'retry_inventory_from_preparation', - 'retry_inventory_from_field_mapping', - 'retry_inventory_from_matching', - }: - # [BE-放行-恢复] 本动作已把当前匹配行置 is_current=False(上方),必须同步清空任务级 - # 派生状态,否则 UI 与 Gate 在下一轮重匹配前仍读到旧 match_status/shortage/line_results, - # 出现"已重试却仍显示旧缺货"的矛盾。 - task.match_status = None - task.shortage_json = None - task.line_results_json = None - if task is not None and ( - action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'} - ): - # 仅库存文件级重试才清空导出指针;匹配/字段映射级重试只作废匹配,不改已生成文件。 - task.export_file_path = None - task.export_file_name = None + for artifact in artifacts: + artifact.status = 'superseded' + result['artifacts'].append(int(artifact.id)) + uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter( + ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}), + ).with_for_update().all() + for upload in uploads: + upload.invalidated_at = now + upload.invalidation_reason = action_code + result['uploads'].append(int(upload.id)) db.session.flush() return result @@ -132,15 +195,16 @@ def invalidate_excel_regeneration_only( if not task_id: return result - from app.models import ShippingNotice, ShippingReservation + from app.models import ShippingOrderTask, ShippingReservation from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - task = db.session.get(ShippingNotice, task_id) + task = db.session.get(ShippingOrderTask, task_id) if task is None: return result now = datetime.utcnow() + notice_ids = [int(row.id) for row in ShippingNotice.query.filter_by(order_task_id=task_id).all()] artifacts = ShippingExportArtifact.query.filter( - ShippingExportArtifact.task_id == task_id, + ShippingExportArtifact.task_id.in_(notice_ids) if notice_ids else false(), ShippingExportArtifact.status.in_({'ready', 'uploading'}), ).with_for_update().all() for artifact in artifacts: @@ -195,9 +259,6 @@ def invalidate_excel_regeneration_only( metadata={'execution_no': execution.execution_no, 'attempt_id': attempt_id}, source='process_gate', ) - if artifacts: - task.export_file_path = None - task.export_file_name = None result['gates'] = invalidate_downstream_gates( execution=execution, change_type='excel_regeneration_only', diff --git a/backend/app/services/shipping_notice/reference_context.py b/backend/app/services/shipping_notice/reference_context.py index efd049fe..a54ce91a 100644 --- a/backend/app/services/shipping_notice/reference_context.py +++ b/backend/app/services/shipping_notice/reference_context.py @@ -97,12 +97,21 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No if not task_no: return None - review_status = _clean_text(getattr(task, "review_status", None)).lower() - match_status = _clean_text(getattr(task, "match_status", None)).lower() - pending_reason = _clean_text(getattr(task, "pending_human_reason", None)).lower() - upload_status = _clean_text(getattr(task, "upload_status", None)).lower() + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + from app import db + from app.models import ShippingOrderTask + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + review_status = _clean_text(getattr(owner, "review_status", None)).lower() + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) + match_status = _clean_text(aggregate_match_status_for_task(match_task_id)).lower() + pending_reason = _clean_text(getattr(owner, "pending_human_reason", None)).lower() + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + upload_attempt = latest_upload_attempt(task) if isinstance(task, ShippingNotice) else None + upload_status = _clean_text(getattr(upload_attempt, "status", None)).lower() - if match_status == "shortage" or pending_reason == "shortage" or getattr(task, "shortage_json", None): + if match_status == "shortage" or pending_reason == "shortage": return { "reason": "shortage", "label": "异常:库存不足", @@ -120,7 +129,7 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No "label": "异常:上传失败", "summary": f"{task_no} 上传失败", } - if _clean_text(getattr(task, "error_message", None)): + if _clean_text(getattr(owner, "error_message", None)): return { "reason": "error", "label": "异常:处理失败", diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 271630c2..8aea5a1a 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -19,8 +19,10 @@ INTERNAL_UUID_RE = re.compile( r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.IGNORECASE, ) -# Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351 -RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{10}|\d{5})\b") +# Reservation 本体后可带一段半角或全角括号备注;普通尾随文本不属于合法值。 +RESERVATION_VALUE_RE = re.compile(r"^(\d{10}|\d{5})(?!\d)\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$") +# ``@`` 是预约号与前缀说明的显式分隔,后缀复用 Reservation 值的括号备注契约。 +RESERVATION_AT_SUFFIX_RE = re.compile(r"@\s*(\d{10}|\d{5})(?!\d)(?=\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$)") PR_NUMBER_LINE_RE = re.compile( r"PR\s*Number\s*[::]?\s*([^\n\r]+)", re.IGNORECASE, @@ -57,29 +59,36 @@ def normalize_reservation_id(value: Any) -> str: def extract_reservation_id(value: Any) -> str: - """从原值提取 Reservation ID 候选;合法性必须另由 `is_valid_reservation_id` 判断。""" + """标准化 Reservation ID,并识别 ``@`` 后带可选括号备注的预约号。 + + Args: + value: Reservation ID 字段原始值;仅允许整体纯数字,或明确 ``@`` 分隔后可带括号备注的纯数字。 + + Returns: + str: 已确认的五位或十位纯数字 Reservation ID;普通尾随文本或金额文本返回空字符串。 + """ text = str(value or "").strip() if not text: return "" direct = normalize_reservation_id(text) - if looks_like_reservation_id(direct): - return direct + direct_match = RESERVATION_VALUE_RE.fullmatch(direct) + if direct_match: + return direct_match.group(1) match = RESERVATION_AT_SUFFIX_RE.search(text) - if match: - return match.group(1) - - if "@" in text: - tail = normalize_reservation_id(text.rsplit("@", 1)[-1]) - if looks_like_reservation_id(tail): - return tail - - return direct + return match.group(1) if match else "" def find_reservation_id_in_document(text: str) -> str: - """扫描全文 PR Number 行或 @1000140351 后缀,提取文档级 Reservation ID。""" + """扫描全文 PR Number 行或 ``@`` 分隔、可带括号备注的 Reservation ID。 + + Args: + text: 文档原始文本;仅接受 ``@`` 后可带括号备注的完整五位或十位纯数字。 + + Returns: + str: 已验证的五位或十位纯数字 Reservation ID;无明确分隔证据时返回空字符串。 + """ body = str(text or "") if not body.strip(): return "" diff --git a/backend/app/services/shipping_notice/reservation_service.py b/backend/app/services/shipping_notice/reservation_service.py index 372b92ed..c9e1f718 100644 --- a/backend/app/services/shipping_notice/reservation_service.py +++ b/backend/app/services/shipping_notice/reservation_service.py @@ -19,6 +19,7 @@ from app.models import ( ShippingInventoryVerification, ShippingInventoryVerificationLine, ShippingOrderSnapshot, + ShippingOrderTask, ShippingReservation, ShippingNotice, ) @@ -38,7 +39,7 @@ def _decimal(value: Any) -> Decimal: return result -def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]: +def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservation]: """由冻结 Snapshot 注册全局预约号;同 PO 的变更只能作为人工修订候选。""" snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None if snapshot is None: @@ -72,11 +73,18 @@ def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]: code='SHIPPING.RESERVATION_PO_CONFLICT', details={'reservation_id': reservation_id, 'registered_po_number': row.po_number_normalized}, ) - elif row.task_id != task.id or row.snapshot_line_id != line.id: + elif ( + row.task_id != task.id + or row.snapshot_line_id != line.id + or row.part_number != part_number + or row.required_qty != _decimal(line.qty) + ): if row.current_artifact_id is not None or row.status in {'artifact_reserved', 'uploaded'}: raise ConflictError('Reservation cannot be revised after export or upload', code='SHIPPING.RESERVATION_REVISION_LOCKED') if row.part_number != part_number or row.required_qty != _decimal(line.qty): - if task.supersedes_task_id == row.task_id: + # 同一 OT 的确认修订复用该 OT(仅 bump order_data_version/progress_version), + # Reservation 与审计事件仍指向该 OT,不新建任务;跨任务变更须人工复核。 + if row.task_id == task.id: _transfer_confirmed_revision(row, task=task, line=line, part_number=part_number) registered.append(row) continue @@ -96,20 +104,40 @@ def ensure_task_reservations(task: ShippingNotice) -> list[ShippingReservation]: return registered +def _owner_task(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderTask: + """将 Notice/OT 输入统一解析为该任务所属的 OT(shipping_order_tasks 聚合根)。""" + if isinstance(task, ShippingOrderTask): + return task + order_task_id = getattr(task, 'order_task_id', None) + owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id is not None else None + if owner is None: + raise ConflictError('Shipping notice has no order task', code='SHIPPING.ORDER_TASK_REQUIRED') + return owner + + def _transfer_confirmed_revision( reservation: ShippingReservation, - *, task: ShippingNotice, + *, task: ShippingOrderTask, line: Any, part_number: str, ) -> None: - """仅允许已确认的直接修订后继接替未履约 Reservation,并追加双向审计。""" + """ + 同一 OT 的已确认修订:复用该 OT(版本 bump),接替未履约 Reservation,并落 OT 级审计。 + + 核心逻辑:修订不新建任务行;仅递增 ``order_data_version`` / ``progress_version``, + Reservation 与 ShippingTaskEvent 均保持指向该 OT,避免写入 Notice id 造成错误外键。 + """ + owner = _owner_task(task) previous = { 'task_id': reservation.task_id, 'snapshot_line_id': reservation.snapshot_line_id, 'part_number': reservation.part_number, 'qty': str(reservation.required_qty), } - reservation.task_id = task.id + # 保留同一 ShippingOrderTask:版本 bump,Reservation/事件仍指向该 OT。 + owner.order_data_version = int(owner.order_data_version or 1) + 1 + owner.progress_version = int(owner.progress_version or 0) + 1 + reservation.task_id = owner.id reservation.snapshot_line_id = line.id reservation.part_number = part_number reservation.required_qty = _decimal(line.qty) @@ -119,16 +147,13 @@ def _transfer_confirmed_revision( 'reservation_id': reservation.reservation_id, 'previous': previous, 'proposed': { - 'task_id': task.id, + 'task_id': owner.id, 'snapshot_line_id': line.id, 'part_number': part_number, 'qty': str(reservation.required_qty), }, } - log_task_event(task, 'reservation_revision_confirmed', details) - parent = db.session.get(ShippingNotice, task.supersedes_task_id) - if parent is not None: - log_task_event(parent, 'reservation_revision_superseded', details) + log_task_event(owner, 'reservation_revision_confirmed', details) def record_inventory_verification( @@ -204,7 +229,7 @@ def reserve_available_for_artifact( released_reservation_ids = { int(row.id) for row in ShippingReservation.query.filter( - ShippingReservation.task_id == task.id, + ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(verification_reservation_ids), ShippingReservation.snapshot_line_id.in_(released_ids), ).all() @@ -220,7 +245,7 @@ def reserve_available_for_artifact( } rows = ( ShippingReservation.query.filter( - ShippingReservation.task_id == task.id, + ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.status.in_({'available', 'pending'}), ShippingReservation.id.in_(set(verification_lines)), ) @@ -268,7 +293,7 @@ def current_available_snapshot_line_ids( (最新核验轮次, 本次可导出的冻结订单行 ID)。 """ verification = ( - ShippingInventoryVerification.query.filter_by(task_id=task.id, status='completed') + ShippingInventoryVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed') .order_by(ShippingInventoryVerification.id.desc()).first() ) if verification is None: @@ -278,7 +303,7 @@ def current_available_snapshot_line_ids( released_reservation_ids = { int(row.id) for row in ShippingReservation.query.filter( - ShippingReservation.task_id == task.id, + ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(verification_reservation_ids), ShippingReservation.snapshot_line_id.in_(released_ids), ).all() @@ -293,7 +318,7 @@ def current_available_snapshot_line_ids( ) } reservations = ShippingReservation.query.filter( - ShippingReservation.task_id == task.id, + ShippingReservation.task_id == _inventory_task_id(task), ShippingReservation.id.in_(reservation_ids), ShippingReservation.status.in_({'available', 'pending'}), ).all() if reservation_ids else [] @@ -305,3 +330,7 @@ def current_available_snapshot_line_ids( if not line_ids: raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY') return verification, line_ids +def _inventory_task_id(task: Any) -> int: + """返回库存事实所属 OT ID;正式 Notice 通过 order_task_id 关联 OT。""" + linked = getattr(task, 'order_task_id', None) + return int(linked) if linked is not None else int(task.id) diff --git a/backend/app/services/shipping_notice/runtime_context.py b/backend/app/services/shipping_notice/runtime_context.py index 7c1d1a03..d03bdb00 100644 --- a/backend/app/services/shipping_notice/runtime_context.py +++ b/backend/app/services/shipping_notice/runtime_context.py @@ -12,7 +12,8 @@ from __future__ import annotations import json from typing import Any -from app.models import ShippingNotice +from app import db +from app.models import ShippingNotice, ShippingOrderIntake, ShippingOrderTask from app.services.agent_runtime_context.builder import build_agent_runtime_context from app.services.shipping_notice.reference_context import build_shipping_reference_context @@ -74,7 +75,9 @@ def _build_refs( """ refs: dict[str, str] = {} task_no = _task_no(task) - file_name = _clean_text(getattr(task, "source_file_name", None)) + file_name = '' + if getattr(task, 'source_intake_id', None): + file_name = _clean_text(getattr(db.session.get(ShippingOrderIntake, int(task.source_intake_id)), 'filename', None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: refs["task_no"] = task_no @@ -114,16 +117,26 @@ def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]: state_hint["focus_task_no"] = task_no if task is not None: + owner = task + if isinstance(task, ShippingNotice) and task.order_task_id: + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + match_status = aggregate_match_status_for_task(getattr(owner, 'id', None)) or '' + upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip() for attr, key in ( ("current_step", "current_step"), ("review_status", "review_status"), - ("match_status", "match_status"), - ("pending_human_reason", "pending_human_reason"), - ("upload_status", "upload_status"), + (None, "match_status"), + (None, "upload_status"), ): - value = _clean_text(getattr(task, attr, None)) + value = match_status if key == 'match_status' else upload_status if key == 'upload_status' else _clean_text(getattr(owner, attr, None)) if value: state_hint[key] = value + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + pending_reason = _clean_text(task_blocking_reason(task)) + if pending_reason: + state_hint['pending_human_reason'] = pending_reason return state_hint @@ -145,10 +158,16 @@ def _build_summary( Returns: 200 字以内的现场摘要。 """ + owner = task + if isinstance(task, ShippingNotice) and task.order_task_id: + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task pieces: list[str] = [] task_no = _task_no(task) - file_name = _clean_text(getattr(task, "source_file_name", None)) - current_step = _clean_text(getattr(task, "current_step", None)) + file_name = '' + if getattr(owner, 'intake_id', None): + intake = db.session.get(ShippingOrderIntake, int(owner.intake_id)) + file_name = _clean_text(getattr(intake, 'filename', None)) + current_step = _clean_text(getattr(owner, "current_step", None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: pieces.append(f"当前任务 {task_no}") diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index e6509640..b73c0ad7 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -9,12 +9,13 @@ services/shipping_notice/shipping_processing_projection.py ShippingProcessExecution / FileAsset / Job。 逻辑:由 GET /shipping-processing/conversations/{id} 与 work-items 路由调用; 直接以 ShippingOrderTask 为 order_task 来源,Stage 1 Intake 作 order_intake; - Intake/OT 均填充 current_gate(优先真实 ProcessExecution)与 source_summary; - 输出前 reconcile status/stage/gate/action,并结合 Notice 失效起点 / Excel Artifact - 写入 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; + Intake/OT 均填充 current_gate(优先真实 ProcessExecution,含无 Notice 时 OT 活跃 Execution) + 与 source_summary;输出前 reconcile status/stage/gate/action,并结合 Notice 失效起点 / + Excel Artifact 写入 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; 不投影会话级批量恢复动作;失败必须由用户在当前 Gate 选择具体动作。 """ @@ -25,6 +26,7 @@ from dataclasses import dataclass from datetime import datetime from typing import Any +from sqlalchemy import or_ from sqlalchemy.orm import load_only, selectinload from app import db @@ -77,12 +79,27 @@ from app.services.shipping_notice.progress_audit_contract import ( logger = logging.getLogger(__name__) +def _latest_notice_for_order_task(order_task: ShippingOrderTask | None) -> ShippingNotice | None: + """按正式 Notice 的 order_task_id 反查最近一张通知单;OT 不保存反向通知指针。""" + if order_task is None or getattr(order_task, 'id', None) is None: + return None + return ( + ShippingNotice.query + .filter(ShippingNotice.order_task_id == int(order_task.id)) + .order_by(ShippingNotice.id.desc()) + .first() + ) + + @dataclass(frozen=True) class _ConversationProjectionLoadContext: """会话投影的一次性只读预取结果,避免 EML 附件按 Intake 重复查询。""" documents_by_intake_id: dict[int, list[ShippingOrderDocument]] intakes_by_no: dict[str, ShippingOrderIntake] + # 冻结选择计划中每个 Intake 的附件项(含已选/跳过状态),用于把尚未物化的 + # 「已选但未识别」附件展示出来,便于排查未识别原因。 + planned_attachments_by_intake_no: dict[str, list[dict[str, Any]]] prefetched_gate_attempts: list[ShippingProcessGateAttempt] read_cache: dict[str, Any] @@ -91,9 +108,18 @@ _CONVERSATION_PROJECTION_READ_CACHE_KEY = 'shipping_conversation_projection_read def _conversation_projection_read_cache() -> dict[str, Any] | None: - """返回当前会话投影的临时只读缓存;单项投影不启用该缓存。""" + """返回当前会话投影的临时只读缓存;单项投影不启用该缓存。 + + 该会话键会被下游 process_gate_projection / order_review_projection 复用并以不同 + 形状覆盖(只写 latest_attempt_by_id / gates_by_execution_id 等子集)。因此只有 + 确实由 _conversation_projection_load_context 赋予 load_context 形状(含 + current_case_by_document_id 标记键)时才视为会话投影缓存;否则按无缓存处理, + 让消费方回退到只读查询,避免读取到缺少 runs_by_id 等键的不完整字典。 + """ cached = db.session.info.get(_CONVERSATION_PROJECTION_READ_CACHE_KEY) - return cached if isinstance(cached, dict) else None + if isinstance(cached, dict) and 'current_case_by_document_id' in cached: + return cached + return None def _conversation_projection_load_context( @@ -309,14 +335,86 @@ def _conversation_projection_load_context( and case.confirmed_task_id is None for case in conversation_stream_cases ) + # 冻结选择计划仅用于 EML 附件(展示已选但未物化/未识别的附件行);直传 PDF + # 不消费该计划,读取它只会多扫一次 runs 快照。非 EML 会话直接跳过,保持 + # 首屏摘要零 runs 查询(否则空白/刚上传首屏会随历史 Run 数量线性变慢)。 + has_eml_intake = any( + str(getattr(intake, 'source_type', '') or '').strip().lower() == 'eml' + for intake in intakes + ) return _ConversationProjectionLoadContext( documents_by_intake_id=documents_by_intake_id, intakes_by_no={str(intake.intake_no): intake for intake in intakes}, + planned_attachments_by_intake_no=( + _frozen_attachment_plan_by_intake(intake_ids) if has_eml_intake else {} + ), prefetched_gate_attempts=prefetched_gate_attempts, read_cache=read_cache, ) +def _frozen_attachment_plan_by_intake( + intake_ids: list[int], +) -> dict[str, list[dict[str, Any]]]: + """读取当前(未被替代)Run 的冻结选择计划,按 Intake 归集附件项。 + + 核心逻辑:选择计划是发送时冻结的可审计事实,包含每个附件的 selected 结论与 + skip_reason_codes;供投影把「已选但尚未物化/未识别」的附件一并展示,便于排查 + 未识别原因。只读取选择计划本身,不触碰附件正文 / Document / 布局。 + """ + if not intake_ids: + return {} + run_rows = ( + ShippingOrderProcessingRun.query.with_entities( + ShippingOrderProcessingRun.input_snapshot_json, + ShippingOrderProcessingRun.request_snapshot_json, + ) + .join( + ShippingOrderProcessingRunIntake, + ShippingOrderProcessingRunIntake.run_id == ShippingOrderProcessingRun.id, + ) + .filter( + ShippingOrderProcessingRunIntake.intake_id.in_(intake_ids), + ShippingOrderProcessingRun.superseded_by_run_id.is_(None), + ) + .all() + ) + planned_by_key: dict[str, dict[str, dict[str, Any]]] = {} + for row in run_rows: + snapshot = ( + row.input_snapshot_json + if isinstance(row.input_snapshot_json, dict) + else row.request_snapshot_json + ) + if not isinstance(snapshot, dict): + continue + selection = snapshot.get('attachment_selection') + if not isinstance(selection, dict): + continue + for item in selection.get('items') or []: + if not isinstance(item, dict): + continue + intake_no = str(item.get('intake_no') or '').strip() + if not intake_no: + continue + attachment_key = str(item.get('attachment_key') or '').strip().lower() + content_hash = str(item.get('content_hash') or '').strip().lower() + filename = str(item.get('filename') or '').strip().lower() + item_key = attachment_key or content_hash or filename + if not item_key: + continue + entries = planned_by_key.setdefault(intake_no, {}) + current = entries.get(item_key) + # 重解析 Run 可能保留同一附件的旧 selected=True 与新 selected=False 快照; + # 展示和计数以用户曾明确选择过该附件为准,避免把实际提交的文件反向隐藏。 + if current is None or (item.get('selected') is True and current.get('selected') is not True): + entries[item_key] = dict(item) + return { + intake_no: list(entries.values()) + for intake_no, entries in planned_by_key.items() + } + + def _has_reparseable_batch_documents_for_projection( *, run: ShippingOrderProcessingRun, load_context: _ConversationProjectionLoadContext | None = None, @@ -560,7 +658,7 @@ def _intake_processing_status(intake: ShippingOrderIntake) -> str: source_type = str(intake.source_type or '').strip().lower() if extraction_status in {'failed', 'error', 'fatal'}: return 'failed' - if extraction_status in {'cancelled', 'canceled'}: + if extraction_status == 'cancelled': return 'cancelled' if parse_status == 'parse_failed': return 'failed' @@ -903,6 +1001,14 @@ def project_intake_work_item( unit_by_document_id=unit_by_document_id, load_context=load_context, ) + aggregate_children = _append_unrecognized_plan_attachments( + intake=intake, + aggregate_children=aggregate_children, + planned_by_intake_no=( + load_context.planned_attachments_by_intake_no + if load_context is not None else {} + ), + ) aggregate_states = [ str(child.get('user_status') or child.get('status') or '').strip().lower() for child in aggregate_children @@ -913,6 +1019,8 @@ def project_intake_work_item( if isinstance(child.get('facts'), dict) ] failed_count = sum(state in {'failed', 'retryable'} for state in aggregate_states) + # [AUTHORITY] 未确认 Candidate Review Case 投影为 waiting_human(等用户处置), + # 属待人工而不是系统处理中。 waiting_count = sum(state == 'waiting_human' for state in aggregate_states) completed_count = sum( state == 'completed' and upload_state == 'succeeded' @@ -945,7 +1053,7 @@ def project_intake_work_item( if any(state in {'failed', 'retryable'} for state in aggregate_states): payload['user_status'] = 'failed' payload['user_group'] = 'failed' - elif any(state in {'waiting_human', 'idle'} for state in aggregate_states): + elif any(state == 'waiting_human' for state in aggregate_states): payload['user_status'] = 'waiting_human' payload['user_group'] = 'waiting_human' elif all(state == 'completed' for state in aggregate_states): @@ -955,7 +1063,7 @@ def project_intake_work_item( payload['user_status'] = 'running' payload['user_group'] = 'processing' representative = next( - (child for child in aggregate_children if str(child.get('user_status') or '') in {'failed', 'retryable', 'waiting_human', 'idle'}), + (child for child in aggregate_children if str(child.get('user_status') or '') in {'failed', 'retryable', 'waiting_human'}), aggregate_children[0], ) payload['user_stage'] = str(representative.get('user_stage') or representative.get('stage') or payload.get('user_stage') or '') @@ -1024,15 +1132,29 @@ def _latest_intake_run_unit_outcomes( return outcomes -def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None: - """ - 从 Run 关联的首个 Intake 推断 source_type。 +_RUN_PRIMARY_INTAKE_CACHE_KEY = 'shipping_run_primary_intake_cache' - 核心逻辑:优先 active RunIntake → Intake.source_type;再回退快照 intakes。 + +def _run_primary_intake(run: ShippingOrderProcessingRun) -> ShippingOrderIntake | None: """ + 取 Run 关联的首个未释放 Intake;请求内按 run_id 记忆化。 + + 核心逻辑:单工作项/会话投影会在一次请求内多次调用 `_source_type_for_run` / + `_first_intake_no_for_run` / `_submission_no_for_run`,此前每次都重复查询 + RunIntake 链接。此处将「Run → 主 Intake」这一事实按 run_id 缓存到当前 + SQLAlchemy 会话(请求级),避免 N 次重复 SQL。快照 fallback 仍由调用方兜底。 + """ + cache = db.session.info.get(_RUN_PRIMARY_INTAKE_CACHE_KEY) + if not isinstance(cache, dict): + cache = {} + db.session.info[_RUN_PRIMARY_INTAKE_CACHE_KEY] = cache + run_id = int(run.id) + if run_id in cache: + return cache[run_id] + intake: ShippingOrderIntake | None = None link = ( ShippingOrderProcessingRunIntake.query.filter( - ShippingOrderProcessingRunIntake.run_id == int(run.id), + ShippingOrderProcessingRunIntake.run_id == run_id, ShippingOrderProcessingRunIntake.released_at.is_(None), ) .order_by(ShippingOrderProcessingRunIntake.position.asc()) @@ -1040,10 +1162,21 @@ def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None: ) if link is not None: intake = db.session.get(ShippingOrderIntake, int(link.intake_id)) - if intake is not None: - source = str(intake.source_type or '').strip().lower() or None - if source in ORDER_INTAKE_SOURCE_TYPES: - return source + cache[run_id] = intake + return intake + + +def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None: + """ + 从 Run 关联的首个 Intake 推断 source_type。 + + 核心逻辑:优先 active RunIntake → Intake.source_type;再回退快照 intakes。 + """ + intake = _run_primary_intake(run) + if intake is not None: + source = str(intake.source_type or '').strip().lower() or None + if source in ORDER_INTAKE_SOURCE_TYPES: + return source snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} for row in snapshot.get('intakes') or []: if not isinstance(row, dict): @@ -1064,18 +1197,9 @@ def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None: def _first_intake_no_for_run(run: ShippingOrderProcessingRun) -> str: """取 Run 首个关联 Intake 编号;无则空串。""" - link = ( - ShippingOrderProcessingRunIntake.query.filter( - ShippingOrderProcessingRunIntake.run_id == int(run.id), - ShippingOrderProcessingRunIntake.released_at.is_(None), - ) - .order_by(ShippingOrderProcessingRunIntake.position.asc()) - .first() - ) - if link is not None: - intake = db.session.get(ShippingOrderIntake, int(link.intake_id)) - if intake is not None: - return str(intake.intake_no) + intake = _run_primary_intake(run) + if intake is not None: + return str(intake.intake_no) snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} for row in snapshot.get('intakes') or []: if isinstance(row, dict) and row.get('intake_no'): @@ -1088,7 +1212,9 @@ def _submission_no_for_run(run: ShippingOrderProcessingRun) -> str: intake_no = _first_intake_no_for_run(run) if not intake_no: return '' - intake = ShippingOrderIntake.query.filter_by(intake_no=intake_no).first() + intake = _run_primary_intake(run) + if intake is None or str(intake.intake_no) != intake_no: + intake = ShippingOrderIntake.query.filter_by(intake_no=intake_no).first() if intake is None or not intake.order_submission_id: return '' submission = db.session.get(ShippingOrderSubmission, int(intake.order_submission_id)) @@ -1291,7 +1417,7 @@ def _current_open_case_for_order_task(order_task: ShippingOrderTask | None) -> S return None cache = _conversation_projection_read_cache() if cache is not None: - case = cache['current_case_by_document_id'].get(int(document_id)) + case = (cache.get('current_case_by_document_id') or {}).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( @@ -1306,6 +1432,65 @@ def _current_open_case_for_order_task(order_task: ShippingOrderTask | None) -> S ) +def _gate_dict_from_order_task_execution( + order_task: ShippingOrderTask, +) -> dict[str, Any] | None: + """ + 从 OT 活跃 ProcessExecution 投影轻量 current_gate(含完整 process_gate 摘要)。 + + 核心逻辑:优先 active_process_execution_id,校验 task_id/非 superseded 后 + 回退按 task_id 取最新活跃 Execution;无有效 Gate 时返回 None。 + + Args: + order_task: 已绑定履约 Execution 的 ShippingOrderTask。 + + Returns: + 含 gate_code/status/next_action_code/_process_gate_summary 的 dict;无 Execution 时 None。 + """ + from app.models import ShippingProcessExecution + from app.services.shipping_notice.process_gate_projection import ( + project_user_gate_summary, + ) + + execution = None + active_execution_id = getattr(order_task, 'active_process_execution_id', None) + if active_execution_id is not None: + execution = db.session.get(ShippingProcessExecution, int(active_execution_id)) + if execution is not None and ( + int(getattr(execution, 'task_id', 0) or 0) != int(order_task.id) + or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded' + ): + execution = None + if execution is None: + execution = ( + ShippingProcessExecution.query.filter_by(task_id=int(order_task.id)) + .filter(ShippingProcessExecution.status != 'superseded') + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None: + return None + summary = project_user_gate_summary(execution) + blocking = summary.get('current_blocking_gate') or summary.get('current_gate') + if not isinstance(blocking, dict) or not blocking.get('gate_code'): + return None + return { + 'gate_code': str(blocking.get('gate_code') or ''), + 'status': str(blocking.get('status') or 'blocked'), + 'next_action_code': ( + summary.get('next_action_code') + or blocking.get('next_action_code') + ), + 'blocking_reason_code': ( + summary.get('blocking_reason_code') + or blocking.get('blocking_reason_code') + ), + 'attempt_no': int(blocking.get('attempt_no') or 0), + # 写动作的 execution_no / Gate version 只能来自正式摘要。 + '_process_gate_summary': summary, + } + + def _order_task_current_gate( run: ShippingOrderProcessingRun, order_task: ShippingOrderTask | None, @@ -1313,8 +1498,9 @@ def _order_task_current_gate( """ 为 order_task 构造统一 current_gate 摘要。 - 核心逻辑:优先开放 Review Case 上的真实 ProcessExecution 门禁投影; - 无 Execution 时回退 Review Case / Run·OT 失败合成摘要;处理中不造假门禁。 + 核心逻辑:优先开放 Review Case 上的真实 ProcessExecution;其次 OT 活跃 Execution + (含尚未创建 Notice 的履约门禁,如库存满足性);无 Execution 时回退 Run·OT + 失败/waiting_review 合成摘要;处理中不造假门禁。 Args: run: Processing Run。 @@ -1388,49 +1574,12 @@ def _order_task_current_gate( 'attempt_no': 0, } - if order_task is not None and order_task.shipping_notice_id: - from app.models import ShippingProcessExecution - from app.services.shipping_notice.process_gate_projection import ( - project_user_gate_summary, - ) - - notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) - if notice is not None: - execution = None - active_execution_id = getattr(notice, 'active_process_execution_id', None) - if active_execution_id is not None: - execution = db.session.get(ShippingProcessExecution, int(active_execution_id)) - if execution is not None and ( - int(getattr(execution, 'task_id', 0) or 0) != int(notice.id) - or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded' - ): - execution = None - if execution is None: - execution = ( - ShippingProcessExecution.query.filter_by(task_id=int(notice.id)) - .filter(ShippingProcessExecution.status != 'superseded') - .order_by(ShippingProcessExecution.id.desc()) - .first() - ) - if execution is not None: - summary = project_user_gate_summary(execution) - blocking = summary.get('current_blocking_gate') or summary.get('current_gate') - if isinstance(blocking, dict) and blocking.get('gate_code'): - return { - 'gate_code': str(blocking.get('gate_code') or ''), - 'status': str(blocking.get('status') or 'blocked'), - 'next_action_code': ( - summary.get('next_action_code') - or blocking.get('next_action_code') - ), - 'blocking_reason_code': ( - summary.get('blocking_reason_code') - or blocking.get('blocking_reason_code') - ), - 'attempt_no': int(blocking.get('attempt_no') or 0), - # 写动作的 execution_no / Gate version 只能来自正式摘要。 - '_process_gate_summary': summary, - } + # [STEP] OT 活跃 Execution 优先于 status 启发式:正式 Notice 可能尚未创建 + # (库存匹配/满足性仍挂在 OT),不得把 waiting_review 误合成 open_order_review。 + if order_task is not None: + from_ot_execution = _gate_dict_from_order_task_execution(order_task) + if from_ot_execution is not None: + return from_ot_execution status = ( str(getattr(order_task, 'status', None) or '').strip().lower() @@ -1485,11 +1634,26 @@ def _child_order_tasks_for_run( .order_by(ShippingOrderTask.id.asc()) .all() ) + # [PERF] 批量预取兄弟 OT 的 Candidate,避免逐一 Lo 循环内 N+1 查询。 + candidate_ids = [ + int(sibling.candidate_id) + for sibling in siblings + if sibling.candidate_id + ] + candidates_by_id: dict[int, ShippingOrderCandidate] = {} + if candidate_ids: + candidates_by_id = { + int(candidate.id): candidate + for candidate in ShippingOrderCandidate.query.filter( + ShippingOrderCandidate.id.in_(candidate_ids), + ).all() + } rows: list[dict[str, Any]] = [] for sibling in siblings: - candidate = None - if sibling.candidate_id: - candidate = db.session.get(ShippingOrderCandidate, int(sibling.candidate_id)) + candidate = ( + candidates_by_id.get(int(sibling.candidate_id)) + if sibling.candidate_id else None + ) status = str(sibling.status or '').strip() or 'processing' if status not in SHIPPING_PROCESSING_STATUSES: status = map_run_status_to_processing_status(status) @@ -1512,10 +1676,8 @@ def _child_order_tasks_for_run( def _notice_no_for_order_task(order_task: ShippingOrderTask | None) -> str | None: - """若 OT 已挂正式 Notice,返回 notice.task_no(业务编号)。""" - if order_task is None or not order_task.shipping_notice_id: - return None - notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) + """若 OT 已创建正式 Notice,返回最近一张通知单 task_no。""" + notice = _latest_notice_for_order_task(order_task) if notice is None: return None return str(notice.task_no or '').strip() or None @@ -1571,8 +1733,8 @@ def _project_order_task_work_item( # [BE-02] 已挂正式 Notice 时与 Case.current_stage 同源(project_stage_for_task)。 stage_label_key = None notice_for_stage = None - if order_task.shipping_notice_id: - notice_for_stage = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) + if order_task is not None: + notice_for_stage = _latest_notice_for_order_task(order_task) if notice_for_stage is not None: from app.services.shipping_notice.order_review_workbench_projection import ( project_stage_for_task, @@ -1582,7 +1744,8 @@ def _project_order_task_work_item( if shared_code in SHIPPING_PROCESSING_STAGES: stage = shared_code stage_label_key = str(shared.get('label_key') or '').strip() or None - active_execution_id = getattr(notice_for_stage, 'active_process_execution_id', None) + # ProcessExecution 属于 OT;正式 Notice 不保存执行指针。 + active_execution_id = getattr(order_task, 'active_process_execution_id', None) if active_execution_id is not None: from app.models import ShippingProcessExecution active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id)) @@ -1620,13 +1783,17 @@ def _project_order_task_work_item( ) # 完成只接受三层可审计成功事实。旧 OT/process_status/upload_status 可能遗留 # completed/uploaded;缺少成功 Attempt 时必须停在货代上传,不能进入完成统计。 - from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + from app.services.shipping_notice.upload_attempt_service import ( + has_verified_upload_success, + project_notice_upload_status, + ) 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 '' + projected_upload = ( + project_notice_upload_status(notice_for_stage) if notice_for_stage is not None else None + ) notice_lifecycle = str(getattr(notice_for_stage, 'lifecycle_status', None) or '').strip().lower() if notice_for_stage is not None else '' if verified_upload_success: status = 'completed' @@ -1635,8 +1802,7 @@ def _project_order_task_work_item( 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'} + or projected_upload == 'uploaded' ): status = 'waiting_human' stage = 'freight_uploading' @@ -1656,8 +1822,8 @@ def _project_order_task_work_item( notice = None invalidated_from_stage = None excel_ready = False - if order_task.shipping_notice_id: - notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) + if order_task is not None: + notice = _latest_notice_for_order_task(order_task) if notice is not None: from app.services.shipping_notice.task_workflow import ( read_notice_invalidated_from_stage, @@ -1711,11 +1877,7 @@ def _project_order_task_work_item( case_no = str(getattr(linked_case, 'case_no', None) or '').strip() or None notice_no_for_task = _notice_no_for_order_task(order_task) - has_formal_ot = bool( - order_task is not None - and getattr(order_task, 'shipping_notice_id', None) is not None - and notice_no_for_task is not None - ) + has_formal_ot = bool(order_task is not None and notice_no_for_task is not None) current_gate = _order_task_current_gate(run, order_task) process_gate = None if isinstance(current_gate, dict): @@ -1800,7 +1962,7 @@ def _project_order_task_work_item( post_confirm=post_confirm_snapshot, is_admin=False, ) - # 建单前 Case 的 STP 事实优先于旧 OT/Run checkpoint。旧 stage 可能仍是 + # 建单前 Case 的 STP 事实优先于 OT/Run 遗留 stage。旧 stage 可能仍是 # document_parsing/customer_resolving,但不可重试 STP 失败实际已经停在 task_creation。 pre_ot_stp = str(bundle.get('user_stage') or '').strip().lower() == 'pre_ot_stp' if pre_ot_stp: @@ -1866,7 +2028,7 @@ def _project_order_task_work_item( child['current_gate'] = dict(payload.get('current_gate') or {}) except Exception: # noqa: BLE001 # Review bundle 是当前用户动作的权威来源;读取失败时不得静默回退到 - # 旧 checkpoint/notice 字段,避免前端展示可继续执行的过时动作。 + # 遗留 notice 字段,避免前端展示可继续执行的过时动作。 payload['user_status'] = 'waiting_human' payload.pop('retryable', None) payload['primary_action'] = None @@ -1883,9 +2045,10 @@ def _project_order_task_work_item( try: from app.models import ShippingInventoryPreparationAttempt + preparation_task_id = getattr(order_task, 'id', None) if order_task is not None else getattr(notice, 'order_task_id', None) preparation = ( ShippingInventoryPreparationAttempt.query - .filter_by(task_id=int(notice.id)) + .filter_by(task_id=int(preparation_task_id)) .filter(ShippingInventoryPreparationAttempt.status != 'superseded') .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) .first() @@ -1905,13 +2068,6 @@ def _project_order_task_work_item( } for row in source_attempts } - # 快照载入状态补入 prepared_sources(如果快照就绪且 inventory_lines_json 已保存但 per_source 尚未标记 prepared) - from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task - - if active_inventory_lines_for_task(notice) and notice.inventory_snapshot_id: - for code in required_sources: - if code and code not in prepared_sources and code not in pending_sources: - prepared_sources.append(code) inventory_preparation = { 'attempt_id': int(preparation.id) if preparation else None, 'attempt_no': int(preparation.attempt_no) if preparation else None, @@ -2068,6 +2224,9 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> """ 将 work_item 状态映射为会话任务卡 status_label(前端 i18n 键)。 + 核心逻辑:status_label 与 F2 user_status 对齐;人工等待只发 waiting_human, + 禁止再用 pending_review 冒充 status(waiting_review 仅属 stage)。 + Args: item: order_task 工作项 dict。 @@ -2078,9 +2237,9 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> 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' + return 'waiting_human' if user_status == 'waiting_human': - return 'pending_review' + return 'waiting_human' if user_status == 'retryable': return 'failed' if user_status in {'completed', 'cancelled', 'failed'}: @@ -2090,7 +2249,7 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> if status == 'failed': return 'failed' if status == 'waiting_review' or stage == 'waiting_review': - return 'pending_review' + return 'waiting_human' if status == 'completed' or stage == 'completed': return 'completed' if status == 'blocked': @@ -2111,7 +2270,7 @@ def _eml_aggregate_user_group( """ if any(state in {'failed', 'retryable'} for state in states): return 'failed' - if any(state in {'waiting_human', 'idle'} for state in states): + if any(state == 'waiting_human' for state in states): return 'waiting_human' if any(state not in {'completed', 'cancelled'} for state in states): return 'processing' @@ -2142,6 +2301,133 @@ def _intake_parse_case_primary_action(*, reparse_authorized: bool) -> dict[str, } +def _eml_leaf_processing_stage( + *, unit_status: str, parse_status: str, source_type: str | None, +) -> str: + """EML 无 OrderTask 叶子的统一 15 阶 stage 推进。 + + 识别主链顺序:document_parsing(材料解析/模板匹配/字段提取)→ + email_adjudicating(交叉裁决/邮件补充合并)→ candidate_creating(生成候选)。 + 仅作用于仍处于接收解析阶段的处理中叶子;失败/需人工/非订单由调用方先行裁决, + 因此这里只返回合法 SHIPPING_PROCESSING_STAGES 成员。 + """ + source = str(source_type or '').strip().lower() or None + unit = str(unit_status or '').strip().lower() + parsed = str(parse_status or '').strip().lower() + if unit == 'merging_supplement': + return 'email_adjudicating' if source == 'eml' else 'candidate_creating' + if unit in {'routing', 'matching_profile', 'extracting'}: + return 'document_parsing' + if unit == 'candidate_ready': + return 'candidate_creating' + # 尚无单元裁决:仍处于材料解析/版面对齐时显示文件解析;已解析则进入候选生成。 + if parsed in {'created', 'queued', 'parsing'}: + return 'document_parsing' + return 'candidate_creating' + + +def _planned_attachment_leaf( + plan_item: dict[str, Any], + *, + intake_no: str, + source_type: str | None = None, +) -> dict[str, Any]: + """把冻结选择计划里尚未物化的附件投影为「未识别」诊断叶子。 + + 核心逻辑:附件的真实识别结果以物化 `ShippingOrderDocument` 为准;计划中已选却 + 尚未物化的附件以 `facts.recognized=False` 标记,用于展示「待识别/处理中」,也用于 + 在文件统计中被排除(不计入已识别 total_files,但仍计入提交基 submitted_files)。 + `source_type` 沿用 Intake 真实来源(eml / direct_pdf),不写死为 eml。 + """ + filename = str(plan_item.get('filename') or '').strip() or None + attachment_key = str(plan_item.get('attachment_key') or '').strip() + return { + 'work_item_type': 'order_intake', + 'work_item_no': f'PLAN:{intake_no}:{attachment_key or filename or "unknown"}', + 'source_type': source_type or 'eml', + 'intake_no': intake_no, + 'status': 'processing', + 'user_status': 'processing', + 'user_stage': 'intake_parse', + 'stage': 'intake_parse', + 'user_group': 'processing', + 'source_summary': { + 'filename': filename, + 'document_count': 0, + 'document_id': None, + 'content_hash': str(plan_item.get('content_hash') or '').strip() or None, + 'attachment_key': attachment_key or None, + }, + 'facts': { + 'recognized': False, + 'plan_state': 'selected_pending', + }, + } + + +def _append_unrecognized_plan_attachments( + *, + intake: ShippingOrderIntake | None, + aggregate_children: list[dict[str, Any]], + planned_by_intake_no: dict[str, list[dict[str, Any]]], +) -> list[dict[str, Any]]: + """在 EML 聚合叶子后追加「已选但尚未物化/未识别」的附件诊断行。 + + 核心逻辑:已物化附件以其 document_id / content_hash / filename 与计划项匹配, + 匹配到的计划项不再重复;仅把计划中 selected=True 且尚未物化的附件追加为未识别行, + 便于排查「为什么这份没识别」。跳过项(duplicate/budget 等)不属于批次提交范围, + 不在此机械追加,避免与 submitted_files 口径冲突。 + + 摘要与详情/工作项路径共用本函数(传入各自的 `planned_by_intake_no`),保证 + 「全空窗期」也能把已选但尚未物化的附件列出,而非只有 submitted/total 计数。 + """ + if intake is None: + return aggregate_children + planned = planned_by_intake_no.get( + str(intake.intake_no or '').strip(), [], + ) + if not planned: + return aggregate_children + recognized_keys: set[str] = set() + for child in aggregate_children: + summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {} + content_hash = str(summary.get('content_hash') or '').strip().lower() + if content_hash: + recognized_keys.add(f'hash:{content_hash}') + document_id = int(summary.get('document_id') or 0) + if document_id > 0: + recognized_keys.add(f'doc:{document_id}') + filename = str(summary.get('filename') or '').strip().lower() + if filename: + recognized_keys.add(f'fn:{filename}') + attachment_key = str(summary.get('attachment_key') or '').strip().lower() + if attachment_key: + recognized_keys.add(f'ak:{attachment_key}') + result = list(aggregate_children) + seen: set[str] = set() + for item in planned: + if item.get('selected') is not True: + continue + filename = str(item.get('filename') or '').strip().lower() + content_hash = str(item.get('content_hash') or '').strip().lower() + attachment_key = str(item.get('attachment_key') or '').strip().lower() + key = ( + f'hash:{content_hash}' if content_hash + else f'fn:{filename}' if filename + else f'ak:{attachment_key}' if attachment_key + else f'plan:{attachment_key}' + ) + if key in recognized_keys or key in seen: + continue + seen.add(key) + result.append(_planned_attachment_leaf( + item, + intake_no=str(intake.intake_no or ''), + source_type=str(getattr(intake, 'source_type', None) or '').strip().lower() or None, + )) + return result + + def _eml_aggregate_document_children( *, intake: ShippingOrderIntake | None, @@ -2233,10 +2519,17 @@ def _eml_aggregate_document_children( # Case 是候选落库后的正式人工阶段事实;Unit 保留 candidate_ready 不能让 # EML 聚合退回「接收解析」。当前 Case 可来自局部重解析后的新 Unit, # 故必须按原 Document 的 Stream 指针查找,不能按旧 unit_id 反查。 + # 会话缓存键会被下游 process_gate_projection 复用并覆盖成不同形状(缺失 + # current_case_by_document_id);只在缓存明确命中时才用它,否则回退查询, + # 避免把真实存在的当前 Case 因缓存形状不匹配而误判为无人工处置。 cache = _conversation_projection_read_cache() + cached_cases = ( + cache.get('current_case_by_document_id') + if isinstance(cache, dict) else None + ) review_case = ( - cache['current_case_by_document_id'].get(int(document.id)) - if cache is not None else ( + cached_cases.get(int(document.id)) + if isinstance(cached_cases, dict) and int(document.id) in cached_cases else ( ShippingOrderReviewCase.query.join( ShippingOrderReviewStream, ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, @@ -2338,6 +2631,13 @@ def _eml_aggregate_document_children( ) ) if review_case is not None else unit_run ) + # [PROGRESS] 仍处接收解析的处理中叶子按真实单元/解析状态推进统一 15 阶, + # 避免整批折叠为 candidate_creating(解析/交叉裁决/生成候选应可区分)。 + leaf_stage = _eml_leaf_processing_stage( + unit_status=unit_status, + parse_status=parse_status, + source_type='eml', + ) leaf = { 'work_item_type': 'document', 'work_item_no': f'DOCUMENT:{document.id}', @@ -2353,8 +2653,8 @@ def _eml_aggregate_document_children( 'submission_no': '', 'intake_no': str(intake.intake_no), 'status': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else 'waiting_review' if review_required else 'processing', - 'stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating', - 'stage_label_key': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating', + 'stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else leaf_stage, + 'stage_label_key': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else leaf_stage, '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, @@ -2367,7 +2667,7 @@ def _eml_aggregate_document_children( ), 'primary_action': review_primary if (review_case is not None or unit_failed) else None, 'user_status': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else review_status if review_case is not None else 'waiting_human' if review_required else 'running', - 'user_stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating', + 'user_stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else leaf_stage, 'user_group': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'processing', 'facts': {'upload_state': 'not_required' if non_order_completed else 'not_created'}, # 接收解析阶段入口由后端裁决:开放 Case 可进入处置;尚无 Case 的失败 @@ -2459,10 +2759,20 @@ def _aggregate_eml_order_task_work_items( ), load_context=load_context, ) + # 追加「已选但尚未物化/未识别」的计划附件诊断行,使列表与 submitted_files + # 口径一致,并把未识别原因暴露给用户排查。 + aggregate_children = _append_unrecognized_plan_attachments( + intake=intake, + aggregate_children=aggregate_children, + planned_by_intake_no=( + load_context.planned_attachments_by_intake_no + if load_context is not None else {} + ), + ) states = [_state(item) for item in aggregate_children] upload_states = [_upload_state(item) for item in aggregate_children] failed_count = sum(state in {'failed', 'retryable'} for state in states) - waiting_count = sum(state in {'waiting_human', 'idle'} for state in states) + waiting_count = sum(state == 'waiting_human' for state in states) # 用户视角的完成必须同时满足任务完成,且已货代上传或已正式裁决无需上传; # 候选已生成等中间态仍在处理中。 completed_count = sum( @@ -2538,7 +2848,7 @@ def _aggregate_eml_order_task_work_items( # 待人工按钮”的矛盾组合。 actionable_states = ( {'failed', 'retryable'} if aggregate_group == 'failed' - else {'waiting_human', 'idle'} if aggregate_group == 'waiting_human' + else {'waiting_human'} if aggregate_group == 'waiting_human' else set() ) actionable_child = next( @@ -2772,11 +3082,33 @@ def _conversation_task_row_from_work_item( # [AUTHORITY] EML 子文件已在后端聚合;会话/批次 UI 直接透传,禁止前端再按 # intake_no、状态或历史 Run 文档列表重新构建。 'aggregate_children': item.get('aggregate_children') or [], + 'source_type': item.get('source_type'), 'user_group': user_group, 'ui_state': _processing_ui_state_from_item(item), } +def _process_gate_allowed_action_codes(item: dict[str, Any]) -> list[str]: + """从 C 摘要(process_gate)提取原始 Gate 动作码,供 A 的 ui_state 透传(§2.5 归一)。 + + 优先级:allowed_actions(原始码列表)→ action_presentation[].code(含展示元数据)。 + C 的这些码已是与写契约(request_gate_action/PROCESS_GATE_ACTION_CODES)对齐的原始码; + A 不再用 available_actions 的展示别名覆盖它们,避免 mark_manual_uploaded→open_manual_upload 漂移。 + """ + process_gate = item.get('process_gate') + if not isinstance(process_gate, dict): + return [] + allowed = list(process_gate.get('allowed_actions') or []) + if allowed: + return [str(c or '').strip() for c in allowed if str(c or '').strip()] + presentation = process_gate.get('action_presentation') or [] + return [ + str(p.get('code') or '').strip() + for p in presentation + if isinstance(p, dict) and str(p.get('code') or '').strip() + ] + + def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: """将最终 Processing 投影封装为用户展示状态与已授权动作。 @@ -2790,6 +3122,16 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: 可被聊天卡、批次中心和工作台直接渲染的 ui_state。 """ primary_raw = item.get('primary_action') + # 正式 OT 的 Gate 摘要是恢复动作唯一来源;工作项兼容投影可能没有同步顶层 + # primary_action,但 current_blocking_gate/next_action_code 仍已明确授权。 + # 回填到 A(ui_state) 后,右侧任务卡才能展示并提交该恢复动作。 + if not isinstance(primary_raw, dict): + process_gate = item.get('process_gate') if isinstance(item.get('process_gate'), dict) else {} + gate_view = process_gate.get('current_blocking_gate') or process_gate.get('current_gate') or {} + gate_status = str(gate_view.get('status') or '').strip().lower() + gate_code = str(process_gate.get('next_action_code') or gate_view.get('next_action_code') or '').strip() + if gate_status in {'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal'} and gate_code: + primary_raw = {'code': gate_code, 'variant': 'primary'} primary = dict(primary_raw) if isinstance(primary_raw, dict) else None source_summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {} lifecycle = project_lifecycle( @@ -2808,7 +3150,7 @@ 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, + processing_stage=str(item.get('stage') or item.get('user_stage') or '').strip() or None, ) lifecycle_stage = lifecycle['lifecycle_stage'] if lifecycle_stage == 'upload_complete': @@ -2826,7 +3168,11 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: primary['target_lifecycle_stage'] = action_target primary_code = str((primary or {}).get('code') or '').strip() if lifecycle_stage != 'upload_complete': - for raw_code in item.get('available_actions') or []: + # [§2.5 差异① 归一] 次动作码透传 C 的原始 Gate 码(allowed_actions/action_presentation), + # 不再经 available_actions 的展示别名(如 mark_manual_uploaded→open_manual_upload)。 + # 使 A == B == C 动作码逐字一致,前端从 A 读到的码能与写契约(request_gate_action)对齐。 + raw_codes = list(_process_gate_allowed_action_codes(item)) or list(item.get('available_actions') or []) + for raw_code in raw_codes: code = str(raw_code or '').strip() if not code or code == primary_code: continue @@ -2877,8 +3223,9 @@ def _strip_legacy_action_fields_for_response(value: Any) -> Any: """在 API 边界移除已下线的顶层动作镜像。 内部投影仍可用 ``primary_action`` / ``available_actions`` 选择 EML 当前代表项, - 但对外唯一动作合同是 ``ui_state``。在最终序列化前剥离镜像,防止新旧合同再次被 - 客户端混用;递归处理 EML 子附件和会话状态组。 + 但对外唯一动作合同是 ``ui_state``。在最终序列化前剥离顶层镜像,防止新旧合同再次被 + 客户端混用;递归处理 EML 子附件和会话状态组。注意:``ui_state`` 是外部动作合同本体, + 其中的 ``primary_action`` / ``secondary_actions`` 必须保留,只剥离聚合/工作项顶层的旧镜像。 Args: value: 已完成全部聚合的公开 DTO 片段。 @@ -2886,15 +3233,21 @@ def _strip_legacy_action_fields_for_response(value: Any) -> Any: 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 _inner(item: Any, *, inside_ui_state: bool = False) -> Any: + if isinstance(item, list): + return [_inner(entry, inside_ui_state=inside_ui_state) for entry in item] + if not isinstance(item, dict): + return item + result: dict[str, Any] = {} + for key, sub in item.items(): + if not inside_ui_state and key in {'primary_action', 'available_actions'}: + continue + if key == 'ui_state': + result[key] = _inner(sub, inside_ui_state=True) + else: + result[key] = _inner(sub, inside_ui_state=inside_ui_state) + return result + return _inner(value) def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) -> str | None: @@ -2934,7 +3287,7 @@ def _lifecycle_stage_from_item(item: dict[str, Any]) -> str | None: 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, + processing_stage=str(item.get('stage') or item.get('user_stage') or '').strip() or None, )['lifecycle_stage'] @@ -3047,7 +3400,7 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> ) actionable_states = ( {'failed', 'retryable'} if group == 'failed' else - {'waiting_human', 'idle'} if group == 'waiting_human' else set() + {'waiting_human'} if group == 'waiting_human' else set() ) representative = next( (child for child in current_children if _state(child) in actionable_states), @@ -3085,11 +3438,11 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> for state, upload_state in zip(states, upload_states) ), 'processing': sum( - state not in {'failed', 'retryable', 'waiting_human', 'idle', 'completed'} + state not in {'failed', 'retryable', 'waiting_human', 'completed'} or (state == 'completed' and upload_state != 'succeeded') for state, upload_state in zip(states, upload_states) ), - 'needs_action': sum(state in {'waiting_human', 'idle'} for state in states), + 'needs_action': sum(state == 'waiting_human' for state in states), 'failed': sum(state in {'failed', 'retryable'} for state in states), 'stages': sorted({ str(child.get('user_stage') or child.get('stage') or '').strip() @@ -3158,6 +3511,10 @@ def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, A for code in LIFECYCLE_STAGE_CODES } for item in ranked_items: + facts = item.get('facts') if isinstance(item.get('facts'), dict) else {} + # 已选但未识别的诊断附件仅用于解释提交文件差异,不能进入业务五阶段。 + if facts.get('recognized') is False: + continue lifecycle_stage = _lifecycle_stage_from_item(item) if lifecycle_stage is None: continue @@ -3226,8 +3583,7 @@ def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str, if not task_no or task_no in seen: continue task = ShippingOrderTask.query.filter_by(task_no=task_no).first() - notice_id = getattr(task, 'shipping_notice_id', None) if task is not None else None - notice = db.session.get(ShippingNotice, int(notice_id)) if notice_id else None + notice = _latest_notice_for_order_task(task) resolved = resolve_task_export_download(notice) if resolved is None: continue @@ -3267,6 +3623,8 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An return { 'status': str(selected.get('user_status') or selected.get('status') or 'running'), 'stage': str(selected.get('user_stage') or selected.get('stage') or ''), + # 5 业务阶段:与右侧批次中心轨道、工作台导航同源(前端只读做 i18n,禁止再映射)。 + 'lifecycle_stage': _lifecycle_stage_from_item(selected), 'blocking_reason': ( dict(selected['blocking_reason']) if isinstance(selected.get('blocking_reason'), dict) @@ -3287,11 +3645,186 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An def _batch_user_group(item: dict[str, Any]) -> str: - """返回领域投影已经裁决的唯一用户分组,缺失时保持未分类。""" + """返回领域投影已经裁决的唯一用户分组,缺失时保持未分类。 + + work_item 未携带显式 ``user_group``(例如直接由 ``_project_order_task_work_item`` + 投影、未经过 EML 聚合)时,以权威 ``user_status`` / ``status`` / ``stage`` 兜底推导同 + 一状态组,保证 status_groups、批次统计与五阶段与该文件的顶层用户态完全同源。 + """ group = str(item.get('user_group') or '').strip().lower() - if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'}: - return group - return 'unclassified' + if group: + if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', 'unclassified'}: + return group + return 'unclassified' + user_status = str(item.get('user_status') or '').strip().lower() + status = str(item.get('status') or '').strip().lower() + stage = str(item.get('stage') or '').strip().lower() + if user_status in {'failed', 'retryable'}: + return 'failed' + if user_status == 'waiting_human': + return 'waiting_human' + if user_status in {'cancelled', 'archived', 'voided', 'deleted'}: + return 'cancelled' + if user_status == 'completed': + return 'completed' + if user_status == 'running': + return 'processing' + if status in {'failed', 'blocked'}: + return 'failed' + if status == 'waiting_review' or stage == 'waiting_review': + return 'waiting_human' + if status in {'cancelled', 'archived', 'voided', 'deleted'} or stage in { + 'cancelled', 'archived', 'voided', 'deleted', + }: + return 'cancelled' + if status == 'completed' or stage == 'completed': + return 'completed' + return 'processing' + + +def _split_eml_rows_by_leaf_status(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """将混合状态 EML 拆为按 PDF 状态分区的只读展示行。""" + result: list[dict[str, Any]] = [] + for row in rows: + children = row.get('aggregate_children') if isinstance(row.get('aggregate_children'), list) else [] + is_eml = str(row.get('source_type') or '').strip().lower() == 'eml' + grouped: dict[str, list[dict[str, Any]]] = {} + for child in children: + if not isinstance(child, dict): + continue + group = _batch_user_group(child) + if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'}: + grouped.setdefault(group, []).append(child) + if not is_eml or not grouped: + result.append(row) + continue + total = len(children) + for group, grouped_children in grouped.items(): + grouped_row = dict(row) + representative = grouped_children[0] + grouped_row.update({ + 'aggregate_children': grouped_children, + 'file_count': len(grouped_children), + 'user_group': group, + 'group': 'needs_action' if group in {'failed', 'waiting_human'} else ( + 'history' if group in {'cancelled', 'archived'} else group + ), + 'status_label': 'waiting_human' if group == 'waiting_human' else ( + 'processing' if group == 'processing' else group + ), + 'user_status': 'running' if group == 'processing' else group, + 'user_stage': representative.get('user_stage') or representative.get('stage'), + 'ui_state': representative.get('ui_state'), + 'available_actions': list(representative.get('available_actions') or []), + 'primary_action': representative.get('primary_action'), + 'blocking_reason': representative.get('blocking_reason'), + }) + summary = dict(row.get('aggregate_summary') or {}) + summary.update({'total': total, 'in_group': len(grouped_children)}) + grouped_row['aggregate_summary'] = summary + result.append(grouped_row) + return result + + +def _conversation_submitted_file_count( + *, user_id: int, conversation_id: str, +) -> int: + """会话级「本次提交/已选附件数」,来自冻结选择计划,物化前即可用且单调递增。 + + 核心逻辑:直传 PDF(非 EML)的提交基只读授权 ShippingOrderIntake(会话内非 EML + Intake 数),不触碰处理 Run 快照;仅 EML Intake 需要其冻结选择计划(当前未被替代 + Run 的快照)来求已选附件数(随追加 / 扩批增长)。该值是用户在发送时刻就已知的 + 「提交基」事实,绝不随物化进度回落为 0。 + 已识别数(处理中/完成/待办/失败)另由 _batch_file_counts 基于物化文档裁决, + 本函数只负责提交基主计数,两者不能混用。 + """ + normalized = str(conversation_id or '').strip() + if not normalized: + return 0 + # [STEP 1] 授权事实先行:直传 PDF(非 EML)的提交基 = 会话内非 EML Intake 数。 + # 只读 ShippingOrderIntake 即可得出;绝不为直传 PDF 会话回退到处理 Run 的 + # JSON 快照解码,避免首屏摘要重新进入 run 轮询路径(BE:summary 不读 run 快照)。 + intake_rows = ( + ShippingOrderIntake.query.with_entities( + ShippingOrderIntake.id, + ShippingOrderIntake.source_type, + ) + .filter( + ShippingOrderIntake.user_id == int(user_id), + ShippingOrderIntake.conversation_id == normalized, + ShippingOrderIntake.purpose == 'shipping_notice', + ) + .all() + ) + direct_pdf_count = sum( + 1 + for row in intake_rows + if str(row.source_type or '').strip().lower() != 'eml' + ) + has_eml = any( + str(row.source_type or '').strip().lower() == 'eml' + for row in intake_rows + ) + if not has_eml: + # 无 EML 参与即不存在冻结附件选择,提交基仅由直传 PDF Intake 构成。 + return direct_pdf_count + # [STEP 2] 仅 EML 需要冻结选择计划(当前 Run 快照)来求已选附件数;这是 + # 首屏摘要的唯一例外(见 project_conversation_processing_summary 注释)。 + rows = ( + ShippingOrderProcessingRun.query.with_entities( + ShippingOrderProcessingRun.input_snapshot_json, + ShippingOrderProcessingRun.request_snapshot_json, + ) + .filter( + ShippingOrderProcessingRun.user_id == int(user_id), + ShippingOrderProcessingRun.conversation_id == normalized, + ShippingOrderProcessingRun.superseded_by_run_id.is_(None), + ) + .all() + ) + selected_eml_attachments: set[tuple[str, str]] = set() + active_intake_ids: set[int] = set() + for row in rows: + # input_snapshot_json 是物化/执行快照(扩批后更新);缺失时回退只读审计快照。 + snapshot = ( + row.input_snapshot_json + if isinstance(row.input_snapshot_json, dict) + else row.request_snapshot_json + ) + if not isinstance(snapshot, dict): + continue + selection = snapshot.get('attachment_selection') + if isinstance(selection, dict): + for item in selection.get('items') or []: + if not isinstance(item, dict) or item.get('selected') is not True: + continue + intake_no = str(item.get('intake_no') or '').strip() + attachment_key = str(item.get('attachment_key') or '').strip().lower() + content_hash = str(item.get('content_hash') or '').strip().lower() + filename = str(item.get('filename') or '').strip().lower() + item_key = attachment_key or content_hash or filename + if intake_no and item_key: + selected_eml_attachments.add((intake_no, item_key)) + for raw_intake in snapshot.get('intakes') or []: + if isinstance(raw_intake, dict) and int(raw_intake.get('intake_id') or 0): + active_intake_ids.add(int(raw_intake['intake_id'])) + if not active_intake_ids: + return len(selected_eml_attachments) + direct_pdf_count + # 直传 PDF(非 EML):每个当前活动 Intake 即为 1 个业务文件。 + # 注意 source_type 为 NULL(历史/未知)也算非 EML,避免 SQL 的 NULL != 'eml' 过滤掉。 + direct_pdf_count = ( + ShippingOrderIntake.query + .filter( + ShippingOrderIntake.id.in_(active_intake_ids), + ShippingOrderIntake.purpose == 'shipping_notice', + or_( + ShippingOrderIntake.source_type.is_(None), + ShippingOrderIntake.source_type != 'eml', + ), + ) + .count() + ) + return len(selected_eml_attachments) + direct_pdf_count def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]: @@ -3299,6 +3832,11 @@ def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]: # 已取消/归档文件保留在历史列表,但不构成当前任务完成率的分母或分子。 groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0} for item in _current_file_representatives(work_items): + # 「已选但尚未物化/未识别」的计划附件只计入提交基 submitted_files, + # 不计入已识别 total_files / 各状态数;否则会把未识别文件误报为已识别。 + facts = item.get('facts') if isinstance(item.get('facts'), dict) else {} + if facts.get('recognized') is False: + continue 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() @@ -3320,6 +3858,7 @@ def _conversation_processing_from_work_items( *, focused_task_no: str | None = None, recent_task_no: str | None = None, + submitted_files: int | None = None, ) -> dict[str, Any]: """ 由最终 work_items 构建完整详情投影。 @@ -3350,6 +3889,11 @@ def _conversation_processing_from_work_items( continue row = _conversation_task_row_from_work_item(item, focused_task_no=focused) all_rows.append(row) + + # [STEP 1] PDF 是状态主体,EML 仅提供邮件上下文。同一 EML 的不同状态附件 + # 必须分别进入各自状态组,绝不能因父卡优先级把处理中附件混入“已完成”。 + all_rows = _split_eml_rows_by_leaf_status(all_rows) + for row in all_rows: if recent and row['user_task_no'] == recent: row['recently_created'] = True def _sort_key(entry: dict[str, Any]) -> str: @@ -3395,6 +3939,9 @@ def _conversation_processing_from_work_items( 'summary': { 'total_tasks': total, 'total_files': total_files, + # 提交基主计数:来自冻结选择计划,物化前即 ≥1、单调递增。 + # 注意与 total_files 解耦——total_files 仍是「已识别数」,用作完成率分母。 + 'submitted_files': max(0, int(submitted_files or 0)), 'processing': len(status_groups['processing']), 'needs_action': len(status_groups['failed']) + len(status_groups['waiting_human']), 'completed': len(status_groups['completed']), @@ -3426,14 +3973,18 @@ def project_conversation_processing_summary( 首屏只需要后端已裁决的状态→EML→PDF树、统计和已授权动作标识;完整 work_items、Gate 执行上下文与旧四组镜像属于详情读模型,必须按需通过 work-item 接口读取。摘要仅批量读取正式 Gate 的最小状态列,绝不加载 - Attempt、Run JSON 或详情上下文,避免同一任务在首屏响应中重复传输三次。 + Attempt 或详情上下文,避免同一任务在首屏响应中重复传输三次。冻结选择计划 + 是唯一例外:仅用于保留用户已选、但仍未识别的附件诊断行。 + + ProcessExecution / ShippingProcessGate 必须按 OT.id(非 candidate_id)批量加载; + 否则 Gate 查空后叶子会退化,批次中心同时丢失五阶段入口与门禁主按钮。 """ del agent_id normalized = str(conversation_id or '').strip() if not normalized: raise ValidationError('conversation_id is required') - # 首屏严禁加载 Run JSON 快照、Plan/Unit 或 Gate Attempt;它们只属于详情读取。 + # 首屏严禁加载 Plan/Unit 或 Gate Attempt;它们只属于详情读取。 # 摘要只读取状态树和操作裁决所需列;正文、解析结果和重复检测 JSON # 属于详情读模型,禁止在首屏查询中触发 ORM 反序列化。 intakes = ShippingOrderIntake.query.options(load_only( @@ -3453,6 +4004,8 @@ def project_conversation_processing_summary( for document in ShippingOrderDocument.query.options(load_only( ShippingOrderDocument.id, ShippingOrderDocument.intake_id, + ShippingOrderDocument.attachment_key, + ShippingOrderDocument.content_hash, ShippingOrderDocument.filename, ShippingOrderDocument.parse_status, ShippingOrderDocument.classification, @@ -3463,6 +4016,16 @@ def project_conversation_processing_summary( 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) + # 冻结选择计划只服务 EML 附件的「已选但未物化」诊断行;直传 PDF 会话无附件选择, + # 不必为了空结果去读处理 Run 快照(摘要禁入 run 轮询路径)。 + has_eml_attachment_selection = any( + str(intake.source_type or '').strip().lower() == 'eml' + for intake in intakes + ) + planned_attachments_by_intake_no = ( + _frozen_attachment_plan_by_intake(intake_ids) + if has_eml_attachment_selection else {} + ) asset_ids = [int(item.asset_id) for item in intakes if item.asset_id] assets = { int(asset.id): asset @@ -3491,12 +4054,12 @@ def project_conversation_processing_summary( 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.active_process_execution_id, ShippingOrderTask.updated_at, )).filter( ShippingOrderTask.user_id == int(user_id), @@ -3507,49 +4070,36 @@ def project_conversation_processing_summary( } # 正式 Notice / Execution / 当前 Gate 是建单后业务阶段的唯一真相。摘要以 # 固定三次批量查询取得最小列,不触碰 Gate Attempt、详情 JSON 或关系加载。 + # task_ids = OT 主键列表;后续 Notice 与 ProcessExecution 均按 OT.id 过滤。 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) + # task_ids 必须保持为 OT 主键:ProcessExecution.task_id 绑定 OT.id。 + # 禁止再写成 list(tasks_by_candidate_id)(那是 candidate_id),否则 Gate 整批查空, + # 批次进度中心会丢掉五阶段入口与门禁主按钮。 executions_by_id: dict[int, ShippingProcessExecution] = {} - latest_execution_by_notice_id: dict[int, ShippingProcessExecution] = {} - if notice_ids: + latest_execution_by_task_id: dict[int, ShippingProcessExecution] = {} + if task_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.task_id.in_(task_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) + latest_execution_by_task_id.setdefault(int(execution.task_id), execution) current_gate_codes = { str(execution.current_gate_code).strip() for execution in executions_by_id.values() @@ -3573,17 +4123,10 @@ def project_conversation_processing_summary( """返回摘要所需的正式当前 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)) + executions_by_id.get(int(task.active_process_execution_id)) + if task.active_process_execution_id is not None + else latest_execution_by_task_id.get(int(task.id)) ) if execution is None: return None @@ -3780,6 +4323,11 @@ def project_conversation_processing_summary( 'source_summary': { 'document_id': int(document.id), 'filename': str(document.filename or '').strip() or None, + # 与详情/工作项叶子保持一致:携带 content_hash / attachment_key, + # 供 _append_unrecognized_plan_attachments 按附件身份去重,避免把 + # 已物化附件再补成一份 pending(recognized=false)重复行。 + 'content_hash': str(document.content_hash or '').strip().lower() or None, + 'attachment_key': str(document.attachment_key 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, @@ -3793,6 +4341,26 @@ def project_conversation_processing_summary( } return _with_processing_ui_state(leaf) + def _is_selected_attachment( + intake: ShippingOrderIntake, + document: ShippingOrderDocument, + ) -> bool: + """判断已物化附件是否属于用户冻结时明确选择的 EML 文件。""" + document_attachment_key = str(document.attachment_key or '').strip().lower() + document_content_hash = str(document.content_hash or '').strip().lower() + for item in planned_attachments_by_intake_no.get(str(intake.intake_no), []): + if item.get('selected') is not True: + continue + if document_attachment_key and document_attachment_key == str( + item.get('attachment_key') or '' + ).strip().lower(): + return True + if document_content_hash and document_content_hash == str( + item.get('content_hash') or '' + ).strip().lower(): + return True + return False + groups: dict[str, list[dict[str, Any]]] = {key: [] for key in ( 'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', )} @@ -3805,13 +4373,33 @@ def project_conversation_processing_summary( 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: + if not _is_selected_attachment(intake, document): + continue + leaf = _leaf(document, task, case) + leaf.update({ + 'current_gate': None, + 'blocking_reason': None, + 'primary_action': None, + 'available_actions': [], + 'intake_parse_authorized': False, + 'facts': {'recognized': False, 'plan_state': 'selected_pending'}, + }) + leaves.append(_with_processing_ui_state(leaf)) continue if task is not None: tasks.append(task) leaves.append(_leaf(document, task, case)) + # 冻结选择计划中已选、但尚未物化 Document 的附件,也作为 pending + # (recognized=false)叶子补齐,与详情/工作项路径共用同一契约;否则空窗期 + # 首屏只剩 submitted/total 计数、没有任何文件名可列(前端只能转圈)。 + leaves = _append_unrecognized_plan_attachments( + intake=intake, + aggregate_children=leaves, + planned_by_intake_no=planned_attachments_by_intake_no, + ) if not leaves: continue states = [str(leaf['user_status']) for leaf in leaves] @@ -3825,9 +4413,13 @@ def project_conversation_processing_summary( groups[group].append({ 'user_task_no': task_no, 'title': title, + # [STEP 1] 保留 Intake 来源,供后续按叶子状态拆分 EML。缺失该字段时 + # _split_eml_rows_by_leaf_status 会把邮件当作普通单文件行,父级状态会 + # 覆盖其中仍在处理的 PDF。 + 'source_type': source_type, '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), + 'status_label': 'waiting_human' 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), @@ -3861,6 +4453,15 @@ def project_conversation_processing_summary( # [AUTHORITY] 首屏摘要与详情投影一样,以同一批文件叶子的互斥用户分组 # 生成总数和四个状态数。此前这里只返回 total_files,前端却按 *_files # 渲染批次概览,造成“总文件有数、四个状态全为 0”的合同断裂。 + split_rows = _split_eml_rows_by_leaf_status([ + row for rows in groups.values() for row in rows + ]) + groups = { + group: [row for row in split_rows if row.get('user_group') == group] + for group in groups + } + # EML 被按叶子状态拆分后才计算文件摘要;计数仍按 document_id 去重,不会因 + # 同一封邮件跨状态展示而重复增加。 summary_file_counts = _batch_file_counts([ row for rows in groups.values() @@ -3871,6 +4472,11 @@ def project_conversation_processing_summary( 'summary': { 'total_tasks': sum(len(rows) for rows in groups.values()), **summary_file_counts, + # 提交基主计数:与 total_files(已识别数)解耦,物化前即 ≥1、单调递增。 + 'submitted_files': _conversation_submitted_file_count( + user_id=int(user_id), + conversation_id=normalized, + ), 'processing': len(groups['processing']), 'needs_action': len(groups['failed']) + len(groups['waiting_human']), 'completed': len(groups['completed']), @@ -4081,9 +4687,8 @@ def project_conversation_processing_items( stage_label_key = None invalidated_from_stage = None excel_ready = False - if getattr(order_task, 'shipping_notice_id', None): - nid = int(order_task.shipping_notice_id) - notice_min = db.session.get(ShippingNotice, nid) + notice_min = _latest_notice_for_order_task(order_task) + if notice_min is not None: if notice_min is not None: from app.services.shipping_notice.order_review_workbench_projection import ( project_stage_for_task, @@ -4111,10 +4716,7 @@ def project_conversation_processing_items( stage_label_key = 'waiting_system_start' 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 - and notice_no_min is not None - ) + has_formal_ot_min = bool(notice_no_min is not None) payload_min = reconcile_processing_projection_facts( { 'work_item_type': 'order_task', @@ -4222,6 +4824,10 @@ def project_conversation_processing_items( work_items, focused_task_no=focused_override, recent_task_no=recent_override, + submitted_files=_conversation_submitted_file_count( + user_id=int(user_id), + conversation_id=normalized, + ), ) # 写路径元数据:保留提交决策与追加计数,供前端卡片提示。 if recent_decision is not None: @@ -4317,4 +4923,4 @@ def get_shipping_processing_work_item( projected = _project_order_task_work_item(run, order_task=order_task) if projected is None: raise NotFoundError('Order task work item not found') - return projected + return _with_processing_ui_state(projected) diff --git a/backend/app/services/shipping_notice/standard_field_registry.py b/backend/app/services/shipping_notice/standard_field_registry.py index cc0abaed..f6359f64 100644 --- a/backend/app/services/shipping_notice/standard_field_registry.py +++ b/backend/app/services/shipping_notice/standard_field_registry.py @@ -94,7 +94,8 @@ def _spec( ) -# [STEP 1] 锁定的 58 项标准目录。Reservation 可同时位于订单头和订单行, +# [STEP 1] 锁定的 58 项标准目录。line_no 是系统生成且只读的订单项次, +# 不参与 Schema 派生规则配置;Reservation 可同时位于订单头和订单行, # 由行级值覆盖订单头值;所有标准字段均可按 Schema 配置抽取规则。 _STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = ( _spec('customer_po_number', 'header', 'string', '客户 PO 号', '客户下达的采购订单标识;不得填写内部 ERP 单号'), @@ -121,12 +122,8 @@ _STANDARD_FIELD_SPECS: tuple[StandardFieldSpec, ...] = ( _spec('urgent_order', 'header', 'boolean', '是否紧急', '是否紧急订单'), _spec('order_remark', 'header', 'string', '订单备注', '订单头备注'), _spec('reservation_id', 'header', 'string', '预约单号', '可选的订单级库存占用/预约单标识;明细可覆盖'), - _spec( - 'line_no', 'line', 'string', '内部项次', - '内部业务项次;可识别、可由 Schema 派生规则补齐、冻结前可人工覆盖;' - '仅接受 1–6 位数字并保留前导零;与 Excel 导出行序号 export_sequence 无关', - ), _spec('reservation_id', 'line', 'string', '预约单号', '可选的行级库存占用/预约单标识;优先于订单头', fulfillment_role='reservation_identity'), + _spec('line_no', 'line', 'integer', '内部项次', '订单明细的系统项次;按订单从 1 开始生成,创建后不可编辑或覆盖'), _spec('part_number', 'line', 'string', '内部料号', '公司内部主料号,用于库存匹配', fulfillment_role='part_number'), _spec('product_revision', 'line', 'string', '产品版本', '产品料号版本/revision'), _spec('customer_part_number', 'line', 'string', '客户料号', '客户侧物料编码'), diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index 8b4f550e..ea85d0dc 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -1,18 +1,16 @@ """ services/shipping_notice/state_machine.py -用途:发货通知检查点(checkpoint)与内部流程状态映射,负责任务 DB 字段与流程事实映射。 -依赖:models.ShippingNotice、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。 -逻辑:tools/workspace 经 apply_task_transition 写库;ui_state/query_service 读取 checkpoint_kind; - resolve_task_ui_state_from_fields 供待办轻量索引批量分类;履约写操作入口为任务处理工作台, - Chat 仅通知与跳转(Chat Turn 写路径已标记废弃)。 - -扩展说明(开发者): -- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt` -- checkpoint_kind 区分 auto_continue / must_human / wait_manual_upload / complete - (导出 CP_EXPORT_* → wait_manual_upload:Excel 后待人工上传登记) -- 用户动作的定义、授权与审计统一由 process_gate_contract / Gate Attempt 负责; - checkpoint 不得派生、下发或执行用户按钮。 +用途:发货通知任务 DB 字段迁移(TaskTransition)与位置/用户模式解析(Gate + review 回退)。 +依赖:models.ShippingNotice/ShippingOrderTask、constants(RS_*/PH_*)、 + process_gate_contract.derive_*(Gate-first)。 +逻辑:tools/workspace 经 apply_task_transition 写库;resolve_task_ui_state 仅: + (1) 有活动 Execution 时用 Gate derive_position / derive_user_mode; + (2) 否则仅凭 review_status 做薄回退。 + 禁止领域标量/OT stage 级联裁决;无 checkpoint API 别名;非独立 CP 状态机。 + POSITION_USER_MODE 仅为可选位置→UserMode 查找表,不是状态机。 + build_task_ui_state 可传入已查 Gate 摘要,经 _ui_state_from_process_gate 派生,避免二次查库。 + 履约写操作入口为任务处理工作台;Chat 仅通知与跳转。 """ from __future__ import annotations @@ -21,27 +19,8 @@ from dataclasses import dataclass from enum import StrEnum from typing import Any -from app import db -from app.models import ShippingOrderExtraction, ShippingOrderLine, ShippingNotice +from app.models import ShippingNotice, ShippingOrderTask from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_EXPORT_GENERATED, - CP_INVENTORY_PENDING, - CP_INVENTORY_SOURCE_REVIEW, - CP_ORDER_FREEZE, - CP_CUSTOMER_REVIEW, - CP_PARSE_REVIEW, - CP_NOTICE_TEXT_EXTRACTION_FAILED, - CP_READY_EXPORT, - CP_READY_MATCH, - CP_REJECTED, - CP_RSV_REQ, - CP_UPLOADED, - CP_COMPLETED, - CP_UPLOAD_FAILED, - CP_UPLOAD_RESULT_UNKNOWN, - CP_UPLOAD_REQ, - CP_WAITING_UPLOAD, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, @@ -52,36 +31,31 @@ from app.services.shipping_notice.constants import ( PH_SHORTAGE, PH_UPLOAD_RPA_FAILED, PH_UPLOAD_RPA_PENDING, - PH_UPLOAD_RESULT_UNKNOWN, - RS_CONFIRMED, RS_PARSE_REVIEW, RS_REJECTED, RS_RSV_REQ, RS_SHORTAGE_REVIEW, + RS_CONFIRMED, ) -def _task_has_dynamic_order_lines(task: ShippingNotice) -> bool: - """判断当前已接受 Extraction 是否有订单行,用于在冻结前显示唯一的冻结入口。""" - extraction_id = task.current_order_extraction_id - if not extraction_id: - return False - extraction = db.session.get(ShippingOrderExtraction, extraction_id) - if extraction is None or extraction.status != "accepted": - return False - return ShippingOrderLine.query.filter_by(extraction_id=extraction.id).first() is not None +def _workflow_owner(task: ShippingNotice): + """Notice 查询流程状态时统一回到其 OT;Notice 不再作为流程状态事实源。""" + from app import db + + if isinstance(task, ShippingOrderTask): + return task + order_task_id = getattr(task, 'order_task_id', None) + return db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else task # --------------------------------------------------------------------------- -# Checkpoint kind(STP 检查点分类;不写入 DB,由注册表静态映射) +# 用户模式枚举(与 derive_user_mode 值域对齐;不是 CheckPoint 状态机) # --------------------------------------------------------------------------- -class CheckpointKind(StrEnum): - """STP 检查点分类:自动可继续 / 必须人工 / 待人工上传登记 / 完成。 - - CP_EXPORT_READY/GENERATED 映射为 WAIT_MANUAL_UPLOAD(Excel 后须登记凭据,非终态)。 - """ +class UserMode(StrEnum): + """用户处置粗分类:auto_continue / must_human / wait_manual_upload / complete。""" AUTO_CONTINUE = "auto_continue" MUST_HUMAN = "must_human" @@ -89,188 +63,179 @@ class CheckpointKind(StrEnum): COMPLETE = "complete" -# checkpoint id → STP kind(静态;无 checkpoint 时视为 auto_continue) -CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = { - CP_PARSE_REVIEW: CheckpointKind.MUST_HUMAN, - CP_CUSTOMER_REVIEW: CheckpointKind.MUST_HUMAN, - CP_UPLOAD_REQ: CheckpointKind.MUST_HUMAN, - CP_INVENTORY_PENDING: CheckpointKind.AUTO_CONTINUE, - # 库存源由规则自动裁决;未稳定只表示内部重算/治理等待,不能形成用户确认停点。 - CP_INVENTORY_SOURCE_REVIEW: CheckpointKind.AUTO_CONTINUE, - CP_ORDER_FREEZE: CheckpointKind.AUTO_CONTINUE, - CP_RSV_REQ: CheckpointKind.MUST_HUMAN, - RS_SHORTAGE_REVIEW: CheckpointKind.MUST_HUMAN, - CP_NOTICE_TEXT_EXTRACTION_FAILED: CheckpointKind.MUST_HUMAN, - CP_UPLOAD_FAILED: CheckpointKind.MUST_HUMAN, - CP_WAITING_UPLOAD: CheckpointKind.WAIT_MANUAL_UPLOAD, - CP_UPLOAD_RESULT_UNKNOWN: CheckpointKind.WAIT_MANUAL_UPLOAD, - CP_READY_MATCH: CheckpointKind.AUTO_CONTINUE, - CP_READY_EXPORT: CheckpointKind.AUTO_CONTINUE, - CP_EXPORT_READY: CheckpointKind.WAIT_MANUAL_UPLOAD, - CP_EXPORT_GENERATED: CheckpointKind.WAIT_MANUAL_UPLOAD, - CP_REJECTED: CheckpointKind.COMPLETE, - CP_UPLOADED: CheckpointKind.COMPLETE, - CP_COMPLETED: CheckpointKind.COMPLETE, +# 位置标签 → 用户模式(无 Gate 时的可选查找;键为 derive_position 字面量,非状态机) +POSITION_USER_MODE: dict[str, UserMode] = { + 'parse_review': UserMode.MUST_HUMAN, + 'customer_review': UserMode.MUST_HUMAN, + 'upload_req': UserMode.MUST_HUMAN, + 'inventory_pending': UserMode.AUTO_CONTINUE, + 'inventory_source_review': UserMode.AUTO_CONTINUE, + 'order_freeze': UserMode.AUTO_CONTINUE, + 'rsv_req': UserMode.MUST_HUMAN, + 'shortage_review': UserMode.MUST_HUMAN, + 'notice_text_extraction_failed': UserMode.MUST_HUMAN, + 'quality_issue': UserMode.MUST_HUMAN, + 'upload_failed': UserMode.MUST_HUMAN, + 'waiting_upload': UserMode.WAIT_MANUAL_UPLOAD, + 'upload_result_unknown': UserMode.WAIT_MANUAL_UPLOAD, + 'ready_to_match': UserMode.AUTO_CONTINUE, + 'ready_to_export': UserMode.AUTO_CONTINUE, + 'export_ready': UserMode.WAIT_MANUAL_UPLOAD, + 'export_generated': UserMode.WAIT_MANUAL_UPLOAD, + 'rejected': UserMode.COMPLETE, + 'uploaded': UserMode.COMPLETE, + 'completed': UserMode.COMPLETE, } -ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_KIND_REGISTRY.keys()) - @dataclass(frozen=True) class TaskUiState: - """统一任务流程状态:checkpoint + STP kind,不包含用户动作。""" + """位置标签 + 用户模式派生视图(非独立状态机事实)。""" - checkpoint: str | None - checkpoint_kind: CheckpointKind = CheckpointKind.AUTO_CONTINUE + position: str | None + user_mode: UserMode = UserMode.AUTO_CONTINUE -def checkpoint_kind_for(checkpoint: str | None) -> CheckpointKind: +def user_mode_for_position(position: str | None) -> UserMode: """ - 按 checkpoint id 解析 STP 检查点分类。 + 按位置标签解析用户模式(查找表,非状态机)。 - 核心逻辑:查 CHECKPOINT_KIND_REGISTRY;无 checkpoint(系统推进中)视为 auto_continue。 + 核心逻辑:查 POSITION_USER_MODE;无位置视为 auto_continue;未知位置默认 must_human。 + + Args: + position: derive_position / 位置字符串;可为 None。 + + Returns: + UserMode 枚举值。 """ - if not checkpoint: - return CheckpointKind.AUTO_CONTINUE - return CHECKPOINT_KIND_REGISTRY.get(str(checkpoint).strip(), CheckpointKind.MUST_HUMAN) + if not position: + return UserMode.AUTO_CONTINUE + return POSITION_USER_MODE.get(str(position).strip(), UserMode.MUST_HUMAN) -def _task_ui_state(checkpoint: str | None) -> TaskUiState: - """构造只含内部流程事实的 TaskUiState。""" +def _task_ui_state(position: str | None) -> TaskUiState: + """构造位置 + 用户模式派生视图。""" return TaskUiState( - checkpoint=checkpoint, - checkpoint_kind=checkpoint_kind_for(checkpoint), + position=position, + user_mode=user_mode_for_position(position), ) -def resolve_task_ui_state_from_fields( - *, - review_status: str | None, - pending_human_reason: str | None, - customer_resolution_status: str | None, - order_snapshot_id: int | None, - inventory_lines_json: Any, - match_status: str | None, - export_file_path: str | None, - has_dynamic_order_lines: bool, - upload_req_options: list[str] | None = None, - upload_req_task: ShippingNotice | None = None, -) -> TaskUiState: +def _ui_state_from_process_gate( + task: ShippingNotice, + gate: dict[str, Any] | None, +) -> TaskUiState | None: """ - 由任务标量字段映射 checkpoint / checkpoint_kind(无 ORM、无额外查询)。 + 由已查得的 Gate 用户摘要派生 position/user_mode。 - 核心逻辑:与 resolve_task_ui_state 同序分支;has_dynamic_order_lines 由调用方批量预计算, - 供待办索引在不全量水合 Task 时保持与单任务路径一致的分类口径。 - upload_req_options / upload_req_task 是已废弃的兼容入参;checkpoint 不再解析用户动作。 + 核心逻辑:与 ``_gate_task_ui_state`` 同源;``build_task_ui_state`` 复用同一次 + Gate 查询结果,禁止再调 ``resolve_task_ui_state`` 二次查 Execution。 + + Args: + task: ShippingNotice 或 ShippingOrderTask(取 review_status)。 + gate: ``_process_gate_user_summary_for_task`` 返回值;无 Gate 时为 None。 + + Returns: + 可派生时返回 TaskUiState;否则 None(调用方走 review_status 薄回退)。 """ + from app.services.shipping_notice.process_gate_contract import derive_position, derive_user_mode - del upload_req_options + if not isinstance(gate, dict) or not gate.get('current_gate_code'): + return None + gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {} + if not isinstance(gate_view, dict): + gate_view = {} + status = str(gate_view.get('status') or '').strip().lower() + summary_status = str(gate.get('status') or '').strip().lower() + if summary_status in {'completed', 'done'}: + user_status = 'completed' + elif status in {'blocked_manual', 'blocked_retryable'} or summary_status == 'blocked': + user_status = 'waiting_human' + elif status == 'failed_terminal' or summary_status == 'failed': + user_status = 'failed' + else: + user_status = 'running' + gate_code = gate.get('current_gate_code') or gate_view.get('gate_code') + mode = derive_user_mode( + user_status=user_status, + gate_code=gate_code, + review_status=getattr(task, 'review_status', None), + lifecycle_stage=gate.get('lifecycle_stage'), + ) + pos = derive_position( + gate_code=gate_code, + review_status=getattr(task, 'review_status', None), + ) + try: + user_mode = UserMode(str(mode)) + except ValueError: + user_mode = user_mode_for_position(pos) + return TaskUiState(position=pos, user_mode=user_mode) - upload_status = str(getattr(upload_req_task, "upload_status", None) if upload_req_task is not None else "").strip().lower() - has_export = bool(str(export_file_path or "").strip()) - # [STEP 1] 终态:上传结果事实或生命周期处置 — 无履约写按钮。 - if upload_status in {"uploaded", "succeeded", "success"}: - return _task_ui_state(CP_UPLOADED) - if upload_req_task is not None and str(getattr(upload_req_task, "lifecycle_status", "") or "").strip().lower() in {"archived", "deleted"}: - return _task_ui_state(CP_COMPLETED) +def _review_status_fallback_ui_state(task: ShippingNotice) -> TaskUiState: + """ + 无活动 Gate 时仅凭 review_status 薄回退派生 position/user_mode。 - if review_status == "rejected": - return _task_ui_state(CP_REJECTED) + 核心逻辑:与 ``resolve_task_ui_state`` 无 Gate 分支同源。 + """ + from app.services.shipping_notice.process_gate_contract import derive_position, derive_user_mode - # [STEP 2] 先完成订单解析复核,再暴露客户确认节点。 - reason = pending_human_reason - if reason == PH_RSV_REQ or review_status == RS_RSV_REQ: - return _task_ui_state(CP_RSV_REQ) - if reason == PH_LOW_CONF or review_status == RS_PARSE_REVIEW: - return _task_ui_state(CP_PARSE_REVIEW) - if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED: - return _task_ui_state(CP_NOTICE_TEXT_EXTRACTION_FAILED) + owner = _workflow_owner(task) + review_status = getattr(owner, 'review_status', None) + pos = derive_position(gate_code=None, review_status=review_status) + mode = derive_user_mode( + user_status=None, + gate_code=None, + review_status=review_status, + lifecycle_stage=None, + ) + try: + user_mode = UserMode(str(mode)) + except ValueError: + user_mode = user_mode_for_position(pos) + return TaskUiState(position=pos, user_mode=user_mode) - if str(customer_resolution_status or "").strip().lower() in {"pending", "needs_review", "failed", "unresolved"}: - return _task_ui_state(CP_CUSTOMER_REVIEW) - # [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。 - if not order_snapshot_id and has_dynamic_order_lines: - return _task_ui_state(CP_ORDER_FREEZE) +def _gate_task_ui_state(task: ShippingNotice) -> TaskUiState | None: + """ + 有活动 Execution 时用 Gate derive_*;否则 None(调用方走 review_status 薄回退)。 - # Excel 已生成即进入通知完成前的人工上传登记节点,即使历史任务未落 match_status, - # 也不能退回“处理中”或丢失下载/登记动作。 - if has_export: - return _task_ui_state(CP_EXPORT_READY) + 懒导入 ui_state,避免与 resolve 循环依赖。 + """ + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task - # [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。 - if reason == PH_RPA_EXHAUSTED: - return _task_ui_state(CP_UPLOAD_REQ) - - if ( - inventory_lines_json - and not review_status - and not pending_human_reason - and not match_status - ): - return _task_ui_state(CP_READY_MATCH) - - if ( - not inventory_lines_json - and not review_status - and not pending_human_reason - and has_dynamic_order_lines - ): - return _task_ui_state(CP_INVENTORY_PENDING) - - # [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。 - if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}: - if has_export: - return _task_ui_state(CP_EXPORT_READY) - return _task_ui_state(CP_READY_EXPORT) - - # [STEP 6] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。 - if reason == PH_INV_UNAVAIL: - return _task_ui_state(CP_UPLOAD_REQ) - if reason == PH_INVENTORY_SOURCE_UNRESOLVED: - return _task_ui_state(CP_INVENTORY_SOURCE_REVIEW) - if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW: - return _task_ui_state(RS_SHORTAGE_REVIEW) - if reason == PH_UPLOAD_RPA_FAILED or upload_status == "failed": - return _task_ui_state(CP_UPLOAD_FAILED) - if reason == PH_UPLOAD_RESULT_UNKNOWN: - return _task_ui_state(CP_UPLOAD_RESULT_UNKNOWN) - if reason == PH_RPA_PENDING: - return _task_ui_state(CP_UPLOAD_REQ) - if reason == PH_UPLOAD_RPA_PENDING or upload_status in {"pending", "uploading"}: - return _task_ui_state(CP_WAITING_UPLOAD) - return _task_ui_state(None) + return _ui_state_from_process_gate(task, _process_gate_user_summary_for_task(task)) def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState: """ - 将 ShippingNotice DB 字段映射为 checkpoint + checkpoint_kind。 + 解析位置 + 用户模式:优先 Gate derive_*,否则仅凭 review_status 薄回退。 - 核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库; - 履约写操作由 Gate 投影生成 ui_state.actions;Chat 不再作为写入口。 + 核心逻辑:无活动 Execution 时调用 derive_position(gate_code=None) / + derive_user_mode(仅 review_status);禁止 match_status / export_file_path / + pending_human / OT stage 级联充当状态机。 + + Args: + task: ShippingNotice 或 ShippingOrderTask。 + + Returns: + TaskUiState(position + user_mode)。 """ - return resolve_task_ui_state_from_fields( - review_status=task.review_status, - pending_human_reason=task.pending_human_reason, - customer_resolution_status=task.customer_resolution_status, - order_snapshot_id=task.order_snapshot_id, - inventory_lines_json=task.inventory_lines_json, - match_status=task.match_status, - export_file_path=task.export_file_path, - has_dynamic_order_lines=_task_has_dynamic_order_lines(task), - upload_req_task=task, - ) + gated = _gate_task_ui_state(task) + if gated is not None: + return gated + return _review_status_fallback_ui_state(task) -def checkpoint_for_task(task: ShippingNotice) -> str | None: - """从 ShippingNotice DB 字段解析当前 checkpoint id。""" - return resolve_task_ui_state(task).checkpoint +def position_for_task(task: ShippingNotice) -> str | None: + """返回当前派生位置标签。""" + return resolve_task_ui_state(task).position def validate_registry() -> list[str]: - """校验每个内部 checkpoint 都有确定的流程分类;测试用。""" - return [] if ALL_CHECKPOINT_IDS == frozenset(CHECKPOINT_KIND_REGISTRY) else ["checkpoint registry mismatch"] + """校验位置→用户模式查找表非空;测试用。""" + return [] if POSITION_USER_MODE else ["POSITION_USER_MODE is empty"] # --------------------------------------------------------------------------- @@ -406,12 +371,15 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N transition: TaskTransition 枚举值。 """ spec = TASK_TRANSITIONS[transition] - if spec.review_status is not _UNSET: - task.review_status = spec.review_status - if spec.pending_human_reason is not _UNSET: - task.pending_human_reason = spec.pending_human_reason - if spec.clear_error_message: - task.error_message = None + owner = _workflow_owner(task) + # 流程状态事实只写入 OT。正式 Notice 仅作为履约实体关联入口, + # 不再动态挂载 review/pending/error 等已删除的历史工作流字段。 + if isinstance(owner, ShippingOrderTask) and spec.review_status is not _UNSET: + owner.review_status = spec.review_status + if isinstance(owner, ShippingOrderTask) and spec.pending_human_reason is not _UNSET: + owner.pending_human_reason = spec.pending_human_reason + if isinstance(owner, ShippingOrderTask) and spec.clear_error_message: + owner.error_message = None # [STEP] 履约态变更后回写 OT stage,避免进度条卡在 order_creating。 try: diff --git a/backend/app/services/shipping_notice/stp_line_inventory_match.py b/backend/app/services/shipping_notice/stp_line_inventory_match.py index 93dab86e..3132401d 100644 --- a/backend/app/services/shipping_notice/stp_line_inventory_match.py +++ b/backend/app/services/shipping_notice/stp_line_inventory_match.py @@ -4,9 +4,10 @@ services/shipping_notice/stp_line_inventory_match.py 用途:STP 阶段 4 跨冻结候选库存源按有效 Reservation + Part Number 匹配并落实行级裁决。 依赖:stp_inventory_freeze、reservation_id、inventory_snapshot_store、inventory_source_repository、 inventory_source_rules、ShippingOrderSnapshot。 -逻辑:ensure_inventory 合并候选快照行;match 仅在冻结候选集内检索;多文件命中为冲突; - 唯一命中且数量充足则冻结 resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记); - 人工指定源后 forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。 +逻辑:ensure_inventory 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制 + __source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结 + resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后 + forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。 """ from __future__ import annotations @@ -272,23 +273,25 @@ def match_order_lines_across_candidates( """ 跨候选库存行按有效 Reservation + Part Number + Unit 匹配。 + 核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定, + 库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。 + Args: order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。 - inventory_lines: 已打 ``__source_code`` 的库存行。 + inventory_lines: 库存行;``__source_code`` 可选(多源合并时用于冲突裁决)。 header_reservation_id: 头级 Reservation,用于行级回退。 Returns: match_status、line_results、shortage_json、resolutions。 """ # [STEP 1] 按 (reservation, part, unit, source) 聚合可用量与样例行。 + # 无 __source_code 时 source='':表示“当前已载入 Excel 内的行”,不得因缺标签跳过。 buckets: dict[tuple[str, str, str, str], dict[str, Any]] = {} for row in inventory_lines: key = _inventory_row_key(row) if key is None: continue source = str(row.get('__source_code') or '').strip().upper() - if not source: - continue bucket_key = (key[0], key[1], key[2], source) bucket = buckets.get(bucket_key) if bucket is None: @@ -336,10 +339,11 @@ def match_order_lines_across_candidates( ] if effective and part else [] # 正式匹配必须存在结构化 CandidateLine,并严格限制在该行允许源内。 # 缺少行级范围本身就是候选事实缺失,不能退化为任务级并集匹配。 + # 无源标签的库存行视为“当前 Excel 已选源”,不因候选源列表再剔除。 source_hits = [ item for item in all_source_hits if ( - item['source_code'] in allowed_source_codes + (not item['source_code'] or item['source_code'] in allowed_source_codes) if has_candidate_scope else True ) @@ -412,6 +416,10 @@ def match_order_lines_across_candidates( else: hit = source_hits[0] available = hit['available_qty'] + # 库存行无源标签时,回退到该行唯一候选源(选源阶段已确定)。 + resolved_source = hit['source_code'] or ( + allowed_source_codes[0] if len(allowed_source_codes) == 1 else '' + ) if available >= required and required > 0: disposition = 'ok' sample = hit['sample_row'] @@ -425,13 +433,13 @@ def match_order_lines_across_candidates( 'shortage_qty': 0.0, 'line_status': 'ok', 'disposition': disposition, - 'resolved_inventory_source_code': hit['source_code'], + 'resolved_inventory_source_code': resolved_source, 'inventory_file_no': sample.get('__inventory_file_no'), 'inventory_row_ref': { 'reservation_id': effective, 'part_number': part, 'unit': unit or None, - 'source_code': hit['source_code'], + 'source_code': resolved_source, }, } has_ok = True @@ -447,7 +455,7 @@ def match_order_lines_across_candidates( 'shortage_qty': float(max(required - available, Decimal('0'))), 'line_status': 'partial' if available > 0 else 'shortage', 'disposition': disposition, - 'resolved_inventory_source_code': hit['source_code'], + 'resolved_inventory_source_code': resolved_source, } has_block = True has_partial = available > 0 diff --git a/backend/app/services/shipping_notice/stp_progress_contract.py b/backend/app/services/shipping_notice/stp_progress_contract.py index 106192fc..669c5204 100644 --- a/backend/app/services/shipping_notice/stp_progress_contract.py +++ b/backend/app/services/shipping_notice/stp_progress_contract.py @@ -87,17 +87,53 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]: Returns: [{code, label, status}, ...];顺序与 STP_PROGRESS_NODE_DEFS 一致。 """ - customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower() - pending = str(getattr(task, 'pending_human_reason', '') or '').strip().lower() - match_status = str(getattr(task, 'match_status', '') or '').strip().lower() + from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + # 客户确认 / 人工阻断:迁移后 Task 直传事实字段为权威来源;缺失时回退 DB 投影。 + customer_status = str( + getattr(task, 'customer_resolution_status', None) + or customer_confirmation_facts(task)['status'] + or '' + ).strip().lower() + pending = str( + getattr(task, 'pending_human_reason', None) + or task_blocking_reason(task) + or '' + ).strip().lower() + direct_match_status = getattr(task, 'match_status', None) + if direct_match_status is None and task.__class__.__name__ == 'ShippingOrderTask': + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + match_facts = list(load_current_match_facts_by_task(getattr(task, 'id', None)).values()) + match_status = 'matched' if match_facts and all( + str(row.get('match_result') or '').strip().lower() == 'matched' + and str(row.get('shortage_qty') or '').strip() in {'', '0', '0.0', '0.00'} + for row in match_facts + ) else ('shortage' if match_facts else '') + elif direct_match_status is None: + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match_status = str(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) or '').strip().lower() + else: + match_status = str(direct_match_status or '').strip().lower() review_status = str(getattr(task, 'review_status', '') or '').strip().lower() - has_export = bool(str(getattr(task, 'export_file_name', '') or '').strip()) - upload_status = str(getattr(task, 'upload_status', '') or '').strip().lower() + from app.services.shipping_notice.upload_attempt_service import ( + latest_export_artifact, + project_notice_upload_status, + ) + direct_export_file = getattr(task, 'export_file_name', None) + if direct_export_file: + has_export = True + else: + artifact = latest_export_artifact(task) + has_export = bool(str(getattr(artifact, 'file_name', '') or '').strip()) + projected_upload = project_notice_upload_status(task) + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task progress_state = ( - 'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} else - 'upload_failed' if upload_status == 'failed' else + 'uploaded' if projected_upload == 'uploaded' else + 'upload_failed' if projected_upload == 'failed' else 'matched' if match_status or has_export else - 'inventory_ready' if getattr(task, 'inventory_lines_json', None) else + 'inventory_ready' if has_ready_inventory_file_for_task(task) else 'pending_review' if pending or review_status else 'created' ) diff --git a/backend/app/services/shipping_notice/task_field_gate.py b/backend/app/services/shipping_notice/task_field_gate.py index b98fb1d5..7e14be0b 100644 --- a/backend/app/services/shipping_notice/task_field_gate.py +++ b/backend/app/services/shipping_notice/task_field_gate.py @@ -74,7 +74,7 @@ def field_conflict_gate_response( 'issues': open_field_conflict_issues(task), }, }, - checkpoint='parse_review', + position='parse_review', stop_agent_turn=True, forbidden_next_tools=blocked, ) diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index ee03cbaf..b4a2f40e 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -21,7 +21,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ValidationError from app.models import ShippingNotice, ShippingOrderTask, ShippingOrderIntake -from app.services.shipping_notice.constants import CP_TASK_EXISTS +from app.services.shipping_notice.constants import POSITION_TASK_EXISTS from app.services.shipping_notice.task_order_field_editor import ( current_header_field_values, retire_current_order_extraction, @@ -129,7 +129,7 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: task_id=existing_by_no.task_no, message=f"已找到发货任务 {existing_by_no.task_no},将继续处理该任务。", data=qs_serialize_task(existing_by_no, TaskProjection.TOOL_INTERNAL), - checkpoint=CP_TASK_EXISTS, + position=POSITION_TASK_EXISTS, ) if conv_id: existing = ( @@ -146,7 +146,7 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。" ), data=qs_serialize_task(existing, TaskProjection.TOOL_INTERNAL), - checkpoint=CP_TASK_EXISTS, + position=POSITION_TASK_EXISTS, ) # [STEP] 接收解析阶段只创建 OT;客户确认由订单复核/客户门禁处理,不能阻止 OT 落库。 diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index 50c33f37..b7b8b700 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -2,7 +2,7 @@ services/shipping_notice/tool_response.py 用途:统一构建发货通知 Tool 的 JSON 响应结构。 -依赖:state_machine 中的 checkpoint 解析能力;ShippingProcessExecution。 +依赖:state_machine.resolve_task_ui_state(位置派生);ShippingProcessExecution。 逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应; 已绑定 ProcessExecution 的任务不再下发旧动作字段(恢复仅由 Gate 驱动)。 """ @@ -83,7 +83,7 @@ def tool_response( data: dict[str, Any] | None = None, human_options: list[str] | None = None, action_buttons: list[dict[str, str]] | None = None, - checkpoint: str | None = None, + position: str | None = None, next_required_action: str | None = None, forbidden_next_tools: list[str] | None = None, stop_agent_turn: bool = False, @@ -92,11 +92,12 @@ def tool_response( """ 构建发货通知 Tool 标准 JSON 响应。 - 核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint; - 显式 checkpoint 优先(如 parse_ok、task_exists)。 - 若任务已有 ProcessExecution:不再填充旧动作字段,避免与 Gate 双真相。 + 核心逻辑:未显式传 position 时从 task 派生位置;显式 position 优先 + (如 parse_ok、task_exists)。若任务已有 ProcessExecution:不再填充旧动作字段, + 避免与 Gate 双真相。 Args: + position: 进程位置标签;None 时从 resolve_task_ui_state(task).position 推导。 stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。 forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。 extra: 需要保留在顶层的额外业务字段。 @@ -109,12 +110,12 @@ def tool_response( gate_owns_recovery = _task_has_process_execution(task) # action_buttons 是历史调用参数,仅为兼容调用方签名;绝不进入对外响应。 del action_buttons - resolved_checkpoint = checkpoint + resolved_position = position # 旧 human_options 参数仅保留调用签名兼容,绝不返回。用户动作必须由 Gate DTO 授权。 del human_options - if checkpoint is None and task is not None: + if position is None and task is not None: ui = resolve_task_ui_state(task) - resolved_checkpoint = ui.checkpoint + resolved_position = ui.position payload: dict[str, Any] = { "status": status, @@ -124,8 +125,8 @@ def tool_response( if task_id: payload["task_id"] = task_id # [STEP] 业务按钮统一由 ui_state.actions 返回;Tool 响应不再生成旧 human_options/action_buttons。 - if resolved_checkpoint: - payload["checkpoint"] = resolved_checkpoint + if resolved_position: + payload["position"] = resolved_position if next_required_action and not gate_owns_recovery: payload["next_required_action"] = _sanitize_user_facing_text(next_required_action) if forbidden_next_tools: diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index be7c979b..ad62d4ee 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -2,14 +2,19 @@ services/shipping_notice/ui_state.py 用途:发货通知任务 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(当前待办、暂停原因、下一自动步骤、操作入口、 - stp_facts、progress_nodes); - 若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影; - Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办); +依赖:models.ShippingNotice/ShippingOrderTask/ShippingProcessExecution、state_machine(UserMode/位置回退)、 + query_service、constants.POSITION_*、process_gate_contract.derive_*、process_gate_projection、 + line_inventory_match_projection、inventory_candidate_projection、 + order_review_fulfillment_decision_service(短缺放行模板字段)、 + order_review_workbench_projection、inventory_source_repository(preparation.source_options)。 +逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode); + Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id); + stage_context.preparation 以 Snapshot 行 + 当前 Match 投影(Notice 经 order_task_id→OT), + 行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源); + 短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line; + 下发 source_options 供行级 override;用户动作统一由 Gate 授权; + build_task_ui_state 同请求内复用一次 Gate 摘要(禁止 resolve 再查一遍); + project_notice_available_actions 供货代上传聚合行内菜单轻量消费。 """ from __future__ import annotations @@ -18,24 +23,24 @@ from typing import Any from app.models import ShippingNotice from app.services.shipping_notice.constants import ( - CP_COMPLETED, - CP_CUSTOMER_REVIEW, - CP_EXPORT_GENERATED, - CP_EXPORT_READY, - CP_INVENTORY_PENDING, - CP_INVENTORY_SOURCE_REVIEW, - CP_ORDER_FREEZE, - CP_NOTICE_TEXT_EXTRACTION_FAILED, - CP_PARSE_REVIEW, - CP_READY_EXPORT, - CP_READY_MATCH, - CP_REJECTED, - CP_RSV_REQ, - CP_UPLOADED, - CP_UPLOAD_FAILED, - CP_UPLOAD_RESULT_UNKNOWN, - CP_UPLOAD_REQ, - CP_WAITING_UPLOAD, + POSITION_COMPLETED, + POSITION_CUSTOMER_REVIEW, + POSITION_EXPORT_GENERATED, + POSITION_EXPORT_READY, + POSITION_INVENTORY_PENDING, + POSITION_INVENTORY_SOURCE_REVIEW, + POSITION_ORDER_FREEZE, + POSITION_NOTICE_TEXT_EXTRACTION_FAILED, + POSITION_PARSE_REVIEW, + POSITION_READY_EXPORT, + POSITION_READY_MATCH, + POSITION_REJECTED, + POSITION_RSV_REQ, + POSITION_UPLOADED, + POSITION_UPLOAD_FAILED, + POSITION_UPLOAD_RESULT_UNKNOWN, + POSITION_UPLOAD_REQ, + POSITION_WAITING_UPLOAD, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, PH_RPA_EXHAUSTED, @@ -53,10 +58,12 @@ from app.services.shipping_notice.lifecycle_projection import ( ) 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, + UserMode, +) +from app.services.shipping_notice.user_facing_status import ( + user_facing_stage_label_for_position, + user_facing_task_stage, ) -from app.services.shipping_notice.user_facing_status import user_facing_task_stage WORKFLOW_STEPS: tuple[dict[str, str], ...] = ( @@ -67,42 +74,52 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = ( {"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"}, ) -_REVIEW_ENTRY_CHECKPOINTS = { - CP_PARSE_REVIEW, - CP_RSV_REQ, - CP_NOTICE_TEXT_EXTRACTION_FAILED, +_REVIEW_ENTRY_POSITIONS = { + POSITION_PARSE_REVIEW, + POSITION_RSV_REQ, + POSITION_NOTICE_TEXT_EXTRACTION_FAILED, } -_NEXT_AUTO_STEP_BY_CHECKPOINT: dict[str, str] = { - CP_INVENTORY_PENDING: "ensure_inventory", - CP_ORDER_FREEZE: "freeze_order", - CP_READY_MATCH: "match_inventory", - CP_READY_EXPORT: "generate_excel", +_NEXT_AUTO_STEP_BY_POSITION: dict[str, str] = { + POSITION_INVENTORY_PENDING: "ensure_inventory", + POSITION_ORDER_FREEZE: "freeze_order", + POSITION_READY_MATCH: "match_inventory", + POSITION_READY_EXPORT: "generate_excel", } -_PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = { - CP_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"), - CP_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"), - CP_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"), - CP_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"), - CP_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源规则正在重新裁决"), - CP_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"), +_PAUSE_REASON_BY_POSITION: dict[str, tuple[str, str]] = { + POSITION_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"), + POSITION_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"), + POSITION_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"), + POSITION_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"), + POSITION_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源规则正在重新裁决"), + POSITION_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"), RS_SHORTAGE_REVIEW: ("shortage", "库存存在缺口"), - CP_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"), - 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 已生成,请下载后在货代平台上传,并在本系统确认已上传"), + POSITION_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"), + POSITION_UPLOAD_FAILED: ("upload_failed", "货代上传失败"), + POSITION_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"), + POSITION_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"), + POSITION_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), + POSITION_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), } def _task_lifecycle( - *, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None, + *, task: ShippingNotice, position: str | None, process_gate: dict[str, Any] | None, ) -> dict[str, Any]: """以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。""" + del position # 生命周期不再由位置码推导。 gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate') from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + # 有正式 Gate 或已验证上传时才开放五阶段入口;否则保持 unclassified(禁止旧 CP 冒充)。 + has_formal = bool( + isinstance(process_gate, dict) + and ( + process_gate.get('current_gate_code') + or process_gate.get('current_blocking_gate') + or process_gate.get('current_gate') + ) + ) return project_lifecycle( current_gate=gate if isinstance(gate, dict) else None, blocking_reason=( @@ -110,9 +127,9 @@ def _task_lifecycle( if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code') else None ), - # ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。 - has_candidate_context=True, + has_candidate_context=has_formal or has_verified_upload_success(task), verified_upload_success=has_verified_upload_success(task), + processing_stage=getattr(task, 'stage', None), ) @@ -184,7 +201,7 @@ def _unified_actions(*, process_gate: dict[str, Any] | None) -> dict[str, Any]: def build_shipping_workflow_steps( task: ShippingNotice, - checkpoint: str | None, + position: str | None, *, lifecycle_stage: str | None = None, ) -> list[dict[str, str]]: @@ -194,6 +211,7 @@ def build_shipping_workflow_steps( Returns: list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。 """ + del position # 五阶段仅由 lifecycle_stage 驱动 lifecycle_index = next( (index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage), None, @@ -218,12 +236,12 @@ def build_shipping_workflow_steps( return steps -_PARSE_STAGE_CHECKPOINTS = { - CP_PARSE_REVIEW, - CP_RSV_REQ, - CP_INVENTORY_SOURCE_REVIEW, - CP_ORDER_FREEZE, - CP_NOTICE_TEXT_EXTRACTION_FAILED, +_PARSE_STAGE_POSITIONS = { + POSITION_PARSE_REVIEW, + POSITION_RSV_REQ, + POSITION_INVENTORY_SOURCE_REVIEW, + POSITION_ORDER_FREEZE, + POSITION_NOTICE_TEXT_EXTRACTION_FAILED, } _WARNING_DISPLAY_ALIASES: dict[str, str] = { @@ -264,34 +282,34 @@ def _parse_validation_issue_text(issue: dict[str, Any]) -> str: return f"第 {line_no} 行料号 {part_number}:缺少合法的 Reservation ID。" -def _collect_parse_stage_issues(task: ShippingNotice, checkpoint: str | None) -> list[str]: +def _collect_parse_stage_issues(task: ShippingNotice, position: str | None) -> list[str]: """ 汇总文件解析阶段(步骤 2)全部待处理问题,供工作台一次列出。 核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发; 以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。 """ - checkpoint_value = str(checkpoint or "").strip() - if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS: + position_value = str(position or "").strip() + if position_value not in _PARSE_STAGE_POSITIONS: return [] issues: list[str] = [] - if checkpoint_value == CP_INVENTORY_SOURCE_REVIEW: + if position_value == POSITION_INVENTORY_SOURCE_REVIEW: _append_unique_issue( issues, task.error_message or "无法根据发货通知唯一确定库存查询来源", ) - elif checkpoint_value == CP_RSV_REQ: + elif position_value == POSITION_RSV_REQ: _append_unique_issue( issues, task.error_message or "解析失败:未识别到 Reservation ID / COM ID(预定单号)", ) - elif checkpoint_value == CP_NOTICE_TEXT_EXTRACTION_FAILED: + elif position_value == POSITION_NOTICE_TEXT_EXTRACTION_FAILED: _append_unique_issue( issues, task.error_message or "未能从发货通知中解析到可审核内容", ) - elif checkpoint_value == CP_PARSE_REVIEW: + elif position_value == POSITION_PARSE_REVIEW: _append_unique_issue(issues, "通知单解析置信度不足,需要复核单头或明细。") if not is_inventory_source_stable(task): _append_unique_issue( @@ -317,7 +335,57 @@ def _collect_parse_stage_issues(task: ShippingNotice, checkpoint: str | None) -> return issues -def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str: +def _derived_entry_surface( + *, + gate_code: str | None, + review_status: str | None, + user_mode: str, + position: str | None = None, +) -> str: + """ + 由 Gate 位置与用户模式推导操作入口面。 + + Returns: + review_workbench | task_workbench | none + """ + rs = str(review_status or '').strip() + code = str(gate_code or '').strip() + pos = str(position or '').strip() + if pos in {POSITION_EXPORT_READY, POSITION_EXPORT_GENERATED, POSITION_WAITING_UPLOAD} or code in { + 'artifact_generation', + 'manual_upload_handoff', + }: + return 'task_workbench' + if rs in {'parse_review', 'rsv_req', 'customer_review'} or code in { + 'order_field_extraction', + 'customer_resolution', + 'reservation_validation', + }: + return 'review_workbench' + if user_mode == 'complete': + return 'none' + if user_mode in {'must_human', 'wait_manual_upload'}: + return 'task_workbench' + if code in { + 'inventory_preparation', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'inventory_source_routing', + 'order_freeze_readiness', + }: + return 'task_workbench' + return 'none' + + +def _derived_current_todo(*, position: str | None) -> str | None: + """从 Gate position 提取只读待办说明。""" + pause = _PAUSE_REASON_BY_POSITION.get(str(position or '')) + return pause[1] if pause else None + + +def _entry_surface_for(position: str | None, kind: UserMode) -> str: """ 解析当前操作应进入的工作台类型。 @@ -325,28 +393,28 @@ def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str: review_workbench | task_workbench | none """ # Excel 就绪虽为 wait_manual_upload,仍进任务工作台以便下载与登记凭据。 - if str(checkpoint or "") in {CP_EXPORT_READY, CP_EXPORT_GENERATED}: + if str(position or "") in {POSITION_EXPORT_READY, POSITION_EXPORT_GENERATED}: return "task_workbench" - if kind == CheckpointKind.COMPLETE: + if kind == UserMode.COMPLETE: return "none" - if str(checkpoint or "") in _REVIEW_ENTRY_CHECKPOINTS: + if str(position or "") in _REVIEW_ENTRY_POSITIONS: return "review_workbench" - if kind in {CheckpointKind.MUST_HUMAN, CheckpointKind.WAIT_MANUAL_UPLOAD}: + if kind in {UserMode.MUST_HUMAN, UserMode.WAIT_MANUAL_UPLOAD}: return "task_workbench" - if kind == CheckpointKind.AUTO_CONTINUE and checkpoint in { - CP_ORDER_FREEZE, - CP_READY_MATCH, - CP_READY_EXPORT, - CP_INVENTORY_PENDING, + if kind == UserMode.AUTO_CONTINUE and position in { + POSITION_ORDER_FREEZE, + POSITION_READY_MATCH, + POSITION_READY_EXPORT, + POSITION_INVENTORY_PENDING, }: # 自动链可继续,但仍允许工作台手动兜底 return "task_workbench" return "none" -def _current_todo_label(checkpoint: str | None) -> str | None: - """从内部 checkpoint 提取只读待办说明,不派生用户动作。""" - pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or "")) +def _current_todo_label(position: str | None) -> str | None: + """从位置标签提取只读待办说明,不派生用户动作。""" + pause = _PAUSE_REASON_BY_POSITION.get(str(position or "")) return pause[1] if pause else None @@ -354,14 +422,11 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: """ 投影 STP 履约事实供 Chat/工作台/待办同源消费。 - 核心逻辑:只读 task + step_payload;无 STP 痕迹时返回 None,避免普通任务噪声。 - - Args: - task: 发货任务。 - - Returns: - stp_facts 字典或 None。 + 核心逻辑:只读 OT 的 CandidateSet、Preparation/Link/File 与行级 Match; + 无 STP 痕迹时返回 None,避免普通任务噪声。禁止读已下线的 OT 库存投影列。 """ + from app import db + from app.models import ShippingOrderTask from app.services.shipping_notice.inventory_candidate_projection import ( project_inventory_candidate_facts, ) @@ -369,26 +434,26 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - status = str(task.inventory_source_status or '').strip() - method = str(task.inventory_source_method or '').strip() - resolutions_raw = payload.get('line_inventory_resolutions') - resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else [] - multi_block = bool(payload.get('multi_source_excel_block')) - candidate_projection = project_inventory_candidate_facts(task) - frozen_codes = ( - list(candidate_projection.get('candidate_source_codes') or []) - or list( - (payload.get('line_inventory_candidates') or {}).get('source_codes') or [] - ) - or task_frozen_inventory_source_codes(task) + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + + candidate_projection = ( + project_inventory_candidate_facts(owner) + if getattr(owner, 'id', None) is not None else { + 'current_set': None, + 'candidate_source_codes': [], + 'line_resolutions': [], + } ) + status = 'candidates_frozen' if candidate_projection.get('current_set') else '' + method = 'candidate_set' if candidate_projection.get('current_set') else '' + frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(owner) has_stp = ( status in {'candidates_frozen', 'resolved'} or method.startswith('stp') or bool(frozen_codes) - or bool(resolutions) - or multi_block + or bool(candidate_projection.get('blocking_reason')) or bool(candidate_projection.get('current_set')) ) if not has_stp: @@ -396,19 +461,38 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: counts: dict[str, int] = {} compact_resolutions: list[dict[str, Any]] = [] - resolution_source = list(candidate_projection.get('line_resolutions') or []) or resolutions + resolution_source = list(candidate_projection.get('line_resolutions') or []) + if not resolution_source and getattr(owner, 'id', None) is not None: + from app.models import ShippingNoticeLineInventoryMatch + + resolution_source = [{ + 'line_index': row.line_index, + 'line_no': row.line_no, + 'disposition': row.match_result, + 'effective_reservation_id': row.reservation_id, + 'part_number': row.part_number, + 'resolved_inventory_source_code': row.inventory_source_code, + 'inventory_file_no': row.matched_file_no, + 'inventory_row_index': row.matched_row_index, + 'match_attempt_id': row.match_attempt_id, + 'required_qty': row.required_qty, + 'matched_qty': row.matched_qty or row.available_qty, + 'shortage_qty': row.shortage_qty, + 'inventory_row_ref': dict(row.detail_json or {}).get('inventory_row_ref'), + } for row in ShippingNoticeLineInventoryMatch.query.filter_by( + task_id=int(owner.id), is_current=True, + ).order_by(ShippingNoticeLineInventoryMatch.line_no, ShippingNoticeLineInventoryMatch.id).all()] for item in resolution_source: disposition = str(item.get('disposition') or 'unknown') counts[disposition] = counts.get(disposition, 0) + 1 compact_resolutions.append({ 'line_index': item.get('line_index'), - 'line_key': item.get('line_key'), + 'line_no': item.get('line_no'), 'disposition': disposition, 'effective_reservation_id': item.get('effective_reservation_id'), 'part_number': item.get('part_number'), 'resolved_inventory_source_code': item.get('resolved_inventory_source_code'), 'inventory_file_no': item.get('inventory_file_no'), - 'inventory_file_sha256': item.get('inventory_file_sha256'), 'inventory_row_index': item.get('inventory_row_index'), 'match_attempt_id': item.get('match_attempt_id'), 'required_qty': item.get('required_qty'), @@ -417,10 +501,19 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: 'inventory_row_ref': item.get('inventory_row_ref'), }) - recovery_codes = multi_source_recovery_source_codes(task) + recovery_codes = multi_source_recovery_source_codes(owner) + payload = getattr(owner, 'step_payload_json', None) + payload = payload if isinstance(payload, dict) else {} + multi_block = bool(payload.get('multi_source_excel_block')) + if not multi_block: + # 行级 source_conflict 与旧 payload 标志等价,摘要暂停原因须同源。 + multi_block = any( + str(item.get('disposition') or '').strip().lower() == 'source_conflict' + for item in compact_resolutions + ) facts = { 'inventory_source_status': status or None, - 'inventory_source_code': str(task.inventory_source_code or '').strip().upper() or None, + 'inventory_source_code': None, 'inventory_source_method': method or None, 'frozen_candidate_codes': [str(code).strip().upper() for code in frozen_codes if str(code or '').strip()], 'candidate_set_id': candidate_projection.get('candidate_set_id'), @@ -440,53 +533,63 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: if str(code or '').strip() ], 'recovery_source_codes': recovery_codes, - 'match_status': str(task.match_status or '').strip() or None, + # 订单任务的库存匹配状态只由行级 Match 聚合;不得读取 OT match_status 投影。 + 'match_status': None, } return {key: facts[key] for key in STP_FACTS_ALLOWED_KEYS if key in facts} def _build_task_summary( task: ShippingNotice, - checkpoint: str | None, + position: str | None, *, - checkpoint_kind: CheckpointKind, + user_mode: UserMode | str, + gate_code: str | None = None, ) -> dict[str, Any]: """ 输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。 - 核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、 - pause_reason、next_auto_step、event_at、entry_surface、allowed_actions、stp_facts、 - progress_nodes(固定节点顺序,禁止前端算百分比)。 + 核心逻辑:文案与入口由 position/user_mode(Gate 或 review 回退)驱动。 """ - title = user_facing_task_stage(task) - message_by_checkpoint: dict[str, str] = { - CP_PARSE_REVIEW: "解析结果需要人工确认后才能继续。", - CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。", - CP_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。", - CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。", - CP_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。", - CP_INVENTORY_SOURCE_REVIEW: "库存源规则正在重新裁决。", - CP_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。", + effective_position = str(position or '').strip() or None + effective_mode = str(user_mode or '').strip() or str(UserMode.AUTO_CONTINUE) + # [PERF] position 已由 Gate 派生时优先用标签表,避免 user_facing_task_stage 再查 Gate。 + title = ( + user_facing_stage_label_for_position(task, position=effective_position) + or user_facing_task_stage(task) + ) + message_by_position: dict[str, str] = { + POSITION_PARSE_REVIEW: "解析结果需要人工确认后才能继续。", + POSITION_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。", + POSITION_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。", + POSITION_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。", + POSITION_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。", + POSITION_INVENTORY_SOURCE_REVIEW: "库存源规则正在重新裁决。", + POSITION_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。", RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。", - CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。", - CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。", - CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", - CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", - CP_WAITING_UPLOAD: "待人工上传确认:请下载 Excel,在货代平台上传后于本系统确认已上传。", - CP_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。", - CP_REJECTED: "任务已驳回,无需继续处理。", - CP_UPLOADED: "任务已完成上传。", - CP_COMPLETED: "任务已关闭。", + POSITION_READY_MATCH: "库存已就绪,系统将自动执行匹配。", + POSITION_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。", + POSITION_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", + POSITION_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", + POSITION_WAITING_UPLOAD: "待人工上传确认:请下载 Excel,在货代平台上传后于本系统确认已上传。", + POSITION_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。", + POSITION_REJECTED: "任务已驳回,无需继续处理。", + POSITION_UPLOADED: "任务已完成上传。", + POSITION_COMPLETED: "任务已关闭。", } - issues = _collect_parse_stage_issues(task, checkpoint) - pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or "")) - pause_reason_code = pause[0] if pause else (task.pending_human_reason or None) - pause_reason = pause[1] if pause else (task.error_message or task.upload_error_message or None) - message = message_by_checkpoint.get(str(checkpoint or ""), title) + issues = _collect_parse_stage_issues(task, effective_position) + pause = _PAUSE_REASON_BY_POSITION.get(str(effective_position or "")) + pause_reason_code = pause[0] if pause else getattr(task, 'pending_human_reason', None) + pause_reason = pause[1] if pause else ( + getattr(task, 'error_message', None) + or getattr(task, 'upload_error_message', None) + or None + ) + message = message_by_position.get(str(effective_position or ""), title) stp_facts = _build_stp_facts(task) current_todo_override: str | None = None + is_auto = effective_mode in {'auto_continue', str(UserMode.AUTO_CONTINUE)} - # [STEP] STP 多源 Excel 阻断:覆盖通用 shortage 文案,并提示可指定库存源。 if stp_facts and stp_facts.get('multi_source_excel_block'): pause_reason_code = 'multi_source_excel_block' pause_reason = '订单行命中多个不同库存源,首期无法生成单一发货 Excel,请拆单或人工指定库存源后继续' @@ -496,51 +599,95 @@ def _build_task_summary( if issue_text not in issues: issues = [*issues, issue_text] current_todo_override = '请拆单或人工指定库存源后继续' - elif stp_facts and str(stp_facts.get('inventory_source_status') or '') == 'candidates_frozen' and checkpoint_kind == CheckpointKind.AUTO_CONTINUE: + elif ( + stp_facts + and str(stp_facts.get('inventory_source_status') or '') == 'candidates_frozen' + and is_auto + ): message = '多候选库存源已冻结,系统正在准备库存并跨文件匹配。' - if checkpoint_kind == CheckpointKind.AUTO_CONTINUE and not (stp_facts and stp_facts.get('multi_source_excel_block')): + if is_auto and not (stp_facts and stp_facts.get('multi_source_excel_block')): pause_reason = None pause_reason_code = None event_at = None if task.updated_at is not None: event_at = task.updated_at.isoformat() + try: + mode_enum = UserMode(effective_mode) + except ValueError: + mode_enum = UserMode.AUTO_CONTINUE + entry_surface = ( + _derived_entry_surface( + gate_code=gate_code, + review_status=getattr(task, 'review_status', None), + user_mode=effective_mode, + position=effective_position, + ) + if (gate_code or position or user_mode) + else _entry_surface_for(effective_position, mode_enum) + ) + # 多库存源冲突必须进人工作台处理,不能因位置仍是 auto inventory_pending 落到 none。 + if stp_facts and stp_facts.get('multi_source_excel_block'): + entry_surface = 'task_workbench' summary: dict[str, Any] = { "title": title, "message": message, - "error_message": task.error_message or task.upload_error_message, + "error_message": ( + getattr(task, 'error_message', None) + or getattr(task, 'upload_error_message', None) + ), "issues": issues, "stage": title, - "checkpoint_kind": str(checkpoint_kind), + "user_mode": effective_mode, "current_todo": ( current_todo_override if current_todo_override is not None else ( pause_reason if stp_facts and stp_facts.get('multi_source_excel_block') - else _current_todo_label(checkpoint) + else ( + _derived_current_todo(position=effective_position) + if effective_position + else _current_todo_label(effective_position) + ) ) ), "pause_reason": pause_reason, "pause_reason_code": pause_reason_code, "next_auto_step": ( - _NEXT_AUTO_STEP_BY_CHECKPOINT.get(str(checkpoint or "")) - if checkpoint_kind == CheckpointKind.AUTO_CONTINUE + _NEXT_AUTO_STEP_BY_POSITION.get(str(effective_position or "")) + if is_auto else None ), "event_at": event_at, - "entry_surface": _entry_surface_for(checkpoint, checkpoint_kind), + "entry_surface": entry_surface, "allowed_actions": [], } if stp_facts is not None: summary['stp_facts'] = stp_facts - # [STEP] 对话侧固定节点梯;前端只渲染 status,不自行推导百分比。 from app.services.shipping_notice.stp_progress_contract import project_task_progress_nodes summary['progress_nodes'] = project_task_progress_nodes(task) return summary +# 通知准备「任务级可编辑」排除集:作废/归档/删除/待作废/取消视图只读。 +_PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES = frozenset({ + 'voided', 'archived', 'deleted', 'pending_void', 'cancelled', 'canceled', +}) + + +def _preparation_editable(task: ShippingNotice) -> bool: + """ + 判定通知准备工作面是否允许任务级编辑/出单门控放行。 + + 核心逻辑:仅按 lifecycle_status 终态/历史视图排除;active/blocked/空值可操作。 + Gate 阻断不在此谓词收紧。 + """ + status = str(getattr(task, 'lifecycle_status', None) or '').strip().lower() + return status not in _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES + + def _build_stage_context( task: ShippingNotice, *, @@ -550,149 +697,162 @@ def _build_stage_context( ) -> dict[str, Any]: """构造五阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。 - 通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成 - 只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。 + 通知准备以冻结 Snapshot 行为轴,合并当前行级 Match + project_line_inventory_view; + Snapshot / Match / CandidateSet / PrepAttempt 一律按 OT 读取(Notice 经 order_task_id); + 行级双字段:selected_source_code=CandidateSet 取数目标(单源才填), + source_code=Match 正式匹配源(禁止用候选回填,避免与匹配结论混淆); + 短缺行另投影发货模板放行字段;匹配成功无短缺行投影 can_fulfill_complete_line; + preparation.source_options 下发全部已启用库存源,供 Excel 未锁定时行级覆写下拉; + Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询。 """ + from app import db + from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask from app.models.shipping_excel_template import ShippingExportArtifact - from app.models.shipping_fulfillment import ( - ShippingInventoryVerification, - ShippingUploadAttempt, + from app.models.shipping_fulfillment import ShippingUploadAttempt + from app.core.errors import ConflictError + from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.line_inventory_match_projection import ( + load_current_match_facts_by_task, + project_line_inventory_view, ) - from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch - from app.models.shipping_notice_line import ShippingNoticeLine - - facts = stp_facts if isinstance(stp_facts, dict) else {} - raw_rows = task.line_results_json if isinstance(task.line_results_json, list) else [] - fact_rows = facts.get('line_resolutions') if isinstance(facts.get('line_resolutions'), list) else [] - fact_by_key = { - str(row.get('line_key') or ''): row - for row in fact_rows - if isinstance(row, dict) and str(row.get('line_key') or '') - } - # 正式结构化匹配事实是通知准备的首要来源;旧 JSON/STP 仅作为历史任务兼容回退。 - current_match_rows = ( - ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=task.id, is_current=True) - .order_by(ShippingNoticeLineInventoryMatch.line_index, ShippingNoticeLineInventoryMatch.id) - .all() - if getattr(task, 'id', None) is not None else [] - ) - match_by_key = { - str(row.line_key or ''): row - for row in current_match_rows - if str(row.line_key or '') - } - match_by_index = { - int(row.line_index): row - for row in current_match_rows - if row.line_index is not None - } - verification_rows: dict[str, dict[str, Any]] = {} - latest_verification = ( - ShippingInventoryVerification.query - .filter_by(task_id=task.id, status='completed') - .order_by(ShippingInventoryVerification.created_at.desc(), ShippingInventoryVerification.id.desc()) - .first() - if getattr(task, 'id', None) is not None else None - ) - if latest_verification is not None: - # 核验行没有 line_key,按冻结订单行/Reservation 顺序作为最后一级兼容回退。 - for position, verification_line in enumerate(latest_verification.lines): - verification_rows[str(position)] = { - 'required_qty': verification_line.required_qty, - 'available_qty': verification_line.available_qty, - 'shortage_qty': ( - max(verification_line.required_qty - verification_line.available_qty, 0) - if verification_line.required_qty is not None and verification_line.available_qty is not None - else None - ), - 'status': verification_line.status, - } - # 冻结订单与库存匹配是不同事实:库存文件尚未准备好时,用户仍必须能核对 - # 已冻结的预约号、料号和需求数量。禁止用“是否有匹配结果”决定订单行是否展示。 from app.services.shipping_notice.order_line_no_resolver import ( notice_line_field_id_map, - resolve_order_line_no_projection, + read_field_by_id, ) + from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + _manual_required_release_fields, + _release_fact_identity, + _shortage_release_required_fields, + ) + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + + facts = stp_facts if isinstance(stp_facts, dict) else {} + # [STEP 1] Snapshot/Match/Candidate 归属 OT;Notice 详情入口必须经 order_task_id 解析, + # 禁止用 Notice.id 查 Match(否则改源/匹配已落库却投影为空行)。 + order_task = _resolve_order_task_for_gate_lookup(task) or task + has_formal_ot = isinstance(order_task, ShippingOrderTask) or getattr(order_task, 'order_snapshot_id', None) is not None + snapshot_id = getattr(order_task, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None + snapshot_lines = ( + ShippingOrderSnapshotLine.query + .filter_by(snapshot_id=int(snapshot.id)) + .order_by(ShippingOrderSnapshotLine.position, ShippingOrderSnapshotLine.id) + .all() + if snapshot is not None else [] + ) + match_by_snapshot_line_id = load_current_match_facts_by_task(getattr(order_task, 'id', None)) + candidate_codes_by_line_no: dict[int, list[str]] = {} + if getattr(order_task, 'id', None) is not None and isinstance(order_task, ShippingOrderTask): + for candidate_line in get_active_candidate_lines(order_task): + try: + line_no_key = int(getattr(candidate_line, 'line_no', 0) or 0) + except (TypeError, ValueError): + line_no_key = 0 + if line_no_key < 1: + continue + candidate_codes_by_line_no[line_no_key] = [ + str(code).strip().upper() + for code in (getattr(candidate_line, 'source_codes_json', None) or []) + if str(code or '').strip() + ] + field_id_by_code = notice_line_field_id_map(order_task) - line_no_field_id_by_code = notice_line_field_id_map(task) frozen_order_lines: list[dict[str, Any]] = [] preparation_lines: list[dict[str, Any]] = [] - notice_lines = ( - ShippingNoticeLine.query.filter_by(notice_id=task.id).order_by(ShippingNoticeLine.position).all() - if getattr(task, 'id', None) is not None else [] - ) - for line in notice_lines: + for snapshot_line in snapshot_lines: + qty_text = str(snapshot_line.qty) if snapshot_line.qty is not None else None + line_no = int(snapshot_line.line_no) if snapshot_line.line_no is not None else None frozen_order_lines.append({ - 'line_key': getattr(line, 'line_key', None), - **resolve_order_line_no_projection( - field_values=dict(getattr(line, 'field_values_json', None) or {}), - field_id_by_code=line_no_field_id_by_code, - fallback_sequence=(int(line.position) + 1) if line.position is not None else None, - ), - 'reservation_id': getattr(line, 'reservation_id', None), - 'part_number': getattr(line, 'part_number', None), - 'required_qty': str(getattr(line, 'required_qty', None)) if getattr(line, 'required_qty', None) is not None else None, + 'snapshot_line_id': int(snapshot_line.id), + 'line_no': line_no, + 'reservation_id': snapshot_line.reservation_id, + 'part_number': snapshot_line.part_number, + 'required_qty': qty_text, }) - - # 匹配表只输出已经存在的匹配/核验事实。历史任务尚未双写正式行时可用旧 JSON - # 兼容,但绝不能把未匹配的冻结订单行伪装为“库存匹配结果”。 - row_count = max(len(raw_rows), len(fact_rows), len(current_match_rows)) - for index in range(row_count): - line = notice_lines[index] if index < len(notice_lines) else None - match_row = match_by_key.get(str(getattr(line, 'line_key', '') or '')) or match_by_index.get(index) - structured = ({ - 'line_key': match_row.line_key, - 'reservation_id': match_row.reservation_id, - 'part_number': match_row.part_number, - 'required_qty': match_row.required_qty, - 'available_qty': match_row.matched_qty or match_row.available_qty, - 'shortage_qty': match_row.shortage_qty, - 'resolved_inventory_source_code': match_row.inventory_source_code, - 'disposition': match_row.match_result, - } if match_row is not None else {}) - legacy_source = fact_by_key.get( - str(getattr(line, 'line_key', '') or ''), - fact_rows[index] if index < len(fact_rows) and isinstance(fact_rows[index], dict) else {}, + fact = match_by_snapshot_line_id.get(int(snapshot_line.id)) + required_qty = (fact or {}).get('required_qty') + if required_qty is None: + required_qty = qty_text + inv_view = project_line_inventory_view( + has_formal_ot=has_formal_ot, + fact=fact, + required_qty=required_qty, + stored_line_status=None, + decision_source=None, + can_fulfill_complete_line=False, + ) + allowed = list((fact or {}).get('allowed_source_codes_snapshot') or []) + candidate_codes = candidate_codes_by_line_no.get(int(line_no), []) if line_no is not None else [] + # [STEP] 双字段真相:Match 正式源 vs CandidateSet 取数目标,禁止互相回填。 + source_code = (fact or {}).get('inventory_source_code') or ( + allowed[0] if len(allowed) == 1 else None + ) + selected_source_code = candidate_codes[0] if len(candidate_codes) == 1 else None + source_ambiguous = ( + str((fact or {}).get('match_result') or '').strip().lower() == 'source_conflict' + or (len(allowed) > 1 and not (fact or {}).get('inventory_source_code')) + or (fact is None and len(candidate_codes) > 1) + ) + source_candidates = ( + allowed if str((fact or {}).get('match_result') or '').strip().lower() == 'source_conflict' or len(allowed) > 1 + else (candidate_codes if source_ambiguous else []) + ) + # [STEP] 短缺行复用 Case 同款模板字段判定;解析失败 fail-closed,禁止只填原因放行。 + release_template_fields: list[dict[str, Any]] = [] + release_field_resolution_error: str | None = None + if bool(inv_view.get('is_shortage')): + try: + release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact) + if release_line_index is None and getattr(snapshot_line, 'position', None) is not None: + release_line_index = int(snapshot_line.position) + release_template_fields = _shortage_release_required_fields( + task=order_task, + line_index=release_line_index, + inventory_snapshot_id=release_snapshot_id, + inventory_source_code=release_source_code or source_code or selected_source_code, + ) + except ConflictError as exc: + release_field_resolution_error = exc.code + # [STEP] 正式 OT 行可履约 = 匹配成功且无短缺;供前端波次勾选(「生成发货通知和 Excel (N 行)」)。 + can_fulfill_complete_line = ( + str(inv_view.get('user_line_status') or '').strip() == 'inventory_matched' + and not bool(inv_view.get('is_shortage')) ) - # 结构化事实优先,但不以空值覆盖历史/STP 投影中仍有价值的证据字段。 - source = { - **(legacy_source if isinstance(legacy_source, dict) else {}), - **{ - key: value - for key, value in structured.items() - if value is not None and value != '' - }, - } - verification = verification_rows.get(str(index), {}) - result = raw_rows[index] if index < len(raw_rows) and isinstance(raw_rows[index], dict) else {} - required_qty = result.get('required_qty', source.get('required_qty', verification.get('required_qty', getattr(line, 'required_qty', None)))) - available_qty = result.get('available_qty', source.get('available_qty', source.get('matched_qty', verification.get('available_qty')))) - shortage_qty = result.get('shortage_qty', source.get('shortage_qty', verification.get('shortage_qty'))) preparation_lines.append({ - 'line_key': getattr(line, 'line_key', None) or source.get('line_key'), - **resolve_order_line_no_projection( - field_values=dict(getattr(line, 'field_values_json', None) or {}) if line is not None else None, - field_id_by_code=line_no_field_id_by_code, - fallback_sequence=index + 1, + 'snapshot_line_id': int(snapshot_line.id), + 'line_no': line_no, + 'customer_po_line_no': read_field_by_id( + dict(snapshot_line.field_values_json or {}), + field_id_by_code, + 'customer_po_line_no', ), - 'reservation_id': result.get('reservation_id') or source.get('effective_reservation_id') or source.get('reservation_id') or getattr(line, 'reservation_id', None), - 'part_number': result.get('part_number') or source.get('part_number') or getattr(line, 'part_number', None), + 'reservation_id': (fact or {}).get('reservation_id') or snapshot_line.reservation_id, + 'part_number': (fact or {}).get('part_number') or snapshot_line.part_number, 'required_qty': required_qty, - 'available_qty': available_qty, - 'shortage_qty': shortage_qty, - 'source_code': source.get('resolved_inventory_source_code') or source.get('inventory_source_code'), - 'status': result.get('line_status') or source.get('disposition') or verification.get('status') or None, + 'available_qty': inv_view.get('available_qty'), + 'shortage_qty': inv_view.get('shortage_qty'), + 'source_code': source_code, + 'selected_source_code': selected_source_code, + 'status': inv_view.get('user_line_status'), + 'source_ambiguous': source_ambiguous, + 'source_candidates': source_candidates, + 'is_shortage': bool(inv_view.get('is_shortage')), + 'user_line_status': inv_view.get('user_line_status'), + 'can_fulfill_complete_line': can_fulfill_complete_line, + 'inventory_allowed_actions': list(inv_view.get('inventory_allowed_actions') or []), + 'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []), + 'inventory_file_no': inv_view.get('inventory_file_no'), + 'release_template_fields': release_template_fields, + 'release_required_fields': _manual_required_release_fields(release_template_fields), + 'release_field_resolution_error': release_field_resolution_error, + 'decision': None, }) - has_match_result = bool(current_match_rows or raw_rows or any( - row.get('matched_qty') is not None - or row.get('shortage_qty') is not None - or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage', 'released'} - for row in fact_rows if isinstance(row, dict) - )) + has_match_result = bool(match_by_snapshot_line_id) gate = process_gate if isinstance(process_gate, dict) else {} - gate_code = str((gate.get('current_blocking_gate') or gate.get('current_gate') or {}).get('gate_code') or '') + gate_code = str( + (gate.get('current_blocking_gate') or gate.get('current_gate') or {}).get('gate_code') or '' + ) preparation_status = ( 'ready' if has_match_result else 'blocked' if gate_code else @@ -701,19 +861,19 @@ def _build_stage_context( inventory_sources: list[dict[str, Any]] = [] latest_preparation = None - if getattr(task, 'id', None): + if getattr(order_task, 'id', None): from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt latest_preparation = ( ShippingInventoryPreparationAttempt.query - .filter_by(task_id=task.id) + .filter_by(task_id=int(order_task.id)) .filter(ShippingInventoryPreparationAttempt.status != 'superseded') .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) .first() ) from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download - downloadable_inventory = resolve_task_inventory_download(task) + downloadable_inventory = resolve_task_inventory_download(order_task) for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []): inventory_sources.append({ 'source_code': source_attempt.source_code, @@ -721,6 +881,18 @@ def _build_stage_context( 'inventory_file_id': source_attempt.inventory_file_id, }) + # [STEP] 人工覆写库存源:下发全部已启用源,供前端行级下拉(override_line_inventory_source)。 + from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources + + source_options = [ + { + 'source_code': str(item.get('source_code') or '').strip().upper(), + 'display_name': str(item.get('display_name') or '') or str(item.get('source_code') or ''), + } + for item in list_database_inventory_sources(enabled_only=True) + if str(item.get('source_code') or '').strip() + ] + artifact = None attempts = [] if getattr(task, 'id', None): @@ -747,21 +919,25 @@ def _build_stage_context( 'awaiting_manual' if lifecycle_stage == 'freight_upload' else 'not_started' ) + source_locked = latest_export_artifact(task) is not None or latest_export_artifact(order_task) is not None return { 'preparation': { 'status': preparation_status, 'reason_code': gate.get('blocking_reason_code') or None, + 'editable': _preparation_editable(task), + 'source_locked': source_locked, 'frozen_order': { - 'task_no': task.task_no, - 'snapshot_id': task.order_snapshot_id, + 'task_no': getattr(order_task, 'task_no', None) or task.task_no, + 'snapshot_id': snapshot_id, }, 'inventory_source_code': facts.get('inventory_source_code'), 'match_status': facts.get('match_status'), 'frozen_order_lines': frozen_order_lines, 'lines': preparation_lines, 'has_match_result': has_match_result, - # 任务级库存准备源只说明文件获取进度;实际匹配源必须从 lines[].source_code 读取。 + # 任务级 inventory_sources 只说明取数进度;行级看 selected_source_code / source_code。 'inventory_sources': inventory_sources, + 'source_options': source_options, 'inventory_file': { 'available': downloadable_inventory is not None, 'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None, @@ -802,21 +978,34 @@ def build_task_ui_state( """ 构建单票任务 UI State。 - 核心逻辑:所有 UI 入口只消费这里输出的 stage/checkpoint/todo/actions/summary, - 禁止 Chat、通知卡与任务中心分别推导状态;checkpoint 仅保留内部状态/自动推进, + 核心逻辑:所有 UI 入口只消费这里输出的 stage/position/user_mode/todo/actions/summary, + 禁止 Chat、通知卡与任务中心分别推导状态; 可点击用户动作只由 Gate 与已验证 Artifact 授权产生。 + Gate 摘要只查一次,再派生 position/user_mode,禁止再走 resolve_task_ui_state 二次查库。 """ - ui = resolve_task_ui_state(task) + from app.services.shipping_notice.state_machine import ( + _review_status_fallback_ui_state, + _ui_state_from_process_gate, + ) + process_gate = _process_gate_user_summary_for_task(task) - lifecycle = _task_lifecycle(task=task, checkpoint=ui.checkpoint, process_gate=process_gate) + ui = _ui_state_from_process_gate(task, process_gate) + if ui is None: + # 与 resolve_task_ui_state 无 Gate 分支同源:仅 review_status 薄回退。 + ui = _review_status_fallback_ui_state(task) + lifecycle = _task_lifecycle(task=task, position=ui.position, process_gate=process_gate) stage = _business_stage(lifecycle) - steps = build_shipping_workflow_steps(task, ui.checkpoint, lifecycle_stage=stage['code']) + steps = build_shipping_workflow_steps(task, ui.position, lifecycle_stage=stage['code']) current_index = int(stage['index']) - 1 current_step = steps[current_index] if 0 <= current_index < len(steps) else None summary = _build_task_summary( task, - ui.checkpoint, - checkpoint_kind=ui.checkpoint_kind, + ui.position, + user_mode=ui.user_mode, + gate_code=( + process_gate.get('current_gate_code') + if isinstance(process_gate, dict) else None + ), ) if process_gate is not None: summary['process_gate'] = process_gate @@ -831,7 +1020,7 @@ def build_task_ui_state( summary['allowed_actions'] = [] actions = _unified_actions(process_gate=process_gate) # [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作, - # 两者不能相互覆盖。即使当前 Gate 阻断并清空旧 checkpoint 动作,也只在 + # 两者不能相互覆盖。即使当前 Gate 阻断并清空旧动作,也只在 # Artifact 已通过 resolve_task_export_download 校验时补入下载授权。 if resolve_task_export_download(task) is not None: download_action = _unified_action({ @@ -842,7 +1031,7 @@ def build_task_ui_state( 'ui_handler': 'excel_download', 'enabled': True, # Artifact 已验证是下载授权的唯一来源;它直接声明展示位置, - # 不依赖旧 checkpoint 或 action code 位置映射。 + # 不依赖旧位置码或 action code 位置映射。 'target_surface': 'freight_upload', 'target_anchor': 'excel_artifact', }, default_kind='view') @@ -858,7 +1047,7 @@ def build_task_ui_state( # 同 PO 成功通知明细与批次 ZIP 的只读留档入口。 process_gate = None actions = {'primary': None, 'secondary': []} - # summary 仅作为 ui_state.actions 的只读镜像,禁止由 checkpoint 或任务字段另行推导。 + # summary 仅作为 ui_state.actions 的只读镜像,禁止由位置码或任务字段另行推导。 summary['allowed_actions'] = [ str(item.get('code')) for item in [actions.get('primary'), *(actions.get('secondary') or [])] @@ -873,11 +1062,6 @@ def build_task_ui_state( ) if include_stage_context else None ) - checkpoint_payload = { - "code": ui.checkpoint, - "kind": str(ui.checkpoint_kind), - "label": str(ui.checkpoint or "") or None, - } reason = None if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"): reason = { @@ -890,8 +1074,8 @@ def build_task_ui_state( "lifecycle_stage": stage["code"], "lifecycle_entries": lifecycle['lifecycle_entries'], "lifecycle_authority": lifecycle['lifecycle_authority'], - "checkpoint": checkpoint_payload, - "checkpoint_view": checkpoint_payload, + "position": ui.position, + "user_mode": str(ui.user_mode), "todo": { "title": summary.get("current_todo") or summary.get("title"), "message": summary.get("message"), @@ -900,12 +1084,11 @@ def build_task_ui_state( # 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。 **({'stage_context': stage_context} if stage_context is not None else {}), "reason": reason, - "lifecycle_status": task.lifecycle_status, - "checkpoint_code": ui.checkpoint, - "checkpoint_kind": str(ui.checkpoint_kind), - "review_status": task.review_status, - "pending_human_reason": task.pending_human_reason, - "match_status": task.match_status, + # OT 与 Notice 字段不完全同构:禁止硬读 Notice 专属列。 + "lifecycle_status": getattr(task, "lifecycle_status", None) or getattr(task, "status", None), + "review_status": getattr(task, "review_status", None), + "pending_human_reason": getattr(task, "pending_human_reason", None), + "match_status": getattr(task, "match_status", None), "current_step": current_step, "steps": steps, "summary": summary, @@ -914,42 +1097,107 @@ def build_task_ui_state( } -def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None: +def _resolve_order_task_for_gate_lookup(task: Any): """ - 按 Task 查找活动 Execution 的用户 Gate 摘要。 + 解析 Execution.task_id 对应的正式 OT。 - 核心逻辑:Task 本身即正式 OT,套用 apply_post_ot_gate_rules, - 使 inventory_preparation 等系统等待不进入 current_blocking_gate。 + 核心逻辑:ShippingProcessExecution.task_id FK 指向 shipping_order_tasks.id。 + 入参可能是 ShippingOrderTask,或挂有 order_task_id 的 ShippingNotice; + Artifact.task_id 才是 Notice 主键,禁止用 Notice.id 查 Execution。 + + Args: + task: ShippingOrderTask 或 ShippingNotice(及具备 order_task_id 的兼容对象)。 Returns: - 用户态 Gate 摘要;无 Execution 时 None。 + 正式 OT;Notice 未绑定 OT 时 None。 """ + from app import db + from app.models import ShippingOrderTask + + if isinstance(task, ShippingOrderTask): + return task + order_task_id = getattr(task, 'order_task_id', None) + if order_task_id is None: + return None + try: + return db.session.get(ShippingOrderTask, int(order_task_id)) + except (TypeError, ValueError): + return None + + +def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None: + """ + 按正式 OT 查找活动 Execution 的用户 Gate 摘要。 + + 核心逻辑:先把 Notice 解析到 order_task_id 对应的 OT,再优先读 + active_process_execution_id,回退按 OT.id 取最新非 superseded Execution; + 套用 apply_post_ot_gate_rules,使 inventory_preparation 等系统等待 + 不进入 current_blocking_gate。货代上传聚合的 available_actions 依赖此路径。 + 同一 HTTP 请求内按 task 主键 memo,避免 build_task_ui_state / resolve 等路径重复查库。 + + Returns: + 用户态 Gate 摘要;无 OT / Execution 时 None。 + """ + from app import db from app.models import ShippingProcessExecution from app.services.shipping_notice.order_review_workbench_projection import ( apply_post_ot_gate_rules, ) from app.services.shipping_notice.process_gate_projection import project_user_gate_summary - task_id = getattr(task, 'id', None) - if task_id is None: - return None + cache_key = ( + type(task).__name__, + getattr(task, 'id', None), + str(getattr(task, 'task_no', '') or ''), + ) try: - task_pk = int(task_id) - except (TypeError, ValueError): - return None - execution = ( - ShippingProcessExecution.query - .filter_by(task_id=task_pk) - .filter(ShippingProcessExecution.status != 'superseded') - .order_by(ShippingProcessExecution.id.desc()) - .first() - ) - if execution is None: - return None - return apply_post_ot_gate_rules( - project_user_gate_summary(execution), - has_formal_ot=True, - ) + from flask import g, has_app_context, has_request_context + if has_app_context() and has_request_context(): + cache = getattr(g, '_shipping_process_gate_summary_by_task', None) + if cache is None: + cache = {} + g._shipping_process_gate_summary_by_task = cache + if cache_key in cache: + return cache[cache_key] + else: + cache = None + except Exception: + cache = None + + # [STEP 1] Notice→OT:Execution.task_id 只认 shipping_order_tasks.id。 + order_task = _resolve_order_task_for_gate_lookup(task) + if order_task is None or getattr(order_task, 'id', None) is None: + result = None + else: + # [STEP 2] 与 processing_projection 同源:优先活跃指针,再回退最新活跃 Execution。 + execution = None + active_execution_id = getattr(order_task, 'active_process_execution_id', None) + if active_execution_id is not None: + execution = db.session.get(ShippingProcessExecution, int(active_execution_id)) + if execution is not None and ( + int(getattr(execution, 'task_id', 0) or 0) != int(order_task.id) + or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded' + ): + execution = None + if execution is None: + execution = ( + ShippingProcessExecution.query + .filter_by(task_id=int(order_task.id)) + .filter(ShippingProcessExecution.status != 'superseded') + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None: + result = None + else: + result = apply_post_ot_gate_rules( + project_user_gate_summary(execution), + has_formal_ot=True, + ) + + if cache is not None: + cache[cache_key] = result + return result def project_notice_available_actions(task: ShippingNotice) -> list[str]: diff --git a/backend/app/services/shipping_notice/upload_attempt_service.py b/backend/app/services/shipping_notice/upload_attempt_service.py index 1dbcf906..af164ed8 100644 --- a/backend/app/services/shipping_notice/upload_attempt_service.py +++ b/backend/app/services/shipping_notice/upload_attempt_service.py @@ -1,9 +1,13 @@ """ services/shipping_notice/upload_attempt_service.py -用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认。 -依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。 -逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,任务工作面通过 Attempt 查询结果。 +用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认;并提供 + Notice 面 upload_status / facts.upload_state 的唯一投影归一。 +依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机、 + process_gate_contract.PROJECTION_UPLOAD_STATES(facts 词汇)。 +逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded。 + Attempt 内成功词为 succeeded,Artifact 为 uploaded;对外 API 字段经 + project_notice_upload_status 统一为 uploaded,禁止调用方再扩同义词集合。 """ from __future__ import annotations @@ -22,6 +26,9 @@ from app.models import ( ShippingUploadAttempt, ) +# Attempt 在途词 → Notice 面 uploading;成功词在投影内按层翻译,不对外暴露别名。 +_UPLOAD_IN_FLIGHT_TOKENS = frozenset({'running', 'uploading', 'triggered', 'queued'}) + def _formal_notice(task: ShippingNotice | Any) -> ShippingNotice | None: """解析上传事实所属的正式 Notice;OT 在 Notice 生成前不产生上传事实。""" @@ -105,6 +112,78 @@ def latest_upload_attempt(task: ShippingNotice) -> ShippingUploadAttempt | None: ).first() +def project_notice_upload_status(task: ShippingNotice | Any) -> str | None: + """投影 Notice 面 upload_status(货代聚合/任务详情对外字段)。 + + 核心逻辑:优先读最新 Attempt,缺则回退 Artifact。 + Attempt 成功词 succeeded、Artifact 成功词 uploaded → 一律输出 uploaded。 + 调用方只允许判断 ``== 'uploaded'`` 或使用 has_verified_upload_success;禁止再读 Attempt 原词做成败。 + + Args: + task: 正式 Notice,或可解析到 Notice 的 OT。 + + Returns: + uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。 + """ + attempt = latest_upload_attempt(task) + if attempt is not None: + status = str(getattr(attempt, 'status', None) or '').strip().lower() + # Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。 + if status == 'succeeded': + return 'uploaded' + if status in _UPLOAD_IN_FLIGHT_TOKENS: + return 'uploading' + if status == 'pending': + return 'pending' + if status == 'failed': + return 'failed' + if status in {'timed_out', 'unknown'}: + return 'unknown' + return status or None + + artifact = latest_export_artifact(task) + if artifact is None: + return None + status = str(getattr(artifact, 'status', None) or '').strip().lower() + if status == 'uploaded': + return 'uploaded' + if status == 'uploading': + return 'uploading' + if status == 'ready': + return 'pending' + return status or None + + +def project_facts_upload_state(task: ShippingNotice | Any) -> str: + """投影 facts.upload_state,取值必须落在 PROJECTION_UPLOAD_STATES。 + + 核心逻辑:与 Notice upload_status 同源读取;成功按 facts 契约输出 succeeded + (Attempt.succeeded / Artifact.uploaded → succeeded)。 + + Args: + task: 正式 Notice 或可解析到 Notice 的 OT。 + + Returns: + not_created | uploading | succeeded | failed | manual_upload_pending。 + """ + attempt = latest_upload_attempt(task) + artifact = latest_export_artifact(task) + if attempt is None: + if artifact is not None and str(getattr(artifact, 'status', None) or '').strip().lower() == 'uploaded': + return 'succeeded' + return 'not_created' + status = str(getattr(attempt, 'status', None) or '').strip().lower() + if status == 'succeeded': + return 'succeeded' + if status in _UPLOAD_IN_FLIGHT_TOKENS or status == 'pending': + return 'uploading' + if status == 'failed': + return 'failed' + if status in {'timed_out', 'unknown'}: + return 'manual_upload_pending' + return 'not_created' + + def has_verified_upload_success(task: ShippingNotice) -> bool: """判断任务是否具备可审计的货代上传成功事实。 diff --git a/backend/app/services/shipping_notice/user_facing_status.py b/backend/app/services/shipping_notice/user_facing_status.py index 5e8f91a3..bbd9b3ef 100644 --- a/backend/app/services/shipping_notice/user_facing_status.py +++ b/backend/app/services/shipping_notice/user_facing_status.py @@ -2,8 +2,11 @@ services/shipping_notice/user_facing_status.py 用途:将任务 DB / 状态机内部码转为面向用户的中文阶段描述,并过滤 Tool 响应中的内部字段。 -依赖:models.ShippingNotice、constants、state_machine.resolve_task_ui_state。 -逻辑:get_task_status 与 tool_response 序列化时调用;STP 多源阻断优先于通用 shortage 文案。 +依赖:models.ShippingNotice、constants、process_gate_contract.derive_position、 + ui_state._process_gate_user_summary_for_task、state_machine.resolve_task_ui_state(回退)。 +逻辑:get_task_status 与 tool_response 序列化时调用;阶段标签优先 Gate position, + 无 Execution 时回退 ui.position;STP 多源阻断优先于通用 shortage 文案; + user_facing_stage_label_for_position 供已持有 position 的调用方免二次查 Gate。 """ from __future__ import annotations @@ -11,18 +14,18 @@ from __future__ import annotations from app import db from app.models import ShippingNotice, ShippingOrderTask from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_INVENTORY_PENDING, - CP_PARSE_REVIEW, - CP_READY_EXPORT, - CP_READY_MATCH, - CP_REJECTED, - CP_RSV_REQ, - CP_UPLOADED, - CP_COMPLETED, - CP_UPLOAD_FAILED, - CP_UPLOAD_REQ, - CP_WAITING_UPLOAD, + POSITION_EXPORT_READY, + POSITION_INVENTORY_PENDING, + POSITION_PARSE_REVIEW, + POSITION_READY_EXPORT, + POSITION_READY_MATCH, + POSITION_REJECTED, + POSITION_RSV_REQ, + POSITION_UPLOADED, + POSITION_COMPLETED, + POSITION_UPLOAD_FAILED, + POSITION_UPLOAD_REQ, + POSITION_WAITING_UPLOAD, PH_RPA_EXHAUSTED, PH_RPA_PENDING, PH_SHORTAGE, @@ -39,20 +42,23 @@ TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset( } ) -_CHECKPOINT_LABELS: dict[str, str] = { - CP_PARSE_REVIEW: "待确认发货通知解析", - CP_UPLOAD_REQ: "待上传或获取库存", - CP_INVENTORY_PENDING: "待上传库存", - CP_RSV_REQ: "待补充 Reservation ID", +# 键对齐 Gate derive_position / 位置标签。 +_POSITION_LABELS: dict[str, str] = { + POSITION_PARSE_REVIEW: "待确认发货通知解析", + POSITION_UPLOAD_REQ: "待上传或获取库存", + POSITION_INVENTORY_PENDING: "待上传库存", + POSITION_RSV_REQ: "待补充 Reservation ID", + "customer_review": "待确认客户", + "quality_issue": "质量异常待处理", "shortage_review": "库存不足,无法发货", - CP_READY_MATCH: "待匹配库存", - CP_READY_EXPORT: "待生成发货 Excel", - CP_EXPORT_READY: "待人工上传登记", - CP_WAITING_UPLOAD: "待人工上传登记", - CP_UPLOAD_FAILED: "货代上传失败,待处理", - CP_REJECTED: "任务已驳回", - CP_UPLOADED: "已完成上传", - CP_COMPLETED: "任务已完成", + POSITION_READY_MATCH: "待匹配库存", + POSITION_READY_EXPORT: "待生成发货 Excel", + POSITION_EXPORT_READY: "待人工上传登记", + POSITION_WAITING_UPLOAD: "待人工上传登记", + POSITION_UPLOAD_FAILED: "货代上传失败,待处理", + POSITION_REJECTED: "任务已驳回", + POSITION_UPLOADED: "已完成上传", + POSITION_COMPLETED: "任务已完成", } _PROCESS_STATUS_LABELS: dict[str, str] = { @@ -79,12 +85,49 @@ _PENDING_REASON_LABELS: dict[str, str] = { } +def user_facing_stage_label_for_position( + task: ShippingNotice, + *, + position: str | None, +) -> str | None: + """ + 在调用方已持有 position 时生成标题,避免再查 Gate。 + + 核心逻辑:多源阻断与 pending_human_reason 优先;否则用位置标签表。 + 无法判定时返回 None,由调用方回退 ``user_facing_task_stage``。 + + Args: + task: 任务实体(读 step_payload / pending_human_reason)。 + position: 已派生的位置码。 + + Returns: + 中文阶段标题;无法仅凭已知事实判定时为 None。 + """ + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + payload = getattr(owner, 'step_payload_json', None) + payload = payload if isinstance(payload, dict) else {} + if payload.get('multi_source_excel_block'): + return '多库存源冲突,待人工处理' + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + reason = str(task_blocking_reason(owner) or '').strip() + if reason in _PENDING_REASON_LABELS: + return _PENDING_REASON_LABELS[reason] + pos = str(position or '').strip() + if pos and pos in _POSITION_LABELS: + return _POSITION_LABELS[pos] + return None + + def user_facing_task_stage(task: ShippingNotice) -> str: """ Short Chinese label for chat / get_task_status — no snake_case codes. 核心逻辑:优先返回更具体的 pending_human_reason 标签,避免 `rpa_pending` - 这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖; + 这类细粒度状态被通用位置文案(如“待上传或获取库存”)覆盖; + 其次 Gate derive_position;无 Gate 回退 resolve_task_ui_state.position; STP 多源 Excel 阻断覆盖通用 shortage 文案。 """ # Notice 只承载正式单据;流程/UI 状态归属关联 OT。 @@ -100,9 +143,23 @@ def user_facing_task_stage(task: ShippingNotice) -> str: reason = str(task_blocking_reason(owner) or '').strip() if reason in _PENDING_REASON_LABELS: return _PENDING_REASON_LABELS[reason] + + # [STEP] Gate-first:位置标签查找。 + from app.services.shipping_notice.process_gate_contract import derive_position + from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task + + gate = _process_gate_user_summary_for_task(owner) + if isinstance(gate, dict) and gate: + pos = derive_position( + gate_code=gate.get('current_gate_code'), + review_status=getattr(owner, 'review_status', None), + ) + if pos and pos in _POSITION_LABELS: + return _POSITION_LABELS[pos] + ui = resolve_task_ui_state(owner) - if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS: - return _CHECKPOINT_LABELS[ui.checkpoint] + if ui.position and ui.position in _POSITION_LABELS: + return _POSITION_LABELS[ui.position] lifecycle = str(getattr(owner, "lifecycle_status", None) or getattr(owner, 'status', None) or "active") return lifecycle == "active" and "处理中" or "已结束" diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 9f2a9960..ecc150dd 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -26,38 +26,6 @@ def pytest_configure(config): ) -@pytest.fixture(autouse=True) -def _capture_legacy_order_rows_for_tests(monkeypatch): - """将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。""" - from app.models import ShippingNotice - - original_init = ShippingNotice.__init__ - legacy_headers = ('customer_name', 'customer_code', 'ship_to', 'po_number', 'required_date') - - def _init(self, **kwargs): - rows = kwargs.pop('lines_json', None) - kwargs.pop('order_lines_migration_status', None) - header_values = {key: kwargs.pop(key) for key in legacy_headers if key in kwargs} - original_init(self, **kwargs) - if rows is not None: - self._test_order_rows = [dict(item) for item in rows if isinstance(item, dict)] - for key, value in header_values.items(): - setattr(self, f'_test_{key}', value) - - monkeypatch.setattr(ShippingNotice, '__init__', _init) - for key in (*legacy_headers, 'lines_json'): - storage = f'_test_{key}' if key != 'lines_json' else '_test_order_rows' - monkeypatch.setattr( - ShippingNotice, - key, - property( - lambda task, name=storage: getattr(task, name, None), - lambda task, value, name=storage: setattr(task, name, value), - ), - raising=False, - ) - - def parse_api_error(body: dict) -> dict: """ 从标准 API 错误 envelope 中提取 error 子对象,供测试断言 error.code / details。 @@ -193,12 +161,17 @@ def seed_task_inventory_source( *, source_code: str = "DSV360_AWSDU", ) -> None: - """测试辅助:为直接构造的 ShippingNotice 写入稳定库存源独立字段。""" + """测试辅助:冻结库存候选集,供库存门禁从正式事实源读取。""" _ensure_test_task_dynamic_order(task) - from app.services.shipping_notice.inventory_source_rules import ( - compute_routing_fingerprint, - extract_routing_context, - ) + from app import db + from app.models import ShippingOrderTask + if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None: + _ensure_test_task_dynamic_order(task) + owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None)) + if owner is None: + raise ValueError('test task must be linked to ShippingOrderTask') + from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task + from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication from app.services.shipping_notice.inventory_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, @@ -207,35 +180,39 @@ def seed_task_inventory_source( source = get_database_inventory_source(source_code) if not source: raise ValueError(f"unknown inventory source for tests: {source_code}") - from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity - - context = extract_routing_context(task) - resolution = resolve_inventory_source_identity(source, context) - if not resolution.ok or not resolution.identity: - raise ValueError( - f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}" - ) - identity = resolution.identity - task.inventory_source_code = identity.source_code - task.inventory_connector_type = identity.connector_type - task.inventory_warehouse_id = identity.warehouse_id - task.inventory_source_status = "resolved" - task.inventory_source_method = "rule_exact" - task.inventory_source_config_version = inventory_sources_runtime_version() - task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) - if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id: + if getattr(task, '_test_customer_confirmed', False) and not owner.order_snapshot_id: freeze_test_task_order_snapshot(task) + if not owner.order_snapshot_id: + raise ValueError('test task must have a frozen order snapshot before inventory source selection') + freeze_candidates_for_task( + owner, + adjudication=InventorySourceAdjudication( + status='resolved', + method='test_fixture', + source_code=str(source.get('source_code') or source_code).strip().upper(), + candidates=[source], + config_version=inventory_sources_runtime_version(), + ), + ) def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: """将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。""" from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot - if task.order_snapshot_id: + from app import db + from app.models import ShippingOrderTask + if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None: + _ensure_test_task_dynamic_order(task) + owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None)) + if owner is None: + raise ValueError('test task must be linked to ShippingOrderTask') + if owner.order_snapshot_id: return rows = list(getattr(task, '_test_order_rows', []) or []) if not rows: - lines = task.lines_json if isinstance(task.lines_json, list) else [] + lines = getattr(task, 'lines_json', None) + lines = lines if isinstance(lines, list) else [] rows = [ { 'part_number': row.get('part_number'), @@ -244,33 +221,19 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: } for row in lines if isinstance(row, dict) ] - task._test_order_rows = rows - _ensure_test_task_dynamic_order(task) - task.order_data_version = int(task.order_data_version or 1) - from app import db - from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction + owner._test_order_rows = rows + _ensure_test_task_dynamic_order(owner) + owner.order_data_version = int(owner.order_data_version or 1) + from app.models import ShippingOrderExtraction db.session.flush() - extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) - 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: - db.session.add(ShippingOrderCustomerMatch( - extraction_id=extraction.id, role='bill_to', - raw_name=customer.standard_name, - normalized_name=str(customer.standard_name or '').upper(), status='confirmed', - customer_id=customer.id, - customer_name_snapshot=customer.standard_name, - customer_short_code_snapshot=customer.short_code, - identity_fingerprint='r' * 64, - identity_rule_version='test.v1', resolution_method='manual', - confirmation_reason='测试确认', confirmed_by_id=None, - )) - db.session.flush() + extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id) + customer = getattr(owner, 'customer', None) + if extraction is not None and customer is not None: + confirm_test_customer_resolution(owner, customer=customer, extraction=extraction) freeze_order_snapshot( - task, + owner, actor_id=None, - expected_order_data_version=int(task.order_data_version), + expected_order_data_version=int(owner.order_data_version), freeze_mode='auto', auto_freeze_policy={ 'test_fixture': True, @@ -284,6 +247,47 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: db.session.flush() +def confirm_test_customer_resolution(task: "ShippingOrderTask", *, customer, extraction=None) -> None: + """为测试 OT 写入唯一客户真相源,不构造已退役的角色匹配记录。""" + from app import db + from app.models import ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderIntake + + candidate = db.session.get(ShippingOrderCandidate, task.candidate_id) if task.candidate_id else None + if candidate is None: + intake = ShippingOrderIntake( + intake_no=f'INT-TEST-RESOLUTION-{task.id}', asset_id=int(task.id), + user_id=int(task.user_id), parser_version='test', + ) + db.session.add(intake) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-TEST-RESOLUTION-{task.id}', intake_id=intake.id, + primary_document_id=1, candidate_key=f'test-resolution-{task.id}', + candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + task.candidate_id = candidate.id + if extraction is not None: + candidate.order_extraction_id = int(extraction.id) + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=candidate.id).one_or_none() + if resolution is None: + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, + intake_id=candidate.intake_id, + resolution_version='test.v1', status='confirmed', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 't' * 64}}, + identity_rule_set_checksum='t' * 64, + ) + db.session.add(resolution) + resolution.status = 'confirmed' + resolution.confirmed_customer_id = customer.id + resolution.confirmation_method = 'test_fixture' + db.session.flush() + + def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: """将 RPA 测试显式构造的旧行样例转换为当前测试所需的动态 FieldValue。""" from decimal import Decimal @@ -292,16 +296,35 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: from app.models import ( ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchemaVersion, + ShippingOrderTask, User, ) from app.services.shipping_notice.order_schema import service as order_schema_service - if task.current_order_extraction_id is not None: + if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None: + if task.id is None: + db.session.add(task) + db.session.flush() + user_id = getattr(task, 'user_id', None) or db.session.query(User.id).order_by(User.id).first() + user_id = user_id[0] if isinstance(user_id, tuple) else user_id + owner = ShippingOrderTask( + task_no=f'OT-TEST-{task.task_no}', + user_id=int(user_id or 1), + status='ready', + current_step='customer_review', + ) + db.session.add(owner) + db.session.flush() + task.order_task_id = owner.id + owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id) + if owner is None: + raise ValueError('test task must be linked to ShippingOrderTask') + if owner.current_order_extraction_id is not None: return rows = list(getattr(task, '_test_order_rows', []) or []) if not rows: return - if task.id is None: - db.session.add(task) + if owner.id is None: + db.session.add(owner) db.session.flush() version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none() if version is None: @@ -335,11 +358,11 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: required = {'part_number', 'reservation_id', 'qty'} if not required.issubset(field_ids): raise ValueError('RPA test schema lacks required order business purposes') - extraction = ShippingOrderExtraction(task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted') + extraction = ShippingOrderExtraction(task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted') db.session.add(extraction) db.session.flush() for position, row in enumerate(rows): - line = ShippingOrderLine(extraction_id=extraction.id, position=position) + line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1) db.session.add(line) db.session.flush() for code in required: @@ -358,7 +381,7 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, value_json=json_value, )) - task.current_order_extraction_id = extraction.id + owner.current_order_extraction_id = extraction.id db.session.flush() @@ -425,9 +448,14 @@ def inventory_csv_with_warehouse( def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]: """构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。""" + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + source_code = next(iter(task_frozen_inventory_source_codes(task)), '') + source = get_database_inventory_source(source_code) or {} return { - "source_code": str(task.inventory_source_code or ""), - "warehouse_id": str(task.inventory_warehouse_id or ""), + "source_code": str(source_code or ""), + "warehouse_id": str(source.get("fixed_warehouse_id") or ""), } @@ -464,6 +492,11 @@ def rpa_callback_payload( status: str = "success", ) -> dict: """构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。""" + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + + source_code = next(iter(task_frozen_inventory_source_codes(task)), '') + source = get_database_inventory_source(source_code) or {} return { "schema_version": "shipping_inventory_rpa.v2", "callback_id": f"test-callback:{run_no}", @@ -472,8 +505,8 @@ def rpa_callback_payload( "file_path": str(file_path), "run_no": run_no, "source_run_no": run_no, - "source_code": task.inventory_source_code, - "warehouse_id": task.inventory_warehouse_id, + "source_code": source_code, + "warehouse_id": str(source.get("fixed_warehouse_id") or ""), "attempt_no": 1, "lease_token": "test-lease-token", "candidate_set_id": 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 6a95bc1e..1ca8a885 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -81,12 +81,12 @@ def _fake_job(job_id=928, status='failed', domain='shipping_notice', job_type='s ('failed', False, 'failed', '业务阻断失败 → failed'), ('manual_fallback', True, 'retryable', 'manual_fallback retryable → retryable'), ('failed', True, 'retryable', '技术失败 retryable → retryable'), - ('idle', False, 'idle', 'Idle → idle(默认)'), + ('idle', False, 'waiting_human', 'Idle automation → waiting_human(禁止再发 idle)'), ], ids=lambda t: t[3] if isinstance(t, tuple) else '', ) -def test_p3_t3_user_status_seven_value_matrix(automation_status, retryable_flag, expected_user_status, label): - """[P3 T3] project_case_user_status 七值归一化与 Q12 invariants 一致。""" +def test_p3_t3_user_status_f2_six_value_matrix(automation_status, retryable_flag, expected_user_status, label): + """[P3 T3] project_case_user_status F2 六值;默认人工等待 waiting_human。""" from app.services.shipping_notice.reconciliation_projector import project_case_user_status case = _fake_case(status='draft') diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py index c46bdf6e..48fc4e51 100644 --- a/backend/tests/test_chat_turn_runtime.py +++ b/backend/tests/test_chat_turn_runtime.py @@ -80,7 +80,7 @@ def test_chat_turn_rejects_legacy_fulfillment_action(app, client): "input": { "type": "action", "display_text": "确认", - "action_type": "shipping.submit_decision", + "action_type": "shipping.match_inventory", "payload": {"task_no": task_no, "decision": "confirm"}, }, }, @@ -128,7 +128,7 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client): "input": { "type": "action", "display_text": "确认", - "action_type": "shipping.submit_decision", + "action_type": "shipping.match_inventory", "payload": {"task_no": "SN-20260706-ABCD1234", "decision": "confirm"}, }, }, diff --git a/backend/tests/test_crane_report_export.py b/backend/tests/test_crane_report_export.py index a904bbc4..4daaa733 100644 --- a/backend/tests/test_crane_report_export.py +++ b/backend/tests/test_crane_report_export.py @@ -106,13 +106,14 @@ def test_export_scheduled_report_flow(monkeypatch): def _download(*args, **kwargs): calls.append("download") captured["download_description"] = kwargs.get("description", "") + captured["download_dir"] = kwargs.get("download_dir", "") return "download-object" monkeypatch.setattr(module, "_wait_and_click_scheduled_download", _download) result = module.export_crane_inventory_report( page, - {"parameters": [], "source_code": "CRANE_TZR2"}, + {"parameters": [], "source_code": "CRANE_TZR2", "__download_dir": "D:/tmp/crane-drop"}, trigger={"task_no": "SN-1001"}, env=lambda name, default="": default, browser_timeout_ms=5_000, @@ -124,6 +125,7 @@ def test_export_scheduled_report_flow(monkeypatch): assert calls == ["run", "wait_run", "schedule", "confirm", "wait_submitted", "open_scheduled", "download"] assert captured["description"] == "HXOPS-CRANE_TZR2-TEST" assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST" + assert captured["download_dir"] == "D:/tmp/crane-drop" def test_should_run_report_before_schedule_uses_driver_environment_only(): @@ -443,3 +445,154 @@ def test_resolve_download_mode_uses_driver_environment_only(): module = _load_export() assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report" assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download" + + +def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch): + """ + expect_download 超时后,应短窗口扫描 downloads_path 并返回目录文件适配器。 + 断言意图:主路径事件丢失时复用 DSV 同款兜底,而不是直接失败。 + """ + module = _load_export() + page = MagicMock() + locator = MagicMock() + fallback = MagicMock() + fallback.suggested_filename = "OnHandDetails.xlsx" + fallback_calls: list[dict] = [] + + class _TimeoutDownloadExpect: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + if exc_type is not None: + return False + raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"') + + @property + def value(self): + raise AssertionError("download event should not resolve") + + page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect() + monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False) + monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True) + monkeypatch.setattr( + module, + "_probe_scheduled_download_status", + lambda *_a, **_k: ("Download", locator), + ) + monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True) + + def _fake_wait(*, download_dir, baseline_names, timeout_seconds): + fallback_calls.append( + { + "download_dir": str(download_dir), + "baseline_names": set(baseline_names), + "timeout_seconds": timeout_seconds, + } + ) + return fallback + + monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait) + + result = module._wait_and_click_scheduled_download( + page, + env=lambda name, default="": default, + browser_timeout_ms=1_000, + description="abc123", + expected_report_name="OnHandDetails.xlsx", + download_dir=str(tmp_path), + ) + + assert result is fallback + assert fallback_calls == [ + { + "download_dir": str(tmp_path), + "baseline_names": set(), + "timeout_seconds": module._CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS, + } + ] + + +def test_wait_and_click_scheduled_download_reraises_when_fallback_misses(tmp_path, monkeypatch): + """ + expect_download 超时且目录无新文件时,应继续抛出原超时。 + 断言意图:兜底失败不能吞掉异常。 + """ + module = _load_export() + page = MagicMock() + + class _TimeoutDownloadExpect: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + if exc_type is not None: + return False + raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"') + + page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect() + monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False) + monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True) + monkeypatch.setattr( + module, + "_probe_scheduled_download_status", + lambda *_a, **_k: ("Download", MagicMock()), + ) + monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True) + monkeypatch.setattr(module, "_wait_for_new_download_file", lambda **_k: None) + + with pytest.raises(TimeoutError, match="download"): + module._wait_and_click_scheduled_download( + page, + env=lambda name, default="": default, + browser_timeout_ms=1_000, + description="abc123", + download_dir=str(tmp_path), + ) + + +def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_path, monkeypatch): + """ + Download 链接点击失败时不应进入目录兜底。 + 断言意图:避免点击失败后空等 15s。 + """ + module = _load_export() + page = MagicMock() + fallback_called = {"value": False} + + class _DownloadExpect: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return False + + @property + def value(self): + raise AssertionError("should not reach download value") + + page.expect_download.side_effect = lambda timeout=None: _DownloadExpect() + monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False) + monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True) + monkeypatch.setattr( + module, + "_probe_scheduled_download_status", + lambda *_a, **_k: ("Download", MagicMock()), + ) + monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: False) + + def _fake_wait(**_kwargs): + fallback_called["value"] = True + return MagicMock() + + monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait) + + with pytest.raises(RuntimeError, match="Download link click failed"): + module._wait_and_click_scheduled_download( + page, + env=lambda name, default="": default, + browser_timeout_ms=1_000, + description="abc123", + download_dir=str(tmp_path), + ) + assert fallback_called["value"] is False diff --git a/backend/tests/test_email_supplement_merge.py b/backend/tests/test_email_supplement_merge.py index 2dca8f2a..848ebe2b 100644 --- a/backend/tests/test_email_supplement_merge.py +++ b/backend/tests/test_email_supplement_merge.py @@ -430,3 +430,60 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers(): html_tables=['''
PO#MPNReservation ID
4518838154B3-AR1000270A14000111701
'''], ) assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']} + + +def test_email_supplement_pn_matching_customer_part_number_does_not_false_conflict(): + """邮件 PN 列的值为客户件号(MPN)时不得与 PDF 内部件号产生误判 part_number 冲突。 + + 回归:ZNE 邮件正文 PO 表把客户件号(504-006043-001)放进 PN 列并映射到 + `part_number`,而 PDF 同一行的 `part_number` 是内部件号(D4-A08AR12000001)、 + `customer_part_number` 是 504-006043-001。邮件值命中 PDF 的客户件号即同一料号, + 不得判成 `part_number` 的 `supplement_field_conflict`。 + """ + order = _order() # header PO 4518738152;line part D4-A08AR12000002 + order['lines'][0]['fields'].append({ + 'field_id': 'customer-part', 'observations': [{'value': '504-006043-001'}], + }) + supplement = { + 'document_id': 44, + 'rows': [{ + 'customer_po_number': '4518738152', + 'part_number': '504-006043-001', # 邮件 PN 列,实为客户件号(MPN) + 'evidence': {}, + }], + } + merged = merge_email_supplements( + orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA, + )[0] + # PDF 内部件号保持不变,且不再误判 part_number 冲突 + assert _value(merged['lines'][0]['fields'], 'part') == 'D4-A08AR12000002' + assert not any(item.get('field') == 'part_number' for item in merged['conflicts']) + + +def test_supplement_field_conflict_pdf_string_evidence_ref_does_not_crash(): + """坐标 PDF observation 的 evidence_ref 是字符串时不得崩溃(dict.update length1 回归)。 + + 回归:`_supplement_field_conflict` 曾用 `dict(pdf.get('evidence_ref') or {})` 直接构造证据, + 而坐标 PDF observation 的 `evidence_ref` 是字符串(如 `layout:...:row-7:qty`), + `dict(<字符串>)` 会按字符拆成长度 1 序列 → `dictionary update sequence element #0 has length 1; 2 is required`。 + 修复后改用 observation 的证据 dict(`layout_evidence`,或 `evidence_ref` 为 dict 时用其本身)。 + """ + from app.services.shipping_notice.order_supplement_merge import _supplement_field_conflict + + conflict = _supplement_field_conflict( + field_code='qty', config={'field_id': 'qty', 'field_code': 'qty'}, line_index=0, + pdf_observations=[{ + 'value': '30', 'document_id': 305, + 'evidence_ref': 'layout:305:p1:t1:row-1:qty', # 字符串(坐标 evidence_ref,触发旧崩溃) + 'layout_evidence': {'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty'}, + }], + email_value='99', email_evidence={'table_index': 0, 'row_index': 1}, + email_document_id=44, schema_version='v1', + ) + + assert conflict['conflict_key'] == '0:qty' + # evidence_ref 保持 dict 契约,并取 observation 的证据 dict(layout_evidence) + assert conflict['sources'][0]['evidence_ref'] == { + 'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty', + } + assert conflict['sources'][1]['evidence_ref'] == {'table_index': 0, 'row_index': 1} diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index be239aab..833153e4 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -14,6 +14,7 @@ import json import os import re import sys +import time from pathlib import Path import pytest @@ -648,9 +649,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): return _FakePlaywright() monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false") monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true") monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False) monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) temp_roots: list[Path] = [] @@ -1346,7 +1349,7 @@ def test_summarize_inventory_batch_results_all_skipped_is_success(): assert summary["has_success"] is False assert summary["status"] not in {"failed", "partial_failed"} def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path): - """真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。""" + """关闭会话复用时,每次都应在配置目录下生成新的 run_* 临时 profile。""" worker = _load_freight_rpa_worker() observed: dict[str, object] = {} @@ -1371,9 +1374,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat return _FakePlaywright() monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false") monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge") monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) _playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads") @@ -1392,8 +1397,8 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat } -def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path): - """DSV 会话复用开关开启时应使用固定 profile,且固定 profile 不能按临时目录清理。""" +def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monkeypatch, tmp_path): + """会话复用开启时按 connector+rpa_profile 固定目录,且不得当作临时目录清理。""" worker = _load_freight_rpa_worker() observed: dict[str, object] = {} @@ -1417,20 +1422,92 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo return _FakePlaywright() monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "true") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true") + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) _playwright, context, page, profile_dir = worker._open_browser( - tmp_path / "downloads", reuse_dsv_session=True + tmp_path / "downloads", + reuse_session=True, + connector_type="crane_footprint", + profile_code="CRANE-MAIN", ) assert context is not None assert page is not None - assert profile_dir == tmp_path / "profile" / "dsv360_session" + assert profile_dir == tmp_path / "profile" / "crane_footprint__CRANE-MAIN_session" + assert observed["profile"] == str(profile_dir) + assert worker._should_cleanup_browser_profile(profile_dir) is False + assert (profile_dir / ".hxops_rpa_session_meta.json").is_file() + + +def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path): + """兼容旧参数 reuse_dsv_session:开启复用时落到 dsv360__* 持久目录。""" + worker = _load_freight_rpa_worker() + observed: dict[str, object] = {} + + class _FakePage: + def set_default_timeout(self, value: int) -> None: + observed["timeout"] = value + + class _FakeContext: + pages = [_FakePage()] + + class _FakeChromium: + def launch_persistent_context(self, profile: str, **kwargs): + observed["profile"] = profile + return _FakeContext() + + class _FakePlaywright: + chromium = _FakeChromium() + + class _FakeStarter: + def start(self): + return _FakePlaywright() + + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true") + monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) + + _playwright, context, page, profile_dir = worker._open_browser( + tmp_path / "downloads", + reuse_dsv_session=True, + connector_type="dsv360", + profile_code="DSV-A", + ) + + assert context is not None + assert page is not None + assert profile_dir == tmp_path / "profile" / "dsv360__DSV-A_session" assert observed["profile"] == str(profile_dir) assert worker._should_cleanup_browser_profile(profile_dir) is False +def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_path): + """超过 TTL 的持久 Profile 应被清空重建,迫使重新登录。""" + worker = _load_freight_rpa_worker() + profile_dir = tmp_path / "dsv360__OLD_session" + profile_dir.mkdir(parents=True) + stale_marker = profile_dir / "stale.txt" + stale_marker.write_text("keep-me", encoding="utf-8") + created = time.time() - (25 * 3600) + (profile_dir / ".hxops_rpa_session_meta.json").write_text( + json.dumps({"created_at_unix": created, "connector_type": "dsv360", "profile_code": "OLD"}), + encoding="utf-8", + ) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24") + + prepared = worker._prepare_reusable_session_profile( + profile_dir, + connector_type="dsv360", + profile_code="OLD", + ) + + assert prepared == profile_dir + assert not stale_marker.exists() + meta = json.loads((profile_dir / ".hxops_rpa_session_meta.json").read_text(encoding="utf-8")) + assert float(meta["created_at_unix"]) > created + def test_is_dsv_username_page_ignores_login_method_page_text(): """第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。""" worker = _load_freight_rpa_worker() diff --git a/backend/tests/test_gate_derivation.py b/backend/tests/test_gate_derivation.py new file mode 100644 index 00000000..e5c9a034 --- /dev/null +++ b/backend/tests/test_gate_derivation.py @@ -0,0 +1,414 @@ +""" +backend/tests/test_gate_derivation.py + +用途:验收 Gate 推导的粗分类 / 位置 / 待办分类,替代旧 checkpoint_kind。 +依赖:process_gate_contract.derive_*、query_service._todo_category_from_gate、 + ui_state._derived_*、user_facing_status、pytest。 +逻辑:Task1–6 契约纯函数与消费点迁移断言;SQL CASE 双读过渡不在此覆盖。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.process_gate_contract import ( + derive_position, + derive_todo_category, + derive_user_mode, +) + + +def test_user_mode_complete_when_rejected(): + assert derive_user_mode( + user_status='completed', + gate_code=None, + review_status='rejected', + lifecycle_stage=None, + ) == 'complete' + + +def test_user_mode_wait_upload_handoff(): + assert derive_user_mode( + user_status='waiting_human', + gate_code='manual_upload_handoff', + review_status=None, + lifecycle_stage='freight_upload', + ) == 'wait_manual_upload' + + +def test_user_mode_must_human(): + assert derive_user_mode( + user_status='waiting_human', + gate_code='inventory_matching', + review_status=None, + lifecycle_stage='fulfillment_prep', + ) == 'must_human' + + +def test_user_mode_auto(): + assert derive_user_mode( + user_status='running', + gate_code='inventory_preparation', + review_status=None, + lifecycle_stage='fulfillment_prep', + ) == 'auto_continue' + + +def test_position_review_dispositions(): + assert derive_position(gate_code=None, review_status='rejected') == 'rejected' + assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue' + assert derive_position(gate_code=None, review_status='rsv_req') == 'rsv_req' + + +def test_position_fulfillment(): + assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending' + assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready' + + +def test_todo_category(): + assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review' + assert derive_todo_category(user_mode='must_human', position='quality_issue') == 'exception' + assert derive_todo_category(user_mode='wait_manual_upload') == 'manual_upload' + assert derive_todo_category(user_mode='complete') == 'done' + assert derive_todo_category(user_mode='auto_continue') == 'in_progress' + + +def test_fetch_gate_positions_empty(): + from app.services.shipping_notice.query_service import fetch_gate_positions + + assert fetch_gate_positions([]) == {} + + +def test_fetch_gate_positions_batched(app): + """关键断言:一次查询按 task_id 返回 current_gate_code / status。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.query_service import fetch_gate_positions + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='GATE-POS') + ot_a = ShippingOrderTask( + task_no='OT-GATE-POS-A', + user_id=user.id, + conversation_id=session.session_id, + status='waiting_review', + stage='step5_match_inventory', + progress_version=1, + ) + ot_b = ShippingOrderTask( + task_no='OT-GATE-POS-B', + user_id=user.id, + conversation_id=session.session_id, + status='processing', + stage='inventory_fetching', + progress_version=1, + ) + db.session.add_all([ot_a, ot_b]) + db.session.flush() + db.session.add_all([ + ShippingProcessExecution( + execution_no='SPE-GATE-POS-A', + task_id=int(ot_a.id), + status='blocked', + current_gate_code='inventory_sufficiency', + ), + ShippingProcessExecution( + execution_no='SPE-GATE-POS-B', + task_id=int(ot_b.id), + status='active', + current_gate_code='inventory_preparation', + ), + ]) + db.session.commit() + + result = fetch_gate_positions([int(ot_a.id), int(ot_b.id), 999999]) + assert result[int(ot_a.id)]['current_gate_code'] == 'inventory_sufficiency' + assert result[int(ot_a.id)]['status'] == 'blocked' + assert result[int(ot_b.id)]['current_gate_code'] == 'inventory_preparation' + assert 999999 not in result + + +def test_early_stop_uses_derive_user_mode(monkeypatch): + from app.services.shipping_notice import progress_workflow as pw + + class FakeTask: + task_no = 'SN-1' + review_status = None + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda t: { + 'current_gate': { + 'status': 'blocked_manual', + 'blocking_reason_code': 'inventory_shortage_review_required', + 'gate_code': 'inventory_sufficiency', + }, + 'responsible_party': 'owner', + 'lifecycle_stage': 'fulfillment_prep', + 'current_gate_code': 'inventory_sufficiency', + 'status': 'blocked', + }, + ) + assert pw._entry_user_mode(FakeTask()) == 'must_human' + + +def test_entry_user_mode_inventory_prep_retryable_stays_auto(monkeypatch): + """ + 回归:候选已冻结但尚未取库存时,sync 可能把 inventory_preparation 投影为 + blocked_retryable + inventory_file_empty;自动推进入口不得判 must_human 早停, + 否则永远进不了 ensure_inventory(复用快照 / 触发 RPA)。 + """ + from app.services.shipping_notice import progress_workflow as pw + + class FakeTask: + task_no = 'OT-INV-EMPTY' + review_status = None + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda t: { + 'current_gate': { + 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_file_empty', + 'gate_code': 'inventory_preparation', + }, + 'current_blocking_gate': { + 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_file_empty', + 'gate_code': 'inventory_preparation', + }, + 'responsible_party': 'worker', + 'lifecycle_stage': 'fulfillment_prep', + 'current_gate_code': 'inventory_preparation', + 'status': 'blocked', + 'blocking_reason_code': 'inventory_file_empty', + }, + ) + assert pw._entry_user_mode(FakeTask()) == 'auto_continue' + + +def test_entry_user_mode_inventory_prep_exhausted_still_must_human(monkeypatch): + """RPA 耗尽属 needs_human,入口仍须早停,不能自动空转重试。""" + from app.services.shipping_notice import progress_workflow as pw + + class FakeTask: + task_no = 'OT-INV-EXHAUSTED' + review_status = None + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda t: { + 'current_blocking_gate': { + 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_rpa_exhausted', + 'gate_code': 'inventory_preparation', + }, + 'lifecycle_stage': 'fulfillment_prep', + 'current_gate_code': 'inventory_preparation', + 'status': 'blocked', + 'blocking_reason_code': 'inventory_rpa_exhausted', + }, + ) + assert pw._entry_user_mode(FakeTask()) == 'must_human' + + +def test_position_inventory_sufficiency(): + assert derive_position(gate_code='inventory_sufficiency', review_status=None) == 'shortage_review' + + +def test_todo_category_from_gate_positions(): + from app.services.shipping_notice.query_service import _todo_category_from_gate + + assert ( + _todo_category_from_gate( + {'current_gate_code': 'order_field_extraction', 'status': 'blocked_manual'}, + None, + ) + == 'review' + ) + assert ( + _todo_category_from_gate( + {'current_gate_code': 'inventory_preparation', 'status': 'active'}, + None, + ) + == 'in_progress' + ) + assert ( + _todo_category_from_gate( + {'current_gate_code': 'inventory_sufficiency', 'status': 'blocked'}, + None, + ) + == 'exception' + ) + + +def test_user_facing_stage_uses_position(monkeypatch): + from app.services.shipping_notice import user_facing_status as ufs + + class FakeTask: + step_payload_json = {} + pending_human_reason = None + lifecycle_status = 'active' + review_status = None + order_task_id = None + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection.task_blocking_reason', + lambda t: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda t: {'current_gate_code': 'inventory_preparation'}, + ) + assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存' + + +def test_derived_entry_surface_review(): + from app.services.shipping_notice.ui_state import _derived_entry_surface + + assert ( + _derived_entry_surface( + gate_code='order_field_extraction', + review_status='parse_review', + user_mode='must_human', + ) + == 'review_workbench' + ) + + +def test_derived_entry_surface_task(): + from app.services.shipping_notice.ui_state import _derived_entry_surface + + assert ( + _derived_entry_surface( + gate_code='artifact_generation', + review_status=None, + user_mode='wait_manual_upload', + ) + == 'task_workbench' + ) + + +def test_summary_prefers_gate_shortage_over_freeze(monkeypatch): + """关键断言:Gate 短缺时摘要不再沿用 OT 默认 order_freeze 文案。""" + from app.services.shipping_notice import ui_state as us + + class FakeTask: + task_no = 'OT-SHORT' + review_status = None + order_task_id = None + updated_at = None + error_message = None + step_payload_json = {} + + monkeypatch.setattr(us, '_build_stp_facts', lambda t: None) + monkeypatch.setattr(us, '_collect_parse_stage_issues', lambda *a, **k: []) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection.task_blocking_reason', + lambda t: 'inventory_shortage_review_required', + ) + monkeypatch.setattr(us, 'user_facing_task_stage', lambda t: '库存不足,无法发货') + monkeypatch.setattr( + 'app.services.shipping_notice.stp_progress_contract.project_task_progress_nodes', + lambda t: [], + ) + summary = us._build_task_summary( + FakeTask(), + 'shortage_review', + user_mode='must_human', + gate_code='inventory_sufficiency', + ) + assert '缺口' in summary['message'] or '库存' in summary['message'] + assert summary['user_mode'] == 'must_human' + assert summary['entry_surface'] == 'task_workbench' + assert summary['next_auto_step'] is None + + +def test_rejected_maps_to_review_disposition(): + assert derive_position(gate_code=None, review_status='rejected') == 'rejected' + + +def test_notice_text_failure_maps_to_quality_issue(): + assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue' + + +def test_sql_todo_category_prefers_gate_inventory_sufficiency(app): + """关键断言:SQL CASE 在 Execution=inventory_sufficiency/blocked 时为 exception。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE') + ot = ShippingOrderTask( + task_no='OT-SQL-GATE-SHORT', + user_id=user.id, + conversation_id=session.session_id, + status='waiting_review', + stage='step5_match_inventory', + progress_version=1, + ) + db.session.add(ot) + db.session.flush() + db.session.add( + ShippingProcessExecution( + execution_no='SPE-SQL-GATE-SHORT', + task_id=int(ot.id), + status='blocked', + current_gate_code='inventory_sufficiency', + ) + ) + db.session.commit() + cat = ( + db.session.query(_order_task_todo_category_sql_expr()) + .filter(ShippingOrderTask.id == ot.id) + .scalar() + ) + assert cat == 'exception' + + +def test_sql_todo_category_prefers_gate_manual_upload(app): + """关键断言:manual_upload_handoff → manual_upload。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE-MU') + ot = ShippingOrderTask( + task_no='OT-SQL-GATE-MU', + user_id=user.id, + conversation_id=session.session_id, + status='waiting_upload', + stage='freight_upload', + progress_version=1, + ) + db.session.add(ot) + db.session.flush() + db.session.add( + ShippingProcessExecution( + execution_no='SPE-SQL-GATE-MU', + task_id=int(ot.id), + status='blocked', + current_gate_code='manual_upload_handoff', + ) + ) + db.session.commit() + cat = ( + db.session.query(_order_task_todo_category_sql_expr()) + .filter(ShippingOrderTask.id == ot.id) + .scalar() + ) + assert cat == 'manual_upload' + + +def test_user_mode_review_status_must_human(): + """复核处置 review_status 在默认 auto 之前映射为 must_human。""" + for rs in ('parse_review', 'rsv_req', 'quality_issue', 'customer_review', 'shortage_review'): + assert derive_user_mode( + user_status='running', + gate_code=None, + review_status=rs, + lifecycle_stage=None, + ) == 'must_human' diff --git a/backend/tests/test_order_document_profile_creation_service.py b/backend/tests/test_order_document_profile_creation_service.py index fe09beeb..1dc2b477 100644 --- a/backend/tests/test_order_document_profile_creation_service.py +++ b/backend/tests/test_order_document_profile_creation_service.py @@ -14,6 +14,8 @@ import pytest from app.extensions import db from app.models import ( + FileAsset, + ShippingOrderDocument, ShippingOrderDocumentProfile, ShippingOrderDocumentProfileAudit, ShippingOrderDocumentProfileDraftRevision, @@ -59,6 +61,9 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi 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 + asset = db.session.get(FileAsset, db.session.get(ShippingOrderDocument, sample.document_id).asset_id) + assert asset.lifecycle_status == 'referenced' + assert int(asset.reference_count or 0) >= 1 assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1 assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id, revision_no=1).count() == 1 assert ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile_id).count() == 1 diff --git a/backend/tests/test_order_document_profile_preview_service.py b/backend/tests/test_order_document_profile_preview_service.py index ba19c61b..be6f1402 100644 --- a/backend/tests/test_order_document_profile_preview_service.py +++ b/backend/tests/test_order_document_profile_preview_service.py @@ -8,6 +8,8 @@ backend/tests/test_order_document_profile_preview_service.py from __future__ import annotations +import gzip +import json from types import SimpleNamespace import numpy as np @@ -15,7 +17,13 @@ import pytest from app import db from app.core.auth.jwt import issue_local_access_token -from app.models import FileAsset, ShippingOrderDocumentProfileSample, ShippingOrderDocument, User +from app.models import ( + FileAsset, + ShippingDocumentLayoutVersion, + ShippingOrderDocumentProfileSample, + ShippingOrderDocument, + User, +) from app.services.shipping_notice import document_profile_quality_service as quality_service from app.services.shipping_notice import order_document_profile_preview_service as preview_service from app.services.shipping_notice import order_document_profile_service as profile_service @@ -120,6 +128,62 @@ def test_frozen_sample_preview_authorizes_once_and_cannot_replay(app, monkeypatc assert parse_api_error(replay.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND' +def test_frozen_sample_preview_recovers_legacy_table_page_count_when_frozen_evidence_has_all_pages( + app, monkeypatch, admin_headers_factory, +): + """历史快照把页数误记为表格页数时,仅可由同一冻结证据中的完整物理页数修复预览。""" + with app.app_context(): + monkeypatch.setattr(quality_service, 'assert_profile_publishable', lambda _profile: None) + schema = _schema_version() + draft = profile_service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample( + draft['id'], + sample_role='annotation', + physical_page_count=2, + include_top_level_pages=False, + ) + published = profile_service.publish( + draft['id'], actor_id=None, expected_lock_version=draft['lock_version'], + ) + profile_id = int(published['id']) + sample_id = int(sample.id) + # 模拟修复上线前已发布的历史记录:页数被退化为仅第一页业务表。 + sample.page_count_snapshot = 1 + layout_version = db.session.get(ShippingDocumentLayoutVersion, sample.layout_version_id) + evidence_ref = (layout_version.payload_json or {}).get('coordinate_evidence_ref') + assert isinstance(evidence_ref, dict) + evidence_asset_no = str(evidence_ref['asset_no']) + db.session.commit() + + preview_store = _PreviewStore() + monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store) + coordinate_evidence_bytes = gzip.compress(json.dumps({ + 'pages': {'1': {'width': 200, 'height': 100}, '2': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]}, + 'tables': {'sample-table': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]}, + }).encode('utf-8')) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', + lambda asset: coordinate_evidence_bytes if asset.asset_no == evidence_asset_no else b'%PDF-frozen-preview', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + lambda _content, render_scale: [ + SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8)), + SimpleNamespace(page_no=2, image=np.full((12, 12, 3), 255, dtype=np.uint8)), + ], + ) + + client = app.test_client() + response = client.post( + f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages', + headers=admin_headers_factory('frozen-preview-legacy-page-count'), + ) + + assert response.status_code == 200 + assert parse_api_data(response.get_json())['page_count'] == 2 + + def test_publishing_profile_retains_sample_asset_for_history_preview(app, monkeypatch): """发布冻结样本必须清除临时 TTL,否则历史版本过期后无法读取 PDF。""" profile_id, _sample_id, document_id = _publish_profile_with_frozen_sample(app, monkeypatch) diff --git a/backend/tests/test_order_document_profile_validation_service_xfa_phase4.py b/backend/tests/test_order_document_profile_validation_service_xfa_phase4.py index 056beb8d..042571c9 100644 --- a/backend/tests/test_order_document_profile_validation_service_xfa_phase4.py +++ b/backend/tests/test_order_document_profile_validation_service_xfa_phase4.py @@ -336,6 +336,9 @@ def test_xfa_layout_signature_becomes_stale_after_definition_change(app, _patch_ 'sample_document_id': ShippingOrderDocumentProfileSample.query.filter_by( profile_id=draft['id'], sample_role='annotation', ).first().document_id, + # 本变更将 bind-po-001 改名为 bind-po-002(字段/值源未变), + # 正式 XFA 按 binding_id 身份识别删除,故显式确认该身份变更。 + 'allow_formal_binding_deletions': ['bind-po-001'], }, actor_id=user.id, profile_id=draft['id'], browser_session_id='xfa-p4-tab', lease_token=lease['lease_token'], diff --git a/backend/tests/test_order_extraction_merge.py b/backend/tests/test_order_extraction_merge.py index 765e306e..42e42301 100644 --- a/backend/tests/test_order_extraction_merge.py +++ b/backend/tests/test_order_extraction_merge.py @@ -175,12 +175,12 @@ def test_same_po_conflicting_reservations_do_not_merge_lines(): def test_same_po_conflicting_line_no_does_not_merge_same_part_number(): - """料号一致但双方都有不同项次时,不能忽略项次而错误补入 Reservation。""" + """料号一致但双方都有不同客户项次(customer_po_line_no)时,不能忽略项次而错误补入 Reservation。""" pdf_line = _partial_line(1, part='PN-1', qty=30) pdf_line['fields'].append(_field('line-id', '00010', 1)) email_line = _partial_line(2, part='PN-1', reservation='1000123456') email_line['fields'].append(_field('line-id', '00020', 2)) - definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'line_no'}]} + definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'customer_po_line_no'}]} merged = merge_unit_orders( orders=[_partial_order(1, lines=[pdf_line]), _partial_order(2, lines=[email_line])], diff --git a/backend/tests/test_shipping_auto_progress_p0_3.py b/backend/tests/test_shipping_auto_progress_p0_3.py index acb1b3e6..d5d9f22c 100644 --- a/backend/tests/test_shipping_auto_progress_p0_3.py +++ b/backend/tests/test_shipping_auto_progress_p0_3.py @@ -4,7 +4,8 @@ tests/test_shipping_auto_progress_p0_3.py 用途:锁定 P0-3 正式 AutoProgress 的 Task 串行、单 Gate、版本围栏及人工回执合同。 依赖:pytest、SQLAlchemy 测试库、auto_progress_controller。 逻辑:直接构造 Task/Candidate/Execution 事实,避免旧 STP 协调器的过期 mock;验证 Job outbox - 仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链。 + 仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链; + 显式 retry_rpa 覆盖 waiting_external 残留 poll。 """ from __future__ import annotations @@ -207,6 +208,62 @@ def test_submit_does_not_redispatch_after_failed_worker_attempt(app): assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1 +def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None: + """waiting_external + 残留 poll 时,显式 retry_rpa 必须改入队 retry_inventory_preparation。 + + 回归背景:行级改源 / 强制获取库存调用 run_task_auto_progress(inventory_mode=retry_rpa) + 后,submit_auto_progress 只改 Execution 指针、不改 Gate.next_action_code,继续入队 + poll;poll 遇失败 Preparation 直接收口,表现为「改源已保存但 RPA 不触发」。 + """ + task = _task_with_candidate() + execution = ensure_execution_for_workflow_version(review_case_id=905, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_source_routing', + reason='test_review_confirmed', + ) + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_preparation', + ).one() + gate.status = 'waiting_external' + gate.blocking_reason_code = 'inventory_rpa_export_failed' + gate.next_action_code = 'poll_inventory_preparation' + execution.status = 'waiting_external' + execution.current_gate_code = 'inventory_preparation' + execution.primary_next_action_code = 'poll_inventory_preparation' + execution.responsible_party = 'worker' + task.active_process_execution_id = int(execution.id) + db.session.commit() + + with patch( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + ), patch( + 'app.services.shipping_notice.process_gate_job_service.cancel_inventory_external_wait_polls', + return_value=0, + ): + result = submit_auto_progress( + task=task, + trigger='manual_override_source', + resume_gate_code='inventory_preparation', + inventory_mode='retry_rpa', + commit=True, + ) + + db.session.refresh(gate) + # 关键断言:显式重抓必须入队 retry_inventory_preparation(而非残留 poll)。 + assert result['status'] == 'queued' + assert result.get('reused') is False + queued = ( + ShippingProcessGateAttempt.query + .filter_by(gate_id=int(gate.id), status='queued') + .order_by(ShippingProcessGateAttempt.attempt_no.desc()) + .first() + ) + assert queued is not None + assert (queued.input_snapshot_json or {}).get('action_code') == 'retry_inventory_preparation' + assert ((queued.input_snapshot_json or {}).get('payload') or {}).get('inventory_mode') == 'retry_rpa' + + def test_active_stp_job_without_retry_metadata_is_reused(app): """活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。""" from types import SimpleNamespace @@ -319,7 +376,7 @@ def test_retry_inventory_matching_fulfillable_passes(): query = MagicMock(get=MagicMock(return_value=_Task())) with patch('app.services.shipping_notice.fulfillment_workflow.match_inventory', return_value={ - 'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'checkpoint': None, + 'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'position': None, }), patch('app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', return_value=None), \ patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \ patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \ diff --git a/backend/tests/test_shipping_excel_template.py b/backend/tests/test_shipping_excel_template.py index 880a3645..75f25409 100644 --- a/backend/tests/test_shipping_excel_template.py +++ b/backend/tests/test_shipping_excel_template.py @@ -78,6 +78,26 @@ def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fac ]) is True +def test_unique_notice_warehouse_id_for_header_mapping(): + """Header 写 warehouse_id:唯一库位放行,多库位拒绝,空库位返回 None。""" + from types import SimpleNamespace + from app.services.shipping_notice.export import _unique_notice_warehouse_id + + assert _unique_notice_warehouse_id([ + SimpleNamespace(inventory_warehouse_id='AWSSG'), + SimpleNamespace(inventory_warehouse_id='awssg'), + ]) == 'AWSSG' + assert _unique_notice_warehouse_id([ + SimpleNamespace(inventory_warehouse_id=None), + SimpleNamespace(inventory_warehouse_id=''), + ]) is None + with pytest.raises(ValueError, match='多库位'): + _unique_notice_warehouse_id([ + SimpleNamespace(inventory_warehouse_id='AWSSG'), + SimpleNamespace(inventory_warehouse_id='MOW'), + ]) + + def _freeze_export_snapshot( task: ShippingOrderTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion, *, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None, diff --git a/backend/tests/test_shipping_gate_orchestration_separation.py b/backend/tests/test_shipping_gate_orchestration_separation.py new file mode 100644 index 00000000..a7f1d2dd --- /dev/null +++ b/backend/tests/test_shipping_gate_orchestration_separation.py @@ -0,0 +1,348 @@ +""" +tests/test_shipping_gate_orchestration_separation.py + +用途:锁定履约 Gate「匹配 Attempt 不内嵌 Excel / 匹配通过后续跑独立 artifact Attempt」。 +依赖:pytest、fulfillment_workflow.try_auto_chain_after_match、process_gate_executor、 + process_gate_bridge、process_gate_service、auto_progress fixtures。 +逻辑:Gate 路径(_orchestrator_internal_dispatch)禁止 generate/upload; + match pass + sync 后须留下可自动投递的 artifact_generation Attempt。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +from app import db +from app.models import ( + Job, + ShippingInventoryCandidateSet, + ShippingOrderTask, + ShippingProcessGate, + ShippingProcessGateAttempt, +) +from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match +from app.services.shipping_notice.process_gate_bridge import ( + mark_gates_passed_through, + sync_fulfillment_gates_from_task, +) +from app.services.shipping_notice.process_gate_service import ( + complete_gate_attempt, + ensure_execution_for_workflow_version, + queue_gate_attempt, +) + + +def _task_with_candidate(*, task_no: str = 'OT-ORCH-SEP-001') -> ShippingOrderTask: + """创建带冻结候选集的正式 OT,供 20-Gate Execution 绑定。""" + task = ShippingOrderTask(task_no=task_no, user_id=1) + db.session.add(task) + db.session.flush() + candidate = ShippingInventoryCandidateSet( + task_id=task.id, + set_version=1, + lifecycle_status='frozen', + input_fingerprint='b' * 64, + ) + db.session.add(candidate) + db.session.flush() + task.active_inventory_candidate_set_id = candidate.id + task.current_order_extraction_id = 101 + task.order_snapshot_id = 201 + db.session.commit() + return task + + +def _patch_fulfillable_inventory(monkeypatch) -> None: + """让 sync_fulfillment 能越过 prep,到达 excel_readiness / artifact。""" + inv_file = SimpleNamespace( + id=1, + snapshot_status='ready', + invalidated_at=None, + mapping_confirmed=True, + source_query_json={}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task', + lambda _task: inv_file, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.active_inventory_lines_for_task', + lambda _task: [{'reservation_id': 'R1', 'part_number': 'P1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge._derived_fulfillment_status', + lambda _task: 'matched', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_completed', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.excel_gate_error', + lambda _task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: None, + ) + + +def test_try_auto_chain_gate_path_does_not_call_generate_or_upload(app, monkeypatch) -> None: + """Gate Attempt 路径:try_auto_chain 不得同 Attempt 内嵌 generate_excel / upload。""" + with app.app_context(): + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True + + task = ShippingOrderTask(task_no='OT-ORCH-CHAIN-0', user_id=1) + db.session.add(task) + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow._current_export_artifact', + lambda _task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.excel_gate_error', + lambda _task: None, + ) + + generate_calls: list[dict] = [] + upload_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.upload_to_freight', + lambda payload: upload_calls.append(dict(payload or {})) or {'status': 'running'}, + ) + + result = try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched'}, + payload={ + 'task_id': task.task_no, + '_orchestrator_internal_dispatch': True, + 'source': 'process_gate', + }, + ) + + assert result['status'] == 'ok' + assert generate_calls == [] + assert upload_calls == [] + + +def test_match_handler_fulfillable_does_not_call_generate_excel(app, monkeypatch) -> None: + """inventory_matching Handler 成功履约时不得调用 generate_excel。""" + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching + + with app.app_context(): + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + _patch_fulfillable_inventory(monkeypatch) + + task = _task_with_candidate(task_no='OT-ORCH-SEP-HANDLER') + execution = ensure_execution_for_workflow_version(review_case_id=9201, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_field_mapping', + reason='test_orch_sep', + ) + task.active_process_execution_id = int(execution.id) + db.session.commit() + + generate_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory', + lambda payload: try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched', 'task_id': task.task_no}, + payload=payload, + ), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}}, + ) + + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='inventory_matching', + ).one() + result = _handle_retry_inventory_matching( + execution=execution, + gate=gate, + payload={'actor_user_id': 1}, + ) + + assert result['outcome'] == 'passed' + assert generate_calls == [] + + db.session.refresh(execution) + artifact_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='artifact_generation', + ).one() + assert artifact_gate.status != 'passed' + assert artifact_gate.next_action_code == 'regenerate_excel_artifact' + + +def test_match_pass_enqueues_artifact_generation_attempt(app, monkeypatch) -> None: + """匹配事实就绪且无 Artifact 时,submit_auto_progress 须入队 artifact Attempt。""" + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + + with app.app_context(): + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_MATCH_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True + _patch_fulfillable_inventory(monkeypatch) + + task = _task_with_candidate(task_no='OT-ORCH-SEP-ENQ') + execution = ensure_execution_for_workflow_version(review_case_id=9202, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_field_mapping', + reason='test_orch_sep_enqueue', + ) + task.active_process_execution_id = int(execution.id) + db.session.commit() + + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=None, + ) + + matching_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='inventory_matching', + ).one() + if matching_gate.status != 'passed': + attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code='inventory_matching', + trigger_type='auto', + actor_type='system', + actor_id=None, + idempotency_key=f'test-orch-sep-match:{execution.id}', + expected_gate_version=int(matching_gate.evaluation_version), + input_snapshot={'action_code': 'retry_inventory_matching', 'payload': {}}, + ) + assert attempt is not None + complete_gate_attempt( + attempt_id=int(attempt.id), + outcome='passed', + output_snapshot={'action_code': 'retry_inventory_matching'}, + effective_result_json={'match_status': 'fulfillable'}, + ) + + db.session.refresh(execution) + artifact_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='artifact_generation', + ).one() + assert artifact_gate.status != 'passed' + assert artifact_gate.next_action_code == 'regenerate_excel_artifact' + + queued = submit_auto_progress(task=task, trigger='user_retry', commit=True) + assert queued.get('status') in {'queued', 'running'} + assert queued.get('gate_code') == 'artifact_generation' + attempt = db.session.get(ShippingProcessGateAttempt, int(queued['attempt_id'])) + assert attempt is not None + assert isinstance(attempt.input_snapshot_json, dict) + assert attempt.input_snapshot_json.get('action_code') == 'regenerate_excel_artifact' + assert Job.query.filter_by(id=int(queued['job_id'])).one().job_type == 'shipping_process_gate' + + +def test_happy_path_generate_excel_only_in_artifact_attempt(app, monkeypatch) -> None: + """端到端:match Handler 不生成;artifact Handler 才调用 generate_excel 一次。""" + from app.services.shipping_notice.process_gate_executor import ( + _handle_regenerate_excel, + _handle_retry_inventory_matching, + ) + + with app.app_context(): + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = False + _patch_fulfillable_inventory(monkeypatch) + + task = _task_with_candidate(task_no='OT-ORCH-SEP-E2E') + execution = ensure_execution_for_workflow_version(review_case_id=9203, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_field_mapping', + reason='test_orch_sep_e2e', + ) + task.active_process_execution_id = int(execution.id) + db.session.commit() + + generate_calls: list[dict] = [] + + def _fake_generate(payload): + generate_calls.append(dict(payload or {})) + artifact = SimpleNamespace( + id=99, + file_path='/tmp/orch-sep.xlsx', + file_name='orch-sep.xlsx', + status='ready', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: artifact, + ) + return {'status': 'ok', 'message': 'excel-ok'} + + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + _fake_generate, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory', + lambda payload: try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched', 'task_id': task.task_no}, + payload=payload, + ), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}}, + ) + + matching_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='inventory_matching', + ).one() + match_result = _handle_retry_inventory_matching( + execution=execution, + gate=matching_gate, + payload={'actor_user_id': 1}, + ) + assert match_result['outcome'] == 'passed' + assert generate_calls == [] + + # match handler 内 sync 已投影 artifact;禁止再 force sync matching(会 allow_repass + # 入队 artifact Attempt,把 next_action 清成 queued→None)。 + db.session.refresh(execution) + artifact_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='artifact_generation', + ).one() + assert artifact_gate.status != 'passed' + assert artifact_gate.next_action_code == 'regenerate_excel_artifact' + + artifact_result = _handle_regenerate_excel( + execution=execution, + gate=artifact_gate, + payload={'actor_user_id': 1}, + ) + assert artifact_result.get('outcome') == 'passed' + assert len(generate_calls) == 1 + assert generate_calls[0].get('_orchestrator_internal_dispatch') is True diff --git a/backend/tests/test_shipping_inventory_link_ot_owner.py b/backend/tests/test_shipping_inventory_link_ot_owner.py new file mode 100644 index 00000000..b22d7613 --- /dev/null +++ b/backend/tests/test_shipping_inventory_link_ot_owner.py @@ -0,0 +1,75 @@ +""" +tests/test_shipping_inventory_link_ot_owner.py + +用途:锁定库存 Link 挂在正式 OT 上;传入 ShippingNotice 时仍须解析到该 OT 的 active link。 +依赖:pytest、inventory_file_store.active_inventory_file_for_task / resolve_inventory_lines_for_execution。 +逻辑:复现「Notice.id ≠ OT.id → Excel 导出读到 0 行库存」回归。 +""" + +from __future__ import annotations + +from app import db +from app.models import ( + ShippingInventoryFile, + ShippingNotice, + ShippingOrderTask, + ShippingTaskInventoryLink, +) +from app.services.shipping_notice.inventory_file_store import ( + active_inventory_file_for_task, + resolve_inventory_lines_for_execution, +) + + +def test_active_inventory_file_for_notice_uses_order_task_link(app, tmp_path) -> None: + """Notice 导出路径必须通过 order_task_id 找到挂在 OT 上的库存 Link。""" + with app.app_context(): + inventory_path = tmp_path / 'ot-owned-inventory.xlsx' + inventory_path.write_bytes(b'inventory-rows') + + # 先占用 Notice 自增 id=1,确保后续正式 Notice.id ≠ OT.id(复现生产错位)。 + db.session.add(ShippingNotice( + task_no='SN-INV-LINK-BURN', + user_id=1, + source_type='manual', + )) + db.session.flush() + + ot = ShippingOrderTask(task_no='OT-INV-LINK-OWNER', user_id=1, source_type='direct_pdf') + inventory_file = ShippingInventoryFile( + inventory_file_no='SIF-INV-LINK-OWNER', + storage_path=str(inventory_path), + source_file_name='ot-owned-inventory.xlsx', + snapshot_status='ready', + inventory_lines_json=[ + {'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001'}, + ], + line_count=1, + ) + db.session.add_all([ot, inventory_file]) + db.session.flush() + + notice = ShippingNotice( + task_no='SN-INV-LINK-OWNER', + user_id=1, + source_type='inventory_gate', + order_task_id=int(ot.id), + ) + db.session.add(notice) + db.session.flush() + assert int(notice.id) != int(ot.id) + + db.session.add(ShippingTaskInventoryLink( + task_id=int(ot.id), + inventory_file_id=int(inventory_file.id), + is_active=True, + access_mode='readonly', + )) + db.session.commit() + + # 断言:不得用 Notice.id 查 Link(会 miss);必须落到 OT Link。 + assert active_inventory_file_for_task(ot) is not None + assert active_inventory_file_for_task(ot).id == inventory_file.id + assert active_inventory_file_for_task(notice) is not None + assert active_inventory_file_for_task(notice).id == inventory_file.id + assert len(resolve_inventory_lines_for_execution(notice)) == 1 diff --git a/backend/tests/test_shipping_inventory_source_adjudication.py b/backend/tests/test_shipping_inventory_source_adjudication.py new file mode 100644 index 00000000..95c71c06 --- /dev/null +++ b/backend/tests/test_shipping_inventory_source_adjudication.py @@ -0,0 +1,152 @@ +""" +tests/test_shipping_inventory_source_adjudication.py + +用途:锁定库存源裁决不得在 unresolved/空候选时兜底全部启用源,并采纳行级 ambiguous。 +依赖:inventory_source_rules、inventory_routing_engine、pytest monkeypatch。 +逻辑:用可控引擎结果复现 OT-C68 类缺陷——行级 PREFIX 多候选被丢弃后膨胀为全源。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +from app.services.shipping_notice.inventory_routing_engine import InventoryRoutingResult +from app.services.shipping_notice import inventory_source_rules as rules + + +def _source(code: str) -> dict: + """构造最小可裁决库存源字典。""" + return { + 'source_code': code, + 'display_name': code, + 'connector_type': 'dbs', + 'warehouse_resolution_mode': 'fixed', + 'fixed_warehouse_id': code, + } + + +def test_result_to_adjudication_unresolved_keeps_empty_candidates(monkeypatch): + """ + unresolved 且规则候选为空时,candidates 必须为空。 + + 关键断言:禁止 list_database_inventory_sources 全源兜底(OT-C68 根因之一)。 + """ + all_sources = [_source(f'SRC_{i}') for i in range(9)] + called = {'list_all': False} + + monkeypatch.setattr( + rules, + 'list_database_inventory_sources', + lambda: (called.__setitem__('list_all', True) or all_sources), + ) + monkeypatch.setattr(rules, 'get_database_inventory_source', lambda code: None) + monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1') + monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp') + + result = InventoryRoutingResult( + 'unresolved', + (), + (), + {'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []}, + ) + adjudication = rules._result_to_adjudication(result, context={}) + + assert adjudication.status == 'unresolved' + assert adjudication.reason == 'routing_rule_unresolved' + assert adjudication.candidates == [] + assert called['list_all'] is False + + +def test_result_to_adjudication_ambiguous_only_keeps_rule_sources(monkeypatch): + """ + ambiguous 多候选只保留规则给出的源;缺失 DB 配置的源不得用全库补齐。 + """ + monkeypatch.setattr( + rules, + 'list_database_inventory_sources', + lambda: [_source('SHOULD_NOT_APPEAR'), _source('ALSO_NO')], + ) + monkeypatch.setattr( + rules, + 'get_database_inventory_source', + lambda code: _source(code) if code in {'A', 'B'} else None, + ) + monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1') + monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp') + + result = InventoryRoutingResult( + 'ambiguous', + ('A', 'B', 'MISSING'), + (33,), + { + 'priority': 100, + 'matched_rules': ['ROUTE_RESERVATION_PREFIX_2'], + 'raw_source_codes': ['A', 'B', 'MISSING'], + }, + ) + adjudication = rules._result_to_adjudication(result, context={}) + + assert adjudication.status == 'ambiguous' + assert [item['source_code'] for item in adjudication.candidates] == ['A', 'B'] + + +def test_adjudicate_accepts_unanimous_line_ambiguous(monkeypatch): + """ + 任务级 unresolved、各行一致 ambiguous 时,必须采纳行级候选,不得回落全源。 + + 复现:Reservation 前缀规则给出 3 源 ambiguous,旧逻辑返回 9 个启用源。 + """ + line_ambiguous = InventoryRoutingResult( + 'ambiguous', + ('DSV360_AWSBI_BYAWSCMH01', 'DSV360_AWSBI_BYAWSFRA01', 'DSV360_AWSCV'), + (33,), + { + 'priority': 100, + 'matched_rules': ['ROUTE_RESERVATION_PREFIX_2'], + 'raw_source_codes': [ + 'DSV360_AWSBI_BYAWSCMH01', + 'DSV360_AWSBI_BYAWSFRA01', + 'DSV360_AWSCV', + ], + }, + ) + task_unresolved = InventoryRoutingResult( + 'unresolved', + (), + (), + {'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []}, + ) + + def _evaluate(*, task, line=None, now=None): + del task, now + return task_unresolved if line is None else line_ambiguous + + monkeypatch.setattr(rules, 'evaluate_inventory_source_rules', _evaluate) + monkeypatch.setattr(rules, 'extract_routing_context', lambda _task: {}) + monkeypatch.setattr( + rules, + '_task_routing_lines', + lambda _task, required=None: [{'reservation_id': '2000488715', '_position': 0}], + ) + monkeypatch.setattr( + rules, + 'get_database_inventory_source', + lambda code: _source(code), + ) + monkeypatch.setattr( + rules, + 'list_database_inventory_sources', + lambda: [_source(f'EXTRA_{i}') for i in range(9)], + ) + monkeypatch.setattr(rules, 'inventory_sources_runtime_version', lambda: 'test-v1') + monkeypatch.setattr(rules, 'compute_routing_fingerprint', lambda _ctx: 'fp') + + adjudication = rules.adjudicate_inventory_source(SimpleNamespace(id=1)) + + assert adjudication.status == 'ambiguous' + assert [item['source_code'] for item in adjudication.candidates] == [ + 'DSV360_AWSBI_BYAWSCMH01', + 'DSV360_AWSBI_BYAWSFRA01', + 'DSV360_AWSCV', + ] + assert adjudication.reason == 'routing_rule_ambiguous' diff --git a/backend/tests/test_shipping_line_scoped_inventory_retry.py b/backend/tests/test_shipping_line_scoped_inventory_retry.py new file mode 100644 index 00000000..85bbfdbd --- /dev/null +++ b/backend/tests/test_shipping_line_scoped_inventory_retry.py @@ -0,0 +1,245 @@ +""" +tests/test_shipping_line_scoped_inventory_retry.py + +用途:守门明细行重抓/重匹配按行 source_codes 收窄,且不伤已发通知行。 +依赖:pytest pure_unit、process_gate_executor、recovery_invalidation_service。 +逻辑:与 display-and-button-contract §6.1 行级收窄约定对齐;不启 Flask/DB。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +pytestmark = pytest.mark.pure_unit + + +def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch): + """行级重抓必须把该行 source_codes 交给 ensure_inventory,并收窄失效范围。""" + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation + + task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-SCOPE') + captured: list[dict] = [] + invalidate_calls: list[dict] = [] + line = SimpleNamespace(source_codes_json=['DBS']) + candidate_set = SimpleNamespace(id=1) + sources = [SimpleNamespace(source_code='DBS')] + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_order_task', + lambda _execution: task, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: candidate_set, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines', + lambda _task: [line], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources', + lambda _task: sources, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_line_inventory_scope', + lambda _task, *, line_scope_key=None: { + 'snapshot_line_id': 1001, + 'line_no': 2, + 'source_codes': ['WH_A'], + } if line_scope_key not in (None, '') else None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream', + lambda **kwargs: invalidate_calls.append(dict(kwargs)) or {}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'rpa': {}}}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_preparation_failed', + ) + 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: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True}, + ) + + _handle_retry_inventory_preparation( + execution=SimpleNamespace(task_id=1, id=21, candidate_set_id=None), + gate=SimpleNamespace(gate_code='inventory_preparation'), + payload={ + 'action_code': 'retry_inventory_preparation', + 'actor_user_id': 5, + 'snapshot_line_id': 1001, + }, + ) + + # 关键断言:行级强制 RPA 只带该行源,失效也按同行源收窄。 + assert captured[-1].get('mode') == 'retry_rpa' + assert captured[-1].get('source_codes') == ['WH_A'] + assert captured[-1].get('snapshot_line_id') == 1001 + assert invalidate_calls[-1].get('source_codes') == ['WH_A'] + assert invalidate_calls[-1].get('snapshot_line_id') == 1001 + + +def test_inventory_matching_line_scope_uses_match_inventory_line(monkeypatch): + """行级重匹配必须走 match_inventory_line,并携带该行 source_codes。""" + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching + + task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-MATCH') + match_calls: list[dict] = [] + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_order_task', + lambda _execution: task, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_line_inventory_scope', + lambda _task, *, line_scope_key=None: { + 'snapshot_line_id': 1002, + 'line_no': 3, + 'source_codes': ['WH_B'], + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._task_payload', + lambda _execution, _payload: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory_line', + lambda payload, *, line_no: match_calls.append({'payload': dict(payload), 'line_no': line_no}) + or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory', + lambda _payload: (_ for _ in ()).throw(AssertionError('整单 match_inventory 不应被行级点击调用')), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_completed', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {}, + ) + + result = _handle_retry_inventory_matching( + execution=SimpleNamespace(task_id=1, id=21), + gate=SimpleNamespace(gate_code='inventory_matching'), + payload={'action_code': 'retry_inventory_matching', 'snapshot_line_id': 1002, 'actor_user_id': 5}, + ) + + assert match_calls and match_calls[0]['line_no'] == 3 + assert match_calls[0]['payload'].get('source_codes') == ['WH_B'] + assert result['outcome'] == 'passed' + + +def test_line_scoped_invalidation_skips_noticed_lines_and_artifacts(monkeypatch): + """行级失效不得改写已发通知行匹配,也不得 supersede 已有 Notice Artifact。""" + from app.services.shipping_notice import recovery_invalidation_service as svc + + link_a = SimpleNamespace( + id=11, inventory_file_id=101, matched_source_code='WH_A', + is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None, + ) + link_b = SimpleNamespace( + id=12, inventory_file_id=102, matched_source_code='WH_B', + is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None, + ) + match_open = SimpleNamespace( + id=21, snapshot_line_id=1001, inventory_source_code='WH_A', + allowed_source_codes_snapshot=['WH_A'], is_current=True, + invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None, + ) + match_noticed = SimpleNamespace( + id=22, snapshot_line_id=1002, inventory_source_code='WH_A', + allowed_source_codes_snapshot=['WH_A'], is_current=True, + invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None, + ) + + class _Query: + def __init__(self, rows): + self._rows = rows + + def filter_by(self, **_kwargs): + return self + + def with_for_update(self): + return self + + def all(self): + return list(self._rows) + + def filter(self, *_a, **_k): + return self + + monkeypatch.setattr(svc, '_noticed_snapshot_line_ids', lambda _task_id: {1002}) + monkeypatch.setattr(svc, 'invalidate_downstream_gates', lambda **_: ['inventory_matching']) + monkeypatch.setattr(svc.db.session, 'get', lambda *_a, **_k: SimpleNamespace(id=1)) + monkeypatch.setattr(svc.db.session, 'flush', lambda: None) + # 纯单测不启 Flask:替换模块内模型符号,避免触碰 Flask-SQLAlchemy query 描述符。 + monkeypatch.setattr( + svc, + 'ShippingTaskInventoryLink', + SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([link_a, link_b]))), + ) + monkeypatch.setattr( + svc, + 'ShippingNoticeLineInventoryMatch', + SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([match_open, match_noticed]))), + ) + monkeypatch.setattr( + svc, + 'ShippingInventoryMapping', + SimpleNamespace( + inventory_file_id=SimpleNamespace(in_=lambda _ids: True), + status='active', + query=SimpleNamespace(filter=lambda *_a, **_k: _Query([])), + ), + ) + monkeypatch.setattr( + svc, + 'ShippingNotice', + SimpleNamespace( + query=SimpleNamespace( + filter_by=lambda **_: (_ for _ in ()).throw(AssertionError('行级失效不得查询 Notice Artifact')) + ) + ), + ) + + result = svc.invalidate_inventory_downstream( + execution=SimpleNamespace(task_id=1), + action_code='retry_inventory_preparation', + attempt_id=9, + source_codes=['WH_A'], + snapshot_line_id=1001, + ) + + assert link_a.is_active is False + assert link_b.is_active is True + assert match_open.is_current is False + assert match_noticed.is_current is True + assert result['links'] == [11] + assert result['matches'] == [21] + assert result['artifacts'] == [] + assert result['uploads'] == [] diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 568df7a0..f4d64b3a 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -306,6 +306,86 @@ def test_inventory_loaded_response_syncs_affected_order_task_progress(monkeypatc assert synced == [task, linked_task] +def test_inventory_loaded_response_reuse_skips_file_line_overwrite(monkeypatch): + """[断言] persist_lines=False 时只推进状态,禁止调用写回 File.inventory_lines_json。""" + from app.services.shipping_notice import inventory_mapping_workflow as workflow + + owner_task = SimpleNamespace(id=1, task_no='OT-REUSE-NO-WRITE') + linked_task = SimpleNamespace(id=2, task_no='OT-REUSE-LINKED') + inventory_file = SimpleNamespace( + inventory_file_no='INV-SHARED', + inventory_lines_json=[{'part_number': 'KEEP', 'qty': 9}], + links=[ + SimpleNamespace(is_active=True, task=owner_task), + SimpleNamespace(is_active=True, task=linked_task), + ], + ) + apply_calls: list[object] = [] + + monkeypatch.setattr(workflow, 'active_inventory_file_for_task', lambda _task: inventory_file) + monkeypatch.setattr( + workflow, + 'apply_inventory_parse_result_to_linked_tasks', + lambda *args, **kwargs: apply_calls.append((args, kwargs)) or [owner_task], + ) + monkeypatch.setattr(workflow, '_can_relink_inventory', lambda _task: True) + monkeypatch.setattr(workflow, 'task_line_purpose_values', lambda _task: []) + monkeypatch.setattr(workflow, 'build_field_alignment_preview', lambda *_a, **_k: {}) + monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_a, **_k: None) + monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_a, **_k: None) + monkeypatch.setattr(workflow, 'log_task_event', lambda *_a, **_k: None) + monkeypatch.setattr(workflow, 'serialize_task_for_tool', lambda _task: {}) + monkeypatch.setattr(workflow, 'tool_response', lambda **kwargs: kwargs) + monkeypatch.setattr(workflow.db.session, 'flush', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.order_task_stage_machine.sync_order_task_stage_for_notice', + lambda _notice: None, + ) + + response = workflow.inventory_loaded_response( + owner_task, + [{'part_number': 'MERGED', 'qty': 1, '__source_code': 'SRC_A'}], + source='snapshot_reuse', + event_type='inventory_snapshot_reused', + commit=False, + persist_lines=False, + ) + + assert apply_calls == [] + assert inventory_file.inventory_lines_json == [{'part_number': 'KEEP', 'qty': 9}] + assert response['status'] == 'ok' + assert response['data']['persist_lines'] is False + + +def test_resolve_inventory_lines_prefers_candidate_prep_when_frozen(monkeypatch): + """[断言] 冻结候选 OT 匹配输入取 prepare 合并行,不依赖 active File 上的单源缓存。""" + from app.services.shipping_notice import inventory_file_store as store + + task = SimpleNamespace(id=88, task_no='OT-RESOLVE-CAND') + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['SRC_A', 'SRC_B'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'ready', + 'lines': [ + {'part_number': 'P1', '__source_code': 'SRC_A'}, + {'part_number': 'P2', '__source_code': 'SRC_B'}, + ], + }, + ) + monkeypatch.setattr( + store, + 'active_inventory_file_for_task', + lambda _task: (_ for _ in ()).throw(AssertionError('must not fall back to active file')), + ) + + rows = store.resolve_inventory_lines_for_execution(task) + assert [row['__source_code'] for row in rows] == ['SRC_A', 'SRC_B'] + + def test_inventory_loaded_response_clears_stale_match_state(monkeypatch): """库存重新载入/复用后必须清空任务级旧匹配结果,避免旧缺货/旧 match_status 残留。""" from app.services.shipping_notice import inventory_mapping_workflow as workflow @@ -2191,7 +2271,7 @@ def test_stp_multi_candidate_missing_files_auto_triggers_probe(monkeypatch, app) }, ) - def _fake_probe(actual_task, *, mode, allow_auto_retry=True): + def _fake_probe(actual_task, *, mode, allow_auto_retry=True, source_codes=None): probe_calls.append((actual_task, mode)) return SimpleNamespace( pending_source_codes=['SRC_A', 'SRC_B'], @@ -2254,7 +2334,7 @@ def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypat ) monkeypatch.setattr( 'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared', - lambda actual_task, *, mode, allow_auto_retry=True: SimpleNamespace( + lambda actual_task, *, mode, allow_auto_retry=True, source_codes=None: SimpleNamespace( pending_source_codes=[], prepared_source_codes=[], failed_source_codes=['SRC_A'], @@ -2271,3 +2351,168 @@ def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypat assert result['status'] == 'needs_human' assert result['data']['blocking_reason']['code'] == 'inventory_preparation_failed' + + +def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch, app): + """[断言] 冻结源 ready 复用必须先 link;禁止未绑定直接 inventory_loaded_response 抛 ValueError。""" + from app.services.shipping_notice import inventory_workflow + + task = SimpleNamespace( + task_no='OT-STP-READY-LINK', + id=701, + inventory_lines_json=None, + inventory_source_status='candidates_frozen', + active_inventory_candidate_set_id=9, + ) + snapshot = SimpleNamespace( + inventory_file_no='INV-READY-001', + source_code='SRC_A', + warehouse_id='WH1', + ) + call_order: list[str] = [] + + monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task) + monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {}) + monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs) + monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None) + monkeypatch.setattr(inventory_workflow.db.session, 'flush', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['SRC_A'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'ready', + 'candidate_set_id': 9, + 'lines': [{'part_number': 'P1', '__source_code': 'SRC_A', '__inventory_file_no': 'INV-READY-001'}], + 'missing_source_codes': [], + 'loaded_source_codes': ['SRC_A'], + 'evidence': [{ + 'source_code': 'SRC_A', + 'status': 'loaded', + 'inventory_file_no': 'INV-READY-001', + 'line_count': 1, + 'required': True, + }], + 'required_source_codes': ['SRC_A'], + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task', + lambda _task: None, + ) + monkeypatch.setattr( + ShippingInventoryFile, + 'query', + SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)), + ) + + def _fake_link(actual_task, inv_file, *, reason, role='member', audit_payload=None): + call_order.append(f'link:{reason}') + assert actual_task is task + assert inv_file is snapshot + assert reason == 'stp_candidate_prep' + return SimpleNamespace(id=1) + + def _fake_loaded(actual_task, lines, **kwargs): + call_order.append('loaded') + assert actual_task is task + assert lines + assert kwargs.get('persist_lines') is False + return {'status': 'ok', 'message': 'linked-and-loaded'} + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task', + _fake_link, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response', + _fake_loaded, + ) + monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _fake_loaded) + + result = inventory_workflow.ensure_inventory({ + 'task_id': task.task_no, + 'mode': 'auto', + '_orchestrator_internal_dispatch': True, + }) + + assert result['status'] == 'ok' + assert call_order == ['link:stp_candidate_prep', 'loaded'] + + +def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app): + """[断言] ready 快照无法绑定 OT 时返回 needs_human,不得抛未绑定 ValueError。""" + from app.services.shipping_notice import inventory_workflow + + task = SimpleNamespace( + task_no='OT-STP-LINK-FAIL', + id=702, + inventory_lines_json=None, + inventory_source_status='candidates_frozen', + active_inventory_candidate_set_id=10, + ) + snapshot = SimpleNamespace(inventory_file_no='INV-MISMATCH', source_code='SRC_A', warehouse_id='WH1') + + monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task) + monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {}) + monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs) + monkeypatch.setattr(inventory_workflow, 'apply_task_transition', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'set_task_step_progress', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow, 'log_task_event', lambda *_a, **_k: None) + monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes', + lambda _task: ['SRC_A'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines', + lambda _task: { + 'status': 'ready', + 'candidate_set_id': 10, + 'lines': [{'part_number': 'P1', '__inventory_file_no': 'INV-MISMATCH'}], + 'missing_source_codes': [], + 'loaded_source_codes': ['SRC_A'], + 'evidence': [{ + 'source_code': 'SRC_A', + 'status': 'loaded', + 'inventory_file_no': 'INV-MISMATCH', + 'required': True, + }], + 'required_source_codes': ['SRC_A'], + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task', + lambda _task: None, + ) + monkeypatch.setattr( + ShippingInventoryFile, + 'query', + SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task', + lambda *_a, **_k: None, + ) + + def _boom(*_a, **_k): + raise AssertionError('inventory_loaded_response must not run when link failed') + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response', + _boom, + ) + monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _boom) + + result = inventory_workflow.ensure_inventory({ + 'task_id': task.task_no, + 'mode': 'auto', + '_orchestrator_internal_dispatch': True, + }) + + assert result['status'] == 'needs_human' + assert result['data']['blocking_reason']['code'] == 'inventory_file_missing' diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index 8335b422..8436d5bd 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -340,7 +340,9 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app): assert data["todo_category"] == "in_progress" assert data["created_by"] == 11 assert data["can_handle"] is True - assert data["ui_state"]["checkpoint"]["code"] == "order_freeze" + # 无 Gate 且无 review_status:薄回退不投影 order_freeze + assert data["ui_state"]["position"] is None + assert data["ui_state"]["user_mode"] == "auto_continue" assert data["artifact_summary"] is None no_viewer = serialize_task_summary(task) @@ -575,11 +577,85 @@ def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app): item = result['items'][0] assert item['business_no'] == 'WYC26082501' + # 权威事实:人工确认成功 → Attempt.status=succeeded,但 Notice 面必须投影为 uploaded。 + assert item['upload_status'] == 'uploaded' # 权威事实:人工确认成功 → manual;不读陈旧列('rpa')或恒 0/99 的 attempt 计数。 assert item['upload_mode'] == 'manual' assert item['upload_attempt'] == 1 +def test_freight_notice_groups_available_actions_use_order_task_execution(app): + """货代上传单条菜单必须经 Notice.order_task_id 读 OT Execution,禁止用 Notice.id 查 Gate。 + + 回归点:ShippingProcessExecution.task_id FK 指向 shipping_order_tasks.id; + Artifact.task_id 才是 Notice 主键。若误用 Notice.id,聚合只会留下 download_excel, + 行内 RPA/确认上传按钮全部消失。 + """ + with app.app_context(): + from app import db + from app.models import ShippingProcessExecution, ShippingProcessGate + from app.services.shipping_notice import query_service + + # 两张表在空库上都会从 1 起号;只给 OT 表垫一条废数据,强制 Notice.id ≠ OT.id, + # 否则「误用 Notice.id 查 Execution」在单测里会碰巧命中。 + db.session.add(ShippingOrderTask( + task_no='OT-GROUP-ACTIONS-PAD', user_id=11, source_type='direct_pdf', + )) + db.session.flush() + + order_task = ShippingOrderTask( + task_no='OT-GROUP-ACTIONS-1', user_id=11, source_type='direct_pdf', + ) + db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-GROUP-ACTIONS-1', + business_no='WYC26090601', + source_type='manual', + user_id=11, + order_task_id=order_task.id, + ) + db.session.add(notice) + db.session.flush() + # Notice.id 与 OT.id 必须不同,否则会掩盖「误用 Notice.id 查 Execution」的回归。 + assert int(notice.id) != int(order_task.id) + + execution = ShippingProcessExecution( + execution_no='EXE-GROUP-ACTIONS-1', + task_id=int(order_task.id), + status='blocked', + current_gate_code='manual_upload_handoff', + primary_next_action_code='mark_manual_uploaded', + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code='manual_upload_handoff', + sequence_no=20, + status='blocked_manual', + evaluation_version=1, + blocking_reason_code='manual_upload_pending', + next_action_code='mark_manual_uploaded', + )) + order_task.active_process_execution_id = int(execution.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: { + 'customer_po_number': 'PO-ACTIONS', + } + try: + result = list_freight_notice_groups_for_task(notice, user_id=11) + finally: + query_service.current_header_field_values_or_empty = original_header_reader + + actions = set(result['items'][0]['available_actions'] or []) + assert 'mark_manual_uploaded' in actions + assert 'retry_freight_upload_rpa' in actions + + def test_list_my_todos_and_count_buckets(app): """待办按 OT 复核事实和 Notice 上传事实分类;count 徽标与 pending 一致。""" with app.app_context(): @@ -1094,8 +1170,10 @@ def test_todo_category_sql_matches_formal_notice_facts(app): def test_serialize_task_detail_workbench_view_drops_editor_fields(app): - """工作台 view=workbench 剔除复核编辑器重字段,保留 ui_state/产物/行摘要,全量视图不受影响。""" + """工作台 view=workbench 跳过 DETAIL 重投影,保留 ui_state/产物/行摘要,全量视图不受影响。""" with app.app_context(): + from unittest.mock import patch + from app import db from app.services.shipping_notice.query_service import serialize_task_detail @@ -1106,11 +1184,16 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app): db.session.commit() full = serialize_task_detail(task, viewer_user_id=11, include_stage_context=True) - wb = serialize_task_detail( - task, viewer_user_id=11, include_stage_context=True, view="workbench", - ) + with patch( + 'app.services.shipping_notice.query_service.serialize_task', + ) as serialize_task_mock: + wb = serialize_task_detail( + task, viewer_user_id=11, include_stage_context=True, view="workbench", + ) - # full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。 + # workbench 不得进入 SUMMARY/DETAIL 重投影(算之前就轻)。 + serialize_task_mock.assert_not_called() + # full 保留编辑器重字段;workbench 身份壳不含它们。 for key in ( "lines", "order_header", "order_header_fields", "order_line_fields", ): @@ -1122,3 +1205,5 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app): assert wb["artifact_summary"] is None assert "notice_line_summary" in wb assert "export_artifacts" not in wb + assert wb["task_no"] == "OT-WORKBENCH-VIEW" + assert wb["order_task_no"] == "OT-WORKBENCH-VIEW" \ No newline at end of file diff --git a/backend/tests/test_shipping_notice_state_machine.py b/backend/tests/test_shipping_notice_state_machine.py index f478c34c..a25e4a72 100644 --- a/backend/tests/test_shipping_notice_state_machine.py +++ b/backend/tests/test_shipping_notice_state_machine.py @@ -1,45 +1,45 @@ """ tests/test_shipping_notice_state_machine.py -用途:校验发货通知 checkpoint 内部流程映射与 STP checkpoint_kind。 -依赖:pytest、state_machine、constants、ShippingNotice。 -逻辑:validate_registry 无错误;关键检查点 kind 正确;resolve_task_ui_state 对简单任务属性可解析。 +用途:校验发货通知位置→用户模式查找表与 Gate/review 薄回退。 +依赖:pytest、state_machine、constants、ShippingOrderTask。 +逻辑:validate_registry 无错误;关键位置 user_mode 正确;resolve_task_ui_state + 无 Gate 时仅凭 review_status 回退。 """ from types import SimpleNamespace from app.models import ShippingOrderTask from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_PARSE_REVIEW, - CP_READY_EXPORT, - CP_UPLOADED, + POSITION_EXPORT_READY, + POSITION_PARSE_REVIEW, + POSITION_UPLOADED, PH_LOW_CONF, RS_PARSE_REVIEW, + RS_REJECTED, ) from app.services.shipping_notice.state_machine import ( - CheckpointKind, - checkpoint_kind_for, + UserMode, resolve_task_ui_state, - resolve_task_ui_state_from_fields, + user_mode_for_position, validate_registry, ) def test_validate_registry_has_no_errors() -> None: - """checkpoint 仅维护内部流程分类。""" + """位置→用户模式查找表非空且自洽。""" assert validate_registry() == [] -def test_checkpoint_kinds_for_stp_stop_points() -> None: - """STP 关键检查点 kind:导出 Excel 后待人工上传登记 / 解析复核 / 已上传终态。""" - assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD - assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN - assert checkpoint_kind_for(CP_UPLOADED) == CheckpointKind.COMPLETE +def test_user_modes_for_stp_stop_points() -> None: + """STP 关键位置 user_mode:导出就绪待人工 / 解析复核 / 已上传终态。""" + assert user_mode_for_position(POSITION_EXPORT_READY) == UserMode.WAIT_MANUAL_UPLOAD + assert user_mode_for_position(POSITION_PARSE_REVIEW) == UserMode.MUST_HUMAN + assert user_mode_for_position(POSITION_UPLOADED) == UserMode.COMPLETE def test_resolve_task_ui_state_parse_review(app) -> None: - """pending_review + parse_review 应映射为 must_human / parse_review。""" + """无 Gate 时 review_status=parse_review 应映射为 must_human / parse_review。""" with app.app_context(): task = ShippingOrderTask( task_no="OT-SM-PARSE", @@ -47,94 +47,41 @@ def test_resolve_task_ui_state_parse_review(app) -> None: review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, ) - ui = resolve_task_ui_state_from_fields( - review_status=task.review_status, - pending_human_reason=task.pending_human_reason, - customer_resolution_status=None, - order_snapshot_id=None, - match_status=None, - export_file_path=None, - has_dynamic_order_lines=False, - ) - assert ui.checkpoint == CP_PARSE_REVIEW - assert ui.checkpoint_kind == CheckpointKind.MUST_HUMAN + ui = resolve_task_ui_state(task) + assert ui.position == POSITION_PARSE_REVIEW + assert ui.user_mode == UserMode.MUST_HUMAN -def test_resolve_task_ui_state_export_ready(app) -> None: - """matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。""" +def test_resolve_task_ui_state_rejected(app) -> None: + """无 Gate 时 review_status=rejected → complete / rejected。""" with app.app_context(): - ui = resolve_task_ui_state_from_fields( - review_status=None, - pending_human_reason=None, - customer_resolution_status=None, - order_snapshot_id=1, - match_status=None, - export_file_path="/tmp/shipping-export.xlsx", - has_dynamic_order_lines=False, + task = ShippingOrderTask( + task_no="OT-SM-REJECT", + user_id=1, + review_status=RS_REJECTED, ) - assert ui.checkpoint == CP_EXPORT_READY - assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD - assert not hasattr(ui, 'human_options') + ui = resolve_task_ui_state(task) + assert ui.position == 'rejected' + assert ui.user_mode == UserMode.COMPLETE -def test_resolve_task_ui_state_uploaded_complete(app, monkeypatch) -> None: - """upload_status=uploaded 应为 complete。""" +def test_resolve_without_review_status_is_thin(app) -> None: + """无 Gate 且无 review_status 时不从领域标量投影位置(薄回退)。""" with app.app_context(): - task = SimpleNamespace(upload_status="uploaded", lifecycle_status="active") - # [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。 - monkeypatch.setattr( - 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success', - lambda _task: True, - ) - ui = resolve_task_ui_state_from_fields( - review_status=None, - pending_human_reason=None, - customer_resolution_status=None, - order_snapshot_id=1, - match_status=None, - export_file_path=None, - has_dynamic_order_lines=False, - upload_req_task=task, - ) - assert ui.checkpoint == CP_UPLOADED - assert ui.checkpoint_kind == CheckpointKind.COMPLETE + task = ShippingOrderTask(task_no="OT-SM-THIN", user_id=1) + ui = resolve_task_ui_state(task) + assert ui.position is None + assert ui.user_mode == UserMode.AUTO_CONTINUE -def test_resolve_with_mocked_simple_namespace_attributes(monkeypatch) -> None: - """无 DB 会话时可用简易命名空间验证 uploaded 终态分支。""" +def test_resolve_with_mocked_simple_namespace_attributes() -> None: + """无 DB 会话时简易命名空间:无 review_status → 薄回退 None/auto。""" task = SimpleNamespace( - upload_status="uploaded", review_status=None, pending_human_reason=None, - customer_resolution_status=None, - order_snapshot_id=None, - inventory_lines_json=None, - match_status=None, - export_file_path=None, - current_order_extraction_id=None, - step_payload_json=None, - ) - # [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。 - monkeypatch.setattr( - 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success', - lambda _task: True, + order_task_id=None, + id=None, ) ui = resolve_task_ui_state(task) # type: ignore[arg-type] - assert ui.checkpoint_kind == CheckpointKind.COMPLETE - assert ui.checkpoint == CP_UPLOADED - - -def test_order_task_inventory_checkpoint_uses_structured_facts(monkeypatch) -> None: - """OT 库存 JSON 为空时,状态机仍须按 Link/File/Match 事实进入导出准备。""" - from app.models import ShippingOrderTask - from app.services.shipping_notice import state_machine - - task = ShippingOrderTask(task_no='OT-SM-STRUCTURED', user_id=1, stage='inventory_matching') - monkeypatch.setattr(state_machine, '_order_task_inventory_facts', lambda _task: { - 'inventory_ready': True, - 'match_complete': True, - 'match_sufficient': True, - 'has_shortage': False, - }) - - assert state_machine.resolve_task_ui_state(task).checkpoint == CP_READY_EXPORT + assert ui.user_mode == UserMode.AUTO_CONTINUE + assert ui.position is None diff --git a/backend/tests/test_shipping_notice_stp_acceptance.py b/backend/tests/test_shipping_notice_stp_acceptance.py index 65e14055..5920ccda 100644 --- a/backend/tests/test_shipping_notice_stp_acceptance.py +++ b/backend/tests/test_shipping_notice_stp_acceptance.py @@ -24,15 +24,15 @@ from app.models import ( User, ) from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_PARSE_REVIEW, + POSITION_EXPORT_READY, + POSITION_PARSE_REVIEW, PH_LOW_CONF, RS_PARSE_REVIEW, ) from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match, upload_to_freight from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.query_service import count_my_todos, list_my_todos -from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for +from app.services.shipping_notice.state_machine import UserMode, user_mode_for_position def _seed_export_artifact_view(monkeypatch) -> None: @@ -61,10 +61,10 @@ def _seed_export_artifact_view(monkeypatch) -> None: ) -def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None: +def test_stp_user_mode_matrix_covers_nine_scenario_stops() -> None: """九条场景依赖的停点 kind 不得漂移。""" - assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN - assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD + assert user_mode_for_position(POSITION_PARSE_REVIEW) == UserMode.MUST_HUMAN + assert user_mode_for_position(POSITION_EXPORT_READY) == UserMode.WAIT_MANUAL_UPLOAD def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app, monkeypatch) -> None: @@ -86,7 +86,7 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app, result = auto_progress({"task_id": task.task_no, "source": "system"}) assert result["status"] == "ok" - assert result.get("checkpoint") == CP_EXPORT_READY + assert result.get("position") == POSITION_EXPORT_READY assert "upload_to_freight" in (result.get("forbidden_next_tools") or []) assert result.get("stop_agent_turn") is True assert "登记凭据" in str(result.get("message") or "") @@ -118,86 +118,120 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None: result = auto_progress({"task_id": task.task_no, "source": "system"}) assert result["status"] == "needs_human" - assert result.get("checkpoint") == CP_PARSE_REVIEW + assert result.get("position") == POSITION_PARSE_REVIEW -def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch) -> None: - """场景:AUTO_UPLOAD=true 时匹配后串联须调用 upload_to_freight(mode=auto)。""" +def test_try_auto_chain_gate_path_skips_generate_and_upload(app, monkeypatch) -> None: + """Gate Attempt 路径:匹配成功后不得内嵌 generate_excel / upload_to_freight。""" with app.app_context(): from app import db - app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True - app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True - task = ShippingNotice( - task_no="SN-STP-RPA-ON", - source_type="manual", - ) + task = ShippingNotice(task_no='SN-STP-CHAIN-GATE', source_type='manual') db.session.add(task) db.session.commit() - # Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。 - _seed_export_artifact_view(monkeypatch) - - upload_calls: list[dict] = [] - - def _fake_upload(payload): - upload_calls.append(dict(payload or {})) - return {"status": "running", "message": "rpa-triggered"} - monkeypatch.setattr( - "app.services.shipping_notice.fulfillment_workflow.upload_to_freight", - _fake_upload, + 'app.services.shipping_notice.fulfillment_workflow._current_export_artifact', + lambda _task: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.excel_gate_error', + lambda _task: None, + ) + + generate_calls: list[dict] = [] + upload_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.upload_to_freight', + lambda payload: upload_calls.append(dict(payload or {})) or {'status': 'running'}, ) result = try_auto_chain_after_match( task, - {"status": "ok", "message": "matched"}, - payload={"task_id": task.task_no}, - ) - # 关键断言:自动链接入货代上传 RPA。 - assert len(upload_calls) == 1 - assert upload_calls[0].get("mode") == "auto" - assert result["status"] == "running" - - -def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch) -> None: - """场景:AUTO_UPLOAD=false 时停在人工上传,不调用 upload_to_freight。""" - with app.app_context(): - from app import db - - app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False - app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True - - task = ShippingNotice( - task_no="SN-STP-NO-RPA", - source_type="manual", - ) - db.session.add(task) - db.session.commit() - - # Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。 - _seed_export_artifact_view(monkeypatch) - - upload_calls: list[dict] = [] - - def _fake_upload(payload): - upload_calls.append(dict(payload or {})) - return {"status": "running", "message": "should-not-run"} - - monkeypatch.setattr( - "app.services.shipping_notice.fulfillment_workflow.upload_to_freight", - _fake_upload, - ) - - result = try_auto_chain_after_match( - task, - {"status": "ok", "message": "matched"}, - payload={"task_id": task.task_no}, + {'status': 'ok', 'message': 'matched'}, + payload={ + 'task_id': task.task_no, + '_orchestrator_internal_dispatch': True, + 'source': 'process_gate', + }, ) + assert result['status'] == 'ok' + assert generate_calls == [] assert upload_calls == [] - assert result["status"] == "ok" - assert "upload_to_freight" in (result.get("forbidden_next_tools") or []) + + +def test_try_auto_chain_legacy_path_submits_artifact_auto_progress(app, monkeypatch) -> None: + """非 Gate 遗留路径:只提交 artifact_generation auto_progress,禁止直跑 generate。""" + with app.app_context(): + from app import db + + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = True + + task = ShippingNotice(task_no='SN-STP-CHAIN-LEGACY', source_type='manual') + db.session.add(task) + db.session.commit() + + progress_calls: list[dict] = [] + generate_calls: list[dict] = [] + + def _fake_progress(task_no, **kwargs): + progress_calls.append({'task_no': task_no, **kwargs}) + return {'status': 'running', 'message': 'queued-artifact'} + + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow.run_task_auto_progress', + _fake_progress, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.generate_excel', + lambda payload: generate_calls.append(dict(payload or {})) or {'status': 'ok'}, + ) + + result = try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched'}, + payload={'task_id': task.task_no, 'source': 'legacy_tool'}, + ) + assert generate_calls == [] + assert len(progress_calls) == 1 + assert progress_calls[0]['resume_gate_code'] == 'artifact_generation' + assert result['status'] == 'running' + + +def test_try_auto_chain_skips_when_auto_generate_disabled(app, monkeypatch) -> None: + """AUTO_GENERATE_EXCEL=false 时遗留路径也不提交下游 chain。""" + with app.app_context(): + from app import db + + app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True + app.config['SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED'] = False + + task = ShippingNotice(task_no='SN-STP-NO-CHAIN', source_type='manual') + db.session.add(task) + db.session.commit() + + progress_calls: list[dict] = [] + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow.run_task_auto_progress', + lambda *args, **kwargs: progress_calls.append(kwargs) or {'status': 'running'}, + ) + + result = try_auto_chain_after_match( + task, + {'status': 'ok', 'message': 'matched'}, + payload={'task_id': task.task_no}, + ) + assert progress_calls == [] + assert result['status'] == 'ok' + assert result.get('message') == 'matched' def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch) -> None: diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index d69053ad..ca4544a8 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -2,8 +2,12 @@ tests/test_shipping_notice_ui_state.py 用途:校验发货通知 UI State 摘要字段与 entry_surface 映射。 -依赖:pytest、ShippingNotice、ui_state、state_machine constants。 -逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。 +依赖:pytest、ShippingNotice、ui_state、state_machine constants、库存源/发货模板模型。 +逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确; + stage_context.preparation 短缺行投影 release_required_fields; + preparation.source_options 下发已启用源供行级覆写下拉; + 行级 selected_source_code(Candidate)与 source_code(Match)分字段; + Notice 详情经 order_task_id→OT 读取 Snapshot/Match。 """ from app import db @@ -14,9 +18,8 @@ from app.models import ( ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, User, ) from app.services.shipping_notice.constants import ( - CP_EXPORT_READY, - CP_ORDER_FREEZE, - CP_PARSE_REVIEW, + POSITION_EXPORT_READY, + POSITION_PARSE_REVIEW, PH_LOW_CONF, RS_PARSE_REVIEW, ) @@ -29,7 +32,7 @@ _REQUIRED_SUMMARY_KEYS = { "message", "issues", "stage", - "checkpoint_kind", + "user_mode", "current_todo", "pause_reason", "next_auto_step", @@ -145,8 +148,9 @@ def test_build_task_ui_state_summary_has_required_keys(app) -> None: ) state = build_task_ui_state(task) assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys()) - assert state["checkpoint"]["code"] == CP_ORDER_FREEZE - assert state["checkpoint_kind"] == "auto_continue" + # 无 Gate 时按领域标量回退:parse_review 不得再被 OT 空 stage 盖成 order_freeze。 + assert state["position"] == POSITION_PARSE_REVIEW + assert state["user_mode"] == "must_human" assert "stp_facts" not in state["summary"] @@ -164,7 +168,7 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None: def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: - """旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。""" + """无正式 Gate 时位置不能再推导五阶段或任何可写 UI 动作。""" with app.app_context(): task = ShippingOrderTask( task_no="OT-UI-STAGE-ACTIONS", user_id=1, @@ -181,7 +185,7 @@ def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None: - """正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。""" + """正式工作台入口必须来自 Gate,不能按旧位置码生成。""" with app.app_context(): task = ShippingOrderTask( task_no="OT-UI-LIFECYCLE-ENTRIES", user_id=1, @@ -305,29 +309,65 @@ def test_entry_surface_parse_review_is_review_workbench(app) -> None: source_type="direct_pdf", ) state = build_task_ui_state(task) - assert state["summary"]["entry_surface"] == "task_workbench" + assert state["summary"]["entry_surface"] == "review_workbench" + + +def test_build_task_ui_state_queries_process_gate_once(app, monkeypatch) -> None: + """build_task_ui_state 同一次构建只查 Gate 摘要一次,禁止再经 resolve 二次查库。""" + with app.app_context(): + calls = {'n': 0} + + def _fake_gate(_task): + calls['n'] += 1 + return { + 'current_gate_code': 'inventory_sufficiency', + 'status': 'blocked', + 'lifecycle_stage': 'fulfillment_prep', + 'current_blocking_gate': { + 'gate_code': 'inventory_sufficiency', + 'status': 'blocked_manual', + }, + 'primary_action': None, + 'action_presentation': [], + } + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + _fake_gate, + ) + task = ShippingOrderTask(task_no="OT-UI-GATE-ONCE", user_id=1, source_type="direct_pdf") + state = build_task_ui_state(task) + assert calls['n'] == 1 + assert state['lifecycle_stage'] == 'fulfillment_prep' def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None: - """Excel Artifact 就绪后仍进入工作台,且未解析的文件不得擅自授权下载。""" + """Gate artifact_generation 投影 export_ready 时进入工作台;未验证 Artifact 不得授权下载。""" with app.app_context(): task = ShippingNotice( task_no="SN-UI-EXPORT", source_type="manual", ) - # Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。 - from types import SimpleNamespace monkeypatch.setattr( - 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', - lambda _task: SimpleNamespace(id=0, file_path='/tmp/shipping-export.xlsx', file_name='shipping-export.xlsx'), + 'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task', + lambda _task: { + 'current_gate_code': 'artifact_generation', + 'status': 'waiting_human', + 'lifecycle_stage': 'freight_upload', + 'current_blocking_gate': { + 'gate_code': 'artifact_generation', + 'status': 'blocked_manual', + }, + }, ) monkeypatch.setattr( - 'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt', + 'app.services.shipping_notice.ui_state.resolve_task_export_download', lambda _task: None, ) state = build_task_ui_state(task) - assert state["checkpoint"]["code"] == CP_EXPORT_READY - assert state["checkpoint_kind"] == "wait_manual_upload" + assert state["position"] == POSITION_EXPORT_READY + # Gate freight_upload + waiting_human → wait_manual_upload + assert state["user_mode"] == "wait_manual_upload" assert state["summary"]["entry_surface"] == "task_workbench" assert state["summary"].get("pause_reason_code") == "wait_manual_upload" assert "货代平台上传" in str(state["summary"].get("pause_reason") or "") @@ -336,7 +376,7 @@ def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None: for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])] if item ] - # 关键断言:没有可验证 Artifact 时,遗留 export_file_name 不得生成下载按钮。 + # 关键断言:没有可验证 Artifact 时不得生成下载按钮。 assert "download_excel" not in button_ids assert "mark_manual_uploaded" not in button_ids @@ -498,6 +538,7 @@ def test_stp_facts_projects_line_resolutions(app) -> None: assert line["status"] == "inventory_matched" assert line["source_ambiguous"] is False assert line["source_candidates"] == [] + assert line["can_fulfill_complete_line"] is True # §1.5 明细按钮数据源:matched/ready 无短缺 → 无库存重试动作;行级库存文件号下发供下载按钮; # line_allowed_actions 仍开放 close_unfulfillable(非终态行可关闭)。 assert line["inventory_file_no"] == "INV-1" @@ -571,8 +612,15 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None: assert "retry_inventory_preparation" in line["inventory_allowed_actions"] -def test_stage_context_preparation_projects_source_ambiguity_and_lock(app) -> None: - """行级 source_conflict 与候选源只读 Match;Excel 生成后锁定。""" +def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monkeypatch) -> None: + """行级 source_conflict 与候选源只读 Match;Excel 未生成时下发 source_options。""" + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources', + lambda enabled_only=True: [ + {'source_code': 'src_a', 'display_name': 'Source A'}, + {'source_code': 'SRC_B', 'display_name': ''}, + ], + ) with app.app_context(): user = User(username='ui-source-ambiguity', email='ui-source-ambiguity@example.com') db.session.add(user) @@ -602,8 +650,97 @@ def test_stage_context_preparation_projects_source_ambiguity_and_lock(app) -> No assert preparation['lines'][0]['source_candidates'] == ['SRC_A', 'SRC_B'] assert preparation['lines'][0]['source_code'] is None assert preparation['source_locked'] is False + # 关键断言:行级覆写下拉依赖 preparation.source_options;编码统一大写。 + assert preparation['source_options'] == [ + {'source_code': 'SRC_A', 'display_name': 'Source A'}, + {'source_code': 'SRC_B', 'display_name': 'SRC_B'}, + ] +def test_stage_context_projects_selected_source_without_backfilling_match_source(app) -> None: + """CandidateSet 单源只填 selected_source_code,禁止回填 Match 的 source_code。""" + with app.app_context(): + task, line = _frozen_task_with_line( + task_no='OT-UI-SELECTED-SOURCE', + reservation_id='RSV-SEL', + part_number='PN-SEL', + qty='2', + ) + candidate_set = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='b' * 64, + ) + db.session.add(candidate_set) + db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1, + )) + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'], + )) + task.active_inventory_candidate_set_id = candidate_set.id + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation'] + row = preparation['lines'][0] + # 关键断言:取数目标与匹配结论分字段;未匹配时 source_code 必须为空。 + assert row['snapshot_line_id'] == line.id + assert row['selected_source_code'] == 'DSV360_AWSSG' + assert row['source_code'] is None + assert row['source_ambiguous'] is False + + +def test_stage_context_notice_resolves_ot_match_and_selected_source(app) -> None: + """Notice 详情入口须经 order_task_id→OT 读 Snapshot/Match/Candidate,禁止用 Notice.id。""" + with app.app_context(): + # 垫偏 OT.id,避免空库 Notice.id==OT.id 碰巧绿。 + for index in range(3): + db.session.add(ShippingOrderTask( + task_no=f'OT-UI-SPACER-{index}', user_id=1, source_type='direct_pdf', + )) + db.session.flush() + task, line = _frozen_task_with_line( + task_no='OT-UI-NOTICE-RESOLVE', + reservation_id='RSV-NOTICE', + part_number='PN-NOTICE', + qty='3', + ) + candidate_set = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='c' * 64, + ) + db.session.add(candidate_set) + db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1, + )) + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'], + )) + task.active_inventory_candidate_set_id = candidate_set.id + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0, + match_result='matched', inventory_status='ready', required_qty='3', available_qty='3', + matched_qty='3', shortage_qty='0', reservation_id='RSV-NOTICE', part_number='PN-NOTICE', + inventory_source_code='DSV360_AWSSG', matched_file_no='INV-NOTICE', is_current=True, + )) + notice = ShippingNotice( + task_no='SN-UI-NOTICE-RESOLVE', + source_type='manual', + user_id=1, + order_task_id=task.id, + ) + db.session.add(notice) + db.session.commit() + + assert int(notice.id) != int(task.id) + preparation = build_task_ui_state(notice, include_stage_context=True)['stage_context']['preparation'] + row = preparation['lines'][0] + # 关键断言:SN 入口仍投影 OT 上的匹配正式源与取数目标。 + assert preparation['frozen_order']['task_no'] == task.task_no + assert preparation['frozen_order']['snapshot_id'] == task.order_snapshot_id + assert row['source_code'] == 'DSV360_AWSSG' + assert row['selected_source_code'] == 'DSV360_AWSSG' + assert preparation['has_match_result'] is True + def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None: """库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。""" with app.app_context(): @@ -913,6 +1050,34 @@ def test_preparation_editable_present_for_live_formal_task(monkeypatch): assert _preparation_editable(NoisyStatusTask()) is False +def test_stage_context_line_actions_without_match_rows(app) -> None: + """正式 OT 无匹配行时,preparation.lines 仍须下发明细库存重试动作。 + + 断言:has_formal_ot 不得用 current_match_rows 判定;无 match 时 fact 兜底 preparing, + inventory_allowed_actions 含 retry_inventory_preparation。 + """ + with app.app_context(): + user = User(username='ui-no-match-actions', email='ui-no-match-actions@example.com') + db.session.add(user) + db.session.flush() + task, _line = _frozen_task_with_line( + task_no='OT-UI-NO-MATCH-ACTIONS', + user_id=user.id, + reservation_id='RSV-NM-1', + part_number='PN-NM-1', + qty='4', + ) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] + assert preparation["has_match_result"] is False + assert len(preparation["lines"]) == 1 + line = preparation["lines"][0] + # 关键断言:无 Match 行时明细仍可点「重试库存准备」,不得因 has_formal_ot=False 空动作。 + assert "retry_inventory_preparation" in line["inventory_allowed_actions"] + assert "close_unfulfillable" in line["line_allowed_actions"] + + def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app) -> None: """[断言] preparation 携带任务级 editable(active=True / voided=False); 行级 customer_po_line_no 直读字段真实值(field_code 兼容键),字段缺失时为 None。""" @@ -936,3 +1101,110 @@ def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app assert preparation["lines"][0]["customer_po_line_no"] is None # 字段缺失/无值的行也必须输出 None,不得用展示序号冒充业务行号。 assert preparation["lines"][1]["customer_po_line_no"] is None + + +def test_stage_context_preparation_projects_shortage_release_template_fields(app) -> None: + """短缺行必须按库存源发货模板投影人工补录字段,禁止 fail-closed 空列表。""" + from app.models import ( + ShippingExcelTemplate, + ShippingInventoryField, + ShippingInventorySource, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ) + + with app.app_context(): + location = ShippingInventoryField.query.filter_by(field_code='location').one() + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + template = db.session.get(ShippingExcelTemplate, int(source.excel_template_id)) + assert template is not None + template.definition_json = { + 'mappings': [ + { + 'row_mode': 'line', + 'source_kind': 'inventory_field', + 'source_key': str(location.id), + }, + ], + } + + user = User(username='ui-release-fields', email='ui-release-fields@example.com') + db.session.add(user) + db.session.flush() + schema = ShippingOrderSchema(schema_code='UI_RELEASE_FIELDS', display_name='UI Release Fields') + db.session.add(schema) + db.session.flush() + schema_version = ShippingOrderSchemaVersion( + schema_id=schema.id, + version=1, + status='published', + definition_json={'fields': []}, + ) + db.session.add(schema_version) + db.session.flush() + + task = ShippingOrderTask( + task_no='OT-UI-RELEASE-FIELDS', + user_id=user.id, + stage='inventory_matching', + ) + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=1, + schema_version_id=schema_version.id, + order_data_version=1, + header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=0, + line_no=1, + reservation_id='RSV-RELEASE', + part_number='PN-RELEASE', + qty='10', + field_values_json={}, + ) + db.session.add(snapshot_line) + db.session.flush() + # 无库存快照时模板库存字段全部人工补录;源码必须能解析到 published 发货模板。 + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, + snapshot_line_id=snapshot_line.id, + line_no=1, + line_index=0, + match_result='not_found', + inventory_status='ready', + required_qty='10', + available_qty='0', + matched_qty='0', + shortage_qty='10', + reservation_id='RSV-RELEASE', + part_number='PN-RELEASE', + inventory_source_code='DSV360_AWSDU', + inventory_snapshot_id=None, + is_current=True, + )) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation'] + line = preparation['lines'][0] + + assert line['is_shortage'] is True + assert line['release_field_resolution_error'] is None + assert line['release_required_fields'] == [ + {'field_id': str(location.id), 'display_name': '库位'}, + ] + assert line['release_template_fields'] == [ + { + 'field_id': str(location.id), + 'display_name': '库位', + 'value': None, + 'value_source': 'manual_required', + 'requires_manual': True, + }, + ] diff --git a/backend/tests/test_shipping_order_review_service.py b/backend/tests/test_shipping_order_review_service.py index fffe2135..a7f7fcac 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -302,8 +302,8 @@ def test_review_queue_projects_each_case_po_and_lifecycle_stage(app): ] -def test_review_queue_uses_formal_task_lifecycle_stage(app): - """Case 已绑定正式任务后,队列阶段必须随正式 Gate/领域事实推进。""" +def test_review_queue_uses_formal_task_lifecycle_stage(app, monkeypatch): + """Case 已绑定正式任务后,队列阶段必须随正式 OT.stage 推进,且不得走全量 ui_state。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-FORMAL-STAGE') run = _materialized_run(user=user, agent=agent, session=session, intake=intake) @@ -332,6 +332,13 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app): case.confirmed_task_id = task.id db.session.commit() + def _forbid_full_ui_state(*_args, **_kwargs): + raise AssertionError('queue summary must not call build_task_ui_state') + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state.build_task_ui_state', + _forbid_full_ui_state, + ) item = serialize_review_queue([run])['items'][0] assert item['po_number'] == 'PO-QUEUE-002' @@ -341,6 +348,65 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app): ] +def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(app, monkeypatch): + """旧 OT.stage=step* 不在五阶段映射表时,队列须用批量 Gate 兜底,不能塌成 intake_parse。""" + from app.models import ShippingProcessExecution, ShippingProcessGate + + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-LEGACY-STAGE') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + candidate = ShippingOrderCandidate( + candidate_no='CAND-REVIEW-QUEUE-LEGACY-STAGE', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key='review-queue-legacy-stage', + order_extraction_run_id=run.id, + po_number='PO-QUEUE-LEGACY', + ) + db.session.add(candidate) + db.session.flush() + case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0]) + task = ShippingOrderTask( + task_no='OT-REVIEW-QUEUE-LEGACY-STAGE', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=run.id, + status='waiting_review', + stage='step5_match_inventory', + ) + db.session.add(task) + db.session.flush() + execution = ShippingProcessExecution( + execution_no='SPE-REVIEW-QUEUE-LEGACY', + task_id=task.id, + review_case_id=case.id, + status='active', + current_gate_code='inventory_sufficiency', + ) + db.session.add(execution) + db.session.flush() + db.session.add(ShippingProcessGate( + execution_id=execution.id, + gate_code='inventory_sufficiency', + sequence_no=16, + status='blocked_manual', + )) + task.active_process_execution_id = execution.id + case.status = 'confirmed' + case.confirmed_task_id = task.id + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.ui_state.build_task_ui_state', + lambda *_a, **_k: (_ for _ in ()).throw(AssertionError('no full ui_state')), + ) + item = serialize_review_queue([run])['items'][0] + + assert item['lifecycle_stage'] == 'fulfillment_prep' + assert item['lifecycle_entries'][2]['state'] == 'current' + + + def test_review_case_does_not_expose_replacement_upload(app): """复核 Case 仅允许原 PDF 重识别,不暴露上传替代文件动作。""" with app.app_context(): @@ -726,7 +792,7 @@ def test_review_case_initialization_closes_legacy_extraction_gates(app): # 未确认 Case 的当前 Gate 是建单前复核(order_review_build),不是正式 Gate。 assert bundle['current_gate']['gate_code'] == 'order_review_build' assert bundle['blocking_reason']['code'] is None - assert bundle['user_status'] == 'idle' + assert bundle['user_status'] == 'waiting_human' def test_candidate_gate_reconciliation_supersedes_active_legacy_attempt(app): diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index cfb55e4f..55cfbcf1 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -1622,6 +1622,103 @@ def test_inventory_preparation_retry_rejects_legacy_task_without_snapshot(monkey assert result['blocking_reason_code'] == 'inventory_source_routing_required' +def test_inventory_preparation_mode_maps_by_action_code(monkeypatch): + """库存准备执行器按已有动作码映射 ensure_inventory mode,禁止人工入口一律 retry_rpa。""" + from types import SimpleNamespace + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation + + task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-MODE-MAP') + captured: list[dict] = [] + line = SimpleNamespace(source_codes_json=['DBS']) + candidate_set = SimpleNamespace(id=1) + sources = [SimpleNamespace(source_code='DBS')] + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._resolve_order_task', + lambda _execution: task, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set', + lambda _task: candidate_set, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines', + lambda _task: [line], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources', + lambda _task: sources, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream', + lambda **_: {}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'rpa': {}}}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_preparation_failed', + ) + 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: {'task_id': task.task_no, '_orchestrator_internal_dispatch': True}, + ) + # poll 路径会查失败 Attempt;无失败行时继续 ensure_inventory。 + monkeypatch.setattr( + 'app.models.ShippingInventoryPreparationAttempt.query', + SimpleNamespace( + filter_by=lambda **_: SimpleNamespace( + filter=lambda *_a, **_k: SimpleNamespace( + order_by=lambda *_a, **_k: SimpleNamespace(first=lambda: None), + ), + order_by=lambda *_a, **_k: SimpleNamespace(first=lambda: None), + ), + ), + ) + + execution = SimpleNamespace(task_id=1, id=21, candidate_set_id=None) + gate = SimpleNamespace(gate_code='inventory_preparation') + + captured.clear() + _handle_retry_inventory_preparation( + execution=execution, gate=gate, + payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5}, + ) + # 显式强制 RPA 码 → mode=retry_rpa。 + assert captured[-1].get('mode') == 'retry_rpa' + + captured.clear() + _handle_retry_inventory_preparation( + execution=execution, gate=gate, + payload={'action_code': 'poll_inventory_preparation', 'actor_user_id': 5}, + ) + # 只读轮询:默认 auto,禁止自动再试。 + assert captured[-1].get('mode') in (None, 'auto') + assert captured[-1].get('allow_auto_retry') is False + + captured.clear() + _handle_retry_inventory_preparation( + execution=execution, gate=gate, + payload={ + 'action_code': 'retry_inventory_preparation', + 'trigger': 'gate_attempt_passed', + 'actor_user_id': 5, + }, + ) + # 首次自动投递:不强制 retry_rpa,保留默认 auto(先复用快照)。 + assert captured[-1].get('mode') in (None, 'auto') + + def test_manual_business_block_is_a_successful_attempt(app): """库存匹配已执行但存在缺口时,Attempt 成功、Gate 保持人工阻断。""" from app import db diff --git a/backend/tests/test_shipping_processing_projection.py b/backend/tests/test_shipping_processing_projection.py index f879c397..74a2e52e 100644 --- a/backend/tests/test_shipping_processing_projection.py +++ b/backend/tests/test_shipping_processing_projection.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_processing_projection.py -???????? processing ?????OT ??????PDF ??????? -???Flask/SQLite?create_order_extraction_run?project_conversation_processing? -????? queued / frozen-failed / completed???? PDF ????????hash ????? + processing OT PDF +Flask/SQLite?create_order_extraction_run?project_conversation_processing? + queued / frozen-failed / completed PDF hash """ from __future__ import annotations @@ -29,11 +29,11 @@ from tests.test_shipping_order_extraction_runs import _seed_run_input def _ensure_run_order_task(*, run, intake, document) -> None: """ - ????????? Candidate + OT???? Run.user_task_no? + Candidate + OT Run.user_task_no? - ??????? test_shipping_conversation_processing_api ??? - Candidate ? Run ???? OT ????? order_task ?? - ????? OT ??????? + test_shipping_conversation_processing_api + Candidate ? Run OT order_task + OT """ candidate = ShippingOrderCandidate.query.filter_by( order_extraction_run_id=int(run.id), @@ -63,7 +63,7 @@ def _ensure_run_order_task(*, run, intake, document) -> None: def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): - """???? Run ?????????? OT ??????""" + """ Run OT """ with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-A') run_processing, _ = create_order_extraction_run( @@ -135,10 +135,10 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): completed_nos = {row['user_task_no'] for row in projection.get('completed') or []} assert run_processing.user_task_no in processing_nos assert run_failed.user_task_no in needs_nos - # ???? completed ????????? completed ??? + # completed completed assert run_done.user_task_no in completed_nos - # ????????? OT ?????? + # OT all_nos = list(processing_nos | needs_nos | completed_nos) assert len(all_nos) == len(set(all_nos)) == 3 @@ -150,7 +150,7 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): assert 'view_details' in (failed_task.get('available_actions') or []) primary = failed_task.get('primary_action') assert primary - # ???cancel / view_details ???? CTA?BE-01?? + # cancel / view_details CTA?BE-01 assert primary not in {'cancel_task', 'cancel_run', 'view_details'} done_task = next( @@ -244,7 +244,7 @@ def test_same_attachment_fingerprint_across_ots_keeps_two_cards(app): def test_completed_current_run_hidden_after_viewed(app): - """UI-04??? completed ?????????""" + """UI-04 completed """ with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-DONE') run, _ = create_order_extraction_run( @@ -273,14 +273,14 @@ def test_completed_current_run_hidden_after_viewed(app): ) shown = after['processing'] + after['needs_action'] + list(after.get('completed') or []) assert all(row['user_task_no'] != run.user_task_no for row in shown) - # ?????? completed ?? history????????? + # completed history history_nos = {row['user_task_no'] for row in (after.get('history') or [])} assert run.user_task_no in history_nos assert after['summary']['history'] >= 1 def _set_run_documents(run, documents: list[dict]) -> None: - """?? Run ?? documents????????PDF ?????""" + """ Run documentsPDF """ snapshot = dict(run.input_snapshot_json or {}) intakes = list(snapshot.get('intakes') or []) if not intakes: @@ -293,7 +293,7 @@ def _set_run_documents(run, documents: list[dict]) -> None: def test_single_pdf_task_title_is_none_for_frontend_unified_label(app): - """BE-05?? PDF ?? title ?? None?????? document_names / objects?""" + """BE-05 PDF title None document_names / objects?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-1PDF') run, _ = create_order_extraction_run( @@ -321,7 +321,7 @@ def test_single_pdf_task_title_is_none_for_frontend_unified_label(app): row for row in projection['processing'] + projection['needs_action'] if row['user_task_no'] == run.user_task_no ) - # ???????????????????????????? title? + # title? assert task['title'] is None assert task['file_count'] == 1 assert task['display_kind'] == 'single_document_task' @@ -332,7 +332,7 @@ def test_single_pdf_task_title_is_none_for_frontend_unified_label(app): def test_multi_pdf_task_does_not_use_first_filename_as_title(app): - """? PDF ???title ???file_count=2?objects ????? PDF?""" + """? PDF title file_count=2?objects PDF?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-2PDF') run, _ = create_order_extraction_run( @@ -485,7 +485,7 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app): def test_same_filename_different_hash_counts_as_two_pdfs(app): - """???? hash?file_count=2???????????""" + """ hash?file_count=2""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-NAME') run, _ = create_order_extraction_run( @@ -525,7 +525,7 @@ def test_same_filename_different_hash_counts_as_two_pdfs(app): def test_same_hash_different_document_id_counts_as_one_pdf(app): - """? hash ?? document_id?????file_count=1?""" + """? hash document_idfile_count=1?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-HASH') run, _ = create_order_extraction_run( @@ -564,7 +564,7 @@ def test_same_hash_different_document_id_counts_as_one_pdf(app): ) assert task['file_count'] == 1 assert task['display_kind'] == 'single_document_task' - # BE-05: title ?? None?? hash ??????????? + # BE-05: title None hash assert task['title'] is None doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document'] assert len(doc_objects) == 1 @@ -572,7 +572,7 @@ def test_same_hash_different_document_id_counts_as_one_pdf(app): def test_sparse_snapshot_enriched_by_extraction_units(app): - """??? 1 PDF ? Unit ?? 2 ?????? multi + file_count=2?""" + """ 1 PDF ? Unit 2 multi + file_count=2?""" from app.models import ( FileAsset, ShippingOrderDocument, @@ -619,7 +619,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app): keep_input_open=True, ) _ensure_run_order_task(run=run, intake=intake, document=document) - # ???? 1 ??????????????????????? + # 1 _set_run_documents(run, [{ 'document_id': int(document.id), 'root_document_id': int(document.id), @@ -660,7 +660,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app): @pytest.mark.skip(reason='workflow ledger removed') def test_sparse_snapshot_enriched_by_workflow_items(app): - """??? 1 PDF ?? Run ?? 2 ? WorkflowItem ????? multi?""" + """ 1 PDF Run 2 ? WorkflowItem multi?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SPARSE-W') from app.models import FileAsset, ShippingOrderDocument diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 7208903a..437136cd 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -508,6 +508,77 @@ def test_order_task_current_gate_ignores_empty_review_case(app) -> None: assert item['current_gate'] is None +def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None: + """ + 无正式 Notice 时仍须读 OT 活跃 Execution,禁止 waiting_review 误合成 open_order_review。 + + 关键断言:库存满足性人工阻断(inventory_sufficiency)发生在 Notice 创建前; + work-item 右卡若回落 order_freeze_readiness,会永久显示「订单复核」而非缺口恢复。 + """ + 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.shipping_processing_projection import ( + get_shipping_processing_work_item, + ) + + user, agent, session, intake, _document = _seed_run_input(suffix='OT-EXEC-NO-NOTICE') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + task = ShippingOrderTask( + task_no='OT-EXEC-NO-NOTICE', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=run.id, + owner_agent_id=int(agent.id), + candidate_id=None, + status='waiting_review', + stage='step5_match_inventory', + progress_version=3, + ) + db.session.add(task) + db.session.flush() + execution = ShippingProcessExecution( + execution_no='SPE-OT-EXEC-NO-NOTICE', + task_id=int(task.id), + status='blocked', + current_gate_code='inventory_sufficiency', + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + task.active_process_execution_id = int(execution.id) + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code='inventory_sufficiency', + sequence_no=16, + status='blocked_manual', + evaluation_version=1, + lock_version=1, + blocking_reason_code='inventory_shortage_review_required', + next_action_code='open_shortage_review', + )) + run.user_task_no = task.task_no + db.session.commit() + + item = get_shipping_processing_work_item( + user_id=user.id, + work_item_type='order_task', + work_item_no=task.task_no, + ) + + assert item['current_gate']['gate_code'] == 'inventory_sufficiency' + assert item['current_gate']['next_action_code'] in { + 'open_shortage_review', + 'retry_inventory_matching', + 'retry_inventory_preparation', + } + assert item['current_gate']['next_action_code'] != 'open_order_review' + assert item['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert item['ui_state']['status'] == 'waiting_human' + primary = (item.get('ui_state') or {}).get('primary_action') or {} + assert str(primary.get('code') or '') != 'open_order_review' + + def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(app) -> None: """历史 OT 不能借同 Run 的当前 Candidate 显示另一 PDF 的订单生命周期。""" with app.app_context(): @@ -1411,6 +1482,96 @@ def test_summary_lifecycle_authority_is_processing_stage_for_stale_completed_tas assert payload['conversation_processing']['ui_state']['status'] == 'waiting_human' +def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app) -> None: + """首屏摘要必须按 OT.id 批量加载 ProcessExecution,禁止误用 candidate_id。 + + 回归:candidate.id ≠ OT.id 时,若用 tasks_by_candidate_id 的 key 去查 + ShippingProcessExecution.task_id,Gate 整批查空;叶子会退化成遗留 stage + + open_order_review,批次中心同时失去五阶段入口与门禁主按钮。 + """ + 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-OT-ID-NOT-CANDIDATE', + ) + # [STEP 1] 垫高 Candidate 序号,强制 candidate.id ≠ OT.id(SQLite 默认同号会掩盖 bug)。 + for idx in range(3): + db.session.add(ShippingOrderCandidate( + candidate_no=f'CAND-PAD-{idx}-{uuid.uuid4().hex[:8]}', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key=f'summary-pad-{idx}-{uuid.uuid4().hex[:8]}', + candidate_status='rejected', + is_current_version=False, + po_number=f'PO-PAD-{idx}', + )) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-SUMMARY-OT-ID-{uuid.uuid4().hex[:8]}', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key=f'summary-ot-id-{uuid.uuid4().hex[:8]}', + candidate_status='accepted', + is_current_version=True, + po_number='PO-SUMMARY-OT-ID', + ) + db.session.add(candidate) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-SUMMARY-OT-ID', + user_id=user.id, + conversation_id=session.session_id, + intake_id=intake.id, + candidate_id=candidate.id, + status='waiting_review', + stage='step3_inventory_prepare', + ) + db.session.add(order_task) + db.session.flush() + assert int(candidate.id) != int(order_task.id) + execution = ShippingProcessExecution( + execution_no='SPE-SUMMARY-OT-ID', + task_id=int(order_task.id), + status='blocked', + current_gate_code='inventory_preparation', + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + order_task.active_process_execution_id = int(execution.id) + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code='inventory_preparation', + sequence_no=13, + status='blocked_retryable', + evaluation_version=1, + lock_version=1, + blocking_reason_code='inventory_rpa_export_failed', + next_action_code='retry_inventory_preparation', + )) + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + 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 + ) + + # 关键断言:Gate 命中后五阶段与库存恢复主操作必须同时存在。 + assert leaf['current_gate']['gate_code'] == 'inventory_preparation' + assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert len(leaf['ui_state']['lifecycle_entries']) == 5 + assert leaf['ui_state']['primary_action']['code'] == 'retry_inventory_preparation' + assert leaf['ui_state']['primary_action']['code'] != 'open_order_review' + + def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -> None: """接收解析 Case 在详情与首屏摘要中均以重解析作为文件主动作。""" with app.app_context(): @@ -1632,7 +1793,7 @@ def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None: leaf = leaves[document_id] # [BE-05] 未确认 Candidate Review Case 由后端 bundle 权威裁决为 idle(待用户处置), # 用户阶段固定在订单复核;建单前 Gate 由 order_review_build / mark_non_order 唯一给出。 - assert leaf['user_status'] == 'idle' + assert leaf['user_status'] == 'waiting_human' assert leaf['user_stage'] == 'order_review' assert leaf['current_gate']['gate_code'] == 'order_review_build' assert leaf['current_gate']['next_action_code'] == 'mark_non_order' @@ -2481,7 +2642,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi assert result[0]['user_status'] == 'waiting_human' assert result[0]['user_stage'] == 'order_review' assert leaf['case_no'] == case.case_no - assert leaf['user_status'] == 'idle' + assert leaf['user_status'] == 'waiting_human' assert leaf['user_stage'] == 'order_review' assert leaf['current_gate']['gate_code'] == 'order_review_build' assert 'edit_draft' in leaf['available_actions'] diff --git a/backend/tests/test_shipping_projection_gate_equivalence.py b/backend/tests/test_shipping_projection_gate_equivalence.py index 7953cf37..6dcd4c61 100644 --- a/backend/tests/test_shipping_projection_gate_equivalence.py +++ b/backend/tests/test_shipping_projection_gate_equivalence.py @@ -417,13 +417,9 @@ def test_gate_maps_to_lifecycle_stage_b(app, gate_chain, scenario): gate_code=gate_code, status='blocked_manual', blocking_reason_code='inventory_preparation_failed', next_action_code='retry_inventory_preparation', ) - # 让 notice 路径(_process_gate_user_summary_for_task 按 task.id=notice.id 查 execution) - # 命中同一 execution:B 在生产中把 Notice 传给 build_task_ui_state。 - from app.models import ShippingProcessExecution - execution = db.session.get(ShippingProcessExecution, execution_id) - execution.task_id = int(notice.id) - db.session.commit() - + # 让 notice 路径经 order_task_id 命中同一 execution(B 在生产中把 Notice + # 传给 build_task_ui_state;Execution.task_id 必须保持为 OT.id)。 + assert int(notice.order_task_id) == int(order_task.id) from app.services.shipping_notice.ui_state import build_task_ui_state b = build_task_ui_state(notice) b_stage = str((b.get('stage') or {}).get('code') or '').strip() diff --git a/backend/tests/test_shipping_review_line_fulfillment_decision.py b/backend/tests/test_shipping_review_line_fulfillment_decision.py index 1a22f0c8..4be7ea24 100644 --- a/backend/tests/test_shipping_review_line_fulfillment_decision.py +++ b/backend/tests/test_shipping_review_line_fulfillment_decision.py @@ -160,6 +160,36 @@ def test_shortage_release_export_uses_audited_header_override_when_no_snapshot_c ) == [{'6': 'ODM-001'}] +def test_narrow_inventory_lines_keeps_only_reservation_and_part_hits(): + """导出匹配前必须按本单 reservation+part 裁剪,不得把全量快照送进逐行匹配。""" + from app.services.shipping_notice.export import ( + _narrow_inventory_lines_by_wanted_match_keys, + _wanted_order_match_keys, + ) + + order_lines = [ + {'ord_rsv': '3000112934', 'ord_part': 'D4-A08AR12000001'}, + ] + wanted = _wanted_order_match_keys( + order_lines, + order_field_ids=['ord_rsv', 'ord_part'], + ) + assert wanted == {('3000112934', 'd4-a08ar12000001')} + + inventory_lines = [ + {'inv_rsv': '3000112934', 'inv_part': 'D4-A08AR12000001', 'extra': 'HIT'}, + {'inv_rsv': '999', 'inv_part': 'OTHER', 'extra': 'MISS'}, + *[{'inv_rsv': f'R{i}', 'inv_part': f'P{i}', 'extra': 'NOISE'} for i in range(200)], + ] + narrowed = _narrow_inventory_lines_by_wanted_match_keys( + inventory_lines, + inventory_field_keys=['inv_rsv', 'inv_part'], + wanted_keys=wanted, + ) + assert len(narrowed) == 1 + assert narrowed[0]['extra'] == 'HIT' + + def test_shortage_release_export_allows_reservation_miss_when_template_uses_no_inventory_field(): """已审计短缺放行时,库存预约单未命中不能阻断只消费订单字段的 Excel。""" from app.services.shipping_notice.export import _match_inventory_lines diff --git a/backend/tests/test_shipping_review_workbench_state_isolation.py b/backend/tests/test_shipping_review_workbench_state_isolation.py index 24e55dc7..c0a0031e 100644 --- a/backend/tests/test_shipping_review_workbench_state_isolation.py +++ b/backend/tests/test_shipping_review_workbench_state_isolation.py @@ -16,9 +16,45 @@ from app.services.shipping_notice.order_review_projection import ( _inventory_rpa_is_running, _project_case_automation_status, ) +from app.services.shipping_notice.ui_state import _unified_actions +from app.services.shipping_notice.shipping_processing_projection import _processing_ui_state_from_item from app.services.shipping_notice.process_gate_projection import project_user_gate_summary +def test_unified_actions_keeps_blocked_gate_next_action_when_presentation_missing(): + """Gate 展示元数据缺失时仍保留已授权的库存 RPA 重试按钮。""" + result = _unified_actions(process_gate={ + 'next_action_code': 'retry_inventory_preparation', + 'current_blocking_gate': { + 'status': 'blocked_retryable', + 'gate_code': 'inventory_preparation', + 'next_action_code': 'retry_inventory_preparation', + }, + 'action_presentation': [], + }) + assert result['primary']['code'] == 'retry_inventory_preparation' + + +def test_processing_ui_state_backfills_blocked_gate_action(): + """工作项顶层动作缺失时,正式 Gate 恢复动作仍进入 ui_state 主动作。""" + result = _processing_ui_state_from_item({ + 'user_status': 'retryable', + 'user_stage': 'inventory_fetch', + 'process_gate': { + 'next_action_code': 'retry_inventory_preparation', + 'current_blocking_gate': { + 'status': 'blocked_retryable', + 'gate_code': 'inventory_preparation', + 'next_action_code': 'retry_inventory_preparation', + }, + }, + 'primary_action': None, + 'available_actions': [], + 'source_summary': {}, + }) + assert result['primary_action']['code'] == 'retry_inventory_preparation' + + def test_inventory_running_is_not_inferred_from_stage_automation_job(): """阶段推进 Job 运行中但未创建库存 Attempt 时,明细不得显示获取库存中。""" task = SimpleNamespace(task_no='OT-TEST-1') diff --git a/backend/tests/test_shipping_status_contract_hygiene.py b/backend/tests/test_shipping_status_contract_hygiene.py new file mode 100644 index 00000000..44967578 --- /dev/null +++ b/backend/tests/test_shipping_status_contract_hygiene.py @@ -0,0 +1,65 @@ +""" +tests/test_shipping_status_contract_hygiene.py + +用途:状态契约卫生门禁——禁止在 projector 白名单外扩散 synonym frozenset。 +依赖:pathlib、re、pytest。 +逻辑:扫描 services/shipping_notice/*.py;白名单内允许持有跨层翻译袋 + (upload_attempt_service、order_review_workbench_projection); + 另断言货代前端视图不再双读 pending_human_reason。 +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +BACKEND_ROOT = Path(__file__).resolve().parents[1] +SERVICES_DIR = BACKEND_ROOT / 'app' / 'services' / 'shipping_notice' +FRONTEND_FREIGHT_VIEW = ( + BACKEND_ROOT.parent + / 'frontend' + / 'src' + / 'features' + / 'chat' + / 'views' + / 'ShippingOrderReviewView.vue' +) + +# 允许持有跨层 synonym 袋的唯一投影模块。 +_WHITELIST = frozenset({ + 'upload_attempt_service.py', + 'order_review_workbench_projection.py', +}) + +# 读侧禁止外溢的典型 synonym 袋(字面量形态)。 +_FORBIDDEN_PATTERNS = ( + re.compile(r"\{['\"]cancelled['\"]\s*,\s*['\"]canceled['\"]"), + re.compile(r"\{['\"]canceled['\"]\s*,\s*['\"]cancelled['\"]"), + re.compile(r"\{['\"]succeeded['\"]\s*,\s*['\"]success['\"]\s*,\s*['\"]completed['\"]"), + re.compile(r"\{['\"]failed['\"]\s*,\s*['\"]dead['\"]"), + re.compile(r"\{['\"]uploaded['\"]\s*,\s*['\"]succeeded['\"]\s*,\s*['\"]success['\"]"), + re.compile(r"\{['\"]waiting_human['\"]\s*,\s*['\"]idle['\"]"), +) + + +@pytest.mark.pure_unit +def test_synonym_frozenset_only_in_whitelist_projectors(): + """白名单外不得出现状态同义词 frozenset/set 字面量。""" + offenders: list[str] = [] + for path in sorted(SERVICES_DIR.glob('*.py')): + if path.name in _WHITELIST or path.name.startswith('_'): + continue + text = path.read_text(encoding='utf-8') + for pattern in _FORBIDDEN_PATTERNS: + if pattern.search(text): + offenders.append(f'{path.name}: {pattern.pattern}') + assert not offenders, 'synonym bags leaked outside projectors:\n' + '\n'.join(offenders) + + +@pytest.mark.pure_unit +def test_freight_view_does_not_read_pending_human_reason(): + """货代上传 FE 禁止再双读 pending_human_reason(D1)。""" + text = FRONTEND_FREIGHT_VIEW.read_text(encoding='utf-8') + assert 'pending_human_reason' not in text diff --git a/backend/tests/test_shipping_stp_phase4_line_inventory_match.py b/backend/tests/test_shipping_stp_phase4_line_inventory_match.py index cedbcb8e..cf563018 100644 --- a/backend/tests/test_shipping_stp_phase4_line_inventory_match.py +++ b/backend/tests/test_shipping_stp_phase4_line_inventory_match.py @@ -145,6 +145,29 @@ def test_cross_candidate_marks_out_of_scope_when_only_disallowed_source_matches( assert result['line_results'][0]['out_of_candidate_scope'] is True +def test_match_without_source_tag_uses_reservation_and_part_only(): + """活动库存 Excel 行可不带 __source_code;匹配只按 Reservation ID + Part Number。""" + result = match_order_lines_across_candidates( + order_lines=[{ + 'part_number': 'D4-A08AR12000001', + 'reservation_id': '3000112934', + 'quantity': '3', + 'allowed_source_codes': ['DSV360_AWSSG'], + 'candidate_scope_present': True, + }], + inventory_lines=[ + {'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0}, + {'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0}, + {'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001', 'available_qty': 1.0}, + ], + ) + assert result['match_status'] == 'fulfillable' + assert result['line_results'][0]['disposition'] == 'ok' + assert result['line_results'][0]['available_qty'] == 3.0 + assert result['line_results'][0]['shortage_qty'] == 0.0 + assert result['line_results'][0]['resolved_inventory_source_code'] == 'DSV360_AWSSG' + + def test_header_reservation_fallback_for_match(): """行缺 Reservation 时可回退头级有效 Reservation。""" result = match_order_lines_across_candidates( diff --git a/backend/tests/test_shipping_task_center_review_run_deep_link.py b/backend/tests/test_shipping_task_center_review_run_deep_link.py index a3f9c7e5..be8b999d 100644 --- a/backend/tests/test_shipping_task_center_review_run_deep_link.py +++ b/backend/tests/test_shipping_task_center_review_run_deep_link.py @@ -1,16 +1,18 @@ """ backend/tests/test_shipping_task_center_review_run_deep_link.py -用途:验收任务中心 Notice 摘要注入 review_run_no,供 UI-04 深链订单处理工作台。 +用途:验收任务中心 Notice/OT 摘要注入 review_run_no 与 order_task_no,供 UI-04 深链 + 与工作台右卡 work-item 投影键。 依赖:query_service._inject_unified_processing_fields、ShippingOrderTask、pytest。 -逻辑:OT 挂 extraction_run 时 SUMMARY 必含 review_run_no / owner_agent_id。 +逻辑:Notice 挂 OT 时 SUMMARY 必含 review_run_no;直接序列化 OT 时 order_task_no + 必须等于自身 task_no(禁止 enrich 冲成 null)。 """ from __future__ import annotations from app import db from app.models import ShippingNotice, ShippingOrderTask -from app.services.shipping_notice.query_service import serialize_task_summary +from app.services.shipping_notice.query_service import serialize_task_detail, serialize_task_summary def test_serialize_task_summary_injects_review_run_no_for_order_processing_deeplink(app): @@ -51,3 +53,48 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl assert data['order_task_no'] == 'OT-TC-DEEPLINK-1' assert data['review_run_no'] == run.run_no assert int(data.get('owner_agent_id') or 0) == int(agent.id) + + +def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app): + """ + OT 自序列化后 enrich 不得把 order_task_no 冲成 null。 + + 关键断言:工作台右卡权威投影键 authoritativeOrderTaskNo 依赖详情里的 + order_task_no;若 enrich 只认 Notice.order_task_id,OT 自身会被写成 null, + 右卡永久停在「正在获取最新状态 / 待机」。 + """ + 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 + + user, agent, session, intake, _document = _seed_run_input(suffix='TC-OT-SELF') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + order_task = ShippingOrderTask( + task_no='OT-TC-OT-SELF-1', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=int(run.id), + owner_agent_id=int(agent.id), + status='waiting_review', + stage='step5_match_inventory', + progress_version=3, + ) + db.session.add(order_task) + db.session.flush() + run.user_task_no = order_task.task_no + run.owner_agent_id = int(agent.id) + db.session.commit() + + summary = serialize_task_summary(order_task, viewer_user_id=user.id) + detail = serialize_task_detail( + order_task, + viewer_user_id=user.id, + include_stage_context=True, + view='workbench', + ) + # 关键断言:SUMMARY / DETAIL 在 enrich 后仍保留自身 OT 号与深链 Run。 + assert summary['order_task_no'] == 'OT-TC-OT-SELF-1' + assert summary['review_run_no'] == run.run_no + assert detail['order_task_no'] == 'OT-TC-OT-SELF-1' + assert detail['task_no'] == 'OT-TC-OT-SELF-1' + assert detail['review_run_no'] == run.run_no diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index b3ecd4be..c45a9192 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -281,8 +281,8 @@ def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app): mark_attempt_result_unknown(attempt) state = resolve_task_ui_state(task) - assert state.checkpoint == 'upload_result_unknown' - # checkpoint 仅描述内部流程;下载与人工凭据登记必须由 Gate/Artifact 下发。 + # 无 Gate 时薄回退不从 upload attempt 投影位置;动作由 Gate/Artifact 下发。 + assert state.position is None assert not hasattr(state, 'human_options') assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' diff --git a/docs/platform/integration-connector-framework-design.md b/docs/platform/integration-connector-framework-design.md index f5576512..f8c73153 100644 --- a/docs/platform/integration-connector-framework-design.md +++ b/docs/platform/integration-connector-framework-design.md @@ -9,7 +9,7 @@ | 关联文档 | [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) | | 首个消费者 | 在途仓自动调拨(`in_transit_transfer`) | -> 本文是既有《HXOPS 企业集成中心与在途仓自动调拨原型设计》(`enterprise-integration-center-prototype.md`)的**首期收敛版**。蓝图描绘的是平台级完整愿景;本文只规定**先落地的那个最小闭环**,避免一次性建成完整 iPaaS 导致的过度设计。蓝图未在本文明示的能力(流程编排、Saga 补偿、Schema Registry、发布中心、Mock/契约测试、可观测、灾备等)一律视为**后续平台化能力**,不在首期范围。 +> 本文是既有《HXOPS 企业集成中心与在途仓自动调拨原型设计》(`enterprise-integration-center-prototype.md`)的可落地设计。目标是直接建设通用连接器配置能力,同时控制边界:不引入低代码流程编排、任意脚本执行等与当前业务无关的 iPaaS 能力。蓝图中的高级能力(Saga 补偿、Schema Registry、灾备等)保留为后续演进项。 --- @@ -72,16 +72,18 @@ ## 3. 核心概念与实体 -### 3.1 配置实体(6) +### 3.1 配置实体(5 个核心表 + 代码注册能力) | 实体 | 存哪 | 职责 | | --- | --- | --- | -| **ConnectorType 连接器类型** | 代码 + 目录 | Transport 实现:首期 `REST`、`SOAP`;后置 `RPA`、`SQL`、`FILE` | +| **ConnectorType 连接器类型** | 代码常量 | Transport 实现:首期 `REST`、`SOAP`;后置 `RPA`、`SQL`、`FILE`,不单独建表 | | **ClientInstance 客户端实例** | DB | 一份连接配置:连到哪、凭据引用、超时/TLS、默认 org/租户 | -| **InterfaceDefinition 接口定义** | DB | 一个可调操作:请求模板 + 参数 Schema + 返回值映射 + 成功/错误条件 | -| **Binding 绑定** | DB | `(Capability, context_selector) → (ClientInstance + InterfaceDefinition + mapping_version)`,含版本/生效区间/优先级/状态 | +| **InterfaceDefinition 接口定义(按版本存储)** | DB | 一个可调操作;每个版本一行,包含请求/响应配置、消息配置、映射、Schema、测试配置和发布状态 | +| **Binding 绑定** | DB | `(Capability, context_selector) → (ClientInstance + InterfaceDefinition 版本)`,含版本/生效区间/优先级/状态 | | **CredentialReference 凭据引用** | DB | 仅存 `secret_ref` + 元数据;真实凭据由 Secret 服务注入,不回显 | -| **Capability 业务能力** | 代码注册 + DB 目录 | 强类型契约(见 §4) | +| **Capability 业务能力** | 代码注册 + DB 目录 | 强类型契约(见 §4),不依赖连接器配置表动态生成业务逻辑 | + +> 当前不单独建立 `Connector`、`MessageProfile`、`MappingVersion`、`Fixture` 表,也不把每个 Header、XML 节点或映射字段拆成关系表。接口版本是配置冻结边界:稳定身份、版本、状态、路由、安全和审计字段使用关系列;协议细节、模板、映射和测试引用使用 JSONB。未来只有在出现跨接口复用、独立权限/查询或统计需求时再拆表。 ### 3.2 运行时实体(2) @@ -92,6 +94,24 @@ > 审计事件可关联以上两个实体,但**审计表不承担运行状态**;运行状态归 IntegrationCall / IntegrationAsyncTask。 +### 3.3 关系字段与 JSONB 边界 + +**必须使用独立列**:主键、业务编码、外键、能力、连接器类型、端点、环境、版本、状态、启用标记、凭据引用、优先级、生效时间、超时、创建/更新时间,以及需要索引、唯一约束、权限、路由、统计或审计的字段。 + +**放入接口版本 JSONB**:REST 请求头/路径/Body 模板,SOAP 版本、命名空间、操作包装、`SOAPAction`、CDATA 和响应解码规则,请求/响应字段映射、白名单转换、成功/失败规则、输入输出 Schema、分页/分片/大小限制和协议扩展参数。 + +**大报文与 Golden Fixture**:真实请求/响应样例不直接塞入接口表;首期使用受控文件或对象存储,并在接口版本 JSON 中保存样例引用、校验和及场景标识。只有需要在线维护、权限管理或测试统计时才独立建 Fixture 表。 + +接口版本建议至少包含以下 JSONB 字段: + +```text +request_config_json +response_config_json +input_schema_json +output_schema_json +test_config_json +``` + --- ## 4. Capability 强类型契约 @@ -123,7 +143,6 @@ capability context_selector # 来源/组织/租户/环境等路由条件(含默认绑定) client_instance # 版本引用 interface_definition # 版本引用 -mapping_version priority environment effective_from / effective_to @@ -131,7 +150,7 @@ status # draft / published / retired ``` - 配置修改**不能影响运行中的任务**。 -- 一次 Run 创建时必须冻结:`ClientInstance 版本`、`InterfaceDefinition 版本`、`Binding 版本`、`Mapping 版本`、`Credential 引用版本`。 +- 一次 Run 创建时必须冻结:`ClientInstance 版本`、`InterfaceDefinition 版本(含消息与映射 JSON)`、`Binding 版本`、`Credential 引用版本`。 --- @@ -174,6 +193,102 @@ rest.call(interface, client, request) -> raw_response soap.call(interface, client, request) -> raw_response ``` +### 7A. 标准 DTO 到目标系统请求的映射模型 + +领域层只传入能力定义的标准 DTO。连接器运行时按以下顺序完成转换: + +```text +标准 Capability DTO + → 输入校验/规范化 + → 声明式字段映射(标准字段 → 目标字段) + → Target Request Model(目标请求模型) + → Message Profile + Serializer(报文包装与序列化) + → Transport(SOAP/REST/...) +``` + +- **简单字段**:例如 `lot` → `img04`、`warehouse` → `img02`,通过路径映射和类型转换完成。 +- **数组/重复节点**:例如多个批号映射为多个 `Record`,由映射引擎按集合展开,禁止领域层拼接 XML。 +- **受控业务转换**:批号集合拼接、分片、日期/数量格式化等只能调用代码注册的白名单函数(如 `controlled_lot_condition`),不能执行任意脚本、SQL 或模板代码。 +- **缺失与冲突**:必填字段缺失、类型不符、映射产生非法结构时立即失败(fail-closed),并返回可定位的字段错误。 +- **输出**:目标响应先按协议解码,再按声明式映射转成标准输出 DTO,并通过 Capability 输出 Schema 校验。 + +映射配置建议采用结构化 JSON,而非自由文本表达式。例如: + +```json +{ + "fields": [ + {"source": "warehouse", "target": "img02", "required": true}, + {"source": "lots", "target": "img04", "expand": "record", "required": true} + ] +} +``` + +### 7B. Message Profile 与 Transport 分离 + +SOAP Transport 只负责 HTTP/SOAP 通讯(URL、TLS、超时、认证、响应状态),不写死任何供应商的操作名或 XML 结构。接口版本 JSON 中的 `message` 配置(逻辑上的 Message Profile,不单独建表)负责协议消息细节: + +- SOAP 版本、Envelope/Body 命名空间; +- 操作元素名称及命名空间; +- `SOAPAction`(包括必须为空字符串的场景); +- 请求参数承载方式(元素、属性、CDATA、纯文本或 JSON); +- body wrapper、内层根节点、重复节点规则; +- 响应外层路径、转义字符串二次解析规则及错误定位。 + +因此 `GetItemStockListRequest`、`RequestContent`、`img01` 等均属于接口版本的消息配置,不属于通用代码。REST 也采用同样的“请求模板 + 序列化器”模型,以便未来接入非 TIPTOP SOAP 服务。配置引擎必须能够从标准 DTO 完整生成最终 HTTP 报文,而不是要求领域层预先拼接目标 XML/JSON。 + +### 7C. WSDL 自动发现、确认与版本冻结 + +WSDL 仅用于生成接口草稿,不能直接作为生产运行时的唯一真相: + +1. 导入 WSDL,发现 service/port/binding/operation、命名空间、SOAP 版本和默认 action; +2. 生成可编辑草稿,并标出 WSDL 无法确定的字段承载方式(如 CDATA 内嵌 XML); +3. 使用真实测试报文进行连接测试和试运行,人工确认请求/响应路径及映射; +4. 发布后生成不可变版本,后续修改必须创建新版本并重新测试; +5. 运行中的 Run 固定引用的版本,禁止配置热变更影响执行。 + +### 7D. TIPTOP Gateway Profile 示例(非通用约束) + +当前 TIPTOP Gateway 可建为 `tiptop_gateway_v1` Message Profile,仅作为一个外部系统适配示例: + +- SOAP 1.1,`SOAPAction` 按对方要求配置(成功样例为空字符串); +- Body 操作包装名由接口定义/WSDL 草稿确认,例如 `GetItemStockListRequest`; +- `request` 参数承载 CDATA 内嵌业务 XML; +- 业务 XML 包含 `Access`、`RequestContent/Parameter/Record/Field`; +- 响应的 `response` 可能是 XML 转义字符串,需先 XML decode,再解析 `Response/Execution/Status` 和 `Document/RecordSet`; +- `Field[@name,@value]` 转换为标准库存记录,具体 `img` 字段字典必须在接口映射中维护。 + +用户名、密码、应用 ID 等只引用 Secret,占位符或 Secret 引用不得在文档、日志和配置快照中保存明文。 + +### 7E. 批号库存批量查询与分片 + +自动调拨输入是收料文件中的批号集合,标准输入示例: + +```json +{"warehouse": "HTP-D43", "lots": ["HOW25071402", "HOW25071403"]} +``` + +连接器必须支持一次请求携带多个批号,不能按批号逐条调用。由于外部系统存在报文大小、网关超时和 XML/JSON 解析限制,接口定义应配置: + +- 最大批号数、最大请求字节数、最大响应字节数; +- 超限时按稳定顺序自动分片; +- 分片并发上限、单片超时、失败策略(是否整体失败); +- 分片结果按批号/料号等业务键去重、合并并保持可追溯的 `trace_id`。 + +分片不是领域规则,属于连接器执行策略;数量核对、来源隔离和调拨决策仍由领域层负责。 + +### 7F. 配置测试与发布门禁 + +每个接口版本至少通过以下测试后才能发布: + +- schema 校验:标准输入、必填项、数组边界、非法类型; +- golden request:生成报文与已确认样例逐项比对(命名空间、wrapper、SOAPAction、CDATA); +- golden response:覆盖成功、业务失败、技术失败、空结果和 XML 转义响应; +- 大批量测试:验证分片、合并、超时和大小上限; +- 安全测试:凭据脱敏、禁止任意表达式、禁止客户端覆盖 `interface_id`; +- 回归测试:输出 DTO 与领域层契约保持兼容。 + +连接测试只证明网络和认证可用;接口试运行还必须证明请求结构、响应解析和业务映射均正确。任何一项失败都不得发布。 + --- ## 8. RPA 与异步执行(后置,但契约先定) @@ -323,7 +438,7 @@ SQL 连接器除"默认只读"外,还须: ### 14.1 首期最小可行(MVP) -实体:`Capability`、`ClientInstance`、`InterfaceDefinition`、`Binding`、`CredentialReference`、`IntegrationCall`。 +实体:5 个核心配置/运行表(`ClientInstance`、按版本存储的 `InterfaceDefinition`、`Binding`、`CredentialReference`、`IntegrationCall`);`Capability` 由代码注册,`ConnectorType` 由代码实现。 Transport:仅 `REST`、`SOAP`。 @@ -339,16 +454,15 @@ verify_duplicate # 确认重复 Invoice 对应原单 | 阶段 | 内容 | 明确不做 | | --- | --- | --- | -| **P0** | 稳定现有调拨业务闭环;ERP 调用收敛为内部 Adapter | 通用配置页 | -| **P1** | 连接器内核:`CapabilityGateway` + REST/SOAP Transport + ClientInstance/InterfaceDefinition/Binding + 版本化配置 + Secret 引用 + 连接测试/接口试运行;`query_inventory` 首个配置绑定消费者 | 通用接口设计器、任意表达式编辑器、SQL/RPA/FILE | -| **P2** | 配置作业 UI(草稿→校验→测试→试运行→预览→发布→回滚/停用)+ AI 暴露(只暴露 3 能力) | interface_id 直传、原始接口暴露 | -| **P3** | 异步与更多协议:RPA / FILE / Webhook / MQ / MCP / SQL 只读查询 | 低代码编排、脚本转换 | +| **P0** | 连接器内核与通用配置闭环:`CapabilityGateway` + REST/SOAP Transport + ClientInstance/InterfaceDefinition/Binding + 版本化配置 + Secret 引用 + 连接测试/接口试运行;`query_inventory` 首个配置绑定消费者 | 任意脚本转换、低代码流程编排 | +| **P1** | 配置作业 UI(草稿→校验→测试→试运行→预览→发布→回滚/停用)+ AI 暴露(只暴露治理后的能力) | interface_id 直传、原始接口暴露 | +| **P2** | 异步与更多协议:RPA / FILE / Webhook / MQ / MCP / SQL 只读查询 | 不受控的通用脚本执行 | --- ## 15. 落地文件与数据迁移(P1 起) -- 模型:`app/models/integration_connector.py`(ClientInstance / InterfaceDefinition / Binding / CredentialReference / IntegrationCall / IntegrationAsyncTask) +- 模型:`app/models/integration_connector.py`(ClientInstance / 按版本存储的 InterfaceDefinition / Binding / CredentialReference / IntegrationCall;异步能力启用后再增加 IntegrationAsyncTask) - 服务:`app/services/integration_connector/`(`capability.py` / `binding.py` / `engine.py` / `mapping.py` / `transports/rest.py` / `transports/soap.py` / `descriptors.py` / `security.py`) - API:`app/api/integration_connector.py`(Admin CRUD + 能力调用端点 + 工具清单) - Admin UI:`frontend/src/features/admin/modules/integration-connector/`(客户端配置作业) @@ -369,12 +483,15 @@ verify_duplicate # 确认重复 Invoice 对应原单 ## 17. 首期验收标准 - 新增外部系统实例(换系统)无需修改调拨领域代码; -- 修改外部字段路径仅需发布新映射版本; +- 修改外部字段路径需发布新的 `InterfaceDefinition` 版本; - 一次 Run 能追溯到冻结的全部配置版本; - 原始 SOAP/REST 报文不进入调拨领域表; - 凭据不回显、不写日志、不进快照; - AI / 外部应用只能调用治理过的 Capability,无法传入 `interface_id` 或原始接口参数; - 数量严格匹配、D+1、写前复查、`result_unknown` 禁重试等规则仍在领域层生效。 +- SOAP 报文可由配置完整生成并解析:支持命名空间、wrapper、SOAPAction、CDATA/内嵌 XML、XML 属性字段及转义响应。 +- 多批号库存查询支持单次批量请求、大小限制下自动分片及结果合并,不产生逐批号调用风暴。 +- WSDL 导入可生成草稿;人工确认后发布冻结版本,golden request/response 和边界测试全部通过。 --- diff --git a/frontend/src/constants/shippingNoticeActions.ts b/frontend/src/constants/shippingNoticeActions.ts index 115507fb..eb0f5fcb 100644 --- a/frontend/src/constants/shippingNoticeActions.ts +++ b/frontend/src/constants/shippingNoticeActions.ts @@ -24,8 +24,6 @@ export type ShippingActionId = (typeof SHIPPING_ACTION_IDS)[number]; export const SHIPPING_KNOWN_ACTION_ID_SET = new Set(SHIPPING_ACTION_IDS); /** Backend state-machine codes — must never appear in user-visible chat text. */ -export const SHIPPING_TERMINAL_CHECKPOINTS = new Set(['uploaded', 'completed', 'rejected']); - export const SHIPPING_INTERNAL_STATUS_TOKENS = [ 'rpa_pending', 'upload_rpa_pending', diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLineNoOverrideDialog.vue b/frontend/src/features/chat/components/shipping-review/ReviewLineNoOverrideDialog.vue deleted file mode 100644 index c0558974..00000000 --- a/frontend/src/features/chat/components/shipping-review/ReviewLineNoOverrideDialog.vue +++ /dev/null @@ -1,259 +0,0 @@ - - - -