feat(shipping-notice): 收敛阶段能力投影并修复库存 RPA 运行链路

下发 preparation capabilities 并与右卡展示同源授权;
库存 RPA 运行态请求内 memo;取消会话 Profile 本地 TTL;
并为 shipping-worker 挂载共享盘。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-09-07 14:46:48 +08:00
1 parent f773237226
commit a6edc4fe61
16 files changed
+433 -179

No files matched your search

@@ -2,12 +2,13 @@
services/shipping_notice/line_inventory_match_projection.py
用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。
依赖:ShippingNoticeLineInventoryMatch、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用;
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
ready+not_found→available=0;result_missing 不得转 0;
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
load_current_match_facts_by_task 在同一 HTTP 请求内按 task_id memo。
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
禁止按行重复查库。
"""
from __future__ import annotations
@@ -15,7 +16,11 @@ from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
from app.models import (
ShippingInventoryFile,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
)
MATCH_NOT_FOUND = 'not_found'
@@ -415,6 +420,55 @@ def resolve_allowed_actions(
return [*inv, *line]
def inventory_rpa_is_running(task: Any) -> bool:
"""
仅依据正式 OT 的库存 RPA Attempt 判断库存获取是否运行中。
核心逻辑:查 (task_no, status in queued|running) 是否存在;阶段推进 Job 的
queued/running 不得冒充本结果。同一 HTTP 请求内按 task_no memo,供 Case 投影
与工作台 stage_context 共享,禁止逐行或重复入口各查一次。
Args:
task: 含 task_no 的正式 OT(或等价命名空间);无 task_no 时返回 False。
Returns:
True 表示存在活动库存 RPA Attempt。
"""
task_no = str(getattr(task, 'task_no', None) or '').strip()
if not task_no:
return False
try:
from flask import g, has_app_context, has_request_context
if has_app_context() and has_request_context():
cache = getattr(g, '_shipping_inventory_rpa_running_by_task_no', None)
if cache is None:
cache = {}
g._shipping_inventory_rpa_running_by_task_no = cache
if task_no in cache:
return bool(cache[task_no])
else:
cache = None
except Exception:
cache = None
try:
running = (
ShippingTaskInventoryRpaAttempt.query
.filter(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
)
.first()
is not None
)
except Exception: # noqa: BLE001
# 纯投影/无数据库测试对象不得把未知状态误判为运行中。
running = False
if cache is not None:
cache[task_no] = running
return running
def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, Any]]:
"""
加载 OT 当前行匹配事实,键为冻结订单行 ID。
@@ -59,7 +59,9 @@ from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.line_inventory_match_projection import (
inventory_rpa_is_running as _inventory_rpa_is_running,
)
@@ -69,30 +71,6 @@ def _safe_filename(value: Any) -> str | None:
return name[:255] or None
def _inventory_rpa_is_running(task: Any) -> bool:
"""仅依据正式 OT 的库存 RPA Attempt 判断库存获取是否运行中。
自动推进 Job(shipping_notice_run)的 queued/running 只表示阶段推进,
不代表库存 RPA 已创建或正在执行;两者必须隔离,避免把明细行伪装成 acquiring_inventory。
"""
task_no = str(getattr(task, 'task_no', None) or '').strip()
if not task_no:
return False
try:
return (
ShippingTaskInventoryRpaAttempt.query
.filter(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
)
.first()
is not None
)
except Exception: # noqa: BLE001
# 纯投影/无数据库测试对象不得把未知状态误判为运行中。
return False
def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[str, Any] | None:
"""
投影已绑定正式 OT 的任务号与自动推进态(与 automation 同源 Job 判定)。
+120 -31
View File
@@ -3,8 +3,8 @@ services/shipping_notice/ui_state.py
用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
依赖:models.ShippingNotice/ShippingOrderTask/ShippingProcessExecution、state_machine(UserMode/位置回退)、
query_service、constants.POSITION_*、process_gate_contract.derive_*、process_gate_projection、
line_inventory_match_projection、inventory_candidate_projection、
query_service、constants.POSITION_*、process_gate_contract.derive_*/STAGE_CAPABILITY_DEFINITIONS、
process_gate_projection、line_inventory_match_projection、inventory_candidate_projection、
order_review_fulfillment_decision_service(短缺放行模板字段)、
order_review_workbench_projection、inventory_source_repository(preparation.source_options)。
逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode);
@@ -12,8 +12,8 @@ services/shipping_notice/ui_state.py
stage_context.preparation 以 Snapshot 行 + 当前 Match 投影(Notice 经 order_task_id→OT),
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
下发 source_options 供行级 override;用户动作统一由 Gate 授权;
build_task_ui_state 同请求内复用一次 Gate 摘要(禁止 resolve 再查一遍);
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要;
project_notice_available_actions 供货代上传聚合行内菜单轻量消费。
"""
@@ -688,6 +688,75 @@ def _preparation_editable(task: ShippingNotice) -> bool:
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_inventory_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_inventory_source':
cap['enabled'] = has_candidates
cap['disabled_reason'] = None if has_candidates else 'no_candidates'
elif code == 'reload_inventory_result':
has_prior = bool(resolved_codes)
cap['enabled'] = has_prior
cap['disabled_reason'] = None if has_prior else 'no_prior_result'
elif code == 'retry_inventory_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,
*,
@@ -703,7 +772,9 @@ def _build_stage_context(
source_code=Match 正式匹配源(禁止用候选回填,避免与匹配结论混淆);
短缺行另投影发货模板放行字段;匹配成功无短缺行投影 can_fulfill_complete_line;
preparation.source_options 下发全部已启用库存源,供 Excel 未锁定时行级覆写下拉;
Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询。
preparation.capabilities 由 `_stage_capabilities_for_task` 追加(点击 bypass,不进右卡渲染);
Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询;
inventory_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。
"""
from app import db
from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask
@@ -712,6 +783,7 @@ def _build_stage_context(
from app.core.errors import ConflictError
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
from app.services.shipping_notice.line_inventory_match_projection import (
inventory_rpa_is_running,
load_current_match_facts_by_task,
project_line_inventory_view,
)
@@ -741,6 +813,8 @@ def _build_stage_context(
if snapshot is not None else []
)
match_by_snapshot_line_id = load_current_match_facts_by_task(getattr(order_task, 'id', None))
# [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):
@@ -780,6 +854,7 @@ def _build_stage_context(
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 []
@@ -920,33 +995,47 @@ def _build_stage_context(
'not_started'
)
source_locked = latest_export_artifact(task) is not None or latest_export_artifact(order_task) is not None
return {
'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,
'source_options': source_options,
'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',
},
# [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,
'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”。后者可能