Files
syops/backend/app/services/shipping_notice/state_machine.py
T
hugo c18c0394d0 feat(shipping_notice): 完成货代发货通知全流程功能迭代与重构
主要变更:
1.  移除废弃的发货通知字段抽取独立Workflow Agent相关代码
2.  重构Dify服务调用,新增inputs参数支持注入环境变量配置的工具API地址与密钥
3.  新增auto_progress工具API与checkpoint catalog接口,支持流程自动推进
4.  统一字段命名,将column_mapping_json改为map_json并兼容旧有调用
5.  重构库存匹配、解析结果的展示格式,改为标准化多语言Markdown表格
6.  新增ODM ID库存字段支持,优化库存解析与映射逻辑
7.  新增LibreOffice转换隔离Profile配置,避免多实例运行冲突
8.  新增完整环境变量配置、数据库迁移脚本与测试用例
9.  适配前端代码,更新字段命名与聊天跳转逻辑
10. 更新OpenAPI规范适配Dify工具调用,删除已归档的旧部署文档
2026-06-08 16:07:20 +08:00

553 lines
20 KiB
Python

"""
Canonical registry for shipping-notice human nodes.
Single source of truth for:
- checkpoint ids (API `checkpoint`, Dify `flow_ckpt`)
- action button specs (`action_buttons`, HXOPS_SHIPPING_ACTIONS)
- task DB fields → checkpoint + human_options (chat-actions API)
- task DB field writes (`TaskTransition` / `apply_task_transition` — tools.py must use these)
When adding a human node, update ONLY this module (+ tests), then:
- tools.py sets task fields via `apply_task_transition(...)` and calls `tool_response(..., checkpoint=CP_*)`
- Dify `组装直接回复` embeds directive only from HTTP `act_json` (approach B); text-only rounds use Hxops `/chat-actions`
- `GET /tools/checkpoint-catalog` is for developers/docs/CI — not wired in Dify canvas
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
CP_INVENTORY_PENDING,
CP_MAP_INFER,
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_REQ,
CP_WAITING_UPLOAD,
PH_ALIGN_REVIEW,
PH_INV_UNAVAIL,
PH_LOW_CONF,
PH_MAP_INFER,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_RSV_REQ,
PH_SHORTAGE,
PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING,
RS_ALIGN_REVIEW,
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,
)
# ---------------------------------------------------------------------------
# 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"},
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
"upload_inventory_file": {
"label": "选择库存文件",
"message": "我要上传库存 Excel",
"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",
},
"paste_inventory_json": {
"label": "粘贴库存",
"message": "我粘贴库存小表",
"variant": "secondary",
},
"edit_inventory_mapping": {
"label": "修改映射",
"message": "修改库存列映射",
"variant": "primary",
},
"match_inventory": {
"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_ALIGN_REVIEW: (
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory",
"reject",
),
CP_MAP_INFER: (
"edit_inventory_mapping",
"upload_inventory_file",
"paste_inventory_json",
"retry_rpa",
),
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"),
RS_SHORTAGE_REVIEW: ("confirm", "reject", "rematch"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("reparse", "reject"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "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, ...] = ("retry_rpa", "upload_inventory_file")
@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]]:
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 human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
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]]:
return build_action_buttons(human_options_for_checkpoint(checkpoint))
def format_actions_directive(option_ids: list[str] | None) -> str:
buttons = build_action_buttons(option_ids)
if not buttons:
return ""
body = json.dumps(buttons, ensure_ascii=False)
return f"<!-- HXOPS_SHIPPING_ACTIONS: {body} -->"
def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
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 with RPA-attempt-aware button subsets."""
if task.pending_human_reason == PH_RPA_EXHAUSTED:
return list(OPTIONS_UPLOAD_FILE_ONLY)
if inventory_rpa_attempts(task) >= max_rpa_inventory_attempts():
return list(OPTIONS_UPLOAD_FILE_ONLY)
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:
"""Prefer task DB state; fall back to static checkpoint registry (for tool_response)."""
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:
"""Map ShippingTask DB fields → checkpoint + human_options for /chat-actions."""
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=[])
if task.pending_human_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 isinstance(task.lines_json, list)
and len(task.lines_json) > 0
):
return TaskUiState(
checkpoint=CP_READY_MATCH,
human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]),
)
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]),
)
reason = task.pending_human_reason
if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW:
return TaskUiState(
checkpoint=CP_ALIGN_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_ALIGN_REVIEW]),
)
if reason == PH_MAP_INFER:
return TaskUiState(
checkpoint=CP_MAP_INFER,
human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]),
)
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_INV_UNAVAIL:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
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_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_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_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:
return resolve_task_ui_state(task).checkpoint
def human_options_for_task(task: ShippingTask) -> list[str] | None:
return resolve_task_ui_state(task).human_options
def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
ui = resolve_task_ui_state(task)
return {
"task_no": task.task_no,
"checkpoint": ui.checkpoint,
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"action_buttons": ui.action_buttons,
}
def build_checkpoint_catalog() -> dict[str, Any]:
"""Export for docs, CI, and developer reference — not embedded in Dify (approach B)."""
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]:
"""Return list of validation errors (empty if ok). Used in tests."""
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"
INVENTORY_ALIGN_REVIEW = "inventory_align_review"
MAP_INFER = "map_infer"
RPA_EXHAUSTED = "rpa_exhausted"
RPA_PENDING = "rpa_pending"
INV_UNAVAIL = "inv_unavail"
RSV_REQUIRED = "rsv_required"
MATCHED_FULFILLABLE = "matched_fulfillable"
MATCH_SHORTAGE = "match_shortage"
REJECTED = "rejected"
CLOSED = "closed"
CONFIRM_SHORTAGE = "confirm_shortage"
CONFIRM_PARSE = "confirm_parse"
CONFIRM_MATCHED = "confirm_matched"
ALIGN_REVIEW_HOLD = "align_review_hold"
MAPPING_CONFIRMED = "mapping_confirmed"
CORRECT_MAPPING = "correct_mapping"
REPARSE_INVENTORY = "reparse_inventory"
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
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.INVENTORY_ALIGN_REVIEW: _TransitionSpec(
process_status="inventory_ready",
review_status=RS_ALIGN_REVIEW,
pending_human_reason=PH_ALIGN_REVIEW,
clear_error_message=True,
),
TaskTransition.MAP_INFER: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_MAP_INFER,
),
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.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_SHORTAGE: _TransitionSpec(
process_status="matched",
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
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.ALIGN_REVIEW_HOLD: _TransitionSpec(
review_status=RS_ALIGN_REVIEW,
pending_human_reason=PH_ALIGN_REVIEW,
),
TaskTransition.MAPPING_CONFIRMED: _TransitionSpec(
review_status=None,
pending_human_reason=None,
),
TaskTransition.CORRECT_MAPPING: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_MAP_INFER,
),
TaskTransition.REPARSE_INVENTORY: _TransitionSpec(
review_status=None,
pending_human_reason=None,
),
TaskTransition.REPARSE_INVENTORY_DEMOTE: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
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:
"""Apply a named transition to task process/review/pending_human_reason fields."""
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