Files
syops/backend/app/services/shipping_notice/state_machine.py
T
hugoandCursor fd6a23f870 feat(shipping-notice): 收敛复核阶段同源投影与 OT 后履约推进
统一 Case/Progress 阶段 label_key、修复 Job 成功未推进 OT 的可重试失败投影与写路径,并落地 OT 后行级匹配/波次履约与版面诊断开关。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 13:11:14 +08:00

676 lines
27 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
services/shipping_notice/state_machine.py
用途:发货通知检查点(checkpoint)与工作台动作按钮的单一注册表,负责任务 DB 字段与 UI 状态映射。
依赖:models.ShippingNotice、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。
逻辑:tools/workspace 经 apply_task_transition 写库;ui_state/query_service 读取 checkpoint_kind 与按钮;
resolve_task_ui_state_from_fields 供待办轻量索引批量分类;履约写操作入口为任务处理工作台,
Chat 仅通知与跳转(Chat Turn 写路径已标记废弃)。
扩展说明(开发者):
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
- checkpoint_kind 区分 auto_continue / must_human / wait_manual_upload / complete
(导出 CP_EXPORT_* → wait_manual_upload:Excel 后待人工上传登记)
- 动作按钮 id 定义于 ACTION_SPECS;DB 写入统一走 TaskTransition
- GET /tools/checkpoint-catalog 供文档/CI,不接入 Dify 画布
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from app import db
from app.models import ShippingOrderExtraction, ShippingOrderLine, ShippingNotice
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
CP_INVENTORY_PENDING,
CP_INVENTORY_SOURCE_REVIEW,
CP_ORDER_FREEZE,
CP_CUSTOMER_REVIEW,
CP_PARSE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_COMPLETED,
CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_NOTICE_TEXT_EXTRACTION_FAILED,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_RSV_REQ,
PH_SHORTAGE,
PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING,
PH_UPLOAD_RESULT_UNKNOWN,
RS_CONFIRMED,
RS_PARSE_REVIEW,
RS_REJECTED,
RS_RSV_REQ,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
max_rpa_inventory_attempts,
)
def _task_has_dynamic_order_lines(task: ShippingNotice) -> bool:
"""判断当前已接受 Extraction 是否有订单行,用于在冻结前显示唯一的冻结入口。"""
extraction_id = task.current_order_extraction_id
if not extraction_id:
return False
extraction = db.session.get(ShippingOrderExtraction, extraction_id)
if extraction is None or extraction.status != "accepted":
return False
return ShippingOrderLine.query.filter_by(extraction_id=extraction.id).first() is not None
# ---------------------------------------------------------------------------
# Checkpoint kind(STP 检查点分类;不写入 DB,由注册表静态映射)
# ---------------------------------------------------------------------------
class CheckpointKind(StrEnum):
"""STP 检查点分类:自动可继续 / 必须人工 / 待人工上传登记 / 完成。
CP_EXPORT_READY/GENERATED 映射为 WAIT_MANUAL_UPLOAD(Excel 后须登记凭据,非终态)。
"""
AUTO_CONTINUE = "auto_continue"
MUST_HUMAN = "must_human"
WAIT_MANUAL_UPLOAD = "wait_manual_upload"
COMPLETE = "complete"
# ---------------------------------------------------------------------------
# Action buttons (id → label / message / variant) — 任务处理工作台动作目录
# ---------------------------------------------------------------------------
ACTION_SPECS: dict[str, dict[str, str]] = {
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
"replace_notice_file": {"label": "重新上传", "message": "重新上传发货通知", "variant": "primary"},
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
"retry_rpa": {"label": "重新获取库存", "message": "重新获取库存", "variant": "secondary"},
"confirm_inventory_source": {"label": "确认库存源", "message": "确认库存查询来源", "variant": "primary"},
"confirm_customer": {"label": "确认客户", "message": "选择并确认标准客户", "variant": "primary"},
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
"upload_inventory_file": {
"label": "上传库存文件",
"message": "上传库存 Excel",
"variant": "primary",
},
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
"mark_manual_uploaded": {
"label": "已手工上传",
"message": "已在货代系统手工上传完成",
"variant": "primary",
},
"match_inventory": {
"label": "匹配库存",
"message": "匹配库存",
"variant": "primary",
},
"freeze_order": {
"label": "冻结订单",
"message": "冻结已复核订单",
"variant": "primary",
},
}
# checkpoint id → default human option ids
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
CP_CUSTOMER_REVIEW: ("confirm_customer",),
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa"),
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa"),
CP_INVENTORY_SOURCE_REVIEW: (
"confirm_inventory_source",
"retry_resolve_inventory_source",
),
CP_ORDER_FREEZE: ("freeze_order",),
CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"),
RS_SHORTAGE_REVIEW: ("retry_rpa", "rematch", "reject"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
# 上传失败仅允许下载;待上传/结果未知允许下载 + 人工凭据登记(禁 RPA retry_upload)。
CP_UPLOAD_FAILED: ("download_excel",),
CP_WAITING_UPLOAD: ("refresh", "download_excel", "mark_manual_uploaded"),
CP_UPLOAD_RESULT_UNKNOWN: ("refresh", "download_excel", "mark_manual_uploaded"),
CP_READY_MATCH: ("match_inventory",),
CP_READY_EXPORT: ("generate_excel",),
CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"),
CP_EXPORT_GENERATED: ("download_excel", "mark_manual_uploaded"),
CP_REJECTED: (),
CP_UPLOADED: (),
CP_COMPLETED: (),
}
# checkpoint id → STP kind(静态;无 checkpoint 时视为 auto_continue)
CHECKPOINT_KIND_REGISTRY: dict[str, CheckpointKind] = {
CP_PARSE_REVIEW: CheckpointKind.MUST_HUMAN,
CP_CUSTOMER_REVIEW: CheckpointKind.MUST_HUMAN,
CP_UPLOAD_REQ: CheckpointKind.MUST_HUMAN,
CP_INVENTORY_PENDING: CheckpointKind.AUTO_CONTINUE,
CP_INVENTORY_SOURCE_REVIEW: CheckpointKind.MUST_HUMAN,
CP_ORDER_FREEZE: CheckpointKind.AUTO_CONTINUE,
CP_RSV_REQ: CheckpointKind.MUST_HUMAN,
RS_SHORTAGE_REVIEW: CheckpointKind.MUST_HUMAN,
CP_NOTICE_TEXT_EXTRACTION_FAILED: CheckpointKind.MUST_HUMAN,
CP_UPLOAD_FAILED: CheckpointKind.MUST_HUMAN,
CP_WAITING_UPLOAD: CheckpointKind.WAIT_MANUAL_UPLOAD,
CP_UPLOAD_RESULT_UNKNOWN: CheckpointKind.WAIT_MANUAL_UPLOAD,
CP_READY_MATCH: CheckpointKind.AUTO_CONTINUE,
CP_READY_EXPORT: CheckpointKind.AUTO_CONTINUE,
CP_EXPORT_READY: CheckpointKind.WAIT_MANUAL_UPLOAD,
CP_EXPORT_GENERATED: CheckpointKind.WAIT_MANUAL_UPLOAD,
CP_REJECTED: CheckpointKind.COMPLETE,
CP_UPLOADED: CheckpointKind.COMPLETE,
CP_COMPLETED: CheckpointKind.COMPLETE,
}
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_REGISTRY.keys())
ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys())
# Dynamic subsets of upload_req (RPA attempts); default full set is CHECKPOINT_REGISTRY[CP_UPLOAD_REQ]
OPTIONS_UPLOAD_FILE_ONLY: tuple[str, ...] = ("upload_inventory_file",)
OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("upload_inventory_file", "retry_rpa")
@dataclass(frozen=True)
class TaskUiState:
"""统一任务 UI 状态:checkpoint + STP kind + 工作台可用动作。"""
checkpoint: str | None
human_options: list[str] | None
checkpoint_kind: CheckpointKind = CheckpointKind.AUTO_CONTINUE
@property
def action_buttons(self) -> list[dict[str, str]]:
return build_action_buttons(self.human_options)
def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
"""将 human_options 动作 id 列表转为前端/Dify 可用的 action_buttons 结构。"""
if not option_ids:
return []
buttons: list[dict[str, str]] = []
for option_id in option_ids:
spec = ACTION_SPECS.get(option_id)
if not spec:
continue
buttons.append({"id": option_id, **spec})
return buttons
def checkpoint_kind_for(checkpoint: str | None) -> CheckpointKind:
"""
按 checkpoint id 解析 STP 检查点分类。
核心逻辑:查 CHECKPOINT_KIND_REGISTRY;无 checkpoint(系统推进中)视为 auto_continue。
"""
if not checkpoint:
return CheckpointKind.AUTO_CONTINUE
return CHECKPOINT_KIND_REGISTRY.get(str(checkpoint).strip(), CheckpointKind.MUST_HUMAN)
def _task_ui_state(checkpoint: str | None, human_options: list[str] | None) -> TaskUiState:
"""构造带 checkpoint_kind 的 TaskUiState。"""
return TaskUiState(
checkpoint=checkpoint,
human_options=human_options,
checkpoint_kind=checkpoint_kind_for(checkpoint),
)
def inventory_source_action_buttons(task: ShippingNotice) -> list[dict[str, str]]:
"""
将库存源候选项转成工作台可直接点击的确认按钮。
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口,
避免先把候选源文本发给 Agent 再等待二次确认。
"""
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
resolution = payload.get("inventory_source_resolution")
candidates = resolution.get("candidates") if isinstance(resolution, dict) else None
normalized_candidates: list[dict[str, Any]] = []
if isinstance(candidates, list):
for item in candidates:
if not isinstance(item, dict):
continue
source_code = str(item.get("source_code") or "").strip().upper()
if not source_code:
continue
normalized_candidates.append(item)
if len(normalized_candidates) == 1:
item = normalized_candidates[0]
source_code = str(item.get("source_code") or "").strip().upper()
display_name = str(item.get("display_name") or source_code).strip()
return [
{
"id": "confirm_inventory_source",
"label": f"确认:{display_name}",
"message": f"确认库存查询来源:{display_name}",
"variant": "primary",
"source_code": source_code,
},
*build_action_buttons(["retry_resolve_inventory_source"]),
]
return build_action_buttons(list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]))
def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
"""按静态 checkpoint id 查 CHECKPOINT_REGISTRY 中的默认 human_options。"""
if not checkpoint:
return None
key = str(checkpoint).strip()
options = CHECKPOINT_REGISTRY.get(key)
if options is None:
return None
return list(options)
def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]:
"""checkpoint → action_buttons 的便捷封装(状态机 UI payload 用)。"""
return build_action_buttons(human_options_for_checkpoint(checkpoint))
def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
"""无 DB 任务时,仅按 checkpoint id 构造 TaskUiState(Tool 早停响应用)。"""
options = human_options_for_checkpoint(checkpoint)
cp = str(checkpoint).strip() if checkpoint else None
if cp and cp not in CHECKPOINT_REGISTRY:
cp = None
return _task_ui_state(cp, options)
def upload_req_options_for_task(task: ShippingNotice) -> list[str]:
"""upload_req checkpoint 的动作子集,随 RPA 重试次数动态收缩。"""
if task.pending_human_reason == PH_RPA_EXHAUSTED:
return list(OPTIONS_RPA_OR_UPLOAD)
if inventory_rpa_attempts(task) >= max_rpa_inventory_attempts():
return list(OPTIONS_RPA_OR_UPLOAD)
if task.pending_human_reason in {PH_INV_UNAVAIL, PH_RPA_PENDING}:
return list(OPTIONS_RPA_OR_UPLOAD)
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
def human_options_for_task_or_checkpoint(
*,
task: ShippingNotice | None = None,
checkpoint: str | None = None,
) -> list[str] | None:
"""优先从 task DB 状态解析 human_options;无 task 时回退静态 checkpoint 注册表。"""
if task is not None:
opts = resolve_task_ui_state(task).human_options
if opts is not None:
return opts
return human_options_for_checkpoint(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,
customer_resolution_status: str | None,
order_snapshot_id: int | None,
inventory_lines_json: Any,
match_status: str | None,
export_file_path: str | None,
has_dynamic_order_lines: bool,
upload_req_options: list[str] | None = None,
upload_req_task: ShippingNotice | None = None,
) -> TaskUiState:
"""
由任务标量字段映射 checkpoint / checkpoint_kind(无 ORM、无额外查询)。
核心逻辑:与 resolve_task_ui_state 同序分支;has_dynamic_order_lines 由调用方批量预计算,
供待办索引在不全量水合 Task 时保持与单任务路径一致的分类口径。
upload_req_options / upload_req_task 仅在命中 upload_req 分支时解析按钮列表。
"""
def _upload_opts() -> list[str]:
if upload_req_options is not None:
return list(upload_req_options)
if upload_req_task is not None:
return upload_req_options_for_task(upload_req_task)
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
# [STEP 1] 终态:已上传、已关闭、已驳回 — 无可用按钮。
if process_status == "uploaded":
return _task_ui_state(CP_UPLOADED, [])
if process_status == "closed":
return _task_ui_state(CP_COMPLETED, [])
if process_status == "rejected" or review_status == "rejected":
return _task_ui_state(CP_REJECTED, [])
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
reason = pending_human_reason
if reason == PH_RSV_REQ or review_status == RS_RSV_REQ:
return _task_ui_state(CP_RSV_REQ, list(CHECKPOINT_REGISTRY[CP_RSV_REQ]))
if reason == PH_LOW_CONF or review_status == RS_PARSE_REVIEW:
return _task_ui_state(CP_PARSE_REVIEW, list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]))
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
return _task_ui_state(
CP_NOTICE_TEXT_EXTRACTION_FAILED,
list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
)
if shipping_case_id is not None and customer_resolution_status != "confirmed":
return _task_ui_state(CP_CUSTOMER_REVIEW, list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]))
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。
if not order_snapshot_id and has_dynamic_order_lines:
return _task_ui_state(CP_ORDER_FREEZE, list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]))
# [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"
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]))
# [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。
if process_status == "matched":
if export_file_path:
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]))
# [STEP 6] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
if reason == PH_INV_UNAVAIL:
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
return _task_ui_state(
CP_INVENTORY_SOURCE_REVIEW,
list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
)
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":
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
):
return _task_ui_state(CP_UPLOAD_REQ, _upload_opts())
if reason == PH_UPLOAD_RPA_PENDING or process_status == "waiting_upload":
return _task_ui_state(CP_WAITING_UPLOAD, list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]))
return _task_ui_state(None, None)
def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState:
"""
将 ShippingNotice DB 字段映射为 checkpoint + checkpoint_kind + human_options。
核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库;
upload_req 按钮仅在命中对应分支时惰性解析(兼容测试用轻量 stub)。
履约写操作由任务处理工作台消费 action_buttons;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,
customer_resolution_status=task.customer_resolution_status,
order_snapshot_id=task.order_snapshot_id,
inventory_lines_json=task.inventory_lines_json,
match_status=task.match_status,
export_file_path=task.export_file_path,
has_dynamic_order_lines=_task_has_dynamic_order_lines(task),
upload_req_task=task,
)
def checkpoint_for_task(task: ShippingNotice) -> str | None:
"""从 ShippingNotice DB 字段解析当前 checkpoint id。"""
return resolve_task_ui_state(task).checkpoint
def human_options_for_task(task: ShippingNotice) -> list[str] | None:
"""从 ShippingNotice DB 字段解析当前可用 human_options(含 RPA 动态子集)。"""
return resolve_task_ui_state(task).human_options
def build_checkpoint_catalog() -> dict[str, Any]:
"""导出 checkpoint 注册表供文档/CI 校验(不接入 Dify 画布)。"""
checkpoints = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
buttons = build_action_buttons(list(option_ids))
checkpoints.append(
{
"id": checkpoint_id,
"checkpoint_kind": str(checkpoint_kind_for(checkpoint_id)),
"human_options": list(option_ids),
"action_buttons": buttons,
}
)
return {
"checkpoints": checkpoints,
"action_specs": ACTION_SPECS,
"checkpoint_kinds": {k: str(v) for k, v in CHECKPOINT_KIND_REGISTRY.items()},
"dify_fallback": {
cp: build_action_buttons(list(opts)) for cp, opts in CHECKPOINT_REGISTRY.items()
},
}
def validate_registry() -> list[str]:
"""校验 CHECKPOINT_REGISTRY 动作完整性与 KIND 覆盖;测试用。"""
errors: list[str] = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
for option_id in option_ids:
if option_id not in ACTION_SPECS:
errors.append(f"checkpoint {checkpoint_id}: unknown action id {option_id!r}")
if checkpoint_id not in CHECKPOINT_KIND_REGISTRY:
errors.append(f"checkpoint {checkpoint_id}: missing checkpoint_kind")
for checkpoint_id in CHECKPOINT_KIND_REGISTRY:
if checkpoint_id not in CHECKPOINT_REGISTRY:
errors.append(f"checkpoint_kind {checkpoint_id}: not in CHECKPOINT_REGISTRY")
return errors
# ---------------------------------------------------------------------------
# Task DB field transitions (tools.py writes via apply_task_transition only)
# ---------------------------------------------------------------------------
_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
class TaskTransition(StrEnum):
"""Named DB state writes used by shipping notice tools."""
PARSED = "parsed"
PARSE_NEEDS_REVIEW = "parse_needs_review"
INVENTORY_READY = "inventory_ready"
RPA_EXHAUSTED = "rpa_exhausted"
RPA_PENDING = "rpa_pending"
INV_UNAVAIL = "inv_unavail"
INVENTORY_SOURCE_REVIEW = "inventory_source_review"
RSV_REQUIRED = "rsv_required"
MATCHED_FULFILLABLE = "matched_fulfillable"
MATCH_SHORTAGE = "match_shortage"
REJECTED = "rejected"
CLOSED = "closed"
CONFIRM_PARSE = "confirm_parse"
CONFIRM_MATCHED = "confirm_matched"
NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
REMATCH_REQUESTED = "rematch_requested"
WAITING_UPLOAD = "waiting_upload"
UPLOAD_RPA_PENDING = "upload_rpa_pending"
UPLOAD_FAILED = "upload_failed"
UPLOADED = "uploaded"
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,
),
TaskTransition.CONFIRM_MATCHED: _TransitionSpec(
review_status=RS_CONFIRMED,
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.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,
),
}
def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> None:
"""
将命名状态迁移写入 ShippingNotice 的 process_status / review_status / pending_human_reason。
核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。
库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → inventory_fetching 等)。
Args:
task: 待更新的 ShippingNotice 实例(尚未 commit)。
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:
task.pending_human_reason = spec.pending_human_reason
if spec.clear_error_message:
task.error_message = None
# [STEP] 履约态变更后回写 OT stage,避免进度条卡在 order_creating。
try:
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_notice,
)
sync_order_task_stage_for_notice(task)
except Exception: # noqa: BLE001 — 无 OT / 无 Flask 上下文时跳过,不阻断主迁移
pass