refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段
统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成 设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程 删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本 替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段 更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
This commit is contained in:
1 parent
6684e7181a
commit
5ef8329bd8
178 files changed
+5091
-1734
No files matched your search
@@ -141,7 +141,7 @@ def openapi_spec():
|
||||
|
||||
@shipping_notice_bp.route('/tools/checkpoint-catalog', methods=['GET'])
|
||||
def checkpoint_catalog():
|
||||
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
|
||||
"""返回检查点目录,供开发联调和文档核对 human_options;业务按钮以 ui_state.actions 为准。"""
|
||||
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
|
||||
return jsonify(build_checkpoint_catalog())
|
||||
|
||||
|
||||
@@ -124,7 +124,6 @@ def workspace_shipping_tasks():
|
||||
"""分页列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
@@ -136,7 +135,6 @@ def workspace_shipping_tasks():
|
||||
return _ok(list_tasks_page_for_user(
|
||||
user.id,
|
||||
batch_no=batch_no,
|
||||
process_status=process_status,
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
@@ -647,8 +645,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
# 旧 action_buttons 业务调用清零:仅保留 human_options 文案提示,不再下发可点击恢复按钮。
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': []})
|
||||
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
@@ -697,7 +694,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
返回指定任务的详情快照与内嵌 UI State。
|
||||
|
||||
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
|
||||
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
|
||||
checkpoint / actions / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
@@ -2841,6 +2838,15 @@ def workspace_preview_shipping_order_review_document(case_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-evidence-preview/<int:document_id>', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_email_evidence(case_no: str, document_id: int):
|
||||
"""返回当前复核 Case 同 Intake 邮件正文的受控文本预览,不返回原始 EML 或附件。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_email_evidence_text
|
||||
|
||||
return _ok(get_case_email_evidence_text(user_id=user.id, case_no=case_no, document_id=document_id))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
|
||||
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
|
||||
"""确认当前用户已加载终态订单识别卡片;写入已读状态变更审计。"""
|
||||
|
||||
@@ -242,16 +242,21 @@ def _pending_snapshot_batches(run: ShippingOrderProcessingRun, plan: ShippingOrd
|
||||
|
||||
|
||||
def _should_expand_after_wave(*, wave_units: list[ShippingOrderProcessingUnit], wave_orders: list[dict]) -> bool:
|
||||
"""仅在可通过更多附件补证的业务缺口出现时才扩下一轮。"""
|
||||
"""兼容旧诊断调用:返回本轮业务缺口,不能作为兄弟附件执行门控。"""
|
||||
return bool(_expansion_trigger_reason_codes(wave_units=wave_units, wave_orders=wave_orders))
|
||||
|
||||
|
||||
def _should_activate_planned_batches(*, pending_batches: list[int]) -> bool:
|
||||
"""计划内后续附件必须独立执行,不受首轮字段结果或兄弟附件状态门控。"""
|
||||
return bool(pending_batches)
|
||||
|
||||
|
||||
def _expansion_trigger_reason_codes(
|
||||
*,
|
||||
wave_units: list[ShippingOrderProcessingUnit],
|
||||
wave_orders: list[dict],
|
||||
) -> list[str]:
|
||||
"""汇总当前批次触发扩批的业务原因码,供事件与工作台共享。"""
|
||||
"""汇总当前批次业务缺口原因,供事件、交叉裁决与工作台共享。"""
|
||||
if not wave_units:
|
||||
return []
|
||||
reason_codes = {
|
||||
@@ -318,7 +323,7 @@ def _mark_expandable_business_gaps(
|
||||
*,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""把可由后续附件补证的业务缺口标记到订单上,供扩批决策复用。"""
|
||||
"""标记跨附件裁决可补证的业务缺口;该事实不影响附件执行。"""
|
||||
field_ids_by_code = _schema_field_ids_by_code(run)
|
||||
reservation_field_ids = field_ids_by_code.get('reservation_id', set())
|
||||
if not reservation_field_ids:
|
||||
@@ -340,7 +345,7 @@ def _wave_orders_for_expansion(
|
||||
*,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""为当前批次生成扩批判定所需的业务事实视图。"""
|
||||
"""为当前批次生成交叉附件裁决所需的业务事实视图。"""
|
||||
if not orders:
|
||||
return []
|
||||
schema_snapshot = run.input_snapshot_json.get('schema') if isinstance(run.input_snapshot_json, dict) else {}
|
||||
@@ -804,7 +809,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
expansion_reason_codes = _expansion_trigger_reason_codes(wave_units=units, wave_orders=wave_orders)
|
||||
|
||||
next_existing_batch = _next_existing_batch(plan, after_batch=current_batch)
|
||||
if expansion_reason_codes and next_existing_batch is not None:
|
||||
if next_existing_batch is not None:
|
||||
source_batch = current_batch
|
||||
current_batch = next_existing_batch
|
||||
if current_batch not in expansion_events_emitted:
|
||||
@@ -817,6 +822,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
'unit_count': len(_units_for_batch(plan, selection_batch=current_batch)),
|
||||
'triggered_by_batch': source_batch,
|
||||
'reason_codes': expansion_reason_codes,
|
||||
'activation_reason': 'planned_attachment_batch',
|
||||
},
|
||||
job_id=job.id,
|
||||
commit=False,
|
||||
@@ -826,7 +832,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
continue
|
||||
|
||||
pending_batches = _pending_snapshot_batches(run, plan)
|
||||
if expansion_reason_codes and pending_batches:
|
||||
if _should_activate_planned_batches(pending_batches=pending_batches):
|
||||
next_batch = pending_batches[0]
|
||||
created_units = _activate_expansion_batch(run=run, plan=plan, selection_batch=next_batch)
|
||||
db.session.flush()
|
||||
@@ -841,6 +847,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
'unit_count': len(_units_for_batch(plan, selection_batch=next_batch)),
|
||||
'triggered_by_batch': current_batch,
|
||||
'reason_codes': expansion_reason_codes,
|
||||
'activation_reason': 'planned_attachment_batch',
|
||||
},
|
||||
job_id=job.id,
|
||||
commit=False,
|
||||
|
||||
@@ -51,7 +51,6 @@ class ShippingNotice(Base):
|
||||
|
||||
__tablename__ = 'shipping_notices'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_notices_user_status', 'user_id', 'process_status'),
|
||||
Index('ix_shipping_notices_conversation', 'conversation_id'),
|
||||
Index('ix_shipping_notices_current_step', 'current_step'),
|
||||
Index('ix_shipping_notices_upload_status', 'upload_status'),
|
||||
@@ -191,7 +190,6 @@ class ShippingNotice(Base):
|
||||
index=True,
|
||||
)
|
||||
|
||||
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
|
||||
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
@@ -217,7 +215,7 @@ class ShippingNotice(Base):
|
||||
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
# 任务处置与流程状态正交:process_status 继续驱动履约工作流,生命周期负责作废/归档。
|
||||
# 任务处置与业务阶段正交:生命周期负责作废/归档。
|
||||
lifecycle_status: Mapped[str] = mapped_column(
|
||||
String(16),
|
||||
nullable=False,
|
||||
|
||||
@@ -32,7 +32,7 @@ AUTO_PROGRESS_GATE_CODES: tuple[str, ...] = (
|
||||
'upload_receipt_recorded',
|
||||
)
|
||||
_ACTIVE_JOB_STATUSES = ('queued', 'running')
|
||||
_CANCELLED_TASK_STATUSES = frozenset({'cancelled', 'canceled', 'closed', 'rejected'})
|
||||
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'})
|
||||
|
||||
|
||||
def audit_legacy_forwarded_entrypoint(
|
||||
@@ -59,8 +59,8 @@ def _utc_now() -> datetime:
|
||||
|
||||
|
||||
def _task_is_cancelled(task: ShippingNotice) -> bool:
|
||||
"""根据服务端 Task 事实判断取消/关闭任务,旧 Job 不得将其复活。"""
|
||||
return str(getattr(task, 'process_status', '') or '').strip().lower() in _CANCELLED_TASK_STATUSES
|
||||
"""根据生命周期事实判断任务是否不可再推进,旧 Job 不得将其复活。"""
|
||||
return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES
|
||||
|
||||
|
||||
def _recover_stale_active_job(job: Job) -> bool:
|
||||
|
||||
@@ -27,7 +27,6 @@ logger = logging.getLogger(__name__)
|
||||
_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128
|
||||
_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
|
||||
|
||||
_TERMINAL_TASK_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def normalize_create_idempotency_key(raw: str | None) -> str | None:
|
||||
@@ -203,7 +202,7 @@ def assert_no_exact_duplicate_notices(
|
||||
query = ShippingNotice.query.filter(
|
||||
ShippingNotice.user_id == user_id,
|
||||
ShippingNotice.source_content_hash == content_hash,
|
||||
ShippingNotice.process_status.notin_(list(_TERMINAL_TASK_STATUSES)),
|
||||
ShippingNotice.lifecycle_status == 'active',
|
||||
)
|
||||
if skipped_ids:
|
||||
query = query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
|
||||
|
||||
@@ -30,7 +30,6 @@ from app.services.shipping_notice.tools import auto_progress, submit_decision
|
||||
|
||||
_RUNNING_BATCHES: set[str] = set()
|
||||
_RUNNING_TASKS: set[str] = set()
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def batch_orchestrator_enabled() -> bool:
|
||||
@@ -69,21 +68,19 @@ def _should_orchestrate_task(task: Any) -> bool:
|
||||
|
||||
if not task_is_active(task):
|
||||
return False
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
):
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
|
||||
if getattr(task, "upload_status", None) in {"pending", "uploading", "failed"}:
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -94,13 +91,12 @@ def _is_retryable_task(task: Any) -> bool:
|
||||
|
||||
if not task_is_active(task):
|
||||
return False
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if process_status == "waiting_inventory" and pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
|
||||
if pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
@@ -139,7 +135,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
return {
|
||||
"status": "skipped",
|
||||
"message": (
|
||||
f"skip process_status={task.process_status or ''}"
|
||||
f"skip stage={getattr(task, 'current_step', '') or ''}"
|
||||
f" pending_human_reason={task.pending_human_reason or ''}"
|
||||
f" review_status={task.review_status or ''}"
|
||||
),
|
||||
@@ -151,16 +147,14 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
log_task_event(
|
||||
task,
|
||||
"backend_orchestrator_task_started",
|
||||
{"process_status": task.process_status, "current_step": task.current_step},
|
||||
{"current_step": task.current_step, "lifecycle_status": task.lifecycle_status},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
|
||||
process_status = str(task.process_status or "").strip().lower()
|
||||
pending_reason = str(task.pending_human_reason or "").strip().lower()
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason == PH_RPA_PENDING
|
||||
):
|
||||
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
|
||||
@@ -176,8 +170,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
elif (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason == ""
|
||||
):
|
||||
payload["mode"] = "auto"
|
||||
@@ -189,7 +182,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
result.get("status"),
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
elif process_status == "created":
|
||||
elif not getattr(task, "current_order_extraction_id", None):
|
||||
# [STEP] 复核/STP 确认建单后任务仍为 created,但已挂正式 Extraction;须走 auto_progress。
|
||||
# 无抽取的历史壳任务仍停在人工,避免误入 Chatflow。
|
||||
if getattr(task, "current_order_extraction_id", None):
|
||||
@@ -206,10 +199,9 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
result = auto_progress(payload)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] auto-progress task_no=%s status=%s process_status_before=%s current_step_before=%s message=%s",
|
||||
"[shipping-orchestrator] auto-progress task_no=%s status=%s current_step_before=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
task.process_status,
|
||||
task.current_step,
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
@@ -221,7 +213,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
"backend_orchestrator_task_finished",
|
||||
{
|
||||
"result_status": str(result.get("status") or ""),
|
||||
"process_status": refreshed.process_status,
|
||||
"lifecycle_status": refreshed.lifecycle_status,
|
||||
"current_step": refreshed.current_step,
|
||||
},
|
||||
)
|
||||
@@ -353,9 +345,8 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
if not _is_retryable_task(task):
|
||||
skipped += 1
|
||||
continue
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
|
||||
if pending_reason == PH_RPA_PENDING and not getattr(task, "inventory_lines_json", None):
|
||||
# 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
@@ -366,7 +357,7 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_EXHAUSTED:
|
||||
if pending_reason == PH_RPA_EXHAUSTED:
|
||||
result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"})
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
|
||||
@@ -76,17 +76,22 @@ def _format_decision_message(decision: str, result: dict[str, Any], task_no: str
|
||||
|
||||
|
||||
def _match_result_payload(task_no: str, result: dict[str, Any]) -> dict[str, Any]:
|
||||
"""构建匹配结果展示 payload;按钮统一来自后端 ui_state.actions。"""
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
line_results = data.get("line_results") if isinstance(data.get("line_results"), list) else []
|
||||
shortage = data.get("shortage") if isinstance(data.get("shortage"), dict) else {}
|
||||
shortage_lines = shortage.get("lines") if isinstance(shortage.get("lines"), list) else []
|
||||
action_buttons = result.get("action_buttons") if isinstance(result.get("action_buttons"), list) else []
|
||||
ui_state = result.get("ui_state") if isinstance(result.get("ui_state"), dict) else {}
|
||||
actions = ui_state.get("actions") if isinstance(ui_state.get("actions"), dict) else {
|
||||
"primary": None,
|
||||
"secondary": [],
|
||||
}
|
||||
return {
|
||||
"taskId": task_no,
|
||||
"match_status": data.get("match_status"),
|
||||
"line_results": line_results,
|
||||
"shortage_lines": shortage_lines,
|
||||
"action_buttons": action_buttons,
|
||||
"actions": actions,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -39,27 +39,26 @@ def build_chat_actions_payload(task) -> dict:
|
||||
构建聊天气泡侧动作按钮兼容 payload。
|
||||
|
||||
核心逻辑:复用统一 UI State 读模型,抽取聊天侧 checkpoint/summary/process_gate;
|
||||
action_buttons 已由 ui_state 在存在 ProcessExecution 时按 Gate 规则收缩(阻断清零)。
|
||||
业务动作只从 ui_state.actions 返回,Chat 不再暴露旧 action_buttons。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice 模型实例。
|
||||
|
||||
Returns:
|
||||
包含 task_no、checkpoint、process_gate、action_buttons 与摘要的字典。
|
||||
包含 task_no、checkpoint、process_gate、actions 与摘要的字典。
|
||||
"""
|
||||
state = build_task_ui_state(task)
|
||||
return {
|
||||
"task_no": state.get("task_no"),
|
||||
"batch_no": state.get("batch_no"),
|
||||
"checkpoint": state.get("checkpoint"),
|
||||
"process_status": state.get("process_status"),
|
||||
"review_status": state.get("review_status"),
|
||||
"pending_human_reason": state.get("pending_human_reason"),
|
||||
"match_status": state.get("match_status"),
|
||||
"current_step": state.get("current_step"),
|
||||
"stage": state.get("stage"),
|
||||
"todo": state.get("todo"),
|
||||
"actions": state.get("actions"),
|
||||
"reason": state.get("reason"),
|
||||
"lifecycle_status": state.get("lifecycle_status"),
|
||||
"summary": state.get("summary"),
|
||||
"process_gate": state.get("process_gate"),
|
||||
"action_buttons": state.get("action_buttons") or [],
|
||||
"updated_at": state.get("updated_at"),
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ CP_UPLOAD_FAILED = "upload_failed"
|
||||
CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
|
||||
CP_WAITING_UPLOAD = "waiting_upload"
|
||||
CP_REJECTED = "rejected"
|
||||
# Derived UI checkpoints (no separate pending_human_reason; from process_status)
|
||||
# Derived UI checkpoints (no separate pending_human_reason; from domain facts)
|
||||
CP_INVENTORY_PENDING = "inventory_pending"
|
||||
CP_READY_MATCH = "ready_to_match"
|
||||
CP_READY_EXPORT = "ready_to_export"
|
||||
|
||||
@@ -441,7 +441,7 @@ def correct_numbered_task_customer(
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING",
|
||||
)
|
||||
if any(
|
||||
version.process_status == "uploaded"
|
||||
str(getattr(version, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}
|
||||
or str(version.upload_status or "").lower() in {"uploaded", "succeeded", "success"}
|
||||
for version in versions
|
||||
):
|
||||
@@ -520,7 +520,6 @@ def correct_numbered_task_customer(
|
||||
latest.upload_error_message = None
|
||||
latest.upload_receipt_json = None
|
||||
latest.idempotency_key = None
|
||||
latest.process_status = "parsed"
|
||||
latest.current_step = None
|
||||
latest.review_status = None
|
||||
latest.pending_human_reason = None
|
||||
|
||||
@@ -245,10 +245,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
decision == "confirm_parse"
|
||||
or task.review_status == RS_PARSE_REVIEW
|
||||
or task.pending_human_reason == PH_LOW_CONF
|
||||
or (
|
||||
task.process_status in {"parsed", "pending_review", "created"}
|
||||
and not match_completed(task)
|
||||
)
|
||||
or not match_completed(task)
|
||||
):
|
||||
parse_validation = (
|
||||
(task.step_payload_json or {}).get("parse_validation")
|
||||
@@ -395,9 +392,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if task.process_status == "waiting_inventory" or (
|
||||
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
|
||||
):
|
||||
if task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json:
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
@@ -406,7 +401,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if task.inventory_lines_json or task.process_status == "inventory_ready":
|
||||
if task.inventory_lines_json:
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
|
||||
@@ -351,11 +351,6 @@ def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]:
|
||||
else {}
|
||||
)
|
||||
document = db.session.get(ShippingOrderDocument, int(cand.primary_document_id))
|
||||
action_buttons: list[str] = []
|
||||
if cand.candidate_status == 'provisional' and cand.consumed_task_id is None and cand.is_current_version:
|
||||
action_buttons.extend(['edit', 'evidence', 'reject'])
|
||||
if cand.validation_status == 'ready' and not blocking:
|
||||
action_buttons.append('promote')
|
||||
return {
|
||||
'candidate_no': cand.candidate_no,
|
||||
'primary_document_id': cand.primary_document_id,
|
||||
@@ -370,7 +365,6 @@ def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]:
|
||||
'acceptance_reason': cand.acceptance_reason,
|
||||
'acceptance_policy_version': cand.acceptance_policy_version,
|
||||
'extraction_source': cand.extraction_source,
|
||||
'action_buttons': action_buttons,
|
||||
'selected': bool(cand.selected),
|
||||
'business_fingerprint': cand.business_fingerprint,
|
||||
'fingerprint_strength': cand.fingerprint_strength,
|
||||
|
||||
@@ -32,41 +32,22 @@ from app.services.shipping_notice.business_fingerprint import (
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
# 与 state_machine 主路径对齐的活跃/完成/关闭态(禁止 needs_review/matching/export_ready 等非主状态)
|
||||
_ACTIVE_PROCESS_STATUSES = frozenset(
|
||||
{
|
||||
'created',
|
||||
'parsed',
|
||||
'pending_review',
|
||||
'inventory_ready',
|
||||
'waiting_inventory',
|
||||
'matched',
|
||||
'waiting_upload',
|
||||
'upload_failed',
|
||||
}
|
||||
)
|
||||
_COMPLETED_PROCESS_STATUSES = frozenset({'uploaded', 'completed'})
|
||||
_CLOSED_PROCESS_STATUSES = frozenset({'closed', 'rejected'})
|
||||
_IRREVERSIBLE_PROCESS_STATUSES = frozenset({'uploaded', 'completed', 'closed', 'rejected'})
|
||||
|
||||
|
||||
def classify_task_lifecycle(process_status: str | None) -> str:
|
||||
"""将 process_status 归类为 active / completed / closed / unknown。"""
|
||||
status = str(process_status or '').strip().lower()
|
||||
if status in _ACTIVE_PROCESS_STATUSES:
|
||||
return 'active'
|
||||
if status in _COMPLETED_PROCESS_STATUSES:
|
||||
return 'completed'
|
||||
if status in _CLOSED_PROCESS_STATUSES:
|
||||
def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str:
|
||||
"""根据生命周期/上传结果事实归类 active / completed / closed。"""
|
||||
if task is None:
|
||||
return 'unknown'
|
||||
get = task.get if isinstance(task, dict) else lambda key, default=None: getattr(task, key, default)
|
||||
lifecycle = str(get('lifecycle_status', '') or '').strip().lower()
|
||||
if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}:
|
||||
return 'closed'
|
||||
return 'unknown'
|
||||
upload = str(get('upload_status', '') or '').strip().lower()
|
||||
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no') or get('upload_receipt_json'):
|
||||
return 'completed'
|
||||
return 'active'
|
||||
|
||||
|
||||
def is_irreversible_task(task: ShippingNotice) -> bool:
|
||||
"""已 uploaded 或终态任务不可原地覆盖源文件。"""
|
||||
status = str(task.process_status or '').strip().lower()
|
||||
if status in _IRREVERSIBLE_PROCESS_STATUSES:
|
||||
return True
|
||||
upload_status = str(task.upload_status or '').strip().lower()
|
||||
return upload_status in {'uploaded', 'succeeded', 'success'}
|
||||
|
||||
@@ -74,11 +55,10 @@ def is_irreversible_task(task: ShippingNotice) -> bool:
|
||||
def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
'task_no': task.task_no,
|
||||
'process_status': task.process_status,
|
||||
'document_version': int(task.document_version or 1),
|
||||
'match_type': match_type,
|
||||
'matched_fields': list(matched_fields),
|
||||
'lifecycle': classify_task_lifecycle(task.process_status),
|
||||
'lifecycle': classify_task_lifecycle(task),
|
||||
'created_at': utc_iso(task.created_at),
|
||||
'content_fingerprint': task.content_fingerprint,
|
||||
'content_fingerprint_version': task.content_fingerprint_version,
|
||||
@@ -181,7 +161,7 @@ def detect_duplicates_for_intake(
|
||||
.filter(
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.source_content_hash == content_hash,
|
||||
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
ShippingNotice.lifecycle_status == 'active',
|
||||
)
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(10)
|
||||
@@ -235,7 +215,7 @@ def detect_duplicates_for_intake(
|
||||
else 'possible_revision'
|
||||
)
|
||||
else:
|
||||
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
|
||||
primary_life = str(matches[0].get('lifecycle') or 'unknown')
|
||||
if primary_life == 'active':
|
||||
status = 'same_active_task'
|
||||
elif primary_life == 'completed':
|
||||
@@ -253,7 +233,7 @@ def detect_duplicates_for_intake(
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.business_fingerprint == fingerprint,
|
||||
ShippingNotice.fingerprint_version == version,
|
||||
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
ShippingNotice.lifecycle_status == 'active',
|
||||
)
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(5)
|
||||
@@ -521,7 +501,7 @@ def detect_duplicates_for_candidate(
|
||||
.filter(
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.source_content_hash == content_hash,
|
||||
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
ShippingNotice.lifecycle_status == 'active',
|
||||
)
|
||||
)
|
||||
if skipped_ids:
|
||||
@@ -574,7 +554,7 @@ def detect_duplicates_for_candidate(
|
||||
else 'possible_revision'
|
||||
)
|
||||
else:
|
||||
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
|
||||
primary_life = str(matches[0].get('lifecycle') or 'unknown')
|
||||
if primary_life == 'active':
|
||||
status = 'same_active_task'
|
||||
elif primary_life == 'completed':
|
||||
@@ -588,7 +568,7 @@ def detect_duplicates_for_candidate(
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.business_fingerprint == fingerprint,
|
||||
ShippingNotice.fingerprint_version == version,
|
||||
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
ShippingNotice.lifecycle_status == 'active',
|
||||
)
|
||||
)
|
||||
if skipped_ids:
|
||||
|
||||
@@ -572,12 +572,12 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'),
|
||||
'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'),
|
||||
'artifact_generation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 生成失败'),
|
||||
'manual_upload_pending': _meta('owner', 'regenerate_manual_upload_todo', '请下载 Excel 后在货代平台上传并登记结果'),
|
||||
'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并登记结果'),
|
||||
'upload_rpa_pending': _meta('worker', 'poll_freight_upload_rpa', '货代平台上传任务等待执行'),
|
||||
'upload_rpa_failed': _meta('worker', 'retry_freight_upload_rpa', '货代平台上传失败,可重试 RPA'),
|
||||
'upload_rpa_login_failed': _meta('admin', 'retry_freight_upload_rpa', '货代平台登录失败,请检查凭据后重试'),
|
||||
'upload_platform_rejected': _meta('owner', 'retry_freight_upload_rpa', '货代平台拒绝上传,请核对文件后重试'),
|
||||
'upload_result_unknown': _meta('owner', 'regenerate_manual_upload_todo', '上传结果暂时无法确认'),
|
||||
'upload_result_unknown': _meta('owner', 'mark_manual_uploaded', '上传结果暂时无法确认'),
|
||||
'review_required': _meta('owner', 'open_order_review', '需要人工复核后才能继续'),
|
||||
'gate_invalidated': _meta('system', 'recheck_freeze_readiness', '上游结果已变化,当前门禁需重新评估'),
|
||||
'technical_failure_present': _meta('system', 'open_order_review', '存在技术失败,需处理后继续'),
|
||||
@@ -595,7 +595,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'void_blocked_external_uploaded': _meta('owner', '', '已存在外部履约,禁止作废,请归档'),
|
||||
'task_rejected_by_user': _meta('owner', '', '订单候选/任务已由用户驳回'),
|
||||
'task_closed_after_upload': _meta('owner', '', '上传完成后任务已关闭'),
|
||||
'close_blocked_missing_receipt': _meta('owner', 'regenerate_manual_upload_todo', '缺少上传回执,暂不可关闭'),
|
||||
'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '缺少上传回执,暂不可关闭'),
|
||||
'late_callback_ignored': _meta('system', '', '迟到的外部回调已忽略'),
|
||||
'excel_downloaded': _meta('owner', '', '已下载发货 Excel'),
|
||||
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
|
||||
|
||||
@@ -116,7 +116,6 @@ def _task_cancel_snapshot(task: ShippingNotice) -> dict[str, Any]:
|
||||
return {
|
||||
'task_no': str(task.task_no),
|
||||
'lifecycle_status': str(task.lifecycle_status or ''),
|
||||
'process_status': str(task.process_status or ''),
|
||||
'export_file_name': task.export_file_name,
|
||||
'void_reason': task.void_reason,
|
||||
'pending_human_reason': task.pending_human_reason,
|
||||
|
||||
@@ -532,8 +532,8 @@ def _trigger_freight_upload_rpa(
|
||||
actor_type='system',
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
before={'process_status': 'waiting_upload'},
|
||||
after={'process_status': str(task.process_status or ''), 'pending_human_reason': 'upload_rpa_pending'},
|
||||
before={'upload_status': str(task.upload_status or '')},
|
||||
after={'upload_status': str(task.upload_status or 'pending'), 'pending_human_reason': 'upload_rpa_pending'},
|
||||
metadata={'attempt_id': int(attempt.id), 'artifact_id': int(attempt.artifact_id)},
|
||||
source='system',
|
||||
)
|
||||
@@ -678,7 +678,7 @@ def _match_step_progress_fields(
|
||||
|
||||
def excel_gate_error(task: ShippingNotice) -> str | None:
|
||||
"""校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。"""
|
||||
if task.process_status == "uploaded" and task.export_file_path:
|
||||
if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} and task.export_file_path:
|
||||
return None
|
||||
if not match_completed(task):
|
||||
return "workflow.fulfillment.excel_gate_unmatched"
|
||||
@@ -742,7 +742,7 @@ def try_auto_chain_after_match(
|
||||
db.session.refresh(task)
|
||||
ui = resolve_task_ui_state(task)
|
||||
excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
|
||||
task.export_file_path and task.process_status != "uploaded"
|
||||
task.export_file_path and str(getattr(task, 'upload_status', None) or '').strip().lower() != 'uploaded'
|
||||
)
|
||||
if excel_ready and _auto_upload_enabled():
|
||||
upload_result = upload_to_freight({
|
||||
@@ -1970,7 +1970,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
operator_id = payload.get('operator_id')
|
||||
evidence_asset_no = str(payload.get('evidence_asset_no') or '')
|
||||
freight_ref_no = str(payload.get('freight_ref_no') or '')
|
||||
before_status = str(task.process_status or '')
|
||||
before_upload_status = str(task.upload_status or '')
|
||||
try:
|
||||
attempt = record_manual_upload(
|
||||
task,
|
||||
@@ -2000,8 +2000,8 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
reason_code='task_closed_after_upload',
|
||||
before={'process_status': before_status or 'waiting_upload'},
|
||||
after={'process_status': str(task.process_status or 'uploaded')},
|
||||
before={'upload_status': before_upload_status or 'pending'},
|
||||
after={'upload_status': str(task.upload_status or 'uploaded')},
|
||||
metadata={
|
||||
'attempt_id': attempt.id,
|
||||
'artifact_id': attempt.artifact_id,
|
||||
@@ -2034,8 +2034,8 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED if task.process_status == 'uploaded' else None,
|
||||
human_options=[] if task.process_status == 'uploaded' else None,
|
||||
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
human_options=[] if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -2194,8 +2194,8 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED if task.process_status == 'uploaded' else None,
|
||||
human_options=[] if task.process_status == 'uploaded' else None,
|
||||
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
human_options=[] if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
|
||||
@@ -2255,7 +2255,7 @@ def run_auto_progress_fulfillment_steps(
|
||||
# [STEP 3] Excel 就绪后按开关触发货代 RPA,或停待人工上传。
|
||||
ui = resolve_task_ui_state(task)
|
||||
excel_ready = ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD or (
|
||||
task.export_file_path and task.process_status != "uploaded"
|
||||
task.export_file_path and str(getattr(task, 'upload_status', None) or '').strip().lower() != 'uploaded'
|
||||
)
|
||||
if excel_ready and _auto_upload_enabled():
|
||||
steps.append("触发货代上传 RPA")
|
||||
|
||||
@@ -714,6 +714,7 @@ def refresh_intake_duplicate_detection(*, user_id: int, intake_no: str) -> dict[
|
||||
与 cancel 同序持锁再改 Candidate,避免并发删除导致 StaleDataError/死锁。
|
||||
"""
|
||||
from app.services.shipping_notice.duplicate_detection import (
|
||||
classify_task_lifecycle,
|
||||
refresh_candidates_and_aggregate_intake,
|
||||
)
|
||||
from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary
|
||||
@@ -810,7 +811,10 @@ def resolve_intake_duplicate(
|
||||
)
|
||||
# 目标状态相对检测结果漂移
|
||||
match_row = next((m for m in matches if str(m.get('task_no') or '').upper() == target_no), None)
|
||||
if match_row and str(match_row.get('process_status') or '') != str(target_task.process_status or ''):
|
||||
if match_row and (
|
||||
str(match_row.get('lifecycle') or '').strip().lower()
|
||||
!= str(classify_task_lifecycle(target_task) or '').strip().lower()
|
||||
):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED',
|
||||
message='目标任务状态已变化,请重新确认',
|
||||
|
||||
@@ -32,12 +32,10 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
|
||||
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def _can_relink_inventory(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
|
||||
return str(task.process_status or "").strip().lower() not in _TERMINAL_PROCESS_STATUSES
|
||||
return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \
|
||||
and str(getattr(task, 'lifecycle_status', None) or '').strip().lower() not in {'voided', 'archived', 'deleted'}
|
||||
|
||||
|
||||
def _safe_ref(value: str) -> str:
|
||||
@@ -551,7 +549,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
|
||||
task = link.task
|
||||
if not link.is_active or not task:
|
||||
continue
|
||||
if task.task_no in task_nos and task.process_status in {"inventory_ready", "parsed", "waiting_inventory"}:
|
||||
if task.task_no in task_nos and not task.match_status and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'}:
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step5_match_inventory",
|
||||
|
||||
@@ -270,7 +270,6 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int |
|
||||
"""
|
||||
if (
|
||||
task.pending_human_reason != PH_RPA_PENDING
|
||||
or task.process_status != "waiting_inventory"
|
||||
or task.inventory_lines_json
|
||||
):
|
||||
return None, None, None
|
||||
@@ -1167,7 +1166,7 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
task.current_step = "step3_inventory_prepare"
|
||||
# [STEP] 状态变更后再写事件,保证 after 快照含确认后的 process_status / phase。
|
||||
# [STEP] 状态变更后再写事件,保证 after 快照含确认后的领域事实 / phase。
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_confirmed",
|
||||
@@ -1296,7 +1295,6 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
timeout_seconds = rpa_inventory_timeout_seconds()
|
||||
if (
|
||||
task.pending_human_reason == PH_RPA_PENDING
|
||||
and task.process_status == "waiting_inventory"
|
||||
and not task.inventory_lines_json
|
||||
):
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
@@ -2492,7 +2490,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
**(inv_file.schema_preview_json or {}),
|
||||
'structure_validation': column_meta['structure_validation'],
|
||||
}
|
||||
if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}:
|
||||
if lines and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} and str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active':
|
||||
inventory_loaded_response(
|
||||
task,
|
||||
lines,
|
||||
|
||||
@@ -37,7 +37,6 @@ from app.services.shipping_notice.state_machine import TaskTransition, apply_tas
|
||||
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | None:
|
||||
@@ -143,7 +142,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
if str(task.process_status or "").strip().lower() in _TERMINAL_PROCESS_STATUSES:
|
||||
if str(getattr(task, 'upload_status', None) or '').strip().lower() in {'uploaded', 'succeeded', 'success'} or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
|
||||
@@ -51,7 +51,7 @@ def _post_op(
|
||||
"200": {
|
||||
"description": (
|
||||
"Tool response (status: ok|running|needs_human|failed). "
|
||||
"May include checkpoint, human_options, action_buttons."
|
||||
"May include checkpoint and human_options; business buttons are exposed only by ui_state.actions."
|
||||
),
|
||||
"content": {
|
||||
"application/json": {
|
||||
|
||||
@@ -1366,7 +1366,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
business_fingerprint=candidate.business_fingerprint, fingerprint_version=candidate.fingerprint_version,
|
||||
content_fingerprint=candidate.content_fingerprint, content_fingerprint_version=candidate.content_fingerprint_version,
|
||||
document_version=1, duplicate_resolution_type='normal', raw_content=document.extracted_text,
|
||||
customer_resolution_status='pending', process_status='created', current_order_extraction_id=int(extraction.id),
|
||||
customer_resolution_status='pending', current_order_extraction_id=int(extraction.id),
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -1579,8 +1579,7 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
|
||||
"""
|
||||
判断确认建单后的任务是否仍需自动推进。
|
||||
|
||||
核心逻辑:已挂正式 Extraction,且仍停在确认后早期态(created / parsed)。
|
||||
确认路径会先 CONFIRM_PARSE→parsed,故不得仅认 created,否则永远不会入队。
|
||||
核心逻辑:已挂正式 Extraction,且仍未进入库存/通知事实链路。
|
||||
重复调度依赖 enqueue 幂等(同 business_ref 有效 Job 不重复入队)。
|
||||
|
||||
Args:
|
||||
@@ -1593,9 +1592,13 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
|
||||
return False
|
||||
if not getattr(task, 'current_order_extraction_id', None):
|
||||
return False
|
||||
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
|
||||
# created:尚未 CONFIRM_PARSE;parsed:刚确认仍待库存推进。
|
||||
return process_status in {'', 'created', 'parsed'}
|
||||
return not bool(
|
||||
getattr(task, 'inventory_snapshot_id', None)
|
||||
or getattr(task, 'inventory_lines_json', None)
|
||||
or getattr(task, 'match_status', None)
|
||||
or getattr(task, 'export_file_path', None)
|
||||
or getattr(task, 'upload_status', None)
|
||||
)
|
||||
|
||||
|
||||
def resolve_confirm_outcome(progress: dict[str, Any] | None) -> str:
|
||||
|
||||
@@ -403,6 +403,12 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
|
||||
for line_index, line in enumerate(orders[0].get('lines') or []):
|
||||
if isinstance(line, dict):
|
||||
fields.extend({**field, '_line_index': line_index} for field in line.get('fields') or [] if isinstance(field, dict))
|
||||
case_document = db.session.get(ShippingOrderDocument, int(case.document_id))
|
||||
intake_id = int(case_document.intake_id) if case_document is not None else None
|
||||
intake_document_types = {
|
||||
int(document.id): str(document.document_type or '').strip()
|
||||
for document in ShippingOrderDocument.query.filter_by(intake_id=intake_id).all()
|
||||
}
|
||||
items: list[dict[str, Any]] = []
|
||||
for field in fields:
|
||||
if not isinstance(field, dict):
|
||||
@@ -457,11 +463,22 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
|
||||
cell_id = (
|
||||
str(observation.get('cell_id') or layout_evidence.get('cell_id') or '')[:128] or None
|
||||
)
|
||||
evidence_document_id = observation.get('document_id') or layout_evidence.get('document_id')
|
||||
try:
|
||||
evidence_document_id = int(evidence_document_id) if evidence_document_id is not None else int(case.document_id)
|
||||
except (TypeError, ValueError):
|
||||
evidence_document_id = int(case.document_id)
|
||||
# Observation 只能引用同一 Intake 的受控 Document;异常引用安全回退到当前 Case PDF。
|
||||
if evidence_document_id not in intake_document_types:
|
||||
evidence_document_id = int(case.document_id)
|
||||
items.append({
|
||||
'evidence_id': f"{field.get('field_id') or 'field'}:{field.get('_line_index', 'header')}:{index}",
|
||||
'field_id': str(field.get('field_id') or ''),
|
||||
'line_index': field.get('_line_index'),
|
||||
'machine_value': observation.get('value'),
|
||||
'document_id': evidence_document_id,
|
||||
'document_type': intake_document_types.get(evidence_document_id) or 'attachment',
|
||||
'source_type': str(observation.get('source_type') or '')[:64] or None,
|
||||
'quote': quote,
|
||||
'page_no': resolved_page,
|
||||
'table_id': table_id,
|
||||
@@ -572,3 +589,23 @@ def get_case_pdf_bytes(*, user_id: int, case_no: str) -> tuple[bytes, str]:
|
||||
if mime_type != 'application/pdf' and not str(document.filename or '').lower().endswith('.pdf'):
|
||||
raise ConflictError('Review document is not a PDF', code='SHIPPING.REVIEW_PREVIEW_INVALID')
|
||||
return read_asset_bytes(asset), str(document.filename or 'document.pdf').replace('\n', '').replace('\r', '')[:255]
|
||||
|
||||
|
||||
def get_case_email_evidence_text(*, user_id: int, case_no: str, document_id: int) -> dict[str, Any]:
|
||||
"""返回同一 Intake 邮件正文的已解析文本,禁止读取原始 EML、附件或存储地址。"""
|
||||
case = get_user_review_case(user_id=user_id, case_no=case_no)
|
||||
case_document = db.session.get(ShippingOrderDocument, int(case.document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if (
|
||||
case_document is None
|
||||
or document is None
|
||||
or int(document.intake_id) != int(case_document.intake_id)
|
||||
or str(document.document_type or '') != 'email_body'
|
||||
):
|
||||
raise NotFoundError('Email evidence preview is unavailable', code='SHIPPING.REVIEW_EVIDENCE_PREVIEW_NOT_FOUND')
|
||||
return {
|
||||
'document_id': int(document.id),
|
||||
'document_type': 'email_body',
|
||||
'filename': str(document.filename or 'email.eml')[:255],
|
||||
'text': str(document.extracted_text or '')[:20_000],
|
||||
}
|
||||
@@ -82,7 +82,7 @@ def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[s
|
||||
'needs_retry': False,
|
||||
'status': 'task_missing',
|
||||
'message': '正式任务关联异常,请联系管理员',
|
||||
'task_process_status': None,
|
||||
'task_progress_state': None,
|
||||
'job_id': None,
|
||||
'error_code': 'task_missing',
|
||||
'recovery_available': False,
|
||||
@@ -113,7 +113,7 @@ def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[s
|
||||
else '任务自动推进进行中或已完成'
|
||||
)
|
||||
),
|
||||
'task_process_status': auto.get('task_process_status'),
|
||||
'task_progress_state': auto.get('task_progress_state'),
|
||||
'job_id': auto.get('job_id'),
|
||||
'error_code': auto.get('error_code'),
|
||||
'reason_code': auto.get('reason_code'),
|
||||
@@ -123,7 +123,6 @@ def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[s
|
||||
'recovery_available': False if formal_ot.get('task_missing') else None,
|
||||
}
|
||||
|
||||
|
||||
def _stp_waiting_timeout_seconds() -> int:
|
||||
"""STP waiting_to_start 超时秒数(服务端配置,禁止前端硬编码)。"""
|
||||
try:
|
||||
@@ -159,9 +158,9 @@ def _project_case_automation_status(
|
||||
投影用户可见的自动建单/推进状态;资格达标不等于正在推进。
|
||||
|
||||
核心逻辑:
|
||||
- 已有正式 OT:只消费 post_confirm / OT process_status(禁止再读 STP 主态)
|
||||
- 已有正式 OT:只消费 post_confirm / OT 领域事实(禁止再读 STP 主态)
|
||||
- post_confirm needs_retry → failed(可重试)
|
||||
- 正式 OT + process_status created/空 → waiting_to_start(无 Job)或 queued
|
||||
- 正式 OT + 尚无领域事实 → waiting_to_start(无 Job)或 queued
|
||||
- 无正式 OT:查 STP Job queued/running/failed;can_auto_create 未入队 → waiting_to_start
|
||||
- phase / owner_type 由 enrich_automation_status 在 serialize 时补齐
|
||||
|
||||
@@ -181,7 +180,7 @@ def _project_case_automation_status(
|
||||
can_build = bool((validation or {}).get('can_build'))
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
|
||||
# [STEP 1] 正式 OT:与 post_confirm 共用 project_post_ot_automation_from_job,禁止只读 process_status。
|
||||
# [STEP 1] 正式 OT:与 post_confirm 共用 project_post_ot_automation_from_job,禁止只读旧字段。
|
||||
if formal_ot.get('has_formal_ot') or formal_ot.get('task_missing') or (
|
||||
isinstance(post_confirm, dict) and (
|
||||
post_confirm.get('task_no') or str(post_confirm.get('status') or '') == 'task_missing'
|
||||
@@ -875,7 +874,7 @@ def serialize_review_case(
|
||||
'label_key': 'task_missing',
|
||||
'source': 'formal_ot',
|
||||
'inconsistent': True,
|
||||
'process_status': None,
|
||||
'progress_state': None,
|
||||
'current_step': None,
|
||||
'stage_node': None,
|
||||
}
|
||||
|
||||
@@ -418,7 +418,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
|
||||
Returns:
|
||||
status / retryable / job_id / error_code / needs_retry / reason_code /
|
||||
task_no / task_process_status / completed_at。
|
||||
task_no / task_progress_state / completed_at。
|
||||
"""
|
||||
if task is None:
|
||||
return {
|
||||
@@ -428,7 +428,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
'job_id': None,
|
||||
'error_code': None,
|
||||
'task_no': None,
|
||||
'task_process_status': None,
|
||||
'task_progress_state': None,
|
||||
'attempts': None,
|
||||
'max_attempts': None,
|
||||
'completed_at': None,
|
||||
@@ -436,7 +436,14 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
}
|
||||
|
||||
task_no = str(getattr(task, 'task_no', None) or '').strip().upper() or None
|
||||
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
|
||||
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
|
||||
progress_state = (
|
||||
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'}
|
||||
else 'export_ready' if getattr(task, 'export_file_path', None)
|
||||
else 'matched' if getattr(task, 'match_status', None)
|
||||
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
|
||||
else 'not_started'
|
||||
)
|
||||
active = find_active_shipping_notice_run_job(task_no=task_no or '')
|
||||
latest = active or find_latest_shipping_notice_run_job(task_no=task_no or '')
|
||||
|
||||
@@ -504,7 +511,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
'retryable': False,
|
||||
'needs_retry': False,
|
||||
'task_no': task_no,
|
||||
'task_process_status': process_status,
|
||||
'task_progress_state': progress_state,
|
||||
'reason_code': None,
|
||||
**_job_fields(active),
|
||||
}
|
||||
@@ -520,13 +527,13 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
'retryable': True,
|
||||
'needs_retry': True,
|
||||
'task_no': task_no,
|
||||
'task_process_status': process_status,
|
||||
'task_progress_state': progress_state,
|
||||
'reason_code': fields.get('error_code') or 'auto_progress_job_failed',
|
||||
**fields,
|
||||
}
|
||||
if latest_status in {'succeeded', 'success', 'completed'}:
|
||||
# Job 标成功但 OT 仍 created:业务故障,不得伪装 waiting / 抹掉 job_id。
|
||||
if process_status in {'', 'created'}:
|
||||
if progress_state in {'', 'not_started'}:
|
||||
exhausted = _attempts_exhausted(latest)
|
||||
reason = 'auto_progress_job_succeeded_but_task_not_advanced'
|
||||
return {
|
||||
@@ -534,7 +541,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
'retryable': True,
|
||||
'needs_retry': True,
|
||||
'task_no': task_no,
|
||||
'task_process_status': process_status,
|
||||
'task_progress_state': progress_state,
|
||||
'reason_code': reason,
|
||||
'error_code': reason,
|
||||
'job_id': fields['job_id'],
|
||||
@@ -547,29 +554,29 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
'retryable': False,
|
||||
'needs_retry': False,
|
||||
'task_no': task_no,
|
||||
'task_process_status': process_status,
|
||||
'task_progress_state': progress_state,
|
||||
'reason_code': None,
|
||||
**fields,
|
||||
}
|
||||
|
||||
# [STEP 3] 无 Job:created → waiting_to_start;其余按 OT 态,禁止仅凭 process_status 伪装 running。
|
||||
if process_status in {'', 'created'}:
|
||||
# [STEP 3] 无 Job:尚无领域事实 → waiting_to_start;其余按 OT 态。
|
||||
if progress_state in {'', 'not_started'}:
|
||||
return {
|
||||
'status': 'waiting_to_start',
|
||||
'retryable': False,
|
||||
'needs_retry': False,
|
||||
'task_no': task_no,
|
||||
'task_process_status': process_status,
|
||||
'task_progress_state': progress_state,
|
||||
'reason_code': 'auto_progress_not_enqueued_yet',
|
||||
**_job_fields(None),
|
||||
}
|
||||
if process_status in {'completed', 'closed', 'done', 'uploaded'}:
|
||||
if progress_state in {'completed', 'closed', 'done', 'uploaded'}:
|
||||
return {
|
||||
'status': 'completed',
|
||||
'retryable': False,
|
||||
'needs_retry': False,
|
||||
'task_no': task_no,
|
||||
'task_process_status': process_status,
|
||||
'task_progress_state': progress_state,
|
||||
'reason_code': None,
|
||||
**_job_fields(None),
|
||||
}
|
||||
@@ -579,7 +586,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
|
||||
'retryable': False,
|
||||
'needs_retry': False,
|
||||
'task_no': task_no,
|
||||
'task_process_status': process_status,
|
||||
'task_progress_state': progress_state,
|
||||
'reason_code': 'auto_progress_not_enqueued_yet',
|
||||
**_job_fields(None),
|
||||
}
|
||||
@@ -602,7 +609,7 @@ def project_stage_for_task(
|
||||
default_code: 无 OT 时的阶段码。
|
||||
|
||||
Returns:
|
||||
{code, label_key, source, inconsistent, process_status, current_step, stage_node}
|
||||
{code, label_key, source, inconsistent, progress_state, current_step, stage_node}
|
||||
"""
|
||||
if task is None:
|
||||
return {
|
||||
@@ -610,7 +617,7 @@ def project_stage_for_task(
|
||||
'label_key': default_code,
|
||||
'source': 'fallback',
|
||||
'inconsistent': False,
|
||||
'process_status': None,
|
||||
'progress_state': None,
|
||||
'current_step': None,
|
||||
'stage_node': None,
|
||||
}
|
||||
@@ -621,7 +628,14 @@ def project_stage_for_task(
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
process_status = str(getattr(task, 'process_status', None) or '').strip().lower() or None
|
||||
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
|
||||
progress_state = (
|
||||
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'}
|
||||
else 'export_ready' if getattr(task, 'export_file_path', None)
|
||||
else 'matched' if getattr(task, 'match_status', None)
|
||||
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
|
||||
else 'not_started'
|
||||
)
|
||||
current_step = str(getattr(task, 'current_step', None) or '').strip() or None
|
||||
|
||||
def _with_label(code: str, *, source: str) -> dict[str, Any]:
|
||||
@@ -632,14 +646,14 @@ def project_stage_for_task(
|
||||
'label_key': label_key,
|
||||
'source': source,
|
||||
'inconsistent': False,
|
||||
'process_status': process_status,
|
||||
'progress_state': progress_state,
|
||||
'current_step': current_step,
|
||||
'stage_node': None,
|
||||
}
|
||||
|
||||
# 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在
|
||||
# freight_uploading,不能用过期阶段覆盖已经完成的履约状态。
|
||||
if process_status in {'uploaded', 'closed', 'completed'}:
|
||||
if progress_state in {'uploaded', 'closed', 'completed'}:
|
||||
return _with_label('completed', source='notice_terminal')
|
||||
|
||||
# [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。
|
||||
@@ -662,19 +676,19 @@ def project_stage_for_task(
|
||||
# [STEP 1b] 正式 OT 已创建但 stage 仍停在 order_creating:业务上已进入获取库存。
|
||||
# Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。
|
||||
if ot_stage == 'order_creating':
|
||||
if process_status in {'waiting_inventory', 'parsed', 'fetching_inventory', 'inventory_fetching'}:
|
||||
if progress_state in {'inventory_ready'}:
|
||||
return _with_label('inventory_fetching', source='notice_inventory')
|
||||
if process_status in {'inventory_ready', 'matching', 'matched'}:
|
||||
if progress_state in {'matched', 'export_ready'}:
|
||||
_status, mapped = map_notice_to_processing_status_stage(task)
|
||||
code = str(mapped or 'inventory_matching').strip() or 'inventory_matching'
|
||||
return _with_label(code, source='notice_map')
|
||||
if process_status in {None, '', 'created'}:
|
||||
if progress_state in {None, '', 'not_started'}:
|
||||
return _with_label('inventory_fetching', source='post_ot_inventory')
|
||||
return _with_label(ot_stage, source='order_task')
|
||||
|
||||
# [STEP 2] Notice 尚停在 created:统一 order_creating(与 Progress 词典同源,禁止冒充库存匹配)。
|
||||
if process_status in {None, '', 'created'}:
|
||||
return _with_label('order_creating', source='process_status')
|
||||
# [STEP 2] Notice 尚无履约领域事实:统一 order_creating。
|
||||
if progress_state in {None, '', 'not_started'}:
|
||||
return _with_label('order_creating', source='domain_facts')
|
||||
|
||||
# [STEP 3] 领域映射(与 sync_order_task_stage_for_notice 同源)。
|
||||
_status, stage = map_notice_to_processing_status_stage(task)
|
||||
|
||||
@@ -587,7 +587,7 @@ def per_source_callback_handler(
|
||||
|
||||
# [STEP 5] Task 已终态(兼容旧枚举 active/blocked 等非终态)
|
||||
terminal_statuses = {'completed', 'cancelled', 'failed_terminal'}
|
||||
if str(getattr(task, 'process_status', '') or '').strip() in terminal_statuses:
|
||||
if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in {'voided', 'archived', 'deleted'} or str(getattr(task, 'upload_status', '') or '').strip().lower() in {'uploaded', 'succeeded', 'success'}:
|
||||
attempt.status = 'superseded'
|
||||
attempt.extra_json = dict(attempt.extra_json or {}, late_callback_ignored=True, reason='task_terminal')
|
||||
attempt.callback_payload_json = dict(callback_payload or {})
|
||||
|
||||
@@ -37,6 +37,30 @@ from app.services.shipping_notice.process_gate_service import (
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _derived_fulfillment_status(task: ShippingNotice) -> str:
|
||||
"""从领域结果事实推导履约分支,不读取旧流程状态字段。"""
|
||||
pending = str(getattr(task, 'pending_human_reason', None) or '').strip()
|
||||
if pending in {'rpa_pending', 'rpa_exhausted', 'inventory_unavailable'}:
|
||||
return 'waiting_inventory'
|
||||
if pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
|
||||
return 'waiting_upload'
|
||||
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
|
||||
if upload_status in {'uploaded', 'succeeded', 'success'}:
|
||||
return 'uploaded'
|
||||
if upload_status == 'failed':
|
||||
return 'upload_failed'
|
||||
if isinstance(getattr(task, 'shortage_json', None), (dict, list)) and task.shortage_json:
|
||||
return 'shortage_review'
|
||||
match_status = str(getattr(task, 'match_status', None) or '').strip().lower()
|
||||
if match_status in {'fulfillable', 'partial', 'unfulfillable'}:
|
||||
return 'matched'
|
||||
if str(getattr(task, 'export_file_path', None) or '').strip():
|
||||
return 'inventory_ready'
|
||||
if isinstance(getattr(task, 'inventory_lines_json', None), list) and task.inventory_lines_json:
|
||||
return 'inventory_ready'
|
||||
return 'created'
|
||||
|
||||
|
||||
def inventory_preparation_reason_code(task: ShippingNotice) -> str:
|
||||
"""
|
||||
由任务事实推导库存准备门禁阻断原因码。
|
||||
@@ -125,7 +149,7 @@ def manual_upload_reason_code(task: ShippingNotice) -> str:
|
||||
)
|
||||
|
||||
pending = str(task.pending_human_reason or '').strip()
|
||||
status = str(task.process_status or '').strip()
|
||||
status = _derived_fulfillment_status(task)
|
||||
if pending == PH_UPLOAD_RPA_PENDING:
|
||||
return 'upload_rpa_pending'
|
||||
if pending == PH_UPLOAD_RPA_FAILED or status == 'upload_failed':
|
||||
@@ -687,7 +711,7 @@ def _supersede_auto_inventory_poll_for_rpa_failure(
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
if (
|
||||
str(task.process_status or '').strip() != 'waiting_inventory'
|
||||
_derived_fulfillment_status(task) != 'waiting_inventory'
|
||||
or str(task.pending_human_reason or '').strip() != PH_RPA_EXHAUSTED
|
||||
):
|
||||
return
|
||||
@@ -744,7 +768,7 @@ def sync_fulfillment_gates_from_task(
|
||||
"""
|
||||
按 ShippingNotice 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。
|
||||
|
||||
核心逻辑:将 process_status / export_file_path / match 相关字段投影为 Gate 结果;
|
||||
核心逻辑:将库存、匹配、上传等领域事实投影为 Gate 结果;
|
||||
RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断
|
||||
manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。
|
||||
由 auto_progress 与 Gate 恢复执行器在履约动作后调用。
|
||||
@@ -769,13 +793,13 @@ def sync_fulfillment_gates_from_task(
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
|
||||
status = str(task.process_status or '').strip()
|
||||
status = _derived_fulfillment_status(task)
|
||||
match_status = str(task.match_status or '').strip()
|
||||
has_export = bool(str(task.export_file_path or '').strip())
|
||||
has_inventory_lines = isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
|
||||
# [STEP 1] 优先读匹配/短缺实体;process_status 仅作库存准备与上传阶段辅助。
|
||||
# [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。
|
||||
done_statuses = {'uploaded', 'closed'}
|
||||
post_inventory = {'inventory_ready', 'matched', 'waiting_upload', 'upload_failed', *done_statuses}
|
||||
sufficiency_ok = match_completed(task)
|
||||
@@ -812,7 +836,7 @@ def sync_fulfillment_gates_from_task(
|
||||
|
||||
# [STEP 2] inventory_preparation — 等待与失败使用细粒度原因码 + Finding 事实
|
||||
task_facts = {
|
||||
'process_status': status or None,
|
||||
'derived_fulfillment_status': status or None,
|
||||
'task_no': str(task.task_no or '') or None,
|
||||
'has_inventory_lines': has_inventory_lines,
|
||||
}
|
||||
@@ -883,7 +907,7 @@ def sync_fulfillment_gates_from_task(
|
||||
|
||||
pending_reason = str(task.pending_human_reason or '').strip()
|
||||
# 只有 Worker 已领取/等待回调才是 waiting_external。RPA 失败或次数耗尽时
|
||||
# 必须退出自动处理中,回到可恢复 Gate,不能因 process_status 相同再次自动入队。
|
||||
# 必须退出自动处理中,回到可恢复 Gate,不能因同一等待事实再次自动入队。
|
||||
if pending_reason == PH_RPA_PENDING:
|
||||
outcome = 'waiting_external'
|
||||
waiting_reason = 'inventory_rpa_queued'
|
||||
@@ -904,7 +928,7 @@ def sync_fulfillment_gates_from_task(
|
||||
reason_code=waiting_reason,
|
||||
details=task_facts,
|
||||
),
|
||||
'process_status': status,
|
||||
'derived_fulfillment_status': status,
|
||||
},
|
||||
blocking_reason_code=waiting_reason,
|
||||
actor_type=actor_type,
|
||||
@@ -928,7 +952,7 @@ def sync_fulfillment_gates_from_task(
|
||||
details=task_facts,
|
||||
)
|
||||
),
|
||||
'process_status': status,
|
||||
'derived_fulfillment_status': status,
|
||||
'has_inventory_lines': has_inventory_lines,
|
||||
},
|
||||
blocking_reason_code=inv_prep_reason,
|
||||
@@ -1109,7 +1133,7 @@ def sync_fulfillment_gates_from_task(
|
||||
uploaded = status in done_statuses
|
||||
upload_reason = None if uploaded else manual_upload_reason_code(task)
|
||||
task_details = {
|
||||
'process_status': status or None,
|
||||
'derived_fulfillment_status': status or None,
|
||||
'task_no': str(task.task_no or '') or None,
|
||||
}
|
||||
if uploaded:
|
||||
@@ -1117,7 +1141,7 @@ def sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
gate_code='freight_upload_rpa',
|
||||
passed=True,
|
||||
effective_result={'process_status': status, 'findings': []},
|
||||
effective_result={'derived_fulfillment_status': status, 'findings': []},
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:freight_rpa:{execution.execution_no}:{status}:passed',
|
||||
@@ -1127,7 +1151,7 @@ def sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
gate_code='manual_upload_handoff',
|
||||
passed=True,
|
||||
effective_result={'process_status': status, 'findings': []},
|
||||
effective_result={'derived_fulfillment_status': status, 'findings': []},
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}:passed',
|
||||
@@ -1153,7 +1177,7 @@ def sync_fulfillment_gates_from_task(
|
||||
reason_code=str(upload_reason),
|
||||
details=task_details,
|
||||
),
|
||||
'process_status': status,
|
||||
'derived_fulfillment_status': status,
|
||||
},
|
||||
blocking_reason_code=upload_reason,
|
||||
actor_type=actor_type,
|
||||
@@ -1169,7 +1193,7 @@ def sync_fulfillment_gates_from_task(
|
||||
gate_code='freight_upload_rpa',
|
||||
passed=True,
|
||||
effective_result={
|
||||
'process_status': status,
|
||||
'derived_fulfillment_status': status,
|
||||
'findings': [],
|
||||
'handoff': 'manual_upload',
|
||||
},
|
||||
@@ -1189,7 +1213,7 @@ def sync_fulfillment_gates_from_task(
|
||||
reason_code=str(upload_reason or 'manual_upload_pending'),
|
||||
details=task_details,
|
||||
),
|
||||
'process_status': status,
|
||||
'derived_fulfillment_status': status,
|
||||
},
|
||||
blocking_reason_code=upload_reason or 'manual_upload_pending',
|
||||
actor_type=actor_type,
|
||||
|
||||
@@ -313,7 +313,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
|
||||
'implementation_status': 'implemented',
|
||||
'recoverable': True,
|
||||
'default_next_actions': {
|
||||
'blocked_manual': 'regenerate_manual_upload_todo',
|
||||
'blocked_manual': 'mark_manual_uploaded',
|
||||
'waiting_external': None,
|
||||
},
|
||||
},
|
||||
@@ -363,6 +363,8 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
|
||||
'poll_freight_upload_rpa',
|
||||
'retry_freight_upload_rpa',
|
||||
'regenerate_manual_upload_todo',
|
||||
# 仅驱动前端打开人工上传凭据登记;不得通过普通 Gate POST 直接确认。
|
||||
'mark_manual_uploaded',
|
||||
})
|
||||
|
||||
# Gate 卡只展示服务端冻结合同中的动作码。每次点击仍受 Workspace API 的
|
||||
|
||||
@@ -141,6 +141,10 @@ def execute_queued_attempt(
|
||||
action = str(snapshot.get('action_code') or gate.next_action_code or '').strip()
|
||||
payload = snapshot.get('payload') if isinstance(snapshot.get('payload'), dict) else {}
|
||||
payload = {**payload, 'action_code': action, 'attempt_id': int(attempt.id)}
|
||||
# Attempt 创建时记录的 actor 是 Gate Worker 的最后可信操作人来源;
|
||||
# 客户端 payload 未携带 actor_user_id 时仍必须传给订单冻结/审计链。
|
||||
if getattr(attempt, 'actor_id', None) is not None:
|
||||
payload.setdefault('actor_user_id', attempt.actor_id)
|
||||
if attempt.recovery_plan_id:
|
||||
payload.setdefault('recovery_plan_id', int(attempt.recovery_plan_id))
|
||||
|
||||
@@ -354,7 +358,10 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any])
|
||||
return {
|
||||
'task_id': str(task.task_no),
|
||||
'source': 'process_gate',
|
||||
'operator_id': payload.get('actor_user_id') or payload.get('user_id'),
|
||||
# Gate Attempt 的调用方可能来自 Worker(operator_id)或 Workspace(actor_user_id)。
|
||||
# 统一注入两种字段,避免正式库存重试冻结订单快照时丢失操作人。
|
||||
'operator_id': payload.get('actor_user_id') or payload.get('user_id') or payload.get('operator_id'),
|
||||
'actor_user_id': payload.get('actor_user_id') or payload.get('user_id') or payload.get('operator_id'),
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
}
|
||||
|
||||
@@ -817,10 +824,15 @@ def _handle_retry_inventory_preparation(
|
||||
outcome = _tool_outcome(
|
||||
action_code='retry_inventory_preparation',
|
||||
response=response,
|
||||
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'},
|
||||
# 用户触发的重新获取库存不能把“已提交但未确认”伪装成业务完成;
|
||||
# Gate 仍可记录 waiting_external,调用方可据此轮询,但测试/审计需区分
|
||||
# 人工重试动作本身与系统自动轮询动作。
|
||||
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'}
|
||||
if payload.get('action_code') == 'poll_inventory_preparation'
|
||||
else {'waiting', 'waiting_external', 'pending'},
|
||||
blocking_reason_code=prep_reason,
|
||||
)
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id)
|
||||
return outcome
|
||||
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ def _resolve_recovery_next_action(
|
||||
[STEP 1] 库存 RPA 失败(inventory_preparation Gate + retryable_tech 原因码)统一下发
|
||||
``retry_inventory_preparation``(重新获取库存),绕过历史「worker/retry_ 技术动作屏蔽」
|
||||
分支,使业务用户在库存 RPA 失败时可直接重试,而非被降级为人工上传入口。
|
||||
[STEP 2] 货代上传 RPA / 人工交接失败保持统一 RPA 重试入口。
|
||||
[STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。
|
||||
[STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留
|
||||
RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。
|
||||
"""
|
||||
@@ -132,7 +132,7 @@ def _resolve_recovery_next_action(
|
||||
blocking_gate_code == 'manual_upload_handoff'
|
||||
and normalized_reason in {'manual_upload_pending', 'upload_result_unknown'}
|
||||
):
|
||||
return 'retry_freight_upload_rpa', False
|
||||
return 'mark_manual_uploaded', False
|
||||
|
||||
# [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导)。
|
||||
next_action = full.get('primary_next_action_code') or _projection_primary_next_action(
|
||||
@@ -578,6 +578,8 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
if blocking:
|
||||
if next_action and is_business_user_action(str(next_action)):
|
||||
allowed_actions.append(str(next_action))
|
||||
# 库存文件可通过受控 Gate 工作台补传,但批次中心仅消费 ui_state.primary_action,
|
||||
# 因而不会把线外上传入口提升为文件卡主按钮。
|
||||
if (
|
||||
str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation'
|
||||
and next_action == 'retry_inventory_preparation'
|
||||
@@ -610,10 +612,20 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
)
|
||||
refs = _execution_navigation_refs(execution)
|
||||
navigation = _navigation_for_action(next_action, refs)
|
||||
current_gate_code = str((current or {}).get('gate_code') or '').strip() or None
|
||||
gate_status = str((current or {}).get('status') or '').strip() or None
|
||||
expected_gate_version = (
|
||||
int((current or {}).get('evaluation_version'))
|
||||
if (current or {}).get('evaluation_version') is not None
|
||||
else None
|
||||
)
|
||||
return {
|
||||
'execution_no': full.get('execution_no'),
|
||||
'status': full.get('status'),
|
||||
'execution_status': execution_status,
|
||||
'current_gate_code': current_gate_code,
|
||||
'gate_status': gate_status,
|
||||
'expected_gate_version': expected_gate_version,
|
||||
# 当前执行 Gate 与人工阻断分开投影:queued/running 不生成待办,但阶段游标必须
|
||||
# 仍来自正式 Gate,避免旧 OT stage 把页面停留在库存匹配。
|
||||
'current_gate': current,
|
||||
@@ -785,7 +797,6 @@ _USER_FACING_DETAIL_KEYS: frozenset[str] = frozenset({
|
||||
'field_code',
|
||||
'technical_retry_exhausted',
|
||||
'request_id',
|
||||
'process_status',
|
||||
'match_status',
|
||||
'task_no',
|
||||
'has_inventory_lines',
|
||||
|
||||
@@ -220,6 +220,15 @@ def request_gate_action(
|
||||
details={'action_code': action},
|
||||
)
|
||||
|
||||
# Gate 20 的确认必须走 mark-manual-uploaded:该 API 强制校验截图/PDF 凭据与货代回执号。
|
||||
# 禁止复用普通 Gate POST,避免调用方绕过人工上传证据门槛。
|
||||
if action == 'mark_manual_uploaded':
|
||||
raise ValidationError(
|
||||
'Manual upload confirmation requires evidence registration',
|
||||
code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED',
|
||||
details={'action_code': action, 'gate_code': gate.gate_code},
|
||||
)
|
||||
|
||||
definition = get_process_gate_definition(gate.gate_code)
|
||||
if (
|
||||
str(actor_type or '') == 'user'
|
||||
@@ -233,15 +242,6 @@ def request_gate_action(
|
||||
)
|
||||
|
||||
primary = _primary_recovery_action(execution=execution, gate=gate)
|
||||
# [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA
|
||||
# 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。
|
||||
# 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。
|
||||
if (
|
||||
gate.gate_code == 'manual_upload_handoff'
|
||||
and gate.blocking_reason_code in {'manual_upload_pending', 'upload_result_unknown'}
|
||||
and action == 'retry_freight_upload_rpa'
|
||||
):
|
||||
primary = action
|
||||
# [STEP] 附属动作仅允许挂在 inventory_source_routing,禁止跨门禁执行库存决定。
|
||||
allowed_side: set[str] = set()
|
||||
if gate.gate_code == 'inventory_source_routing':
|
||||
|
||||
@@ -33,6 +33,13 @@ from app.services.shipping_notice.process_gate_contract import (
|
||||
get_process_gate_definition,
|
||||
primary_next_action_for_gate,
|
||||
)
|
||||
|
||||
|
||||
def _auto_match_enabled() -> bool:
|
||||
"""读取全量自动推进的库存匹配开关,缺失时保持现有默认开启语义。"""
|
||||
from app.services.shipping_notice.tool_common import auto_match_enabled
|
||||
|
||||
return bool(auto_match_enabled())
|
||||
from app.services.shipping_notice.process_gate_dependency import compute_invalidated_gates
|
||||
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
|
||||
|
||||
@@ -765,13 +772,15 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
if next_gate is None or not next_gate.next_action_code:
|
||||
return
|
||||
definition = get_process_gate_definition(next_gate.gate_code)
|
||||
# default_next_actions 中可恢复不等于可自动执行。库存匹配等动作必须由
|
||||
# 用户明确点击;否则库存准备通过后会立刻消费“重试库存匹配”按钮,页面
|
||||
# 只剩被自动执行后的结果,用户无法控制重试时机。
|
||||
# 默认动作可恢复不等于永远禁止自动执行。全量自动推进开启时,库存准备
|
||||
# 通过后必须继续进入库存匹配;关闭自动匹配时才保留人工恢复入口。
|
||||
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
|
||||
return
|
||||
if (
|
||||
next_gate.next_action_code in {'retry_inventory_matching'}
|
||||
(
|
||||
next_gate.next_action_code in {'retry_inventory_matching'}
|
||||
and not _auto_match_enabled()
|
||||
)
|
||||
or str(next_gate.next_action_code).startswith('open_')
|
||||
):
|
||||
return
|
||||
|
||||
@@ -45,6 +45,7 @@ _WRITE_ACTION_CODES = frozenset({
|
||||
'open_inventory_match_review',
|
||||
'open_shortage_review',
|
||||
'upload_inventory_file',
|
||||
'retry_inventory_preparation',
|
||||
'retry',
|
||||
'retry_parse',
|
||||
'retry_failed_documents',
|
||||
@@ -174,15 +175,32 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
领域映射唯一来源,禁止写状态机反向依赖投影私有函数。
|
||||
|
||||
Args:
|
||||
notice: ShippingNotice 或具备 process_status/current_step/upload_status 的对象。
|
||||
notice: ShippingNotice 或具备领域事实/current_step/upload_status 的对象。
|
||||
|
||||
Returns:
|
||||
(ShippingProcessingStatus, ShippingProcessingStage)。
|
||||
"""
|
||||
ps = str(getattr(notice, 'process_status', None) or '').strip().lower()
|
||||
step = str(getattr(notice, 'current_step', None) or '').strip().lower()
|
||||
upload_st = str(getattr(notice, 'upload_status', None) or '').strip().lower()
|
||||
export_path = str(getattr(notice, 'export_file_path', None) or '').strip()
|
||||
pending = str(getattr(notice, 'pending_human_reason', None) or '').strip().lower()
|
||||
review = str(getattr(notice, 'review_status', None) or '').strip().lower()
|
||||
match = str(getattr(notice, 'match_status', None) or '').strip().lower()
|
||||
lifecycle = str(getattr(notice, 'lifecycle_status', None) or '').strip().lower()
|
||||
if upload_st in {'uploaded', 'succeeded', 'success'} or lifecycle in {'archived', 'deleted'}:
|
||||
ps = 'uploaded'
|
||||
elif upload_st in {'uploading', 'pending', 'failed'} or pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
|
||||
ps = 'waiting_upload' if upload_st != 'failed' else 'upload_failed'
|
||||
elif export_path:
|
||||
ps = 'matched'
|
||||
elif match:
|
||||
ps = 'matched'
|
||||
elif getattr(notice, 'inventory_lines_json', None):
|
||||
ps = 'inventory_ready'
|
||||
elif pending or review:
|
||||
ps = 'pending_review'
|
||||
else:
|
||||
ps = 'created'
|
||||
|
||||
if ps in {'uploaded', 'closed', 'completed'}:
|
||||
return ('completed', 'completed')
|
||||
@@ -708,13 +726,8 @@ def apply_user_projection_fields(
|
||||
rd_reason_code = str((retry_decision or {}).get('reason_code') or '').strip() or None
|
||||
|
||||
# ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) =====
|
||||
notice_process_status = None
|
||||
if notice is not None:
|
||||
notice_process_status = str(getattr(notice, 'process_status', None) or '').strip().lower() or None
|
||||
_rd_has_completed_process = bool(
|
||||
notice is not None
|
||||
and notice_process_status in {'completed', 'fulfilled', 'closed'}
|
||||
)
|
||||
notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else ''
|
||||
_rd_has_completed_process = notice_upload_status in {'uploaded', 'succeeded', 'success'}
|
||||
|
||||
def _compute_user_status() -> str:
|
||||
# [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision
|
||||
@@ -910,6 +923,7 @@ def apply_user_projection_fields(
|
||||
# ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None =====
|
||||
_ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = {
|
||||
'retry': 'workspace.shippingNotice.processGate.actionCodes.retry_with_latest_rules',
|
||||
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
'open_inventory_source_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_source_review',
|
||||
'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review',
|
||||
'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review',
|
||||
@@ -921,6 +935,7 @@ def apply_user_projection_fields(
|
||||
}
|
||||
_ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = {
|
||||
'retry': 'chat.shippingProcessing.action.retry',
|
||||
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
'open_inventory_source_review': 'chat.shippingProcessing.action.open_inventory_source_review',
|
||||
'open_inventory_match_review': 'chat.shippingProcessing.action.open_inventory_match_review',
|
||||
'open_order_review': 'chat.shippingProcessing.action.open_order_review',
|
||||
|
||||
@@ -290,6 +290,7 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = (
|
||||
'open_inventory_match_review',
|
||||
'open_shortage_review',
|
||||
'upload_inventory_file',
|
||||
'retry_inventory_preparation',
|
||||
'retry_inventory_matching',
|
||||
'retry',
|
||||
'refresh',
|
||||
@@ -837,7 +838,6 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'export_file_name',
|
||||
'order_data_version',
|
||||
'order_snapshot_id',
|
||||
'process_status',
|
||||
'changed_field_paths',
|
||||
'draft_version',
|
||||
'validation_blocking_count',
|
||||
|
||||
@@ -403,6 +403,30 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None
|
||||
except (TypeError, ValueError):
|
||||
operator_id = None
|
||||
# [STEP 0] 公开入口先执行 STP 早停,避免仅为查询/人工节点创建新的 Gate Attempt。
|
||||
# 正式 20-Gate 编排仍由后续分支负责;这里仅返回用户可执行的当前结果。
|
||||
early_task = resolve_task_from_payload({'task_no': task_no}) if task_no else None
|
||||
if early_task is not None:
|
||||
early_ui = resolve_task_ui_state(early_task)
|
||||
if early_ui.checkpoint_kind == CheckpointKind.MUST_HUMAN:
|
||||
return tool_response(
|
||||
status='needs_human', task=early_task,
|
||||
message='当前任务需要人工处理,已暂停自动推进。',
|
||||
data=serialize_task_for_tool(early_task),
|
||||
human_options=early_ui.human_options,
|
||||
checkpoint=early_ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if early_ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD and not fulfillment_workflow.is_auto_upload_enabled():
|
||||
return tool_response(
|
||||
status='ok', task=early_task,
|
||||
message='Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。',
|
||||
data=serialize_task_for_tool(early_task),
|
||||
human_options=early_ui.human_options,
|
||||
checkpoint=early_ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=['upload_to_freight'],
|
||||
)
|
||||
return run_task_auto_progress(
|
||||
task_no, trigger=trigger,
|
||||
expected_version=expected_version,
|
||||
@@ -435,7 +459,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"auto_progress_started",
|
||||
{
|
||||
"source": source,
|
||||
"process_status": task.process_status,
|
||||
"lifecycle_status": task.lifecycle_status,
|
||||
"current_step": task.current_step,
|
||||
"reason_code": "auto_progress_started",
|
||||
},
|
||||
|
||||
@@ -359,14 +359,14 @@ def list_batch_task_summaries(batch: Any) -> list[dict[str, Any]]:
|
||||
def compute_batch_process_summary(tasks: list[ShippingNotice]) -> dict[str, int]:
|
||||
"""批次进度汇总(Tool / 工作台 / 写回 batch.process_summary_json 共用公式)。"""
|
||||
total = len(tasks)
|
||||
completed = sum(1 for item in tasks if item.process_status in {"uploaded", "completed", "closed"})
|
||||
failed = sum(1 for item in tasks if item.process_status in {"rejected"} or item.upload_status == "failed")
|
||||
running = sum(1 for item in tasks if item.process_status not in {"uploaded", "completed", "closed", "rejected"})
|
||||
pending = sum(1 for item in tasks if item.process_status in {"created", "pending_review"} or not item.current_step)
|
||||
completed = sum(1 for item in tasks if _is_task_completed(item))
|
||||
failed = sum(1 for item in tasks if _is_task_failed(item))
|
||||
running = sum(1 for item in tasks if _is_task_active(item))
|
||||
pending = max(0, total - completed - failed - running - sum(1 for item in tasks if _is_task_needs_human(item)))
|
||||
focus = next(
|
||||
(
|
||||
item for item in sort_batch_tasks(tasks)
|
||||
if item.process_status not in {"uploaded", "completed", "closed", "rejected"}
|
||||
if not _is_task_completed(item) and not _is_task_failed(item)
|
||||
),
|
||||
None,
|
||||
)
|
||||
@@ -383,14 +383,17 @@ def compute_batch_process_summary(tasks: list[ShippingNotice]) -> dict[str, int]
|
||||
|
||||
def _is_task_completed(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否已进入完成态,用于会话级聚合统计。"""
|
||||
return str(task.process_status or "").strip().lower() in {"uploaded", "completed", "closed"}
|
||||
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
|
||||
return upload_status in {"uploaded", "succeeded", "success"} or bool(
|
||||
str(getattr(task, "freight_ref_no", None) or "").strip()
|
||||
)
|
||||
|
||||
|
||||
def _is_task_failed(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否失败或上传失败,用于会话级异常优先展示。"""
|
||||
return (
|
||||
str(task.process_status or "").strip().lower() in {"rejected"}
|
||||
or str(task.upload_status or "").strip().lower() == "failed"
|
||||
str(getattr(task, "review_status", None) or "").strip().lower() == "rejected"
|
||||
or str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
|
||||
)
|
||||
|
||||
|
||||
@@ -405,8 +408,15 @@ def _is_task_active(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否仍处于自动执行或等待外部系统返回的状态。"""
|
||||
if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task):
|
||||
return False
|
||||
status = str(task.process_status or "").strip().lower()
|
||||
return status not in {"created", "pending_review"} and bool(status)
|
||||
lifecycle = str(getattr(task, "lifecycle_status", "active") or "active").strip().lower()
|
||||
if lifecycle != "active":
|
||||
return False
|
||||
return bool(
|
||||
getattr(task, "current_step", None)
|
||||
or getattr(task, "inventory_snapshot_id", None)
|
||||
or getattr(task, "export_file_path", None)
|
||||
or getattr(task, "upload_status", None)
|
||||
)
|
||||
|
||||
|
||||
def compute_conversation_workspace_summary(batches: list[Any]) -> dict[str, int]:
|
||||
@@ -470,7 +480,7 @@ def resolve_task_from_payload(
|
||||
if conv_id:
|
||||
candidates = (
|
||||
ShippingNotice.query.filter_by(conversation_id=conv_id)
|
||||
.filter(ShippingNotice.process_status.notin_(["rejected", "closed", "uploaded"]))
|
||||
.filter(ShippingNotice.lifecycle_status == "active")
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(2)
|
||||
.all()
|
||||
@@ -492,7 +502,6 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||||
"shipping_case_id": task.shipping_case_id,
|
||||
"case_no": task.shipping_case.case_no if task.shipping_case else None,
|
||||
"business_no": task.shipping_case.business_no if task.shipping_case else None,
|
||||
"process_status": task.process_status,
|
||||
"current_step": task.current_step,
|
||||
"review_status": task.review_status,
|
||||
"match_status": task.match_status,
|
||||
@@ -523,7 +532,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||||
|
||||
payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task)
|
||||
# Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。
|
||||
if raw_content and (not lines or str(task.process_status or "").strip().lower() == "created"):
|
||||
if raw_content and not lines:
|
||||
limit = max_notice_chars()
|
||||
payload["raw_text"] = raw_content[:limit] if len(raw_content) > limit else raw_content
|
||||
if len(raw_content) > limit:
|
||||
@@ -656,7 +665,6 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
|
||||
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
|
||||
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
|
||||
"current_step": task.current_step,
|
||||
"process_status": task.process_status,
|
||||
"review_status": task.review_status,
|
||||
"match_status": task.match_status,
|
||||
"upload_status": task.upload_status,
|
||||
@@ -841,8 +849,10 @@ def _todo_category_from_task_row(
|
||||
extraction_id is not None
|
||||
and int(extraction_id) in extractions_with_lines
|
||||
)
|
||||
upload_status = str(getattr(row, "upload_status", None) or "").strip().lower()
|
||||
if upload_status in {"uploaded", "succeeded", "success"}:
|
||||
return "done"
|
||||
ui = resolve_task_ui_state_from_fields(
|
||||
process_status=getattr(row, "process_status", None),
|
||||
review_status=getattr(row, "review_status", None),
|
||||
pending_human_reason=getattr(row, "pending_human_reason", None),
|
||||
shipping_case_id=getattr(row, "shipping_case_id", None),
|
||||
@@ -945,11 +955,11 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
|
||||
"""
|
||||
将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。
|
||||
|
||||
核心逻辑:优先 Notice.order_task_id → ShippingOrderTask;有 OT 时用 Notice 履约
|
||||
process_status 映射为 shipping_processing_status(与 shipping_processing_projection 同源),
|
||||
核心逻辑:优先 Notice.order_task_id → ShippingOrderTask;有 OT 时用领域事实
|
||||
映射为 shipping_processing_status(与 shipping_processing_projection 同源),
|
||||
并注入 shipping_processing_stage / progress_version / order_task_no;
|
||||
另附带 review_run_no / owner_agent_id / conversation_id(经 OT.extraction_run),
|
||||
供任务中心「进入订单处理」深链;无 OT 时仍按 Notice.process_status 映射。
|
||||
供任务中心「进入订单处理」深链。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice(正式发货任务)。
|
||||
@@ -957,7 +967,7 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
|
||||
"""
|
||||
from app.models import ShippingOrderProcessingRun, ShippingOrderTask
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
_notice_processing_status_stage,
|
||||
_notice_domain_progress_stage,
|
||||
)
|
||||
|
||||
order_task = None
|
||||
@@ -973,7 +983,7 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
|
||||
.first()
|
||||
)
|
||||
|
||||
status, stage = _notice_processing_status_stage(task)
|
||||
status, stage = _notice_domain_progress_stage(task)
|
||||
data['shipping_processing_status'] = status
|
||||
data['shipping_processing_stage'] = (
|
||||
str(getattr(order_task, 'stage', None) or '').strip() or stage
|
||||
@@ -1114,7 +1124,6 @@ def list_tasks_for_user(
|
||||
user_id: int,
|
||||
*,
|
||||
batch_no: str | None = None,
|
||||
process_status: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""列出用户可见任务摘要,可按批次或工作台用户态状态过滤。"""
|
||||
@@ -1123,14 +1132,6 @@ def list_tasks_for_user(
|
||||
)
|
||||
if batch_no:
|
||||
return []
|
||||
if process_status:
|
||||
if process_status == "shortage_review":
|
||||
q = q.filter(
|
||||
(ShippingNotice.review_status == "shortage_review")
|
||||
| (ShippingNotice.pending_human_reason.in_(("shortage", "shortage_review")))
|
||||
)
|
||||
else:
|
||||
q = q.filter(ShippingNotice.process_status == process_status)
|
||||
rows = q.order_by(desc(ShippingNotice.created_at)).limit(max(1, min(limit, 500))).all()
|
||||
return [
|
||||
serialize_task_summary(c, viewer_user_id=user_id)
|
||||
@@ -1144,7 +1145,6 @@ def list_tasks_page_for_user(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
batch_no: str | None = None,
|
||||
process_status: str | None = None,
|
||||
lifecycle_status: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -1160,20 +1160,19 @@ def list_tasks_page_for_user(
|
||||
)
|
||||
if batch_no:
|
||||
return {"items": [], "page": normalized_page, "page_size": normalized_page_size, "total": 0}
|
||||
if process_status:
|
||||
if process_status == "shortage_review":
|
||||
q = q.filter(
|
||||
(ShippingNotice.review_status == "shortage_review")
|
||||
| (ShippingNotice.pending_human_reason.in_(("shortage", "shortage_review")))
|
||||
)
|
||||
else:
|
||||
q = q.filter(ShippingNotice.process_status == process_status)
|
||||
if lifecycle_status:
|
||||
normalized_lifecycle = str(lifecycle_status).strip().lower()
|
||||
if normalized_lifecycle == 'deleted':
|
||||
q = q.filter(ShippingNotice.deleted_at.is_not(None))
|
||||
elif normalized_lifecycle == 'active':
|
||||
q = q.filter(ShippingNotice.deleted_at.is_(None), ShippingNotice.lifecycle_status == 'active')
|
||||
q = q.filter(
|
||||
ShippingNotice.deleted_at.is_(None),
|
||||
ShippingNotice.lifecycle_status == 'active',
|
||||
db.or_(
|
||||
ShippingNotice.upload_status.is_(None),
|
||||
db.func.lower(ShippingNotice.upload_status).notin_(('uploaded', 'succeeded', 'success')),
|
||||
),
|
||||
)
|
||||
elif normalized_lifecycle == 'voided':
|
||||
# 作废后移入回收站的任务仍须出现在“已作废”视图,便于业务审计与追溯。
|
||||
q = q.filter(ShippingNotice.lifecycle_status == normalized_lifecycle)
|
||||
@@ -1373,13 +1372,18 @@ def serialize_review_case_todo(
|
||||
"created_by": case.owner_user_id,
|
||||
"source_file_name": source_name,
|
||||
"customer_name": None,
|
||||
"process_status": None,
|
||||
"updated_at": case.updated_at.isoformat() if case.updated_at else None,
|
||||
"created_at": case.created_at.isoformat() if case.created_at else None,
|
||||
"ui_state": {
|
||||
"checkpoint": "order_review",
|
||||
"stage": {"code": "order_review", "label": "订单复核", "index": 2, "total": 4},
|
||||
"checkpoint": {"code": "order_review", "kind": str(CheckpointKind.MUST_HUMAN), "label": "订单复核"},
|
||||
"todo": {"title": current_todo, "message": current_todo},
|
||||
"actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []},
|
||||
"reason": {"code": f"review_case_{case.status}", "message": current_todo},
|
||||
"lifecycle_status": "active",
|
||||
"process_gate": None,
|
||||
"checkpoint_code": "order_review",
|
||||
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
|
||||
"action_buttons": action_buttons,
|
||||
"summary": {
|
||||
"title": "待人工复核",
|
||||
"message": current_todo,
|
||||
@@ -1531,15 +1535,22 @@ def serialize_intake_todo(
|
||||
"source_file_name": source_name,
|
||||
"source_type": str(intake.source_type or "").strip() or None,
|
||||
"customer_name": None,
|
||||
"process_status": parse_status,
|
||||
"updated_at": intake.updated_at.isoformat() if intake.updated_at else None,
|
||||
"created_at": intake.created_at.isoformat() if intake.created_at else None,
|
||||
"ui_state": {
|
||||
"checkpoint": "intake_parse",
|
||||
"stage": {"code": "intake_parse", "label": "接收解析", "index": 1, "total": 4},
|
||||
"checkpoint": {"code": "order_field_extraction", "kind": str(
|
||||
CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE
|
||||
), "label": "订单解析"},
|
||||
"todo": {"title": title, "message": message},
|
||||
"actions": {"primary": ({"code": "retry_parse", "label": "重新解析", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if failed else None), "secondary": []},
|
||||
"reason": ({"code": str(intake.error_code or "intake_parse_failed"), "message": message} if failed else None),
|
||||
"lifecycle_status": "active",
|
||||
"process_gate": None,
|
||||
"checkpoint_code": "order_field_extraction",
|
||||
"checkpoint_kind": str(
|
||||
CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE
|
||||
),
|
||||
"action_buttons": ["retry_parse"] if failed else [],
|
||||
"summary": {
|
||||
"title": title,
|
||||
"message": message,
|
||||
@@ -1579,31 +1590,42 @@ def _todo_category_sql_filter(allowed: frozenset[str]):
|
||||
# wait_manual_upload:waiting_upload / 已有导出文件且未 uploaded。
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingNotice.process_status.in_(("waiting_upload", "upload_failed")),
|
||||
ShippingNotice.upload_status.in_(("pending", "uploading", "failed")),
|
||||
db.and_(
|
||||
ShippingNotice.export_file_path.isnot(None),
|
||||
ShippingNotice.process_status.notin_(("uploaded", "closed", "rejected")),
|
||||
db.or_(
|
||||
ShippingNotice.upload_status.is_(None),
|
||||
db.func.lower(ShippingNotice.upload_status).notin_(("uploaded", "succeeded", "success")),
|
||||
),
|
||||
ShippingNotice.lifecycle_status == "active",
|
||||
),
|
||||
)
|
||||
)
|
||||
if "done" in allowed:
|
||||
# 已上传/关闭/驳回终态(不含待人工上传登记)。
|
||||
clauses.append(
|
||||
ShippingNotice.process_status.in_(("uploaded", "closed", "rejected"))
|
||||
db.or_(
|
||||
ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")),
|
||||
ShippingNotice.review_status == RS_REJECTED,
|
||||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||||
)
|
||||
)
|
||||
if "review" in allowed:
|
||||
clauses.append(
|
||||
db.or_(
|
||||
ShippingNotice.process_status == "pending_review",
|
||||
ShippingNotice.review_status.isnot(None),
|
||||
ShippingNotice.pending_human_reason.isnot(None),
|
||||
)
|
||||
)
|
||||
if "exception" in allowed:
|
||||
clauses.append(ShippingNotice.pending_human_reason.isnot(None))
|
||||
if "in_progress" in allowed:
|
||||
clauses.append(
|
||||
ShippingNotice.process_status.in_(
|
||||
("created", "parsed", "matched", "inventory_ready")
|
||||
db.or_(
|
||||
ShippingNotice.current_step.isnot(None),
|
||||
ShippingNotice.inventory_snapshot_id.isnot(None),
|
||||
ShippingNotice.export_file_path.isnot(None),
|
||||
ShippingNotice.upload_status.isnot(None),
|
||||
)
|
||||
)
|
||||
if not clauses:
|
||||
@@ -1657,12 +1679,13 @@ def _task_todo_category_sql_expr():
|
||||
"""
|
||||
has_lines = _task_has_dynamic_order_lines_sql()
|
||||
reason = ShippingNotice.pending_human_reason
|
||||
upload_status = db.func.lower(db.func.coalesce(ShippingNotice.upload_status, ""))
|
||||
match_status = db.func.lower(db.func.coalesce(ShippingNotice.match_status, ""))
|
||||
return case(
|
||||
(ShippingNotice.process_status == "uploaded", literal("done")),
|
||||
(ShippingNotice.process_status == "closed", literal("done")),
|
||||
(upload_status.in_(("uploaded", "succeeded", "success")), literal("done")),
|
||||
(ShippingNotice.lifecycle_status.in_(("archived", "deleted")), literal("done")),
|
||||
(
|
||||
db.or_(
|
||||
ShippingNotice.process_status == "rejected",
|
||||
ShippingNotice.review_status == RS_REJECTED,
|
||||
),
|
||||
literal("done"),
|
||||
@@ -1691,9 +1714,10 @@ def _task_todo_category_sql_expr():
|
||||
literal("in_progress"),
|
||||
),
|
||||
(reason == PH_RPA_EXHAUSTED, literal("exception")),
|
||||
# Excel 已生成即进入待人工上传登记,不依赖历史 match_status 是否补写。
|
||||
(ShippingNotice.export_file_path.isnot(None), literal("manual_upload")),
|
||||
(
|
||||
db.and_(
|
||||
ShippingNotice.process_status == "parsed",
|
||||
_sql_str_blank(ShippingNotice.review_status),
|
||||
_sql_str_blank(reason),
|
||||
_sql_json_falsy(ShippingNotice.inventory_lines_json),
|
||||
@@ -1702,7 +1726,6 @@ def _task_todo_category_sql_expr():
|
||||
),
|
||||
(
|
||||
db.and_(
|
||||
ShippingNotice.process_status == "inventory_ready",
|
||||
_sql_str_blank(ShippingNotice.review_status),
|
||||
_sql_str_blank(reason),
|
||||
_sql_str_blank(ShippingNotice.match_status),
|
||||
@@ -1712,12 +1735,12 @@ def _task_todo_category_sql_expr():
|
||||
),
|
||||
(
|
||||
db.and_(
|
||||
ShippingNotice.process_status == "matched",
|
||||
match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
|
||||
ShippingNotice.export_file_path.isnot(None),
|
||||
),
|
||||
literal("manual_upload"),
|
||||
),
|
||||
(ShippingNotice.process_status == "matched", literal("in_progress")),
|
||||
(match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")), literal("in_progress")),
|
||||
(reason == PH_INV_UNAVAIL, literal("exception")),
|
||||
(reason == PH_INVENTORY_SOURCE_UNRESOLVED, literal("exception")),
|
||||
(
|
||||
@@ -1727,7 +1750,7 @@ def _task_todo_category_sql_expr():
|
||||
(
|
||||
db.or_(
|
||||
reason == PH_UPLOAD_RPA_FAILED,
|
||||
ShippingNotice.process_status == "upload_failed",
|
||||
upload_status == "failed",
|
||||
),
|
||||
literal("exception"),
|
||||
),
|
||||
@@ -1735,7 +1758,7 @@ def _task_todo_category_sql_expr():
|
||||
(reason == PH_RPA_PENDING, literal("exception")),
|
||||
(reason == PH_UPLOAD_RPA_PENDING, literal("exception")),
|
||||
# Excel 后待人工上传登记。
|
||||
(ShippingNotice.process_status == "waiting_upload", literal("manual_upload")),
|
||||
(upload_status.in_(("pending", "uploading")), literal("manual_upload")),
|
||||
else_=literal("in_progress"),
|
||||
)
|
||||
|
||||
@@ -1803,28 +1826,20 @@ def _todo_tasks_base_query(
|
||||
ShippingNotice.pending_human_reason.isnot(None),
|
||||
ShippingNotice.review_status.isnot(None),
|
||||
ShippingNotice.export_file_path.isnot(None),
|
||||
ShippingNotice.process_status.in_(
|
||||
(
|
||||
"pending_review",
|
||||
"matched",
|
||||
"waiting_upload",
|
||||
"upload_failed",
|
||||
"parsed",
|
||||
"inventory_ready",
|
||||
"created",
|
||||
)
|
||||
),
|
||||
ShippingNotice.current_step.isnot(None),
|
||||
ShippingNotice.inventory_snapshot_id.isnot(None),
|
||||
ShippingNotice.upload_status.isnot(None),
|
||||
)
|
||||
)
|
||||
elif normalized_bucket == "done":
|
||||
# Excel 就绪(matched+export / waiting_upload)与历史上传完成均归 done。
|
||||
q = q.filter(
|
||||
db.or_(
|
||||
ShippingNotice.process_status.in_(
|
||||
("uploaded", "closed", "rejected", "waiting_upload")
|
||||
),
|
||||
ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")),
|
||||
ShippingNotice.review_status == RS_REJECTED,
|
||||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||||
db.and_(
|
||||
ShippingNotice.process_status == "matched",
|
||||
ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
|
||||
ShippingNotice.export_file_path.isnot(None),
|
||||
),
|
||||
)
|
||||
@@ -1833,25 +1848,8 @@ def _todo_tasks_base_query(
|
||||
|
||||
|
||||
def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False):
|
||||
"""徽标统计用的活跃 Task 粗筛范围(不含 done)。"""
|
||||
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin).filter(
|
||||
db.or_(
|
||||
ShippingNotice.pending_human_reason.isnot(None),
|
||||
ShippingNotice.review_status.isnot(None),
|
||||
ShippingNotice.export_file_path.isnot(None),
|
||||
ShippingNotice.process_status.in_(
|
||||
(
|
||||
"pending_review",
|
||||
"matched",
|
||||
"waiting_upload",
|
||||
"upload_failed",
|
||||
"parsed",
|
||||
"inventory_ready",
|
||||
"created",
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
"""徽标统计用的活跃 Task 范围;分类 CASE 负责排除 done。"""
|
||||
return _visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
|
||||
|
||||
def list_my_todos(
|
||||
@@ -2062,11 +2060,11 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]:
|
||||
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
|
||||
.filter(
|
||||
db.or_(
|
||||
ShippingNotice.process_status.in_(
|
||||
("uploaded", "closed", "rejected", "waiting_upload")
|
||||
),
|
||||
ShippingNotice.upload_status.in_(("uploaded", "succeeded", "success")),
|
||||
ShippingNotice.review_status == RS_REJECTED,
|
||||
ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")),
|
||||
db.and_(
|
||||
ShippingNotice.process_status == "matched",
|
||||
ShippingNotice.match_status.in_(("fulfillable", "partial", "unfulfillable", "matched")),
|
||||
ShippingNotice.export_file_path.isnot(None),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -95,16 +95,11 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool:
|
||||
|
||||
if not task_is_active(task):
|
||||
return False
|
||||
process_status = str(task.process_status or '').strip()
|
||||
pending_reason = str(task.pending_human_reason or '').strip()
|
||||
return (
|
||||
process_status == 'waiting_inventory'
|
||||
and pending_reason == PH_RPA_PENDING
|
||||
pending_reason == PH_RPA_PENDING
|
||||
and not task.inventory_lines_json
|
||||
) or (
|
||||
process_status == 'waiting_upload'
|
||||
and pending_reason == PH_UPLOAD_RPA_PENDING
|
||||
)
|
||||
) or pending_reason == PH_UPLOAD_RPA_PENDING
|
||||
|
||||
|
||||
def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
|
||||
@@ -280,7 +275,7 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
|
||||
hang_created = bool(
|
||||
refreshed is not None
|
||||
and getattr(refreshed, 'current_order_extraction_id', None)
|
||||
and str(getattr(refreshed, 'process_status', None) or '').strip().lower() in {'', 'created'}
|
||||
and not getattr(refreshed, 'order_snapshot_id', None)
|
||||
and status in {'ok', 'needs_human', 'skipped'}
|
||||
)
|
||||
if hang_created:
|
||||
|
||||
@@ -80,7 +80,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa
|
||||
confidence=ReconcileConfidence.CERTAIN,
|
||||
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps,
|
||||
confirmed_task_id=int(task_id),
|
||||
lifecycle=classify_task_lifecycle(task.process_status)),
|
||||
lifecycle=classify_task_lifecycle(task)),
|
||||
)
|
||||
steps.append({'step': 'L1a-confirmed_task_id', 'passed': False,
|
||||
'reason': 'confirmed_task_id 指向的 ShippingNotice 不存在或无 task_no',
|
||||
@@ -101,7 +101,7 @@ def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMa
|
||||
confidence=ReconcileConfidence.CERTAIN,
|
||||
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps,
|
||||
confirmed_task_no=confirmed_task_no,
|
||||
lifecycle=classify_task_lifecycle(task.process_status)),
|
||||
lifecycle=classify_task_lifecycle(task)),
|
||||
)
|
||||
steps.append({'step': 'L1b-confirmed_task_no', 'passed': False,
|
||||
'reason': 'confirmed_task_no 反向查无 ShippingNotice',
|
||||
@@ -165,7 +165,7 @@ def _step_l1cde_downstream_links(
|
||||
case_no=case_no, match_level_steps=steps,
|
||||
candidate_id=int(candidate.id),
|
||||
linked_candidate_task_id=int(fulfilled_task_id),
|
||||
lifecycle=classify_task_lifecycle(task.process_status),
|
||||
lifecycle=classify_task_lifecycle(task),
|
||||
),
|
||||
)
|
||||
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False,
|
||||
@@ -194,7 +194,7 @@ def _step_l1cde_downstream_links(
|
||||
evidence=ReconcileMatchEvidence(
|
||||
case_no=case_no, match_level_steps=steps,
|
||||
wave_linked_task_id=wave_task_ids[0],
|
||||
lifecycle=classify_task_lifecycle(task.process_status),
|
||||
lifecycle=classify_task_lifecycle(task),
|
||||
),
|
||||
)
|
||||
steps.append({'step': 'L1c-wave_line_task', 'passed': False,
|
||||
@@ -226,7 +226,7 @@ def _step_l1cde_downstream_links(
|
||||
evidence=ReconcileMatchEvidence(
|
||||
case_no=case_no, match_level_steps=steps,
|
||||
source_document_id=document_id,
|
||||
lifecycle=classify_task_lifecycle(task.process_status),
|
||||
lifecycle=classify_task_lifecycle(task),
|
||||
),
|
||||
)
|
||||
steps.append({'step': 'L1d-document_foreign_key', 'passed': False,
|
||||
@@ -247,7 +247,7 @@ def _step_l1cde_downstream_links(
|
||||
file_tasks = (
|
||||
ShippingNotice.query
|
||||
.filter_by(user_id=int(case.owner_user_id), source_content_hash=content_hash)
|
||||
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
|
||||
.filter(ShippingNotice.lifecycle_status == 'active')
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(5)
|
||||
.all()
|
||||
@@ -264,7 +264,7 @@ def _step_l1cde_downstream_links(
|
||||
evidence=ReconcileMatchEvidence(
|
||||
case_no=case_no, match_level_steps=steps,
|
||||
content_hash=content_hash,
|
||||
lifecycle=classify_task_lifecycle(task.process_status),
|
||||
lifecycle=classify_task_lifecycle(task),
|
||||
),
|
||||
)
|
||||
steps.append({'step': 'L1d-file_hash_match', 'passed': False,
|
||||
@@ -403,7 +403,7 @@ def _step_l2_structural_match(
|
||||
ShippingNotice.query
|
||||
.filter(ShippingNotice.user_id == int(case.owner_user_id),
|
||||
ShippingNotice.business_fingerprint == payload['business_fingerprint'])
|
||||
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
|
||||
.filter(ShippingNotice.lifecycle_status == 'active')
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(5)
|
||||
.all()
|
||||
@@ -415,7 +415,7 @@ def _step_l2_structural_match(
|
||||
'recalculated': payload['fingerprint_recalculated'],
|
||||
'task_no': str(task.task_no)}})
|
||||
evidence['match_level_steps'] = steps
|
||||
evidence['lifecycle'] = classify_task_lifecycle(task.process_status)
|
||||
evidence['lifecycle'] = classify_task_lifecycle(task)
|
||||
return ReconcileMatchResult(
|
||||
match_level=ReconcileMatchLevel.L2,
|
||||
task_no=str(task.task_no),
|
||||
@@ -442,7 +442,7 @@ def _step_l2_structural_match(
|
||||
.filter_by(user_id=int(case.owner_user_id))
|
||||
.filter(ShippingNotice.customer_code == payload['customer_code']
|
||||
if hasattr(ShippingNotice, 'customer_code') else True)
|
||||
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
|
||||
.filter(ShippingNotice.lifecycle_status == 'active')
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(20)
|
||||
.all()
|
||||
@@ -467,7 +467,7 @@ def _step_l2_structural_match(
|
||||
((task.structured_result_json or {}).get('business_summary') or {}).get('po_numbers') or []}),
|
||||
'task_no': str(task.task_no)}})
|
||||
evidence['match_level_steps'] = steps
|
||||
evidence['lifecycle'] = classify_task_lifecycle(task.process_status)
|
||||
evidence['lifecycle'] = classify_task_lifecycle(task)
|
||||
return ReconcileMatchResult(
|
||||
match_level=ReconcileMatchLevel.L2,
|
||||
task_no=str(task.task_no),
|
||||
@@ -490,7 +490,7 @@ def _step_l2_structural_match(
|
||||
ShippingNotice.query
|
||||
.filter((ShippingNotice.source_document_id == document_id) |
|
||||
(ShippingNotice.document_id == document_id))
|
||||
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
|
||||
.filter(ShippingNotice.lifecycle_status == 'active')
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(5)
|
||||
.all()
|
||||
@@ -501,7 +501,7 @@ def _step_l2_structural_match(
|
||||
'count': len(doc_tasks_multi)}})
|
||||
evidence['match_level_steps'] = steps
|
||||
evidence['candidate_matches'] = [
|
||||
{'task_no': str(t.task_no), 'lifecycle': classify_task_lifecycle(t.process_status)}
|
||||
{'task_no': str(t.task_no), 'lifecycle': classify_task_lifecycle(t)}
|
||||
for t in doc_tasks_multi
|
||||
]
|
||||
return ReconcileMatchResult(
|
||||
|
||||
@@ -81,7 +81,7 @@ class ReconcileProgressResult:
|
||||
outcome: Literal[
|
||||
'reused_existing', # L1 命中,已绑定到既有 Task
|
||||
'duplicate_decision_required', # L2/L3 命中,等待人工裁决
|
||||
'ownership_anomaly_rejected', # 归属异常(Q13),process_status=rejected
|
||||
'ownership_anomaly_rejected', # 归属异常(Q13),进入人工隔离
|
||||
'stp_enqueued', # 无冲突或用户裁决后,已入队 STP
|
||||
'resume_result', # 仅 resume 结果(未到入队)
|
||||
'idempotent_replay', # 同 operation_id 幂等回返
|
||||
@@ -453,7 +453,7 @@ def reconcile_and_progress(
|
||||
• replay_mode(bool):允许 legacy_job_id.reference_key != case_no。
|
||||
默认 false(防跨 Case 错挂)。
|
||||
• BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计
|
||||
→ ReviewCase 无 process_status 列则抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY,
|
||||
→ 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY,
|
||||
否则返回 outcome=ownership_anomaly_rejected。
|
||||
|
||||
Args:
|
||||
@@ -732,7 +732,7 @@ def reconcile_and_progress(
|
||||
pending_reason = 'ownership_anomaly'
|
||||
# [Phase 4 Q13 硬隔离] — 先回滚 BRANCH B/C 半写(_write_back_case_task_binding)
|
||||
# 避免把 Case 的 candidate_id / confirmed_task_id / fulfilled_task_id 留痕;
|
||||
# 再单独写 sensitive 审计;再根据 ReviewCase 是否有 process_status 列返回
|
||||
# 再单独写 sensitive 审计;ReviewCase 不承担履约阶段字段
|
||||
# outcome=ownership_anomaly_rejected 或抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY。
|
||||
try:
|
||||
db.session.rollback()
|
||||
@@ -777,34 +777,13 @@ def reconcile_and_progress(
|
||||
pass
|
||||
msg = (f'ambiguous ownership: match_level={match_result.get("match_level")} '
|
||||
f'user_action={user_action}; marked ownership_anomaly pending human review')
|
||||
case_attr_writable = hasattr(case_after, 'process_status')
|
||||
if not case_attr_writable:
|
||||
# ReviewCase 没有 process_status(process_status 属于 CaseEvent/Wave 层)
|
||||
# → 降级:抛 422 给前端显式提示 hard_isolation=True(让前端走裁决面板)
|
||||
raise ValidationError(
|
||||
msg,
|
||||
code='SHIPPING.RECONCILE_OWNERSHIP_ANOMALY',
|
||||
details={
|
||||
'hard_isolation': True,
|
||||
'match': {
|
||||
k: match_result.get(k)
|
||||
for k in ('match_level', 'confidence', 'task_no')
|
||||
},
|
||||
'user_action': user_action,
|
||||
'next_suggested_actions': [
|
||||
'reuse_existing', 'create_revision', 'force_create',
|
||||
],
|
||||
'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None),
|
||||
'replay_mode': bool(replay_mode),
|
||||
},
|
||||
)
|
||||
final_result = ReconcileProgressResult(
|
||||
outcome='ownership_anomaly_rejected',
|
||||
case_no=str(case_after.case_no), match=match_result,
|
||||
task_no=None, job_id=None, idempotency_key=idem_key,
|
||||
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
|
||||
)
|
||||
# 用 case_after 替换引用,防止后续审计写已失效对象
|
||||
# 用 case_after 替换引用,防止后续审计写入已失效对象。
|
||||
case = case_after
|
||||
user = db.session.get(User, int(user_id))
|
||||
|
||||
|
||||
@@ -98,7 +98,6 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No
|
||||
if not task_no:
|
||||
return None
|
||||
|
||||
process_status = _clean_text(getattr(task, "process_status", None)).lower()
|
||||
review_status = _clean_text(getattr(task, "review_status", None)).lower()
|
||||
match_status = _clean_text(getattr(task, "match_status", None)).lower()
|
||||
pending_reason = _clean_text(getattr(task, "pending_human_reason", None)).lower()
|
||||
@@ -110,13 +109,13 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No
|
||||
"label": "异常:库存不足",
|
||||
"summary": f"{task_no} 库存匹配失败",
|
||||
}
|
||||
if process_status == "rejected" or review_status == "rejected":
|
||||
if review_status == "rejected" or str(getattr(task, "lifecycle_status", "") or "").lower() in {"voided", "archived"}:
|
||||
return {
|
||||
"reason": "rejected",
|
||||
"label": "已驳回",
|
||||
"summary": f"{task_no} 已被驳回",
|
||||
}
|
||||
if process_status == "upload_failed" or upload_status == "failed" or pending_reason == "upload_rpa_failed":
|
||||
if upload_status == "failed" or pending_reason == "upload_rpa_failed":
|
||||
return {
|
||||
"reason": "upload_failed",
|
||||
"label": "异常:上传失败",
|
||||
|
||||
@@ -138,7 +138,6 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st
|
||||
if task is not None:
|
||||
for attr, key in (
|
||||
("current_step", "current_step"),
|
||||
("process_status", "status"),
|
||||
("review_status", "review_status"),
|
||||
("match_status", "match_status"),
|
||||
("pending_human_reason", "pending_human_reason"),
|
||||
@@ -177,7 +176,6 @@ def _build_summary(
|
||||
task_no = _task_no(task)
|
||||
batch_no = _batch_no(batch, task)
|
||||
file_name = _clean_text(getattr(task, "source_file_name", None))
|
||||
status = _clean_text(getattr(task, "process_status", None))
|
||||
current_step = _clean_text(getattr(task, "current_step", None))
|
||||
normalized_run_purpose = _clean_text(run_purpose)
|
||||
if task_no:
|
||||
@@ -188,8 +186,6 @@ def _build_summary(
|
||||
pieces.append(f"来源文件 {file_name}")
|
||||
if normalized_run_purpose:
|
||||
pieces.append(f"本次执行目的为 {normalized_run_purpose}")
|
||||
if status:
|
||||
pieces.append(f"当前状态 {status}")
|
||||
if current_step:
|
||||
pieces.append(f"当前步骤 {current_step}")
|
||||
if not pieces:
|
||||
|
||||
@@ -34,6 +34,7 @@ from app.models import (
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingRunIntake,
|
||||
ShippingOrderProcessingUnit,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderSubmission,
|
||||
ShippingOrderTask,
|
||||
@@ -268,12 +269,13 @@ def _intake_processing_status(intake: ShippingOrderIntake) -> str:
|
||||
将 Intake.parse_status 映射为统一 status。
|
||||
|
||||
核心逻辑:parse_failed→failed;parsing/queued/created→processing;
|
||||
parsed 且已消费→completed,否则仍 processing。
|
||||
direct_pdf 已消费可完成;EML 交接后若无替代 OT 仍保持处理中。
|
||||
"""
|
||||
parse_status = str(intake.parse_status or '').strip().lower()
|
||||
extraction_status = str(
|
||||
getattr(intake, 'order_extraction_status', None) or ''
|
||||
).strip().lower()
|
||||
source_type = str(intake.source_type or '').strip().lower()
|
||||
if extraction_status in {'failed', 'error', 'fatal'}:
|
||||
return 'failed'
|
||||
if extraction_status in {'cancelled', 'canceled'}:
|
||||
@@ -282,7 +284,12 @@ def _intake_processing_status(intake: ShippingOrderIntake) -> str:
|
||||
return 'failed'
|
||||
if parse_status in {'cancelled', 'expired'}:
|
||||
return 'cancelled'
|
||||
if parse_status == 'consumed' or intake.consumed_at is not None:
|
||||
# EML 的 consumed_at 只是进入订单识别链路的内部交接标记。未有 OT/Candidate
|
||||
# 且提取仅部分完成时,不能把用户卡误报为已完成。
|
||||
if (
|
||||
source_type != 'eml'
|
||||
and (parse_status == 'consumed' or intake.consumed_at is not None)
|
||||
):
|
||||
return 'completed'
|
||||
if parse_status == 'parsed':
|
||||
return 'completed' if intake.consumed_at is not None else 'processing'
|
||||
@@ -294,12 +301,20 @@ def _intake_processing_stage(intake: ShippingOrderIntake) -> str:
|
||||
将 Intake 解析阶段映射为统一 stage。
|
||||
|
||||
核心逻辑:direct_pdf 全程用 document_parsing(禁止 email_*);
|
||||
eml 在解析中用 email_parsing;已解析/消费用 completed 或 candidate_creating。
|
||||
EML 在解析中用 email_parsing,部分完成/已交接但无 OT 时停在 candidate_creating。
|
||||
"""
|
||||
source = str(intake.source_type or '').strip().lower() or None
|
||||
parse_status = str(intake.parse_status or '').strip().lower()
|
||||
if parse_status in {'consumed'} or intake.consumed_at is not None:
|
||||
extraction_status = str(
|
||||
getattr(intake, 'order_extraction_status', None) or ''
|
||||
).strip().lower()
|
||||
if (
|
||||
source != 'eml'
|
||||
and (parse_status in {'consumed'} or intake.consumed_at is not None)
|
||||
):
|
||||
return _clamp_processing_stage('completed', source_type=source)
|
||||
if source == 'eml' and extraction_status in {'partially_completed', 'partial', 'interrupted'}:
|
||||
return _clamp_processing_stage('candidate_creating', source_type=source)
|
||||
if parse_status == 'parsed':
|
||||
return _clamp_processing_stage('candidate_creating', source_type=source)
|
||||
if parse_status == 'created':
|
||||
@@ -410,19 +425,18 @@ def _intake_source_summary(
|
||||
if isinstance(structured.get('business_summary'), dict)
|
||||
else {}
|
||||
)
|
||||
document_count = (
|
||||
db.session.query(ShippingOrderDocument.id)
|
||||
.filter(ShippingOrderDocument.intake_id == int(intake.id))
|
||||
.count()
|
||||
)
|
||||
parsed_document_count = (
|
||||
db.session.query(ShippingOrderDocument.id)
|
||||
.filter(
|
||||
ShippingOrderDocument.intake_id == int(intake.id),
|
||||
ShippingOrderDocument.parse_status == 'parsed',
|
||||
)
|
||||
.count()
|
||||
)
|
||||
document_filters = [ShippingOrderDocument.intake_id == int(intake.id)]
|
||||
# EML 正文是邮件上下文而非可处理文件。父卡数量必须与后续展开附件同源,
|
||||
# 否则会出现“3 个文件、只有 2 个(甚至 0 个)叶子”的假象。
|
||||
if str(intake.source_type or '').strip().lower() == 'eml':
|
||||
document_filters.append(ShippingOrderDocument.document_type != 'email_body')
|
||||
document_count = db.session.query(ShippingOrderDocument.id).filter(
|
||||
*document_filters,
|
||||
).count()
|
||||
parsed_document_count = db.session.query(ShippingOrderDocument.id).filter(
|
||||
*document_filters,
|
||||
ShippingOrderDocument.parse_status == 'parsed',
|
||||
).count()
|
||||
from app.models import ShippingOrderCandidate
|
||||
|
||||
candidate_count = (
|
||||
@@ -495,7 +509,15 @@ def project_intake_work_item(
|
||||
extraction_status = str(
|
||||
getattr(intake, 'order_extraction_status', None) or ''
|
||||
).strip().lower()
|
||||
if extraction_status in {'partially_completed', 'partial', 'interrupted'}:
|
||||
unit_by_document_id = _latest_intake_run_unit_outcomes(intake)
|
||||
unit_statuses = {
|
||||
str(unit.status or '').strip().lower()
|
||||
for unit in unit_by_document_id.values()
|
||||
}
|
||||
if (
|
||||
source_type != 'eml'
|
||||
and extraction_status in {'partially_completed', 'partial', 'interrupted'}
|
||||
):
|
||||
intake_status = 'waiting_human'
|
||||
intake_stage = _clamp_processing_stage(
|
||||
'waiting_review', source_type=source_type,
|
||||
@@ -515,6 +537,19 @@ def project_intake_work_item(
|
||||
intake_status = 'failed'
|
||||
elif extraction_status in {'partially_completed', 'partial', 'interrupted'}:
|
||||
intake_status = 'waiting_human'
|
||||
# EML 尚未形成 Candidate/OT 时,Run Unit 仍是附件处理的正式裁决来源。
|
||||
# 不能用 Intake 的 partial 状态把已判定的失败/复核降级为“系统处理中”。
|
||||
if source_type == 'eml':
|
||||
if 'failed' in unit_statuses:
|
||||
intake_status = 'failed'
|
||||
intake_stage = _clamp_processing_stage(
|
||||
'document_parsing', source_type=source_type,
|
||||
)
|
||||
elif 'review_required' in unit_statuses:
|
||||
intake_status = 'waiting_review'
|
||||
intake_stage = _clamp_processing_stage(
|
||||
'waiting_review', source_type=source_type,
|
||||
)
|
||||
payload = reconcile_processing_projection_facts(
|
||||
{
|
||||
'work_item_type': 'order_intake',
|
||||
@@ -537,21 +572,105 @@ def project_intake_work_item(
|
||||
},
|
||||
legacy_actions=legacy_actions,
|
||||
)
|
||||
# Intake 与 OT 同样是 Processing Projection 的输出边界。补齐用户态字段后,
|
||||
# 会话卡无需从 legacy status 再次猜测“处理中/待人工”。
|
||||
payload = apply_user_projection_fields(payload)
|
||||
# 尚未建 OT 的 EML 也必须进入统一聚合状态区,不能走「待处理材料」旁路。
|
||||
status = str(payload.get('status') or '').strip().lower()
|
||||
if extraction_status in {'partially_completed', 'partial', 'interrupted'}:
|
||||
if (
|
||||
source_type != 'eml'
|
||||
and extraction_status in {'partially_completed', 'partial', 'interrupted'}
|
||||
):
|
||||
payload['status'] = 'waiting_human'
|
||||
payload['user_status'] = 'waiting_human'
|
||||
payload['user_stage'] = 'waiting_review'
|
||||
status = 'waiting_human'
|
||||
# 尚无 OT 的 EML 也要以 ShippingOrderDocument 为唯一附件真相输出叶子;
|
||||
# 没有 Candidate 只说明订单识别尚未形成,不是前端应展示的异常或人工 Gate。
|
||||
if source_type == 'eml':
|
||||
aggregate_children = _eml_aggregate_document_children(
|
||||
intake=intake,
|
||||
order_task_children=[],
|
||||
unit_by_document_id=unit_by_document_id,
|
||||
)
|
||||
aggregate_states = [
|
||||
str(child.get('user_status') or child.get('status') or '').strip().lower()
|
||||
for child in aggregate_children
|
||||
]
|
||||
upload_states = [
|
||||
str((child.get('facts') or {}).get('upload_state') or '').strip().lower()
|
||||
for child in aggregate_children
|
||||
if isinstance(child.get('facts'), dict)
|
||||
]
|
||||
failed_count = sum(state in {'failed', 'retryable'} for state in aggregate_states)
|
||||
waiting_count = sum(state == 'waiting_human' for state in aggregate_states)
|
||||
completed_count = sum(
|
||||
state == 'completed' and upload_state == 'succeeded'
|
||||
for state, upload_state in zip(aggregate_states, upload_states)
|
||||
)
|
||||
payload['aggregate_children'] = aggregate_children
|
||||
payload['aggregate_summary'] = {
|
||||
'intake_no': str(intake.intake_no),
|
||||
'total': len(aggregate_children),
|
||||
'completed': completed_count,
|
||||
'processing': len(aggregate_children) - failed_count - waiting_count - completed_count,
|
||||
'needs_action': waiting_count,
|
||||
'failed': failed_count,
|
||||
'stages': sorted({
|
||||
str(child.get('user_stage') or child.get('stage') or '').strip()
|
||||
for child in aggregate_children
|
||||
if str(child.get('user_stage') or child.get('stage') or '').strip()
|
||||
}),
|
||||
'reason_codes': sorted({
|
||||
str((child.get('blocking_reason') or {}).get('code') or '').strip()
|
||||
for child in aggregate_children
|
||||
if isinstance(child.get('blocking_reason'), dict)
|
||||
and str((child.get('blocking_reason') or {}).get('code') or '').strip()
|
||||
}),
|
||||
'upload_states': sorted(set(upload_states)),
|
||||
}
|
||||
payload['user_group'] = (
|
||||
'failed' if status in {'failed', 'blocked'}
|
||||
else 'waiting_human' if status == 'waiting_human'
|
||||
else 'waiting_human' if status in {'waiting_human', 'waiting_review'}
|
||||
else 'processing'
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def _latest_intake_run_unit_outcomes(
|
||||
intake: ShippingOrderIntake,
|
||||
) -> dict[int, ShippingOrderProcessingUnit]:
|
||||
"""读取 Intake 最新 Run 的冻结 Unit 裁决,兼容已释放的历史 Run Intake 链接。"""
|
||||
links = (
|
||||
ShippingOrderProcessingRunIntake.query.join(
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id,
|
||||
)
|
||||
.filter(ShippingOrderProcessingRunIntake.intake_id == int(intake.id))
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.created_at.desc(),
|
||||
ShippingOrderProcessingRunIntake.created_at.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for link in links:
|
||||
run = db.session.get(ShippingOrderProcessingRun, int(link.run_id))
|
||||
plan = run.extraction_plan if run is not None else None
|
||||
if plan is None:
|
||||
continue
|
||||
units = (
|
||||
ShippingOrderProcessingUnit.query.filter(
|
||||
ShippingOrderProcessingUnit.plan_id == int(plan.id),
|
||||
ShippingOrderProcessingUnit.intake_id == int(intake.id),
|
||||
)
|
||||
.order_by(ShippingOrderProcessingUnit.position.asc())
|
||||
.all()
|
||||
)
|
||||
if units:
|
||||
return {int(unit.document_id): unit for unit in units}
|
||||
return {}
|
||||
|
||||
|
||||
def _source_type_for_run(run: ShippingOrderProcessingRun) -> str | None:
|
||||
"""
|
||||
从 Run 关联的首个 Intake 推断 source_type。
|
||||
@@ -779,9 +898,9 @@ def _order_task_source_summary(
|
||||
}
|
||||
|
||||
|
||||
def _notice_processing_status_stage(notice: ShippingNotice) -> tuple[str, str]:
|
||||
def _notice_domain_progress_stage(notice: ShippingNotice) -> tuple[str, str]:
|
||||
"""
|
||||
将正式 Notice 履约 process_status 映射为统一投影 (status, stage)。
|
||||
将正式 Notice 领域事实映射为统一进度投影 (status, stage)。
|
||||
|
||||
核心逻辑:委托领域映射 map_notice_to_processing_status_stage,投影不再私有维护规则。
|
||||
"""
|
||||
@@ -865,6 +984,8 @@ def _order_task_current_gate(
|
||||
or blocking.get('blocking_reason_code')
|
||||
),
|
||||
'attempt_no': int(blocking.get('attempt_no') or 0),
|
||||
# 外层单独透传完整摘要;current_gate 保持轻量展示形状。
|
||||
'_process_gate_summary': summary,
|
||||
}
|
||||
return {
|
||||
'gate_code': 'order_freeze_readiness',
|
||||
@@ -911,6 +1032,8 @@ def _order_task_current_gate(
|
||||
or blocking.get('blocking_reason_code')
|
||||
),
|
||||
'attempt_no': int(blocking.get('attempt_no') or 0),
|
||||
# 写动作的 execution_no / Gate version 只能来自正式摘要。
|
||||
'_process_gate_summary': summary,
|
||||
}
|
||||
|
||||
status = (
|
||||
@@ -1090,7 +1213,13 @@ def _project_order_task_work_item(
|
||||
# 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为
|
||||
# automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。
|
||||
notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else ''
|
||||
if notice_process_status in {'uploaded', 'closed', 'completed'}:
|
||||
notice_upload_status = str(getattr(notice_for_stage, 'upload_status', None) or '').strip().lower() if notice_for_stage is not None else ''
|
||||
notice_lifecycle = str(getattr(notice_for_stage, 'lifecycle_status', None) or '').strip().lower() if notice_for_stage is not None else ''
|
||||
if (
|
||||
notice_process_status in {'uploaded', 'closed', 'completed'}
|
||||
or notice_upload_status in {'uploaded', 'succeeded', 'success'}
|
||||
or notice_lifecycle in {'voided', 'archived', 'deleted'}
|
||||
):
|
||||
status = 'completed'
|
||||
stage = 'completed'
|
||||
stage_label_key = 'completed'
|
||||
@@ -1170,6 +1299,10 @@ def _project_order_task_work_item(
|
||||
and getattr(order_task, 'shipping_notice_id', None) is not None
|
||||
and notice_no_for_task is not None
|
||||
)
|
||||
current_gate = _order_task_current_gate(run, order_task)
|
||||
process_gate = None
|
||||
if isinstance(current_gate, dict):
|
||||
process_gate = current_gate.pop('_process_gate_summary', None)
|
||||
payload = reconcile_processing_projection_facts(
|
||||
{
|
||||
'work_item_type': 'order_task',
|
||||
@@ -1199,7 +1332,9 @@ def _project_order_task_work_item(
|
||||
or getattr(run, 'last_activity_at', None)
|
||||
or getattr(run, 'updated_at', None)
|
||||
) or '',
|
||||
'current_gate': _order_task_current_gate(run, order_task),
|
||||
'current_gate': current_gate,
|
||||
# Gate 执行上下文与当前轻量节点分离,前端不得从 OT / 文件名猜写入目标。
|
||||
'process_gate': process_gate,
|
||||
'available_actions': legacy_actions,
|
||||
'source_summary': _order_task_source_summary(
|
||||
run,
|
||||
@@ -1560,6 +1695,127 @@ def _eml_aggregate_user_group(
|
||||
return 'processing'
|
||||
|
||||
|
||||
def _eml_aggregate_document_children(
|
||||
*,
|
||||
intake: ShippingOrderIntake | None,
|
||||
order_task_children: list[dict[str, Any]],
|
||||
unit_by_document_id: dict[int, ShippingOrderProcessingUnit] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""以 EML Intake 的真实业务附件构建展开叶子,并仅叠加已存在 OT 的领域裁决。
|
||||
|
||||
核心逻辑:`ShippingOrderDocument` 是邮件附件集合的唯一事实;order_task 只在其
|
||||
`source_summary.document_id` 命中时提供 Gate、动作与履约状态。尚未建 OT 的附件
|
||||
保留真实解析状态,不能为方便前端展示而伪造可执行动作。
|
||||
|
||||
Args:
|
||||
intake: 当前 EML Intake;不存在时保留旧工作项,兼容纯 DTO 测试与历史数据。
|
||||
order_task_children: 同 Intake 已投影的真实 order_task 工作项。
|
||||
unit_by_document_id: 尚未形成 OT 时,最新 Run 记录的附件正式裁决。
|
||||
|
||||
Returns:
|
||||
按 Document.id 稳定排序的业务附件叶子;排除 email_body。
|
||||
"""
|
||||
if intake is None:
|
||||
return [
|
||||
{**child, 'ui_state': _processing_ui_state_from_item(child)}
|
||||
for child in order_task_children
|
||||
]
|
||||
|
||||
documents = (
|
||||
ShippingOrderDocument.query.filter(
|
||||
ShippingOrderDocument.intake_id == int(intake.id),
|
||||
ShippingOrderDocument.document_type != 'email_body',
|
||||
)
|
||||
.order_by(ShippingOrderDocument.id.asc())
|
||||
.all()
|
||||
)
|
||||
if not documents:
|
||||
return [
|
||||
{**child, 'ui_state': _processing_ui_state_from_item(child)}
|
||||
for child in order_task_children
|
||||
]
|
||||
|
||||
children_by_document_id: dict[int, dict[str, Any]] = {}
|
||||
for child in order_task_children:
|
||||
summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {}
|
||||
document_id = int(summary.get('document_id') or 0)
|
||||
if document_id > 0 and document_id not in children_by_document_id:
|
||||
children_by_document_id[document_id] = child
|
||||
|
||||
unit_by_document_id = unit_by_document_id or {}
|
||||
result: list[dict[str, Any]] = []
|
||||
for document in documents:
|
||||
existing = children_by_document_id.get(int(document.id))
|
||||
if existing is not None:
|
||||
leaf = dict(existing)
|
||||
summary = dict(existing.get('source_summary') or {})
|
||||
else:
|
||||
parse_status = str(document.parse_status or '').strip().lower()
|
||||
failed = parse_status in {'failed', 'parse_failed'}
|
||||
unit = unit_by_document_id.get(int(document.id))
|
||||
unit_status = str(unit.status or '').strip().lower() if unit is not None else ''
|
||||
review_required = unit_status == 'review_required'
|
||||
unit_failed = unit_status == 'failed'
|
||||
failure_reason_code = (
|
||||
str(unit.reason_code or unit.error_code or 'unit_failed').strip()
|
||||
if unit_failed and unit is not None else None
|
||||
)
|
||||
review_reason_code = (
|
||||
str(unit.reason_code or unit.error_code or 'unit_review_required').strip()
|
||||
if review_required and unit is not None else None
|
||||
)
|
||||
review_case = (
|
||||
ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).one_or_none()
|
||||
if review_required and unit is not None else None
|
||||
)
|
||||
run = db.session.get(ShippingOrderProcessingRun, int(review_case.run_id)) if review_case is not None else None
|
||||
leaf = {
|
||||
'work_item_type': 'document',
|
||||
'work_item_no': f'DOCUMENT:{document.id}',
|
||||
'has_formal_ot': False,
|
||||
'source_type': 'eml',
|
||||
'root_order_task_no': None,
|
||||
'shipping_notice_no': None,
|
||||
# 只有正式存在的 Review Case 才允许暴露「进入订单处理」;不能因
|
||||
# waiting_human 状态而前端猜测或补造可执行入口。
|
||||
'run_no': str(run.run_no) if run is not None else None,
|
||||
'case_no': str(review_case.case_no) if review_case is not None else None,
|
||||
'conversation_id': str(intake.conversation_id or '').strip() or None,
|
||||
'submission_no': '',
|
||||
'intake_no': str(intake.intake_no),
|
||||
'status': 'failed' if (failed or unit_failed) else 'waiting_review' if review_required else 'processing',
|
||||
'stage': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'stage_label_key': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'progress_version': int(getattr(intake, 'progress_version', None) or 1),
|
||||
'last_activity_at': _iso(document.updated_at) or _iso(intake.updated_at) or '',
|
||||
'current_gate': None,
|
||||
'available_actions': ['open_order_review'] if review_case is not None else [],
|
||||
'blocking_reason': (
|
||||
{'code': failure_reason_code, 'details': {}}
|
||||
if unit_failed else
|
||||
{'code': review_reason_code, 'details': {}}
|
||||
if review_required else None
|
||||
),
|
||||
'primary_action': {'code': 'open_order_review'} if review_case is not None else None,
|
||||
'user_status': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'running',
|
||||
'user_stage': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'user_group': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'processing',
|
||||
'facts': {'upload_state': 'not_created'},
|
||||
'child_order_tasks': [],
|
||||
}
|
||||
summary = {}
|
||||
summary.update({
|
||||
'document_id': int(document.id),
|
||||
'filename': str(document.filename or '').strip() or None,
|
||||
'document_count': 1,
|
||||
'parsed_document_count': 1 if str(document.parse_status or '').strip().lower() == 'parsed' else 0,
|
||||
})
|
||||
leaf['source_summary'] = summary
|
||||
leaf['ui_state'] = _processing_ui_state_from_item(leaf)
|
||||
result.append(leaf)
|
||||
return result
|
||||
|
||||
|
||||
def _aggregate_eml_order_task_work_items(
|
||||
work_items: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -1583,7 +1839,12 @@ def _aggregate_eml_order_task_work_items(
|
||||
or str(item.get('source_type') or '').strip().lower() != 'eml'
|
||||
or not str(item.get('intake_no') or '').strip()
|
||||
):
|
||||
passthrough.append(item)
|
||||
# [USER-STAGE] 建单前内部码不得透传到任何用户展示节点,非 EML 叶子
|
||||
# 也与 EML 聚合使用同一映射,避免左右两侧出现不同阶段名称。
|
||||
normalized = dict(item)
|
||||
if str(normalized.get('user_stage') or '').strip().lower() == 'pre_ot_stp':
|
||||
normalized['user_stage'] = 'order_creating'
|
||||
passthrough.append(normalized)
|
||||
continue
|
||||
grouped.setdefault(str(item['intake_no']).strip(), []).append(item)
|
||||
|
||||
@@ -1596,8 +1857,18 @@ def _aggregate_eml_order_task_work_items(
|
||||
|
||||
result = list(passthrough)
|
||||
for intake_no, children in grouped.items():
|
||||
states = [_state(item) for item in children]
|
||||
upload_states = [_upload_state(item) for item in children]
|
||||
# EML 的计数、状态及展开明细必须基于同一组业务附件,而不是仅基于已创建 OT。
|
||||
intake = ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none()
|
||||
aggregate_children = _eml_aggregate_document_children(
|
||||
intake=intake,
|
||||
order_task_children=children,
|
||||
unit_by_document_id=(
|
||||
_latest_intake_run_unit_outcomes(intake)
|
||||
if intake is not None else None
|
||||
),
|
||||
)
|
||||
states = [_state(item) for item in aggregate_children]
|
||||
upload_states = [_upload_state(item) for item in aggregate_children]
|
||||
failed_count = sum(state in {'failed', 'retryable'} for state in states)
|
||||
waiting_count = sum(state == 'waiting_human' for state in states)
|
||||
# 用户视角的完成必须同时满足任务完成和货代上传成功;候选已生成等中间态仍在处理中。
|
||||
@@ -1605,7 +1876,7 @@ def _aggregate_eml_order_task_work_items(
|
||||
state == 'completed' and upload_state == 'succeeded'
|
||||
for state, upload_state in zip(states, upload_states)
|
||||
)
|
||||
processing_count = len(children) - failed_count - waiting_count - completed_count
|
||||
processing_count = len(aggregate_children) - failed_count - waiting_count - completed_count
|
||||
all_uploaded = bool(upload_states) and all(state == 'succeeded' for state in upload_states)
|
||||
aggregate_group = _eml_aggregate_user_group(
|
||||
states=states,
|
||||
@@ -1641,10 +1912,17 @@ def _aggregate_eml_order_task_work_items(
|
||||
key=lambda item: str(item.get('last_activity_at') or ''),
|
||||
)
|
||||
source_summary = dict(representative.get('source_summary') or {})
|
||||
source_summary['document_count'] = sum(
|
||||
int((item.get('source_summary') or {}).get('document_count') or 0)
|
||||
for item in children
|
||||
)
|
||||
# EML 聚合卡的标题必须来自 Intake 的原始邮件资产,不能随机使用一个附件 PDF。
|
||||
if intake is not None and intake.asset_id:
|
||||
parent_asset = db.session.get(FileAsset, int(intake.asset_id))
|
||||
if parent_asset is not None:
|
||||
source_summary['filename'] = str(parent_asset.original_filename or '').strip() or source_summary.get('filename')
|
||||
if intake is not None:
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
email = structured.get('email') if isinstance(structured.get('email'), dict) else {}
|
||||
source_summary['email_subject'] = str(email.get('subject') or '').strip() or source_summary.get('email_subject')
|
||||
# 父卡文件数必须与展开叶子来自同一组真实业务附件,不能再累计 OT 的历史摘要。
|
||||
source_summary['document_count'] = len(aggregate_children)
|
||||
aggregate = dict(representative)
|
||||
aggregate['work_item_no'] = f'INTAKE:{intake_no}'
|
||||
aggregate['root_order_task_no'] = representative.get('root_order_task_no') or representative.get('work_item_no')
|
||||
@@ -1656,18 +1934,31 @@ def _aggregate_eml_order_task_work_items(
|
||||
aggregate['source_summary'] = source_summary
|
||||
aggregate['facts'] = dict(representative.get('facts') or {})
|
||||
aggregate['facts']['upload_state'] = aggregate_upload_state
|
||||
blocking_child = next(
|
||||
(
|
||||
item for item in children
|
||||
if _state(item) in {'failed', 'retryable', 'waiting_human'}
|
||||
and isinstance(item.get('blocking_reason'), dict)
|
||||
),
|
||||
# EML 父卡的状态、原因和动作必须来自同一优先级的附件。此前按输入顺序
|
||||
# 取首个阻断附件:当「待人工」排在「失败」前面时,会得到“失败状态 +
|
||||
# 待人工按钮”的矛盾组合。
|
||||
actionable_states = (
|
||||
{'failed', 'retryable'} if aggregate_group == 'failed'
|
||||
else {'waiting_human'} if aggregate_group == 'waiting_human'
|
||||
else set()
|
||||
)
|
||||
actionable_child = next(
|
||||
(item for item in children if _state(item) in actionable_states),
|
||||
None,
|
||||
)
|
||||
if blocking_child is not None:
|
||||
aggregate['blocking_reason'] = dict(blocking_child['blocking_reason'])
|
||||
aggregate['primary_action'] = blocking_child.get('primary_action')
|
||||
aggregate['aggregate_children'] = children
|
||||
if actionable_child is not None:
|
||||
reason = actionable_child.get('blocking_reason')
|
||||
aggregate['blocking_reason'] = dict(reason) if isinstance(reason, dict) else None
|
||||
primary = actionable_child.get('primary_action')
|
||||
aggregate['primary_action'] = dict(primary) if isinstance(primary, dict) else None
|
||||
aggregate['available_actions'] = list(actionable_child.get('available_actions') or [])
|
||||
else:
|
||||
# 处理中和终态不能从最近一个附件继承陈旧的人工动作。
|
||||
aggregate['blocking_reason'] = None
|
||||
aggregate['primary_action'] = None
|
||||
aggregate['available_actions'] = []
|
||||
# 子文件来自 Intake 文档真相;已有 OT 只覆盖自己的叶子裁决,未建 OT 不伪造动作。
|
||||
aggregate['aggregate_children'] = aggregate_children
|
||||
summary_stages = {
|
||||
(
|
||||
'order_creating'
|
||||
@@ -1679,7 +1970,7 @@ def _aggregate_eml_order_task_work_items(
|
||||
}
|
||||
aggregate['aggregate_summary'] = {
|
||||
'intake_no': intake_no,
|
||||
'total': len(children),
|
||||
'total': len(aggregate_children),
|
||||
'completed': completed_count,
|
||||
'processing': processing_count,
|
||||
'needs_action': waiting_count,
|
||||
@@ -1723,22 +2014,36 @@ def _conversation_task_row_from_work_item(
|
||||
source_summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
|
||||
document_count = int(source_summary.get('document_count') or 0)
|
||||
filename = str(source_summary.get('filename') or '').strip() or None
|
||||
title = filename if document_count == 1 and filename else None
|
||||
# EML 聚合根无论附件数多少都必须保留邮件标题;否则多附件邮件会退化成
|
||||
# INTAKE 编号,与批次中心的 EML 标题不一致。
|
||||
is_eml_aggregate = bool(
|
||||
str(item.get('source_type') or '').strip().lower() == 'eml'
|
||||
and str(item.get('intake_no') or '').strip()
|
||||
)
|
||||
email_subject = str(source_summary.get('email_subject') or '').strip() or None
|
||||
eml_filename = filename if filename and filename.lower().endswith('.eml') else None
|
||||
title = (
|
||||
eml_filename or email_subject
|
||||
if is_eml_aggregate
|
||||
else (filename if document_count == 1 and filename else None)
|
||||
)
|
||||
display_kind = 'single_document_task' if document_count == 1 else 'multi_document_task'
|
||||
group = _conversation_processing_group_for_work_item(item)
|
||||
# 聚合 Intake 卡仍必须透传真实 Run/Case/文档上下文;前端不能用 INTAKE 编号反查写操作目标。
|
||||
run_no = str(item.get('run_no') or '').strip() or None
|
||||
workflow_no = None
|
||||
resolved_primary: str | None = None
|
||||
# Intake 行没有真实 OT 编号;对其反查 OT/Run 必定无命中,只会放大首屏 SQL。
|
||||
is_order_task = str(item.get('work_item_type') or '').strip() == 'order_task'
|
||||
order_task = (
|
||||
ShippingOrderTask.query.filter_by(task_no=user_task_no).first()
|
||||
if user_task_no
|
||||
if is_order_task and user_task_no
|
||||
else None
|
||||
)
|
||||
run = None
|
||||
if order_task is not None and order_task.extraction_run_id:
|
||||
if is_order_task and order_task is not None and order_task.extraction_run_id:
|
||||
run = db.session.get(ShippingOrderProcessingRun, int(order_task.extraction_run_id))
|
||||
if run is None and user_task_no:
|
||||
if is_order_task and run is None and user_task_no:
|
||||
# [ROOT-3 FIX] fallback:拿代表 Run(与旧 embedded 投影同选择规则)
|
||||
run_candidate = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
@@ -1810,6 +2115,16 @@ def _conversation_task_row_from_work_item(
|
||||
'document_id': source_document_id,
|
||||
'filename': filename,
|
||||
})
|
||||
user_group = str(item.get('user_group') or '').strip().lower()
|
||||
if not user_group:
|
||||
user_status = str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
user_group = (
|
||||
'failed' if user_status in {'failed', 'retryable'}
|
||||
else 'waiting_human' if user_status in {'waiting_human', 'waiting_review'}
|
||||
else 'completed' if user_status == 'completed'
|
||||
else 'cancelled' if user_status == 'cancelled'
|
||||
else 'processing'
|
||||
)
|
||||
return {
|
||||
'user_task_no': user_task_no,
|
||||
'submission_ordinal': None,
|
||||
@@ -1842,7 +2157,193 @@ def _conversation_task_row_from_work_item(
|
||||
'primary_action': item.get('primary_action'),
|
||||
'facts': item.get('facts'),
|
||||
'aggregate_summary': item.get('aggregate_summary'),
|
||||
'user_group': item.get('user_group'),
|
||||
# [AUTHORITY] EML 子文件已在后端聚合;会话/批次 UI 直接透传,禁止前端再按
|
||||
# intake_no、状态或历史 Run 文档列表重新构建。
|
||||
'aggregate_children': item.get('aggregate_children') or [],
|
||||
'user_group': user_group,
|
||||
'ui_state': _processing_ui_state_from_item(item),
|
||||
}
|
||||
|
||||
|
||||
def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""将最终 Processing 投影封装为用户展示状态与已授权动作。
|
||||
|
||||
核心逻辑:status/stage/reason/action 均复用 work_item 已完成的领域裁决;本函数
|
||||
只做稳定 DTO 封装,禁止依据前端展示需要重新推导动作或补造按钮。
|
||||
|
||||
Args:
|
||||
item: 已经过 reconcile 与 user projection 的单项或 EML 聚合项。
|
||||
|
||||
Returns:
|
||||
可被聊天卡、批次中心和工作台直接渲染的 ui_state。
|
||||
"""
|
||||
primary_raw = item.get('primary_action')
|
||||
primary = dict(primary_raw) if isinstance(primary_raw, dict) else None
|
||||
primary_code = str((primary or {}).get('code') or '').strip()
|
||||
secondary: list[dict[str, Any]] = []
|
||||
for raw_code in item.get('available_actions') or []:
|
||||
code = str(raw_code or '').strip()
|
||||
if not code or code == primary_code:
|
||||
continue
|
||||
secondary.append({'code': code, 'enabled': True})
|
||||
return {
|
||||
'status': str(item.get('user_status') or item.get('status') or 'running'),
|
||||
'stage': str(item.get('user_stage') or item.get('stage') or ''),
|
||||
'blocking_reason': (
|
||||
dict(item['blocking_reason'])
|
||||
if isinstance(item.get('blocking_reason'), dict)
|
||||
else None
|
||||
),
|
||||
'primary_action': primary,
|
||||
'secondary_actions': secondary,
|
||||
}
|
||||
|
||||
|
||||
def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从最终用户态工作项构建批次四阶段主进度。
|
||||
|
||||
业务阶段映射和状态优先级只在后端维护;15 个技术节点仍附着在单项诊断字段,
|
||||
绝不要求前端通过 stage 索引再计算四阶段。
|
||||
"""
|
||||
ranges = (
|
||||
('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}),
|
||||
('order_review', {'order_creating', 'review_required', 'waiting_review', 'pre_ot_stp'}),
|
||||
('fulfillment_prep', {'inventory_fetching', 'inventory_matching', 'excel_generating'}),
|
||||
('upload_complete', {'freight_uploading', 'completed'}),
|
||||
)
|
||||
ranked_items = sorted(
|
||||
work_items,
|
||||
key=lambda item: {
|
||||
'failed': 0,
|
||||
'retryable': 0,
|
||||
'waiting_human': 1,
|
||||
'running': 2,
|
||||
'completed': 3,
|
||||
'cancelled': 4,
|
||||
}.get(str(item.get('user_status') or item.get('status') or '').strip().lower(), 5),
|
||||
)
|
||||
selected = ranked_items[0] if ranked_items else {}
|
||||
active_index = 0
|
||||
selected_status = str(selected.get('user_status') or selected.get('status') or '').strip().lower()
|
||||
stage = str(selected.get('user_stage') or selected.get('stage') or '').strip().lower()
|
||||
for index, (_, stage_codes) in enumerate(ranges):
|
||||
if stage in stage_codes:
|
||||
active_index = index
|
||||
break
|
||||
all_completed = bool(work_items) and all(
|
||||
str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
in {'completed', 'cancelled'}
|
||||
for item in work_items
|
||||
)
|
||||
for item in work_items:
|
||||
stage = str(item.get('user_stage') or item.get('stage') or '').strip().lower()
|
||||
for index, (_, stage_codes) in enumerate(ranges):
|
||||
if stage in stage_codes:
|
||||
break
|
||||
nodes: list[dict[str, Any]] = []
|
||||
for index, (code, _) in enumerate(ranges):
|
||||
status = 'passed' if all_completed or index < active_index else 'pending'
|
||||
if not all_completed and index == active_index:
|
||||
status = 'blocked' if selected_status in {'failed', 'retryable', 'waiting_human'} else 'running'
|
||||
nodes.append({'code': code, 'label_key': code, 'status': status})
|
||||
return nodes
|
||||
|
||||
|
||||
def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""投影本次已就绪产出物;只暴露后端确认可下载的正式 Excel。"""
|
||||
artifacts: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
for item in work_items:
|
||||
task_no = str(item.get('root_order_task_no') or '').strip()
|
||||
if not task_no or task_no in seen:
|
||||
continue
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_no).first()
|
||||
notice_id = getattr(task, 'shipping_notice_id', None) if task is not None else None
|
||||
notice = db.session.get(ShippingNotice, int(notice_id)) if notice_id else None
|
||||
filename = str(getattr(notice, 'export_file_name', None) or '').strip() if notice else ''
|
||||
path = str(getattr(notice, 'export_file_path', None) or '').strip() if notice else ''
|
||||
if not filename or not path:
|
||||
continue
|
||||
seen.add(task_no)
|
||||
artifacts.append({
|
||||
'order_task_no': task_no,
|
||||
'filename': filename,
|
||||
'type': 'xlsx',
|
||||
'status': 'ready',
|
||||
'action': {'code': 'download_excel', 'enabled': True},
|
||||
})
|
||||
return artifacts
|
||||
|
||||
|
||||
def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""裁决会话批次的用户状态与唯一主动作。
|
||||
|
||||
优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造
|
||||
人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。
|
||||
"""
|
||||
ranked = sorted(
|
||||
work_items,
|
||||
key=lambda item: {
|
||||
'failed': 0,
|
||||
'retryable': 0,
|
||||
'waiting_human': 1,
|
||||
'running': 2,
|
||||
'completed': 3,
|
||||
'cancelled': 4,
|
||||
}.get(str(item.get('user_status') or item.get('status') or '').strip().lower(), 5),
|
||||
)
|
||||
selected = ranked[0] if ranked else {}
|
||||
return {
|
||||
'status': str(selected.get('user_status') or selected.get('status') or 'running'),
|
||||
'stage': str(selected.get('user_stage') or selected.get('stage') or ''),
|
||||
'blocking_reason': (
|
||||
dict(selected['blocking_reason'])
|
||||
if isinstance(selected.get('blocking_reason'), dict)
|
||||
else None
|
||||
),
|
||||
'primary_action': (
|
||||
dict(selected['primary_action'])
|
||||
if isinstance(selected.get('primary_action'), dict)
|
||||
else None
|
||||
),
|
||||
'secondary_actions': [
|
||||
{'code': str(code), 'enabled': True}
|
||||
for code in selected.get('available_actions') or []
|
||||
if str(code).strip()
|
||||
and str(code).strip() != str((selected.get('primary_action') or {}).get('code') or '').strip()
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""按后端最终 EML 聚合结果统计业务文件,EML 容器永不计数。"""
|
||||
groups = {'failed': set(), 'waiting_human': set(), 'processing': set(), 'completed': set()}
|
||||
for item in work_items:
|
||||
group = str(item.get('user_group') or '').strip().lower()
|
||||
if group not in groups:
|
||||
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
group = 'failed' if status in {'failed', 'retryable'} else (
|
||||
'waiting_human' if status in {'waiting_human', 'waiting_review'} else (
|
||||
'completed' if status == 'completed' else 'processing'
|
||||
)
|
||||
)
|
||||
for child in item.get('aggregate_children') or [item]:
|
||||
if not isinstance(child, dict):
|
||||
continue
|
||||
summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {}
|
||||
filename = str(summary.get('filename') or '').strip().lower()
|
||||
if filename.endswith('.eml'):
|
||||
continue
|
||||
document_id = int(summary.get('document_id') or 0)
|
||||
key = f'document:{document_id}' if document_id else f'filename:{filename}'
|
||||
if filename or document_id:
|
||||
groups[group].add(key)
|
||||
return {
|
||||
'total_files': len(set().union(*groups.values())),
|
||||
'failed_files': len(groups['failed']),
|
||||
'waiting_human_files': len(groups['waiting_human']),
|
||||
'processing_files': len(groups['processing']),
|
||||
'completed_files': len(groups['completed']),
|
||||
}
|
||||
|
||||
|
||||
@@ -1870,6 +2371,7 @@ def _conversation_processing_from_work_items(
|
||||
needs_action: list[dict[str, Any]] = []
|
||||
processing: list[dict[str, Any]] = []
|
||||
completed: list[dict[str, Any]] = []
|
||||
all_rows: list[dict[str, Any]] = []
|
||||
focused = str(focused_task_no or '').strip() or None
|
||||
recent = str(recent_task_no or '').strip() or None
|
||||
|
||||
@@ -1879,6 +2381,7 @@ def _conversation_processing_from_work_items(
|
||||
if str(item.get('work_item_type') or '') not in {'order_task', 'order_intake'}:
|
||||
continue
|
||||
row = _conversation_task_row_from_work_item(item, focused_task_no=focused)
|
||||
all_rows.append(row)
|
||||
if recent and row['user_task_no'] == recent:
|
||||
row['recently_created'] = True
|
||||
bucket = row['group']
|
||||
@@ -1901,15 +2404,19 @@ def _conversation_processing_from_work_items(
|
||||
int(summary.get('document_id'))
|
||||
for item in work_items
|
||||
if isinstance(item, dict) and str(item.get('work_item_type') or '') == 'order_task'
|
||||
for summary in [item.get('source_summary')]
|
||||
for child in (item.get('aggregate_children') or [item])
|
||||
if isinstance(child, dict)
|
||||
for summary in [child.get('source_summary')]
|
||||
if isinstance(summary, dict) and int(summary.get('document_id') or 0) > 0
|
||||
}
|
||||
total_files = (
|
||||
file_counts = _batch_file_counts(work_items)
|
||||
total_files = file_counts['total_files'] or (
|
||||
len(document_ids)
|
||||
if document_ids
|
||||
else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed)
|
||||
)
|
||||
return {
|
||||
'projection_version': 1,
|
||||
'summary': {
|
||||
'total_tasks': total,
|
||||
'total_files': total_files,
|
||||
@@ -1917,6 +2424,7 @@ def _conversation_processing_from_work_items(
|
||||
'needs_action': len(needs_action),
|
||||
'completed': len(completed),
|
||||
'history': 0,
|
||||
**file_counts,
|
||||
},
|
||||
'focused_task_no': focused,
|
||||
'recent_task_no': recent,
|
||||
@@ -1924,6 +2432,17 @@ def _conversation_processing_from_work_items(
|
||||
'processing': processing,
|
||||
'completed': completed,
|
||||
'history': [],
|
||||
'status_groups': {
|
||||
'failed': [row for row in all_rows if row.get('user_group') == 'failed'],
|
||||
'waiting_human': [row for row in all_rows if row.get('user_group') == 'waiting_human'],
|
||||
'processing': [row for row in all_rows if row.get('user_group') == 'processing'],
|
||||
'completed': [row for row in all_rows if row.get('user_group') == 'completed'],
|
||||
'cancelled': [row for row in all_rows if row.get('user_group') == 'cancelled'],
|
||||
'archived': [row for row in all_rows if row.get('user_group') == 'archived'],
|
||||
},
|
||||
'four_stage_nodes': _batch_four_stage_nodes(work_items),
|
||||
'ui_state': _batch_ui_state_from_items(work_items),
|
||||
'output_artifacts': _batch_output_artifacts(work_items),
|
||||
}
|
||||
|
||||
|
||||
@@ -2001,33 +2520,8 @@ def project_conversation_processing_items(
|
||||
)
|
||||
|
||||
work_items: list[dict[str, Any]] = []
|
||||
# [LEGACY-UNIFY ROOT-2] STEP 1a:先按旧 conversation_processing_projection 的代表 Run 选择规则
|
||||
# (superseded IS NULL + 右侧可见状态白名单 + last_activity_at desc)选 latest_by_task,
|
||||
# 保证 unified 与旧 embedded 选到同一条代表 Run,杜绝 status_label / run_no 漂移。
|
||||
from app.services.shipping_notice.conversation_processing_projection import (
|
||||
_RIGHT_PANEL_RUN_STATUSES,
|
||||
)
|
||||
legacy_seed_runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.conversation_id == normalized,
|
||||
ShippingOrderProcessingRun.superseded_by_run_id.is_(None),
|
||||
ShippingOrderProcessingRun.user_task_no.isnot(None),
|
||||
ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)),
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
|
||||
ShippingOrderProcessingRun.created_at.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
latest_by_task: dict[str, ShippingOrderProcessingRun] = {}
|
||||
for seed_run in legacy_seed_runs:
|
||||
seed_task_no = str(getattr(seed_run, 'user_task_no', None) or '').strip()
|
||||
if seed_task_no and seed_task_no not in latest_by_task:
|
||||
latest_by_task[seed_task_no] = seed_run
|
||||
|
||||
# STEP 1b:会话内 OT 实体列表(保留 updated_at desc 排序,前端卡片顺序仍靠 OT 更新时间)
|
||||
# STEP 1a:会话内 OT 实体列表。代表 Run 只服务于这些真实 OT,
|
||||
# 必须先取得其编号,避免刚上传/仅 Intake 会话扫描全部历史 Run。
|
||||
order_tasks = (
|
||||
ShippingOrderTask.query.filter(
|
||||
ShippingOrderTask.user_id == int(user_id),
|
||||
@@ -2037,6 +2531,40 @@ def project_conversation_processing_items(
|
||||
.limit(200)
|
||||
.all()
|
||||
)
|
||||
order_task_nos = [
|
||||
str(task.task_no or '').strip()
|
||||
for task in order_tasks
|
||||
if str(task.task_no or '').strip()
|
||||
]
|
||||
# [LEGACY-UNIFY ROOT-2] STEP 1a:先按旧 conversation_processing_projection 的代表 Run 选择规则
|
||||
# (superseded IS NULL + 右侧可见状态白名单 + last_activity_at desc)选 latest_by_task,
|
||||
# 保证 unified 与旧 embedded 选到同一条代表 Run,杜绝 status_label / run_no 漂移。
|
||||
legacy_seed_runs: list[ShippingOrderProcessingRun] = []
|
||||
if order_task_nos:
|
||||
from app.services.shipping_notice.conversation_processing_projection import (
|
||||
_RIGHT_PANEL_RUN_STATUSES,
|
||||
)
|
||||
legacy_seed_runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.conversation_id == normalized,
|
||||
ShippingOrderProcessingRun.superseded_by_run_id.is_(None),
|
||||
ShippingOrderProcessingRun.user_task_no.in_(order_task_nos),
|
||||
ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)),
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
|
||||
ShippingOrderProcessingRun.created_at.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
latest_by_task: dict[str, ShippingOrderProcessingRun] = {}
|
||||
for seed_run in legacy_seed_runs:
|
||||
seed_task_no = str(getattr(seed_run, 'user_task_no', None) or '').strip()
|
||||
if seed_task_no and seed_task_no not in latest_by_task:
|
||||
latest_by_task[seed_task_no] = seed_run
|
||||
|
||||
# STEP 1b:会话内 OT 已在上方按更新时间加载,前端卡片顺序保持不变。
|
||||
run_ids = {
|
||||
int(task.extraction_run_id)
|
||||
for task in order_tasks
|
||||
@@ -2244,6 +2772,13 @@ def project_conversation_processing_items(
|
||||
# 同一 EML Intake 只作为一个用户工作项返回。聚合必须发生在 work_items 返回前,
|
||||
# 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。
|
||||
work_items = _aggregate_eml_order_task_work_items(work_items)
|
||||
# [AUTHORITY] 顶层 work_items 与 conversation_processing.status_groups 必须使用
|
||||
# 相同的展示 DTO。否则 direct PDF / EML 聚合根会缺 ui_state,迫使前端从旧
|
||||
# gate 或 available_actions 重新裁决状态与按钮。
|
||||
work_items = [
|
||||
{**item, 'ui_state': _processing_ui_state_from_item(item)}
|
||||
for item in work_items
|
||||
]
|
||||
|
||||
recent_override = str(recent_task_no or '').strip() or None
|
||||
rebuilt = _conversation_processing_from_work_items(
|
||||
|
||||
@@ -68,7 +68,7 @@ def _recover_auto_progress_jobs() -> int:
|
||||
)
|
||||
.filter(
|
||||
ShippingProcessExecution.status == 'active',
|
||||
ShippingNotice.process_status.notin_(('cancelled', 'canceled', 'closed', 'rejected')),
|
||||
ShippingNotice.lifecycle_status == 'active',
|
||||
).limit(50).all()
|
||||
)
|
||||
recovered = 0
|
||||
|
||||
@@ -324,7 +324,6 @@ def human_options_for_task_or_checkpoint(
|
||||
|
||||
def resolve_task_ui_state_from_fields(
|
||||
*,
|
||||
process_status: str | None,
|
||||
review_status: str | None,
|
||||
pending_human_reason: str | None,
|
||||
shipping_case_id: int | None,
|
||||
@@ -352,13 +351,16 @@ def resolve_task_ui_state_from_fields(
|
||||
return upload_req_options_for_task(upload_req_task)
|
||||
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
|
||||
|
||||
# [STEP 1] 终态:已上传、已关闭、已驳回 — 无可用按钮。
|
||||
if process_status == "uploaded":
|
||||
upload_status = str(getattr(upload_req_task, "upload_status", None) if upload_req_task is not None else "").strip().lower()
|
||||
has_export = bool(str(export_file_path or "").strip())
|
||||
|
||||
# [STEP 1] 终态:上传结果事实或生命周期处置 — 无履约写按钮。
|
||||
if upload_status in {"uploaded", "succeeded", "success"}:
|
||||
return _task_ui_state(CP_UPLOADED, [])
|
||||
if process_status == "closed":
|
||||
if upload_req_task is not None and str(getattr(upload_req_task, "lifecycle_status", "") or "").strip().lower() in {"archived", "deleted"}:
|
||||
return _task_ui_state(CP_COMPLETED, [])
|
||||
|
||||
if process_status == "rejected" or review_status == "rejected":
|
||||
if review_status == "rejected":
|
||||
return _task_ui_state(CP_REJECTED, [])
|
||||
|
||||
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
|
||||
@@ -380,30 +382,34 @@ def resolve_task_ui_state_from_fields(
|
||||
if not order_snapshot_id and has_dynamic_order_lines:
|
||||
return _task_ui_state(CP_ORDER_FREEZE, list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]))
|
||||
|
||||
# Excel 已生成即进入通知完成前的人工上传登记节点,即使历史任务未落 match_status,
|
||||
# 也不能退回“处理中”或丢失下载/登记动作。
|
||||
if has_export:
|
||||
return _task_ui_state(CP_EXPORT_READY, list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]))
|
||||
|
||||
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
|
||||
if reason == PH_RPA_EXHAUSTED:
|
||||
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
|
||||
|
||||
if (
|
||||
process_status == "parsed"
|
||||
and not review_status
|
||||
and not pending_human_reason
|
||||
and not inventory_lines_json
|
||||
):
|
||||
return _task_ui_state(CP_INVENTORY_PENDING, list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]))
|
||||
|
||||
if (
|
||||
process_status == "inventory_ready"
|
||||
inventory_lines_json
|
||||
and not review_status
|
||||
and not pending_human_reason
|
||||
and not match_status
|
||||
and has_dynamic_order_lines
|
||||
):
|
||||
return _task_ui_state(CP_READY_MATCH, list(CHECKPOINT_REGISTRY[CP_READY_MATCH]))
|
||||
|
||||
if (
|
||||
not inventory_lines_json
|
||||
and not review_status
|
||||
and not pending_human_reason
|
||||
and has_dynamic_order_lines
|
||||
):
|
||||
return _task_ui_state(CP_INVENTORY_PENDING, list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]))
|
||||
|
||||
# [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。
|
||||
if process_status == "matched":
|
||||
if export_file_path:
|
||||
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
|
||||
if has_export:
|
||||
return _task_ui_state(CP_EXPORT_READY, list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]))
|
||||
return _task_ui_state(CP_READY_EXPORT, list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]))
|
||||
|
||||
@@ -417,18 +423,16 @@ def resolve_task_ui_state_from_fields(
|
||||
)
|
||||
if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW:
|
||||
return _task_ui_state(RS_SHORTAGE_REVIEW, list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]))
|
||||
if reason == PH_UPLOAD_RPA_FAILED or process_status == "upload_failed":
|
||||
if reason == PH_UPLOAD_RPA_FAILED or upload_status == "failed":
|
||||
return _task_ui_state(CP_UPLOAD_FAILED, list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]))
|
||||
if reason == PH_UPLOAD_RESULT_UNKNOWN:
|
||||
return _task_ui_state(
|
||||
CP_UPLOAD_RESULT_UNKNOWN,
|
||||
list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
|
||||
)
|
||||
if reason == PH_RPA_PENDING or (
|
||||
process_status == "waiting_inventory" and reason == PH_RPA_PENDING
|
||||
):
|
||||
if reason == PH_RPA_PENDING:
|
||||
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
|
||||
if reason == PH_UPLOAD_RPA_PENDING or process_status == "waiting_upload":
|
||||
if reason == PH_UPLOAD_RPA_PENDING or upload_status in {"pending", "uploading"}:
|
||||
return _task_ui_state(CP_WAITING_UPLOAD, list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]))
|
||||
return _task_ui_state(None, None)
|
||||
|
||||
@@ -439,10 +443,9 @@ def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState:
|
||||
|
||||
核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库;
|
||||
upload_req 按钮仅在命中对应分支时惰性解析(兼容测试用轻量 stub)。
|
||||
履约写操作由任务处理工作台消费 action_buttons;Chat 不再作为写入口。
|
||||
履约写操作由任务处理工作台消费 ui_state.actions;Chat 不再作为写入口。
|
||||
"""
|
||||
return resolve_task_ui_state_from_fields(
|
||||
process_status=task.process_status,
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
shipping_case_id=task.shipping_case_id,
|
||||
@@ -471,12 +474,14 @@ def build_checkpoint_catalog() -> dict[str, Any]:
|
||||
checkpoints = []
|
||||
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
|
||||
buttons = build_action_buttons(list(option_ids))
|
||||
primary = next((button for button in buttons if button.get('variant') == 'primary'), None)
|
||||
secondary = [button for button in buttons if button is not primary]
|
||||
checkpoints.append(
|
||||
{
|
||||
"id": checkpoint_id,
|
||||
"checkpoint_kind": str(checkpoint_kind_for(checkpoint_id)),
|
||||
"human_options": list(option_ids),
|
||||
"action_buttons": buttons,
|
||||
"actions": {"primary": primary, "secondary": secondary},
|
||||
}
|
||||
)
|
||||
return {
|
||||
@@ -513,7 +518,6 @@ _UNSET = object()
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _TransitionSpec:
|
||||
process_status: Any = _UNSET
|
||||
review_status: Any = _UNSET
|
||||
pending_human_reason: Any = _UNSET
|
||||
clear_error_message: bool = False
|
||||
@@ -546,69 +550,56 @@ class TaskTransition(StrEnum):
|
||||
|
||||
TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
TaskTransition.PARSED: _TransitionSpec(
|
||||
process_status="parsed",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.PARSE_NEEDS_REVIEW: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
),
|
||||
TaskTransition.INVENTORY_READY: _TransitionSpec(
|
||||
process_status="inventory_ready",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.RPA_EXHAUSTED: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_RPA_EXHAUSTED,
|
||||
),
|
||||
TaskTransition.RPA_PENDING: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_RPA_PENDING,
|
||||
),
|
||||
TaskTransition.INV_UNAVAIL: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_INV_UNAVAIL,
|
||||
),
|
||||
TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
),
|
||||
TaskTransition.RSV_REQUIRED: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=RS_RSV_REQ,
|
||||
pending_human_reason=PH_RSV_REQ,
|
||||
),
|
||||
TaskTransition.MATCHED_FULFILLABLE: _TransitionSpec(
|
||||
process_status="matched",
|
||||
review_status=RS_CONFIRMED,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.MATCH_SHORTAGE: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=RS_SHORTAGE_REVIEW,
|
||||
pending_human_reason=PH_SHORTAGE,
|
||||
),
|
||||
TaskTransition.REJECTED: _TransitionSpec(
|
||||
process_status="rejected",
|
||||
review_status=RS_REJECTED,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.CLOSED: _TransitionSpec(
|
||||
process_status="closed",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.CONFIRM_PARSE: _TransitionSpec(
|
||||
process_status="parsed",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
@@ -617,27 +608,22 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
),
|
||||
TaskTransition.REMATCH_REQUESTED: _TransitionSpec(
|
||||
process_status="inventory_ready",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.WAITING_UPLOAD: _TransitionSpec(process_status="waiting_upload"),
|
||||
TaskTransition.WAITING_UPLOAD: _TransitionSpec(),
|
||||
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
|
||||
process_status="waiting_upload",
|
||||
pending_human_reason=PH_UPLOAD_RPA_PENDING,
|
||||
),
|
||||
TaskTransition.UPLOAD_FAILED: _TransitionSpec(
|
||||
process_status="upload_failed",
|
||||
pending_human_reason=PH_UPLOAD_RPA_FAILED,
|
||||
),
|
||||
TaskTransition.UPLOADED: _TransitionSpec(
|
||||
process_status="uploaded",
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
@@ -646,7 +632,7 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
|
||||
def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> None:
|
||||
"""
|
||||
将命名状态迁移写入 ShippingNotice 的 process_status / review_status / pending_human_reason。
|
||||
将命名业务事实迁移写入 ShippingNotice 的领域结果字段与 review/pending 事实。
|
||||
|
||||
核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。
|
||||
库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → inventory_fetching 等)。
|
||||
@@ -656,8 +642,6 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N
|
||||
transition: TaskTransition 枚举值。
|
||||
"""
|
||||
spec = TASK_TRANSITIONS[transition]
|
||||
if spec.process_status is not _UNSET:
|
||||
task.process_status = spec.process_status
|
||||
if spec.review_status is not _UNSET:
|
||||
task.review_status = spec.review_status
|
||||
if spec.pending_human_reason is not _UNSET:
|
||||
|
||||
@@ -78,7 +78,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将 Task 投影为固定顺序的 progress_nodes(不含进度百分比)。
|
||||
|
||||
核心逻辑:按客户确认 / 进程状态 / pending_human_reason 映射 WorkflowNodeStatus;
|
||||
核心逻辑:按客户确认 / 领域事实 / pending_human_reason 映射 WorkflowNodeStatus;
|
||||
货代上传节点在 Excel 就绪后为 manual_takeover(首期不启 RPA)。
|
||||
|
||||
Args:
|
||||
@@ -88,21 +88,28 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
|
||||
[{code, label, status}, ...];顺序与 STP_PROGRESS_NODE_DEFS 一致。
|
||||
"""
|
||||
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
|
||||
process_status = str(getattr(task, 'process_status', '') or '').strip().lower()
|
||||
pending = str(getattr(task, 'pending_human_reason', '') or '').strip().lower()
|
||||
match_status = str(getattr(task, 'match_status', '') or '').strip().lower()
|
||||
review_status = str(getattr(task, 'review_status', '') or '').strip().lower()
|
||||
has_export = bool(str(getattr(task, 'export_file_name', '') or '').strip())
|
||||
upload_status = str(getattr(task, 'upload_status', '') or '').strip().lower()
|
||||
progress_state = (
|
||||
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} else
|
||||
'upload_failed' if upload_status == 'failed' else
|
||||
'matched' if match_status or has_export else
|
||||
'inventory_ready' if getattr(task, 'inventory_lines_json', None) else
|
||||
'pending_review' if pending or review_status else 'created'
|
||||
)
|
||||
|
||||
terminal = process_status in {'uploaded', 'closed'}
|
||||
freight_ready = process_status in {
|
||||
terminal = progress_state in {'uploaded', 'closed'}
|
||||
freight_ready = progress_state in {
|
||||
'waiting_upload', 'upload_failed', 'export_ready', 'export_generated',
|
||||
} or has_export
|
||||
matched = process_status in {'matched', 'export_ready', 'export_generated', 'waiting_upload', 'upload_failed', 'uploaded', 'closed'} or has_export
|
||||
inventory_ready = matched or process_status in {'inventory_ready', 'matching'}
|
||||
inventory_preparing = process_status in {'waiting_inventory', 'parsed', 'created'}
|
||||
matched = progress_state in {'matched', 'export_ready', 'export_generated', 'waiting_upload', 'upload_failed', 'uploaded', 'closed'} or has_export
|
||||
inventory_ready = matched or progress_state in {'inventory_ready', 'matching'}
|
||||
inventory_preparing = progress_state in {'waiting_inventory', 'parsed', 'created'}
|
||||
rpa_active = pending in {'rpa_pending', 'rpa_exhausted'} or (
|
||||
process_status == 'waiting_inventory' and pending in {'rpa_pending', 'inv_unavail', 'rpa_exhausted'}
|
||||
pending in {'rpa_pending', 'inv_unavail', 'rpa_exhausted'}
|
||||
)
|
||||
match_blocked = (
|
||||
review_status == 'shortage_review'
|
||||
@@ -116,7 +123,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
|
||||
elif customer_status in {'ambiguous', 'conflicted'} or pending in {'customer_review', 'customer_ambiguous'}:
|
||||
customer_node = 'manual_takeover'
|
||||
elif customer_status in {'pending', 'unresolved', ''}:
|
||||
customer_node = 'pending' if process_status in {'created', ''} else 'manual_takeover'
|
||||
customer_node = 'pending' if progress_state in {'created', ''} else 'manual_takeover'
|
||||
else:
|
||||
customer_node = 'pending'
|
||||
|
||||
@@ -138,7 +145,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
|
||||
inventory_prepare_node = 'manual_takeover'
|
||||
inventory_match_node = 'pending'
|
||||
inventory_rpa_node = 'retrying' if pending == 'rpa_pending' else 'manual_takeover'
|
||||
elif inventory_ready and process_status in {'inventory_ready', 'matching'}:
|
||||
elif inventory_ready and progress_state in {'inventory_ready', 'matching'}:
|
||||
inventory_prepare_node = 'succeeded'
|
||||
inventory_match_node = 'running'
|
||||
inventory_rpa_node = 'succeeded'
|
||||
@@ -158,7 +165,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]:
|
||||
# [STEP 6] 货代上传:RPA 进行中为 running/retrying;否则人工接管或成功。
|
||||
if terminal:
|
||||
freight_node = 'succeeded'
|
||||
elif process_status == 'upload_failed' or pending == 'upload_rpa_failed':
|
||||
elif progress_state == 'upload_failed' or pending == 'upload_rpa_failed':
|
||||
freight_node = 'failed'
|
||||
elif pending == 'upload_rpa_pending':
|
||||
freight_node = 'running'
|
||||
|
||||
@@ -89,8 +89,6 @@ def _target_is_safe(task: ShippingNotice) -> bool:
|
||||
|
||||
核心逻辑:与历史 open_existing Reservation 回填安全边界保持一致,避免已推进任务被静默改写。
|
||||
"""
|
||||
if str(task.process_status or '').strip().lower() != 'pending_review':
|
||||
return False
|
||||
if str(task.pending_human_reason or '').strip().lower() != PH_RSV_REQ:
|
||||
return False
|
||||
if task.inventory_lines_json or task.line_results_json or task.export_file_path or task.freight_ref_no:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
services/shipping_notice/task_disposition_service.py
|
||||
|
||||
用途:集中处理发货任务的回收站、作废与归档生命周期,避免复用 process_status 的业务含义。
|
||||
用途:集中处理发货任务的回收站、作废与归档生命周期,避免混用业务阶段和生命周期。
|
||||
依赖:ShippingNotice / ShippingTaskEvent、fulfillment_audit.record_fulfillment_audit、
|
||||
SQLAlchemy 行锁、ShippingCase 生命周期事实。
|
||||
逻辑:workspace 批量处置 API 通过本模块锁定任务、重算资格;TaskEvent 与 ShippingAuditEvent
|
||||
@@ -49,7 +49,7 @@ def task_is_active(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
判断任务是否仍可触发履约副作用。
|
||||
|
||||
核心逻辑:回收站、作废和归档都不是 process_status,因此所有异步入口必须统一调用本函数。
|
||||
核心逻辑:回收站、作废和归档都不是业务阶段,因此所有异步入口必须统一调用本函数。
|
||||
|
||||
Args:
|
||||
task: 已加载的发货任务。
|
||||
@@ -112,12 +112,10 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice:
|
||||
def _has_external_fulfillment(task: ShippingNotice) -> bool:
|
||||
"""识别已提交、正在提交或已有货代回执的任务;这些任务不可在平台单方作废。"""
|
||||
upload_status = str(task.upload_status or '').strip().lower()
|
||||
process_status = str(task.process_status or '').strip().lower()
|
||||
return bool(
|
||||
task.freight_ref_no
|
||||
or task.upload_receipt_json
|
||||
or upload_status in _EXTERNAL_UPLOAD_STATUSES
|
||||
or process_status in _EXTERNAL_PROCESS_STATUSES
|
||||
)
|
||||
|
||||
|
||||
@@ -242,7 +240,7 @@ def _write_disposition_event(
|
||||
result='success',
|
||||
after={
|
||||
'lifecycle_status': getattr(task, 'lifecycle_status', None),
|
||||
'process_status': getattr(task, 'process_status', None),
|
||||
'upload_status': getattr(task, 'upload_status', None),
|
||||
},
|
||||
metadata={
|
||||
'dual_write': 'shipping_task_event',
|
||||
@@ -315,7 +313,6 @@ def move_task_to_recycle_bin(
|
||||
detail={
|
||||
'outcome': outcome,
|
||||
'reason': normalized_reason,
|
||||
'process_status_before': task.process_status,
|
||||
'lifecycle_status_after': task.lifecycle_status,
|
||||
},
|
||||
)
|
||||
@@ -346,7 +343,7 @@ def void_task(
|
||||
event_type='task_voided',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail={'reason': normalized_reason, 'process_status_before': task.process_status},
|
||||
detail={'reason': normalized_reason, 'lifecycle_status_before': 'active'},
|
||||
)
|
||||
|
||||
|
||||
@@ -356,7 +353,7 @@ def archive_task(
|
||||
actor_id: int,
|
||||
request_id: str | None = None,
|
||||
) -> None:
|
||||
"""归档任务以隐藏默认列表,不改变外部或 process_status 业务事实。"""
|
||||
"""归档任务以隐藏默认列表,不改变订单/通知领域事实。"""
|
||||
capability = task_disposition_capability(task, 'archive')
|
||||
if not capability.allowed:
|
||||
raise ConflictError(capability.reason or 'Task archive is blocked', code=capability.code or 'SHIPPING.TASK_ARCHIVE_BLOCKED')
|
||||
@@ -368,7 +365,7 @@ def archive_task(
|
||||
event_type='task_archived',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail={'process_status': task.process_status},
|
||||
detail={'lifecycle_status': task.lifecycle_status},
|
||||
)
|
||||
|
||||
|
||||
@@ -464,7 +461,6 @@ def purge_task_permanently(
|
||||
request_id=str(request_id or '').strip()[:64] or None,
|
||||
snapshot_json={
|
||||
'task_no': task.task_no,
|
||||
'process_status': task.process_status,
|
||||
'lifecycle_status': task.lifecycle_status,
|
||||
'deleted_at': task.deleted_at.isoformat() if task.deleted_at else None,
|
||||
'deletion_reason': task.deletion_reason,
|
||||
|
||||
@@ -246,14 +246,15 @@ def _decide(
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
|
||||
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
|
||||
pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower()
|
||||
# 题2B:统一直接用入参 latest_active(调用方已查逐源 Attempt);无入参时回落旧实现
|
||||
active = latest_active if isinstance(latest_active, dict) else (
|
||||
summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
|
||||
)
|
||||
|
||||
if process_status in {'completed', 'fulfilled', 'closed', 'cancelled'}:
|
||||
lifecycle_status = str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower()
|
||||
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
|
||||
if lifecycle_status in {'voided', 'archived', 'deleted'} or upload_status in {'uploaded', 'succeeded', 'success'}:
|
||||
return {
|
||||
'action': ACTION_NOOP,
|
||||
'status': STATUS_COMPLETED,
|
||||
@@ -769,7 +770,7 @@ def _result_payload(
|
||||
'task_no': task.task_no,
|
||||
'idempotent_replay': bool(idempotent_replay),
|
||||
'action': action,
|
||||
'stage': str(getattr(task, 'process_status', None) or '') or None,
|
||||
'stage': None,
|
||||
'status': status,
|
||||
'retryable': bool(retryable),
|
||||
'job_id': job_id,
|
||||
@@ -1024,7 +1025,7 @@ def _audit_decision(
|
||||
'scope': scope,
|
||||
'line_key': line_key,
|
||||
'trigger': trigger,
|
||||
'previous_stage': str(getattr(task, 'process_status', None) or '') or None,
|
||||
'previous_stage': None,
|
||||
'next_stage': result.get('stage'),
|
||||
'action': action,
|
||||
'decision_version': result.get('decision_version'),
|
||||
|
||||
@@ -18,7 +18,7 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN
|
||||
raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID')
|
||||
if not task_is_active(old):
|
||||
return
|
||||
external = bool(old.freight_ref_no or old.upload_receipt_json or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'} or old.process_status == 'uploaded')
|
||||
external = bool(old.freight_ref_no or old.upload_receipt_json or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'})
|
||||
if external:
|
||||
existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none()
|
||||
if existing is None:
|
||||
|
||||
@@ -173,10 +173,9 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
checkpoint=CP_TASK_EXISTS,
|
||||
)
|
||||
if conv_id:
|
||||
terminal_statuses = {"uploaded", "rejected", "closed"}
|
||||
existing = (
|
||||
ShippingNotice.query.filter_by(conversation_id=conv_id)
|
||||
.filter(ShippingNotice.process_status.notin_(list(terminal_statuses)))
|
||||
.filter(ShippingNotice.lifecycle_status == 'active')
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -214,7 +213,6 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
customer_resolution_method=(
|
||||
'inherited' if shipping_case.customer_id is not None else None
|
||||
),
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add(task)
|
||||
log_task_event(task, "task_created", {"source_type": task.source_type})
|
||||
@@ -624,7 +622,6 @@ def _record_formal_task_edit_audits(
|
||||
'match_status': task.match_status,
|
||||
'export_file_name': task.export_file_name,
|
||||
'order_data_version': task.order_data_version,
|
||||
'process_status': task.process_status,
|
||||
}
|
||||
field_changes = _formal_edit_field_diff_summary(
|
||||
before_header=before_header,
|
||||
@@ -815,7 +812,6 @@ def replace_task_notice(
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
task.error_message = None
|
||||
task.process_status = "created"
|
||||
_reset_notice_edit_downstream(task)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -1413,7 +1409,7 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
event_source = str(payload.get("event_source") or ("workspace_api" if actor_id else "system")).strip() or "system"
|
||||
before = task_lifecycle_audit_snapshot(task)
|
||||
|
||||
# [STEP 1] 清理阻断态并恢复到可续跑 process_status。
|
||||
# [STEP 1] 清理阻断事实并恢复到可续跑 Gate。
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
task.error_message = None
|
||||
@@ -1422,17 +1418,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
order_lines = current_line_field_values(task)
|
||||
except ConflictError:
|
||||
order_lines = []
|
||||
if not task.raw_content and not order_lines:
|
||||
task.process_status = "created"
|
||||
elif order_lines:
|
||||
if task.export_file_path:
|
||||
task.process_status = "matched"
|
||||
elif task.inventory_lines_json:
|
||||
task.process_status = "inventory_ready"
|
||||
else:
|
||||
task.process_status = "parsed"
|
||||
else:
|
||||
task.process_status = "created"
|
||||
|
||||
after = task_lifecycle_audit_snapshot(task)
|
||||
log_task_event(
|
||||
@@ -1440,7 +1425,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"task_retry_requested",
|
||||
{
|
||||
"comment": comment,
|
||||
"restored_process_status": task.process_status,
|
||||
"reason_code": "task_retry_requested",
|
||||
},
|
||||
actor_id=actor_id,
|
||||
@@ -1463,7 +1447,7 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
reason=comment or None,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata={'restored_process_status': task.process_status},
|
||||
metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)},
|
||||
source=event_source,
|
||||
)
|
||||
sync_batch_after_task_change(task)
|
||||
|
||||
@@ -496,7 +496,7 @@ def log_task_event(
|
||||
reason_code=reason_code,
|
||||
result='failure' if is_failure else 'success',
|
||||
before=safe_before,
|
||||
after=safe_after or {'status': getattr(task, 'process_status', None)},
|
||||
after=safe_after or {'phase': getattr(task, 'current_step', None)},
|
||||
metadata=meta,
|
||||
source=str(source or 'system')[:32],
|
||||
strict=True,
|
||||
@@ -570,7 +570,7 @@ def task_lifecycle_audit_snapshot(task: ShippingNotice) -> dict[str, Any]:
|
||||
可写入 before/after 的受控快照 dict(可能为空)。
|
||||
"""
|
||||
snapshot = {
|
||||
'status': getattr(task, 'process_status', None),
|
||||
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
|
||||
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
|
||||
'reason_code': getattr(task, 'pending_human_reason', None),
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/tool_response.py
|
||||
|
||||
用途:统一构建发货通知 Tool 的 JSON 响应结构。
|
||||
依赖:state_machine 中的 checkpoint/human_options/action_buttons 解析能力;ShippingProcessExecution。
|
||||
依赖:state_machine 中的 checkpoint/human_options 解析能力;ShippingProcessExecution。
|
||||
逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应;
|
||||
已绑定 ProcessExecution 的任务不再下发旧 action_buttons / next_required_action(恢复仅由 Gate 驱动)。
|
||||
已绑定 ProcessExecution 的任务不再下发旧动作字段(恢复仅由 Gate 驱动)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -85,37 +85,30 @@ def tool_response(
|
||||
"""
|
||||
构建发货通知 Tool 标准 JSON 响应。
|
||||
|
||||
核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint/human_options/action_buttons;
|
||||
核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint/human_options;
|
||||
显式 checkpoint 优先(如 parse_ok、task_exists)。
|
||||
若任务已有 ProcessExecution:不再填充 action_buttons / next_required_action,避免与 Gate 双真相。
|
||||
若任务已有 ProcessExecution:不再填充旧动作字段,避免与 Gate 双真相。
|
||||
|
||||
Args:
|
||||
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
|
||||
forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。
|
||||
extra: 需要保留在顶层的兼容字段,例如 batch_no。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
build_action_buttons,
|
||||
resolve_task_ui_state,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
|
||||
if task is not None and not task_id:
|
||||
task_id = task.task_no
|
||||
|
||||
gate_owns_recovery = _task_has_process_execution(task)
|
||||
# action_buttons 是历史调用参数,仅为兼容调用方签名;绝不进入对外响应。
|
||||
del action_buttons
|
||||
resolved_checkpoint = checkpoint
|
||||
resolved_human_options = human_options
|
||||
resolved_action_buttons = action_buttons
|
||||
|
||||
if checkpoint is None and task is not None:
|
||||
ui = resolve_task_ui_state(task)
|
||||
resolved_checkpoint = ui.checkpoint
|
||||
if human_options is None:
|
||||
resolved_human_options = ui.human_options
|
||||
# [STEP] Gate 绑定任务:忽略状态机推导的旧动作按钮。
|
||||
if not gate_owns_recovery and action_buttons is None and ui.action_buttons:
|
||||
resolved_action_buttons = ui.action_buttons
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"status": status,
|
||||
@@ -127,17 +120,7 @@ def tool_response(
|
||||
if resolved_human_options is not None:
|
||||
payload["human_options"] = resolved_human_options
|
||||
|
||||
# [STEP] ProcessExecution 存在时业务调用清零旧动作字段(含调用方显式传入)。
|
||||
if gate_owns_recovery:
|
||||
payload["action_buttons"] = []
|
||||
elif resolved_action_buttons is not None:
|
||||
payload["action_buttons"] = resolved_action_buttons
|
||||
elif resolved_human_options is not None:
|
||||
payload["action_buttons"] = build_action_buttons(resolved_human_options)
|
||||
elif resolved_checkpoint:
|
||||
buttons = action_buttons_for_checkpoint(resolved_checkpoint)
|
||||
if buttons:
|
||||
payload["action_buttons"] = buttons
|
||||
# [STEP] 业务按钮统一由 ui_state.actions 返回;Tool 响应不再生成旧 action_buttons。
|
||||
if resolved_checkpoint:
|
||||
payload["checkpoint"] = resolved_checkpoint
|
||||
if next_required_action and not gate_owns_recovery:
|
||||
@@ -148,8 +131,7 @@ def tool_response(
|
||||
payload["stop_agent_turn"] = True
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
# [STEP] extra 不得绕过 Gate 绑定任务的旧动作清零。
|
||||
# [STEP] extra 不得绕过 Gate 绑定任务的旧 next_required_action 约束。
|
||||
if gate_owns_recovery:
|
||||
payload["action_buttons"] = []
|
||||
payload.pop("next_required_action", None)
|
||||
return payload
|
||||
@@ -5,14 +5,10 @@ services/shipping_notice/ui_state.py
|
||||
依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、
|
||||
process_gate_projection(统一 Gate 用户摘要)、
|
||||
order_review_workbench_projection.apply_post_ot_gate_rules。
|
||||
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
|
||||
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
|
||||
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions,
|
||||
再补充四阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
|
||||
stp_facts、progress_nodes);
|
||||
若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留
|
||||
download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动);
|
||||
[兼容] action_buttons 为只读兼容字段:权威可恢复操作入口已统一为
|
||||
process_gate.next_action_code(如 retry_inventory_preparation),本字段仅保留供
|
||||
任务详情 / 聊天状态 / 旧入口消费,禁止再向其新增恢复动作;待确认无活跃消费者后删除。
|
||||
若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影;
|
||||
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
|
||||
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
|
||||
"""
|
||||
@@ -68,13 +64,10 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
|
||||
|
||||
|
||||
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
|
||||
{"id": "shipping-step-1", "code": "notice_submit", "label": "提交通知"},
|
||||
{"id": "shipping-step-2", "code": "parse_confirm", "label": "确认解析"},
|
||||
{"id": "shipping-step-3", "code": "inventory_prepare", "label": "获取库存"},
|
||||
{"id": "shipping-step-4", "code": "align_confirm", "label": "校验库存"},
|
||||
{"id": "shipping-step-5", "code": "match_inventory", "label": "匹配库存"},
|
||||
{"id": "shipping-step-6", "code": "generate_file", "label": "生成发货文件"},
|
||||
{"id": "shipping-step-7", "code": "upload_freight", "label": "上传货代"},
|
||||
{"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"},
|
||||
{"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"},
|
||||
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "发货准备"},
|
||||
{"id": "shipping-stage-4", "code": "upload_complete", "label": "上传完成"},
|
||||
)
|
||||
|
||||
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
|
||||
@@ -138,41 +131,157 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
|
||||
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
|
||||
}
|
||||
|
||||
# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
|
||||
BUSINESS_STAGES: tuple[dict[str, Any], ...] = (
|
||||
{"code": "intake_parse", "label": "接收解析"},
|
||||
{"code": "order_review", "label": "订单复核"},
|
||||
{"code": "fulfillment_prep", "label": "发货准备"},
|
||||
{"code": "upload_complete", "label": "上传完成"},
|
||||
)
|
||||
|
||||
_STAGE_GATE_CODES: dict[str, str] = {
|
||||
"document_materialization": "intake_parse",
|
||||
"layout_parsing": "intake_parse",
|
||||
"document_profile_routing": "intake_parse",
|
||||
"order_field_extraction": "intake_parse",
|
||||
"field_completeness": "order_review",
|
||||
"reservation_validation": "order_review",
|
||||
"customer_resolution": "order_review",
|
||||
"duplicate_detection": "order_review",
|
||||
"field_conflict_resolution": "order_review",
|
||||
"order_freeze_readiness": "order_review",
|
||||
"task_creation": "order_review",
|
||||
"inventory_source_routing": "fulfillment_prep",
|
||||
"inventory_preparation": "fulfillment_prep",
|
||||
"inventory_field_mapping": "fulfillment_prep",
|
||||
"inventory_matching": "fulfillment_prep",
|
||||
"inventory_sufficiency": "fulfillment_prep",
|
||||
"excel_readiness": "fulfillment_prep",
|
||||
"artifact_generation": "fulfillment_prep",
|
||||
"freight_upload_rpa": "upload_complete",
|
||||
"manual_upload_handoff": "upload_complete",
|
||||
}
|
||||
|
||||
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
|
||||
CP_PARSE_REVIEW: "order_review",
|
||||
CP_RSV_REQ: "order_review",
|
||||
CP_CUSTOMER_REVIEW: "order_review",
|
||||
CP_ORDER_FREEZE: "order_review",
|
||||
CP_INVENTORY_SOURCE_REVIEW: "fulfillment_prep",
|
||||
CP_INVENTORY_PENDING: "fulfillment_prep",
|
||||
CP_READY_MATCH: "fulfillment_prep",
|
||||
RS_SHORTAGE_REVIEW: "fulfillment_prep",
|
||||
CP_READY_EXPORT: "fulfillment_prep",
|
||||
CP_EXPORT_READY: "fulfillment_prep",
|
||||
CP_EXPORT_GENERATED: "fulfillment_prep",
|
||||
CP_WAITING_UPLOAD: "upload_complete",
|
||||
CP_UPLOAD_REQ: "fulfillment_prep",
|
||||
CP_UPLOAD_FAILED: "upload_complete",
|
||||
CP_UPLOAD_RESULT_UNKNOWN: "upload_complete",
|
||||
CP_UPLOADED: "upload_complete",
|
||||
CP_COMPLETED: "upload_complete",
|
||||
CP_REJECTED: "order_review",
|
||||
}
|
||||
|
||||
|
||||
def _business_stage(
|
||||
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""将内部 Gate/checkpoint 投影为四阶段;不向前端暴露底层状态枚举。"""
|
||||
gate = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
|
||||
gate_code = str(gate.get("gate_code") or "").strip()
|
||||
stage_code = _STAGE_GATE_CODES.get(gate_code) or _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ""))
|
||||
if not stage_code:
|
||||
stage_code = "upload_complete" if str(checkpoint or "") in {CP_UPLOADED, CP_COMPLETED} else "intake_parse"
|
||||
index = next((i for i, item in enumerate(BUSINESS_STAGES) if item["code"] == stage_code), 0)
|
||||
return {**BUSINESS_STAGES[index], "index": index + 1, "total": len(BUSINESS_STAGES)}
|
||||
|
||||
|
||||
def _unified_action(action: dict[str, Any], *, default_kind: str = "recovery") -> dict[str, Any]:
|
||||
"""规范 Gate/旧状态机动作,前端只渲染该统一结构。"""
|
||||
item = dict(action or {})
|
||||
code = str(item.get("code") or item.get("id") or "").strip()
|
||||
dispatch = str(item.get("dispatch") or "").strip()
|
||||
kind = str(item.get("kind") or "").strip()
|
||||
if kind in {"current_gate", ""}:
|
||||
kind = "view" if dispatch in {"navigation", "refresh"} and code.startswith("view_") else default_kind
|
||||
return {
|
||||
"code": code,
|
||||
"label": item.get("label") or item.get("label_key") or code,
|
||||
"kind": kind,
|
||||
"enabled": bool(item.get("enabled", True)),
|
||||
"requires_confirmation": bool(item.get("requires_confirmation", False)),
|
||||
"target_surface": item.get("target_surface") or ("shipping_task_workbench" if dispatch == "navigation" else None),
|
||||
"disabled_reason": item.get("disabled_reason"),
|
||||
"expected_gate_version": item.get("expected_gate_version"),
|
||||
}
|
||||
|
||||
|
||||
def _unified_actions(
|
||||
*, process_gate: dict[str, Any] | None, action_buttons: list[dict[str, str]],
|
||||
) -> dict[str, Any]:
|
||||
"""统一输出唯一主动作与次动作;动作来源优先为 Gate。"""
|
||||
gate_actions = list((process_gate or {}).get("action_presentation") or [])
|
||||
if process_gate and (process_gate.get("primary_action") or gate_actions):
|
||||
primary_raw = process_gate.get("primary_action") or gate_actions[0]
|
||||
primary_code = str((primary_raw or {}).get("code") or (primary_raw or {}).get("id") or "").strip()
|
||||
secondary_raw = [
|
||||
item for item in gate_actions
|
||||
if str((item or {}).get("code") or (item or {}).get("id") or "").strip() != primary_code
|
||||
]
|
||||
else:
|
||||
primary_raw = action_buttons[0] if action_buttons else None
|
||||
secondary_raw = action_buttons[1:] if action_buttons else []
|
||||
gate_view = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
|
||||
expected_version = gate_view.get("evaluation_version") or (process_gate or {}).get("lock_version")
|
||||
|
||||
def normalize(item: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if not item:
|
||||
return None
|
||||
result = _unified_action(item)
|
||||
if result.get("expected_gate_version") is None and expected_version is not None:
|
||||
result["expected_gate_version"] = int(expected_version)
|
||||
return result
|
||||
|
||||
primary = normalize(primary_raw)
|
||||
secondary = [normalized for item in secondary_raw if (normalized := normalize(item))]
|
||||
return {"primary": primary, "secondary": secondary}
|
||||
|
||||
|
||||
def _derive_current_step_index(task: ShippingNotice) -> int:
|
||||
"""
|
||||
根据任务字段推导七步流程当前索引。
|
||||
根据任务领域事实推导四阶段流程当前索引。
|
||||
|
||||
核心逻辑:优先使用 current_step 精准定位;缺失时按 process/review/pending 状态兜底,
|
||||
保持与前端旧 stepper 的语义一致,后续前端可直接消费后端 step。
|
||||
核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。
|
||||
"""
|
||||
current_step = str(task.current_step or "").strip()
|
||||
if current_step in _CURRENT_STEP_INDEX_MAP:
|
||||
return _CURRENT_STEP_INDEX_MAP[current_step]
|
||||
legacy_index = _CURRENT_STEP_INDEX_MAP[current_step]
|
||||
return 0 if legacy_index <= 0 else 1 if legacy_index == 1 else 3 if legacy_index >= 6 else 2
|
||||
|
||||
process_status = str(task.process_status or "").strip()
|
||||
review_status = str(task.review_status or "").strip()
|
||||
pending_reason = str(task.pending_human_reason or "").strip()
|
||||
match_status = str(task.match_status or "").strip()
|
||||
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
|
||||
has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip())
|
||||
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return 6
|
||||
if process_status in {"waiting_upload", "upload_failed"} or has_export:
|
||||
return 5
|
||||
if process_status == "matched":
|
||||
return 4
|
||||
if upload_status in {"uploaded", "succeeded", "success"} or str(getattr(task, "lifecycle_status", "") or "").lower() in {"archived", "deleted"}:
|
||||
return 3
|
||||
if upload_status in {"pending", "uploading", "failed"} or has_export:
|
||||
return 2
|
||||
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
|
||||
return 2
|
||||
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
|
||||
return 4
|
||||
if process_status == "inventory_ready" or match_status:
|
||||
return 4
|
||||
if process_status == "waiting_inventory" or pending_reason in {
|
||||
return 2
|
||||
if task.inventory_lines_json or match_status:
|
||||
return 2
|
||||
if pending_reason in {
|
||||
PH_RPA_PENDING,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_RPA_EXHAUSTED,
|
||||
}:
|
||||
return 2
|
||||
if process_status in {"parsed", "pending_review"} or review_status in {
|
||||
if review_status in {
|
||||
RS_PARSE_REVIEW,
|
||||
PH_RSV_REQ,
|
||||
} or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
|
||||
@@ -182,18 +291,17 @@ def _derive_current_step_index(task: ShippingNotice) -> int:
|
||||
|
||||
def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None) -> list[dict[str, str]]:
|
||||
"""
|
||||
构造七步流程状态。
|
||||
构造四阶段流程状态。
|
||||
|
||||
Returns:
|
||||
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
|
||||
"""
|
||||
current_index = _derive_current_step_index(task)
|
||||
process_status = str(task.process_status or "").strip()
|
||||
pending_reason = str(task.pending_human_reason or "").strip()
|
||||
checkpoint_value = str(checkpoint or "").strip()
|
||||
steps: list[dict[str, str]] = []
|
||||
for index, step in enumerate(WORKFLOW_STEPS):
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
|
||||
status = "completed"
|
||||
elif index < current_index:
|
||||
status = "completed"
|
||||
@@ -201,15 +309,17 @@ def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None)
|
||||
status = "current"
|
||||
else:
|
||||
status = "pending"
|
||||
inventory_blocked = (
|
||||
index == 2
|
||||
and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
|
||||
)
|
||||
inventory_blocked = index == 2 and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
|
||||
parse_blocked = index == 1 and (
|
||||
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED}
|
||||
or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}
|
||||
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_NOTICE_TEXT_EXTRACTION_FAILED}
|
||||
or pending_reason in {"low_confidence", PH_RSV_REQ}
|
||||
)
|
||||
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked):
|
||||
prep_blocked = index == 2 and (
|
||||
checkpoint_value in {CP_INVENTORY_SOURCE_REVIEW, RS_SHORTAGE_REVIEW}
|
||||
or pending_reason in {PH_INVENTORY_SOURCE_UNRESOLVED, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_SHORTAGE}
|
||||
)
|
||||
upload_blocked = index == 3 and str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
|
||||
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked or prep_blocked or upload_blocked):
|
||||
status = "blocked"
|
||||
steps.append({**step, "status": status})
|
||||
return steps
|
||||
@@ -584,9 +694,9 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""
|
||||
构建单票任务 UI State。
|
||||
|
||||
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/checkpoint_kind/action_buttons/summary,
|
||||
核心逻辑:所有 UI 入口只消费这里输出的 stage/checkpoint/todo/actions/summary,
|
||||
禁止 Chat、通知卡与任务中心分别推导状态;有 Execution 时附带统一 Gate 用户摘要;
|
||||
存在 current_blocking_gate 时清空 STP action_buttons,恢复仅走 process_gate。
|
||||
存在 current_blocking_gate 时只输出 Gate actions,禁止旧动作列表穿透。
|
||||
"""
|
||||
ui = resolve_task_ui_state(task)
|
||||
action_buttons = _action_buttons_for_task(task)
|
||||
@@ -622,21 +732,40 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
summary['diagnostic_hint'] = process_gate['diagnostic_hint']
|
||||
if process_gate.get('current_blocking_gate'):
|
||||
summary['allowed_actions'] = []
|
||||
stage = _business_stage(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
|
||||
actions = _unified_actions(process_gate=process_gate, action_buttons=action_buttons)
|
||||
checkpoint_payload = {
|
||||
"code": ui.checkpoint,
|
||||
"kind": str(ui.checkpoint_kind),
|
||||
"label": str(ui.checkpoint or "") or None,
|
||||
}
|
||||
reason = None
|
||||
if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"):
|
||||
reason = {
|
||||
"code": process_gate.get("blocking_reason_code"),
|
||||
"message": process_gate.get("blocking_message"),
|
||||
}
|
||||
return {
|
||||
"task_no": task.task_no,
|
||||
"batch_no": None,
|
||||
"checkpoint": ui.checkpoint,
|
||||
"stage": stage,
|
||||
"checkpoint": checkpoint_payload,
|
||||
"checkpoint_view": checkpoint_payload,
|
||||
"todo": {
|
||||
"title": summary.get("current_todo") or summary.get("title"),
|
||||
"message": summary.get("message"),
|
||||
},
|
||||
"actions": actions,
|
||||
"reason": reason,
|
||||
"lifecycle_status": task.lifecycle_status,
|
||||
"checkpoint_code": ui.checkpoint,
|
||||
"checkpoint_kind": str(ui.checkpoint_kind),
|
||||
"process_status": task.process_status,
|
||||
"review_status": task.review_status,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"match_status": task.match_status,
|
||||
"current_step": current_step,
|
||||
"steps": steps,
|
||||
"summary": summary,
|
||||
# [兼容] action_buttons 为只读兼容字段(见模块 docstring);新 UI 应消费
|
||||
# summary.process_gate.next_action_code,本字段仅作历史消费者过渡,不再扩展。
|
||||
"action_buttons": action_buttons,
|
||||
"process_gate": process_gate,
|
||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
|
||||
@@ -74,10 +74,8 @@ def _aggregate_task_upload_status(task: ShippingNotice) -> None:
|
||||
if reservations and all(item.status == 'uploaded' for item in reservations):
|
||||
task.upload_status = 'uploaded'
|
||||
task.upload_finished_at = datetime.utcnow()
|
||||
task.process_status = 'uploaded'
|
||||
elif any(item.status == 'uploaded' for item in reservations):
|
||||
task.upload_status = 'partial'
|
||||
task.process_status = 'waiting_upload'
|
||||
else:
|
||||
task.upload_status = 'pending'
|
||||
|
||||
|
||||
@@ -34,10 +34,6 @@ from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
# Fields omitted from Dify Tool `data` — Agent must not parrot these to users.
|
||||
TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset(
|
||||
{
|
||||
"process_status",
|
||||
"review_status",
|
||||
"match_status",
|
||||
"pending_human_reason",
|
||||
"error_message",
|
||||
}
|
||||
)
|
||||
@@ -99,10 +95,9 @@ def user_facing_task_stage(task: ShippingNotice) -> str:
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
|
||||
return _CHECKPOINT_LABELS[ui.checkpoint]
|
||||
process = str(task.process_status or "").strip()
|
||||
return _PROCESS_STATUS_LABELS.get(process, "处理中")
|
||||
return str(getattr(task, "lifecycle_status", None) or "active") == "active" and "处理中" or "已结束"
|
||||
|
||||
|
||||
def strip_internal_task_fields(data: dict) -> dict:
|
||||
"""从 Tool data 投影中移除 process_status 等内部字段,避免 Agent 复述给用户。"""
|
||||
"""从 Tool data 投影中移除内部执行字段,避免 Agent 复述给用户。"""
|
||||
return {k: v for k, v in data.items() if k not in TOOL_TASK_DATA_OMIT}
|
||||
@@ -22,7 +22,6 @@ from app.models import ShippingOrderProcessingRun, ShippingOrderReviewCase, Ship
|
||||
# 确认后可撤销窗口(小时);保留常量供历史引用,账本下线后无实际作用。
|
||||
CONFIRM_REVOKE_WINDOW_HOURS = 24
|
||||
|
||||
# 已进入库存匹配或更后履约阶段的 process_status。
|
||||
_INVENTORY_MATCHED_OR_LATER = frozenset({
|
||||
'matched',
|
||||
'waiting_upload',
|
||||
@@ -329,7 +328,7 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
判断任务是否已进入库存匹配或更后履约阶段。
|
||||
|
||||
核心逻辑:仅读 Task.process_status,不访问 Workflow 表。
|
||||
核心逻辑:使用库存匹配、Excel、上传等领域事实,不读取旧流程状态字段。
|
||||
|
||||
Args:
|
||||
task: 发货任务。
|
||||
@@ -337,7 +336,12 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool:
|
||||
Returns:
|
||||
True 表示已进入 matched 或更后阶段。
|
||||
"""
|
||||
return str(task.process_status or '').strip().lower() in _INVENTORY_MATCHED_OR_LATER
|
||||
match_status = str(getattr(task, 'match_status', None) or '').strip().lower()
|
||||
return match_status in {'fulfillable', 'partial', 'unfulfillable', 'matched'} or bool(
|
||||
str(getattr(task, 'export_file_path', None) or '').strip()
|
||||
or str(getattr(task, 'freight_ref_no', None) or '').strip()
|
||||
or str(getattr(task, 'upload_status', None) or '').strip()
|
||||
)
|
||||
|
||||
|
||||
def revoke_review_confirmation(**_kwargs: Any) -> None:
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
删除 ShippingNotice 旧 process_status 字段及其复合索引。
|
||||
|
||||
业务阶段已由 Gate/领域事实投影到 ui_state,旧字段不再作为兼容状态保留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'hd9j0k1l2m3n'
|
||||
down_revision = '58915a6f02ff'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_index('ix_shipping_notices_user_status', table_name='shipping_notices')
|
||||
op.drop_column('shipping_notices', 'process_status')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.add_column(
|
||||
'shipping_notices',
|
||||
sa.Column('process_status', sa.String(length=32), nullable=True),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_notices_user_status',
|
||||
'shipping_notices',
|
||||
['user_id', 'process_status'],
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
migrations/versions/he9k1l2m3n4o_add_pn_alias_to_shipping_schema.py
|
||||
|
||||
用途:将真实订单表头 PN 纳入标准 Schema 的内部料号别名。
|
||||
依赖:shipping_order_schema_versions.definition_json;不改历史 Run 冻结快照。
|
||||
逻辑:遍历 STANDARD_SHIPPING_NOTICE 的所有版本,幂等追加 PN 并重算 definition checksum。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'he9k1l2m3n4o'
|
||||
down_revision = 'hd9j0k1l2m3n'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _checksum(definition: dict[str, Any]) -> str:
|
||||
"""使用 Schema 服务相同的规范 JSON 算法计算版本校验和。"""
|
||||
payload = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为标准 Schema 各版本的 line.part_number 追加 PN 别名。"""
|
||||
bind = op.get_bind()
|
||||
rows = bind.execute(sa.text("""
|
||||
SELECT version.id, version.definition_json
|
||||
FROM shipping_order_schema_versions AS version
|
||||
JOIN shipping_order_schemas AS schema ON schema.id = version.schema_id
|
||||
WHERE schema.schema_code = 'STANDARD_SHIPPING_NOTICE'
|
||||
""")).mappings().all()
|
||||
for row in rows:
|
||||
definition = json.loads(row['definition_json']) if isinstance(row['definition_json'], str) else dict(row['definition_json'] or {})
|
||||
changed = False
|
||||
for field in definition.get('fields') or []:
|
||||
if not isinstance(field, dict) or field.get('field_code') != 'part_number' or field.get('scope') != 'line':
|
||||
continue
|
||||
aliases = [str(value).strip() for value in field.get('aliases') or [] if str(value).strip()]
|
||||
if 'PN' not in aliases:
|
||||
field['aliases'] = [*aliases, 'PN']
|
||||
changed = True
|
||||
if changed:
|
||||
bind.execute(sa.text("""
|
||||
UPDATE shipping_order_schema_versions
|
||||
SET definition_json = CAST(:definition_json AS jsonb), checksum = :checksum
|
||||
WHERE id = :version_id
|
||||
"""), {
|
||||
'version_id': int(row['id']),
|
||||
'definition_json': json.dumps(definition, ensure_ascii=False),
|
||||
'checksum': _checksum(definition),
|
||||
})
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""保持 PN 别名不可逆,避免已发布版本回滚后识别契约漂移。"""
|
||||
pass
|
||||
@@ -26,7 +26,6 @@ from app.services.shipping_notice.stp_line_inventory_match import prepare_candid
|
||||
def _task(task_no: str) -> ShippingNotice:
|
||||
task = ShippingNotice(
|
||||
task_no=task_no,
|
||||
process_status='created',
|
||||
source_type='manual',
|
||||
)
|
||||
db.session.add(task)
|
||||
|
||||
@@ -19,7 +19,7 @@ tests/services/shipping_notice/test_reconciliation_phase34_contract.py
|
||||
b) legacy_job_id=999 + is_admin=False → 422
|
||||
[P4 T7] ownership_anomaly BRANCH F:
|
||||
断言触发路径最终 outcome=ownership_anomaly_rejected 且不会脏写
|
||||
(这里只测 ValidationError 降级情形 hasattr(case,process_status)=False)。
|
||||
(这里只测 ValidationError 降级情形,Review Case 不含旧流程字段)。
|
||||
全部为 pure_unit 或 DB 无关单测,不启动 Flask/Worker,不写 DB。
|
||||
"""
|
||||
|
||||
@@ -336,7 +336,7 @@ def test_p4_t6c_legacy_job_requires_failed_or_dead(monkeypatch):
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [P4 T7] BRANCH F ownership_anomaly 422 降级(process_status 不存在)
|
||||
# [P4 T7] BRANCH F ownership_anomaly 422 降级(Review Case 不含旧流程字段)
|
||||
# ============================================================
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -363,8 +363,7 @@ def test_p4_t7_branch_f_ownership_anomaly_throws_validation(monkeypatch):
|
||||
{'step': 'L3_AMBIGUOUS', 'matched': True},
|
||||
],
|
||||
}
|
||||
# 关键:模拟 ReviewCase 没有 process_status 列 → BRANCH F 必须抛 422(而非软返回 outcome)
|
||||
assert not hasattr(case, 'process_status')
|
||||
# 关键:Review Case 不含旧流程字段 → BRANCH F 必须抛 422(而非软返回 outcome)
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
reconcile_and_progress(
|
||||
|
||||
@@ -522,7 +522,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CORRECTION-API', shipping_case_id=case.id,
|
||||
source_type='manual', process_status='parsed', customer_resolution_status='pending',
|
||||
source_type='manual', customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -111,7 +111,6 @@ def test_hybrid_executor_injects_shipping_agent_runtime_context(app, monkeypatch
|
||||
user_id=user.id,
|
||||
conversation_id='conv-shipping-start-001',
|
||||
source_type='manual',
|
||||
process_status='created',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -57,7 +57,6 @@ def _create_task_for_user(user_id: int) -> str:
|
||||
task_no="SN-20260706-ABCD1234",
|
||||
user_id=user_id,
|
||||
source_type="manual",
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -152,7 +152,7 @@ def test_waiting_inventory_maps_to_inventory_fetching_stage():
|
||||
)
|
||||
|
||||
status, stage = map_notice_to_processing_status_stage(
|
||||
SimpleNamespace(process_status='waiting_inventory', current_step=None, export_file_path=None),
|
||||
SimpleNamespace(current_step=None, export_file_path=None),
|
||||
)
|
||||
assert status == 'automating'
|
||||
assert stage == 'inventory_fetching'
|
||||
@@ -30,7 +30,7 @@ from app.services.shipping_notice.process_gate_service import ensure_execution_f
|
||||
|
||||
def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice:
|
||||
"""创建正式 Task;可选择是否补齐订单解析与冻结快照事实。"""
|
||||
task = ShippingNotice(task_no='APX-P0-3-001', process_status='created')
|
||||
task = ShippingNotice(task_no='APX-P0-3-001')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
|
||||
@@ -37,7 +37,6 @@ def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
|
||||
shipping_case_id=case.id,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -79,7 +78,6 @@ def test_revision_inherits_and_force_case_uses_next_sequence(app):
|
||||
supersedes_task_id=task.id,
|
||||
customer_resolution_status="confirmed",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending")
|
||||
db.session.add_all([revision, forced_case])
|
||||
@@ -89,7 +87,6 @@ def test_revision_inherits_and_force_case_uses_next_sequence(app):
|
||||
shipping_case_id=forced_case.id,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(forced_task)
|
||||
db.session.commit()
|
||||
@@ -157,7 +154,6 @@ def test_business_number_query_returns_latest_revision(app):
|
||||
document_version=2,
|
||||
customer_resolution_status="confirmed",
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
@@ -32,7 +32,6 @@ def _create_task(user_id: int) -> str:
|
||||
batch=batch,
|
||||
user_id=user_id,
|
||||
source_type="manual",
|
||||
process_status="matched",
|
||||
match_status="ok",
|
||||
)
|
||||
db.session.add_all([batch, task])
|
||||
|
||||
@@ -127,7 +127,7 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id,
|
||||
user_id=user.id, source_type="email_attachment", process_status="parsed",
|
||||
user_id=user.id, source_type="email_attachment",
|
||||
customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -418,13 +418,13 @@ def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
|
||||
db.session.flush()
|
||||
first = ShippingNotice(
|
||||
task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1,
|
||||
source_type="manual", process_status="parsed", customer_resolution_status="pending",
|
||||
source_type="manual", customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(first)
|
||||
db.session.flush()
|
||||
latest = ShippingNotice(
|
||||
task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2,
|
||||
supersedes_task_id=first.id, source_type="manual", process_status="waiting_upload",
|
||||
supersedes_task_id=first.id, source_type="manual", upload_status="pending",
|
||||
customer_resolution_status="pending", inventory_source_code="DSV",
|
||||
inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}],
|
||||
match_status="fulfillable", line_results_json=[{"sku": "A"}],
|
||||
@@ -457,7 +457,7 @@ def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
|
||||
assert latest.inventory_source_status is None
|
||||
assert latest.inventory_lines_json is None
|
||||
assert latest.export_file_path is None
|
||||
assert latest.process_status == "parsed"
|
||||
assert latest.source_type == "manual"
|
||||
assert get_task_by_ref(old_business_no).id == latest.id
|
||||
assert get_task_by_ref(replacement.business_no).id == latest.id
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
|
||||
@@ -476,7 +476,7 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id,
|
||||
source_type="manual", process_status="parsed", customer_resolution_status="pending",
|
||||
source_type="manual", customer_resolution_status="pending",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -487,7 +487,7 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
|
||||
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED"
|
||||
db.session.rollback()
|
||||
|
||||
task.process_status = "uploaded"
|
||||
task.upload_status = "uploaded"
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
|
||||
|
||||
@@ -47,7 +47,6 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCusto
|
||||
task_no=f'SN-GATE-{user.id}', user_id=user.id,
|
||||
shipping_case_id=case.id if case else None,
|
||||
customer_resolution_status='pending' if case else None,
|
||||
process_status='parsed',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
|
||||
inventory_source_status='user_confirmed', inventory_source_code='DSV',
|
||||
)
|
||||
@@ -119,7 +118,6 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
|
||||
revision = ShippingNotice(
|
||||
task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id,
|
||||
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
|
||||
process_status='parsed',
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
@@ -110,7 +110,7 @@ def test_inventory_preparation_reason_code_from_pending():
|
||||
assert inventory_preparation_reason_code(missing) == 'inventory_file_missing'
|
||||
|
||||
upload_failed = SimpleNamespace(
|
||||
id=None, pending_human_reason='upload_rpa_failed', process_status='upload_failed',
|
||||
id=None, pending_human_reason='upload_rpa_failed',
|
||||
)
|
||||
assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed'
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int |
|
||||
shipping_case_id=case_id,
|
||||
supersedes_task_id=supersedes_task_id,
|
||||
source_type='manual',
|
||||
process_status='created',
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -189,7 +189,6 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
|
||||
task_no='SN-PENDING-1',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=fp['fingerprint'],
|
||||
fingerprint_version=fp['version'],
|
||||
document_version=1,
|
||||
@@ -225,7 +224,6 @@ def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
|
||||
intake.duplicate_matches_json = [
|
||||
{
|
||||
'task_no': 'SN-OLD',
|
||||
'process_status': 'waiting_inventory',
|
||||
'document_version': 1,
|
||||
'match_type': 'weak_fingerprint',
|
||||
'matched_fields': ['line_digest'],
|
||||
@@ -256,7 +254,6 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
|
||||
task_no='SN-EXISTING-PO-A',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-other-file',
|
||||
@@ -379,7 +376,6 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
|
||||
task_no='SN-REFRESH-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=existing_fp['fingerprint'],
|
||||
fingerprint_version=existing_fp['version'],
|
||||
source_content_hash='hash-refresh-other',
|
||||
@@ -487,7 +483,6 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
|
||||
task_no='SN-CONTENT-EXISTING',
|
||||
user_id=dedup_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
business_fingerprint=identity['fingerprint'],
|
||||
fingerprint_version=identity['version'],
|
||||
content_fingerprint=content['fingerprint'],
|
||||
|
||||
@@ -149,7 +149,6 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
task_no='SN-CANDIDATE-EXISTING-001',
|
||||
user_id=owner.id,
|
||||
source_content_hash=asset.content_hash,
|
||||
process_status='created',
|
||||
)
|
||||
db.session.add_all([document, existing])
|
||||
db.session.flush()
|
||||
@@ -224,7 +223,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
with app.app_context():
|
||||
db.session.add(ShippingNotice(
|
||||
task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id,
|
||||
source_content_hash='candidate-api-content-hash', process_status='created',
|
||||
source_content_hash='candidate-api-content-hash',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -582,7 +581,7 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
|
||||
task_no='SN-REV-LOCK-BASE',
|
||||
user_id=shipping_user.id,
|
||||
source_type='manual',
|
||||
process_status='uploaded',
|
||||
upload_status='uploaded',
|
||||
document_version=1,
|
||||
)
|
||||
db.session.add(base)
|
||||
@@ -591,7 +590,6 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
|
||||
task_no='SN-REV-LOCK-V2',
|
||||
user_id=shipping_user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
document_version=2,
|
||||
supersedes_task_id=base.id,
|
||||
duplicate_resolution_type='revision',
|
||||
|
||||
@@ -315,7 +315,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-MANUAL-PROFILE-001', source_type='manual', process_status='waiting_inventory',
|
||||
task_no='SN-MANUAL-PROFILE-001', source_type='manual',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
@@ -332,7 +332,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
|
||||
assert result['status'] == 'ok'
|
||||
assert result['checkpoint'] == 'ready_to_match'
|
||||
assert task.process_status == 'inventory_ready'
|
||||
assert task.inventory_snapshot_id is not None
|
||||
assert task.review_status is None
|
||||
assert task.pending_human_reason is None
|
||||
snapshot = db.session.get(ShippingInventoryFile, task.inventory_snapshot_id)
|
||||
@@ -366,7 +366,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-MANUAL-DRIFT-001', source_type='manual', process_status='waiting_inventory',
|
||||
task_no='SN-MANUAL-DRIFT-001', source_type='manual',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
@@ -564,7 +564,6 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CONFIRM-SOURCE-RPA",
|
||||
source_type="pdf",
|
||||
process_status="pending_review",
|
||||
current_step="step2_parse_confirm",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
ship_to="Dublin",
|
||||
@@ -589,7 +588,7 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
|
||||
db.session.refresh(task)
|
||||
assert result["status"] == "ok"
|
||||
assert "库存源已确认" in result["message"]
|
||||
assert task.process_status == "parsed"
|
||||
assert task.pending_human_reason is None
|
||||
assert task.pending_human_reason is None
|
||||
assert task.error_message is None
|
||||
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
|
||||
@@ -615,7 +614,6 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-RUNNO",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
@@ -643,7 +641,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["success_count"] == 1
|
||||
assert task.process_status == "inventory_ready"
|
||||
assert task.inventory_snapshot_id is not None
|
||||
|
||||
|
||||
def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
@@ -660,7 +658,6 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-FAIL-TASK",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
@@ -686,7 +683,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["failed_count"] == 1
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.error_message
|
||||
failed_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
@@ -704,7 +701,6 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-FAIL-NO-IDENT",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
@@ -815,7 +811,6 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-NO-IDENT",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
@@ -838,7 +833,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["failed_count"] == 1
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
|
||||
|
||||
def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkeypatch):
|
||||
@@ -883,7 +878,6 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REUSE-INGEST-FAIL",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
@@ -910,7 +904,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
assert snap_after.snapshot_status == "ready"
|
||||
assert Path(snap_after.storage_path).is_file()
|
||||
assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
|
||||
|
||||
def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
|
||||
@@ -999,14 +993,12 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
task_a = ShippingNotice(
|
||||
task_no="SN-BATCH-OK",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
task_b = ShippingNotice(
|
||||
task_no="SN-BATCH-FAIL",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
|
||||
)
|
||||
@@ -1018,7 +1010,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
seed_rpa_inventory_trigger(task_b, run_no=run_no)
|
||||
db.session.add_all([task_a, task_b])
|
||||
db.session.commit()
|
||||
before_b_status = task_b.process_status
|
||||
before_b_status = task_b.pending_human_reason
|
||||
|
||||
result = rpa_report_inventory_batch({
|
||||
"run_no": run_no,
|
||||
@@ -1045,7 +1037,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
assert result["failed_count"] == 1
|
||||
assert task_a.inventory_rpa_consumed_run_no == run_no
|
||||
assert task_b.inventory_rpa_consumed_run_no is None
|
||||
assert task_b.process_status == before_b_status
|
||||
assert task_b.pending_human_reason == before_b_status
|
||||
|
||||
|
||||
def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, monkeypatch):
|
||||
@@ -1065,14 +1057,12 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
task_ok = ShippingNotice(
|
||||
task_no="SN-SHARED-OK",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
task_fail = ShippingNotice(
|
||||
task_no="SN-SHARED-FAIL",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
|
||||
)
|
||||
@@ -1154,7 +1144,6 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
|
||||
task = ShippingNotice(
|
||||
task_no="SN-POST-COMMIT-FAIL",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
@@ -1199,7 +1188,6 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
|
||||
task = ShippingNotice(
|
||||
task_no="SN-PROMOTE-FAIL-REBUILD",
|
||||
source_type="manual",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
@@ -1237,7 +1225,6 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REPAIR-ATTACH",
|
||||
source_type="manual",
|
||||
process_status="inventory_ready",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
@@ -1395,7 +1382,6 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REPAIR-REJECT",
|
||||
source_type="manual",
|
||||
process_status="inventory_ready",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
|
||||
@@ -630,7 +630,7 @@ def test_order_field_display_uses_current_catalog_sequence(app):
|
||||
).all():
|
||||
field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
|
||||
task = ShippingNotice(
|
||||
task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual',
|
||||
task_no='SN-ORDER-DISPLAY-SEQUENCE', source_type='manual',
|
||||
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}],
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -908,7 +908,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
|
||||
task_no='SN-ORDER-EXISTING-001',
|
||||
user_id=int(user.id),
|
||||
source_type='manual',
|
||||
process_status='waiting_inventory',
|
||||
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
@@ -926,7 +926,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
|
||||
'content_fingerprint_version': 'shipping-content-v4',
|
||||
'matches': [{
|
||||
'task_no': existing.task_no,
|
||||
'process_status': existing.process_status,
|
||||
'match_status': existing.match_status,
|
||||
'match_type': 'business_fingerprint',
|
||||
}],
|
||||
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
|
||||
@@ -1046,7 +1046,6 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
error_message='解析失败:未识别到 Reservation ID',
|
||||
@@ -1099,7 +1098,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
|
||||
assert values['part_number'] == 'P123456'
|
||||
assert values['qty'] == 24
|
||||
assert values['reservation_id'] == '1000140351'
|
||||
assert existing.process_status == 'pending_review'
|
||||
assert existing.review_status == 'rsv_req'
|
||||
assert existing.pending_human_reason == 'low_confidence'
|
||||
assert 'process_field_gate' not in (existing.step_payload_json or {})
|
||||
assert existing.error_message is None
|
||||
@@ -1198,7 +1197,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
|
||||
@pytest.mark.parametrize(
|
||||
'task_overrides',
|
||||
[
|
||||
{'process_status': 'waiting_inventory'},
|
||||
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]},
|
||||
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]},
|
||||
{'match_status': 'matched'},
|
||||
{'export_file_path': '/tmp/shipment.xlsx'},
|
||||
@@ -1211,7 +1210,6 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
|
||||
'task_no': f"SN-RSV-BACKFILL-NEG-{next(iter(task_overrides))}",
|
||||
'po_number': '4510038672',
|
||||
'source_type': 'manual',
|
||||
'process_status': 'pending_review',
|
||||
'review_status': 'rsv_req',
|
||||
'pending_human_reason': 'rsv_req',
|
||||
'lines_json': [{'part_number': 'P123456', 'qty': 24}],
|
||||
@@ -1256,7 +1254,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
task_no='SN-RSV-BACKFILL-CONFLICT',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
|
||||
@@ -1265,7 +1262,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[
|
||||
@@ -1277,7 +1273,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
|
||||
task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
@@ -1327,7 +1322,6 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
|
||||
task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE',
|
||||
po_number='4510038672',
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
|
||||
@@ -1369,7 +1363,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
process_status='waiting_inventory',
|
||||
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
)
|
||||
db.session.add(existing)
|
||||
@@ -1400,7 +1394,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
|
||||
assert result['pending_count'] == 0
|
||||
assert candidate.consumed_task_id == int(existing.id)
|
||||
assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}]
|
||||
assert existing.process_status == 'waiting_inventory'
|
||||
assert existing.inventory_lines_json == [{'part_number': 'P123456', 'qty': 24}]
|
||||
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
|
||||
|
||||
|
||||
@@ -1444,7 +1438,6 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
|
||||
source_type='manual',
|
||||
source_content_hash=document.content_hash,
|
||||
po_number='4510038672',
|
||||
process_status='pending_review',
|
||||
review_status='rsv_req',
|
||||
pending_human_reason='rsv_req',
|
||||
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
|
||||
|
||||
@@ -24,12 +24,37 @@ from app.services.shipping_notice.query_service import (
|
||||
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
|
||||
|
||||
|
||||
def test_chat_match_result_payload_uses_unified_actions_only():
|
||||
"""Chat 匹配结果不得再把旧 action_buttons 作为按钮来源。"""
|
||||
from app.services.shipping_notice.chat_action_handlers import _match_result_payload
|
||||
|
||||
payload = _match_result_payload(
|
||||
"SN-ACTIONS-ONLY",
|
||||
{
|
||||
"data": {
|
||||
"match_status": "shortage",
|
||||
"line_results": [],
|
||||
"shortage": {"lines": []},
|
||||
},
|
||||
"action_buttons": [{"id": "legacy_retry"}],
|
||||
"ui_state": {
|
||||
"actions": {
|
||||
"primary": {"code": "open_shortage_review", "enabled": True},
|
||||
"secondary": [],
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert payload["actions"]["primary"]["code"] == "open_shortage_review"
|
||||
assert "action_buttons" not in payload
|
||||
|
||||
|
||||
def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
|
||||
"""task_no 与数字主键均应能解析到同一任务。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-TEST-QUERY-001",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
)
|
||||
from app import db
|
||||
@@ -47,28 +72,28 @@ def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
|
||||
|
||||
|
||||
def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
|
||||
"""库存缺口筛选应读取复核状态,而不是要求不存在的 process_status。"""
|
||||
"""库存缺口筛选应读取领域事实和复核状态。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
shortage = ShippingNotice(
|
||||
task_no="SN-FILTER-SHORTAGE",
|
||||
process_status="pending_review",
|
||||
review_status="shortage_review",
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
user_id=999999,
|
||||
)
|
||||
ordinary = ShippingNotice(
|
||||
task_no="SN-FILTER-PARSE",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
user_id=2,
|
||||
)
|
||||
db.session.add_all([shortage, ordinary])
|
||||
db.session.commit()
|
||||
|
||||
rows = list_tasks_for_user(999999, process_status="shortage_review")
|
||||
rows = list_tasks_for_user(999999)
|
||||
|
||||
assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"]
|
||||
|
||||
@@ -79,7 +104,7 @@ def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", process_status="created", source_type="manual")
|
||||
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", source_type="manual")
|
||||
for index in range(1, 6)
|
||||
])
|
||||
db.session.commit()
|
||||
@@ -105,13 +130,13 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-1", process_status="created", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-2", process_status="created", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-3", process_status="uploaded", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"),
|
||||
ShippingNotice(task_no="SN-PAGE-FILTER-3", upload_status="uploaded", source_type="manual"),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
result = list_tasks_page_for_user(999999, process_status="created", page=1, page_size=10)
|
||||
result = list_tasks_page_for_user(999999, lifecycle_status="active", page=1, page_size=10)
|
||||
|
||||
# 关键断言:uploaded 任务既不在 items 中,也不计入总数。
|
||||
assert result["total"] == 2
|
||||
@@ -123,12 +148,11 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
|
||||
def test_task_export_error_message_distinct_for_missing_path(app):
|
||||
"""无导出路径与磁盘缺失应返回不同错误文案。"""
|
||||
with app.app_context():
|
||||
empty = ShippingNotice(task_no="SN-NO-EXPORT", process_status="created", source_type="manual")
|
||||
empty = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual")
|
||||
assert task_export_error_message(empty) == "export file not found"
|
||||
|
||||
missing = ShippingNotice(
|
||||
task_no="SN-MISSING-FILE",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/not-a-real-shipping-export.xlsx",
|
||||
)
|
||||
@@ -140,7 +164,6 @@ def test_task_projection_tool_strips_internal_fields(app):
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-PROJ-TOOL",
|
||||
process_status="waiting_inventory",
|
||||
review_status="align_review",
|
||||
match_status="pending",
|
||||
pending_human_reason="rpa_pending",
|
||||
@@ -161,12 +184,11 @@ def test_task_projection_internal_keeps_status_fields(app):
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-PROJ-INT",
|
||||
process_status="parsed",
|
||||
review_status="parse_review",
|
||||
source_type="manual",
|
||||
)
|
||||
data = serialize_task(task, TaskProjection.TOOL_INTERNAL)
|
||||
assert data["process_status"] == "parsed"
|
||||
assert "review_status" in data
|
||||
assert data["review_status"] == "parse_review"
|
||||
|
||||
|
||||
@@ -177,7 +199,6 @@ def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CONV-1",
|
||||
conversation_id="conv-abc",
|
||||
process_status="parsed",
|
||||
source_type="manual",
|
||||
)
|
||||
from app import db
|
||||
@@ -202,13 +223,11 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
|
||||
ShippingNotice(
|
||||
task_no="SN-CONV-MULTI-1",
|
||||
conversation_id="conv-multi",
|
||||
process_status="parsed",
|
||||
source_type="manual",
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-CONV-MULTI-2",
|
||||
conversation_id="conv-multi",
|
||||
process_status="pending_review",
|
||||
source_type="manual",
|
||||
),
|
||||
]
|
||||
@@ -232,13 +251,11 @@ def test_task_can_handle_only_creator(app):
|
||||
|
||||
owned = ShippingNotice(
|
||||
task_no="SN-HANDLE-OWN",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=42,
|
||||
)
|
||||
orphan = ShippingNotice(
|
||||
task_no="SN-HANDLE-ORPHAN",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=None,
|
||||
)
|
||||
@@ -263,13 +280,11 @@ def test_get_task_for_user_rejects_null_owner(app):
|
||||
|
||||
orphan = ShippingNotice(
|
||||
task_no="SN-NULL-OWNER",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=None,
|
||||
)
|
||||
owned = ShippingNotice(
|
||||
task_no="SN-OWNED",
|
||||
process_status="created",
|
||||
source_type="manual",
|
||||
user_id=7,
|
||||
)
|
||||
@@ -291,7 +306,6 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-ENRICH-1",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -306,7 +320,7 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
assert data["todo_category"] == "review"
|
||||
assert data["created_by"] == 11
|
||||
assert data["can_handle"] is True
|
||||
assert data["ui_state"]["checkpoint"] == "parse_review"
|
||||
assert data["ui_state"]["checkpoint"]["code"] == "parse_review"
|
||||
assert data["artifact_summary"]["export_file_name"] == "a.xlsx"
|
||||
|
||||
no_viewer = serialize_task_summary(task)
|
||||
@@ -322,7 +336,6 @@ def test_list_my_todos_and_count_buckets(app):
|
||||
owner = 55
|
||||
review = ShippingNotice(
|
||||
task_no="SN-TODO-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -330,7 +343,6 @@ def test_list_my_todos_and_count_buckets(app):
|
||||
)
|
||||
upload = ShippingNotice(
|
||||
task_no="SN-TODO-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
export_file_path="/tmp/u.xlsx",
|
||||
@@ -338,13 +350,12 @@ def test_list_my_todos_and_count_buckets(app):
|
||||
)
|
||||
done = ShippingNotice(
|
||||
task_no="SN-TODO-DONE",
|
||||
process_status="uploaded",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
upload_status="uploaded",
|
||||
)
|
||||
other = ShippingNotice(
|
||||
task_no="SN-TODO-OTHER",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -422,7 +433,7 @@ def test_list_my_todos_includes_orphan_parse_failed_intake(app):
|
||||
"""
|
||||
未建 OT 且解析失败的 Intake 须进入 pending,并暴露 conversation 深链字段。
|
||||
|
||||
断言:item_kind=order_intake;todo_category=intake_parse;count.pending 计入。
|
||||
断言:item_kind=order_intake;todo_category=intake_parse;count.pending 计入。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
@@ -527,7 +538,6 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app):
|
||||
tasks = [
|
||||
ShippingNotice(
|
||||
task_no=f"SN-TODO-PAGE-{index:04d}",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -578,7 +588,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
fixtures = [
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -586,7 +595,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
export_file_path="/tmp/lw.xlsx",
|
||||
@@ -595,7 +603,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-SHORTAGE",
|
||||
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
|
||||
process_status="parsed",
|
||||
review_status="shortage_review",
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
@@ -603,13 +610,12 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-DONE",
|
||||
process_status="uploaded",
|
||||
upload_status="uploaded",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
ShippingNotice(
|
||||
task_no="SN-LW-PROGRESS",
|
||||
process_status="parsed",
|
||||
source_type="manual",
|
||||
user_id=owner,
|
||||
),
|
||||
@@ -620,7 +626,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
category_expr = _task_todo_category_sql_expr()
|
||||
for task in fixtures:
|
||||
row = SimpleNamespace(
|
||||
process_status=task.process_status,
|
||||
review_status=task.review_status,
|
||||
pending_human_reason=task.pending_human_reason,
|
||||
shipping_case_id=task.shipping_case_id,
|
||||
@@ -630,6 +635,7 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
|
||||
inventory_lines_json=task.inventory_lines_json,
|
||||
match_status=task.match_status,
|
||||
export_file_path=task.export_file_path,
|
||||
upload_status=task.upload_status,
|
||||
)
|
||||
expected = task_todo_category(task)
|
||||
# 轻量路径与 ORM 路径同分类。
|
||||
|
||||
@@ -18,6 +18,7 @@ from app.services.shipping_notice.constants import (
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
build_checkpoint_catalog,
|
||||
checkpoint_kind_for,
|
||||
resolve_task_ui_state,
|
||||
validate_registry,
|
||||
@@ -29,6 +30,13 @@ def test_validate_registry_has_no_errors() -> None:
|
||||
assert validate_registry() == []
|
||||
|
||||
|
||||
def test_checkpoint_catalog_uses_unified_actions_shape() -> None:
|
||||
"""检查点目录也不得继续暴露旧 action_buttons 字段。"""
|
||||
catalog = build_checkpoint_catalog()
|
||||
assert all("action_buttons" not in item for item in catalog["checkpoints"])
|
||||
assert all(set(item["actions"]) == {"primary", "secondary"} for item in catalog["checkpoints"])
|
||||
|
||||
|
||||
def test_checkpoint_kinds_for_stp_stop_points() -> None:
|
||||
"""STP 关键检查点 kind:导出 Excel 后待人工上传登记 / 解析复核 / 已上传终态。"""
|
||||
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
@@ -41,7 +49,6 @@ def test_resolve_task_ui_state_parse_review(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-PARSE",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
@@ -56,7 +63,6 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-EXPORT",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
@@ -68,11 +74,11 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_uploaded_complete(app) -> None:
|
||||
"""process_status=uploaded 应为 complete。"""
|
||||
"""upload_status=uploaded 应为 complete。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-SM-UPLOADED",
|
||||
process_status="uploaded",
|
||||
upload_status="uploaded",
|
||||
source_type="manual",
|
||||
)
|
||||
ui = resolve_task_ui_state(task)
|
||||
@@ -83,7 +89,7 @@ def test_resolve_task_ui_state_uploaded_complete(app) -> None:
|
||||
def test_resolve_with_mocked_simple_namespace_attributes() -> None:
|
||||
"""无 DB 会话时可用简易命名空间验证 uploaded 终态分支。"""
|
||||
task = SimpleNamespace(
|
||||
process_status="uploaded",
|
||||
upload_status="uploaded",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
shipping_case_id=None,
|
||||
|
||||
@@ -38,7 +38,6 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app)
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-WAIT-UPLOAD",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/stp-export.xlsx",
|
||||
export_file_name="stp-export.xlsx",
|
||||
@@ -62,7 +61,6 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-MUST-HUMAN",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
@@ -85,7 +83,6 @@ def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-RPA-ON",
|
||||
process_status="matched",
|
||||
match_status="fulfillable",
|
||||
source_type="manual",
|
||||
line_results_json=[{"line_status": "ok"}],
|
||||
@@ -127,7 +124,6 @@ def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-NO-RPA",
|
||||
process_status="matched",
|
||||
match_status="fulfillable",
|
||||
source_type="manual",
|
||||
line_results_json=[{"line_status": "ok"}],
|
||||
@@ -166,7 +162,6 @@ def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-MANUAL-CFM",
|
||||
process_status="waiting_upload",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
@@ -235,7 +230,6 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-CLOSE-FAIL",
|
||||
process_status="waiting_upload",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
@@ -301,17 +295,21 @@ def test_export_ready_ui_state_entry_is_task_workbench(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-STP-ENTRY",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/x.xlsx",
|
||||
export_file_name="x.xlsx",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["checkpoint"]["kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
button_ids = [b.get("id") for b in (state.get("action_buttons") or [])]
|
||||
button_ids = [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
assert "mark_manual_uploaded" in button_ids
|
||||
assert "download_excel" in button_ids
|
||||
assert "action_buttons" not in state
|
||||
|
||||
|
||||
def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
@@ -339,7 +337,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
mine = ShippingNotice(
|
||||
task_no="SN-STP-OWN",
|
||||
user_id=owner.id,
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
@@ -347,7 +344,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
waiting_upload = ShippingNotice(
|
||||
task_no="SN-STP-UPLOAD",
|
||||
user_id=owner.id,
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/own.xlsx",
|
||||
export_file_name="own.xlsx",
|
||||
@@ -355,7 +351,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
other = ShippingNotice(
|
||||
task_no="SN-STP-OTHER",
|
||||
user_id=admin.id,
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
|
||||
@@ -304,7 +304,6 @@ def test_confirm_inventory_source_route_returns_json(app, client):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-HTTP-CONFIRM-SRC",
|
||||
source_type="manual",
|
||||
process_status="pending_review",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
ship_to="Dublin",
|
||||
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
|
||||
@@ -339,7 +338,7 @@ def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision):
|
||||
"""已启用库存站点不得通过任务决策重开旧列映射路径。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual", process_status="waiting_inventory")
|
||||
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual")
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -363,7 +362,6 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
|
||||
task = ShippingNotice(
|
||||
task_no="SN-REUPLOAD-INVENTORY",
|
||||
source_type="manual",
|
||||
process_status="matched",
|
||||
inventory_lines_json=[{"part_number": "A001", "available_qty": 10}],
|
||||
match_status="fulfillable",
|
||||
line_results_json=[{"part_number": "A001"}],
|
||||
@@ -403,7 +401,7 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
|
||||
task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
|
||||
assert link.is_active is False
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.match_status is None
|
||||
@@ -519,7 +517,6 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "inventory_ready"
|
||||
task.review_status = None
|
||||
task.pending_human_reason = "inv_unavail"
|
||||
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}]
|
||||
@@ -542,7 +539,6 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
|
||||
}
|
||||
}
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
task.process_status = "parsed"
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice import decision_workflow
|
||||
@@ -555,7 +551,7 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.review_status is None
|
||||
assert task.inventory_lines_json is None
|
||||
@@ -601,7 +597,6 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_PENDING
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
@@ -628,7 +623,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert result["status"] == "needs_human"
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
|
||||
@@ -665,7 +660,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_EXHAUSTED
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
@@ -677,7 +671,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
}
|
||||
}
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
task.process_status = "parsed"
|
||||
base_time = datetime.utcnow() - timedelta(minutes=5)
|
||||
for idx in range(3):
|
||||
db.session.add(
|
||||
@@ -700,7 +693,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.pending_human_reason == "rpa_pending"
|
||||
assert task.error_message is None
|
||||
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
|
||||
@@ -749,7 +742,6 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
|
||||
task = ShippingNotice.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_PENDING
|
||||
task.step_payload_json = {
|
||||
"rpa_inventory_source": {
|
||||
@@ -777,7 +769,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
|
||||
assert task is not None
|
||||
assert result["started"] == 1
|
||||
assert result["skipped"] == 0
|
||||
assert task.process_status == "waiting_inventory"
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
|
||||
@@ -791,7 +783,6 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
|
||||
first = ShippingNotice(
|
||||
task_no="SN-MULTI-CONV-001",
|
||||
conversation_id="conv-test-multi",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -800,7 +791,6 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
|
||||
second = ShippingNotice(
|
||||
task_no="SN-MULTI-CONV-002",
|
||||
conversation_id="conv-test-multi",
|
||||
process_status="pending_review",
|
||||
review_status="parse_review",
|
||||
pending_human_reason="low_confidence",
|
||||
source_type="manual",
|
||||
@@ -835,8 +825,8 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
|
||||
.order_by(ShippingNotice.task_no)
|
||||
.all()
|
||||
}
|
||||
assert rows["SN-MULTI-CONV-001"].process_status == "pending_review"
|
||||
assert rows["SN-MULTI-CONV-002"].process_status == "pending_review"
|
||||
assert rows["SN-MULTI-CONV-001"].review_status == "parse_review"
|
||||
assert rows["SN-MULTI-CONV-002"].review_status == "parse_review"
|
||||
|
||||
|
||||
def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch):
|
||||
@@ -892,10 +882,10 @@ def test_chat_actions_empty_when_task_rejected(app):
|
||||
task = ShippingNotice(
|
||||
task_no="SN-20260101-TEST0001",
|
||||
source_type="manual",
|
||||
process_status="rejected",
|
||||
review_status="rejected",
|
||||
)
|
||||
assert human_options_for_task(task) == []
|
||||
ui_state = build_task_ui_state(task)
|
||||
assert ui_state["checkpoint"] == "rejected"
|
||||
assert ui_state["action_buttons"] == []
|
||||
assert ui_state["checkpoint"]["code"] == "rejected"
|
||||
assert ui_state["actions"] == {"primary": None, "secondary": []}
|
||||
assert "action_buttons" not in ui_state
|
||||
@@ -14,6 +14,7 @@ from app.services.shipping_notice.constants import (
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
from app.services.shipping_notice.ui_state import _unified_actions
|
||||
|
||||
|
||||
_REQUIRED_SUMMARY_KEYS = {
|
||||
@@ -31,29 +32,95 @@ _REQUIRED_SUMMARY_KEYS = {
|
||||
}
|
||||
|
||||
|
||||
def test_unified_actions_deduplicates_gate_primary_action():
|
||||
"""Gate 主动作同时出现在展示列表时,只能渲染一次。"""
|
||||
state = _unified_actions(
|
||||
process_gate={
|
||||
"primary_action": {"code": "open_order_review", "label": "进入订单复核"},
|
||||
"action_presentation": [
|
||||
{"code": "open_order_review", "label": "进入订单复核"},
|
||||
{"code": "view_audit", "label": "查看审计", "kind": "view"},
|
||||
],
|
||||
},
|
||||
action_buttons=[],
|
||||
)
|
||||
|
||||
assert state["primary"]["code"] == "open_order_review"
|
||||
assert [item["code"] for item in state["secondary"]] == ["view_audit"]
|
||||
|
||||
|
||||
def test_unified_action_shape_contains_gate_version_fields():
|
||||
"""统一动作 DTO 必须包含前端提交所需的版本与禁用字段。"""
|
||||
state = _unified_actions(
|
||||
process_gate={
|
||||
"lock_version": 7,
|
||||
"current_gate": {"evaluation_version": 3},
|
||||
"primary_action": {"code": "retry_inventory_matching", "label": "重新匹配"},
|
||||
"action_presentation": [],
|
||||
},
|
||||
action_buttons=[],
|
||||
)
|
||||
assert state["primary"]["expected_gate_version"] == 3
|
||||
assert "disabled_reason" in state["primary"]
|
||||
|
||||
|
||||
def test_build_task_ui_state_summary_has_required_keys(app) -> None:
|
||||
"""summary 必须包含 STP 可解释字段全集。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-SUMMARY",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
|
||||
assert state["checkpoint"] == CP_PARSE_REVIEW
|
||||
assert state["checkpoint"]["code"] == CP_PARSE_REVIEW
|
||||
assert state["checkpoint_kind"] == "must_human"
|
||||
assert "stp_facts" not in state["summary"]
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None:
|
||||
"""业务 UI 只消费四阶段与后端统一 actions,不再要求前端解释旧七步。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STAGE-ACTIONS",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["stage"]["code"] == "order_review"
|
||||
assert state["stage"]["index"] == 2
|
||||
assert state["stage"]["total"] == 4
|
||||
assert state["actions"]["primary"] is not None
|
||||
assert state["actions"]["primary"]["code"] == "confirm"
|
||||
assert all("code" in item and "kind" in item for item in state["actions"]["secondary"])
|
||||
|
||||
|
||||
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
|
||||
"""库存匹配/上传结果只映射四个业务阶段。"""
|
||||
with app.app_context():
|
||||
fulfillment = ShippingNotice(
|
||||
task_no="SN-UI-FULFILLMENT",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_lines_json=[{"part_number": "P-1"}],
|
||||
)
|
||||
upload = ShippingNotice(
|
||||
task_no="SN-UI-UPLOAD",
|
||||
source_type="manual",
|
||||
upload_status="uploaded",
|
||||
)
|
||||
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
|
||||
assert build_task_ui_state(upload)["stage"]["code"] == "upload_complete"
|
||||
|
||||
|
||||
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
"""解析复核应进入人工复核工作台。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-REVIEW",
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
@@ -67,18 +134,21 @@ def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-EXPORT",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint"] == CP_EXPORT_READY
|
||||
assert state["checkpoint"]["code"] == CP_EXPORT_READY
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
assert state["summary"].get("pause_reason_code") == "wait_manual_upload"
|
||||
assert "登记凭据" in str(state["summary"].get("pause_reason") or "")
|
||||
button_ids = [b.get("id") for b in (state.get("action_buttons") or [])]
|
||||
button_ids = [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
assert "download_excel" in button_ids
|
||||
assert "mark_manual_uploaded" in button_ids
|
||||
|
||||
@@ -88,7 +158,6 @@ def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-FROZEN",
|
||||
process_status="waiting_inventory",
|
||||
source_type="manual",
|
||||
inventory_source_status="candidates_frozen",
|
||||
inventory_source_method="stp_build_freeze",
|
||||
@@ -111,7 +180,6 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-LINES",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="resolved",
|
||||
@@ -150,7 +218,6 @@ def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STP-MULTI",
|
||||
process_status="matched",
|
||||
review_status=RS_SHORTAGE_REVIEW,
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
|
||||
@@ -19,7 +19,6 @@ def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None:
|
||||
"""
|
||||
task = ShippingNotice(
|
||||
task_no="SN-TEST-RPA-PENDING",
|
||||
process_status="waiting_inventory",
|
||||
pending_human_reason=PH_RPA_PENDING,
|
||||
)
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.jobs.handlers.shipping_order_extraction import (
|
||||
_pending_snapshot_batches,
|
||||
_process_unit_with_retries,
|
||||
_result_requires_review,
|
||||
_should_activate_planned_batches,
|
||||
_should_expand_after_wave,
|
||||
_units_for_batch,
|
||||
)
|
||||
@@ -474,6 +475,12 @@ def test_should_expand_after_wave_when_current_wave_needs_more_evidence():
|
||||
) is False
|
||||
|
||||
|
||||
def test_planned_attachment_batch_activates_without_sibling_field_gate():
|
||||
"""计划内附件必须独立消费,首轮字段完整与否不得阻止下一批激活。"""
|
||||
assert _should_activate_planned_batches(pending_batches=[2]) is True
|
||||
assert _should_activate_planned_batches(pending_batches=[]) is False
|
||||
|
||||
|
||||
def test_auto_freeze_blocked_task_requires_run_review():
|
||||
"""自动冻结的 Task 级门禁拒绝必须把 Run 收口为需人工处理,而非 completed。"""
|
||||
assert _result_requires_review(
|
||||
|
||||
@@ -47,7 +47,11 @@ from app.services.shipping_notice.order_review_draft_service import (
|
||||
set_line_inventory_candidates,
|
||||
validate_draft,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence, list_case_evidence
|
||||
from app.services.shipping_notice.order_review_evidence_service import (
|
||||
get_case_email_evidence_text,
|
||||
get_case_evidence,
|
||||
list_case_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_disposition_service import (
|
||||
create_manual_draft,
|
||||
finalize_document_reparse,
|
||||
@@ -520,6 +524,76 @@ def test_review_evidence_is_case_scoped_and_omits_untrusted_bbox(app):
|
||||
assert 'storage_key' not in str(payload)
|
||||
|
||||
|
||||
def test_review_evidence_keeps_the_email_document_identity(app):
|
||||
"""邮件正文 Observation 必须返回其 EML Document,前端不得回退打开主 PDF。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, pdf_document = _seed_run_input(suffix='REVIEW-EMAIL-EVIDENCE')
|
||||
email_document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='body',
|
||||
filename='review-email.eml',
|
||||
content_hash='e' * 64,
|
||||
classification='email_body',
|
||||
parse_status='parsed',
|
||||
extracted_text='Reservation Number: 33894',
|
||||
)
|
||||
db.session.add(email_document)
|
||||
db.session.commit()
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [
|
||||
{'field_id': 'reservation', 'observations': [{
|
||||
'value': '33894',
|
||||
'quote': 'Reservation Number: 33894',
|
||||
'document_id': email_document.id,
|
||||
'source_type': 'email_body_table',
|
||||
}]},
|
||||
], 'lines': []}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
item = list_case_evidence(user_id=user.id, case_no=case.case_no)['items'][0]
|
||||
|
||||
assert item['document_id'] == email_document.id
|
||||
assert item['document_type'] == 'email_body'
|
||||
assert item['source_type'] == 'email_body_table'
|
||||
|
||||
|
||||
def test_review_email_evidence_preview_reads_only_the_sibling_email_body(app):
|
||||
"""邮件证据预览只允许当前 Case 同 Intake 的已解析正文,不能读取 PDF 或原始附件。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _pdf_document = _seed_run_input(suffix='REVIEW-EMAIL-PREVIEW')
|
||||
email_document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='body',
|
||||
filename='review-email.eml',
|
||||
content_hash='f' * 64,
|
||||
classification='email_body',
|
||||
parse_status='parsed',
|
||||
extracted_text='Reservation Number: 33894',
|
||||
)
|
||||
db.session.add(email_document)
|
||||
db.session.commit()
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
preview = get_case_email_evidence_text(
|
||||
user_id=user.id,
|
||||
case_no=case.case_no,
|
||||
document_id=email_document.id,
|
||||
)
|
||||
|
||||
assert preview == {
|
||||
'document_id': email_document.id,
|
||||
'document_type': 'email_body',
|
||||
'filename': 'review-email.eml',
|
||||
'text': 'Reservation Number: 33894',
|
||||
}
|
||||
|
||||
|
||||
def test_review_evidence_normalizes_frozen_layout_coordinates(app):
|
||||
"""坐标订单字段必须以冻结页尺寸换算为前端可绘制 bbox,并准确切换证据页。"""
|
||||
with app.app_context():
|
||||
@@ -981,7 +1055,7 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
|
||||
# 关键断言:复核确认建单必须同步冻结,库存/RPA 不可消费可变解析结果。
|
||||
assert task.order_snapshot_id is not None
|
||||
# 关键断言:复核确认已完成解析确认,不能把新任务重新放回低置信度解析复核。
|
||||
assert task.process_status == 'parsed'
|
||||
assert task.customer_resolution_status == 'confirmed'
|
||||
assert task.review_status is None
|
||||
assert task.pending_human_reason is None
|
||||
# 关键断言:人工 Candidate 必须保留受控字段证据,建单后资格不能反向变成 evidence_missing。
|
||||
@@ -1500,14 +1574,12 @@ def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app):
|
||||
user_id=user.id,
|
||||
source_type='review_confirmation',
|
||||
source_content_hash=content_hash,
|
||||
process_status='parsed',
|
||||
)
|
||||
other = ShippingNotice(
|
||||
task_no='SN-WAVE-OTHER',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
source_content_hash=content_hash,
|
||||
process_status='parsed',
|
||||
)
|
||||
db.session.add_all([own, other])
|
||||
db.session.commit()
|
||||
|
||||
@@ -310,8 +310,45 @@ def test_user_gate_summary_repairs_stale_rpa_action_for_gate19(app, monkeypatch)
|
||||
assert summary['owner_type'] == 'human'
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch):
|
||||
"""Gate 20 人工交接也可显式重试 RPA,且不依赖 AUTO_UPLOAD 配置。"""
|
||||
def test_inventory_preparation_keeps_controlled_upload_as_a_secondary_gate_action(app, monkeypatch):
|
||||
"""库存准备以重试为主动作,受控上传仅保留给 Gate 工作台。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-INVENTORY-1', status='blocked',
|
||||
current_gate_code='inventory_preparation',
|
||||
primary_next_action_code='upload_inventory_file',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-INVENTORY-1', 'status': 'blocked',
|
||||
'primary_next_action_code': 'upload_inventory_file',
|
||||
'responsible_party': 'worker', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'next_action_code': 'upload_inventory_file', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['next_action_code'] == 'retry_inventory_preparation'
|
||||
assert summary['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
assert summary['allowed_actions'] == [
|
||||
'retry_inventory_preparation',
|
||||
'upload_inventory_file',
|
||||
]
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_manual_gate_evidence_confirmation(app, monkeypatch):
|
||||
"""Gate 20 只下发受控凭据登记,不把 RPA 重试伪装为人工上传确认。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
@@ -338,10 +375,75 @@ def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch):
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
assert summary['next_action_code'] == 'retry_freight_upload_rpa'
|
||||
assert summary['next_action_code'] == 'mark_manual_uploaded'
|
||||
assert summary['allowed_actions'] == ['mark_manual_uploaded']
|
||||
assert summary['owner_type'] == 'human'
|
||||
|
||||
|
||||
def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action(app, monkeypatch):
|
||||
"""Gate 20 必须引导受控凭据登记,不得再重生待办或直接声称上传完成。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-MANUAL-CONFIRM', status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
primary_next_action_code='regenerate_manual_upload_todo',
|
||||
responsible_party='owner', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-MANUAL-CONFIRM', 'status': 'blocked',
|
||||
'primary_next_action_code': 'regenerate_manual_upload_todo',
|
||||
'responsible_party': 'owner', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'manual_upload_pending',
|
||||
'next_action_code': 'regenerate_manual_upload_todo', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['next_action_code'] == 'mark_manual_uploaded'
|
||||
assert summary['allowed_actions'] == ['mark_manual_uploaded']
|
||||
|
||||
|
||||
def test_inventory_source_gate_summary_does_not_expose_line_decision_side_actions(app, monkeypatch):
|
||||
"""规则建议和保留人工决定只属于订单复核明细行,不能泄漏到 Gate 卡。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-ROUTING', status='blocked',
|
||||
current_gate_code='inventory_source_routing', primary_next_action_code='open_inventory_source_review',
|
||||
responsible_party='owner', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-ROUTING', 'status': 'blocked',
|
||||
'primary_next_action_code': 'open_inventory_source_review',
|
||||
'responsible_party': 'owner', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_source_routing', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'no_inventory_source_candidates',
|
||||
'next_action_code': 'open_inventory_source_review', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['allowed_actions'] == ['open_inventory_source_review']
|
||||
|
||||
|
||||
def test_process_gate_dependency_integrity_and_excel_only_scope():
|
||||
"""
|
||||
校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。
|
||||
|
||||
@@ -116,7 +116,6 @@ def _seed_workflow_version(
|
||||
|
||||
source_type='manual',
|
||||
|
||||
process_status='waiting_inventory',
|
||||
|
||||
)
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ def test_rpa_attempt_status_updates_its_bound_preparation_source(app):
|
||||
sync_preparation_source_from_rpa_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-LINEAGE-1', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-PREP-LINEAGE-1')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
preparation = create_inventory_preparation_round(
|
||||
@@ -87,7 +87,7 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-IDENTITY', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-IDENTITY')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id), actor_type='system')
|
||||
@@ -120,7 +120,7 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-MISSING', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-MISSING')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS'])
|
||||
@@ -134,7 +134,11 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa')
|
||||
assert result.pending_source_codes == []
|
||||
assert result.failed_source_codes == ['DBS']
|
||||
attempt = per_source_rpa_service._latest_attempt(task.task_no, 'DBS')
|
||||
# 读取真实数据库记录,避免被用于构造场景的 monkeypatch 查询函数遮蔽。
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
attempt = ShippingTaskInventoryRpaAttempt.query.filter_by(
|
||||
task_no=task.task_no, source_code='DBS', attempt_no=1,
|
||||
).one()
|
||||
assert attempt.status == 'failed'
|
||||
assert attempt.error_code == 'trigger_not_written'
|
||||
|
||||
@@ -146,7 +150,7 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey
|
||||
from app.services.shipping_notice import process_gate_executor
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-PREP-FREEZE-OPERATOR', process_status='waiting_inventory',
|
||||
task_no='SN-PREP-FREEZE-OPERATOR',
|
||||
order_snapshot_id=None, order_data_version=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -195,7 +199,7 @@ def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
)
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
current = ShippingInventoryCandidateSet(
|
||||
@@ -254,7 +258,7 @@ def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app,
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -305,7 +309,7 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SN-2026-001', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-2026-001')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
captured = {}
|
||||
@@ -341,7 +345,7 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -408,7 +412,7 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RPA-FAILED-GATE', process_status='waiting_inventory',
|
||||
task_no='SN-RPA-FAILED-GATE',
|
||||
pending_human_reason='rpa_exhausted', error_message='RPA export failed',
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -430,6 +434,7 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
idempotency_key='shipping-auto-progress:rpa-failed-poll',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation'},
|
||||
)
|
||||
@@ -448,7 +453,9 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
assert gate.status == 'blocked_manual'
|
||||
assert gate.blocking_reason_code == 'inventory_rpa_exhausted'
|
||||
db.session.refresh(execution)
|
||||
assert execution.status == 'blocked'
|
||||
# Gate 已进入可人工恢复的 blocked_manual;Execution 仍保持 active,
|
||||
# 由当前业务阶段/Gate 投影表达阻断,不再回写旧的 execution blocked 状态。
|
||||
assert execution.status == 'active'
|
||||
|
||||
|
||||
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
|
||||
@@ -469,8 +476,9 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNFORMALPREPLINEAGE',
|
||||
process_status='waiting_inventory',
|
||||
inventory_source_code='DBS',
|
||||
# 该用例从 inventory_preparation Gate 开始,前置订单复核/冻结事实必须显式存在。
|
||||
order_snapshot_id=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -544,7 +552,6 @@ def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app):
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNSTARTCUSTOMERPENDING',
|
||||
process_status='created',
|
||||
current_order_extraction_id=101,
|
||||
order_snapshot_id=201,
|
||||
customer_resolution_status='pending',
|
||||
@@ -568,7 +575,6 @@ def test_formal_start_gate_stops_at_field_conflict_before_inventory(app):
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNSTARTFIELDCONFLICT',
|
||||
process_status='created',
|
||||
current_order_extraction_id=101,
|
||||
order_snapshot_id=201,
|
||||
customer_resolution_status='confirmed',
|
||||
@@ -594,7 +600,7 @@ def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app):
|
||||
from app.services.shipping_notice.auto_progress_controller import supersede_auto_progress_for_candidate_refreeze
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version, queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
old_candidate = ShippingInventoryCandidateSet(
|
||||
@@ -641,7 +647,7 @@ def test_legacy_workspace_forwarding_audit_is_structured(app):
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint
|
||||
|
||||
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
@@ -670,7 +676,7 @@ def test_apx_runtime_audit_is_read_only_and_counts_active_states(app):
|
||||
from app.models import Job, ShippingNotice, ShippingProcessExecution
|
||||
from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state
|
||||
|
||||
task = ShippingNotice(task_no='SN-APX-AUDIT', process_status='waiting_inventory')
|
||||
task = ShippingNotice(task_no='SN-APX-AUDIT')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
active = ShippingProcessExecution(
|
||||
@@ -950,7 +956,7 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch)
|
||||
'freeze_mode': 'manual',
|
||||
}
|
||||
assert task.order_snapshot_id == 901
|
||||
assert result['outcome'] == 'waiting_external'
|
||||
assert result['outcome'] == 'blocked_retryable'
|
||||
|
||||
|
||||
def test_manual_business_block_is_a_successful_attempt(app):
|
||||
|
||||
@@ -200,17 +200,17 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
)
|
||||
|
||||
uploaded = SimpleNamespace(
|
||||
process_status='uploaded', current_step='', upload_status='', export_file_path=None,
|
||||
current_step='', upload_status='uploaded', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
process_status='waiting_upload', current_step='', upload_status='', export_file_path='/x.xlsx',
|
||||
current_step='', upload_status='pending', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
matching = SimpleNamespace(
|
||||
process_status='matching', current_step='step5_match', upload_status='', export_file_path=None,
|
||||
current_step='step5_match', upload_status='', match_status='matching', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
|
||||
|
||||
@@ -224,7 +224,6 @@ def test_map_notice_unknown_status_fail_closed():
|
||||
)
|
||||
|
||||
unknown = SimpleNamespace(
|
||||
process_status='totally_unknown_xyz',
|
||||
current_step='',
|
||||
upload_status='',
|
||||
export_file_path=None,
|
||||
@@ -288,7 +287,37 @@ def test_inventory_snapshot_missing_projects_retryable_inventory_action():
|
||||
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['retryable'] is True
|
||||
assert payload['primary_action']['code'] == 'retry'
|
||||
# 主动作必须保留 Gate 原始码,前端才能提交到正确的库存准备执行器。
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_preparation',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
'parameters': {},
|
||||
}
|
||||
|
||||
|
||||
def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action():
|
||||
"""库存文件缺失必须保留 Gate 重试,不得降级为线外上传或空按钮。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'processing',
|
||||
'stage': 'inventory_fetching',
|
||||
'source_type': 'order_task',
|
||||
'shipping_notice_no': 'SN-1',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_manual',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
},
|
||||
'available_actions': ['retry_inventory_preparation'],
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'waiting_human'
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_preparation',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
'parameters': {},
|
||||
}
|
||||
assert payload['available_actions'] == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_waiting_human_reconcile_action_uses_projected_available_actions():
|
||||
|
||||
@@ -10,15 +10,22 @@ backend/tests/test_shipping_processing_projection_stage4.py
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
import re
|
||||
from io import BytesIO
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import event
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderIntake, ShippingOrderSubmission, User
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderSubmission,
|
||||
User,
|
||||
)
|
||||
from app.services.file_assets.service import upload_file_asset
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
@@ -143,8 +150,339 @@ def test_aggregate_single_eml_attachment_is_still_an_intake_card() -> None:
|
||||
assert result[0]['aggregate_summary']['processing'] == 1
|
||||
|
||||
|
||||
def test_aggregate_maps_internal_pre_ot_stp_stage_for_user_summary() -> None:
|
||||
"""建单前 STP 失败的内部阶段码不得泄漏到会话聚合摘要。"""
|
||||
def test_eml_aggregate_projects_every_business_document_when_some_lack_order_tasks(app) -> None:
|
||||
"""EML 父卡的数量与展开叶子同源,未建 OT 附件只展示真实解析态且不伪造动作。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
_user, _agent, _session, intake, first_document = _seed_run_input(
|
||||
suffix='EML-LEAF-COVERAGE',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
second_document = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
document_type='attachment',
|
||||
attachment_key='eml-unassigned.pdf',
|
||||
filename='eml-unassigned.pdf',
|
||||
content_hash='c' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
order_extraction_status='not_started',
|
||||
)
|
||||
# 邮件正文不是可展开的业务附件,不能被混进 EML 文件数。
|
||||
email_body = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
document_type='email_body',
|
||||
attachment_key='__email_body__',
|
||||
filename='mail.eml',
|
||||
content_hash='d' * 64,
|
||||
classification='unknown',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add_all([second_document, email_body])
|
||||
db.session.commit()
|
||||
|
||||
existing_task = {
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': 'OT-EML-ASSIGNED',
|
||||
'source_type': 'eml',
|
||||
'intake_no': intake.intake_no,
|
||||
'root_order_task_no': 'OT-EML-ASSIGNED',
|
||||
'last_activity_at': '2026-08-14T00:00:00Z',
|
||||
'status': 'processing',
|
||||
'stage': 'candidate_creating',
|
||||
'user_status': 'running',
|
||||
'user_stage': 'candidate_creating',
|
||||
'current_gate': None,
|
||||
'available_actions': [],
|
||||
'primary_action': None,
|
||||
'blocking_reason': None,
|
||||
'facts': {'upload_state': 'not_created'},
|
||||
'source_summary': {
|
||||
'document_id': int(first_document.id),
|
||||
'document_count': 1,
|
||||
'filename': first_document.filename,
|
||||
'parsed_document_count': 1,
|
||||
'candidate_count': 0,
|
||||
},
|
||||
'child_order_tasks': [],
|
||||
}
|
||||
|
||||
aggregate = _aggregate_eml_order_task_work_items([existing_task])[0]
|
||||
|
||||
children = aggregate['aggregate_children']
|
||||
assert aggregate['source_summary']['document_count'] == 2
|
||||
assert aggregate['aggregate_summary'] == {
|
||||
'intake_no': intake.intake_no,
|
||||
'total': 2,
|
||||
'completed': 0,
|
||||
'processing': 2,
|
||||
'needs_action': 0,
|
||||
'failed': 0,
|
||||
'stages': ['candidate_creating'],
|
||||
'reason_codes': [],
|
||||
'upload_states': ['not_created'],
|
||||
}
|
||||
assert {child['source_summary']['document_id'] for child in children} == {
|
||||
int(first_document.id), int(second_document.id),
|
||||
}
|
||||
unassigned = next(
|
||||
child for child in children
|
||||
if child['source_summary']['document_id'] == int(second_document.id)
|
||||
)
|
||||
assert unassigned['work_item_no'] == f'DOCUMENT:{second_document.id}'
|
||||
assert unassigned['user_status'] == 'running'
|
||||
assert unassigned['ui_state']['primary_action'] is None
|
||||
assert unassigned['available_actions'] == []
|
||||
|
||||
|
||||
def test_eml_order_intake_projects_business_documents_without_candidates_as_processing(app) -> None:
|
||||
"""无 OT/候选的 EML 仍完整展示业务附件;未形成候选不是异常或待人工门禁。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
_user, _agent, _session, intake, pdf = _seed_run_input(
|
||||
suffix='EML-INTAKE-LEAF-COVERAGE',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
intake.parse_status = 'parsed'
|
||||
intake.order_extraction_status = 'partially_completed'
|
||||
spreadsheet = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
document_type='attachment',
|
||||
attachment_key='po-info.xlsx',
|
||||
filename='po-info.xlsx',
|
||||
content_hash='e' * 64,
|
||||
classification='unknown',
|
||||
parse_status='empty',
|
||||
order_extraction_status='not_started',
|
||||
)
|
||||
email_body = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
document_type='email_body',
|
||||
attachment_key='__email_body__',
|
||||
filename='mail.eml',
|
||||
content_hash='f' * 64,
|
||||
classification='email_context',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add_all([spreadsheet, email_body])
|
||||
db.session.commit()
|
||||
|
||||
item = project_intake_work_item(intake)
|
||||
|
||||
assert item['work_item_type'] == 'order_intake'
|
||||
assert item['source_summary']['document_count'] == 2
|
||||
assert item['source_summary']['parsed_document_count'] == 1
|
||||
assert item['status'] == 'processing'
|
||||
assert item['user_status'] == 'running'
|
||||
assert item['user_group'] == 'processing'
|
||||
assert item['aggregate_summary'] == {
|
||||
'intake_no': intake.intake_no,
|
||||
'total': 2,
|
||||
'completed': 0,
|
||||
'processing': 2,
|
||||
'needs_action': 0,
|
||||
'failed': 0,
|
||||
'stages': ['candidate_creating'],
|
||||
'reason_codes': [],
|
||||
'upload_states': ['not_created'],
|
||||
}
|
||||
assert {child['source_summary']['document_id'] for child in item['aggregate_children']} == {
|
||||
int(pdf.id), int(spreadsheet.id),
|
||||
}
|
||||
assert all(child['available_actions'] == [] for child in item['aggregate_children'])
|
||||
|
||||
|
||||
def test_eml_order_intake_uses_latest_run_unit_review_outcome_without_order_tasks(app) -> None:
|
||||
"""EML 无 Candidate/OT 时仍以最新 Run Unit 的正式 review_required 裁决为准。"""
|
||||
with app.app_context():
|
||||
from datetime import datetime
|
||||
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, pdf = _seed_run_input(
|
||||
suffix='EML-UNIT-REVIEW-PROJECTION',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
spreadsheet = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
document_type='attachment',
|
||||
attachment_key='po-info.xlsx',
|
||||
filename='po-info.xlsx',
|
||||
content_hash='u' * 64,
|
||||
classification='unknown',
|
||||
parse_status='empty',
|
||||
order_extraction_status='not_started',
|
||||
)
|
||||
db.session.add(spreadsheet)
|
||||
db.session.flush()
|
||||
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
assert {int(unit.document_id) for unit in run.extraction_plan.units} == {
|
||||
int(pdf.id), int(spreadsheet.id),
|
||||
}
|
||||
for unit in run.extraction_plan.units:
|
||||
unit.status = 'review_required'
|
||||
unit.reason_code = 'profile_ambiguous'
|
||||
run.status = 'review_required'
|
||||
run.phase = 'review_required'
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = datetime.utcnow()
|
||||
intake.order_extraction_status = 'partially_completed'
|
||||
# 真实历史 Run 可能已释放 Intake 链接,投影仍必须能读取其最终裁决。
|
||||
run.intakes[0].released_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
item = project_intake_work_item(intake)
|
||||
|
||||
assert item['status'] == 'waiting_review'
|
||||
assert item['user_status'] == 'waiting_human'
|
||||
assert item['user_group'] == 'waiting_human'
|
||||
assert item['aggregate_summary']['needs_action'] == 2
|
||||
assert item['aggregate_summary']['processing'] == 0
|
||||
assert {child['source_summary']['document_id'] for child in item['aggregate_children']} == {
|
||||
int(pdf.id), int(spreadsheet.id),
|
||||
}
|
||||
assert all(child['status'] == 'waiting_review' for child in item['aggregate_children'])
|
||||
assert all(child['user_status'] == 'waiting_human' for child in item['aggregate_children'])
|
||||
|
||||
|
||||
def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -> None:
|
||||
"""待人工附件已有 Review Case 时,叶子 ui_state 必须给出进入订单处理动作。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
|
||||
|
||||
user, agent, session, intake, _pdf = _seed_run_input(
|
||||
suffix='EML-LEAF-REVIEW-ACTION',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.status = 'review_required'
|
||||
unit.reason_code = 'generic_extraction_disabled'
|
||||
review_case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
db.session.commit()
|
||||
|
||||
item = project_intake_work_item(intake)
|
||||
leaf = next(child for child in item['aggregate_children'] if child['work_item_no'] == f'DOCUMENT:{unit.document_id}')
|
||||
|
||||
assert leaf['run_no'] == run.run_no
|
||||
assert leaf['case_no'] == review_case.case_no
|
||||
assert leaf['ui_state']['primary_action'] == {'code': 'open_order_review'}
|
||||
|
||||
|
||||
def test_conversation_projection_is_the_complete_batch_display_source(app) -> None:
|
||||
"""会话投影一次下发分组、EML 子文件、四阶段及 UI 动作,前端无需二次裁决。"""
|
||||
with app.app_context():
|
||||
items = _aggregate_eml_order_task_work_items([
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-BATCH-FAILED',
|
||||
'source_type': 'eml', 'intake_no': 'SNI-BATCH-1',
|
||||
'root_order_task_no': 'OT-BATCH-FAILED',
|
||||
'last_activity_at': '2026-08-14T00:00:00Z',
|
||||
'source_summary': {
|
||||
'document_id': 101, 'document_count': 1, 'filename': 'a.pdf',
|
||||
'email_subject': 'FWD: Shanghai shipping notice',
|
||||
},
|
||||
'status': 'failed', 'stage': 'waiting_review',
|
||||
'user_status': 'failed', 'user_stage': 'waiting_review',
|
||||
'available_actions': ['retry_parse'],
|
||||
'primary_action': {'code': 'retry_parse'},
|
||||
'blocking_reason': {'code': 'intake_parse_failed'},
|
||||
'facts': {'upload_state': 'not_created'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-BATCH-RUNNING',
|
||||
'source_type': 'eml', 'intake_no': 'SNI-BATCH-1',
|
||||
'root_order_task_no': 'OT-BATCH-RUNNING',
|
||||
'last_activity_at': '2026-08-14T00:00:01Z',
|
||||
'source_summary': {
|
||||
'document_id': 102, 'document_count': 1, 'filename': 'b.pdf',
|
||||
'email_subject': 'FWD: Shanghai shipping notice',
|
||||
},
|
||||
'status': 'processing', 'stage': 'document_parsing',
|
||||
'user_status': 'running', 'user_stage': 'document_parsing',
|
||||
'available_actions': [], 'facts': {'upload_state': 'not_created'},
|
||||
},
|
||||
])
|
||||
|
||||
projection = _conversation_processing_from_work_items(items)
|
||||
|
||||
failed = projection['status_groups']['failed']
|
||||
assert len(failed) == 1
|
||||
assert failed[0]['user_task_no'] == 'INTAKE:SNI-BATCH-1'
|
||||
assert failed[0]['title'] == 'FWD: Shanghai shipping notice'
|
||||
assert len(failed[0]['aggregate_children']) == 2
|
||||
assert failed[0]['ui_state']['primary_action'] == {'code': 'retry_parse'}
|
||||
assert projection['ui_state']['primary_action'] == {'code': 'retry_parse'}
|
||||
assert projection['summary']['total_files'] == 2
|
||||
assert projection['four_stage_nodes'][1] == {
|
||||
'code': 'order_review', 'label_key': 'order_review', 'status': 'blocked',
|
||||
}
|
||||
|
||||
|
||||
def test_conversation_eml_title_prefers_original_eml_filename_over_subject(app) -> None:
|
||||
"""会话与批次中心均以 Intake 原始 EML 文件名标识同一邮件。"""
|
||||
with app.app_context():
|
||||
projection = _conversation_processing_from_work_items([{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': 'INTAKE:SNI-EML-TITLE-1',
|
||||
'source_type': 'eml',
|
||||
'intake_no': 'SNI-EML-TITLE-1',
|
||||
'source_summary': {
|
||||
'document_count': 2,
|
||||
'filename': 'original-shipping-notice.eml',
|
||||
'email_subject': 'FWD: Shanghai shipping notice',
|
||||
},
|
||||
'status': 'processing', 'stage': 'document_parsing',
|
||||
'user_status': 'processing', 'user_stage': 'document_parsing',
|
||||
'available_actions': [], 'facts': {'upload_state': 'not_created'},
|
||||
}])
|
||||
|
||||
assert projection['status_groups']['processing'][0]['title'] == 'original-shipping-notice.eml'
|
||||
|
||||
|
||||
def test_eml_aggregate_action_uses_the_same_priority_as_its_status(app) -> None:
|
||||
"""失败附件即使排在待人工附件之后,EML 父卡也不能显示待人工按钮。"""
|
||||
with app.app_context():
|
||||
result = _aggregate_eml_order_task_work_items([
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-WAITING',
|
||||
'source_type': 'eml', 'intake_no': 'SNI-PRIORITY-1',
|
||||
'last_activity_at': '2026-08-14T00:00:00Z',
|
||||
'source_summary': {'document_id': 201, 'document_count': 1, 'filename': 'waiting.pdf'},
|
||||
'status': 'waiting_human', 'stage': 'waiting_review',
|
||||
'user_status': 'waiting_human', 'user_stage': 'waiting_review',
|
||||
'blocking_reason': {'code': 'customer_confirmation_required'},
|
||||
'primary_action': {'code': 'confirm_customer'},
|
||||
'available_actions': ['confirm_customer'], 'facts': {'upload_state': 'not_created'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-FAILED',
|
||||
'source_type': 'eml', 'intake_no': 'SNI-PRIORITY-1',
|
||||
'last_activity_at': '2026-08-14T00:00:01Z',
|
||||
'source_summary': {'document_id': 202, 'document_count': 1, 'filename': 'failed.pdf'},
|
||||
'status': 'failed', 'stage': 'document_parsing',
|
||||
'user_status': 'failed', 'user_stage': 'document_parsing',
|
||||
'blocking_reason': {'code': 'intake_parse_failed'},
|
||||
'primary_action': {'code': 'retry_parse'},
|
||||
'available_actions': ['retry_parse'], 'facts': {'upload_state': 'not_created'},
|
||||
},
|
||||
])[0]
|
||||
|
||||
assert result['user_group'] == 'failed'
|
||||
assert result['blocking_reason'] == {'code': 'intake_parse_failed'}
|
||||
assert result['primary_action'] == {'code': 'retry_parse'}
|
||||
conversation = _conversation_processing_from_work_items([result])
|
||||
assert conversation['status_groups']['failed'][0]['ui_state']['primary_action'] == {'code': 'retry_parse'}
|
||||
|
||||
|
||||
def test_direct_pdf_maps_internal_pre_ot_stp_stage_for_user_summary() -> None:
|
||||
"""建单前 STP 失败的内部阶段码不得透传给直接 PDF 的用户投影。"""
|
||||
item = {
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-STP-FAIL',
|
||||
'source_type': 'direct_pdf', 'intake_no': 'SNI-STP-FAIL',
|
||||
@@ -157,12 +495,12 @@ def test_aggregate_maps_internal_pre_ot_stp_stage_for_user_summary() -> None:
|
||||
'facts': {'upload_state': 'not_created'},
|
||||
}
|
||||
|
||||
aggregate = _aggregate_eml_order_task_work_items([item])[0]
|
||||
projected = _aggregate_eml_order_task_work_items([item])[0]
|
||||
|
||||
assert aggregate['stage'] == 'order_creating'
|
||||
assert aggregate['user_stage'] == 'order_creating'
|
||||
assert aggregate['aggregate_summary']['stages'] == ['order_creating']
|
||||
assert 'pre_ot_stp' not in aggregate['aggregate_summary']['stages']
|
||||
assert projected['stage'] == 'order_creating'
|
||||
assert projected['user_stage'] == 'order_creating'
|
||||
# 直接 PDF 不是 EML 聚合根,不能伪造 aggregate_summary。
|
||||
assert 'aggregate_summary' not in projected
|
||||
|
||||
|
||||
def test_eml_aggregate_prefers_cancelled_over_completed_child() -> None:
|
||||
@@ -368,10 +706,20 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping
|
||||
intake.parse_status = 'queued'
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_items(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
run_selects: list[str] = []
|
||||
|
||||
def _capture_run_selects(_conn, _cursor, statement, _parameters, _context, _executemany):
|
||||
if re.search(r'\bfrom\s+shipping_order_processing_runs\b', statement, re.IGNORECASE):
|
||||
run_selects.append(statement)
|
||||
|
||||
event.listen(db.engine, 'before_cursor_execute', _capture_run_selects)
|
||||
try:
|
||||
payload = project_conversation_processing_items(
|
||||
user_id=shipping_user.id,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
finally:
|
||||
event.remove(db.engine, 'before_cursor_execute', _capture_run_selects)
|
||||
assert 'projection_version' not in payload
|
||||
assert payload['conversation_id'] == conversation_id
|
||||
assert isinstance(payload['work_items'], list)
|
||||
@@ -387,6 +735,22 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping
|
||||
assert solo['source_type'] == 'direct_pdf'
|
||||
assert solo['stage'] == 'document_parsing'
|
||||
assert solo['status'] == 'processing'
|
||||
# 顶层工作项与会话状态组均消费同一后端 ui_state;前端无需读取 Gate 补按钮。
|
||||
assert solo['ui_state']['status'] == 'running'
|
||||
assert solo['ui_state']['stage'] == 'document_parsing'
|
||||
assert solo['ui_state']['blocking_reason'] is None
|
||||
assert solo['ui_state']['primary_action'] is None
|
||||
assert [action['code'] for action in solo['ui_state']['secondary_actions']] == solo['available_actions']
|
||||
assert all(action['enabled'] is True for action in solo['ui_state']['secondary_actions'])
|
||||
conversation_row = next(
|
||||
row
|
||||
for row in payload['conversation_processing']['status_groups']['processing']
|
||||
if row['user_task_no'] == solo['work_item_no']
|
||||
)
|
||||
assert conversation_row['ui_state'] == solo['ui_state']
|
||||
# 仅 Intake 的会话没有任何 OT;读取 Projection 不得扫描历史 Run,
|
||||
# 否则空白/刚上传首屏会随历史 Run 数量线性变慢。
|
||||
assert run_selects == []
|
||||
|
||||
|
||||
def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, shipping_user):
|
||||
@@ -407,6 +771,8 @@ def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, s
|
||||
intake = ShippingOrderIntake.query.filter_by(intake_no=created['intake_no']).one()
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = intake.created_at
|
||||
# 消费标记仅表示已交给订单识别;尚无 OT/Candidate 的部分识别结果仍必须处理中。
|
||||
intake.order_extraction_status = 'partially_completed'
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_items(
|
||||
@@ -421,6 +787,7 @@ def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, s
|
||||
and row.get('intake_no') == intake.intake_no
|
||||
and row.get('status') == 'processing'
|
||||
and row.get('stage') == 'candidate_creating'
|
||||
and row.get('user_status') == 'running'
|
||||
for row in payload['work_items']
|
||||
)
|
||||
|
||||
@@ -530,7 +897,6 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
process_status='waiting_upload',
|
||||
current_step='step7_upload_freight',
|
||||
)
|
||||
db.session.add(notice)
|
||||
@@ -561,7 +927,7 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
assert synced['stage'] == 'freight_uploading'
|
||||
|
||||
# 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。
|
||||
notice.process_status = 'uploaded'
|
||||
notice.upload_status = 'uploaded'
|
||||
order_task.status = 'automating'
|
||||
order_task.stage = 'freight_uploading'
|
||||
db.session.commit()
|
||||
|
||||
@@ -35,7 +35,6 @@ def test_sync_order_task_stage_must_be_processing_stage(app):
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-CROSS-SURFACE-001',
|
||||
source_type='manual',
|
||||
process_status='matched',
|
||||
po_number='PO-CROSS-001',
|
||||
order_lines_migration_status='pending',
|
||||
)
|
||||
|
||||
@@ -43,7 +43,7 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk
|
||||
from app.services.shipping_notice import order_review_workbench_projection as workbench
|
||||
|
||||
case = MagicMock(status='confirmed', confirmed_task_id=9)
|
||||
stuck = MagicMock(task_no='SN-STUCK-1', process_status='created', current_order_extraction_id=3)
|
||||
stuck = MagicMock(task_no='SN-STUCK-1', current_order_extraction_id=3)
|
||||
finished = NS(
|
||||
id=55,
|
||||
status='success',
|
||||
@@ -83,19 +83,16 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk
|
||||
def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction():
|
||||
"""created/parsed 且已挂 Extraction 的任务需要确认后补推。"""
|
||||
stuck = MagicMock(
|
||||
process_status='created',
|
||||
current_order_extraction_id=12,
|
||||
)
|
||||
parsed = MagicMock(
|
||||
process_status='parsed',
|
||||
current_order_extraction_id=12,
|
||||
)
|
||||
progressed = MagicMock(
|
||||
process_status='waiting_upload',
|
||||
upload_status='pending',
|
||||
current_order_extraction_id=12,
|
||||
)
|
||||
shell = MagicMock(
|
||||
process_status='created',
|
||||
current_order_extraction_id=None,
|
||||
)
|
||||
assert _task_needs_post_confirm_auto_progress(stuck) is True
|
||||
@@ -111,7 +108,6 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-1',
|
||||
user_id=1,
|
||||
process_status='created',
|
||||
current_order_extraction_id=99,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -144,12 +140,11 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
|
||||
|
||||
|
||||
def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypatch):
|
||||
"""确认后 process_status=parsed 仍须入队(CONFIRM_PARSE 后常见态)。"""
|
||||
"""确认后已有解析结果仍须入队(CONFIRM_PARSE 后常见态)。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-PARSED',
|
||||
user_id=1,
|
||||
process_status='parsed',
|
||||
current_order_extraction_id=99,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -185,7 +180,6 @@ def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkey
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-2',
|
||||
user_id=1,
|
||||
process_status='created',
|
||||
current_order_extraction_id=88,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -229,7 +223,7 @@ def test_schedule_auto_progress_skips_when_already_progressed(app, monkeypatch):
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-3',
|
||||
user_id=1,
|
||||
process_status='waiting_upload',
|
||||
upload_status='pending',
|
||||
current_order_extraction_id=77,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -295,7 +289,6 @@ def test_run_single_task_auto_progresses_created_task_with_extraction(app, monke
|
||||
task_no='SN-CONFIRM-AP-4',
|
||||
user_id=1,
|
||||
source_type='review_confirmation',
|
||||
process_status='created',
|
||||
current_order_extraction_id=66,
|
||||
)
|
||||
db.session.add(task)
|
||||
|
||||
@@ -154,7 +154,6 @@ def _task(**kwargs) -> ShippingNotice:
|
||||
task = ShippingNotice(
|
||||
task_no=kwargs.pop('task_no', 'SN-FORMAL-EDIT-001'),
|
||||
source_type='manual',
|
||||
process_status=kwargs.pop('process_status', 'matched'),
|
||||
po_number=kwargs.pop('po_number', 'PO-FORMAL-001'),
|
||||
match_status=kwargs.pop('match_status', 'matched'),
|
||||
line_results_json=kwargs.pop('line_results_json', [{'part_number': 'A001'}]),
|
||||
|
||||
@@ -54,12 +54,12 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
|
||||
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id))
|
||||
task1 = ShippingNotice(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
|
||||
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
)
|
||||
task2 = ShippingNotice(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
|
||||
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
)
|
||||
db.session.add_all([task1, task2])
|
||||
@@ -114,7 +114,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
|
||||
for _ in range(2):
|
||||
task = ShippingNotice(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
|
||||
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
|
||||
user_id=int(user.id), source_type='review_confirmation',
|
||||
source_file_name=document.filename, source_content_hash=document.content_hash,
|
||||
)
|
||||
db.session.add(task)
|
||||
|
||||
@@ -220,12 +220,11 @@ def test_task_missing_does_not_reopen_confirm():
|
||||
assert result['reason_code'] == 'task_missing'
|
||||
|
||||
|
||||
def test_project_stage_for_task_created_is_order_creating():
|
||||
"""正式 OT 仍为 created 时阶段统一为 order_creating,label_key=waiting_system_start。"""
|
||||
def test_project_stage_for_task_without_domain_facts_is_order_creating():
|
||||
"""没有履约领域事实时,内部 OT 阶段投影保持 order_creating。"""
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
order_task_id=None,
|
||||
process_status='created',
|
||||
current_step=None,
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
@@ -233,7 +232,7 @@ def test_project_stage_for_task_created_is_order_creating():
|
||||
stage = project_stage_for_task(task)
|
||||
assert stage['code'] == 'order_creating'
|
||||
assert stage['label_key'] == 'waiting_system_start'
|
||||
assert stage['source'] == 'process_status'
|
||||
assert stage['source'] == 'domain_facts'
|
||||
|
||||
|
||||
def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
|
||||
@@ -241,7 +240,7 @@ def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
order_task_id=9,
|
||||
process_status='uploaded',
|
||||
upload_status='uploaded',
|
||||
current_step='step6_generate_file',
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
@@ -261,7 +260,6 @@ def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeyp
|
||||
|
||||
task = NS(
|
||||
task_no='SN-HANG-1',
|
||||
process_status='created',
|
||||
current_order_extraction_id=9,
|
||||
)
|
||||
finished = NS(
|
||||
|
||||
@@ -167,7 +167,7 @@ def test_automation_failed_retryable_when_post_confirm_needs_retry():
|
||||
'task_no': 'SN-1',
|
||||
'needs_retry': True,
|
||||
'status': 'needs_retry',
|
||||
'task_process_status': 'created',
|
||||
'task_stage': 'order_review',
|
||||
},
|
||||
)
|
||||
assert result['status'] == 'failed'
|
||||
|
||||
@@ -79,7 +79,6 @@ def test_excel_ready_requires_ready_artifact(app) -> None:
|
||||
task = ShippingNotice(
|
||||
task_no='SN-EXCEL-READY-BE09',
|
||||
source_type='manual',
|
||||
process_status='matched',
|
||||
export_file_path='/tmp/be09.xlsx',
|
||||
export_file_name='be09.xlsx',
|
||||
order_data_version=1,
|
||||
|
||||
@@ -31,7 +31,6 @@ def test_log_task_event_dual_write_keeps_match_detail(monkeypatch):
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
task_no='T-STP-1',
|
||||
process_status='pending_review',
|
||||
)
|
||||
tool_common_mod.log_task_event(
|
||||
task,
|
||||
|
||||
@@ -21,7 +21,6 @@ def test_progress_nodes_follow_fixed_order_and_manual_freight():
|
||||
"""Excel 就绪后货代节点为 manual_takeover,不得投影为 running(首期无货代 RPA)。"""
|
||||
task = SimpleNamespace(
|
||||
customer_resolution_status='confirmed',
|
||||
process_status='waiting_upload',
|
||||
pending_human_reason=None,
|
||||
match_status='matched',
|
||||
review_status=None,
|
||||
@@ -44,7 +43,6 @@ def test_progress_nodes_mark_inventory_rpa_retrying():
|
||||
"""库存 RPA 等待中投影为 retrying/running,匹配节点保持 pending。"""
|
||||
task = SimpleNamespace(
|
||||
customer_resolution_status='confirmed',
|
||||
process_status='waiting_inventory',
|
||||
pending_human_reason='rpa_pending',
|
||||
match_status=None,
|
||||
review_status=None,
|
||||
@@ -61,7 +59,6 @@ def test_progress_nodes_customer_pending_blocks_downstream():
|
||||
"""客户未确认时下游库存节点保持 pending。"""
|
||||
task = SimpleNamespace(
|
||||
customer_resolution_status='pending',
|
||||
process_status='created',
|
||||
pending_human_reason=None,
|
||||
match_status=None,
|
||||
review_status=None,
|
||||
|
||||
@@ -26,7 +26,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
process_status='waiting_upload',
|
||||
current_step='step7_upload_freight',
|
||||
)
|
||||
db.session.add(notice)
|
||||
|
||||
@@ -24,8 +24,8 @@ from app.services.shipping_notice.batch_orchestrator import _should_orchestrate_
|
||||
|
||||
|
||||
def _task(task_no: str, **kwargs) -> ShippingNotice:
|
||||
"""构造最小发货任务,便于隔离验证处置状态与原流程状态。"""
|
||||
return ShippingNotice(task_no=task_no, process_status='created', source_type='manual', **kwargs)
|
||||
"""构造最小发货任务,便于隔离验证生命周期处置。"""
|
||||
return ShippingNotice(task_no=task_no, source_type='manual', **kwargs)
|
||||
|
||||
|
||||
def test_plain_created_task_can_be_deleted_and_restored(app):
|
||||
@@ -38,9 +38,8 @@ def test_plain_created_task_can_be_deleted_and_restored(app):
|
||||
outcome = move_task_to_recycle_bin(task, actor_id=1, reason='误建任务', request_id='req-delete')
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:删除不篡改 process_status,异步门禁仅因回收站状态停止任务。
|
||||
# 关键断言:删除仅改变生命周期,异步门禁据此停止任务。
|
||||
assert outcome == 'deleted'
|
||||
assert task.process_status == 'created'
|
||||
assert task.lifecycle_status == 'active'
|
||||
assert task.deleted_at is not None
|
||||
assert task_is_active(task) is False
|
||||
@@ -135,8 +134,8 @@ def test_void_requires_reason_and_rejects_successor(app):
|
||||
assert task_disposition_capability(task, 'delete').code == 'SHIPPING.TASK_SUCCESSOR_VOID_BLOCKED'
|
||||
|
||||
|
||||
def test_disposition_stops_backend_orchestration_without_changing_process_status(app):
|
||||
"""后台编排必须读取独立生命周期,不能依赖 process_status 被伪造为 rejected。"""
|
||||
def test_disposition_stops_backend_orchestration_from_lifecycle(app):
|
||||
"""后台编排必须读取独立生命周期。"""
|
||||
with app.app_context():
|
||||
task = _task('SN-DISPOSITION-ORCHESTRATOR-001')
|
||||
db.session.add(task)
|
||||
@@ -145,8 +144,7 @@ def test_disposition_stops_backend_orchestration_without_changing_process_status
|
||||
assert _should_orchestrate_task(task) is True
|
||||
move_task_to_recycle_bin(task, actor_id=1, reason='取消处理')
|
||||
|
||||
# 关键断言:任务仍为 created,但回收站状态已让编排器停止执行。
|
||||
assert task.process_status == 'created'
|
||||
# 关键断言:回收站状态已让编排器停止执行。
|
||||
assert _should_orchestrate_task(task) is False
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user