把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与 枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa 持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀, 上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
392 lines
14 KiB
Python
392 lines
14 KiB
Python
"""
|
||
services/shipping_notice/state_machine.py
|
||
|
||
用途:发货通知任务 DB 字段迁移(TaskTransition)与位置/用户模式解析(Gate + review 回退)。
|
||
依赖:models.ShippingNotice/ShippingOrderTask、constants(RS_*/PH_*)、
|
||
process_gate_contract.derive_*(Gate-first)。
|
||
逻辑:tools/workspace 经 apply_task_transition 写库;resolve_task_ui_state 仅:
|
||
(1) 有活动 Execution 时用 Gate derive_position / derive_user_mode;
|
||
(2) 否则仅凭 review_status 做薄回退。
|
||
禁止领域标量/OT stage 级联裁决;无 checkpoint API 别名;非独立 CP 状态机。
|
||
POSITION_USER_MODE 仅为可选位置→UserMode 查找表,不是状态机。
|
||
build_task_ui_state 可传入已查 Gate 摘要,经 _ui_state_from_process_gate 派生,避免二次查库。
|
||
履约写操作入口为任务处理工作台;Chat 仅通知与跳转。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
from enum import StrEnum
|
||
from typing import Any
|
||
|
||
from app.models import ShippingNotice, ShippingOrderTask
|
||
from app.services.shipping_notice.constants import (
|
||
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,
|
||
RS_PARSE_REVIEW,
|
||
RS_REJECTED,
|
||
RS_RSV_REQ,
|
||
RS_SHORTAGE_REVIEW,
|
||
RS_CONFIRMED,
|
||
)
|
||
|
||
|
||
def _workflow_owner(task: ShippingNotice):
|
||
"""Notice 查询流程状态时统一回到其 OT;Notice 不再作为流程状态事实源。"""
|
||
from app import db
|
||
|
||
if isinstance(task, ShippingOrderTask):
|
||
return task
|
||
order_task_id = getattr(task, 'order_task_id', None)
|
||
return db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else task
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 用户模式枚举(与 derive_user_mode 值域对齐;不是 CheckPoint 状态机)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class UserMode(StrEnum):
|
||
"""用户处置粗分类:auto_continue / must_human / wait_manual_upload / complete。"""
|
||
|
||
AUTO_CONTINUE = "auto_continue"
|
||
MUST_HUMAN = "must_human"
|
||
WAIT_MANUAL_UPLOAD = "wait_manual_upload"
|
||
COMPLETE = "complete"
|
||
|
||
|
||
# 位置标签 → 用户模式(无 Gate 时的可选查找;键为 derive_position 字面量,非状态机)
|
||
POSITION_USER_MODE: dict[str, UserMode] = {
|
||
'parse_review': UserMode.MUST_HUMAN,
|
||
'customer_review': UserMode.MUST_HUMAN,
|
||
'upload_req': UserMode.MUST_HUMAN,
|
||
'inventory_pending': UserMode.AUTO_CONTINUE,
|
||
'inventory_source_review': UserMode.AUTO_CONTINUE,
|
||
'order_freeze': UserMode.AUTO_CONTINUE,
|
||
'rsv_req': UserMode.MUST_HUMAN,
|
||
'shortage_review': UserMode.MUST_HUMAN,
|
||
'notice_text_extraction_failed': UserMode.MUST_HUMAN,
|
||
'quality_issue': UserMode.MUST_HUMAN,
|
||
'upload_failed': UserMode.MUST_HUMAN,
|
||
'waiting_upload': UserMode.WAIT_MANUAL_UPLOAD,
|
||
'upload_result_unknown': UserMode.WAIT_MANUAL_UPLOAD,
|
||
'ready_to_match': UserMode.AUTO_CONTINUE,
|
||
'ready_to_export': UserMode.AUTO_CONTINUE,
|
||
'export_ready': UserMode.WAIT_MANUAL_UPLOAD,
|
||
'export_generated': UserMode.WAIT_MANUAL_UPLOAD,
|
||
'rejected': UserMode.COMPLETE,
|
||
'uploaded': UserMode.COMPLETE,
|
||
'completed': UserMode.COMPLETE,
|
||
}
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class TaskUiState:
|
||
"""位置标签 + 用户模式派生视图(非独立状态机事实)。"""
|
||
|
||
position: str | None
|
||
user_mode: UserMode = UserMode.AUTO_CONTINUE
|
||
|
||
|
||
def user_mode_for_position(position: str | None) -> UserMode:
|
||
"""
|
||
按位置标签解析用户模式(查找表,非状态机)。
|
||
|
||
核心逻辑:查 POSITION_USER_MODE;无位置视为 auto_continue;未知位置默认 must_human。
|
||
|
||
Args:
|
||
position: derive_position / 位置字符串;可为 None。
|
||
|
||
Returns:
|
||
UserMode 枚举值。
|
||
"""
|
||
if not position:
|
||
return UserMode.AUTO_CONTINUE
|
||
return POSITION_USER_MODE.get(str(position).strip(), UserMode.MUST_HUMAN)
|
||
|
||
|
||
def _task_ui_state(position: str | None) -> TaskUiState:
|
||
"""构造位置 + 用户模式派生视图。"""
|
||
return TaskUiState(
|
||
position=position,
|
||
user_mode=user_mode_for_position(position),
|
||
)
|
||
|
||
|
||
def _ui_state_from_process_gate(
|
||
task: ShippingNotice,
|
||
gate: dict[str, Any] | None,
|
||
) -> TaskUiState | None:
|
||
"""
|
||
由已查得的 Gate 用户摘要派生 position/user_mode。
|
||
|
||
核心逻辑:与 ``_gate_task_ui_state`` 同源;``build_task_ui_state`` 复用同一次
|
||
Gate 查询结果,禁止再调 ``resolve_task_ui_state`` 二次查 Execution。
|
||
|
||
Args:
|
||
task: ShippingNotice 或 ShippingOrderTask(取 review_status)。
|
||
gate: ``_process_gate_user_summary_for_task`` 返回值;无 Gate 时为 None。
|
||
|
||
Returns:
|
||
可派生时返回 TaskUiState;否则 None(调用方走 review_status 薄回退)。
|
||
"""
|
||
from app.services.shipping_notice.process_gate_contract import derive_position, derive_user_mode
|
||
|
||
if not isinstance(gate, dict) or not gate.get('current_gate_code'):
|
||
return None
|
||
gate_view = gate.get('current_blocking_gate') or gate.get('current_gate') or {}
|
||
if not isinstance(gate_view, dict):
|
||
gate_view = {}
|
||
status = str(gate_view.get('status') or '').strip().lower()
|
||
summary_status = str(gate.get('status') or '').strip().lower()
|
||
if summary_status in {'completed', 'done'}:
|
||
user_status = 'completed'
|
||
elif status in {'blocked_manual', 'blocked_retryable'} or summary_status == 'blocked':
|
||
user_status = 'waiting_human'
|
||
elif status == 'failed_terminal' or summary_status == 'failed':
|
||
user_status = 'failed'
|
||
else:
|
||
user_status = 'running'
|
||
gate_code = gate.get('current_gate_code') or gate_view.get('gate_code')
|
||
mode = derive_user_mode(
|
||
user_status=user_status,
|
||
gate_code=gate_code,
|
||
review_status=getattr(task, 'review_status', None),
|
||
lifecycle_stage=gate.get('lifecycle_stage'),
|
||
)
|
||
pos = derive_position(
|
||
gate_code=gate_code,
|
||
review_status=getattr(task, 'review_status', None),
|
||
)
|
||
try:
|
||
user_mode = UserMode(str(mode))
|
||
except ValueError:
|
||
user_mode = user_mode_for_position(pos)
|
||
return TaskUiState(position=pos, user_mode=user_mode)
|
||
|
||
|
||
def _review_status_fallback_ui_state(task: ShippingNotice) -> TaskUiState:
|
||
"""
|
||
无活动 Gate 时仅凭 review_status 薄回退派生 position/user_mode。
|
||
|
||
核心逻辑:与 ``resolve_task_ui_state`` 无 Gate 分支同源。
|
||
"""
|
||
from app.services.shipping_notice.process_gate_contract import derive_position, derive_user_mode
|
||
|
||
owner = _workflow_owner(task)
|
||
review_status = getattr(owner, 'review_status', None)
|
||
pos = derive_position(gate_code=None, review_status=review_status)
|
||
mode = derive_user_mode(
|
||
user_status=None,
|
||
gate_code=None,
|
||
review_status=review_status,
|
||
lifecycle_stage=None,
|
||
)
|
||
try:
|
||
user_mode = UserMode(str(mode))
|
||
except ValueError:
|
||
user_mode = user_mode_for_position(pos)
|
||
return TaskUiState(position=pos, user_mode=user_mode)
|
||
|
||
|
||
def _gate_task_ui_state(task: ShippingNotice) -> TaskUiState | None:
|
||
"""
|
||
有活动 Execution 时用 Gate derive_*;否则 None(调用方走 review_status 薄回退)。
|
||
|
||
懒导入 ui_state,避免与 resolve 循环依赖。
|
||
"""
|
||
from app.services.shipping_notice.ui_state import _process_gate_user_summary_for_task
|
||
|
||
return _ui_state_from_process_gate(task, _process_gate_user_summary_for_task(task))
|
||
|
||
|
||
def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState:
|
||
"""
|
||
解析位置 + 用户模式:优先 Gate derive_*,否则仅凭 review_status 薄回退。
|
||
|
||
核心逻辑:无活动 Execution 时调用 derive_position(gate_code=None) /
|
||
derive_user_mode(仅 review_status);禁止 match_status / export_file_path /
|
||
pending_human / OT stage 级联充当状态机。
|
||
|
||
Args:
|
||
task: ShippingNotice 或 ShippingOrderTask。
|
||
|
||
Returns:
|
||
TaskUiState(position + user_mode)。
|
||
"""
|
||
gated = _gate_task_ui_state(task)
|
||
if gated is not None:
|
||
return gated
|
||
return _review_status_fallback_ui_state(task)
|
||
|
||
|
||
def position_for_task(task: ShippingNotice) -> str | None:
|
||
"""返回当前派生位置标签。"""
|
||
return resolve_task_ui_state(task).position
|
||
|
||
|
||
def validate_registry() -> list[str]:
|
||
"""校验位置→用户模式查找表非空;测试用。"""
|
||
return [] if POSITION_USER_MODE else ["POSITION_USER_MODE is empty"]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Task DB field transitions (tools.py writes via apply_task_transition only)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
_UNSET = object()
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class _TransitionSpec:
|
||
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(
|
||
review_status=None,
|
||
pending_human_reason=None,
|
||
),
|
||
TaskTransition.PARSE_NEEDS_REVIEW: _TransitionSpec(
|
||
review_status=RS_PARSE_REVIEW,
|
||
pending_human_reason=PH_LOW_CONF,
|
||
),
|
||
TaskTransition.INVENTORY_READY: _TransitionSpec(
|
||
review_status=None,
|
||
pending_human_reason=None,
|
||
clear_error_message=True,
|
||
),
|
||
TaskTransition.RPA_EXHAUSTED: _TransitionSpec(
|
||
review_status=None,
|
||
pending_human_reason=PH_RPA_EXHAUSTED,
|
||
),
|
||
TaskTransition.RPA_PENDING: _TransitionSpec(
|
||
review_status=None,
|
||
pending_human_reason=PH_RPA_PENDING,
|
||
),
|
||
TaskTransition.INV_UNAVAIL: _TransitionSpec(
|
||
review_status=None,
|
||
pending_human_reason=PH_INV_UNAVAIL,
|
||
),
|
||
TaskTransition.INVENTORY_SOURCE_REVIEW: _TransitionSpec(
|
||
review_status=None,
|
||
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
|
||
),
|
||
TaskTransition.RSV_REQUIRED: _TransitionSpec(
|
||
review_status=RS_RSV_REQ,
|
||
pending_human_reason=PH_RSV_REQ,
|
||
),
|
||
TaskTransition.MATCHED_FULFILLABLE: _TransitionSpec(
|
||
review_status=RS_CONFIRMED,
|
||
pending_human_reason=None,
|
||
),
|
||
TaskTransition.MATCH_SHORTAGE: _TransitionSpec(
|
||
review_status=RS_SHORTAGE_REVIEW,
|
||
pending_human_reason=PH_SHORTAGE,
|
||
),
|
||
TaskTransition.REJECTED: _TransitionSpec(
|
||
review_status=RS_REJECTED,
|
||
pending_human_reason=None,
|
||
),
|
||
TaskTransition.CLOSED: _TransitionSpec(
|
||
review_status=None,
|
||
pending_human_reason=None,
|
||
clear_error_message=True,
|
||
),
|
||
TaskTransition.CONFIRM_PARSE: _TransitionSpec(
|
||
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(
|
||
review_status=None,
|
||
pending_human_reason=PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||
),
|
||
TaskTransition.REMATCH_REQUESTED: _TransitionSpec(
|
||
review_status=None,
|
||
pending_human_reason=None,
|
||
clear_error_message=True,
|
||
),
|
||
TaskTransition.WAITING_UPLOAD: _TransitionSpec(),
|
||
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
|
||
pending_human_reason=PH_UPLOAD_RPA_PENDING,
|
||
),
|
||
TaskTransition.UPLOAD_FAILED: _TransitionSpec(
|
||
pending_human_reason=PH_UPLOAD_RPA_FAILED,
|
||
),
|
||
TaskTransition.UPLOADED: _TransitionSpec(
|
||
pending_human_reason=None,
|
||
clear_error_message=True,
|
||
),
|
||
}
|
||
|
||
|
||
def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> None:
|
||
"""
|
||
将命名业务事实迁移写入 ShippingNotice 的领域结果字段与 review/pending 事实。
|
||
|
||
核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。
|
||
库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → onhand_fetching 等)。
|
||
|
||
Args:
|
||
task: 待更新的 ShippingNotice 实例(尚未 commit)。
|
||
transition: TaskTransition 枚举值。
|
||
"""
|
||
spec = TASK_TRANSITIONS[transition]
|
||
owner = _workflow_owner(task)
|
||
# 流程状态事实只写入 OT。正式 Notice 仅作为履约实体关联入口,
|
||
# 不再动态挂载 review/pending/error 等已删除的历史工作流字段。
|
||
if isinstance(owner, ShippingOrderTask) and spec.review_status is not _UNSET:
|
||
owner.review_status = spec.review_status
|
||
if isinstance(owner, ShippingOrderTask) and spec.pending_human_reason is not _UNSET:
|
||
owner.pending_human_reason = spec.pending_human_reason
|
||
if isinstance(owner, ShippingOrderTask) and spec.clear_error_message:
|
||
owner.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
|