Files
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00

1452 lines
68 KiB
Python
Raw Permalink 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/ui_state.py
用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
依赖:models.ShippingNotice/ShippingOrderTask/ShippingProcessExecution、state_machine(UserMode/位置回退)、
query_service、constants.POSITION_*、process_gate_contract.derive_*/STAGE_CAPABILITY_DEFINITIONS、
process_gate_projection、line_onhand_match_projection、onhand_candidate_projection、
order_review_fulfillment_decision_service(短缺放行模板字段)、
order_review_workbench_projection、onhand_source_repository(preparation.source_options)。
逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode);
Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id);
五阶段 processing_stage 同样经 Notice→OT.stage(Notice 无 stage 列),
禁止仅靠 Gate 兜底把 order_freeze 误映射为订单复核;
stage_context.preparation 值列(预约号/料号/需求数量)有效值优先(快照 + 已接受修正,
经 effective_line_facts_for_notice),无有效值时回退快照列;匹配结果列仍以 Snapshot 行
+ 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT),
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
prep 行直透投影 part_available_qty(料号兜底总量,仅库存就绪时非空)供前端「可用数量」列;
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要;
project_notice_available_actions 供货代上传聚合行内菜单轻量消费。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingNotice
from app.services.shipping_notice.constants import (
POSITION_COMPLETED,
POSITION_CUSTOMER_REVIEW,
POSITION_EXPORT_GENERATED,
POSITION_EXPORT_READY,
POSITION_INVENTORY_PENDING,
POSITION_INVENTORY_SOURCE_REVIEW,
POSITION_ORDER_FREEZE,
POSITION_NOTICE_TEXT_EXTRACTION_FAILED,
POSITION_PARSE_REVIEW,
POSITION_READY_EXPORT,
POSITION_READY_MATCH,
POSITION_REJECTED,
POSITION_RSV_REQ,
POSITION_UPLOADED,
POSITION_UPLOAD_FAILED,
POSITION_UPLOAD_RESULT_UNKNOWN,
POSITION_UPLOAD_REQ,
POSITION_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.onhand_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 (
can_download_task_export,
resolve_task_export_download,
serialize_task_summary,
)
from app.services.shipping_notice.state_machine import (
UserMode,
)
from app.services.shipping_notice.user_facing_status import (
user_facing_stage_label_for_position,
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": "通知完成"},
)
_REVIEW_ENTRY_POSITIONS = {
POSITION_PARSE_REVIEW,
POSITION_RSV_REQ,
POSITION_NOTICE_TEXT_EXTRACTION_FAILED,
}
_NEXT_AUTO_STEP_BY_POSITION: dict[str, str] = {
POSITION_INVENTORY_PENDING: "ensure_onhand",
POSITION_ORDER_FREEZE: "freeze_order",
POSITION_READY_MATCH: "match_inventory",
POSITION_READY_EXPORT: "generate_excel",
}
_PAUSE_REASON_BY_POSITION: dict[str, tuple[str, str]] = {
POSITION_PARSE_REVIEW: ("parse_review_required", "解析结果需要人工确认"),
POSITION_RSV_REQ: ("rsv_required", "缺少后续匹配必需字段"),
POSITION_CUSTOMER_REVIEW: ("customer_ambiguous", "客户未唯一确认"),
POSITION_UPLOAD_REQ: ("inventory_unavailable", "需要提供库存数据或重试库存获取"),
POSITION_INVENTORY_SOURCE_REVIEW: ("inventory_source_unresolved", "库存源规则正在重新裁决"),
POSITION_ORDER_FREEZE: ("order_freeze_pending", "订单待冻结后进入库存履约"),
RS_SHORTAGE_REVIEW: ("shortage", "库存存在缺口"),
POSITION_NOTICE_TEXT_EXTRACTION_FAILED: ("notice_text_extraction_failed", "通知文本解析失败"),
POSITION_UPLOAD_FAILED: ("upload_failed", "货代上传失败"),
POSITION_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"),
POSITION_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"),
POSITION_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"),
POSITION_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"),
}
def _task_lifecycle(
*, task: ShippingNotice, position: str | None, process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。
核心逻辑:``processing_stage`` 与批次/工作台同源——优先实体 ``stage``,
Notice 无 stage 列时经 ``order_task_id`` 读 OT.stage;再用正式 Gate 做
**仅向前**抬升(与 reconcile BE-08 / sync_order_task_stage_for_notice 同表)。
``order_freeze_readiness`` 不在抬升表中,故不能把 OT.stage=order_creating
压回「订单复核」。
"""
del position # 生命周期不再由位置码推导。
gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate')
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
from app.services.shipping_notice.processing_projection_invariants import (
shipping_processing_stage_index,
)
from app.services.shipping_notice.order_task_stage_machine import (
_PROCESS_GATE_TO_PROCESSING_STAGE,
)
# 有正式 Gate 或已验证上传时才开放五阶段入口;否则保持 unclassified(禁止旧 CP 冒充)。
has_formal = bool(
isinstance(process_gate, dict)
and (
process_gate.get('current_gate_code')
or process_gate.get('current_blocking_gate')
or process_gate.get('current_gate')
)
)
# [STEP 1] Notice 无 stage 列;进度权威在 OT。
processing_stage = str(getattr(task, 'stage', None) or '').strip() or None
if not processing_stage:
order_task = _resolve_order_task_for_gate_lookup(task)
if order_task is not None:
processing_stage = str(getattr(order_task, 'stage', None) or '').strip() or None
# [STEP 2] Gate→15 阶仅向前抬升;禁止 freeze 等建单前 Gate 回拉后半段。
gate_code = ''
if isinstance(gate, dict):
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower()
if not gate_code and isinstance(process_gate, dict):
gate_code = str(process_gate.get('current_gate_code') or '').strip().lower()
gate_as_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code)
if gate_as_stage:
stage_idx = shipping_processing_stage_index(processing_stage)
gate_idx = shipping_processing_stage_index(gate_as_stage)
if stage_idx is None or (gate_idx is not None and gate_idx >= stage_idx):
processing_stage = gate_as_stage
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
),
has_candidate_context=has_formal or has_verified_upload_success(task),
verified_upload_success=has_verified_upload_success(task),
processing_stage=processing_stage,
)
def _business_stage(lifecycle: dict[str, Any]) -> dict[str, Any]:
"""将共享生命周期结果包装为任务详情阶段 DTO;无正式事实时不猜阶段。"""
stage_code = str(lifecycle.get('lifecycle_stage') or '')
index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), None)
if index is None:
return {'code': 'unclassified', 'label': '状态待同步', 'index': 0, 'total': len(LIFECYCLE_STAGES)}
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 build_shipping_workflow_steps(
task: ShippingNotice,
position: str | None,
*,
lifecycle_stage: str | None = None,
) -> list[dict[str, str]]:
"""
构造五阶段流程状态。
Returns:
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
"""
del position # 五阶段仅由 lifecycle_stage 驱动
lifecycle_index = next(
(index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage),
None,
)
# 五阶段只使用共享生命周期裁决;缺少正式事实时全部保持 pending。
current_index = lifecycle_index
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 current_index is None:
status = "pending"
elif index < current_index:
status = "completed"
elif index == current_index:
status = "current"
else:
status = "pending"
steps.append({**step, "status": status})
return steps
_PARSE_STAGE_POSITIONS = {
POSITION_PARSE_REVIEW,
POSITION_RSV_REQ,
POSITION_INVENTORY_SOURCE_REVIEW,
POSITION_ORDER_FREEZE,
POSITION_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, position: str | None) -> list[str]:
"""
汇总文件解析阶段(步骤 2)全部待处理问题,供工作台一次列出。
核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发;
以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。
"""
position_value = str(position or "").strip()
if position_value not in _PARSE_STAGE_POSITIONS:
return []
issues: list[str] = []
if position_value == POSITION_INVENTORY_SOURCE_REVIEW:
_append_unique_issue(
issues,
task.error_message or "无法根据发货通知唯一确定库存查询来源",
)
elif position_value == POSITION_RSV_REQ:
_append_unique_issue(
issues,
task.error_message or "解析失败:未识别到 Reservation ID / COM ID(预定单号)",
)
elif position_value == POSITION_NOTICE_TEXT_EXTRACTION_FAILED:
_append_unique_issue(
issues,
task.error_message or "未能从发货通知中解析到可审核内容",
)
elif position_value == POSITION_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 _derived_entry_surface(
*,
gate_code: str | None,
review_status: str | None,
user_mode: str,
position: str | None = None,
) -> str:
"""
由 Gate 位置与用户模式推导操作入口面。
Returns:
review_workbench | task_workbench | none
"""
rs = str(review_status or '').strip()
code = str(gate_code or '').strip()
pos = str(position or '').strip()
if pos in {POSITION_EXPORT_READY, POSITION_EXPORT_GENERATED, POSITION_WAITING_UPLOAD} or code in {
'artifact_generation',
'manual_upload_handoff',
}:
return 'task_workbench'
if rs in {'parse_review', 'rsv_req', 'customer_review'} or code in {
'order_field_extraction',
'customer_resolution',
'reservation_validation',
}:
return 'review_workbench'
if user_mode == 'complete':
return 'none'
if user_mode in {'must_human', 'wait_manual_upload'}:
return 'task_workbench'
if code in {
'onhand_preparation',
'onhand_matching',
'onhand_sufficiency',
'excel_readiness',
'artifact_generation',
'onhand_source_routing',
'order_freeze_readiness',
}:
return 'task_workbench'
return 'none'
def _derived_current_todo(*, position: str | None) -> str | None:
"""从 Gate position 提取只读待办说明。"""
pause = _PAUSE_REASON_BY_POSITION.get(str(position or ''))
return pause[1] if pause else None
def _entry_surface_for(position: str | None, kind: UserMode) -> str:
"""
解析当前操作应进入的工作台类型。
Returns:
review_workbench | task_workbench | none
"""
# Excel 就绪虽为 wait_manual_upload,仍进任务工作台以便下载与登记凭据。
if str(position or "") in {POSITION_EXPORT_READY, POSITION_EXPORT_GENERATED}:
return "task_workbench"
if kind == UserMode.COMPLETE:
return "none"
if str(position or "") in _REVIEW_ENTRY_POSITIONS:
return "review_workbench"
if kind in {UserMode.MUST_HUMAN, UserMode.WAIT_MANUAL_UPLOAD}:
return "task_workbench"
if kind == UserMode.AUTO_CONTINUE and position in {
POSITION_ORDER_FREEZE,
POSITION_READY_MATCH,
POSITION_READY_EXPORT,
POSITION_INVENTORY_PENDING,
}:
# 自动链可继续,但仍允许工作台手动兜底
return "task_workbench"
return "none"
def _current_todo_label(position: str | None) -> str | None:
"""从位置标签提取只读待办说明,不派生用户动作。"""
pause = _PAUSE_REASON_BY_POSITION.get(str(position or ""))
return pause[1] if pause else None
def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
"""
投影 STP 履约事实供 Chat/工作台/待办同源消费。
核心逻辑:只读 OT 的 CandidateSet、Preparation/Link/File 与行级 Match;
无 STP 痕迹时返回 None,避免普通任务噪声。禁止读已下线的 OT 库存投影列。
"""
from app import db
from app.models import ShippingOrderTask
from app.services.shipping_notice.onhand_candidate_projection import (
project_inventory_candidate_facts,
)
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
from app.services.shipping_notice.stp_line_onhand_match import multi_source_recovery_source_codes
from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS
owner = task
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
candidate_projection = (
project_inventory_candidate_facts(owner)
if getattr(owner, 'id', None) is not None else {
'current_set': None,
'candidate_source_codes': [],
'line_resolutions': [],
}
)
status = 'candidates_frozen' if candidate_projection.get('current_set') else ''
method = 'candidate_set' if candidate_projection.get('current_set') else ''
frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_onhand_source_codes(owner)
has_stp = (
status in {'candidates_frozen', 'resolved'}
or method.startswith('stp')
or bool(frozen_codes)
or bool(candidate_projection.get('blocking_reason'))
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 [])
if not resolution_source and getattr(owner, 'id', None) is not None:
from app.models import ShippingNoticeLineOnhandMatch
resolution_source = [{
'line_index': row.line_index,
'line_no': row.line_no,
'disposition': row.match_result,
'effective_reservation_id': row.reservation_id,
'part_number': row.part_number,
'resolved_inventory_source_code': row.source_code,
'inventory_file_no': row.matched_file_no,
'inventory_row_index': row.matched_row_index,
'match_attempt_id': row.match_attempt_id,
'required_qty': row.required_qty,
'matched_qty': row.matched_qty or row.available_qty,
'shortage_qty': row.shortage_qty,
'inventory_row_ref': dict(row.detail_json or {}).get('inventory_row_ref'),
} for row in ShippingNoticeLineOnhandMatch.query.filter_by(
task_id=int(owner.id), is_current=True,
).order_by(ShippingNoticeLineOnhandMatch.line_no, ShippingNoticeLineOnhandMatch.id).all()]
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_no': item.get('line_no'),
'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_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(owner)
payload = getattr(owner, 'step_payload_json', None)
payload = payload if isinstance(payload, dict) else {}
multi_block = bool(payload.get('multi_source_excel_block'))
if not multi_block:
# 行级 source_conflict 与旧 payload 标志等价,摘要暂停原因须同源。
multi_block = any(
str(item.get('disposition') or '').strip().lower() == 'source_conflict'
for item in compact_resolutions
)
facts = {
'inventory_source_status': status or None,
'inventory_source_code': 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 聚合;不得读取 OT match_status 投影。
'match_status': None,
}
return {key: facts[key] for key in STP_FACTS_ALLOWED_KEYS if key in facts}
def _build_task_summary(
task: ShippingNotice,
position: str | None,
*,
user_mode: UserMode | str,
gate_code: str | None = None,
) -> dict[str, Any]:
"""
输出可解释任务摘要,供通知卡、人工复核与任务工作台同源消费。
核心逻辑:文案与入口由 position/user_mode(Gate 或 review 回退)驱动。
"""
effective_position = str(position or '').strip() or None
effective_mode = str(user_mode or '').strip() or str(UserMode.AUTO_CONTINUE)
# [PERF] position 已由 Gate 派生时优先用标签表,避免 user_facing_task_stage 再查 Gate。
title = (
user_facing_stage_label_for_position(task, position=effective_position)
or user_facing_task_stage(task)
)
message_by_position: dict[str, str] = {
POSITION_PARSE_REVIEW: "解析结果需要人工确认后才能继续。",
POSITION_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
POSITION_CUSTOMER_REVIEW: "客户尚未唯一确认,请在任务处理中选择标准客户。",
POSITION_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
POSITION_INVENTORY_PENDING: "发货通知已就绪,系统将自动准备库存数据。",
POSITION_INVENTORY_SOURCE_REVIEW: "库存源规则正在重新裁决。",
POSITION_ORDER_FREEZE: "订单已复核,系统将自动冻结后进入库存履约。",
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
POSITION_READY_MATCH: "库存已就绪,系统将自动执行匹配。",
POSITION_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。",
POSITION_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。",
POSITION_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。",
POSITION_WAITING_UPLOAD: "待人工上传确认:请下载 Excel,在货代平台上传后于本系统确认已上传。",
POSITION_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。",
POSITION_REJECTED: "任务已驳回,无需继续处理。",
POSITION_UPLOADED: "任务已完成上传。",
POSITION_COMPLETED: "任务已关闭。",
}
issues = _collect_parse_stage_issues(task, effective_position)
pause = _PAUSE_REASON_BY_POSITION.get(str(effective_position or ""))
pause_reason_code = pause[0] if pause else getattr(task, 'pending_human_reason', None)
pause_reason = pause[1] if pause else (
getattr(task, 'error_message', None)
or getattr(task, 'upload_error_message', None)
or None
)
message = message_by_position.get(str(effective_position or ""), title)
stp_facts = _build_stp_facts(task)
current_todo_override: str | None = None
is_auto = effective_mode in {'auto_continue', str(UserMode.AUTO_CONTINUE)}
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 is_auto
):
message = '多候选库存源已冻结,系统正在准备库存并跨文件匹配。'
if is_auto 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()
try:
mode_enum = UserMode(effective_mode)
except ValueError:
mode_enum = UserMode.AUTO_CONTINUE
entry_surface = (
_derived_entry_surface(
gate_code=gate_code,
review_status=getattr(task, 'review_status', None),
user_mode=effective_mode,
position=effective_position,
)
if (gate_code or position or user_mode)
else _entry_surface_for(effective_position, mode_enum)
)
# 多库存源冲突必须进人工作台处理,不能因位置仍是 auto inventory_pending 落到 none。
if stp_facts and stp_facts.get('multi_source_excel_block'):
entry_surface = 'task_workbench'
summary: dict[str, Any] = {
"title": title,
"message": message,
"error_message": (
getattr(task, 'error_message', None)
or getattr(task, 'upload_error_message', None)
),
"issues": issues,
"stage": title,
"user_mode": effective_mode,
"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 (
_derived_current_todo(position=effective_position)
if effective_position
else _current_todo_label(effective_position)
)
)
),
"pause_reason": pause_reason,
"pause_reason_code": pause_reason_code,
"next_auto_step": (
_NEXT_AUTO_STEP_BY_POSITION.get(str(effective_position or ""))
if is_auto
else None
),
"event_at": event_at,
"entry_surface": entry_surface,
"allowed_actions": [],
}
if stp_facts is not None:
summary['stp_facts'] = stp_facts
from app.services.shipping_notice.stp_progress_contract import project_task_progress_nodes
summary['progress_nodes'] = project_task_progress_nodes(task)
return summary
# 通知准备「任务级可编辑」排除集:作废/归档/删除/待作废/取消视图只读。
_PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES = frozenset({
'voided', 'archived', 'deleted', 'pending_void', 'cancelled', 'canceled',
})
def _preparation_editable(task: ShippingNotice) -> bool:
"""
判定通知准备工作面是否允许任务级编辑/出单门控放行。
核心逻辑:仅按 lifecycle_status 终态/历史视图排除;active/blocked/空值可操作。
Gate 阻断不在此谓词收紧。
"""
status = str(getattr(task, 'lifecycle_status', None) or '').strip().lower()
return status not in _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES
def _stage_capabilities_for_task(
task: Any,
*,
lifecycle_stage: str | None,
preparation: dict[str, Any],
source_locked: bool,
) -> list[dict[str, Any]]:
"""
按阶段能力契约计算通知准备阶段的常驻能力(enabled / disabled_reason)。
核心逻辑:可用性 = 阶段 + Excel 未生成 + 数据谓词,不由门禁通过与否决定。
预条件:改源→有候选源;重抓→有候选源或失败源;重读→已有抓取结果;
重匹配→已有匹配结果。右卡展示仍只读处理投影 A;本列表仅供点击后
``stageCapabilityBypass`` 查找(见 display-and-button-contract §3.2)。
Args:
task: Notice 或 OT(能力计算不读实体字段,保留形参供调用方透传)。
lifecycle_stage: 五阶段码;仅 ``fulfillment_prep`` 下发库存能力。
preparation: 已装配的 preparation 摘要(含 source_options / failed /
resolved / has_match_result)。
source_locked: Excel 已生成时全部能力禁用。
Returns:
能力列表,每项含 code/scope/action_code/enabled/disabled_reason。
"""
del task # 能力谓词只读 preparation 摘要,避免再查库。
from app.services.shipping_notice.process_gate_contract import STAGE_CAPABILITY_DEFINITIONS
result: list[dict[str, Any]] = []
source_options = preparation.get('source_options') or []
has_candidates = bool(source_options)
failed_codes = preparation.get('failed_source_codes') or []
resolved_codes = preparation.get('resolved_source_codes') or []
has_match_result = bool(preparation.get('has_match_result'))
def disabled(reason: str) -> dict[str, Any]:
return {'enabled': False, 'disabled_reason': reason}
for code, definition in STAGE_CAPABILITY_DEFINITIONS.items():
if definition.get('stage') != lifecycle_stage:
continue
cap: dict[str, Any] = {
'code': code,
'scope': definition.get('scope'),
'action_code': definition.get('action_code'),
'enabled': False,
'disabled_reason': None,
}
if source_locked:
cap.update(disabled('excel_locked'))
elif code == 'retry_onhand_preparation':
# 重抓:候选源或失败源任一在场即可重试(库存文件未准备时通常走候选源)。
retry_available = has_candidates or bool(failed_codes)
cap['enabled'] = retry_available
cap['disabled_reason'] = None if retry_available else 'no_candidates'
elif code == 'override_line_onhand_source':
cap['enabled'] = has_candidates
cap['disabled_reason'] = None if has_candidates else 'no_candidates'
elif code == 'reload_onhand_result':
has_prior = bool(resolved_codes)
cap['enabled'] = has_prior
cap['disabled_reason'] = None if has_prior else 'no_prior_result'
elif code == 'retry_onhand_matching':
cap['enabled'] = has_match_result
cap['disabled_reason'] = None if has_match_result else 'no_match_result'
result.append(cap)
return result
def _build_stage_context(
task: ShippingNotice,
*,
lifecycle_stage: str,
stp_facts: dict[str, Any] | None,
process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""构造五阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。
通知准备以冻结 Snapshot 行为轴,合并当前行级 Match + project_line_inventory_view;
Snapshot / Match / CandidateSet / PrepAttempt 一律按 OT 读取(Notice 经 order_task_id);
行级双字段:selected_source_code=CandidateSet 取数目标(单源才填),
source_code=Match 正式匹配源(禁止用候选回填,避免与匹配结论混淆);
短缺行另投影发货模板放行字段;匹配成功无短缺行投影 can_fulfill_complete_line;
preparation.source_options 下发全部已启用库存源,供 Excel 未锁定时行级覆写下拉;
preparation.capabilities 由 `_stage_capabilities_for_task` 追加(点击 bypass,不进右卡渲染);
Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询;
onhand_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。
"""
from app import db
from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask
from app.models.shipping_excel_template import ShippingExportArtifact
from app.models.shipping_fulfillment import ShippingUploadAttempt
from app.core.errors import ConflictError
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines
from app.services.shipping_notice.line_onhand_match_projection import (
inventory_rpa_is_running,
load_current_match_facts_by_task,
project_line_inventory_view,
)
from app.services.shipping_notice.order_line_no_resolver import (
notice_line_field_id_map,
read_field_by_id,
)
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
_manual_required_release_fields,
_release_fact_identity,
_shortage_release_required_fields,
)
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
facts = stp_facts if isinstance(stp_facts, dict) else {}
# [STEP 1] Snapshot/Match/Candidate 归属 OT;Notice 详情入口必须经 order_task_id 解析,
# 禁止用 Notice.id 查 Match(否则改源/匹配已落库却投影为空行)。
order_task = _resolve_order_task_for_gate_lookup(task) or task
has_formal_ot = isinstance(order_task, ShippingOrderTask) or getattr(order_task, 'order_snapshot_id', None) is not None
snapshot_id = getattr(order_task, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None
snapshot_lines = (
ShippingOrderSnapshotLine.query
.filter_by(snapshot_id=int(snapshot.id))
.order_by(ShippingOrderSnapshotLine.position, ShippingOrderSnapshotLine.id)
.all()
if snapshot is not None else []
)
match_by_snapshot_line_id = load_current_match_facts_by_task(getattr(order_task, 'id', None))
# [BE-有效视图] 值列消费有效订单值(快照 + 已接受修正):保存即显新值,
# 匹配结果列仍读当前匹配事实,诚实反映最近一轮匹配结论。
# 全循环只算一次,行内按 snapshot_line_id 取用;无冻结快照(如未绑定 OT 的 Notice)
# 保持空映射,行级回退快照列。有效视图解析失败(如历史/合成数据缺 Schema 版本)
# 与 ODM 投影同款降级:不阻断工作台渲染,值列退回快照列(此时有效值=快照值)。
effective_facts: dict[int, dict[str, Any]] = {}
if order_task is not None and getattr(order_task, 'order_snapshot_id', None):
try:
effective_facts = effective_line_facts_for_notice(order_task)
except Exception: # 遗留/合成快照缺 Schema 版本等:回退冻结列展示
from flask import current_app
current_app.logger.warning('effective order view resolution failed; falling back to frozen columns', exc_info=True)
effective_facts = {}
# [STEP] 与 Case 投影同源:库存 RPA 运行态只查一次 Attempt(请求内 memo),再传入各行纯函数。
inventory_rpa_running = inventory_rpa_is_running(order_task)
candidate_codes_by_line_no: dict[int, list[str]] = {}
if getattr(order_task, 'id', None) is not None and isinstance(order_task, ShippingOrderTask):
for candidate_line in get_active_candidate_lines(order_task):
try:
line_no_key = int(getattr(candidate_line, 'line_no', 0) or 0)
except (TypeError, ValueError):
line_no_key = 0
if line_no_key < 1:
continue
candidate_codes_by_line_no[line_no_key] = [
str(code).strip().upper()
for code in (getattr(candidate_line, 'source_codes_json', None) or [])
if str(code or '').strip()
]
field_id_by_code = notice_line_field_id_map(order_task)
frozen_order_lines: list[dict[str, Any]] = []
preparation_lines: list[dict[str, Any]] = []
for snapshot_line in snapshot_lines:
qty_text = str(snapshot_line.qty) if snapshot_line.qty is not None else None
line_no = int(snapshot_line.line_no) if snapshot_line.line_no is not None else None
# [BE-有效视图] 冻结订单行值列有效值优先(预约号/料号/需求数量):行内按
# snapshot_line_id 取有效事实,取不到(None)时回退冻结快照列;键名与前端
# 契约稳定不动(shipping.api.types.ts ShippingOrderFrozenLine)。
eff = effective_facts.get(int(snapshot_line.id)) or {}
frozen_order_lines.append({
'snapshot_line_id': int(snapshot_line.id),
'line_no': line_no,
'reservation_id': eff.get('reservation_id') if eff.get('reservation_id') is not None else snapshot_line.reservation_id,
'part_number': eff.get('part_number') if eff.get('part_number') is not None else snapshot_line.part_number,
'required_qty': str(eff['qty']) if eff.get('qty') is not None else qty_text,
})
fact = match_by_snapshot_line_id.get(int(snapshot_line.id))
# [BE-有效视图] 需求数量:有效事实 → 匹配事实 → 快照列(Decimal 需 str 化)。
required_qty = (
str(eff['qty'])
if eff.get('qty') is not None
else (fact or {}).get('required_qty')
)
if required_qty is None:
required_qty = qty_text
# [BE-有效视图] 预约号/料号:有效事实 → 匹配事实 → 快照列;保存修正后即使
# 匹配事实未刷新,prep 覆盖合并也立即显示新值。
reservation_id_value = (
eff.get('reservation_id')
if eff.get('reservation_id') is not None
else (fact or {}).get('reservation_id') or snapshot_line.reservation_id
)
part_number_value = (
eff.get('part_number')
if eff.get('part_number') is not None
else (fact or {}).get('part_number') or snapshot_line.part_number
)
inv_view = project_line_inventory_view(
has_formal_ot=has_formal_ot,
fact=fact,
required_qty=required_qty,
stored_line_status=None,
decision_source=None,
can_fulfill_complete_line=False,
inventory_rpa_running=inventory_rpa_running,
)
allowed = list((fact or {}).get('allowed_source_codes_snapshot') or [])
candidate_codes = candidate_codes_by_line_no.get(int(line_no), []) if line_no is not None else []
# [STEP] 双字段真相:Match 正式源 vs CandidateSet 取数目标,禁止互相回填。
source_code = (fact or {}).get('inventory_source_code') or (
allowed[0] if len(allowed) == 1 else None
)
selected_source_code = candidate_codes[0] if len(candidate_codes) == 1 else None
source_ambiguous = (
str((fact or {}).get('match_result') or '').strip().lower() == 'source_conflict'
or (len(allowed) > 1 and not (fact or {}).get('inventory_source_code'))
or (fact is None and len(candidate_codes) > 1)
)
source_candidates = (
allowed if str((fact or {}).get('match_result') or '').strip().lower() == 'source_conflict' or len(allowed) > 1
else (candidate_codes if source_ambiguous else [])
)
# [STEP] 短缺行复用 Case 同款模板字段判定;解析失败 fail-closed,禁止只填原因放行。
release_template_fields: list[dict[str, Any]] = []
release_field_resolution_error: str | None = None
if bool(inv_view.get('is_shortage')):
try:
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
if release_line_index is None and getattr(snapshot_line, 'position', None) is not None:
release_line_index = int(snapshot_line.position)
# scope 仅在 decide 落库时写入审计快照;prep 行投影契约本期不新增字段。
release_template_fields, _evidence_scope = _shortage_release_required_fields(
task=order_task,
line_index=release_line_index,
inventory_snapshot_id=release_snapshot_id,
inventory_source_code=release_source_code or source_code or selected_source_code,
)
except ConflictError as exc:
release_field_resolution_error = exc.code
# [STEP] 正式 OT 行可履约 = 匹配成功且无短缺;供前端波次勾选(「生成发货通知和 Excel (N 行)」)。
can_fulfill_complete_line = (
str(inv_view.get('user_line_status') or '').strip() == 'inventory_matched'
and not bool(inv_view.get('is_shortage'))
)
preparation_lines.append({
'snapshot_line_id': int(snapshot_line.id),
'line_no': line_no,
'customer_po_line_no': read_field_by_id(
dict(snapshot_line.field_values_json or {}),
field_id_by_code,
'customer_po_line_no',
),
'reservation_id': reservation_id_value,
'part_number': part_number_value,
'required_qty': required_qty,
'available_qty': inv_view.get('available_qty'),
'shortage_qty': inv_view.get('shortage_qty'),
'part_available_qty': inv_view.get('part_available_qty'),
'source_code': source_code,
'selected_source_code': selected_source_code,
'status': inv_view.get('user_line_status'),
'source_ambiguous': source_ambiguous,
'source_candidates': source_candidates,
'is_shortage': bool(inv_view.get('is_shortage')),
'user_line_status': inv_view.get('user_line_status'),
'can_fulfill_complete_line': can_fulfill_complete_line,
'inventory_allowed_actions': list(inv_view.get('inventory_allowed_actions') or []),
'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []),
'inventory_file_no': inv_view.get('inventory_file_no'),
'release_template_fields': release_template_fields,
'release_required_fields': _manual_required_release_fields(release_template_fields),
'release_field_resolution_error': release_field_resolution_error,
'decision': None,
})
has_match_result = bool(match_by_snapshot_line_id)
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(order_task, 'id', None):
from app.models.shipping_onhand_preparation import ShippingOnhandPreparationAttempt
latest_preparation = (
ShippingOnhandPreparationAttempt.query
.filter_by(task_id=int(order_task.id))
.filter(ShippingOnhandPreparationAttempt.status != 'superseded')
.order_by(ShippingOnhandPreparationAttempt.attempt_no.desc())
.first()
)
from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download
downloadable_inventory = resolve_task_inventory_download(order_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.onhand_file_id,
})
# [STEP] 人工覆写库存源:下发全部已启用源,供前端行级下拉(override_line_inventory_source)。
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
source_options = [
{
'source_code': str(item.get('source_code') or '').strip().upper(),
'display_name': str(item.get('display_name') or '') or str(item.get('source_code') or ''),
}
for item in list_database_inventory_sources(enabled_only=True)
if str(item.get('source_code') or '').strip()
]
# [STEP] 整单 ODM 裁决投影:一个预约单号多个 ODM ID 时,逐行下发候选与已选
# (同一快照文件的行同步使用同一值);投影失败不阻断工作台渲染,仅退化为无 ODM 入口。
try:
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
odm_projection = notice_odm_options(task)
except Exception:
odm_projection = {}
odm_lines_by_sid = {
str(item.get('snapshot_line_id')): item for item in odm_projection.get('lines') or []
}
for prep_line in preparation_lines:
entry = odm_lines_by_sid.get(str(prep_line.get('snapshot_line_id')))
if entry is None:
continue
prep_line['odm_values'] = list(entry.get('odm_values') or [])
prep_line['chosen_odm_id'] = entry.get('chosen_odm_id')
prep_line['odm_conflict'] = len(entry.get('odm_values') or []) > 1
odm_options_payload = {
'conflict': any(bool(item.get('odm_conflict')) for item in preparation_lines),
'customer_odm_ids': list(odm_projection.get('customer_odm_ids') or []),
'whitelist_applied': bool(odm_projection.get('whitelist_applied')),
}
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'
)
source_locked = latest_export_artifact(task) is not None or latest_export_artifact(order_task) is not None
# [STEP] 先装配 preparation 再追加 capabilities,避免字面量自引用。
preparation = {
'status': preparation_status,
'reason_code': gate.get('blocking_reason_code') or None,
'editable': _preparation_editable(task),
'source_locked': source_locked,
'frozen_order': {
'task_no': getattr(order_task, 'task_no', None) or task.task_no,
'snapshot_id': 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,
# 任务级 inventory_sources 只说明取数进度;行级看 selected_source_code / source_code。
'inventory_sources': inventory_sources,
# 供阶段能力预条件:失败可重试源 / 已有抓取结果。
'failed_source_codes': [
item['source_code'] for item in inventory_sources
if str(item.get('status') or '').strip().lower() == 'failed'
],
'resolved_source_codes': list(facts.get('resolved_ok_source_codes') or []),
'source_options': source_options,
# 整单 ODM 裁决:conflict=True 时前端展示候选下拉,选择后可重试生成 Excel。
'odm_options': odm_options_payload,
'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',
},
}
preparation['capabilities'] = _stage_capabilities_for_task(
task,
lifecycle_stage=lifecycle_stage,
preparation=preparation,
source_locked=source_locked,
)
return {
'preparation': preparation,
'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_edit_window(task: ShippingNotice) -> dict[str, Any]:
"""二期编辑窗(D10)谓词:header/lines 可编辑矩阵,工作台以此隐藏/禁用出单入口。"""
from app.services.shipping_notice import order_edit_window_service as order_edit_window
return order_edit_window.editable_scope(task)
def build_task_ui_state(
task: ShippingNotice,
*,
include_stage_context: bool = False,
viewer_user_id: int | None = None,
viewer_is_admin: bool = False,
) -> dict[str, Any]:
"""
构建单票任务 UI State。
核心逻辑:所有 UI 入口只消费这里输出的 stage/position/user_mode/todo/actions/summary,
禁止 Chat、通知卡与任务中心分别推导状态;
可点击用户动作只由 Gate 与已验证 Artifact 授权产生。
Gate 摘要只查一次,再派生 position/user_mode,禁止再走 resolve_task_ui_state 二次查库。
Args:
task: 源任务实体。
include_stage_context: 是否附带 stage_context(工作面只读事实)。
viewer_user_id: 当前查看者;给定时时 download_excel 动作按导出统一谓词
(can_download_task_export:创建者或管理员)门禁下发;为 None 时维持
聊天链路旧口径(仅按 Artifact 授权,聊天会话与创建者同源)。
viewer_is_admin: 查看者是否平台管理员(配合 viewer_user_id 使用)。
"""
from app.services.shipping_notice.state_machine import (
_review_status_fallback_ui_state,
_ui_state_from_process_gate,
)
process_gate = _process_gate_user_summary_for_task(task)
ui = _ui_state_from_process_gate(task, process_gate)
if ui is None:
# 与 resolve_task_ui_state 无 Gate 分支同源:仅 review_status 薄回退。
ui = _review_status_fallback_ui_state(task)
lifecycle = _task_lifecycle(task=task, position=ui.position, process_gate=process_gate)
stage = _business_stage(lifecycle)
steps = build_shipping_workflow_steps(task, ui.position, 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.position,
user_mode=ui.user_mode,
gate_code=(
process_gate.get('current_gate_code')
if isinstance(process_gate, dict) else None
),
)
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 阻断并清空旧动作,也只在
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
# 下载动作与导出端点消费同一谓词:viewer 已知时按创建者/管理员门禁,
# 避免非创建者"看得到点不动";viewer 未知(聊天链路)维持 Artifact 口径。
if resolve_task_export_download(task) is not None and (
viewer_user_id is None
or can_download_task_export(task, user_id=int(viewer_user_id), is_admin=viewer_is_admin)
):
download_action = _unified_action({
'id': 'download_excel',
'label': '下载 Excel',
'kind': 'view',
'dispatch': 'view',
'ui_handler': 'excel_download',
'enabled': True,
# Artifact 已验证是下载授权的唯一来源;它直接声明展示位置,
# 不依赖旧位置码或 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)
if stage['code'] == 'upload_complete':
# [STEP] 上传成功已核验即为生命周期终态。历史 Gate 可能在异步收口窗口仍
# 可读取,但不能继续下发“下一步”或下载 Excel 等工作台动作;完成面只提供
# 同 PO 成功通知明细与批次 ZIP 的只读留档入口。
process_gate = None
actions = {'primary': None, 'secondary': []}
# summary 仅作为 ui_state.actions 的只读镜像,禁止由位置码或任务字段另行推导。
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
)
edit_window = (
_build_edit_window(task)
if include_stage_context else 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,
"stage": stage,
"lifecycle_stage": stage["code"],
"lifecycle_entries": lifecycle['lifecycle_entries'],
"lifecycle_authority": lifecycle['lifecycle_authority'],
"position": ui.position,
"user_mode": str(ui.user_mode),
"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 {}),
# 二期编辑窗门控矩阵(无 Export Artifact 且无活动 Attempt 才可编辑);
# 波次出单工具条与字段编辑守卫的数据源,禁止再次静默丢失。
**({'edit_window': edit_window} if edit_window is not None else {}),
"reason": reason,
# OT 与 Notice 字段不完全同构:禁止硬读 Notice 专属列。
"lifecycle_status": getattr(task, "lifecycle_status", None) or getattr(task, "status", None),
"review_status": getattr(task, "review_status", None),
"pending_human_reason": getattr(task, "pending_human_reason", None),
"match_status": getattr(task, "match_status", None),
"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 _resolve_order_task_for_gate_lookup(task: Any):
"""
解析 Execution.task_id 对应的正式 OT。
核心逻辑:ShippingProcessExecution.task_id FK 指向 shipping_order_tasks.id。
入参可能是 ShippingOrderTask,或挂有 order_task_id 的 ShippingNotice;
Artifact.task_id 才是 Notice 主键,禁止用 Notice.id 查 Execution。
Args:
task: ShippingOrderTask 或 ShippingNotice(及具备 order_task_id 的兼容对象)。
Returns:
正式 OT;Notice 未绑定 OT 时 None。
"""
from app import db
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
return task
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id is None:
return None
try:
return db.session.get(ShippingOrderTask, int(order_task_id))
except (TypeError, ValueError):
return None
def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None:
"""
按正式 OT 查找活动 Execution 的用户 Gate 摘要。
核心逻辑:先把 Notice 解析到 order_task_id 对应的 OT,再优先读
active_process_execution_id,回退按 OT.id 取最新非 superseded Execution;
套用 apply_post_ot_gate_rules,使 onhand_preparation 等系统等待
不进入 current_blocking_gate。货代上传聚合的 available_actions 依赖此路径。
同一 HTTP 请求内按 task 主键 memo,避免 build_task_ui_state / resolve 等路径重复查库。
Returns:
用户态 Gate 摘要;无 OT / Execution 时 None。
"""
from app import db
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
cache_key = (
type(task).__name__,
getattr(task, 'id', None),
str(getattr(task, 'task_no', '') or ''),
)
try:
from flask import g, has_app_context, has_request_context
if has_app_context() and has_request_context():
cache = getattr(g, '_shipping_process_gate_summary_by_task', None)
if cache is None:
cache = {}
g._shipping_process_gate_summary_by_task = cache
if cache_key in cache:
return cache[cache_key]
else:
cache = None
except Exception:
cache = None
# [STEP 1] Notice→OT:Execution.task_id 只认 shipping_order_tasks.id。
order_task = _resolve_order_task_for_gate_lookup(task)
if order_task is None or getattr(order_task, 'id', None) is None:
result = None
else:
# [STEP 2] 与 processing_projection 同源:优先活跃指针,再回退最新活跃 Execution。
execution = None
active_execution_id = getattr(order_task, 'active_process_execution_id', None)
if active_execution_id is not None:
execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
if execution is not None and (
int(getattr(execution, 'task_id', 0) or 0) != int(order_task.id)
or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded'
):
execution = None
if execution is None:
execution = (
ShippingProcessExecution.query
.filter_by(task_id=int(order_task.id))
.filter(ShippingProcessExecution.status != 'superseded')
.order_by(ShippingProcessExecution.id.desc())
.first()
)
if execution is None:
result = None
else:
result = apply_post_ot_gate_rules(
project_user_gate_summary(execution),
has_formal_ot=True,
)
if cache is not None:
cache[cache_key] = result
return result
def project_notice_available_actions(task: ShippingNotice) -> list[str]:
"""轻量投影单张 Notice 的已授权动作码,供货代上传面板按 business_no 展示单条菜单。
核心逻辑:与 ``build_task_ui_state`` 的 actions 同源(Gate 摘要 + 统一动作 + 已验证
Excel 下载授权),但**不**构建 stage_context / summary / steps / progress_nodes 等昂贵
重活。list_freight_notice_groups_for_task 会遍历同 PO 的多张 Notice,逐张调用完整
``build_task_ui_state`` 会造成 N 倍放大;此处只返回动作码,用于面板首屏即可。
Returns:
已启用动作码列表(primary + secondary + 已验证下载)。
"""
process_gate = _process_gate_user_summary_for_task(task)
actions = _unified_actions(process_gate=process_gate)
codes = [
str(item.get('code') or '').strip()
for item in [actions.get('primary'), *(actions.get('secondary') or [])]
if isinstance(item, dict) and item.get('enabled') is True and str(item.get('code') or '').strip()
]
# 与 build_task_ui_state 同款下载授权:Artifact 已验证后补入只读下载。
from app.services.shipping_notice.query_service import resolve_task_export_download
if resolve_task_export_download(task) is not None:
download_code = 'download_excel'
if download_code not in codes:
codes.append(download_code)
return codes