refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段

统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成
设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程
删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本
替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段
更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
This commit is contained in:
hugo committed 2026-08-15 10:19:10 +08:00
1 parent 6684e7181a
commit 5ef8329bd8
178 files changed
+5091 -1734

No files matched your search

+176 -47
View File
@@ -5,14 +5,10 @@ services/shipping_notice/ui_state.py
依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、
process_gate_projection(统一 Gate 用户摘要)、
order_review_workbench_projection.apply_post_ot_gate_rules。
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions,
再补充四阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
stp_facts、progress_nodes);
若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留
download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动);
[兼容] action_buttons 为只读兼容字段:权威可恢复操作入口已统一为
process_gate.next_action_code(如 retry_inventory_preparation),本字段仅保留供
任务详情 / 聊天状态 / 旧入口消费,禁止再向其新增恢复动作;待确认无活跃消费者后删除。
若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影;
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
"""
@@ -68,13 +64,10 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-step-1", "code": "notice_submit", "label": "提交通知"},
{"id": "shipping-step-2", "code": "parse_confirm", "label": "确认解析"},
{"id": "shipping-step-3", "code": "inventory_prepare", "label": "获取库存"},
{"id": "shipping-step-4", "code": "align_confirm", "label": "校验库存"},
{"id": "shipping-step-5", "code": "match_inventory", "label": "匹配库存"},
{"id": "shipping-step-6", "code": "generate_file", "label": "生成发货文件"},
{"id": "shipping-step-7", "code": "upload_freight", "label": "上传货代"},
{"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"},
{"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"},
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "发货准备"},
{"id": "shipping-stage-4", "code": "upload_complete", "label": "上传完成"},
)
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
@@ -138,41 +131,157 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
}
# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
BUSINESS_STAGES: tuple[dict[str, Any], ...] = (
{"code": "intake_parse", "label": "接收解析"},
{"code": "order_review", "label": "订单复核"},
{"code": "fulfillment_prep", "label": "发货准备"},
{"code": "upload_complete", "label": "上传完成"},
)
_STAGE_GATE_CODES: dict[str, str] = {
"document_materialization": "intake_parse",
"layout_parsing": "intake_parse",
"document_profile_routing": "intake_parse",
"order_field_extraction": "intake_parse",
"field_completeness": "order_review",
"reservation_validation": "order_review",
"customer_resolution": "order_review",
"duplicate_detection": "order_review",
"field_conflict_resolution": "order_review",
"order_freeze_readiness": "order_review",
"task_creation": "order_review",
"inventory_source_routing": "fulfillment_prep",
"inventory_preparation": "fulfillment_prep",
"inventory_field_mapping": "fulfillment_prep",
"inventory_matching": "fulfillment_prep",
"inventory_sufficiency": "fulfillment_prep",
"excel_readiness": "fulfillment_prep",
"artifact_generation": "fulfillment_prep",
"freight_upload_rpa": "upload_complete",
"manual_upload_handoff": "upload_complete",
}
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_PARSE_REVIEW: "order_review",
CP_RSV_REQ: "order_review",
CP_CUSTOMER_REVIEW: "order_review",
CP_ORDER_FREEZE: "order_review",
CP_INVENTORY_SOURCE_REVIEW: "fulfillment_prep",
CP_INVENTORY_PENDING: "fulfillment_prep",
CP_READY_MATCH: "fulfillment_prep",
RS_SHORTAGE_REVIEW: "fulfillment_prep",
CP_READY_EXPORT: "fulfillment_prep",
CP_EXPORT_READY: "fulfillment_prep",
CP_EXPORT_GENERATED: "fulfillment_prep",
CP_WAITING_UPLOAD: "upload_complete",
CP_UPLOAD_REQ: "fulfillment_prep",
CP_UPLOAD_FAILED: "upload_complete",
CP_UPLOAD_RESULT_UNKNOWN: "upload_complete",
CP_UPLOADED: "upload_complete",
CP_COMPLETED: "upload_complete",
CP_REJECTED: "order_review",
}
def _business_stage(
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""将内部 Gate/checkpoint 投影为四阶段;不向前端暴露底层状态枚举。"""
gate = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
gate_code = str(gate.get("gate_code") or "").strip()
stage_code = _STAGE_GATE_CODES.get(gate_code) or _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ""))
if not stage_code:
stage_code = "upload_complete" if str(checkpoint or "") in {CP_UPLOADED, CP_COMPLETED} else "intake_parse"
index = next((i for i, item in enumerate(BUSINESS_STAGES) if item["code"] == stage_code), 0)
return {**BUSINESS_STAGES[index], "index": index + 1, "total": len(BUSINESS_STAGES)}
def _unified_action(action: dict[str, Any], *, default_kind: str = "recovery") -> dict[str, Any]:
"""规范 Gate/旧状态机动作,前端只渲染该统一结构。"""
item = dict(action or {})
code = str(item.get("code") or item.get("id") or "").strip()
dispatch = str(item.get("dispatch") or "").strip()
kind = str(item.get("kind") or "").strip()
if kind in {"current_gate", ""}:
kind = "view" if dispatch in {"navigation", "refresh"} and code.startswith("view_") else default_kind
return {
"code": code,
"label": item.get("label") or item.get("label_key") or code,
"kind": kind,
"enabled": bool(item.get("enabled", True)),
"requires_confirmation": bool(item.get("requires_confirmation", False)),
"target_surface": item.get("target_surface") or ("shipping_task_workbench" if dispatch == "navigation" else None),
"disabled_reason": item.get("disabled_reason"),
"expected_gate_version": item.get("expected_gate_version"),
}
def _unified_actions(
*, process_gate: dict[str, Any] | None, action_buttons: list[dict[str, str]],
) -> dict[str, Any]:
"""统一输出唯一主动作与次动作;动作来源优先为 Gate。"""
gate_actions = list((process_gate or {}).get("action_presentation") or [])
if process_gate and (process_gate.get("primary_action") or gate_actions):
primary_raw = process_gate.get("primary_action") or gate_actions[0]
primary_code = str((primary_raw or {}).get("code") or (primary_raw or {}).get("id") or "").strip()
secondary_raw = [
item for item in gate_actions
if str((item or {}).get("code") or (item or {}).get("id") or "").strip() != primary_code
]
else:
primary_raw = action_buttons[0] if action_buttons else None
secondary_raw = action_buttons[1:] if action_buttons else []
gate_view = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
expected_version = gate_view.get("evaluation_version") or (process_gate or {}).get("lock_version")
def normalize(item: dict[str, Any] | None) -> dict[str, Any] | None:
if not item:
return None
result = _unified_action(item)
if result.get("expected_gate_version") is None and expected_version is not None:
result["expected_gate_version"] = int(expected_version)
return result
primary = normalize(primary_raw)
secondary = [normalized for item in secondary_raw if (normalized := normalize(item))]
return {"primary": primary, "secondary": secondary}
def _derive_current_step_index(task: ShippingNotice) -> int:
"""
根据任务字段推导七步流程当前索引。
根据任务领域事实推导四阶段流程当前索引。
核心逻辑:优先使用 current_step 精准定位;缺失时按 process/review/pending 状态兜底,
保持与前端旧 stepper 的语义一致,后续前端可直接消费后端 step。
核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。
"""
current_step = str(task.current_step or "").strip()
if current_step in _CURRENT_STEP_INDEX_MAP:
return _CURRENT_STEP_INDEX_MAP[current_step]
legacy_index = _CURRENT_STEP_INDEX_MAP[current_step]
return 0 if legacy_index <= 0 else 1 if legacy_index == 1 else 3 if legacy_index >= 6 else 2
process_status = str(task.process_status or "").strip()
review_status = str(task.review_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
match_status = str(task.match_status or "").strip()
upload_status = str(getattr(task, "upload_status", None) or "").strip().lower()
has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip())
if process_status in _TERMINAL_PROCESS_STATUSES:
return 6
if process_status in {"waiting_upload", "upload_failed"} or has_export:
return 5
if process_status == "matched":
return 4
if upload_status in {"uploaded", "succeeded", "success"} or str(getattr(task, "lifecycle_status", "") or "").lower() in {"archived", "deleted"}:
return 3
if upload_status in {"pending", "uploading", "failed"} or has_export:
return 2
if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}:
return 2
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
return 4
if process_status == "inventory_ready" or match_status:
return 4
if process_status == "waiting_inventory" or pending_reason in {
return 2
if task.inventory_lines_json or match_status:
return 2
if pending_reason in {
PH_RPA_PENDING,
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
}:
return 2
if process_status in {"parsed", "pending_review"} or review_status in {
if review_status in {
RS_PARSE_REVIEW,
PH_RSV_REQ,
} or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
@@ -182,18 +291,17 @@ def _derive_current_step_index(task: ShippingNotice) -> int:
def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None) -> list[dict[str, str]]:
"""
构造七步流程状态。
构造四阶段流程状态。
Returns:
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
"""
current_index = _derive_current_step_index(task)
process_status = str(task.process_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
checkpoint_value = str(checkpoint or "").strip()
steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS):
if process_status in _TERMINAL_PROCESS_STATUSES:
if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
status = "completed"
elif index < current_index:
status = "completed"
@@ -201,15 +309,17 @@ def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None)
status = "current"
else:
status = "pending"
inventory_blocked = (
index == 2
and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
)
inventory_blocked = index == 2 and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED}
parse_blocked = index == 1 and (
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED}
or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}
checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_NOTICE_TEXT_EXTRACTION_FAILED}
or pending_reason in {"low_confidence", PH_RSV_REQ}
)
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked):
prep_blocked = index == 2 and (
checkpoint_value in {CP_INVENTORY_SOURCE_REVIEW, RS_SHORTAGE_REVIEW}
or pending_reason in {PH_INVENTORY_SOURCE_UNRESOLVED, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_SHORTAGE}
)
upload_blocked = index == 3 and str(getattr(task, "upload_status", None) or "").strip().lower() == "failed"
if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked or prep_blocked or upload_blocked):
status = "blocked"
steps.append({**step, "status": status})
return steps
@@ -584,9 +694,9 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
"""
构建单票任务 UI State。
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/checkpoint_kind/action_buttons/summary,
核心逻辑:所有 UI 入口只消费这里输出的 stage/checkpoint/todo/actions/summary,
禁止 Chat、通知卡与任务中心分别推导状态;有 Execution 时附带统一 Gate 用户摘要;
存在 current_blocking_gate 时清空 STP action_buttons,恢复仅走 process_gate。
存在 current_blocking_gate 时只输出 Gate actions,禁止旧动作列表穿透。
"""
ui = resolve_task_ui_state(task)
action_buttons = _action_buttons_for_task(task)
@@ -622,21 +732,40 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
summary['diagnostic_hint'] = process_gate['diagnostic_hint']
if process_gate.get('current_blocking_gate'):
summary['allowed_actions'] = []
stage = _business_stage(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
actions = _unified_actions(process_gate=process_gate, action_buttons=action_buttons)
checkpoint_payload = {
"code": ui.checkpoint,
"kind": str(ui.checkpoint_kind),
"label": str(ui.checkpoint or "") or None,
}
reason = None
if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"):
reason = {
"code": process_gate.get("blocking_reason_code"),
"message": process_gate.get("blocking_message"),
}
return {
"task_no": task.task_no,
"batch_no": None,
"checkpoint": ui.checkpoint,
"stage": stage,
"checkpoint": checkpoint_payload,
"checkpoint_view": checkpoint_payload,
"todo": {
"title": summary.get("current_todo") or summary.get("title"),
"message": summary.get("message"),
},
"actions": actions,
"reason": reason,
"lifecycle_status": task.lifecycle_status,
"checkpoint_code": ui.checkpoint,
"checkpoint_kind": str(ui.checkpoint_kind),
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"match_status": task.match_status,
"current_step": current_step,
"steps": steps,
"summary": summary,
# [兼容] action_buttons 为只读兼容字段(见模块 docstring);新 UI 应消费
# summary.process_gate.next_action_code,本字段仅作历史消费者过渡,不再扩展。
"action_buttons": action_buttons,
"process_gate": process_gate,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}