将货代发货流程从四阶段扩展为五阶段,拆分上传相关逻辑至独立的货代上传阶段; 统一多语言文案修正客户状态语义,将"客户尚未识别"调整为符合业务的"客户尚未确认"; 新增严格的上传成功验证谓词,需同时满足任务状态、全部预约单上传成功、存在有效成功上传尝试三个条件方可标记为完成; 新增坐标取值模型配置,支持Legacy冻结绝对坐标和锚点框架受限平移两种模式; 更新全链路相关文档、前端组件、后端服务与测试用例,确保业务逻辑对齐新业务规则。
1065 lines
48 KiB
Python
1065 lines
48 KiB
Python
"""
|
||
services/shipping_notice/ui_state.py
|
||
|
||
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
|
||
依赖: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,再统一投影 actions,
|
||
再补充五阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
|
||
stp_facts、progress_nodes);
|
||
若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影;
|
||
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
|
||
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
from app.models import ShippingNotice
|
||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||
from app.services.shipping_notice.constants import (
|
||
CP_COMPLETED,
|
||
CP_CUSTOMER_REVIEW,
|
||
CP_EXPORT_GENERATED,
|
||
CP_EXPORT_READY,
|
||
CP_INVENTORY_PENDING,
|
||
CP_INVENTORY_SOURCE_REVIEW,
|
||
CP_ORDER_FREEZE,
|
||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||
CP_PARSE_REVIEW,
|
||
CP_READY_EXPORT,
|
||
CP_READY_MATCH,
|
||
CP_REJECTED,
|
||
CP_RSV_REQ,
|
||
CP_UPLOADED,
|
||
CP_UPLOAD_FAILED,
|
||
CP_UPLOAD_RESULT_UNKNOWN,
|
||
CP_UPLOAD_REQ,
|
||
CP_WAITING_UPLOAD,
|
||
PH_INV_UNAVAIL,
|
||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||
PH_RPA_EXHAUSTED,
|
||
PH_RPA_PENDING,
|
||
PH_RSV_REQ,
|
||
PH_SHORTAGE,
|
||
PH_UPLOAD_RPA_PENDING,
|
||
RS_PARSE_REVIEW,
|
||
RS_SHORTAGE_REVIEW,
|
||
)
|
||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||
from app.services.shipping_notice.lifecycle_projection import (
|
||
LIFECYCLE_STAGES,
|
||
project_lifecycle,
|
||
)
|
||
from app.services.shipping_notice.query_service import (
|
||
compute_batch_process_summary,
|
||
list_sorted_batch_tasks,
|
||
resolve_task_export_download,
|
||
serialize_batch_summary,
|
||
serialize_task_summary,
|
||
)
|
||
from app.services.shipping_notice.state_machine import (
|
||
CheckpointKind,
|
||
resolve_task_ui_state,
|
||
)
|
||
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
|
||
|
||
|
||
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
|
||
{"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": "freight_upload", "label": "货代上传"},
|
||
{"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"},
|
||
)
|
||
|
||
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
|
||
"step1_notice_submit": 0,
|
||
"step2_parse_confirm": 1,
|
||
"step3_inventory_prepare": 2,
|
||
"step2_inventory_prepare": 2,
|
||
"step4_align_confirm": 3,
|
||
"step5_match_inventory": 4,
|
||
"step3_inventory_match": 4,
|
||
"step4_shortage_review": 4,
|
||
"step6_generate_file": 5,
|
||
"step5_export_excel": 5,
|
||
"step7_upload_freight": 6,
|
||
"step6_upload_freight": 6,
|
||
"step7_finish": 6,
|
||
}
|
||
|
||
_TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"}
|
||
_BLOCKED_CHECKPOINTS = {
|
||
CP_PARSE_REVIEW,
|
||
CP_RSV_REQ,
|
||
CP_INVENTORY_SOURCE_REVIEW,
|
||
CP_ORDER_FREEZE,
|
||
RS_SHORTAGE_REVIEW,
|
||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||
CP_UPLOAD_REQ,
|
||
CP_UPLOAD_FAILED,
|
||
CP_UPLOAD_RESULT_UNKNOWN,
|
||
CP_CUSTOMER_REVIEW,
|
||
CP_EXPORT_READY,
|
||
CP_EXPORT_GENERATED,
|
||
}
|
||
|
||
_REVIEW_ENTRY_CHECKPOINTS = {
|
||
CP_PARSE_REVIEW,
|
||
CP_RSV_REQ,
|
||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||
}
|
||
|
||
_NEXT_AUTO_STEP_BY_CHECKPOINT: dict[str, str] = {
|
||
CP_INVENTORY_PENDING: "ensure_inventory",
|
||
CP_ORDER_FREEZE: "freeze_order",
|
||
CP_READY_MATCH: "match_inventory",
|
||
CP_READY_EXPORT: "generate_excel",
|
||
}
|
||
|
||
_PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
|
||
CP_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"),
|
||
CP_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"),
|
||
CP_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"),
|
||
CP_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"),
|
||
CP_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源规则正在重新裁决"),
|
||
CP_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"),
|
||
RS_SHORTAGE_REVIEW: ("shortage", "库存存在缺口"),
|
||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"),
|
||
CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"),
|
||
CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"),
|
||
CP_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"),
|
||
CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
|
||
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
|
||
}
|
||
|
||
# 业务人员可见的五阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
|
||
_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: "freight_upload",
|
||
CP_UPLOAD_REQ: "fulfillment_prep",
|
||
CP_UPLOAD_FAILED: "freight_upload",
|
||
CP_UPLOAD_RESULT_UNKNOWN: "freight_upload",
|
||
CP_UPLOADED: "freight_upload",
|
||
CP_COMPLETED: "freight_upload",
|
||
CP_REJECTED: "order_review",
|
||
}
|
||
|
||
|
||
def _task_lifecycle(
|
||
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
|
||
) -> dict[str, Any]:
|
||
"""以共享裁决器投影正式任务生命周期;旧 checkpoint 仅作无 Gate 的兼容兜底。"""
|
||
gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate')
|
||
legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ''))
|
||
if legacy_stage is None:
|
||
legacy_stage = 'freight_upload' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None
|
||
if legacy_stage is None:
|
||
# 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。
|
||
legacy_index = _derive_current_step_index(task)
|
||
legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload')[legacy_index]
|
||
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
|
||
|
||
return project_lifecycle(
|
||
current_gate=gate if isinstance(gate, dict) else None,
|
||
blocking_reason=(
|
||
{'code': process_gate.get('blocking_reason_code')}
|
||
if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code')
|
||
else None
|
||
),
|
||
legacy_stage=legacy_stage,
|
||
# ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。
|
||
has_candidate_context=True,
|
||
verified_upload_success=has_verified_upload_success(task),
|
||
)
|
||
|
||
|
||
def _business_stage(lifecycle: dict[str, Any]) -> dict[str, Any]:
|
||
"""将共享生命周期结果包装为任务详情既有的阶段 DTO。"""
|
||
stage_code = str(lifecycle.get('lifecycle_stage') or 'intake_parse')
|
||
index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), 0)
|
||
return {**LIFECYCLE_STAGES[index], 'index': index + 1, 'total': len(LIFECYCLE_STAGES)}
|
||
|
||
|
||
def _unified_action(action: dict[str, Any], *, default_kind: str = "recovery") -> dict[str, Any]:
|
||
"""规范 Gate/旧状态机动作,前端只渲染该统一结构。
|
||
|
||
``target_surface`` / ``target_anchor`` 均由 Gate 或 Artifact 授权来源声明;
|
||
生命周期页面只能按它们放置动作,禁止再从 action code、Excel 文件或上传状态推断。
|
||
"""
|
||
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,
|
||
# Gate 合同决定执行分派;前端不得再依据动作码猜测是 POST、跳转还是弹窗。
|
||
"dispatch": dispatch or "mutation",
|
||
"ui_handler": item.get("ui_handler"),
|
||
"enabled": bool(item.get("enabled", True)),
|
||
"requires_confirmation": bool(item.get("requires_confirmation", False)),
|
||
"target_surface": item.get("target_surface"),
|
||
"target_anchor": item.get("target_anchor"),
|
||
"disabled_reason": item.get("disabled_reason"),
|
||
"expected_gate_version": item.get("expected_gate_version"),
|
||
}
|
||
|
||
|
||
def _unified_actions(*, process_gate: dict[str, Any] | None) -> 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 = None
|
||
secondary_raw = []
|
||
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 精准定位;缺失时按复核、库存、导出、上传事实兜底。
|
||
"""
|
||
current_step = str(task.current_step or "").strip()
|
||
if current_step in _CURRENT_STEP_INDEX_MAP:
|
||
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
|
||
|
||
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 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 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 review_status in {
|
||
RS_PARSE_REVIEW,
|
||
PH_RSV_REQ,
|
||
} or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}:
|
||
return 1
|
||
return 0
|
||
|
||
|
||
def build_shipping_workflow_steps(
|
||
task: ShippingNotice,
|
||
checkpoint: str | None,
|
||
*,
|
||
lifecycle_stage: str | None = None,
|
||
) -> list[dict[str, str]]:
|
||
"""
|
||
构造五阶段流程状态。
|
||
|
||
Returns:
|
||
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
|
||
"""
|
||
lifecycle_index = next(
|
||
(index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage),
|
||
None,
|
||
)
|
||
# 正式 Gate 已存在时,五阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。
|
||
current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task)
|
||
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):
|
||
# ``upload_complete`` 已由唯一成功谓词裁决。历史 Task.upload_status 不能让
|
||
# 流程条伪装为完成,否则会与 lifecycle_entries 和批次完成率分叉。
|
||
if lifecycle_stage == "upload_complete":
|
||
status = "completed"
|
||
elif index < current_index:
|
||
status = "completed"
|
||
elif index == current_index:
|
||
status = "current"
|
||
else:
|
||
status = "pending"
|
||
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_NOTICE_TEXT_EXTRACTION_FAILED}
|
||
or pending_reason in {"low_confidence", PH_RSV_REQ}
|
||
)
|
||
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
|
||
|
||
|
||
_PARSE_STAGE_CHECKPOINTS = {
|
||
CP_PARSE_REVIEW,
|
||
CP_RSV_REQ,
|
||
CP_INVENTORY_SOURCE_REVIEW,
|
||
CP_ORDER_FREEZE,
|
||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||
}
|
||
|
||
_WARNING_DISPLAY_ALIASES: dict[str, str] = {
|
||
"parse_fallback_heuristic": "解析引擎回退到启发式规则,请人工核对字段。",
|
||
"heuristic_no_lines_detected": "启发式解析未识别到订单行,请核对通知内容。",
|
||
}
|
||
|
||
|
||
def _normalize_issue_text(raw: Any) -> str:
|
||
"""将 warnings / error 原文规范化为可展示短文案,过滤空值。"""
|
||
text = str(raw or "").strip()
|
||
if not text:
|
||
return ""
|
||
return _WARNING_DISPLAY_ALIASES.get(text, text)
|
||
|
||
|
||
def _append_unique_issue(issues: list[str], raw: Any) -> None:
|
||
"""追加去重后的问题文案,保持首次出现顺序。"""
|
||
text = _normalize_issue_text(raw)
|
||
if text and text not in issues:
|
||
issues.append(text)
|
||
|
||
|
||
def _parse_validation_issue_text(issue: dict[str, Any]) -> str:
|
||
"""把关键字段问题转换成工作台文案,并保留行号、内部料号与原始值。"""
|
||
line_no = int(issue.get("line_index") or 0) + 1
|
||
part_number = str(issue.get("part_number") or "-").strip() or "-"
|
||
raw_value = str(issue.get("raw_value") or "").strip()
|
||
resolved_value = str(issue.get("resolved_value") or "").strip()
|
||
reason = str(issue.get("reason") or "").strip()
|
||
if reason == "value_corrected":
|
||
return f"第 {line_no} 行料号 {part_number}:Reservation ID 已由 {raw_value or '空值'} 纠正为 {resolved_value}。"
|
||
if reason == "source_conflict":
|
||
values = ", ".join(str(item) for item in issue.get("evidence_values") or [])
|
||
return f"第 {line_no} 行料号 {part_number}:Reservation ID {raw_value or '空值'} 与原文列证据 {values or '-'} 冲突。"
|
||
if reason == "invalid_format":
|
||
return f"第 {line_no} 行料号 {part_number}:Reservation ID {raw_value or '空值'} 格式不合法。"
|
||
return f"第 {line_no} 行料号 {part_number}:缺少合法的 Reservation ID。"
|
||
|
||
|
||
def _collect_parse_stage_issues(task: ShippingNotice, checkpoint: str | None) -> list[str]:
|
||
"""
|
||
汇总文件解析阶段(步骤 2)全部待处理问题,供工作台一次列出。
|
||
|
||
核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发;
|
||
以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。
|
||
"""
|
||
checkpoint_value = str(checkpoint or "").strip()
|
||
if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS:
|
||
return []
|
||
|
||
issues: list[str] = []
|
||
if checkpoint_value == CP_INVENTORY_SOURCE_REVIEW:
|
||
_append_unique_issue(
|
||
issues,
|
||
task.error_message or "无法根据发货通知唯一确定库存查询来源",
|
||
)
|
||
elif checkpoint_value == CP_RSV_REQ:
|
||
_append_unique_issue(
|
||
issues,
|
||
task.error_message or "解析失败:未识别到 Reservation ID / COM ID(预定单号)",
|
||
)
|
||
elif checkpoint_value == CP_NOTICE_TEXT_EXTRACTION_FAILED:
|
||
_append_unique_issue(
|
||
issues,
|
||
task.error_message or "未能从发货通知中解析到可审核内容",
|
||
)
|
||
elif checkpoint_value == CP_PARSE_REVIEW:
|
||
_append_unique_issue(issues, "通知单解析置信度不足,需要复核单头或明细。")
|
||
if not is_inventory_source_stable(task):
|
||
_append_unique_issue(
|
||
issues,
|
||
"解析确认通过后,若库存源仍无法唯一命中,还需选择正式库存源。",
|
||
)
|
||
|
||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||
progress = payload.get("current_step_progress") if isinstance(payload, dict) else None
|
||
extra = progress.get("extra") if isinstance(progress, dict) else None
|
||
warnings = extra.get("warnings") if isinstance(extra, dict) else None
|
||
if isinstance(warnings, list):
|
||
for item in warnings:
|
||
_append_unique_issue(issues, item)
|
||
|
||
parse_validation = payload.get("parse_validation") if isinstance(payload, dict) else None
|
||
structured_issues = parse_validation.get("issues") if isinstance(parse_validation, dict) else None
|
||
if isinstance(structured_issues, list):
|
||
for item in structured_issues:
|
||
if isinstance(item, dict):
|
||
_append_unique_issue(issues, _parse_validation_issue_text(item))
|
||
|
||
return issues
|
||
|
||
|
||
def _entry_surface_for(checkpoint: str | None, kind: CheckpointKind) -> str:
|
||
"""
|
||
解析当前操作应进入的工作台类型。
|
||
|
||
Returns:
|
||
review_workbench | task_workbench | none
|
||
"""
|
||
# Excel 就绪虽为 wait_manual_upload,仍进任务工作台以便下载与登记凭据。
|
||
if str(checkpoint or "") in {CP_EXPORT_READY, CP_EXPORT_GENERATED}:
|
||
return "task_workbench"
|
||
if kind == CheckpointKind.COMPLETE:
|
||
return "none"
|
||
if str(checkpoint or "") in _REVIEW_ENTRY_CHECKPOINTS:
|
||
return "review_workbench"
|
||
if kind in {CheckpointKind.MUST_HUMAN, CheckpointKind.WAIT_MANUAL_UPLOAD}:
|
||
return "task_workbench"
|
||
if kind == CheckpointKind.AUTO_CONTINUE and checkpoint in {
|
||
CP_ORDER_FREEZE,
|
||
CP_READY_MATCH,
|
||
CP_READY_EXPORT,
|
||
CP_INVENTORY_PENDING,
|
||
}:
|
||
# 自动链可继续,但仍允许工作台手动兜底
|
||
return "task_workbench"
|
||
return "none"
|
||
|
||
|
||
def _current_todo_label(checkpoint: str | None) -> str | None:
|
||
"""从内部 checkpoint 提取只读待办说明,不派生用户动作。"""
|
||
pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||
return pause[1] if pause else None
|
||
|
||
|
||
def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
|
||
"""
|
||
投影 STP 履约事实供 Chat/工作台/待办同源消费。
|
||
|
||
核心逻辑:只读 task + step_payload;无 STP 痕迹时返回 None,避免普通任务噪声。
|
||
|
||
Args:
|
||
task: 发货任务。
|
||
|
||
Returns:
|
||
stp_facts 字典或 None。
|
||
"""
|
||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||
project_inventory_candidate_facts,
|
||
)
|
||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||
from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes
|
||
from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS
|
||
|
||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||
status = str(task.inventory_source_status or '').strip()
|
||
method = str(task.inventory_source_method or '').strip()
|
||
resolutions_raw = payload.get('line_inventory_resolutions')
|
||
resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else []
|
||
multi_block = bool(payload.get('multi_source_excel_block'))
|
||
candidate_projection = project_inventory_candidate_facts(task)
|
||
frozen_codes = (
|
||
list(candidate_projection.get('candidate_source_codes') or [])
|
||
or list(
|
||
(payload.get('line_inventory_candidates') or {}).get('source_codes') or []
|
||
)
|
||
or task_frozen_inventory_source_codes(task)
|
||
)
|
||
has_stp = (
|
||
status in {'candidates_frozen', 'resolved'}
|
||
or method.startswith('stp')
|
||
or bool(frozen_codes)
|
||
or bool(resolutions)
|
||
or multi_block
|
||
or bool(candidate_projection.get('current_set'))
|
||
)
|
||
if not has_stp:
|
||
return None
|
||
|
||
counts: dict[str, int] = {}
|
||
compact_resolutions: list[dict[str, Any]] = []
|
||
resolution_source = list(candidate_projection.get('line_resolutions') or []) or resolutions
|
||
for item in resolution_source:
|
||
disposition = str(item.get('disposition') or 'unknown')
|
||
counts[disposition] = counts.get(disposition, 0) + 1
|
||
compact_resolutions.append({
|
||
'line_index': item.get('line_index'),
|
||
'line_key': item.get('line_key'),
|
||
'disposition': disposition,
|
||
'effective_reservation_id': item.get('effective_reservation_id'),
|
||
'part_number': item.get('part_number'),
|
||
'resolved_inventory_source_code': item.get('resolved_inventory_source_code'),
|
||
'inventory_file_no': item.get('inventory_file_no'),
|
||
'inventory_file_sha256': item.get('inventory_file_sha256'),
|
||
'inventory_row_index': item.get('inventory_row_index'),
|
||
'match_attempt_id': item.get('match_attempt_id'),
|
||
'required_qty': item.get('required_qty'),
|
||
'matched_qty': item.get('matched_qty'),
|
||
'shortage_qty': item.get('shortage_qty'),
|
||
'inventory_row_ref': item.get('inventory_row_ref'),
|
||
})
|
||
|
||
recovery_codes = multi_source_recovery_source_codes(task)
|
||
facts = {
|
||
'inventory_source_status': status or None,
|
||
'inventory_source_code': str(task.inventory_source_code or '').strip().upper() or None,
|
||
'inventory_source_method': method or None,
|
||
'frozen_candidate_codes': [str(code).strip().upper() for code in frozen_codes if str(code or '').strip()],
|
||
'candidate_set_id': candidate_projection.get('candidate_set_id'),
|
||
'candidate_set_version': candidate_projection.get('candidate_set_version'),
|
||
'candidate_set_status': candidate_projection.get('candidate_set_status'),
|
||
'candidate_source_codes': list(candidate_projection.get('candidate_source_codes') or []),
|
||
'prepared_source_codes': list(candidate_projection.get('prepared_source_codes') or []),
|
||
'pending_source_codes': list(candidate_projection.get('pending_source_codes') or []),
|
||
'failed_source_codes': list(candidate_projection.get('failed_source_codes') or []),
|
||
'source_attempts': dict(candidate_projection.get('source_attempts') or {}),
|
||
'resolution_counts': counts,
|
||
'line_resolutions': compact_resolutions,
|
||
'multi_source_excel_block': multi_block,
|
||
'resolved_ok_source_codes': [
|
||
str(code).strip().upper()
|
||
for code in (payload.get('resolved_ok_source_codes') or [])
|
||
if str(code or '').strip()
|
||
],
|
||
'recovery_source_codes': recovery_codes,
|
||
'match_status': str(task.match_status or '').strip() or None,
|
||
}
|
||
return {key: facts[key] for key in STP_FACTS_ALLOWED_KEYS if key in facts}
|
||
|
||
|
||
def _build_task_summary(
|
||
task: ShippingNotice,
|
||
checkpoint: str | None,
|
||
*,
|
||
checkpoint_kind: CheckpointKind,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。
|
||
|
||
核心逻辑:保留 title/message/issues;补充 stage、checkpoint_kind、current_todo、
|
||
pause_reason、next_auto_step、event_at、entry_surface、allowed_actions、stp_facts、
|
||
progress_nodes(固定节点顺序,禁止前端算百分比)。
|
||
"""
|
||
title = user_facing_task_stage(task)
|
||
message_by_checkpoint: dict[str, str] = {
|
||
CP_PARSE_REVIEW: "解析结果需要人工确认后才能继续。",
|
||
CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
|
||
CP_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。",
|
||
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
|
||
CP_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。",
|
||
CP_INVENTORY_SOURCE_REVIEW: "库存源规则正在重新裁决。",
|
||
CP_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。",
|
||
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
|
||
CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。",
|
||
CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。",
|
||
CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
|
||
CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
|
||
CP_WAITING_UPLOAD: "待人工上传登记:请下载 Excel,在货代平台上传后于本系统登记凭据。",
|
||
CP_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。",
|
||
CP_REJECTED: "任务已驳回,无需继续处理。",
|
||
CP_UPLOADED: "任务已完成上传。",
|
||
CP_COMPLETED: "任务已关闭。",
|
||
}
|
||
issues = _collect_parse_stage_issues(task, checkpoint)
|
||
pause = _PAUSE_REASON_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||
pause_reason_code = pause[0] if pause else (task.pending_human_reason or None)
|
||
pause_reason = pause[1] if pause else (task.error_message or task.upload_error_message or None)
|
||
message = message_by_checkpoint.get(str(checkpoint or ""), title)
|
||
stp_facts = _build_stp_facts(task)
|
||
current_todo_override: str | None = None
|
||
|
||
# [STEP] STP 多源 Excel 阻断:覆盖通用 shortage 文案,并提示可指定库存源。
|
||
if stp_facts and stp_facts.get('multi_source_excel_block'):
|
||
pause_reason_code = 'multi_source_excel_block'
|
||
pause_reason = '订单行命中多个不同库存源,首期无法生成单一发货 Excel,请拆单或人工指定库存源后继续'
|
||
message = pause_reason
|
||
title = '多库存源冲突,待人工处理'
|
||
issue_text = pause_reason
|
||
if issue_text not in issues:
|
||
issues = [*issues, issue_text]
|
||
current_todo_override = '请拆单或人工指定库存源后继续'
|
||
elif stp_facts and str(stp_facts.get('inventory_source_status') or '') == 'candidates_frozen' and checkpoint_kind == CheckpointKind.AUTO_CONTINUE:
|
||
message = '多候选库存源已冻结,系统正在准备库存并跨文件匹配。'
|
||
|
||
if checkpoint_kind == CheckpointKind.AUTO_CONTINUE and not (stp_facts and stp_facts.get('multi_source_excel_block')):
|
||
pause_reason = None
|
||
pause_reason_code = None
|
||
event_at = None
|
||
if task.updated_at is not None:
|
||
event_at = task.updated_at.isoformat()
|
||
summary: dict[str, Any] = {
|
||
"title": title,
|
||
"message": message,
|
||
"error_message": task.error_message or task.upload_error_message,
|
||
"issues": issues,
|
||
"stage": title,
|
||
"checkpoint_kind": str(checkpoint_kind),
|
||
"current_todo": (
|
||
current_todo_override
|
||
if current_todo_override is not None
|
||
else (
|
||
pause_reason
|
||
if stp_facts and stp_facts.get('multi_source_excel_block')
|
||
else _current_todo_label(checkpoint)
|
||
)
|
||
),
|
||
"pause_reason": pause_reason,
|
||
"pause_reason_code": pause_reason_code,
|
||
"next_auto_step": (
|
||
_NEXT_AUTO_STEP_BY_CHECKPOINT.get(str(checkpoint or ""))
|
||
if checkpoint_kind == CheckpointKind.AUTO_CONTINUE
|
||
else None
|
||
),
|
||
"event_at": event_at,
|
||
"entry_surface": _entry_surface_for(checkpoint, checkpoint_kind),
|
||
"allowed_actions": [],
|
||
}
|
||
if stp_facts is not None:
|
||
summary['stp_facts'] = stp_facts
|
||
# [STEP] 对话侧固定节点梯;前端只渲染 status,不自行推导百分比。
|
||
from app.services.shipping_notice.stp_progress_contract import project_task_progress_nodes
|
||
|
||
summary['progress_nodes'] = project_task_progress_nodes(task)
|
||
return summary
|
||
|
||
|
||
def _build_stage_context(
|
||
task: ShippingNotice,
|
||
*,
|
||
lifecycle_stage: str,
|
||
stp_facts: dict[str, Any] | None,
|
||
process_gate: dict[str, Any] | None,
|
||
) -> dict[str, Any]:
|
||
"""构造五阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。
|
||
|
||
通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成
|
||
只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。
|
||
"""
|
||
from app.models.shipping_excel_template import ShippingExportArtifact
|
||
from app.models.shipping_fulfillment import (
|
||
ShippingInventoryVerification,
|
||
ShippingUploadAttempt,
|
||
)
|
||
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
|
||
from app.models.shipping_notice_line import ShippingNoticeLine
|
||
|
||
facts = stp_facts if isinstance(stp_facts, dict) else {}
|
||
raw_rows = task.line_results_json if isinstance(task.line_results_json, list) else []
|
||
fact_rows = facts.get('line_resolutions') if isinstance(facts.get('line_resolutions'), list) else []
|
||
fact_by_key = {
|
||
str(row.get('line_key') or ''): row
|
||
for row in fact_rows
|
||
if isinstance(row, dict) and str(row.get('line_key') or '')
|
||
}
|
||
# 正式结构化匹配事实是通知准备的首要来源;旧 JSON/STP 仅作为历史任务兼容回退。
|
||
current_match_rows = (
|
||
ShippingNoticeLineInventoryMatch.query
|
||
.filter_by(task_id=task.id, is_current=True)
|
||
.order_by(ShippingNoticeLineInventoryMatch.line_index, ShippingNoticeLineInventoryMatch.id)
|
||
.all()
|
||
if getattr(task, 'id', None) is not None else []
|
||
)
|
||
match_by_key = {
|
||
str(row.line_key or ''): row
|
||
for row in current_match_rows
|
||
if str(row.line_key or '')
|
||
}
|
||
match_by_index = {
|
||
int(row.line_index): row
|
||
for row in current_match_rows
|
||
if row.line_index is not None
|
||
}
|
||
verification_rows: dict[str, dict[str, Any]] = {}
|
||
latest_verification = (
|
||
ShippingInventoryVerification.query
|
||
.filter_by(task_id=task.id, status='completed')
|
||
.order_by(ShippingInventoryVerification.created_at.desc(), ShippingInventoryVerification.id.desc())
|
||
.first()
|
||
if getattr(task, 'id', None) is not None else None
|
||
)
|
||
if latest_verification is not None:
|
||
# 核验行没有 line_key,按冻结订单行/Reservation 顺序作为最后一级兼容回退。
|
||
for position, verification_line in enumerate(latest_verification.lines):
|
||
verification_rows[str(position)] = {
|
||
'required_qty': verification_line.required_qty,
|
||
'available_qty': verification_line.available_qty,
|
||
'shortage_qty': (
|
||
max(verification_line.required_qty - verification_line.available_qty, 0)
|
||
if verification_line.required_qty is not None and verification_line.available_qty is not None
|
||
else None
|
||
),
|
||
'status': verification_line.status,
|
||
}
|
||
# 冻结订单与库存匹配是不同事实:库存文件尚未准备好时,用户仍必须能核对
|
||
# 已冻结的预约号、料号和需求数量。禁止用“是否有匹配结果”决定订单行是否展示。
|
||
frozen_order_lines: list[dict[str, Any]] = []
|
||
preparation_lines: list[dict[str, Any]] = []
|
||
notice_lines = (
|
||
ShippingNoticeLine.query.filter_by(notice_id=task.id).order_by(ShippingNoticeLine.position).all()
|
||
if getattr(task, 'id', None) is not None else []
|
||
)
|
||
for line in notice_lines:
|
||
frozen_order_lines.append({
|
||
'line_key': getattr(line, 'line_key', None),
|
||
'reservation_id': getattr(line, 'reservation_id', None),
|
||
'part_number': getattr(line, 'part_number', None),
|
||
'required_qty': str(getattr(line, 'required_qty', None)) if getattr(line, 'required_qty', None) is not None else None,
|
||
})
|
||
|
||
# 匹配表只输出已经存在的匹配/核验事实。历史任务尚未双写正式行时可用旧 JSON
|
||
# 兼容,但绝不能把未匹配的冻结订单行伪装为“库存匹配结果”。
|
||
row_count = max(len(raw_rows), len(fact_rows), len(current_match_rows))
|
||
for index in range(row_count):
|
||
line = notice_lines[index] if index < len(notice_lines) else None
|
||
match_row = match_by_key.get(str(getattr(line, 'line_key', '') or '')) or match_by_index.get(index)
|
||
structured = ({
|
||
'line_key': match_row.line_key,
|
||
'reservation_id': match_row.reservation_id,
|
||
'part_number': match_row.part_number,
|
||
'required_qty': match_row.required_qty,
|
||
'available_qty': match_row.matched_qty or match_row.available_qty,
|
||
'shortage_qty': match_row.shortage_qty,
|
||
'resolved_inventory_source_code': match_row.inventory_source_code,
|
||
'disposition': match_row.match_result,
|
||
} if match_row is not None else {})
|
||
legacy_source = fact_by_key.get(
|
||
str(getattr(line, 'line_key', '') or ''),
|
||
fact_rows[index] if index < len(fact_rows) and isinstance(fact_rows[index], dict) else {},
|
||
)
|
||
# 结构化事实优先,但不以空值覆盖历史/STP 投影中仍有价值的证据字段。
|
||
source = {
|
||
**(legacy_source if isinstance(legacy_source, dict) else {}),
|
||
**{
|
||
key: value
|
||
for key, value in structured.items()
|
||
if value is not None and value != ''
|
||
},
|
||
}
|
||
verification = verification_rows.get(str(index), {})
|
||
result = raw_rows[index] if index < len(raw_rows) and isinstance(raw_rows[index], dict) else {}
|
||
required_qty = result.get('required_qty', source.get('required_qty', verification.get('required_qty', getattr(line, 'required_qty', None))))
|
||
available_qty = result.get('available_qty', source.get('available_qty', source.get('matched_qty', verification.get('available_qty'))))
|
||
shortage_qty = result.get('shortage_qty', source.get('shortage_qty', verification.get('shortage_qty')))
|
||
preparation_lines.append({
|
||
'line_key': getattr(line, 'line_key', None) or source.get('line_key'),
|
||
'reservation_id': result.get('reservation_id') or source.get('effective_reservation_id') or source.get('reservation_id') or getattr(line, 'reservation_id', None),
|
||
'part_number': result.get('part_number') or source.get('part_number') or getattr(line, 'part_number', None),
|
||
'required_qty': required_qty,
|
||
'available_qty': available_qty,
|
||
'shortage_qty': shortage_qty,
|
||
'source_code': source.get('resolved_inventory_source_code') or source.get('inventory_source_code'),
|
||
'status': result.get('line_status') or source.get('disposition') or verification.get('status') or None,
|
||
})
|
||
|
||
has_match_result = bool(current_match_rows or raw_rows or any(
|
||
row.get('matched_qty') is not None
|
||
or row.get('shortage_qty') is not None
|
||
or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage'}
|
||
for row in fact_rows if isinstance(row, dict)
|
||
))
|
||
gate = process_gate if isinstance(process_gate, dict) else {}
|
||
gate_code = str((gate.get('current_blocking_gate') or gate.get('current_gate') or {}).get('gate_code') or '')
|
||
preparation_status = (
|
||
'ready' if has_match_result else
|
||
'blocked' if gate_code else
|
||
'processing'
|
||
)
|
||
|
||
inventory_sources: list[dict[str, Any]] = []
|
||
latest_preparation = None
|
||
if getattr(task, 'id', None):
|
||
from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt
|
||
|
||
latest_preparation = (
|
||
ShippingInventoryPreparationAttempt.query
|
||
.filter_by(task_id=task.id)
|
||
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
|
||
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
|
||
.first()
|
||
)
|
||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||
|
||
downloadable_inventory = resolve_task_inventory_download(task)
|
||
for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []):
|
||
inventory_sources.append({
|
||
'source_code': source_attempt.source_code,
|
||
'status': source_attempt.status,
|
||
'inventory_file_id': source_attempt.inventory_file_id,
|
||
})
|
||
|
||
artifact = None
|
||
attempts = []
|
||
if getattr(task, 'id', None):
|
||
artifact = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by(
|
||
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
|
||
).first()
|
||
attempts = ShippingUploadAttempt.query.join(
|
||
ShippingExportArtifact,
|
||
ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id,
|
||
).filter(
|
||
ShippingExportArtifact.task_id == task.id,
|
||
).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all()
|
||
latest_attempt = attempts[0] if attempts else None
|
||
succeeded_attempt = next(
|
||
(item for item in attempts if str(getattr(item, 'status', '') or '').lower() == 'succeeded'),
|
||
None,
|
||
)
|
||
latest_status = str(getattr(latest_attempt, 'status', '') or '').lower()
|
||
upload_outcome = (
|
||
'succeeded' if latest_status == 'succeeded' else
|
||
'failed' if latest_status in {'failed', 'timed_out'} else
|
||
'unknown' if latest_status == 'unknown' else
|
||
'running' if latest_status in {'pending', 'running'} else
|
||
'awaiting_manual' if lifecycle_stage == 'freight_upload' else
|
||
'not_started'
|
||
)
|
||
return {
|
||
'preparation': {
|
||
'status': preparation_status,
|
||
'reason_code': gate.get('blocking_reason_code') or None,
|
||
'frozen_order': {
|
||
'task_no': task.task_no,
|
||
'snapshot_id': task.order_snapshot_id,
|
||
},
|
||
'inventory_source_code': facts.get('inventory_source_code'),
|
||
'match_status': facts.get('match_status'),
|
||
'frozen_order_lines': frozen_order_lines,
|
||
'lines': preparation_lines,
|
||
'has_match_result': has_match_result,
|
||
# 任务级库存准备源只说明文件获取进度;实际匹配源必须从 lines[].source_code 读取。
|
||
'inventory_sources': inventory_sources,
|
||
'inventory_file': {
|
||
'available': downloadable_inventory is not None,
|
||
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,
|
||
},
|
||
'artifact': {
|
||
'file_name': artifact.file_name if artifact is not None else None,
|
||
'status': artifact.status if artifact is not None else 'not_generated',
|
||
},
|
||
},
|
||
'upload': {
|
||
'outcome': upload_outcome,
|
||
# 成功工作面只能消费该不可变成功事实,而非“最近一条 Attempt”。后者可能
|
||
# 是迟到失败或人工核对记录,不能反向定义完成证据。
|
||
'succeeded_attempt': ({
|
||
'id': succeeded_attempt.id,
|
||
'status': succeeded_attempt.status,
|
||
'mode': succeeded_attempt.mode,
|
||
'freight_ref_no': succeeded_attempt.freight_ref_no,
|
||
'finished_at': succeeded_attempt.finished_at.isoformat() if succeeded_attempt.finished_at else None,
|
||
} if succeeded_attempt is not None else None),
|
||
'latest_attempt': ({
|
||
'id': latest_attempt.id,
|
||
'status': latest_attempt.status,
|
||
'mode': latest_attempt.mode,
|
||
'freight_ref_no': latest_attempt.freight_ref_no,
|
||
'error_code': latest_attempt.error_code,
|
||
'finished_at': latest_attempt.finished_at.isoformat() if latest_attempt.finished_at else None,
|
||
} if latest_attempt is not None else None),
|
||
},
|
||
}
|
||
|
||
|
||
def build_task_ui_state(
|
||
task: ShippingNotice,
|
||
*,
|
||
include_stage_context: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
构建单票任务 UI State。
|
||
|
||
核心逻辑:所有 UI 入口只消费这里输出的 stage/checkpoint/todo/actions/summary,
|
||
禁止 Chat、通知卡与任务中心分别推导状态;checkpoint 仅保留内部状态/自动推进,
|
||
可点击用户动作只由 Gate 与已验证 Artifact 授权产生。
|
||
"""
|
||
ui = resolve_task_ui_state(task)
|
||
process_gate = _process_gate_user_summary_for_task(task)
|
||
lifecycle = _task_lifecycle(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
|
||
stage = _business_stage(lifecycle)
|
||
steps = build_shipping_workflow_steps(task, ui.checkpoint, lifecycle_stage=stage['code'])
|
||
current_index = int(stage['index']) - 1
|
||
current_step = steps[current_index] if 0 <= current_index < len(steps) else None
|
||
summary = _build_task_summary(
|
||
task,
|
||
ui.checkpoint,
|
||
checkpoint_kind=ui.checkpoint_kind,
|
||
)
|
||
if process_gate is not None:
|
||
summary['process_gate'] = process_gate
|
||
# 仅输出当前 Gate;删除旧门禁重复摘要键(若历史调用方写入)。
|
||
summary.pop('auto_build_gates', None)
|
||
summary.pop('failed_gates', None)
|
||
if process_gate.get('blocking_message'):
|
||
summary['current_blocking_message'] = process_gate['blocking_message']
|
||
if process_gate.get('diagnostic_hint'):
|
||
summary['diagnostic_hint'] = process_gate['diagnostic_hint']
|
||
if process_gate.get('current_blocking_gate'):
|
||
summary['allowed_actions'] = []
|
||
actions = _unified_actions(process_gate=process_gate)
|
||
# [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作,
|
||
# 两者不能相互覆盖。即使当前 Gate 阻断并清空旧 checkpoint 动作,也只在
|
||
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
|
||
if resolve_task_export_download(task) is not None:
|
||
download_action = _unified_action({
|
||
'id': 'download_excel',
|
||
'label': '下载 Excel',
|
||
'kind': 'view',
|
||
'dispatch': 'view',
|
||
'ui_handler': 'excel_download',
|
||
'enabled': True,
|
||
# Artifact 已验证是下载授权的唯一来源;它直接声明展示位置,
|
||
# 不依赖旧 checkpoint 或 action code 位置映射。
|
||
'target_surface': 'freight_upload',
|
||
'target_anchor': 'excel_artifact',
|
||
}, default_kind='view')
|
||
action_codes = {
|
||
str((action or {}).get('code') or '')
|
||
for action in [actions.get('primary'), *(actions.get('secondary') or [])]
|
||
}
|
||
if download_action['code'] not in action_codes:
|
||
actions['secondary'].append(download_action)
|
||
# summary 仅作为 ui_state.actions 的只读镜像,禁止由 checkpoint 或任务字段另行推导。
|
||
summary['allowed_actions'] = [
|
||
str(item.get('code'))
|
||
for item in [actions.get('primary'), *(actions.get('secondary') or [])]
|
||
if isinstance(item, dict) and str(item.get('code') or '').strip()
|
||
]
|
||
stage_context = (
|
||
_build_stage_context(
|
||
task,
|
||
lifecycle_stage=stage['code'],
|
||
stp_facts=summary.get('stp_facts'),
|
||
process_gate=process_gate,
|
||
)
|
||
if include_stage_context else None
|
||
)
|
||
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,
|
||
"stage": stage,
|
||
"lifecycle_stage": stage["code"],
|
||
"lifecycle_entries": lifecycle['lifecycle_entries'],
|
||
"lifecycle_authority": lifecycle['lifecycle_authority'],
|
||
"checkpoint": checkpoint_payload,
|
||
"checkpoint_view": checkpoint_payload,
|
||
"todo": {
|
||
"title": summary.get("current_todo") or summary.get("title"),
|
||
"message": summary.get("message"),
|
||
},
|
||
"actions": actions,
|
||
# 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。
|
||
**({'stage_context': stage_context} if stage_context is not None else {}),
|
||
"reason": reason,
|
||
"lifecycle_status": task.lifecycle_status,
|
||
"checkpoint_code": ui.checkpoint,
|
||
"checkpoint_kind": str(ui.checkpoint_kind),
|
||
"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,
|
||
"process_gate": process_gate,
|
||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||
}
|
||
|
||
|
||
def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None:
|
||
"""
|
||
按 Task 查找活动 Execution 的用户 Gate 摘要。
|
||
|
||
核心逻辑:Task 本身即正式 OT,套用 apply_post_ot_gate_rules,
|
||
使 inventory_preparation 等系统等待不进入 current_blocking_gate。
|
||
|
||
Returns:
|
||
用户态 Gate 摘要;无 Execution 时 None。
|
||
"""
|
||
from app.models import ShippingProcessExecution
|
||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||
apply_post_ot_gate_rules,
|
||
)
|
||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||
|
||
task_id = getattr(task, 'id', None)
|
||
if task_id is None:
|
||
return None
|
||
try:
|
||
task_pk = int(task_id)
|
||
except (TypeError, ValueError):
|
||
return None
|
||
execution = (
|
||
ShippingProcessExecution.query
|
||
.filter_by(task_id=task_pk)
|
||
.filter(ShippingProcessExecution.status != 'superseded')
|
||
.order_by(ShippingProcessExecution.id.desc())
|
||
.first()
|
||
)
|
||
if execution is None:
|
||
return None
|
||
return apply_post_ot_gate_rules(
|
||
project_user_gate_summary(execution),
|
||
has_formal_ot=True,
|
||
)
|
||
|
||
|
||
def build_batch_ui_state(batch: Any) -> dict[str, Any]:
|
||
"""
|
||
构建批次级会话上传集合摘要(非履约写操作面)。
|
||
|
||
Raises:
|
||
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
|
||
"""
|
||
del batch
|
||
raise_shipping_batches_removed()
|