Files
syops/backend/app/services/shipping_notice/state_machine.py
T
hugo 1e5aedb9ed feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
2026-08-26 02:47:07 +08:00

424 lines
16 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 字段与流程事实映射。
依赖: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 后待人工上传登记)
- 用户动作的定义、授权与审计统一由 process_gate_contract / Gate Attempt 负责;
checkpoint 不得派生、下发或执行用户按钮。
"""
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,
)
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"
# 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.AUTO_CONTINUE,
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_KIND_REGISTRY.keys())
@dataclass(frozen=True)
class TaskUiState:
"""统一任务流程状态:checkpoint + STP kind,不包含用户动作。"""
checkpoint: str | None
checkpoint_kind: CheckpointKind = CheckpointKind.AUTO_CONTINUE
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) -> TaskUiState:
"""构造只含内部流程事实的 TaskUiState。"""
return TaskUiState(
checkpoint=checkpoint,
checkpoint_kind=checkpoint_kind_for(checkpoint),
)
def resolve_task_ui_state_from_fields(
*,
review_status: str | None,
pending_human_reason: str | 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 是已废弃的兼容入参;checkpoint 不再解析用户动作。
"""
del upload_req_options
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 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 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)
if reason == PH_LOW_CONF or review_status == RS_PARSE_REVIEW:
return _task_ui_state(CP_PARSE_REVIEW)
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
return _task_ui_state(CP_NOTICE_TEXT_EXTRACTION_FAILED)
if str(customer_resolution_status or "").strip().lower() in {"pending", "needs_review", "failed", "unresolved"}:
return _task_ui_state(CP_CUSTOMER_REVIEW)
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。
if not order_snapshot_id and has_dynamic_order_lines:
return _task_ui_state(CP_ORDER_FREEZE)
# Excel 已生成即进入通知完成前的人工上传登记节点,即使历史任务未落 match_status,
# 也不能退回“处理中”或丢失下载/登记动作。
if has_export:
return _task_ui_state(CP_EXPORT_READY)
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
if reason == PH_RPA_EXHAUSTED:
return _task_ui_state(CP_UPLOAD_REQ)
if (
inventory_lines_json
and not review_status
and not pending_human_reason
and not match_status
):
return _task_ui_state(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)
# [STEP 5] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel(STP 停点)。
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
if has_export:
return _task_ui_state(CP_EXPORT_READY)
return _task_ui_state(CP_READY_EXPORT)
# [STEP 6] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
if reason == PH_INV_UNAVAIL:
return _task_ui_state(CP_UPLOAD_REQ)
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
return _task_ui_state(CP_INVENTORY_SOURCE_REVIEW)
if reason == PH_SHORTAGE or review_status == RS_SHORTAGE_REVIEW:
return _task_ui_state(RS_SHORTAGE_REVIEW)
if reason == PH_UPLOAD_RPA_FAILED or upload_status == "failed":
return _task_ui_state(CP_UPLOAD_FAILED)
if reason == PH_UPLOAD_RESULT_UNKNOWN:
return _task_ui_state(CP_UPLOAD_RESULT_UNKNOWN)
if reason == PH_RPA_PENDING:
return _task_ui_state(CP_UPLOAD_REQ)
if reason == PH_UPLOAD_RPA_PENDING or upload_status in {"pending", "uploading"}:
return _task_ui_state(CP_WAITING_UPLOAD)
return _task_ui_state(None)
def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState:
"""
将 ShippingNotice DB 字段映射为 checkpoint + checkpoint_kind。
核心逻辑:委托 resolve_task_ui_state_from_fields;订单行动态存在性按需查库;
履约写操作由 Gate 投影生成 ui_state.actions;Chat 不再作为写入口。
"""
return resolve_task_ui_state_from_fields(
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
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 validate_registry() -> list[str]:
"""校验每个内部 checkpoint 都有确定的流程分类;测试用。"""
return [] if ALL_CHECKPOINT_IDS == frozenset(CHECKPOINT_KIND_REGISTRY) else ["checkpoint registry mismatch"]
# ---------------------------------------------------------------------------
# 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 → inventory_fetching 等)。
Args:
task: 待更新的 ShippingNotice 实例(尚未 commit)。
transition: TaskTransition 枚举值。
"""
spec = TASK_TRANSITIONS[transition]
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