- 移除不必要的状态引用 - 更新上传处理提示文本,使用国际化支持 - 扩展发货任务摘要接口,增加错误信息和短缺信息 - 更新多语言支持的文本,改善用户体验 - 增加批次工作区的汇总信息和操作提示
494 lines
19 KiB
Python
494 lines
19 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 asc, 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"})
|
|
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- 任务编号。"""
|
|
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 基础字段(裁剪前)。"""
|
|
from app.services.shipping_notice.notice_upload import max_notice_chars
|
|
|
|
payload: dict[str, Any] = {
|
|
"task_no": task.task_no,
|
|
"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,
|
|
"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,
|
|
"step_payload": task.step_payload_json or {},
|
|
}
|
|
raw_content = str(task.raw_content or "").strip()
|
|
lines = task.lines_json or []
|
|
# 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_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,
|
|
"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": task.step_payload_json or {},
|
|
"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,
|
|
}
|
|
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_conversation_batch_workspace(batch: ShippingBatch, user_id: int) -> dict[str, Any]:
|
|
"""序列化会话工作台中的单个批次,包含批次摘要、任务列表与焦点任务。"""
|
|
focus_task = get_focus_task_for_batch(batch.batch_no, user_id)
|
|
return {
|
|
**serialize_batch_summary(batch),
|
|
"tasks": list_batch_task_summaries(batch),
|
|
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
|
}
|
|
|
|
|
|
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, user_id)
|
|
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
|