Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-14 17:08:06 +08:00
commit 8fac0362bc
50 files changed
+2038 -365

No files matched your search

+11 -3
View File
@@ -2,8 +2,8 @@
api/chat/sessions.py
用途:处理聊天会话、历史消息与本地结构化消息路由。
依赖:chat.shared、chat.core、ChatSession、ChatLog。
逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。
依赖:chat.shared、chat.core、ChatSession、ChatLog、_normalize_user_attachments。
逻辑:校验当前用户和 Agent 后读写会话及日志;用户附件快照写库前规范化,超限显式失败不落半截。
"""
from __future__ import annotations
@@ -246,7 +246,8 @@ def save_local_message():
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题;
user 角色 payload 含 user_attachments 时写库前调用 _normalize_user_attachments,超限抛 ValidationError。
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
@@ -286,6 +287,13 @@ def save_local_message():
if user_query and _looks_like_review_auto_title(session.title or ''):
session.title = _session_title_from_text(user_query)
# [STEP] 用户附件快照写前规范化;超限由 _normalize_user_attachments 显式失败,禁止落半截
if role == 'user' and isinstance(payload, dict) and 'user_attachments' in payload:
payload = {
**payload,
'user_attachments': _normalize_user_attachments(payload.get('user_attachments')),
}
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
# 这样能保证前端表单状态(例如已确认)被持久化
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
+17 -4
View File
@@ -43,7 +43,7 @@ from app.core.errors import (
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。
CHAT_USER_ATTACHMENT_LIMIT = 20
CHAT_USER_ATTACHMENT_LIMIT = 200
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
@@ -53,18 +53,31 @@ def _normalize_user_attachments(value) -> list[dict]:
"""
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举;
列表长度超过 CHAT_USER_ATTACHMENT_LIMIT 时显式失败,禁止静默截断。
Args:
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
value: 前端 user_attachments 原始值;必须为列表。
Returns:
可安全写入 JSON 的附件快照列表;非法项目被忽略。
Raises:
ValidationError: 列表长度超过上限(code=CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED)。
"""
if not isinstance(value, list):
return []
if len(value) > CHAT_USER_ATTACHMENT_LIMIT:
raise ValidationError(
f'User attachments exceed limit ({CHAT_USER_ATTACHMENT_LIMIT})',
code='CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED',
details={
'limit': CHAT_USER_ATTACHMENT_LIMIT,
'count': len(value),
},
)
normalized: list[dict] = []
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
for item in value:
if not isinstance(item, dict):
continue
raw_name = str(item.get('name') or '')
@@ -4,10 +4,13 @@ backend/app/jobs/handlers/shipping_order_extraction.py
用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
ensure_workflow_items_for_run(物化后兜底建 Item)、order_extraction_merge、
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)、
order_extraction_has_extractable_ready_work(收口自交接判断)。
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
收口时用 DB 实况判断:有 extractable ready work 则 layout_ready_continue 自交接;
仅 layouts_pending 且无 ready work 时以 partial_units_done 回到 waiting_layout;
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
两处续抽均 continue_from_running,避免复用即将结束的 running Job;
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
@@ -46,6 +49,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
begin_input_freeze,
complete_input_freeze,
mark_order_extraction_persistence_started,
order_extraction_has_extractable_ready_work,
order_extraction_layout_prerequisite_issues,
order_extraction_layouts_pending,
order_extraction_ready_document_ids,
@@ -1158,8 +1162,36 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
job_id=job.id,
)
raise
# [STEP] 仍有兄弟文件版式未完成:已抽 Unit 保留,Job 成功收口并回到 waiting_layout,禁止 Run 终态。
if layout_blocked_in_wave or order_extraction_layouts_pending(run):
# [STEP] 收口前用 DB 实况判断版面就绪:有可抽 ready work 则自交接续抽,
# 覆盖「Job 中途 layout 变 ready」与「开工快照过期跳过」;勿仅信 layout_blocked_in_wave。
has_ready_work = order_extraction_has_extractable_ready_work(run)
layouts_pending = order_extraction_layouts_pending(run)
if has_ready_work:
continue_job_id = _enqueue_ready_order_extraction_job(
run,
message='附件版面已就绪,继续识别剩余附件',
continue_from_running=True,
)
run.current_job_id = continue_job_id
run.phase = 'waiting_layout' if layouts_pending else 'queued'
db.session.commit()
finish_job(
job.id,
result={
'run_no': run.run_no,
'waiting_layout': bool(layouts_pending),
'waiting_continue': True,
'handoff_status': 'layout_ready_continue',
'merged_unit_count': len(pending_merge_unit_ids),
'ready_document_ids': sorted(ready_document_ids),
'continue_job_id': int(continue_job_id),
},
message='附件版面已就绪,已排队继续识别剩余附件',
owned_attempt=owned_attempt,
)
return
if layouts_pending:
# 仅仍有 layout pending、无可抽 ready work:回到 waiting_layout,靠 layout 完成回调唤醒。
run.phase = 'waiting_layout'
db.session.commit()
finish_job(
@@ -1197,7 +1229,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
commit=False,
)
continue_job_id = _enqueue_ready_order_extraction_job(
run, message='运行时预算已用尽,继续识别剩余附件',
run,
message='运行时预算已用尽,继续识别剩余附件',
continue_from_running=True,
)
run.current_job_id = continue_job_id
run.phase = 'waiting_layout'
@@ -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),
+65 -12
View File
@@ -1,16 +1,19 @@
"""
backend/tests/test_chat_user_attachments.py
用途:验证聊天附件快照的后端白名单清洗与归属安全合并。
依赖:chat API 附件辅助函数、pytest monkeypatch。
逻辑:覆盖敏感字段过滤、数量/大小边界、无 ChatLog ID 不写入和有效终态合并。
用途:验证聊天附件快照的后端白名单清洗、超限显式失败与归属安全合并。
依赖:chat API 附件辅助函数、pytest、ValidationError。
逻辑:覆盖敏感字段过滤、数量上限显式失败、无效项丢弃、无 ChatLog ID 不写入和有效终态合并。
"""
import pytest
from app.api.chat import (
CHAT_USER_ATTACHMENT_LIMIT,
_merge_user_attachments_from_terminal_event,
_normalize_user_attachments,
)
from app.core.errors import ValidationError
def test_normalize_user_attachments_keeps_only_display_whitelist():
@@ -34,7 +37,7 @@ def test_normalize_user_attachments_keeps_only_display_whitelist():
}]
def test_normalize_user_attachments_limits_items_and_drops_invalid_values():
def test_normalize_user_attachments_keeps_all_items_at_limit():
valid = {
'name': 'file.pdf',
'size': 1,
@@ -42,16 +45,66 @@ def test_normalize_user_attachments_limits_items_and_drops_invalid_values():
'type': 'document',
'source': 'local',
}
items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 5)]
items[0] = {**valid, 'type': 'executable'}
items[1] = {**valid, 'source': 'unknown'}
items[2] = {**valid, 'size': -1, 'extension': '../pdf'}
items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(CHAT_USER_ATTACHMENT_LIMIT)]
normalized = _normalize_user_attachments(items)
assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT
assert normalized[0]['name'] == 'file-0.pdf'
assert normalized[-1]['name'] == f'file-{CHAT_USER_ATTACHMENT_LIMIT - 1}.pdf'
assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT - 2
assert 'size' not in normalized[0]
assert 'extension' not in normalized[0]
def test_normalize_user_attachments_keeps_more_than_legacy_twenty():
valid = {
'name': 'file.pdf',
'size': 1,
'extension': 'pdf',
'type': 'document',
'source': 'local',
}
items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(21)]
normalized = _normalize_user_attachments(items)
assert len(normalized) == 21
def test_normalize_user_attachments_raises_when_over_limit():
valid = {
'name': 'file.pdf',
'size': 1,
'extension': 'pdf',
'type': 'document',
'source': 'local',
}
items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 1)]
with pytest.raises(ValidationError) as exc_info:
_normalize_user_attachments(items)
err = exc_info.value
assert err.code == 'CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED'
assert err.details.get('limit') == CHAT_USER_ATTACHMENT_LIMIT
assert err.details.get('count') == CHAT_USER_ATTACHMENT_LIMIT + 1
def test_normalize_user_attachments_drops_invalid_values_without_truncating_valid_tail():
valid = {
'name': 'file.pdf',
'size': 1,
'extension': 'pdf',
'type': 'document',
'source': 'local',
}
items = [
{**valid, 'type': 'executable'},
{**valid, 'source': 'unknown'},
]
# 旧 [:20] 会在处理完前 20 项后丢弃尾部合法项;无 slice 后应保留 tail。
items.extend({**valid, 'type': 'executable'} for _ in range(18))
items.append({**valid, 'name': 'kept-tail.pdf'})
normalized = _normalize_user_attachments(items)
assert normalized == [{
'name': 'kept-tail.pdf',
'type': 'document',
'source': 'local',
'extension': 'pdf',
'size': 1,
}]
def test_merge_user_attachments_requires_terminal_chat_log_id(monkeypatch):
+99
View File
@@ -412,3 +412,102 @@ def test_user_mode_review_status_must_human():
review_status=rs,
lifecycle_stage=None,
) == 'must_human'
def test_sql_todo_category_review_gate_blocked_is_review(app):
"""订单复核 Gate 阻断必须进 review,不得落入 in_progress。"""
with app.app_context():
from app import db
from app.models import ShippingOrderTask, ShippingProcessExecution
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-REVIEW-BLOCK')
ot = ShippingOrderTask(
task_no='OT-SQL-REVIEW-BLOCK',
user_id=user.id,
conversation_id=session.session_id,
status='waiting_review',
stage='order_review',
progress_version=1,
)
db.session.add(ot)
db.session.flush()
db.session.add(
ShippingProcessExecution(
execution_no='SPE-SQL-REVIEW-BLOCK',
task_id=int(ot.id),
status='blocked',
current_gate_code='order_field_extraction',
)
)
db.session.commit()
cat = (
db.session.query(_order_task_todo_category_sql_expr())
.filter(ShippingOrderTask.id == ot.id)
.scalar()
)
assert cat == 'review'
def test_sql_todo_category_running_inventory_prep_is_in_progress(app):
"""库存准备 Execution=active 才是系统处理中。"""
with app.app_context():
from app import db
from app.models import ShippingOrderTask, ShippingProcessExecution
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-RUNNING')
ot = ShippingOrderTask(
task_no='OT-SQL-RUNNING-PREP',
user_id=user.id,
conversation_id=session.session_id,
status='processing',
stage='notification_preparation',
progress_version=1,
)
db.session.add(ot)
db.session.flush()
db.session.add(
ShippingProcessExecution(
execution_no='SPE-SQL-RUNNING-PREP',
task_id=int(ot.id),
status='active',
current_gate_code='inventory_preparation',
)
)
db.session.commit()
cat = (
db.session.query(_order_task_todo_category_sql_expr())
.filter(ShippingOrderTask.id == ot.id)
.scalar()
)
assert cat == 'in_progress'
def test_sql_todo_category_without_gate_is_not_in_progress(app):
"""无 Gate 的 OT 不得进入处理中桶。"""
with app.app_context():
from app import db
from app.models import ShippingOrderTask
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-NO-GATE')
ot = ShippingOrderTask(
task_no='OT-SQL-NO-GATE',
user_id=user.id,
conversation_id=session.session_id,
status='waiting_review',
stage='order_review',
progress_version=1,
)
db.session.add(ot)
db.session.commit()
cat = (
db.session.query(_order_task_todo_category_sql_expr())
.filter(ShippingOrderTask.id == ot.id)
.scalar()
)
assert cat == 'exception'
@@ -337,7 +337,7 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
db.session.commit()
data = serialize_task_summary(task, viewer_user_id=11)
assert data["todo_category"] == "in_progress"
assert data["todo_category"] == "exception"
assert data["created_by"] == 11
assert data["can_handle"] is True
# 无 Gate 且无 review_status:薄回退不投影 order_freeze
@@ -1161,12 +1161,74 @@ def test_todo_category_sql_matches_formal_notice_facts(app):
assert sql_category == expected
pending = list_my_todos(owner, bucket="pending", page=1, page_size=50)
assert pending["total"] == 1
assert pending["total"] == 2
counts = count_my_todos(owner)
assert counts["pending"] == 1
assert counts["pending"] == 2
assert counts["done"] == 1
assert counts["processing"] == 0
assert counts["total_pending_badge"] == 2
def test_count_my_todos_running_gate_is_processing_and_not_double_counted(app):
"""有 Notice 的 OT 只计 Notice 分支;active 库存准备进处理中。"""
with app.app_context():
from app import db
from app.models import ShippingProcessExecution
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
owner = 91
order_task = ShippingOrderTask(
task_no="OT-RUN-ONCE", source_type="direct_pdf", user_id=owner,
status="processing", stage="notification_preparation",
)
notice = ShippingNotice(task_no="SN-RUN-ONCE", source_type="manual", user_id=owner)
db.session.add_all([order_task, notice])
db.session.flush()
notice.order_task_id = order_task.id
db.session.add(ShippingProcessExecution(
execution_no="SPE-RUN-ONCE",
task_id=int(order_task.id),
status="active",
current_gate_code="inventory_preparation",
))
db.session.commit()
counts = count_my_todos(owner)
assert counts["processing"] == 1
assert counts["total_pending_badge"] == 1
processing = list_my_todos(owner, bucket="processing", page=1, page_size=50)
assert processing["total"] == 1
assert processing["items"][0]["task_no"] in {"SN-RUN-ONCE", "OT-RUN-ONCE"}
def test_list_my_todos_order_review_gate_stays_in_pending(app):
"""订单复核 blocked Gate 进入待处理,不进处理中。"""
with app.app_context():
from app import db
from app.models import ShippingProcessExecution
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
owner = 92
order_task = ShippingOrderTask(
task_no="OT-REVIEW-PENDING", source_type="direct_pdf", user_id=owner,
status="waiting_review", stage="order_review",
)
db.session.add(order_task)
db.session.flush()
db.session.add(ShippingProcessExecution(
execution_no="SPE-REVIEW-PENDING",
task_id=int(order_task.id),
status="blocked",
current_gate_code="order_field_extraction",
))
db.session.commit()
counts = count_my_todos(owner)
assert counts["processing"] == 0
pending = list_my_todos(owner, bucket="pending", page=1, page_size=50)
assert pending["total"] == 1
assert pending["items"][0]["todo_category"] == "review"
processing = list_my_todos(owner, bucket="processing", page=1, page_size=50)
assert processing["total"] == 0
def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
@@ -1,4 +1,9 @@
"""订单抽取 Worker 的单元级自动重试与技术失败收口测试。"""
"""
订单抽取 Worker 单元测试。
覆盖:物化顺序、partial waiting_layout、layout_ready_continue 自交接、
runtime_budget_continue、layout 调度失败收口、以及 continue_from_running 去重。
"""
from types import SimpleNamespace
@@ -190,6 +195,7 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
)
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {101})
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True)
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
@@ -300,6 +306,7 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {201, 202})
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
@@ -339,7 +346,9 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
monkeypatch.setattr(
handler, '_enqueue_ready_order_extraction_job',
lambda _run, *, message: events.append(f'enqueue:{message}') or 999,
lambda _run, *, message, continue_from_running=False: (
events.append(f'enqueue:{message}:continue={continue_from_running}') or 999
),
)
def fake_finish(*_args, **kwargs):
@@ -356,7 +365,7 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
assert 'processed:51' in events
assert 'processed:52' not in events
assert any(item.startswith('enqueue:') for item in events)
assert any(item.startswith('enqueue:') and item.endswith(':continue=True') for item in events)
assert 'terminalized' not in events
assert 'persist_started' not in events
assert run.status == 'processing'
@@ -368,6 +377,267 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
assert pending_unit.status == 'pending'
def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(monkeypatch):
"""
开工快照仍 layout_pending,收口时 DB 已有 extractable ready work:须 layout_ready_continue 自交接。
断言:入队续抽且 continue_from_running=True;Run 不终态;handoff_status=layout_ready_continue。
"""
import app.jobs.handlers.shipping_order_extraction as handler
events: list[str] = []
finished: dict = {}
enqueue_calls: list[dict] = []
run = SimpleNamespace(
id=6, user_id=9, run_no='SNER-WORKER-LAYOUT-CONTINUE', status='queued', phase='queued',
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
execution_result_json=None, extraction_completed_at=None,
)
job = SimpleNamespace(id=6, attempts=1, business_ref=run.run_no, max_attempts=3)
ready_unit = SimpleNamespace(
id=61, document_id=301, intake_id=1, status='pending', result_json=None, position=1,
cancellation_requested_at=None,
)
stale_pending_unit = SimpleNamespace(
id=62, document_id=302, intake_id=1, status='pending', result_json=None, position=2,
cancellation_requested_at=None,
)
plan = SimpleNamespace(id=6, unit_count=2, units=[ready_unit, stale_pending_unit])
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else ready_unit)
monkeypatch.setattr(
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
)
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
position=SimpleNamespace(asc=lambda: None),
status=SimpleNamespace(in_=lambda *_a, **_k: True),
query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(all=lambda: [ready_unit, stale_pending_unit]),
),
),
))
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
monkeypatch.setattr(
handler, 'materialize_order_extraction_run_inputs',
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
)
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
# 开工快照:302 仍 pending;收口时 mock 为已有 ready work、layout 已全部就绪。
monkeypatch.setattr(
handler, 'order_extraction_layout_prerequisite_issues',
lambda _run: {302: 'layout_pending'},
)
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {301})
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: True)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
)
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [ready_unit, stale_pending_unit])
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status),
)
def _process(**_kwargs):
events.append('processed')
ready_unit.status = 'merging_supplement'
return [{'po_number': 'PO-LAYOUT-CONTINUE', '_hxops_intake_id': 1}]
monkeypatch.setattr(handler, '_process_unit_with_retries', _process)
monkeypatch.setattr(
handler, 'merge_unit_orders',
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
)
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
def _fake_enqueue(_run, *, message, continue_from_running=False):
enqueue_calls.append({'message': message, 'continue_from_running': continue_from_running})
events.append(f'enqueue:continue={continue_from_running}')
return 1006
monkeypatch.setattr(handler, '_enqueue_ready_order_extraction_job', _fake_enqueue)
def fake_finish(*_args, **kwargs):
events.append('finished')
finished.update(kwargs)
monkeypatch.setattr(handler, 'finish_job', fake_finish)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 6})
assert 'processed' in events
assert 'progressed' in events
assert 'terminalized' not in events
assert 'persist_started' not in events
assert enqueue_calls == [{
'message': '附件版面已就绪,继续识别剩余附件',
'continue_from_running': True,
}]
assert run.status == 'processing'
assert run.phase == 'queued'
assert run.current_job_id == 1006
assert finished['result']['handoff_status'] == 'layout_ready_continue'
assert finished['result']['waiting_continue'] is True
assert finished['result']['waiting_layout'] is False
assert finished['result']['continue_job_id'] == 1006
assert stale_pending_unit.status == 'pending'
def test_worker_layout_ready_continue_keeps_waiting_layout_when_siblings_still_pending(monkeypatch):
"""
收口时已有 ready work,但仍有兄弟 layout pending:自交接且 phase 保持 waiting_layout。
断言:handoff_status=layout_ready_continue;waiting_layout=True;不终态 Run。
"""
import app.jobs.handlers.shipping_order_extraction as handler
finished: dict = {}
run = SimpleNamespace(
id=7, user_id=9, run_no='SNER-WORKER-LAYOUT-CONTINUE-PARTIAL', status='queued', phase='queued',
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
execution_result_json=None, extraction_completed_at=None,
)
job = SimpleNamespace(id=7, attempts=1, business_ref=run.run_no, max_attempts=3)
ready_unit = SimpleNamespace(
id=71, document_id=401, intake_id=1, status='pending', result_json=None, position=1,
cancellation_requested_at=None,
)
stale_pending_unit = SimpleNamespace(
id=72, document_id=402, intake_id=1, status='pending', result_json=None, position=2,
cancellation_requested_at=None,
)
plan = SimpleNamespace(id=7, unit_count=2, units=[ready_unit, stale_pending_unit])
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else ready_unit)
monkeypatch.setattr(
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
)
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
position=SimpleNamespace(asc=lambda: None),
status=SimpleNamespace(in_=lambda *_a, **_k: True),
query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(all=lambda: [ready_unit, stale_pending_unit]),
),
),
))
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
monkeypatch.setattr(
handler, 'materialize_order_extraction_run_inputs',
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
)
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
monkeypatch.setattr(
handler, 'order_extraction_layout_prerequisite_issues',
lambda _run: {402: 'layout_pending'},
)
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {401})
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True)
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: True)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
)
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [ready_unit, stale_pending_unit])
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status),
)
monkeypatch.setattr(
handler, '_process_unit_with_retries',
lambda **_kwargs: (setattr(ready_unit, 'status', 'merging_supplement') or [
{'po_number': 'PO-PARTIAL-CONTINUE', '_hxops_intake_id': 1},
]),
)
monkeypatch.setattr(
handler, 'merge_unit_orders',
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
)
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: {})
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: (_ for _ in ()).throw(
AssertionError('must not terminalize'),
))
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: None)
monkeypatch.setattr(
handler, '_enqueue_ready_order_extraction_job',
lambda _run, *, message, continue_from_running=False: 1007,
)
monkeypatch.setattr(handler, 'finish_job', lambda *_a, **kwargs: finished.update(kwargs))
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 7})
assert run.status == 'processing'
assert run.phase == 'waiting_layout'
assert run.current_job_id == 1007
assert finished['result']['handoff_status'] == 'layout_ready_continue'
assert finished['result']['waiting_layout'] is True
assert finished['result']['waiting_continue'] is True
def test_enqueue_ready_order_extraction_job_continue_from_running_dedupes_queued_only(monkeypatch):
"""
continue_from_running=True 时 enqueue 必须只对 queued 去重,避免复用当前 running Job。
断言:传入 dedupe_statuses=('queued',)。
"""
from app.services.shipping_notice import order_extraction_run_service as svc
captured: dict = {}
def _fake_enqueue(*_args, **kwargs):
captured.update(kwargs)
return 42
monkeypatch.setattr('app.jobs.queue.enqueue', _fake_enqueue)
monkeypatch.setattr(svc.db.session, 'get', lambda *_a, **_k: None)
run = SimpleNamespace(run_no='SNER-DEDUP', user_id=9)
job_id = svc._enqueue_ready_order_extraction_job(
run, message='续抽', continue_from_running=True,
)
assert job_id == 42
assert captured.get('dedupe_statuses') == ('queued',)
assert captured.get('business_ref') == 'SNER-DEDUP'
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
"""版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。"""
import app.jobs.handlers.shipping_order_extraction as handler
@@ -94,10 +94,10 @@ def test_override_pins_line_and_rematches_only_that_line(monkeypatch, app):
assert pinned['audit']['action'] == 'override_line_inventory_source'
assert pinned['audit']['after']['selected_source_code'] == 'SRC_X'
assert retrigger_calls and retrigger_calls[0] == task.task_no
# [回归] 库存源覆写后必须把 inventory_preparation 作为定向人工恢复重新推进(retry_rpa),
# 否则 AutoProgress 读残留的 poll_inventory_preparation 只轮询、不触发 RPA。
# [回归] 改源后必须定向回 inventory_preparation;mode=auto 按指定源复用快照(无文件才 RPA)。
assert retrigger_kwargs and retrigger_kwargs[0].get('resume_gate_code') == 'inventory_preparation'
assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'retry_rpa'
assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'auto'
assert retrigger_kwargs and retrigger_kwargs[0].get('trigger') == 'manual_override_source'
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human'}
@@ -266,6 +266,60 @@ def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeyp
assert queued[0]['gate_code'] == 'inventory_preparation'
def test_auto_progress_seeds_pending_inventory_preparation_after_routing_pass(
gate_execution, monkeypatch,
):
"""人工指定源使 routing passed 后,必须补种并入队 pending 的库存准备。
[回归] pending 门禁 next_action_code 为空时旧逻辑静默 return,工作台永久显示
「库存文件未准备」;手动选源即定论,应按冻结源执行准备,不得再停在路由。
"""
from app.services.shipping_notice import process_gate_service
for prior_gate in ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
).all():
prior_gate.status = 'passed'
prior_gate.next_action_code = None
prep = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
prep.status = 'pending'
prep.next_action_code = None
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
assert gate_execution.current_gate_code == 'inventory_preparation'
assert prep.next_action_code is None
queued: list[dict[str, object]] = []
monkeypatch.setattr(
process_gate_service,
'queue_gate_attempt',
lambda **kwargs: (queued.append(kwargs), SimpleNamespace(id=91))[1],
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
lambda **_kwargs: None,
)
routing = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_source_routing',
).one()
process_gate_service._enqueue_auto_progress_after_gate_pass(
execution=gate_execution,
gate=routing,
)
assert prep.next_action_code == 'retry_inventory_preparation'
assert gate_execution.primary_next_action_code == 'retry_inventory_preparation'
assert len(queued) == 1
assert queued[0]['gate_code'] == 'inventory_preparation'
assert queued[0]['input_snapshot']['action_code'] == 'retry_inventory_preparation'
assert queued[0]['input_snapshot']['payload']['trigger'] == 'gate_attempt_passed'
def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch):
"""已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。"""
from app.services.shipping_notice import process_gate_service
@@ -334,6 +388,77 @@ def test_auto_progress_does_not_queue_manual_inventory_navigation(gate_execution
assert queued == []
def test_refresh_pointers_skips_stale_invalidated_when_downstream_blocked(gate_execution):
"""已建单成功后又被标 invalidated 的上游,不得盖住下游真实 blocked_manual。
复现:task_creation 已 passed_at + invalidated,inventory_sufficiency=blocked_manual;
刷新指针必须停在库存充足性,而不是「生成订单草稿」。
"""
from datetime import datetime, timezone
from app.services.shipping_notice import process_gate_service
now = datetime.now(timezone.utc).replace(tzinfo=None)
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
if gate.gate_code == 'task_creation':
gate.status = 'invalidated'
gate.passed_at = now
gate.invalidated_at = now
gate.blocking_reason_code = 'gate_invalidated'
gate.next_action_code = 'retry_task_creation'
elif gate.gate_code in {
'document_materialization', 'layout_parsing', 'document_profile_routing',
'order_field_extraction', 'field_completeness', 'reservation_validation',
'customer_resolution', 'duplicate_detection', 'field_conflict_resolution',
'order_freeze_readiness', 'inventory_source_routing', 'inventory_preparation',
'inventory_field_mapping', 'inventory_matching',
}:
gate.status = 'passed'
gate.passed_at = now
elif gate.gate_code == 'inventory_sufficiency':
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'inventory_shortage_review_required'
gate.next_action_code = 'open_shortage_review'
elif gate.gate_code == 'excel_readiness':
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'excel_not_ready'
# 其余保持 pending
db.session.flush()
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
assert gate_execution.current_gate_code == 'inventory_sufficiency'
assert gate_execution.primary_next_action_code == 'open_shortage_review'
assert gate_execution.status == 'blocked'
def test_refresh_pointers_keeps_invalidated_when_downstream_still_passed(gate_execution):
"""故意失效且下游仍为 passed 时,current 必须停在 invalidated,等待重评。"""
from datetime import datetime, timezone
from app.services.shipping_notice import process_gate_service
now = datetime.now(timezone.utc).replace(tzinfo=None)
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
if gate.gate_code == 'task_creation':
gate.status = 'invalidated'
gate.passed_at = now
gate.invalidated_at = now
gate.blocking_reason_code = 'gate_invalidated'
gate.next_action_code = 'retry_task_creation'
else:
gate.status = 'passed'
gate.passed_at = now
db.session.flush()
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
assert gate_execution.current_gate_code == 'task_creation'
assert gate_execution.status == 'blocked'
@@ -765,6 +765,67 @@ def test_batch_stage_summary_uses_the_same_user_group_as_file_counts() -> None:
assert fulfillment['summary']['processing'] == 0
def test_batch_waiting_human_has_zero_processing_on_card_and_stage() -> None:
"""顶卡 processing_files 与阶段 processing 必须同时为 0。"""
work_items = [{
'work_item_type': 'order_task',
'work_item_no': 'OT-WAIT-CARD',
'user_group': 'waiting_human',
'user_status': 'waiting_human',
'user_stage': 'waiting_review',
'source_summary': {'document_id': 601, 'filename': 'review.pdf'},
}]
counts = _batch_file_counts(work_items)
assert counts['processing_files'] == 0
assert counts['waiting_human_files'] == 1
order_review = next(
node for node in _batch_lifecycle_nodes(work_items)
if node['code'] == 'order_review'
)
assert order_review['summary']['processing'] == 0
assert order_review['summary']['needs_action'] == 1
assert _batch_ui_state_from_items(work_items)['status'] == 'waiting_human'
def test_batch_ui_state_does_not_show_completed_when_human_wait_exists() -> None:
"""需处理文件存在时批次主状态不得为 completed。"""
work_items = [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-DONE-FILE',
'user_group': 'completed', 'user_status': 'completed',
'user_stage': 'upload_complete',
'source_summary': {'document_id': 602, 'filename': 'done.pdf'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-WAIT-FILE',
'user_group': 'waiting_human', 'user_status': 'running',
'user_stage': 'waiting_review',
'source_summary': {'document_id': 603, 'filename': 'wait.pdf'},
},
]
assert _batch_ui_state_from_items(work_items)['status'] == 'waiting_human'
assert _batch_file_counts(work_items)['processing_files'] == 0
def test_unclassified_file_does_not_inflate_stage_processing() -> None:
"""未分类文件不得把五阶段写成「N 份处理中」。"""
work_items = [{
'work_item_type': 'order_task',
'work_item_no': 'OT-UNCLASSIFIED',
'user_group': 'unclassified',
'user_status': 'unknown',
'user_stage': 'freight_uploading',
'source_summary': {'document_id': 604, 'filename': 'odd.pdf'},
}]
assert _batch_file_counts(work_items)['processing_files'] == 0
freight = next(
node for node in _batch_lifecycle_nodes(work_items)
if node['code'] == 'freight_upload'
)
assert freight['summary']['processing'] == 0
assert freight['summary']['total'] == 0
def test_conversation_status_groups_use_the_same_current_file_representative() -> None:
"""文件清单不能保留旧失败项,否则会与互斥统计和当前 CTA 相互矛盾。"""
projection = _conversation_processing_from_work_items([
@@ -36,6 +36,23 @@ def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage():
)
def test_legacy_step_key_stage_maps_to_fulfillment_prep():
"""OT.stage 若残留 step5_match_inventory,生命周期必须进通知准备而非接收解析。"""
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
result = project_lifecycle(
current_gate={'gate_code': 'task_creation', 'status': 'invalidated'},
blocking_reason={'code': 'gate_invalidated'},
has_candidate_context=True,
processing_stage='step5_match_inventory',
)
# processing_stage 权威高于错误的 task_creation 门禁。
assert result['lifecycle_stage'] == 'fulfillment_prep'
assert result['lifecycle_authority'] == 'processing_stage'
current = next(e for e in result['lifecycle_entries'] if e['state'] == 'current')
assert current['code'] == 'fulfillment_prep'
def test_fifteen_stages_inventory_source_before_review():
"""库存源解析必须排在人工复核与建单之前(跨面共用同一有序元组)。"""
stages = list(SHIPPING_PROCESSING_STAGES)