Files
syops/backend/app/services/shipping_notice/query_service.py
T

738 lines
31 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
services/shipping_notice/query_service.py
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、task_line_store。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*;
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 供持久只读展示;
订单行经 task_line_store.read_task_order_lines,支持 shadow 差异观测。
"""
from __future__ import annotations
import re
from enum import Enum
from pathlib import Path
from typing import Any
from sqlalchemy import asc, desc
from app import db
from app.models import (
ShippingBatch,
ShippingCase,
ShippingNoticeCandidate,
ShippingNoticeIntake,
ShippingTask,
)
from app.services.shipping_notice.task_line_store import read_task_order_lines
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)
class TaskProjection(str, Enum):
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
TOOL = "tool"
TOOL_INTERNAL = "tool_internal"
SUMMARY = "summary"
DETAIL = "detail"
class BatchProjection(str, Enum):
"""批次读模型投影:工作台全量 / Tool 精简。"""
SUMMARY = "summary"
TOOL = "tool"
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:
"""解析任务导出文件路径;文件不存在或路径无效时返回 None。"""
if not task or not task.export_file_path:
return None
path = Path(task.export_file_path)
if not path.is_file():
return None
return path, task.export_file_name or path.name
def task_export_error_message(task: ShippingTask | None) -> str:
"""导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。"""
if not task or not task.export_file_path:
return "export file not found"
path = Path(task.export_file_path)
if not path.is_file():
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]]:
"""返回批次下已排序任务的摘要投影列表。"""
return [serialize_task(item, TaskProjection.SUMMARY) 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 {}
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": task.customer_name,
"customer_code": task.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": task.ship_to,
"po_number": task.po_number,
"required_date": task.required_date,
"lines": read_task_order_lines(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;
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
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 []),
}
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 {}
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": task.customer_name,
"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,
"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_site_id": task.inventory_site_id,
"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))
return data
if projection == TaskProjection.DETAIL:
step_payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
data = serialize_task(task, TaskProjection.SUMMARY)
data.update({
"customer_code": task.customer_code,
"ship_to": task.ship_to,
"po_number": task.po_number,
"required_date": task.required_date,
"step_payload": step_payload,
"upload_receipt": task.upload_receipt_json or {},
"export_version": task.export_version,
"idempotency_key": task.idempotency_key,
"lines": read_task_order_lines(task),
"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_data_version": int(task.order_data_version or 1),
"field_conflicts": _serialize_open_field_conflicts(task),
"events": [
{
"event_type": e.event_type,
"detail_json": e.detail_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 serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
"""工作台任务列表用的 SUMMARY 投影。"""
return serialize_task(task, TaskProjection.SUMMARY)
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
"""工作台任务详情用的 DETAIL 投影(含 lines、events 等)。"""
return serialize_task(task, TaskProjection.DETAIL)
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]]:
"""列出用户可见任务摘要,可按 batch_no / process_status 过滤。"""
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:
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) for c in rows]
def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None:
"""按 task_no 查找任务并校验 user_id 归属。"""
task = get_task_by_ref(task_no)
if not task:
return None
if task.user_id is not None and task.user_id != user_id:
return None
return task