feat(shipping-notice): 落地字段资产治理与唯一 Schema,自动建单随版本冻结
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b7307fc573
commit
3a1dbf7ce5
144 files changed
+15167
-4480
No files matched your search
@@ -1,11 +1,16 @@
|
||||
"""
|
||||
services/shipping_notice/query_service.py
|
||||
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、动态订单字段编辑器。
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingNoticeCandidate、ShippingTask、ShippingTaskEvent、
|
||||
ShippingOrderReviewCase、ShippingOrderExtractionRun、state_machine、动态订单字段编辑器。
|
||||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||||
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
|
||||
SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*;
|
||||
SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event;
|
||||
list_my_todos / count_my_todos 合并建单前 Review Case 与 Task 待办(管理员可读全局,仅创建者 can_handle);
|
||||
客户关键字 SQL 同时过滤 Review Case(文件名/Case 号/PO)与 Task(客户快照/来源文件名);
|
||||
待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT,
|
||||
仅水合当前页(禁止 500 截断冒充总数);
|
||||
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 供持久只读展示;
|
||||
订单行仅从任务锁定 Extraction 的 FieldValue 投影,未抽取任务返回空行集。
|
||||
"""
|
||||
@@ -17,7 +22,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import asc, desc
|
||||
from sqlalchemy import asc, case, desc, exists, func, literal, select, union_all
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
@@ -27,10 +32,41 @@ from app.models import (
|
||||
ShippingExportArtifactLine,
|
||||
ShippingInventoryVerification,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingTask,
|
||||
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,
|
||||
@@ -42,6 +78,38 @@ EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.
|
||||
_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"})
|
||||
_TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
|
||||
"pending": _PENDING_TODO_CATEGORIES,
|
||||
"processing": frozenset({"in_progress"}),
|
||||
"done": frozenset({"done"}),
|
||||
}
|
||||
|
||||
# 建单前人工复核 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": "复核要求重识别,处理中",
|
||||
}
|
||||
|
||||
|
||||
class TaskProjection(str, Enum):
|
||||
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
|
||||
@@ -273,8 +341,8 @@ def list_sorted_batch_tasks(batch: ShippingBatch) -> list[ShippingTask]:
|
||||
|
||||
|
||||
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)]
|
||||
"""返回批次下已排序任务的摘要投影列表(含任务中心 enrich 字段)。"""
|
||||
return [serialize_task_summary(item) for item in list_sorted_batch_tasks(batch)]
|
||||
|
||||
|
||||
def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]:
|
||||
@@ -750,14 +818,223 @@ def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
|
||||
"""工作台任务列表用的 SUMMARY 投影。"""
|
||||
return serialize_task(task, TaskProjection.SUMMARY)
|
||||
def task_todo_category(task: ShippingTask) -> str:
|
||||
"""
|
||||
由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。
|
||||
|
||||
核心逻辑:complete→done;wait_manual_upload→manual_upload;
|
||||
must_human 且属复核入口→review,其余 must_human→exception;auto_continue→in_progress。
|
||||
|
||||
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 serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
|
||||
"""工作台任务详情用的 DETAIL 投影(含 lines、events 等)。"""
|
||||
return serialize_task(task, TaskProjection.DETAIL)
|
||||
def _todo_category_from_ui(checkpoint: str | None, kind: CheckpointKind) -> str:
|
||||
"""将 checkpoint_kind(及复核入口集合)映射为 todo_category。"""
|
||||
if kind == CheckpointKind.COMPLETE:
|
||||
return "done"
|
||||
if kind == CheckpointKind.WAIT_MANUAL_UPLOAD:
|
||||
return "manual_upload"
|
||||
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
|
||||
)
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
process_status=getattr(row, "process_status", None),
|
||||
review_status=getattr(row, "review_status", None),
|
||||
pending_human_reason=getattr(row, "pending_human_reason", None),
|
||||
shipping_case_id=getattr(row, "shipping_case_id", 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: ShippingTask, 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: ShippingTask) -> 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: ShippingTask) -> 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 _enrich_task_center_fields(
|
||||
task: ShippingTask,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。
|
||||
|
||||
核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle;
|
||||
recent_event / artifact_summary / ui_state 懒加载同源状态,避免任务中心再推导。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
data: 已构建的序列化字典。
|
||||
viewer_user_id: 当前查看者;为 None 时省略 can_handle。
|
||||
is_admin: 是否管理员视图(仅影响 can_handle 调用签名,不开放代操作)。
|
||||
|
||||
Returns:
|
||||
同一 data 引用(已 enrich)。
|
||||
"""
|
||||
data["todo_category"] = task_todo_category(task)
|
||||
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)
|
||||
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
data["ui_state"] = build_task_ui_state(task)
|
||||
return data
|
||||
|
||||
|
||||
def serialize_task_summary(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
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: ShippingTask,
|
||||
*,
|
||||
viewer_user_id: int | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
|
||||
|
||||
Args:
|
||||
task: 源任务。
|
||||
viewer_user_id: 当前查看者;用于 can_handle。
|
||||
is_admin: 是否管理员视图。
|
||||
"""
|
||||
data = serialize_task(task, TaskProjection.DETAIL)
|
||||
return _enrich_task_center_fields(
|
||||
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
|
||||
)
|
||||
|
||||
|
||||
def get_batch_for_user(batch_no: str, user_id: int) -> ShippingBatch | None:
|
||||
@@ -830,7 +1107,10 @@ def list_tasks_for_user(
|
||||
else:
|
||||
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]
|
||||
return [
|
||||
serialize_task_summary(c, viewer_user_id=user_id)
|
||||
for c in rows
|
||||
]
|
||||
|
||||
|
||||
def list_tasks_page_for_user(
|
||||
@@ -887,7 +1167,10 @@ def list_tasks_page_for_user(
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"items": [serialize_task_summary(item) for item in rows],
|
||||
"items": [
|
||||
serialize_task_summary(item, viewer_user_id=user_id)
|
||||
for item in rows
|
||||
],
|
||||
"page": normalized_page,
|
||||
"page_size": normalized_page_size,
|
||||
"total": total,
|
||||
@@ -895,10 +1178,614 @@ def list_tasks_page_for_user(
|
||||
|
||||
|
||||
def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None:
|
||||
"""按 task_no 查找任务并校验 user_id 归属。"""
|
||||
"""
|
||||
按 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 not None and task.user_id != user_id:
|
||||
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,
|
||||
) -> ShippingTask | 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 _task_matches_customer_filter(task: ShippingTask, customer: str) -> bool:
|
||||
"""待办列表客户关键字过滤:匹配 case 快照、来源文件名或当前订单头客户名。"""
|
||||
needle = str(customer or "").strip().lower()
|
||||
if not needle:
|
||||
return True
|
||||
case = task.shipping_case
|
||||
candidates: list[str] = []
|
||||
if case is not None:
|
||||
for value in (
|
||||
getattr(case, "customer_name_snapshot", None),
|
||||
getattr(case, "customer_short_code_snapshot", None),
|
||||
):
|
||||
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 = ShippingTask.query.filter(
|
||||
ShippingTask.deleted_at.is_(None),
|
||||
ShippingTask.lifecycle_status == "active",
|
||||
)
|
||||
if not is_admin:
|
||||
# 待办中心拒绝无主任务;仅创建者可见。
|
||||
q = q.filter(ShippingTask.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.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。
|
||||
|
||||
Args:
|
||||
case: 开放中的 Review Case。
|
||||
viewer_user_id: 当前查看者;用于 can_handle。
|
||||
is_admin: 是否管理员视图(不开放代操作)。
|
||||
|
||||
Returns:
|
||||
与任务 SUMMARY 兼容的待办字典。
|
||||
"""
|
||||
del is_admin
|
||||
run = db.session.get(ShippingOrderExtractionRun, case.run_id) if case.run_id else None
|
||||
document = db.session.get(ShippingNoticeDocument, case.document_id) if case.document_id else None
|
||||
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)
|
||||
)
|
||||
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,
|
||||
"process_status": 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": {
|
||||
"checkpoint": "order_review",
|
||||
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
|
||||
"action_buttons": [],
|
||||
"summary": {
|
||||
"title": "待人工复核",
|
||||
"message": current_todo,
|
||||
"stage": "待人工复核",
|
||||
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
|
||||
"current_todo": current_todo,
|
||||
"pause_reason": current_todo,
|
||||
"pause_reason_code": 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": [],
|
||||
"issues": [],
|
||||
"error_message": 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 "done" in allowed:
|
||||
clauses.append(ShippingTask.process_status.in_(("uploaded", "closed", "rejected")))
|
||||
if "manual_upload" in allowed:
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingTask.process_status.in_(("waiting_upload", "upload_failed")),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
)
|
||||
)
|
||||
if "review" in allowed:
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingTask.process_status == "pending_review",
|
||||
ShippingTask.review_status.isnot(None),
|
||||
)
|
||||
)
|
||||
if "exception" in allowed:
|
||||
clauses.append(ShippingTask.pending_human_reason.isnot(None))
|
||||
if "in_progress" in allowed:
|
||||
clauses.append(
|
||||
ShippingTask.process_status.in_(
|
||||
("created", "parsed", "matched", "inventory_ready")
|
||||
)
|
||||
)
|
||||
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 == ShippingTask.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 / [] / {})。"""
|
||||
return db.or_(column.is_(None), column == [], column == {})
|
||||
|
||||
|
||||
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 = ShippingTask.pending_human_reason
|
||||
return case(
|
||||
(ShippingTask.process_status == "uploaded", literal("done")),
|
||||
(ShippingTask.process_status == "closed", literal("done")),
|
||||
(
|
||||
db.or_(
|
||||
ShippingTask.process_status == "rejected",
|
||||
ShippingTask.review_status == RS_REJECTED,
|
||||
),
|
||||
literal("done"),
|
||||
),
|
||||
(
|
||||
db.or_(reason == PH_RSV_REQ, ShippingTask.review_status == RS_RSV_REQ),
|
||||
literal("review"),
|
||||
),
|
||||
(
|
||||
db.or_(reason == PH_LOW_CONF, ShippingTask.review_status == RS_PARSE_REVIEW),
|
||||
literal("review"),
|
||||
),
|
||||
(reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.shipping_case_id.isnot(None),
|
||||
db.or_(
|
||||
ShippingTask.customer_resolution_status.is_(None),
|
||||
ShippingTask.customer_resolution_status != "confirmed",
|
||||
),
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
(
|
||||
db.and_(ShippingTask.order_snapshot_id.is_(None), has_lines),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(reason == PH_RPA_EXHAUSTED, literal("exception")),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "parsed",
|
||||
_sql_str_blank(ShippingTask.review_status),
|
||||
_sql_str_blank(reason),
|
||||
_sql_json_falsy(ShippingTask.inventory_lines_json),
|
||||
),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "inventory_ready",
|
||||
_sql_str_blank(ShippingTask.review_status),
|
||||
_sql_str_blank(reason),
|
||||
_sql_str_blank(ShippingTask.match_status),
|
||||
has_lines,
|
||||
),
|
||||
literal("in_progress"),
|
||||
),
|
||||
(
|
||||
db.and_(
|
||||
ShippingTask.process_status == "matched",
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
),
|
||||
literal("manual_upload"),
|
||||
),
|
||||
(ShippingTask.process_status == "matched", literal("in_progress")),
|
||||
(reason == PH_INV_UNAVAIL, literal("exception")),
|
||||
(reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")),
|
||||
(
|
||||
db.or_(reason == PH_SHORTAGE, ShippingTask.review_status == RS_SHORTAGE_REVIEW),
|
||||
literal("exception"),
|
||||
),
|
||||
(
|
||||
db.or_(
|
||||
reason == PH_UPLOAD_RPA_FAILED,
|
||||
ShippingTask.process_status == "upload_failed",
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
(reason == PH_UPLOAD_RESULT_UNKNOWN, literal("exception")),
|
||||
(reason == PH_RPA_PENDING, literal("exception")),
|
||||
(
|
||||
db.or_(
|
||||
reason == PH_UPLOAD_RPA_PENDING,
|
||||
ShippingTask.process_status == "waiting_upload",
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
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(ShippingNoticeDocument.id).filter(
|
||||
ShippingNoticeDocument.filename.ilike(customer_like),
|
||||
)
|
||||
matching_candidate_ids = db.session.query(ShippingNoticeCandidate.id).filter(
|
||||
ShippingNoticeCandidate.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(ShippingTask.task_no == str(task_no).strip())
|
||||
if customer_needle:
|
||||
q = q.outerjoin(ShippingCase, ShippingCase.id == ShippingTask.shipping_case_id).filter(
|
||||
db.or_(
|
||||
ShippingCase.customer_name_snapshot.ilike(customer_like),
|
||||
ShippingCase.customer_short_code_snapshot.ilike(customer_like),
|
||||
ShippingTask.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_(
|
||||
ShippingTask.pending_human_reason.isnot(None),
|
||||
ShippingTask.review_status.isnot(None),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
ShippingTask.process_status.in_(
|
||||
(
|
||||
"pending_review",
|
||||
"matched",
|
||||
"waiting_upload",
|
||||
"upload_failed",
|
||||
"parsed",
|
||||
"inventory_ready",
|
||||
"created",
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
elif normalized_bucket == "done":
|
||||
q = q.filter(
|
||||
ShippingTask.process_status.in_(("uploaded", "closed", "rejected"))
|
||||
)
|
||||
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 粗筛范围(不含 done)。"""
|
||||
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin).filter(
|
||||
db.or_(
|
||||
ShippingTask.pending_human_reason.isnot(None),
|
||||
ShippingTask.review_status.isnot(None),
|
||||
ShippingTask.export_file_path.isnot(None),
|
||||
ShippingTask.process_status.in_(
|
||||
(
|
||||
"pending_review",
|
||||
"matched",
|
||||
"waiting_upload",
|
||||
"upload_failed",
|
||||
"parsed",
|
||||
"inventory_ready",
|
||||
"created",
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
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 + 建单后 Task 异常/上传。
|
||||
|
||||
核心逻辑:pending 桶合并开放 Review Case(todo_category=review,含 review_run_no 深链);
|
||||
Task 分类下推为与状态机同序的 SQL CASE;两端 UNION ALL 后数据库 COUNT + OFFSET/LIMIT,
|
||||
仅水合当前页 id(禁止 limit(500) 截断冒充总数)。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户。
|
||||
bucket: pending(review|exception|manual_upload)| processing | done。
|
||||
page / page_size: 分页参数。
|
||||
is_admin: 管理员全局只读视图。
|
||||
todo_category: 可选细分类覆盖 bucket。
|
||||
customer: 客户名/代码/来源文件名/Case 号/PO 模糊过滤(Task 与 Review Case 均参与)。
|
||||
task_no: 精确任务号过滤(仅 Task 项;复核项忽略)。
|
||||
|
||||
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", "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
|
||||
|
||||
# [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"),
|
||||
)
|
||||
)
|
||||
|
||||
tasks_q = _todo_tasks_base_query(
|
||||
user_id,
|
||||
is_admin=is_admin,
|
||||
allowed=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"),
|
||||
ShippingTask.id.label("entity_id"),
|
||||
func.coalesce(ShippingTask.updated_at, ShippingTask.created_at).label("sort_at"),
|
||||
ShippingTask.task_no.label("sort_ref"),
|
||||
)
|
||||
)
|
||||
|
||||
# [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_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
|
||||
tasks_by_id: dict[int, ShippingTask] = {}
|
||||
if page_task_ids:
|
||||
for task in ShippingTask.query.filter(ShippingTask.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
|
||||
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 计入 pending;Task 用 SQL CASE 分类后 COUNT,
|
||||
不扫描全量 ORM 行。
|
||||
|
||||
Returns:
|
||||
{pending, processing, done, total_pending_badge}
|
||||
"""
|
||||
pending = _visible_open_review_cases_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)
|
||||
pending += (
|
||||
active.filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES)))).count()
|
||||
)
|
||||
processing = active.filter(category_expr == "in_progress").count()
|
||||
done = (
|
||||
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
.filter(ShippingTask.process_status.in_(("uploaded", "closed", "rejected")))
|
||||
.filter(category_expr == "done")
|
||||
.count()
|
||||
)
|
||||
return {
|
||||
"pending": pending,
|
||||
"processing": processing,
|
||||
"done": done,
|
||||
"total_pending_badge": pending,
|
||||
}
|
||||
Reference in new issue
Block a user