""" services/shipping_notice/query_service.py 用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、 ShippingReservation、ShippingOrderReviewCase、ShippingOrderExtractionRun、state_machine、动态订单字段编辑器。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉; SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event; list_my_todos / count_my_todos 合并建单前 Review Case 与 Task 待办(管理员可读全局,仅创建者 can_handle); 客户关键字 SQL 同时过滤 Review Case(文件名/Case 号/PO)与 Task(客户快照/来源文件名); 待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT, 仅水合当前页(禁止 500 截断冒充总数); DETAIL 另投影 parse_validation / process_field_gate / source_candidate 与履约时间线(Reservation/Artifact); 订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。 """ from __future__ import annotations import re from enum import Enum from pathlib import Path from typing import Any from sqlalchemy import String, asc, case, cast, desc, exists, func, literal, select, union_all from app import db from app.models import ( ShippingBatch, ShippingCase, ShippingExportArtifact, ShippingExportArtifactLine, ShippingInventoryVerification, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, ShippingOrderExtraction, ShippingOrderExtractionRun, ShippingOrderLine, ShippingOrderReviewCase, ShippingReservation, ShippingTask, 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, PH_NOTICE_TEXT_EXTRACTION_FAILED, PH_RPA_EXHAUSTED, PH_RPA_PENDING, PH_RSV_REQ, PH_SHORTAGE, PH_UPLOAD_RESULT_UNKNOWN, PH_UPLOAD_RPA_FAILED, PH_UPLOAD_RPA_PENDING, RS_PARSE_REVIEW, RS_REJECTED, RS_RSV_REQ, RS_SHORTAGE_REVIEW, ) from app.services.shipping_notice.state_machine import ( CheckpointKind, 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, current_line_field_values_or_empty, current_order_field_display_or_empty, ) EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" _TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE) _BUSINESS_NO_RE = re.compile(r"(? dict[str, list[dict[str, Any]]]: """为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。""" verifications = ShippingInventoryVerification.query.filter_by(task_id=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() 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() } reservations_by_artifact: dict[int, list[str]] = {} for line in artifact_lines: reservations_by_artifact.setdefault(int(line.artifact_id), []).append( reservation_ids.get(int(line.reservation_id), str(line.reservation_id)) ) attempts = ShippingUploadAttempt.query.filter( ShippingUploadAttempt.artifact_id.in_(artifact_ids), ).order_by(ShippingUploadAttempt.created_at, ShippingUploadAttempt.id).all() if artifact_ids else [] return { 'inventory_verifications': [{ 'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.inventory_snapshot_id, 'source_config_version': item.source_config_version, 'created_at': item.created_at.isoformat() if item.created_at else None, 'lines': [{ 'reservation_id': reservation_ids.get(int(line.reservation_id), str(line.reservation_id)), 'required_qty': str(line.required_qty), 'available_qty': str(line.available_qty), 'status': line.status, } for line in item.lines], } for item in verifications], 'export_artifacts': [{ 'id': item.id, 'artifact_no': item.artifact_no, 'status': item.status, 'file_name': item.file_name, 'file_size': item.file_size, 'created_at': item.created_at.isoformat() if item.created_at else None, 'reservation_ids': reservations_by_artifact.get(int(item.id), []), } for item in artifacts], 'upload_attempts': [{ 'id': item.id, 'artifact_id': item.artifact_id, 'attempt_no': item.attempt_no, 'mode': item.mode, 'status': item.status, 'callback_id': item.callback_id, 'freight_ref_no': item.freight_ref_no, 'error_code': item.error_code, 'error_message': item.error_message, 'evidence_asset_id': item.evidence_asset_id, 'operator_id': item.operator_id, 'started_at': item.started_at.isoformat() if item.started_at else None, 'finished_at': item.finished_at.isoformat() if item.finished_at else None, 'created_at': item.created_at.isoformat() if item.created_at else None, } for item in attempts], } def _task_batch_no(task: ShippingTask) -> str | None: if task.batch is not None and task.batch.batch_no: return task.batch.batch_no return None def task_sort_key(task: ShippingTask) -> tuple[int, str]: """批次内任务排序键:batch_index 优先,其次 created_at。""" return ( task.batch_index if task.batch_index is not None else 10**9, task.created_at.isoformat() if task.created_at else "", ) def sort_batch_tasks(tasks: list[ShippingTask]) -> list[ShippingTask]: """按 batch_index、created_at 对批次任务列表排序(返回新列表)。""" return sorted(tasks, key=task_sort_key) def get_task_by_ref(task_ref: str) -> ShippingTask | None: """按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。""" value = str(task_ref or "").strip() if not value: return None task = ShippingTask.query.filter_by(task_no=value).first() if task: return task case = db.session.query(ShippingCase).filter_by(business_no=value.upper()).first() if case is not None: visited: set[int] = set() while case.id not in visited: visited.add(int(case.id)) replacement = ( db.session.query(ShippingCase) .filter_by(replaces_case_id=case.id) .order_by(ShippingCase.id.desc()) .first() ) if replacement is None: break case = replacement return ( db.session.query(ShippingTask) .filter_by(shipping_case_id=case.id) .order_by(ShippingTask.document_version.desc(), ShippingTask.id.desc()) .first() ) if value.isdigit(): return db.session.get(ShippingTask, int(value)) return None def get_batch_by_no(batch_no: str) -> ShippingBatch | None: """按 batch_no 查找批次(不做用户权限校验)。""" value = str(batch_no or "").strip() if not value: return None return ShippingBatch.query.filter_by(batch_no=value).first() def resolve_order_extraction_ui_target( *, user_id: int, conversation_id: str, intake_nos: list[str], ) -> tuple[ShippingBatch | None, ShippingTask | None]: """ 按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。 核心逻辑:先查当前用户、当前会话、指定 Intake 直接消费的新 Batch;没有新 Batch 时, 再沿 Candidate.consumed_task_id 查找打开的既有 Task。禁止回退到“用户最近批次”,避免并发会话串单。 Args: user_id: 当前聊天用户 ID。 conversation_id: 当前 HXOPS ChatSession.session_id。 intake_nos: 本轮 agent_runtime_context.refs.intake_nos。 Returns: `(batch, task)`;新建批次时 batch 非空,只有 open_existing 时 task 非空。 """ normalized = sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()}) session_id = str(conversation_id or '').strip() if not normalized or not session_id: return None, None intakes = ( db.session.query(ShippingNoticeIntake) .filter( ShippingNoticeIntake.user_id == int(user_id), ShippingNoticeIntake.conversation_id == session_id, ShippingNoticeIntake.intake_no.in_(normalized), ) .order_by(ShippingNoticeIntake.id.asc()) .all() ) if {item.intake_no for item in intakes} != set(normalized): return None, None batch_ids = [int(item.consumed_batch_id) for item in intakes if item.consumed_batch_id is not None] if batch_ids: batch = ( db.session.query(ShippingBatch) .filter( ShippingBatch.id.in_(batch_ids), ShippingBatch.user_id == int(user_id), ShippingBatch.conversation_id == session_id, ) .order_by(ShippingBatch.created_at.desc(), ShippingBatch.id.desc()) .first() ) if batch is not None: return batch, None task = ( db.session.query(ShippingTask) .join(ShippingNoticeCandidate, ShippingNoticeCandidate.consumed_task_id == ShippingTask.id) .filter( ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]), ShippingTask.user_id == int(user_id), ) .order_by(ShippingNoticeCandidate.id.asc(), ShippingTask.id.asc()) .first() ) return None, task def get_task_in_batch(batch_no: str, task_no: str) -> ShippingTask | None: """查找属于指定批次的任务;批次不存在或任务不在批次内时返回 None。""" batch = get_batch_by_no(batch_no) if not batch: return None task = get_task_by_ref(task_no) if not task or task.batch_id != batch.id: return None return task def resolve_task_export_download(task: ShippingTask | None) -> tuple[Path, str] | None: """解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。""" if not task or not task.export_file_path: return None from app.models import ShippingExportArtifact artifact = ShippingExportArtifact.query.filter_by( task_id=task.id, status='ready', file_path=task.export_file_path, ).order_by( ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(), ).first() if artifact is None: return None path = Path(artifact.file_path) if not path.is_file(): return None return path, artifact.file_name or path.name def task_export_error_message(task: ShippingTask | None) -> str: """导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。""" if not task or task.id is None or not task.export_file_path: return "export file not found" resolved = resolve_task_export_download(task) if resolved is None: return "export file missing on disk" return "" def list_sorted_batch_tasks(batch: ShippingBatch) -> list[ShippingTask]: """返回批次下已排序的任务 ORM 列表。""" return sort_batch_tasks(list(batch.tasks or [])) def list_batch_task_summaries(batch: ShippingBatch) -> list[dict[str, Any]]: """返回批次下已排序任务的摘要投影列表(含任务中心 enrich 字段)。""" return [serialize_task_summary(item) for item in list_sorted_batch_tasks(batch)] def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]: """批次进度汇总(Tool / 工作台 / 写回 batch.process_summary_json 共用公式)。""" total = len(tasks) completed = sum(1 for item in tasks if item.process_status in {"uploaded", "completed", "closed"}) failed = sum(1 for item in tasks if item.process_status in {"rejected"} or item.upload_status == "failed") running = sum(1 for item in tasks if item.process_status not in {"uploaded", "completed", "closed", "rejected"}) pending = sum(1 for item in tasks if item.process_status in {"created", "pending_review"} or not item.current_step) focus = next( ( item for item in sort_batch_tasks(tasks) if item.process_status not in {"uploaded", "completed", "closed", "rejected"} ), None, ) return { "total": total, "completed": completed, "failed": failed, "running": running, "pending": pending, "current_index": int(focus.batch_index or 0) if focus else (total if total else 0), "current_task_no": focus.task_no if focus else None, } def _is_task_completed(task: ShippingTask) -> bool: """判断任务是否已进入完成态,用于会话级聚合统计。""" return str(task.process_status or "").strip().lower() in {"uploaded", "completed", "closed"} def _is_task_failed(task: ShippingTask) -> bool: """判断任务是否失败或上传失败,用于会话级异常优先展示。""" return ( str(task.process_status or "").strip().lower() in {"rejected"} or str(task.upload_status or "").strip().lower() == "failed" ) def _is_task_needs_human(task: ShippingTask) -> bool: """判断任务是否停在人工门;失败态不重复计入人工门。""" if _is_task_failed(task) or _is_task_completed(task): return False return bool(getattr(task, "review_status", None) or getattr(task, "pending_human_reason", None)) def _is_task_active(task: ShippingTask) -> bool: """判断任务是否仍处于自动执行或等待外部系统返回的状态。""" if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task): return False status = str(task.process_status or "").strip().lower() return status not in {"created", "pending_review"} and bool(status) def compute_conversation_workspace_summary(batches: list[ShippingBatch]) -> dict[str, int]: """按会话聚合多个批次的状态计数,供 Agent 会话级工作台展示。""" tasks: list[ShippingTask] = [] for batch in batches: tasks.extend(list(batch.tasks or [])) completed = sum(1 for task in tasks if _is_task_completed(task)) failed = sum(1 for task in tasks if _is_task_failed(task)) needs_human = sum(1 for task in tasks if _is_task_needs_human(task)) running = sum(1 for task in tasks if _is_task_active(task)) pending = max(0, len(tasks) - completed - failed - needs_human - running) return { "batch_count": len(batches), "total": len(tasks), "completed": completed, "running": running, "failed": failed, "needs_human": needs_human, "pending": pending, } def extract_task_no_from_text(text: str) -> str | None: """从自然语言文本中提取 SN 技术号或客户业务号。""" raw = str(text or "") match = _TASK_NO_RE.search(raw) or _BUSINESS_NO_RE.search(raw) return match.group(0).upper() if match else None def resolve_task_from_payload( payload: dict[str, Any], *, allow_conversation_fallback: bool = True, ) -> ShippingTask | None: """ 按 task_id/task_no、文本内嵌 SN- 或 conversation_id 解析任务(只读)。 核心逻辑:显式任务号永远优先;conversation_id 仅在同会话下只有一票可操作任务时回退, 多票场景返回 None,避免用户只说“确认/继续”时误推进最近一票。 """ if not isinstance(payload, dict): return None for key in ("task_id", "task_no"): task = get_task_by_ref(str(payload.get(key) or "")) if task: return task for key in ("comment", "user_message", "raw_text", "query"): hint = extract_task_no_from_text(str(payload.get(key) or "")) if hint: task = get_task_by_ref(hint) if task: return task if not allow_conversation_fallback: return None conv_id = str(payload.get("conversation_id") or "").strip() if conv_id: candidates = ( ShippingTask.query.filter_by(conversation_id=conv_id) .filter(ShippingTask.process_status.notin_(["rejected", "closed", "uploaded"])) .order_by(ShippingTask.id.desc()) .limit(2) .all() ) if len(candidates) == 1: return candidates[0] return None def _task_tool_payload(task: ShippingTask) -> dict[str, Any]: """Tool data 基础字段(裁剪前)。""" 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) payload: dict[str, Any] = { "task_no": task.task_no, "shipping_case_id": task.shipping_case_id, "case_no": task.shipping_case.case_no if task.shipping_case else None, "business_no": task.shipping_case.business_no if task.shipping_case else None, "process_status": task.process_status, "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'), "customer_code": header.get('customer_code'), "customer_resolution_status": task.customer_resolution_status, "customer_resolution_method": task.customer_resolution_method, "customer_id": task.shipping_case.customer_id if task.shipping_case else None, "customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None, "customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None, "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, "conversation_id": task.conversation_id, "step_payload": step_payload, "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() lines = payload["lines"] from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task) # Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。 if raw_content and (not lines or str(task.process_status or "").strip().lower() == "created"): limit = max_notice_chars() payload["raw_text"] = raw_content[:limit] if len(raw_content) > limit else raw_content if len(raw_content) > limit: payload["raw_text_truncated"] = True return payload def _serialize_inventory_snapshot(task: ShippingTask) -> dict[str, Any] | None: """工作台任务摘要中的库存快照投影。""" from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link return serialize_inventory_snapshot_link(task) def _task_version_chain_fields(task: ShippingTask) -> dict[str, Any]: """ 组装任务版本链与重复决策投影字段。 核心逻辑:查 supersedes / 被谁 supersede / duplicate_source,供工作台与 Chat 导航。 """ supersedes_task_no = None if task.supersedes_task_id: prev = db.session.get(ShippingTask, int(task.supersedes_task_id)) if prev is not None: supersedes_task_no = prev.task_no superseded_by = ( db.session.query(ShippingTask) .filter(ShippingTask.supersedes_task_id == int(task.id)) .order_by(ShippingTask.document_version.desc(), ShippingTask.id.desc()) .first() ) duplicate_source_task_no = None if task.duplicate_source_task_id: src = db.session.get(ShippingTask, int(task.duplicate_source_task_id)) if src is not None: duplicate_source_task_no = src.task_no return { 'document_version': int(task.document_version or 1), 'supersedes_task_no': supersedes_task_no, 'superseded_by_task_no': superseded_by.task_no if superseded_by else None, '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, } def _dict_or_none(value: Any) -> dict[str, Any] | None: """将 step_payload 内对象投影为 dict;非 dict 时返回 None。""" return dict(value) if isinstance(value, dict) else None def _serialize_open_field_conflicts(task: ShippingTask) -> list[dict[str, Any]]: """投影未解决字段冲突,供工作台冲突复核 UI。""" from app.services.shipping_notice.task_field_conflict_service import ( list_open_field_conflicts, serialize_field_conflict, ) return [serialize_field_conflict(row) for row in list_open_field_conflicts(task)] def _serialize_source_candidate_projection(task: ShippingTask) -> dict[str, Any] | None: """ 投影建单来源 Candidate 的只读审计字段。 核心逻辑:按 source_candidate_id 取落库 evidence / missing_fields / field_confidence, 并投影当前字段裁决与不可变 Observation 历史; Candidate 已清理或不存在时返回 None,不阻断 Task Detail。 """ if not task.source_candidate_id: return None candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id)) if candidate is None: return None field_confidence = candidate.field_confidence_json structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {} extraction = structured.get("extraction") if isinstance(structured.get("extraction"), dict) else {} adjudication = ( extraction.get("field_adjudication") if isinstance(extraction.get("field_adjudication"), dict) else {} ) return { "candidate_no": candidate.candidate_no, "missing_fields": list(candidate.missing_fields_json or []), "field_confidence": dict(field_confidence) if isinstance(field_confidence, dict) else {}, "evidence": list(candidate.evidence_json or []), "conflicts": list(candidate.conflicts_json or []), "field_adjudication": { "schema_version": adjudication.get("schema_version"), "decisions": list(adjudication.get("decisions") or []), "observations": list(adjudication.get("observations") or []), "observation_history": list(adjudication.get("observation_history") or []), "conflicts": list(adjudication.get("conflicts") or []), } if adjudication else None, } def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]: """按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。""" from app.services.shipping_notice.rpa import rpa_runtime_mode if projection == TaskProjection.TOOL: from app.services.shipping_notice.user_facing_status import strip_internal_task_fields return strip_internal_task_fields(_task_tool_payload(task)) 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) data = { "id": task.id, "task_no": task.task_no, "shipping_case_id": task.shipping_case_id, "case_no": task.shipping_case.case_no if task.shipping_case else None, "business_no": task.shipping_case.business_no if task.shipping_case else None, "batch_no": _task_batch_no(task), "source_type": task.source_type, "source_file_name": task.source_file_name, "source_file_type": task.source_file_type, "batch_index": task.batch_index, "batch_total": task.batch_total, "customer_name": header.get('customer_name') or header.get('bill_to_customer'), "customer_resolution_status": task.customer_resolution_status, "customer_resolution_method": task.customer_resolution_method, "customer_id": task.shipping_case.customer_id if task.shipping_case else None, "customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None, "customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None, "current_step": task.current_step, "process_status": task.process_status, "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, "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, "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_source_confirmed_at": task.inventory_source_confirmed_at.isoformat() if task.inventory_source_confirmed_at else None, "inventory_source_confirmed_by": task.inventory_source_confirmed_by, "inventory_snapshot": _serialize_inventory_snapshot(task), "shortage": task.shortage_json, "line_results": task.line_results_json or [], "created_at": task.created_at.isoformat() if task.created_at else None, "updated_at": task.updated_at.isoformat() if task.updated_at else None, } data.update(_task_version_chain_fields(task)) from app.services.shipping_notice.task_disposition_service import task_disposition_capability data['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),) } 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) data = serialize_task(task, TaskProjection.SUMMARY) 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, "upload_receipt": task.upload_receipt_json or {}, "export_version": task.export_version, "idempotency_key": task.idempotency_key, "lines": current_line_field_values_or_empty(task), "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, # [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), "field_conflicts": _serialize_open_field_conflicts(task), **_fulfillment_timeline(task), "events": [ { "event_type": e.event_type, "detail_json": e.detail_json, "actor_id": e.actor_id, "request_id": e.request_id, "source": e.source, "before_json": e.before_json, "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 "") ], }) return data raise ValueError(f"unsupported task projection: {projection}") def serialize_task_for_tool(task: ShippingTask) -> dict[str, Any]: """Dify Tool `data` 投影(剔除内部状态码)。""" return serialize_task(task, TaskProjection.TOOL) def serialize_batch(batch: ShippingBatch, projection: BatchProjection) -> dict[str, Any]: """按投影类型序列化批次。""" if projection == BatchProjection.SUMMARY: return serialize_batch_summary(batch) if projection == BatchProjection.TOOL: data = serialize_batch_summary(batch) return { "batch_no": data["batch_no"], "conversation_id": data["conversation_id"], "current_focus_task_no": data["current_focus_task_no"], "file_count": data["file_count"], "process_summary": data["process_summary"], } raise ValueError(f"unsupported batch projection: {projection}") def serialize_batch_for_tool(batch: ShippingBatch | None) -> dict[str, Any] | None: """Tool 批次 data 投影。""" if not batch: return None return serialize_batch(batch, BatchProjection.TOOL) def serialize_batch_summary(batch: ShippingBatch) -> dict[str, Any]: """工作台批次列表/详情用的批次摘要投影。""" tasks = list(batch.tasks or []) return { "id": batch.id, "batch_no": batch.batch_no, "conversation_id": batch.conversation_id, "current_focus_task_no": batch.current_focus_task_no, "file_count": batch.file_count, "process_summary": batch.process_summary_json or compute_batch_process_summary(tasks), "created_at": batch.created_at.isoformat() if batch.created_at else None, "updated_at": batch.updated_at.isoformat() if batch.updated_at else None, } def serialize_conversation_batch_workspace(batch: ShippingBatch) -> dict[str, Any]: """ 序列化会话工作台中的单个批次。 核心逻辑:直接复用批次级 UI State 构建器,确保会话级工作台与批次详情页的 `tasks[].ui_state / focus_task_ui_state / action_buttons` 完全同源,避免按钮来源漂移。 """ from app.services.shipping_notice.ui_state import build_batch_ui_state return build_batch_ui_state(batch) def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]: """返回一个 Agent 会话下用户可见的所有发货批次与聚合摘要。""" value = str(conversation_id or "").strip() batches: list[ShippingBatch] = [] if value: batches = ( ShippingBatch.query.filter(ShippingBatch.conversation_id == value) .filter((ShippingBatch.user_id == user_id) | (ShippingBatch.user_id.is_(None))) .order_by(asc(ShippingBatch.created_at), asc(ShippingBatch.id)) .all() ) ordered_batches = batches return { "conversation_id": value, "summary": compute_conversation_workspace_summary(ordered_batches), "batches": [ serialize_conversation_batch_workspace(batch) for batch in ordered_batches ], } def task_todo_category(task: ShippingTask) -> str: """ 由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。 核心逻辑:wait_manual_upload→manual_upload(含 Excel 导出后待登记); complete→done;must_human 且属复核入口→review,其余 must_human→exception; auto_continue→in_progress。 筛选 manual_upload 时 SQL 侧亦覆盖 waiting_upload / 有导出文件的任务。 Returns: review | exception | manual_upload | in_progress | done """ ui = resolve_task_ui_state(task) return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind) def _todo_category_from_ui(checkpoint: str | None, kind: CheckpointKind) -> str: """将 checkpoint_kind(及复核入口集合)映射为 todo_category。""" if kind == CheckpointKind.WAIT_MANUAL_UPLOAD: return "manual_upload" if kind == CheckpointKind.COMPLETE: return "done" if kind == CheckpointKind.MUST_HUMAN: if str(checkpoint or "") in _REVIEW_TODO_CHECKPOINTS: return "review" return "exception" return "in_progress" def _todo_category_from_task_row( row: Any, *, extractions_with_lines: set[int], ) -> str: """ 用轻量任务行计算 todo_category,避免索引阶段全量 ORM + 订单行 N+1。 核心逻辑:委托 resolve_task_ui_state_from_fields;has_dynamic_order_lines 查批量集合。 """ extraction_id = getattr(row, "current_order_extraction_id", None) has_lines = ( extraction_id is not None and int(extraction_id) in extractions_with_lines ) ui = resolve_task_ui_state_from_fields( process_status=getattr(row, "process_status", None), review_status=getattr(row, "review_status", None), pending_human_reason=getattr(row, "pending_human_reason", None), shipping_case_id=getattr(row, "shipping_case_id", None), customer_resolution_status=getattr(row, "customer_resolution_status", None), order_snapshot_id=getattr(row, "order_snapshot_id", None), inventory_lines_json=getattr(row, "inventory_lines_json", None), 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=[], ) return _todo_category_from_ui(ui.checkpoint, ui.checkpoint_kind) def _extractions_with_accepted_lines(extraction_ids: set[int]) -> set[int]: """ 批量返回「已接受且至少有一行」的 extraction_id 集合。 核心逻辑:两次 IN 查询替代逐任务 get Extraction + first Line。 """ if not extraction_ids: return set() accepted_ids = { int(row[0]) for row in db.session.query(ShippingOrderExtraction.id).filter( ShippingOrderExtraction.id.in_(tuple(extraction_ids)), ShippingOrderExtraction.status == "accepted", ).all() } if not accepted_ids: return set() return { int(row[0]) for row in db.session.query(ShippingOrderLine.extraction_id).filter( ShippingOrderLine.extraction_id.in_(tuple(accepted_ids)), ).distinct().all() } def task_can_handle(task: ShippingTask, user_id: int, *, is_admin: bool = False) -> bool: """ 判断当前用户是否可对该任务执行写操作。 核心逻辑:仅创建者可处理(task.user_id == user_id 且非空); user_id IS NULL 一律不可写;管理员代操作首期不开放(他人任务 can_handle=False, 若管理员本人是创建者仍可处理)。is_admin 保留供调用方显式传参,不单独绕过归属。 Args: task: 目标任务。 user_id: 当前操作者用户 ID。 is_admin: 是否管理员视图;不改变归属判定。 Returns: 是否允许写操作。 """ del is_admin # 首期管理员不可代操作;保留参数以对齐 API 契约。 return task.user_id is not None and int(task.user_id) == int(user_id) def _latest_task_event_summary(task: ShippingTask) -> dict[str, Any] | None: """ 取任务最近一条 ShippingTaskEvent 摘要;无事件时返回 None。 核心逻辑:按 created_at/id 降序取一条,投影 event_type / created_at / detail。 """ if task.id is None: return None event = ( ShippingTaskEvent.query.filter_by(task_id=task.id) .order_by(ShippingTaskEvent.created_at.desc(), ShippingTaskEvent.id.desc()) .first() ) if event is None: return None return { "event_type": event.event_type, "created_at": event.created_at.isoformat() if event.created_at else None, "detail_json": event.detail_json, "actor_id": event.actor_id, } def _artifact_summary_for_task(task: ShippingTask) -> dict[str, Any] | None: """ 投影任务导出 Artifact 摘要(Excel 文件名/路径);无导出时返回 None。 核心逻辑:优先读任务上的 export_file_*;有路径或文件名即视为有摘要。 """ file_name = str(task.export_file_name or "").strip() or None file_path = str(task.export_file_path or "").strip() or None if not file_name and not file_path: return None return { "export_file_name": file_name, "export_file_path": file_path, } def _enrich_task_center_fields( task: ShippingTask, data: dict[str, Any], *, viewer_user_id: int | None = None, is_admin: bool = False, ) -> dict[str, Any]: """ 为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。 核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle; recent_event / artifact_summary / ui_state 懒加载同源状态,避免任务中心再推导; DETAIL 另附 workflow_item(含 Workflow Event)供时间线与最后活动展示。 Args: task: 源任务。 data: 已构建的序列化字典。 viewer_user_id: 当前查看者;为 None 时省略 can_handle。 is_admin: 是否管理员视图(仅影响 can_handle 调用签名,不开放代操作)。 Returns: 同一 data 引用(已 enrich)。 """ data["todo_category"] = task_todo_category(task) data["item_kind"] = "task" data["todo_ref"] = task.task_no data["created_by"] = task.user_id if viewer_user_id is not None: data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin) data["recent_event"] = _latest_task_event_summary(task) data["artifact_summary"] = _artifact_summary_for_task(task) # [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。 from app.services.shipping_notice.ui_state import build_task_ui_state data["ui_state"] = build_task_ui_state(task) return data def _attach_workflow_item_projection(task: ShippingTask, data: dict[str, Any]) -> dict[str, Any]: """ 为任务详情附带绑定的 WorkflowItem 投影(含可见 Workflow Event)。 核心逻辑:按 current_task_no 定位 Item;未绑定时 workflow_item=None,不阻断详情。 """ try: from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_task_no from app.services.shipping_notice.workflow_progress_projection import serialize_workflow_item item = find_item_by_current_task_no(task_no=str(task.task_no or '')) data['workflow_item'] = ( serialize_workflow_item(item, include_events=True) if item is not None else None ) except Exception: data['workflow_item'] = None return data def serialize_task_summary( task: ShippingTask, *, viewer_user_id: int | None = None, is_admin: bool = False, ) -> dict[str, Any]: """ 工作台任务列表用的 SUMMARY 投影(含任务中心 enrich)。 Args: task: 源任务。 viewer_user_id: 当前查看者;用于 can_handle;缺省时省略该字段。 is_admin: 是否管理员视图。 """ data = serialize_task(task, TaskProjection.SUMMARY) return _enrich_task_center_fields( task, data, viewer_user_id=viewer_user_id, is_admin=is_admin, ) def serialize_task_detail( task: ShippingTask, *, viewer_user_id: int | None = None, is_admin: bool = False, ) -> dict[str, Any]: """ 工作台任务详情用的 DETAIL 投影(含 lines、events、WorkflowItem 与任务中心 enrich)。 Args: task: 源任务。 viewer_user_id: 当前查看者;用于 can_handle。 is_admin: 是否管理员视图。 """ data = serialize_task(task, TaskProjection.DETAIL) _enrich_task_center_fields( task, data, viewer_user_id=viewer_user_id, is_admin=is_admin, ) return _attach_workflow_item_projection(task, data) def get_batch_for_user(batch_no: str, user_id: int) -> ShippingBatch | None: """按 batch_no 查找批次并校验 user_id 归属。""" batch = get_batch_by_no(batch_no) if not batch: return None if batch.user_id is not None and batch.user_id != user_id: return None return batch def list_batches_for_user( user_id: int, *, limit: int = 100, ) -> list[dict[str, Any]]: """列出用户可见批次摘要(按 created_at 降序,limit 上限 500)。""" q = ShippingBatch.query.filter( (ShippingBatch.user_id == user_id) | (ShippingBatch.user_id.is_(None)) ) rows = q.order_by(desc(ShippingBatch.created_at)).limit(max(1, min(limit, 500))).all() return [serialize_batch_summary(item) for item in rows] def list_tasks_for_batch(batch_no: str, user_id: int) -> list[dict[str, Any]]: """列出批次下已排序任务的 SUMMARY 投影;批次不存在或无权限时返回空列表。""" batch = get_batch_for_user(batch_no, user_id) if not batch: return [] return list_batch_task_summaries(batch) def get_focus_task_for_batch(batch_no: str, user_id: int) -> ShippingTask | None: """获取批次当前 focus 任务;未设置时返回 batch_index 最小的首票。""" batch = get_batch_for_user(batch_no, user_id) if not batch: return None focus_task_no = str(batch.current_focus_task_no or "").strip() if focus_task_no: task = get_task_by_ref(focus_task_no) if task and task.batch_id == batch.id: return task tasks = list_sorted_batch_tasks(batch) return tasks[0] if tasks else None def list_tasks_for_user( user_id: int, *, batch_no: str | None = None, process_status: str | None = None, limit: int = 100, ) -> list[dict[str, Any]]: """列出用户可见任务摘要,可按批次或工作台用户态状态过滤。""" q = ShippingTask.query.filter( (ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None)) ) if batch_no: batch = get_batch_for_user(batch_no, user_id) if not batch: return [] q = q.filter(ShippingTask.batch_id == batch.id) if process_status: if process_status == "shortage_review": q = q.filter( (ShippingTask.review_status == "shortage_review") | (ShippingTask.pending_human_reason.in_(("shortage", "shortage_review"))) ) else: q = q.filter(ShippingTask.process_status == process_status) rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all() return [ serialize_task_summary(c, viewer_user_id=user_id) for c in rows ] def list_tasks_page_for_user( user_id: int, *, page: int = 1, page_size: int = 20, batch_no: str | None = None, process_status: str | None = None, lifecycle_status: str | None = None, ) -> dict[str, Any]: """ 分页列出当前用户可见的发货任务摘要。 工作台任务量增长后必须由数据库分页,不能先拉取固定上限再在浏览器切页; `items` 仅表示当前页,`total` 用于计算稳定的页码与空页回退。 """ normalized_page = max(1, int(page)) normalized_page_size = max(1, min(int(page_size), 100)) q = ShippingTask.query.filter( (ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None)) ) if batch_no: batch = get_batch_for_user(batch_no, user_id) if not batch: return {"items": [], "page": normalized_page, "page_size": normalized_page_size, "total": 0} q = q.filter(ShippingTask.batch_id == batch.id) if process_status: if process_status == "shortage_review": q = q.filter( (ShippingTask.review_status == "shortage_review") | (ShippingTask.pending_human_reason.in_(("shortage", "shortage_review"))) ) else: q = q.filter(ShippingTask.process_status == process_status) if lifecycle_status: normalized_lifecycle = str(lifecycle_status).strip().lower() if normalized_lifecycle == 'deleted': q = q.filter(ShippingTask.deleted_at.is_not(None)) elif normalized_lifecycle == 'active': q = q.filter(ShippingTask.deleted_at.is_(None), ShippingTask.lifecycle_status == 'active') elif normalized_lifecycle == 'voided': # 作废后移入回收站的任务仍须出现在“已作废”视图,便于业务审计与追溯。 q = q.filter(ShippingTask.lifecycle_status == normalized_lifecycle) else: q = q.filter(ShippingTask.deleted_at.is_(None), ShippingTask.lifecycle_status == normalized_lifecycle) else: q = q.filter(ShippingTask.deleted_at.is_(None), ShippingTask.lifecycle_status == 'active') total = q.order_by(None).count() rows = ( q.order_by(desc(ShippingTask.created_at)) .offset((normalized_page - 1) * normalized_page_size) .limit(normalized_page_size) .all() ) return { "items": [ serialize_task_summary(item, viewer_user_id=user_id) for item in rows ], "page": normalized_page, "page_size": normalized_page_size, "total": total, } def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None: """ 按 task_no 查找任务并校验写路径归属(严格创建者)。 核心逻辑:仅当 task.user_id == user_id 时返回;user_id IS NULL 一律拒绝, 避免历史无主任务被任意登录用户写入。管理员只读请用 get_task_visible_to_user。 """ task = get_task_by_ref(task_no) if not task: return None if task.user_id is None or int(task.user_id) != int(user_id): return None return task def get_task_visible_to_user( task_no: str, user_id: int, *, is_admin: bool = False, ) -> ShippingTask | None: """ 按 task_no 查找当前用户可见的任务(创建者或管理员只读)。 核心逻辑:管理员可读全部;普通用户仅可读自己创建且 user_id 非空的任务。 写操作仍须经 get_task_for_user / task_can_handle 门禁。 Args: task_no: 任务编号。 user_id: 当前用户。 is_admin: 为 True 时允许管理员只读可见。 Returns: 可见任务或 None。 """ task = get_task_by_ref(task_no) if not task: return None if is_admin: return task if task.user_id is None or int(task.user_id) != int(user_id): return None return task def _task_matches_customer_filter(task: ShippingTask, customer: str) -> bool: """待办列表客户关键字过滤:匹配 case 快照、来源文件名或当前订单头客户名。""" needle = str(customer or "").strip().lower() if not needle: return True case = task.shipping_case candidates: list[str] = [] if case is not None: for value in ( getattr(case, "customer_name_snapshot", None), getattr(case, "customer_short_code_snapshot", None), ): if value: candidates.append(str(value)) if task.source_file_name: candidates.append(str(task.source_file_name)) header = current_header_field_values_or_empty(task) for key in ("customer_name", "bill_to_customer", "ship_to_customer", "customer_code"): value = header.get(key) if value: candidates.append(str(value)) return any(needle in item.lower() for item in candidates) def _visible_tasks_query_for_todos(user_id: int, *, is_admin: bool = False): """构造「我的待办」可见任务基础查询(活跃生命周期)。""" q = ShippingTask.query.filter( ShippingTask.deleted_at.is_(None), ShippingTask.lifecycle_status == "active", ) if not is_admin: # 待办中心拒绝无主任务;仅创建者可见。 q = q.filter(ShippingTask.user_id == user_id) return q def _visible_open_review_cases_query(user_id: int, *, is_admin: bool = False): """ 构造建单前开放 Review Case 查询(尚未确认建单)。 核心逻辑:排除已确认/非订单/已替代 Case;非管理员仅 owner_user_id==user_id。 """ q = ShippingOrderReviewCase.query.filter( ShippingOrderReviewCase.status.in_(tuple(_OPEN_REVIEW_CASE_STATUSES)), ShippingOrderReviewCase.confirmed_task_id.is_(None), ) if not is_admin: q = q.filter(ShippingOrderReviewCase.owner_user_id == int(user_id)) return q def serialize_review_case_todo( case: ShippingOrderReviewCase, *, viewer_user_id: int | None = None, is_admin: bool = False, ) -> dict[str, Any]: """ 将建单前 Review Case 投影为「我的待办」列表项,供打开人工复核深链。 核心逻辑:附带 review_run_no / review_case_no / owner_agent_id / conversation_id; todo_category 固定 review;entry_surface=review_workbench。 Args: case: 开放中的 Review Case。 viewer_user_id: 当前查看者;用于 can_handle。 is_admin: 是否管理员视图(不开放代操作)。 Returns: 与任务 SUMMARY 兼容的待办字典。 """ del is_admin run = db.session.get(ShippingOrderExtractionRun, case.run_id) if case.run_id else None document = db.session.get(ShippingNoticeDocument, case.document_id) if case.document_id else None source_name = None if document is not None: source_name = str(getattr(document, "filename", None) or "").strip() or None current_todo = _REVIEW_CASE_STATUS_TODO.get(str(case.status), "订单 PDF 待人工复核") can_handle = ( viewer_user_id is not None and case.owner_user_id is not None and int(case.owner_user_id) == int(viewer_user_id) ) run_no = str(getattr(run, "run_no", None) or "").strip() or None conversation_id = str(getattr(run, "conversation_id", None) or "").strip() or None owner_agent_id = getattr(run, "owner_agent_id", None) item: dict[str, Any] = { "item_kind": "review_case", "todo_ref": case.case_no, "task_no": None, "todo_category": "review", "review_run_no": run_no, "review_case_no": case.case_no, "review_case_status": case.status, "conversation_id": conversation_id, "owner_agent_id": int(owner_agent_id) if owner_agent_id is not None else None, "created_by": case.owner_user_id, "source_file_name": source_name, "customer_name": None, "process_status": None, "updated_at": case.updated_at.isoformat() if case.updated_at else None, "created_at": case.created_at.isoformat() if case.created_at else None, "ui_state": { "checkpoint": "order_review", "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), "action_buttons": [], "summary": { "title": "待人工复核", "message": current_todo, "stage": "待人工复核", "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), "current_todo": current_todo, "pause_reason": current_todo, "pause_reason_code": f"review_case_{case.status}", "next_auto_step": None, "event_at": case.updated_at.isoformat() if case.updated_at else None, "entry_surface": "review_workbench", "allowed_actions": [], "issues": [], "error_message": None, }, }, } if viewer_user_id is not None: item["can_handle"] = can_handle return item def _todo_category_sql_filter(allowed: frozenset[str]): """ 将待办类别粗筛下推到 SQL,缩小活跃任务读取面。 核心逻辑:与 task_todo_category 对齐的保守 OR;精确分类由 _task_todo_category_sql_expr 完成。 """ clauses = [] if "manual_upload" in allowed: # wait_manual_upload:waiting_upload / 已有导出文件且未 uploaded。 clauses.append( db.or_( ShippingTask.process_status.in_(("waiting_upload", "upload_failed")), db.and_( ShippingTask.export_file_path.isnot(None), ShippingTask.process_status.notin_(("uploaded", "closed", "rejected")), ), ) ) if "done" in allowed: # 已上传/关闭/驳回终态(不含待人工上传登记)。 clauses.append( ShippingTask.process_status.in_(("uploaded", "closed", "rejected")) ) if "review" in allowed: clauses.append( db.or_( ShippingTask.process_status == "pending_review", ShippingTask.review_status.isnot(None), ) ) if "exception" in allowed: clauses.append(ShippingTask.pending_human_reason.isnot(None)) if "in_progress" in allowed: clauses.append( ShippingTask.process_status.in_( ("created", "parsed", "matched", "inventory_ready") ) ) if not clauses: return None return db.or_(*clauses) def _task_has_dynamic_order_lines_sql(): """ SQL 版「已接受 Extraction 且至少有一行」。 核心逻辑:关联 EXISTS,对齐 _task_has_dynamic_order_lines,供分类 CASE 复用。 """ return exists( select(1) .select_from(ShippingOrderExtraction) .where( ShippingOrderExtraction.id == ShippingTask.current_order_extraction_id, ShippingOrderExtraction.status == "accepted", exists( select(1) .select_from(ShippingOrderLine) .where(ShippingOrderLine.extraction_id == ShippingOrderExtraction.id) ), ) ) def _sql_json_falsy(column): """ JSON 列在 Python 中视为假值的 SQL 近似(None / [] / {})。 核心逻辑:Postgres `json` 无等号运算符(`json = json` 会 UndefinedFunction); 转为 text 再与紧凑字面量比较,兼容 SQLite 测试库。 """ as_text = cast(column, String) return db.or_(column.is_(None), as_text == '[]', as_text == '{}') def _sql_str_blank(column): """字符串列空白:NULL 或空串。""" return db.or_(column.is_(None), column == "") def _task_todo_category_sql_expr(): """ 将 resolve_task_ui_state_from_fields 同序映射为 todo_category SQL CASE。 核心逻辑:分支顺序与状态机一致;直接产出 review|exception|manual_upload|in_progress|done, 供 UNION 分页与徽标 COUNT 在数据库内过滤,避免轻量全量索引。 """ has_lines = _task_has_dynamic_order_lines_sql() reason = ShippingTask.pending_human_reason return case( (ShippingTask.process_status == "uploaded", literal("done")), (ShippingTask.process_status == "closed", literal("done")), ( db.or_( ShippingTask.process_status == "rejected", ShippingTask.review_status == RS_REJECTED, ), literal("done"), ), ( db.or_(reason == PH_RSV_REQ, ShippingTask.review_status == RS_RSV_REQ), literal("review"), ), ( db.or_(reason == PH_LOW_CONF, ShippingTask.review_status == RS_PARSE_REVIEW), literal("review"), ), (reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")), ( db.and_( ShippingTask.shipping_case_id.isnot(None), db.or_( ShippingTask.customer_resolution_status.is_(None), ShippingTask.customer_resolution_status != "confirmed", ), ), literal("exception"), ), ( db.and_(ShippingTask.order_snapshot_id.is_(None), has_lines), literal("in_progress"), ), (reason == PH_RPA_EXHAUSTED, literal("exception")), ( db.and_( ShippingTask.process_status == "parsed", _sql_str_blank(ShippingTask.review_status), _sql_str_blank(reason), _sql_json_falsy(ShippingTask.inventory_lines_json), ), literal("in_progress"), ), ( db.and_( ShippingTask.process_status == "inventory_ready", _sql_str_blank(ShippingTask.review_status), _sql_str_blank(reason), _sql_str_blank(ShippingTask.match_status), has_lines, ), literal("in_progress"), ), ( db.and_( ShippingTask.process_status == "matched", ShippingTask.export_file_path.isnot(None), ), literal("manual_upload"), ), (ShippingTask.process_status == "matched", literal("in_progress")), (reason == PH_INV_UNAVAIL, literal("exception")), (reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")), ( db.or_(reason == PH_SHORTAGE, ShippingTask.review_status == RS_SHORTAGE_REVIEW), literal("exception"), ), ( db.or_( reason == PH_UPLOAD_RPA_FAILED, ShippingTask.process_status == "upload_failed", ), literal("exception"), ), (reason == PH_UPLOAD_RESULT_UNKNOWN, literal("manual_upload")), (reason == PH_RPA_PENDING, literal("exception")), (reason == PH_UPLOAD_RPA_PENDING, literal("exception")), # Excel 后待人工上传登记。 (ShippingTask.process_status == "waiting_upload", 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"): stamp = value.isoformat() else: stamp = str(value or "") return (stamp, str(ref or "")) def _apply_review_case_customer_filter(cases_q, *, customer_needle: str, customer_like: str): """对开放 Review Case 查询追加客户关键字过滤。""" if not customer_needle: return cases_q matching_document_ids = db.session.query(ShippingNoticeDocument.id).filter( ShippingNoticeDocument.filename.ilike(customer_like), ) matching_candidate_ids = db.session.query(ShippingNoticeCandidate.id).filter( ShippingNoticeCandidate.po_number.ilike(customer_like), ) return cases_q.filter( db.or_( ShippingOrderReviewCase.case_no.ilike(customer_like), ShippingOrderReviewCase.document_id.in_(matching_document_ids), ShippingOrderReviewCase.candidate_id.in_(matching_candidate_ids), ) ) def _todo_tasks_base_query( user_id: int, *, is_admin: bool, allowed: frozenset[str], normalized_bucket: str, customer_needle: str, customer_like: str, task_no: str | None, ): """ 构造带粗筛 + 精确 category CASE 过滤的 Task 待办查询。 核心逻辑:可见性 / 客户 / bucket 粗筛后,用 _task_todo_category_sql_expr().in_(allowed)。 """ q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin) if task_no: q = q.filter(ShippingTask.task_no == str(task_no).strip()) if customer_needle: q = q.outerjoin(ShippingCase, ShippingCase.id == ShippingTask.shipping_case_id).filter( db.or_( ShippingCase.customer_name_snapshot.ilike(customer_like), ShippingCase.customer_short_code_snapshot.ilike(customer_like), ShippingTask.source_file_name.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_( ShippingTask.pending_human_reason.isnot(None), ShippingTask.review_status.isnot(None), ShippingTask.export_file_path.isnot(None), ShippingTask.process_status.in_( ( "pending_review", "matched", "waiting_upload", "upload_failed", "parsed", "inventory_ready", "created", ) ), ) ) elif normalized_bucket == "done": # Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。 q = q.filter( db.or_( ShippingTask.process_status.in_( ("uploaded", "closed", "rejected", "waiting_upload") ), db.and_( ShippingTask.process_status == "matched", ShippingTask.export_file_path.isnot(None), ), ) ) return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed)))) def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False): """徽标统计用的活跃 Task 粗筛范围(不含 done)。""" return _visible_tasks_query_for_todos(user_id, is_admin=is_admin).filter( db.or_( ShippingTask.pending_human_reason.isnot(None), ShippingTask.review_status.isnot(None), ShippingTask.export_file_path.isnot(None), ShippingTask.process_status.in_( ( "pending_review", "matched", "waiting_upload", "upload_failed", "parsed", "inventory_ready", "created", ) ), ) ) def list_my_todos( user_id: int, *, bucket: str = "pending", page: int = 1, page_size: int = 20, is_admin: bool = False, todo_category: str | None = None, customer: str | None = None, task_no: str | None = None, ) -> dict[str, Any]: """ 分页列出「我的待办」:建单前 Review Case + 建单后 Task 异常/上传。 核心逻辑:pending 桶合并开放 Review Case(todo_category=review,含 review_run_no 深链); Task 分类下推为与状态机同序的 SQL CASE;两端 UNION ALL 后数据库 COUNT + OFFSET/LIMIT, 仅水合当前页 id(禁止 limit(500) 截断冒充总数)。 Args: user_id: 当前用户。 bucket: pending(review|exception|manual_upload)| processing | done。 page / page_size: 分页参数。 is_admin: 管理员全局只读视图。 todo_category: 可选细分类覆盖 bucket。 customer: 客户名/代码/来源文件名/Case 号/PO 模糊过滤(Task 与 Review Case 均参与)。 task_no: 精确任务号过滤(仅 Task 项;复核项忽略)。 Returns: {items, page, page_size, total} """ normalized_page = max(1, int(page)) normalized_page_size = max(1, min(int(page_size), 100)) normalized_bucket = str(bucket or "pending").strip().lower() allowed = _TODO_BUCKET_CATEGORIES.get(normalized_bucket, _PENDING_TODO_CATEGORIES) if todo_category: cat = str(todo_category).strip().lower() allowed = frozenset({cat}) if cat in { "review", "exception", "manual_upload", "in_progress", "done", } else allowed customer_needle = str(customer or "").strip() customer_like = f"%{customer_needle}%" if customer_needle else "" include_review_cases = "review" in allowed and not task_no # [STEP 1] 两端投影为统一列:kind / entity_id / sort_at / sort_ref。 branches = [] if include_review_cases: cases_q = _apply_review_case_customer_filter( _visible_open_review_cases_query(user_id, is_admin=is_admin), customer_needle=customer_needle, customer_like=customer_like, ) branches.append( cases_q.with_entities( literal("review_case").label("kind"), ShippingOrderReviewCase.id.label("entity_id"), ShippingOrderReviewCase.updated_at.label("sort_at"), ShippingOrderReviewCase.case_no.label("sort_ref"), ) ) tasks_q = _todo_tasks_base_query( user_id, is_admin=is_admin, allowed=allowed, normalized_bucket=normalized_bucket, customer_needle=customer_needle, customer_like=customer_like, task_no=task_no, ) branches.append( tasks_q.with_entities( literal("task").label("kind"), ShippingTask.id.label("entity_id"), func.coalesce(ShippingTask.updated_at, ShippingTask.created_at).label("sort_at"), ShippingTask.task_no.label("sort_ref"), ) ) # [STEP 2] UNION ALL → COUNT 真总数 → OFFSET/LIMIT 仅取当前页引用。 if len(branches) == 1: union_stmt = branches[0].order_by(None).statement else: union_stmt = union_all(*[branch.order_by(None).statement for branch in branches]) combined = union_stmt.subquery("todo_union") total = int( db.session.execute(select(func.count()).select_from(combined)).scalar_one() or 0 ) offset = (normalized_page - 1) * normalized_page_size page_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)) .offset(offset) .limit(normalized_page_size) ).all() if total and offset < total else [] ) # [STEP 3] 仅水合当前页 ORM 并按 UNION 顺序序列化。 page_case_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "review_case"] page_task_ids = [int(entity_id) for kind, entity_id in page_refs if kind == "task"] cases_by_id: dict[int, ShippingOrderReviewCase] = {} if page_case_ids: for case in ShippingOrderReviewCase.query.filter( ShippingOrderReviewCase.id.in_(page_case_ids), ).all(): cases_by_id[int(case.id)] = case tasks_by_id: dict[int, ShippingTask] = {} if page_task_ids: for task in ShippingTask.query.filter(ShippingTask.id.in_(page_task_ids)).all(): tasks_by_id[int(task.id)] = task page_rows: list[dict[str, Any]] = [] for kind, entity_id in page_refs: entity_id_int = int(entity_id) if kind == "review_case": case = cases_by_id.get(entity_id_int) if case is None: continue page_rows.append( serialize_review_case_todo( case, viewer_user_id=user_id, is_admin=is_admin, ) ) 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) ) return { "items": page_rows, "page": normalized_page, "page_size": normalized_page_size, "total": total, } def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]: """ 统计「我的待办」各 bucket 数量,供导航徽标使用。 核心逻辑:开放 Review Case 计入 pending;Task 用 SQL CASE 分类后 COUNT, 不扫描全量 ORM 行。 Returns: {pending, processing, done, total_pending_badge} """ pending = _visible_open_review_cases_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) pending += ( active.filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES)))).count() ) processing = active.filter(category_expr == "in_progress").count() done = ( _visible_tasks_query_for_todos(user_id, is_admin=is_admin) .filter( db.or_( ShippingTask.process_status.in_( ("uploaded", "closed", "rejected", "waiting_upload") ), db.and_( ShippingTask.process_status == "matched", ShippingTask.export_file_path.isnot(None), ), ) ) .filter(category_expr == "done") .count() ) return { "pending": pending, "processing": processing, "done": done, "total_pending_badge": pending, }