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

376 lines
14 KiB
Python

"""
services/shipping_notice/query_service.py
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影。
依赖:models.ShippingBatch、ShippingTask、ShippingTaskEvent。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉。
"""
from __future__ import annotations
import re
from enum import Enum
from pathlib import Path
from typing import Any
from sqlalchemy import desc
from app import db
from app.models import ShippingBatch, ShippingTask
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
_TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", 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 或数字主键查找任务(Tool API / 内部引用解析)。"""
value = str(task_ref or "").strip()
if not value:
return None
task = ShippingTask.query.filter_by(task_no=value).first()
if task:
return task
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 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"})
return {
"total": total,
"completed": completed,
"failed": failed,
"running": running,
}
def extract_task_no_from_text(text: str) -> str | None:
"""从自然语言文本中提取 SN- 任务编号。"""
match = _TASK_NO_RE.search(str(text or ""))
return match.group(0).upper() if match else None
def resolve_task_from_payload(payload: dict[str, Any]) -> ShippingTask | None:
"""按 task_id/task_no、文本内嵌 SN- 或 conversation_id 解析任务(只读)。"""
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
conv_id = str(payload.get("conversation_id") or "").strip()
if conv_id:
return (
ShippingTask.query.filter_by(conversation_id=conv_id)
.filter(ShippingTask.process_status.notin_(["rejected"]))
.order_by(ShippingTask.id.desc())
.first()
)
return None
def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"""Tool data 基础字段(裁剪前)。"""
return {
"task_no": task.task_no,
"process_status": task.process_status,
"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,
"ship_to": task.ship_to,
"po_number": task.po_number,
"required_date": task.required_date,
"lines": task.lines_json or [],
"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,
}
def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]:
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
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:
return {
"id": task.id,
"task_no": task.task_no,
"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,
"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,
"conversation_id": task.conversation_id,
"export_file_name": task.export_file_name,
"freight_ref_no": task.freight_ref_no,
"created_at": task.created_at.isoformat() if task.created_at else None,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}
if projection == TaskProjection.DETAIL:
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": task.step_payload_json or {},
"upload_receipt": task.upload_receipt_json or {},
"export_version": task.export_version,
"idempotency_key": task.idempotency_key,
"lines": task.lines_json or [],
"shortage": task.shortage_json,
"line_results": task.line_results_json or [],
"parse_confidence": task.parse_confidence,
"error_message": task.error_message,
"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_task_summary(task: ShippingTask) -> dict[str, Any]:
return serialize_task(task, TaskProjection.SUMMARY)
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
return serialize_task(task, TaskProjection.DETAIL)
def get_batch_for_user(batch_no: str, user_id: int) -> ShippingBatch | None:
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]]:
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]]:
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:
batch = get_batch_for_user(batch_no, user_id)
if not batch:
return None
focus_task_no = str(batch.current_focus_task_no or "").strip()
if focus_task_no:
task = get_task_by_ref(focus_task_no)
if task and task.batch_id == batch.id:
return task
tasks = list_sorted_batch_tasks(batch)
return tasks[0] if tasks else None
def list_tasks_for_user(
user_id: int,
*,
batch_no: str | None = None,
process_status: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
q = ShippingTask.query.filter(
(ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None))
)
if batch_no:
batch = get_batch_for_user(batch_no, user_id)
if not batch:
return []
q = q.filter(ShippingTask.batch_id == batch.id)
if process_status:
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 = 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