2101 lines
87 KiB
Python
2101 lines
87 KiB
Python
"""
|
||
services/shipping_notice/query_service.py
|
||
|
||
用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
|
||
依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
|
||
ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、
|
||
ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、
|
||
order_review_projection(任务中心 STP retry 动作投影)。
|
||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||
tools.py 通过 TaskProjection 委托序列化与任务解析,写路径逐步下沉;
|
||
SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event,
|
||
以及统一 shipping_processing_status / progress_version / order_task_no(BE-02),
|
||
并注入 review_run_no 供任务中心深链订单处理工作台(UI-04);
|
||
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 截断冒充总数);
|
||
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 与履约时间线(Reservation/Artifact);
|
||
co8 起 WorkflowItem 账本已下线,不再附加 workflow_item 投影(BE-06);
|
||
订单行仅从任务锁定 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.core.errors import ValidationError
|
||
from app.models import (
|
||
FileAsset,
|
||
ShippingExportArtifact,
|
||
ShippingExportArtifactLine,
|
||
ShippingInventoryVerification,
|
||
ShippingOrderCandidate,
|
||
ShippingOrderDocument,
|
||
ShippingOrderIntake,
|
||
ShippingOrderExtraction,
|
||
ShippingOrderProcessingRun,
|
||
ShippingOrderProcessingRunIntake,
|
||
ShippingOrderLine,
|
||
ShippingOrderReviewCase,
|
||
ShippingOrderSnapshot,
|
||
ShippingOrderReviewStream,
|
||
ShippingOrderSubmission,
|
||
ShippingReservation,
|
||
ShippingNotice,
|
||
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,
|
||
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,
|
||
)
|
||
from app.services.shipping_notice.po_number import normalize_po_number
|
||
|
||
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"(?<![A-Z0-9])[A-Z]{2,6}\d{8}(?![A-Z0-9])", re.IGNORECASE)
|
||
|
||
# 人工复核工作台入口检查点 → todo_category=review;其余 must_human → exception
|
||
_REVIEW_TODO_CHECKPOINTS = frozenset({
|
||
CP_PARSE_REVIEW,
|
||
CP_RSV_REQ,
|
||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||
})
|
||
|
||
_PENDING_TODO_CATEGORIES = frozenset({"review", "exception", "manual_upload", "intake_parse"})
|
||
_TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
|
||
"pending": _PENDING_TODO_CATEGORIES,
|
||
"processing": frozenset({"in_progress"}),
|
||
"done": frozenset({"done"}),
|
||
}
|
||
|
||
# 尚未挂 OT、仍需用户/系统关注的 Intake 解析状态(进入我的待办)。
|
||
_ORPHAN_INTAKE_TODO_PARSE_STATUSES = frozenset({
|
||
"created",
|
||
"queued",
|
||
"parsing",
|
||
"parse_failed",
|
||
})
|
||
|
||
# 建单前人工复核 Case 仍开放写操作的状态(未确认建单)。
|
||
_OPEN_REVIEW_CASE_STATUSES = frozenset({
|
||
"unreviewed",
|
||
"draft",
|
||
"ready",
|
||
"quality_issue",
|
||
"reparse_pending",
|
||
})
|
||
|
||
|
||
_REVIEW_CASE_STATUS_TODO: dict[str, str] = {
|
||
"unreviewed": "订单 PDF 待人工复核确认",
|
||
"draft": "复核草稿待继续编辑",
|
||
"ready": "复核草稿已就绪,可确认建单",
|
||
"quality_issue": "复核标记为质量问题,待处置",
|
||
"reparse_pending": "复核要求重识别,处理中",
|
||
}
|
||
|
||
|
||
def _review_case_lifecycle_projection(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||
"""复用统一生命周期投影裁决 Review Case 的当前阶段与入口。
|
||
|
||
当前有效 Candidate 才能进入订单复核;空、过期或被替代 Candidate 仍属于接收解析。
|
||
此处只组装已有事实并调用 ``project_lifecycle``,不新增状态机或前端专用阶段。
|
||
"""
|
||
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.lifecycle_projection import project_lifecycle
|
||
|
||
has_candidate_context = is_current_reviewable_candidate(candidate)
|
||
if has_candidate_context:
|
||
return project_lifecycle(
|
||
current_gate=None,
|
||
blocking_reason=None,
|
||
has_candidate_context=True,
|
||
processing_stage='waiting_review',
|
||
)
|
||
return project_lifecycle(
|
||
current_gate=None,
|
||
blocking_reason=None,
|
||
has_candidate_context=False,
|
||
has_intake_parse_context=False,
|
||
processing_stage='document_parsing',
|
||
)
|
||
|
||
|
||
class TaskProjection(str, Enum):
|
||
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
|
||
|
||
TOOL = "tool"
|
||
TOOL_INTERNAL = "tool_internal"
|
||
SUMMARY = "summary"
|
||
DETAIL = "detail"
|
||
|
||
|
||
def _fulfillment_timeline(task: ShippingNotice) -> 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 get_task_by_ref(task_ref: str) -> ShippingNotice | None:
|
||
"""按 task_no、business_no 或数字主键精确查找 Notice。"""
|
||
value = str(task_ref or "").strip()
|
||
if not value:
|
||
return None
|
||
task = ShippingNotice.query.filter_by(task_no=value).first()
|
||
if task:
|
||
return task
|
||
task = ShippingNotice.query.filter_by(business_no=value.upper()).first()
|
||
if task:
|
||
return task
|
||
if value.isdigit():
|
||
return db.session.get(ShippingNotice, int(value))
|
||
return None
|
||
|
||
|
||
def resolve_order_extraction_ui_target(
|
||
*,
|
||
user_id: int,
|
||
conversation_id: str,
|
||
intake_nos: list[str],
|
||
) -> tuple[None, ShippingNotice | None]:
|
||
"""
|
||
按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。
|
||
|
||
核心逻辑:沿 Candidate.consumed_task_id 查找当前用户的既有 Task。
|
||
禁止回退到“用户最近任务”,避免并发会话串单。
|
||
|
||
Args:
|
||
user_id: 当前聊天用户 ID。
|
||
conversation_id: 当前 HXOPS ChatSession.session_id。
|
||
intake_nos: 本轮 agent_runtime_context.refs.intake_nos。
|
||
Returns:
|
||
`(None, task)`;`shipping_batches` 已删除,任务是唯一恢复锚点。
|
||
"""
|
||
normalized = sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()})
|
||
session_id = str(conversation_id or '').strip()
|
||
if not normalized or not session_id:
|
||
return None, None
|
||
|
||
intakes = (
|
||
db.session.query(ShippingOrderIntake)
|
||
.filter(
|
||
ShippingOrderIntake.user_id == int(user_id),
|
||
ShippingOrderIntake.conversation_id == session_id,
|
||
ShippingOrderIntake.intake_no.in_(normalized),
|
||
)
|
||
.order_by(ShippingOrderIntake.id.asc())
|
||
.all()
|
||
)
|
||
if {item.intake_no for item in intakes} != set(normalized):
|
||
return None, None
|
||
|
||
# co8 起 Intake.consumed_batch_id 已删除;仅通过 Candidate→Task 反查已有任务。
|
||
task = (
|
||
db.session.query(ShippingNotice)
|
||
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingNotice.id)
|
||
.filter(
|
||
ShippingOrderCandidate.intake_id.in_([int(item.id) for item in intakes]),
|
||
ShippingNotice.user_id == int(user_id),
|
||
)
|
||
.order_by(ShippingOrderCandidate.id.asc(), ShippingNotice.id.asc())
|
||
.first()
|
||
)
|
||
return None, task
|
||
|
||
|
||
def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str] | None:
|
||
"""解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。"""
|
||
if not task or not task.export_file_path:
|
||
return None
|
||
from app.models import ShippingExportArtifact
|
||
# 已人工/RPA 上传完成的 Artifact 仍是用户可下载的最终 Excel;
|
||
# 不能因履约完成将 status=uploaded 排除在下载解析之外。
|
||
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()
|
||
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: ShippingNotice | 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 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,
|
||
) -> ShippingNotice | 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 = (
|
||
ShippingNotice.query.filter_by(conversation_id=conv_id)
|
||
.filter(ShippingNotice.lifecycle_status == "active")
|
||
.order_by(ShippingNotice.id.desc())
|
||
.limit(2)
|
||
.all()
|
||
)
|
||
if len(candidates) == 1:
|
||
return candidates[0]
|
||
return None
|
||
|
||
|
||
def _task_tool_payload(task: ShippingNotice) -> 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,
|
||
"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'),
|
||
"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,
|
||
"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:
|
||
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: ShippingNotice) -> 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: ShippingNotice) -> dict[str, Any]:
|
||
"""
|
||
组装任务版本链与重复决策投影字段。
|
||
|
||
核心逻辑:查 supersedes / 被谁 supersede / duplicate_source,供工作台与 Chat 导航。
|
||
"""
|
||
supersedes_task_no = None
|
||
if task.supersedes_task_id:
|
||
prev = db.session.get(ShippingNotice, int(task.supersedes_task_id))
|
||
if prev is not None:
|
||
supersedes_task_no = prev.task_no
|
||
superseded_by = (
|
||
db.session.query(ShippingNotice)
|
||
.filter(ShippingNotice.supersedes_task_id == int(task.id))
|
||
.order_by(ShippingNotice.document_version.desc(), ShippingNotice.id.desc())
|
||
.first()
|
||
)
|
||
duplicate_source_task_no = None
|
||
if task.duplicate_source_task_id:
|
||
src = db.session.get(ShippingNotice, 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: ShippingNotice) -> 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: ShippingNotice) -> 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(ShippingOrderCandidate, 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: ShippingNotice, 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,
|
||
"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,
|
||
"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_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,
|
||
"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: ShippingNotice) -> dict[str, Any]:
|
||
"""Dify Tool `data` 投影(剔除内部状态码)。"""
|
||
return serialize_task(task, TaskProjection.TOOL)
|
||
|
||
|
||
def task_todo_category(task: ShippingNotice) -> 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
|
||
)
|
||
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=[],
|
||
)
|
||
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: ShippingNotice, 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: ShippingNotice) -> 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: ShippingNotice) -> 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 _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||
"""
|
||
投影发货通知列表需要的项次、料号、数量与当前库存事实。
|
||
|
||
核心逻辑:Notice 行定义“本通知包含哪些业务行”;项次(line_no)经
|
||
order_line_no_resolver 统一解析(字段真实值 → 客户 PO 行号 → 展示序号),
|
||
并附 line_no_source 标注,禁止前端按 position 或序号自行推导业务项次。
|
||
当前库存只读取同 Notice、`is_current=true` 的匹配事实;未找到匹配事实时明确
|
||
返回 null,禁止由前端估算库存。
|
||
"""
|
||
if task.id is None:
|
||
return []
|
||
matches_by_line_key = {
|
||
str(item.line_key): item
|
||
for item in ShippingNoticeLineInventoryMatch.query.filter(
|
||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||
).all()
|
||
if item.line_key
|
||
}
|
||
rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
|
||
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
|
||
).all()
|
||
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,
|
||
),
|
||
'part_number': item.part_number,
|
||
'customer_part_number': (item.field_values_json or {}).get('customer_part_number'),
|
||
'reservation_id': item.reservation_id,
|
||
'shipment_qty': str(item.required_qty) if item.required_qty is not None else None,
|
||
'available_qty': matches_by_line_key.get(str(item.line_key or '')).available_qty
|
||
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
|
||
'shortage_qty': matches_by_line_key.get(str(item.line_key or '')).shortage_qty
|
||
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
|
||
'inventory_status': matches_by_line_key.get(str(item.line_key or '')).inventory_status
|
||
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
|
||
} for item in rows]
|
||
|
||
|
||
def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]) -> None:
|
||
"""
|
||
将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。
|
||
|
||
核心逻辑:优先 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(正式发货任务)。
|
||
data: 就地写入的序列化字典。
|
||
"""
|
||
from app.models import ShippingOrderProcessingRun, ShippingOrderTask
|
||
from app.services.shipping_notice.shipping_processing_projection import (
|
||
_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)
|
||
data['shipping_processing_status'] = status
|
||
data['shipping_processing_stage'] = (
|
||
str(getattr(order_task, 'stage', None) or '').strip() or stage
|
||
)
|
||
data['progress_version'] = int(
|
||
getattr(order_task, 'progress_version', None)
|
||
or getattr(task, 'progress_version', None)
|
||
or 1
|
||
)
|
||
data['order_task_no'] = (
|
||
str(getattr(order_task, 'task_no', None) or '').strip() or None
|
||
)
|
||
# [UI-04] 任务中心仅作列表入口;深链订单处理工作台需要 Run 编号与 Agent。
|
||
if order_task is not None and getattr(order_task, 'extraction_run_id', None):
|
||
run = db.session.get(ShippingOrderProcessingRun, int(order_task.extraction_run_id))
|
||
if run is not None:
|
||
run_no = str(getattr(run, 'run_no', None) or '').strip() or None
|
||
if run_no:
|
||
data['review_run_no'] = run_no
|
||
if not str(data.get('conversation_id') or '').strip():
|
||
cid = str(getattr(run, 'conversation_id', None) or '').strip() or None
|
||
if cid:
|
||
data['conversation_id'] = cid
|
||
if data.get('owner_agent_id') is None and getattr(run, 'owner_agent_id', None) is not None:
|
||
data['owner_agent_id'] = int(run.owner_agent_id)
|
||
|
||
|
||
def _enrich_task_center_fields(
|
||
task: ShippingNotice,
|
||
data: dict[str, Any],
|
||
*,
|
||
viewer_user_id: int | None = None,
|
||
is_admin: bool = False,
|
||
include_stage_context: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。
|
||
|
||
核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle;
|
||
recent_event / artifact_summary / ui_state 懒加载同源状态;
|
||
注入 shipping_processing_status / progress_version / order_task_no(统一进度)。
|
||
``include_stage_context`` 直接透传给 ``build_task_ui_state``,使 DETAIL 一次投影即可携带
|
||
工作面只读事实,避免调用方在同一请求里再 build 一次被覆盖。
|
||
|
||
Args:
|
||
task: 源任务。
|
||
data: 已构建的序列化字典。
|
||
viewer_user_id: 当前查看者;为 None 时省略 can_handle。
|
||
is_admin: 是否管理员视图(仅影响 can_handle 调用签名,不开放代操作)。
|
||
include_stage_context: 是否让内嵌 ui_state 附带 stage_context。
|
||
|
||
Returns:
|
||
同一 data 引用(已 enrich)。
|
||
"""
|
||
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)
|
||
data['notice_line_summary'] = _notice_line_summary_for_task(task)
|
||
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
|
||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||
|
||
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"))),
|
||
)
|
||
_inject_unified_processing_fields(task, data)
|
||
# [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。
|
||
data['workflow_item'] = None
|
||
return data
|
||
|
||
|
||
def serialize_task_summary(
|
||
task: ShippingNotice,
|
||
*,
|
||
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: ShippingNotice,
|
||
*,
|
||
viewer_user_id: int | None = None,
|
||
is_admin: bool = False,
|
||
include_stage_context: bool = False,
|
||
view: str = 'full',
|
||
) -> dict[str, Any]:
|
||
"""
|
||
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
|
||
|
||
Args:
|
||
task: 源任务。
|
||
viewer_user_id: 当前查看者;用于 can_handle。
|
||
is_admin: 是否管理员视图。
|
||
include_stage_context: 是否让内嵌 ui_state 附带 stage_context(避免调用方重复 build)。
|
||
view: 投影视图。``full`` 返回完整详情(含复核编辑器数据);``workbench`` 为
|
||
订单生命周期工作台首屏裁剪版:工作台只消费 ui_state + 进度/产物/行摘要,
|
||
不读取行明细/订单头/事件/字段冲突等复核编辑器重字段。把这些字段从响应剔除,
|
||
避免每次进入工作台都拉取 67KB 级详情(对应 /shipping-tasks/:task_no 的大响应)。
|
||
"""
|
||
data = serialize_task(task, TaskProjection.DETAIL)
|
||
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)
|
||
return _enrich_task_center_fields(
|
||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||
include_stage_context=include_stage_context,
|
||
)
|
||
|
||
|
||
def list_tasks_for_user(
|
||
user_id: int,
|
||
*,
|
||
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()
|
||
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,
|
||
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 = 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)
|
||
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()
|
||
)
|
||
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) -> ShippingNotice | 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,
|
||
) -> ShippingNotice | 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 list_freight_notice_groups_for_task(
|
||
task: ShippingNotice,
|
||
*,
|
||
user_id: int,
|
||
is_admin: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
按当前 Notice 所属客户 PO 返回货代上传的 Notice 聚合行。
|
||
|
||
核心逻辑:一个 business_no 就是一张独立发货 Excel;同一 PO 后续补货产生的
|
||
Notice 必须作为另一组返回。查询只取当前用户可见的 active Notice,且强制排除尚未
|
||
分配 business_no 的历史/中间对象,前端不得由 PDF 草稿行猜测分组。
|
||
|
||
Args:
|
||
task: 当前订单工作台已授权读取的正式 Notice。
|
||
user_id: 当前用户;非管理员仅返回其创建的 Notice。
|
||
is_admin: 管理员只读可见范围。
|
||
|
||
Returns:
|
||
包含 PO 及一行一个 business_no 的货代上传聚合投影。
|
||
"""
|
||
po_number = _notice_po_number(task)
|
||
if not po_number:
|
||
return {'po_number': None, 'items': [], 'reason': 'po_missing'}
|
||
|
||
candidates = ShippingNotice.query.filter(
|
||
ShippingNotice.deleted_at.is_(None),
|
||
ShippingNotice.lifecycle_status == 'active',
|
||
ShippingNotice.business_no.isnot(None),
|
||
)
|
||
if not is_admin:
|
||
candidates = candidates.filter(ShippingNotice.user_id == int(user_id))
|
||
|
||
items: list[dict[str, Any]] = []
|
||
for notice in candidates.order_by(ShippingNotice.created_at.asc(), ShippingNotice.id.asc()).all():
|
||
if _notice_po_number(notice) != po_number:
|
||
continue
|
||
business_no = str(notice.business_no or '').strip()
|
||
if not business_no:
|
||
continue
|
||
# [STEP] 主区单条菜单只消费服务端已裁决的 Notice 动作,禁止按 upload_status 猜测。
|
||
# 轻量投影仅返回动作码,避免逐张 Notice 跑完整 build_task_ui_state 造成 N 倍放大。
|
||
from app.services.shipping_notice.ui_state import project_notice_available_actions
|
||
available_actions = project_notice_available_actions(notice)
|
||
# [STEP] upload_mode/upload_attempt 从 ShippingUploadAttempt 权威事实解析。
|
||
# denormalized Notice.upload_mode 恒为 None,不能作为「人工/RPA」展示来源。
|
||
upload_mode, upload_attempt = _task_upload_attempt_facts(notice.id)
|
||
items.append({
|
||
'business_no': business_no,
|
||
'po_number': po_number,
|
||
'upload_status': notice.upload_status,
|
||
'upload_mode': upload_mode,
|
||
'upload_attempt': upload_attempt,
|
||
'upload_error_code': notice.upload_error_code,
|
||
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 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,
|
||
'available_actions': available_actions,
|
||
'lines': _notice_line_summary_for_task(notice),
|
||
})
|
||
return {
|
||
'po_number': po_number,
|
||
'items': items,
|
||
'reason': None if items else 'no_business_notice',
|
||
}
|
||
|
||
|
||
def _task_upload_attempt_facts(task_id: int | None) -> tuple[str | None, int]:
|
||
"""从 ShippingUploadAttempt 权威事实解析任务上传方式与尝试次数。
|
||
|
||
读取侧不再消费 denormalized 的 Notice.upload_mode / upload_attempt(这两个列从未被
|
||
写入真实值,恒为 None/0)。成功态的 mode 优先(通知完成面以此区分人工/RPA),
|
||
否则回退最近一条 attempt 的 mode,与 ui_state._build_stage_context 的判定保持一致。
|
||
|
||
Args:
|
||
task_id: 正式 Notice 主键;为空时返回 (None, 0)。
|
||
|
||
Returns:
|
||
tuple[str | None, int]: (mode, attempt_count);无任何 attempt 时返回 (None, 0)。
|
||
"""
|
||
if not task_id:
|
||
return None, 0
|
||
attempts = (
|
||
ShippingUploadAttempt.query
|
||
.join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id)
|
||
.filter(ShippingExportArtifact.task_id == int(task_id))
|
||
.order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc())
|
||
.all()
|
||
)
|
||
if not attempts:
|
||
return None, 0
|
||
succeeded = next(
|
||
(item for item in attempts if str(item.status or '').strip().lower() == 'succeeded'),
|
||
None,
|
||
)
|
||
anchor = succeeded or attempts[0]
|
||
return (anchor.mode if anchor is not None else None), len(attempts)
|
||
|
||
|
||
def _notice_po_number(notice: ShippingNotice) -> str:
|
||
"""读取 Notice 的正式客户 PO;动态 Schema、冻结快照和兼容投影按稳定顺序回退。"""
|
||
header = current_header_field_values_or_empty(notice)
|
||
for field_code in ('customer_po_number', 'po_number'):
|
||
normalized = normalize_po_number(header.get(field_code))
|
||
if normalized:
|
||
return normalized
|
||
|
||
snapshot = None
|
||
if notice.order_snapshot_id:
|
||
snapshot = db.session.get(ShippingOrderSnapshot, notice.order_snapshot_id)
|
||
if snapshot:
|
||
for value in (snapshot.customer_po_number, (snapshot.header_values_json or {}).get('po_number')):
|
||
normalized = normalize_po_number(value)
|
||
if normalized:
|
||
return normalized
|
||
|
||
candidate = (
|
||
db.session.get(ShippingOrderCandidate, notice.source_candidate_id)
|
||
if notice.source_candidate_id else None
|
||
)
|
||
normalized = normalize_po_number(getattr(candidate, 'po_number', None))
|
||
return normalized
|
||
|
||
|
||
def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool:
|
||
"""待办列表客户关键字过滤:匹配 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))
|
||
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 = ShippingNotice.query.filter(
|
||
ShippingNotice.deleted_at.is_(None),
|
||
ShippingNotice.lifecycle_status == "active",
|
||
)
|
||
if not is_admin:
|
||
# 待办中心拒绝无主任务;仅创建者可见。
|
||
q = q.filter(ShippingNotice.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.join(
|
||
ShippingOrderReviewStream,
|
||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||
).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;
|
||
STP failed/manual_fallback 时投影 retry_stp_auto_create(与工作台底栏同一幂等键)。
|
||
|
||
Args:
|
||
case: 开放中的 Review Case。
|
||
viewer_user_id: 当前查看者;用于 can_handle。
|
||
is_admin: 是否管理员视图(不开放代操作)。
|
||
|
||
Returns:
|
||
与任务 SUMMARY 兼容的待办字典。
|
||
"""
|
||
del is_admin
|
||
run = db.session.get(ShippingOrderProcessingRun, case.run_id) if case.run_id else None
|
||
document = db.session.get(ShippingOrderDocument, case.document_id) if case.document_id else None
|
||
lifecycle = _review_case_lifecycle_projection(case)
|
||
lifecycle_stage = str(lifecycle.get('lifecycle_stage') or 'unclassified')
|
||
lifecycle_entries = list(lifecycle.get('lifecycle_entries') or [])
|
||
from app.services.shipping_notice.lifecycle_projection import LIFECYCLE_STAGES
|
||
stage_index = next(
|
||
(index for index, item in enumerate(LIFECYCLE_STAGES)
|
||
if item.get('code') == lifecycle_stage),
|
||
0,
|
||
)
|
||
stage_definition = next(
|
||
(item for item in LIFECYCLE_STAGES if item['code'] == lifecycle_stage),
|
||
{'code': lifecycle_stage, 'label': '状态待同步'},
|
||
)
|
||
source_name = None
|
||
if document is not None:
|
||
source_name = str(getattr(document, "filename", None) or "").strip() or None
|
||
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)
|
||
)
|
||
allowed_actions: list[str] = []
|
||
action_buttons: list[str] = []
|
||
automation_status: str | None = None
|
||
# [STEP] 任务中心与底栏共用 STP 重试入口:仅 failed/manual_fallback + 可处理人。
|
||
try:
|
||
from app.services.shipping_notice.order_review_projection import (
|
||
_project_case_automation_status,
|
||
_project_post_confirm_auto_progress,
|
||
)
|
||
|
||
draft = case.current_draft
|
||
automation = _project_case_automation_status(
|
||
case,
|
||
validation=dict(draft.validation_result_json or {}) if draft is not None else None,
|
||
post_confirm=_project_post_confirm_auto_progress(case),
|
||
)
|
||
if isinstance(automation, dict):
|
||
automation_status = str(automation.get('status') or '').strip() or None
|
||
if (
|
||
can_handle
|
||
and automation.get('retryable')
|
||
and automation_status in {'failed', 'manual_fallback'}
|
||
and not case.confirmed_task_id
|
||
):
|
||
allowed_actions.append('retry_stp_auto_create')
|
||
action_buttons.append('retry_stp_auto_create')
|
||
current_todo = '自动建单推进失败,可重试自动推进'
|
||
except Exception: # noqa: BLE001
|
||
automation_status = None
|
||
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,
|
||
"updated_at": case.updated_at.isoformat() if case.updated_at else None,
|
||
"created_at": case.created_at.isoformat() if case.created_at else None,
|
||
"ui_state": {
|
||
"stage": {**stage_definition, "index": stage_index + 1, "total": len(LIFECYCLE_STAGES)},
|
||
# [AUTHORITY] 任务中心、批次中心和工作台均消费统一生命周期投影;
|
||
# 前端不得按 Case 状态或待办类别补造订单复核权限。
|
||
"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']},
|
||
"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),
|
||
"current_todo": current_todo,
|
||
"pause_reason": current_todo,
|
||
"pause_reason_code": (
|
||
f"stp_automation_{automation_status}"
|
||
if automation_status in {'failed', 'manual_fallback'}
|
||
else 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": allowed_actions,
|
||
"automation_status": automation_status,
|
||
"issues": [],
|
||
"error_message": None,
|
||
},
|
||
},
|
||
}
|
||
if viewer_user_id is not None:
|
||
item["can_handle"] = can_handle
|
||
return item
|
||
|
||
|
||
def _linked_active_ot_intake_ids_subquery():
|
||
"""
|
||
已挂接到有效 Processing Run(已有 user_task_no)的 Intake id 子查询。
|
||
|
||
核心逻辑:未释放的 RunIntake 即视为已进入 order_task,不再作为孤儿 Intake 待办。
|
||
"""
|
||
return (
|
||
db.session.query(ShippingOrderProcessingRunIntake.intake_id.label("intake_id"))
|
||
.join(
|
||
ShippingOrderProcessingRun,
|
||
ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id,
|
||
)
|
||
.filter(
|
||
ShippingOrderProcessingRunIntake.released_at.is_(None),
|
||
ShippingOrderProcessingRun.user_task_no.isnot(None),
|
||
)
|
||
.distinct()
|
||
.subquery()
|
||
)
|
||
|
||
|
||
def _visible_orphan_intakes_query(user_id: int, *, is_admin: bool = False):
|
||
"""
|
||
可见的尚未建 OT Intake 查询(解析中/解析失败)。
|
||
|
||
核心逻辑:purpose=shipping_notice 且 parse_status ∈ 孤儿集合;排除已挂 OT;
|
||
非管理员仅本人。
|
||
|
||
Args:
|
||
user_id: 当前用户。
|
||
is_admin: 管理员可读全局。
|
||
|
||
Returns:
|
||
SQLAlchemy Query[ShippingOrderIntake]。
|
||
"""
|
||
linked = _linked_active_ot_intake_ids_subquery()
|
||
q = ShippingOrderIntake.query.filter(
|
||
ShippingOrderIntake.purpose == "shipping_notice",
|
||
ShippingOrderIntake.parse_status.in_(tuple(sorted(_ORPHAN_INTAKE_TODO_PARSE_STATUSES))),
|
||
~ShippingOrderIntake.id.in_(db.session.query(linked.c.intake_id)),
|
||
)
|
||
if not is_admin:
|
||
q = q.filter(ShippingOrderIntake.user_id == int(user_id))
|
||
return q
|
||
|
||
|
||
def _apply_orphan_intake_customer_filter(
|
||
query,
|
||
*,
|
||
customer_needle: str,
|
||
customer_like: str,
|
||
):
|
||
"""
|
||
按来源文件名 / Intake 编号模糊过滤孤儿 Intake。
|
||
|
||
核心逻辑:无关键字时原样返回;否则 JOIN FileAsset 匹配 original_filename 或 intake_no。
|
||
"""
|
||
if not customer_needle:
|
||
return query
|
||
return (
|
||
query.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
|
||
.filter(
|
||
db.or_(
|
||
FileAsset.original_filename.ilike(customer_like),
|
||
ShippingOrderIntake.intake_no.ilike(customer_like),
|
||
)
|
||
)
|
||
)
|
||
|
||
|
||
def serialize_intake_todo(
|
||
intake: ShippingOrderIntake,
|
||
*,
|
||
viewer_user_id: int | None = None,
|
||
is_admin: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
将尚未建 OT 的 Intake 投影为「我的待办」列表项,供对话恢复卡深链。
|
||
|
||
核心逻辑:todo_category=intake_parse;entry_surface=conversation_processing;
|
||
失败态附带 error_code;可经 conversation_id + owner_agent_id 打开会话。
|
||
|
||
Args:
|
||
intake: ShippingOrderIntake。
|
||
viewer_user_id: 当前查看者。
|
||
is_admin: 管理员视图标记(不开放代操作)。
|
||
|
||
Returns:
|
||
与任务 SUMMARY 兼容的待办字典。
|
||
"""
|
||
del is_admin
|
||
asset = db.session.get(FileAsset, int(intake.asset_id)) if intake.asset_id else None
|
||
source_name = None
|
||
if asset is not None:
|
||
source_name = str(getattr(asset, "original_filename", None) or "").strip() or None
|
||
submission = None
|
||
if intake.order_submission_id:
|
||
submission = db.session.get(ShippingOrderSubmission, int(intake.order_submission_id))
|
||
owner_agent_id = getattr(submission, "owner_agent_id", None) if submission is not None else None
|
||
parse_status = str(intake.parse_status or "").strip().lower()
|
||
failed = parse_status == "parse_failed"
|
||
title = "材料解析失败" if failed else "材料解析中"
|
||
message = (
|
||
str(intake.error_message or "").strip()
|
||
or str(intake.error_code or "").strip()
|
||
or ("请从失败节点重试解析" if failed else "材料仍在解析,请稍后在对话中查看进度")
|
||
)
|
||
can_handle = (
|
||
viewer_user_id is not None
|
||
and int(intake.user_id) == int(viewer_user_id)
|
||
)
|
||
item: dict[str, Any] = {
|
||
"item_kind": "order_intake",
|
||
"todo_ref": intake.intake_no,
|
||
"task_no": None,
|
||
"todo_category": "intake_parse",
|
||
"intake_no": intake.intake_no,
|
||
"intake_parse_status": parse_status,
|
||
"conversation_id": str(intake.conversation_id or "").strip() or None,
|
||
"owner_agent_id": int(owner_agent_id) if owner_agent_id is not None else None,
|
||
"created_by": intake.user_id,
|
||
"source_file_name": source_name,
|
||
"source_type": str(intake.source_type or "").strip() or None,
|
||
"customer_name": None,
|
||
"updated_at": intake.updated_at.isoformat() if intake.updated_at else None,
|
||
"created_at": intake.created_at.isoformat() if intake.created_at else None,
|
||
"ui_state": {
|
||
"stage": {"code": "intake_parse", "label": "接收解析", "index": 1, "total": 4},
|
||
# 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": "订单解析"},
|
||
"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
|
||
),
|
||
"current_todo": title,
|
||
"pause_reason": message if failed else None,
|
||
"pause_reason_code": (
|
||
str(intake.error_code or "").strip() or "intake_parse_failed"
|
||
if failed
|
||
else f"intake_{parse_status}"
|
||
),
|
||
"next_auto_step": None if failed else "document_parsing",
|
||
"event_at": intake.updated_at.isoformat() if intake.updated_at else None,
|
||
"entry_surface": "conversation_processing",
|
||
"allowed_actions": ["retry_parse"] if failed else [],
|
||
"issues": [],
|
||
"error_message": str(intake.error_message or "").strip() or 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_(
|
||
ShippingNotice.upload_status.in_(("pending", "uploading", "failed")),
|
||
db.and_(
|
||
ShippingNotice.export_file_path.isnot(None),
|
||
db.or_(
|
||
ShippingNotice.upload_status.is_(None),
|
||
db.func.lower(ShippingNotice.upload_status).notin_(("uploaded", "succeeded", "success")),
|
||
),
|
||
ShippingNotice.lifecycle_status == "active",
|
||
),
|
||
)
|
||
)
|
||
if "done" in allowed:
|
||
# 已上传/关闭/驳回终态(不含待人工上传登记)。
|
||
clauses.append(
|
||
db.or_(
|
||
ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")),
|
||
ShippingNotice.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),
|
||
)
|
||
)
|
||
if "exception" in allowed:
|
||
clauses.append(ShippingNotice.pending_human_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),
|
||
)
|
||
)
|
||
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 == ShippingNotice.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 = 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, ""))
|
||
return case(
|
||
(upload_status.in_(("uploaded", "succeeded", "success")), literal("done")),
|
||
(ShippingNotice.lifecycle_status.in_(("archived", "deleted")), literal("done")),
|
||
(
|
||
db.or_(
|
||
ShippingNotice.review_status == RS_REJECTED,
|
||
),
|
||
literal("done"),
|
||
),
|
||
(
|
||
db.or_(reason == PH_RSV_REQ, ShippingNotice.review_status == RS_RSV_REQ),
|
||
literal("review"),
|
||
),
|
||
(
|
||
db.or_(reason == PH_LOW_CONF, ShippingNotice.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")),
|
||
),
|
||
literal("exception"),
|
||
),
|
||
(
|
||
db.and_(ShippingNotice.order_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")),
|
||
(
|
||
db.and_(
|
||
_sql_str_blank(ShippingNotice.review_status),
|
||
_sql_str_blank(reason),
|
||
_sql_json_falsy(ShippingNotice.inventory_lines_json),
|
||
),
|
||
literal("in_progress"),
|
||
),
|
||
(
|
||
db.and_(
|
||
_sql_str_blank(ShippingNotice.review_status),
|
||
_sql_str_blank(reason),
|
||
_sql_str_blank(ShippingNotice.match_status),
|
||
has_lines,
|
||
),
|
||
literal("in_progress"),
|
||
),
|
||
(
|
||
db.and_(
|
||
match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
|
||
ShippingNotice.export_file_path.isnot(None),
|
||
),
|
||
literal("manual_upload"),
|
||
),
|
||
(match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), 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),
|
||
literal("exception"),
|
||
),
|
||
(
|
||
db.or_(
|
||
reason == PH_UPLOAD_RPA_FAILED,
|
||
upload_status == "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 后待人工上传登记。
|
||
(upload_status.in_(("pending", "uploading")), 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(ShippingOrderDocument.id).filter(
|
||
ShippingOrderDocument.filename.ilike(customer_like),
|
||
)
|
||
matching_candidate_ids = db.session.query(ShippingOrderCandidate.id).filter(
|
||
ShippingOrderCandidate.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(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),
|
||
)
|
||
)
|
||
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),
|
||
)
|
||
)
|
||
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,
|
||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||
db.and_(
|
||
ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
|
||
ShippingNotice.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 范围;分类 CASE 负责排除 done。"""
|
||
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||
|
||
|
||
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 + 未建 OT Intake + 建单后 Task。
|
||
|
||
核心逻辑:pending 桶合并开放 Review Case、孤儿 Intake(intake_parse)与 Task;
|
||
Task 分类下推为与状态机同序的 SQL CASE;多端 UNION ALL 后数据库 COUNT + OFFSET/LIMIT,
|
||
仅水合当前页 id(禁止 limit(500) 截断冒充总数)。
|
||
|
||
Args:
|
||
user_id: 当前用户。
|
||
bucket: pending(review|exception|manual_upload|intake_parse)| processing | done。
|
||
page / page_size: 分页参数。
|
||
is_admin: 管理员全局只读视图。
|
||
todo_category: 可选细分类覆盖 bucket。
|
||
customer: 客户名/代码/来源文件名/Case 号/PO/Intake 号模糊过滤。
|
||
task_no: 精确任务号过滤(仅 Task 项;复核/Intake 项忽略)。
|
||
|
||
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", "intake_parse", "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
|
||
include_orphan_intakes = "intake_parse" 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"),
|
||
)
|
||
)
|
||
|
||
if include_orphan_intakes:
|
||
intakes_q = _apply_orphan_intake_customer_filter(
|
||
_visible_orphan_intakes_query(user_id, is_admin=is_admin),
|
||
customer_needle=customer_needle,
|
||
customer_like=customer_like,
|
||
)
|
||
branches.append(
|
||
intakes_q.with_entities(
|
||
literal("order_intake").label("kind"),
|
||
ShippingOrderIntake.id.label("entity_id"),
|
||
func.coalesce(
|
||
ShippingOrderIntake.updated_at, ShippingOrderIntake.created_at,
|
||
).label("sort_at"),
|
||
ShippingOrderIntake.intake_no.label("sort_ref"),
|
||
)
|
||
)
|
||
|
||
# Task 分支:exclusive intake_parse 细筛时跳过,避免无 category 子句扫出全量 Task。
|
||
task_allowed = frozenset(cat for cat in allowed if cat != "intake_parse")
|
||
if task_allowed:
|
||
tasks_q = _todo_tasks_base_query(
|
||
user_id,
|
||
is_admin=is_admin,
|
||
allowed=task_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"),
|
||
ShippingNotice.id.label("entity_id"),
|
||
func.coalesce(ShippingNotice.updated_at, ShippingNotice.created_at).label("sort_at"),
|
||
ShippingNotice.task_no.label("sort_ref"),
|
||
)
|
||
)
|
||
|
||
if not branches:
|
||
return {
|
||
"items": [],
|
||
"page": normalized_page,
|
||
"page_size": normalized_page_size,
|
||
"total": 0,
|
||
}
|
||
|
||
# [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_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"]
|
||
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
|
||
intakes_by_id: dict[int, ShippingOrderIntake] = {}
|
||
if page_intake_ids:
|
||
for intake in ShippingOrderIntake.query.filter(
|
||
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
|
||
|
||
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
|
||
if kind == "order_intake":
|
||
intake = intakes_by_id.get(entity_id_int)
|
||
if intake is None:
|
||
continue
|
||
page_rows.append(
|
||
serialize_intake_todo(
|
||
intake, 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 + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT。
|
||
|
||
Returns:
|
||
{pending, processing, done, total_pending_badge}
|
||
"""
|
||
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()
|
||
processing = active.filter(category_expr == "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,
|
||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||
db.and_(
|
||
ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
|
||
ShippingNotice.export_file_path.isnot(None),
|
||
),
|
||
)
|
||
)
|
||
.filter(category_expr == "done")
|
||
.count()
|
||
)
|
||
return {
|
||
"pending": pending,
|
||
"processing": processing,
|
||
"done": done,
|
||
"total_pending_badge": pending,
|
||
}
|