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”。后者可能
+6 -5
View File
@@ -1483,8 +1483,8 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
assert worker._should_cleanup_browser_profile(profile_dir) is False
def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_path):
"""超过 TTL 的持久 Profile 应被清空重建,迫使重新登录。"""
def test_prepare_reusable_session_profile_keeps_existing_dir(tmp_path):
"""持久 Profile 不按本地时间清空;已有内容应保留供站点会话继续复用。"""
worker = _load_freight_rpa_worker()
profile_dir = tmp_path / "dsv360__OLD_session"
profile_dir.mkdir(parents=True)
@@ -1495,7 +1495,6 @@ def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_pat
json.dumps({"created_at_unix": created, "connector_type": "dsv360", "profile_code": "OLD"}),
encoding="utf-8",
)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24")
prepared = worker._prepare_reusable_session_profile(
profile_dir,
@@ -1504,9 +1503,11 @@ def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_pat
)
assert prepared == profile_dir
assert not stale_marker.exists()
assert stale_marker.exists()
meta = json.loads((profile_dir / ".hxops_rpa_session_meta.json").read_text(encoding="utf-8"))
assert float(meta["created_at_unix"]) > created
assert float(meta["created_at_unix"]) == created
assert "ttl_hours" not in meta
def test_is_dsv_username_page_ignores_login_method_page_text():
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
@@ -612,6 +612,65 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
def test_stage_context_hides_inventory_actions_while_rpa_running(app) -> None:
"""库存 RPA queued/running 时,工作台 preparation 行不得下发重试 RPA 动作。
与 Case 投影同源:inventory_rpa_is_running 在行循环外算一次;运行中 actions 为空。
"""
from app.models import ShippingTaskInventoryRpaAttempt
with app.app_context():
user = User(username='ui-rpa-running', email='ui-rpa-running@example.com')
db.session.add(user)
db.session.flush()
task = ShippingOrderTask(task_no='OT-UI-RPA-RUNNING', user_id=user.id, stage='inventory_matching')
db.session.add(task)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=1, schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
snapshot_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0, line_no=1,
reservation_id='RSV-RPA', part_number='PN-RPA', qty='10', field_values_json={},
)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
snapshot_line_id=snapshot_line.id,
line_no=1,
line_index=0,
match_result='matched',
inventory_status='ready',
required_qty='10',
available_qty='7',
matched_qty='7',
shortage_qty='3',
reservation_id='RSV-RPA',
part_number='PN-RPA',
inventory_source_code='DBS_DUB',
is_current=True,
))
db.session.add(ShippingTaskInventoryRpaAttempt(
task_no=task.task_no,
source_code='DBS_DUB',
attempt_no=1,
source_run_no='PSR-UI-RPA-1',
status='running',
))
db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
line = preparation['lines'][0]
# 关键断言:RPA 运行中必须清空库存动作,前端 Bot 不得渲染/触发。
assert line['user_line_status'] == 'acquiring_inventory'
assert line['inventory_allowed_actions'] == []
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monkeypatch) -> None:
"""行级 source_conflict 与候选源只读 Match;Excel 未生成时下发 source_options。"""
monkeypatch.setattr(
@@ -59,7 +59,7 @@ def test_inventory_running_is_not_inferred_from_stage_automation_job():
"""阶段推进 Job 运行中但未创建库存 Attempt 时,明细不得显示获取库存中。"""
task = SimpleNamespace(task_no='OT-TEST-1')
with patch(
'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query',
'app.services.shipping_notice.line_inventory_match_projection.ShippingTaskInventoryRpaAttempt.query',
) as query:
query.filter.return_value.first.return_value = None
assert _inventory_rpa_is_running(task) is False
@@ -69,7 +69,7 @@ def test_inventory_running_requires_queued_or_running_attempt():
"""只有库存 RPA Attempt queued/running 才能投影 acquiring_inventory。"""
task = SimpleNamespace(task_no='OT-TEST-2')
with patch(
'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query',
'app.services.shipping_notice.line_inventory_match_projection.ShippingTaskInventoryRpaAttempt.query',
) as query:
query.filter.return_value.first.return_value = SimpleNamespace(status='queued')
assert _inventory_rpa_is_running(task) is True