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

@@ -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'