feat(shipping-notice): 人工重取库存前置候选刷新并放开行级库存源下拉
- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更 - 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配 - 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定 - 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口 - 同步四语言文案、技术文档与实施计划
This commit is contained in:
1 parent
e38e5a63fe
commit
ea94fb28db
35 files changed
+2675
-83
No files matched your search
@@ -186,6 +186,7 @@ def workspace_shipping_tasks():
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
|
||||
@@ -394,14 +395,38 @@ def workspace_batch_restore_shipping_tasks():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
|
||||
def workspace_shipping_export_archive():
|
||||
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
||||
"""按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = data.get('task_nos')
|
||||
if task_nos is not None and not isinstance(task_nos, list):
|
||||
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or [])
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
|
||||
stream, filename, manifest = build_export_archive(
|
||||
user_id=user.id,
|
||||
task_nos=task_nos or [],
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
# 与 business_no 批量导出同一审计口径:按票落 record_access_audit(自行提交)。
|
||||
for entry in manifest.get('entries') or []:
|
||||
aggregate_no = str(entry.get('business_no') or '').strip()
|
||||
task_no = str(entry.get('task_no') or '').strip()
|
||||
if not aggregate_no and not task_no:
|
||||
continue
|
||||
record_access_audit(
|
||||
action='download_task_excel',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task_no or aggregate_no,
|
||||
actor_id=user.id,
|
||||
task_no=task_no or None,
|
||||
reason_code='excel_downloaded',
|
||||
metadata={
|
||||
'export': 'batch_zip',
|
||||
'batch_status': str(entry.get('status') or ''),
|
||||
},
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -455,7 +480,11 @@ def workspace_confirm_shipping_customer(task_no: str):
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
|
||||
return _ok(serialize_task_detail(updated))
|
||||
return _ok(serialize_task_detail(
|
||||
updated,
|
||||
viewer_user_id=user.id,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
@@ -499,7 +528,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task, viewer_user_id=user.id) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
@@ -657,7 +686,12 @@ def workspace_shipping_task_ui_state(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task, include_stage_context=True))
|
||||
return _ok(build_task_ui_state(
|
||||
task,
|
||||
include_stage_context=True,
|
||||
viewer_user_id=user.id,
|
||||
viewer_is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
@@ -1032,6 +1066,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin
|
||||
return task
|
||||
|
||||
|
||||
def _load_business_notice_readable_for_user(
|
||||
*,
|
||||
business_no: str,
|
||||
user_id: int,
|
||||
is_admin: bool,
|
||||
) -> ShippingNotice:
|
||||
"""
|
||||
按精确发货通知单号加载当前用户可下载的 Notice(创建者或管理员)。
|
||||
|
||||
核心逻辑:下载是只读动作,授权走 can_download_task_export 统一谓词口径
|
||||
(可下载=可见),不经过写路径的履约归属断言;管理员可下载其可见的正式
|
||||
Notice,且每次下载均由端点写入 record_access_audit。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号。
|
||||
user_id: 当前服务端会话用户主键。
|
||||
is_admin: 是否平台管理员。
|
||||
|
||||
Returns:
|
||||
可下载的 ShippingNotice。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 编号不存在、非正式 Notice 或用户不可见。
|
||||
"""
|
||||
normalized = str(business_no or '').strip().upper()
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(normalized, user_id, is_admin=is_admin)
|
||||
if not isinstance(task, ShippingNotice) or str(task.business_no or '').strip().upper() != normalized:
|
||||
raise NotFoundError('Shipping notice not found')
|
||||
return task
|
||||
|
||||
|
||||
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
|
||||
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
|
||||
@@ -1138,9 +1204,13 @@ def workspace_batch_start_shipping_notice_rpa_upload():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
|
||||
def workspace_shipping_notice_export(business_no: str):
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
|
||||
user = _require_user()
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||
task = _load_business_notice_readable_for_user(
|
||||
business_no=business_no,
|
||||
user_id=int(user.id),
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
@@ -1162,7 +1232,7 @@ def workspace_shipping_notice_export(business_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
|
||||
def workspace_shipping_notice_export_archive():
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_values = data.get('business_nos')
|
||||
@@ -1174,8 +1244,32 @@ def workspace_shipping_notice_export_archive():
|
||||
if not business_nos or len(business_nos) > 100:
|
||||
raise ValidationError('business_nos must contain 1 to 100 business numbers')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
|
||||
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos)
|
||||
stream, filename, manifest = build_export_archive(
|
||||
user_id=int(user.id),
|
||||
business_nos=business_nos,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
# 批量导出与单票下载同一审计口径:按票落 record_access_audit(自行提交),
|
||||
# manifest.business_no 是 aggregate 事实源;missing/checksum 票据也留痕。
|
||||
for entry in manifest.get('entries') or []:
|
||||
aggregate_no = str(entry.get('business_no') or '').strip()
|
||||
task_no = str(entry.get('task_no') or '').strip()
|
||||
if not aggregate_no and not task_no:
|
||||
continue
|
||||
record_access_audit(
|
||||
action='download_notice_excel',
|
||||
aggregate_type='shipping_notice',
|
||||
aggregate_id=aggregate_no or task_no,
|
||||
actor_id=user.id,
|
||||
task_no=task_no or None,
|
||||
reason_code='excel_downloaded',
|
||||
metadata={
|
||||
'export': 'batch_zip',
|
||||
'batch_status': str(entry.get('status') or ''),
|
||||
},
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -1183,9 +1277,10 @@ def workspace_shipping_notice_export_archive():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
"""下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=bool(user.is_platform_admin()))
|
||||
task = _require_formal_notice(task)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
|
||||
@@ -169,7 +169,7 @@ class ShippingQueryShortageDetailsAction:
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "query_shortage_details", "label": "查询缺口明细..."})
|
||||
detail = serialize_task_detail(task)
|
||||
detail = serialize_task_detail(task, viewer_user_id=int(ctx.user_id))
|
||||
content = format_shortage_details_message(detail if isinstance(detail, dict) else {})
|
||||
yield from stream_text_events(content, payload={"task_no": task.task_no})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "query_shortage_details"})
|
||||
|
||||
@@ -18,7 +18,10 @@ from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_visible_to_user,
|
||||
resolve_task_export_download,
|
||||
)
|
||||
|
||||
MAX_ARCHIVE_TASKS = 100
|
||||
|
||||
@@ -28,15 +31,17 @@ def _select_tasks(
|
||||
user_id: int,
|
||||
task_refs: list[str] | None,
|
||||
selection_name: str,
|
||||
is_admin: bool = False,
|
||||
require_business_no: bool = False,
|
||||
) -> tuple[list[ShippingNotice], str]:
|
||||
"""按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。"""
|
||||
"""按显式 task_no 或 business_no 选择当前用户可下载通知,禁止部分越权成功。"""
|
||||
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip()))
|
||||
if not normalized_tasks:
|
||||
raise ValidationError(f'{selection_name} is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
tasks = []
|
||||
for task_no in normalized_tasks:
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
# 下载授权与单票导出同一谓词:创建者或管理员(可下载=可见)。
|
||||
task = get_task_visible_to_user(task_no, user_id, is_admin=is_admin)
|
||||
# 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。
|
||||
if not isinstance(task, ShippingNotice) or (
|
||||
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
|
||||
@@ -90,10 +95,17 @@ def build_export_archive(
|
||||
user_id: int,
|
||||
task_nos: list[str] | None = None,
|
||||
business_nos: list[str] | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> tuple[BinaryIO, str, dict]:
|
||||
"""
|
||||
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
|
||||
|
||||
Args:
|
||||
user_id: 当前下载用户;与 ``is_admin`` 共同构成下载授权谓词口径。
|
||||
task_nos: 按 SN 技术号选择(与 business_nos 二选一)。
|
||||
business_nos: 按发货通知单号选择(与 task_nos 二选一)。
|
||||
is_admin: 是否平台管理员;管理员可打包其可见的正式 Notice。
|
||||
|
||||
Returns:
|
||||
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
|
||||
"""
|
||||
@@ -105,6 +117,7 @@ def build_export_archive(
|
||||
user_id=user_id,
|
||||
task_refs=selection_values,
|
||||
selection_name=selection_name,
|
||||
is_admin=is_admin,
|
||||
require_business_no=business_nos is not None,
|
||||
)
|
||||
artifacts = _ready_artifacts(tasks)
|
||||
@@ -115,11 +128,16 @@ def build_export_archive(
|
||||
included = 0
|
||||
with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive:
|
||||
for task in tasks:
|
||||
# business_no 供端点按票写入访问审计(与单票下载同一 aggregate 口径)。
|
||||
entry_base = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': str(getattr(task, 'business_no', '') or ''),
|
||||
}
|
||||
task_artifacts = artifacts.get(int(task.id), []) if task.id is not None else []
|
||||
if not task_artifacts:
|
||||
entries.append({'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
|
||||
entries.append({**entry_base, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
|
||||
for artifact in task_artifacts:
|
||||
entry = {'task_no': task.task_no, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
|
||||
entry = {**entry_base, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
|
||||
entry['artifact_no'] = artifact.artifact_no
|
||||
path = Path(artifact.file_path)
|
||||
if not path.is_file():
|
||||
|
||||
@@ -716,6 +716,255 @@ def freeze_manual_line_source_selection(
|
||||
return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections)
|
||||
|
||||
|
||||
def active_candidate_set_is_manually_pinned(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
判断活动候选集是否含人工选源(「人工指定即定论」的统一判定入口)。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingOrderTask。
|
||||
session: 可选 Session。
|
||||
|
||||
Returns:
|
||||
bool: True 表示人工已裁决候选源,自动重路由必须跳过。
|
||||
"""
|
||||
sess = session or db.session
|
||||
active_set = (
|
||||
sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
|
||||
if getattr(task, 'active_inventory_candidate_set_id', None) is not None
|
||||
else None
|
||||
)
|
||||
if active_set is None:
|
||||
return False
|
||||
if getattr(active_set, 'frozen_by_id', None) is not None:
|
||||
return True
|
||||
return any(
|
||||
str(getattr(source, 'candidate_origin', '') or '').strip().lower() == 'manual_override'
|
||||
for source in (active_set.sources or [])
|
||||
)
|
||||
|
||||
|
||||
def refresh_candidates_from_current_routing(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
execution_id: int | None = None,
|
||||
session: Session | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
任务级:按当前库存源主数据与路由规则重跑裁决并重冻结候选集;返回是否产生新版本候选集。
|
||||
【AI 触发时机】:仅「重新获取库存(RPA)」的任务级人工重取路径作为前置步骤调用;
|
||||
禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。
|
||||
|
||||
核心逻辑:
|
||||
[守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单
|
||||
不得自动改源,换源走 override_line_inventory_source 行级覆写。
|
||||
[守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override')
|
||||
时跳过:人工指定即定论,禁止重路由洗掉人工裁决。
|
||||
[STEP 1] 记录当前活动 set_id。
|
||||
[STEP 2] adjudicate_and_apply_inventory_source(execution_id=...) 重裁决 + 幂等冻结
|
||||
(freeze 服务 input_fingerprint 未变则复用旧集,零副作用;重裁决为 unresolved 时
|
||||
apply 不落任何事实,活动集保持不变,同样视为无变化)。
|
||||
[STEP 3] 活动集变化时冻结服务已内置旧版本下游失效(_invalidate_task_candidate_outputs:
|
||||
匹配事实/准备 Attempt/RPA Attempt 等),此处仅补写任务事件供审计追溯。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingOrderTask(须已冻结候选集)。
|
||||
execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
|
||||
session: 可选 Session。
|
||||
|
||||
Returns:
|
||||
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
sess = session or db.session
|
||||
if len(task_frozen_inventory_source_codes(task)) <= 1:
|
||||
return False
|
||||
if active_candidate_set_is_manually_pinned(task, session=sess):
|
||||
return False
|
||||
before = get_active_candidate_set(task)
|
||||
before_set_id = int(before.id) if before is not None else None
|
||||
adjudicate_and_apply_inventory_source(task, execution_id=execution_id)
|
||||
sess.flush()
|
||||
after = get_active_candidate_set(task)
|
||||
after_set_id = int(after.id) if after is not None else None
|
||||
if before_set_id == after_set_id:
|
||||
return False
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
log_task_event(
|
||||
task,
|
||||
'inventory_candidates_refreshed',
|
||||
{
|
||||
'scope': 'task',
|
||||
'previous_set_id': before_set_id,
|
||||
'new_set_id': after_set_id,
|
||||
'source_codes': task_frozen_inventory_source_codes(task),
|
||||
},
|
||||
source='system',
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def refresh_line_candidates_from_current_routing(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
line_no: int,
|
||||
execution_id: int | None = None,
|
||||
session: Session | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。
|
||||
【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带
|
||||
line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。
|
||||
|
||||
核心逻辑:
|
||||
[守卫 1] 目标行当前候选 >1(未定源)才重评;单源行已定,改源走行级覆写。
|
||||
[守卫 2] 活动候选集含人工选源时跳过(与任务级刷新同一条红线:人工指定即定论)。
|
||||
[STEP 1] 行级规则重评:_task_routing_lines(task) 按 line_no-1 取目标行(越界返回 False),
|
||||
evaluate_inventory_source_rules(task=task, line=...) 得到规则原始候选,经
|
||||
get_database_inventory_source 过滤停用源(对齐 _result_to_adjudication 语义);
|
||||
仅接受 resolved/ambiguous 结论,unresolved 保持旧行为不刷新。
|
||||
[STEP 2] 以活动集全量行为骨架构建 line_projections:目标行替换为新候选,其余行原样继承
|
||||
(保留既有行候选,不做整单重路由)。
|
||||
[STEP 3] freeze_candidates_for_task(candidates_frozen 裁决)幂等冻结;created_new 即新版
|
||||
候选集(supersede 旧集时内置下游失效),写行级刷新任务事件并返回 True。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingOrderTask(须已冻结候选集)。
|
||||
line_no: 目标订单项次(1 基,对应冻结快照 line_no)。
|
||||
execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
|
||||
session: 可选 Session。
|
||||
|
||||
Returns:
|
||||
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
_task_routing_lines,
|
||||
compute_routing_fingerprint,
|
||||
evaluate_inventory_source_rules,
|
||||
extract_routing_context,
|
||||
)
|
||||
|
||||
sess = session or db.session
|
||||
active_set = get_active_candidate_set(task)
|
||||
if active_set is None:
|
||||
return False
|
||||
if active_candidate_set_is_manually_pinned(task, session=sess):
|
||||
return False
|
||||
existing_lines = {
|
||||
int(row.line_no): row
|
||||
for row in (active_set.lines or [])
|
||||
if getattr(row, 'line_no', None) is not None
|
||||
}
|
||||
target = existing_lines.get(int(line_no))
|
||||
if target is None:
|
||||
return False
|
||||
current_codes = [
|
||||
str(code).strip().upper()
|
||||
for code in (target.source_codes_json or [])
|
||||
if str(code or '').strip()
|
||||
]
|
||||
if len(current_codes) <= 1:
|
||||
return False
|
||||
|
||||
routing_lines = _task_routing_lines(task)
|
||||
position = int(line_no) - 1
|
||||
if position < 0 or position >= len(routing_lines):
|
||||
return False
|
||||
line_result = evaluate_inventory_source_rules(task=task, line=routing_lines[position])
|
||||
line_status = str(getattr(line_result, 'status', '') or '').strip().lower()
|
||||
if line_status not in {'resolved', 'ambiguous'}:
|
||||
return False
|
||||
new_codes: list[str] = []
|
||||
for raw in (getattr(line_result, 'source_codes', None) or []):
|
||||
code = str(raw or '').strip().upper()
|
||||
if code and code not in new_codes and get_database_inventory_source(code) is not None:
|
||||
new_codes.append(code)
|
||||
if not new_codes:
|
||||
return False
|
||||
|
||||
line_projections: list[dict[str, Any]] = []
|
||||
union_codes: list[str] = []
|
||||
for row_line_no in sorted(existing_lines):
|
||||
row = existing_lines[row_line_no]
|
||||
codes = (
|
||||
new_codes
|
||||
if row_line_no == int(line_no)
|
||||
else [
|
||||
str(code).strip().upper()
|
||||
for code in (row.source_codes_json or [])
|
||||
if str(code or '').strip()
|
||||
]
|
||||
)
|
||||
for code in codes:
|
||||
if code not in union_codes:
|
||||
union_codes.append(code)
|
||||
line_projections.append({
|
||||
'line_no': row_line_no,
|
||||
'source_line_no': str(getattr(row, 'source_line_no', '') or '') or None,
|
||||
'part_number': getattr(row, 'part_number', None),
|
||||
'reservation_id': getattr(row, 'reservation_id', None),
|
||||
'candidate_inventory_source_codes': codes,
|
||||
})
|
||||
if not union_codes:
|
||||
return False
|
||||
|
||||
context = extract_routing_context(task)
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status='candidates_frozen',
|
||||
method='line_refresh_reroute',
|
||||
source_code=None,
|
||||
connector_type=None,
|
||||
warehouse_id=None,
|
||||
config_version=inventory_sources_runtime_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[{'source_code': code} for code in union_codes],
|
||||
evidence=[{
|
||||
'line_candidates_refresh': {
|
||||
'line_no': int(line_no),
|
||||
'previous_codes': current_codes,
|
||||
'new_codes': new_codes,
|
||||
},
|
||||
}],
|
||||
reason='line_refresh_reroute',
|
||||
)
|
||||
freeze_result = freeze_candidates_for_task(
|
||||
task,
|
||||
adjudication=adjudication,
|
||||
line_projections=line_projections,
|
||||
execution_id=execution_id,
|
||||
session=sess,
|
||||
)
|
||||
if not freeze_result.created_new:
|
||||
return False
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
log_task_event(
|
||||
task,
|
||||
'inventory_candidates_refreshed',
|
||||
{
|
||||
'scope': 'line',
|
||||
'line_no': int(line_no),
|
||||
'previous_codes': current_codes,
|
||||
'new_codes': new_codes,
|
||||
'new_set_id': int(freeze_result.candidate_set_id),
|
||||
},
|
||||
source='system',
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def freeze_wave_notice_routing(
|
||||
notice: ShippingNotice,
|
||||
*,
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
@@ -82,8 +83,35 @@ def _candidate_set_filter(
|
||||
return list(rows)
|
||||
|
||||
|
||||
def resolve_inventory_fact_task(task: Any) -> Any:
|
||||
"""
|
||||
将库存事实读取对象归一为正式 OT。
|
||||
|
||||
核心逻辑:候选集/库存 Link 全部挂在 OT 上,而货代上传等入口按 business_no
|
||||
加载 ShippingNotice——Notice 没有 active_inventory_candidate_set_id 字段,
|
||||
直接查询会 fail-closed 成「库存源尚未确定」(历史缺陷:RPA 上传被恒拦截,
|
||||
自动推进的 freight_upload_rpa 门禁也因此秒切人工)。OT 原样返回;Notice 沿
|
||||
order_task_id 解析,缺绑定或 OT 不存在时原样返回,由上层无候选集语义继续
|
||||
fail-closed。
|
||||
|
||||
Args:
|
||||
task: ShippingOrderTask 或 ShippingNotice。
|
||||
|
||||
Returns:
|
||||
归一后的 OT(或无法解析时的原对象)。
|
||||
"""
|
||||
if isinstance(task, ShippingNotice):
|
||||
order_task_id = getattr(task, 'order_task_id', None)
|
||||
if order_task_id is None:
|
||||
return task
|
||||
order_task = _session().get(ShippingOrderTask, int(order_task_id))
|
||||
if order_task is not None:
|
||||
return order_task
|
||||
return task
|
||||
|
||||
|
||||
def get_active_candidate_set(
|
||||
task: ShippingOrderTask,
|
||||
task: ShippingOrderTask | ShippingNotice,
|
||||
*,
|
||||
session: Session | None = None,
|
||||
) -> ShippingInventoryCandidateSet | None:
|
||||
@@ -92,7 +120,9 @@ def get_active_candidate_set(
|
||||
|
||||
核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id;
|
||||
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
|
||||
传入 ShippingNotice 时先归一为其 order_task(见 resolve_inventory_fact_task)。
|
||||
"""
|
||||
task = resolve_inventory_fact_task(task)
|
||||
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
|
||||
if candidate_set_id is None:
|
||||
return None
|
||||
|
||||
@@ -277,9 +277,14 @@ def assert_inventory_source_gate(
|
||||
|
||||
|
||||
def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
|
||||
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。"""
|
||||
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。
|
||||
|
||||
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
task = resolve_inventory_fact_task(task)
|
||||
source_codes = task_frozen_inventory_source_codes(task)
|
||||
source_code = source_codes[0] if len(source_codes) == 1 else None
|
||||
source = get_database_inventory_source(source_code) if source_code else None
|
||||
@@ -294,13 +299,19 @@ def resolve_inventory_source_warehouse_id(
|
||||
*,
|
||||
source: dict[str, Any] | None,
|
||||
) -> str | None:
|
||||
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。"""
|
||||
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。
|
||||
|
||||
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
|
||||
"""
|
||||
if not source:
|
||||
return None
|
||||
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
|
||||
if mode == 'fixed':
|
||||
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
|
||||
|
||||
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
|
||||
|
||||
task = resolve_inventory_fact_task(task)
|
||||
task_id = getattr(task, 'id', None)
|
||||
source_code = str(source.get('source_code') or '').strip().upper()
|
||||
if not task_id or not source_code:
|
||||
|
||||
@@ -5,6 +5,9 @@ services/shipping_notice/line_inventory_match_persistence.py
|
||||
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
|
||||
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
|
||||
新快照新增行并切换 is_current;不覆盖历史快照事实。
|
||||
行级 inventory_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」;
|
||||
仅行结果未回填文件号(如 not_found)时才回退任务级锚点快照——多源池下锚点文件
|
||||
≠命中文件,混用会导致 Excel 仓库列写成锚点仓(历史缺陷:AWSCV 单写成 CMH01)。
|
||||
匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列,
|
||||
供后续投影层与自动放行服务读取。
|
||||
"""
|
||||
@@ -111,12 +114,14 @@ def persist_line_inventory_match_facts(
|
||||
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
|
||||
|
||||
snap_id = active_inventory_runtime_facts(task).get('inventory_file_id')
|
||||
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
|
||||
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
|
||||
# 任务级锚点快照仅作行结果缺文件号时的回退身份;命中文件归因在行循环内逐行解析。
|
||||
snapshot_file_no = None
|
||||
if snap_id is not None:
|
||||
snapshot = ShippingInventoryFile.query.get(int(snap_id))
|
||||
snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None
|
||||
# 命中文件号 → 文件 ID 缓存;文件号查不到文件时缓存 None,本行回退锚点快照
|
||||
# (命中证据仍以 matched_file_no 为准,不把锚点伪装成命中文件)。
|
||||
file_id_by_no: dict[str, int | None] = {}
|
||||
|
||||
line_results = [
|
||||
item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict)
|
||||
@@ -156,6 +161,23 @@ def persist_line_inventory_match_facts(
|
||||
continue
|
||||
snapshot_line_id = int(snapshot_line.id)
|
||||
|
||||
# [STEP] 行级文件归因:匹配结果自带 inventory_file_no 时解析命中文件 ID;
|
||||
# 未回填(如 not_found)或文件号无法解析时回退任务级锚点快照。
|
||||
# 禁止把锚点文件身份盖到命中了其他源文件的行上(历史缺陷根因)。
|
||||
line_file_no = str(result.get('inventory_file_no') or '').strip() or None
|
||||
line_snap_id = snap_id
|
||||
if line_file_no is not None:
|
||||
if line_file_no not in file_id_by_no:
|
||||
hit_file = (
|
||||
ShippingInventoryFile.query
|
||||
.filter_by(inventory_file_no=line_file_no)
|
||||
.first()
|
||||
)
|
||||
file_id_by_no[line_file_no] = int(hit_file.id) if hit_file is not None else None
|
||||
resolved_file_id = file_id_by_no[line_file_no]
|
||||
if resolved_file_id is not None:
|
||||
line_snap_id = resolved_file_id
|
||||
|
||||
match_result, inventory_status = map_disposition_to_match_codes(
|
||||
disposition=str(result.get('disposition') or res.get('disposition') or ''),
|
||||
part_number=result.get('part_number') or res.get('part_number'),
|
||||
@@ -172,8 +194,8 @@ def persist_line_inventory_match_facts(
|
||||
else []
|
||||
)
|
||||
|
||||
# [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0)
|
||||
if snap_id is None and (
|
||||
# [STEP] BE-5:本行无任何库存文件身份时禁止 ready/not_found(不得规范为 0)
|
||||
if line_snap_id is None and (
|
||||
inventory_status == 'ready'
|
||||
or match_result in {'matched', 'not_found'}
|
||||
):
|
||||
@@ -195,20 +217,20 @@ def persist_line_inventory_match_facts(
|
||||
)
|
||||
unit_value = str(unit_raw or '').strip()[:32] or None
|
||||
|
||||
# [STEP] 同 OT+行+快照:更新;否则新建并撤销旧 current
|
||||
# [STEP] 同 OT+行+命中文件:更新;否则新建并撤销旧 current
|
||||
existing = None
|
||||
if snap_id is not None:
|
||||
if line_snap_id is not None:
|
||||
existing = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(
|
||||
task_id=int(task.id),
|
||||
snapshot_line_id=snapshot_line_id,
|
||||
line_no=line_no,
|
||||
inventory_snapshot_id=int(snap_id),
|
||||
inventory_snapshot_id=int(line_snap_id),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is None and snap_id is None:
|
||||
if existing is None and line_snap_id is None:
|
||||
existing = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
|
||||
@@ -253,7 +275,7 @@ def persist_line_inventory_match_facts(
|
||||
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
|
||||
'inventory_file_no': file_no,
|
||||
'inventory_row_ref': result.get('inventory_row_ref'),
|
||||
'snapshot_missing': snap_id is None,
|
||||
'snapshot_missing': line_snap_id is None,
|
||||
'evidence_ref_plain': evidence_plain if evidence_ref else None,
|
||||
}
|
||||
row = ShippingNoticeLineInventoryMatch(
|
||||
@@ -273,7 +295,7 @@ def persist_line_inventory_match_facts(
|
||||
else None
|
||||
),
|
||||
candidate_line_id=int(candidate_line.id) if candidate_line is not None else None,
|
||||
inventory_snapshot_id=int(snap_id) if snap_id is not None else None,
|
||||
inventory_snapshot_id=int(line_snap_id) if line_snap_id is not None else None,
|
||||
match_result=match_result,
|
||||
inventory_status=inventory_status,
|
||||
required_qty=str(required) if required is not None else None,
|
||||
@@ -304,7 +326,7 @@ def persist_line_inventory_match_facts(
|
||||
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
|
||||
'allowed_source_codes_snapshot': list(allowed_source_codes),
|
||||
'inventory_file_no': file_no,
|
||||
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
|
||||
'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None,
|
||||
'inventory_row_ref': result.get('inventory_row_ref'),
|
||||
'match_result': match_result,
|
||||
}).encode('utf-8')
|
||||
@@ -342,7 +364,7 @@ def persist_line_inventory_match_facts(
|
||||
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
|
||||
'inventory_file_no': file_no,
|
||||
'inventory_row_ref': result.get('inventory_row_ref'),
|
||||
'snapshot_missing': snap_id is None,
|
||||
'snapshot_missing': line_snap_id is None,
|
||||
'evidence_ref_plain': evidence_plain if evidence_ref else None,
|
||||
}
|
||||
existing.match_result = match_result
|
||||
@@ -385,7 +407,7 @@ def persist_line_inventory_match_facts(
|
||||
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
|
||||
'allowed_source_codes_snapshot': list(allowed_source_codes),
|
||||
'inventory_file_no': file_no,
|
||||
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
|
||||
'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None,
|
||||
'inventory_row_ref': result.get('inventory_row_ref'),
|
||||
'match_result': match_result,
|
||||
}).encode('utf-8')
|
||||
|
||||
@@ -938,6 +938,42 @@ def _handle_retry_inventory_preparation(
|
||||
freeze_mode='manual',
|
||||
)
|
||||
db.session.flush()
|
||||
# [STEP 0B] 人工重取前的候选源刷新(幂等):任务级 retry_inventory_preparation 先按当前
|
||||
# 主数据/路由规则整单重判候选集;行级重抓(line_scope 非空)仅重评目标行候选。
|
||||
# 两者均无变化零副作用;有变化则新版候选集随 supersede 自带旧事实失效,再走下方
|
||||
# 既有失效与重取链——补源场景由此闭环:管理端启用新源后点「重新获取库存(RPA)」
|
||||
# 即可让新源进入取数与匹配范围,无需重建订单。
|
||||
# 轮询/自动首投(外层条件已排除)与 Excel 已生成(源锁定,D7 边界)不刷新;
|
||||
# 已定源(任务级整单/行级目标行候选 ≤1)与人工钉源不刷新(helper 内守卫,改源走
|
||||
# override_line_inventory_source)。
|
||||
# 行键失效(line_scope_key/snapshot_line_id 解析不到行)时 _resolve_line_inventory_scope
|
||||
# 返回 None,按既有降级语义走任务级刷新(升级前行为一致)。
|
||||
if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation':
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
|
||||
if latest_export_artifact(task) is None:
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import (
|
||||
refresh_candidates_from_current_routing,
|
||||
refresh_line_candidates_from_current_routing,
|
||||
)
|
||||
|
||||
if line_scope is None:
|
||||
refresh_candidates_from_current_routing(task, execution_id=int(execution.id))
|
||||
elif refresh_line_candidates_from_current_routing(
|
||||
task, line_no=int(line_scope['line_no']), execution_id=int(execution.id),
|
||||
):
|
||||
# 刷新产生新候选集后旧 scope 已过期:按同参重解析行作用域,让本次失效与
|
||||
# RPA 取数直接使用新冻结码;重解析为 None(如行键已失效)则保守沿用旧值。
|
||||
refreshed_scope = _resolve_line_inventory_scope(
|
||||
task,
|
||||
line_scope_key=(
|
||||
payload.get('line_scope_key')
|
||||
if payload.get('line_scope_key') is not None
|
||||
else payload.get('snapshot_line_id')
|
||||
),
|
||||
)
|
||||
if refreshed_scope is not None:
|
||||
line_scope = refreshed_scope
|
||||
if payload.get('action_code') in {
|
||||
'retry_inventory_preparation',
|
||||
'retry_inventory_from_preparation',
|
||||
|
||||
@@ -1564,13 +1564,22 @@ def _enrich_task_center_fields(
|
||||
data["created_by"] = task.user_id
|
||||
if viewer_user_id is not None:
|
||||
data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin)
|
||||
# 下载能力与导出端点同一谓词;SUMMARY/DETAIL 均下发,供抽屉/批量勾选消费。
|
||||
data["can_download_export"] = can_download_task_export(
|
||||
task, user_id=int(viewer_user_id), is_admin=is_admin,
|
||||
)
|
||||
data["recent_event"] = _latest_task_event_summary(task)
|
||||
data["artifact_summary"] = _artifact_summary_for_task(task)
|
||||
data['notice_line_summary'] = _notice_line_summary_for_task(task)
|
||||
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
ui_state = build_task_ui_state(task, include_stage_context=include_stage_context)
|
||||
ui_state = build_task_ui_state(
|
||||
task,
|
||||
include_stage_context=include_stage_context,
|
||||
viewer_user_id=viewer_user_id,
|
||||
viewer_is_admin=is_admin,
|
||||
)
|
||||
data["ui_state"] = ui_state
|
||||
# [PERF] 优先复用 ui_state.process_gate(build_task_ui_state 已查 Execution);
|
||||
# 无 Gate 时回退 position/user_mode,避免再跑一次 resolve_task_ui_state。
|
||||
@@ -1730,12 +1739,15 @@ def list_tasks_page_for_user(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
lifecycle_status: str | None = None,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出当前用户可见的发货任务摘要。
|
||||
|
||||
工作台任务量增长后必须由数据库分页,不能先拉取固定上限再在浏览器切页;
|
||||
`items` 仅表示当前页,`total` 用于计算稳定的页码与空页回退。
|
||||
``is_admin`` 只影响 SUMMARY 的能力字段(can_handle / can_download_export),
|
||||
不扩大列表可见范围(仍为本人 + 无主 Notice)。
|
||||
"""
|
||||
normalized_page = max(1, int(page))
|
||||
normalized_page_size = max(1, min(int(page_size), 100))
|
||||
@@ -1795,7 +1807,7 @@ def list_tasks_page_for_user(
|
||||
rows = [row for row in rows if row is not None]
|
||||
return {
|
||||
"items": [
|
||||
serialize_task_summary(item, viewer_user_id=user_id)
|
||||
serialize_task_summary(item, viewer_user_id=user_id, is_admin=is_admin)
|
||||
for item in rows
|
||||
],
|
||||
"page": normalized_page,
|
||||
@@ -1849,6 +1861,35 @@ def get_task_visible_to_user(
|
||||
return task
|
||||
|
||||
|
||||
def can_download_task_export(
|
||||
task: ShippingOrderTask | ShippingNotice | None,
|
||||
*,
|
||||
user_id: int,
|
||||
is_admin: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
导出下载的唯一授权谓词:创建者或平台管理员(与导出端点同一口径)。
|
||||
|
||||
核心逻辑:单票/批量 Excel 下载端点与 UI 的 download_excel 动作、
|
||||
can_download_export 字段都必须消费本谓词,禁止各处另行推导归属;
|
||||
管理员放开下载(可下载=可见)后,每次下载仍须写入 record_access_audit。
|
||||
无主任务(user_id IS NULL)仅管理员可下载。
|
||||
|
||||
Args:
|
||||
task: 已加载的任务实体(可为 None)。
|
||||
user_id: 当前查看/下载用户。
|
||||
is_admin: 是否平台管理员。
|
||||
|
||||
Returns:
|
||||
当前用户是否允许下载该任务的正式 Excel。
|
||||
"""
|
||||
if task is None:
|
||||
return False
|
||||
if is_admin:
|
||||
return True
|
||||
return task.user_id is not None and int(task.user_id) == int(user_id)
|
||||
|
||||
|
||||
def list_freight_notice_groups_for_task(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
|
||||
@@ -61,7 +61,11 @@ from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGES,
|
||||
project_lifecycle,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary
|
||||
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,
|
||||
)
|
||||
@@ -1162,6 +1166,8 @@ 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。
|
||||
@@ -1170,6 +1176,14 @@ def build_task_ui_state(
|
||||
禁止 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,
|
||||
@@ -1210,7 +1224,12 @@ def build_task_ui_state(
|
||||
# [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作,
|
||||
# 两者不能相互覆盖。即使当前 Gate 阻断并清空旧动作,也只在
|
||||
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
|
||||
if resolve_task_export_download(task) is not None:
|
||||
# 下载动作与导出端点消费同一谓词: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',
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
tests/test_inventory_source_gate_notice_task.py
|
||||
|
||||
用途:锁定「库存源稳定门禁 / 库存身份对 ShippingNotice 的归一」契约。
|
||||
依赖:pytest、inventory_source_gate、inventory_candidate_projection、app 夹具(内存测试库)。
|
||||
逻辑:货代上传入口按 business_no 加载 Notice,而候选集事实挂在 OT 上;门禁必须沿
|
||||
order_task_id 归一读取。历史缺陷:Notice 缺 active_inventory_candidate_set_id
|
||||
字段导致 is_inventory_source_stable(Notice) 恒 False,RPA 上传被
|
||||
「库存源尚未确定」静默拦截(无事件、无 attempt 记录)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _make_frozen_task_with_notice(task_no: str):
|
||||
"""构造带冻结候选集(单源 CRANE)的 OT 及其已绑定 Notice。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
|
||||
task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=1,
|
||||
lifecycle_status='frozen',
|
||||
input_fingerprint=f'fp-{task_no}',
|
||||
routing_rule_version_json={},
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
source_code='CRANE',
|
||||
candidate_order=1,
|
||||
candidate_origin='rule',
|
||||
))
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
line_no=1,
|
||||
part_number='PN-1',
|
||||
reservation_id='3000092917',
|
||||
source_codes_json=['CRANE'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = int(candidate_set.id)
|
||||
db.session.flush()
|
||||
|
||||
notice = ShippingNotice(
|
||||
task_no=f'SN-{task_no}',
|
||||
order_task_id=int(task.id),
|
||||
business_no=f'USZ{task_no[-6:]}',
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
return task, notice
|
||||
|
||||
|
||||
def _patch_source_lookup(monkeypatch):
|
||||
"""注入启用的 CRANE 源配置(inventory_match 动态仓),免建 RPA Profile。"""
|
||||
from app.services.shipping_notice import inventory_source_gate as gate_mod
|
||||
|
||||
def _source(code):
|
||||
if str(code).upper() != 'CRANE':
|
||||
return None
|
||||
return {
|
||||
'source_code': 'CRANE',
|
||||
'display_name': 'Crane FootPrint',
|
||||
'connector_type': 'crane',
|
||||
'warehouse_resolution_mode': 'inventory_match',
|
||||
'fixed_warehouse_id': None,
|
||||
'enabled': True,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source)
|
||||
|
||||
|
||||
def test_inventory_source_stable_resolves_notice_to_order_task(app, monkeypatch):
|
||||
"""门禁对 Notice 必须沿 order_task_id 读取冻结候选集,判定与 OT 一致。"""
|
||||
_patch_source_lookup(monkeypatch)
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
task_inventory_identity,
|
||||
)
|
||||
|
||||
task, notice = _make_frozen_task_with_notice('OT-NOTICE-GATE-OK')
|
||||
# 断言意图:OT 与其 Notice 的稳定性判定一致(历史缺陷:Notice 恒 False)
|
||||
assert is_inventory_source_stable(task) is True
|
||||
assert is_inventory_source_stable(notice) is True
|
||||
# 断言意图:库存身份(RPA 网点/仓库)对两者一致,且能解析到源
|
||||
identity_ot = task_inventory_identity(task)
|
||||
identity_notice = task_inventory_identity(notice)
|
||||
assert identity_ot == identity_notice
|
||||
assert identity_notice['inventory_source_code'] == 'CRANE'
|
||||
|
||||
|
||||
def test_inventory_source_stable_fail_closed_without_order_task(app, monkeypatch):
|
||||
"""Notice 缺 OT 绑定时保持 fail-closed(不得误判稳定)。"""
|
||||
_patch_source_lookup(monkeypatch)
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
|
||||
orphan = ShippingNotice(
|
||||
task_no='SN-ORPHAN-NOTICE',
|
||||
business_no='USZORPH01',
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(orphan)
|
||||
db.session.flush()
|
||||
# 断言意图:无法归一到 OT 的 Notice 保持 fail-closed
|
||||
assert is_inventory_source_stable(orphan) is False
|
||||
@@ -187,3 +187,91 @@ def test_persist_updates_part_available_qty_on_existing_row(app):
|
||||
assert rows[0].part_available_qty is None
|
||||
# 断言意图:同快照幂等更新,始终只有一条 current 事实
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 行级文件归因契约(多源池:锚点文件 ≠ 命中文件)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_inventory_file(app, file_no: str, warehouse_id: str) -> int:
|
||||
"""构造最小可用库存快照文件,返回主键。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
|
||||
file_row = ShippingInventoryFile(
|
||||
inventory_file_no=file_no,
|
||||
storage_path=f'/tmp/{file_no}.xlsx',
|
||||
source_code='DSV360_TEST',
|
||||
warehouse_id=warehouse_id,
|
||||
warehouse_code=warehouse_id,
|
||||
snapshot_status='ready',
|
||||
line_count=1,
|
||||
share_mode='warehouse_pool',
|
||||
)
|
||||
db.session.add(file_row)
|
||||
db.session.flush()
|
||||
return int(file_row.id)
|
||||
|
||||
|
||||
def _ok_result(*, line_index: int = 0, inventory_file_no: str | None = None) -> dict:
|
||||
"""构造命中库存的行结果桩;inventory_file_no 模拟匹配器回填的命中文件身份。"""
|
||||
result = {
|
||||
'line_index': line_index,
|
||||
'disposition': 'ok',
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '3000092917',
|
||||
'required_qty': 8.0,
|
||||
'available_qty': 8.0,
|
||||
}
|
||||
if inventory_file_no is not None:
|
||||
result['inventory_file_no'] = inventory_file_no
|
||||
return result
|
||||
|
||||
|
||||
def test_persist_attributes_line_to_hit_file_not_anchor(app):
|
||||
"""多源池下行命中 B 文件时,inventory_snapshot_id 必须归因 B,而非任务锚点 A。
|
||||
|
||||
历史缺陷:持久化把任务级锚点文件 ID 盖到所有行,Excel 仓库列因此写成
|
||||
锚点仓(AWSCV 单写成 CMH01)。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
|
||||
task = _make_snapshot_task('OT-LINE-FILE-ATTR')
|
||||
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR', 'BYAWSCMH01')
|
||||
hit_id = _make_inventory_file(app, 'SIF-TEST-HIT', 'AWSCV')
|
||||
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_ok_result(inventory_file_no='SIF-TEST-HIT')],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=anchor_id,
|
||||
)
|
||||
# 断言意图:行事实挂到命中文件,而不是任务级锚点文件
|
||||
assert rows[0].inventory_snapshot_id == hit_id
|
||||
assert rows[0].matched_file_no == 'SIF-TEST-HIT'
|
||||
# 断言意图:仓库身份可由命中文件直接推出(Excel 仓库列数据源)
|
||||
hit_file = db.session.get(ShippingInventoryFile, rows[0].inventory_snapshot_id)
|
||||
assert hit_file.warehouse_id == 'AWSCV'
|
||||
|
||||
|
||||
def test_persist_falls_back_to_anchor_without_line_file_no(app):
|
||||
"""行结果未回填文件号(如 not_found)时,保持任务级锚点回退,行为不变。"""
|
||||
with app.app_context():
|
||||
task = _make_snapshot_task('OT-LINE-FILE-FALLBACK')
|
||||
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR-FB', 'BYAWSCMH01')
|
||||
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=None)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=anchor_id,
|
||||
)
|
||||
# 断言意图:无命中文件身份的行回退锚点快照(历史行为兼容)
|
||||
assert rows[0].inventory_snapshot_id == anchor_id
|
||||
@@ -31,6 +31,12 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact(Excel 源锁定判断,查库)依赖;
|
||||
# 纯单测无 Flask/DB,打桩为「Excel 已生成」使刷新块短路,保持本用例聚焦行级收窄断言。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: SimpleNamespace(id=77),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_export_archive.py
|
||||
|
||||
用途:shipping_notice 批量导出归档(build_export_archive)下载授权单测。
|
||||
依赖:pytest、ShippingNotice、export_archive.build_export_archive。
|
||||
逻辑:批量选择与单票导出消费同一谓词口径(创建者或管理员);无 Artifact 时
|
||||
保留 manifest missing 语义,并按票携带 business_no 供端点写访问审计。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import ShippingNotice
|
||||
|
||||
|
||||
def test_build_export_archive_selects_by_creator_or_admin(app):
|
||||
"""批量归档与单票下载同一谓词:陌生用户整体拒绝,创建者/管理员放行。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
|
||||
owned = ShippingNotice(
|
||||
task_no="SN-ARC-OWNED", business_no="QMN-ARC-1", user_id=7, source_type="manual",
|
||||
)
|
||||
db.session.add(owned)
|
||||
db.session.commit()
|
||||
|
||||
# 非创建者普通用户:任一越权即整体拒绝(防部分成功)。
|
||||
with pytest.raises(NotFoundError):
|
||||
build_export_archive(user_id=8, business_nos=["QMN-ARC-1"])
|
||||
|
||||
# 创建者放行;无 Artifact 时保留 missing_artifact 语义并携带 business_no。
|
||||
_stream, _name, manifest = build_export_archive(user_id=7, business_nos=["QMN-ARC-1"])
|
||||
assert manifest["entries"][0]["status"] == "missing_artifact"
|
||||
assert manifest["entries"][0]["business_no"] == "QMN-ARC-1"
|
||||
|
||||
# 管理员可下载=可见:他人正式 Notice 放行(端点按票补访问审计)。
|
||||
_stream, _name, admin_manifest = build_export_archive(
|
||||
user_id=8, business_nos=["QMN-ARC-1"], is_admin=True,
|
||||
)
|
||||
assert admin_manifest["entries"][0]["task_no"] == "SN-ARC-OWNED"
|
||||
@@ -321,6 +321,28 @@ def test_get_task_for_user_rejects_null_owner(app):
|
||||
assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None
|
||||
|
||||
|
||||
def test_can_download_task_export_creator_or_admin(app):
|
||||
"""导出统一谓词:创建者/管理员可下载;非创建者普通用户与无主单一律拒绝。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import can_download_task_export
|
||||
|
||||
owned = ShippingNotice(task_no="SN-DL-OWNED", business_no="QMN-DL-1", user_id=7, source_type="manual")
|
||||
orphan = ShippingNotice(task_no="SN-DL-ORPHAN", business_no="QMN-DL-2", user_id=None, source_type="manual")
|
||||
db.session.add_all([owned, orphan])
|
||||
db.session.commit()
|
||||
|
||||
# 创建者可下载;同票对非创建者普通用户拒绝。
|
||||
assert can_download_task_export(owned, user_id=7) is True
|
||||
assert can_download_task_export(owned, user_id=8) is False
|
||||
# 管理员可下载=可见:他人票与无主票均放行(下载留痕审计兜底)。
|
||||
assert can_download_task_export(owned, user_id=8, is_admin=True) is True
|
||||
assert can_download_task_export(orphan, user_id=7) is False
|
||||
assert can_download_task_export(orphan, user_id=7, is_admin=True) is True
|
||||
# 缺实体一律拒绝。
|
||||
assert can_download_task_export(None, user_id=7, is_admin=True) is False
|
||||
|
||||
|
||||
def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
"""SUMMARY enrich 含 todo_category / created_by / can_handle / ui_state。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -465,6 +465,39 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa
|
||||
assert "download_excel" in button_ids
|
||||
|
||||
|
||||
def test_task_ui_state_gates_download_by_viewer(app, monkeypatch) -> None:
|
||||
"""下载动作与导出端点同一谓词:创建者/管理员下发,非创建者不下发;viewer 缺省维持聊天旧口径。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-VIEWER-EXPORT",
|
||||
source_type="manual",
|
||||
user_id=7,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
lambda _task: (object(), 'shipping-export.xlsx'),
|
||||
)
|
||||
|
||||
def button_ids(state):
|
||||
return [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
|
||||
# 创建者与管理员可见下载动作(管理员可下载=可见,消除"看得到点不动")。
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=7))
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=8, viewer_is_admin=True))
|
||||
# 非创建者普通用户不得收到下载动作(端点仍会拒绝,UI 不再误导)。
|
||||
assert "download_excel" not in button_ids(build_task_ui_state(task, viewer_user_id=8))
|
||||
# viewer 缺省 = 聊天链路(会话与创建者同源),维持仅 Artifact 授权的旧口径。
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task))
|
||||
|
||||
|
||||
def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None:
|
||||
"""当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1651,6 +1651,12 @@ def test_inventory_preparation_mode_maps_by_action_code(monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact + 候选源刷新前置(查库)依赖;
|
||||
# 本用例聚焦动作码→mode 映射,打桩为「Excel 已生成」使刷新块短路,隔离刷新链副作用。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: SimpleNamespace(id=77),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
"""
|
||||
tests/test_shipping_refresh_inventory_candidates.py
|
||||
|
||||
用途:人工重取前的候选集刷新守卫与幂等语义——任务级整单重路由、行级单行重评,
|
||||
未定源才刷新;人工钉源/已定源/无变化场景一律跳过或零副作用。
|
||||
依赖:inventory_candidate_freeze_service(被测 helper)、inventory_source_gate 与
|
||||
inventory_source_rules(重裁决/重评入口,测试中 monkeypatch 隔离)、
|
||||
process_gate_executor(Task 2 的挂载点集成测试)。
|
||||
逻辑:任务级守卫(多候选、非人工钉源)+ 幂等判定(活动 set_id 变化);行级守卫
|
||||
(目标行多候选、非人工钉源)+ 行级规则重评 + 定向行替换冻结;执行器仅在
|
||||
人工 retry(任务级/行级)且非 Excel 锁定时调用对应 helper。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _task(set_id=10):
|
||||
"""构造最小 OT 形状:仅 helper/执行器读取的字段。"""
|
||||
return SimpleNamespace(
|
||||
id=19, task_no='SN-REFRESH',
|
||||
order_snapshot_id=3,
|
||||
active_inventory_candidate_set_id=set_id,
|
||||
step_payload_json={},
|
||||
)
|
||||
|
||||
|
||||
def _active_set(line_defs):
|
||||
"""构造最小活动候选集:lines 为 (line_no, codes) 列表。"""
|
||||
return SimpleNamespace(
|
||||
id=10, frozen_by_id=None, sources=[],
|
||||
lines=[
|
||||
SimpleNamespace(
|
||||
line_no=line_no, source_codes_json=list(codes),
|
||||
source_line_no=str(line_no), part_number=f'PN{line_no}', reservation_id=f'R{line_no}',
|
||||
)
|
||||
for line_no, codes in line_defs
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _patch_routing_common(monkeypatch, *, fingerprint='fp-test', config_version='cfg-test'):
|
||||
"""隔离路由上下文与配置版本(避免测试依赖真实库表与指纹算法)。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.extract_routing_context',
|
||||
lambda _task: {'customer': 'X'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.compute_routing_fingerprint',
|
||||
lambda _ctx: fingerprint,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.inventory_sources_runtime_version',
|
||||
lambda: config_version,
|
||||
)
|
||||
|
||||
|
||||
# ---------- 任务级刷新 ----------
|
||||
|
||||
def test_refresh_skips_when_single_source_resolved(app, monkeypatch):
|
||||
"""[断言] 守卫:源已定(冻结候选 ≤1)不重路由——换源只能走行级覆写,禁止自动改源。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU'],
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_refresh_skips_when_manual_selection_exists(app, monkeypatch):
|
||||
"""[断言] 守卫:人工选源即定论,重取不得洗掉人工裁决。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_refresh_returns_true_and_logs_event_when_set_changes(app, monkeypatch):
|
||||
"""[断言] 重裁决产生新版本:返回 True 并写 inventory_candidates_refreshed 任务事件(scope=task)。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task(set_id=10)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
|
||||
)
|
||||
|
||||
def _fake_readjudicate(_task, **_k):
|
||||
task.active_inventory_candidate_set_id = 11
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
_fake_readjudicate,
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task, execution_id=5) is True
|
||||
assert events and events[0][0] == 'inventory_candidates_refreshed'
|
||||
assert events[0][1]['scope'] == 'task'
|
||||
assert events[0][1]['previous_set_id'] == 10
|
||||
assert events[0][1]['new_set_id'] == 11
|
||||
|
||||
|
||||
def test_refresh_is_noop_when_routing_result_identical(app, monkeypatch):
|
||||
"""[断言] 幂等:重裁决输入指纹未变(复用旧集,set_id 不变)时返回 False,不写事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task(set_id=10)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: None,
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not events
|
||||
|
||||
|
||||
# ---------- 行级刷新 ----------
|
||||
|
||||
def test_line_refresh_skips_when_target_line_single_source(app, monkeypatch):
|
||||
"""[断言] 守卫:目标行候选 ≤1(已定源)不重评——改源走行级覆写。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSDU'])]),
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_manual_selection_exists(app, monkeypatch):
|
||||
"""[断言] 守卫:候选集含人工选源即定论,行级重取不得洗掉人工裁决。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_routing_unresolved(app, monkeypatch):
|
||||
"""[断言] 行级规则重评为 unresolved(或候选全部停用)时保持旧行为,不冻结不刷新。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='unresolved', source_codes=()),
|
||||
)
|
||||
freeze_called = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda *_a, **_k: freeze_called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not freeze_called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_routed_sources_all_disabled(app, monkeypatch):
|
||||
"""[断言] 规则原始候选未过滤启停(InventoryRoutingResult 契约):候选全部停用时不得入集,保持旧行为。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='resolved', source_codes=('DSV360_AWSDU',)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: None,
|
||||
)
|
||||
freeze_called = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda *_a, **_k: freeze_called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not freeze_called
|
||||
|
||||
|
||||
def test_line_refresh_freezes_new_version_when_routing_changes(app, monkeypatch):
|
||||
"""[断言] 行级重评产生新候选:目标行替换、其余行继承,新版本冻结返回 True 并写行级刷新事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([
|
||||
(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01']),
|
||||
(2, ['DSV360_AWSCV']),
|
||||
]),
|
||||
)
|
||||
_patch_routing_common(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}, {'part_number': 'PN2'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSDU', 'DSV360_AWSCV')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: {'source_code': code},
|
||||
)
|
||||
freeze_kwargs = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda _task, **_k: freeze_kwargs.append(dict(_k)) or SimpleNamespace(created_new=True, candidate_set_id=12),
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1, execution_id=5) is True
|
||||
projections = freeze_kwargs[0]['line_projections']
|
||||
assert projections[0]['line_no'] == 1
|
||||
assert projections[0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
assert projections[1]['line_no'] == 2
|
||||
assert projections[1]['candidate_inventory_source_codes'] == ['DSV360_AWSCV']
|
||||
assert events and events[0][0] == 'inventory_candidates_refreshed'
|
||||
assert events[0][1]['scope'] == 'line'
|
||||
assert events[0][1]['line_no'] == 1
|
||||
assert events[0][1]['new_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
|
||||
|
||||
def test_line_refresh_is_noop_when_fingerprint_identical(app, monkeypatch):
|
||||
"""[断言] 幂等:行级重评结论与现状一致(冻结复用旧集 created_new=False)时返回 False,不写事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
_patch_routing_common(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: {'source_code': code},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda _task, **_k: SimpleNamespace(created_new=False, candidate_set_id=10),
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not events
|
||||
|
||||
|
||||
def _retry_payload(**overrides):
|
||||
base = {'action_code': 'retry_inventory_preparation', 'actor_user_id': 7}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def _exercise_retry_handler(
|
||||
monkeypatch, task, payload, *,
|
||||
refresh_calls, line_scope=None, excel_artifact=None, ensure_calls=None, line_refresh_result=False,
|
||||
):
|
||||
"""按既有 override 测试模式直调重取处理器:隔离重路由、失效、准备轮次与 ensure_inventory。
|
||||
|
||||
refresh_calls 记录 ('task'|'line', kwargs),用于断言挂载路径与透传参数。
|
||||
line_scope 传 dict 时每次解析都返回它(缺省行为);传 list 时按调用次序逐个弹出
|
||||
(用尽后返回 None),用于断言「刷新产生新集后重解析行作用域」。
|
||||
line_refresh_result 控制行级刷新 helper mock 的返回值(True 表示产生了新候选集)。
|
||||
ensure_calls 顺序捕获 ensure_inventory 收到的 payload(供断言取数范围)。
|
||||
另须打桩 inventory_candidate_projection 三个读取函数:执行器 [STEP 0A] 会真实查库校验
|
||||
活动 CandidateSet,假 Task 不打桩会被提前拦回 inventory_source_routing_required,
|
||||
永远到不了被测的 [STEP 0B] 刷新块(与 test_shipping_line_scoped_inventory_retry 同模式)。
|
||||
"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
execution = SimpleNamespace(id=5, task_id=int(task.id), candidate_set_id=None)
|
||||
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=1),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
|
||||
lambda _task: [SimpleNamespace(source_codes_json=['DSV360_AWSDU'])],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
|
||||
lambda _task: [SimpleNamespace(source_code='DSV360_AWSDU')],
|
||||
)
|
||||
if isinstance(line_scope, list):
|
||||
scope_sequence = list(line_scope)
|
||||
monkeypatch.setattr(
|
||||
executor,
|
||||
'_resolve_line_inventory_scope',
|
||||
lambda _task, **_k: scope_sequence.pop(0) if scope_sequence else None,
|
||||
)
|
||||
else:
|
||||
monkeypatch.setattr(executor, '_resolve_line_inventory_scope', lambda _task, **_k: line_scope)
|
||||
monkeypatch.setattr(executor, '_task_payload', lambda _execution, _payload: {'task_id': task.task_no})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: excel_artifact,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_candidates_from_current_routing',
|
||||
lambda _task, **_k: refresh_calls.append(('task', dict(_k))) or False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_line_candidates_from_current_routing',
|
||||
lambda _task, **_k: refresh_calls.append(('line', dict(_k))) or line_refresh_result,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
|
||||
lambda **_k: {'outcome': 'passed'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||||
lambda **_k: None,
|
||||
)
|
||||
if ensure_calls is None:
|
||||
ensure_calls = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda _payload: ensure_calls.append(dict(_payload)) or {'status': 'ok', 'data': {}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_preparation_failed',
|
||||
)
|
||||
return executor._handle_retry_inventory_preparation(
|
||||
execution=execution, gate=gate, payload=payload,
|
||||
)
|
||||
|
||||
|
||||
def test_retry_refreshes_task_candidates_for_task_level_retry(app, monkeypatch):
|
||||
"""[断言] 任务级人工重取触发整单刷新前置(透传 execution_id);随后仍走既有失效与重取链。"""
|
||||
refresh_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(), refresh_calls=refresh_calls,
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'task'
|
||||
assert refresh_calls[0][1].get('execution_id') == 5
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_refreshes_line_candidates_for_line_scope_retry(app, monkeypatch):
|
||||
"""[断言] 行级重抓触发目标行刷新前置(透传 line_no 与 execution_id),不做整单重路由。"""
|
||||
refresh_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'line'
|
||||
assert refresh_calls[0][1].get('line_no') == 1
|
||||
assert refresh_calls[0][1].get('execution_id') == 5
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_skips_refresh_for_poll_and_excel_lock(app, monkeypatch):
|
||||
"""[断言] 轮询路径与 Excel 已生成(源锁定,任务级+行级)均不刷新候选集。"""
|
||||
refresh_calls = []
|
||||
task = _task()
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(action_code='poll_inventory_preparation'),
|
||||
refresh_calls=refresh_calls,
|
||||
)
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(), refresh_calls=refresh_calls,
|
||||
excel_artifact=SimpleNamespace(id=77),
|
||||
)
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
excel_artifact=SimpleNamespace(id=77),
|
||||
)
|
||||
assert not refresh_calls
|
||||
|
||||
|
||||
def test_retry_line_refresh_requeries_with_new_scope(app, monkeypatch):
|
||||
"""[断言] 行级刷新产生新候选集后须按同参重解析行作用域:同一次点击的失效与 RPA 取数
|
||||
直接使用新冻结码,而非刷新前解析的旧码;重解析为 None 时才保守沿用旧值。"""
|
||||
refresh_calls = []
|
||||
ensure_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope=[
|
||||
{'source_codes': ['DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
{'source_codes': ['DSV360_AWSDU', 'DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
],
|
||||
line_refresh_result=True,
|
||||
ensure_calls=ensure_calls,
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'line'
|
||||
assert refresh_calls[0][1].get('line_no') == 1
|
||||
assert ensure_calls and ensure_calls[-1].get('source_codes') == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_from_preparation_does_not_refresh(app, monkeypatch):
|
||||
"""[断言] retry_inventory_from_preparation 不做候选集刷新前置(仅 retry_inventory_preparation 触发,锁定文档排除项)。"""
|
||||
refresh_calls = []
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(action_code='retry_inventory_from_preparation'),
|
||||
refresh_calls=refresh_calls,
|
||||
)
|
||||
assert not refresh_calls
|
||||
Reference in new issue
Block a user