Merge branch 'hugo-shipping-notice' into dev
This commit is contained in:
commit
8fac0362bc
50 files changed
+2038
-365
No files matched your search
@@ -3,10 +3,11 @@ services/shipping_notice/auto_progress_controller.py
|
||||
|
||||
用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。
|
||||
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务;
|
||||
process_gate_job_service.cancel_inventory_external_wait_polls(显式 retry_rpa 终止轮询)。
|
||||
process_gate_job_service.cancel_inventory_external_wait_polls(显式回到库存准备时终止轮询)。
|
||||
逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job
|
||||
在同一数据库事务落库。显式 inventory_mode=retry_rpa 时覆盖 waiting_external 残留 poll,
|
||||
强制入队 retry_inventory_preparation。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
|
||||
在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 inventory_preparation 时
|
||||
覆盖 waiting_external 残留 poll 并入队准备动作(改源默认 auto 复用指定源快照)。
|
||||
库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -413,9 +414,15 @@ def submit_auto_progress(
|
||||
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
# 显式回到库存准备:用户点「重新获取」(retry_rpa) 或人工改源
|
||||
# (manual_override_source)。后者 inventory_mode 可为 auto(复用指定源快照),
|
||||
# 但仍须取消残留 poll / 活动 Attempt,否则会只读轮询、不按新源取数。
|
||||
explicit_inventory_retry = (
|
||||
str(inventory_mode or '').strip() == 'retry_rpa'
|
||||
and str(resume_gate_code or '').strip() == 'inventory_preparation'
|
||||
str(resume_gate_code or '').strip() == 'inventory_preparation'
|
||||
and (
|
||||
str(inventory_mode or '').strip() == 'retry_rpa'
|
||||
or str(trigger or '').strip() == 'manual_override_source'
|
||||
)
|
||||
)
|
||||
if not explicit_inventory_retry:
|
||||
sync_fulfillment_gates_from_task(
|
||||
|
||||
@@ -5,8 +5,8 @@ services/shipping_notice/lifecycle_projection.py
|
||||
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
|
||||
逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因;
|
||||
[B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时
|
||||
兜底;无正式事实时保持未分类。本模块只做只读业务投影,不授权任何写操作;
|
||||
阶段入口与实际动作权限必须分开。
|
||||
兜底;无正式事实时保持未分类。兼容 OT.stage 上残留的 step_key 别名。
|
||||
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -75,6 +75,11 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
|
||||
'freight_uploading': 'freight_upload',
|
||||
'manual_upload_handoff': 'freight_upload',
|
||||
'completed': 'upload_complete',
|
||||
# 历史 step_key 曾被误写入 OT.stage;投影只读别名,避免工作台掉回接收解析空白页。
|
||||
'step5_match_inventory': 'fulfillment_prep',
|
||||
'step6_generate_file': 'fulfillment_prep',
|
||||
'step3_inventory_prepare': 'fulfillment_prep',
|
||||
'step7_upload_freight': 'freight_upload',
|
||||
}
|
||||
|
||||
def lifecycle_entries(
|
||||
|
||||
@@ -1263,13 +1263,27 @@ def revive_layout_prerequisite_failed_units(run: ShippingOrderProcessingRun) ->
|
||||
|
||||
|
||||
def _enqueue_ready_order_extraction_job(
|
||||
run: ShippingOrderProcessingRun, *, message: str,
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
message: str,
|
||||
continue_from_running: bool = False,
|
||||
) -> int:
|
||||
"""
|
||||
为已有 ready 活的 Run 入队(或复用)extraction Job,并抬高 queued 优先级以便插队。
|
||||
|
||||
核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到
|
||||
_ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。
|
||||
自交接续抽(预算耗尽 / layout ready)须 continue_from_running=True,仅对 queued
|
||||
去重,避免复用即将结束的 running Job。
|
||||
|
||||
Args:
|
||||
run: 订单抽取 Run。
|
||||
message: Job 初始状态说明。
|
||||
continue_from_running: True 时 dedupe_statuses=('queued',),供当前 running
|
||||
Job 出口自交接;False(默认)可复用 queued/running,供 layout 完成回调唤醒。
|
||||
|
||||
Returns:
|
||||
入队或复用的 Job.id。
|
||||
"""
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
@@ -1283,6 +1297,7 @@ def _enqueue_ready_order_extraction_job(
|
||||
priority=_ORDER_EXTRACTION_READY_PRIORITY,
|
||||
max_attempts=3,
|
||||
message=message,
|
||||
dedupe_statuses=('queued',) if continue_from_running else None,
|
||||
commit=False,
|
||||
)
|
||||
job = db.session.get(Job, int(job_id))
|
||||
|
||||
@@ -971,11 +971,15 @@ def _handle_retry_inventory_preparation(
|
||||
inventory_payload['source_codes'] = list(line_scope['source_codes'])
|
||||
inventory_payload['snapshot_line_id'] = int(line_scope['snapshot_line_id'])
|
||||
# [STEP] 按已有动作码映射 ensure_inventory mode(零新动作码)。
|
||||
# 禁止「人工入口一律 retry_rpa」:仅显式强制 RPA 码写 retry_rpa;poll 只读轮询;
|
||||
# 首次 gate_attempt_passed 自动投递保持默认 auto(先复用快照)。
|
||||
# 禁止「人工入口一律 retry_rpa」:poll 只读;gate_attempt_passed 首投保持 auto;
|
||||
# 人工改源显式 inventory_mode=auto 按指定源复用快照;其余强制 RPA 码才跳过复用。
|
||||
action_code = str(payload.get('action_code') or '').strip()
|
||||
if action_code in _FORCE_INVENTORY_RPA_ACTION_CODES and not is_initial_auto_dispatch:
|
||||
inventory_payload['mode'] = 'retry_rpa'
|
||||
requested_mode = str(payload.get('inventory_mode') or '').strip()
|
||||
if requested_mode == 'auto' and str(payload.get('trigger') or '') == 'manual_override_source':
|
||||
inventory_payload['mode'] = 'auto'
|
||||
else:
|
||||
inventory_payload['mode'] = 'retry_rpa'
|
||||
if action_code == 'poll_inventory_preparation':
|
||||
# [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试,
|
||||
# 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。
|
||||
@@ -1015,8 +1019,9 @@ def _handle_override_line_inventory_source(
|
||||
覆写为任一**已启用**库存源,而不仅限于规则候选。先放开、后续再收紧到仅候选源。
|
||||
|
||||
校验顺序:Excel 锁 → 源存在且启用 → 定位行候选 → 覆写;
|
||||
覆写后把该行候选钉为所选源并重跑该行匹配(snapshot 复用/触发 RPA 由既有
|
||||
auto-progress / ensure_inventory 处理:有未过期快照直接匹配,否则重新 RPA)。
|
||||
覆写后把该行候选钉为所选源。人工指定即定论:不再重跑路由规则。
|
||||
- 当前在 routing:passed 后由 complete → enqueue 首投库存准备(按冻结源取数)。
|
||||
- 当前在准备/匹配:定向回 inventory_preparation,mode=auto(有快照复用,无则 RPA)。
|
||||
|
||||
Args:
|
||||
execution: 门禁执行上下文。
|
||||
@@ -1104,9 +1109,9 @@ def _handle_override_line_inventory_source(
|
||||
},
|
||||
}
|
||||
|
||||
# 首次人工选源完成的是 routing Gate 本身;让 Attempt 以 passed 收口后,
|
||||
# process_gate_service 会统一入队下一道 inventory_preparation,避免在当前
|
||||
# routing Attempt 内递归触发 RPA 而把 Gate 状态写错。
|
||||
# 人工指定源即定论:冻结候选后不再重跑路由规则。routing Gate 以 passed 收口,
|
||||
# complete_gate_attempt → _enqueue_auto_progress_after_gate_pass 首投 inventory_preparation
|
||||
#(按已冻结源取数:有 ready 快照复用,否则再 RPA)。禁止在本 Attempt 内递归推进。
|
||||
if gate.gate_code == 'inventory_source_routing':
|
||||
return {
|
||||
'outcome': 'passed',
|
||||
@@ -1123,18 +1128,16 @@ def _handle_override_line_inventory_source(
|
||||
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
# [ROOT CAUSE FIX · RPA 不触发] 行级库存源覆写冻结新候选后,必须把 inventory_preparation Gate
|
||||
# 作为「定向人工恢复」重新推进:显式传 resume_gate_code='inventory_preparation' 与
|
||||
# inventory_mode='retry_rpa'。否则 AutoProgress 会读取该 Gate 残留的 next_action_code
|
||||
# (waiting_external → poll_inventory_preparation),只排队一个只读 poll,既不创建
|
||||
# InventoryPreparationAttempt 也不触发 RPA,最终永远停在 inventory_file_empty。
|
||||
# 与 execute_stage_capability 的「重新获取库存」路径保持同一语义(见 process_gate_service)。
|
||||
# [ROOT CAUSE FIX] 已在准备/匹配阶段改源:必须定向回到 inventory_preparation,
|
||||
# 并取消残留 poll(见 submit_auto_progress 对 manual_override_source)。
|
||||
# inventory_mode=auto:按新冻结源执行——有未过期快照直接复用,无文件才 RPA;
|
||||
# 禁止无差别 retry_rpa 把「已有指定源文件」误判成必须重导。
|
||||
run_task_auto_progress(
|
||||
task.task_no,
|
||||
trigger='manual_override_source',
|
||||
operator_id=actor_id,
|
||||
resume_gate_code='inventory_preparation',
|
||||
inventory_mode='retry_rpa',
|
||||
inventory_mode='auto',
|
||||
)
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id)
|
||||
# 覆写库存源只改变后续取数/匹配的输入,不能把“库存准备”本身伪造成成功。
|
||||
|
||||
@@ -7,6 +7,7 @@ services/shipping_notice/process_gate_projection.py
|
||||
逻辑:Chat、复核台与任务中心读取用户安全投影;管理员诊断中心读取完整投影;
|
||||
用户端同一时间最多一个阻断 + 一个主要恢复动作;诊断 Finding 不进入用户阻断;
|
||||
pending/queued/running 不冒充人工待办,但保留 execution_status 供观测;
|
||||
无 Gate 行时 current_gate_code 回退 Execution.current_gate_code(对齐待办 SQL);
|
||||
explainability.details 仅白名单业务事实;request_id 仅真实 HTTP 请求号,
|
||||
execution_no 写入 details;blocking_message 为中文兜底,前端优先 i18n。
|
||||
"""
|
||||
@@ -676,7 +677,11 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
if not blocking and str(next_action or '').strip() == 'confirm_customer':
|
||||
next_action = None
|
||||
|
||||
current_gate_code = str((current or {}).get('gate_code') or '').strip() or None
|
||||
current_gate_code = (
|
||||
str((current or {}).get('gate_code') or '').strip()
|
||||
or str(getattr(execution, 'current_gate_code', None) or '').strip()
|
||||
or None
|
||||
)
|
||||
allowed_actions: list[str] = []
|
||||
action_items: list[dict[str, str]] = []
|
||||
is_formal_inventory_matching = bool(
|
||||
|
||||
@@ -236,6 +236,8 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
||||
根据 Gate 列表重算 Execution 当前门禁与主恢复动作。
|
||||
|
||||
核心逻辑:取第一个非 passed/skipped 门禁为 current;全部通过则 completed。
|
||||
若上游 Gate 已是 invalidated,但下游仍停在真实阻断/执行态,则跳过该
|
||||
invalidated(陈旧失效残留),避免把已建单成功的 task_creation 误标为当前门禁。
|
||||
"""
|
||||
gates = (
|
||||
ShippingProcessGate.query
|
||||
@@ -245,12 +247,21 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
||||
)
|
||||
last_passed = None
|
||||
current = None
|
||||
for gate in gates:
|
||||
# 下游仍“在办事/已阻断”时,上游 invalidated 只是过期残留,不能抢 current。
|
||||
_ACTIVE_DOWNSTREAM = frozenset({
|
||||
'blocked_manual', 'blocked_retryable', 'waiting_external',
|
||||
'failed_terminal', 'running', 'queued',
|
||||
})
|
||||
for index, gate in enumerate(gates):
|
||||
if gate.status == 'passed':
|
||||
last_passed = gate.gate_code
|
||||
continue
|
||||
if gate.status == 'skipped':
|
||||
continue
|
||||
if gate.status == 'invalidated' and any(
|
||||
later.status in _ACTIVE_DOWNSTREAM for later in gates[index + 1:]
|
||||
):
|
||||
continue
|
||||
current = gate
|
||||
break
|
||||
execution.last_passed_gate_code = last_passed
|
||||
@@ -957,8 +968,10 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
) -> None:
|
||||
"""门禁通过后为绑定任务提交下一 Gate 的唯一 AutoProgress Attempt/Job。
|
||||
|
||||
核心逻辑:不再写 legacy shipping_notice_run;统一由 submit_auto_progress 创建
|
||||
ProcessGate Attempt/Job。已完成或仍需人工的任务会安全早停。
|
||||
核心逻辑:刷新指针后对「当前未通过 Gate」入队唯一 Attempt/Job。典型场景:
|
||||
人工指定库存源使 ``inventory_source_routing`` passed 后,下一道仍是
|
||||
``pending`` 且 ``next_action_code`` 为空的 ``inventory_preparation``——必须在此
|
||||
补种首投动作并入队,按已冻结源取数,禁止静默 return 导致永久「库存文件未准备」。
|
||||
"""
|
||||
try:
|
||||
# 直接为下一 Gate 创建 Attempt/ProcessGate Job,避免重新进入
|
||||
@@ -970,8 +983,21 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if next_gate is None or not next_gate.next_action_code:
|
||||
if next_gate is None:
|
||||
return
|
||||
# [STEP] pending 门禁创建时 next_action 为空;契约 default_next_actions 也没有
|
||||
# pending/queued。若不补种,人工选源 passed 后会永远卡在库存准备未跑。
|
||||
if not next_gate.next_action_code:
|
||||
if str(next_gate.status or '').strip() != 'pending':
|
||||
return
|
||||
seeded = primary_next_action_for_gate(
|
||||
gate_code=str(next_gate.gate_code),
|
||||
status='blocked_retryable',
|
||||
)
|
||||
if not seeded:
|
||||
return
|
||||
next_gate.next_action_code = seeded
|
||||
execution.primary_next_action_code = seeded
|
||||
if not action_belongs_to_gate(
|
||||
gate_code=next_gate.gate_code,
|
||||
action_code=str(next_gate.next_action_code),
|
||||
|
||||
@@ -679,8 +679,13 @@ _USER_STAGE_TO_CODE: dict[str, str] = {
|
||||
'waiting_review': 'waiting_human_review',
|
||||
'inventory_fetching': 'inventory_fetch',
|
||||
'inventory_matching': 'inventory_match',
|
||||
# step_key 误写入 OT.stage 时的只读别名(与 lifecycle_projection 同源)。
|
||||
'step5_match_inventory': 'inventory_match',
|
||||
'step3_inventory_prepare': 'inventory_fetch',
|
||||
'step6_generate_file': 'excel_generate',
|
||||
'excel_generating': 'excel_generate',
|
||||
'freight_uploading': 'freight_upload',
|
||||
'step7_upload_freight': 'freight_upload',
|
||||
'completed': 'completed',
|
||||
'failed': 'failed_terminal',
|
||||
'cancelled': 'cancelled',
|
||||
|
||||
@@ -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 = (
|
||||
|
||||
@@ -3523,7 +3523,9 @@ def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, A
|
||||
# 历史取消/归档只能保留在 history/status_groups,既不推动任一工作面,
|
||||
# 也不得作为「通知完成」的分子或分母。
|
||||
item_group = _batch_user_group(item)
|
||||
if item_group in {'cancelled', 'archived'}:
|
||||
if item_group in {'cancelled', 'archived', 'unclassified'}:
|
||||
continue
|
||||
if item_group not in {'failed', 'waiting_human', 'processing', 'completed'}:
|
||||
continue
|
||||
summary = stage_summaries[lifecycle_stage]
|
||||
summary['total'] += 1
|
||||
@@ -3537,8 +3539,10 @@ def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, A
|
||||
summary['needs_action'] += 1
|
||||
elif item_group == 'waiting_human':
|
||||
summary['needs_action'] += 1
|
||||
else:
|
||||
elif item_group == 'processing':
|
||||
summary['processing'] += 1
|
||||
else:
|
||||
continue
|
||||
if summary['blocking_reason'] is None and isinstance(item.get('blocking_reason'), dict):
|
||||
reason = item['blocking_reason']
|
||||
summary['blocking_reason'] = {
|
||||
@@ -3604,8 +3608,8 @@ def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str,
|
||||
def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""裁决会话批次的用户状态与唯一主动作。
|
||||
|
||||
优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造
|
||||
人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。
|
||||
优先级与文件 ``user_group`` 一致:失败优先,其次待人工,再次系统处理中。
|
||||
有需处理时主状态不得标成 completed。
|
||||
"""
|
||||
# 批次主状态与文件计数、五阶段必须消费同一份“每文件唯一当前代表项”。
|
||||
# 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成
|
||||
@@ -3614,16 +3618,28 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An
|
||||
_current_file_representatives(work_items),
|
||||
key=lambda item: {
|
||||
'failed': 0,
|
||||
'retryable': 0,
|
||||
'waiting_human': 1,
|
||||
'running': 2,
|
||||
'processing': 2,
|
||||
'completed': 3,
|
||||
'cancelled': 4,
|
||||
}.get(str(item.get('user_status') or item.get('status') or '').strip().lower(), 5),
|
||||
'archived': 4,
|
||||
}.get(_batch_user_group(item), 5),
|
||||
)
|
||||
selected = ranked[0] if ranked else {}
|
||||
selected_group = _batch_user_group(selected) if selected else ''
|
||||
status_by_group = {
|
||||
'failed': 'failed',
|
||||
'waiting_human': 'waiting_human',
|
||||
'processing': 'running',
|
||||
'completed': 'completed',
|
||||
'cancelled': 'cancelled',
|
||||
'archived': 'archived',
|
||||
}
|
||||
return {
|
||||
'status': str(selected.get('user_status') or selected.get('status') or 'running'),
|
||||
'status': status_by_group.get(
|
||||
selected_group,
|
||||
str(selected.get('user_status') or selected.get('status') or 'running'),
|
||||
),
|
||||
'stage': str(selected.get('user_stage') or selected.get('stage') or ''),
|
||||
# 5 业务阶段:与右侧批次中心轨道、工作台导航同源(前端只读做 i18n,禁止再映射)。
|
||||
'lifecycle_stage': _lifecycle_stage_from_item(selected),
|
||||
|
||||
Reference in new issue
Block a user