feat(shipping-notice): 优化货运订单履约流程与用户体验
- 优化聊天附件列表为横向可滚动布局并新增配套测试用例 - 移除自动填充默认用户消息逻辑,空备注时不再伪造默认正文 - 修复流程Gate动作展示逻辑,隐藏历史遗留操作与自动阶段无效按钮 - 完善库存匹配重试与订单快照冻结校验流程 - 优化进度展示优先级,优先显示人工待处理状态 - 移除Excel导出自动推导金额逻辑,强制使用Schema配置字段 - 新增货代通用报表RPA详细设计文档 - 更新相关测试用例与断言逻辑
This commit is contained in:
1 parent
dc282f3b1d
commit
11cef575b4
51 files changed
+2197
-112
No files matched your search
@@ -172,12 +172,6 @@ def _mapping_value(
|
||||
field_code = str(field.field_code or '') if field else ''
|
||||
if value in (None, '') and field_code == 'line_no' and export_sequence is not None:
|
||||
value = export_sequence
|
||||
if value in (None, '') and field_code == 'line_amount_with_tax':
|
||||
value = order_values.get('__line_amount')
|
||||
qty = order_values.get('__qty')
|
||||
unit_price = order_values.get('__unit_price')
|
||||
if value in (None, '') and qty not in (None, '') and unit_price not in (None, ''):
|
||||
value = Decimal(str(qty)) * Decimal(str(unit_price))
|
||||
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
|
||||
value = header_values.get(key)
|
||||
elif kind == 'inventory_field':
|
||||
@@ -467,9 +461,6 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
if line.id not in available_line_ids:
|
||||
continue
|
||||
row = dict(values)
|
||||
row['__qty'] = line.qty
|
||||
row['__unit_price'] = line.unit_price
|
||||
row['__line_amount'] = line.amount
|
||||
line_values.append(row)
|
||||
for index, row in enumerate(line_values, start=1):
|
||||
row['__export_sequence'] = index
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
services/shipping_notice/fulfillment_audit.py
|
||||
backend/app/services/shipping_notice/fulfillment_audit.py
|
||||
|
||||
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
|
||||
@@ -148,6 +148,49 @@ def record_fulfillment_audit(
|
||||
) from exc
|
||||
|
||||
|
||||
def emit_stp_auto_create_blocked_manual_audit(
|
||||
*,
|
||||
case: Any | None,
|
||||
job_id: int,
|
||||
error_code: str,
|
||||
next_action: str,
|
||||
details: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
记录 STP 自动建单业务阻断的人工处理审计事件。
|
||||
|
||||
核心逻辑:使用订单复核 Case 作为可选聚合,Job 作为稳定元数据引用;Worker 无请求上下文时仍可写入。
|
||||
Args:
|
||||
case: 可选 ShippingOrderReviewCase,优先提供 case_no;不得传入正文或凭据。
|
||||
job_id: STP Job 主键。
|
||||
error_code: 稳定业务阻断错误码。
|
||||
next_action: 后续人工处理动作编码。
|
||||
details: 脱敏诊断事实,仅允许审计元数据白名单字段。
|
||||
Returns:
|
||||
None。审计失败由 record_fulfillment_audit 按 strict 契约抛出。
|
||||
"""
|
||||
case_no = str(getattr(case, 'case_no', '') or '').strip() or None
|
||||
metadata = {
|
||||
'job_id': int(job_id),
|
||||
'next_action': str(next_action or '').strip() or None,
|
||||
**dict(details or {}),
|
||||
}
|
||||
record_fulfillment_audit(
|
||||
event_type='stp_auto_create_blocked_manual',
|
||||
aggregate_type='order_review_case' if case_no else 'shipping_job',
|
||||
aggregate_id=case_no or str(job_id),
|
||||
action='stp_auto_create_blocked_manual',
|
||||
actor_type='worker',
|
||||
task_no=case_no,
|
||||
review_case_no=case_no,
|
||||
reason_code=str(error_code or '').strip() or None,
|
||||
error_code=str(error_code or '').strip() or None,
|
||||
result='rejected',
|
||||
metadata=metadata,
|
||||
source='worker',
|
||||
)
|
||||
|
||||
|
||||
def record_access_audit(
|
||||
*,
|
||||
action: str,
|
||||
|
||||
@@ -27,7 +27,7 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
|
||||
from app.services.shipping_notice.constants import CP_UPLOADED
|
||||
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
|
||||
@@ -1170,6 +1170,10 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
'available_qty': float(available_qty) if available_qty is not None else 0.0,
|
||||
'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0,
|
||||
}
|
||||
entry['line_status'] = (
|
||||
'ok' if match_result == 'matched' and entry['shortage_qty'] <= 0
|
||||
else 'shortage'
|
||||
)
|
||||
task.line_results_json.append(entry)
|
||||
if match_result == 'matched':
|
||||
has_ok = True
|
||||
@@ -1441,8 +1445,12 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
),
|
||||
matching_rule_version='stp_line_v2',
|
||||
)
|
||||
match_status = str(match_payload.get('match_status') or 'unfulfillable')
|
||||
line_results = list(match_payload.get('line_results') or [])
|
||||
# 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单,
|
||||
# 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。
|
||||
match_status, shortages = _recompute_task_match_aggregate(task)
|
||||
line_results = list(task.line_results_json or [])
|
||||
task.match_status = match_status
|
||||
task.shortage_json = {'lines': shortages}
|
||||
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
||||
verification = record_inventory_verification(
|
||||
task, inventory_snapshot_id=task.inventory_snapshot_id,
|
||||
|
||||
@@ -299,6 +299,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
|
||||
source_type=str(task.inventory_connector_type or "").strip() or None,
|
||||
warehouse_id=warehouse_id,
|
||||
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
|
||||
source_query_json={'trigger_type': 'manual_upload'},
|
||||
identity_status="pending",
|
||||
snapshot_status="ready",
|
||||
exported_at=datetime.utcnow(),
|
||||
@@ -393,6 +394,7 @@ def save_task_inventory_file_from_local_path(
|
||||
schema_preview_json=preview,
|
||||
share_mode="task_only",
|
||||
line_count=0,
|
||||
source_query_json={'trigger_type': 'manual_upload'},
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
|
||||
@@ -675,12 +675,27 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
|
||||
校验 RPA 回调轮次契约(run_no + 幂等)。
|
||||
核心逻辑:success/skipped/failed 共用;无有效触发或旧轮次/重放均拒绝。
|
||||
"""
|
||||
# Batch 回调顶层 run_no 是 batch identity;逐源 item 的 source_run_no
|
||||
# 才是正式 Attempt identity。先按 source_run_no 接受当前 Attempt,避免
|
||||
# per-source 已成功后又被 task-level batch_run_no 的旧 trigger 校验否决。
|
||||
source_run_no = str(payload.get('source_run_no') or '').strip()
|
||||
if source_run_no:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
current_attempt = (
|
||||
db.session.query(ShippingTaskInventoryRpaAttempt)
|
||||
.filter_by(task_no=task.task_no, source_run_no=source_run_no)
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.id.desc())
|
||||
.first()
|
||||
)
|
||||
if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running', 'succeeded'}:
|
||||
return None
|
||||
|
||||
run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or ""))
|
||||
if run_no_error:
|
||||
# 逐源 batch Trigger 的任务事件可能仍保留旧的 task-level batch_run_no;
|
||||
# source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt
|
||||
# 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。
|
||||
source_run_no = str(payload.get('source_run_no') or '').strip()
|
||||
if source_run_no:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
@@ -872,9 +887,13 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str,
|
||||
def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
合并 batch 顶层契约字段到 result item。
|
||||
核心逻辑:仅合并 run_no / task_no;成功回调身份字段必须由 Worker 显式返回,禁止后端从任务补齐。
|
||||
核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
|
||||
Worker item 显式返回,禁止后端从任务或数据库补齐。
|
||||
"""
|
||||
merged = dict(item)
|
||||
top_schema_version = str(payload.get('schema_version') or '').strip()
|
||||
if top_schema_version and not str(merged.get('schema_version') or '').strip():
|
||||
merged['schema_version'] = top_schema_version
|
||||
top_run_no = str(payload.get("run_no") or "").strip()
|
||||
if top_run_no and not str(merged.get("run_no") or "").strip():
|
||||
merged["run_no"] = top_run_no
|
||||
@@ -1909,6 +1928,10 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
structure_check = validate_production_inventory_structure(
|
||||
source_code=str(rpa_source['source_code']), path=ingest_path,
|
||||
)
|
||||
# RPA 来源已通过正式 Profile 结构校验;映射是确定性事实,不应再要求人工确认。
|
||||
inv_file.field_mapping_json = dict(structure_check['field_mapping'])
|
||||
inv_file.mapping_source = 'parsing_profile'
|
||||
inv_file.mapping_confirmed = True
|
||||
lines, column_meta = ingest_inventory_file(
|
||||
ingest_path, move_to=None,
|
||||
field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile',
|
||||
@@ -1956,6 +1979,8 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
column_meta=column_meta,
|
||||
source="rpa_callback",
|
||||
event_type="inventory_rpa_ready",
|
||||
field_mapping=dict(structure_check['field_mapping']),
|
||||
mapping_source='parsing_profile',
|
||||
commit=False,
|
||||
)
|
||||
item_savepoint.commit()
|
||||
@@ -2245,6 +2270,21 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
})
|
||||
else:
|
||||
_handle_rpa_inventory_failed(task, merged_item, runtime, commit=False)
|
||||
# 失败回调已把 Task 从 rpa_pending 还原为库存不可用;必须立即同步正式 Gate,
|
||||
# 否则 Execution 仍是 waiting_external,前端会错误停在“系统处理中”。
|
||||
if task.active_process_execution_id:
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
execution = db.session.get(
|
||||
ShippingProcessExecution,
|
||||
int(task.active_process_execution_id),
|
||||
)
|
||||
if execution is not None:
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='system',
|
||||
)
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"warehouse_id": warehouse_id,
|
||||
@@ -2400,6 +2440,10 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
structure_check = validate_production_inventory_structure(
|
||||
source_code=source_code, path=ingest_path,
|
||||
)
|
||||
# 定时预热快照同样经过正式 Profile 校验,后续绑定任务可直接匹配。
|
||||
inv_file.field_mapping_json = dict(structure_check['field_mapping'])
|
||||
inv_file.mapping_source = 'parsing_profile'
|
||||
inv_file.mapping_confirmed = True
|
||||
created_entry = {
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"source_code": inv_file.source_code or source_code,
|
||||
@@ -2455,6 +2499,8 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
column_meta=column_meta,
|
||||
source="rpa_batch_callback",
|
||||
event_type="inventory_rpa_ready",
|
||||
field_mapping=dict(structure_check['field_mapping']),
|
||||
mapping_source='parsing_profile',
|
||||
commit=False,
|
||||
)
|
||||
_mark_inventory_rpa_run_no_consumed(
|
||||
|
||||
@@ -2381,6 +2381,8 @@ def submit_order_extraction(
|
||||
primary_run: ShippingOrderProcessingRun | None = None
|
||||
any_reused = False
|
||||
for index, intake_no in enumerate(list(intake_nos or [])):
|
||||
# [STEP 2] 首个 Run 可能在空 conversation_id 下创建本地会话;后续 Intake
|
||||
# 必须沿用该会话,避免一次多 EML 被拆成多个左侧对话。
|
||||
created_run, reused_one = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=owner_agent.id,
|
||||
@@ -2395,6 +2397,7 @@ def submit_order_extraction(
|
||||
any_reused = any_reused or reused_one
|
||||
if primary_run is None:
|
||||
primary_run = created_run
|
||||
conversation_id = created_run.conversation_id
|
||||
if primary_run is None:
|
||||
raise ValidationError(
|
||||
'intake_nos is required',
|
||||
|
||||
@@ -16,6 +16,8 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并
|
||||
持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task
|
||||
豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束;
|
||||
新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照
|
||||
Task 推入库存/RPA;
|
||||
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
|
||||
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
|
||||
避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox),
|
||||
@@ -357,6 +359,24 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
|
||||
if isinstance(run.input_snapshot_json, dict) else {}
|
||||
)
|
||||
configs = [item for item in definition.get('fields') or [] if isinstance(item, dict) and item.get('enabled', True)]
|
||||
formal_line_codes = {
|
||||
str(item.get('field_code') or '')
|
||||
for item in configs
|
||||
if str(item.get('scope') or '') == 'line' and item.get('field_code')
|
||||
}
|
||||
unknown_line_fields = sorted({
|
||||
str(key)
|
||||
for line in summary.get('lines') or []
|
||||
if isinstance(line, dict)
|
||||
for key in line
|
||||
if str(key) not in formal_line_codes and not str(key).startswith('_')
|
||||
})
|
||||
if unknown_line_fields:
|
||||
raise ValidationError(
|
||||
'订单明细包含未在当前 Schema 中定义的字段',
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
details={'fields': unknown_line_fields, 'schema_version_id': int(case.current_draft.schema_version_id)},
|
||||
)
|
||||
normalized = _build_confirmation_normalized_result(case=case, summary=summary)
|
||||
extraction = ShippingOrderExtraction(
|
||||
run_id=int(run.id), intake_id=int(intake_id), schema_version_id=int(case.current_draft.schema_version_id),
|
||||
@@ -1388,6 +1408,16 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
)
|
||||
else:
|
||||
try_auto_confirm_task_customer(task)
|
||||
# [STEP] Review 确认建单与自动建单必须共享订单快照前置条件。
|
||||
# 冻结失败由外层 AppError 回滚,不能留下已建单但库存链路无法启动的半成品。
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=int(user_id),
|
||||
expected_order_data_version=int(task.order_data_version or 1),
|
||||
freeze_mode='manual',
|
||||
)
|
||||
except AppError as err:
|
||||
_reject_confirmation(
|
||||
case,
|
||||
|
||||
@@ -443,11 +443,17 @@ def ensure_all_required_sources_prepared(
|
||||
dict(legacy_rpa_source, **{'source_code': source_code}),
|
||||
payload=per_source_payload,
|
||||
)
|
||||
if trigger_result:
|
||||
new_att.trigger_file_path = str(trigger_result)
|
||||
if not trigger_result:
|
||||
# 没有真实文件就不能宣称 queued;否则 Gate 会显示等待 RPA,Worker 永远不会领取。
|
||||
new_att.status = 'failed'
|
||||
new_att.error_code = 'trigger_not_written'
|
||||
new_att.error_message = '库存 RPA trigger 文件未生成'
|
||||
new_att.execution_phase = 'trigger_write_failed'
|
||||
new_att.updated_at = datetime.utcnow()
|
||||
failed.append(source_code)
|
||||
else:
|
||||
new_att.trigger_file_path = trigger_fname
|
||||
pending.append(source_code)
|
||||
new_att.trigger_file_path = str(trigger_result)
|
||||
pending.append(source_code)
|
||||
except Exception as exc: # pragma: no cover - RPA 环境异常
|
||||
new_att.status = 'failed'
|
||||
new_att.error_code = 'trigger_write_error'
|
||||
|
||||
@@ -18,6 +18,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
@@ -666,6 +667,74 @@ def _fulfillment_blocking_finding(
|
||||
}]
|
||||
|
||||
|
||||
def _supersede_auto_inventory_poll_for_rpa_failure(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
task: ShippingNotice,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
) -> None:
|
||||
"""RPA 已耗尽时终止同 Gate 的自动轮询,释放业务结果回写。
|
||||
|
||||
自动轮询 Attempt 不产生新的库存事实;其在 RPA 已失败后继续 queued/running
|
||||
会使 sync_gate_from_business_result 早退,Gate 永久停留 waiting_external。
|
||||
仅处理 trigger_type=auto 且 action_code=poll_inventory_preparation,绝不终止
|
||||
用户主动 retry_inventory_preparation。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
if (
|
||||
str(task.process_status or '').strip() != 'waiting_inventory'
|
||||
or str(task.pending_human_reason or '').strip() != PH_RPA_EXHAUSTED
|
||||
):
|
||||
return
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).with_for_update().first()
|
||||
if gate is None:
|
||||
return
|
||||
active_attempts = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter(
|
||||
ShippingProcessGateAttempt.gate_id == int(gate.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
ShippingProcessGateAttempt.trigger_type == 'auto',
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
for attempt in active_attempts:
|
||||
snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {}
|
||||
if str(snapshot.get('action_code') or '').strip() != 'poll_inventory_preparation':
|
||||
continue
|
||||
before = {'status': attempt.status, 'gate_code': gate.gate_code}
|
||||
attempt.status = 'superseded'
|
||||
attempt.finished_at = now
|
||||
attempt.lease_token = None
|
||||
attempt.lease_expires_at = None
|
||||
attempt.error_code = 'rpa_callback_failed'
|
||||
attempt.error_summary = 'RPA callback failed; automatic inventory poll superseded.'
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_attempt_superseded',
|
||||
aggregate_type='process_gate_attempt',
|
||||
aggregate_id=str(attempt.id),
|
||||
action='supersede_auto_inventory_poll',
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
task_no=str(task.task_no or '') or None,
|
||||
reason_code='rpa_callback_failed',
|
||||
before=before,
|
||||
after={'status': 'superseded', 'gate_code': gate.gate_code},
|
||||
metadata={'execution_no': execution.execution_no},
|
||||
source='process_gate_bridge',
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def sync_fulfillment_gates_from_task(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
@@ -690,6 +759,13 @@ def sync_fulfillment_gates_from_task(
|
||||
if task is None:
|
||||
return
|
||||
|
||||
_supersede_auto_inventory_poll_for_rpa_failure(
|
||||
execution=execution,
|
||||
task=task,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
|
||||
@@ -711,9 +787,14 @@ def sync_fulfillment_gates_from_task(
|
||||
match_passed = match_status in {'fulfillable', 'partial', 'unfulfillable'} or status in {
|
||||
'matched', 'waiting_upload', 'upload_failed', *done_statuses,
|
||||
}
|
||||
# 仅当存在活跃库存文件且未确认映射时阻断;无文件但已有解析行视为映射已由 Profile 固化。
|
||||
# 仅手动上传且未确认映射的文件允许进入人工字段映射;库存源/RPA 文件必须由
|
||||
# 正式 Profile 在入库时确定性确认,不能因为历史快照缺少该标记而阻塞。
|
||||
source_query = getattr(inv_file, 'source_query_json', None) if inv_file is not None else None
|
||||
trigger_type = str((source_query or {}).get('trigger_type') or '').strip().lower() if isinstance(source_query, dict) else ''
|
||||
is_manual_upload = trigger_type == 'manual_upload'
|
||||
mapping_needed = (
|
||||
inv_file is not None
|
||||
and is_manual_upload
|
||||
and not mapping_confirmed
|
||||
and status not in {'matched', 'waiting_upload', 'upload_failed', *done_statuses}
|
||||
)
|
||||
@@ -753,7 +834,9 @@ def sync_fulfillment_gates_from_task(
|
||||
preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first()
|
||||
except Exception: # noqa: BLE001
|
||||
preparation = None
|
||||
if preparation is not None:
|
||||
# 已绑定库存行代表正式快照已成功落库;历史 PreparationAttempt 即使仍标为
|
||||
# waiting_external,也只能保留审计,不能覆盖当前任务事实并阻止进入匹配。
|
||||
if preparation is not None and not has_inventory_lines:
|
||||
source_rows = list(getattr(preparation, 'source_attempts', []) or [])
|
||||
required = [str(row.source_code or '').strip().upper() for row in source_rows]
|
||||
prepared = [code for code, row in zip(required, source_rows) if row.status in {'ready', 'reusable'}]
|
||||
@@ -767,7 +850,10 @@ def sync_fulfillment_gates_from_task(
|
||||
'pending_sources': pending,
|
||||
'failed_sources': failed,
|
||||
})
|
||||
if preparation.status in {'queued', 'running', 'waiting_external'} or pending:
|
||||
# Task 已明确 rpa_exhausted 时,Preparation 的旧 waiting_external 不能
|
||||
# 继续把 Gate 投影成系统处理中;Preparation 保留 waiting 作为原始审计事实。
|
||||
task_rpa_exhausted = str(task.pending_human_reason or '').strip() == 'rpa_exhausted'
|
||||
if not task_rpa_exhausted and (preparation.status in {'queued', 'running', 'waiting_external'} or pending):
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='inventory_preparation', passed=False,
|
||||
outcome='waiting_external', effective_result={'findings': [], **task_facts},
|
||||
@@ -793,17 +879,25 @@ def sync_fulfillment_gates_from_task(
|
||||
)
|
||||
# Continue below for mapping/matching facts.
|
||||
if status == 'waiting_inventory':
|
||||
from app.services.shipping_notice.constants import PH_RPA_PENDING
|
||||
waiting_reason = (
|
||||
'inventory_rpa_queued'
|
||||
if str(task.pending_human_reason or '').strip() == PH_RPA_PENDING
|
||||
else 'inventory_preparation_waiting'
|
||||
)
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
|
||||
pending_reason = str(task.pending_human_reason or '').strip()
|
||||
# 只有 Worker 已领取/等待回调才是 waiting_external。RPA 失败或次数耗尽时
|
||||
# 必须退出自动处理中,回到可恢复 Gate,不能因 process_status 相同再次自动入队。
|
||||
if pending_reason == PH_RPA_PENDING:
|
||||
outcome = 'waiting_external'
|
||||
waiting_reason = 'inventory_rpa_queued'
|
||||
elif pending_reason == PH_RPA_EXHAUSTED:
|
||||
outcome = 'blocked_manual'
|
||||
waiting_reason = 'inventory_rpa_exhausted'
|
||||
else:
|
||||
outcome = 'blocked_retryable'
|
||||
waiting_reason = inventory_preparation_reason_code(task) or 'inventory_preparation_failed'
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='inventory_preparation',
|
||||
passed=False,
|
||||
outcome='waiting_external',
|
||||
outcome=outcome,
|
||||
effective_result={
|
||||
'findings': _fulfillment_blocking_finding(
|
||||
gate_code='inventory_preparation',
|
||||
@@ -894,7 +988,9 @@ def sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
gate_code='inventory_matching',
|
||||
passed=match_passed,
|
||||
outcome='blocked_manual' if (not match_passed and status in {'pending_review', 'inventory_ready'}) else None,
|
||||
# 库存快照已就绪但 match_status 未落终态表示匹配自动推进已中断。此时必须
|
||||
# 提供 retry_inventory_matching,不能保留 pending 并伪装为系统处理中。
|
||||
outcome='blocked_retryable' if not match_passed else None,
|
||||
effective_result={
|
||||
'findings': (
|
||||
[] if match_passed else _fulfillment_blocking_finding(
|
||||
|
||||
@@ -15,6 +15,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
@@ -762,14 +763,33 @@ def _handle_retry_inventory_preparation(
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
|
||||
recovery_plan_id = payload.get('recovery_plan_id')
|
||||
# Gate Worker 通过 _task_payload 传递 operator_id;人工 API 可能传 actor_user_id/user_id。
|
||||
# 三者必须统一,否则冻结订单快照会收到 None,并在 RPA Attempt/trigger 创建前失败。
|
||||
actor_id = (
|
||||
payload.get('actor_user_id')
|
||||
or payload.get('user_id')
|
||||
or payload.get('operator_id')
|
||||
)
|
||||
preparation_round = None
|
||||
if task is not None and payload.get('action_code') != 'poll_inventory_preparation':
|
||||
# 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实,
|
||||
# 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。
|
||||
if not task.order_snapshot_id:
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=actor_id,
|
||||
expected_order_data_version=int(task.order_data_version or 1),
|
||||
freeze_mode='manual',
|
||||
)
|
||||
db.session.flush()
|
||||
if payload.get('action_code') in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'}:
|
||||
invalidate_inventory_downstream(
|
||||
execution=execution,
|
||||
action_code=str(payload.get('action_code')),
|
||||
attempt_id=payload.get('attempt_id'),
|
||||
actor_id=payload.get('actor_user_id'),
|
||||
actor_id=actor_id,
|
||||
)
|
||||
preparation_round = create_inventory_preparation_round(
|
||||
task=task,
|
||||
|
||||
@@ -107,6 +107,7 @@ def _resolve_recovery_next_action(
|
||||
blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower()
|
||||
normalized_reason = str((blocking or {}).get('blocking_reason_code') or '').strip().lower()
|
||||
status = str((blocking or {}).get('status') or '').strip().lower()
|
||||
has_formal_task = bool(execution and getattr(execution, 'task_id', None))
|
||||
|
||||
# [STEP 1] 库存准备失败统一允许业务用户手动重新获取库存;人工上传是辅助输入入口。
|
||||
if blocking_gate_code == 'inventory_preparation':
|
||||
@@ -114,6 +115,13 @@ def _resolve_recovery_next_action(
|
||||
if inventory_action:
|
||||
return inventory_action, False
|
||||
|
||||
# 库存匹配失败属于业务可恢复阻断;即使 Gate 责任方是 worker,
|
||||
# 业务用户仍必须能重新提交匹配,不能只投影“可重试”状态而隐藏按钮。
|
||||
if blocking_gate_code == 'inventory_matching' and (
|
||||
has_formal_task or status == 'blocked_retryable'
|
||||
):
|
||||
return 'retry_inventory_matching', False
|
||||
|
||||
# [STEP 2] 货代上传 RPA 失败 / 人工交接失败:保持统一的 RPA 重试入口。
|
||||
if (
|
||||
blocking_gate_code == 'freight_upload_rpa'
|
||||
@@ -143,10 +151,11 @@ def _resolve_recovery_next_action(
|
||||
next_action = None
|
||||
technical_auto_only = True
|
||||
|
||||
# RecoveryPlan 复核入口兜底(inventory_matching / inventory_sufficiency)。
|
||||
# RecoveryPlan 复核入口兜底(建单前 inventory_matching / inventory_sufficiency)。
|
||||
# 正式 OT 的库存匹配只能重试,不能下发无写操作的复核导航入口。
|
||||
if not next_action:
|
||||
recovery_targets = full.get('recovery_targets') or []
|
||||
if recovery_targets and blocking_gate_code == 'inventory_matching':
|
||||
if recovery_targets and blocking_gate_code == 'inventory_matching' and not has_formal_task:
|
||||
next_action = 'open_inventory_match_review'
|
||||
technical_auto_only = False
|
||||
elif recovery_targets and blocking_gate_code == 'inventory_sufficiency':
|
||||
@@ -428,6 +437,23 @@ def _navigation_for_action(action_code: str | None, refs: dict[str, Any]) -> dic
|
||||
return None
|
||||
|
||||
|
||||
def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) -> bool:
|
||||
"""判断 pending 匹配 Gate 是否已有可复用的已确认库存快照。"""
|
||||
if not execution.task_id:
|
||||
return False
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
|
||||
task = ShippingNotice.query.get(int(execution.task_id))
|
||||
if task is None or not isinstance(task.inventory_lines_json, list) or not task.inventory_lines_json:
|
||||
return False
|
||||
inventory_file = active_inventory_file_for_task(task)
|
||||
return bool(
|
||||
inventory_file is not None
|
||||
and bool(getattr(inventory_file, 'mapping_confirmed', False))
|
||||
)
|
||||
|
||||
|
||||
def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, Any]:
|
||||
"""
|
||||
用户端安全投影:唯一当前阻断 + 主要恢复动作;不含管理员诊断 JSON。
|
||||
@@ -482,6 +508,20 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
}
|
||||
current = full.get('current_gate')
|
||||
blocking = None
|
||||
if (
|
||||
isinstance(current, dict)
|
||||
and str(current.get('gate_code') or '').strip().lower() == 'inventory_field_mapping'
|
||||
and str(current.get('status') or '').strip().lower() == 'pending'
|
||||
):
|
||||
current = {**current, 'status': 'blocked_manual', 'next_action_code': 'confirm_inventory_field_mapping'}
|
||||
if (
|
||||
isinstance(current, dict)
|
||||
and str(current.get('gate_code') or '').strip().lower() == 'inventory_matching'
|
||||
and str(current.get('status') or '').strip().lower() == 'pending'
|
||||
and _has_confirmed_inventory_for_matching(execution)
|
||||
):
|
||||
# 库存快照已确认但匹配未落终态,说明自动推进已中断;不能继续显示系统处理中。
|
||||
current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_inventory_matching'}
|
||||
if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | {
|
||||
'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated',
|
||||
}:
|
||||
@@ -525,6 +565,16 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
|
||||
allowed_actions: list[str] = []
|
||||
action_items: list[dict[str, str]] = []
|
||||
is_formal_inventory_matching = bool(
|
||||
getattr(execution, 'task_id', None)
|
||||
and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_matching'
|
||||
)
|
||||
recovery_targets = full.get('recovery_targets') or []
|
||||
if is_formal_inventory_matching:
|
||||
recovery_targets = [
|
||||
target for target in recovery_targets
|
||||
if str(target.get('action_code') or '').strip() == 'retry_inventory_from_preparation'
|
||||
]
|
||||
if blocking:
|
||||
if next_action and is_business_user_action(str(next_action)):
|
||||
allowed_actions.append(str(next_action))
|
||||
@@ -533,7 +583,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
and next_action == 'retry_inventory_preparation'
|
||||
):
|
||||
allowed_actions.append('upload_inventory_file')
|
||||
for target in full.get('recovery_targets') or []:
|
||||
for target in recovery_targets:
|
||||
code = str(target.get('action_code') or '').strip()
|
||||
if code and code not in allowed_actions and is_business_user_action(code):
|
||||
allowed_actions.append(code)
|
||||
@@ -569,7 +619,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
'current_gate': current,
|
||||
'current_blocking_gate': blocking,
|
||||
# 客户端只消费服务端已校验的恢复目标,不自行推导跨 Gate 路径。
|
||||
'recovery_targets': full.get('recovery_targets') or [],
|
||||
'recovery_targets': recovery_targets,
|
||||
'active_recovery_plans': full.get('active_recovery_plans') or [],
|
||||
'blocking_reason_code': reason_code,
|
||||
'blocking_message': _user_facing_blocking_message(reason_code),
|
||||
|
||||
@@ -109,6 +109,20 @@ def get_execution_by_no(execution_no: str) -> ShippingProcessExecution:
|
||||
return row
|
||||
|
||||
|
||||
def _primary_recovery_action(
|
||||
*, execution: ShippingProcessExecution, gate: ShippingProcessGate,
|
||||
) -> str | None:
|
||||
"""按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。"""
|
||||
if gate.gate_code == 'inventory_preparation':
|
||||
return inventory_preparation_primary_action(gate.status)
|
||||
# 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。
|
||||
if gate.gate_code == 'inventory_matching' and execution.task_id:
|
||||
return 'retry_inventory_matching'
|
||||
return gate.next_action_code or primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status=gate.status,
|
||||
)
|
||||
|
||||
|
||||
def request_gate_action(
|
||||
*,
|
||||
execution_no: str,
|
||||
@@ -218,10 +232,7 @@ def request_gate_action(
|
||||
details={'gate_code': gate.gate_code, 'action_code': action},
|
||||
)
|
||||
|
||||
primary = inventory_preparation_primary_action(gate.status) if gate.gate_code == 'inventory_preparation' else None
|
||||
primary = primary or gate.next_action_code or primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status=gate.status,
|
||||
)
|
||||
primary = _primary_recovery_action(execution=execution, gate=gate)
|
||||
# [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA
|
||||
# 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。
|
||||
# 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。
|
||||
|
||||
@@ -765,8 +765,16 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
if next_gate is None or not next_gate.next_action_code:
|
||||
return
|
||||
definition = get_process_gate_definition(next_gate.gate_code)
|
||||
# default_next_actions 中可恢复不等于可自动执行。库存匹配等动作必须由
|
||||
# 用户明确点击;否则库存准备通过后会立刻消费“重试库存匹配”按钮,页面
|
||||
# 只剩被自动执行后的结果,用户无法控制重试时机。
|
||||
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
|
||||
return
|
||||
if (
|
||||
next_gate.next_action_code in {'retry_inventory_matching'}
|
||||
or str(next_gate.next_action_code).startswith('open_')
|
||||
):
|
||||
return
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=next_gate.gate_code,
|
||||
@@ -911,7 +919,33 @@ def sync_gate_from_business_result(
|
||||
.first()
|
||||
)
|
||||
if active_attempt is not None:
|
||||
return gate
|
||||
# 库存快照已落库时,自动轮询已获得其等待的正式事实。直接复用此 Attempt
|
||||
# 完成库存准备,避免先终止后重新排队时被自动推进器插入新的轮询。用户主动
|
||||
# Attempt 绝不在这里完成或覆盖。
|
||||
snapshot = (
|
||||
active_attempt.input_snapshot_json
|
||||
if isinstance(active_attempt.input_snapshot_json, dict)
|
||||
else {}
|
||||
)
|
||||
inventory_ready = bool(
|
||||
gate_code == 'inventory_preparation'
|
||||
and passed
|
||||
and isinstance(effective_result_json, dict)
|
||||
and effective_result_json.get('has_inventory_lines')
|
||||
)
|
||||
is_auto_poll = (
|
||||
active_attempt.trigger_type == 'auto'
|
||||
and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation'
|
||||
)
|
||||
if not inventory_ready or not is_auto_poll:
|
||||
return gate
|
||||
return complete_gate_attempt(
|
||||
attempt_id=int(active_attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot=effective_result_json,
|
||||
recommendation_json=recommendation_json,
|
||||
effective_result_json=effective_result_json,
|
||||
)
|
||||
|
||||
if allow_repass and gate.status == 'passed':
|
||||
gate.status = 'invalidated'
|
||||
|
||||
@@ -290,6 +290,7 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = (
|
||||
'open_inventory_match_review',
|
||||
'open_shortage_review',
|
||||
'upload_inventory_file',
|
||||
'retry_inventory_matching',
|
||||
'retry',
|
||||
'refresh',
|
||||
'regenerate_excel',
|
||||
|
||||
@@ -9,6 +9,7 @@ services/shipping_notice/rpa.py
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
@@ -837,11 +837,19 @@ def _order_task_current_gate(
|
||||
|
||||
notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id))
|
||||
if notice is not None:
|
||||
execution = (
|
||||
ShippingProcessExecution.query.filter_by(task_id=int(notice.id))
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
execution = None
|
||||
active_execution_id = getattr(notice, '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(notice.id):
|
||||
execution = None
|
||||
if execution is None:
|
||||
execution = (
|
||||
ShippingProcessExecution.query.filter_by(task_id=int(notice.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if execution is not None:
|
||||
summary = project_user_gate_summary(execution)
|
||||
blocking = summary.get('current_blocking_gate') or summary.get('current_gate')
|
||||
@@ -1015,6 +1023,14 @@ def _project_order_task_work_item(
|
||||
if shared_code in SHIPPING_PROCESSING_STAGES:
|
||||
stage = shared_code
|
||||
stage_label_key = str(shared.get('label_key') or '').strip() or None
|
||||
active_execution_id = getattr(notice_for_stage, 'active_process_execution_id', None)
|
||||
if active_execution_id is not None:
|
||||
from app.models import ShippingProcessExecution
|
||||
active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
|
||||
active_gate = str(getattr(active_execution, 'current_gate_code', '') or '').strip().lower()
|
||||
if active_gate in SHIPPING_PROCESSING_STAGES:
|
||||
stage = active_gate
|
||||
stage_label_key = active_gate
|
||||
# order_creating 无共享投影时仍统一用户文案键。
|
||||
if not stage_label_key and stage == 'order_creating':
|
||||
stage_label_key = 'waiting_system_start'
|
||||
|
||||
@@ -387,8 +387,8 @@ def test_excel_pull_request_number_uses_export_date_without_changing_case_number
|
||||
assert shipping_case.business_no == 'IVMX26080801'
|
||||
|
||||
|
||||
def test_export_mapping_falls_back_to_export_sequence_and_derived_line_amount(app):
|
||||
"""LineNumber 缺失时用导出行序号,Shipment Value 缺失时用数量乘单价。"""
|
||||
def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app):
|
||||
"""正式金额必须来自 Schema FieldValue,禁止由快照或单价静默推导。"""
|
||||
with app.app_context():
|
||||
fields = _lookup_standard_fields('line_no', 'line_amount_with_tax')
|
||||
task = ShippingNotice(task_no='TASK-MAPPING')
|
||||
@@ -400,7 +400,7 @@ def test_export_mapping_falls_back_to_export_sequence_and_derived_line_amount(ap
|
||||
assert _mapping_value(
|
||||
{'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'},
|
||||
task=task, order_values={'__qty': Decimal('14'), '__unit_price': Decimal('941.76')}, inventory_values={},
|
||||
) == 13184.64
|
||||
) is None
|
||||
|
||||
|
||||
def test_clear_template_data_rows_keeps_headers_and_removes_residual_values():
|
||||
|
||||
@@ -470,6 +470,32 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
|
||||
assert result["failed_count"] == 1
|
||||
|
||||
|
||||
def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path):
|
||||
"""RPA 文件经过正式 Profile 校验后必须直接确认映射,不进入人工 Gate。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "inventory-mapping-confirmed.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
"run_no": "RUN-MAPPING-CONFIRMED",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
|
||||
}))
|
||||
assert result["success_count"] == 1
|
||||
snapshot = ShippingInventoryFile.query.filter_by(rpa_run_no="RUN-MAPPING-CONFIRMED").one()
|
||||
assert snapshot.mapping_source == "parsing_profile"
|
||||
assert snapshot.mapping_confirmed is True
|
||||
assert snapshot.field_mapping_json
|
||||
|
||||
|
||||
def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
|
||||
"""全 failed 时接口 status 仍为 ok,业务结果见 result_status=failed。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
@@ -11,11 +11,12 @@ import pytest
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
|
||||
|
||||
|
||||
def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path):
|
||||
def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
|
||||
"""batch 开启时单票按需应写 inventory_export_batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
|
||||
app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
|
||||
source = {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
|
||||
@@ -13,7 +13,7 @@ from datetime import datetime
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderProcessingRun
|
||||
from app.models import ChatSession, ShippingOrderProcessingRun
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
evaluate_can_append,
|
||||
@@ -167,6 +167,35 @@ def test_submit_idempotent_by_submission_id(app):
|
||||
assert ShippingOrderProcessingRun.query.count() == 1
|
||||
|
||||
|
||||
def test_submit_multiple_unbound_intakes_creates_one_chat_session(app):
|
||||
"""一次多邮件首次提交可建多个 Run,但必须共用服务端新建的一个会话。"""
|
||||
with app.app_context():
|
||||
user, agent, _session, first_intake, _document = _seed_run_input(suffix='MULTI-EML-A')
|
||||
_, _, _, second_intake, _document = _seed_run_input(
|
||||
suffix='MULTI-EML-B',
|
||||
agent_code='shipping_notice_multi_eml_b',
|
||||
)
|
||||
first_intake.conversation_id = None
|
||||
second_intake.user_id = user.id
|
||||
second_intake.conversation_id = None
|
||||
db.session.commit()
|
||||
|
||||
payload = submit_order_extraction(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id='',
|
||||
intake_nos=[first_intake.intake_no, second_intake.intake_no],
|
||||
submission_id='SUB-TEST-MULTI-EML-ONE-CONVERSATION',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
runs = ShippingOrderProcessingRun.query.order_by(ShippingOrderProcessingRun.id).all()
|
||||
conversation_ids = {run.conversation_id for run in runs}
|
||||
assert len(runs) == 2
|
||||
assert conversation_ids == {runs[0].conversation_id}
|
||||
assert ChatSession.query.filter(ChatSession.session_id.in_(conversation_ids)).count() == 1
|
||||
|
||||
|
||||
def test_legacy_create_can_still_block_parallel_when_flag_false(app):
|
||||
"""兼容路径 allow_parallel_conversation_runs=False 仍抛 CONVERSATION_ACTIVE。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -978,6 +978,8 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
|
||||
assert getattr(task, 'order_task_id', None) is not None
|
||||
assert task.source_candidate_id is not None
|
||||
assert task.current_order_extraction_id is not None
|
||||
# 关键断言:复核确认建单必须同步冻结,库存/RPA 不可消费可变解析结果。
|
||||
assert task.order_snapshot_id is not None
|
||||
# 关键断言:复核确认已完成解析确认,不能把新任务重新放回低置信度解析复核。
|
||||
assert task.process_status == 'parsed'
|
||||
assert task.review_status is None
|
||||
|
||||
@@ -197,6 +197,49 @@ def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technica
|
||||
]
|
||||
|
||||
|
||||
def test_formal_inventory_matching_uses_only_executable_retries(app, monkeypatch):
|
||||
"""正式 OT 库存匹配阻断不得投影无写操作的复核入口。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-INV-OT-1', status='blocked',
|
||||
current_gate_code='inventory_matching', primary_next_action_code='open_inventory_match_review',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-INV-OT-1', 'status': 'blocked',
|
||||
'primary_next_action_code': 'open_inventory_match_review',
|
||||
'responsible_party': 'worker',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_matching',
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_match_incomplete',
|
||||
'next_action_code': 'open_inventory_match_review',
|
||||
},
|
||||
'recovery_targets': [
|
||||
{'action_code': 'open_inventory_match_review', 'target_gate': 'inventory_matching'},
|
||||
{'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'},
|
||||
],
|
||||
'gates': [], 'active_recovery_plans': [],
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['next_action_code'] == 'retry_inventory_matching'
|
||||
assert summary['allowed_actions'] == [
|
||||
'retry_inventory_matching',
|
||||
'retry_inventory_from_preparation',
|
||||
]
|
||||
assert summary['recovery_targets'] == [
|
||||
{'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'},
|
||||
]
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch):
|
||||
"""所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -13,11 +13,16 @@ Gate 的 responsible_party='worker' 被历史「worker/retry_ 技术动作屏蔽
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.process_gate_projection import (
|
||||
_resolve_recovery_next_action,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_recovery_service import (
|
||||
_primary_recovery_action,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -118,6 +123,51 @@ def test_inventory_matching_recovery_target_navigates_to_review():
|
||||
assert action == 'open_inventory_match_review'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_formal_inventory_matching_recovery_target_retries_matching():
|
||||
"""正式 OT 的库存匹配阻断必须下发可执行的重新库存匹配。"""
|
||||
full, blocking = _mk(
|
||||
{'gate_code': 'inventory_matching', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_match_failed'},
|
||||
recovery_targets=[{'action_code': 'retry_inventory_from_preparation'}],
|
||||
)
|
||||
action, tech_only = _resolve_recovery_next_action(
|
||||
blocking=blocking,
|
||||
full=full,
|
||||
execution=SimpleNamespace(task_id=99),
|
||||
)
|
||||
assert action == 'retry_inventory_matching'
|
||||
assert tech_only is False
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_formal_inventory_matching_request_validation_uses_retry_action():
|
||||
"""正式 OT 的请求校验必须与用户投影一致,覆盖旧导航动作。"""
|
||||
action = _primary_recovery_action(
|
||||
execution=SimpleNamespace(task_id=99),
|
||||
gate=SimpleNamespace(
|
||||
gate_code='inventory_matching',
|
||||
status='blocked_manual',
|
||||
next_action_code='open_inventory_match_review',
|
||||
),
|
||||
)
|
||||
assert action == 'retry_inventory_matching'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_inventory_matching_retryable_exposes_retry_action():
|
||||
"""库存匹配 Gate 可重试时必须直接显示重新匹配按钮。"""
|
||||
full, blocking = _mk(
|
||||
{'gate_code': 'inventory_matching', 'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_match_failed'},
|
||||
)
|
||||
action, technical_auto_only = _resolve_recovery_next_action(
|
||||
blocking=blocking, full=full, execution=None,
|
||||
)
|
||||
assert action == 'retry_inventory_matching'
|
||||
assert technical_auto_only is False
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_inventory_preparation_retryable_without_reason_uses_contract_action():
|
||||
"""无特定原因码、仅 blocked_retryable 时沿用 Gate 合同默认动作(retry_inventory_preparation)。"""
|
||||
|
||||
@@ -114,6 +114,77 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
|
||||
assert captured['callback_id'].endswith(':C1')
|
||||
|
||||
|
||||
def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
"""trigger 写入返回空路径时,Attempt 必须失败,禁止伪装 queued。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-TRIGGER-MISSING', process_status='waiting_inventory')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS'])
|
||||
monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False)
|
||||
monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_trigger_for_task', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code: {'source_code': code, 'warehouse_id': 'WH-1'},
|
||||
)
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa')
|
||||
assert result.pending_source_codes == []
|
||||
assert result.failed_source_codes == ['DBS']
|
||||
attempt = per_source_rpa_service._latest_attempt(task.task_no, 'DBS')
|
||||
assert attempt.status == 'failed'
|
||||
assert attempt.error_code == 'trigger_not_written'
|
||||
|
||||
|
||||
def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkeypatch, app):
|
||||
"""正式 Gate Worker 仅携带 operator_id 时,也必须先冻结快照再写 RPA trigger。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution
|
||||
from app.services.shipping_notice import process_gate_executor
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-PREP-FREEZE-OPERATOR', process_status='waiting_inventory',
|
||||
order_snapshot_id=None, order_data_version=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-PREP-FREEZE-OPERATOR', task_id=task.id,
|
||||
current_gate_code='inventory_preparation', status='blocked',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
|
||||
seen = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot',
|
||||
lambda task, **kwargs: seen.update(kwargs) or object(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda payload: {'status': 'running', 'data': {'rpa': {}}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
|
||||
gate = type('Gate', (), {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', 'blocking_reason_code': None})()
|
||||
result = process_gate_executor._handle_retry_inventory_preparation(
|
||||
execution=execution, gate=gate,
|
||||
payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77},
|
||||
)
|
||||
assert seen['actor_id'] == 77
|
||||
assert result['outcome'] in {'blocked_retryable', 'blocked_manual'}
|
||||
|
||||
|
||||
def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
"""旧 CandidateSet 回调必须在写入库存事实前被拒绝。"""
|
||||
from app import db
|
||||
@@ -308,6 +379,78 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
|
||||
).count() == 1
|
||||
|
||||
|
||||
def test_batch_callback_inherits_authenticated_top_level_schema_version():
|
||||
"""Worker 将 schema_version 放在 batch 顶层时,结果项仍须通过逐源身份校验。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _merge_batch_callback_item
|
||||
|
||||
merged = _merge_batch_callback_item(
|
||||
{
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'run_no': 'BATCH-1',
|
||||
'task_no': 'SN-1',
|
||||
},
|
||||
{
|
||||
'source_code': 'DSV360_AWSSG',
|
||||
'source_run_no': 'PSR-SN-1-DSV360_AWSSG-A1-ABC',
|
||||
},
|
||||
)
|
||||
|
||||
assert merged['schema_version'] == 'shipping_inventory_rpa.v2'
|
||||
assert merged['run_no'] == 'BATCH-1'
|
||||
assert merged['task_no'] == 'SN-1'
|
||||
|
||||
|
||||
def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
"""RPA 已耗尽时自动轮询必须终态化,Gate 才能退出系统处理中。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RPA-FAILED-GATE', process_status='waiting_inventory',
|
||||
pending_human_reason='rpa_exhausted', error_message='RPA export failed',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-RPA-FAILED-GATE', task_id=task.id, status='waiting_external',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_preparation',
|
||||
).one()
|
||||
auto_poll = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
idempotency_key='shipping-auto-progress:rpa-failed-poll',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation'},
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
|
||||
db.session.refresh(auto_poll)
|
||||
db.session.refresh(gate)
|
||||
assert auto_poll.status == 'superseded'
|
||||
assert auto_poll.error_code == 'rpa_callback_failed'
|
||||
assert ShippingProcessGateAttempt.query.filter(
|
||||
ShippingProcessGateAttempt.gate_id == gate.id,
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
).count() == 0
|
||||
assert gate.status == 'blocked_manual'
|
||||
assert gate.blocking_reason_code == 'inventory_rpa_exhausted'
|
||||
db.session.refresh(execution)
|
||||
assert execution.status == 'blocked'
|
||||
|
||||
|
||||
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
|
||||
"""正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。"""
|
||||
from app import db
|
||||
@@ -749,6 +892,67 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa
|
||||
assert result['operator_id'] == 9
|
||||
|
||||
|
||||
def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch):
|
||||
"""旧 Task 缺订单快照时,Gate 重试必须先冻结,不能再次返回快照缺失。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
|
||||
|
||||
task = SimpleNamespace(
|
||||
order_snapshot_id=None,
|
||||
order_data_version=7,
|
||||
task_no='SN-LEGACY-SNAPSHOT-1',
|
||||
)
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
'app.models.ShippingNotice.query',
|
||||
SimpleNamespace(get=lambda _task_id: task),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor.db.session.flush',
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot',
|
||||
lambda target, **kwargs: captured.update(target=target, **kwargs) or setattr(target, 'order_snapshot_id', 901),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda _payload: {'status': 'running', 'message': 'waiting RPA'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_preparation_failed',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'task_id': task.task_no},
|
||||
)
|
||||
|
||||
result = _handle_retry_inventory_preparation(
|
||||
execution=SimpleNamespace(task_id=13, id=21),
|
||||
gate=SimpleNamespace(gate_code='inventory_preparation'),
|
||||
payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5},
|
||||
)
|
||||
|
||||
# 关键断言:正式 Gate 入口也补冻结,后续才允许进入库存 RPA。
|
||||
assert captured == {
|
||||
'target': task,
|
||||
'actor_id': 5,
|
||||
'expected_order_data_version': 7,
|
||||
'freeze_mode': 'manual',
|
||||
}
|
||||
assert task.order_snapshot_id == 901
|
||||
assert result['outcome'] == 'waiting_external'
|
||||
|
||||
|
||||
def test_manual_business_block_is_a_successful_attempt(app):
|
||||
"""库存匹配已执行但存在缺口时,Attempt 成功、Gate 保持人工阻断。"""
|
||||
from app import db
|
||||
|
||||
@@ -429,3 +429,58 @@ def test_project_user_gate_summary_clears_stale_confirm_customer(monkeypatch):
|
||||
summary = project_user_gate_summary(execution)
|
||||
assert summary['current_blocking_gate'] is None
|
||||
assert summary['next_action_code'] is None
|
||||
|
||||
|
||||
def test_project_user_gate_summary_exposes_retry_for_confirmed_inventory_pending_match(monkeypatch):
|
||||
"""已确认库存快照而匹配仍 pending 时,必须给精确重匹配按钮。"""
|
||||
execution = SimpleNamespace(execution_no='EX-MATCH-1', id=1, task_id=9, current_gate_code='inventory_matching')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EX-MATCH-1', 'status': 'running', 'primary_next_action_code': None,
|
||||
'responsible_party': 'worker', 'gates': [],
|
||||
'current_gate': {'gate_code': 'inventory_matching', 'status': 'pending', 'blocking_reason_code': None},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection._has_confirmed_inventory_for_matching',
|
||||
lambda _execution: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection._execution_navigation_refs',
|
||||
lambda _execution: {'case_no': 'SORC-1', 'review_case_no': 'SORC-1', 'review_run_no': 'RUN-1', 'task_no': 'SN-1'},
|
||||
)
|
||||
|
||||
summary = project_user_gate_summary(execution)
|
||||
|
||||
assert summary['current_blocking_gate']['status'] == 'blocked_retryable'
|
||||
assert summary['next_action_code'] == 'retry_inventory_matching'
|
||||
assert summary['allowed_actions'] == ['retry_inventory_matching']
|
||||
|
||||
|
||||
def test_project_user_gate_summary_keeps_pending_match_system_owned_without_inventory(monkeypatch):
|
||||
"""没有确认库存时不得伪造重匹配入口。"""
|
||||
execution = SimpleNamespace(execution_no='EX-MATCH-2', id=2, task_id=10, current_gate_code='inventory_matching')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EX-MATCH-2', 'status': 'running', 'primary_next_action_code': None,
|
||||
'responsible_party': 'worker', 'gates': [],
|
||||
'current_gate': {'gate_code': 'inventory_matching', 'status': 'pending', 'blocking_reason_code': None},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection._has_confirmed_inventory_for_matching',
|
||||
lambda _execution: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection._execution_navigation_refs',
|
||||
lambda _execution: {'case_no': None, 'review_case_no': None, 'review_run_no': None, 'task_no': 'SN-2'},
|
||||
)
|
||||
|
||||
summary = project_user_gate_summary(execution)
|
||||
|
||||
assert summary['current_blocking_gate'] is None
|
||||
assert summary['next_action_code'] is None
|
||||
@@ -17,6 +17,41 @@ from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
)
|
||||
|
||||
|
||||
def test_current_match_facts_rebuild_shortage_detail(monkeypatch):
|
||||
"""当前行事实有缺口时,工作台详情必须拿到数量和 shortage 状态。"""
|
||||
from app.services.shipping_notice import fulfillment_workflow as mod
|
||||
|
||||
rows = [
|
||||
SimpleNamespace(
|
||||
line_index=0, line_key='line-1', match_result='matched',
|
||||
part_number='PN-1', reservation_id='R1', unit='EA',
|
||||
inventory_source_code='SRC', required_qty=3, available_qty=3,
|
||||
shortage_qty=0,
|
||||
),
|
||||
SimpleNamespace(
|
||||
line_index=1, line_key='line-2', match_result='not_found',
|
||||
part_number='PN-2', reservation_id='R2', unit='EA',
|
||||
inventory_source_code='SRC', required_qty=5, available_qty=0,
|
||||
shortage_qty=5,
|
||||
),
|
||||
]
|
||||
fake_match_model = SimpleNamespace(
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(all=lambda: rows),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(mod, 'ShippingNoticeLineInventoryMatch', fake_match_model)
|
||||
task = SimpleNamespace(id=101, line_results_json=None, shortage_json=None)
|
||||
|
||||
status, shortages = mod._recompute_task_match_aggregate(task)
|
||||
|
||||
assert status == 'partial'
|
||||
assert task.line_results_json[1]['available_qty'] == 0.0
|
||||
assert task.line_results_json[1]['shortage_qty'] == 5.0
|
||||
assert task.line_results_json[1]['line_status'] == 'shortage'
|
||||
assert task.shortage_json == {'lines': shortages}
|
||||
|
||||
|
||||
def test_cross_candidate_unique_hit_is_fulfillable():
|
||||
"""唯一候选文件命中且数量充足 → fulfillable 并冻结源。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
|
||||
Reference in new issue
Block a user