Files
syops/backend/app/services/shipping_notice/state_machine.py
T
hugo 90f77634d6 feat(shipping-order): 迭代货代订单提取与履约全流程功能
添加订单字段自动标注配置,默认仅关键字段参与自动框选
完善字段规范化逻辑,支持更多日期格式解析
添加订单候选人工采纳、驳回的完整流程,包含API、前端交互与状态管理
完善盲测功能,支持订单级字段真值校验,调整盲测集唯一性约束
加固库存校验逻辑,防止重复预约与数量不一致问题
优化坐标匹配逻辑,支持表格外的锚点定位
新增上传结果未知的状态处理,完善任务状态机
更新多语言文案与文档说明,补充功能细节
修复订单合并、重解析的边缘情况问题
补充相关测试用例,完善质量保障
2026-07-27 20:48:40 +08:00

581 lines
22 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.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts、order_field_purposes。
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;ui_state.py 与历史兼容模块都从本文件读取按钮/状态;新增人工节点时仅改本文件与测试;
是否具备可匹配订单行经锁定 Extraction 的 FieldValue 判断。
扩展说明(开发者):
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
- 动作按钮 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, ShippingTask
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: ShippingTask) -> 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
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
max_rpa_inventory_attempts,
)
# ---------------------------------------------------------------------------
# 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"},
"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 (HTTP / Dify before task reload)
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"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "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: (),
}
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:
checkpoint: str | None
human_options: list[str] | None
@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 inventory_source_action_buttons(task: ShippingTask) -> list[dict[str, str]]:
"""
将库存源候选项转成聊天区可直接点击的确认按钮。
核心逻辑:库存源待确认时,按钮必须携带 source_code,前端点击后可直接调用确认接口并触发 RPA,
避免先把候选源文本发给 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 TaskUiState(checkpoint=cp, human_options=options)
def upload_req_options_for_task(task: ShippingTask) -> 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: ShippingTask | 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(task: ShippingTask) -> TaskUiState:
"""
将 ShippingTask DB 字段映射为 checkpoint + human_options,供统一 UI State 读模型消费。
核心逻辑:终态 → 正向流程节点 → pending_human_reason 分支 → 默认 None。
"""
# [STEP 1] 终态:已上传、已关闭、已驳回 — 无可用按钮。
if task.process_status == "uploaded":
return TaskUiState(checkpoint=CP_UPLOADED, human_options=[])
if task.process_status == "closed":
return TaskUiState(checkpoint=CP_COMPLETED, human_options=[])
if task.process_status == "rejected" or task.review_status == "rejected":
return TaskUiState(checkpoint=CP_REJECTED, human_options=[])
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
reason = task.pending_human_reason
if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ:
return TaskUiState(
checkpoint=CP_RSV_REQ,
human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]),
)
if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW:
return TaskUiState(
checkpoint=CP_PARSE_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
)
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
return TaskUiState(
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
)
if task.shipping_case_id is not None and task.customer_resolution_status != "confirmed":
return TaskUiState(
checkpoint=CP_CUSTOMER_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]),
)
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结动作始终在 Chat Turn 执行。
if not task.order_snapshot_id and _task_has_dynamic_order_lines(task):
return TaskUiState(
checkpoint=CP_ORDER_FREEZE,
human_options=list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]),
)
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
if reason == PH_RPA_EXHAUSTED:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if (
task.process_status == "parsed"
and not task.review_status
and not task.pending_human_reason
and not task.inventory_lines_json
):
return TaskUiState(
checkpoint=CP_INVENTORY_PENDING,
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]),
)
if (
task.process_status == "inventory_ready"
and not task.review_status
and not task.pending_human_reason
and not task.match_status
and bool(_task_has_dynamic_order_lines(task))
):
return TaskUiState(
checkpoint=CP_READY_MATCH,
human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]),
)
# [STEP 4] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel。
if task.process_status == "matched":
if task.export_file_path:
return TaskUiState(
checkpoint=CP_EXPORT_READY,
human_options=list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]),
)
return TaskUiState(
checkpoint=CP_READY_EXPORT,
human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]),
)
# [STEP 5] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
if reason == PH_INV_UNAVAIL:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if reason == PH_INVENTORY_SOURCE_UNRESOLVED:
return TaskUiState(
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]),
)
if reason == PH_SHORTAGE or task.review_status == RS_SHORTAGE_REVIEW:
return TaskUiState(
checkpoint=RS_SHORTAGE_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]),
)
if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed":
return TaskUiState(
checkpoint=CP_UPLOAD_FAILED,
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]),
)
if reason == PH_UPLOAD_RESULT_UNKNOWN:
return TaskUiState(
checkpoint=CP_UPLOAD_RESULT_UNKNOWN,
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
)
if reason == PH_RPA_PENDING or (
task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING
):
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if reason == PH_UPLOAD_RPA_PENDING or task.process_status == "waiting_upload":
return TaskUiState(
checkpoint=CP_WAITING_UPLOAD,
human_options=list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]),
)
return TaskUiState(checkpoint=None, human_options=None)
def checkpoint_for_task(task: ShippingTask) -> str | None:
"""从 ShippingTask DB 字段解析当前 checkpoint id。"""
return resolve_task_ui_state(task).checkpoint
def human_options_for_task(task: ShippingTask) -> list[str] | None:
"""从 ShippingTask 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,
"human_options": list(option_ids),
"action_buttons": buttons,
}
)
return {
"checkpoints": checkpoints,
"action_specs": ACTION_SPECS,
"dify_fallback": {
cp: build_action_buttons(list(opts)) for cp, opts in CHECKPOINT_REGISTRY.items()
},
}
def validate_registry() -> list[str]:
"""校验 CHECKPOINT_REGISTRY 中 action id 是否均存在于 ACTION_SPECS;测试用。"""
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}")
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: ShippingTask, transition: TaskTransition) -> None:
"""
将命名状态迁移写入 ShippingTask 的 process_status / review_status / pending_human_reason。
核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。
Args:
task: 待更新的 ShippingTask 实例(尚未 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