diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 8252face..fa662e01 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -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//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//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//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//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: diff --git a/backend/app/services/shipping_notice/chat_action_extended_handlers.py b/backend/app/services/shipping_notice/chat_action_extended_handlers.py index 82f08c51..3e6066ac 100644 --- a/backend/app/services/shipping_notice/chat_action_extended_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_extended_handlers.py @@ -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"}) diff --git a/backend/app/services/shipping_notice/export_archive.py b/backend/app/services/shipping_notice/export_archive.py index f44c6d5d..48e83d0c 100644 --- a/backend/app/services/shipping_notice/export_archive.py +++ b/backend/app/services/shipping_notice/export_archive.py @@ -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(): diff --git a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py index acdf8873..ecfd5780 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py +++ b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py @@ -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, *, diff --git a/backend/app/services/shipping_notice/inventory_candidate_projection.py b/backend/app/services/shipping_notice/inventory_candidate_projection.py index bb42bcff..68dd12a2 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_projection.py +++ b/backend/app/services/shipping_notice/inventory_candidate_projection.py @@ -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 diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py index d84d0305..8ae4d075 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -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: diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_inventory_match_persistence.py index 56bb7ed8..2ef9fc87 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_persistence.py +++ b/backend/app/services/shipping_notice/line_inventory_match_persistence.py @@ -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') diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index 096b034c..efd03c70 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -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', diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index cd490a3f..683fb292 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -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, *, diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index cfe8babd..e15d5c49 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -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', diff --git a/backend/tests/test_inventory_source_gate_notice_task.py b/backend/tests/test_inventory_source_gate_notice_task.py new file mode 100644 index 00000000..d3c43a76 --- /dev/null +++ b/backend/tests/test_inventory_source_gate_notice_task.py @@ -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 diff --git a/backend/tests/test_line_inventory_match_persistence.py b/backend/tests/test_line_inventory_match_persistence.py index b3ed9299..43ebde3b 100644 --- a/backend/tests/test_line_inventory_match_persistence.py +++ b/backend/tests/test_line_inventory_match_persistence.py @@ -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 diff --git a/backend/tests/test_shipping_line_scoped_inventory_retry.py b/backend/tests/test_shipping_line_scoped_inventory_retry.py index 85bbfdbd..a56aebd7 100644 --- a/backend/tests/test_shipping_line_scoped_inventory_retry.py +++ b/backend/tests/test_shipping_line_scoped_inventory_retry.py @@ -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, diff --git a/backend/tests/test_shipping_notice_export_archive.py b/backend/tests/test_shipping_notice_export_archive.py new file mode 100644 index 00000000..5d28d676 --- /dev/null +++ b/backend/tests/test_shipping_notice_export_archive.py @@ -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" diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index 9ebf9f87..9f67b39e 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -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(): diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index abcffd5a..449972d6 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -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(): diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 5df0855e..fd8435ca 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -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, diff --git a/backend/tests/test_shipping_refresh_inventory_candidates.py b/backend/tests/test_shipping_refresh_inventory_candidates.py new file mode 100644 index 00000000..1ad25d17 --- /dev/null +++ b/backend/tests/test_shipping_refresh_inventory_candidates.py @@ -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 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index b307d7a1..0ccd237d 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -15,7 +15,9 @@ **已完成桶**:默认子视图「通知完成」为跨 OT 平铺的明细行报表(`GET /shipping-tasks/my-todos/done-lines`),行 = 标准 12 字段(客户/客户编号/订单日期/订单项次/料号/数量/约定出货日期/客户PO/已用数量/open qty/订单单号/单价)+ 页面溯源列(`business_no||task_no`);筛选支持 客户 / 料号 / 发货通知日期(Notice created_at)范围,按明细行分页;导出 `GET .../done-lines/export` 严格 12 列中文表头(OT 不落列,openpyxl 直写,不注册模板)。已用数量/open qty 后端暂无数据源,契约留空;约定出货日期取行级 `required_date`(缺失回退快照表头列)、订单单号取表头 `source_order_number`(field_id 键)、单价取行 `unit_price`。「复核驳回 / 已作废」子视图走既有任务表 + 抽屉,`my-todos` 新增 `terminal_kind` 参数(`upload_complete|reject_void`)服务端过滤。 -**批量操作**:仅「货代上传」阶段的正式 Notice 行有复选框(`isFreightUploadRow`),勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。 +**批量操作**:仅「货代上传」阶段且当前用户可下载(`isBatchDownloadableRow` = `isFreightUploadRow` + 后端谓词字段 `can_download_export`)的正式 Notice 行有复选框,勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。 + +**Excel 下载权限统一口径(2026-10-13)**:单票(`/shipping-tasks//export`、`/shipping-notices//export`)与批量(`/shipping-notices/batch/export`、`/shipping-exports/archive`)的下载授权一律消费 `query_service.can_download_task_export` 统一谓词——**创建者或平台管理员(可下载=可见,无主单仅管理员)**;管理员下载消除"看得到点不动",全部下载(含批量按票)写 `record_access_audit`(批量 `metadata.export=batch_zip` 并附 `batch_status`)。UI 与端点同源:SUMMARY/DETAIL enrich 下发 `can_download_export`;`ui_state` 的 `download_excel` 动作按查看者门禁下发(viewer 缺省的聊天链路维持仅 Artifact 授权旧口径);任务中心复选框/全选、抽屉下载链接均消费谓词字段,禁止前端由 `created_by` 自行反推。写路径归属(`get_task_for_user` / 履约归属断言)不变。 ## 任务中心 OT 直链工作台:深链补 Case 锚点 + 任务详情兜底(2026-09-17) @@ -1902,7 +1904,7 @@ GET /api/admin/shipping-order-schema/published-contract - `GET /api/workspace/shipping-tasks?page=1&page_size=10` 由数据库执行排序、总数统计和切片,返回 `{ items, page, page_size, total }`;业务阶段统一由 `ui_state.stage` 投影,接口不再接受 `process_status`。 - 工作台每页展示 10 条任务,筛选或刷新重置为第一页;任务多选、全选和 ZIP 下载只作用于当前页,切页时清空选择,禁止跨页误操作。 - 工作台提供“下载本批次 ZIP”和任务列表显式多选两种入口;多选可全选当前页结果并显示选择数量。 -- 后端按当前用户重新解析批次/任务,任一显式任务越权则整体拒绝;单次最多 100 票。 +- 后端按当前用户重新解析批次/任务,任一显式任务越权则整体拒绝;单次最多 100 票。下载授权与单票导出同一谓词(`can_download_task_export`:创建者或管理员),成功后按票写 `record_access_audit`(`metadata.export=batch_zip`,manifest entries 携带 `business_no` 供审计聚合)。 - 每票只选择最新且仍与 Task 当前导出路径一致的 `status=ready` Artifact,并在打包前复算 SHA-256;任务纠错清空引用、文件缺失或校验失败均不进入 ZIP 文件区,但必须进入 `manifest.json`。 - manifest 状态为 `included / missing_artifact / missing_file / checksum_mismatch`;同名文件保留首个,其余追加 `task_no`,禁止覆盖。 - ZIP 使用 `SpooledTemporaryFile`:小文件在内存,超过 16 MiB 自动落临时磁盘,由响应结束后释放。 @@ -3968,3 +3970,32 @@ inventory_preparation Gate - Excel/波次条件零改动:出单仍需人工勾选波次,放行行可勾选资格规则不变(`export.py` / wave 服务 / 满足性聚合未改动)。 - 同名不同义:订单明细表 / 聊天匹配卡的「可用数量」仍是预约匹配语义;prep 工作台新「可用数量」列是料号兜底总量,两处是否统一待产品定。 - 存量 canonical-only 快照行料号兜底不生效(与基线一致)。 + +## 2026-10-13 候选库存源刷新(人工重取前置:任务级+行级,幂等) + +**背景**:多候选订单建单时冻结候选库存源集合;之后管理端补配/新增库存源,存量单的 +取数范围(RPA 逐源 / 行级按行候选收窄)与匹配池(候选域过滤)均不会自动纳入新源, +通知准备阶段出现"下拉只有 3 个候选源、重新匹配无法感知新源"的运营阻断 +(prod 实例 SORC-E19FE1B9AB8F4FD2)。 + +**方案(升级不换按钮)**:「重新获取库存(RPA)」(`retry_inventory_preparation`)人工重取前 +新增幂等前置刷新,任务级与行级共用守卫红线: +- 任务级(`refresh_candidates_from_current_routing`):重跑 `adjudicate_and_apply_inventory_source` + 整单重判候选集。 +- 行级(`refresh_line_candidates_from_current_routing`):仅重评目标行——行级规则重评 + (`evaluate_inventory_source_rules(task, line)`,候选经理 `get_database_inventory_source` + 启停过滤,仅接受 resolved/ambiguous),以活动集全量行为骨架定向替换目标行候选后 + `freeze_candidates_for_task` 重冻结,其余行原样继承。 +- 两者均幂等:输入指纹未变复用旧集零副作用;有变化生成新 `set_version`,supersede 旧集时 + 由 `_invalidate_task_candidate_outputs` 内置失效旧匹配事实/准备与 RPA Attempt,随后既有 + `invalidate_inventory_downstream` + `ensure_inventory(mode='retry_rpa')` 按新候选重取并重算匹配。 +- 守卫:已定源不刷新(任务级冻结候选 ≤1 / 行级目标行候选 ≤1),换源走 + `override_line_inventory_source`;候选集含人工选源(frozen_by_id / + candidate_origin='manual_override')不刷新(人工指定即定论);Excel 已生成(D7)不刷新; + 轮询/自动首投/`retry_inventory_from_preparation` 不刷新。 +- 前端歧义行(source_ambiguous)库存源下拉由"仅候选"改为"候选置顶 + 全部已启用源 + 去重兜底"(`features/chat/shipping/inlineSourceOptions.ts` 纯函数),与后端覆写 + 动作"任一已启用源都允许"的既有语义对齐;人工补选新源提交后自动重冻结该行并重匹配。 + +**审计**:产生新版本时写任务事件 `inventory_candidates_refreshed` +(scope=task:previous_set_id/new_set_id/source_codes;scope=line:line_no/previous_codes/new_codes/new_set_id)。 diff --git a/docs/funclist.md b/docs/funclist.md index 27407db2..98c975c5 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -229,6 +229,7 @@ | **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 | | **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 | | 库存匹配料号兜底自动放行与料号维度可用数量展示(2026-10-09) | 已实现 | 匹配器按料号键二次汇总下发 `part_available_qty`(行允许源内、忽略预约号与单位,跨源不合并;迁移 `0a575f3afc32` 新列,存量行重匹配后回填),投影/ui_state prep 行透出;前端匹配表原「可用数量」改「预约数量」并新增「可用数量」列(四语言);匹配落库后 `auto_release_part_fallback_shortages` 对「缺口+料号总量≥需求+证据字段全部自动取值」行由系统创建 `release_inventory_shortage` 决定(`decision_source='system'`,快照 `auto_release`/`release_evidence_scope`),证据不可解析/字段分歧/总量不足降级人工,不自动撤销;证据带出优先级:预约号+料号 → 料号键重筛 → 人工补录,`release_field_values` 为导出 Excel 证据覆盖唯一来源;Excel/波次出单条件不变(出单仍需人工勾选波次)。见 [features/shipping-notice/technical.md](features/shipping-notice/technical.md)「料号兜底自动放行与数量列」。 | +| 库存候选源刷新(人工重取前置,2026-10-13) | 已实现 | 「重新获取库存(RPA)」人工重取前按当前主数据幂等重判候选集(任务级整单重路由、行级仅重评目标行;仅未定源,人工钉源/已定源/Excel 已生成/轮询路径均不刷新),新版候选集 supersede 时内置失效旧库存事实,随后按新候选重取重算;前端歧义行库存源下拉改为候选置顶 + 全部已启用源兜底 | ### 排程平台任务契约中心(schedule) diff --git a/docs/superpowers/plans/2026-10-13-shipping-inventory-candidates-refresh.md b/docs/superpowers/plans/2026-10-13-shipping-inventory-candidates-refresh.md new file mode 100644 index 00000000..5ec2c7bc --- /dev/null +++ b/docs/superpowers/plans/2026-10-13-shipping-inventory-candidates-refresh.md @@ -0,0 +1,1077 @@ +# 库存候选集刷新(任务级+行级人工重取前置)实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 让「重新获取库存(RPA)」的**任务级与行级**人工重取前,按当前主数据幂等重判候选库存源(任务级整单重路由;行级仅重评目标行),并放开前端歧义行库存源下拉到全部已启用源。 + +**Architecture:** 零新动作码、零契约变更、零 UI 按钮变更。后端在 `_handle_retry_inventory_preparation` 人工重试分支插入前置刷新:任务级走 `refresh_candidates_from_current_routing`(复用 `adjudicate_and_apply_inventory_source` + freeze 幂等);行级走 `refresh_line_candidates_from_current_routing`(行级规则重评 + 以活动集为骨架定向替换目标行后 `freeze_candidates_for_task` 冻结,`created_new` 判变化)。两者共用三条守卫红线;新版候选集 supersede 时由 `_invalidate_task_candidate_outputs` 内置失效旧库存事实。前端把行级下拉选项抽为纯函数 `mergeInlineSourceOptions`(候选置顶 + 全量源去重兜底)。 + +**Tech Stack:** Flask + SQLAlchemy(backend/app/services/shipping_notice)、Vue 3 + TS + Vitest(frontend/src/features/chat)。 + +**Spec:** 会话内已确认的「升级不换按钮 + 任务级/行级都刷新」方案(2026-10-13 诊断与设计,要点见 Global Constraints;诊断结论另存于 `.engramory-memory/shipping-source-selection-impl.md`)。 + +## Global Constraints + +- **零新动作码**:不改 `process_gate_contract` 动作清单、不下发新 capability、前端不新增按钮。 +- **刷新只是显式人工重取的伴随前置**:仅 `retry_inventory_preparation` 触发——任务级(`line_scope` 为空)整单刷新;行级(`line_scope` 非空)仅刷新目标行。`poll_inventory_preparation`(只读轮询)、自动首投(`trigger=='gate_attempt_passed'`)、`retry_inventory_from_preparation`(恢复流变体)一律不刷新。 +- **守卫红线(任务级与行级同源)**:① 已定源不自动改源——任务级冻结候选 ≤1 不刷新,行级该行候选 ≤1 不刷新;换源走 `override_line_inventory_source` 行级覆写;② 活动候选集含人工选源(`frozen_by_id` 非空或 `candidate_origin=='manual_override'`)不刷新——人工指定即定论;③ Excel 已生成(`latest_export_artifact` 非空,D7 锁定边界)不刷新。 +- **幂等**:输入指纹未变时 `freeze_candidates_for_task` 复用旧集(`created_new=False`),刷新返回 False、零副作用;主数据有变但路由结论未变时会产生新版集(配置版本进入指纹),此时用户本就在显式重取,失效重取符合预期,重复点击收敛。 +- **行级候选必须过滤可用性**:`InventoryRoutingResult.source_codes` 为规则原始候选(未做启停过滤),入候选集前必须经 `get_database_inventory_source` 校验(对齐 `_result_to_adjudication` 语义)。 +- **不改 `models.py`,无数据库迁移**(候选集天然支持 `set_version` 多版本)。 +- **不动既有边界**:`inventory_candidate_freeze_service.py` 中已有的 `#region debug-point A/C/E` 调试代码块**保持原样不要删除**(边界外事项,另行处理)。 +- i18n 四语言(zh-CN / zh-TW / en / th)同步;禁止硬编码文案。 +- 注释遵循 AGENTS §5:文件层三要素 + 函数层 docstring/JSDoc;业务步骤用 `[STEP n]`;禁止逐行翻译代码。 +- **禁止自动 commit**:每个任务以 `git add <具体文件>` 收尾,提交由用户显式决定。 +- 后端测试命令:`cd backend && .\.venv\Scripts\python.exe -m pytest tests/ -q`;前端验证:`cd frontend && npx vitest run ` + 最终 `npm run build` 必须通过。 + +--- + +### Task 1: 后端刷新 helper(freeze service 内新增,任务级+行级) + +**Files:** +- Modify: `backend/app/services/shipping_notice/inventory_candidate_freeze_service.py`(在 `freeze_manual_line_source_selection` 之后追加三个函数) +- Test: `backend/tests/test_shipping_refresh_inventory_candidates.py`(新建) + +**Interfaces:** +- Consumes: `adjudicate_and_apply_inventory_source(task, *, execution_id=None)`(inventory_source_gate.py:121);`get_active_candidate_set(task)`(inventory_candidate_projection.py);`task_frozen_inventory_source_codes(task)`(stp_inventory_freeze.py:186);`evaluate_inventory_source_rules(*, task, line=None)` / `_task_routing_lines(task)` / `extract_routing_context` / `compute_routing_fingerprint`(inventory_source_rules.py,重导出自 routing_engine);`get_database_inventory_source` / `inventory_sources_runtime_version`(inventory_source_repository.py);`log_task_event`(tool_common.py);同模块 `freeze_candidates_for_task`。 +- Produces: + - `active_candidate_set_is_manually_pinned(task, *, session=None) -> bool` + - `refresh_candidates_from_current_routing(task, *, execution_id=None, session=None) -> bool`(任务级,True=产生新版候选集) + - `refresh_line_candidates_from_current_routing(task, *, line_no: int, execution_id=None, session=None) -> bool`(行级,True=产生新版候选集) + - 任务事件 `inventory_candidates_refreshed`(payload 含 `scope: 'task'|'line'`)。 + +- [ ] **Step 1: 写失败测试(新建测试文件)** + +```python +""" +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 +``` + +- [ ] **Step 2: 运行测试确认失败** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q` +Expected: FAIL(`AttributeError: ... has no attribute 'refresh_candidates_from_current_routing'` 等) + +- [ ] **Step 3: 实现 helper(追加到 `freeze_manual_line_source_selection` 之后)** + +```python +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 +``` + +- [ ] **Step 4: 运行测试确认通过** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q` +Expected: PASS(10 passed) + +- [ ] **Step 5: 暂存** + +```bash +git add backend/app/services/shipping_notice/inventory_candidate_freeze_service.py backend/tests/test_shipping_refresh_inventory_candidates.py +``` + +--- + +### Task 2: 执行器前置步骤(任务级+行级挂载) + +**Files:** +- Modify: `backend/app/services/shipping_notice/process_gate_executor.py`(`_handle_retry_inventory_preparation` 内,约 928-952 行的 `if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:` 块内、`invalidate_inventory_downstream(...)` 调用之前插入) +- Test: `backend/tests/test_shipping_refresh_inventory_candidates.py`(追加集成用例) + +**Interfaces:** +- Consumes: Task 1 的 `refresh_candidates_from_current_routing(task, *, execution_id=None)` 与 `refresh_line_candidates_from_current_routing(task, *, line_no, execution_id=None)`;`latest_export_artifact(task)`(upload_attempt_service.py);`line_scope['line_no']`(executor 内 `_resolve_line_inventory_scope` 产物,含 `snapshot_line_id`/`line_no`/`source_codes`)。 +- Produces: 无新接口(行为变更:人工重取——任务级先整单刷新、行级先刷新目标行——再走既有失效 + `ensure_inventory(mode='retry_rpa')` 重取链)。 + +- [ ] **Step 1: 追加失败测试(同测试文件末尾)** + +```python +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): + """按既有 override 测试模式直调重取处理器:隔离重路由、失效、准备轮次与 ensure_inventory。 + + refresh_calls 记录 ('task'|'line', kwargs),用于断言挂载路径与透传参数。 + """ + 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(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 False, + ) + 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, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + lambda _payload: {'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 +``` + +- [ ] **Step 2: 运行测试确认失败** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q` +Expected: 新增 3 例 FAIL(`refresh_calls` 为空,断言不成立);Task 1 的 10 例保持 PASS + +- [ ] **Step 3: 实现前置步骤** + +在 `_handle_retry_inventory_preparation` 中定位该块(约 928 行): + +```python + if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: +``` + +在该块内、`if payload.get('action_code') in { 'retry_inventory_preparation', ... }:` 的 `invalidate_inventory_downstream(...)` 调用**之前**插入: + +```python + # [STEP 0B] 人工重取前的候选源刷新(幂等):任务级 retry_inventory_preparation 先按当前 + # 主数据/路由规则整单重判候选集;行级重抓(line_scope 非空)仅重评目标行候选。 + # 两者均无变化零副作用;有变化则新版候选集随 supersede 自带旧事实失效,再走下方 + # 既有失效与重取链——补源场景由此闭环:管理端启用新源后点「重新获取库存(RPA)」 + # 即可让新源进入取数与匹配范围,无需重建订单。 + # 轮询/自动首投(外层条件已排除)与 Excel 已生成(源锁定,D7 边界)不刷新; + # 已定源(任务级整单/行级目标行候选 ≤1)与人工钉源不刷新(helper 内守卫,改源走 + # override_line_inventory_source)。 + 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)) + else: + refresh_line_candidates_from_current_routing( + task, line_no=int(line_scope['line_no']), execution_id=int(execution.id), + ) +``` + +- [ ] **Step 4: 运行测试确认通过** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q` +Expected: PASS(13 passed) + +- [ ] **Step 5: 回归相邻测试面(轮询语义与覆写动作不受影响)** + +Run: `cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_inventory_poll_failure_semantics.py tests/test_shipping_override_inventory_source.py tests/test_shipping_line_source_ambiguity.py -q` +Expected: PASS(如遇与本改动无关的既有 WIP 失败,记录并对照 `git stash` 验证,不得顺手修改) + +- [ ] **Step 6: 暂存** + +```bash +git add backend/app/services/shipping_notice/process_gate_executor.py backend/tests/test_shipping_refresh_inventory_candidates.py +``` + +--- + +### Task 3: 前端下拉合并(候选置顶 + 全量源兜底) + +**Files:** +- Create: `frontend/src/features/chat/shipping/inlineSourceOptions.ts` +- Create: `frontend/src/features/chat/shipping/inlineSourceOptions.test.ts` +- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(`inlineSourceOptions` 函数改约 3053-3068 行;删除仅被其使用的 `lineSourceOptionLabel` 约 2657-2661 行与 `overrideSourceOptionLabel` 约 2666-2668 行) + +**Interfaces:** +- Consumes: `formSourceOptions`(视图已有 computed,来自 `ui_state.stage_context.preparation.source_options`);行投影字段 `source_ambiguous` / `source_candidates`。 +- Produces: `mergeInlineSourceOptions(line: InlineSourceLine, enabledSources: ReadonlyArray): InlineSourceOption[]`(纯函数,供视图 `inlineSourceOptions` 委托)。 + +- [ ] **Step 1: 写失败测试(新建 spec,命名对齐同目录 `shippingText.test.ts`)** + +```ts +/** + * features/chat/shipping/inlineSourceOptions.test.ts + * + * 用途:行级库存源下拉选项合并的纯函数单测——歧义行候选置顶、全量源兜底去重、空态回退。 + * 依赖:被测 mergeInlineSourceOptions(无副作用纯函数)。 + * 逻辑:断言合并顺序(候选在前、已启用源按后端下发序追加)、去重、大小写归一与空态。 + */ +import { describe, expect, it } from 'vitest'; +import { mergeInlineSourceOptions } from './inlineSourceOptions'; + +describe('mergeInlineSourceOptions', () => { + it('歧义行候选置顶,后接全部已启用源去重兜底(补源场景:新源出现在末尾)', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: true, source_candidates: ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'] }, + [{ source_code: 'DSV360_AWSCV' }, { source_code: 'DSV360_AWSDU' }], + ); + expect(options.map((option) => option.value)).toEqual([ + 'DSV360_AWSCV', + 'DSV360_AWSBI_BYAWSCMH01', + 'DSV360_AWSDU', + ]); + }); + + it('非歧义行仅给全部已启用源(保持既有行为,不前置候选)', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: false, source_candidates: ['DSV360_AWSCV'] }, + [{ source_code: 'DSV360_AWSDU' }], + ); + expect(options.map((option) => option.value)).toEqual(['DSV360_AWSDU']); + }); + + it('歧义行候选缺省时退化为全部已启用源,编码统一大写', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: true }, + [{ source_code: 'dsv360_awssg' }], + ); + expect(options.map((option) => option.value)).toEqual(['DSV360_AWSSG']); + }); + + it('两侧皆空返回空数组(调用方据此回退文本展示)', () => { + expect(mergeInlineSourceOptions({ source_ambiguous: true }, [])).toEqual([]); + }); +}); +``` + +- [ ] **Step 2: 运行测试确认失败** + +Run: `cd frontend && npx vitest run src/features/chat/shipping/inlineSourceOptions.test.ts` +Expected: FAIL(Cannot find module './inlineSourceOptions') + +- [ ] **Step 3: 实现纯函数(新建 `inlineSourceOptions.ts`)** + +```ts +/** + * features/chat/shipping/inlineSourceOptions.ts + * + * 用途:通知准备行级「库存源」编辑下拉的选项合并(纯函数,无副作用)。 + * 依赖:无(仅入参结构约束,类型与 ui_state preparation 投影字段对齐)。 + * 逻辑:多候选歧义行(source_ambiguous)的路由冻结候选置顶,后接全部已启用库存源 + * (preparation.source_options)去重兜底——后端 override_line_inventory_source 已放开 + * 「任一已启用源都允许」,管理端补源后新源即使不在候选内也可人工指定。 + */ + +/** 行级库存源下拉选项(value=源编码,label=展示编码,统一大写便于识别)。 */ +export interface InlineSourceOption { + value: string; + label: string; +} + +/** 准备行投影中与本合并相关的字段(ui_state preparation.lines[] 子集)。 */ +export interface InlineSourceLine { + source_ambiguous?: boolean; + source_candidates?: Array; +} + +/** 后端下发的已启用库存源(ui_state preparation.source_options[] 子集)。 */ +export interface EnabledSourceOption { + source_code?: string | null; +} + +/** + * 合并行级库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底,按源编码去重保序。 + * @param line - 准备行(读 source_ambiguous / source_candidates) + * @param enabledSources - 后端下发的全部已启用库存源(保持后端排序) + * @returns 下拉选项;两侧皆空时返回空数组(调用方据此回退文本展示) + */ +export function mergeInlineSourceOptions( + line: InlineSourceLine, + enabledSources: ReadonlyArray, +): InlineSourceOption[] { + const merged = new Map(); + if (line.source_ambiguous) { + for (const raw of line.source_candidates || []) { + const code = String(raw || '').trim().toUpperCase(); + if (code && !merged.has(code)) merged.set(code, { value: code, label: code }); + } + } + for (const source of enabledSources) { + const code = String(source.source_code || '').trim().toUpperCase(); + if (code && !merged.has(code)) merged.set(code, { value: code, label: code }); + } + return [...merged.values()]; +} +``` + +- [ ] **Step 4: 运行测试确认通过** + +Run: `cd frontend && npx vitest run src/features/chat/shipping/inlineSourceOptions.test.ts` +Expected: PASS(4 passed) + +- [ ] **Step 5: 视图接入(`ShippingOrderReviewView.vue`)** + +1. 在既有 `../shipping/` 相对导入区追加: +```ts +import { mergeInlineSourceOptions } from '../shipping/inlineSourceOptions'; +``` +2. 将 `inlineSourceOptions`(约 3053-3068 行)整体替换为: +```ts +/** + * 行级编辑态库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底(合并去重,纯函数委托)。 + * 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。 + */ +function inlineSourceOptions(line: { + source_ambiguous?: boolean; + source_candidates?: Array; +}): Array<{ value: string; label: string }> { + return mergeInlineSourceOptions(line, formSourceOptions.value); +} +``` +3. 删除 `lineSourceOptionLabel`(约 2657-2661 行)与 `overrideSourceOptionLabel`(约 2666-2668 行)及其注释——二者仅被旧 `inlineSourceOptions` 使用,删除后全仓无引用(`formSourceOptions` computed 保留,仍在使用)。 + +- [ ] **Step 6: 全量验证(受影响 spec + 构建)** + +Run: `cd frontend && npx vitest run src/features/chat/views/ShippingOrderReviewView.spec.ts && npm run build` +Expected: vitest PASS(既有 108+ 用例不回归);build 成功 + +- [ ] **Step 7: 暂存** + +```bash +git add frontend/src/features/chat/shipping/inlineSourceOptions.ts frontend/src/features/chat/shipping/inlineSourceOptions.test.ts frontend/src/features/chat/views/ShippingOrderReviewView.vue +``` + +--- + +### Task 4: i18n 提示文案 + 文档同步 + +**Files:** +- Modify: `frontend/src/locales/zh-CN/chat.json`、`frontend/src/locales/zh-TW/chat.json`、`frontend/src/locales/en/chat.json`、`frontend/src/locales/th/chat.json`(各 1 处 `diagnosisInventoryRpaAdvice`) +- Modify: `docs/features/shipping-notice/technical.md`(末尾追加章节)、`docs/funclist.md`(shipping-notice 表追加 1 行) + +**Interfaces:** +- Consumes: Task 1/2 的后端行为语义(任务级+行级刷新前置)。 +- Produces: 四语言一致的提示文案;文档与代码一致(AGENTS §9)。 + +- [ ] **Step 1: 四语言更新 `diagnosisInventoryRpaAdvice`(键已在四语言存在,只改值)** + +- `zh-CN`(约 689 行): +```json +"diagnosisInventoryRpaAdvice": "建议先重新获取库存(将按最新主数据重新裁决候选源:任务级整单重判、行级仅重评该行);若外部系统不可用,可人工上传库存文件。" +``` +- `zh-TW`(约 655 行): +```json +"diagnosisInventoryRpaAdvice": "建議先重新獲取庫存(將依最新主檔重新裁決候選來源:任務級整單重判、行級僅重評該行);若外部系統不可用,可人工上傳庫存檔。" +``` +- `en`(约 655 行): +```json +"diagnosisInventoryRpaAdvice": "Retry inventory fetch first (candidate sources are re-adjudicated against the latest master data: task-level re-routes the whole order, line-level re-evaluates only that line); if the external system is unavailable, upload an inventory file manually." +``` +- `th`(约 655 行): +```json +"diagnosisInventoryRpaAdvice": "ลองดึงสต็อกใหม่ก่อน (ระบบจะประเมินแหล่งสต็อกที่เป็นไปได้ใหม่ตามข้อมูลหลักล่าสุด: ระดับงานประเมินทั้งใบสั่ง ระดับบรรทัดประเมินเฉพาะบรรทัดนั้น) หากระบบภายนอกใช้ไม่ได้ ให้อัปโหลดไฟล์สต็อกด้วยตนเอง" +``` + +- [ ] **Step 2: 构建验证(JSON 合法性由 build 兜底)** + +Run: `cd frontend && npm run build` +Expected: 成功 + +- [ ] **Step 3: `docs/features/shipping-notice/technical.md` 末尾追加(只追加,不改既有内容)** + +```markdown +## 2026-10-13 候选库存源刷新(人工重取前置:任务级+行级,幂等) + +**背景**:多候选订单建单时冻结候选库存源集合;之后管理端补配/新增库存源,存量单的 +取数范围(RPA 逐源 / 行级按行候选收窄)与匹配池(候选域过滤)均不会自动纳入新源, +通知准备阶段出现"下拉只有 3 个候选源、重新匹配无法感知新源"的运营阻断 +(prod 实例 SORC-E19FE1B9AB8F4FD2)。 + +**方案(升级不换按钮)**:「重新获取库存(RPA)」(`retry_inventory_preparation`)人工重取前 +新增幂等前置刷新,任务级与行级共用守卫红线: +- 任务级(`refresh_candidates_from_current_routing`):重跑 `adjudicate_and_apply_inventory_source` + 整单重判候选集。 +- 行级(`refresh_line_candidates_from_current_routing`):仅重评目标行——行级规则重评 + (`evaluate_inventory_source_rules(task, line)`,候选经理 `get_database_inventory_source` + 启停过滤,仅接受 resolved/ambiguous),以活动集全量行为骨架定向替换目标行候选后 + `freeze_candidates_for_task` 重冻结,其余行原样继承。 +- 两者均幂等:输入指纹未变复用旧集零副作用;有变化生成新 `set_version`,supersede 旧集时 + 由 `_invalidate_task_candidate_outputs` 内置失效旧匹配事实/准备与 RPA Attempt,随后既有 + `invalidate_inventory_downstream` + `ensure_inventory(mode='retry_rpa')` 按新候选重取并重算匹配。 +- 守卫:已定源不刷新(任务级冻结候选 ≤1 / 行级目标行候选 ≤1),换源走 + `override_line_inventory_source`;候选集含人工选源(frozen_by_id / + candidate_origin='manual_override')不刷新(人工指定即定论);Excel 已生成(D7)不刷新; + 轮询/自动首投/`retry_inventory_from_preparation` 不刷新。 +- 前端歧义行(source_ambiguous)库存源下拉由"仅候选"改为"候选置顶 + 全部已启用源 + 去重兜底"(`features/chat/shipping/inlineSourceOptions.ts` 纯函数),与后端覆写 + 动作"任一已启用源都允许"的既有语义对齐;人工补选新源提交后自动重冻结该行并重匹配。 + +**审计**:产生新版本时写任务事件 `inventory_candidates_refreshed` +(scope=task:previous_set_id/new_set_id/source_codes;scope=line:line_no/previous_codes/new_codes/new_set_id)。 +``` + +- [ ] **Step 4: `docs/funclist.md` shipping-notice 表追加 1 行** + +在货代发货通知功能清单表(`### 货代发货通知(shipping-notice)`,3 列:功能项 | 状态 | 说明)末尾追加: + +```markdown +| 库存候选源刷新(人工重取前置,2026-10-13) | 已实现 | 「重新获取库存(RPA)」人工重取前按当前主数据幂等重判候选集(任务级整单重路由、行级仅重评目标行;仅未定源,人工钉源/已定源/Excel 已生成/轮询路径均不刷新),新版候选集 supersede 时内置失效旧库存事实,随后按新候选重取重算;前端歧义行库存源下拉改为候选置顶 + 全部已启用源兜底 | +``` + +- [ ] **Step 5: 暂存** + +```bash +git add frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json docs/features/shipping-notice/technical.md docs/funclist.md +``` + +--- + +## 任务依赖与验证总览 + +- Task 1 → Task 2(执行器消费两个 helper);Task 3、Task 4 相互独立,可并行。 +- 全部完成后整体回归:`cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py tests/test_inventory_poll_failure_semantics.py tests/test_shipping_override_inventory_source.py -q` + `cd frontend && npm run build`。 +- 人工冒烟(部署 dev 后):多候选缺口单——任务级「重新获取库存(RPA)」→ 整单候选按当前主数据重判;行级「重新获取库存(RPA)」→ 仅该行候选重评;两者在主数据无变化时行为与升级前一致;管理端启用新源后再点 → 新源进入对应范围。 diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts index 4b7ef7b8..a879ed9a 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts @@ -90,6 +90,13 @@ export const REVIEW_BUILD_ELIGIBILITY_BLOCKED = 'SHIPPING.REVIEW_BUILD_ELIGIBILI */ export const PROGRESS_POLL_MS = 5000; +/** + * waiting_human / failed 的降频保活间隔。两者不是不可逆终态:自愈回收、 + * RPA 回调仍会把任务继续推进(历史缺陷:一帧停死令界面永久冻结在旧阶段), + * 降频而非停转,状态回到活跃态自动恢复基础间隔。 + */ +export const PROGRESS_POLL_IDLE_MS = 15000; + /** / Case */ export type DraftVersionConflict = { localVersion: number; @@ -449,6 +456,7 @@ export function useShippingOrderReview(options: { // 浏览器端 window.setInterval 返回 number;勿用 ReturnType, // 其在 @types/node 与 DOM lib 混用时会解析为 NodeJS.Timeout 导致 TS2322。 let progressPollTimer: number | null = null; + let progressPollIntervalMs = PROGRESS_POLL_MS; let stpCreatePollTimer: number | null = null; let reparseCaseRefreshTimer: number | null = null; @@ -639,15 +647,17 @@ export function useShippingOrderReview(options: { if (!authoritativeOrderTaskNo.value && !targetRunNo) return; showWorkflowProgress.value = true; workflowProgressPolling.value = true; - // RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。 - // 等待人工(waiting_human,即“中断”)视为线性终态:结果不会自行变化,继续轮询浪费资源。 - // 注意:统一投影的用户态值是 waiting_human(旧字段是 needs_human),若沿用旧的 - // needs_human 会让已中断任务永远匹配不到终态、一直空转轮询;failed 同理是停止状态。 - // 可重试失败(retryable)不在此列,需保留轮询以便后续成功回调自动刷新工作流。 - const UNIFIED_TERMINAL = new Set(['completed', 'cancelled', 'waiting_human', 'failed']); + // RPA 超时、可重试失败、人工复核与自愈回收都可能被后续回调推进,页面留存期间持续 + // 读取 Projection。completed/cancelled 是不可逆终态,命中即停;waiting_human/failed + // 不是终态(自愈回收、回调仍会推进),历史缺陷是一帧停死令界面永久冻结在旧阶段—— + // 改为降频保活,状态回到活跃态自动恢复基础间隔。 + const WORKFLOW_STOP_STATUSES = new Set(['completed', 'cancelled']); + const WORKFLOW_SLOW_STATUSES = new Set(['waiting_human', 'failed']); let lastUnifiedStatus = ''; let lastLifecycleFingerprint = ''; - const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']); + // Run 级 partially_completed 只代表解析阶段收尾,OT 随后仍会被 STP 建单产出; + // 命中即停会令提交订单后的轮询在 OT 诞生前死亡(历史缺陷),同样只降频不停转。 + const RUN_STOP_STATUSES = new Set(['completed', 'cancelled']); const tick = async () => { // 页面不可见时暂停轮询(返回前台后下一拍自动恢复),避免后台标签持续占用服务端。 if (typeof document !== 'undefined' && document.hidden) return; @@ -677,10 +687,13 @@ export function useShippingOrderReview(options: { // 否则提交订单后秒级阻断时五阶段条卡在订单复核、自动跳转永不触发。 await refreshActiveAutomationLifecycle(); } - if (UNIFIED_TERMINAL.has(unifiedStatus)) { + if (WORKFLOW_STOP_STATUSES.has(unifiedStatus)) { stopWorkflowProgressPolling(); return; } + ensureWorkflowProgressInterval( + WORKFLOW_SLOW_STATUSES.has(unifiedStatus) ? PROGRESS_POLL_IDLE_MS : PROGRESS_POLL_MS, + ); return; } if (targetRunNo) { @@ -695,15 +708,26 @@ export function useShippingOrderReview(options: { userTaskNo: reviewProgressContext.value?.user_task_no, }); if (synthesized) reviewProgressContext.value = synthesized; - if (RUN_TERMINAL.has(String(run.status || '').trim())) { + const runStatus = String(run.status || '').trim(); + if (RUN_STOP_STATUSES.has(runStatus)) { stopWorkflowProgressPolling(); + return; } + ensureWorkflowProgressInterval(runStatus === 'failed' ? PROGRESS_POLL_IDLE_MS : PROGRESS_POLL_MS); } } catch { /* */ } }; + // 状态分级轮询:活跃态基础间隔;waiting_human/failed 降频保活。间隔变化才重建定时器。 + const ensureWorkflowProgressInterval = (intervalMs: number) => { + if (progressPollTimer != null && progressPollIntervalMs === intervalMs) return; + if (progressPollTimer != null) window.clearInterval(progressPollTimer); + progressPollIntervalMs = intervalMs; + progressPollTimer = window.setInterval(() => { void tick(); }, intervalMs); + }; void tick(); + progressPollIntervalMs = PROGRESS_POLL_MS; progressPollTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS); }; diff --git a/frontend/src/features/chat/shipping/inlineSourceOptions.test.ts b/frontend/src/features/chat/shipping/inlineSourceOptions.test.ts new file mode 100644 index 00000000..160fcb61 --- /dev/null +++ b/frontend/src/features/chat/shipping/inlineSourceOptions.test.ts @@ -0,0 +1,43 @@ +/** + * features/chat/shipping/inlineSourceOptions.test.ts + * + * 用途:行级库存源下拉选项合并的纯函数单测——歧义行候选置顶、全量源兜底去重、空态回退。 + * 依赖:被测 mergeInlineSourceOptions(无副作用纯函数)。 + * 逻辑:断言合并顺序(候选在前、已启用源按后端下发序追加)、去重、大小写归一与空态。 + */ +import { describe, expect, it } from 'vitest'; +import { mergeInlineSourceOptions } from './inlineSourceOptions'; + +describe('mergeInlineSourceOptions', () => { + it('歧义行候选置顶,后接全部已启用源去重兜底(补源场景:新源出现在末尾)', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: true, source_candidates: ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'] }, + [{ source_code: 'DSV360_AWSCV' }, { source_code: 'DSV360_AWSDU' }], + ); + expect(options.map((option) => option.value)).toEqual([ + 'DSV360_AWSCV', + 'DSV360_AWSBI_BYAWSCMH01', + 'DSV360_AWSDU', + ]); + }); + + it('非歧义行仅给全部已启用源(保持既有行为,不前置候选)', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: false, source_candidates: ['DSV360_AWSCV'] }, + [{ source_code: 'DSV360_AWSDU' }], + ); + expect(options.map((option) => option.value)).toEqual(['DSV360_AWSDU']); + }); + + it('歧义行候选缺省时退化为全部已启用源,编码统一大写', () => { + const options = mergeInlineSourceOptions( + { source_ambiguous: true }, + [{ source_code: 'dsv360_awssg' }], + ); + expect(options.map((option) => option.value)).toEqual(['DSV360_AWSSG']); + }); + + it('两侧皆空返回空数组(调用方据此回退文本展示)', () => { + expect(mergeInlineSourceOptions({ source_ambiguous: true }, [])).toEqual([]); + }); +}); diff --git a/frontend/src/features/chat/shipping/inlineSourceOptions.ts b/frontend/src/features/chat/shipping/inlineSourceOptions.ts new file mode 100644 index 00000000..a6ce7fb9 --- /dev/null +++ b/frontend/src/features/chat/shipping/inlineSourceOptions.ts @@ -0,0 +1,50 @@ +/** + * features/chat/shipping/inlineSourceOptions.ts + * + * 用途:通知准备行级「库存源」编辑下拉的选项合并(纯函数,无副作用)。 + * 依赖:无(仅入参结构约束,类型与 ui_state preparation 投影字段对齐)。 + * 逻辑:多候选歧义行(source_ambiguous)的路由冻结候选置顶,后接全部已启用库存源 + * (preparation.source_options)去重兜底——后端 override_line_inventory_source 已放开 + * 「任一已启用源都允许」,管理端补源后新源即使不在候选内也可人工指定。 + */ + +/** 行级库存源下拉选项(value=源编码,label=展示编码,统一大写便于识别)。 */ +export interface InlineSourceOption { + value: string; + label: string; +} + +/** 准备行投影中与本合并相关的字段(ui_state preparation.lines[] 子集)。 */ +export interface InlineSourceLine { + source_ambiguous?: boolean; + source_candidates?: Array; +} + +/** 后端下发的已启用库存源(ui_state preparation.source_options[] 子集)。 */ +export interface EnabledSourceOption { + source_code?: string | null; +} + +/** + * 合并行级库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底,按源编码去重保序。 + * @param line - 准备行(读 source_ambiguous / source_candidates) + * @param enabledSources - 后端下发的全部已启用库存源(保持后端排序) + * @returns 下拉选项;两侧皆空时返回空数组(调用方据此回退文本展示) + */ +export function mergeInlineSourceOptions( + line: InlineSourceLine, + enabledSources: ReadonlyArray, +): InlineSourceOption[] { + const merged = new Map(); + if (line.source_ambiguous) { + for (const raw of line.source_candidates || []) { + const code = String(raw || '').trim().toUpperCase(); + if (code && !merged.has(code)) merged.set(code, { value: code, label: code }); + } + } + for (const source of enabledSources) { + const code = String(source.source_code || '').trim().toUpperCase(); + if (code && !merged.has(code)) merged.set(code, { value: code, label: code }); + } + return [...merged.values()]; +} diff --git a/frontend/src/features/chat/types/shipping.api.types.ts b/frontend/src/features/chat/types/shipping.api.types.ts index e0bf26da..bcabd5b1 100644 --- a/frontend/src/features/chat/types/shipping.api.types.ts +++ b/frontend/src/features/chat/types/shipping.api.types.ts @@ -922,6 +922,8 @@ export interface ShippingTaskSummary { owner_agent_id?: number | null; /** 当前用户是否可写;管理员查看他人任务时为 false */ can_handle?: boolean; + /** 当前用户是否可下载正式 Excel(与导出端点同一谓词:创建者或管理员) */ + can_download_export?: boolean; /** 统一 ShippingProcessing status(列表轮询优先读此字段)。 */ shipping_processing_status?: string | null; /** 统一 ShippingProcessing stage(任务中心紧凑进度)。 */ diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index 26b2b648..1a33949a 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -52,6 +52,7 @@ import { resolveExtractionActivityMessage, resolveRunLifecycleUserStatus, } from '../shipping/shippingProcessingLabels'; +import { mergeInlineSourceOptions } from '../shipping/inlineSourceOptions'; import ReviewActionConfirmDialog, { type ReviewConfirmAction, type ReviewConfirmPayload, @@ -2654,20 +2655,9 @@ const formalPreparationSourceLocked = computed(() => Boolean(formalPreparationCo /** 库存源选择不再有独立确认流:行进入就地编辑态后在下拉中改选,随行级「保存」统一提交 * (override_line_inventory_source Gate 动作,见 saveInlineEdit);展示态回退为文本。 */ -/** 选源下拉项文案:源编码始终可见(等宽语义由样式层保证)。 */ -function lineSourceOptionLabel(code: string): string { - // 兜底:只会展示源编码(如 DSV360_AWSSG),不展示冗长显示名。 - return String(code || '').trim().toUpperCase(); -} - /** 人工覆写库存源(方案 3·放开):后端下发全部已启用源 source_options,供行级下拉人工指定。 */ const formSourceOptions = computed(() => formalPreparationContext.value?.source_options || []); -function overrideSourceOptionLabel(code: string): string { - // 兜底:下拉只展示源编码(如 DSV360_AWSSG),不展示冗长 display_name,便于快速识别。 - return String(code || '').trim().toUpperCase(); -} - /** 整单 ODM 裁决列可见性:任一行候选多于一个时展示(候选已经客户范围过滤)。 */ const formalPreparationOdmColumnVisible = computed(() => (formalPreparationContext.value?.lines || []).some((line) => (line.odm_values?.length || 0) > 1), @@ -3051,20 +3041,14 @@ function isInlineEditing(line: { snapshot_line_id?: number | null }): boolean { } /** - * 编辑态库存源下拉选项:多文件冲突行优先取候选源,其余行取全部已启用源; + * 行级编辑态库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底(合并去重,纯函数委托)。 * 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。 */ function inlineSourceOptions(line: { source_ambiguous?: boolean; source_candidates?: Array; }): Array<{ value: string; label: string }> { - if (line.source_ambiguous && (line.source_candidates?.length || 0) > 0) { - return (line.source_candidates || []).map((code) => ({ value: String(code), label: lineSourceOptionLabel(String(code)) })); - } - if (formSourceOptions.value.length) { - return formSourceOptions.value.map((s) => ({ value: String(s.source_code), label: overrideSourceOptionLabel(String(s.source_code)) })); - } - return []; + return mergeInlineSourceOptions(line, formSourceOptions.value); } /** 同步编辑态库存源草稿(与三个值列一致:改动仅在保存时提交)。 */ @@ -3516,9 +3500,11 @@ async function runFreightBatchAction(action: 'download' | 'confirm' | 'rpa') { if (action === 'download') { await downloadWorkspaceShippingNoticeExportArchive(selectedFreightBusinessNos.value); } else if (action === 'confirm') { - await batchConfirmWorkspaceShippingNoticesUploaded(selectedFreightBusinessNos.value); + const summary = await batchConfirmWorkspaceShippingNoticesUploaded(selectedFreightBusinessNos.value); + warnBlockedFreightNoticeResults(summary.results); } else { - await batchStartWorkspaceShippingNoticeRpaUpload(selectedFreightBusinessNos.value); + const summary = await batchStartWorkspaceShippingNoticeRpaUpload(selectedFreightBusinessNos.value); + warnBlockedFreightNoticeResults(summary.results); } // 确认/RPA 后重拉同 PO 通知聚合,使通知完成面能立即呈现最新 uploaded 状态。 if (action === 'confirm' || action === 'rpa') { @@ -3554,9 +3540,11 @@ async function runFreightNoticeAction( freightBatchBusy.value = action; try { if (action === 'confirm') { - await batchConfirmWorkspaceShippingNoticesUploaded([group.business_no]); + const summary = await batchConfirmWorkspaceShippingNoticesUploaded([group.business_no]); + warnBlockedFreightNoticeResults(summary.results); } else if (action === 'rpa') { - await batchStartWorkspaceShippingNoticeRpaUpload([group.business_no]); + const summary = await batchStartWorkspaceShippingNoticeRpaUpload([group.business_no]); + warnBlockedFreightNoticeResults(summary.results); } else { if (String(formalTaskDetail.value?.business_no || '').trim() !== group.business_no) return; await submitFormalGateAction('regenerate_excel_artifact'); @@ -3577,6 +3565,25 @@ async function runFreightNoticeAction( } } +/** + * 批量 RPA/确认结果逐单消费:被拦截项的原因必须浮出。 + * 核心逻辑:批量接口恒返回 202 成功 envelope,逐单 blocked 藏在 results 里 + * (历史缺陷:前端不检查,界面零反馈,用户以为点击无效——如「库存源尚未确定」)。 + * blocked 携带后端本地化 message(AppError 在顶层、tool_response 在 result 内), + * 去重后合并为一条 warning;accepted 项的状态推进由既有投影刷新呈现。 + * @param results - 批量接口返回的逐单结果数组。 + */ +function warnBlockedFreightNoticeResults(results: Array> | undefined): void { + const reasons = new Set(); + for (const item of results || []) { + if (String(item?.status || '') !== 'blocked') continue; + const detail = item as { message?: unknown; code?: unknown; result?: { message?: unknown } }; + const reason = String(detail.message || detail.result?.message || detail.code || '').trim(); + if (reason) reasons.add(reason); + } + if (reasons.size) msg.warning(Array.from(reasons).join(';')); +} + /** 当前任务的 Excel 重生只可映射到其自身 business_no,禁止跨 PO/通知单展示。 */ function canRegenerateFreightNotice(group: ShippingFreightNoticeGroup): boolean { return canRunFreightNoticeAction(group, 'regenerate_excel_artifact') diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts index 2ed380fd..b1e02b10 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts @@ -147,6 +147,8 @@ function notice(businessNo: string, poNumber: string, partNumber: string) { id: Number(businessNo.slice(-2)), task_no: `SN-${businessNo}`, business_no: businessNo, item_kind: 'task', todo_ref: `SN-${businessNo}`, source_type: 'post_ot_fulfillment_wave', po_number: poNumber, customer_name: 'Customer', upload_status: 'pending', + // 后端 SUMMARY 契约:下载能力与导出端点同一谓词(创建者或管理员)。 + can_download_export: true, ui_state: { stage: { code: 'freight_upload', label: '货代上传' }, lifecycle_entries: [] }, notice_line_summary: [ { line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' }, diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue index 86ceccde..14adec40 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue @@ -38,7 +38,7 @@ import { useShippingTodoBadge } from '../composables/useShippingTodoBadge'; import { useMessage } from '@/shared/composables/useMessage'; import { BusinessError } from '@/shared/api/client'; import { - isFreightUploadRow, + isBatchDownloadableRow, lifecycleStageCodeOf, todoItemKey, type LifecycleStageCode, @@ -134,8 +134,8 @@ const filteredTasks = computed(() => ( ? tasks.value : tasks.value.filter((item) => lifecycleStageCodeOf(item) === lifecycleStageFilter.value) )); -/** 批量可选行:货代上传阶段的正式 Notice(业务约束:批量仅该阶段可用)。 */ -const selectableRows = computed(() => filteredTasks.value.filter((item) => isFreightUploadRow(item))); +/** 批量可选行:货代上传阶段的正式 Notice 且当前用户可下载(与批量导出端点同口径)。 */ +const selectableRows = computed(() => filteredTasks.value.filter((item) => isBatchDownloadableRow(item))); const selectedBusinessNoSet = computed(() => new Set(selectedBusinessNos.value)); /** 当前桶是否为通知完成明细报表视图。 */ @@ -366,7 +366,7 @@ async function loadTodos(resetPage = false, options?: { silent?: boolean }) { tasks.value = result.items || []; const visibleBusinessNos = new Set( tasks.value - .filter((item) => isFreightUploadRow(item)) + .filter((item) => isBatchDownloadableRow(item)) .map((item) => String(item.business_no || '').trim()), ); selectedBusinessNos.value = selectedBusinessNos.value.filter((value) => visibleBusinessNos.has(value)); diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskDrawer.vue b/frontend/src/features/workspace/shipping-task-center/ShippingTaskDrawer.vue index 5a269e8d..4ea27178 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskDrawer.vue +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskDrawer.vue @@ -137,6 +137,9 @@ const exportFileName = computed(() => String( props.item?.artifact_summary?.export_file_name || '', )); +/** 下载能力由后端统一谓词下发(创建者或管理员);缺失按不可下载处理。 */ +const canDownloadExport = computed(() => props.item?.can_download_export === true); + const lineRows = computed(() => { const item = props.item as ShippingTaskSummary | null; return Array.isArray(item?.notice_line_summary) ? item!.notice_line_summary : []; @@ -376,7 +379,7 @@ onBeforeUnmount(() => document.removeEventListener('keydown', onEsc)); {{ $t('chat.shippingOrderReview.autoProgress.retryStp') }} (); const selectedSet = computed(() => new Set(props.selectedBusinessNos || [])); -const selectableRows = computed(() => props.items.filter((item) => isFreightUploadRow(item))); +/** 复选框与全选状态消费同一可下载谓词,保证"能勾的都能下单成功"。 */ +const selectableRows = computed(() => props.items.filter((item) => isBatchDownloadableRow(item))); const hasSelection = computed(() => (props.selectedBusinessNos?.length || 0) > 0); const allSelectableChecked = computed(() => ( selectableRows.value.length > 0 @@ -158,7 +159,7 @@ function onToggleAll(): void { >