Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-18 15:08:38 +08:00
commit 0e4e581f9a
89 files changed
+7559 -816

No files matched your search

+2
View File
@@ -142,6 +142,8 @@ SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=data/shipping_notice/freight_receipt_rpa/receipt_drop
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/shipping_notice/freight_receipt_rpa/receipt_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
+2
View File
@@ -147,6 +147,8 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_drop
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
+2
View File
@@ -171,6 +171,8 @@ SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
# AWS 库存列映射(可选 JSON 字符串)
@@ -29,7 +29,7 @@ class ShippingReceiptReportConfig(Base):
inventory_source_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
@@ -40,10 +40,7 @@ class ShippingReceiptReportConfig(Base):
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# DBS 可包含多个 Warehouse;Crane 固定 Inbound Details,保留空数组。
warehouse_ids_json: Mapped[list[str]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# 与库存同构:Warehouse 是查询条件之一(支持多值),逐仓拆分在排程/触发时由该条件运行时派生,不单独持久化仓库清单。
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
@@ -67,19 +67,6 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
return dict(value)
def _json_string_list(data: dict[str, Any], field: str) -> list[str]:
"""读取非空、去重的字符串列表,供 Source 别名等业务配置使用。"""
value = data.get(field, [])
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
result: list[str] = []
for item in value:
normalized = item.strip()
if normalized and normalized not in result:
result.append(normalized)
return result
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
value = data.get('login_config_json', {})
@@ -269,19 +256,18 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
return {
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
'id': config.id, 'inventory_source_id': config.inventory_source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
'config_version': config.config_version,
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
}
def _validate_receipt_report_config(
source: ShippingInventorySource, data: dict[str, Any],
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
enabled = _bool(data, 'enabled', True)
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
try:
parameters = _validate_query_parameters(data)
except ValidationError as exc:
@@ -289,19 +275,22 @@ def _validate_receipt_report_config(
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
raw_path = _json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = _validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
if enabled and not raw_warehouses:
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
return enabled, path, parameters, raw_warehouses
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
if len(warehouse_conditions) != 1 or not any(warehouse_values):
raise ValidationError(
'DBS receipt report requires exactly one Warehouse query condition with values',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return path, parameters
if source.connector_type == 'crane':
if raw_warehouses:
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if parameters:
@@ -309,7 +298,7 @@ def _validate_receipt_report_config(
'Crane receipt report does not support query parameters',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return enabled, {'report_name': 'Inbound Details'}, [], []
return {'report_name': 'Inbound Details'}, []
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
@@ -327,7 +316,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
path, parameters = _validate_receipt_report_config(source, data)
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
before = _receipt_report_config_payload(config) if config else None
is_new = config is None
@@ -337,10 +326,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
db.session.add(config)
else:
config.config_version += 1
config.enabled = enabled
config.report_path_json = path
config.query_parameters_json = parameters
config.warehouse_ids_json = warehouses
config.updated_by = actor_id
db.session.flush()
after = _receipt_report_config_payload(config)
@@ -1,19 +1,20 @@
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:file_preparation / erp_adapter / precheck_service / models。
逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属
(Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。
依赖:movement_file_repository / gateway_adapter / precheck_service / models。
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;ERP 访问走 CapabilityGateway(绑定缺失时 fail-closed)。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
RouteNotResolvedError,
@@ -21,28 +22,6 @@ from app.services.in_transit_transfer.precheck_service import (
TransferDeps,
)
RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN"
class ReceiptRowsNotFrozenError(AppError):
"""收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。"""
def __init__(self, message: str = "receipt file row contract not frozen"):
super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ShippingReceiptFileRepository:
"""默认收料 ready 文件仓库(只读复用 shipping 收料归档)。
行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。"""
raise ReceiptRowsNotFrozenError(
"receipt file rows unfrozen: sample/sheet contract required (Q3)"
)
class DefaultRouteResolver:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
@@ -86,7 +65,7 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/ERP 网关)。"""
if _override is not None:
return _override
return TransferDeps(
@@ -98,21 +77,19 @@ def get_transfer_dependencies() -> TransferDeps:
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from flask import current_app
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
trigger_dir = str(
current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or ""
).strip()
if not trigger_dir:
return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"}
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
return {
"ok": bool(outcome.get("ok")),
"callback_id": outcome.get("callback_id"),
"error_code": outcome.get("error_code"),
"error_message": outcome.get("error_message"),
}
@@ -6,7 +6,9 @@
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、openpyxl。
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域字段 + 溯源字段
(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整校验由下游
file_parser 完成。
"""
from __future__ import annotations
@@ -31,14 +33,14 @@ class ShippingReceiptFileRepository:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
@@ -85,7 +87,8 @@ def _extract_movement_rows(
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。
输出以领域字段 code 为 key 的行,并附带溯源字段(sheet=实际使用的工作表标题、
row_no=数据行在工作表中的真实 1-based 行号),供 file_parser.parse_movement_rows 校验。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
@@ -112,7 +115,15 @@ def _extract_movement_rows(
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
return [_map_header_row(headers, row, header_to_code) for row in data_rows]
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
sheet_title = str(ws.title or '').strip()
return [
{"sheet": sheet_title, "row_no": header_idx + 2 + offset,
**_map_header_row(headers, row, header_to_code)}
for offset, row in enumerate(data_rows)
]
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
@@ -37,6 +37,7 @@ from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_movement_rows,
parse_receipt_rows,
)
from app.services.in_transit_transfer.file_preparation import (
@@ -188,7 +189,9 @@ def run_precheck(
"file_version": ready_file.file_version,
"checksum": ready_file.checksum,
}
parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows)
# 真实仓库(movement_file_repository)产出 movement 领域字段行
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
source_items = _precheck_invoices(
invoices=invoices,
@@ -9,7 +9,7 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, timedelta
from app import db
from app.models import TransferSourceJob
@@ -55,3 +55,33 @@ def advance_source_job_from_receipt_callback(
job.finished_at = datetime.utcnow()
db.session.flush()
return job
def recover_stale_waiting_source_jobs() -> int:
"""把超过收料回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与收料超时回收同批调用;
不自动重试 RPA——用户可在来源选择卡手动重试(与收料回收"绝不自动重试"口径一致)。
Returns:
本次回收的任务数。
"""
from flask import current_app
try:
timeout = max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
timeout = 900
cutoff = datetime.utcnow() - timedelta(seconds=timeout)
stale = (
TransferSourceJob.query
.filter(TransferSourceJob.status == _WAITING_RPA_CALLBACK, TransferSourceJob.updated_at < cutoff)
.all()
)
for job in stale:
job.status = _FAILED
job.error_code = 'RPA_RECEIPT_CALLBACK_TIMEOUT'
job.error_message = f'receipt rpa callback not received within {timeout}s'
job.finished_at = datetime.utcnow()
if stale:
db.session.commit()
return len(stale)
@@ -2,10 +2,11 @@
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models。
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
写 trigger writer 可注入替身(测试)。
写 trigger 失败把单元行标 failed 并 commit;写 trigger writer 可注入替身(测试)。
"""
from __future__ import annotations
@@ -23,27 +24,29 @@ def _build_trigger_unit(
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is None:
raise RuntimeError(f'receipt config missing: {source_code}')
profile = source.rpa_profile
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses else None
# Warehouse 条件即逐仓拆分维度:按需触发取第一个仓,单元快照剥离 Warehouse 条件。
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses and warehouses[0] else None
snapshot = {
'config_id': config.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'query_parameters_json': receipt_unit_parameters(config),
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return {
'unit_run_id': 0,
'inventory_source_id': source.id,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
@@ -71,7 +74,7 @@ def trigger_receipt_rpa(
reason: str = 'transfer_retry_receipt',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源收料 RPA 抓取。
"""触发一次来源收料 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
Args:
source_code: 来源实例编码。
@@ -83,13 +86,33 @@ def trigger_receipt_rpa(
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
"""
try:
unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
from app import db
from app.models import ShippingReceiptRpaUnitRun
unit = ShippingReceiptRpaUnitRun(
schedule_run_id=0, # 调拨触发无 ScheduleRun,沿用 0 占位约定
inventory_source_id=unit_payload['inventory_source_id'],
source_code=unit_payload['source_code'],
connector_type=unit_payload['connector_type'],
warehouse_id=unit_payload.get('warehouse_id'),
callback_id=unit_payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(unit_payload['config_snapshot']),
)
db.session.add(unit)
db.session.flush()
unit_payload['unit_run_id'] = unit.id
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
path = writer_fn(run_no, [unit], payload={
path = writer_fn(run_no, [unit_payload], payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'source_code': source_code,
@@ -97,5 +120,13 @@ def trigger_receipt_rpa(
'reason': reason,
})
if not path:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
db.session.commit()
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path}
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
unit.trigger_snapshot_json = unit_payload
db.session.commit()
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
@@ -7,7 +7,7 @@ from typing import Any
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values, write_receipt_export_batch_trigger
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
@@ -28,7 +28,7 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
wanted = _wanted_source_codes(task)
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
).filter(ShippingInventorySource.enabled.is_(True)).all()
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
@@ -37,7 +37,7 @@ def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportCo
callback_id = f'receipt:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [],
'report_path_json': config.report_path_json or {}, 'query_parameters_json': receipt_unit_parameters(config),
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return ShippingReceiptRpaUnitRun(
@@ -78,7 +78,8 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
units: list[ShippingReceiptRpaUnitRun] = []
for source, config in _eligible_sources(task):
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
for warehouse_id in warehouses:
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
unit.schedule_run_id = run.id
+1 -1
View File
@@ -57,7 +57,7 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
).filter(ShippingInventorySource.enabled.is_(True)).all()
return [{
'label': source.display_name or source.source_code, 'value': source.source_code,
'description': f'{source.connector_type} · 收料已配置',
@@ -371,6 +371,14 @@ def prepare_schedule_queue() -> int:
current_app.logger.warning("[schedule-worker] RPA cleanup warnings: %s", "; ".join(cleanup_warnings[:5]))
_worker_initialized = True
# 调拨来源等待回调 Job 的超时回收与下方 RPA 心跳告警同属每轮领取维护:
# 不能挂在 worker 启动一次性分支里,否则进程长期驻留期间超时任务永远无法终态化。
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
transfer_stale = recover_stale_waiting_source_jobs()
if transfer_stale:
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
@@ -0,0 +1,129 @@
"""
services/shipping_notice/effective_order_view.py
用途:向履约链提供「冻结快照 + 冻结后人工修正」的有效订单值视图。
依赖:export.order_field_id_values(冻结投影)、ShippingOrderFieldValue/ShippingOrderLine/
ShippingOrderTask/ShippingOrderSnapshot(修正事实与行对位)。
逻辑:快照仍是审计锚点,本模块把当前 accepted Extraction 的 FieldValue 按(行 position × field_id)
对位叠加到快照投影上,供库存匹配、Excel 导出与 Notice 行物化统一消费;整行替换(增删行)
后 position 不再可比,行级叠加保守跳过(保持冻结值),由后续行集有效视图统一承接。
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from app import db
from app.models import (
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSnapshot,
ShippingOrderTask,
)
from app.services.shipping_notice.export import order_field_id_values
def _owner_task(task: Any) -> Any:
"""与 export.order_field_id_values 同源的任务归属解析(Notice → OT;OT 原样返回)。"""
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id:
return db.session.get(ShippingOrderTask, order_task_id)
return task
def effective_order_field_values(task: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""
返回叠加了冻结后人工修正的订单 Header/Line 有效值(形状同 order_field_id_values)。
核心逻辑:以冻结快照为基线;当前 accepted Extraction 的 FieldValue 按(行 position ×
field_id)对位覆盖。当前 Extraction 与快照 Extraction 不同(发生过整行替换)时跳过
行级叠加,避免错位污染匹配键;单头值不受行替换影响,始终叠加最新已接受值。
Args:
task: ShippingNotice 或 ShippingOrderTask。
Returns:
(header dict[field_id, value], lines list[dict[field_id, value]])。
"""
header, lines = order_field_id_values(task)
owner = _owner_task(task)
current_id = getattr(owner, 'current_order_extraction_id', None)
if current_id is None:
return header, lines
snapshot = (
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
if getattr(owner, 'order_snapshot_id', None) else None
)
header = dict(header)
lines = [dict(row) for row in lines]
values = ShippingOrderFieldValue.query.filter_by(extraction_id=int(current_id)).all()
# [STEP 1] 单头修正:整行替换会把单头决定复制到新 Extraction(见 task_order_field_editor),
# 因此单头值始终以当前 Extraction 的已接受值为准。
for item in values:
if item.line_id is None:
header[str(item.field_id)] = item.value_json
# [STEP 2] 行级修正:仅在当前 Extraction 即冻结来源 Extraction 时按 position 对位。
if snapshot is not None and int(current_id) == int(snapshot.extraction_id):
position_by_line_id = {
int(row.id): int(row.position)
for row in ShippingOrderLine.query.filter_by(extraction_id=int(current_id)).all()
}
overlay_by_index: dict[int, dict[str, Any]] = {}
for item in values:
if item.line_id is None:
continue
index = position_by_line_id.get(int(item.line_id))
if index is None:
continue
overlay_by_index.setdefault(index, {})[str(item.field_id)] = item.value_json
for index, row in enumerate(lines):
row.update(overlay_by_index.get(index, {}))
return header, lines
def _coerce_qty(value: Any) -> Decimal | None:
"""把字段值安全转为数量;空/非法值返回 None。"""
if value in (None, ''):
return None
try:
return Decimal(str(value).replace(',', '').strip())
except (InvalidOperation, ValueError, TypeError):
return None
def effective_line_facts_for_notice(owner: ShippingOrderTask) -> dict[int, dict[str, Any]]:
"""
按 snapshot_line_id 返回 Notice 行物化所需的有效事实(强类型键 + 完整字段值)。
核心逻辑:经 effective_order_field_values 取有效值后,按冻结履约规则的
required_field_ids 把 part_number/reservation_id/qty 三个用途键解析为强类型事实;
缺少规则映射时对应键为 None(由消费方回退冻结列)。
Args:
owner: 已冻结订单的 ShippingOrderTask。
Returns:
{snapshot_line_id: {'part_number', 'reservation_id', 'qty', 'field_values'}}。
Raises:
ValueError: 任务没有冻结快照。
"""
snapshot = (
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
if getattr(owner, 'order_snapshot_id', None) else None
)
if snapshot is None:
raise ValueError('任务没有可用于通知行物化的冻结订单快照')
_header, lines = effective_order_field_values(owner)
required_ids = (snapshot.rule_versions_json or {}).get('fulfillment_rule', {}).get('required_field_ids')
required_ids = required_ids if isinstance(required_ids, dict) else {}
part_fid = str(required_ids.get('part_number') or '')
rsv_fid = str(required_ids.get('reservation_id') or '')
qty_fid = str(required_ids.get('qty') or '')
facts: dict[int, dict[str, Any]] = {}
for line_orm, values in zip(snapshot.lines, lines, strict=True):
facts[int(line_orm.id)] = {
'part_number': values.get(part_fid) if part_fid else None,
'reservation_id': values.get(rsv_fid) if rsv_fid else None,
'qty': _coerce_qty(values.get(qty_fid)) if qty_fid else None,
'field_values': dict(values),
}
return facts
+27 -2
View File
@@ -142,7 +142,10 @@ def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。
库存匹配/Excel 消费方应改用 effective_order_view.effective_order_field_values 获取含冻结后修正的有效值。
"""
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
assert_task_not_supersession_blocked(task)
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
@@ -779,7 +782,8 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
from app.services.shipping_notice.effective_order_view import effective_order_field_values
header_values, all_line_values = effective_order_field_values(task)
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
@@ -814,6 +818,26 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
for source_index, line in enumerate(snapshot.lines)
if source_index in release_overrides_by_source_line
}
# [STEP 1] 已结案(close_unfulfillable)行不再有履约要求:即使预约仍有库存,
# 也必须从滚动导出资格中剔除(与上方放行查询同源同口径:只认活动决定)。
closed_snapshot_line_ids = set()
if source_notice.id is not None:
closed_rows = (
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
)
.all()
)
closed_snapshot_line_ids = {
int(snapshot.lines[int(decision.line_index)].id)
for decision in closed_rows
if decision.line_index is not None
and 0 <= int(decision.line_index) < len(snapshot.lines)
}
selected_snapshot_line_ids = {
int(row.snapshot_line_id)
for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all()
@@ -824,6 +848,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
source_notice,
released_snapshot_line_ids=released_snapshot_line_ids,
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
closed_snapshot_line_ids=closed_snapshot_line_ids,
)
except ConflictError:
raise
@@ -718,12 +718,47 @@ def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
}
def _closed_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
"""读取当前任务已结案(close_unfulfillable)的冻结行 ID,供满足性与聚合豁免共用。
核心逻辑:与 ``_released_snapshot_line_ids_for_task`` 同源同口径——只认活动决定,
经 line_index 映射快照行;结案行不再是履约要求,在满足性/建单/导出各处按豁免处理。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
if task.id is None:
return set()
if not getattr(task, 'order_snapshot_id', None):
return set()
decisions = (
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
)
.all()
)
from app.models import ShippingOrderSnapshot
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if snapshot is None:
return set()
return {
int(snapshot.lines[int(row.line_index)].id)
for row in decisions
if row.line_index is not None
and 0 <= int(row.line_index) < len(snapshot.lines)
}
def match_completed(task: ShippingNotice) -> bool:
"""
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
已人工放行的短缺行视同满足(与 ``_recompute_task_match_aggregate`` 同源)。
已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求,
从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。
"""
from app.models import ShippingNoticeLineInventoryMatch
@@ -738,17 +773,23 @@ def match_completed(task: ShippingNotice) -> bool:
db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if getattr(task, 'order_snapshot_id', None) else None
)
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []}
closed_ids = _closed_snapshot_line_ids_for_task(task)
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []} - closed_ids
if not expected_line_ids:
# 全部行已结案:订单无剩余履约内容,不得自动进入建通知/Excel(应走作废流程)。
return False
current_line_ids = {
int(row.snapshot_line_id)
for row in rows
if getattr(row, 'snapshot_line_id', None) is not None
}
# 满足性必须覆盖冻结订单的全部项次;仅有部分当前 Match 不能代表整单可履约。
if expected_line_ids and current_line_ids != expected_line_ids:
} - closed_ids
# 满足性必须覆盖剩余待履约的全部项次;仅有部分当前 Match 不能代表整单可履约。
if current_line_ids != expected_line_ids:
return False
released_ids = _released_snapshot_line_ids_for_task(task)
for row in rows:
if getattr(row, 'snapshot_line_id', None) is not None and int(row.snapshot_line_id) in closed_ids:
continue
result = str(row.match_result or '').strip()
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
if result == 'matched' and shortage <= 0:
@@ -823,6 +864,7 @@ def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]:
_verification, line_ids = current_available_snapshot_line_ids(
_source_notice_for_order_facts(task),
released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task),
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
)
except ConflictError:
return set()
@@ -1344,6 +1386,8 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage)
且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂,
出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。
已结案(close_unfulfillable)行不再是履约要求:不阻断、不进缺货列表,
但也不计入满足(结案行非可履约内容),全结案 ⇒ unfulfillable,与 match_completed 口径一致。
"""
rows = (
ShippingNoticeLineInventoryMatch.query
@@ -1353,6 +1397,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
if not rows:
return 'unfulfillable', []
released_snapshot_line_ids = _released_snapshot_line_ids_for_task(task)
closed_snapshot_line_ids = _closed_snapshot_line_ids_for_task(task)
has_ok = False
has_block = False
shortages: list[dict[str, Any]] = []
@@ -1378,7 +1423,12 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
# 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。
shortage = _line_shortage_qty(shortage_qty)
released = entry['snapshot_line_id'] in released_snapshot_line_ids
if match_result == 'matched' and shortage <= 0:
closed = entry['snapshot_line_id'] in closed_snapshot_line_ids
if closed:
# [BE-结案-豁免] 结案行不再是履约要求:不阻断、不进缺货列表,
# 但也不计入满足(非可履约内容);全结案 ⇒ 无可履约内容 ⇒ unfulfillable。
entry['line_status'] = 'closed'
elif match_result == 'matched' and shortage <= 0:
entry['line_status'] = 'ok'
has_ok = True
elif released and shortage > 0:
@@ -1390,21 +1440,25 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
has_block = True
shortages.append(entry)
line_results.append(entry)
owner = _workflow_owner(task)
if hasattr(owner, 'step_payload_json'):
payload = dict(owner.step_payload_json or {})
payload['current_match_projection'] = {
'match_status': 'partial' if has_block and has_ok else ('unfulfillable' if has_block else 'fulfillable'),
'line_results': line_results,
'shortage': {'lines': shortages},
}
owner.step_payload_json = payload
# 结案行既不计满足也不阻断:无 ok 且无 block(如全结案)时无可履约内容 ⇒ unfulfillable,
# 与 match_completed 的整单口径保持一致,避免 Gate 同步误判满足后空转编排。
if has_block and has_ok:
status = 'partial'
elif has_block:
status = 'unfulfillable'
else:
elif has_ok:
status = 'fulfillable'
else:
status = 'unfulfillable'
owner = _workflow_owner(task)
if hasattr(owner, 'step_payload_json'):
payload = dict(owner.step_payload_json or {})
payload['current_match_projection'] = {
'match_status': status,
'line_results': line_results,
'shortage': {'lines': shortages},
}
owner.step_payload_json = payload
return status, shortages
@@ -1615,7 +1669,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if lang:
inv_payload["lang"] = lang
return ensure_inventory(inv_payload)
_order_header_values, order_field_lines = order_field_id_values(task)
# [STEP 2] 兜底匹配基线读取有效视图(冻结快照 + 冻结后人工修正):
# 匹配身份键(料号/预约等字段值)必须与展示值(__required_qty/__display_part_number)
# 同源,否则出现"按冻结料号匹配、却展示有效料号"的混合投影。
from app.services.shipping_notice.effective_order_view import effective_order_field_values
_order_header_values, order_field_lines = effective_order_field_values(task)
purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'})
for index, order_line in enumerate(order_field_lines):
purpose_line = purpose_lines[index] if index < len(purpose_lines) else {}
@@ -2039,6 +2097,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
_verification, available_line_ids = current_available_snapshot_line_ids(
_source_notice_for_order_facts(task),
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
)
except ConflictError:
available_line_ids = set()
@@ -508,6 +508,26 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str,
return out
def load_current_match_facts_by_line_index(task_id: int | None) -> dict[int, dict[str, Any]]:
"""按 line_index 索引当前匹配事实(Case 履约投影专用)。
核心逻辑:与 load_current_match_facts_by_task 同一查询;Case 草稿行只有
_line_index 没有 snapshot_line_id,必须按行号索引才能关联上事实。
"""
if task_id is None:
return {}
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.all()
)
return {
int(row.line_index): serialize_match_fact(row)
for row in rows
if row.line_index is not None
}
def aggregate_match_status_for_task(task_id: int | None) -> str | None:
"""根据当前行级 Match 聚合任务匹配状态,禁止读取 OT/Notice 缓存字段。"""
facts = list(load_current_match_facts_by_task(task_id).values())
@@ -21,6 +21,7 @@ def replace_notice_lines_from_snapshot(
snapshot: ShippingOrderSnapshot,
snapshot_line_ids: set[int] | None = None,
inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
line_overrides: dict[int, dict[str, Any]] | None = None,
) -> int:
"""
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
@@ -29,6 +30,10 @@ def replace_notice_lines_from_snapshot(
notice_id: shipping_notices.id。
snapshot: 已 flush 且带 lines 的 Snapshot。
snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。
inventory_facts_by_snapshot_line_id: 行级库存事实(来源/文件/仓库)。
line_overrides: effective_order_view.effective_line_facts_for_notice 的输出,
按 snapshot_line_id 携带冻结后人工修正;仅非 None 值覆盖快照列,
缺失或 None 时回退冻结快照值。
Returns:
写入行数。
@@ -44,6 +49,7 @@ def replace_notice_lines_from_snapshot(
continue
notice_position += 1
inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
override = (line_overrides or {}).get(int(line.id)) or {}
rows.append(
ShippingNoticeLine(
notice_id=int(notice_id),
@@ -51,13 +57,17 @@ def replace_notice_lines_from_snapshot(
position=notice_position - 1,
# 发货通知项次按当前通知单重新从 1 编排。
line_no=notice_position,
part_number=getattr(line, 'part_number', None),
reservation_id=getattr(line, 'reservation_id', None),
required_qty=getattr(line, 'qty', None),
part_number=override.get('part_number')
if override.get('part_number') is not None else getattr(line, 'part_number', None),
reservation_id=override.get('reservation_id')
if override.get('reservation_id') is not None else getattr(line, 'reservation_id', None),
required_qty=override.get('qty')
if override.get('qty') is not None else getattr(line, 'qty', None),
inventory_source_code=inventory_facts.get('inventory_source_code'),
inventory_file_id=inventory_facts.get('inventory_file_id'),
inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'),
field_values_json=dict(getattr(line, 'field_values_json', None) or {}),
field_values_json=dict(override['field_values'])
if override.get('field_values') else dict(getattr(line, 'field_values_json', None) or {}),
created_at=now,
)
)
@@ -2,7 +2,7 @@
services/shipping_notice/order_field_purposes.py
用途:将冻结订单 Snapshot 按冻结货代策略能力投影给履约链。
依赖:冻结履约策略、export.order_field_id_values、ShippingNotice。
依赖:冻结履约策略、effective_order_view.effective_order_field_values、ShippingNotice。
逻辑:路由、门禁、匹配和展示只通过固定规则冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。
"""
@@ -12,7 +12,8 @@ from typing import Any
from app import db
from app.models import ShippingOrderSnapshot, ShippingNotice
from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values
from app.services.shipping_notice.effective_order_view import effective_order_field_values
from app.services.shipping_notice.export import _source_notice_for_order_facts
_PURPOSE_BY_CAPABILITY = {
@@ -47,9 +48,9 @@ def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | No
def task_line_purpose_values(task: ShippingNotice, *, required: set[str] | None = None) -> list[dict[str, Any]]:
"""按订单行位置返回用途键值,值只来自冻结 Snapshot。"""
"""按订单行位置返回用途键值,值来自冻结 Snapshot 叠加冻结后人工修正的有效视图(effective_order_view)。"""
purpose_ids = task_line_purpose_field_ids(task, required=required)
_header, lines = order_field_id_values(task)
_header, lines = effective_order_field_values(task)
return [
{purpose: line.get(field_id) for purpose, field_id in purpose_ids.items()}
for line in lines
@@ -426,12 +426,20 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
]
def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None:
def _sync_confirmed_task_fulfillment_gates(
*,
case: ShippingOrderReviewCase,
actor_id: int,
trigger: str = 'inventory_shortage_released',
) -> None:
"""
短缺放行后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
短缺放行/行结案后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
核心逻辑:Gate 重投影不改写库存事实;复用既有 auto-fulfill Job,由 Job 再判断
是否恰好只有一条开放且可履约的明细。多条明细不会自动合并,仍由用户勾选创建 wave。
Args:
trigger: 编排触发标签(放行 inventory_shortage_released / 结案 line_fulfillment_closed)。
"""
task_id = getattr(case, 'confirmed_task_id', None)
if task_id is None:
@@ -469,7 +477,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
submit_auto_progress(
task=task,
trigger='inventory_shortage_released',
trigger=trigger,
operator_id=actor_id,
commit=False,
)
@@ -480,7 +488,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
enqueue_post_ot_auto_fulfill_job(
task_no=str(task.task_no),
trigger='inventory_shortage_released',
trigger=trigger,
commit=False,
)
@@ -763,7 +771,6 @@ def project_review_case_line_decisions(
"""
from app.services.shipping_notice.line_inventory_match_projection import (
line_auto_fulfill_enabled,
load_current_match_facts_by_task,
project_line_inventory_view,
)
from app.services.shipping_notice.order_review_workbench_projection import (
@@ -810,7 +817,11 @@ def project_review_case_line_decisions(
'status': 'resolving',
'source': 'inventory_source_clue',
}
match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
# [BE-键修复] Case 草稿行只有 _line_index;补一条按行号索引的事实通道。
from app.services.shipping_notice.line_inventory_match_projection import (
load_current_match_facts_by_line_index,
)
match_facts_by_line = load_current_match_facts_by_line_index(formal_ot.get('task_id'))
labels = dict(source_labels or {})
if not labels:
draft = getattr(case, 'current_draft', None)
@@ -835,7 +846,12 @@ def project_review_case_line_decisions(
decision = by_key.get(key)
# 正式 OT 的库存数量以当前行匹配事实为准;草稿 validation_result 只保留
# 解析阶段投影,不能因为其中没有 available_qty 就错误阻断人工出单。
fact = match_facts.get(key)
# [BE-键修复] 草稿行只有 _line_index;旧实现误用 draft_line_id 查 snapshot_line_id 键,恒 miss。
line_index = draft_line.get('_line_index')
fact = (
match_facts_by_line.get(int(line_index))
if line_index is not None else None
)
fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {}
fulfill_proj = dict(proj)
if isinstance(fact, dict):
@@ -1083,7 +1099,7 @@ def decide_review_line_fulfillment(
case_no: Case 编号。
draft_line_id: 草稿行键。
decision_code: 决定码。
reason: 关闭/重开/短缺放行必填原因。
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
expected_draft_version: 可选草稿乐观锁。
actor_is_admin: 是否管理员(重开授权)。
@@ -1098,7 +1114,9 @@ def decide_review_line_fulfillment(
code='SHIPPING.REVIEW_LINE_DECISION_INVALID',
details={'decision_code': code},
)
if code in {DECISION_CLOSE, DECISION_REOPEN, DECISION_RELEASE_SHORTAGE} and not str(reason or '').strip():
# [BE-放行免因] 短缺放行不强制原因:人工放行事实已由审计链完整记录
# (操作人 + 时间 + 决定快照 release_field_values);结案/重开仍要求原因。
if code in {DECISION_CLOSE, DECISION_REOPEN} and not str(reason or '').strip():
raise ValidationError(
'Reason is required',
code='SHIPPING.REVIEW_LINE_DECISION_REASON_REQUIRED',
@@ -1239,8 +1257,13 @@ def decide_review_line_fulfillment(
db.session.add(row)
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
db.session.flush()
if code == DECISION_RELEASE_SHORTAGE:
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=int(user_id))
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
_sync_confirmed_task_fulfillment_gates(
case=case,
actor_id=int(user_id),
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
@@ -914,14 +914,12 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
'snapshot_after_ref',
'path_id_hash',
'revision_no',
# 独立收料报表配置快照:路径、受控条件与仓库清单均不含 selector、凭据或日期筛选。
# 独立收料报表配置快照:路径与受控条件(含 Warehouse 拆分条件)均不含 selector、凭据、日期筛选或启停字段。
'inventory_source_id',
'connector_type',
'enabled',
'config_version',
'report_path_json',
'query_parameters_json',
'warehouse_ids_json',
'file_id',
'recipient_user_id',
'message_type',
@@ -1468,8 +1468,8 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
order_task_id → ShippingOrderTask。有 OT 时用领域事实映射为
shipping_processing_status(与 shipping_processing_projection 同源),
并注入 shipping_processing_stage / progress_version / order_task_no;
另附带 review_run_no / owner_agent_id / conversation_id(经 OT.extraction_run),
供任务中心「进入订单处理」深链。
另附带 review_run_no / review_case_no / owner_agent_id / conversation_id(经 OT.extraction_run
与 OT 反查确认 Case),供任务中心「进入订单处理」深链。
Args:
task: ShippingNotice 或 ShippingOrderTask。
@@ -1517,6 +1517,19 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
data['conversation_id'] = cid
if data.get('owner_agent_id') is None and getattr(run, 'owner_agent_id', None) is not None:
data['owner_agent_id'] = int(run.owner_agent_id)
# [STEP 3] 注入确认 Case 号:工作台以 case_no 绑定工作项,OT 直链缺失该字段时
# 选法 2 不会拉 Case,任务详情身份链断裂、五阶段页签全锁(2026-09-17 工作台直链修复)。
# confirmed_task_id 唯一约束保证 OT→Case 至多一条,点查代价可忽略。
if order_task is not None and not str(data.get('review_case_no') or '').strip():
confirmed_case = (
ShippingOrderReviewCase.query
.filter_by(confirmed_task_id=int(order_task.id))
.first()
)
if confirmed_case is not None:
case_no = str(confirmed_case.case_no or '').strip()
if case_no:
data['review_case_no'] = case_no
def _enrich_task_center_fields(
@@ -1,4 +1,12 @@
"""收料 RPA callback 的原样归档服务。"""
"""收料 RPA callback 的原样归档服务。
用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线)。
依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、
audit_service、in_transit_transfer.receipt_callback_bridge(惰性导入)。
逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job;
桥是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
"""
from __future__ import annotations
@@ -35,6 +43,35 @@ def _read_receipt_callback_file(file_path: str) -> bytes:
return path.read_bytes()
def _advance_transfer_source_job(
unit: 'ShippingReceiptRpaUnitRun', *, ok: bool,
file_no: str | None = None, file_sha256: str | None = None,
error_code: str | None = None, error_message: str | None = None,
) -> None:
"""收料回调终态推进调拨来源任务;失败只记日志,绝不回滚收料归档终态。
Args:
unit: 已落终态的收料单元行(用其 source_code 定位调拨任务)。
ok: 回调是否成功(True 仅在 success 且带 file_no 时推进 file_ready)。
file_no / file_sha256: success 时绑定的归档文件号与指纹。
error_code / error_message: 失败时的错误码与描述。
"""
try:
from app import db
from app.services.in_transit_transfer.receipt_callback_bridge import advance_source_job_from_receipt_callback
advanced = advance_source_job_from_receipt_callback(
source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256,
callback_ok=ok, error_code=error_code, error_message=error_message,
)
if advanced is not None:
# 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交,
# 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。
db.session.commit()
except Exception as exc: # noqa: BLE001 —— 桥是记账,不是收料链路的正确性依赖
from flask import current_app
current_app.logger.warning('[receipt-callback] advance transfer source job failed: %s', exc)
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
"""幂等接收单个收料单元回调,原样归档三年且不写库存快照表。"""
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
@@ -55,6 +92,7 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
metadata={'callback_status': status},
)
db.session.commit()
_advance_transfer_source_job(unit, ok=False, error_code='RPA_RECEIPT_EMPTY', error_message='receipt export empty')
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
return {'unit_run_id': unit.id, 'status': 'empty'}
@@ -68,6 +106,7 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
metadata={'callback_status': status},
)
db.session.commit()
_advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
return {'unit_run_id': unit.id, 'status': 'failed'}
@@ -88,6 +127,7 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
db.session.flush()
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
db.session.commit()
_advance_transfer_source_job(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
deliver_receipt_file(record.id)
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
@@ -18,6 +18,35 @@ def receipt_trigger_dir() -> Path | None:
return Path(value) if value else None
def receipt_warehouse_values(config: Any) -> list[str]:
"""从收料配置的查询条件中提取 Warehouse 条件值(去空去重,保持顺序)。
Warehouse 条件即逐仓拆分维度(与库存配置同构,不单独持久化仓库清单);
排程/触发按返回值逐仓展开执行单元。DBS 配置由校验保证恰一条非空条件。
"""
values: list[str] = []
for item in (config.query_parameters_json or []):
if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse':
continue
for raw in (item.get('values') or []):
cleaned = str(raw or '').strip()
if cleaned and cleaned not in values:
values.append(cleaned)
return values
def receipt_unit_parameters(config: Any) -> list[dict[str, Any]]:
"""构建单个执行单元的受控条件:剥离 Warehouse 条件。
Worker 会按单元的 warehouse_id 自动追加单值 Warehouse 条件,
快照里保留用户维护的 Warehouse 条件会与之重复冲突。
"""
return [
dict(item) for item in (config.query_parameters_json or [])
if not (isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse')
]
def write_receipt_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
"""写入收料批量 trigger;worker 仅允许消费 shipping_receipt_rpa.v1。"""
trigger_dir = receipt_trigger_dir()
@@ -2,8 +2,9 @@
services/shipping_notice/reservation_service.py
用途:管理冻结订单预约单的注册、库存核验轮次和滚动制单占用。
依赖:ShippingOrderSnapshot、履约 ORM、统一 AppError。
逻辑:每轮核验追加记录;只有本轮全部满足的预约单可被同一事务选择并绑定到一个新 Artifact。
依赖:ShippingOrderSnapshot、effective_order_view(有效订单值视图)、履约 ORM、统一 AppError。
逻辑:预约身份按「冻结快照 + 冻结后已接受人工修正」的有效值注册;每轮核验追加记录;
只有本轮全部满足的预约单可被同一事务选择并绑定到一个新 Artifact。
"""
from __future__ import annotations
@@ -40,17 +41,37 @@ def _decimal(value: Any) -> Decimal:
def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservation]:
"""由冻结 Snapshot 注册全局预约号;同 PO 的变更只能作为人工修订候选。"""
"""
由有效订单视图(冻结快照 + 已接受人工修正)注册全局预约号;同 PO 的料号/数量
变更按同一 OT 确认修订自动接替,跨任务或已占用预约仍走人工复核/锁定拒绝。
核心逻辑:预约身份(预约号/料号/数量)以 effective_line_facts_for_notice 的有效值为准;
否则就地编辑料号/数量后,重匹配写入的有效值与按冻结列注册的预约不一致,
核验比对必抛 RESERVATION_MISMATCH 使核验轮次无法创建、任务卡死。
行集替换等无法按行对位的场景(ValueError)保守回退冻结快照列,
由行集有效视图特性统一承接。
"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
if snapshot is None:
raise ValidationError('Frozen order snapshot is required', code='SHIPPING.ORDER_SNAPSHOT_REQUIRED')
po_number = normalize_po_number(snapshot.customer_po_number).upper()
# [BE-有效视图] 延迟导入避免与 export 的模块级循环依赖(export 反向惰性引用本模块)。
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
try:
effective_facts = effective_line_facts_for_notice(task)
except ValueError:
effective_facts = {}
registered: list[ShippingReservation] = []
seen: set[str] = set()
for line in snapshot.lines:
reservation_id = validated_reservation_id(line.reservation_id)
part_number = str(line.part_number or '').strip()
if not reservation_id or not part_number or line.qty is None:
eff = effective_facts.get(int(line.id)) or {}
# 有效事实优先,None(无规则映射/值非法)回退冻结快照列。
effective_reservation_id = eff.get('reservation_id') if eff.get('reservation_id') is not None else line.reservation_id
effective_part_number = eff.get('part_number') if eff.get('part_number') is not None else line.part_number
effective_qty = eff.get('qty') if eff.get('qty') is not None else line.qty
reservation_id = validated_reservation_id(effective_reservation_id)
part_number = str(effective_part_number or '').strip()
if not reservation_id or not part_number or effective_qty is None:
raise ValidationError('Reservation id, part number and quantity are required', code='SHIPPING.RESERVATION_INVALID')
if reservation_id in seen:
raise ConflictError('Reservation is duplicated in the frozen order', code='SHIPPING.RESERVATION_DUPLICATED_IN_ORDER')
@@ -59,7 +80,7 @@ def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservatio
if row is None:
row = ShippingReservation(
task_id=task.id, snapshot_line_id=line.id, reservation_id=reservation_id,
po_number_normalized=po_number, part_number=part_number, required_qty=_decimal(line.qty), status='pending',
po_number_normalized=po_number, part_number=part_number, required_qty=_decimal(effective_qty), status='pending',
)
db.session.add(row)
elif not po_number:
@@ -77,15 +98,16 @@ def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservatio
row.task_id != task.id
or row.snapshot_line_id != line.id
or row.part_number != part_number
or row.required_qty != _decimal(line.qty)
or row.required_qty != _decimal(effective_qty)
):
if row.current_artifact_id is not None or row.status in {'artifact_reserved', 'uploaded'}:
raise ConflictError('Reservation cannot be revised after export or upload', code='SHIPPING.RESERVATION_REVISION_LOCKED')
if row.part_number != part_number or row.required_qty != _decimal(line.qty):
if row.part_number != part_number or row.required_qty != _decimal(effective_qty):
# 同一 OT 的确认修订复用该 OT(仅 bump order_data_version/progress_version),
# Reservation 与审计事件仍指向该 OT,不新建任务;跨任务变更须人工复核。
# [BE-有效视图] 编辑料号/数量后的差异在此自动完成接替,核验得以继续。
if row.task_id == task.id:
_transfer_confirmed_revision(row, task=task, line=line, part_number=part_number)
_transfer_confirmed_revision(row, task=task, line=line, part_number=part_number, qty=effective_qty)
registered.append(row)
continue
raise ConflictError(
@@ -95,7 +117,7 @@ def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservatio
'reservation_id': reservation_id,
'registered_task_id': row.task_id,
'previous': {'part_number': row.part_number, 'qty': str(row.required_qty)},
'proposed': {'part_number': part_number, 'qty': str(_decimal(line.qty))},
'proposed': {'part_number': part_number, 'qty': str(_decimal(effective_qty))},
},
)
raise ConflictError('Reservation is already registered by another order version', code='SHIPPING.RESERVATION_ALREADY_REGISTERED')
@@ -120,12 +142,20 @@ def _transfer_confirmed_revision(
*, task: ShippingOrderTask,
line: Any,
part_number: str,
qty: Any | None = None,
) -> None:
"""
同一 OT 的已确认修订:复用该 OT(版本 bump),接替未履约 Reservation,并落 OT 级审计。
核心逻辑:修订不新建任务行;仅递增 ``order_data_version`` / ``progress_version``,
Reservation 与 ShippingTaskEvent 均保持指向该 OT,避免写入 Notice id 造成错误外键。
Args:
reservation: 待接替的未履约预约单。
task: 当前归属 OT(或可解析到 OT 的任务)。
line: 预约对应的冻结快照行(修订后 snapshot_line_id 仍指向该行)。
part_number: 有效料号(已 strip)。
qty: 有效数量;缺省时回退冻结行数量 ``line.qty``(供既有调用方兼容)。
"""
owner = _owner_task(task)
previous = {
@@ -140,7 +170,8 @@ def _transfer_confirmed_revision(
reservation.task_id = owner.id
reservation.snapshot_line_id = line.id
reservation.part_number = part_number
reservation.required_qty = _decimal(line.qty)
# [BE-有效视图] 数量以有效值为准;行集替换等回退场景沿用冻结行数量。
reservation.required_qty = _decimal(qty if qty is not None else line.qty)
reservation.status = 'pending'
reservation.current_artifact_id = None
details = {
@@ -175,11 +206,13 @@ def record_inventory_verification(
reservation_id = validated_reservation_id(item.get('reservation_id'))
part_number = str(item.get('part_number') or '').strip()
reservation = by_key.get(reservation_id)
if reservation is None or reservation.part_number != part_number:
# [BE-有效视图] 料号比对两侧归一化(strip + upper):匹配结果与注册值可能仅存在
# 大小写/空白差异,直接比较会造成假阳性 RESERVATION_MISMATCH 阻断核验。
if reservation is None or str(reservation.part_number or '').strip().upper() != str(part_number or '').strip().upper():
raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
required = _decimal(item.get('required_qty'))
# The frozen order is the quantity authority. A reduced or duplicate result
# must not turn an insufficient reservation into an exportable line.
# [BE-有效视图] 数量权威是按有效订单值视图注册的预约值(非冻结快照列);
# 缩量/重复的核验结果不得把短缺行升级为可导出行。
if reservation_id in seen_reservation_ids or required != reservation.required_qty:
raise ValidationError('Inventory result quantity is inconsistent with the frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
seen_reservation_ids.add(reservation_id)
@@ -277,6 +310,7 @@ def current_available_snapshot_line_ids(
*,
released_snapshot_line_ids: set[int] | None = None,
selected_snapshot_line_ids: set[int] | None = None,
closed_snapshot_line_ids: set[int] | None = None,
) -> tuple[ShippingInventoryVerification, set[int]]:
"""
取得最新核验中可导出的冻结订单行。
@@ -288,6 +322,7 @@ def current_available_snapshot_line_ids(
task: 当前正式发货任务。
released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。
selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时仅返回该集合。
closed_snapshot_line_ids: 已结案冻结行 ID;无论库存状态一律从可导出集合剔除。
Returns:
(最新核验轮次, 本次可导出的冻结订单行 ID)。
@@ -323,10 +358,11 @@ def current_available_snapshot_line_ids(
ShippingReservation.status.in_({'available', 'pending'}),
).all() if reservation_ids else []
selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())}
closed_ids = {int(item) for item in (closed_snapshot_line_ids or set())}
line_ids = {
item.snapshot_line_id for item in reservations
if not selected_ids or int(item.snapshot_line_id) in selected_ids
}
} - closed_ids
if not line_ids:
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
return verification, line_ids
@@ -1,12 +1,13 @@
"""
services/shipping_notice/schema_edit_policy.py
用途:正式任务字段编辑策略(Schema 显式放行;无策略默认只读;Excel ready 硬冻结)。
用途:正式任务字段编辑策略(状态制:无策略默认可写;显式 editable=False 反向锁;Excel ready 硬冻结)。
依赖:task_order_field_editor(锁定 Schema)、ShippingExportArtifact、ConflictError;
被 task_workflow / 复核 formal patch / 投影 formal_editable_field_ids 引用。
逻辑:默认 editable_after_task_creation=False;仅 Schema editable=True 可写;
Excel ready = ready Artifact 匹配路径 + 可选 order_data_version 指纹;
change_effect 供 task_workflow 下游失效编排消费。不考虑 legacy 白名单兼容绕过。
逻辑:默认 editable_after_task_creation=True(建单后 Excel 生成前可编辑);
仅 Schema 显式 editable=False 反向关闭;Excel ready = ready Artifact 匹配路径 +
可选 order_data_version 指纹;change_effect 供 task_workflow 下游失效编排消费。
不考虑 legacy 白名单兼容绕过。
"""
from __future__ import annotations
@@ -18,8 +19,8 @@ from app.core.errors import ConflictError
if TYPE_CHECKING:
from app.models import ShippingNotice
# 默认:创建正式任务后字段不可编辑。
DEFAULT_EDITABLE_AFTER_TASK_CREATION: Final[bool] = False
# 默认:建单后 Excel 生成前字段可编辑(状态制);个别字段需要锁定时在 Schema 配置 editable=false 反向关闭。
DEFAULT_EDITABLE_AFTER_TASK_CREATION: Final[bool] = True
# 允许的 change_effect。
ALLOWED_CHANGE_EFFECTS: Final[frozenset[str]] = frozenset({
@@ -36,7 +37,7 @@ _AUDIT_VALUE_MAX_CHARS: Final[int] = 256
def field_task_edit_policy(field_config: dict[str, Any] | None) -> dict[str, Any]:
"""
读取 Schema 字段上的 task_edit_policy;缺省返回安全只读策略。
读取 Schema 字段上的 task_edit_policy;无策略时按状态制默认(Excel ready 前可写)。
Args:
field_config: Schema 单字段配置。
@@ -46,7 +47,8 @@ def field_task_edit_policy(field_config: dict[str, Any] | None) -> dict[str, Any
"""
raw = field_config.get('task_edit_policy') if isinstance(field_config, dict) else None
policy = dict(raw) if isinstance(raw, dict) else {}
editable = bool(policy.get('editable')) if policy else False
# 无策略时初始化为全局默认开关;显式 editable=false 的反向锁优先于默认值。
editable = bool(policy.get('editable')) if policy else DEFAULT_EDITABLE_AFTER_TASK_CREATION
if not DEFAULT_EDITABLE_AFTER_TASK_CREATION and 'editable' not in policy:
editable = False
effect = str(policy.get('change_effect') or 'none').strip() or 'none'
@@ -98,7 +100,8 @@ def is_field_editable_for_formal_task(
"""
判断正式任务下该字段是否可编辑。
核心逻辑:Excel ready 时一律不可编辑;否则必须 Schema 显式 editable=True;
核心逻辑:Excel ready 时一律不可编辑;否则按状态制默认可写,
仅 Schema 显式 editable=False 反向关闭;
若 editable_until=excel_ready 且 Excel 已就绪则关闭(与全局冻结一致)。
Args:
@@ -182,7 +185,7 @@ def is_formal_field_code_editable(
"""
判断正式任务下 field_code 是否允许写入。
核心逻辑:仅 Schema 显式 editable=True 且未 Excel 冻结时放行;无 legacy 白名单。
核心逻辑:未 Excel 冻结时按状态制默认放行,仅 Schema 显式 editable=False 反向关闭;无 legacy 白名单。
Args:
task: 目标 ShippingNotice。
@@ -18,6 +18,7 @@ from app.models import (
ShippingOrderTask,
ShippingOrderSnapshot,
)
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
from app.services.shipping_notice.tool_common import generate_task_no
@@ -34,6 +35,10 @@ def create_shipping_notice_after_inventory_gate(
【触发时机】:库存准备成功、所有目标订单行匹配成功或已人工放行,且即将生成 Excel 时。
不得在接收解析或订单复核确认阶段调用。
核心逻辑:通知行物化使用 effective_order_view 的有效行事实,携带冻结后人工修正值。
已结案(close_unfulfillable)行从目标行集剔除,不参与门禁也不写入通知行;
全部行结案时 target_ids 为空仍按门禁未通过拒绝。
Args:
order_task: 已冻结订单快照的 OT。
snapshot_line_ids: 可选的本次通知行集合;为空表示整单。
@@ -87,10 +92,15 @@ def create_shipping_notice_after_inventory_gate(
fact_rows = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(order_task.id), is_current=True,
).all()
target_ids = selected_ids or {int(line.id) for line in snapshot.lines}
by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None}
from app.services.shipping_notice.fulfillment_workflow import _released_snapshot_line_ids_for_task
from app.services.shipping_notice.fulfillment_workflow import (
_closed_snapshot_line_ids_for_task,
_released_snapshot_line_ids_for_task,
)
released_ids = _released_snapshot_line_ids_for_task(order_task)
# [BE-结案-豁免] 结案行不再是履约要求:从目标行集剔除,不参与门禁、不物化为通知行。
closed_ids = _closed_snapshot_line_ids_for_task(order_task)
target_ids = (selected_ids or {int(line.id) for line in snapshot.lines}) - closed_ids
if not target_ids or any(
int(line_id) not in by_line
or (
@@ -154,7 +164,9 @@ def create_shipping_notice_after_inventory_gate(
replace_notice_lines_from_snapshot(
notice_id=int(notice.id),
snapshot=snapshot,
snapshot_line_ids=selected_ids,
# [BE-结案-豁免] 物化行集必须与门禁通过的 target_ids 一致:结案行不写入通知行。
snapshot_line_ids=target_ids,
inventory_facts_by_snapshot_line_id=inventory_facts_by_snapshot_line_id,
line_overrides=effective_line_facts_for_notice(order_task),
)
return notice
@@ -9,6 +9,7 @@ services/shipping_notice/task_order_field_editor.py
from __future__ import annotations
from datetime import date
from decimal import Decimal, InvalidOperation
from typing import Any
@@ -177,6 +178,19 @@ def _normalized_value(value: Any, config: dict[str, Any]) -> Any:
return str(value).strip()
def _json_value(value: Any) -> Any:
"""把人工输入转为 JSON 列可序列化形状;与 order_schema.runtime._json_value 对齐。
核心逻辑:Decimal → format(normalize, 'f') 字符串(保留精度且 json.dumps 可序列化),
date → isoformat;其余原样。类型化列(value_decimal 等)仍保存原生值。
"""
if isinstance(value, Decimal):
return format(value.normalize(), 'f')
if isinstance(value, date):
return value.isoformat()
return value
def _field_value_columns(value: Any, value_type: str) -> dict[str, Any]:
"""生成唯一 FieldValue 的类型化列,JSON 值始终作为下游读取的统一入口。"""
return {
@@ -185,7 +199,7 @@ def _field_value_columns(value: Any, value_type: str) -> dict[str, Any]:
'value_integer': value if value_type == 'integer' else None,
'value_date': value if value_type == 'date' else None,
'value_boolean': value if value_type == 'boolean' else None,
'value_json': value,
'value_json': _json_value(value),
}
@@ -222,7 +236,7 @@ def replace_current_line_field_value(*, task: ShippingNotice, position: int, fie
raise ConflictError('Order field decision is unavailable', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
# 人工复核后的值成为当前决策真相,保留原 Observation 与冲突审计链。
decision.decision_status = 'accepted'
decision.resolved_value_json = normalized
decision.resolved_value_json = _json_value(normalized)
columns = _field_value_columns(normalized, str(config.get('value_type') or 'string'))
if field_value is None:
field_value = ShippingOrderFieldValue(
@@ -264,7 +278,7 @@ def replace_current_header_field_value(*, task: ShippingNotice, field_code: str,
if decision is None:
raise ConflictError('Order header decision is unavailable', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
decision.decision_status = 'accepted'
decision.resolved_value_json = normalized
decision.resolved_value_json = _json_value(normalized)
columns = _field_value_columns(normalized, str(config.get('value_type') or 'string'))
if field_value is None:
db.session.add(ShippingOrderFieldValue(
@@ -349,7 +363,7 @@ def replace_current_line_fields(*, task: ShippingNotice, lines: list[dict[str, A
line_id=line.id,
field_id=str(config['field_id']),
decision_status='accepted' if value is not None else 'missing',
resolved_value_json=value,
resolved_value_json=_json_value(value),
supporting_observation_ids_json=[],
reason_code='human_line_set' if value is not None else 'missing',
)
@@ -920,7 +920,8 @@ def _commit_notice_edit(
reviewed_by_id = review_context.get('reviewed_by_id')
evidence_ref = str(review_context.get('evidence_ref') or '')
reason = str(review_context.get('reason') or '')
if not reviewed_by_id or not evidence_ref or not reason:
# 仅操作人身份是审计底线;reason/evidence_ref 已由 _prepare_review_context 哨兵兜底。
if not reviewed_by_id:
raise ConflictError('Review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
order_task = _resolve_order_task_for_notice(task)
@@ -1029,7 +1030,7 @@ def _commit_notice_edit(
def _prepare_review_context(task: ShippingNotice, payload: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
"""校验正式编辑的操作者、证据和原因;Excel ready 后拒绝写入。"""
"""校验正式编辑的操作者身份;reason/evidence 可缺省并落哨兵值;Excel ready 后拒绝写入。"""
from app.services.shipping_notice.schema_edit_policy import assert_formal_task_not_excel_frozen
try:
@@ -1050,14 +1051,18 @@ def _prepare_review_context(task: ShippingNotice, payload: dict[str, Any]) -> tu
actor_id = int(payload.get('reviewed_by_id'))
except (TypeError, ValueError):
return None, tool_response(status='failed', task=task, message='缺少复核人员', data={'error_code': 'SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED'})
reason = str(payload.get('reason') or payload.get('comment') or '').strip()
if not reason:
return None, tool_response(status='failed', task=task, message='人工纠错必须提供证据和原因', data={'error_code': 'SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED'})
# 快捷就地编辑不强制填写原因/证据:审计链自动记录 old→new + 操作人 + 时间;
# 提供了证据时仍走原校验。哨兵值满足 shipping_order_review_events 的 NOT NULL 列。
reason = str(payload.get('reason') or payload.get('comment') or '').strip() or 'quick_field_edit'
from app.services.shipping_notice.review_evidence_service import validate_review_evidence
try:
evidence_ref = validate_review_evidence(task=task, evidence=payload.get('evidence'), reason=reason)
except ValidationError as exc:
return None, tool_response(status='failed', task=task, message='人工纠错证据无效', data={'error_code': exc.code})
evidence = payload.get('evidence') or None
if evidence is not None:
try:
evidence_ref = validate_review_evidence(task=task, evidence=evidence, reason=reason)
except ValidationError as exc:
return None, tool_response(status='failed', task=task, message='人工纠错证据无效', data={'error_code': exc.code})
else:
evidence_ref = 'inline:match-table'
return {'reviewed_by_id': actor_id, 'evidence_ref': evidence_ref, 'reason': reason}, None
@@ -11,7 +11,9 @@ services/shipping_notice/ui_state.py
Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id);
五阶段 processing_stage 同样经 Notice→OT.stage(Notice 无 stage 列),
禁止仅靠 Gate 兜底把 order_freeze 误映射为订单复核;
stage_context.preparation 以 Snapshot 行 + 当前 Match 投影(Notice 经 order_task_id→OT),
stage_context.preparation 值列(预约号/料号/需求数量)有效值优先(快照 + 已接受修正,
经 effective_line_facts_for_notice),无有效值时回退快照列;匹配结果列仍以 Snapshot 行
+ 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT),
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
@@ -830,6 +832,7 @@ def _build_stage_context(
_shortage_release_required_fields,
)
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
facts = stp_facts if isinstance(stp_facts, dict) else {}
# [STEP 1] Snapshot/Match/Candidate 归属 OT;Notice 详情入口必须经 order_task_id 解析,
@@ -846,6 +849,19 @@ def _build_stage_context(
if snapshot is not None else []
)
match_by_snapshot_line_id = load_current_match_facts_by_task(getattr(order_task, 'id', None))
# [BE-有效视图] 值列消费有效订单值(快照 + 已接受修正):保存即显新值,
# 匹配结果列仍读当前匹配事实,诚实反映最近一轮匹配结论。
# 全循环只算一次,行内按 snapshot_line_id 取用;无冻结快照(如未绑定 OT 的 Notice)
# 保持空映射,行级回退快照列。有效视图解析失败(如历史/合成数据缺 Schema 版本)
# 与 ODM 投影同款降级:不阻断工作台渲染,值列退回快照列(此时有效值=快照值)。
effective_facts: dict[int, dict[str, Any]] = {}
if order_task is not None and getattr(order_task, 'order_snapshot_id', None):
try:
effective_facts = effective_line_facts_for_notice(order_task)
except Exception: # 遗留/合成快照缺 Schema 版本等:回退冻结列展示
from flask import current_app
current_app.logger.warning('effective order view resolution failed; falling back to frozen columns', exc_info=True)
effective_facts = {}
# [STEP] 与 Case 投影同源:库存 RPA 运行态只查一次 Attempt(请求内 memo),再传入各行纯函数。
inventory_rpa_running = inventory_rpa_is_running(order_task)
candidate_codes_by_line_no: dict[int, list[str]] = {}
@@ -869,17 +885,38 @@ def _build_stage_context(
for snapshot_line in snapshot_lines:
qty_text = str(snapshot_line.qty) if snapshot_line.qty is not None else None
line_no = int(snapshot_line.line_no) if snapshot_line.line_no is not None else None
# [BE-有效视图] 冻结订单行值列有效值优先(预约号/料号/需求数量):行内按
# snapshot_line_id 取有效事实,取不到(None)时回退冻结快照列;键名与前端
# 契约稳定不动(shipping.api.types.ts ShippingOrderFrozenLine)。
eff = effective_facts.get(int(snapshot_line.id)) or {}
frozen_order_lines.append({
'snapshot_line_id': int(snapshot_line.id),
'line_no': line_no,
'reservation_id': snapshot_line.reservation_id,
'part_number': snapshot_line.part_number,
'required_qty': qty_text,
'reservation_id': eff.get('reservation_id') if eff.get('reservation_id') is not None else snapshot_line.reservation_id,
'part_number': eff.get('part_number') if eff.get('part_number') is not None else snapshot_line.part_number,
'required_qty': str(eff['qty']) if eff.get('qty') is not None else qty_text,
})
fact = match_by_snapshot_line_id.get(int(snapshot_line.id))
required_qty = (fact or {}).get('required_qty')
# [BE-有效视图] 需求数量:有效事实 → 匹配事实 → 快照列(Decimal 需 str 化)。
required_qty = (
str(eff['qty'])
if eff.get('qty') is not None
else (fact or {}).get('required_qty')
)
if required_qty is None:
required_qty = qty_text
# [BE-有效视图] 预约号/料号:有效事实 → 匹配事实 → 快照列;保存修正后即使
# 匹配事实未刷新,prep 覆盖合并也立即显示新值。
reservation_id_value = (
eff.get('reservation_id')
if eff.get('reservation_id') is not None
else (fact or {}).get('reservation_id') or snapshot_line.reservation_id
)
part_number_value = (
eff.get('part_number')
if eff.get('part_number') is not None
else (fact or {}).get('part_number') or snapshot_line.part_number
)
inv_view = project_line_inventory_view(
has_formal_ot=has_formal_ot,
fact=fact,
@@ -934,8 +971,8 @@ def _build_stage_context(
field_id_by_code,
'customer_po_line_no',
),
'reservation_id': (fact or {}).get('reservation_id') or snapshot_line.reservation_id,
'part_number': (fact or {}).get('part_number') or snapshot_line.part_number,
'reservation_id': reservation_id_value,
'part_number': part_number_value,
'required_qty': required_qty,
'available_qty': inv_view.get('available_qty'),
'shortage_qty': inv_view.get('shortage_qty'),
@@ -0,0 +1,34 @@
"""
backend/migrations/versions/rc1a2b3c4d5e_drop_receipt_config_enabled.py
用途:删除收料报表配置的独立 enabled 列,站点启停即库存+收料统一开关。
依赖:Alembic revision dd22ee33ff44;shipping_receipt_report_configs 已存在。
逻辑:收料是否运行改为只看库存站点 enabled 与配置是否存在;四处后端门禁同步去掉该列过滤。
Revision ID: rc1a2b3c4d5e
Revises: dd22ee33ff44
Create Date: 2026-09-18 11:30:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "rc1a2b3c4d5e"
down_revision = "dd22ee33ff44"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除 shipping_receipt_report_configs.enabled;启用语义统一归属库存站点。"""
op.drop_column("shipping_receipt_report_configs", "enabled")
def downgrade() -> None:
"""恢复 enabled 列并统一置 true;历史双开关状态无法无损还原。"""
op.add_column(
"shipping_receipt_report_configs",
sa.Column("enabled", sa.Boolean(), server_default=sa.text("true"), nullable=False),
)
@@ -0,0 +1,103 @@
"""
backend/migrations/versions/rc2b3c4d5e6f_drop_receipt_warehouse_list.py
用途:删除收料配置的 warehouse_ids_json 列,仓库清单改为查询条件中的 Warehouse 条件。
依赖:Alembic revision rc1a2b3c4d5e;shipping_receipt_report_configs 与 shipping_inventory_sources 已存在。
逻辑:升级时先把存量 DBS 配置的仓库清单注入为一条 Warehouse 查询条件(数据保全)再删列;
降级时从 Warehouse 条件反提清单尽力恢复,条件本身保留。
Revision ID: rc2b3c4d5e6f
Revises: rc1a2b3c4d5e
Create Date: 2026-09-18 12:20:00.000000
"""
from __future__ import annotations
import json
from typing import Any
import sqlalchemy as sa
from alembic import op
revision = "rc2b3c4d5e6f"
down_revision = "rc1a2b3c4d5e"
branch_labels = None
depends_on = None
def _as_list(raw: Any) -> list:
"""把 JSON 列读成 list;驱动可能返回 list 或字符串。"""
if raw is None:
return []
if isinstance(raw, list):
return list(raw)
if isinstance(raw, str):
text = raw.strip()
if not text:
return []
loaded = json.loads(text)
return list(loaded) if isinstance(loaded, list) else []
return []
def _warehouse_values(parameters: list) -> list[str]:
"""提取查询条件里的 Warehouse 值(去空去重,保持顺序)。"""
values: list[str] = []
for item in parameters:
if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse':
continue
for value in (item.get('values') or []):
cleaned = str(value or '').strip()
if cleaned and cleaned not in values:
values.append(cleaned)
return values
def upgrade() -> None:
"""先把存量 DBS 仓库清单转为 Warehouse 查询条件,再删除 warehouse_ids_json 列。"""
conn = op.get_bind()
rows = conn.execute(sa.text(
"SELECT c.id, c.query_parameters_json, c.warehouse_ids_json"
" FROM shipping_receipt_report_configs c"
" JOIN shipping_inventory_sources s ON s.id = c.inventory_source_id"
" WHERE s.connector_type = 'dbs'"
)).mappings().all()
for row in rows:
parameters = _as_list(row['query_parameters_json'])
warehouses = [str(v or '').strip() for v in _as_list(row['warehouse_ids_json']) if str(v or '').strip()]
has_warehouse_condition = any(
isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse'
for item in parameters
)
if warehouses and not has_warehouse_condition:
parameters.append({
'name': 'Warehouse', 'mode': 'single' if len(warehouses) == 1 else 'multi_text',
'values': warehouses, 'required': False, 'select_all': False,
})
conn.execute(
sa.text("UPDATE shipping_receipt_report_configs SET query_parameters_json = CAST(:params AS JSON) WHERE id = :id"),
{'params': json.dumps(parameters), 'id': row['id']},
)
op.drop_column('shipping_receipt_report_configs', 'warehouse_ids_json')
def downgrade() -> None:
"""恢复 warehouse_ids_json 列并从 Warehouse 条件尽力反提;条件本身保留。"""
op.add_column(
'shipping_receipt_report_configs',
sa.Column('warehouse_ids_json', sa.JSON(), nullable=False, server_default=sa.text("'[]'")),
)
conn = op.get_bind()
rows = conn.execute(sa.text(
"SELECT c.id, c.query_parameters_json"
" FROM shipping_receipt_report_configs c"
" JOIN shipping_inventory_sources s ON s.id = c.inventory_source_id"
" WHERE s.connector_type = 'dbs'"
)).mappings().all()
for row in rows:
warehouses = _warehouse_values(_as_list(row['query_parameters_json']))
if warehouses:
conn.execute(
sa.text("UPDATE shipping_receipt_report_configs SET warehouse_ids_json = CAST(:warehouses AS JSON) WHERE id = :id"),
{'warehouses': json.dumps(warehouses), 'id': row['id']},
)
+24 -13
View File
@@ -686,7 +686,12 @@ def client(app):
@pytest.fixture
def dbs_ready_file() -> dict:
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。"""
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。
rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date),
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_precheck 按
parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。
"""
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
@@ -696,22 +701,25 @@ def dbs_ready_file() -> dict:
"checksum": "d" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 10, "invoice_no": "INV-001", "material_no": "MAT-001",
{"sheet": "Receipt", "row_no": 10, "doc_no": "INV-001", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"receipt_date": "2026-08-05", "receipt_quantity": "500", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 11, "invoice_no": "INV-001", "material_no": "MAT-001",
"movement_date": "2026-08-05", "quantity": "500", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 11, "doc_no": "INV-001", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"receipt_date": "2026-08-05", "receipt_quantity": "700", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 20, "invoice_no": "INV-002", "material_no": "MAT-002",
"movement_date": "2026-08-05", "quantity": "700", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 20, "doc_no": "INV-002", "material_code": "MAT-002",
"material_name": "控制器组件", "specification": "标准型 / 48V",
"receipt_date": "2026-08-05", "receipt_quantity": "1200", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-05", "quantity": "1200", "source_code": "DBS-AWSBI"},
],
}
@pytest.fixture
def crane_ready_file() -> dict:
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。"""
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
"""
return {
"source_code": "CRANE-SZ",
"business_date": "2026-08-06",
@@ -721,16 +729,19 @@ def crane_ready_file() -> dict:
"checksum": "c" * 64,
"status": "ready",
"rows": [
{"sheet": "Inbound", "row_no": 5, "invoice_no": "INV-008", "material_no": "MAT-200",
{"sheet": "Inbound", "row_no": 5, "doc_no": "INV-008", "material_code": "MAT-200",
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
"receipt_date": "2026-08-05", "receipt_quantity": "600", "source_code": "CRANE-SZ"},
"movement_date": "2026-08-05", "quantity": "600", "source_code": "CRANE-SZ"},
],
}
@pytest.fixture
def same_day_receipt_file() -> dict:
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。"""
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
"""
return {
"source_code": "DBS-AWSSG",
"business_date": "2026-08-06",
@@ -740,9 +751,9 @@ def same_day_receipt_file() -> dict:
"checksum": "s" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 3, "invoice_no": "INV-041", "material_no": "MAT-041",
{"sheet": "Receipt", "row_no": 3, "doc_no": "INV-041", "material_code": "MAT-041",
"material_name": "连接器组件", "specification": "C 型",
"receipt_date": "2026-08-06", "receipt_quantity": "400", "source_code": "DBS-AWSSG"},
"movement_date": "2026-08-06", "quantity": "400", "source_code": "DBS-AWSSG"},
],
}
+36 -1
View File
@@ -13,7 +13,42 @@ from app.jobs.context import JobContext
from app.jobs.handlers.schedule_run import run_schedule
from app.jobs.types import JobType
from app.models import Job, ScheduleRun, ScheduleTask, User
from app.services.schedule.queue_service import enqueue_due_schedule_runs, enqueue_manual_schedule_run
from app.services.schedule.queue_service import (
enqueue_due_schedule_runs,
enqueue_manual_schedule_run,
prepare_schedule_queue,
)
def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycle(app, monkeypatch):
"""关键断言:调拨来源等待回调 Job 的超时回收每轮领取都执行,不只在 worker 启动时扫一次。
[STEP 1] 用计数桩替换 receipt_callback_bridge.recover_stale_waiting_source_jobs(queue_service
在函数体内延迟 import,桩生效)并复位 _worker_initialized,隔离模块级启动标记。
[STEP 2] 连续两轮调用真实 prepare_schedule_queue(空库下其余恢复均为 no-op)。
[STEP 3] 第二轮后计数必须为 2:若回收仍挂在启动一次性分支,第二次调用不会触发,计数停留 1。
"""
from app.services.in_transit_transfer import receipt_callback_bridge
from app.services.schedule import queue_service
from app.services.shipping_notice import rpa_worker_heartbeat_alert
calls: list[int] = []
def _fake_recover() -> int:
calls.append(1)
return 0
def _fake_heartbeat(**_kwargs):
return {"skipped": True, "reason": "test_stub"}
monkeypatch.setattr(receipt_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
monkeypatch.setattr(queue_service, "_worker_initialized", False)
assert prepare_schedule_queue() == 0
assert len(calls) == 1 # 第一轮:启动 + 每轮维护都应触发回收
assert prepare_schedule_queue() == 0
assert len(calls) == 2 # 第二轮:回收仍须执行(修复前停留 1,此处为核心回归断言)
def _create_task(*, due: bool = False, platform_api_path: str | None = None, name: str = "schedule queue test") -> ScheduleTask:
@@ -13,6 +13,7 @@ import pytest
from openpyxl import Workbook
from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows
from app.services.in_transit_transfer.file_parser import parse_movement_rows
pytestmark = pytest.mark.pure_unit
@@ -44,7 +45,7 @@ def _movement_xlsx_bytes() -> bytes:
def test_extract_movement_rows_maps_columns_to_domain_fields():
"""表头别名被映射为定死领域字段 code 的行字段。"""
"""表头别名被映射为定死领域字段 code 的行字段,并携带真实溯源 sheet/row_no。"""
rows = _extract_movement_rows(
_movement_xlsx_bytes(),
field_mapping=MOVEMENT_MAPPING,
@@ -59,6 +60,17 @@ def test_extract_movement_rows_maps_columns_to_domain_fields():
assert str(first['movement_date']) == '2026-08-05'
second = rows[1]
assert second['quantity'] == 300
# [断言意图] 溯源字段必须指向真实电子表格位置:sheet=实际工作表标题,
# row_no=工作表 1-based 行号(表头第 1 行 → 数据行在第 2/3 行)。
assert first['sheet'] == 'Movement'
assert second['sheet'] == 'Movement'
assert first['row_no'] == 2
assert second['row_no'] == 3
# [断言意图] 仓库产出直连解析器:含溯源字段的行必须通过 parse_movement_rows
# 行校验(不出现 missing_sheet_or_row_no 整链阻断),证据行号透传到解析行。
parsed = parse_movement_rows(source_code='DBS-AWSBI', rows=rows)
assert [row.row_no for row in parsed] == [2, 3]
assert [row.invoice_no for row in parsed] == ['MOV-001', 'MOV-001']
def test_extract_movement_rows_skips_missing_alias_columns():
@@ -79,3 +91,6 @@ def test_extract_movement_rows_skips_missing_alias_columns():
assert rows[0]['doc_no'] == 'MOV-9'
assert rows[0]['quantity'] == 120
assert 'movement_date' not in rows[0]
# 部分映射下溯源字段仍在:sheet/row_no 不依赖业务列是否齐全。
assert rows[0]['sheet'] == 'S'
assert rows[0]['row_no'] == 2
@@ -13,6 +13,7 @@ import pytest
from app.services.in_transit_transfer.erp_adapter import ErpAdapter
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
TransferDeps,
create_precheck,
restore_precheck,
@@ -162,3 +163,26 @@ def test_route_not_resolved_marks_source_failed(dbs_ready_file):
by_source = {stage.source_code: stage for stage in result.sources}
assert by_source["DBS-AWSBI"].stage == "failed"
assert by_source["CRANE-SZ"].stage == "waiting_rpa_callback" # 无文件 → 等待,不阻断
def test_run_precheck_consumes_movement_field_rows(app):
"""run_precheck 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。"""
# [断言意图] 真实仓库 rows 以 doc_no/material_code/quantity/movement_date 为键;
# 预检应正确产出 executable 明细而非 ReceiptFileSchemaError
# 注:sheet/row_no 为解析校验必带的溯源字段(与 parse_movement_rows 契约一致,同校验)。
deps, erp_fake, _rpa = make_transfer_deps(
{
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
"rows": [{
"sheet": "Movement", "row_no": 1,
"doc_no": "INV-1", "material_code": "M1", "material_name": "物料1",
"quantity": 5, "movement_date": "2026-09-16",
}],
},
routes={"DSV360_AWSDU": RouteMapping(erp_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
)
erp_fake.seed_inventory("INV-1", 5) # FakeERP 按 invoice_no 键维护账面库存
result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
item = next(i for i in result.items if i.invoice_no == "INV-1")
assert item.result == "executable"
@@ -0,0 +1,55 @@
"""收料回调桥与超时回收测试。
用途:验证收料回调终态能推进调拨 waiting_rpa_callback 来源任务(Task 6),
以及超时未回调的任务被回收为 failed(Task 8)。
依赖:app(SQLite)fixture、TransferSourceJob/TransferRun 工厂、回调桥函数。
逻辑:成功带文件 → file_ready;失败/空数据 → failed 带错误码;桥内异常不外抛。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from app import db
from app.models import TransferSourceJob, TransferRun
from app.services.in_transit_transfer.receipt_callback_bridge import (
advance_source_job_from_receipt_callback,
)
def _make_waiting_job(run_no: str, source_code: str = "DSV360_AWSDU") -> TransferSourceJob:
"""造一个处于 waiting_rpa_callback 的来源任务(status/trigger_type 必须取冻结枚举值)。"""
run = TransferRun(run_no=run_no, business_date="2026-09-17", status="preparing_files", trigger_type="manual")
db.session.add(run)
db.session.flush()
job = TransferSourceJob(run_id=run.id, source_code=source_code, status="waiting_rpa_callback")
db.session.add(job)
db.session.commit()
return job
def test_success_callback_advances_job_to_file_ready(app):
"""成功回调(含文件号/sha256)应把最新等待任务推进为 file_ready。"""
job = _make_waiting_job("RUN-BRIDGE-1")
advanced = advance_source_job_from_receipt_callback(
source_code=job.source_code, file_no="42", file_sha256="abc", callback_ok=True,
)
assert advanced is not None and advanced.status == "file_ready"
assert advanced.file_no == "42" and advanced.file_sha256 == "abc"
assert advanced.finished_at is not None
def test_recover_stale_waiting_source_jobs(app):
"""超过收料回调超时的等待任务回收为 failed;新任务不动。"""
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
stale = _make_waiting_job("RUN-BRIDGE-STALE-1", "DSV360_AWSDU")
stale.updated_at = datetime.utcnow() - timedelta(seconds=3600)
fresh = _make_waiting_job("RUN-BRIDGE-STALE-2", "DSV360_AWSSG")
assert fresh.updated_at > datetime.utcnow() - timedelta(seconds=60)
recovered = recover_stale_waiting_source_jobs()
db.session.expire_all()
assert recovered == 1
assert db.session.get(TransferSourceJob, stale.id).status == "failed"
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_RECEIPT_CALLBACK_TIMEOUT"
assert db.session.get(TransferSourceJob, fresh.id).status == "waiting_rpa_callback"
@@ -1,7 +1,8 @@
"""真实收料 RPA 触发服务测试。
用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者;
配置/来源/触发目录缺失时 fail-closed(ok=False)。
触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。
@@ -21,9 +22,9 @@ def receipt_source():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
assert source is not None
config = ShippingReceiptReportConfig(
inventory_source_id=source.id, enabled=True,
inventory_source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[], warehouse_ids_json=[],
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
)
from app import db
@@ -50,6 +51,8 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
assert result['callback_id']
assert result['trigger_path'].endswith('.json')
assert calls['units'][0]['source_code'] == 'DSV360_AWSDU'
# 关键断言:按需触发取 Warehouse 条件的第一个仓作为拆分维度。
assert calls['units'][0]['warehouse_id'] == 'AWSDU'
assert calls['units'][0]['credential_envelope']
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
@@ -70,3 +73,56 @@ def test_trigger_receipt_rpa_missing_config_fails_closed(app):
"""来源启用但无收料配置 → ok=False。"""
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
captured: dict = {}
def fake_writer(run_no, units, payload=None):
# [断言意图] writer 收到的载荷必须携带真实 unit.id——
# 单元行先 flush 拿 id,再序列化进 trigger,回调才能按 callback_id 找到单元。
captured["units"] = units
return "trigger.json"
outcome = trigger_receipt_rpa(
source_code=receipt_source.source_code, business_date="2026-09-17",
reason="transfer_retry_receipt", writer=fake_writer,
)
assert outcome["ok"] is True
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
assert unit.status == "awaiting_rpa"
assert unit.schedule_run_id == 0 # 调拨触发无排程 run,沿用 0 占位约定
assert captured["units"][0]["unit_run_id"] == unit.id
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_path, monkeypatch):
"""deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。"""
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
outcome = _DefaultRpaTrigger().trigger(
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
)
assert outcome["ok"] is True
# [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
outcome = trigger_receipt_rpa(
source_code=receipt_source.source_code, business_date="2026-09-17",
reason="transfer_retry_receipt", writer=lambda *a, **k: None,
)
assert outcome["ok"] is False
unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
ShippingReceiptRpaUnitRun.id.desc()).first()
assert unit.status == "failed"
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
@@ -29,15 +29,16 @@ def _create_users() -> None:
def _dbs_payload() -> dict:
"""构造 DBS 收料配置;日期未出现表示保持系统页面默认 NULL。"""
"""构造 DBS 收料配置;Warehouse 条件即逐仓拆分维度,日期未出现表示保持系统页面默认 NULL。"""
return {
'enabled': True,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
},
'warehouse_ids_json': ['AWSDU', 'AWSDU-02'],
'query_parameters_json': [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}],
'query_parameters_json': [
{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['AWSDU', 'AWSDU-02'], 'required': False, 'select_all': False},
{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False},
],
}
@@ -65,7 +66,9 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
)
assert response.status_code == 200
config = parse_api_data(response.get_json())
assert config['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
# 关键断言:Warehouse 条件原样保存,作为逐仓拆分维度的唯一持久化位置。
warehouse_condition = next(item for item in config['query_parameters_json'] if item['name'] == 'Warehouse')
assert warehouse_condition['values'] == ['AWSDU', 'AWSDU-02']
assert config['report_path_json']['report_group'] == 'Inbound'
with app.app_context():
@@ -78,7 +81,7 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
).one()
assert audit.before_snapshot_json is None
assert audit.after_snapshot_json['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02']
def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, client):
@@ -120,9 +123,40 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
# 关键断言:Warehouse 条件即逐仓拆分维度——缺失、重复、空值都必须拒绝。
missing_warehouse = _dbs_payload()
missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}]
response = client.put(
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
json=missing_warehouse, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
duplicate_warehouse = _dbs_payload()
duplicate_warehouse['query_parameters_json'] = [
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU-02'], 'required': False, 'select_all': False},
]
response = client.put(
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
json=duplicate_warehouse, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
empty_warehouse = _dbs_payload()
empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}]
response = client.put(
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
json=empty_warehouse, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
invalid_crane = {
'enabled': True, 'report_path_json': {'report_name': 'Other Report'},
'warehouse_ids_json': ['NOT-ALLOWED'], 'query_parameters_json': [],
'report_path_json': {'report_name': 'Other Report'},
'query_parameters_json': [],
}
response = client.put(
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
@@ -153,7 +187,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
crane_id = crane_source.id
default_query = {
'enabled': True, 'report_path_json': {'report_name': 'Inbound Details'}, 'warehouse_ids_json': [],
'report_path_json': {'report_name': 'Inbound Details'},
'query_parameters_json': [],
}
response = client.put(
+217
View File
@@ -0,0 +1,217 @@
"""
tests/test_effective_order_view.py
用途:验证「冻结快照 + 冻结后人工修正」的有效订单值视图。
依赖:pytest、effective_order_view、task_order_field_editor、订单 Schema/快照模型。
逻辑:覆盖行级修正对位叠加、快照不可变、整行替换后的保守跳过与 Notice 行事实投影。
"""
from __future__ import annotations
from decimal import Decimal
from types import SimpleNamespace
from app import db
from app.models import (
ShippingNotice,
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.effective_order_view import (
effective_line_facts_for_notice,
effective_order_field_values,
)
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
from app.services.shipping_notice.task_order_field_editor import (
replace_current_line_field_value,
replace_current_line_fields,
)
def _seed_frozen_order():
"""最小冻结订单夹具:OT + accepted Extraction(两行三字段)+ 冻结快照。"""
user = User(username='eff-view-user', email='eff-view@test.local', role='user', status='active')
db.session.add(user)
schema = ShippingOrderSchema(schema_code='EFFVIEW', display_name='EffView')
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published',
definition_json={'fields': [
{'field_id': 'f-part', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'field_category': 'order_line', 'sequence': 1, 'enabled': True},
{'field_id': 'f-rsv', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'field_category': 'order_line', 'sequence': 2, 'enabled': True},
{'field_id': 'f-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'field_category': 'order_line', 'sequence': 3, 'enabled': True},
]},
)
db.session.add(version)
db.session.flush()
order = ShippingOrderTask(task_no='OT-EFFVIEW-1', source_type='direct_pdf', user_id=user.id)
db.session.add(order)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=order.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
order_data_version=1,
rule_versions_json={'fulfillment_rule': {'required_field_ids': {
'part_number': 'f-part', 'reservation_id': 'f-rsv', 'qty': 'f-qty',
}}},
header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
snap_lines = []
for position, part in enumerate(('D4-A08AR12000002-', 'D4-B07BR07000001')):
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
db.session.add(line)
db.session.flush()
for field_id, value in (('f-part', part), ('f-rsv', f'RSV-{position + 1}'), ('f-qty', '10')):
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=field_id,
decision_status='accepted', resolved_value_json=value,
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_id=decision.id,
value_text=str(value), value_json=value,
))
snap_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=position, line_no=position + 1,
part_number=part, reservation_id=f'RSV-{position + 1}', qty=Decimal('10'),
field_values_json={'f-part': part, 'f-rsv': f'RSV-{position + 1}', 'f-qty': '10'},
)
db.session.add(snap_line)
db.session.flush()
snap_lines.append(snap_line)
order.current_order_extraction_id = extraction.id
order.order_snapshot_id = snapshot.id
db.session.flush()
return SimpleNamespace(user=user, order=order, extraction=extraction, snapshot=snapshot, snap_lines=snap_lines)
def test_edited_part_number_flows_into_effective_values(app):
"""冻结后人工修正料号,有效视图必须返回修正值(匹配/Excel 的读取口径)。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
_header, lines = effective_order_field_values(fixture.order)
# 断言:第 0 行为修正值、第 1 行保持冻结值,证明对位叠加只影响被改行。
assert lines[0]['f-part'] == 'D4-A08AR12000002'
assert lines[1]['f-part'] == 'D4-B07BR07000001'
def test_snapshot_stays_frozen_after_edit(app):
"""有效视图不得回写快照:冻结事实仍是审计锚点。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
# 断言:快照强类型列与 field_values_json 均保持冻结原值。
assert fixture.snap_lines[0].part_number == 'D4-A08AR12000002-'
assert fixture.snap_lines[0].field_values_json['f-part'] == 'D4-A08AR12000002-'
def test_line_set_replacement_skips_line_overlay(app):
"""整行替换后 position 不再可比:行级叠加保守跳过,返回冻结行值。"""
with app.app_context():
fixture = _seed_frozen_order()
# 注:替换行不带 qty——本测试只验证行集替换守卫;decimal 经整行替换路径的可持久化
# 已由 test_line_set_replacement_with_decimal_persists_without_json_error 单独覆盖。
replace_current_line_fields(task=fixture.order, lines=[
{'part_number': 'D4-A08AR12000002', 'reservation_id': 'RSV-1'},
])
_header, lines = effective_order_field_values(fixture.order)
# 断言:行级叠加被守卫跳过(行集维度属后续特性),值仍来自冻结快照两行原样。
assert [row['f-part'] for row in lines] == ['D4-A08AR12000002-', 'D4-B07BR07000001']
def test_effective_line_facts_for_notice(app):
"""Notice 行物化事实按冻结规则映射强类型键并携带修正值。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
facts = effective_line_facts_for_notice(fixture.order)
first = facts[int(fixture.snap_lines[0].id)]
# 断言:料号为修正值,数量被安全转为 Decimal,字段值字典完整。
assert first['part_number'] == 'D4-A08AR12000002'
assert first['reservation_id'] == 'RSV-1'
assert first['qty'] == Decimal('10')
assert first['field_values']['f-rsv'] == 'RSV-1'
def test_decimal_edit_persists_without_json_error(app):
"""数量(decimal 字段)人工编辑必须可持久化:value_json 存字符串、value_decimal 存 Decimal。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='qty', value='12.5',
)
rows = [
item for item in ShippingOrderFieldValue.query.filter_by(
extraction_id=fixture.extraction.id,
).all()
if item.value_json is not None
]
# 夹具两行均预置了 f-qty FieldValue(未编辑行 value_json='10'),须限定被编辑的第 0 行再断言。
edited_line = ShippingOrderLine.query.filter_by(
extraction_id=fixture.extraction.id, position=0,
).one()
qty_rows = [item for item in rows if item.field_id == 'f-qty' and item.line_id == edited_line.id]
# 断言:JSON 列存规范字符串(与机器路径 _json_value 对齐),类型列保留 Decimal。
assert qty_rows, 'qty FieldValue 必须存在'
assert all(item.value_json == '12.5' for item in qty_rows)
assert any(item.value_decimal == Decimal('12.5') for item in qty_rows)
def test_line_set_replacement_with_decimal_persists_without_json_error(app):
"""整行替换带 decimal 字段必须同样可持久化:新当前 Extraction 的 qty JSON 列存字符串、类型列存 Decimal。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_fields(task=fixture.order, lines=[
{'part_number': 'D4-A08AR12000002', 'reservation_id': 'RSV-1', 'qty': '12.5'},
])
rows = ShippingOrderFieldValue.query.filter_by(
extraction_id=fixture.order.current_order_extraction_id,
field_id='f-qty',
).all()
line_qty_rows = [item for item in rows if item.line_id is not None]
# 断言:整行替换路径的 Decision/FieldValue 均经 _json_value 落库且不得抛序列化错误。
assert line_qty_rows, '替换行集的 qty FieldValue 必须存在'
assert all(item.value_json == '12.5' for item in line_qty_rows)
assert all(item.value_decimal == Decimal('12.5') for item in line_qty_rows)
def test_matching_purpose_values_use_effective_view(app):
"""库存匹配用途投影必须读到修正后的料号(修复改值不进匹配的断层)。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
notice = ShippingNotice(
task_no='SN-EFFVIEW-1', source_type='manual', user_id=fixture.user.id,
order_task_id=fixture.order.id,
)
db.session.add(notice)
db.session.flush()
purpose_values = task_line_purpose_values(notice)
# 断言:第 0 行用途值为修正料号,第 1 行保持冻结值。
assert purpose_values[0]['part_number'] == 'D4-A08AR12000002'
assert purpose_values[1]['part_number'] == 'D4-B07BR07000001'
@@ -30,6 +30,67 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch)
assert ShippingInventoryFile.query.count() == 0
def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
"""收料回调 success 落归档后,必须推进调拨 waiting 来源任务(B3 接线)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-CB2', schedule_task_id=task.id, status='running')
db.session.add(run); db.session.flush()
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge', status='awaiting_rpa', config_snapshot_json={})
db.session.add(unit)
transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E', business_date='2026-09-17', status='preparing_files', trigger_type='manual')
db.session.add(transfer_run); db.session.flush()
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
db.session.add(job); db.session.commit()
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
result = ingest_receipt_callback(payload)
# [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id
db.session.expire_all()
advanced = db.session.get(TransferSourceJob, job.id)
assert advanced.status == "file_ready"
assert advanced.file_no == str(result["file_id"])
def test_ingest_failed_advance_is_durable(app):
"""failed 回调推进调拨任务后必须已 commit——rollback 不得丢弃该推进(B3 持久性)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-CB3', schedule_task_id=task.id, status='running')
db.session.add(run); db.session.flush()
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={})
db.session.add(unit)
transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E-FAIL', business_date='2026-09-17', status='preparing_files', trigger_type='manual')
db.session.add(transfer_run); db.session.flush()
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
db.session.add(job); db.session.commit()
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
result = ingest_receipt_callback(payload)
assert result['status'] == 'failed'
# [断言意图] 推进必须已落库而非仅 flush:rollback 丢弃会话内未提交变更,
# 只有真正 commit 过的推进才能在 expire_all 后被新查询读到。
db.session.rollback()
db.session.expire_all()
advanced = db.session.get(TransferSourceJob, job.id)
assert advanced.status == 'failed'
assert advanced.error_code == 'RPA_TEST_FAIL'
def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
"""Callback cannot read arbitrary local xlsx files outside the receipt-only drop root."""
from app.core.errors import ValidationError
@@ -19,9 +19,9 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch
parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True,
)
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, enabled=True, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, warehouse_ids_json=['A', 'B']),])
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False}]),])
db.session.flush()
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, enabled=True, report_path_json={'report_name': 'Inbound Details'}, warehouse_ids_json=[]))
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[]))
task = ScheduleTask(schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', job_params={'source_codes': [dbs.source_code, crane.source_code]})
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-1', schedule_task_id=task.id, status='running')
@@ -45,10 +45,12 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch
}
assert dbs_unit['report_path_json']['report_name'] == 'Receipt Detail'
assert dbs_unit['warehouse_id'] == 'A'
# 关键断言:单元快照必须剥离 Warehouse 条件,Worker 才能按 warehouse_id 自动追加不重复。
assert all(item['name'] != 'Warehouse' for item in dbs_unit['query_parameters_json'])
def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
"""动态排程选项只暴露库存站点已启用且收料配置也启用的站点。"""
"""动态排程选项只暴露库存站点已启用且已配置收料的站点。"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.services.schedule.job_options import list_job_options
@@ -56,9 +58,9 @@ def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
db.session.add(ShippingReceiptReportConfig(
inventory_source_id=source.id, enabled=True,
inventory_source_id=source.id,
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'},
warehouse_ids_json=['A'],
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['A'], 'required': False, 'select_all': False}],
))
db.session.commit()
@@ -41,3 +41,30 @@ def test_receipt_crane_driver_forces_inbound_details_entry_route():
assert module._inbound_details_entry_url('https://wms-portal.craneww.com/') == (
'https://wms-portal.craneww.com/#/inbound-details-query'
)
def test_receipt_worker_uses_common_trigger_consumer():
"""收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'claim_trigger' in text
assert 'archive_trigger' in text
assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块
def test_receipt_worker_logs_full_lifecycle_and_banner():
"""收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'configure_file_logging' in text
assert 'maybe_rotate_open_log' in text
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段
assert '[receipt-unit] success' in text # 成功单元留痕(此前成功路径零输出)
assert '[receipt-unit] failed' in text
assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text
def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
assert 'SHIPPING_NOTICE_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
+64 -6
View File
@@ -609,7 +609,8 @@ def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch):
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
"""配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
worker = _load_freight_rpa_worker()
# 等价迁移:文件日志实现已提取至公共 worker_logging 模块,本用例改测公共接口。
worker_logging = _load_worker_logging()
log_path = tmp_path / "logs" / "worker.log"
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
@@ -618,7 +619,7 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
original_stderr = sys.stderr
try:
resolved = worker._configure_file_logging()
resolved = worker_logging.configure_file_logging()
print("hello stdout")
print("hello stderr", file=sys.stderr)
finally:
@@ -645,7 +646,8 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
"""日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
worker = _load_freight_rpa_worker()
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
worker_logging = _load_worker_logging()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
Path(f"{log_path}.1").write_text("old-1", encoding="utf-8")
@@ -653,7 +655,7 @@ def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
worker._rotate_log_file_if_needed(log_path)
worker_logging.rotate_log_file_if_needed(log_path)
assert not log_path.exists()
assert Path(f"{log_path}.1").read_text(encoding="utf-8") == "current-log"
@@ -662,18 +664,41 @@ def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp_path):
"""备份数量为 0 时,超过大小的当前日志应直接删除。"""
worker = _load_freight_rpa_worker()
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
worker_logging = _load_worker_logging()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0")
worker._rotate_log_file_if_needed(log_path)
worker_logging.rotate_log_file_if_needed(log_path)
assert not log_path.exists()
def _load_worker_logging():
"""加载 scripts/rpa/common/worker_logging.py 供单测直接断言。
历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py,
已提取为公共模块;Worker 内部私有名(_configure_file_logging 等)已删除,
日志行为用例统一改测公共接口,行为断言保持等价。
"""
common_dir = _repo_root() / "scripts" / "rpa" / "common"
if str(common_dir) not in sys.path:
sys.path.insert(0, str(common_dir))
module_path = common_dir / "worker_logging.py"
spec = importlib.util.spec_from_file_location("worker_logging_under_test", module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
# 模块顶层 `from rpa_common import _env` 依赖 sys.path,须先登记再执行;
# _ACTIVE_* 运行态按用例独立加载实例,避免跨用例状态串扰。
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
def _load_worker_disk_cleanup():
"""加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py"
@@ -823,6 +848,39 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
assert not orphan_run.exists()
def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
"""
崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。
断言意图:收料 Worker 的一次性 Profile 以 receipt_ 前缀创建,异常中断后
残留目录同样按孤儿 Profile 规则清理;会话复用目录按名豁免(与年龄无关);
未超期的 receipt_* Profile 正在使用中,前缀匹配不得误删。
"""
cleanup = _load_worker_disk_cleanup()
root = tmp_path / "browser_profile"
stale_receipt = root / "receipt_abcd1234"
stale_receipt.mkdir(parents=True)
(stale_receipt / "Cookies").write_text("drop", encoding="utf-8")
young_receipt = root / "receipt_fresh5678"
young_receipt.mkdir()
session_dir = root / "dsv_session"
session_dir.mkdir()
now = time.time()
old = now - 10 * 24 * 3600
os.utime(stale_receipt, (old, old))
os.utime(young_receipt, (now - 3600, now - 3600))
os.utime(session_dir, (old, old))
stats = cleanup.DiskCleanupStats()
# cutoff 对齐真实调用语义:run_worker_disk_cleanup 传入 now - 孤儿最大存活(默认 24h)
cleanup.cleanup_orphan_runtime_profiles(root, cutoff_unix=now - 24 * 3600, stats=stats)
# 过期 receipt_* 目录树删除;未过期 receipt_* 与 _session 结尾目录即使过期也保留
assert not stale_receipt.exists() and session_dir.exists()
assert young_receipt.exists()
assert stats.deleted_dirs == 1
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
worker = _load_freight_rpa_worker()
+65
View File
@@ -0,0 +1,65 @@
"""
tests/test_line_closure_export.py
用途:验证滚动导出资格对已结案行的剔除(含"有库存的结案行也不导出"边缘场景)。
依赖:pytest、reservation_service、fulfillment_workflow、核验/预约模型、行级履约决定。
逻辑:两行均有可用预约,结案其一后,导出资格集合只保留未结案行。
"""
from __future__ import annotations
from decimal import Decimal
from app import db
from app.models import (
ShippingInventoryVerification,
ShippingInventoryVerificationLine,
ShippingReservation,
)
from app.services.shipping_notice.fulfillment_workflow import exportable_snapshot_line_ids
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
from tests.test_effective_order_view import _seed_frozen_order
from tests.test_line_closure_fulfillment import _seed_close_decision
def _seed_available_reservations(fixture):
"""两行各建一条 available 预约 + 一轮 completed 核验。"""
verification = ShippingInventoryVerification(task_id=fixture.order.id, status='completed')
db.session.add(verification)
db.session.flush()
for index, snap_line in enumerate(fixture.snap_lines):
reservation = ShippingReservation(
task_id=fixture.order.id, snapshot_line_id=snap_line.id,
reservation_id=f'RSV-CLOSE-{index}', po_number_normalized='PO-CLOSE',
part_number=snap_line.part_number, required_qty=Decimal('10'), status='available',
)
db.session.add(reservation)
db.session.flush()
db.session.add(ShippingInventoryVerificationLine(
verification_id=verification.id, reservation_id=reservation.id,
required_qty=Decimal('10'), available_qty=Decimal('10'), status='available',
))
db.session.flush()
def test_closed_line_with_inventory_is_not_exportable(app):
"""结案行即使库存充足、核验 available 也不得进入导出资格集合。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_available_reservations(fixture)
_seed_close_decision(fixture, 1)
_verification, available = current_available_snapshot_line_ids(
fixture.order, closed_snapshot_line_ids={int(fixture.snap_lines[1].id)},
)
# 断言:仅未结案的第 0 行可导出。
assert available == {int(fixture.snap_lines[0].id)}
def test_exportable_snapshot_line_ids_excludes_closed(app):
"""滚动导出入口(exportable_snapshot_line_ids)自动剔除结案行。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_available_reservations(fixture)
_seed_close_decision(fixture, 1)
# 断言:导出集合不含结案行(该行预约仍 available,验证 closed 过滤优先)。
assert exportable_snapshot_line_ids(fixture.order) == {int(fixture.snap_lines[0].id)}
@@ -0,0 +1,141 @@
"""
tests/test_line_closure_fulfillment.py
用途:验证行结案(close_unfulfillable)在满足性聚合与整单门禁中的豁免语义。
依赖:pytest、fulfillment_workflow、行级履约决定模型、冻结订单夹具。
逻辑:两行订单关闭短缺行后整单应判定满足;全部行结案时整单不通过(无剩余履约内容)。
"""
from __future__ import annotations
from app import db
from app.models import (
ShippingNoticeLineInventoryMatch,
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision,
)
from app.services.shipping_notice.fulfillment_workflow import (
_closed_snapshot_line_ids_for_task,
_recompute_task_match_aggregate,
match_completed,
)
from tests.test_effective_order_view import _seed_frozen_order
def _seed_match_facts(fixture):
"""第 0 行 matched+ready,第 1 行 not_found 短缺(历史阻塞点)。"""
for snap_line, result, shortage in (
(fixture.snap_lines[0], 'matched', '0'),
(fixture.snap_lines[1], 'not_found', '10'),
):
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=fixture.order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
line_index=snap_line.position, match_result=result, inventory_status='ready',
required_qty='10', available_qty='10' if result == 'matched' else '0',
shortage_qty=shortage, reservation_id=snap_line.reservation_id,
part_number=snap_line.part_number, is_current=True,
))
db.session.flush()
def _seed_close_decision(fixture, line_index, *, case_no='SNRC-CLOSE-1', version=1):
"""给已确认 Case 补一条活动结案决定(FK 不强制,挂哨兵父 id 即可)。"""
case = ShippingOrderReviewCase.query.filter_by(case_no=case_no).first()
if case is None:
case = ShippingOrderReviewCase(
case_no=case_no, run_id=901, unit_id=902, document_id=903,
owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
)
db.session.add(case)
db.session.flush()
db.session.add(ShippingOrderReviewLineDecision(
review_case_id=case.id, draft_line_id=f'line-{line_index}', line_index=line_index,
decision_version=version, decision_code='close_unfulfillable', decision_source='user',
line_status='closed_unfulfillable', is_active=True, reason='该行不再发货',
actor_user_id=fixture.user.id, snapshot_json={},
))
db.session.flush()
def test_closed_line_ids_helper_mirrors_release_query(app):
"""结案行集合必须与放行同款:活动决定 + line_index 映射快照行。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_close_decision(fixture, 1)
# 断言:仅第 1 行(line_index=1)进入结案集合。
assert _closed_snapshot_line_ids_for_task(fixture.order) == {int(fixture.snap_lines[1].id)}
def test_aggregate_exempts_closed_shortage_line(app):
"""关闭短缺行后聚合应判满足:closed 行不阻断、不进缺货列表。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_match_facts(fixture)
_seed_close_decision(fixture, 1)
status, shortages = _recompute_task_match_aggregate(fixture.order)
payload = fixture.order.step_payload_json or {}
line_results = payload['current_match_projection']['line_results']
# 断言:整单满足、缺货列表为空、结案行状态为 closed 而非 shortage。
assert status == 'fulfillable'
assert shortages == []
assert line_results[1]['line_status'] == 'closed'
def test_match_completed_passes_with_closed_line(app):
"""整单满足性门禁对结案行豁免:一行 matched + 一行 closed 即通过。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_match_facts(fixture)
# 断言:结案前整单不通过(历史阻塞行为)。
assert match_completed(fixture.order) is False
_seed_close_decision(fixture, 1)
# 断言:结案后整单通过(本任务修复目标)。
assert match_completed(fixture.order) is True
def test_all_lines_closed_fails_match_completed(app):
"""全部行结案=无剩余履约内容:整单满足性不通过(此类单应走作废流程)。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_match_facts(fixture)
_seed_close_decision(fixture, 1, version=1)
_seed_close_decision(fixture, 0, version=1)
# 断言:无任何待履约行时 match_completed 返回 False,避免自动建空通知。
assert match_completed(fixture.order) is False
def test_all_lines_closed_aggregate_is_unfulfillable(app):
"""全结案聚合口径锁定:结案行不计满足 ⇒ 整单 unfulfillable(与 match_completed 一致)。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_match_facts(fixture)
_seed_close_decision(fixture, 1, version=1)
_seed_close_decision(fixture, 0, version=1)
status, shortages = _recompute_task_match_aggregate(fixture.order)
# 断言:无 ok 也无 block(无可履约内容)⇒ unfulfillable,且不产生缺货列表。
assert status == 'unfulfillable'
assert shortages == []
def test_closed_status_precedence_over_ok(app):
"""分类优先级锁定:matched+ready 行结案后记 closed(非 ok),且不再贡献整单满足。"""
with app.app_context():
fixture = _seed_frozen_order()
# 仅第 0 行有匹配事实(matched+ready)且已结案:聚合视角为单行订单。
snap_line = fixture.snap_lines[0]
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=fixture.order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
line_index=snap_line.position, match_result='matched', inventory_status='ready',
required_qty='10', available_qty='10', shortage_qty='0',
reservation_id=snap_line.reservation_id, part_number=snap_line.part_number,
is_current=True,
))
db.session.flush()
_seed_close_decision(fixture, 0)
status, shortages = _recompute_task_match_aggregate(fixture.order)
payload = fixture.order.step_payload_json or {}
line_results = payload['current_match_projection']['line_results']
# 断言:结案分类优先于匹配满足;无 ok 无 block ⇒ 整单 unfulfillable。
assert line_results[0]['line_status'] == 'closed'
assert status == 'unfulfillable'
assert shortages == []
@@ -0,0 +1,63 @@
"""
tests/test_line_closure_gate_sync.py
用途:验证结案决定落库后的 Gate 重算联动(对齐放行路径),含 trigger 透传。
依赖:pytest、order_review_fulfillment_decision_service、fulfillment_workflow、匹配事实夹具。
逻辑:结案使聚合转为满足后,_sync 必须重算任务履约态并以 line_fulfillment_closed 触发编排。
"""
from __future__ import annotations
from types import SimpleNamespace
from app import db
from app.models import ShippingProcessExecution
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
_sync_confirmed_task_fulfillment_gates,
)
from tests.test_effective_order_view import _seed_frozen_order
from tests.test_line_closure_fulfillment import _seed_close_decision, _seed_match_facts
def test_close_decision_syncs_gates_with_closed_trigger(app, monkeypatch):
"""结案行豁免使整单满足后,Gate 同步须重算并以 line_fulfillment_closed 触发编排。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_match_facts(fixture)
_seed_close_decision(fixture, 1)
# 计划自审补齐:submit_auto_progress 仅在 OT 绑定活动 Execution 时触发,
# 冻结订单夹具默认不带执行实例,须按结案现场补一条 blocked 的最小执行。
execution = ShippingProcessExecution(
execution_no='EXE-CLOSE-GATE-SYNC', task_id=int(fixture.order.id),
status='blocked', current_gate_code='inventory_sufficiency', lock_version=1,
)
db.session.add(execution)
db.session.flush()
fixture.order.active_process_execution_id = int(execution.id)
db.session.flush()
calls = []
def _capture_progress(*args, **kwargs):
calls.append(('submit_auto_progress', kwargs.get('trigger')))
def _capture_enqueue(*args, **kwargs):
calls.append(('enqueue_post_ot_auto_fulfill_job', kwargs.get('trigger')))
# 拦截编排出口:函数内为局部 import,直接 patch 源模块属性即可生效。
monkeypatch.setattr(
'app.services.shipping_notice.auto_progress_controller.submit_auto_progress',
_capture_progress,
)
monkeypatch.setattr(
'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
_capture_enqueue,
)
fake_case = SimpleNamespace(confirmed_task_id=fixture.order.id)
_sync_confirmed_task_fulfillment_gates(
case=fake_case, actor_id=fixture.user.id, trigger='line_fulfillment_closed',
)
payload = fixture.order.step_payload_json or {}
# 断言:任务履约态被重算为满足,且两个编排出口都带结案 trigger。
assert payload['current_match_projection']['match_status'] == 'fulfillable'
assert ('submit_auto_progress', 'line_fulfillment_closed') in calls
assert ('enqueue_post_ot_auto_fulfill_job', 'line_fulfillment_closed') in calls
@@ -0,0 +1,159 @@
"""
tests/test_reservation_effective_view.py
用途:验证预约注册与核验比对消费「冻结快照 + 已接受人工修正」的有效订单值视图
(修复编辑料号/数量后核验必抛 SHIPPING.RESERVATION_MISMATCH 的阻断缺陷)。
依赖:pytest、reservation_service、task_order_field_editor、test_effective_order_view 夹具。
逻辑:先按冻结值注册预约 → 就地编辑料号/数量 → 再次 ensure 应走同 OT 确认修订
(transfer,自动接替未履约预约)而非抛错;核验比对按归一化料号匹配有效值。
"""
from __future__ import annotations
from decimal import Decimal
import pytest
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingReservation,
)
from app.services.shipping_notice.reservation_service import (
ensure_task_reservations,
record_inventory_verification,
)
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
from tests.test_effective_order_view import _seed_frozen_order
# 预约层契约只接受 5/10 位纯数字预约号(validated_reservation_id);夹具的 'RSV-*'
# 为占位值,须补成契约内值才能驱动预约注册,同时补 PO 以支撑二次注册的归属校验。
_NUMERIC_RESERVATION_IDS = ('1234567890', '2234567890')
def _seed_frozen_order_for_reservations():
"""复用有效视图夹具并补齐预约层契约值:纯数字预约号 + 单头 PO。"""
fixture = _seed_frozen_order()
for snap_line, reservation_id in zip(fixture.snap_lines, _NUMERIC_RESERVATION_IDS):
snap_line.reservation_id = reservation_id
fixture.snapshot.customer_po_number = 'PO-0001'
order_lines = ShippingOrderLine.query.filter_by(
extraction_id=fixture.extraction.id,
).order_by(ShippingOrderLine.position).all()
for line, reservation_id in zip(order_lines, _NUMERIC_RESERVATION_IDS):
for item in ShippingOrderFieldValue.query.filter_by(
extraction_id=fixture.extraction.id, line_id=line.id, field_id='f-rsv',
).all():
item.value_text = reservation_id
item.value_json = reservation_id
for item in ShippingOrderFieldDecision.query.filter_by(
extraction_id=fixture.extraction.id, line_id=line.id, field_id='f-rsv',
).all():
item.resolved_value_json = reservation_id
db.session.flush()
return fixture
def _registered_reservation(fixture, index: int = 0) -> ShippingReservation:
"""按夹具第 index 行的预约号取全局预约注册行。"""
return ShippingReservation.query.filter_by(
task_id=fixture.order.id, reservation_id=_NUMERIC_RESERVATION_IDS[index],
).one()
def test_ensure_task_reservations_follows_effective_values(app):
"""预约注册必须消费有效值:编辑料号后再次 ensure 应自动修订(transfer)而非校验失败。"""
with app.app_context():
fixture = _seed_frozen_order_for_reservations()
# 第一次注册:按冻结值(带尾巴的旧料号)建预约。
ensure_task_reservations(fixture.order)
reservation = _registered_reservation(fixture)
# 断言:初始注册值为冻结快照列原值。
assert reservation.part_number == 'D4-A08AR12000002-'
# 就地编辑第 0 行料号为正确值。
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
# 第二次 ensure(重匹配核验前的真实调用时序):必须成功且预约更新为有效值。
ensure_task_reservations(fixture.order)
db.session.refresh(reservation)
# 断言:预约料号已随有效值修订,状态回 pending(可重新核验)。
assert reservation.part_number == 'D4-A08AR12000002'
assert reservation.status == 'pending'
# 断言:修订走同 OT 确认修订路径,落 reservation_revision_confirmed 审计事件。
assert any(
event.event_type == 'reservation_revision_confirmed'
for event in fixture.order.events
)
def test_ensure_task_reservations_revises_required_qty_from_effective_value(app):
"""编辑数量后再次 ensure 必须按有效数量修订预约,而非保持冻结数量。"""
with app.app_context():
fixture = _seed_frozen_order_for_reservations()
ensure_task_reservations(fixture.order)
reservation = _registered_reservation(fixture)
# 断言:初始注册数量为冻结值 10。
assert reservation.required_qty == Decimal('10')
replace_current_line_field_value(
task=fixture.order, position=0, field_code='qty', value='15',
)
ensure_task_reservations(fixture.order)
db.session.refresh(reservation)
# 断言:需求数量已随有效值修订为 15,且版本在原 OT 上递增(不新建任务)。
# order_data_version 经历两次 bump:编辑器写修正 +1,确认修订接替 +1。
assert reservation.required_qty == Decimal('15')
assert reservation.status == 'pending'
assert fixture.order.order_data_version == 3
assert fixture.order.progress_version == 2
def test_record_inventory_verification_maps_effective_part_number(app):
"""编辑料号后的库存核验必须能按有效料号(归一化后)映射预约,不再抛 RESERVATION_MISMATCH。"""
with app.app_context():
fixture = _seed_frozen_order_for_reservations()
ensure_task_reservations(fixture.order)
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
# 模拟重匹配写入的有效值事实:第 0 行料号带大小写/空白差异(归一化后应相等)。
verification = record_inventory_verification(
fixture.order, inventory_snapshot_id=None, source_config_version='v1',
line_results=[
{
'reservation_id': '1234567890', 'part_number': ' d4-a08ar12000002 ',
'required_qty': Decimal('10'), 'available_qty': Decimal('10'), 'line_status': 'ok',
},
{
'reservation_id': '2234567890', 'part_number': 'D4-B07BR07000001',
'required_qty': Decimal('10'), 'available_qty': Decimal('10'), 'line_status': 'ok',
},
],
)
# 断言:核验轮次成功创建,修订后的预约按有效值完整满足并转 available。
assert verification.lines[0].status == 'available'
assert verification.result_json['available_count'] == 2
def test_locked_reservation_still_rejects_effective_revision(app):
"""已占用/已上传的预约不受有效值自动修订影响:保留 RESERVATION_REVISION_LOCKED 拒绝。"""
with app.app_context():
fixture = _seed_frozen_order_for_reservations()
ensure_task_reservations(fixture.order)
reservation = _registered_reservation(fixture)
reservation.status = 'artifact_reserved'
db.session.flush()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
# 断言:带 Artifact 锁的预约不得自动修订,必须走人工复核。
with pytest.raises(ConflictError) as locked:
ensure_task_reservations(fixture.order)
assert locked.value.code == 'SHIPPING.RESERVATION_REVISION_LOCKED'
db.session.refresh(reservation)
# 断言:预约料号保持注册原值,未被静默改写。
assert reservation.part_number == 'D4-A08AR12000002-'
@@ -0,0 +1,46 @@
"""
tests/test_review_line_fulfillment_shortage_projection.py
用途:锁定行级履约投影的匹配事实关联(修复草稿行ID vs 快照行ID 键错位)。
依赖:pytest、order_review_fulfillment_decision_service、有效视图夹具。
逻辑:确认 Case + 短缺匹配事实下,投影必须报 has_shortage=True 且行级 is_shortage=True。
"""
from __future__ import annotations
from app import db
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewDraft
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
project_review_case_line_decisions,
)
from tests.test_effective_order_view import _seed_frozen_order
def test_line_fulfillment_has_shortage_with_match_facts(app):
"""修复键错位:草稿行经 _line_index 关联匹配事实,has_shortage 必须为真。"""
with app.app_context():
fixture = _seed_frozen_order()
# 短缺事实:第 0 行 not_found、缺 10。
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=fixture.order.id, snapshot_line_id=fixture.snap_lines[0].id,
line_no=1, line_index=0, match_result='not_found', inventory_status='ready',
required_qty='10', available_qty='0', shortage_qty='10',
reservation_id='RSV-1', part_number='D4-A08AR12000002-', is_current=True,
))
case = ShippingOrderReviewCase(
case_no='SNRC-SHORTAGE-PROJ', run_id=911, unit_id=912, document_id=913,
owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
)
db.session.add(case)
db.session.flush()
db.session.add(ShippingOrderReviewDraft(
case_id=case.id, draft_version=1, schema_version_id=fixture.snapshot.schema_version_id,
header_values_json={}, lines_json=[{'draft_line_id': 'line-1', 'part_number': 'D4-A08AR12000002-'}],
))
db.session.flush()
case.current_draft_id = case.drafts[0].id if case.drafts else None
db.session.flush()
result = project_review_case_line_decisions(case)
# 断言:修复前 has_shortage 恒 False(键错位);修复后为 True。
assert result['has_shortage'] is True
assert result['lines'][0]['is_shortage'] is True
@@ -0,0 +1,79 @@
"""trigger_consumer 公共模块测试。
用途:锁定 trigger 文件四态目录契约(根目录待领取 → processing 处理中 →
processed/failed 终态)的领取与归档行为。
依赖:标准库 tempfile/pathlib、scripts.rpa.common.trigger_consumer。
逻辑:claim 原子性(二次领取返回 None)、归档落位、非法入参拒绝。
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common"))
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
def _write_trigger(root: Path, name: str = "batch_1.json") -> Path:
path = root / name
path.write_text('{"schema_version": "x"}', encoding="utf-8")
return path
def test_claim_moves_file_into_processing(tmp_path):
"""首次领取应把 trigger 原子移入 processing/ 并返回新路径。"""
path = _write_trigger(tmp_path)
claimed = claim_trigger(path)
assert claimed == tmp_path / "processing" / path.name
assert claimed.read_text(encoding="utf-8") == '{"schema_version": "x"}'
assert not path.exists()
def test_claim_twice_returns_none(tmp_path):
"""同一 trigger 二次领取必须返回 None(防双消费/重复导出)。"""
path = _write_trigger(tmp_path)
assert claim_trigger(path) is not None
assert claim_trigger(path) is None
def test_archive_processed_and_failed(tmp_path):
"""processing/ 中的文件按 outcome 归档到同名终态目录。"""
path = _write_trigger(tmp_path)
claimed = claim_trigger(path)
done = archive_trigger(claimed, "processed")
assert done == tmp_path / "processed" / path.name and done.exists()
path2 = _write_trigger(tmp_path, "batch_2.json")
claimed2 = claim_trigger(path2)
failed = archive_trigger(claimed2, "failed")
assert failed == tmp_path / "failed" / path2.name and failed.exists()
def test_archive_rejects_bad_outcome_and_unclaimed_path(tmp_path):
"""非法 outcome 与未经领取的路径都必须拒绝,防止归档错位。"""
path = _write_trigger(tmp_path)
with pytest.raises(ValueError):
archive_trigger(path, "processed") # 未领取,不在 processing/ 下
claimed = claim_trigger(_write_trigger(tmp_path, "batch_3.json"))
with pytest.raises(ValueError):
archive_trigger(claimed, "done") # outcome 白名单外
def test_inventory_worker_scans_with_claim(tmp_path):
"""库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。"""
root = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory"
text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8")
assert "claim_trigger" in text
# 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent
assert text.count('trigger_path.parent / "failed"') == 0
def test_receipt_worker_runs_periodic_disk_cleanup():
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
+84
View File
@@ -0,0 +1,84 @@
"""worker_logging 公共文件日志模块测试。
用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、
按大小轮转滚动备份、shutdown 恢复标准流。
依赖:标准库 + scripts/rpa/common/worker_logging。
逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common"))
from worker_logging import ( # noqa: E402
WorkerLogTee,
configure_file_logging,
log_line_timestamp,
rotate_log_file_if_needed,
shutdown_logging,
)
@pytest.fixture(autouse=True)
def _restore_streams():
"""每用例后强制恢复标准流并关闭日志,避免污染其他测试。"""
yield
shutdown_logging()
def test_tee_writes_timestamped_lines_to_both_streams(tmp_path, capsys):
"""tee 应把带时间戳的行同时写入控制台与日志文件。"""
log_file = (tmp_path / "worker.log").open("w", encoding="utf-8", buffering=1)
tee = WorkerLogTee(sys.stdout, log_file)
original_stdout = sys.stdout
sys.stdout = tee
try:
print("hello-worker")
finally:
sys.stdout = original_stdout
log_file.close()
content = (tmp_path / "worker.log").read_text(encoding="utf-8")
assert "hello-worker" in content
assert content.startswith(log_line_timestamp()[:10]) # 日期前缀存在
assert "hello-worker" in capsys.readouterr().out
def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch):
"""超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
path = tmp_path / "worker.log"
for round_no in range(3):
path.write_text(f"round-{round_no}-padding", encoding="utf-8")
rotate_log_file_if_needed(path)
# [断言意图] 滚动语义:最新内容滚入 .1,次新在 .2,最旧(round-0)被删,主文件位空缺待新写入
assert Path(f"{path}.1").read_text(encoding="utf-8") == "round-2-padding"
assert Path(f"{path}.2").read_text(encoding="utf-8") == "round-1-padding"
assert not Path(f"{path}.3").exists()
assert not path.exists() # 轮转后主文件位腾空,由调用方以追加模式重建
def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys):
"""configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log"))
enabled = configure_file_logging()
assert enabled == tmp_path / "logs" / "worker.log"
assert enabled.parent.is_dir() # 日志目录自动创建
print("banner-line")
shutdown_logging()
content = (tmp_path / "logs" / "worker.log").read_text(encoding="utf-8")
assert "banner-line" in content
assert "[logging] tee enabled" in content
out = capsys.readouterr().out
assert "banner-line" in out
def test_configure_without_env_is_noop(monkeypatch):
"""未配置 LOG_FILE 时 configure 返回 None 且不改标准流。"""
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", raising=False)
assert configure_file_logging() is None
@@ -1,22 +1,28 @@
"""
backend/tests/test_shipping_formal_task_edit_audit.py
用途:验收正式任务编辑成功/拒绝与 change_effect 失效写入 ShippingAuditEvent。
用途:验收正式任务编辑成功审计、反向锁拒绝审计与 change_effect 失效写入 ShippingAuditEvent。
依赖:task_workflow、ShippingAuditEvent、test_shipping_review_formal_task_edit 种子助手。
逻辑:editable 拒绝写 formal_task_edit_rejected;inventory 失效写
formal_task_field_edited + inventory_match_invalidated + excel_export_invalidated。
逻辑:未配置策略字段编辑成功写 formal_task_field_edited(old→new;reason/evidence 缺省落哨兵值);
显式 editable=False 反向锁仍拒绝并写 formal_task_edit_rejected;Excel ready 冻结仍拒绝;
inventory 失效写 formal_task_field_edited + inventory_match_invalidated + excel_export_invalidated。
"""
from __future__ import annotations
from app import db
from app.models import ShippingAuditEvent, ShippingNoticeLineInventoryMatch
from app.models import (
ShippingAuditEvent,
ShippingNoticeLineInventoryMatch,
ShippingOrderReviewEvent,
)
from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES
from app.services.shipping_notice.task_workflow import update_notice_line
from tests.test_shipping_review_formal_task_edit import (
_attach_extraction,
_link_order_task,
_review_payload,
_seed_ready_export_artifact,
_task,
)
@@ -31,10 +37,75 @@ def test_formal_task_edit_audit_event_types_frozen():
})
def test_formal_edit_rejection_writes_audit_event(app):
"""Schema 禁止编辑时仍落 formal_task_edit_rejected,可被审计中心检索。"""
def test_unconfigured_field_edit_writes_formal_task_edited_audit(app):
"""新契约:未配置策略字段编辑成功,写 formal_task_field_edited(old→new 可检索)。"""
with app.app_context():
task = _task(task_no='SN-FORMAL-AUDIT-REJ-001')
task = _task(task_no='SN-FORMAL-AUDIT-EDIT-001')
_attach_extraction(
task,
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
)
db.session.commit()
response = update_notice_line({
'task_no': task.task_no,
'line_index': 0,
'patch': {'reservation_id': '3000092917'},
**_review_payload(),
})
assert response['status'] == 'ok'
edited = (
ShippingAuditEvent.query
.filter_by(task_no=task.task_no, event_type='formal_task_field_edited')
.one()
)
assert edited.result == 'success'
meta = edited.metadata_json or {}
field_changes = meta.get('field_changes') or []
assert field_changes
assert field_changes[0]['previous_value'] == '3000000001'
assert field_changes[0]['new_value'] == '3000092917'
def test_quick_edit_without_reason_evidence_uses_sentinel_audit_values(app):
"""新契约:reason/evidence 缺省时编辑成功,审计落哨兵值(NOT NULL 审计列不破坏)。"""
with app.app_context():
task = _task(task_no='SN-FORMAL-AUDIT-SENTINEL-001')
_attach_extraction(
task,
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
)
db.session.commit()
response = update_notice_line({
'task_no': task.task_no,
'line_index': 0,
'patch': {'reservation_id': '3000092917'},
'event_source': 'workspace_api',
'reviewed_by_id': 1,
'expected_order_data_version': 1,
})
assert response['status'] == 'ok'
edited = (
ShippingAuditEvent.query
.filter_by(task_no=task.task_no, event_type='formal_task_field_edited')
.one()
)
assert edited.result == 'success'
assert (edited.metadata_json or {}).get('evidence_ref') == 'inline:match-table'
event = ShippingOrderReviewEvent.query.filter_by(task_id=task.id).one()
assert event.evidence_ref == 'inline:match-table'
assert event.reason == 'quick_field_edit'
assert int(event.reviewed_by_id) == 1
def test_explicit_readonly_field_still_rejected_with_audit(app):
"""状态制下显式 editable=false 仍为反向锁:拒绝写入并落 formal_task_edit_rejected 审计。"""
with app.app_context():
task = _task(task_no='SN-FORMAL-AUDIT-RELOCK-001')
_attach_extraction(
task,
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
@@ -50,6 +121,9 @@ def test_formal_edit_rejection_writes_audit_event(app):
})
assert response['status'] == 'failed'
assert response['data']['error_code'] == 'SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN'
# Excel 未 ready(无冻结),拒绝必须来自策略反向锁而非冻结门。
from app.services.shipping_notice.schema_edit_policy import is_excel_ready_for_task
assert is_excel_ready_for_task(task) is False
events = (
ShippingAuditEvent.query
@@ -59,6 +133,36 @@ def test_formal_edit_rejection_writes_audit_event(app):
assert len(events) == 1
assert events[0].result == 'rejected'
assert events[0].error_code == 'SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN'
meta = events[0].metadata_json or {}
assert meta.get('scope') == 'line'
assert meta.get('field_codes') == ['reservation_id']
def test_excel_ready_freeze_still_rejects_edit(app):
"""Excel ready(ready Artifact)后全局冻结仍拒绝编辑,即使字段处于默认可编辑状态。"""
with app.app_context():
task = _task(task_no='SN-FORMAL-AUDIT-FROZEN-001')
_attach_extraction(
task,
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
)
_seed_ready_export_artifact(task)
db.session.commit()
response = update_notice_line({
'task_no': task.task_no,
'line_index': 0,
'patch': {'reservation_id': '3000092917'},
**_review_payload(),
})
assert response['status'] == 'failed'
assert response['data']['error_code'] == 'SHIPPING.ORDER_EXCEL_FROZEN'
# 冻结门位于 _prepare_review_context(策略检查之前),当前不写 formal_task_edit_rejected 审计。
assert (
ShippingAuditEvent.query
.filter_by(task_no=task.task_no, event_type='formal_task_edit_rejected')
.count()
) == 0
def test_inventory_invalidation_writes_formal_edit_audit_chain(app):
@@ -0,0 +1,100 @@
"""
tests/test_shipping_notice_creation_effective.py
用途:验证正式通知行物化携带冻结后修正值,且整单建通知排除已结案行。
依赖:pytest、shipping_notice_creation_service、notice_line_service、行级履约决定模型。
逻辑:库存门禁通过(或行豁免)后建 Notice,断言 NoticeLine 的料号/数量来自有效视图,
结案行既不进门禁目标集也不物化为通知行。
"""
from __future__ import annotations
import pytest
from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingCustomer,
ShippingNoticeLine,
ShippingNoticeLineInventoryMatch,
)
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
from tests.test_effective_order_view import _seed_frozen_order
from tests.test_line_closure_fulfillment import _seed_close_decision
def _seed_customer(snapshot):
"""给快照挂一个 active 客户(建 Notice 门禁必填)。"""
customer = ShippingCustomer(standard_name='有效视图客户', short_code='EFFC', status='active')
db.session.add(customer)
db.session.flush()
snapshot.customer_id = customer.id
db.session.flush()
def _seed_match_row(order, snap_line, *, match_result='matched', shortage='0'):
"""给冻结行补一条当前匹配事实(matched+ready 表示门禁可过)。"""
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
line_index=snap_line.position, match_result=match_result, inventory_status='ready',
required_qty='10', available_qty='10', shortage_qty=shortage,
reservation_id=snap_line.reservation_id, part_number=snap_line.part_number,
is_current=True,
))
db.session.flush()
def test_notice_lines_carry_corrected_part_number(app):
"""修正后的料号必须进入正式通知行(通知行会被 Excel/货代消费)。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_customer(fixture.snapshot)
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
_seed_match_row(fixture.order, fixture.snap_lines[0])
# 注:brief 原文为整单调用,但夹具第二行无匹配事实会触发门禁 ConflictError(经控制器确认),
# 改为仅选中第 0 行——与 Step 2 预期断言差异(单行)一致。
notice = create_shipping_notice_after_inventory_gate(
fixture.order, snapshot_line_ids={int(fixture.snap_lines[0].id)},
)
rows = ShippingNoticeLine.query.filter_by(notice_id=notice.id).all()
# 断言:通知行料号是修正值,而不是快照冻结的带尾巴旧值。
assert [row.part_number for row in rows] == ['D4-A08AR12000002']
def test_notice_creation_skips_closed_line(app):
"""一行 matched + 一行结案:整单建通知成功且通知行不含结案行。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_customer(fixture.snapshot)
_seed_match_row(fixture.order, fixture.snap_lines[0])
_seed_match_row(
fixture.order, fixture.snap_lines[1], match_result='not_found', shortage='10',
)
_seed_close_decision(fixture, 1)
notice = create_shipping_notice_after_inventory_gate(fixture.order)
rows = ShippingNoticeLine.query.filter_by(notice_id=notice.id).all()
# 断言:只有第 0 行进入通知;结案行既过门禁又被物化排除。
assert [row.snapshot_line_id for row in rows] == [int(fixture.snap_lines[0].id)]
def test_whole_order_notice_rejected_when_all_lines_closed(app):
"""全部行结案=无可履约内容:整单建 Notice 必须按门禁未通过拒绝,防止建空通知。"""
with app.app_context():
fixture = _seed_frozen_order()
_seed_customer(fixture.snapshot)
_seed_match_row(fixture.order, fixture.snap_lines[0])
_seed_match_row(
fixture.order, fixture.snap_lines[1], match_result='not_found', shortage='10',
)
_seed_close_decision(fixture, 1, version=1)
_seed_close_decision(fixture, 0, version=1)
# 断言:结案剔除后目标行集为空,整单调用走门禁未通过分支(与 match_completed 口径一致)。
with pytest.raises(ConflictError) as exc_info:
create_shipping_notice_after_inventory_gate(fixture.order)
assert exc_info.value.code == 'SHIPPING.INVENTORY_GATE_NOT_PASSED'
assert 'SHIPPING.INVENTORY_GATE_NOT_PASSED' in repr(exc_info.value)
@@ -1,9 +1,9 @@
"""
tests/test_shipping_order_field_purposes.py
用途:验证履约门禁只从冻结订单快照及其冻结策略读取预约单号。
依赖:订单 Schema service、冻结快照模型、reservation_gate。
逻辑:当前任务不得读取可变 FieldValue 或旧任务行投影;策略缺少能力时必须明确阻断。
用途:验证履约门禁按有效视图(冻结快照 + 冻结后人工修正)读取预约单号。
依赖:订单 Schema service、冻结快照模型、reservation_gate(内部经 effective_order_view 叠加修正)。
逻辑:冻结后人工修正的预约单必须进入门禁判定(修正值生效);策略缺少能力时仍明确阻断。
"""
from __future__ import annotations
@@ -87,15 +87,29 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool =
return task
def test_task_reservation_gate_uses_frozen_value_not_mutable_projection_or_field_value(app):
"""门禁以冻结预约单为准,后续 FieldValue 变化均不得重解释履约。"""
def test_task_reservation_gate_reads_effective_amendment_over_frozen_value(app):
"""有效视图契约:冻结后人工修正的预约单必须进入门禁判定(修正值生效)。"""
with app.app_context():
task = _task_with_reservation('3000000001')
# 模拟编辑窗的人工修正:当前 accepted Extraction 的 FieldValue 即修正事实,
# 经 effective_order_view 对位叠加后必须被门禁消费(区别于旧冻结-only 契约)。
value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one()
value.value_text = '3000000002'
value.value_json = '3000000002'
db.session.commit()
assert task_reservation_gate_issues(task) == []
def test_task_reservation_gate_rejects_invalid_effective_amendment(app):
"""有效视图契约:非法修正值同样进入门禁判定并被拦截(不再静默回退冻结值)。"""
with app.app_context():
task = _task_with_reservation('3000000001')
value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one()
value.value_text = 'INVALID'
value.value_json = 'INVALID'
db.session.commit()
assert task_reservation_gate_issues(task) == []
issues = task_reservation_gate_issues(task)
assert issues != []
def test_task_reservation_gate_blocks_snapshot_without_reservation_capability(app):
@@ -451,7 +451,9 @@ def test_confirmed_review_case_serializes_editability_from_formal_order_task(app
payload = serialize_review_case(case)
assert payload['has_formal_ot'] is True
assert payload['formal_editable_field_ids'] == []
# 新契约(状态制):冻结 Schema 未配置 task_edit_policy 的 qty-id 默认可编辑;
# 正式 OT 无 ready Artifact(Excel 未就绪)不冻结,投影按状态制从 OT 判定可编辑字段。
assert payload['formal_editable_field_ids'] == ['qty-id']
from app.services.shipping_notice.order_review_draft_service import (
add_line,
build_confirmable_draft_summary,
@@ -20,15 +20,13 @@ def _receipt_config(source_id: int):
return ShippingReceiptReportConfig(
inventory_source_id=source_id,
enabled=True,
report_path_json={
'program_group': 'Bison',
'program_label': 'AWSBI',
'report_group': 'Inbound',
'report_name': 'Receipt Detail',
},
query_parameters_json=[],
warehouse_ids_json=['AWSDU'],
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
)
@@ -1,11 +1,11 @@
"""
backend/tests/test_shipping_review_formal_task_edit.py
用途:验收正式任务字段写路径(Schema 策略 + order_data_version)与 change_effect 下游失效。
用途:验收正式任务字段写路径(状态制编辑闸门 + order_data_version)与 change_effect 下游失效。
依赖:task_workflow、schema_edit_policy、order_schema_service、ShippingOrderTask。
逻辑:默认 reservation_id 不可写;Schema editable=True 可写并递增版本;
rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并置 invalidated_from_stage;
正式字段编辑以 Excel ready 为硬冻结,不再用 order_snapshot_id 阻断。
逻辑:未配置 task_edit_policy 的字段默认可写(状态制),显式 editable=False 反向锁;
可写成功递增 order_data_version;Excel ready 为硬冻结;
rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并置 invalidated_from_stage。
"""
from __future__ import annotations
@@ -284,16 +284,13 @@ def _seed_ready_export_artifact(task: ShippingOrderTask, *, path: str | None = N
return artifact
def test_formal_edit_rejects_default_readonly_field(app):
"""Schema 显式 editable=false 时拒绝,即使字段在 legacy 白名单内。"""
def test_formal_edit_accepts_unconfigured_field_by_default(app):
"""新契约:未配置 task_edit_policy 的字段在 Excel 未就绪时可直接编辑。"""
with app.app_context():
task = _task()
_attach_extraction(
task,
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
field_policies={
'reservation_id': {'editable': False},
},
)
db.session.commit()
@@ -303,8 +300,9 @@ def test_formal_edit_rejects_default_readonly_field(app):
'patch': {'reservation_id': '3000092917'},
**_review_payload(),
})
assert response['status'] == 'failed'
assert response['data']['error_code'] == 'SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN'
assert response['status'] == 'ok'
refreshed = db.session.get(ShippingOrderTask, task.id)
assert int(refreshed.order_data_version) == 2
def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
@@ -28,6 +28,7 @@ from app.services.shipping_notice.reservation_service import (
record_inventory_verification,
)
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
@@ -240,26 +241,30 @@ def test_confirmed_task_revision_transfers_unfulfilled_reservation_with_audit(ap
ensure_task_reservations(first_task)
db.session.flush()
original = ShippingReservation.query.filter_by(reservation_id=first_snapshot.lines[0].reservation_id).one()
line = first_snapshot.lines[0]
ot_id = int(first_task.id)
ot_count = ShippingOrderTask.query.count()
# 修订沿用同一 OT:不新建任务/快照,仅改写冻结行数据并沿用该 OT,
# 由 _transfer_confirmed_revision 完成 version bump 与 Reservation 接替。
line = first_snapshot.lines[0]
line.part_number = '000123-REV'
line.qty = Decimal('13.5')
# 修订沿用同一 OT:不新建任务/快照。契约翻转(有效视图):冻结快照不再就地改写,
# 改经人工字段编辑器写入已接受修正,由预约层按有效值自动完成 transfer 接替。
replace_current_line_field_value(task=first_task, position=0, field_code='part_number', value='000123-REV')
replace_current_line_field_value(task=first_task, position=0, field_code='qty', value='13.5')
db.session.flush()
registered = ensure_task_reservations(first_task)
# 同一 OT 上完成接替:不新建任务行,仅版本 bump,Reservation 仍指向该 OT。
# (order_data_version 在冻结值 7 之上经历两次编辑器 bump 与一次确认修订 bump。)
assert registered == [original]
assert original.task_id == ot_id
assert original.snapshot_line_id == line.id
assert original.part_number == '000123-REV'
assert original.required_qty == Decimal('13.5')
assert first_task.order_data_version == 8
assert first_task.order_data_version == 10
assert first_task.progress_version == 2
# 冻结快照保持审计锚点:强类型列不得被修订改写。
assert line.part_number == '000123'
assert line.qty == Decimal('12.50000000')
# 不产生重复 OT 行。
assert ShippingOrderTask.query.count() == ot_count
# 审计事件落在该 OT 上。
@@ -1,16 +1,17 @@
"""
backend/tests/test_shipping_schema_edit_policy.py
用途:验收正式任务 Schema 编辑策略默认只读与显式放行(无 legacy 绕过)。
用途:验收正式任务 Schema 编辑策略状态制默认(未配置默认可写)与显式反向锁。
依赖:schema_edit_policy、pytest。
逻辑:无 task_edit_policy → 不可编辑;显式 editable=True → 可编辑;
excel_ready 后全局关闭。
逻辑:无 task_edit_policy → 默认可编辑(Excel ready 前状态制放行);显式 editable=False → 反向锁;
excel_ready 后全局硬冻结。
"""
from __future__ import annotations
from app.services.shipping_notice.schema_edit_policy import (
DEFAULT_EDITABLE_AFTER_TASK_CREATION,
field_task_edit_policy,
is_excel_ready_for_task,
is_field_editable_for_formal_task,
list_editable_formal_field_ids,
@@ -18,13 +19,20 @@ from app.services.shipping_notice.schema_edit_policy import (
)
def test_default_formal_fields_are_readonly() -> None:
"""默认创建任务后不可编辑。"""
assert DEFAULT_EDITABLE_AFTER_TASK_CREATION is False
assert not is_field_editable_for_formal_task({'field_id': 'po-id'})
def test_default_formal_fields_are_editable_until_excel_ready() -> None:
"""新契约:未配置策略的字段默认可编辑(状态制),显式 editable=false 仍可反向锁。"""
assert DEFAULT_EDITABLE_AFTER_TASK_CREATION is True
assert field_task_edit_policy(None)['editable'] is True
assert field_task_edit_policy({'task_edit_policy': {'editable': False}})['editable'] is False
# Excel 未就绪时未配置策略字段可写;Excel ready 后仍全局硬冻结。
assert is_field_editable_for_formal_task({'field_id': 'po-id'}, excel_ready=False) is True
assert is_field_editable_for_formal_task({'field_id': 'po-id'}, excel_ready=True) is False
assert list_editable_formal_field_ids([
{'field_id': 'po-id', 'field_code': 'po_number'},
]) == []
], excel_ready=False) == ['po-id']
assert list_editable_formal_field_ids([
{'field_id': 'po-id', 'field_code': 'po_number'},
], excel_ready=True) == []
def test_schema_explicit_editable_is_honored_until_excel_ready() -> None:
@@ -1,11 +1,12 @@
"""
backend/tests/test_shipping_task_center_review_run_deep_link.py
用途:验收任务中心 Notice/OT 摘要注入 review_run_no 与 order_task_no,供 UI-04 深链
与工作台右卡 work-item 投影键。
用途:验收任务中心 Notice/OT 摘要注入 review_run_no / order_task_no / review_case_no,
供 UI-04 深链(run_no + case_no)与工作台右卡 work-item 投影键。
依赖:query_service._inject_unified_processing_fields、ShippingOrderTask、pytest。
逻辑:Notice 挂 OT 时 SUMMARY 必含 review_run_no;直接序列化 OT 时 order_task_no
必须等于自身 task_no(禁止 enrich 冲成 null)。
必须等于自身 task_no(禁止 enrich 冲成 null);OT 有确认 Case 时必须注入
review_case_no(缺它工作台选法 2 不拉 Case、身份链断裂、五阶段页签全锁)。
"""
from __future__ import annotations
@@ -98,3 +99,50 @@ def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app):
assert detail['order_task_no'] == 'OT-TC-OT-SELF-1'
assert detail['task_no'] == 'OT-TC-OT-SELF-1'
assert detail['review_run_no'] == run.run_no
def test_serialize_order_task_injects_confirmed_review_case_no_for_workbench_deeplink(app):
"""
OT 摘要/详情必须携带确认 Case 号,任务中心 OT 直链才能绑定工作台工作项。
关键断言:无 case_no 的 OT 直链下,工作台对正式下游阶段任务走选法 2 不拉 Case,
activeCase/displayCase/confirmedNoticeTaskNo 全空、五阶段页签全锁;
review_case_no 是 openOrderProcessing 追加 case_no 深链参数的唯一来源,
SUMMARY 与 workbench DETAIL 都必须注入。
"""
with app.app_context():
from app.models import ShippingOrderReviewCase
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, document = _seed_run_input(suffix='TC-CASE-LINK')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
order_task = ShippingOrderTask(
task_no='OT-TC-CASE-LINK-1',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=int(run.id),
owner_agent_id=int(agent.id),
status='blocked',
stage='inventory_fetching',
progress_version=2,
)
db.session.add(order_task)
db.session.flush()
# 模拟 RPA 超时阻断的正式下游 OT:存在一条已确认绑定该 OT 的复核 Case。
case = ShippingOrderReviewCase(
case_no='SNRC-TC-CASE-LINK', run_id=int(run.id),
unit_id=int(run.extraction_plan.units[0].id),
document_id=int(document.id), owner_user_id=user.id,
status='confirmed', confirmed_task_id=int(order_task.id),
)
db.session.add(case)
db.session.commit()
summary = serialize_task_summary(order_task, viewer_user_id=user.id)
detail = serialize_task_detail(
order_task, viewer_user_id=user.id, include_stage_context=True, view='workbench',
)
# 关键断言:SUMMARY / workbench DETAIL 均注入确认 Case 号(深链 case_no 锚点)。
assert summary['review_case_no'] == 'SNRC-TC-CASE-LINK'
assert detail['review_case_no'] == 'SNRC-TC-CASE-LINK'
@@ -0,0 +1,40 @@
"""
tests/test_ui_state_effective_values.py
用途:验证通知准备投影的值列(预约号/料号/需求数量)消费有效订单值视图。
依赖:pytest、ui_state._build_stage_context 阶段上下文构建、有效视图夹具 _seed_frozen_order。
逻辑:编辑料号后(重匹配前),frozen_order_lines 与 preparation.lines 的值列必须立即显示
新值(有效值优先、快照列回退);匹配结果列不受影响,仍诚实反映最近一轮匹配。
"""
from __future__ import annotations
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
from tests.test_effective_order_view import _seed_frozen_order
def test_preparation_value_columns_follow_effective_values(app):
"""保存修正后(重匹配前)值列立即显示新值。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
from app.services.shipping_notice import ui_state
# _build_stage_context 实签名为 (task, *, lifecycle_stage, stp_facts, process_gate);
# 直接传正式 OT(夹具即 OT),经 _resolve_order_task_for_gate_lookup 原样返回。
context = ui_state._build_stage_context(
fixture.order,
lifecycle_stage='fulfillment_prep',
stp_facts=None,
process_gate=None,
)
preparation = context['preparation']
frozen_lines = preparation['frozen_order_lines']
prep_lines = preparation['lines']
# 断言:值列为有效值(而非快照冻结的带尾巴旧值)。
assert frozen_lines[0]['part_number'] == 'D4-A08AR12000002'
assert prep_lines[0]['part_number'] == 'D4-A08AR12000002'
# 断言:未被编辑的第 1 行保持冻结值(对位叠加只影响被改行)。
assert frozen_lines[1]['part_number'] == 'D4-B07BR07000001'
assert prep_lines[1]['part_number'] == 'D4-B07BR07000001'
+47 -13
View File
@@ -17,6 +17,16 @@
**批量操作**:仅「货代上传」阶段的正式 Notice 行有复选框(`isFreightUploadRow`),勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。
## 任务中心 OT 直链工作台:深链补 Case 锚点 + 任务详情兜底(2026-09-17)
**背景缺陷**:我的待办抽屉对 task 类待办(OT/Notice)发出的「进入订单生命周期工作台」深链只有 `run_no + lifecycle_stage + conversation_id + task_no`,**没有 `case_no`**(后端 task 投影从不注入 `review_case_no`)。处于正式下游阶段(通知准备/货代上传)的 OT 进工作台后,队列项命中 `isFormalDownstreamNavItem`(选法 2)刻意不拉 Case → `activeCase` 恒空 → `displayCase/activeReviewNavItem/confirmedNoticeTaskNo` 全部解析为空 → `loadFormalTaskDetail` 空号早退、挂载时已按 `route.query.task_no` 预取的任务详情被丢弃 → `lifecycleUiState` 三级裁决(activeCase → formalTaskDetail → 队列项 entries)全部落空,五阶段页签全锁(「请先完成当前阶段」)+「当前步骤需要人工处理」空壳。处于订单复核阶段的任务不受影响(不命中选法 2,Case 正常加载),因此缺陷只在被 Gate 阻断的下游阶段任务上暴露。
**后端**(`query_service._inject_unified_processing_fields`,列表与详情同源):解析出权威 OT 后按 `ShippingOrderReviewCase.confirmed_task_id`(唯一约束)反查确认 Case,为 task 类待办注入 `review_case_no`;`openOrderProcessing` 既有逻辑检测到该字段即自动追加 `case_no` 深链参数,工作台由此可直接绑定工作项。
**前端**(`ShippingOrderReviewView`):新增 `deepLinkOrderTaskNo`(只认 `OT-` 前缀,SN 号不作 work-item 键);`loadFormalTaskDetail` 在 `confirmedNoticeTaskNo` 为空**且不存在任何 Case 上下文**(`displayCase` 为空,即选法 2 直链态)时回退深链 OT 号,使挂载预取被消费;`onMounted` 在深链携带 OT 号时显式触发一次(复用预取请求,不重复拉取)。已有 Case 上下文时禁止回退,防止深链 OT 串到用户切换后的其他文件。回看前置阶段(如订单复核)的 Case 数据由既有 `REVIEW_EDITOR_NEEDED_STAGES` 懒加载 watcher 按深链 `case_no` 补拉,不改变选法 2 的性能契约。
**连带修复(同日)——懒加载与初次装配的代际竞态**:上述修复让 `formalTaskDetail` 首次可在装配期落地,暴露一个既有缺陷——阶段懒加载 watcher 随之触发的 `loadReviewCase` 会自增 `caseLoadGeneration`,令在途 `load()` 的数据装配全部按代际失效,且其 `finally` 在代际守卫**之后**才清 `initialLoading`,首屏永久卡在「正在加载复核结果...」、run/queue 永不装配。两层收口:① 懒加载 watcher 源改为 `[lifecycleActiveStageCode, initialLoading, runLoading]`,装配期(任一旗为真)让位,装配完成后由旗标翻转重新触发、按当前 stage 补拉 Case;② `load()` 的 `finally` 中 `initialLoading` 清旗移到代际守卫之前(该旗仅由 `isInitialLoad` 的本次 load 置位,无条件收尾语义正确),即使未来出现新的代际接管方,壳也只会短暂缺数据而不会永久卡死。
## 阻塞原因具体化:资格快照回退 + 原因/动作语义分离(2026-09-17)
**背景**:批次中心与工作台「当前任务」对建单前 Review Case 一律显示兜底文案「当前步骤需要人工处理」(同卡重复两遍),而具体原因(如 `customer_unresolved`「客户尚未确认」)早已随资格评估持久化在 `draft.validation_result_json.issues[].explainability`,只是从未进入 `blocking_reason` 通道。
@@ -701,6 +711,24 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
- **重解析终态闭环不变式(2026-08-30)**:PDF 级重解析后继 Run 收口时业务必须二选一 —— 新版 Case 已上位 Stream,或旧版 Case 已恢复为可编辑状态;新版缺失或激活被拒时转入既有失败恢复链(`finalize_document_reparse`),禁止旧 Case 停留在 `reparse_pending` 被孤儿化。前端配套:重解析完成后工作台落在历史版本时自动跳转 Stream 当前版本(版本历史面板显式查看除外),跳转失败必有可见报错。
- **变更边界**:Run 冻结解析器版本、策略版本、超时和最大尝试次数;运行时版本漂移安全阻断旧 Run。用户态 Run API 不返回正文、解析快照、原始结果或内部配置。
### 有效订单值视图与行结案豁免(2026-09-17)
**有效订单值视图(effective_order_view)**:订单冻结后的人工字段修正(编辑窗
`update-notice-fields`)写入当前 accepted Extraction 的 Decision/FieldValue;库存匹配
(order_field_purposes → effective_order_field_values)、Excel 行值(export)与通知行物化
(notice_line_service.line_overrides)统一消费「冻结快照 + 修正叠加」的有效值。快照保持
不可变审计锚点;整行替换(增删行)后行级叠加保守跳过(行集维度待后续特性)。
**行结案(close_unfulfillable)端到端豁免**:与 `release_inventory_shortage` 同源同口径——
满足性聚合与 `match_completed` 中结案行不阻断、不进缺货列表(行状态 `closed`);整单建
Notice 的目标行集剔除结案行(不物化为通知行);滚动导出资格(reservation_service /
export / exportable_snapshot_line_ids)无论库存状态一律剔除结案行;结案决定落库后触发
`_sync_confirmed_task_fulfillment_gates(trigger='line_fulfillment_closed')` 重算 Gate。
**边界**:全部行结案时 `match_completed` 按不通过处理(无剩余履约内容,应走作废流程);
「冻结后重解析改道试算+应用」(二期 D)尚未实现,重解析窗口仍维持确认前语义。
**结案时序边界(操作规约)**:结案触发自动推进存在时序边界——多行订单若先结案短缺行使整单立即满足,异步编排会把“尚未结案的有库存行”一并建入通知。规约:多行结案必须使用缺口复核的批量关行(close_remaining_fulfillment,多选行单事务提交,Worker 只见终态),或按「先结有库存行、最后结短缺行」的顺序逐行结案;自动履约的“恰好单一开放行”守卫(line_auto_fulfill_coordinator)保证多条开放行永不自动合并。
### 2026-07-21 文档级抽取优化历史阶段与 Review 门禁
> 本路线描述“避免把邮件和全部附件一次性丢给单个 LLM”的目标架构,不沿用旧整单/整封邮件单次模型调用作为兼容路径。各阶段必须按顺序实施;阶段内测试、自检和 Review 的阻断问题全部关闭并满足验收标准后,才能自动进入下一阶段。Dify 画布由管理员按本文档手工修改,代码阶段不直接操作 Dify。
@@ -2945,7 +2973,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui
| trigger 目录 | `data\inventory_triggers` | `data\freight_receipt_rpa\receipt_triggers` |
| drop 目录 | `data\inventory_drop` | `data\freight_receipt_rpa\receipt_drop` |
| 回调端点 | `/api/shipping-notice/rpa/inventory-batch-ready` | `/api/shipping-notice/rpa/receipt-batch-ready` |
| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | **无**:收料 Worker 不发心跳、不写 `.hxops_rpa_shared_mount` |
| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | 心跳已接:以 `<主机名>-receipt` 独立身份周期上报(ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_ID`);仍不写 `.hxops_rpa_shared_mount` 哨兵,触发前无 fail-fast 在线检查 |
| 结果归属 | 库存快照/库存匹配 | MinIO 原样归档 + 企微投递,绝不进入库存链路 |
路径对应关系(测试环境;正式环境把 `Test` / `test-data` 换成 `Prod` / `prod-data`):
@@ -2993,15 +3021,17 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
-SecretFile "C:\HxopsRpaSecrets\test.xml"
```
启动成功会输出 `[freight_receipt_rpa_worker] started trigger_dir=... drop_dir=...`,随后轮询 `receipt_triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_receipt_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。
启动成功会输出 `[freight_receipt_rpa_worker] started` 独立行,后跟缩进字段块(` mock=...`、` api_base=...`、` trigger_dir=...`、` drop_dir=...`、` log=...` 等,完整字段以 `receipt_rpa_worker.py` 启动 banner 为准),随后轮询 `receipt_triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_receipt_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。
后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,仅把动作换成收料启动脚本。收料 Worker 不写 `worker.log`,日志输出到控制台;计划任务建议用 `cmd.exe` 包装做文件重定向:
启动脚本同时自动注入两个 Worker 运行变量:`SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`(ps1 自动设为 `data\freight_receipt_rpa\logs\worker.log`,文件日志带时间戳并按大小轮转,无需手工配置)与 `SHIPPING_NOTICE_RPA_WORKER_ID=<主机名>-receipt`(独立心跳身份,监控端按此身份出独立收料卡片,不与库存 Worker 的 `<主机名>-<pid>` 混淆)。收料 Worker 的文件日志、启动 banner、心跳上报与周期磁盘保留清理(含共享 Profile 的孤儿 `receipt_*`)能力均已与库存 Worker 对齐;两个 Worker 禁止共写同一日志文件,各自由启动脚本指向各自根目录下的 `logs\worker.log`。
后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,仅把动作换成收料启动脚本。收料 Worker 由启动脚本注入 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`,文件日志写入 `data\freight_receipt_rpa\logs\worker.log`(tee 控制台、带时间戳、按大小轮转);计划任务仍可用 `cmd.exe` 包装对控制台输出做重定向留档:
```powershell
$TestApiBase = "http://<test后端地址>:<端口>"
$ReceiptAction = New-ScheduledTaskAction `
-Execute "cmd.exe" `
-Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_receipt_rpa\logs\receipt_worker.log"" 2>&1" `
-Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_receipt_rpa\logs\receipt_console_output.log"" 2>&1" `
-WorkingDirectory "C:\HxopsRpaTest"
# $Trigger / $Principal / $Settings 与 1.5.10 的库存任务完全一致:
# AtLogOn + Interactive;RestartCount 10、RestartInterval 1 分钟、ExecutionTimeLimit 0、MultipleInstances IgnoreNew。
@@ -3032,11 +3062,11 @@ SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900
- 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。
- 企微逐文件推送与汇总发给排程任务配置的接收人(`notify_user_ids` + `notify_enabled`),接收人必须已完成企微绑定,否则投递记 `WECOM_USER_UNBOUND` 失败。
排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用收料配置,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `receipt_worker.log` 巡检。
排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `data\freight_receipt_rpa\logs\worker.log` 巡检。
#### 1.9.4 端到端验证
1. 管理端「货代管理 → 库存站点」抽屉为目标站点启用收料配置:DBS 必须配置 Warehouse(每个 Warehouse 展开一个单元);Crane 固定 `Inbound Details`,拒绝 Warehouse 与查询条件。
1. 管理端「货代管理 → 库存站点」抽屉为目标站点配置收料卡(与库存同构):DBS 必须在查询条件中维护 Warehouse 条件(支持多值,每个 Warehouse 展开一个单元);报表日期不得出现在查询条件中。Crane 固定 `Inbound Details`,拒绝查询条件。收料无独立开关,站点启用即参与收料排程。
2. 链路演练(不依赖真实货代网站):以 `-Mock` 启动收料 Worker → 排程管理手工执行一次「货代收料 RPA」→ 确认回调、MinIO 归档、企微投递全链路成功后停止 Mock Worker。
3. 真实链路:启动真实收料 Worker 并触发排程,依次确认:
- `ls /mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers` 出现 `receipt_export_batch_{run_no}.json`;
@@ -3054,8 +3084,8 @@ SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900
- 回调报 `SHIPPING.RECEIPT_CALLBACK_FILE_INVALID`:`file_path` 不在收料 drop 根内、非 `.xlsx`、空文件或超过 `FILE_ASSET_MAX_SIZE_MB`;多为收料/库存目录串用所致。
- 单元长期 `awaiting_rpa`、排程停在 `awaiting_receipt_rpa_callback`:Worker 停止或崩溃;超过 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 由回收逻辑置 `RPA.RECEIPT_CALLBACK_TIMEOUT`,**不自动重试**,需管理员带原因重试或等下一轮 Cron。
- DBS/Crane 登录或导出失败:先在 Windows 手工登录确认 MFA/SSO/代理;Crane 无论 Profile 首页保存为何,Worker 均强制进入 `#/inbound-details-query` 用页面默认条件执行;确认 Profile 已启用且 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 两端一致(否则无法解密凭据)。
- `receipt_drop` 磁盘占用增长:归档完成后本地文件不再被后端读取,收料 Worker **不做本地清理**;按运维周期人工清理,建议保留最近几天便于排障。
- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `receipt_worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。
- `receipt_drop` 磁盘占用增长:收料 Worker 已启用周期磁盘保留清理(启动 + 周期各一轮,清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`);如需更早释放仍可人工清理,建议保留最近几天便于排障。
- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `data\freight_receipt_rpa\logs\worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。
#### 1.9.6 收料 RPA 三环境速查
@@ -3064,6 +3094,10 @@ SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900
| Windows 本地联调 | 本地后端;默认 `backend/data/shipping_notice/freight_receipt_rpa/*` | 当前项目 `scripts/rpa/receipt/`;`dev` | 不连 test/prod、不用 test/prod Key;`-Mock` 可全链路演练 |
| Linux 测试服务器 | `/mnt/hxops-rpa-test-data/freight_receipt_rpa/*`;`.env.test` | `C:\HxopsRpaTest\data\freight_receipt_rpa`;`test` | 与库存测试共用同一 SMB 共享与挂载 |
| Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/*`;`.env.prod` | `C:\HxopsRpaProd\data\freight_receipt_rpa`;`prod` | 测试真实链路验收通过后再开启正式排程 |
| `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` | dev `data/shipping_notice/freight_receipt_rpa/receipt_triggers`;test `/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers`;prod `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_triggers` | 与后端同一物理目录(test `C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_triggers`;prod `C:\HxopsRpaProd\data\freight_receipt_rpa\receipt_triggers`) | 本地联调两端默认一致,无需配置 |
| `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR` | dev `data/shipping_notice/freight_receipt_rpa/receipt_drop`;test `/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop`;prod `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_drop` | 与后端同一物理目录(test `C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_drop`;prod `C:\HxopsRpaProd\data\freight_receipt_rpa\receipt_drop`) | 本地联调两端默认一致,无需配置 |
收料 trigger/drop 目录必须与 Windows 收料 Worker 上 `start_receipt_worker.ps1` 读取的同名变量指向**同一物理目录**;目录内子结构(processing/processed/failed)由统一契约管理,见 `scripts/rpa/README.md`。
Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与 Worker 指向一致,无需配置目录变量):
@@ -3698,9 +3732,9 @@ Case 状态:`unreviewed`、`draft`、`ready`、`confirming`、`confirmed`、`n
- 嵌套标注采用固定语义层级:明细字段高于物理行容器,表头只展示列级字段,不显示内部表头行容器。物理行内部不吞掉字段点击,管理员通过物理行标签、边缘或已选中的缩放手柄操作父区域。
# 独立收料报表 RPA
收料不进入库存快照、匹配或 ERP 链路。站点的一对一 `ShippingReceiptReportConfig` 保存收料路径、受控条件和 Warehouse;`ShippingReceiptRpaUnitRun` 保存每次冻结单元与重试关系;`ShippingReceiptReportFile` 保存原样对象、SHA-256、到期和删除事实;`ShippingReceiptNotificationDelivery` 保存企微投递幂等事实。
收料不进入库存快照、匹配或 ERP 链路,也没有独立启停字段:是否运行统一由库存站点 `enabled` 与配置是否存在决定。站点的一对一 `ShippingReceiptReportConfig` 保存收料路径与受控查询条件(Warehouse 条件即逐仓拆分维度,不单独持久化仓库清单);`ShippingReceiptRpaUnitRun` 保存每次冻结单元与重试关系;`ShippingReceiptReportFile` 保存原样对象、SHA-256、到期和删除事实;`ShippingReceiptNotificationDelivery` 保存企微投递幂等事实。
DBS 每个 Warehouse 单独导出且不填报表日期;Crane 固定 `Inbound Details`,按本次唯一 Description 等待并下载匹配项,禁止取“最新历史报表”。重试创建新的单元并以 `retry_of_id` 关联旧失败单元,绝不覆盖历史。库存 Worker 与收料 Worker 可在不同专用目录下并行运行,但首版不复用跨排程登录会话。
DBS 每个 Warehouse 单独导出且不填报表日期。**Warehouse 即逐仓拆分维度,配置与库存完全同构**:仓库维护在查询条件的 Warehouse 条件里(支持多值,逗号分隔),不单独持久化仓库清单;排程/按需触发时由后端运行时从该条件派生仓库清单(`receipt_rpa.receipt_warehouse_values`),一仓展开一个执行单元、一个归档文件,并把单元快照中的 Warehouse 条件剥离(`receipt_rpa.receipt_unit_parameters`)——收料 Worker(`receipt_dbs_export.py`)执行时再把当前 `warehouse_id` 作为必填单值条件自动追加,单元快照若保留该条件会重复冲突。校验要求 DBS 收料配置恰一条非空 Warehouse 条件(`shipping_inventory_service._validate_receipt_report_config`)。报表日期固定不筛选同理属于受控边界:跨日排程不筛日期,避免管理端误传日期导致导出漏数。Crane 固定 `Inbound Details`,按本次唯一 Description 等待并下载匹配项,禁止取“最新历史报表”。重试创建新的单元并以 `retry_of_id` 关联旧失败单元,绝不覆盖历史。库存 Worker 与收料 Worker 可在不同专用目录下并行运行,但首版不复用跨排程登录会话。
### 可靠性、补偿与审计边界
@@ -3712,7 +3746,7 @@ DBS 每个 Warehouse 单独导出且不填报表日期;Crane 固定 `Inbound D
### 管理、接收人与接口
- 管理员在既有“货代管理 → 库存站点”抽屉维护独立收料区;保存只调用 `GET/PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config`,不会调用库存 Source 保存接口,也不会改动库存路径、条件、版本或启停门禁。
- 管理员在既有“货代管理 → 库存站点”抽屉维护独立收料卡;统一「保存更改」先调用库存 Source 保存接口、再调用 `PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config`(仅当站点已有收料配置或本次展开并填写过收料卡时提交),两接口字段边界互不穿透,收料保存不改动库存路径、条件或版本。
- 接收人通过“工作台 → 收料文件”调用 `GET /api/workspace/receipt-report-files?limit=100` 查看本人排程归档;列表不返回 bucket、object key 或凭据。下载仍经 `GET /api/workspace/receipt-report-files/{file_id}/download` 再次鉴权并记录审计。
- 管理员的失败单元重试和通知重发接口分别为 `POST /api/admin/receipt-rpa-units/{unit_id}/retry`、`POST /api/admin/receipt-report-files/{file_id}/resend`;二者均只产生新的可审计事实,前者不覆盖旧单元,后者不重新导出。
@@ -3720,8 +3754,8 @@ DBS 每个 Warehouse 单独导出且不填报表日期;Crane 固定 `Inbound D
| 接口 | 权限 | 关键请求/响应约束 | 审计 |
| --- | --- | --- | --- |
| `GET /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` | 管理员 | 返回独立收料路径、可选条件、Warehouse;不返回凭据 | 配置读取沿用管理端访问链路 |
| `PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` | 管理员 | body 仅 `enabled/report_path_json/query_parameters_json/warehouse_ids_json`;DBS 启用须 Warehouse;日期/selector 拒绝;Crane 固定 `Inbound Details`,拒绝 Warehouse 和全部查询条件;Worker 无论 Profile 登录 URL 的原 hash,均强制进入 `#/inbound-details-query` 并使用页面默认条件执行 | `shipping_receipt_report_config_saved`,含前后快照 |
| `GET /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` | 管理员 | 返回独立收料路径与查询条件(含 Warehouse 拆分条件);不返回凭据 | 配置读取沿用管理端访问链路 |
| `PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` | 管理员 | body 仅 `report_path_json/query_parameters_json`;DBS 必须恰一条非空 Warehouse 条件;日期/selector 拒绝;Crane 固定 `Inbound Details`,拒绝全部查询条件;Worker 无论 Profile 登录 URL 的原 hash,均强制进入 `#/inbound-details-query` 并使用页面默认条件执行 | `shipping_receipt_report_config_saved`,含前后快照 |
| `POST /api/shipping-notice/rpa/receipt-batch-ready` | 收料 Worker | 仅 `shipping_receipt_rpa.v1`;`file_path` 必须在 receipt drop 根且为 `.xlsx`;校验大小、SHA-256 | 归档、通知、排程终态均保留事实 |
| `GET /api/workspace/receipt-report-files` | 管理员或排程接收人 | 当前用户授权过滤后再应用 `limit`;不泄露对象存储定位 | `shipping_receipt_report_files_listed` |
| `GET /api/workspace/receipt-report-files/{file_id}/download` | 管理员或对应接收人 | 原样下载;过期对象或无权限拒绝 | 成功/拒绝均记录下载审计 |
+2
View File
@@ -24,6 +24,8 @@
- 货代上传:下载 Excel、RPA 上传、按发货通知单号人工确认已上传、失败恢复和未知结果核对;未知结果禁止自动重试。
- 我的待办改版(2026-09-16):紧凑表格 + 按需详情抽屉;阶段筛选 tab 计数后端全量聚合(仅四个可动作阶段);批量操作仅货代上传阶段可勾选、勾选后浮动操作条;已完成桶拆子视图——「通知完成」为跨单平铺明细报表(客户/料号/发货通知日期筛选,按明细行分页,导出严格 12 列标准 Excel),「复核驳回/已作废」为任务表 + 抽屉。
- 阻塞原因具体化(2026-09-17):批次中心/工作台对建单前 Case 回退消费草稿校验快照的首要阻断 issue(冻结 explainability 契约透传 code/message/next_action),展示「客户尚未确认」等具体原因;「下一步」渲染建议动作文案;通用兜底码不再渲染,同卡重复原因行去重。
- 订单冻结后的人工字段修正(料号等)现可进入库存匹配、Excel 与通知行(有效订单值视图);缺口复核中的行结案(close_unfulfillable)现具备端到端豁免(不再阻塞整单,导出/建通知自动剔除结案行)。
- 通知准备界面支持料号/预约号/数量就地编辑(保存后手动重新匹配库存生效);缺口复核入口与行结案按钮修复可见;编辑权限为状态制(Excel 生成前可改)。
- 通知完成:只读展示已核验的上传成功证据;仅 Task 聚合、全部预约单与成功 Upload Attempt 同时满足时显示并计入完成。
- 通知完成:上传通知或登记上传回执;仅服务端确认的上传 Attempt 成功后显示完成结果。
- 货代发货会话主区域为批次进度中心:有会话即全屏常驻展示(不可关闭),无会话显示欢迎页与附件提交入口;历史会话点击直达中心
@@ -0,0 +1,643 @@
# 收料 Worker 能力对齐库存 Worker(日志/心跳/清理)实施计划
> **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:** 收料 Worker 具备库存 Worker 的全部运行能力——文件日志(tee+时间戳+轮转)、完整启动 banner、成功/失败全路径留痕、心跳上报(独立 Worker 身份)、磁盘保留清理(含 `receipt_*` 孤儿 Profile);日志机制提取为 `common/worker_logging.py`,库存 Worker 同步切换,杜绝第二份复制。
**Architecture:** 把库存 Worker 内置的日志实现(`_TeeStream`/`_configure_file_logging`/`_maybe_rotate_open_log`/轮转辅助,约 200 行)原样提取到 `scripts/rpa/common/worker_logging.py`,库存 Worker 切换为委托(行为等价,既有测试必须全绿);收料 Worker 接入同一模块并在主循环补齐 banner、心跳(`rpa_heartbeat`,独立 `SHIPPING_NOTICE_RPA_WORKER_ID`)、周期磁盘清理(`run_worker_disk_cleanup` 直接复用)。库存与收料是两个独立进程:**日志文件必须各自独立,禁止共写**;心跳身份必须不同,否则监控端同一 Worker 卡片会在两种上下文间抖动。
**Tech Stack:** 纯标准库(Worker 脚本)、pytest(后端测试)。
**Spec:** 用户 2026-09-18 口径——「上面库存 worker 有的,收料都需要有」。本计划推翻 2026-08-19 收料交付时的冻结决策「收料 Worker 无心跳/哨兵」;`rpa_heartbeat`/`worker_disk_cleanup`/`trigger_consumer` 均为既有共享模块,直接复用。
## Global Constraints
- 库存 Worker 本轮**只做日志委托切换**(纯等价重构),其余行为零改动;心跳/清理/触发逻辑不碰。
- 收料 Worker 的功能增补不改变四态 trigger 目录契约与回调契约(`shipping_receipt_rpa.v1`、`/api/shipping-notice/rpa/receipt-batch-ready` 不动)。
- 心跳必须使用独立 Worker 身份:`SHIPPING_NOTICE_RPA_WORKER_ID=<hostname>-receipt`(ps1 设置),禁止与库存 Worker 同身份上报。
- 不新增第三方依赖;不改后端 API;无数据库/迁移改动;前端零改动。
- Conventional Commits:`<type>(<scope>): <中文祈使句>`,scope ∈ `rpa` / `shipping-notice`。
- `.env.*` 文件零改动:Worker 全部新变量由 `start_receipt_worker.ps1` 以 Process 级注入(Worker 不读 .env 文件)。
- 测试从 `backend/` 运行:`python -m pytest -q <路径>`;已知既有失败(`reuse_session` 两个用例等)不属本计划,不修不扩。
- 工作树可能含用户 in-flight 改动:提交只 `git add` 各任务明确列出的文件。
---
### Task 1: 提取 `common/worker_logging.py`(自库存 Worker,行为等价)+ 单测
**Files:**
- Create: `scripts/rpa/common/worker_logging.py`
- Test: `backend/tests/test_rpa_worker_logging.py`
**Interfaces:**
- Produces(Task 2/3 消费):
- `configure_file_logging() -> Path | None`:读 env `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`(相对路径基于仓库 `backend/`),启用后 stdout/stderr 全部 tee 落盘并加 `YYYY-MM-DD HH:MM:SS` 本地时间戳;重复调用幂等(已启用时直接返回现有路径)。
- `maybe_rotate_open_log() -> None`:按 `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES`(默认 10MB,<=0 禁用)运行中轮转。
- `active_log_path() -> Path | None`。
- `shutdown_logging() -> None`:恢复 stdout/stderr 并关闭句柄(原 atexit 逻辑公开化,仍保留 atexit 注册)。
- `WorkerLogTee`(含 `replace_log_file`)、`log_line_timestamp() -> str`、`rotate_log_file_if_needed(path) -> None` 供测试与后续复用。
- 源码提取自 `scripts/rpa/inventory/inventory_rpa_worker.py:139-152`(`_log_line_timestamp`)、`159-248`(`_TeeStream` + 活跃状态)、`250-297`(`_configure_file_logging`)、`299-323`(`_maybe_rotate_open_log`)、`325-345`(`_log_int_env`/`_rotate_log_file_if_needed`)。**逐行为等价迁移**:只改模块内引用(`_env` 从 rpa_common 导入、`_backend_dir` 改为 `Path(__file__).resolve().parents[3] / "backend"`),docstring 保留原文。
- [ ] **Step 1: 写失败测试**
```python
"""worker_logging 公共文件日志模块测试。
用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、
按大小轮转滚动备份、shutdown 恢复标准流。
依赖:标准库 + scripts/rpa/common/worker_logging。
逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common"))
from worker_logging import ( # noqa: E402
WorkerLogTee,
configure_file_logging,
log_line_timestamp,
rotate_log_file_if_needed,
shutdown_logging,
)
@pytest.fixture(autouse=True)
def _restore_streams():
"""每用例后强制恢复标准流并关闭日志,避免污染其他测试。"""
yield
shutdown_logging()
def test_tee_writes_timestamped_lines_to_both_streams(tmp_path, capsys):
"""tee 应把带时间戳的行同时写入控制台与日志文件。"""
log_file = (tmp_path / "worker.log").open("w", encoding="utf-8", buffering=1)
tee = WorkerLogTee(sys.stdout, log_file)
original_stdout = sys.stdout
sys.stdout = tee
try:
print("hello-worker")
finally:
sys.stdout = original_stdout
log_file.close()
content = (tmp_path / "worker.log").read_text(encoding="utf-8")
assert "hello-worker" in content
assert content.startswith(log_line_timestamp()[:10]) # 日期前缀存在
assert "hello-worker" in capsys.readouterr().out
def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch):
"""超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
path = tmp_path / "worker.log"
for round_no in range(3):
path.write_text(f"round-{round_no}-padding", encoding="utf-8")
rotate_log_file_if_needed(path)
# [断言意图] 滚动语义:最新内容滚入 .1,次新在 .2,最旧(round-0)被删,主文件位空缺待新写入
assert Path(f"{path}.1").read_text(encoding="utf-8") == "round-2-padding"
assert Path(f"{path}.2").read_text(encoding="utf-8") == "round-1-padding"
assert not Path(f"{path}.3").exists()
assert not path.exists() # 轮转后主文件位腾空,由调用方以追加模式重建
def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys):
"""configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log"))
enabled = configure_file_logging()
assert enabled == tmp_path / "logs" / "worker.log"
assert enabled.parent.is_dir() # 日志目录自动创建
print("banner-line")
shutdown_logging()
content = (tmp_path / "logs" / "worker.log").read_text(encoding="utf-8")
assert "banner-line" in content
assert "[logging] tee enabled" in content
out = capsys.readouterr().out
assert "banner-line" in out
def test_configure_without_env_is_noop(monkeypatch):
"""未配置 LOG_FILE 时 configure 返回 None 且不改标准流。"""
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", raising=False)
assert configure_file_logging() is None
```
- [ ] **Step 2: 运行确认失败**
Run: `cd backend && python -m pytest -q tests/test_rpa_worker_logging.py`
Expected: FAIL(ModuleNotFoundError: worker_logging)
- [ ] **Step 3: 实现(从 inventory_rpa_worker.py:139-345 等价迁移)**
模块骨架(函数体从库存 Worker 原样搬运,仅做下列机械替换,禁止行为改动):
```python
"""scripts/rpa/common/worker_logging.py
用途:RPA Worker 通用文件日志——stdout/stderr tee 落盘、行级本地时间戳、
按大小轮转(启动前 + 运行中),供库存/收料等所有 Worker 复用。
依赖:rpa_common._env(环境变量读取与历史名兼容)、标准库。
逻辑:configure_file_logging 读 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用;
maybe_rotate_open_log 在主循环周期调用做运行中轮转;shutdown_logging 恢复标准流。
"""
from __future__ import annotations
import atexit
import sys
from pathlib import Path
from typing import TextIO
from rpa_common import _env
def _backend_dir() -> Path:
"""返回仓库内 backend 根目录(本模块位于 <repo>/scripts/rpa/common/)。"""
return Path(__file__).resolve().parents[3] / "backend"
def log_line_timestamp() -> str:
# 原样搬运 inventory_rpa_worker.py:139-152(`%Y-%m-%d %H:%M:%S` 本地时区)。
def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int:
# 原样搬运 :325-330(_env 已从 rpa_common 导入)。
class WorkerLogTee:
# 原样搬运 :159-197(__init__/replace_log_file/_emit_line/write/flush/isatty)。
# 活跃状态四元组 + configure_file_logging() + maybe_rotate_open_log() + _rotate_log_file_if_needed(path)
# 原样搬运 :199-345,仅两处机械替换:
# 1) `_env(...)` 已改为模块顶部 `from rpa_common import _env`(原文件内同名函数);
# 2) `_configure_file_logging` 内部闭包 `_close_log` 提升为模块级公开函数 `shutdown_logging()`,
# atexit.register(shutdown_logging) 保留;`maybe_rotate_open_log`/`shutdown_logging`
# 共享同一组模块级 _ACTIVE_* 状态。
# 额外导出:def active_log_path() -> Path | None: return _ACTIVE_LOG_PATH
# 幂等保护:configure_file_logging 开头 `if _ACTIVE_LOG_PATH is not None: return _ACTIVE_LOG_PATH`。
```
> 执行者注意:搬运时保持函数体逐行一致(含注释),上述缩略注释不是让你重写实现。完成后 `git diff` 自查:除模块头/导入/`shutdown_logging` 提升外不得有其他差异。
- [ ] **Step 4: 运行确认通过**
Run: `cd backend && python -m pytest -q tests/test_rpa_worker_logging.py`
Expected: 4 passed
- [ ] **Step 5: 提交**
```bash
git add scripts/rpa/common/worker_logging.py backend/tests/test_rpa_worker_logging.py
git commit -m "feat(rpa): 提取Worker通用文件日志模块worker_logging"
```
---
### Task 2: 库存 Worker 切换委托 worker_logging(纯等价重构)
**Files:**
- Modify: `scripts/rpa/inventory/inventory_rpa_worker.py`(删除 :139-345 的本地实现,改为导入委托)
- Test: 既有 `backend/tests/test_freight_rpa_worker.py` 等(零新增,全量必须绿)
**Interfaces:**
- Consumes: Task 1 的 `configure_file_logging / maybe_rotate_open_log / active_log_path`。
- Produces: 库存 Worker 行为零变化;`_maybe_rotate_open_log()` 与 `log_file=_ACTIVE_LOG_PATH` 调用点改走公共模块。
- [ ] **Step 1: 切换**
1. 删除本地 `_log_line_timestamp`、`_log_int_env`、`_TeeStream`、`_ACTIVE_*` 四个全局、`_configure_file_logging`、`_maybe_rotate_open_log`、`_rotate_log_file_if_needed`(:139-345 区段)。
2. 导入区加 `from worker_logging import active_log_path, configure_file_logging, maybe_rotate_open_log # noqa: E402`。
3. 调用点机械替换:`_configure_file_logging()` → `configure_file_logging()`;`_maybe_rotate_open_log()` → `maybe_rotate_open_log()`;`log_file=_ACTIVE_LOG_PATH` → `log_file=active_log_path()`。
4. `grep -n "_ACTIVE_\|_TeeStream\|_configure_file_logging\|_maybe_rotate\|_rotate_log_file\|_log_line_timestamp\|_log_int_env" scripts/rpa/inventory/inventory_rpa_worker.py` 确认零残留(若 `worker_disk_cleanup` 或测试引用了这些名字,逐一改为公共模块引用)。
- [ ] **Step 2: 回归**
Run: `cd backend && python -m pytest -q tests/test_freight_rpa_worker.py tests/test_freight_rpa_worker_inventory_params.py tests/test_inventory_rpa_download_save_fallback.py tests/test_rpa_worker_heartbeat.py tests/test_rpa_trigger_consumer.py tests/test_rpa_worker_logging.py`
Expected: 除已知 2 个 `reuse_session` 既有失败外全绿;日志相关行为断言(若有引用内部名的用例)按公共模块名等价更新并在注释说明。
- [ ] **Step 3: 提交**
```bash
git add scripts/rpa/inventory/inventory_rpa_worker.py
git commit -m "refactor(rpa): 库存Worker日志切换公共worker_logging模块"
```
---
### Task 3: 收料 Worker 接入文件日志 + 完整 banner + 全路径留痕
**Files:**
- Modify: `scripts/rpa/receipt/receipt_rpa_worker.py`
- Modify: `scripts/rpa/receipt/start_receipt_worker.ps1`(补 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`)
- Test: `backend/tests/test_freight_receipt_worker_contract.py`(追加静态断言)
**Interfaces:**
- Consumes: Task 1 `configure_file_logging / maybe_rotate_open_log`;Task 2 后 inventory 与 receipt 共用同一模块。
- Produces: 收料 Worker 启动即落盘 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 指向的文件;每个 trigger 的领取/归档、每个单元的成功/失败、每批次开始均有带时间戳日志。
- [ ] **Step 1: 写失败测试(追加静态契约断言)**
```python
def test_receipt_worker_logs_full_lifecycle_and_banner():
"""收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'configure_file_logging' in text
assert 'maybe_rotate_open_log' in text
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段
assert '[receipt-unit] success' in text # 成功单元留痕(此前成功路径零输出)
assert '[receipt-unit] failed' in text
assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text
```
- [ ] **Step 2: 运行确认失败**
Run: `cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py::test_receipt_worker_logs_full_lifecycle_and_banner`
Expected: FAIL
- [ ] **Step 3: 实现收料 Worker 改动**
1. 导入区(`from trigger_consumer import ...` 旁)加:
```python
import worker_logging # noqa: E402
```
后续全部使用 `worker_logging.` 限定名(configure_file_logging / maybe_rotate_open_log / active_log_path)。
2. 新增本地掩码辅助(放 `_require_dir` 前):
```python
def _mask_secret(value: str | None) -> str:
"""掩码打印密钥:保留前 4 后 4,其余以 .... 代替;缺失或过短返回占位。"""
value = str(value or '').strip()
if len(value) <= 8:
return '***' if value else 'missing'
return f'{value[:4]}....{value[-4:]}'
```
3. `main()` 重写为(保持轮询骨架与 trigger_consumer 用法不变):
```python
def main() -> None:
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR')
trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR')
poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3'))
# [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。
print(
'[freight_receipt_rpa_worker] started\n'
f' mock={env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")}\n'
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
f' poll_seconds={poll}\n'
f' headless={env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")} '
f'channel={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
f' credential_key={_mask_secret(env("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"))}\n'
f' trigger_dir={trigger_dir}\n'
f' drop_dir={drop_dir}\n'
f' browser_profile_dir={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
f' log={worker_logging.active_log_path() or "stdout-only"}'
)
while True:
for path in sorted(trigger_dir.glob('*.json')):
worker_logging.maybe_rotate_open_log()
try:
_claim_and_process(path, drop_dir)
except Exception as exc:
print(f'[receipt-trigger] failed {path.name}: {exc}')
time.sleep(poll)
```
> 执行说明:main() 内其他 `worker_logging.*` 限定名(banner 的 `active_log_path()`、循环内的 `maybe_rotate_open_log()`)与本步使用同一 `import worker_logging` 导入,无需再单独 from-import。
4. `_claim_and_process` 补领取/归档留痕:
```python
claimed = claim_trigger(path)
if claimed is None:
return
print(f'[receipt-trigger] claimed {claimed.name}')
try:
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
archive_trigger(claimed, 'processed')
print(f'[receipt-trigger] archived processed {claimed.name}')
except (Exception, SystemExit):
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
archive_trigger(claimed, 'failed')
print(f'[receipt-trigger] archived failed {claimed.name}')
raise
```
5. `_process_units` 分组循环开头与单元回调处补留痕:
```python
for (connector, _profile, login_url), group in grouped.items():
print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
# …… 原逻辑不变,成功回调前补:
print(
f'[receipt-unit] success source={unit["source_code"]} '
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
)
_post_callback({...}) # 原样
```
6. `_report_failure` 补一行(回调前):
```python
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
print(f'[receipt-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
_post_callback({...}) # 原样
```
7. `start_receipt_worker.ps1` 的 `$processVars` 有序表追加(`SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS` 行之后):
```powershell
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot 'logs\worker.log'
```
- [ ] **Step 4: 运行确认通过**
Run: `cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py tests/test_rpa_worker_logging.py`
Expected: 全部 passed(既有「只消费 receipt 目录/无 freight_rpa_worker 字样」等断言不受影响——banner 前缀仍是 `[freight_receipt_rpa_worker]`)
- [ ] **Step 5: 提交**
```bash
git add scripts/rpa/receipt/receipt_rpa_worker.py scripts/rpa/receipt/start_receipt_worker.ps1 backend/tests/test_freight_receipt_worker_contract.py
git commit -m "feat(rpa): 收料Worker补文件日志完整banner与全路径留痕"
```
---
### Task 4: 收料 Worker 心跳对齐(独立 Worker 身份)
**Files:**
- Modify: `scripts/rpa/receipt/receipt_rpa_worker.py`
- Modify: `scripts/rpa/receipt/start_receipt_worker.ps1`(补 `SHIPPING_NOTICE_RPA_WORKER_ID`)
- Test: `backend/tests/test_rpa_worker_heartbeat.py`(追加收料侧静态断言)+ `test_freight_receipt_worker_contract.py`
**Interfaces:**
- Consumes: 既有 `rpa_heartbeat.maybe_send_heartbeat(trigger_dir=, drop_dir=, last_sent_mono=, force=)` 与 `start_heartbeat_loop(trigger_dir=, drop_dir=, interval_seconds=)`(与库存 Worker `main` 中的调用形态一致,镜像即可);后端端点 `POST /api/shipping-notice/rpa/heartbeat`(已存在,不改)。
- Produces: 监控端出现独立收料 Worker 卡片(`<hostname>-receipt`),上报运行态 idle/busy 与收料 trigger/drop 积压。
- [ ] **Step 1: 写失败测试(追加到 test_freight_receipt_worker_contract.py)**
```python
def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
assert 'SHIPPING_NOTICE_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
```
- [ ] **Step 2: 运行确认失败**
Run: `cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py::test_receipt_worker_reports_heartbeat_with_dedicated_identity`
Expected: FAIL
- [ ] **Step 3: 实现**
1. `receipt_rpa_worker.py` 导入区加 `import rpa_heartbeat # noqa: E402`(common 已在 sys.path)。
2. `main()` 中 STEP 1 banner 之后、`while True` 之前补(镜像库存 Worker main 的接线):
```python
heartbeat_seconds = max(
15,
int(env('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
)
rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
)
rpa_heartbeat.start_heartbeat_loop(
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), interval_seconds=heartbeat_seconds,
)
print(f' heartbeat_seconds={heartbeat_seconds}')
```
(banner 文本补一行 `heartbeat_seconds=`;`set_worker_runtime_status` 不需要——收料单线程串行,processing 期间保持 idle 口径与 `_scan_triggers` 语义差异可接受;若要完全对齐库存,可在 `_claim_and_process` 领取成功后 `rpa_heartbeat.set_worker_runtime_status("busy")`、finally 里 `set_worker_runtime_status("idle")`——**要求做上**,与库存监控语义一致。)
3. `start_receipt_worker.ps1` `$processVars` 追加:
```powershell
SHIPPING_NOTICE_RPA_WORKER_ID = "${env:COMPUTERNAME}-receipt"
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = '20'
```
- [ ] **Step 4: 运行确认通过**
Run: `cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py tests/test_rpa_worker_heartbeat.py`
Expected: 全部 passed(若 `test_rpa_worker_heartbeat.py` 有按 worker id 断言的用例,确认不受新 id 影响)
- [ ] **Step 5: 提交**
```bash
git add scripts/rpa/receipt/receipt_rpa_worker.py scripts/rpa/receipt/start_receipt_worker.ps1 backend/tests/test_freight_receipt_worker_contract.py
git commit -m "feat(rpa): 收料Worker接入心跳上报并使用独立Worker身份"
```
---
### Task 5: 收料 Worker 磁盘保留清理 + 孤儿 `receipt_*` Profile 清理
**Files:**
- Modify: `scripts/rpa/receipt/receipt_rpa_worker.py`(主循环周期清理)
- Modify: `scripts/rpa/common/worker_disk_cleanup.py`(孤儿 Profile 匹配前缀扩展 `receipt_*`)
- Test: `backend/tests/test_rpa_trigger_consumer.py` 追加静态断言;`worker_disk_cleanup` 行为测试追加 `receipt_*` 用例(找到该模块既有测试文件并跟随其模式)
**Interfaces:**
- Consumes: `run_worker_disk_cleanup(*, inventory_trigger_dir, upload_trigger_dir, drop_dir, upload_queue_dir, browser_profile_dir, log_file, now_unix)` 全参数默认 None;`cleanup_interval_seconds()`、`format_cleanup_summary(stats)`。收料映射:`inventory_trigger_dir=<收料 trigger 根>`(该函数只清 processed/failed 归档 JSON,绝不碰根目录待领取 `*.json`)、`drop_dir=<收料 drop>`、`browser_profile_dir=<共享 profile 根>`、`log_file=<收料日志路径>`、`upload_trigger_dir/upload_queue_dir=None`。
- Produces: 收料 Worker 每 `SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS`(默认同库存)执行一轮保留清理,并打印与库存同格式的 summary;崩溃残留的 `receipt_*` 临时 Profile 超期后被清理。
- [ ] **Step 1: 写失败测试**
静态断言(追加到 test_rpa_trigger_consumer.py):
```python
def test_receipt_worker_runs_periodic_disk_cleanup():
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
```
行为测试(在 `worker_disk_cleanup` 既有测试文件追加,跟随其 fixture 模式):
```python
def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
"""崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。"""
root = tmp_path / "browser_profile"
stale_receipt = root / "receipt_abcd1234"; stale_receipt.mkdir()
session_dir = root / "dsv_session"; session_dir.mkdir()
old = time.time() - 10 * 24 * 3600
os.utime(stale_receipt, (old, old))
stats = DiskCleanupStats()
cleanup_orphan_runtime_profiles(root, cutoff_unix=time.time(), stats=stats)
assert not stale_receipt.exists() and session_dir.exists()
```
(导入路径/Stats 构造以该测试文件既有写法为准。)
- [ ] **Step 2: 运行确认失败**
Run: `cd backend && python -m pytest -q tests/test_rpa_trigger_consumer.py::test_receipt_worker_runs_periodic_disk_cleanup`
Expected: FAIL
- [ ] **Step 3: 实现**
1. `worker_disk_cleanup.py`:孤儿 Profile 前缀元组化——
```python
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "receipt_")
# cleanup_orphan_runtime_profiles 中 `if not name.startswith("run_"):` 改为
# `if not name.startswith(_RUNTIME_PROFILE_TEMP_PREFIXES):`
# docstring 补一句:收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。
```
(`str.startswith` 接受元组,无需循环。)
2. `receipt_rpa_worker.py` 导入区加:
```python
import worker_disk_cleanup # noqa: E402
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
```
3. `main()`:banner 后补启动即清一轮 + 主循环按间隔清理(对齐库存节奏;收料无 upload/queue 目录,对应参数传 None):
```python
last_cleanup_mono = 0.0
cleanup_interval = cleanup_interval_seconds()
def _run_cleanup_if_due(now_mono: float, *, force: bool = False) -> float:
"""按间隔执行保留清理;启动时强制一轮。返回更新后的上次清理时间。"""
nonlocal last_cleanup_mono
if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
return last_cleanup_mono
profile_root_raw = str(env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
stats = run_worker_disk_cleanup(
inventory_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
drop_dir=drop_dir,
browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
log_file=worker_logging.active_log_path(),
)
print(format_cleanup_summary(stats))
return now_mono
last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)
```
主循环 `while True:` 内 `time.sleep(poll)` 前补 `last_cleanup_mono = _run_cleanup_if_due(time.monotonic())`。
banner 补一行 ` disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}`。
- [ ] **Step 4: 运行确认通过**
Run: `cd backend && python -m pytest -q tests/test_rpa_trigger_consumer.py tests/test_rpa_worker_logging.py`(以及 worker_disk_cleanup 既有测试文件——用 `grep -rln "worker_disk_cleanup" backend/tests` 找到后一并跑)
Expected: 全部 passed
- [ ] **Step 5: 提交**
```bash
git add scripts/rpa/receipt/receipt_rpa_worker.py scripts/rpa/common/worker_disk_cleanup.py backend/tests/test_rpa_trigger_consumer.py <disk_cleanup 测试文件>
git commit -m "feat(rpa): 收料Worker周期磁盘保留清理并覆盖receipt孤儿Profile"
```
---
### Task 6: 文档契约同步
**Files:**
- Modify: `scripts/rpa/README.md`
- Modify: `docs/features/shipping-notice/technical.md`(§1.9 收料 Worker 部署增量;该文件可能有用户 in-flight 改动——只编辑,提交与否以当时工作树状态由执行者按控制器指令处理;默认**不提交**,与此前裁定一致)
- [ ] **Step 1: README 增「Worker 运行能力对齐表 + 日志」小节(四态契约小节之后)**
```markdown
## Worker 运行能力(库存 / 收料对齐)
| 能力 | 库存 Worker | 收料 Worker |
| --- | --- | --- |
| 文件日志(tee+时间戳+轮转) | `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` | 同左(ps1 默认 `data\freight_receipt_rpa\logs\worker.log`) |
| 启动 banner / 运行中轮转 | ✅ | ✅(同一 `worker_logging` 模块) |
| 心跳上报 | `<hostname>` | `<hostname>-receipt`(独立身份,ps1 注入) |
| 磁盘保留清理 | 周期 + 启动一轮 | 同左(清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`) |
规则:**两个 Worker 禁止共写同一日志文件**(多进程写同一文件会交错且 Windows 轮转竞争);
每个 Worker 的 `LOG_FILE` 必须指向各自根目录下的 `logs/worker.log`。
```
- [ ] **Step 2: technical.md §1.9 收料 Worker 部署增量处补两行**
在收料 Worker 部署变量说明处补:`SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`(ps1 自动设为 `logs\worker.log`)与 `SHIPPING_NOTICE_RPA_WORKER_ID=<主机名>-receipt`(独立心跳身份);并注明日志/心跳/清理能力已与库存 Worker 对齐。
- [ ] **Step 3: 提交**
```bash
git add scripts/rpa/README.md
git commit -m "docs(rpa): 补收料Worker运行能力对齐说明与日志独立规则"
```
---
### Task 7: 回归 + 本机验收
**Files:** 无新改动(发现问题回对应任务修复后重跑)
- [ ] **Step 1: 全量相关回归**
Run: `cd backend && python -m pytest -q tests/test_rpa_worker_logging.py tests/test_freight_receipt_worker_contract.py tests/test_rpa_trigger_consumer.py tests/test_freight_rpa_worker.py tests/test_freight_rpa_worker_inventory_params.py tests/test_rpa_worker_heartbeat.py tests/test_inventory_rpa_download_save_fallback.py tests/test_freight_receipt_rpa_callback.py tests/test_freight_receipt_rpa_schedule.py`
Expected: 除已知 2 个 `reuse_session` 既有失败外全绿。
- [ ] **Step 2: 语法编译**
Run: `cd backend && python -m py_compile ../scripts/rpa/common/worker_logging.py ../scripts/rpa/common/worker_disk_cleanup.py ../scripts/rpa/inventory/inventory_rpa_worker.py ../scripts/rpa/receipt/receipt_rpa_worker.py`
Expected: 无输出
- [ ] **Step 3: 本机人工验收(含上次遗留的 env 修正)**
1. **先修本机环境**:当前 shell/系统里旧的 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_{TRIGGER,DROP}_DIR`(指向 `receipts_triggers` 复数旧目录)必须删除或改为 `backend\data\shipping_notice\freight_receipt_rpa\receipt_triggers`/`receipt_drop`(`rpa_common._env` 只读进程环境变量、不读 .env 文件)。
2. 设 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 后裸跑收料 Worker:确认 banner 全字段落盘到 `freight_receipt_rpa/logs/worker.log` 且行首有时间戳。
3. `SHIPPING_NOTICE_RPA_WORKER_MOCK=true` 跑一次 mock trigger:确认 `[receipt-trigger] claimed` → `[receipt-unit] success` → `archived processed` 全链路留痕。
4. 管理端 Worker 监控确认出现 `<主机名>-receipt` 独立在线卡片(心跳 20s)。
5. 库存 Worker 照常启动一次,确认日志行为与改前一致(tee 启动行、轮转配置打印)。
- [ ] **Step 4: 执行记录**
结果写入本文件末尾「执行记录」小节。
## 明确不做
- 库存 Worker 除日志委托切换外的任何行为改动(心跳/清理/触发保持原样)。
- 后端 API/监控端改动(心跳端点已存在,新 Worker 身份自动出现卡片)。
- 收料 Worker 的失败自动重试(冻结决策:只标失败人工重试)。
- 把两个 Worker 的日志合并到一个文件(多进程共写是反模式)。
---
## 执行记录(2026-09-18,Subagent-Driven Development)
**结果:7 个任务全部完成 + 最终全分支审查「With fixes」→ 文档修复波收口 → 复审 all findings addressed。**
提交清单(base `051f80e1e`,7 个提交):
`9eabcc2b9` 提取 worker_logging → `2a1fcfd91` 库存 Worker 委托切换 → `f3655a4c5` 收料文件日志+banner+留痕 → `5b5ab263b` 心跳独立身份 → `54cf2a4f4` 磁盘清理+receipt_* 孤儿(含 try/except 修复轮)→ `b00194dcd` 文档契约(含 5 处矛盾句修复轮)→ `20d41fa41` 终审文档偏差修正(technical.md §1.9 入库 + 库存身份口径 + 幽灵文件名 + banner 描述)。
回归:Task 7 全量 sweep 147 passed / 4 failed(全部为计划前既有基线:reuse_session×2 + heartbeat Flask fail-fast×2)/ 1 skipped;py_compile 通过。
执行中的两次裁定修正:
1. T5 清理闭包缺 try/except(库存参照版有)——SMB 抖动可杀主循环,补包裹 + 失败推进时钟 + 年轻 receipt_* 存活断言(`54cf2a4f4`)。
2. T6 文档 5 处旧句与新增能力矛盾——全部修订并修正 §1.9.3 幽灵文件名(`b00194dcd`)。
**待人工完成(Task 7 Step 3 本机验收):**
1. 清除 shell/系统环境变量中旧的 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_{TRIGGER,DROP}_DIR`(指向 `receipts_triggers` 复数旧目录)或改为规范路径——`rpa_common._env` 只读进程环境变量、不读 .env 文件。
2. 设 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 裸跑收料 Worker:banner 全字段落盘 `freight_receipt_rpa/logs/worker.log` 且行首带时间戳。
3. `SHIPPING_NOTICE_RPA_WORKER_MOCK=true` 跑一次 mock trigger:`[receipt-trigger] claimed` → `[receipt-unit] success` → `archived processed` 全链路留痕。
4. 管理端 Worker 监控确认 `<主机名>-receipt` 独立在线卡片。
5. 库存 Worker 照常启动一次,确认日志行为与改前一致。
后续跟进建议(终审提出,均 SHIP 不阻塞):WorkerLogTee 加线程锁、收料 rotate 调用移到清理节奏、build_heartbeat_payload capabilities 按 Worker 参数化、关闭 4 个既有测试基线失败。
@@ -0,0 +1,797 @@
# 货代发货通知:通知准备就地编辑 + 入口修复 实施计划
> **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:** 让订单确认后(Excel 生成前)的履约字段(料号/预约号/数量)在通知准备界面就地编辑并持久化,编辑后手点「重新匹配库存」全链路生效;同时修复缺口复核面板的两个入口 bug,让"不发货的行"有结案出路。
**Architecture:** 编辑权限从「字段字典逐字段配置」翻转为「状态制」(Excel 未生成 + 无活动 Attempt = 可编辑,字段配置退化为反向锁);写路径完全复用现有 `update-notice-line`(Decision/FieldValue + 版本号 + 自动 old→new 审计),零新增端点、零白名单、零新表。读路径把三处仍锚定冻结快照列的消费方(通知准备值列、预约/核验层)切到已有的有效订单值视图(`effective_order_view`)。前端在匹配表三个单元格加编辑框。另修缺口复核面板的键错位与结案入口。
**Tech Stack:** Flask + SQLAlchemy 2.0(后端既有栈);Vue 3 + TypeScript + i18n 四语言(前端);pytest + vitest。
**Spec:** 2026-09-17/18 头脑风暴对话结论(用户逐项确认的 6 项清单 + 三次设计简化裁决:无原因必填、无白名单、无候选值接口、编辑框样式、无自动触发)。前置分支成果:`051f80e1e`(有效视图 + 行结案豁免,已在 hugo-shipping-notice)。
## Global Constraints
- 分支:从 `hugo-shipping-notice` 切 worktree 分支 `fix/shipping-notice-inline-edit-entry-repair` 实施;完成后按用户惯例并入 `hugo-shipping-notice`。
- Conventional Commits:`<type>(shipping-notice): 中文主题`,≤100 字符。
- 注释三层结构(AGENTS.md §5):修改逻辑必须同步更新受影响注释。
- **无数据库迁移**(无模型变更);无新错误码 → **除前端新增文案外无新增 errors.json 键**。
- **i18n 四语言强制**:前端新增文案必须同时补 `zh-CN / zh-TW / en / th`(AGENTS.md §8)。
- 前端改动必须保证 `npm run build`(含 vue-tsc)通过。
- 测试命令(worktree 内,需先做 Task 0 的 junction):
- 后端 `cd backend && ./.venv/Scripts/python.exe -m pytest <目标> -v`
- 前端 `cd frontend && npx vue-tsc -b --pretty false && npm run build`
- **禁止 `git stash`**(共享 stash 栈有用户条目);验证用 `git diff` / 临时 commit。
- 下游追踪结论(2026-09-18 探查报告)作为本计划的边界事实:Excel ready 后编辑被硬冻结(不可达窗口不做);「通知已存在后编辑不重物化通知行」为本期声明边界,不在本包修。
---
### Task 0: 环境准备(worktree + junction)
**Files:** 无代码变更。
- [ ] **Step 1: 创建 worktree 并接好依赖 junction**
```bash
cd "D:/Workspace/HxProjects/hxops"
git worktree add .worktrees/editfeat -b fix/shipping-notice-inline-edit-entry-repair hugo-shipping-notice
cd .worktrees/editfeat
powershell -Command "New-Item -ItemType Junction -Path node_modules -Target 'D:\Workspace\HxProjects\hxops\node_modules'"
powershell -Command "New-Item -ItemType Junction -Path backend\.venv -Target 'D:\Workspace\HxProjects\hxops\backend\.venv'"
mkdir backend/.pytest_tmp
```
(注意用 PowerShell 建 junction,Git Bash 的 `cmd //c mklink` 会篡改路径为 `D:\D:\...`。)
- [ ] **Step 2: 冒烟验证**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_effective_order_view.py -q`
Expected: 5 passed
---
### Task 1: Decimal 写 JSON 列 bug 修复(数量编辑的前提)
**Files:**
- Modify: `backend/app/services/shipping_notice/task_order_field_editor.py`(`_field_value_columns` :180-189、`replace_current_line_field_value` :225、`replace_current_header_field_value` :267)
- Test: `backend/tests/test_effective_order_view.py`(追加)
**Interfaces:**
- Produces: 编辑 decimal 字段不再抛 `TypeError: Object of type Decimal is not JSON serializable`;`value_json`/`resolved_value_json` 对 decimal 存 `format(value.normalize(), 'f')` 字符串(与机器路径 `order_schema/runtime.py:119-125 _json_value` 对齐),`value_decimal` 列仍存真 Decimal。
- [ ] **Step 1: 写失败测试**
在 `backend/tests/test_effective_order_view.py` 追加(文件已有 import 区,补 `replace_current_line_field_value` 已存在的无需重复;补 `from app.models import ShippingOrderFieldValue` 若缺失):
```python
def test_decimal_edit_persists_without_json_error(app):
"""数量(decimal 字段)人工编辑必须可持久化:value_json 存字符串、value_decimal 存 Decimal。"""
with app.app_context():
fixture = _seed_frozen_order()
# 修复前此处抛 TypeError: Object of type Decimal is not JSON serializable。
replace_current_line_field_value(
task=fixture.order, position=0, field_code='qty', value='12.5',
)
row = ShippingOrderFieldValue.query.filter_by(
extraction_id=fixture.extraction.id, line_id=fixture.snap_lines[0].__dict__['_sa_instance_state'].dict['id'] if False else None,
)
```
上面的查询写法不对,直接用关系取(替换为以下最终版本):
```python
def test_decimal_edit_persists_without_json_error(app):
"""数量(decimal 字段)人工编辑必须可持久化:value_json 存字符串、value_decimal 存 Decimal。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='qty', value='12.5',
)
rows = [
item for item in ShippingOrderFieldValue.query.filter_by(
extraction_id=fixture.extraction.id,
).all()
if item.value_json is not None
]
qty_rows = [item for item in rows if item.field_id == 'f-qty' and item.line_id is not None]
# 断言:JSON 列存规范字符串(与机器路径 _json_value 对齐),类型列保留 Decimal。
assert qty_rows, 'qty FieldValue 必须存在'
assert all(item.value_json == '12.5' for item in qty_rows)
assert any(item.value_decimal == Decimal('12.5') for item in qty_rows)
```
- [ ] **Step 2: 运行确认失败**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_effective_order_view.py::test_decimal_edit_persists_without_json_error -v`
Expected: FAIL,`TypeError: Object of type Decimal is not JSON serializable`(flush 时)
- [ ] **Step 3: 实现**
`task_order_field_editor.py`:
(a) 在 `_field_value_columns`(:180)之前新增:
```python
def _json_value(value: Any) -> Any:
"""把人工输入转为 JSON 列可序列化形状;与 order_schema.runtime._json_value 对齐。
核心逻辑:Decimal → format(normalize, 'f') 字符串(保留精度且 json.dumps 可序列化),
date → isoformat;其余原样。类型化列(value_decimal 等)仍保存原生值。
"""
if isinstance(value, Decimal):
return format(value.normalize(), 'f')
if isinstance(value, date):
return value.isoformat()
return value
```
(文件顶部 import 区补 `from datetime import date`。)
(b) `_field_value_columns`(:180-189)中 `'value_json': value,` 改为 `'value_json': _json_value(value),`。
(c) `replace_current_line_field_value` :225 `decision.resolved_value_json = normalized` 改为 `decision.resolved_value_json = _json_value(normalized)`;`replace_current_header_field_value` :267 同样处理。
- [ ] **Step 4: 运行确认通过**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_effective_order_view.py tests/test_shipping_review_formal_task_edit.py -v`
Expected: 全部 PASS(新增 1 + 既有 5/10+)
- [ ] **Step 5: 提交**
```bash
git add backend/app/services/shipping_notice/task_order_field_editor.py backend/tests/test_effective_order_view.py
git commit -m "fix(shipping-notice): 人工编辑decimal字段可持久化并保留原始JSON形状"
```
---
### Task 2: 编辑闸门翻转为状态制 + 原因/证据改可选
**Files:**
- Modify: `backend/app/services/shipping_notice/schema_edit_policy.py`(:22 常量、:49-51 初始化)
- Modify: `backend/app/services/shipping_notice/task_workflow.py`(`_prepare_review_context` :1031-1061、`_commit_notice_edit` :923-924)
- Test: `backend/tests/test_shipping_schema_edit_policy.py`(:21-23 改写)、`backend/tests/test_shipping_review_formal_task_edit.py`(:287-307 改写)、`backend/tests/test_shipping_formal_task_edit_audit.py`(:34-61 改写)
**Interfaces:**
- Produces: 未配置 `task_edit_policy` 的字段默认可编辑(Excel ready 仍硬冻结;显式 `editable:false` 仍可反向锁);`reason`/`evidence` 缺省时自动落哨兵值(审计列 NOT NULL 不破坏)。
- [ ] **Step 1: 改写三个测试为新契约(先写失败)**
`backend/tests/test_shipping_schema_edit_policy.py` :21-23 原断言 `DEFAULT_EDITABLE_AFTER_TASK_CREATION is False` 改为:
```python
def test_default_formal_fields_are_editable_until_excel_ready():
"""新契约:未配置策略的字段默认可编辑(状态制),显式 editable=false 仍可反向锁。"""
assert DEFAULT_EDITABLE_AFTER_TASK_CREATION is True
assert field_task_edit_policy(None)['editable'] is True
assert field_task_edit_policy({'task_edit_policy': {'editable': False}})['editable'] is False
```
(import 区按该文件现有导入补 `DEFAULT_EDITABLE_AFTER_TASK_CREATION`。)
`backend/tests/test_shipping_review_formal_task_edit.py` :287-307 `test_formal_edit_rejects_default_readonly_field` 改写为 accepts 语义(保留原夹具调用方式,仅翻转断言):
```python
def test_formal_edit_accepts_unconfigured_field_by_default():
"""新契约:未配置 task_edit_policy 的字段在 Excel 未就绪时可直接编辑。"""
# 沿用本文件既有夹具构造正式任务与请求体,字段用夹具中未配置策略的行字段;
# 响应断言 success(不再抛 ORDER_FIELD_EDIT_FORBIDDEN),order_data_version 递增。
```
(实现者按该文件 :287-307 原用例的夹具与请求构造照抄,仅把「断言拒绝」换成「断言成功 + 版本递增」;原用例中若显式传了 `task_edit_policy` 夹具则去掉该配置。)
`backend/tests/test_shipping_formal_task_edit_audit.py` :34-61 同理:原断言拒绝+`ORDER_FIELD_EDIT_FORBIDDEN` 审计,改为断言编辑成功且审计事件为 `formal_task_field_edited`(old→new 存在)。
同时 grep 证据必填断言:`grep -rn "ORDER_REVIEW_EVIDENCE_REQUIRED" backend/tests` ——列出后逐个改写为「缺省时成功且审计 evidence_ref 为哨兵值」。
- [ ] **Step 2: 运行确认失败**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_schema_edit_policy.py tests/test_shipping_review_formal_task_edit.py tests/test_shipping_formal_task_edit_audit.py -v`
Expected: FAIL(新契约断言失败,旧实现返回 False / 拒绝)
- [ ] **Step 3: 实现**
(a) `schema_edit_policy.py` :22 改为:
```python
# 默认:建单后 Excel 生成前字段可编辑(状态制);个别字段需要锁定时在 Schema 配置 editable=false 反向关闭。
DEFAULT_EDITABLE_AFTER_TASK_CREATION: Final[bool] = True
```
(b) `field_task_edit_policy` :49-51 改为(**注意:只改常量不够,初始化必须同步**,否则无配置字段仍为 False):
```python
editable = bool(policy.get('editable')) if policy else DEFAULT_EDITABLE_AFTER_TASK_CREATION
if not DEFAULT_EDITABLE_AFTER_TASK_CREATION and 'editable' not in policy:
editable = False
```
(c) `task_workflow.py` `_prepare_review_context`(:1031-1061):`reason` 缺省改为哨兵、`evidence` 缺省跳过校验(先读全函数再落改):
```python
# 快捷就地编辑不强制填写原因/证据:审计链自动记录 old→new + 操作人 + 时间;
# 提供了证据时仍走原校验。哨兵值满足 shipping_order_review_events 的 NOT NULL 列。
reason = str(review_context.get('reason') or '').strip() or 'quick_field_edit'
evidence = review_context.get('evidence') or None
if evidence is not None:
validate_review_evidence(evidence) # 原 :1047-1061 的校验调用保持
evidence_ref = ... # 原有证据引用构建逻辑
else:
evidence_ref = 'inline:match-table'
```
(`reviewed_by_id` 与 `event_source='workspace_api'` 的要求**保留不变**——操作人身份是审计底线。)
(d) `_commit_notice_edit` :923-924 的 `if not reviewed_by_id or not evidence_ref or not reason: raise` 改为仅 `if not reviewed_by_id: raise`(evidence_ref/reason 已由上游哨兵兜底)。
- [ ] **Step 4: 运行确认通过 + 契约域回归**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_schema_edit_policy.py tests/test_shipping_review_formal_task_edit.py tests/test_shipping_formal_task_edit_audit.py tests/test_effective_order_view.py -v`
Expected: 全部 PASS。再跑 `grep -rn "ORDER_FIELD_EDIT_FORBIDDEN" backend/tests | grep -v test_shipping_schema_edit_policy` 核对无遗漏的旧契约断言(有则一并改写为新契约)。
- [ ] **Step 5: 提交**
```bash
git add backend/app/services/shipping_notice/schema_edit_policy.py backend/app/services/shipping_notice/task_workflow.py backend/tests/test_shipping_schema_edit_policy.py backend/tests/test_shipping_review_formal_task_edit.py backend/tests/test_shipping_formal_task_edit_audit.py
git commit -m "feat(shipping-notice): 编辑闸门翻转为状态制并放宽原因证据必填"
```
---
### Task 3: 预约/核验层切有效视图(修 RESERVATION_MISMATCH 阻断)
**Files:**
- Modify: `backend/app/services/shipping_notice/reservation_service.py`(`ensure_task_reservations` :42-104、`record_inventory_verification` :178-184)
- Test: `backend/tests/test_reservation_effective_view.py`(新建)
**Interfaces:**
- Consumes: `effective_order_view.effective_line_facts_for_notice(owner: ShippingOrderTask) -> {int: {'part_number','reservation_id','qty','field_values'}}`(已存在)。
- Produces: 预约注册/核验比对以有效值为准;编辑后重匹配不再抛 `SHIPPING.RESERVATION_MISMATCH`。
- [ ] **Step 1: 写失败测试**
创建 `backend/tests/test_reservation_effective_view.py`:
```python
"""
tests/test_reservation_effective_view.py
用途:验证预约注册与核验比对消费有效订单值视图(编辑后不再 RESERVATION_MISMATCH)。
依赖:pytest、reservation_service、task_order_field_editor、effective view 夹具。
逻辑:先按冻结值注册预约 → 就地编辑料号 → 再次 ensure 应自动修订(transfer)而非抛错。
"""
from __future__ import annotations
from app import db
from app.models import ShippingReservation
from app.services.shipping_notice.reservation_service import ensure_task_reservations
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
from tests.test_effective_order_view import _seed_frozen_order
def test_ensure_task_reservations_follows_effective_values(app):
"""预约注册必须消费有效值:编辑料号后再次 ensure 应更新预约(修订)而非校验失败。"""
with app.app_context():
fixture = _seed_frozen_order()
# 第一次注册:按冻结值(带尾巴的旧料号)建预约。
ensure_task_reservations(fixture.order)
reservation = ShippingReservation.query.filter_by(
task_id=fixture.order.id,
).one()
# 断言:初始注册值为冻结快照列原值。
assert reservation.part_number == 'D4-A08AR12000002-'
# 就地编辑第 0 行料号为正确值。
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
# 第二次 ensure(重匹配核验前的真实调用时序):必须成功且预约更新为有效值。
ensure_task_reservations(fixture.order)
db.session.refresh(reservation)
# 断言:预约料号已随有效值修订,状态回 pending(可重新核验)。
assert reservation.part_number == 'D4-A08AR12000002'
```
(若 `ensure_task_reservations` 的实际入参/返回与上述调用不符,以 `reservation_service.py:42-104` 实际签名为准适配调用方式,断言语义不变。)
- [ ] **Step 2: 运行确认失败**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_reservation_effective_view.py -v`
Expected: FAIL——第二次调用抛 `SHIPPING.RESERVATION_MISMATCH` 或 `RESERVATION_REVISION_REVIEW_REQUIRED`(编辑后有效值 ≠ 注册值)
- [ ] **Step 3: 实现**
先通读 `ensure_task_reservations`(:42-104)与 `_transfer_confirmed_revision`(:118-156)全函数再落改。语义目标:
(a) `ensure_task_reservations` :50-54 的快照列读取改为有效事实优先:
```python
# [BE-有效视图] 预约身份以有效订单值为准(冻结快照 + 已接受修正),
# 否则就地编辑料号/数量后核验比对必抛 RESERVATION_MISMATCH。
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
effective_facts = effective_line_facts_for_notice(task)
for line in snapshot.lines:
eff = effective_facts.get(int(line.id)) or {}
reservation_id_value = eff.get('reservation_id') if eff.get('reservation_id') is not None else line.reservation_id
part_number_value = eff.get('part_number') if eff.get('part_number') is not None else line.part_number
qty_value = eff.get('qty') if eff.get('qty') is not None else line.qty
# ……后续 :55-101 的重复/冲突/注册/修订判定全部改用以上三个值
```
(b) part/qty 不一致分支:当该行**无 Artifact 锁**(:82-83 既有锁判断)且预约属于同一 OT 时,走 `_transfer_confirmed_revision`(:118-156,其内部已有 bump 版本 + `reservation_revision_confirmed` 事件 + status 回 pending)完成自动修订;仅当行已锁定(已导出)时保留原 `RESERVATION_REVISION_REVIEW_REQUIRED` 拒绝。
(c) `record_inventory_verification` :178-184 的料号比对改为两侧归一化(消除大小写/空白造成的假阳性,数量比对逻辑不变):
```python
if reservation is None or str(reservation.part_number or '').strip().upper() != str(part_number or '').strip().upper():
```
- [ ] **Step 4: 运行确认通过 + 预约域回归**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_reservation_effective_view.py -v` 后追加:`grep -rln "ensure_task_reservations\|RESERVATION_MISMATCH" backend/tests | head` 找到既有预约测试文件并全量跑(FAIL 的按新契约逐个核对:若断言"快照值注册"则更新为有效值语义)。
Expected: 全部 PASS
- [ ] **Step 5: 提交**
```bash
git add backend/app/services/shipping_notice/reservation_service.py backend/tests/test_reservation_effective_view.py
git commit -m "fix(shipping-notice): 预约注册与核验比对改读有效订单值视图"
```
---
### Task 4: 通知准备值列切有效视图
**Files:**
- Modify: `backend/app/services/shipping_notice/ui_state.py`(`frozen_order_lines` :867-878、`preparation_lines` :880-882/:937-938)
- Test: `backend/tests/test_ui_state_effective_values.py`(新建)
**Interfaces:**
- Consumes: `effective_line_facts_for_notice(order_task)`(Task 3 同款)。
- Produces: 前端 `formalPreparationDisplayLines`(ShippingOrderReviewView.vue:2562-2572 以 `frozen_order_lines` 为底、prep.lines 覆盖)在保存后**立即显示新值**;匹配结果列仍来自匹配事实(诚实反映最近一轮)。
- [ ] **Step 1: 写失败测试**
创建 `backend/tests/test_ui_state_effective_values.py`:
```python
"""
tests/test_ui_state_effective_values.py
用途:验证通知准备投影的值列(预约号/料号/需求数量)消费有效订单值视图。
依赖:pytest、ui_state 阶段上下文构建、有效视图夹具。
逻辑:编辑料号后(重匹配前),值列必须立即显示新值;匹配状态列不受影响。
"""
from __future__ import annotations
from app import db
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
from tests.test_effective_order_view import _seed_frozen_order
def test_preparation_value_columns_follow_effective_values(app):
"""保存修正后(重匹配前)值列立即显示新值。"""
with app.app_context():
fixture = _seed_frozen_order()
replace_current_line_field_value(
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
)
from app.services.shipping_notice import ui_state
context = ui_state._build_stage_context(fixture.order)
lines = context['preparation']['frozen_order_lines'] if 'preparation' in context else context.get('frozen_order_lines', [])
# 断言:值列为有效值(而非快照冻结的带尾巴旧值)。
assert lines[0]['part_number'] == 'D4-A08AR12000002'
```
(`_build_stage_context` 的实际函数名/返回形状以 ui_state.py:793-794 与 :1067-1068 为准适配;断言语义不变:值列 = 有效值。若该构建函数需要更多入参,参照其既有测试或调用方 `query_service` 的传参方式构造。)
- [ ] **Step 2: 运行确认失败**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_ui_state_effective_values.py -v`
Expected: FAIL,`part_number == 'D4-A08AR12000002-'`(仍读冻结列)
- [ ] **Step 3: 实现**
`ui_state.py`(先读 :837-960 全段):
(a) :848 之后(snapshot 解析完成处)计算一次有效事实:
```python
# [BE-有效视图] 值列消费有效订单值(快照 + 已接受修正):保存即显新值,
# 匹配结果列仍读当前匹配事实,诚实反映最近一轮匹配结论。
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
effective_facts = (
effective_line_facts_for_notice(order_task)
if order_task is not None and getattr(order_task, 'order_snapshot_id', None) else {}
)
```
(b) `frozen_order_lines`(:867-878):`reservation_id`/`part_number`/`required_qty` 改为有效值优先、快照列回退:
```python
eff = effective_facts.get(int(snapshot_line.id)) or {}
frozen_order_lines.append({
'snapshot_line_id': int(snapshot_line.id),
'line_no': line_no,
'reservation_id': eff.get('reservation_id') if eff.get('reservation_id') is not None else snapshot_line.reservation_id,
'part_number': eff.get('part_number') if eff.get('part_number') is not None else snapshot_line.part_number,
'required_qty': str(eff['qty']) if eff.get('qty') is not None else qty_text,
})
```
(键名不动——前端类型 `shipping.api.types.ts:1490-1497` 契约稳定;注释同步改为「有效值优先」。)
(c) `preparation_lines` 的三处(:880-882 required_qty、:937 reservation_id、:938 part_number):把「fact → 快照」的回退链改为「**有效事实 → fact → 快照**」——保存后即使 fact 未刷新,覆盖合并(前端 :2570 prep 覆盖 frozen)也显示新值:
```python
eff = effective_facts.get(int(snapshot_line.id)) or {}
# part_number:有效事实 → 匹配事实 → 快照列
part_number_value = (
eff.get('part_number')
if eff.get('part_number') is not None
else (fact or {}).get('part_number') or snapshot_line.part_number
)
# reservation_id / required_qty 同构(required_qty 记得 str() 化)
```
- [ ] **Step 4: 运行确认通过 + ui_state 域回归**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_ui_state_effective_values.py -v`;再 `grep -rln "ui_state" backend/tests | head -8` 跑既有 ui_state 相关测试(FAIL 的核对:若断言值列为冻结值,更新为有效值语义)。
Expected: 全部 PASS
- [ ] **Step 5: 提交**
```bash
git add backend/app/services/shipping_notice/ui_state.py backend/tests/test_ui_state_effective_values.py
git commit -m "fix(shipping-notice): 通知准备值列改读有效订单值视图"
```
---
### Task 5: 前端匹配表三单元格编辑框(+ i18n 四语言)
**Files:**
- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(表格 :4936-4952 区段;保存逻辑复用 :2859 `loadFormalTaskDetail`)
- Modify: `frontend/src/features/chat/api/shipping.api.ts`(`updateWorkspaceShippingNoticeLine` :1205-1225 的 evidence/reason 参数改可选)
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`(`shippingOrderReview` 子树新增 3 键)
- Test: 手动走查(前端无既有组件测试基建覆盖该区段;`npx vue-tsc -b` + build 为门禁)
**Interfaces:**
- Consumes: `updateWorkspaceShippingNoticeLine(taskNo, lineIndex, patch, comment, options)`(lineIndex = `line.line_no - 1`,与后端 `ShippingOrderLine.position` 0 基对齐);Task 2 后 evidence/reason 可选。
- Produces: 料号/预约号/需求数量三单元格点击变编辑框,保存成功后刷新并提示「请点击重新匹配库存」。
- [ ] **Step 1: api 签名放宽**
`shipping.api.ts` :1205-1225 `updateWorkspaceShippingNoticeLine` 的 options 中 `evidence`/`reason` 改为可选(`evidence?`/`reason?`),未传时不带这两个字段。同步改 :1177 `updateWorkspaceShippingNoticeFields` 同构参数。
- [ ] **Step 2: 表格单元格改造**
在 ShippingOrderReviewView.vue 的 prep 表格(:4952 行)把三个 `<td>` 的纯文本改为「文本 + 点击进入编辑」模式(普通编辑框,不抄下拉):
```vue
<td>
<input
v-if="editingLine?.snapshot_line_id === line.snapshot_line_id"
v-model="editingLine.part_number"
class="..."
:disabled="inlineEditSaving"
@keyup.enter="saveInlineEdit(line)"
@keyup.esc="cancelInlineEdit"
/>
<span v-else class="cursor-pointer" @click="startInlineEdit(line)">{{ line.part_number || '—' }}</span>
</td>
```
(`reservation_id`、`required_qty` 两个 td 同构;`required_qty` 用 `type="number"` 输入。)
script 区新增状态与方法(放在 :2792 附近的行级操作函数区):
```typescript
/** 就地编辑状态:仅一行处于编辑态;保存走既有 update-notice-line 通道。 */
const editingLine = ref<{ snapshot_line_id: number; line_no: number; part_number: string; reservation_id: string; required_qty: string } | null>(null);
const inlineEditSaving = ref(false);
function startInlineEdit(line: { snapshot_line_id: number; line_no: number; part_number?: string | null; reservation_id?: string | null; required_qty?: string | null }) {
editingLine.value = {
snapshot_line_id: line.snapshot_line_id,
line_no: line.line_no,
part_number: String(line.part_number ?? ''),
reservation_id: String(line.reservation_id ?? ''),
required_qty: String(line.required_qty ?? ''),
};
}
function cancelInlineEdit() { editingLine.value = null; }
async function saveInlineEdit(line: { snapshot_line_id: number }) {
const draft = editingLine.value;
if (!draft || inlineEditSaving.value) return;
const patch: Record<string, string> = {};
if (draft.part_number !== String(line.part_number ?? '')) patch.part_number = draft.part_number;
if (draft.reservation_id !== String(line.reservation_id ?? '')) patch.reservation_id = draft.reservation_id;
if (draft.required_qty !== String(line.required_qty ?? '')) patch.qty = draft.required_qty;
if (!Object.keys(patch).length) { cancelInlineEdit(); return; }
inlineEditSaving.value = true;
try {
await updateWorkspaceShippingNoticeLine(
/* taskNo */ formalTaskDetail.value?.task_no ?? '',
/* lineIndex */ draft.line_no - 1,
patch,
/* comment */ '',
{ expectedOrderDataVersion: formalTaskDetail.value?.order_data_version },
);
cancelInlineEdit();
useMessage().success(t('chat.shippingOrderReview.inlineEdit.saved'));
await loadFormalTaskDetail();
} finally {
inlineEditSaving.value = false;
}
}
```
(`taskNo`/`order_data_version` 的实际取值字段以 `formalTaskDetail` 类型为准适配;`useMessage`/`t` 按该文件既有用法。失败提示走既有 HTTP 客户端 BusinessError 通道,不重复实现。)
禁用态:`inventory_rpa_is_running`(`formalTaskDetail.ui_state.preparation` 内字段,见类型 :1490-1497)为 true 时,`startInlineEdit` 直接 return 并提示 `inlineEdit.busy`。
- [ ] **Step 3: i18n 四语言**
在 `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` 的 `shippingOrderReview` 子树下新增:
```json
"inlineEdit": {
"saved": "已保存,请点击「重新匹配库存」生效",
"busy": "系统处理中,请稍后再修改"
}
```
zh-TW:`已儲存,請點擊「重新匹配庫存」生效` / `系統處理中,請稍後再修改`;en:`Saved. Click "Re-match inventory" to apply` / `System is busy. Please try again later`;th:`บันทึกแล้ว กด "จับคู่สินค้าคงเหลือใหม่" เพื่อใช้งาน` / `ระบบกำลังประมวลผล โปรดลองอีกครั้งภายหลัง`。
- [ ] **Step 4: 构建门禁**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/frontend" && npx vue-tsc -b --pretty false && npm run build`
Expected: 0 error
- [ ] **Step 5: 提交**
```bash
git add frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/features/chat/api/shipping.api.ts frontend/src/locales
git commit -m "feat(shipping-notice): 通知准备匹配表支持履约字段就地编辑"
```
---
### Task 6: 缺口复核入口修复(键错位 + 结案按钮 + 滚动锚)
**Files:**
- Modify: `backend/app/services/shipping_notice/line_inventory_match_projection.py`(:472-508 后新增按 line_index 的加载器)
- Modify: `backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py`(:821/:846 键修复)
- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(结案按钮 + 滚动锚 :3823-3832)
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`(结案文案)
- Test: `backend/tests/test_review_line_fulfillment_shortage_projection.py`(新建)
**Interfaces:**
- Consumes: 匹配事实行内 `line_index`;`decide_review_line_fulfillment`(既有 API `POST /shipping-notice/order-review-cases/<case_no>/line-fulfillment/decide`)。
- Produces: `line_fulfillment.has_shortage` 正确 → `hasInventoryIssues=True` → `open_shortage_review` 动作可见;prep 表「更多操作」新增结案入口。
- [ ] **Step 1: 写失败测试(键错位)**
创建 `backend/tests/test_review_line_fulfillment_shortage_projection.py`:
```python
"""
tests/test_review_line_fulfillment_shortage_projection.py
用途:锁定行级履约投影的匹配事实关联(修复草稿行ID vs 快照行ID 键错位)。
依赖:pytest、order_review_fulfillment_decision_service、有效视图夹具。
逻辑:确认 Case + 短缺匹配事实下,投影必须报 has_shortage=True 且行级 is_shortage=True。
"""
from __future__ import annotations
from app import db
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewDraft
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
project_review_case_line_decisions,
)
from tests.test_effective_order_view import _seed_frozen_order
def test_line_fulfillment_has_shortage_with_match_facts(app):
"""修复键错位:草稿行经 _line_index 关联匹配事实,has_shortage 必须为真。"""
with app.app_context():
fixture = _seed_frozen_order()
# 短缺事实:第 0 行 not_found、缺 10。
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=fixture.order.id, snapshot_line_id=fixture.snap_lines[0].id,
line_no=1, line_index=0, match_result='not_found', inventory_status='ready',
required_qty='10', available_qty='0', shortage_qty='10',
reservation_id='RSV-1', part_number='D4-A08AR12000002-', is_current=True,
))
case = ShippingOrderReviewCase(
case_no='SNRC-SHORTAGE-PROJ', run_id=911, unit_id=912, document_id=913,
owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
)
db.session.add(case)
db.session.flush()
db.session.add(ShippingOrderReviewDraft(
case_id=case.id, draft_version=1, schema_version_id=fixture.snapshot.schema_version_id,
header_values_json={}, lines_json=[{'draft_line_id': 'line-1', 'part_number': 'D4-A08AR12000002-'}],
))
db.session.flush()
case.current_draft_id = case.drafts[0].id if case.drafts else None
db.session.flush()
result = project_review_case_line_decisions(case)
# 断言:修复前 has_shortage 恒 False(键错位);修复后为 True。
assert result['has_shortage'] is True
assert result['lines'][0]['is_shortage'] is True
```
(`ShippingOrderReviewDraft` 必填列以模型为准适配;`current_draft` 关系按 :128-130 `post_update` 语义先 flush 再回填 current_draft_id。)
- [ ] **Step 2: 运行确认失败**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_review_line_fulfillment_shortage_projection.py -v`
Expected: FAIL,`has_shortage` 为 False
- [ ] **Step 3: 实现后端键修复**
(a) `line_inventory_match_projection.py` :508 后新增:
```python
def load_current_match_facts_by_line_index(task_id: int) -> dict[int, dict[str, Any]]:
"""按 line_index 索引当前匹配事实(Case 履约投影专用)。
核心逻辑:与 load_current_match_facts_by_task 同一查询;Case 草稿行只有
_line_index 没有 snapshot_line_id,必须按行号索引才能关联上事实。
"""
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.all()
)
return {
int(row.line_index): serialize_match_fact(row)
for row in rows
if row.line_index is not None
}
```
(`serialize_match_fact` 与查询结构照抄 :496-508 既有实现;不共享 g memo 亦可,或复用同款 memo。)
(b) `order_review_fulfillment_decision_service.py` :821 加载改双通道、:846 查找改行号:
```python
match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_line_index
match_facts_by_line = load_current_match_facts_by_line_index(int(formal_ot.get('task_id')))
```
```python
# [BE-键修复] 草稿行只有 _line_index;旧实现误用 draft_line_id 查 snapshot_line_id 键,恒 miss。
line_index = draft_line.get('_line_index')
fact = (
match_facts_by_line.get(int(line_index))
if line_index is not None else None
)
```
- [ ] **Step 4: 运行确认通过 + 决定域回归**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_review_line_fulfillment_shortage_projection.py tests/test_shipping_review_line_fulfillment_decision.py tests/test_line_closure_gate_sync.py -v`
Expected: 全部 PASS
- [ ] **Step 5: 前端结案按钮 + 滚动锚**
(a) `ShippingOrderReviewView.vue` prep 表「更多操作」td(:4952 行尾)追加结案按钮(与既有放行缺口按钮 `openReleaseInventoryShortage` 同款交互:弹原因输入):
```vue
<button
v-if="formalPreparationLineAllows(line, 'close')"
class="..."
:title="t('chat.shippingOrderReview.lineActions.closeLine')"
@click="openCloseLineDialog(line)"
>⨂</button>
```
script 区(放行按钮函数旁)新增:通过 `activeCase.value.line_fulfillment.lines` 按 `snapshot_line_id`(或 line_index)找到 `draft_line_id`,调用既有 line-fulfillment decide API:
```typescript
async function confirmCloseLine(lineIndex: number, reason: string) {
const caseNo = activeCase.value?.case_no;
const target = (activeCase.value?.line_fulfillment?.lines || []).find(
(item) => item.line_index === lineIndex,
);
if (!caseNo || !target?.draft_line_id) return;
await closeReviewLineFulfillment(caseNo, target.draft_line_id, reason); // 既有/新增 api 封装,decision_code='close_unfulfillable'
await loadFormalTaskDetail();
}
```
(api 层若无 close 封装,按 :2149 decide API 的既有调用模式加 `decideReviewLineFulfillment(caseNo, draftLineId, decisionCode, reason)`;原因输入复用放行缺口的弹层模式。)
(b) 滚动锚 :3823-3832:`hasFormalOt` 分支的 `review-order-lines-table` 改为 `review-fulfillment-prep-workspace`(缺口语境的真实宿主)。
(c) i18n 四语言 `chat.json` `shippingOrderReview.lineActions`:
```json
"closeLine": "结案(不再发货)",
"closeLineReason": "请填写结案原因",
"closeLineConfirm": "确认结案"
```
zh-TW:`結案(不再發貨)`/`請填寫結案原因`/`確認結案`;en:`Close line (no shipment)`/`Enter a reason to close`/`Confirm close`;th:`ปิดบรรทัด (ไม่จัดส่ง)`/`กรอกเหตุผลเพื่อปิด`/`ยืนยันการปิด`。
- [ ] **Step 6: 构建门禁 + 提交**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/frontend" && npx vue-tsc -b --pretty false && npm run build`
```bash
git add backend/app/services/shipping_notice/line_inventory_match_projection.py backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py backend/tests/test_review_line_fulfillment_shortage_projection.py frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/locales
git commit -m "fix(shipping-notice): 修复缺口投影键错位并补齐结案入口"
```
---
### Task 7: 文档同步与回归
**Files:**
- Modify: `docs/features/shipping-notice/technical.md`(在「有效订单值视图与行结案豁免(2026-09-17)」小节后追加)
- Modify: `docs/funclist.md`
- [ ] **Step 1: technical.md 追加小节**
```markdown
### 通知准备就地编辑与入口修复(2026-09-18)
**编辑权限状态制**:正式订单字段(含履约三要素 料号/预约号/数量)默认在
「Excel 未生成 + 无活动 Attempt」时可编辑(DEFAULT_EDITABLE_AFTER_TASK_CREATION=True,
Schema task_edit_policy 退化为反向锁);原因/证据不强制,审计链自动记录 old→new
(shipping_order_review_events / formal_task_field_edited)。通知准备匹配表三单元格
就地编辑 → 保存(order_data_version+1)→ 手动「重新匹配库存」生效。
**有效值消费面补全**:通知准备值列、预约注册(ensure_task_reservations)与核验比对
(record_inventory_verification)均改读有效订单值视图——修复编辑后重匹配必抛
RESERVATION_MISMATCH 的阻断;匹配结果列仍反映最近一轮匹配事实。
**缺口复核入口修复**:行级履约投影的匹配事实关联由 draft_line_id 改为 line_index
(修复 has_shortage 恒 False 导致入口被隐藏);prep 表新增行级结案入口,滚动锚指向
prep 工作区。**边界**:Excel ready 后编辑硬冻结;通知已存在后编辑不重物化通知行
(可达窗口窄,声明边界);done_line_report/OT 通知列表投影仍显示冻结原值(历史定格语义)。
```
- [ ] **Step 2: funclist.md 追加一行**
```markdown
- 通知准备界面支持料号/预约号/数量就地编辑(保存后手动重新匹配库存生效);缺口复核入口与行结案按钮修复可见;编辑权限为状态制(Excel 生成前可改)。
```
- [ ] **Step 3: 后端定向回归 + 前端构建**
Run: `cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_effective_order_view.py tests/test_reservation_effective_view.py tests/test_ui_state_effective_values.py tests/test_review_line_fulfillment_shortage_projection.py tests/test_shipping_schema_edit_policy.py tests/test_shipping_review_formal_task_edit.py tests/test_shipping_formal_task_edit_audit.py tests/test_shipping_stp_phase4_line_inventory_match.py tests/test_shipping_review_line_fulfillment_decision.py tests/test_line_closure_gate_sync.py tests/test_reservation_effective_view.py -q`
Run: `cd frontend && npx vue-tsc -b --pretty false && npm run build`
Expected: 全绿(前端 0 error)。域内回归为主口径(与用户确认的回归策略一致)。
- [ ] **Step 4: 手工走查清单(并入交付说明)**
1. 卡匹配订单:匹配表改料号(去尾部 `-`)→ 保存 → 值列立即显示新值 → 点「重新匹配库存」→ 匹配/核验通过(不再 RESERVATION_MISMATCH)。
2. 改需求数量 → 保存 → 重匹配 → 缺口数量按新值计算。
3. 系统处理中(RPA 运行)时编辑框不可进入。
4. 缺口状态订单:订单复核工作台出现缺口复核入口(open_shortage_review 可见可点,滚动到 prep 工作区);prep 表行级「结案」可用 → 结案后整单不再被该行阻断。
5. Excel 生成后:编辑框不可进入(冻结)。
- [ ] **Step 5: 提交**
```bash
git add docs/features/shipping-notice/technical.md docs/funclist.md
git commit -m "docs(shipping-notice): 补充就地编辑与入口修复语义文档"
```
---
## Self-Review(已执行)
1. **覆盖度**:清单 6 项 ↔ 任务:闸门翻转+原因可选=T2;值列=T4;预约/核验=T3;编辑框+样式=i18n=T5;Decimal=T1;面板两 bug=T6(键修复+结案按钮+滚动锚;死组件 ReviewInventoryIssueList 明确**不挂载**——其职能由 prep 表内嵌入口承接,清理列后续);文档回归=T7。✔
2. **占位符**:T2 Step1 的两个测试改写给出了断言语义+「照抄原夹具」指引(原夹具代码未在侦察中展开,属于对实现者的定向指令而非 TBD);T3/T4 的适配注记同性质。其余步骤均有完整代码。✔(有意为之的例外已标注。)
3. **类型一致性**:`effective_line_facts_for_notice(owner)`(既有,T3/T4 消费一致);`load_current_match_facts_by_line_index(task_id)`(T6 定义与使用一致);前端 `updateWorkspaceShippingNoticeLine(taskNo, lineIndex, patch, comment, options)`(既有签名,T5 传参对齐);i18n 键名 T5/T6 与 Step 中引用一致。✔
4. **已知风险**:T2 契约翻转的测试改动面依赖 grep 兜底(步骤内含);T3 的 ensure_task_reservations 分支结构需先通读再落改(语义表已给);T4 `_build_stage_context` 函数名/返回形状按实际适配;T6 结案按钮的 draft_line_id 解析依赖 T6 键修复后的投影行(有 snapshot_line_id/line_index 可依)。
@@ -129,88 +129,44 @@
<label><span>{{ t('admin.shippingInventory.warehouseResolution') }}</span><select v-model="source.warehouse_resolution_mode" class="select-field"><option value="fixed">{{ t('admin.shippingInventory.fixedWarehouse') }}</option><option value="inventory_match">{{ t('admin.shippingInventory.inventoryMatch') }}</option></select></label>
<label v-if="source.warehouse_resolution_mode === 'fixed'"><span>{{ t('admin.shippingInventory.warehouse') }}</span><input v-model="source.fixed_warehouse_id" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.snapshotTtl') }}</span><input v-model.number="source.snapshot_ttl_seconds" class="input-field" min="1" type="number" required></label>
<section v-if="selectedId" class="readiness-card full" :class="{ ready: source.enabled }">
<header class="readiness-heading">
<div>
<span class="readiness-kicker">{{ t('admin.shippingInventory.activationStatus') }}</span>
<strong>{{ readinessHeadline }}</strong>
<p>{{ readinessGuidance }}</p>
</div>
<span class="readiness-count">{{ readinessSummary }}</span>
</header>
<section class="readiness-section">
<div class="readiness-section-heading">
<b>{{ t('admin.shippingInventory.activationRequiredTitle') }}</b>
<small>{{ t('admin.shippingInventory.activationRequiredHint') }}</small>
</div>
<ol v-if="firstBlockingCheck && !source.enabled" class="readiness-steps">
<li :class="`is-${firstBlockingCheck.status}`">
<span class="readiness-marker" aria-hidden="true">{{ readinessMarker(firstBlockingCheck.status) }}</span>
<div class="readiness-copy"><b>{{ t(`admin.shippingInventory.activationRequirement.${firstBlockingCheck.code}`) }}</b><small>{{ readinessDetail(firstBlockingCheck) }}</small></div>
<button v-if="readinessActionLabel(firstBlockingCheck)" type="button" class="readiness-action" :disabled="isReadinessActionBlocked(firstBlockingCheck)" :title="isReadinessActionBlocked(firstBlockingCheck) ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="runReadinessAction(firstBlockingCheck)">{{ readinessActionLabel(firstBlockingCheck) }}</button>
</li>
</ol>
</section>
<details v-if="optionalReadinessChecks.length" class="readiness-optional">
<summary><span>{{ t('admin.shippingInventory.activationOptionalTitle') }}</span><small>{{ t('admin.shippingInventory.activationOptionalHint') }}</small></summary>
<ol class="readiness-steps">
<li v-for="check in optionalReadinessChecks" :key="check.code" :class="`is-${check.status}`">
<span class="readiness-marker" aria-hidden="true">{{ readinessMarker(check.status) }}</span>
<div class="readiness-copy"><b>{{ t(`admin.shippingInventory.activationRequirement.${check.code}`) }}</b><small>{{ readinessDetail(check) }}</small></div>
</li>
</ol>
</details>
<template v-if="configurationTest">
<p class="readiness-run" :class="{ failed: configurationTest.status === 'failed' }">{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<details class="readiness-audit"><summary>{{ t('admin.shippingInventory.configurationTestRunNo') }} {{ configurationTest.run_no }}</summary><dl><div><dt>{{ t('admin.shippingInventory.configurationTestConfigVersion') }}</dt><dd>{{ configurationTest.source_config_version }}</dd></div><div><dt>{{ t('admin.shippingInventory.configurationTestConnectionVersion') }}</dt><dd>{{ configurationTest.rpa_profile_config_version }}</dd></div><div><dt>{{ t('admin.shippingInventory.configurationTestUpdatedAt') }}</dt><dd>{{ formatDate(configurationTest.completed_at || configurationTest.created_at) }}</dd></div></dl></details>
<p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p>
<p v-if="configurationTest.status === 'completed_empty'" class="form-tip">{{ t('admin.shippingInventory.configurationTestEmptyResult') }}</p>
<section v-if="configurationTest.status === 'completed'" class="recommendation-list">
<p v-if="configurationTest.result?.current_profile_verified" class="configuration-test-verified">{{ t(`admin.shippingInventory.currentProfileVerified.${configurationTest.result.profile_match_level || 'compatible'}`) }}</p>
<article v-for="candidate in configurationTest.result?.analysis?.match_result?.candidates || []" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }} · {{ t('admin.shippingInventory.configurationTestCandidateHint') }}</small></article>
<p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section>
</template>
<footer v-if="source.enabled || source.activation?.ready" class="readiness-footer">
<button v-if="source.enabled" type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
<button
v-else
type="button"
class="btn-primary btn-sm"
:disabled="sourceDirty"
:title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined"
@click="requestSourceActivation"
>{{ t('admin.shippingInventory.activateSource') }}</button>
</footer>
</section>
<div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div>
<template v-if="source.connector_type === 'dbs'">
<div class="subsection full">{{ t('admin.shippingInventory.reportPath') }}</div>
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="source.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="source.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="source.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="source.report_path_json.report_name" class="input-field" required></label>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}</div>
<div v-for="(parameter, index) in source.query_parameters_json" :key="`${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<button type="button" class="btn-danger btn-sm" @click="source.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
<section class="path-card full">
<button type="button" class="path-card-header" :aria-expanded="inventoryPathOpen" @click="inventoryPathOpen = !inventoryPathOpen">
<span class="path-card-title"><b>{{ t('admin.shippingInventory.reportPath') }}</b></span>
<span class="path-card-toggle" aria-hidden="true">{{ inventoryPathOpen ? '▾' : '▸' }}</span>
</button>
<div v-show="inventoryPathOpen" class="path-card-body">
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="source.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="source.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="source.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="source.report_path_json.report_name" class="input-field" required></label>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}</div>
<div v-for="(parameter, index) in source.query_parameters_json" :key="`${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
<button type="button" class="btn-danger btn-sm" @click="source.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
</div>
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</div>
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</template>
<section v-if="selectedId" class="receipt-report-config full">
<div class="subsection">{{ t('admin.shippingInventory.receiptReportConfig') }}<small>{{ t('admin.shippingInventory.receiptReportConfigHint') }}</small></div>
<div class="switch-field"><span>{{ t('admin.shippingInventory.receiptReportEnabled') }}</span><button type="button" class="status-switch" :class="{ on: receiptConfig.enabled }" role="switch" :aria-checked="receiptConfig.enabled" @click="receiptConfig.enabled = !receiptConfig.enabled"><i></i><b>{{ receiptConfig.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
</section>
</template>
<section v-if="selectedId" class="path-card receipt full" :class="{ configured: receiptConfigExists }">
<button type="button" class="path-card-header" :aria-expanded="receiptSectionOpen" @click="toggleReceiptSection">
<span class="path-card-title"><b>{{ t('admin.shippingInventory.receiptReportConfig') }}</b><small>{{ t('admin.shippingInventory.receiptReportConfigHint') }}</small></span>
<span class="path-badge" :class="receiptConfigExists ? 'on' : 'off'">{{ receiptConfigExists ? t('admin.shippingInventory.pathSectionConfigured') : t('admin.shippingInventory.pathSectionNotConfigured') }}</span>
<span class="path-card-toggle" aria-hidden="true">{{ receiptSectionOpen ? '▾' : '▸' }}</span>
</button>
<div v-show="receiptSectionOpen" class="path-card-body">
<template v-if="source.connector_type === 'dbs'">
<label><span>{{ t('admin.shippingInventory.programGroup') }}</span><input v-model="receiptConfig.report_path_json.program_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.programLabel') }}</span><input v-model="receiptConfig.report_path_json.program_label" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportGroup') }}</span><input v-model="receiptConfig.report_path_json.report_group" class="input-field" required></label>
<label><span>{{ t('admin.shippingInventory.reportName') }}</span><input v-model="receiptConfig.report_path_json.report_name" class="input-field" required></label>
<label class="full"><span>{{ t('admin.shippingInventory.receiptWarehouses') }}</span><input class="input-field" :value="receiptConfig.warehouse_ids_json.join(', ')" :placeholder="t('admin.shippingInventory.receiptWarehousesHint')" @input="receiptConfig.warehouse_ids_json = splitValues(($event.target as HTMLInputElement).value)"></label>
<div class="subsection full">{{ t('admin.shippingInventory.receiptOptionalParameters') }}</div>
<div class="subsection full">{{ t('admin.shippingInventory.queryParameters') }}<small>{{ t('admin.shippingInventory.receiptQueryParametersHint') }}</small></div>
<div v-for="(parameter, index) in receiptConfig.query_parameters_json" :key="`receipt-${index}-${parameter.name}`" class="parameter-row full">
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
@@ -222,8 +178,8 @@
<button type="button" class="btn-secondary btn-sm full" @click="addReceiptParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
</template>
<p v-else class="form-tip full">{{ t('admin.shippingInventory.receiptCraneFixedPath') }}</p>
<div class="receipt-config-actions full"><button type="button" class="btn-secondary btn-sm" :disabled="receiptConfigLoading || receiptConfigSaving" @click="saveReceiptConfig">{{ receiptConfigSaving ? t('admin.shippingInventory.saving') : t('admin.shippingInventory.saveReceiptReportConfig') }}</button></div>
</section>
</div>
</section>
</template>
<template v-else-if="activeTab === 'parsing'">
@@ -377,6 +333,48 @@
<div class="switch-field"><span>{{ t('admin.shippingInventory.enabled') }}</span><button type="button" class="status-switch" :class="{ on: mapping.enabled }" role="switch" :aria-checked="mapping.enabled" @click="mapping.enabled = !mapping.enabled"><i></i><b>{{ mapping.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
</template>
<section v-if="selectedId" class="readiness-card full" :class="{ ready: source.enabled }">
<div class="readiness-inline">
<template v-if="source.enabled">
<span class="readiness-marker is-passed" aria-hidden="true">✓</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.activationReady') }}</b><small v-if="configurationTest?.completed_at">{{ t('admin.shippingInventory.readinessLastVerified', { time: formatDate(configurationTest.completed_at) }) }}</small></div>
<button type="button" class="btn-danger btn-sm" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
</template>
<template v-else-if="firstBlockingCheck">
<span class="readiness-marker" :class="`is-${firstBlockingCheck.status}`" aria-hidden="true">{{ readinessMarker(firstBlockingCheck.status) }}</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.readinessBlockedBy', { requirement: t(`admin.shippingInventory.activationRequirement.${firstBlockingCheck.code}`) }) }}</b><small>{{ t('admin.shippingInventory.readinessAutoEnableHint') }}</small></div>
<button v-if="readinessActionLabel(firstBlockingCheck)" type="button" class="readiness-action" :disabled="isReadinessActionBlocked(firstBlockingCheck)" :title="isReadinessActionBlocked(firstBlockingCheck) ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="runReadinessAction(firstBlockingCheck)">{{ readinessActionLabel(firstBlockingCheck) }}</button>
</template>
<template v-else>
<span class="readiness-marker is-passed" aria-hidden="true">✓</span>
<div class="readiness-copy"><b>{{ t('admin.shippingInventory.activationCanEnable') }}</b></div>
<button type="button" class="btn-primary btn-sm" :disabled="sourceDirty" :title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="requestSourceActivation">{{ t('admin.shippingInventory.activateSource') }}</button>
</template>
</div>
<details v-if="optionalReadinessChecks.length" class="readiness-optional">
<summary><span>{{ t('admin.shippingInventory.activationOptionalTitle') }}</span><small>{{ t('admin.shippingInventory.readinessOptionalPending', { count: optionalReadinessPending }) }}</small></summary>
<ol class="readiness-steps">
<li v-for="check in optionalReadinessChecks" :key="check.code" :class="`is-${check.status}`">
<span class="readiness-marker" aria-hidden="true">{{ readinessMarker(check.status) }}</span>
<div class="readiness-copy"><b>{{ t(`admin.shippingInventory.activationRequirement.${check.code}`) }}</b><small>{{ readinessDetail(check) }}</small></div>
</li>
</ol>
</details>
<template v-if="configurationTest">
<p v-if="configurationTest.status === 'failed'" class="readiness-run failed">{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p>
<p v-if="configurationTest.status === 'completed_empty'" class="form-tip">{{ t('admin.shippingInventory.configurationTestEmptyResult') }}</p>
<details v-if="configurationTest.status !== 'failed'" class="readiness-audit">
<summary>{{ t('admin.shippingInventory.configurationTestRunNo') }} {{ configurationTest.run_no }} · {{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</summary>
<dl><div><dt>{{ t('admin.shippingInventory.configurationTestConfigVersion') }}</dt><dd>{{ configurationTest.source_config_version }}</dd></div><div><dt>{{ t('admin.shippingInventory.configurationTestConnectionVersion') }}</dt><dd>{{ configurationTest.rpa_profile_config_version }}</dd></div><div><dt>{{ t('admin.shippingInventory.configurationTestUpdatedAt') }}</dt><dd>{{ formatDate(configurationTest.completed_at || configurationTest.created_at) }}</dd></div></dl>
<section v-if="configurationTest.status === 'completed'" class="recommendation-list">
<p v-if="configurationTest.result?.current_profile_verified" class="configuration-test-verified">{{ t(`admin.shippingInventory.currentProfileVerified.${configurationTest.result.profile_match_level || 'compatible'}`) }}</p>
<article v-for="candidate in configurationTest.result?.analysis?.match_result?.candidates || []" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }} · {{ t('admin.shippingInventory.configurationTestCandidateHint') }}</small></article>
<p v-if="!configurationTest.result?.current_profile_verified && !(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section>
</details>
</template>
</section>
<div v-if="isEditableTab" class="form-actions full">
<button v-if="!parsingReadOnly" type="submit" class="btn-primary" :disabled="saving || ruleReadOnly || templateReadOnly || inventoryFieldReadOnly">{{ saving ? t('admin.shippingInventory.saving') : t('admin.save') }}</button>
<button v-if="activeTab === 'rules' && selectedId && selectedRuleStatus === 'draft'" type="button" class="btn-secondary btn-sm" @click="publishCurrentRule">{{ t('admin.shippingInventory.publish') }}</button>
@@ -627,9 +625,12 @@ const bulkBinding = reactive({ visible: false, sourceIds: [] as number[], profil
const batchValidation = reactive({ visible: false, sourceIds: [] as number[], query: '', statusFilter: 'all' as 'all' | 'processing' | 'completed' | 'completed_empty' | 'failed', saving: false, result: null as ShippingInventoryValidationBatch | null });
let batchValidationTimer: number | null = null;
const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], enabled: false, activation: { ready: false, checks: [] as ShippingInventoryReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation });
const receiptConfig = reactive({ enabled: false, report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record<string, string>, query_parameters_json: [] as Parameter[], warehouse_ids_json: [] as string[] });
const receiptConfigLoading = ref(false);
const receiptConfigSaving = ref(false);
const receiptConfig = reactive({ report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record<string, string>, query_parameters_json: [] as Parameter[] });
const receiptConfigExists = ref(false);
const receiptSectionTouched = ref(false);
const receiptSectionOpen = ref(false);
const inventoryPathOpen = ref(true);
const receiptBaseline = ref('');
const sourceBaseline = ref('');
const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] });
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
@@ -646,26 +647,15 @@ const matchingOrderFields = computed(() => routingFields.value.filter((field) =>
const canAddParsingMatchKey = computed(() => Boolean(
structureAnalysis.value && unusedMatchingInventoryFields.value.length && unusedOrderMatchFields.value.length,
));
const sourceDirty = computed(() => Boolean(selectedId.value && sourceBaseline.value && sourceBaseline.value !== serialiseSourceInput()));
const sourceDirty = computed(() => Boolean(selectedId.value && (
(sourceBaseline.value && sourceBaseline.value !== serialiseSourceInput())
|| (receiptConfigExists.value && receiptBaseline.value && receiptBaseline.value !== serialiseReceiptInput())
)));
const readinessChecks = computed<ShippingInventoryReadinessCheck[]>(() => source.activation?.checks || []);
const requiredReadinessChecks = computed(() => readinessChecks.value.filter((item) => item.blocking));
const firstBlockingCheck = computed(() => requiredReadinessChecks.value.find((item) => item.status !== 'passed'));
const optionalReadinessChecks = computed(() => readinessChecks.value.filter((item) => !item.blocking));
const readinessSummary = computed(() => {
const required = requiredReadinessChecks.value;
const total = required.length;
const passed = required.filter((item) => item.status === 'passed').length;
return t('admin.shippingInventory.readinessProgress', { passed, total });
});
const readinessHeadline = computed(() => {
if (source.enabled) return t('admin.shippingInventory.activationReady');
return source.activation?.ready ? t('admin.shippingInventory.activationCanEnable') : t('admin.shippingInventory.activationDraft');
});
const readinessGuidance = computed(() => source.enabled
? t('admin.shippingInventory.activationEnabledHint')
: source.activation?.ready
? t('admin.shippingInventory.activationCanEnableHint')
: t('admin.shippingInventory.activationMissingHint'));
const optionalReadinessPending = computed(() => optionalReadinessChecks.value.filter((item) => item.status !== 'passed').length);
const sampleReplacementNotice = computed(() => {
const difference = pendingSampleReplacement.value?.difference || {};
const missing = Array.isArray(difference.missing_mapped_headers) ? difference.missing_mapped_headers : [];
@@ -848,36 +838,37 @@ async function load(): Promise<void> {
}
}
/** 重置当前站点的独立收料表单,不借用库存报表路径或查询条件。 */
/** 重置当前站点的独立收料表单与卡片状态,与库存同构(路径+查询条件)。 */
function resetReceiptConfig(connectorType: unknown): void {
Object.assign(receiptConfig, {
enabled: false,
report_path_json: String(connectorType || '').toLowerCase() === 'crane'
? { report_name: 'Inbound Details' }
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' },
query_parameters_json: [],
warehouse_ids_json: [],
});
}
/** 读取收料独立配置;读取失败不影响库存站点配置和既有库存运行。 */
async function loadReceiptConfig(sourceId: number, connectorType: unknown): Promise<void> {
receiptConfigLoading.value = true;
resetReceiptConfig(connectorType);
receiptConfigExists.value = false;
receiptSectionTouched.value = false;
receiptSectionOpen.value = false;
receiptBaseline.value = '';
try {
const config = await getShippingReceiptReportConfig(sourceId);
if (!config) return;
const isCrane = String(connectorType || '').toLowerCase() === 'crane';
Object.assign(receiptConfig, {
enabled: Boolean(config.enabled),
report_path_json: isCrane
? { report_name: 'Inbound Details' }
: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '', ...((config.report_path_json || {}) as Record<string, string>) },
query_parameters_json: Array.isArray(config.query_parameters_json) ? config.query_parameters_json.map((parameter) => ({ ...parameter })) : [],
warehouse_ids_json: Array.isArray(config.warehouse_ids_json) ? [...config.warehouse_ids_json].map(String) : [],
});
receiptConfigExists.value = true;
receiptSectionOpen.value = true;
} catch (cause) { showError(cause, 'loadFailed'); }
finally { receiptConfigLoading.value = false; }
finally { receiptBaseline.value = serialiseReceiptInput(); }
}
/** 新增 DBS 可选收料条件;Crane 固定默认查询,不维护查询条件。 */
@@ -885,16 +876,10 @@ function addReceiptParameter(): void {
receiptConfig.query_parameters_json.push({ name: '', mode: 'single', values: [], required: false, select_all: false });
}
/** 仅提交白名单收料字段到独立 API,绝不调用库存 Source 保存接口。 */
async function saveReceiptConfig(): Promise<void> {
if (!selectedId.value) return;
receiptConfigSaving.value = true;
try {
await saveShippingReceiptReportConfig(selectedId.value, buildReceiptReportConfigPayload(receiptConfig));
await loadReceiptConfig(selectedId.value, source.connector_type);
message.success(t('admin.shippingInventory.receiptReportSaved'));
} catch (cause) { showError(cause, 'saveFailed'); }
finally { receiptConfigSaving.value = false; }
/** 展开收料卡即视为有配置意图:统一保存时会提交收料配置,避免未展开时误建空配置。 */
function toggleReceiptSection(): void {
receiptSectionOpen.value = !receiptSectionOpen.value;
if (receiptSectionOpen.value) receiptSectionTouched.value = true;
}
/** 切换管理对象时同步深链并清空选择,避免不同对象的数据残留在编辑器中。 */
@@ -949,6 +934,11 @@ function createNew(): void {
if (activeTab.value === 'sources') {
Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], enabled: false, activation: { ready: false, checks: [], missing_requirements: ['configuration_test'] } });
resetReceiptConfig('dbs');
receiptConfigExists.value = false;
receiptSectionTouched.value = false;
receiptSectionOpen.value = false;
inventoryPathOpen.value = true;
receiptBaseline.value = '';
sourceBaseline.value = '';
}
if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }], source_codes: [] });
@@ -1174,7 +1164,21 @@ async function saveCurrent(): Promise<void> {
await createShippingExcelTemplate(form);
}
}
if (activeTab.value === 'sources') await saveShippingInventorySource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, report_path_json: normaliseInventoryReportPath(source.connector_type, source.report_path_json) }, selectedId.value || undefined);
if (activeTab.value === 'sources') {
await saveShippingInventorySource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, report_path_json: normaliseInventoryReportPath(source.connector_type, source.report_path_json) }, selectedId.value || undefined);
// 收料与站点同批保存:仅当已有配置或管理员展开过收料卡时才提交,避免未配置站点被误建空收料配置。
if (selectedId.value && (receiptSectionTouched.value || (receiptConfigExists.value && receiptBaseline.value !== serialiseReceiptInput()))) {
try {
await saveShippingReceiptReportConfig(selectedId.value, buildReceiptReportConfigPayload(receiptConfig));
receiptConfigExists.value = true;
receiptBaseline.value = serialiseReceiptInput();
} catch (cause) {
showError(cause, 'saveFailed');
await load();
return; // 站点已保存但收料保存失败:保持抽屉打开,修正后可直接重试统一保存。
}
}
}
if (activeTab.value === 'rules') await saveShippingInventoryRule({ rule_code: rule.rule_code, rule_name: rule.rule_name || rule.rule_code, scope: rule.scope, priority: rule.priority, match_mode: 'all', action_type: 'add_source_candidates', action_payload_json: { source_codes: splitValues(rule.source_codes) }, conditions: rule.conditions.map((condition) => ({ source_kind: 'order_field', order_field_id: condition.order_field_id, operator: condition.operator, expected_value_json: normalizeExpectedValue(condition) })) }, selectedId.value || undefined);
if (activeTab.value === 'mappings') await saveShippingInventoryExternalMapping({ ...mapping, freight_warehouse_id: mapping.freight_warehouse_id || null, external_organization_code: mapping.external_organization_code || null, external_site_code: mapping.external_site_code || null }, selectedId.value || undefined);
await load();
@@ -1553,6 +1557,14 @@ function serialiseSourceInput(): string {
});
}
/** 将收料配置表单稳定序列化,作为统一保存与启用守卫的收料脏检查基线。 */
function serialiseReceiptInput(): string {
return JSON.stringify({
report_path_json: receiptConfig.report_path_json,
query_parameters_json: receiptConfig.query_parameters_json,
});
}
/** 返回状态轨道的简洁可视标记,文本状态仍由相邻内容提供,避免颜色成为唯一信息来源。 */
function readinessMarker(status: ShippingInventoryReadinessCheck['status']): string {
const marker = readinessMarkerKind(status);
@@ -1673,10 +1685,10 @@ onMounted(load);
.filename-variable-menu button { display: grid; width: 100%; grid-template-columns: 154px minmax(0, 1fr); gap: 8px; border: 0; border-radius: 4px; background: transparent; padding: 7px 8px; color: #64748b; font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
.filename-variable-menu button:hover, .filename-variable-menu button.active { background: #eef8f7; color: #145f5a; }.filename-variable-menu code { color: #047f76; font-size: 12px; }.filename-variable-menu p { margin: 0; padding: 8px; color: #94a3b8; font-size: 12px; }
.readiness-card { display: grid; gap: 12px; border: 1px solid #cfe2ea; border-radius: 12px; background: #fbfdfe; padding: 16px; }.readiness-card.ready { border-color: #b9dfc4; background: #fcfffd; }
.readiness-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }.readiness-heading > div { display: grid; gap: 5px; }.readiness-kicker { color: #5f798c; font-size: 11px; font-weight: 700; letter-spacing: .04em; }.readiness-heading strong { color: #263b4e; font-size: 14px; line-height: 1.4; }.readiness-heading p { margin: 0; color: #6d8292; font-size: 12px; line-height: 1.45; }.readiness-count { flex: 0 0 auto; border: 1px solid #cce7f1; border-radius: 999px; background: #edf8fc; padding: 5px 9px; color: #176f9f; font-size: 12px; font-weight: 700; white-space: nowrap; }.readiness-card.ready .readiness-count { border-color: #cce8d4; background: #eef9f1; color: #19703a; }
.readiness-section { border: 1px solid #e1edf2; border-radius: 9px; background: #fff; padding: 0 12px; }.readiness-section-heading { display: grid; gap: 2px; padding: 11px 0 8px; }.readiness-section-heading b { color: #385166; font-size: 12px; }.readiness-section-heading small { color: #8192a0; font-size: 11px; }.readiness-steps { display: grid; gap: 0; margin: 0; padding: 0; list-style: none; }.readiness-steps li { display: grid; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 46px; border-top: 1px solid #edf2f5; padding: 7px 0; }.readiness-marker { display: inline-grid; width: 20px; height: 20px; place-items: center; border-radius: 50%; background: #e9eef3; color: #6c7d8d; font-size: 12px; font-weight: 800; }.readiness-copy { display: grid; min-width: 0; gap: 2px; }.readiness-copy b { overflow: hidden; color: #425466; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.readiness-copy small { color: #8190a0; font-size: 11px; line-height: 1.35; }.readiness-steps .is-passed .readiness-marker { background: #dff6e6; color: #16803a; }.readiness-steps .is-passed .readiness-copy b { color: #2d6b40; }.readiness-steps .is-failed .readiness-marker, .readiness-steps .is-stale .readiness-marker { background: #fff0ed; color: #bf4a38; }.readiness-steps .is-failed .readiness-copy b, .readiness-steps .is-stale .readiness-copy b { color: #9d382b; }
.readiness-inline { display: flex; align-items: center; gap: 10px; }.readiness-inline .readiness-copy { flex: 1 1 auto; }.readiness-inline .readiness-copy b { white-space: normal; }.readiness-inline .readiness-copy small { white-space: normal; }.readiness-inline .btn-sm, .readiness-inline .readiness-action { flex: 0 0 auto; }
.readiness-steps { display: grid; gap: 0; margin: 0; padding: 0; list-style: none; }.readiness-steps li { display: grid; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 46px; border-top: 1px solid #edf2f5; padding: 7px 0; }.readiness-marker { display: inline-grid; width: 20px; height: 20px; place-items: center; border-radius: 50%; background: #e9eef3; color: #6c7d8d; font-size: 12px; font-weight: 800; }.readiness-copy { display: grid; min-width: 0; gap: 2px; }.readiness-copy b { overflow: hidden; color: #425466; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.readiness-copy small { color: #8190a0; font-size: 11px; line-height: 1.35; }.readiness-steps .is-passed .readiness-marker { background: #dff6e6; color: #16803a; }.readiness-steps .is-passed .readiness-copy b { color: #2d6b40; }.readiness-steps .is-failed .readiness-marker, .readiness-steps .is-stale .readiness-marker { background: #fff0ed; color: #bf4a38; }.readiness-steps .is-failed .readiness-copy b, .readiness-steps .is-stale .readiness-copy b { color: #9d382b; }.readiness-inline > .readiness-marker.is-passed { background: #dff6e6; color: #16803a; }.readiness-inline > .readiness-marker.is-failed, .readiness-inline > .readiness-marker.is-stale { background: #fff0ed; color: #bf4a38; }
.readiness-optional { border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-optional summary, .readiness-audit summary { display: flex; align-items: baseline; gap: 8px; color: #61798a; cursor: pointer; list-style: none; }.readiness-optional summary::-webkit-details-marker, .readiness-audit summary::-webkit-details-marker { display: none; }.readiness-optional summary::before, .readiness-audit summary::before { color: #4d849f; content: '›'; font-size: 16px; line-height: .8; transition: transform .15s; }.readiness-optional[open] summary::before, .readiness-audit[open] summary::before { transform: rotate(90deg); }.readiness-optional summary span { color: #516b7d; font-size: 12px; font-weight: 700; }.readiness-optional summary small { color: #8797a5; font-size: 11px; }.readiness-optional .readiness-steps { margin-top: 8px; }
.readiness-action { border: 0; border-radius: 5px; background: #e8f3f9; padding: 6px 8px; color: #16759f; font: inherit; font-size: 11px; font-weight: 700; cursor: pointer; }.readiness-action:hover { background: #d8edf7; }.readiness-run { margin: 0; border-left: 3px solid #74b8d8; background: #f0f8fc; padding: 8px 10px; color: #547185; font-size: 11px; line-height: 1.5; }.readiness-run.failed { border-left-color: #e06a58; background: #fff5f3; color: #9d382b; }.readiness-audit { margin: 0; border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-audit summary { color: #61798a; font-size: 11px; font-weight: 700; }.readiness-audit dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; margin: 9px 0 0; overflow: hidden; border: 1px solid #dce8ef; border-radius: 7px; background: #dce8ef; }.readiness-audit dl > div { min-width: 0; background: #fff; padding: 8px 9px; }.readiness-audit dt { color: #7b8998; font-size: 11px; font-weight: 700; }.readiness-audit dd { overflow: hidden; margin: 4px 0 0; color: #3d5366; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-variant-numeric: tabular-nums; text-overflow: ellipsis; white-space: nowrap; }.readiness-footer { display: flex; justify-content: flex-end; border-top: 1px solid #e6eef4; padding-top: 11px; }
.readiness-action { border: 0; border-radius: 5px; background: #e8f3f9; padding: 6px 8px; color: #16759f; font: inherit; font-size: 11px; font-weight: 700; cursor: pointer; }.readiness-action:hover { background: #d8edf7; }.readiness-run { margin: 0; border-left: 3px solid #74b8d8; background: #f0f8fc; padding: 8px 10px; color: #547185; font-size: 11px; line-height: 1.5; }.readiness-run.failed { border-left-color: #e06a58; background: #fff5f3; color: #9d382b; }.readiness-audit { margin: 0; border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-audit summary { color: #61798a; font-size: 11px; font-weight: 700; }.readiness-audit dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; margin: 9px 0 0; overflow: hidden; border: 1px solid #dce8ef; border-radius: 7px; background: #dce8ef; }.readiness-audit dl > div { min-width: 0; background: #fff; padding: 8px 9px; }.readiness-audit dt { color: #7b8998; font-size: 11px; font-weight: 700; }.readiness-audit dd { overflow: hidden; margin: 4px 0 0; color: #3d5366; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-variant-numeric: tabular-nums; text-overflow: ellipsis; white-space: nowrap; }
.form-tip { border-radius: 8px; background: #f1f6fa; padding: 11px; color: #5d7084; font-size: 12px; line-height: 1.55; }
.upload-config-section { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; border: 1px solid #e1edf2; border-radius: 9px; background: #fff; padding: 0 12px 12px; }.upload-config-heading { display: grid; gap: 2px; grid-column: 1 / -1; padding: 11px 0 8px; }.upload-config-heading b { color: #385166; font-size: 12px; }.upload-config-heading small { color: #8192a0; font-size: 11px; }.upload-config-section .full { grid-column: 1 / -1; }.upload-config-section textarea.input-field { resize: vertical; }
.configuration-test-verified { margin: 0; border-left: 3px solid #34a56b; background: #effaf3; padding: 9px 10px; color: #256b43; font-size: 12px; font-weight: 600; line-height: 1.45; }
@@ -1685,9 +1697,12 @@ onMounted(load);
.sample-evidence-card dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px 16px; margin: 0; }.sample-evidence-card dl div { min-width: 0; }.sample-evidence-card dt { color: #8190a0; font-size: 11px; }.sample-evidence-card dd { margin: 3px 0 0; overflow-wrap: anywhere; color: #475569; font-size: 12px; font-weight: 600; }
.sample-replacement-input { display: grid; gap: 6px; border-top: 1px solid #e5edf3; padding-top: 11px; color: #52677a; font-size: 12px; font-weight: 600; }.sample-replacement-input input { max-width: 100%; }.sample-replacement-warning { border-left: 3px solid #e5a21a; background: #fff9eb; padding: 8px 10px; color: #855e00 !important; }.sample-replacement-warning p { margin: 0; }.sample-replacement-warning ul { display: grid; gap: 3px; margin: 7px 0 0; padding-left: 17px; }
.parameter-row { display: grid; align-items: center; grid-template-columns: 1.1fr .9fr 1.25fr auto auto auto; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
.receipt-report-config { display: grid; grid-column: 1 / -1; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #dbe8ee; margin-top: 8px; padding-top: 14px; }
.receipt-report-config .subsection, .receipt-report-config .full { grid-column: 1 / -1; }
.receipt-config-actions { display: flex; justify-content: flex-end; }
.path-card { display: grid; grid-column: 1 / -1; border: 1px solid #dbe8ee; border-radius: 10px; background: #fff; overflow: hidden; }
.path-card-header { display: flex; align-items: center; gap: 10px; border: 0; background: #f7fbfd; padding: 10px 12px; cursor: pointer; font: inherit; text-align: left; }.path-card-header:hover { background: #eff7fa; }
.path-card-title { display: grid; flex: 1 1 auto; min-width: 0; gap: 2px; }.path-card-title b { color: #145f5a; font-size: 12px; font-weight: 800; }.path-card-title small { color: #94a3b8; font-size: 11px; font-weight: 400; }
.path-badge { flex: 0 0 auto; border-radius: 999px; background: #eef2f5; padding: 3px 8px; color: #7b8998; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #e6f6ec; color: #19703a; }
.path-card-toggle { flex: 0 0 auto; color: #4d849f; font-size: 14px; line-height: 1; }
.path-card-body { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #e6eef4; padding: 14px 12px; }.path-card-body .full { grid-column: 1 / -1; }
.condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
.condition-row { grid-template-columns: 1.15fr .9fr 1fr auto; }
.mapping-row { grid-template-columns: 1fr 1fr auto; }
@@ -1728,5 +1743,5 @@ onMounted(load);
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
@media (max-width: 980px) { .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary, .receipt-report-config { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .btn-primary { width: 100%; } }
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary, .path-card-body { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .btn-primary { margin-top: 12px; }.batch-source-list { grid-template-columns: 1fr; }.batch-stat-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }.batch-run { grid-template-columns: 9px minmax(0, 1fr); }.batch-run-error { grid-column: 2; }.readiness-inline { flex-wrap: wrap; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; } }
</style>
@@ -2,7 +2,8 @@
* features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts
* 用途:覆盖收料报表表单的独立载荷边界。
* 依赖:receiptReportConfigForm、vitest。
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口。
* 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口;
* 收料无独立启停字段,载荷不得包含 enabled。
*/
import { describe, expect, it } from 'vitest';
@@ -10,24 +11,30 @@ import { buildReceiptReportConfigPayload } from './receiptReportConfigForm';
describe('receiptReportConfigForm', () => {
it('builds a receipt-only payload without inventory source fields', () => {
// 关键断言:收料路径、条件与仓库必须走独立 API,不能夹带库存 RPA 配置。
// 关键断言:收料路径与条件必须走独立 API,不能夹带库存 RPA 配置或启停字段。
const payload = buildReceiptReportConfigPayload({
enabled: true,
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
warehouse_ids_json: ['A', 'B'],
query_parameters_json: [
{ name: 'Warehouse', mode: 'multi_text', values: ['AWSDU', 'AWSDU-02'], required: false, select_all: false },
{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false },
],
source_code: 'INVENTORY-SHOULD-NOT-LEAK',
snapshot_ttl_seconds: 86400,
enabled: true,
warehouse_ids_json: ['SHOULD-NOT-LEAK'],
inventory_report_path_json: { report_name: 'On Hand' },
});
} as Parameters<typeof buildReceiptReportConfigPayload>[0] & Record<string, unknown>);
expect(payload).toEqual({
enabled: true,
report_path_json: { program_group: 'Bison', program_label: 'AWSBI', report_group: 'Inbound', report_name: 'Receipt Detail' },
query_parameters_json: [{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false }],
warehouse_ids_json: ['A', 'B'],
query_parameters_json: [
{ name: 'Warehouse', mode: 'multi_text', values: ['AWSDU', 'AWSDU-02'], required: false, select_all: false },
{ name: 'Owner', mode: 'single', values: ['AWS'], required: false, select_all: false },
],
});
expect(payload).not.toHaveProperty('source_code');
expect(payload).not.toHaveProperty('snapshot_ttl_seconds');
expect(payload).not.toHaveProperty('enabled');
expect(payload).not.toHaveProperty('warehouse_ids_json');
});
});
@@ -2,14 +2,13 @@
* features/admin/modules/shipping-inventory/receiptReportConfigForm.ts
* 用途:构建独立收料报表配置的受限保存载荷。
* 依赖:无外部依赖。
* 逻辑:页面仅将收料路径、可选条件和 Warehouse 列表提交到收料配置 API,隔离库存站点字段。
* 逻辑:页面仅将收料路径与查询条件提交到收料配置 API,与库存同构(Warehouse 为条件之一),
* 隔离库存站点字段;收料无独立启停字段,是否运行统一由库存站点 enabled 决定。
*/
export type ReceiptReportConfigInput = {
enabled: boolean;
report_path_json: Record<string, unknown>;
query_parameters_json: Array<Record<string, unknown>>;
warehouse_ids_json: string[];
};
/**
@@ -20,9 +19,7 @@ export type ReceiptReportConfigInput = {
*/
export function buildReceiptReportConfigPayload(input: ReceiptReportConfigInput): ReceiptReportConfigInput {
return {
enabled: Boolean(input.enabled),
report_path_json: { ...(input.report_path_json || {}) },
query_parameters_json: (input.query_parameters_json || []).map((item) => ({ ...item })),
warehouse_ids_json: [...(input.warehouse_ids_json || [])],
};
}
@@ -1178,7 +1178,7 @@ export async function updateWorkspaceShippingNoticeFields(
taskNo: string,
fields: Partial<ShippingNoticeHeader>,
comment: string | undefined,
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence?: ShippingReviewEvidence; reason?: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-fields`,
@@ -1186,8 +1186,9 @@ export async function updateWorkspaceShippingNoticeFields(
fields,
...(comment ? { comment } : {}),
expected_order_data_version: options.expectedOrderDataVersion,
evidence: options.evidence,
reason: options.reason,
// 证据/理由改为可选:未传时不带字段,与后端免证据编辑通道(Task 2)对齐。
...(options.evidence ? { evidence: options.evidence } : {}),
...(options.reason ? { reason: options.reason } : {}),
...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
}),
);
@@ -1207,7 +1208,7 @@ export async function updateWorkspaceShippingNoticeLine(
lineIndex: number,
patch: Partial<ShippingNoticeLine> & { quantity?: number },
comment: string | undefined,
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence?: ShippingReviewEvidence; reason?: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-line`,
@@ -1216,8 +1217,9 @@ export async function updateWorkspaceShippingNoticeLine(
patch,
...(comment ? { comment } : {}),
expected_order_data_version: options.expectedOrderDataVersion,
evidence: options.evidence,
reason: options.reason,
// 证据/理由改为可选:未传时不带字段,与后端免证据编辑通道(Task 2)对齐。
...(options.evidence ? { evidence: options.evidence } : {}),
...(options.reason ? { reason: options.reason } : {}),
...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
}),
);
@@ -1186,8 +1186,11 @@ export function useShippingOrderReview(options: {
statusMessage.value = null;
}
} finally {
if (generation !== caseLoadGeneration) return;
// [2026-09-17] initialLoading 仅由 isInitialLoad 的本 load 置位,必须无条件收尾:
// 被 loadReviewCase 等懒加载路径接管代际时,代际守卫之后的清旗会被跳过,
// 首屏永久卡在「正在加载复核结果...」。
if (isInitialLoad) initialLoading.value = false;
if (generation !== caseLoadGeneration) return;
runLoading.value = false;
// 跨 Run 的 beginCrossRunSwitch 会提前打开 caseSwitchLoading;整页 load 收尾必须关掉。
caseSwitchLoading.value = false;
@@ -17,8 +17,9 @@
-->
<script setup lang="ts">
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import type { Component } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Bot, Check, ChevronDown, Crosshair, Download, MoreHorizontal, Plus, RefreshCw, Undo2, Copy, Trash2 } from 'lucide-vue-next';
import { Bot, Check, ChevronDown, Crosshair, Download, MoreHorizontal, Pencil, Plus, RefreshCw, Undo2, Copy, Trash2, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
@@ -37,6 +38,7 @@ import {
retryWorkspaceShippingOrderStpAutoCreate,
retryShippingNoticeIntake,
decideWorkspaceShippingOrderReviewLineFulfillment,
updateWorkspaceShippingNoticeLine,
waveWorkspaceShippingOrderReviewLineFulfillment,
setWorkspaceShippingTaskOdmChoice,
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
@@ -1363,6 +1365,9 @@ onMounted(() => {
document.addEventListener('keydown', onExceptionNavKeydown, true);
// [PERF] 深链进入时尽早并行发起任务详情,与 load() 重叠,削减首屏串行加载。
prefetchDeepLinkedTaskDetail();
// OT 直链(无 case_no)下 confirmedNoticeTaskNo 恒空、watch(hasFormalOt) 永不触发;
// 挂载即消费深链预取(复用同一请求,不重复拉取),任务详情才能落地驱动五阶段页签。
if (deepLinkOrderTaskNo.value) void loadFormalTaskDetail();
});
onBeforeUnmount(() => {
@@ -1927,7 +1932,8 @@ async function handleCurrentTaskAction(
break;
case 'open_inventory_match_review':
if (hasFormalOt.value) {
scrollWorkbenchAnchor('review-order-lines-table');
// 正式 OT 后匹配/缺口语境的真实宿主是通知准备工作区;订单明细表不承载库存结果。
scrollWorkbenchAnchor('review-fulfillment-prep-workspace');
} else {
workbenchMode.value = 'inventory';
scrollWorkbenchAnchor('review-inventory-issue-list');
@@ -2430,6 +2436,15 @@ const confirmedNoticeTaskNo = computed(() => String(
|| '',
).trim());
/**
* 深链显式携带的 OT 号(任务中心抽屉等 OT 直链)。
* 仅认 OT- 前缀;Notice 的 SN 号不是 work-item 键,与 externalOrderTaskNo 同一口径。
*/
const deepLinkOrderTaskNo = computed(() => {
const taskNo = String(route.query.task_no || '').trim();
return taskNo.startsWith('OT-') ? taskNo : '';
});
const freightNoticeGroups = ref<ShippingFreightNoticeGroup[]>([]);
const freightNoticeGroupsLoading = ref(false);
const freightNoticeGroupsReason = ref<string | null>(null);
@@ -2591,9 +2606,8 @@ function formalPreparationLineSource(line: {
/** 锁定边界 = Excel 生成(D7):后端 preparation.source_locked 下发,生成后行源只读。 */
const formalPreparationSourceLocked = computed(() => Boolean(formalPreparationContext.value?.source_locked));
/** 多文件冲突行的行内选源暂存(line_no → 选定 source_code),提交后由后端映射快照行并重匹配。 */
const lineSourceSelections = ref<Record<string, string>>({});
const lineSourceBusy = ref(false);
/** 库存源选择不再有独立确认流:行进入就地编辑态后在下拉中改选,随行级「保存」统一提交
* (override_line_inventory_source Gate 动作,见 saveInlineEdit);展示态回退为文本。 */
/** 选源下拉项文案:源编码始终可见(等宽语义由样式层保证)。 */
function lineSourceOptionLabel(code: string): string {
@@ -2601,58 +2615,14 @@ function lineSourceOptionLabel(code: string): string {
return String(code || '').trim().toUpperCase();
}
/**
* 提交歧义行选定源:走正式 Gate 动作 override_line_inventory_source(方案 3·放开,唯一选源入口),
* 后端校验启用/Excel 锁并仅重匹配该行;成功后清空行内暂存并刷新任务详情。
*/
async function submitLineSourceSelection(line: { snapshot_line_id?: number | null; line_no?: string | number | null }) {
const selectionKey = String(line.snapshot_line_id ?? '');
const sourceCode = String(lineSourceSelections.value[selectionKey] || '').trim();
const lineNo = Number(line.line_no);
if (!sourceCode || !Number.isInteger(lineNo) || lineNo < 1 || lineSourceBusy.value) return;
lineSourceBusy.value = true;
try {
await submitFormalGateAction('override_line_inventory_source', {
line_no: lineNo,
source_code: sourceCode,
});
delete lineSourceSelections.value[selectionKey];
} finally {
lineSourceBusy.value = false;
}
}
/** 人工覆写库存源(方案 3·放开):后端下发全部已启用源 source_options,供行级下拉人工指定。 */
const formSourceOptions = computed(() => formalPreparationContext.value?.source_options || []);
const overrideSourceSelections = ref<Record<string, string>>({});
const overrideSourceBusy = ref(false);
function overrideSourceOptionLabel(code: string): string {
// 兜底:下拉只展示源编码(如 DSV360_AWSSG),不展示冗长 display_name,便于快速识别。
return String(code || '').trim().toUpperCase();
}
/**
* 提交人工覆写行库存源:走正式 Gate 动作 override_line_inventory_source(方案 3·放开),
* 后端校验源启用/Excel 锁并仅重匹配该行;成功后清空暂存并刷新任务详情。
*/
async function submitOverrideSource(line: { snapshot_line_id?: number | null; line_no?: string | number | null }) {
const selectionKey = String(line.snapshot_line_id ?? '');
const sourceCode = String(overrideSourceSelections.value[selectionKey] || '').trim();
const lineNo = Number(line.line_no);
if (!sourceCode || !Number.isInteger(lineNo) || lineNo < 1 || overrideSourceBusy.value) return;
overrideSourceBusy.value = true;
try {
await submitFormalGateAction('override_line_inventory_source', {
line_no: lineNo,
source_code: sourceCode,
});
delete overrideSourceSelections.value[selectionKey];
} finally {
overrideSourceBusy.value = false;
}
}
/** 整单 ODM 裁决列可见性:任一行候选多于一个时展示(候选已经客户范围过滤)。 */
const formalPreparationOdmColumnVisible = computed(() =>
(formalPreparationContext.value?.lines || []).some((line) => (line.odm_values?.length || 0) > 1),
@@ -2749,7 +2719,7 @@ async function confirmReleaseInventoryShortage() {
const caseNo = activeCase.value?.case_no;
const reason = releaseInventoryReason.value.trim();
const requiredFields = line?.release_required_fields || [];
if (!line || !caseNo || !reason || requiredFields.some((field) => !releaseInventoryFieldValues.value[field.field_id]?.trim()) || releaseInventoryBusy.value) return;
if (!line || !caseNo || requiredFields.some((field) => !releaseInventoryFieldValues.value[field.field_id]?.trim()) || releaseInventoryBusy.value) return;
releaseInventoryBusy.value = true;
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
@@ -2776,6 +2746,160 @@ function formalPreparationLineInventoryFileNo(line: { snapshot_line_id?: number
return String(line.inventory_file_no || fulfillment?.inventory_file_no || '').trim();
}
/** 行内放行补录条(常显子行):短缺行携带必填放行字段时直接在行下补填,替代弹窗。 */
const releaseBarValues = ref<Record<string, Record<string, string>>>({});
const releaseBarBusy = ref<Record<string, boolean>>({});
function releaseBarKey(line: { snapshot_line_id?: number | null }): string {
return String(line.snapshot_line_id ?? '');
}
/** 放行必填字段:仅短缺行且投影声明了必填补录项(有候选缺失才需要补录)。 */
function releaseBarLineRequiredFields(line: { snapshot_line_id?: number | null }) {
const fulfillment = formalPreparationLineFulfillment(line);
return fulfillment?.release_required_fields || [];
}
/** 缺字段型短缺行:放行走行内补录(而非仅原因的旧弹窗路径)。 */
function releaseBarHasFields(line: {
snapshot_line_id?: number | null;
shortage_qty?: string | number | null;
}): boolean {
return Number(line.shortage_qty || 0) > 0 && releaseBarLineRequiredFields(line).length > 0;
}
/** 补录条展开态:默认收起(表格保持干净),由 ⋯ 菜单「放行缺口」或缺 N 项徽标点击展开。 */
const releaseBarExpandedFor = ref<string | null>(null);
function expandReleaseBar(line: { snapshot_line_id?: number | null }) {
if (inlineEditBusy.value) {
msg.warning(t('chat.shippingOrderReview.inlineEdit.busy'));
return;
}
releaseBarExpandedFor.value = releaseBarKey(line);
}
function releaseBarValue(
line: { snapshot_line_id?: number | null },
field: { field_id?: string | null },
): string {
return releaseBarValues.value[releaseBarKey(line)]?.[String(field.field_id)] ?? '';
}
function updateReleaseBarValue(
line: { snapshot_line_id?: number | null },
field: { field_id?: string | null },
value: string,
) {
const key = releaseBarKey(line);
releaseBarValues.value = {
...releaseBarValues.value,
[key]: { ...(releaseBarValues.value[key] || {}), [String(field.field_id)]: value },
};
}
/** 放行按钮可用性:后端授权 + 必填补录项全部已填 + 非保存中。 */
function releaseBarReadyFor(line: { snapshot_line_id?: number | null }): boolean {
const fulfillment = formalPreparationLineFulfillment(line);
const required = releaseBarLineRequiredFields(line);
return Boolean(
fulfillment?.line_allowed_actions?.includes('release_inventory_shortage')
&& required.every((field) => releaseBarValue(line, field).trim())
&& !releaseBarBusy.value[releaseBarKey(line)],
);
}
/** 行内放行提交:走既有 decide 通道;原因可选(人工放行事实由审计链记录)。 */
async function confirmReleaseBar(line: { snapshot_line_id?: number | null }) {
const caseNo = activeCase.value?.case_no;
const fulfillment = formalPreparationLineFulfillment(line);
const key = releaseBarKey(line);
const required = releaseBarLineRequiredFields(line);
if (
!caseNo || !fulfillment?.draft_line_id
|| !required.every((field) => releaseBarValue(line, field).trim())
|| releaseBarBusy.value[key]
) return;
releaseBarBusy.value = { ...releaseBarBusy.value, [key]: true };
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(fulfillment.draft_line_id || ''),
decision_code: 'release_inventory_shortage',
reason: '',
release_field_values: { ...(releaseBarValues.value[key] || {}) },
expected_draft_version: activeCase.value?.draft?.draft_version,
});
const next = { ...releaseBarValues.value };
delete next[key];
releaseBarValues.value = next;
// 放行写入成功即结束用户交互;Notice/Excel 由后端 Job 异步创建(与原弹窗通道一致)。
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
releaseBarBusy.value = { ...releaseBarBusy.value, [key]: false };
}
}
/** 行结案弹窗状态;与放行缺口弹窗同款交互(原因必填),走 line-fulfillment decide 通道。 */
const closeLineDialogLine = ref<ShippingOrderReviewLineFulfillmentLine | null>(null);
const closeLineReason = ref('');
const closeLineBusy = ref(false);
/**
* 结案按钮可见性:仅「无货可发」的未终态 prep 行开放。
* 核心逻辑:line_allowed_actions 由后端投影下发(终态行返回空数组,天然排除已结案/
* 已放行/已入波次行),前端再叠加短缺信号(is_shortage / 缺量>0 / not_found)过滤;
* 后端 decide API 才是权威闸门,这里只做入口收敛。
*/
function formalPreparationLineCloseVisible(line: { snapshot_line_id?: number | null; shortage_qty?: string | number | null }): boolean {
if (!formalPreparationLineAllows(line, 'close_unfulfillable')) return false;
const fulfillment = formalPreparationLineFulfillment(line);
if (fulfillment?.decision?.decision_code === 'close_unfulfillable') return false;
const notFound = String(fulfillment?.match_result || '').trim().toLowerCase() === 'not_found';
const shortageQty = Number(line.shortage_qty ?? fulfillment?.shortage_qty ?? 0) > 0;
return Boolean(fulfillment?.is_shortage) || shortageQty || notFound;
}
/**
* 打开行结案弹窗:按快照行身份定位履约投影行(携带 draft_line_id)。
* 核心逻辑:与行内编辑互斥——弹窗打开即取消该行编辑态,避免两套写路径叠加。
*/
function openCloseLineDialog(line: { snapshot_line_id?: number | null }) {
const fulfillment = formalPreparationLineFulfillment(line);
if (!fulfillment) return;
cancelInlineEdit();
closeLineDialogLine.value = fulfillment;
closeLineReason.value = '';
}
/**
* 提交行结案决定(decision_code='close_unfulfillable',原因必填)。
* 核心逻辑:复用既有 line-fulfillment decide API;成功后走恢复协调刷新三投影,
* prep 表即时反映已结案状态(后端拒绝无效流转时以 BusinessError 文案提示)。
*/
async function confirmCloseLine() {
const line = closeLineDialogLine.value;
const caseNo = activeCase.value?.case_no;
const reason = closeLineReason.value.trim();
if (!line || !caseNo || !reason || closeLineBusy.value) return;
closeLineBusy.value = true;
try {
await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, {
draft_line_id: String(line.draft_line_id || ''),
decision_code: 'close_unfulfillable',
reason,
expected_draft_version: activeCase.value?.draft?.draft_version,
});
closeLineDialogLine.value = null;
handleGateRecoveryAccepted();
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
closeLineBusy.value = false;
}
}
/** 下载行级实际匹配快照,禁止退回到任务级 active link。 */
async function downloadFormalPreparationLineInventoryFile(line: {
snapshot_line_id?: number | null;
@@ -2800,6 +2924,257 @@ async function retryFormalPreparationLine(
await submitFormalGateAction(actionCode, { snapshot_line_id: Number(snapshotLineId) });
}
/**
* 库存 RPA 是否运行中(就地编辑的 busy 禁用条件)。
* 核心逻辑:后端 preparation 摘要当前未下发 inventory_rpa_is_running(仅内部计算),
* 故先消费可选下发字段(后端补发即生效),缺失时以 status==='processing'
* (尚无匹配结果且无门禁 → 首轮抓取进行中)兜底;重匹配期间的写冲突由
* 后端 SHIPPING.EDIT_WINDOW_SYSTEM_BUSY 守卫兜底。
*/
const inlineEditBusy = computed(() => {
const preparation = formalTaskDetail.value?.ui_state?.stage_context?.preparation;
if (!preparation) return false;
const running = (preparation as { inventory_rpa_is_running?: unknown }).inventory_rpa_is_running;
if (typeof running === 'boolean') return running;
return preparation.status === 'processing';
});
/** 就地编辑状态:仅一行处于编辑态;保存走既有 update-notice-line 通道(免证据人工修订)。
* 编辑入口 = 行级「编辑」按钮(防单元格误触);编辑态下更多操作列替换为保存/取消。 */
const editingLine = ref<{
snapshot_line_id: number;
line_no: number;
part_number: string;
reservation_id: string;
required_qty: string;
source_code: string;
} | null>(null);
const inlineEditSaving = ref(false);
/**
* 就地编辑草稿种子值:把展示占位「—」还原为空串,避免占位符被当作真实值提交。
* @param value - prep 行展示值(可能为 null / '—' / 数字)
* @returns 可直接进入输入框的字符串
*/
function inlineEditSeedValue(value: unknown): string {
const text = String(value ?? '').trim();
return text === '—' ? '' : text;
}
/**
* 进入单个准备行的就地编辑(料号 / 预约号 / 需求数量三个值列)。
* @param line - prep 展示行;snapshot_line_id 定位编辑行,line_no-1 与后端 line_index 0 基对齐
*/
function startInlineEdit(line: {
snapshot_line_id?: number | null;
line_no?: string | number | null;
part_number?: string | null;
reservation_id?: string | null;
required_qty?: string | number | null;
selected_source_code?: string | null;
source_code?: string | null;
}) {
if (!line.snapshot_line_id || inlineEditSaving.value) return;
// 库存 RPA 运行中禁止改值:匹配进行中修改会与重匹配竞态。
if (inlineEditBusy.value) {
msg.warning(t('chat.shippingOrderReview.inlineEdit.busy'));
return;
}
editingLine.value = {
snapshot_line_id: Number(line.snapshot_line_id),
line_no: Number(line.line_no || 0),
part_number: inlineEditSeedValue(line.part_number),
reservation_id: inlineEditSeedValue(line.reservation_id),
required_qty: inlineEditSeedValue(line.required_qty),
source_code: inlineEditSeedValue(line.selected_source_code || line.source_code),
};
}
/** 行是否处于就地编辑态(统一 Number 收敛,避免模板严格等于的类型漂移)。 */
function isInlineEditing(line: { snapshot_line_id?: number | null }): boolean {
return editingLine.value?.snapshot_line_id === Number(line.snapshot_line_id);
}
/**
* 编辑态库存源下拉选项:多文件冲突行优先取候选源,其余行取全部已启用源;
* 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。
*/
function inlineSourceOptions(line: {
source_ambiguous?: boolean;
source_candidates?: Array<string>;
}): 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 [];
}
/** 同步编辑态库存源草稿(与三个值列一致:改动仅在保存时提交)。 */
function updateInlineEditSource(value: string) {
if (editingLine.value) editingLine.value.source_code = value;
}
/** 行级动作收纳菜单(⋯)打开状态:键 = snapshot_line_id,单行互斥;坐标视口固定定位,
* Teleport 到 body——表格祖先容器 overflow-auto 会裁剪 absolute 浮层并转为滚动高度。 */
const overflowMenuOpenFor = ref<string | null>(null);
const overflowMenuPos = ref<{ top: number; left: number }>({ top: 0, left: 0 });
function toggleOverflowMenu(key: string, event?: MouseEvent) {
if (overflowMenuOpenFor.value === key) {
overflowMenuOpenFor.value = null;
return;
}
const rect = (event?.currentTarget as HTMLElement | undefined)?.getBoundingClientRect();
const menuWidth = 176;
overflowMenuPos.value = {
top: rect ? Math.min(rect.bottom + 4, window.innerHeight - 8) : 0,
left: rect ? Math.max(8, Math.min(rect.right - menuWidth, window.innerWidth - menuWidth - 8)) : 0,
};
overflowMenuOpenFor.value = key;
}
/**
* 行级收纳菜单项:低频/诊断类动作入口(守卫条件与原常显按钮完全一致),
* 高频的「编辑」保持常显;无可用项时 ⋯ 整体不渲染。
*/
function overflowItems(line: {
snapshot_line_id?: number | null;
shortage_qty?: string | number | null;
}): Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise<void> }> {
const items: Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise<void> }> = [];
if (formalPreparationLineAllows(line, 'retry_inventory_matching')) {
items.push({
key: 'retry_inventory_matching',
icon: RefreshCw,
labelKey: inventoryActionLabelKey('retry_inventory_matching')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_matching'),
});
}
// 放行缺口:缺字段型短缺行 → 行内展开补录条(替代弹窗);仅缺原因的行 → 旧弹窗(原因已可选)。
if (formalPreparationLineAllows(line, 'release_inventory_shortage')) {
items.push({
key: 'release_inventory_shortage',
icon: Check,
labelKey: inventoryActionLabelKey('release_inventory_shortage')!,
run: () => {
if (releaseBarHasFields(line)) expandReleaseBar(line);
else openReleaseInventoryShortage(line);
},
});
}
if (formalPreparationLineCloseVisible(line)) {
items.push({
key: 'close_unfulfillable',
icon: X,
labelKey: 'chat.shippingOrderReview.lineActions.closeLine',
run: () => openCloseLineDialog(line),
});
}
if (formalPreparationLineAllows(line, 'retry_inventory_preparation')) {
items.push({
key: 'retry_inventory_preparation',
icon: Bot,
labelKey: inventoryActionLabelKey('retry_inventory_preparation')!,
run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_preparation'),
});
}
if (formalPreparationLineInventoryFileNo(line)) {
items.push({
key: 'download_inventory_file',
icon: Download,
labelKey: inventoryActionLabelKey('download_inventory_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory',
run: () => downloadFormalPreparationLineInventoryFile(line),
});
}
return items;
}
/** 同步需求数量输入:数字输入框经 @input 手动回写,避免 v-model 的隐式 number 转型。 */
function updateInlineEditQty(value: string) {
if (editingLine.value) editingLine.value.required_qty = value;
}
/** 退出就地编辑并丢弃未保存修改。 */
function cancelInlineEdit() {
editingLine.value = null;
}
/**
* 保存就地编辑:仅提交有变化且非空的字段(part_number / reservation_id / qty),
* 成功后提示「请点击重新匹配库存」并刷新任务详情(值列即刻显示新值,重匹配仍需手动触发)。
* @param line - 当前编辑行,用于与编辑起始值比对计算差量补丁
*/
async function saveInlineEdit(line: {
snapshot_line_id?: number | null;
part_number?: string | null;
reservation_id?: string | null;
required_qty?: string | number | null;
selected_source_code?: string | null;
source_code?: string | null;
}) {
const draft = editingLine.value;
if (!draft || !draft.snapshot_line_id || inlineEditSaving.value) return;
// 编辑态行与触发行的快照身份不一致(如刷新后错位)时直接丢弃,禁止错行提交。
if (draft.snapshot_line_id !== Number(line.snapshot_line_id)) {
cancelInlineEdit();
return;
}
const taskNo = String(formalTaskDetail.value?.task_no || '').trim();
const lineIndex = Number(draft.line_no) - 1;
if (!taskNo || !Number.isInteger(lineIndex) || lineIndex < 0) {
cancelInlineEdit();
return;
}
const patch: Record<string, string> = {};
const nextPartNumber = draft.part_number.trim();
if (nextPartNumber !== inlineEditSeedValue(line.part_number)) patch.part_number = nextPartNumber;
const nextReservationId = draft.reservation_id.trim();
if (nextReservationId !== inlineEditSeedValue(line.reservation_id)) patch.reservation_id = nextReservationId;
const nextQty = draft.required_qty.trim();
if (nextQty !== inlineEditSeedValue(line.required_qty) && nextQty) patch.qty = nextQty;
// 库存源草稿与进入编辑时的种子值比对:变化即随保存提交行级源覆写。
const seedSourceCode = inlineEditSeedValue(line.selected_source_code || line.source_code);
const nextSourceCode = draft.source_code.trim();
const sourceChanged = Boolean(nextSourceCode) && nextSourceCode !== seedSourceCode;
if (!Object.keys(patch).length && !sourceChanged) {
cancelInlineEdit();
return;
}
inlineEditSaving.value = true;
try {
// 字段值先落库(update-notice-line);随后的源覆写会触发单行重匹配,读到的是修正后的字段值。
if (Object.keys(patch).length) {
await updateWorkspaceShippingNoticeLine(
taskNo,
lineIndex,
patch,
undefined,
// 免证据人工修订(后端 Task 2 已放宽 evidence/reason);乐观锁版本缺失时
// 退回后端初值 1,冲突由后端 ORDER_DATA_VERSION_MISMATCH 的 409 语义兜底。
{ expectedOrderDataVersion: Number(formalTaskDetail.value?.order_data_version ?? 1) },
);
}
// 库存源覆写沿用既有 Gate 动作(override_line_inventory_source),后端校验后仅重匹配该行。
if (sourceChanged) {
await submitFormalGateAction('override_line_inventory_source', {
line_no: draft.line_no,
source_code: nextSourceCode,
});
}
cancelInlineEdit();
msg.success(t('chat.shippingOrderReview.inlineEdit.saved'));
await loadFormalTaskDetail();
} catch (error) {
// BusinessError.message 即后端业务文案(版本冲突 / 系统处理中),复用既有提示通道。
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
inlineEditSaving.value = false;
}
}
/**
* 人工上传登记是后端 Gate 的受控写动作;仅进入「货代上传」工作面不构成授权。
* [§2 单源] 授权从 A(shippingProcessingProjection.ui_state)读 —— §2.5 差异① 已归一,A 的
@@ -2845,7 +3220,12 @@ async function handleManualUploadSuccess() {
* 拉取确认后的 Notice 履约详情,供 Gate Action 与 Artifact 视图使用。
*/
async function loadFormalTaskDetail() {
const taskNo = confirmedNoticeTaskNo.value;
// 深链 OT 兜底:无 case_no 的 OT 直链下选法 2 不拉 Case,activeCase/displayCase
// 均为空、confirmedNoticeTaskNo 恒空;此时必须消费深链 task_no,否则挂载预取的
// 任务详情被丢弃、五阶段页签无身份可裁决(全锁死)。一旦存在任何 Case 上下文
// 则禁止回退,防止深链 OT 串到用户切换后的其他文件。
const taskNo = confirmedNoticeTaskNo.value
|| (displayCase.value ? '' : deepLinkOrderTaskNo.value);
const generation = ++formalTaskDetailGeneration;
if (!taskNo) {
formalTaskDetail.value = null;
@@ -4087,13 +4467,10 @@ const closeAuxiliaryPanelsForCaseSwitch = () => {
llmSuggestionOpen: false,
versionHistoryOpen: false,
};
// [NO-OPTIMISTIC MEMORY] 行级选源/覆写是「点保存才生效」的实提交,未保存的暂存选择
// 不得跨文件/切换残留(否则会把上一文件的未保存意图带进新行)。切换即清空暂存,
// 行回到后端 selected_source_code / source_code,用户须重新选择并点保存。
lineSourceSelections.value = {};
lineSourceBusy.value = false;
overrideSourceSelections.value = {};
overrideSourceBusy.value = false;
// [NO-OPTIMISTIC MEMORY] 行级就地编辑是「点保存才生效」的实提交,未保存的编辑草稿
// 不得跨文件/切换残留(否则会把上一文件的未保存意图带进新行)。切换即丢弃草稿,
// 行回到后端 selected_source_code / source_code,用户须重新进入编辑并保存。
cancelInlineEdit();
};
/**
@@ -4539,8 +4916,13 @@ watch(
// 用户查看面(含回看已完成阶段)驱动 Case 懒加载:选法 2 正式下游切 PDF 后 activeCase
// 为 null,回看接收解析/订单复核/通知准备时必须按需补拉目标 Case,否则这些工作面
// 只能渲染空白或残留上一份 PDF 的数据。
lifecycleActiveStageCode,
(stage) => {
// [2026-09-17] 初次装配(initialLoading/runLoading)未完成前必须让位:loadReviewCase
// 会自增 caseLoadGeneration,令在途 load() 的 finally 跳过 initialLoading 清旗,
// 首屏永久卡在「正在加载复核结果...」且 run/queue 永不装配。装配完成后由旗标
// 翻转重新触发本 watcher,按当前 stage 补拉 Case。
[lifecycleActiveStageCode, initialLoading, runLoading],
([stage]) => {
if (initialLoading.value || runLoading.value) return;
if (!stage || !REVIEW_EDITOR_NEEDED_STAGES.includes(stage)) return;
// 禁止使用 displayCase 兜底:它可能停留在上一份 PDF 的快照上造成串味;
// 目标一律取当前工作面的 activeCase 或切换管线的 requestedCaseNo。
@@ -4927,7 +5309,7 @@ watch(
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><tr v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`" :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary">{{ line.reservation_id || '—' }}</td><td class="max-w-[220px] truncate px-3 py-2" :title="line.part_number || '—'">{{ line.part_number || '—' }}</td><td class="whitespace-nowrap px-3 py-2">{{ line.required_qty ?? '—' }}</td><td class="max-w-[220px] px-3 py-2"><div v-if="line.source_ambiguous && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-source-ambiguous-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceAmbiguous')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.source_code || ''" @change="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="code in line.source_candidates || []" :key="code" :value="code">{{ lineSourceOptionLabel(code) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || lineSourceBusy || !preparationEditable" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" @click="submitLineSourceSelection(line)"><Check class="h-3.5 w-3.5" /></button></div><span v-else-if="line.source_ambiguous && formalPreparationSourceLocked" class="text-xs text-secondary" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked')">{{ t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked') }}</span><span v-else-if="!formalPreparationSourceLocked && formSourceOptions.length" class="flex items-center gap-1" :data-testid="`review-line-source-override-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-override-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.selected_source_code || line.source_code || ''" @change="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="s in formSourceOptions" :key="String(s.source_code)" :value="String(s.source_code)">{{ overrideSourceOptionLabel(String(s.source_code)) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-override-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || overrideSourceBusy" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :data-line-index="lineIndex" @click="submitOverrideSource(line)"><Check class="h-3.5 w-3.5" /></button></span><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalLine truncated
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
</table>
</div>
</div>
@@ -5706,7 +6088,31 @@ watch(
</label>
<div class="mt-4 flex justify-end gap-2">
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" :disabled="releaseInventoryBusy" @click="releaseInventoryLine = null">{{ t('chat.shippingOrderReview.workbench.close') }}</button>
<button type="button" class="rounded bg-amber-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50" :disabled="releaseInventoryBusy || !releaseInventoryReason.trim() || (releaseInventoryLine.release_required_fields || []).some((field) => !releaseInventoryFieldValues[field.field_id]?.trim())" @click="confirmReleaseInventoryShortage">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseConfirm') }}</button>
<button type="button" class="rounded bg-amber-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50" :disabled="releaseInventoryBusy || (releaseInventoryLine.release_required_fields || []).some((field) => !releaseInventoryFieldValues[field.field_id]?.trim())" @click="confirmReleaseInventoryShortage">{{ t('chat.shippingOrderReview.lifecycle.prepare.releaseConfirm') }}</button>
</div>
</div>
</div>
<div
v-if="closeLineDialogLine"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="review-close-line-dialog"
@click.self="closeLineDialogLine = null"
>
<div class="w-full max-w-md rounded-xl border border-default bg-surface p-4 shadow-xl">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.lineActions.closeLine') }}</h2>
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.closeFulfillment.subtitle') }}</p>
<textarea
v-model="closeLineReason"
rows="3"
class="mt-3 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
data-testid="review-close-line-reason"
:placeholder="t('chat.shippingOrderReview.lineActions.closeLineReason')"
:disabled="closeLineBusy"
/>
<div class="mt-4 flex justify-end gap-2">
<button type="button" class="rounded border border-default px-3 py-1.5 text-sm" :disabled="closeLineBusy" @click="closeLineDialogLine = null">{{ t('chat.shippingOrderReview.workbench.close') }}</button>
<button type="button" class="rounded bg-rose-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50" data-testid="review-close-line-submit" :disabled="closeLineBusy || !closeLineReason.trim()" @click="confirmCloseLine">{{ t('chat.shippingOrderReview.lineActions.closeLineConfirm') }}</button>
</div>
</div>
</div>
@@ -142,6 +142,16 @@ const lineRows = computed(() => {
return Array.isArray(item?.notice_line_summary) ? item!.notice_line_summary : [];
});
/**
* 数量/缺口展示值:后端 Numeric(24,8) 透出形如 "24.00000000",
* 统一转 number 去尾零(24.00000000→24、2.50000000→2.5),缺失保持 —。
*/
function formatQty(value: unknown): string {
if (value === null || value === undefined || value === '') return '—';
const num = Number(value);
return Number.isFinite(num) ? String(num) : String(value);
}
watch(() => props.item, (item) => {
if (!item) return;
const stage = defaultLifecycleTarget(item);
@@ -173,7 +183,7 @@ onBeforeUnmount(() => document.removeEventListener('keydown', onEsc));
data-testid="my-todos-drawer-scrim"
@click="emit('close')"
/>
<aside class="flex w-[34rem] max-w-[94vw] flex-col bg-surface shadow-2xl">
<aside class="flex w-[52rem] max-w-[94vw] flex-col bg-surface shadow-2xl">
<div class="border-b border-default px-5 py-4">
<div class="flex items-start justify-between gap-3">
<h3 class="break-all font-mono text-base font-bold text-primary" data-testid="my-todos-drawer-title">
@@ -238,14 +248,14 @@ onBeforeUnmount(() => document.removeEventListener('keydown', onEsc));
<table class="w-full border-collapse text-xs" data-testid="my-todos-drawer-lines">
<thead>
<tr class="border-b border-default bg-surface-soft/60 text-left text-muted">
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.lineNo') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.partNumber') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.customerPartNumber') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.reservationId') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shipmentQty') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.availableQty') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shortageQty') }}</th>
<th class="px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.status') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.lineNo') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.partNumber') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.customerPartNumber') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.reservationId') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shipmentQty') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.availableQty') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shortageQty') }}</th>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.status') }}</th>
</tr>
</thead>
<tbody>
@@ -255,18 +265,18 @@ onBeforeUnmount(() => document.removeEventListener('keydown', onEsc));
class="border-b border-[#f0f3f8]"
>
<td class="px-2.5 py-2 font-mono">{{ line.line_no }}</td>
<td class="px-2.5 py-2 font-mono">{{ line.part_number || '—' }}</td>
<td class="px-2.5 py-2">{{ line.customer_part_number || '—' }}</td>
<td class="px-2.5 py-2 font-mono">{{ line.reservation_id || '—' }}</td>
<td class="px-2.5 py-2 tabular-nums">{{ line.shipment_qty ?? '—' }}</td>
<td class="px-2.5 py-2 tabular-nums">{{ line.available_qty ?? '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2 font-mono">{{ line.part_number || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2">{{ line.customer_part_number || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2 font-mono">{{ line.reservation_id || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2 tabular-nums">{{ formatQty(line.shipment_qty) }}</td>
<td class="whitespace-nowrap px-2.5 py-2 tabular-nums">{{ formatQty(line.available_qty) }}</td>
<td
class="px-2.5 py-2 tabular-nums"
class="whitespace-nowrap px-2.5 py-2 tabular-nums"
:class="Number(line.shortage_qty || 0) > 0 ? 'font-bold text-red-600' : ''"
>
{{ line.shortage_qty ?? '—' }}
{{ formatQty(line.shortage_qty) }}
</td>
<td class="px-2.5 py-2">{{ line.inventory_status || '—' }}</td>
<td class="whitespace-nowrap px-2.5 py-2">{{ line.inventory_status || '—' }}</td>
</tr>
</tbody>
</table>
+9 -17
View File
@@ -629,14 +629,11 @@
"orderSchemaRequired": "Publish an Order Fields version first; inventory parsing profiles, shipping Excel templates, and routing rules can then reference order fields.",
"connections": "System Connections",
"receiptReportConfig": "Receipt Report Configuration",
"receiptReportConfigHint": "Separate from inventory report paths and inventory query parameters. DBS exports each Warehouse below separately; report date is never filtered.",
"receiptReportEnabled": "Enable receipt export",
"receiptWarehouses": "Receipt Warehouse list",
"receiptWarehousesHint": "Separate multiple Warehouses with commas",
"receiptOptionalParameters": "Optional query parameters (excluding report date)",
"receiptReportConfigHint": "Same structure as inventory configuration: report path + query parameters. Each warehouse in the Warehouse condition exports one receipt file per schedule; report date is never filtered. Receipt has no separate switch and follows the site's unified enablement.",
"receiptQueryParametersHint": "Same as inventory query parameters. Warehouse supports multiple values (comma-separated); each Warehouse exports one receipt file. Report date filtering is never allowed.",
"receiptCraneFixedPath": "Crane receipt export is fixed to Inbound Details and is not split by Warehouse. No query conditions are maintained; execution directly runs the page defaults.",
"saveReceiptReportConfig": "Save receipt configuration",
"receiptReportSaved": "Receipt report configuration saved",
"pathSectionConfigured": "Configured",
"pathSectionNotConfigured": "Not configured",
"parsingProfiles": "Inventory Parsing",
"parsingProfilesHelp": "Maintain inventory file structures, field mappings, and order-field match keys shared by inventory sites.",
"inventoryMapping": "Inventory Parsing",
@@ -896,12 +893,11 @@
"parsingBindingOperationBulk": "Bulk binding",
"parsingBindingVersion": "Configuration version {before} to {after}",
"sourceSavedDisabledHint": "The site remains disabled after its first save. Complete the test export, inventory parsing, and shipping template before activation.",
"activationStatus": "Production Readiness",
"readinessProgress": "{passed} of {total} complete",
"activationRequiredTitle": "Next step",
"activationRequiredHint": "Complete the current item and the system will continue deciding whether the site can be enabled automatically.",
"readinessBlockedBy": "One step left before enablement: {requirement}",
"readinessAutoEnableHint": "After completion the system will evaluate and enable the site automatically.",
"readinessLastVerified": "Last verified {time}",
"readinessOptionalPending": "{count} item(s) pending for later",
"activationOptionalTitle": "Prepare later (does not block enablement)",
"activationOptionalHint": "Complete when inventory exists or before an actual transfer.",
"readinessState": {
"passed": "Complete",
"required": "Action required",
@@ -918,12 +914,8 @@
"configure_warehouse_mapping": "Configure warehouse mapping"
},
"saveBeforeReadinessAction": "Save the current inventory-site changes before taking this action.",
"activationReady": "The inventory site is enabled and can run in production.",
"activationDraft": "The inventory site is disabled. Complete the following items before activation.",
"activationReady": "Site enabled. Inventory and receipt runs follow the site switch.",
"activationCanEnable": "All enablement conditions pass. You can enable this inventory site.",
"activationEnabledHint": "This site participates in production inventory runs.",
"activationCanEnableHint": "Click Enable Inventory Site to start production runs, or run another successful test export to auto-enable.",
"activationMissingHint": "Complete only the unfinished required items. Later preparation does not block enablement.",
"activationRequirement": {
"rpa_profile": "System connection is available",
"parsing_profile": "Inventory file parsing profile",
+17
View File
@@ -2219,6 +2219,12 @@
"hint": "Other lines on the same snapshot file use this ODM ID too; Excel generation retries automatically",
"column": "ODM ID"
},
"inlineEdit": {
"saved": "Saved. Click \"Re-match inventory\" to apply",
"busy": "System is busy. Please try again later",
"save": "Save",
"cancel": "Cancel"
},
"fulfillmentDecision": {
"title": "Line fulfillment decisions",
"subtitle": "Select inventory-ready or manually released lines to create an independent shipping notice and Excel.",
@@ -2354,6 +2360,13 @@
"success": "Lines closed",
"failed": "Close failed. Try again."
},
"lineActions": {
"closeLine": "Close line (no shipment)",
"closeLineReason": "Enter a reason to close",
"closeLineConfirm": "Confirm close",
"editLine": "Edit",
"more": "More actions"
},
"auditTrail": {
"open": "Audit trail",
"title": "Operation audit",
@@ -2742,6 +2755,10 @@
"inventory_rpa_export_failed": "Inventory export failed",
"inventory_file_empty": "Inventory file empty"
}
},
"releaseBar": {
"label": "Release info",
"badge": "{n} missing release field(s)"
}
},
"shippingOrderExtractionElapsed": "Elapsed {elapsed}",
+9 -17
View File
@@ -629,14 +629,11 @@
"orderSchemaRequired": "โปรดเผยแพร่เวอร์ชันฟิลด์คำสั่งซื้อก่อน เพื่อให้โปรไฟล์การแยกวิเคราะห์สต็อก เทมเพลต Excel สำหรับจัดส่ง และกฎการกำหนดเส้นทางอ้างอิงฟิลด์คำสั่งซื้อได้",
"connections": "การเชื่อมต่อระบบ",
"receiptReportConfig": "การตั้งค่ารายงานรับสินค้า",
"receiptReportConfigHint": "แยกจากเส้นทางรายงานสต็อกและเงื่อนไขค้นหาสต็อก DBS ส่งออกแยกตาม Warehouse ด้านล่าง และไม่กรองวันที่รายงาน",
"receiptReportEnabled": "เปิดใช้การส่งออกรับสินค้า",
"receiptWarehouses": "รายการ Warehouse รับสินค้า",
"receiptWarehousesHint": "คั่นหลาย Warehouse ด้วยเครื่องหมายจุลภาค",
"receiptOptionalParameters": "เงื่อนไขค้นหาเพิ่มเติม (ไม่รวมวันที่รายงาน)",
"receiptReportConfigHint": "โครงสร้างเหมือนการตั้งค่าสต็อก: เส้นทางรายงาน + เงื่อนไขค้นหา แต่ละ Warehouse ในเงื่อนไขจะส่งออกไฟล์รับสินค้าหนึ่งไฟล์ต่อรอบ และไม่กรองวันที่รายงาน การรับสินค้าไม่มีสวิตช์แยก และจะเปิดหรือปิดตามไซต์โดยรวม",
"receiptQueryParametersHint": "เหมือนเงื่อนไขค้นหาสต็อก Warehouse รองรับหลายค่า (คั่นด้วยเครื่องหมายจุลภาค) แต่ละ Warehouse จะส่งออกไฟล์รับสินค้าหนึ่งไฟล์ และห้ามกรองวันที่รายงาน",
"receiptCraneFixedPath": "การส่งออกรับสินค้าของ Crane ถูกกำหนดเป็น Inbound Details และไม่แยกตาม Warehouse ไม่มีการบำรุงรักษาเงื่อนไขค้นหา และระบบจะ Run Report ด้วยค่าเริ่มต้นของหน้าเว็บโดยตรง",
"saveReceiptReportConfig": "บันทึกการตั้งค่ารับสินค้า",
"receiptReportSaved": "บันทึกการตั้งค่ารายงานรับสินค้าแล้ว",
"pathSectionConfigured": "ตั้งค่าแล้ว",
"pathSectionNotConfigured": "ยังไม่ได้ตั้งค่า",
"parsingProfiles": "แผนการแยกวิเคราะห์ไฟล์สต็อก",
"parsingProfilesHelp": "จัดการโครงสร้างไฟล์สต็อก การจับคู่ฟิลด์ และคีย์จับคู่ฟิลด์คำสั่งซื้อที่ใช้ร่วมกันได้ระหว่างไซต์สต็อก",
"inventoryMapping": "แผนการแยกวิเคราะห์ไฟล์สต็อก",
@@ -896,12 +893,11 @@
"parsingBindingOperationBulk": "ผูกแบบกลุ่ม",
"parsingBindingVersion": "เวอร์ชันการตั้งค่า {before} → {after}",
"sourceSavedDisabledHint": "ไซต์จะยังปิดใช้งานหลังบันทึกครั้งแรก โปรดทำการส่งออกทดสอบ แผนการอ่าน และเทมเพลตการจัดส่งให้เสร็จก่อนเปิดใช้งาน",
"activationStatus": "การตรวจสอบก่อนใช้งานจริง",
"readinessProgress": "เสร็จแล้ว {passed} / {total}",
"activationRequiredTitle": "ขั้นตอนถัดไป",
"activationRequiredHint": "ทำรายการปัจจุบันให้เสร็จ แล้วระบบจะพิจารณาการเปิดใช้งานอัตโนมัติต่อไป",
"readinessBlockedBy": "เหลืออีกหนึ่งขั้นก่อนเปิดใช้งาน: {requirement}",
"readinessAutoEnableHint": "เมื่อเสร็จแล้วระบบจะประเมินและเปิดใช้งานไซต์ให้อัตโนมัติ",
"readinessLastVerified": "ตรวจสอบล่าสุด {time}",
"readinessOptionalPending": "เหลือ {count} รายการที่ทำภายหลัง",
"activationOptionalTitle": "การเตรียมภายหลัง (ไม่ขัดขวางการเปิดใช้งาน)",
"activationOptionalHint": "ดำเนินการเมื่อมีสต็อกหรือก่อนโอนย้ายจริง",
"readinessState": {
"passed": "เสร็จสมบูรณ์",
"required": "ต้องดำเนินการ",
@@ -918,12 +914,8 @@
"configure_warehouse_mapping": "ตั้งค่าการแมปคลังสินค้า"
},
"saveBeforeReadinessAction": "โปรดบันทึกการเปลี่ยนแปลงไซต์สต็อกปัจจุบันก่อนดำเนินการนี้",
"activationReady": "เปิดใช้งานไซต์สต็อกแล้วและพร้อมใช้งานจริง",
"activationDraft": "ไซต์สต็อกยังปิดใช้งาน โปรดทำรายการต่อไปนี้ให้เสร็จก่อนเปิดใช้งาน",
"activationReady": "ไซต์เปิดใช้งานแล้ว งานสต็อกและรับสินค้าจะเปิดหรือปิดตามสวิตช์ไซต์",
"activationCanEnable": "ผ่านทุกเงื่อนไขแล้ว สามารถเปิดใช้งานไซต์สต็อกนี้ได้",
"activationEnabledHint": "ไซต์นี้เข้าร่วมการทำงานสต็อกจริงแล้ว",
"activationCanEnableHint": "คลิกเปิดใช้งานไซต์สต็อกเพื่อเริ่มใช้งานจริง หรือทดสอบส่งออกอีกครั้ง ระบบจะเปิดใช้งานอัตโนมัติเมื่อผ่าน",
"activationMissingHint": "ทำเฉพาะเงื่อนไขการเปิดใช้งานที่ยังไม่ผ่าน การเตรียมภายหลังไม่ขัดขวางการเปิดใช้งาน",
"activationRequirement": {
"rpa_profile": "การเชื่อมต่อระบบพร้อมใช้งาน",
"parsing_profile": "แผนการแยกวิเคราะห์ไฟล์สต็อก",
+17
View File
@@ -2219,6 +2219,12 @@
"hint": "แถวอื่นในไฟล์สแนปชอตเดียวกันจะใช้ ODM ID เดียวกัน และสร้าง Excel ใหม่โดยอัตโนมัติ",
"column": "ODM ID"
},
"inlineEdit": {
"saved": "บันทึกแล้ว กด \"จับคู่สินค้าคงเหลือใหม่\" เพื่อใช้งาน",
"busy": "ระบบกำลังประมวลผล โปรดลองอีกครั้งภายหลัง",
"save": "บันทึก",
"cancel": "ยกเลิก"
},
"fulfillmentDecision": {
"title": "การตัดสินใจการปฏิบัติตามบรรทัด",
"subtitle": "เลือกหลายบรรทัดที่สต็อกพร้อมหรืออนุมัติด้วยมือ เพื่อสร้างใบแจ้งการจัดส่งและ Excel แยกอิสระ",
@@ -2354,6 +2360,13 @@
"success": "ปิดบรรทัดแล้ว",
"failed": "ปิดล้มเหลว โปรดลองใหม่"
},
"lineActions": {
"closeLine": "ปิดบรรทัด (ไม่จัดส่ง)",
"closeLineReason": "กรอกเหตุผลเพื่อปิด",
"closeLineConfirm": "ยืนยันการปิด",
"editLine": "แก้ไข",
"more": "การดำเนินการเพิ่มเติม"
},
"auditTrail": {
"open": "บันทึก audit",
"title": "Audit การดำเนินการ",
@@ -2742,6 +2755,10 @@
"inventory_rpa_export_failed": "ส่งออกสต็อกล้มเหลว",
"inventory_file_empty": "ไฟล์สต็อกว่าง"
}
},
"releaseBar": {
"label": "ข้อมูลเพิ่มเติมเพื่อปล่อยของ",
"badge": "ขาด {n} รายการก่อนปล่อย"
}
},
"shippingOrderExtractionElapsed": "ใช้เวลา {elapsed}",
+9 -17
View File
@@ -758,14 +758,11 @@
"orderSchemaRequired": "请先在「订单 Schema」发布一个版本;库存解析、发货模板和路由规则才能引用订单字段。",
"connections": "系统连接",
"receiptReportConfig": "收料报表配置",
"receiptReportConfigHint": "独立于库存报表路径与库存查询条件。DBS 会按下方每个 Warehouse 分别导出;报表日期固定不筛选。",
"receiptReportEnabled": "启用收料导出",
"receiptWarehouses": "收料 Warehouse 列表",
"receiptWarehousesHint": "多个 Warehouse 用英文逗号分隔",
"receiptOptionalParameters": "可选查询条件(不含报表日期)",
"receiptReportConfigHint": "与库存配置同构:报表路径 + 查询条件。Warehouse 条件填几个仓,排程逐仓拆分导出几个收料文件;报表日期固定不筛选。收料无独立开关,随站点统一启停。",
"receiptQueryParametersHint": "与库存查询条件一致。Warehouse 支持多值(英文逗号分隔),每个 Warehouse 拆分导出一个收料文件;报表日期固定禁填。",
"receiptCraneFixedPath": "Crane 收料固定导出 Inbound Details,不按 Warehouse 拆分,也不维护查询条件;执行时直接使用页面默认条件点击 Run Report。",
"saveReceiptReportConfig": "保存收料配置",
"receiptReportSaved": "收料报表配置已保存",
"pathSectionConfigured": "已配置",
"pathSectionNotConfigured": "未配置",
"parsingProfiles": "库存解析",
"parsingProfilesHelp": "维护可由多个库存站点共享的库存文件结构、字段对应关系和订单字段匹配键。",
"inventoryMapping": "库存解析",
@@ -1025,12 +1022,11 @@
"parsingBindingOperationBulk": "批量绑定",
"parsingBindingVersion": "配置版本 {before} → {after}",
"sourceSavedDisabledHint": "首次保存后站点保持停用;请完成测试导出、库存解析和发货模板配置后再启用。",
"activationStatus": "正式运行检查",
"readinessProgress": "{passed} / {total} 已完成",
"activationRequiredTitle": "下一步",
"activationRequiredHint": "完成当前项目后,系统会继续判断是否可以自动启用。",
"readinessBlockedBy": "启用前还差一步:{requirement}",
"readinessAutoEnableHint": "完成后系统会自动判断并启用站点。",
"readinessLastVerified": "上次验证 {time}",
"readinessOptionalPending": "{count} 项待后续完成",
"activationOptionalTitle": "后续准备(不影响启用)",
"activationOptionalHint": "有库存数据或实际调拨前再完成。",
"readinessState": {
"passed": "已完成",
"required": "需要完成",
@@ -1047,12 +1043,8 @@
"configure_warehouse_mapping": "配置仓库映射"
},
"saveBeforeReadinessAction": "请先保存当前库存站点更改,再执行此操作。",
"activationReady": "库存站点已启用,可进入正式库存运行。",
"activationDraft": "库存站点当前停用;完成以下项目后才可启用。",
"activationReady": "站点已启用,库存与收料随站点统一运行。",
"activationCanEnable": "启用条件已满足,可启用该库存站点。",
"activationEnabledHint": "站点已参与正式库存运行。",
"activationCanEnableHint": "点击“启用库存站点”即可投入正式运行;也可再次测试导出,通过后仍会自动启用。",
"activationMissingHint": "仅需完成“启用条件”中的未通过项目;后续准备不影响启用。",
"activationRequirement": {
"rpa_profile": "系统连接可用",
"parsing_profile": "库存解析",
+17
View File
@@ -2326,6 +2326,12 @@
"hint": "同一快照文件的其他行会同步使用该 ODM ID,确认后自动重试生成 Excel",
"column": "ODM ID"
},
"inlineEdit": {
"saved": "已保存,请点击「重新匹配库存」生效",
"busy": "系统处理中,请稍后再修改",
"save": "保存",
"cancel": "取消"
},
"fulfillmentDecision": {
"title": "行级履约决定",
"subtitle": "可多选库存满足或已人工放行的明细,生成独立发货通知和 Excel。",
@@ -2473,6 +2479,13 @@
"success": "行已关闭",
"failed": "关闭失败,请重试"
},
"lineActions": {
"closeLine": "结案(不再发货)",
"closeLineReason": "请填写结案原因",
"closeLineConfirm": "确认结案",
"editLine": "编辑",
"more": "更多操作"
},
"auditTrail": {
"open": "审计记录",
"title": "操作审计",
@@ -2850,6 +2863,10 @@
"missing_order_table": "缺少订单表格",
"other": "其他(须填写说明)"
}
},
"releaseBar": {
"label": "放行补录",
"badge": "缺 {n} 项放行信息"
}
},
"shippingProcessing": {
+9 -17
View File
@@ -629,14 +629,11 @@
"orderSchemaRequired": "請先在「訂單欄位規則」發佈一個版本;庫存解析、出貨範本和路由規則才能引用訂單欄位。",
"connections": "系統連線",
"receiptReportConfig": "收料報表設定",
"receiptReportConfigHint": "獨立於庫存報表路徑與庫存查詢條件。DBS 會依下方每個 Warehouse 分別匯出;報表日期固定不篩選。",
"receiptReportEnabled": "啟用收料匯出",
"receiptWarehouses": "收料 Warehouse 清單",
"receiptWarehousesHint": "多個 Warehouse 以英文逗號分隔",
"receiptOptionalParameters": "可選查詢條件(不含報表日期)",
"receiptReportConfigHint": "與庫存設定同構:報表路徑 + 查詢條件。Warehouse 條件填幾個倉,排程逐倉拆分匯出幾個收料檔案;報表日期固定不篩選。收料無獨立開關,隨站點統一啟停。",
"receiptQueryParametersHint": "與庫存查詢條件一致。Warehouse 支援多值(英文逗號分隔),每個 Warehouse 拆分匯出一個收料檔案;報表日期固定禁填。",
"receiptCraneFixedPath": "Crane 收料固定匯出 Inbound Details,不依 Warehouse 拆分,也不維護查詢條件;執行時直接使用頁面預設條件點擊 Run Report。",
"saveReceiptReportConfig": "儲存收料設定",
"receiptReportSaved": "收料報表設定已儲存",
"pathSectionConfigured": "已設定",
"pathSectionNotConfigured": "未設定",
"parsingProfiles": "庫存解析",
"parsingProfilesHelp": "維護可由多個庫存站點共用的庫存檔案結構、欄位對應與訂單欄位匹配鍵。",
"inventoryMapping": "庫存解析",
@@ -896,12 +893,11 @@
"parsingBindingOperationBulk": "批量綁定",
"parsingBindingVersion": "設定版本 {before} → {after}",
"sourceSavedDisabledHint": "首次儲存後站點保持停用;請完成測試匯出、庫存解析與出貨範本設定後再啟用。",
"activationStatus": "正式執行檢查",
"readinessProgress": "已完成 {passed} / {total}",
"activationRequiredTitle": "下一步",
"activationRequiredHint": "完成目前項目後,系統會繼續判斷是否可自動啟用。",
"readinessBlockedBy": "啟用前還差一步:{requirement}",
"readinessAutoEnableHint": "完成後系統會自動判斷並啟用站點。",
"readinessLastVerified": "上次驗證 {time}",
"readinessOptionalPending": "{count} 項待後續完成",
"activationOptionalTitle": "後續準備(不影響啟用)",
"activationOptionalHint": "有庫存資料或實際調撥前再完成。",
"readinessState": {
"passed": "已完成",
"required": "需要完成",
@@ -918,12 +914,8 @@
"configure_warehouse_mapping": "設定倉庫對應"
},
"saveBeforeReadinessAction": "請先儲存目前庫存站點的變更,再執行此操作。",
"activationReady": "庫存站點已啟用,可進入正式庫存執行。",
"activationDraft": "庫存站點目前停用;完成以下項目後才可啟用。",
"activationReady": "站點已啟用,庫存與收料隨站點統一執行。",
"activationCanEnable": "已符合啟用條件,可啟用此庫存站點。",
"activationEnabledHint": "站點已參與正式庫存執行。",
"activationCanEnableHint": "點選「啟用庫存站點」即可投入正式執行;也可再次測試匯出,通過後仍會自動啟用。",
"activationMissingHint": "只需完成「啟用條件」中未通過的項目;後續準備不影響啟用。",
"activationRequirement": {
"rpa_profile": "系統連線可用",
"parsing_profile": "庫存解析",
+17
View File
@@ -2219,6 +2219,12 @@
"hint": "同一快照檔案的其他行會同步使用該 ODM ID,確認後自動重試產生 Excel",
"column": "ODM ID"
},
"inlineEdit": {
"saved": "已儲存,請點擊「重新匹配庫存」生效",
"busy": "系統處理中,請稍後再修改",
"save": "儲存",
"cancel": "取消"
},
"fulfillmentDecision": {
"title": "行級履約決定",
"subtitle": "可多選庫存滿足或已人工放行的明細,產生獨立發貨通知和 Excel。",
@@ -2354,6 +2360,13 @@
"success": "行已關閉",
"failed": "關閉失敗,請重試"
},
"lineActions": {
"closeLine": "結案(不再發貨)",
"closeLineReason": "請填寫結案原因",
"closeLineConfirm": "確認結案",
"editLine": "編輯",
"more": "更多操作"
},
"auditTrail": {
"open": "稽核記錄",
"title": "操作稽核",
@@ -2742,6 +2755,10 @@
"inventory_rpa_export_failed": "庫存匯出失敗",
"inventory_file_empty": "庫存檔案為空"
}
},
"releaseBar": {
"label": "放行補錄",
"badge": "缺 {n} 項放行資訊"
}
},
"shippingOrderExtractionElapsed": "已用時 {elapsed}",
+29 -3
View File
@@ -119,6 +119,32 @@ DSV Worker 默认使用 `#file2`,也可用 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_
`em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #` 时回调成功,Reference
作为货代回执号。CRANE 上传路径尚未确认,Worker 会显式失败,绝不会误用 DSV 页面。
## Trigger 目录四态契约(所有 Worker 强制)
| 目录 | 含义 | 进入方式 |
| --- | --- | --- |
| `<root>/*.json` | 待领取 | 后端经临时文件+`os.replace` 原子写入 |
| `<root>/processing/` | 已领取、处理中 | Worker 经 `common/trigger_consumer.claim_trigger` 原子 rename |
| `<root>/processed/` | 处理并回调成功 | `archive_trigger(claimed, 'processed')` |
| `<root>/failed/` | 处理或回调失败,需人工 | `archive_trigger(claimed, 'failed')` |
- 领取失败(返回 None)= 已被其他消费者处理,跳过,禁止原地读取根目录文件。
- Worker 崩溃可能留下 `processing/` 残留:重启不会自动重跑(防重复导出/重复回调);
人工确认导出未完成则移回根目录重跑,已完成则人工补回调后归档。
- 新增 Worker 一律复用 `common/trigger_consumer.py`,禁止再自建目录搬移逻辑。
## Worker 运行能力(库存 / 收料对齐)
| 能力 | 库存 Worker | 收料 Worker |
| --- | --- | --- |
| 文件日志(tee+时间戳+轮转) | `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` | 同左(ps1 默认 `data\freight_receipt_rpa\logs\worker.log`) |
| 启动 banner / 运行中轮转 | ✅ | ✅(同一 `worker_logging` 模块) |
| 心跳上报 | `<hostname>-<pid>`(随进程重启变化,ps1 未注入 `WORKER_ID`) | `<hostname>-receipt`(独立身份,ps1 注入) |
| 磁盘保留清理 | 周期 + 启动一轮 | 同左(清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`) |
规则:**两个 Worker 禁止共写同一日志文件**(多进程写同一文件会交错且 Windows 轮转竞争);
每个 Worker 的 `LOG_FILE` 必须指向各自根目录下的 `logs/worker.log`。
## 部署、启动与停止手册
本节说明库存 RPA 测试导出的三种运行方式:
@@ -170,9 +196,9 @@ Linux HXOPS 后端 Windows RPA Worker
2. 程序:整目录复制 `scripts\rpa` 时已包含 `receipt\`;`receipt_rpa_worker.py` 要求同级存在 `connectors/`、`common/`、`inventory/`、`receipt/` 四个子目录,不能单拷 `receipt\`。
3. 依赖:在库存 Worker 依赖之上补 `cryptography`:`python -m pip install playwright openpyxl pyyaml cryptography`。
4. Secret:与库存共用 `new_rpa_worker_secret.ps1` 生成的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`,无需新建。
5. 启动:`scripts\rpa\receipt\start_receipt_worker.ps1`,参数与库存启动脚本一致(`-Environment`、`-ApiBase`、`-WorkerRoot`、`-SecretFile`,可选 `-Mock` / `-Headless`);成功输出 `[freight_receipt_rpa_worker] started trigger_dir=... drop_dir=...`。
6. 心跳/哨兵:收料 Worker **不发心跳、不写哨兵**,不参与「RPA Worker 在线」检查;收料触发前无 fail-fast,Worker 停止只会让单元等到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。
7. 日志:收料 Worker 只输出到控制台;计划任务用 `cmd.exe` 包装 `>>` 重定向到 `data\freight_receipt_rpa\logs\receipt_worker.log`(完整任务计划示例见 technical.md §1.9.2)。
5. 启动:`scripts\rpa\receipt\start_receipt_worker.ps1`,参数与库存启动脚本一致(`-Environment`、`-ApiBase`、`-WorkerRoot`、`-SecretFile`,可选 `-Mock` / `-Headless`);成功输出 `[freight_receipt_rpa_worker] started` 独立行,后跟缩进字段块(` mock=...`、` api_base=...`、` trigger_dir=...`、` drop_dir=...`、` log=...` 等,完整字段以 `receipt_rpa_worker.py` 启动 banner 为准)。
6. 心跳/哨兵:心跳已接——以独立身份 `<主机名>-receipt`(ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_ID`)按 `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS`(默认 20 秒)周期上报 `/api/shipping-notice/rpa/heartbeat`;仍不写 `.hxops_rpa_shared_mount` 哨兵、触发前无 fail-fast 在线检查,Worker 停止只会让单元等到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。
7. 日志:文件日志已接——ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`,默认 `data\freight_receipt_rpa\logs\worker.log`(tee 控制台 + 时间戳 + 按大小轮转,与库存 Worker 同一 `worker_logging` 模块,两个 Worker 禁止共写同一日志文件);计划任务仍可用 `cmd.exe` 包装 `>>` 重定向控制台输出留档(完整任务计划示例见 technical.md §1.9.2)。
8. 后端:`.env` 追加 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` / `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR` 两个共享子路径(漏配会写容器本地默认路径,Windows 看不到);容器 bind mount 无需新增。收料文件回调后原样归档 MinIO 保留三年,到期清理由平台任务「货代收料归档到期清理」负责。
+60
View File
@@ -0,0 +1,60 @@
"""RPA trigger 文件统一消费契约:领取(claim)与归档(archive)原语。
用途:为库存/收料/上传等所有 Windows Worker 提供一致的 trigger 目录生命周期,
替代各 Worker 各自实现"原地处理/领取归档"两套逻辑(重复轮子收敛点)。
依赖:仅标准库 pathlib;禁止引入 playwright 或后端 app 依赖(Worker 独立运行)。
逻辑:目录四态契约——
<root>/*.json 待领取(后端临时文件+os.replace 原子写入)
<root>/processing/ 已领取处理中(崩溃残留人工可见,不会被重扫重复导出)
<root>/processed/ 处理并回调成功
<root>/failed/ 处理或回调失败,需人工排查
领取 = 同盘 rename 到 processing/(原子);被第二个消费者抢走时返回 None。
"""
from __future__ import annotations
from pathlib import Path
_PROCESSING = "processing"
_OUTCOMES = ("processed", "failed")
def claim_trigger(path: Path) -> Path | None:
"""原子领取一个 trigger 文件到同根 processing/ 目录。
Args:
path: 根目录下的 trigger json 路径。
Returns:
领取后的 processing/ 内路径;文件不存在或已被他人领取时返回 None。
"""
processing_dir = path.parent / _PROCESSING
try:
processing_dir.mkdir(parents=True, exist_ok=True)
claimed = processing_dir / path.name
path.replace(claimed)
return claimed
except OSError:
# Windows 下目标已存在(被另一 Worker 先领取)或文件已消失:放弃本个。
return None
def archive_trigger(claimed: Path, outcome: str) -> Path:
"""把 processing/ 中已处理完的 trigger 归档到终态目录。
Args:
claimed: claim_trigger 返回的 processing/ 内路径。
outcome: 仅允许 'processed'(回调成功)或 'failed'(需人工排查)。
Returns:
归档后的完整路径。
Raises:
ValueError: outcome 非法,或 claimed 不在 processing/ 目录下。
"""
if outcome not in _OUTCOMES:
raise ValueError(f"invalid trigger outcome: {outcome}")
if claimed.parent.name != _PROCESSING:
raise ValueError("trigger must be claimed into processing/ before archive")
target_dir = claimed.parent.parent / outcome
target_dir.mkdir(parents=True, exist_ok=True)
target = target_dir / claimed.name
claimed.replace(target)
return target
+9 -5
View File
@@ -48,6 +48,9 @@ _PROTECTED_DROP_DIRNAMES = frozenset(
)
_DROP_ROOT_SUFFIXES = frozenset({".xlsx", ".xls", ".csv", ".hxops_consumed"})
_TRIGGER_ARCHIVE_DIRNAMES = ("processed", "failed")
# 一次性运行 Profile 前缀:库存 Worker 用 run_*,收料 Worker 用 receipt_*,
# 两者均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "receipt_")
_DEFAULT_RETENTION_DAYS = 7
_DEFAULT_INTERVAL_SECONDS = 3600
_DEFAULT_ORPHAN_PROFILE_HOURS = 24
@@ -108,7 +111,7 @@ def cleanup_interval_seconds() -> int:
def orphan_profile_max_age_seconds() -> int:
"""
读取孤儿临时 Profile(run_*)最大存活秒数。
读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
@@ -332,10 +335,11 @@ def cleanup_orphan_runtime_profiles(
stats: DiskCleanupStats,
) -> None:
"""
清理浏览器 Profile 根下过期的一次性 `run_*` 目录。
清理浏览器 Profile 根下过期的一次性 `run_*` / `receipt_*` 目录。
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
仅删除 `run_*` 临时目录,避免异常中断后残留撑盘。
仅删除 `run_*` / `receipt_*` 临时目录,避免异常中断后残留撑盘。
收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。
"""
if profile_root is None or not profile_root.is_dir():
return
@@ -350,7 +354,7 @@ def cleanup_orphan_runtime_profiles(
if name.endswith("_session") or name == "dsv360_session":
stats.skipped += 1
continue
if not name.startswith("run_"):
if not name.startswith(_RUNTIME_PROFILE_TEMP_PREFIXES):
stats.skipped += 1
continue
if not _is_older_than(path, cutoff_unix=cutoff_unix):
@@ -375,7 +379,7 @@ def run_worker_disk_cleanup(
【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。
核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` Profile。全部 best-effort。
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `receipt_*` Profile。全部 best-effort。
Args:
inventory_trigger_dir: 库存 trigger 根目录。
+249
View File
@@ -0,0 +1,249 @@
"""scripts/rpa/common/worker_logging.py
用途:RPA Worker 通用文件日志——stdout/stderr tee 落盘、行级本地时间戳、
按大小轮转(启动前 + 运行中),供库存/收料等所有 Worker 复用。
依赖:rpa_common._env(环境变量读取与历史名兼容)、标准库。
逻辑:configure_file_logging 读 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用;
maybe_rotate_open_log 在主循环周期调用做运行中轮转;shutdown_logging 恢复标准流。
"""
from __future__ import annotations
import atexit
import sys
from datetime import UTC, datetime
from pathlib import Path
from typing import TextIO
from rpa_common import _env
def _backend_dir() -> Path:
"""返回仓库内 backend 根目录(本模块位于 <repo>/scripts/rpa/common/)。"""
return Path(__file__).resolve().parents[3] / "backend"
def log_line_timestamp() -> str:
"""
生成 worker 日志行首时间戳(本地时区)。
核心逻辑:RPA 批量导出常跨 1+ 小时,行级时间便于对照 DSV 页面卡顿与超时点。
Returns:
str: `YYYY-MM-DD HH:MM:SS` 格式字符串。
"""
return datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int:
"""读取日志相关整数环境变量;非法值回退默认值。"""
try:
value = int(_env(name, str(default)) or str(default))
except ValueError:
return default
return max(value, min_value)
class WorkerLogTee:
"""
同时写入控制台与日志文件的轻量 stream。
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量
保留最后几行排障信息;支持运行中替换底层日志句柄以便按大小轮转。
"""
def __init__(self, console: TextIO, log_file: TextIO) -> None:
self._console = console
self._log_file = log_file
self._pending = ""
self.encoding = getattr(console, "encoding", "utf-8")
def replace_log_file(self, log_file: TextIO) -> TextIO:
"""
替换底层日志文件句柄(用于运行中轮转)。
核心逻辑:先 flush 缓冲,再切换句柄;调用方负责关闭旧句柄与打开新文件。
Args:
log_file: 新的追加写日志句柄。
Returns:
TextIO: 被替换下来的旧日志句柄。
"""
self.flush()
previous = self._log_file
self._log_file = log_file
return previous
def _emit_line(self, line: str, *, newline: bool) -> None:
"""将单行(可含时间戳前缀)写入控制台与日志文件。"""
if line:
stamped = f"{log_line_timestamp()} {line}"
self._console.write(stamped)
self._log_file.write(stamped)
if newline:
self._console.write("\n")
self._log_file.write("\n")
def write(self, text: str) -> int:
self._pending += text
while "\n" in self._pending:
line, self._pending = self._pending.split("\n", 1)
self._emit_line(line, newline=True)
self.flush()
return len(text)
def flush(self) -> None:
if self._pending:
self._emit_line(self._pending, newline=False)
self._pending = ""
self._console.flush()
self._log_file.flush()
def isatty(self) -> bool:
return bool(getattr(self._console, "isatty", lambda: False)())
# 运行中日志轮转需要持有 Tee 与路径;仅由 configure_file_logging / maybe_rotate_open_log 维护。
_ACTIVE_LOG_PATH: Path | None = None
_ACTIVE_STDOUT_TEE: WorkerLogTee | None = None
_ACTIVE_STDERR_TEE: WorkerLogTee | None = None
_ACTIVE_LOG_HANDLE: TextIO | None = None
def configure_file_logging() -> Path | None:
"""
按 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用 worker 文件日志。
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
登录、下载、回调失败与长批次耗时。
Returns:
Path | None: 已启用的日志路径;未配置时返回 None。
"""
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
if _ACTIVE_LOG_PATH is not None:
return _ACTIVE_LOG_PATH
raw = _env("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE")
if not raw:
return None
path = Path(raw).expanduser()
if not path.is_absolute():
path = (_backend_dir() / path).resolve()
path.parent.mkdir(parents=True, exist_ok=True)
rotate_log_file_if_needed(path)
log_file = path.open("a", encoding="utf-8", buffering=1)
original_stdout = sys.stdout
original_stderr = sys.stderr
stdout_tee = WorkerLogTee(original_stdout, log_file)
stderr_tee = WorkerLogTee(original_stderr, log_file)
sys.stdout = stdout_tee # type: ignore[assignment]
sys.stderr = stderr_tee # type: ignore[assignment]
_ACTIVE_LOG_PATH = path
_ACTIVE_STDOUT_TEE = stdout_tee
_ACTIVE_STDERR_TEE = stderr_tee
_ACTIVE_LOG_HANDLE = log_file
atexit.register(shutdown_logging)
print(f"[logging] tee enabled path={path}")
return path
def shutdown_logging() -> None:
"""
恢复 stdout/stderr 并关闭日志句柄(原 _configure_file_logging 内 _close_log 逻辑公开化)。
核心逻辑:把标准流还原为启用 tee 前的原流,关闭当前日志句柄并清空 _ACTIVE_* 状态;
由 configure_file_logging 注册到 atexit 兜底,进程退出时保证日志落盘完整。
未启用文件日志时 no-op。
"""
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
stdout_tee = _ACTIVE_STDOUT_TEE
stderr_tee = _ACTIVE_STDERR_TEE
if stdout_tee is not None:
sys.stdout = stdout_tee._console
if stderr_tee is not None:
sys.stderr = stderr_tee._console
handle = _ACTIVE_LOG_HANDLE
try:
handle.close()
except Exception:
pass
_ACTIVE_LOG_PATH = None
_ACTIVE_STDOUT_TEE = None
_ACTIVE_STDERR_TEE = None
_ACTIVE_LOG_HANDLE = None
def active_log_path() -> Path | None:
"""返回当前已启用的日志文件路径;未启用文件日志时返回 None。"""
return _ACTIVE_LOG_PATH
def maybe_rotate_open_log() -> None:
"""
常驻 Worker 运行中按大小轮转当前日志。
核心逻辑:Windows 下无法对仍打开的文件 rename,须先关闭句柄 → 调用既有
`rotate_log_file_if_needed` → 再以追加模式打开新文件并挂回 TeeStream。
未启用文件日志或未超限时 no-op。
"""
global _ACTIVE_LOG_HANDLE
path = _ACTIVE_LOG_PATH
stdout_tee = _ACTIVE_STDOUT_TEE
stderr_tee = _ACTIVE_STDERR_TEE
handle = _ACTIVE_LOG_HANDLE
if path is None or stdout_tee is None or stderr_tee is None or handle is None:
return
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
if max_bytes <= 0:
return
try:
handle.flush()
if path.stat().st_size < max_bytes:
return
except OSError:
return
try:
handle.close()
except Exception:
pass
_ACTIVE_LOG_HANDLE = None
rotate_log_file_if_needed(path)
new_handle = path.open("a", encoding="utf-8", buffering=1)
stdout_tee.replace_log_file(new_handle)
stderr_tee.replace_log_file(new_handle)
_ACTIVE_LOG_HANDLE = new_handle
print(f"[logging] rotated open log path={path}")
def rotate_log_file_if_needed(path: Path) -> None:
"""
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
核心逻辑:当 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 已存在且大小达到 `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES`
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT`
的旧文件会被删除。`SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。
"""
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
backup_count = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", 5, min_value=0)
if max_bytes <= 0 or not path.is_file():
return
try:
if path.stat().st_size < max_bytes:
return
except OSError:
return
if backup_count <= 0:
path.unlink(missing_ok=True)
return
oldest = Path(f"{path}.{backup_count}")
oldest.unlink(missing_ok=True)
for index in range(backup_count - 1, 0, -1):
src = Path(f"{path}.{index}")
if src.exists():
src.replace(Path(f"{path}.{index + 1}"))
path.replace(Path(f"{path}.1"))
+17 -218
View File
@@ -40,7 +40,6 @@ Optional:
"""
from __future__ import annotations
import atexit
from contextlib import contextmanager
import json
import os
@@ -53,7 +52,7 @@ import urllib.error
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Callable, TextIO
from typing import Any, Callable
from cryptography.fernet import Fernet, InvalidToken
@@ -90,6 +89,9 @@ import worker_disk_cleanup # noqa: E402
from download_artifact_fallback import ( # noqa: E402
wait_for_new_download_file as _wait_for_new_download_file,
)
from trigger_consumer import claim_trigger # noqa: E402
# 日志实现已提取至公共模块(scripts/rpa/common/worker_logging.py),本 Worker 仅委托调用。
from worker_logging import active_log_path, configure_file_logging, maybe_rotate_open_log # noqa: E402
# 测试与 smoke 向后兼容 re-export
_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
@@ -135,214 +137,6 @@ except ImportError:
Workbook = None # type: ignore
def _log_line_timestamp() -> str:
"""
生成 worker 日志行首时间戳(本地时区)。
核心逻辑:RPA 批量导出常跨 1+ 小时,行级时间便于对照 DSV 页面卡顿与超时点。
Returns:
str: `YYYY-MM-DD HH:MM:SS` 格式字符串。
"""
return datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
class _TeeStream:
"""
同时写入控制台与日志文件的轻量 stream。
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量
保留最后几行排障信息;支持运行中替换底层日志句柄以便按大小轮转。
"""
def __init__(self, console: TextIO, log_file: TextIO) -> None:
self._console = console
self._log_file = log_file
self._pending = ""
self.encoding = getattr(console, "encoding", "utf-8")
def replace_log_file(self, log_file: TextIO) -> TextIO:
"""
替换底层日志文件句柄(用于运行中轮转)。
核心逻辑:先 flush 缓冲,再切换句柄;调用方负责关闭旧句柄与打开新文件。
Args:
log_file: 新的追加写日志句柄。
Returns:
TextIO: 被替换下来的旧日志句柄。
"""
self.flush()
previous = self._log_file
self._log_file = log_file
return previous
def _emit_line(self, line: str, *, newline: bool) -> None:
"""将单行(可含时间戳前缀)写入控制台与日志文件。"""
if line:
stamped = f"{_log_line_timestamp()} {line}"
self._console.write(stamped)
self._log_file.write(stamped)
if newline:
self._console.write("\n")
self._log_file.write("\n")
def write(self, text: str) -> int:
self._pending += text
while "\n" in self._pending:
line, self._pending = self._pending.split("\n", 1)
self._emit_line(line, newline=True)
self.flush()
return len(text)
def flush(self) -> None:
if self._pending:
self._emit_line(self._pending, newline=False)
self._pending = ""
self._console.flush()
self._log_file.flush()
def isatty(self) -> bool:
return bool(getattr(self._console, "isatty", lambda: False)())
# 运行中日志轮转需要持有 Tee 与路径;仅由 _configure_file_logging / _maybe_rotate_open_log 维护。
_ACTIVE_LOG_PATH: Path | None = None
_ACTIVE_STDOUT_TEE: _TeeStream | None = None
_ACTIVE_STDERR_TEE: _TeeStream | None = None
_ACTIVE_LOG_HANDLE: TextIO | None = None
def _configure_file_logging() -> Path | None:
"""
按 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用 worker 文件日志。
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
登录、下载、回调失败与长批次耗时。
Returns:
Path | None: 已启用的日志路径;未配置时返回 None。
"""
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
raw = _env("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE")
if not raw:
return None
path = Path(raw).expanduser()
if not path.is_absolute():
path = (_backend_dir() / path).resolve()
path.parent.mkdir(parents=True, exist_ok=True)
_rotate_log_file_if_needed(path)
log_file = path.open("a", encoding="utf-8", buffering=1)
original_stdout = sys.stdout
original_stderr = sys.stderr
stdout_tee = _TeeStream(original_stdout, log_file)
stderr_tee = _TeeStream(original_stderr, log_file)
sys.stdout = stdout_tee # type: ignore[assignment]
sys.stderr = stderr_tee # type: ignore[assignment]
_ACTIVE_LOG_PATH = path
_ACTIVE_STDOUT_TEE = stdout_tee
_ACTIVE_STDERR_TEE = stderr_tee
_ACTIVE_LOG_HANDLE = log_file
def _close_log() -> None:
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
sys.stdout = original_stdout
sys.stderr = original_stderr
handle = _ACTIVE_LOG_HANDLE or log_file
try:
handle.close()
except Exception:
pass
_ACTIVE_LOG_PATH = None
_ACTIVE_STDOUT_TEE = None
_ACTIVE_STDERR_TEE = None
_ACTIVE_LOG_HANDLE = None
atexit.register(_close_log)
print(f"[logging] tee enabled path={path}")
return path
def _maybe_rotate_open_log() -> None:
"""
常驻 Worker 运行中按大小轮转当前日志。
核心逻辑:Windows 下无法对仍打开的文件 rename,须先关闭句柄 → 调用既有
`_rotate_log_file_if_needed` → 再以追加模式打开新文件并挂回 TeeStream。
未启用文件日志或未超限时 no-op。
"""
global _ACTIVE_LOG_HANDLE
path = _ACTIVE_LOG_PATH
stdout_tee = _ACTIVE_STDOUT_TEE
stderr_tee = _ACTIVE_STDERR_TEE
handle = _ACTIVE_LOG_HANDLE
if path is None or stdout_tee is None or stderr_tee is None or handle is None:
return
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
if max_bytes <= 0:
return
try:
handle.flush()
if path.stat().st_size < max_bytes:
return
except OSError:
return
try:
handle.close()
except Exception:
pass
_ACTIVE_LOG_HANDLE = None
_rotate_log_file_if_needed(path)
new_handle = path.open("a", encoding="utf-8", buffering=1)
stdout_tee.replace_log_file(new_handle)
stderr_tee.replace_log_file(new_handle)
_ACTIVE_LOG_HANDLE = new_handle
print(f"[logging] rotated open log path={path}")
def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int:
"""读取日志相关整数环境变量;非法值回退默认值。"""
try:
value = int(_env(name, str(default)) or str(default))
except ValueError:
return default
return max(value, min_value)
def _rotate_log_file_if_needed(path: Path) -> None:
"""
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
核心逻辑:当 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 已存在且大小达到 `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES`
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT`
的旧文件会被删除。`SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。
"""
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
backup_count = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", 5, min_value=0)
if max_bytes <= 0 or not path.is_file():
return
try:
if path.stat().st_size < max_bytes:
return
except OSError:
return
if backup_count <= 0:
path.unlink(missing_ok=True)
return
oldest = Path(f"{path}.{backup_count}")
oldest.unlink(missing_ok=True)
for index in range(backup_count - 1, 0, -1):
src = Path(f"{path}.{index}")
if src.exists():
src.replace(Path(f"{path}.{index + 1}"))
path.replace(Path(f"{path}.1"))
def _backend_dir() -> Path:
"""
返回仓库内 backend 根目录。
@@ -1550,7 +1344,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip()
task_no = str(body.get("task_no") or "").strip()
sources = body.get("inventory_sources") or []
failed_dir = trigger_path.parent / "failed"
failed_dir = processed_dir.parent / "failed"
# [DEBUG-TIMING] 批处理整体耗时基线:从进入 handler 到回调完成。
batch_started_at = time.monotonic()
print(f"[inventory-batch-timing] handler start run={run_no}")
@@ -1862,7 +1656,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
_handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
return
task_no = str(body.get("task_no") or "").strip()
failed_dir = trigger_path.parent / "failed"
failed_dir = processed_dir.parent / "failed"
if not task_no:
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
trigger_path.unlink(missing_ok=True)
@@ -2598,7 +2392,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
file_path = str(body.get("file_path") or "").strip()
attempt_id = body.get("attempt_id")
callback_id = str(body.get("callback_id") or "").strip()
failed_dir = trigger_path.parent / "failed"
failed_dir = processed_dir.parent / "failed"
if not task_no:
trigger_path.unlink(missing_ok=True)
return
@@ -2686,11 +2480,16 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
for path in sorted(trigger_dir.glob("*.json")):
if not path.is_file():
continue
# 统一四态契约:先原子领取到 processing/ 再处理;被抢走/已消失则跳过,
# 防止 Worker 重启或多实例部署时同一批 trigger 被重复导出、重复回调。
claimed = claim_trigger(path)
if claimed is None:
continue
rpa_heartbeat.set_worker_runtime_status("busy")
try:
handler(path, *extra_args)
handler(claimed, *extra_args)
except Exception as exc:
print(f"[error] {path.name}: {exc}", file=sys.stderr)
print(f"[error] {claimed.name}: {exc}", file=sys.stderr)
finally:
rpa_heartbeat.set_worker_runtime_status("idle")
@@ -2726,14 +2525,14 @@ def _run_periodic_disk_cleanup(
if not force and (now_mono - last_cleanup_mono) < interval:
return last_cleanup_mono
try:
_maybe_rotate_open_log()
maybe_rotate_open_log()
stats = worker_disk_cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger_dir,
upload_trigger_dir=upload_trigger_dir,
drop_dir=drop_dir,
upload_queue_dir=upload_queue_dir,
browser_profile_dir=_browser_profile_root(),
log_file=_ACTIVE_LOG_PATH,
log_file=active_log_path(),
)
print(worker_disk_cleanup.format_cleanup_summary(stats))
except Exception as exc:
@@ -2748,7 +2547,7 @@ def main() -> None:
核心逻辑:主循环扫描库存/上传 trigger;空闲时按间隔清理本机归档与临时文件,
防止长期运行撑爆 RPA 主机盘符。
"""
log_path = _configure_file_logging()
log_path = configure_file_logging()
drop_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR")
inv_trigger_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR")
upload_queue_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR")
+99 -15
View File
@@ -32,6 +32,11 @@ if _RPA_ROOT is not None:
_sys.path.insert(0, _dir)
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
import rpa_heartbeat # noqa: E402
import worker_logging # noqa: E402
import worker_disk_cleanup # noqa: E402
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
import receipt_crane_export # noqa: E402
import receipt_dbs_export # noqa: E402
@@ -41,6 +46,14 @@ def _backend_dir() -> Path:
return _RPA_ROOT.parents[1] / 'backend'
def _mask_secret(value: str | None) -> str:
"""掩码打印密钥:保留前 4 后 4,其余以 .... 代替;缺失或过短返回占位。"""
value = str(value or '').strip()
if len(value) <= 8:
return '***' if value else 'missing'
return f'{value[:4]}....{value[-4:]}'
def _require_dir(variable: str) -> Path:
"""读取 receipt 专用目录;不回退至库存共享路径。"""
value = env(variable)
@@ -149,6 +162,7 @@ def _validate_unit(unit: dict[str, Any]) -> None:
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
print(f'[receipt-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
@@ -164,6 +178,7 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
_validate_unit(item)
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
for (connector, _profile, login_url), group in grouped.items():
print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
mock = env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false').lower() == 'true'
resources = (None, None, None, None)
try:
@@ -187,6 +202,10 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
else:
download = receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0)
output = _save_download(download, drop_dir, unit)
print(
f'[receipt-unit] success source={unit["source_code"]} '
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
)
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', 'file_path': str(output), 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()})
except Exception as exc:
_report_failure(unit, exc)
@@ -200,40 +219,105 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
shutil.rmtree(profile_dir, ignore_errors=True)
def _claim_and_process(path: Path, drop_dir: Path, processed_dir: Path, failed_dir: Path) -> None:
"""原子领取一个 receipt trigger;成功归档 processed,callback 异常归档 failed。"""
claimed_dir = path.parent / 'processing'
claimed_dir.mkdir(parents=True, exist_ok=True)
claimed = claimed_dir / path.name
try:
path.replace(claimed)
except OSError:
def _claim_and_process(path: Path, drop_dir: Path) -> None:
"""原子领取一个 receipt trigger;成功归档 processed,异常归档 failed。
领取与归档统一走 common/trigger_consumer(四态目录契约),
本函数只保留收料批次处理与 SystemExit 兜底。
"""
claimed = claim_trigger(path)
if claimed is None:
return
print(f'[receipt-trigger] claimed {claimed.name}')
# 心跳运行态对齐库存 Worker:领取成功即 busy,处理结束(含归档 failed 后 re-raise)
# 由 finally 恢复 idle,保证 SystemExit 兜底路径也不会让监控长期挂 busy。
rpa_heartbeat.set_worker_runtime_status('busy')
try:
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
processed_dir.mkdir(parents=True, exist_ok=True)
claimed.replace(processed_dir / claimed.name)
archive_trigger(claimed, 'processed')
print(f'[receipt-trigger] archived processed {claimed.name}')
except (Exception, SystemExit):
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
failed_dir.mkdir(parents=True, exist_ok=True)
claimed.replace(failed_dir / claimed.name)
archive_trigger(claimed, 'failed')
print(f'[receipt-trigger] archived failed {claimed.name}')
raise
finally:
rpa_heartbeat.set_worker_runtime_status('idle')
def main() -> None:
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR')
trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR')
poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3'))
processed_dir, failed_dir = trigger_dir / 'processed', trigger_dir / 'failed'
print(f'[freight_receipt_rpa_worker] started trigger_dir={trigger_dir} drop_dir={drop_dir}')
heartbeat_seconds = max(
15,
int(env('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
)
last_cleanup_mono = 0.0
cleanup_interval = cleanup_interval_seconds()
# [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。
print(
'[freight_receipt_rpa_worker] started\n'
f' mock={env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")}\n'
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
f' poll_seconds={poll}\n'
f' heartbeat_seconds={heartbeat_seconds}\n'
f' headless={env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")} '
f'channel={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
f' credential_key={_mask_secret(env("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"))}\n'
f' trigger_dir={trigger_dir}\n'
f' drop_dir={drop_dir}\n'
f' browser_profile_dir={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
f' log={worker_logging.active_log_path() or "stdout-only"}\n'
f' disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}'
)
def _run_cleanup_if_due(now_mono: float, *, force: bool = False) -> float:
"""按间隔执行保留清理;启动时强制一轮。
best-effort 语义:清理失败仅打印告警,不中断主循环;且无论成败都推进
上次清理时钟(返回 now_mono),避免持续性故障在每次 poll 后立刻重试刷屏。
"""
nonlocal last_cleanup_mono
if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
return last_cleanup_mono
profile_root_raw = str(env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
try:
stats = run_worker_disk_cleanup(
inventory_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
drop_dir=drop_dir,
browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
log_file=worker_logging.active_log_path(),
)
print(format_cleanup_summary(stats))
except Exception as exc:
print(f'[receipt-cleanup] failed: {exc}')
return now_mono
# [STEP 2] 启动即清一轮(对齐库存节奏),避免重启前堆积的归档/孤儿 Profile 撑盘。
last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)
# 启动时立即上报一次心跳(对齐库存 Worker),让监控端第一时间出现独立的
# `<hostname>-receipt` 收料 Worker 卡片(WORKER_ID 由 ps1 注入,避免按 pid 抖动)。
rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
)
# 心跳节奏交由独立守护线程承担:收料批量导出会长时间阻塞主循环,
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
rpa_heartbeat.start_heartbeat_loop(
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), interval_seconds=heartbeat_seconds,
)
while True:
for path in sorted(trigger_dir.glob('*.json')):
worker_logging.maybe_rotate_open_log()
try:
_claim_and_process(path, drop_dir, processed_dir, failed_dir)
_claim_and_process(path, drop_dir)
except Exception as exc:
print(f'[receipt-trigger] failed {path.name}: {exc}')
last_cleanup_mono = _run_cleanup_if_due(time.monotonic())
time.sleep(poll)
@@ -42,6 +42,10 @@ $processVars = [ordered]@{
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3'
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot 'logs\worker.log'
# 独立 Worker 身份:监控端按 worker_id 出独立收料卡片,固定后缀避免与库存 Worker/按 pid 的身份抖动。
SHIPPING_NOTICE_RPA_WORKER_ID = "${env:COMPUTERNAME}-receipt"
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = '20'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop'
# 浏览器 Profile 目录复用既有标准变量(与库存 RPA Worker 一致),不另设 RECEIPT_* 冗余变量。