feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码

This commit is contained in:
hugo committed 2026-08-23 00:27:18 +08:00
1 parent 935bf26fa6
commit 7cfd5d167e
230 files changed
+9337 -10989

No files matched your search

@@ -1,14 +1,13 @@
"""
services/shipping_notice/query_service.py
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
依赖:ShippingCase、ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
ShippingReservation、ShippingOrderReviewCase、ShippingOrderProcessingRun、
ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、
order_review_projection(任务中心 STP retry 动作投影)。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
co8 起 shipping_batches 已删除,批次 list API 返回空、按 batch_no 查询返回 None;
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
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);
@@ -54,7 +53,6 @@ from app.models import (
ShippingTaskEvent,
ShippingUploadAttempt,
)
from app.services.shipping_notice.batch_legacy_removed import SHIPPING_BATCHES_REMOVED_MESSAGE
from app.services.shipping_notice.constants import (
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_REVIEW,
@@ -162,13 +160,6 @@ class TaskProjection(str, Enum):
DETAIL = "detail"
class BatchProjection(str, Enum):
"""批次读模型投影:工作台全量 / Tool 精简。"""
SUMMARY = "summary"
TOOL = "tool"
def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]:
"""为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。"""
verifications = ShippingInventoryVerification.query.filter_by(task_id=task.id).order_by(
@@ -219,25 +210,6 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]
}
def _task_batch_no(task: ShippingNotice) -> str | None:
"""shipping_batches 已删除;任务不再挂 batch_no。"""
del task
return None
def task_sort_key(task: ShippingNotice) -> 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[ShippingNotice]) -> list[ShippingNotice]:
"""按 batch_index、created_at 对批次任务列表排序(返回新列表)。"""
return sorted(tasks, key=task_sort_key)
def get_task_by_ref(task_ref: str) -> ShippingNotice | None:
"""按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。"""
value = str(task_ref or "").strip()
@@ -271,12 +243,6 @@ def get_task_by_ref(task_ref: str) -> ShippingNotice | None:
return None
def get_batch_by_no(batch_no: str) -> None:
"""按 batch_no 查找批次;shipping_batches 已删除,固定返回 None。"""
del batch_no
return None
def resolve_order_extraction_ui_target(
*,
user_id: int,
@@ -286,15 +252,15 @@ def resolve_order_extraction_ui_target(
"""
按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。
核心逻辑:先查当前用户、当前会话、指定 Intake 直接消费的新 Batch;没有新 Batch 时,
再沿 Candidate.consumed_task_id 查找打开的既有 Task。禁止回退到“用户最近批次”,避免并发会话串单。
核心逻辑:沿 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 非空。
`(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()
@@ -328,12 +294,6 @@ def resolve_order_extraction_ui_target(
return None, task
def get_task_in_batch(batch_no: str, task_no: str) -> ShippingNotice | None:
"""查找属于指定批次的任务;shipping_batches 已删除,固定返回 None。"""
del batch_no, task_no
return None
def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str] | None:
"""解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。"""
if not task or not task.export_file_path:
@@ -366,102 +326,6 @@ def task_export_error_message(task: ShippingNotice | None) -> str:
return ""
def list_sorted_batch_tasks(batch: Any) -> list[ShippingNotice]:
"""shipping_batches 已删除;保留签名供过渡调用方,固定返回空列表。"""
del batch
return []
def list_batch_task_summaries(batch: Any) -> list[dict[str, Any]]:
"""shipping_batches 已删除;固定返回空列表。"""
del batch
return []
def compute_batch_process_summary(tasks: list[ShippingNotice]) -> dict[str, int]:
"""批次进度汇总(Tool / 工作台 / 写回 batch.process_summary_json 共用公式)。"""
total = len(tasks)
completed = sum(1 for item in tasks if _is_task_completed(item))
failed = sum(1 for item in tasks if _is_task_failed(item))
running = sum(1 for item in tasks if _is_task_active(item))
pending = max(0, total - completed - failed - running - sum(1 for item in tasks if _is_task_needs_human(item)))
focus = next(
(
item for item in sort_batch_tasks(tasks)
if not _is_task_completed(item) and not _is_task_failed(item)
),
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: ShippingNotice) -> bool:
"""判断任务是否已进入完成态,用于会话级聚合统计。"""
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
return upload_status in {"uploaded", "succeeded", "success"} or bool(
str(getattr(task, "freight_ref_no", None) or "").strip()
)
def _is_task_failed(task: ShippingNotice) -> bool:
"""判断任务是否失败或上传失败,用于会话级异常优先展示。"""
return (
str(getattr(task, "review_status", None) or "").strip().lower() == "rejected"
or str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
)
def _is_task_needs_human(task: ShippingNotice) -> 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: ShippingNotice) -> bool:
"""判断任务是否仍处于自动执行或等待外部系统返回的状态。"""
if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task):
return False
lifecycle = str(getattr(task, "lifecycle_status", "active") or "active").strip().lower()
if lifecycle != "active":
return False
return bool(
getattr(task, "current_step", None)
or getattr(task, "inventory_snapshot_id", None)
or getattr(task, "export_file_path", None)
or getattr(task, "upload_status", None)
)
def compute_conversation_workspace_summary(batches: list[Any]) -> dict[str, int]:
"""按会话聚合多个批次的状态计数,供 Agent 会话级工作台展示。"""
tasks: list[ShippingNotice] = []
for batch in batches:
tasks.extend(list(getattr(batch, "tasks", None) 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 "")
@@ -674,12 +538,9 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
"shipping_case_id": task.shipping_case_id,
"case_no": task.shipping_case.case_no if task.shipping_case else None,
"business_no": task.shipping_case.business_no if task.shipping_case else None,
"batch_no": _task_batch_no(task),
"source_type": task.source_type,
"source_file_name": task.source_file_name,
"source_file_type": task.source_file_type,
"batch_index": task.batch_index,
"batch_total": task.batch_total,
"customer_name": header.get('customer_name') or header.get('bill_to_customer'),
"customer_resolution_status": task.customer_resolution_status,
"customer_resolution_method": task.customer_resolution_method,
@@ -790,41 +651,6 @@ def serialize_task_for_tool(task: ShippingNotice) -> dict[str, Any]:
return serialize_task(task, TaskProjection.TOOL)
def serialize_batch(batch: Any, projection: BatchProjection) -> dict[str, Any]:
"""shipping_batches 已删除;禁止序列化批次对象。"""
del batch, projection
raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE)
def serialize_batch_for_tool(batch: Any | None) -> dict[str, Any] | None:
"""Tool 批次 data 投影;shipping_batches 已删除。"""
del batch
return None
def serialize_batch_summary(batch: Any) -> dict[str, Any]:
"""shipping_batches 已删除;禁止序列化批次摘要。"""
del batch
raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE)
def serialize_conversation_batch_workspace(batch: Any) -> dict[str, Any]:
"""shipping_batches 已删除;禁止构建会话批次工作台。"""
del batch
raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE)
def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]:
"""返回一个 Agent 会话下用户可见的所有发货批次与聚合摘要(co8 起固定空集)。"""
value = str(conversation_id or "").strip()
del user_id
return {
"conversation_id": value,
"summary": compute_conversation_workspace_summary([]),
"batches": [],
}
def task_todo_category(task: ShippingNotice) -> str:
"""
由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。
@@ -1112,46 +938,15 @@ def serialize_task_detail(
)
def get_batch_for_user(batch_no: str, user_id: int) -> None:
"""按 batch_no 查找批次;shipping_batches 已删除,固定返回 None。"""
del batch_no, user_id
return None
def list_batches_for_user(
user_id: int,
*,
limit: int = 100,
) -> list[dict[str, Any]]:
"""列出用户可见批次摘要;shipping_batches 已删除,固定返回空列表。"""
del user_id, limit
return []
def list_tasks_for_batch(batch_no: str, user_id: int) -> list[dict[str, Any]]:
"""列出批次下任务;shipping_batches 已删除,固定返回空列表。"""
del batch_no, user_id
return []
def get_focus_task_for_batch(batch_no: str, user_id: int) -> ShippingNotice | None:
"""获取批次 focus 任务;shipping_batches 已删除,固定返回 None。"""
del batch_no, user_id
return None
def list_tasks_for_user(
user_id: int,
*,
batch_no: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
"""列出用户可见任务摘要,可按批次或工作台用户态状态过滤。"""
"""列出用户可见任务摘要。"""
q = ShippingNotice.query.filter(
(ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None))
)
if batch_no:
return []
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)
@@ -1164,7 +959,6 @@ def list_tasks_page_for_user(
*,
page: int = 1,
page_size: int = 20,
batch_no: str | None = None,
lifecycle_status: str | None = None,
) -> dict[str, Any]:
"""
@@ -1178,8 +972,6 @@ def list_tasks_page_for_user(
q = ShippingNotice.query.filter(
(ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None))
)
if batch_no:
return {"items": [], "page": normalized_page, "page_size": normalized_page_size, "total": 0}
if lifecycle_status:
normalized_lifecycle = str(lifecycle_status).strip().lower()
if normalized_lifecycle == 'deleted':