feat(shipping-notice): 完善处理投影与待办轮询

- 统一处理阶段、Gate 状态及跨页面投影
- 优化订单提取自动推进与待办分类查询
- 完善任务中心待办与批次轮询逻辑
- 补充后端投影、Gate、查询及 Worker 测试
- 新增待办轮询设计文档并更新技术文档
This commit is contained in:
hugo committed 2026-09-14 17:06:11 +08:00
1 parent 9d2fa522fa
commit fbca0b485c
22 files changed
+1454 -225

No files matched your search

@@ -15,8 +15,10 @@ services/shipping_notice/query_service.py
list_my_todos / count_my_todos 合并建单前 Review Case、未建 OT Intake 与 Task 待办;
serialize_review_case_todo 在 STP failed/manual_fallback 时投影 retry_stp_auto_create;
客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与确认客户/来源文档;
待办 todo_category 优先 Gate derive_*(单任务 / enrich / 行级);无 Execution 回退 position/user_mode;
SQL CASE 仍为粗筛近似(双读过渡,与 Gate 可能短暂漂移);
待办 todo_category 优先 Gate derive_*(单任务 / enrich / 行级);
无 Execution fail-closed 进 pending(复核位 review,有 Excel 则 manual_upload,否则 exception),禁止默认 in_progress;
SQL CASE 与 derive_todo_category / F2 running 同序,处理中桶只对应系统在跑;
list 与 count 都以 CASE 为权威,禁止再用「有原因/有产物」粗筛漏掉 fail-closed 项;
list 用 UNION ALL + COUNT/OFFSET/LIMIT,仅水合当前页(禁止 500 截断冒充总数);
fetch_gate_positions 批量读 Execution.current_gate_code,供 Gate 推导待办避免 N+1;
DETAIL 另投影 parse_validation / process_field_gate / source_candidate 与履约时间线(Reservation/Artifact);
@@ -110,6 +112,19 @@ _REVIEW_TODO_POSITIONS = frozenset({
'notice_text_extraction_failed',
'quality_issue',
})
_REVIEW_TODO_GATE_CODES = frozenset({
'order_field_extraction',
'customer_resolution',
'reservation_validation',
})
_EXCEPTION_TODO_GATE_CODES = frozenset({
'inventory_sufficiency',
'freight_upload_rpa',
'inventory_source_routing',
'excel_readiness',
})
_RUNNING_EXECUTION_STATUSES = frozenset({'active', 'waiting_external'})
_BLOCKED_OR_FAILED_EXECUTION_STATUSES = frozenset({'blocked', 'failed'})
_PENDING_TODO_CATEGORIES = frozenset({"review", "exception", "manual_upload", "intake_parse"})
_TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = {
"pending": _PENDING_TODO_CATEGORIES,
@@ -1051,7 +1066,8 @@ def _todo_category_from_gate(
"""
从 Gate 位置推导 todo_category(替代 user_mode 路径)。
核心逻辑:derive_user_mode + derive_position → derive_todo_category。
核心逻辑:derive_user_mode + derive_position → derive_todo_category;
无 Gate 时不得经本函数默认 in_progress。
Args:
gate_pos: ``{'current_gate_code', 'status'}``;可为 None(仅靠 review_status)。
@@ -1112,12 +1128,11 @@ def _todo_category_from_process_gate(
def task_todo_category(task: ShippingNotice) -> str:
"""
推导待办分类(服务端唯一口径):优先 Gate,无 Execution 回退 position/user_mode。
推导待办分类(服务端唯一口径):优先 Gate;无 Execution 时 fail-closed。
核心逻辑:wait_manual_upload→manual_upload;complete→done;
must_human 且属复核入口→review,其余 must_human→exception;
auto_continue→in_progress。
SQL CASE 仍为粗筛近似。
auto_continue 且有 Gate 推进中→in_progress;无 Gate 禁止默认 in_progress。
Returns:
review | exception | manual_upload | in_progress | done
@@ -1128,14 +1143,19 @@ def task_todo_category(task: ShippingNotice) -> str:
_process_gate_user_summary_for_task(task),
getattr(task, 'review_status', None),
)
if gated is not None:
return gated
# Gate 投影无 current_gate_code(常见于仅有 Execution 指针、尚无 Gate 行)时,
# 与 SQL CASE 同源读最新 Execution,避免列表 hydrate 与 COUNT 分叉。
gated = _todo_category_from_latest_execution(task)
if gated is not None:
return gated
ui = resolve_task_ui_state(task)
return _todo_category_from_ui(ui.position, ui.user_mode)
return _todo_category_after_missing_gate(task, position=ui.position, user_mode=ui.user_mode)
def _todo_category_from_ui(position: str | None, kind: UserMode) -> str:
"""将 user_mode(及复核入口位置集合)映射为 todo_category(无 Gate 时回退)。"""
"""将 user_mode(及复核入口位置集合)映射为 todo_category。"""
if kind == UserMode.WAIT_MANUAL_UPLOAD:
return "manual_upload"
if kind == UserMode.COMPLETE:
@@ -1147,6 +1167,98 @@ def _todo_category_from_ui(position: str | None, kind: UserMode) -> str:
return "in_progress"
def _todo_category_without_gate(*, position: str | None, user_mode: Any) -> str:
"""
无 Gate 时的待办分类:保留人工/完成细类,禁止把未知态当成系统处理中。
核心逻辑:先走 ``_todo_category_from_ui``;若得到 in_progress 则按复核位
降为 review,否则 exception。
"""
kind = user_mode if isinstance(user_mode, UserMode) else UserMode(
str(user_mode or UserMode.AUTO_CONTINUE),
)
category = _todo_category_from_ui(position, kind)
if category != "in_progress":
return category
if str(position or "") in _REVIEW_TODO_POSITIONS:
return "review"
return "exception"
def _notice_current_export_artifact(task: Any):
"""
取 Notice 当前可上传链路上的最新 Excel Artifact。
核心逻辑:``ShippingExportArtifact.task_id`` 是 Notice.id;OT 根实体返回 None。
"""
if isinstance(task, ShippingOrderTask):
return None
notice_id = getattr(task, 'id', None)
if notice_id is None:
return None
return (
ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == int(notice_id),
ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')),
)
.order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc())
.first()
)
def _todo_category_after_missing_gate(task: Any, *, position: str | None, user_mode: Any) -> str:
"""
无 Gate 摘要时的待办分类。
核心逻辑:与 SQL 同序——当前 Artifact 已 uploaded→done;否则先走
``_todo_category_without_gate``;仍为 exception 且有 ready/uploading Excel→manual_upload。
"""
artifact = _notice_current_export_artifact(task)
if artifact is not None and str(getattr(artifact, 'status', '') or '').strip() == 'uploaded':
return 'done'
category = _todo_category_without_gate(position=position, user_mode=user_mode)
if category != "exception":
return category
if artifact is not None and str(getattr(artifact, 'status', '') or '').strip() in {
'ready', 'uploading',
}:
return "manual_upload"
return category
def _todo_category_from_latest_execution(task: Any) -> str | None:
"""
Gate 行缺失时按最新 Execution 指针推导 todo_category,与 SQL CASE 对齐。
核心逻辑:Execution.task_id 只认 OT.id;有 ``current_gate_code`` 则走
``_todo_category_from_gate``;否则返回 None 供无 Gate fail-closed。
"""
if isinstance(task, ShippingOrderTask):
order_task_id = getattr(task, 'id', None)
else:
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id is None:
return None
execution = (
ShippingProcessExecution.query
.filter(
ShippingProcessExecution.task_id == int(order_task_id),
ShippingProcessExecution.status != 'superseded',
)
.order_by(ShippingProcessExecution.id.desc())
.first()
)
if execution is None or not str(getattr(execution, 'current_gate_code', '') or '').strip():
return None
return _todo_category_from_gate(
{
'current_gate_code': execution.current_gate_code,
'status': getattr(execution, 'status', None),
},
getattr(task, 'review_status', None),
)
def _todo_category_from_task_row(
row: Any,
*,
@@ -1156,7 +1268,8 @@ def _todo_category_from_task_row(
"""
用轻量任务行计算 todo_category,避免索引阶段全量 ORM + 订单行 N+1。
核心逻辑:若调用方已批量取 gate_pos 则走 Gate;否则仅凭 review_status 薄回退。
核心逻辑:若调用方已批量取 gate_pos 则走 Gate;否则仅凭 review_status 薄回退,
且 fail-closed 不得默认 in_progress。
"""
del extractions_with_lines # 领域行事实不再参与位置裁决
if gate_pos is not None and gate_pos.get('current_gate_code'):
@@ -1166,7 +1279,6 @@ def _todo_category_from_task_row(
)
from app.services.shipping_notice.process_gate_contract import (
derive_position,
derive_todo_category,
derive_user_mode,
)
review_status = getattr(row, 'review_status', None)
@@ -1177,7 +1289,7 @@ def _todo_category_from_task_row(
review_status=review_status,
lifecycle_stage=None,
)
return derive_todo_category(user_mode=user_mode, position=position)
return _todo_category_after_missing_gate(row, position=position, user_mode=user_mode)
def _extractions_with_accepted_lines(extraction_ids: set[int]) -> set[int]:
@@ -1435,12 +1547,15 @@ def _enrich_task_center_fields(
ui_state.get("process_gate") if isinstance(ui_state, dict) else None,
ui_state.get("review_status") if isinstance(ui_state, dict) else getattr(task, 'review_status', None),
)
if gated is None:
gated = _todo_category_from_latest_execution(task)
if gated is not None:
data["todo_category"] = gated
else:
data["todo_category"] = _todo_category_from_ui(
ui_state.get("position") if isinstance(ui_state, dict) else None,
UserMode(str((ui_state or {}).get("user_mode") or UserMode.AUTO_CONTINUE)),
data["todo_category"] = _todo_category_after_missing_gate(
task,
position=ui_state.get("position") if isinstance(ui_state, dict) else None,
user_mode=(ui_state or {}).get("user_mode") or UserMode.AUTO_CONTINUE,
)
_inject_unified_processing_fields(task, data)
# [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。
@@ -1922,14 +2037,31 @@ def _gate_todo_category_sql_whens(task_id_column):
"""
Gate 优先的 todo_category CASE when 列表(对齐 derive_todo_category)。
核心逻辑:复核 gate→review;人工上传 handoff→manual_upload;
短缺/失败类 gate→exception;准备/匹配运行中→in_progress。
核心逻辑:Execution.status 区分系统在跑与阻断;复核 gate 仅在 blocked/failed
时进 review;人工上传 handoff→manual_upload;短缺/失败类 gate→exception;
active/waiting_external→in_progress。禁止无状态默认 in_progress。
"""
gate_code = _latest_process_execution_field_sql(task_id_column, 'current_gate_code')
gate_exec_status = _latest_process_execution_field_sql(task_id_column, 'status')
blocked_or_failed = gate_exec_status.in_(tuple(sorted(_BLOCKED_OR_FAILED_EXECUTION_STATUSES)))
running_exec = gate_exec_status.in_(tuple(sorted(_RUNNING_EXECUTION_STATUSES)))
return [
(
gate_code.in_(('order_field_extraction', 'customer_resolution', 'reservation_validation')),
db.and_(
gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))),
blocked_or_failed,
),
literal('review'),
),
(
db.and_(
gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))),
running_exec,
),
literal('in_progress'),
),
(
gate_code.in_(tuple(sorted(_REVIEW_TODO_GATE_CODES))),
literal('review'),
),
(
@@ -1945,35 +2077,28 @@ def _gate_todo_category_sql_whens(task_id_column):
),
(
db.and_(
gate_code.in_(
(
'inventory_sufficiency',
'freight_upload_rpa',
'inventory_source_routing',
'excel_readiness',
)
),
gate_exec_status.in_(('blocked', 'failed')),
gate_code.in_(tuple(sorted(_EXCEPTION_TODO_GATE_CODES))),
blocked_or_failed,
),
literal('exception'),
),
(
gate_code.in_(
(
'inventory_preparation',
'inventory_matching',
'inventory_field_mapping',
'order_freeze_readiness',
'artifact_generation',
)
),
gate_exec_status.in_(('failed',)),
literal('exception'),
),
(
gate_exec_status.in_(('blocked',)),
literal('exception'),
),
(
running_exec,
literal('in_progress'),
),
]
def _order_task_todo_category_sql_expr():
"""按 Gate 优先、再领域事实投影 OT 待办,禁止读取库存 JSON 投影。"""
"""按 Gate 优先、再领域事实投影 OT 待办;无判定时 fail-closed 为 exception。"""
stage = db.func.lower(db.func.coalesce(ShippingOrderTask.stage, ""))
reason = db.func.lower(db.func.coalesce(ShippingOrderTask.pending_human_reason, ""))
ready_file = exists(
@@ -2046,7 +2171,7 @@ def _order_task_todo_category_sql_expr():
literal("in_progress"),
),
(stage.in_(("inventory_source_resolving", "notification_preparation", "inventory_fetching", "inventory_matching", "order_creating")), literal("in_progress")),
else_=literal("in_progress"),
else_=literal("exception"),
)
def _visible_open_review_cases_query(user_id: int, *, is_admin: bool = False):
@@ -2484,7 +2609,8 @@ def _task_todo_category_sql_expr():
待办 todo_category 的 SQL CASE:Gate 优先,再 review_status / 领域标量回退。
核心逻辑:不再与 resolve_task_ui_state「同序」;与 ORM
``task_todo_category`` / ``derive_todo_category`` 对齐,供 UNION 分页与徽标 COUNT。
``task_todo_category`` / ``derive_todo_category`` 对齐。无 Gate 且无法判定时
fail-closed 为 exception,禁止 else in_progress。
"""
has_lines = _task_has_dynamic_order_lines_sql()
reason = select(ShippingOrderTask.pending_human_reason).where(
@@ -2538,33 +2664,15 @@ def _task_todo_category_sql_expr():
literal("exception"),
),
(
db.and_(snapshot_id.is_(None), has_lines),
db.and_(
snapshot_id.is_(None),
has_lines,
),
literal("in_progress"),
),
(reason == PH_RPA_EXHAUSTED, literal("exception")),
# Excel 已生成即进入待人工上传登记,不依赖历史 match_status 是否补写。
(artifact_exists, literal("manual_upload")),
(
db.and_(
_sql_str_blank(review_status),
_sql_str_blank(reason),
~exists().where(
ShippingTaskInventoryLink.task_id == ShippingNotice.order_task_id,
ShippingTaskInventoryLink.is_active.is_(True),
ShippingTaskInventoryLink.invalidated_at.is_(None),
),
),
literal("in_progress"),
),
(
db.and_(
_sql_str_blank(review_status),
_sql_str_blank(reason),
~match_exists,
has_lines,
),
literal("in_progress"),
),
(
db.and_(
match_exists,
@@ -2572,7 +2680,6 @@ def _task_todo_category_sql_expr():
),
literal("manual_upload"),
),
(match_exists, literal("in_progress")),
(reason == PH_INV_UNAVAIL, literal("exception")),
(reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")),
(
@@ -2591,7 +2698,7 @@ def _task_todo_category_sql_expr():
(reason == PH_UPLOAD_RPA_PENDING, literal("exception")),
# Excel 后待人工上传登记。
(upload_pending, literal("manual_upload")),
else_=literal("in_progress"),
else_=literal("exception"),
)
def _todo_sort_key_from_dt(value: Any, ref: str) -> tuple[str, str]:
@@ -2657,23 +2764,15 @@ def _todo_tasks_base_query(
task_no: str | None,
):
"""
构造带粗筛 + 精确 category CASE 过滤的 Task 待办查询。
构造带精确 category CASE 过滤的 Task 待办查询。
核心逻辑:可见性 / 客户 / bucket 粗筛后,用 _task_todo_category_sql_expr().in_(allowed)。
核心逻辑:可见性 / 客户过滤后,用 _task_todo_category_sql_expr().in_(allowed);
done 桶另加终态粗筛。pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。
"""
q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
workflow_pending_reason = select(ShippingOrderTask.pending_human_reason).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
workflow_current_step = select(ShippingOrderTask.current_step).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery()
workflow_customer_pending = exists(
select(1).select_from(ShippingCustomerShadowResolution)
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
.where(ShippingOrderTask.id == ShippingNotice.order_task_id,
ShippingCustomerShadowResolution.status != 'confirmed')
)
artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded'))))
upload_success = _verified_upload_success_sql_expr()
upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(('pending', 'running', 'failed', 'unknown'))))
match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True)))
if task_no:
q = q.filter(ShippingNotice.task_no == str(task_no).strip())
@@ -2703,25 +2802,9 @@ def _todo_tasks_base_query(
)
)
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_(
workflow_pending_reason.isnot(None),
workflow_review_status.isnot(None),
artifact_exists,
workflow_current_step.isnot(None),
exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(
ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None),
)),
upload_pending,
)
)
elif normalized_bucket == "done":
# [STEP] 精确分类由 CASE 下推。pending 含无 Gate fail-closed,禁止再用
# 「有原因/有产物/有 Execution」粗筛把裸 Notice 漏掉,否则 list 与 count 分叉。
if normalized_bucket == "done":
# Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。
q = q.filter(
db.or_(
@@ -2842,8 +2925,11 @@ def list_my_todos(
)
)
# 库存准备尚未创建正式 Notice 时,待办必须来自 OT,否则失败任务会从任务中心消失。
ot_allowed = frozenset(cat for cat in task_allowed if cat in {"exception", "in_progress"})
# 库存准备尚未创建正式 Notice 时,待办必须来自 OT,否则失败/复核任务会从任务中心消失。
ot_allowed = frozenset(
cat for cat in task_allowed
if cat in {"exception", "in_progress", "review", "manual_upload"}
)
if ot_allowed:
ot_q = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin)
if task_no:
@@ -2988,7 +3074,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
pending += active.filter(category_expr.in_(task_pending_cats)).count()
ot_active = _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin)
ot_category = _order_task_todo_category_sql_expr()
pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse", "manual_upload"})))).count()
pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))).count()
processing = active.filter(category_expr == "in_progress").count()
processing += ot_active.filter(ot_category == "in_progress").count()
done = (