Merge branch 'hugo-auto-transfer' into dev

This commit is contained in:
hugo committed 2026-10-26 17:58:09 +08:00
commit 00c52fdaae
44 files changed
+1487 -524

No files matched your search

+2 -2
View File
@@ -43,7 +43,7 @@ def _ok(data, *, status: int = 200):
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET'])
@require_admin
def list_shipping_rpa_profiles():
"""列出脱敏后的 RPA Profile 配置。"""
"""列出 RPA Profile;响应含用户名明文,不含密码与密文。"""
return _ok(freight_rpa_source_admin_service.list_profiles())
@@ -57,7 +57,7 @@ def create_shipping_rpa_profile():
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
@require_admin
def update_shipping_rpa_profile(profile_id: int):
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
"""更新 RPA Profile;用户名与已存明文相同、或密码留空时不重写对应密文。"""
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
+7 -1
View File
@@ -18,7 +18,7 @@ backend/app/api/freight_rpa.py
from __future__ import annotations
from flask import Blueprint, jsonify, request
from flask import Blueprint, current_app, jsonify, request
from app.core.errors import ValidationError
from app.core.tool_auth import require_tool_auth
@@ -65,6 +65,12 @@ def heartbeat():
except ValueError as exc:
raise ValidationError(str(exc))
# 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。
# 到期的 Crane 定时回查跟着心跳落成 trigger;写失败不让心跳本身失败。
try:
from app.services.freight_rpa.upload.crane_recheck import materialize_due_crane_rechecks
materialize_due_crane_rechecks()
except Exception:
current_app.logger.exception('crane recheck materialize failed')
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
@@ -1102,6 +1102,47 @@ def workspace_confirm_shipping_notice_uploaded(business_no: str):
))
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/refresh-crane-upload', methods=['POST'])
def workspace_refresh_crane_upload_status(business_no: str):
"""手动刷新一张仍在分配中的 Crane 发货单。
核心逻辑:校验当前用户可见的通知单,读取最近一次上传尝试,写入一条只查状态的 trigger。
不改 10 分钟定时回查的到期时间,也不重新上传 Excel。
Args:
business_no: 对外发货通知单号,同时是 Crane 的 Pull Request #。
Returns:
JSON: business_no 与 trigger_queued。
Raises:
ValidationError: 没有可刷新的上传尝试或来源连接。
ConflictError: 当前不是分配中,或上一次手动刷新还在排队。
"""
user = _require_user()
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
from app.services.freight_rpa.upload.crane_recheck import request_manual_crane_refresh
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
attempt = latest_upload_attempt(task)
from app.models import ShippingExportArtifact
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) if attempt is not None else None
snapshot = task_rpa_inventory_source(task) or {}
upload_source = get_rpa_trigger_inventory_source(str(snapshot.get('source_code') or '')) if snapshot.get('source_code') else None
if attempt is None or artifact is None or not isinstance(upload_source, dict):
raise ValidationError('Crane upload status cannot be refreshed', code='SHIPPING.UPLOAD_CRANE_ALLOCATING')
trigger_path = request_manual_crane_refresh(
attempt,
upload_source,
task_no=str(task.task_no),
export_file_path=str(artifact.file_path or ''),
)
db.session.commit()
return _ok({'business_no': str(task.business_no), 'trigger_queued': bool(trigger_path)})
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
def workspace_start_shipping_notice_rpa_upload(business_no: str):
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
+3 -5
View File
@@ -69,11 +69,9 @@ class FreightRpaProfile(Base):
login_config_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
)
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
# result_mode / result_selector / success_texts / timeout_seconds。
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
# 连接级“发货 Excel 自动上传”开关。只保存 {enabled}。
# 上传页、文件控件、提交和成功判断在连接器代码里,由 login_url 的主机拼出入口。
# 该配置变更不递增 config_version(见 admin 服务)。
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
@@ -7,6 +7,7 @@ services/admin/freight_rpa_source_admin_service.py
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
onhand_source_repository.validate_source_profile、audit_service。
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
Profile 列表与保存回执返回用户名明文,密码与密文不返回;
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
"""
@@ -15,7 +16,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.core.errors import ConflictError, NotFoundError, ServiceUnavailableError, ValidationError
from app.extensions import db
from app.models import (
FreightRpaOnhandExternalMapping,
@@ -38,7 +39,7 @@ from app.services.admin.freight_rpa_form_utils import (
validate_report_path as _validate_report_path,
)
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
from app.services.shipping_notice.upload_config_validation import validate_upload_config
@@ -77,27 +78,50 @@ def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
def _stored_username(profile: FreightRpaProfile) -> str | None:
"""解密已保存的用户名,供管理端辨认账号。
核心逻辑:用户名是账号标识,库内仍只存密文;解密失败时返回 None,避免坏密文拖垮连接列表。
密码不走本函数。
Args:
profile: 已持久化的货代登录连接。
Returns:
str | None: 用户名明文;未配置或无法解密时为 None。
"""
if not profile.username_ciphertext:
return None
try:
return decrypt_credential(profile.username_ciphertext)
except (ServiceUnavailableError, ValidationError):
return None
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
"""序列化系统连接。用户名明文回传,密码与密文不出现在响应中。"""
return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'connector_type': profile.connector_type, 'login_url': profile.login_url,
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
'upload_config_json': profile.upload_config_json,
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
'config_version': profile.config_version,
'username': _stored_username(profile),
'username_masked': _mask(profile.username_ciphertext),
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
}
def _mask(ciphertext: str | None) -> str | None:
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
"""密码等不可回显凭据只报告是否已配置。"""
return 'configured' if ciphertext else None
def list_profiles() -> list[dict[str, Any]]:
"""列出 Profile 元数据,不返回可恢复的凭据。"""
"""列出 Profile。响应含用户名明文,不含密码与密文。"""
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
@@ -113,7 +137,11 @@ def delete_profile(profile_id: int) -> None:
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
"""创建或更新货代登录连接。
核心逻辑:用户名留空,或与已存明文相同,不重写用户名密文;密码留空则保留既有密码密文。
只有用户名实际变更或提交了新密码时才刷新 credential_updated_at。
"""
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
if profile_id and profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
@@ -138,11 +166,14 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
)
username = _text(data, 'username')
password = _text(data, 'password')
if username is not None:
# [STEP] 管理端回显的用户名会随保存再次提交;与库内明文相同则不轮换 Fernet 密文。
username_changed = False
if username is not None and _stored_username(profile) != username:
profile.username_ciphertext = encrypt_credential(username)
username_changed = True
if password is not None:
profile.password_ciphertext = encrypt_credential(password)
if username is not None or password is not None:
if username_changed or password is not None:
profile.credential_updated_at = datetime.utcnow()
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
if 'upload_config_json' in data:
@@ -3,8 +3,9 @@ services/freight_rpa/common/credential_crypto.py
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
逻辑:管理服务写入 Profile 前调用 encrypt_credential;管理端读取 Profile 时只解密用户名用于展示;
密码仅在 RPA 执行内存中调用 decrypt_credential。密码与密文不得进入 API 响应或日志。
主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
"""
from __future__ import annotations
@@ -48,7 +49,7 @@ def decrypt_credential(ciphertext: str) -> str:
ciphertext: 数据库中保存的 Fernet 密文。
Returns:
str: 仅供 RPA 执行内存使用的明文。
str: 明文。密码只留在 RPA 执行内存;用户名可由管理端 Profile 接口返回。禁止写入日志。
Raises:
ServiceUnavailableError: 未配置或配置了无效的主密钥。
@@ -44,6 +44,7 @@ from app.core.errors import NotFoundError
from app.models import (
FreightRpaInboundReportConfig,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
FreightRpaOnhandReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
@@ -659,6 +660,72 @@ def latest_usable_inbound_file(
return _inbound_file_view(report)
def latest_usable_inbound_files_by_source(
source_ids: list[int],
*,
now: datetime | None = None,
) -> dict[str, InboundFileView]:
"""一次取出这批来源各自最新的可用入站归档(来源状态批量投影用)。
用途:调拨 GET /sources 批量渲染来源卡时按批取文件身份,查询次数不随
来源个数增长;口径与 latest_usable_inbound_file 完全一致(同一
usable_inbound_file_condition 权威),只是按来源主键集合一次取回。
Args:
source_ids: 来源主键集合(FreightRpaInboundUnitRun.source_id)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
source_code → InboundFileView;没有可用文件的来源不出现,每个来源
只留 created_at/id 最新一条。
"""
rows = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
usable_inbound_file_condition(now=now),
)
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
.all()
)
picked: dict[str, InboundFileView] = {}
for report in rows:
view = _inbound_file_view(report)
if view.source_code not in picked:
picked[view.source_code] = view
return picked
def expired_inbound_source_codes(
source_ids: list[int],
*,
now: datetime | None = None,
) -> set[str]:
"""一次找出仍有失效未清理入站归档的来源编码(expired 投影依据,存在性判断)。
用途:调拨来源状态批量投影判断哪些来源因隔日旧文件/保留期已到提示重抓;
口径与 has_expired_inbound_file 同核(expired_inbound_file_condition)。
Args:
source_ids: 来源主键集合。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
至少有一份失效未清理入站归档的 source_code 集合。
"""
rows = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
expired_inbound_file_condition(now=now),
)
.with_entities(FreightRpaInboundUnitRun.source_code)
.distinct()
.all()
)
return {str(row[0]) for row in rows}
def read_inbound_file_bytes(file_id: int) -> bytes:
"""按 file_id 读取入站归档文件的对象字节。
@@ -0,0 +1,234 @@
"""
services/freight_rpa/upload/crane_recheck.py
用途:Crane 发货单进入分配中之后的状态回查。
依赖:ShippingUploadAttempt、freight_rpa.upload.trigger_io、page_contract。
逻辑:自动上传只排一次 10 分钟后的回查;手动刷新另写一条 status_check trigger,
不顺延、不取消那一次定时。两条回查都只让 Worker 重新登录并按 Pull Request # 看行。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import ConflictError, ValidationError
from app.extensions import db
from app.models import ShippingExportArtifact, ShippingNotice, ShippingUploadAttempt
from app.services.freight_rpa.upload.page_contract import crane_recheck_due_at
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
CRANE_ALLOCATING_CODE = 'CRANE_ALLOCATING'
def is_crane_allocating(attempt: ShippingUploadAttempt | None) -> bool:
"""当前尝试是否停在 Crane 已接收、尚未分配完成。"""
return (
attempt is not None
and attempt.status == 'running'
and attempt.error_code == CRANE_ALLOCATING_CODE
)
def _evidence(attempt: ShippingUploadAttempt) -> dict[str, Any]:
raw = attempt.success_evidence_json
return dict(raw) if isinstance(raw, dict) else {}
def _recheck(evidence: dict[str, Any]) -> dict[str, Any]:
raw = evidence.get('crane_recheck')
return dict(raw) if isinstance(raw, dict) else {}
def remember_crane_allocating(
attempt: ShippingUploadAttempt,
artifact: ShippingExportArtifact,
callback_id: str,
*,
now: datetime | None = None,
) -> ShippingUploadAttempt:
"""把尝试标成分配中,并在首次进入时记下唯一一次定时回查。
核心逻辑:due_at 只在还没有时写入。后续回查回调仍是分配中时,不改到期时间,
也不把定时标记成已触发。
Args:
attempt: 本次上传尝试。
artifact: 已提交的发货 Excel。
callback_id: 本次回调幂等键。重复的同一个键直接返回。
now: 测试注入的当前时间。
Returns:
ShippingUploadAttempt: 仍为 running、错误码为 CRANE_ALLOCATING 的尝试。
"""
evidence = _evidence(attempt)
if evidence.get('last_callback_id') == callback_id or attempt.callback_id == callback_id:
return attempt
recheck = _recheck(evidence)
if not recheck.get('due_at'):
pull_request_no = str(artifact.file_name or '').rsplit('.', 1)[0] or str(artifact.file_name or '')
recheck = {
'due_at': crane_recheck_due_at(now).isoformat(timespec='seconds'),
'fired': False,
'pull_request_no': pull_request_no,
}
evidence['crane_recheck'] = recheck
evidence['last_callback_id'] = callback_id
evidence['manual_refresh_inflight'] = False
attempt.success_evidence_json = evidence
attempt.status = 'running'
attempt.error_code = CRANE_ALLOCATING_CODE
attempt.error_message = None
attempt.finished_at = None
if not attempt.callback_id:
attempt.callback_id = callback_id
artifact.status = 'uploading'
db.session.flush()
return attempt
def _write_status_check(
attempt: ShippingUploadAttempt,
upload_source: dict[str, Any],
*,
task_no: str,
export_file_path: str,
pull_request_no: str,
kind: str,
) -> str | None:
"""写入一条只查状态的上传 trigger。文件复制失败时返回 None。"""
# 定时回查的回调键固定,重复心跳不会写成两次有效回调。
# 手动刷新每次使用新键,避免上一次「仍在分配」把这一次回调当成重复而跳过。
callback_id = f'crane-recheck:{attempt.id}:scheduled'
trigger_filename = f'upload_recheck_{task_no}_scheduled.json'
if kind == 'manual':
callback_id = f'crane-recheck:{attempt.id}:manual:{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
trigger_filename = f'upload_recheck_{task_no}_manual.json'
_queue, trigger_path, _callback = write_upload_trigger(
task_no,
export_file_path,
{'mode': 'status_check', 'recheck_kind': kind, 'pull_request_no': pull_request_no},
attempt_id=int(attempt.id),
artifact_id=int(attempt.artifact_id),
connector_type='crane',
upload_config={'enabled': True},
login_url=str(upload_source.get('login_url') or '').strip() or None,
credential_envelope=upload_source.get('credential_envelope') if isinstance(upload_source.get('credential_envelope'), dict) else None,
callback_id=callback_id,
business_no=pull_request_no,
trigger_filename=trigger_filename,
)
return trigger_path
def fire_scheduled_crane_recheck(
attempt: ShippingUploadAttempt,
upload_source: dict[str, Any],
*,
task_no: str,
export_file_path: str,
now: datetime | None = None,
) -> bool:
"""到期后写入唯一一次定时回查。未到期、已触发或不是分配中时不写文件。
Returns:
bool: 本次是否新写了 trigger。
"""
if not is_crane_allocating(attempt):
return False
evidence = _evidence(attempt)
recheck = _recheck(evidence)
if recheck.get('fired') or not recheck.get('due_at'):
return False
due_at = datetime.fromisoformat(str(recheck['due_at']))
if due_at > (now or datetime.utcnow()):
return False
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
trigger_path = _write_status_check(
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
pull_request_no=pull_request_no, kind='scheduled',
)
if not trigger_path:
return False
recheck['fired'] = True
evidence['crane_recheck'] = recheck
attempt.success_evidence_json = evidence
db.session.flush()
return True
def request_manual_crane_refresh(
attempt: ShippingUploadAttempt,
upload_source: dict[str, Any],
*,
task_no: str,
export_file_path: str,
) -> str:
"""手动刷新:立刻写一条状态回查,不改定时回查的到期时间和已触发标记。
Raises:
ConflictError: 当前不是分配中,或上一次手动刷新还没回调。
ValidationError: 共享目录写不出 trigger。
"""
if not is_crane_allocating(attempt):
raise ConflictError(
'Crane upload is not waiting for allocation',
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
)
evidence = _evidence(attempt)
if evidence.get('manual_refresh_inflight'):
raise ConflictError(
'A Crane status refresh is already queued',
code='SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT',
)
recheck = _recheck(evidence)
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
due_at = recheck.get('due_at')
fired = bool(recheck.get('fired'))
trigger_path = _write_status_check(
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
pull_request_no=pull_request_no, kind='manual',
)
if not trigger_path:
raise ValidationError(
'Crane status refresh trigger directory is unavailable',
code='SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE',
)
evidence['manual_refresh_inflight'] = True
evidence['crane_recheck'] = {**recheck, 'due_at': due_at, 'fired': fired, 'pull_request_no': pull_request_no}
attempt.success_evidence_json = evidence
db.session.flush()
return trigger_path
def materialize_due_crane_rechecks(now: datetime | None = None) -> int:
"""心跳时把已到期且尚未触发的 Crane 定时回查写成 trigger。
Returns:
int: 新写入的 trigger 数量。
"""
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
moment = now or datetime.utcnow()
written = 0
attempts = ShippingUploadAttempt.query.filter_by(status='running', error_code=CRANE_ALLOCATING_CODE).all()
for attempt in attempts:
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
notice = db.session.get(ShippingNotice, artifact.task_id) if artifact is not None else None
if artifact is None or notice is None or not artifact.file_path:
continue
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
snapshot = task_rpa_inventory_source(notice) or {}
source_code = str(snapshot.get('source_code') or '').strip()
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
if not isinstance(upload_source, dict) or str(upload_source.get('connector_type') or '').lower() != 'crane':
continue
if fire_scheduled_crane_recheck(
attempt, upload_source, task_no=str(notice.task_no),
export_file_path=str(artifact.file_path), now=moment,
):
written += 1
if written:
db.session.commit()
return written
@@ -0,0 +1,68 @@
"""
services/freight_rpa/upload/page_contract.py
用途:货代发货 Excel 上传的平台页面契约。入口路径、文件控件和成功条件由代码固定。
依赖:标准库 urllib。
逻辑:系统连接只保存是否启用自动上传;Worker 用登录地址的主机拼出上传页。
DBS 上传后当页即可判定;Crane 先进入分配中,10 分钟后再查一次。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from urllib.parse import urlsplit
CRANE_RECHECK_DELAY = timedelta(minutes=10)
DBS_UPLOAD_PATH = '/main/portal/frame/WMSUpload2'
CRANE_UPLOAD_HASH = '/#/shipping-order-upload'
def build_upload_entry_url(connector_type: str, login_url: str) -> str:
"""按平台把登录地址的主机拼成上传页。
核心逻辑:页面路径属于连接器代码。管理端不再保存上传入口 URL。
Args:
connector_type: dbs 或 crane。
login_url: 系统连接上的 HTTPS 登录地址。
Returns:
str: 该平台固定上传页。
Raises:
ValueError: 连接类型或登录地址无法构成上传页。
"""
kind = str(connector_type or '').strip().lower()
parsed = urlsplit(str(login_url or '').strip())
host = parsed.netloc.strip()
if parsed.scheme.lower() != 'https' or not host or not parsed.hostname:
raise ValueError('login_url must be HTTPS with a host')
if kind == 'dbs':
return f'https://{host}{DBS_UPLOAD_PATH}'
if kind == 'crane':
return f'https://{host}{CRANE_UPLOAD_HASH}'
raise ValueError(f'unsupported connector_type: {connector_type or "<empty>"}')
def classify_crane_order_row(order_status: str, order_status_description: str) -> str:
"""判断 Crane 发货单行处于分配中、已分配,还是都不是。
Args:
order_status: Order Status 列文本。
order_status_description: Order Status Description 列文本。
Returns:
str: allocated、allocating 或 other。
"""
status = ' '.join(str(order_status or '').split()).lower()
description = ' '.join(str(order_status_description or '').split()).lower()
if status == 'processing' and description == 'shipping order allocated':
return 'allocated'
if status == 'processing' and description == 'allocating the shipping order':
return 'allocating'
return 'other'
def crane_recheck_due_at(now: datetime | None = None) -> datetime:
"""自动上传进入分配中之后,唯一一次定时回查的到期时间。"""
return (now or datetime.utcnow()) + CRANE_RECHECK_DELAY
@@ -76,6 +76,7 @@ def write_upload_trigger(
credential_envelope: dict[str, Any] | None = None,
callback_id: str | None = None,
business_no: str | None = None,
trigger_filename: str | None = None,
) -> tuple[str | None, str | None, str | None]:
"""
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
@@ -84,7 +85,7 @@ def write_upload_trigger(
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
平台页面动作由 Worker 连接器代码固定;upload_config 只携带是否启用自动上传。
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
Args:
@@ -100,6 +101,7 @@ def write_upload_trigger(
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
trigger_filename: 触发文件名。状态回查使用独立文件名,避免覆盖正在上传的 trigger。
Returns:
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
@@ -113,14 +115,21 @@ def write_upload_trigger(
trigger_dir.mkdir(parents=True, exist_ok=True)
src = Path(export_file_path)
if not src.is_file():
status_check = str((payload or {}).get('mode') or '') == 'status_check'
if not src.is_file() and not status_check:
return None, None, None
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
emit_no = str(business_no or '').strip() or task_no
suffix = str(src.suffix or '.xlsx').lower()
dest = queue / f"{emit_no}{suffix}"
shutil.copy2(src, dest)
if src.is_file():
shutil.copy2(src, dest)
queued_file = str(dest)
elif status_check:
queued_file = ''
else:
return None, None, None
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
body = {
@@ -135,10 +144,10 @@ def write_upload_trigger(
"upload_config_hash": upload_config_hash,
"login_url": login_url,
"credential_envelope": credential_envelope,
"file_path": str(dest),
"file_path": queued_file,
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
trigger_path = trigger_dir / f"upload_{task_no}.json"
trigger_path = trigger_dir / (trigger_filename or f"upload_{task_no}.json")
_write_trigger_json_atomic(trigger_path, body)
return str(dest), str(trigger_path), resolved_callback_id
@@ -4,10 +4,11 @@
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
调拨不维护独立抓取状态表(低耦合)。
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
入站可用条件同口径)。
依赖:freight_rpa.reports.queries(入站可用归档批量/单来源读取、失效来源存在性、
get_outbound_config、解析失败标记只读写入口;入站归档文件模型不直连——
阶段 B Task 4 边界);入站/出站执行单元行与出站归档文件、出站报表配置模型
(出站证据轴 2026-10-22 起直连读取,不在边界禁列);
date_policy.business_date_utc_window(出站文件新鲜度与入站可用条件同口径)。
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
@@ -28,10 +29,9 @@ from typing import Any, Callable
from sqlalchemy import and_, not_, or_
from app.core.errors import ValidationError
from app.models.freight_rpa_inbound_report import (
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
# 入站归档文件模型归 freight_rpa 域读写(阶段 B Task 4 边界),批量/单来源读取
# 一律经 queries 只读函数;入站执行单元模型不在禁列(状态投影按 status 消费)。
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun
from app.models.freight_rpa_outbound_report import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
@@ -39,12 +39,12 @@ from app.models.freight_rpa_outbound_report import (
)
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure as _clear_parse_failure_by_id,
expired_inbound_file_condition,
expired_inbound_source_codes,
get_outbound_config,
has_expired_inbound_file,
latest_usable_inbound_file,
latest_usable_inbound_files_by_source,
mark_inbound_parse_failure as _mark_parse_failure_by_id,
usable_inbound_file_condition,
)
from app.services.in_transit_transfer.date_policy import business_date_utc_window
@@ -288,13 +288,13 @@ def _project_file_status(
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
"""一次取出这批来源各自最新的可用归档。
"""一次取出这批来源各自最新的可用出站归档(入站批查已下沉 queries 层)。
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
Args:
file_model: 入站或出站归档文件模型。
file_model: 出站归档文件模型。
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
source_ids: 要投影的来源主键。
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
@@ -359,13 +359,13 @@ def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str,
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
"""一次找出仍有失效未清理归档的来源编码。
"""一次找出仍有失效未清理出站归档的来源编码(入站批查已下沉 queries 层)。
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
Args:
file_model: 入站或出站归档文件模型。
file_model: 出站归档文件模型。
unit_model: 对应的执行单元模型。
source_ids: 要投影的来源主键。
filters: 失效文件条件。
@@ -412,19 +412,17 @@ def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict
.all()
)
}
inbound_files = _latest_files_by_source(
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
source_ids,
usable_inbound_file_condition(now=now),
)
inbound_files = {
code: _FileFact(
file_id=view.file_id,
original_filename=view.original_filename,
sha256=view.sha256,
parse_failed_at=view.parse_failed_at,
)
for code, view in latest_usable_inbound_files_by_source(source_ids, now=now).items()
}
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
inbound_expired = _expired_source_codes(
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
source_ids,
expired_inbound_file_condition(now=now),
)
inbound_expired = expired_inbound_source_codes(source_ids, now=now)
outbound_files = _latest_files_by_source(
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
@@ -2,18 +2,24 @@
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
排程「启用通知」通用企微通知,本任务不自建领域通知。
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
依赖:auto_transfer、recovery_service、transfer deps、job_registry.ScheduleExecuteResult、
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
transfer_type_config_service.get_enabled(缺省类型口径)、
date_policy(业务日与日期解析)。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
不依赖其他排程成功;来源留空兜底为全部启用入站来源;【调拨类型 2026-10-23】
job_params.transfer_types 为 multi_select,留空=全部启用中的类型配置,
按类型逐轮 run_auto_transfer(恢复复核与类型无关,循环外只跑一次);
类型配置为空/读取失败 fail-closed 硬失败,不静默跳过;可选异动日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无
run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有
Run 或硬失败交由框架完成卡按排程「启用通知」发送。
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(全部
类型均无 run_no 且无 errors)置 domain_notification_managed 保持静默
(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
返回:七元组位序=(total, success, failed, skipped, details, errors, step_logs),
warnings 无对应槽位——恢复/来源汇总写 step_logs(dict),不得挤占 errors 位。
"""
from __future__ import annotations
@@ -21,11 +27,13 @@ from __future__ import annotations
from datetime import timedelta
from typing import Any
from app.core.errors import AppError
from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
from app.services.schedule.job_registry import ScheduleExecuteResult
@@ -52,6 +60,33 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
return codes
def _wanted_transfer_types(params: dict[str, Any], errors: list[str]) -> list[str]:
"""提取结构化 transfer_types;留空回落为全部启用中的类型配置(fail-closed)。
Args:
params: 排程结构化参数(job_params.transfer_types 可为列表/字符串/缺省)。
errors: 错误累积列表(类型配置读取失败/为空时写入,由调用方硬失败)。
Returns:
去空白后的类型编码列表;配置为空或脏配置读取失败时为空列表(已落错误)。
"""
values = params.get("transfer_types") or []
if isinstance(values, str):
values = [values]
codes = [str(item).strip() for item in values if str(item).strip()]
if codes:
return codes
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
try:
codes = [dto.code for dto in get_enabled()]
except AppError as exc:
errors.append(f"调拨类型配置读取失败: {exc}")
return []
if not codes:
errors.append("无启用中的调拨类型配置(须先在管理端调拨类型页创建并启用)")
return codes
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
@@ -77,12 +112,14 @@ def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: li
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
"""自动调拨:恢复(一次)→ 按类型逐轮「匹配(严格相等)+ 执行」;通知走排程「启用通知」。
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
核心逻辑:不自建领域汇总通知(收件人取排程表单底部「启用通知」配置);
仅在空数据日(全部类型均无 run_no 且无 errors)置 domain_notification_managed
抑制框架完成卡(C5 空数据日静默);有 run_no 或硬失败时框架卡照常发送/兜底。
调拨类型留空=全部启用类型逐轮执行(D8:类型=平台配置,排程不隐式假设单一
类型;配置为空/读取失败 fail-closed 硬失败);历史恢复与类型无关,循环外
只跑一次(重复恢复会对同一批行重复建 Attempt 并重复外部查询)。
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
@@ -90,7 +127,7 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
Args:
task: 排程任务(job_params: source_codes/recover_history/
task: 排程任务(job_params: transfer_types/source_codes/recover_history/
receipt_from_offset_days/receipt_to_offset_days)。
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
Returns:
@@ -101,60 +138,99 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
recover_history = bool(params.get("recover_history", True))
business_date = str(business_date_now())
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
# 防止坏参数被静默忽略后退化成全量积压处理。
param_errors: list[str] = []
# [STEP 1] 配置解析与 T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
# 防止坏参数被静默忽略后退化成全量积压处理。硬失败以 failed_count=1 落终态
# failed(total=0 且 errors 非空会被框架判 success「无待处理数据」,不可用)。
errors: list[str] = []
transfer_types = _wanted_transfer_types(params, errors)
movement_date_from = _offset_to_date(
business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors)
business_date, params.get("receipt_from_offset_days"), "异动日期起点", errors)
movement_date_to = _offset_to_date(
business_date, params.get("receipt_to_offset_days"), "异动日期终点", param_errors)
if param_errors:
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
business_date, params.get("receipt_to_offset_days"), "异动日期终点", errors)
if errors:
return (1, 0, 1, 0, [], errors, [
{"step": "config", "status": "failed", "detail": f"sources={len(source_codes)}"},
])
deps = transfer_deps.get_transfer_dependencies()
# [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数
# job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时
# 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出),
# 不回落固定类型(类型=平台配置,排程不隐式假设)。
transfer_type = str(params.get("transfer_type") or "").strip() or None
outcome = run_auto_transfer(
business_date=business_date,
deps=deps,
source_codes=source_codes,
recover_history=recover_history,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=transfer_type,
)
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
if not outcome.run_no and not outcome.errors:
# [STEP 2] 恢复复核只跑一次:扫全部 blocked_recoverable 行(与类型无关),
# result_unknown / manually_closed 在服务内只读隔离/永久排除。恢复失败计一个
# failed 单元——否则「恢复失败+各类型均空数据日」total=0 会被框架判 success。
recovery = RecoveryOutcome()
recovery_failed = False
if recover_history:
try:
recovery = run_daily_recovery(business_date=business_date, deps=deps)
except Exception as exc: # noqa: BLE001
recovery_failed = True
errors.append(f"recovery_failed: {exc}")
step_logs: list[dict[str, Any]] = [{
"step": "recovery",
"status": "failed" if recovery_failed else ("success" if recover_history else "skipped"),
"detail": {
"recovered": recovery.recovered_count,
"still_blocked": recovery.still_blocked_count,
"skipped_result_unknown": recovery.skipped_result_unknown,
"skipped_manually_closed": recovery.skipped_manually_closed,
},
}]
failed_units = 1 if recovery_failed else 0
# [STEP 3] 按类型逐轮自动调拨:单类型失败不阻断其余类型(run_auto_transfer
# 内部捕获进 outcome.errors)。
results: list[dict[str, Any]] = []
success_runs = 0
failed_runs = 0
for code in transfer_types:
outcome = run_auto_transfer(
business_date=business_date,
deps=deps,
source_codes=source_codes,
recover_history=False,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=code,
)
errors.extend(outcome.errors)
if outcome.run_no:
results.append({
"transfer_type": code,
"run_no": outcome.run_no,
"status": outcome.run_status,
})
if outcome.run_status in {"success", "partial_failed"}:
success_runs += 1
else:
failed_runs += 1
elif outcome.errors:
failed_runs += 1
# [STEP 4] 空数据日静默门禁:全部类型均无 run 且无错误(C5)时置标记抑制
# 框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
if not results and not errors:
run.response_summary_json = {
**(run.response_summary_json or {}),
"domain_notification_managed": True,
}
results: list[dict[str, Any]] = []
errors: list[str] = list(outcome.errors)
recovery = outcome.recovery
warnings: list[str] = [
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
]
if outcome.run_no:
results.append({
"run_no": outcome.run_no,
"status": outcome.run_status,
step_logs.append({
"step": "auto_transfer", "status": "skipped",
"detail": "no executable items; execution and notification skipped",
})
elif not outcome.errors:
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
warnings.append("no executable items; execution and notification skipped")
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
summary_text = (
f"sources={len(source_codes)} types={len(transfer_types)} "
f"runs={len(results)} recovered={recovery.recovered_count} "
f"still_blocked={recovery.still_blocked_count}"
)
return (
success + recovery.recovered_count,
success,
recovery.still_blocked_count,
success_runs + failed_runs + recovery.recovered_count + failed_units,
success_runs,
failed_runs + failed_units + recovery.still_blocked_count,
0,
results,
warnings,
errors,
step_logs + [
{"step": "summary", "status": "failed" if errors else "success", "detail": summary_text},
],
)
+17 -1
View File
@@ -5,7 +5,8 @@ backend/app/services/schedule/job_options.py
依赖:models.Agent、shipping_notice.onhand_source_repository。
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources;
在途调拨注册键为 transfer_types(启用中的调拨类型配置)。
"""
from __future__ import annotations
@@ -78,6 +79,20 @@ def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]:
} for source, _config in rows]
def _transfer_types_options() -> list[dict[str, Any]]:
"""启用中的调拨类型(value=类型编码;供在途自动调拨排程选类型,留空=全部)。"""
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
return [
{
"label": (dto.names or {}).get("zh-CN") or dto.code,
"value": dto.code,
"description": dto.description or None,
}
for dto in get_enabled()
]
def _hxops_users_options() -> list[dict[str, Any]]:
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
from app.models import User
@@ -118,6 +133,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
"freight_rpa_sources": _freight_rpa_sources_options,
"freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options,
"freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options,
"transfer_types": _transfer_types_options,
"hxops_users": _hxops_users_options,
"users": _users_options,
}
+12 -1
View File
@@ -606,10 +606,21 @@ def _register_builtin_platform_jobs() -> None:
handler=run_in_transit_transfer_schedule,
description=(
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
"缺收料文件时自动触发收料 RPA。调拨类型留空=全部启用类型逐轮执行。"
"执行时间建议配置在期望调拨时点之前。"
),
category="platform",
params_schema=(
{
"key": "transfer_types",
"type": "multi_select",
"label": "调拨类型",
"label_key": "admin.schedule.form.transferTypeCodes",
"required": False,
"default": [],
"options_source": "transfer_types",
"help": "留空=全部启用中的调拨类型;按类型逐轮匹配并执行,恢复复核只跑一次。",
},
{
"key": "source_codes",
"type": "multi_select",
@@ -2520,7 +2520,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
raw_result = str(payload.get('result') or '').strip().lower()
if raw_result in {'success', 'failed', 'unknown'}:
if raw_result in {'success', 'failed', 'unknown', 'allocating'}:
result_status = raw_result
else:
result_status = 'success' if success else 'failed'
@@ -2614,6 +2614,25 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
)
if completed.status == 'running' and completed.error_code == 'CRANE_ALLOCATING':
set_task_step_progress(
task,
stage="freight_uploading",
step_title="上传货代",
status="running",
message='货代已接收文件,正在分配,稍后自动回查一次',
progress_percent=90,
detail='Processing + Allocating the Shipping Order',
)
log_task_event(task, 'upload_rpa_allocating', {'artifact_id': completed.artifact_id, 'attempt_id': completed.id})
db.session.commit()
return tool_response(
status='running',
task=task,
message='货代已接收文件,正在分配',
data=serialize_task_for_tool(task),
)
if completed.status == 'unknown':
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
set_task_step_progress(
@@ -1951,16 +1951,19 @@ def list_freight_notice_groups_for_task(
.first()
)
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
projected_upload_status = project_notice_upload_status(notice)
hide_allocating_error = projected_upload_status == 'allocating'
items.append({
'business_no': business_no,
'po_number': po_number,
# Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。
'upload_status': project_notice_upload_status(notice),
'upload_status': projected_upload_status,
'upload_mode': upload_mode,
'upload_attempt': upload_attempt,
'upload_error_code': getattr(latest_attempt, 'error_code', None),
'upload_error_code': None if hide_allocating_error else getattr(latest_attempt, 'error_code', None),
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None,
# 分配中的内部错误码不是失败原因,不能把这一行显示成需人工。
'upload_error_message': None if hide_allocating_error else ((getattr(latest_attempt, 'error_message', None) or '')[:500] or None),
'export_file_name': getattr(artifact, 'file_name', None),
'available_actions': available_actions,
'lines': _notice_line_summary_for_task(notice),
@@ -75,6 +75,14 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
return existing
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
allocating = ShippingUploadAttempt.query.filter_by(
artifact_id=artifact.id, status='running', error_code='CRANE_ALLOCATING',
).first()
if allocating is not None:
raise ConflictError(
'Crane has accepted the file and is still allocating; refresh status instead of uploading again',
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
)
# 业务决定:结果未知(timed_out/unknown)不再阻断重新下发 RPA。该状态表示“无法判断上传是否成功/失败”,
# 为避免用户卡死、无法继续尝试,允许再次触发;若上次实际上传成功,重复触发可能产生重复单,
# 需由用户在 CRANE 侧核查(错误文案已提示)。幂等 key 去重仍保留。
@@ -123,7 +131,7 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
task: 正式 Notice,或可解析到 Notice 的 OT。
Returns:
uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。
uploaded | allocating | uploading | pending | failed | unknown | 其它透传小写 | None。
"""
attempt = latest_upload_attempt(task)
if attempt is not None:
@@ -131,6 +139,8 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
# Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。
if status == 'succeeded':
return 'uploaded'
if status == 'running' and str(getattr(attempt, 'error_code', None) or '') == 'CRANE_ALLOCATING':
return 'allocating'
if status in _UPLOAD_IN_FLIGHT_TOKENS:
return 'uploading'
if status == 'pending':
@@ -221,9 +231,9 @@ def _normalize_callback_result(result: str | None, success: bool) -> str:
"""
if result is not None:
normalized = str(result or '').strip().lower()
if normalized not in {'success', 'failed', 'unknown'}:
if normalized not in {'success', 'failed', 'unknown', 'allocating'}:
raise ValidationError(
'result must be success, failed or unknown',
'result must be success, failed, unknown or allocating',
code='SHIPPING.UPLOAD_RESULT_INVALID',
)
return normalized
@@ -243,7 +253,7 @@ def complete_attempt(
callback_id: 回调幂等键(唯一)。
freight_ref_no: 成功时货代回执号。
error_message: 失败/未知时的脱敏错误信息。
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
result: success / failed / unknown / allocating。allocating 表示 Crane 已接收且仍在分配。
Returns:
ShippingUploadAttempt: 已更新状态的 Attob。
@@ -266,10 +276,16 @@ def complete_attempt(
if artifact.status in {'superseded', 'invalidated'}:
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
if str(result or '').strip().lower() == 'allocating':
return attempt
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
result_status = _normalize_callback_result(result, success)
if result_status == 'allocating':
from app.services.freight_rpa.upload.crane_recheck import remember_crane_allocating
return remember_crane_allocating(attempt, artifact, callback)
attempt.callback_id = callback
attempt.finished_at = datetime.utcnow()
task = db.session.get(ShippingNotice, artifact.task_id)
@@ -1,11 +1,10 @@
"""
services/shipping_notice/upload_config_validation.py
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
用途:系统连接只保存「是否启用发货 Excel 自动上传」。
依赖:app.core.errors.ValidationError;标准库 hashlib/json。
逻辑:页面路径、选择器和成功文案由连接器代码固定,管理端提交的这些字段一律丢弃。
upload_config 快照只保留 enabled,供本次上传审计。
"""
from __future__ import annotations
@@ -16,192 +15,34 @@ from typing import Any
from app.core.errors import ValidationError
# 连接类型与各平台已审核域名(主机名白名单,后缀匹配以覆盖同域子站)。
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
ALLOWED_PLATFORM_DOMAINS: dict[str, tuple[str, ...]] = {
'dbs': ('dbschenker.com',),
'crane': ('craneww.com',),
}
ALLOWED_SUBMIT_MODES = frozenset({'auto_after_file', 'click_submit'})
ALLOWED_RESULT_MODES = frozenset({'page_notice', 'history_record'})
# 字段白名单:禁止把额外键(模板、Cookie、脚本)混入配置。
ALLOWED_KEYS = frozenset({
'enabled', 'entry_url', 'file_input_selector',
'submit_mode', 'submit_selector',
'result_mode', 'result_selector', 'success_texts', 'timeout_seconds',
})
MAX_ENTRY_URL_LENGTH = 500
MAX_SELECTOR_LENGTH = 200
MAX_SUCCESS_TEXTS = 10
MAX_SUCCESS_TEXT_LENGTH = 200
MIN_TIMEOUT_SECONDS = 1
MAX_TIMEOUT_SECONDS = 600
DEFAULT_TIMEOUT_SECONDS = 120
# 复用的字符黑名单:任何脚本/表达式/注入语义都拒绝。
_BLOCKED_SELECTOR_MARKERS = (
'javascript:', '<script', 'expression(', 'onclick=', 'onload=', 'onerror=',
'onmouseover=', 'onmouseout=', 'onfocus=', 'onblur=', 'onchange=', 'oninput=',
)
_BLOCKED_SELECTOR_CHARS = ('(', ')', '{', '}', ';', '<', '>', '`', '\\', '\n', '\r')
def _reject(message: str, *, field: str) -> None:
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
def _normalize_text(value: Any) -> str:
return str(value or '').strip()
def _validate_entry_url(connector_type: str, value: Any, *, required: bool = True) -> str | None:
"""校验上传入口为 HTTPS 且主机名属于已审核平台域名。"""
url = _normalize_text(value)
if not url:
if required:
_reject('entry_url is required', field='entry_url')
return None
if len(url) > MAX_ENTRY_URL_LENGTH:
_reject('entry_url is too long', field='entry_url')
if not url.lower().startswith('https://'):
_reject('entry_url must be HTTPS', field='entry_url')
# 简单主机名解析:仅定位 host:port 部分,禁止 userinfo/query 进入主机判断。
scheme_rest = url[8:]
authority = scheme_rest.split('/', 1)[0].split('?', 1)[0].split('#', 1)[0]
host = authority.split('@')[-1].split(':')[0].strip().lower()
if not host:
_reject('entry_url host is invalid', field='entry_url')
allowed = ALLOWED_PLATFORM_DOMAINS.get(connector_type, ())
if not any(host == domain or host.endswith('.' + domain) for domain in allowed):
_reject(
f'entry_url host not allowed for {connector_type}',
field='entry_url',
)
return url
def _validate_css_selector(value: Any, *, field: str, required: bool) -> str | None:
"""校验普通 CSS selector:限制长度、拒绝脚本及表达式语义。"""
selector = _normalize_text(value)
if not selector:
if required:
_reject(f'{field} is required', field=field)
return None
if len(selector) > MAX_SELECTOR_LENGTH:
_reject(f'{field} is too long', field=field)
lowered = selector.lower()
for marker in _BLOCKED_SELECTOR_MARKERS:
if marker in lowered:
_reject(f'{field} contains script semantics', field=field)
for char in _BLOCKED_SELECTOR_CHARS:
if char in selector:
_reject(f'{field} contains an invalid character', field=field)
return selector
def _validate_success_texts(value: Any) -> list[str]:
if value in (None, ''):
return []
if not isinstance(value, list):
_reject('success_texts must be a list', field='success_texts')
if len(value) > MAX_SUCCESS_TEXTS:
_reject('success_texts is too long', field='success_texts')
result: list[str] = []
for item in value:
text = _normalize_text(item)
if not text or len(text) > MAX_SUCCESS_TEXT_LENGTH:
_reject('success_texts contains an invalid item', field='success_texts')
if text not in result:
result.append(text)
return result
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
"""白名单校验连接级上传配置,返回规范化 JSON;raw 为空/None 表示未配置(返回 None)。
"""只保留 enabled。页面参数即使随旧表单提交也不落库。
Args:
connector_type: 连接类型,仅允许 dbs / crane。
raw: 管理端提交的原始上传配置对象。
raw: 管理端提交的上传配置。None 或空串表示未配置。
Returns:
dict | None: 规范化受限 JSON;未配置时返回 None。
dict | None: ``{"enabled": bool}``;未配置时返回 None。
Raises:
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
enabled=true 但缺少上传或结果判定所需字段。
ValidationError: 连接类型非法或上传配置不是对象。
"""
normalized_connector = _normalize_text(connector_type).lower()
normalized_connector = str(connector_type or '').strip().lower()
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
_reject('connector_type must be dbs or crane', field='connector_type')
if raw in (None, ''):
return None
if not isinstance(raw, dict):
_reject('upload_config must be an object', field='upload_config_json')
unknown = set(raw) - ALLOWED_KEYS
if unknown:
_reject(f'upload_config contains unsupported fields: {sorted(unknown)}', field='upload_config_json')
enabled = raw.get('enabled') is True
config: dict[str, Any] = {
'enabled': enabled,
'entry_url': _validate_entry_url(normalized_connector, raw.get('entry_url'), required=enabled),
'file_input_selector': _validate_css_selector(
raw.get('file_input_selector'), field='file_input_selector', required=enabled,
),
'submit_mode': _normalize_text(raw.get('submit_mode')),
'submit_selector': _validate_css_selector(
raw.get('submit_selector'), field='submit_selector', required=False,
),
'result_mode': _normalize_text(raw.get('result_mode')),
'result_selector': _validate_css_selector(
raw.get('result_selector'), field='result_selector', required=False,
),
'success_texts': _validate_success_texts(raw.get('success_texts')),
'timeout_seconds': raw.get('timeout_seconds', DEFAULT_TIMEOUT_SECONDS),
}
if config['submit_mode'] not in ALLOWED_SUBMIT_MODES:
_reject('submit_mode must be auto_after_file or click_submit', field='submit_mode')
if config['result_mode'] not in ALLOWED_RESULT_MODES:
_reject('result_mode must be page_notice or history_record', field='result_mode')
if config['submit_mode'] == 'auto_after_file':
# auto_after_file 由页面在选文件后自动提交,不应同时配置提交按钮选择器。
config['submit_selector'] = None
try:
timeout = int(config['timeout_seconds'])
except (TypeError, ValueError):
_reject('timeout_seconds must be an integer', field='timeout_seconds')
if timeout < MIN_TIMEOUT_SECONDS or timeout > MAX_TIMEOUT_SECONDS:
_reject(
f'timeout_seconds must be within [{MIN_TIMEOUT_SECONDS}, {MAX_TIMEOUT_SECONDS}]',
field='timeout_seconds',
)
config['timeout_seconds'] = timeout
if enabled:
# 完成一次上传所需的公共字段由上述必填校验覆盖;此处补齐连接差异。
if not config['file_input_selector']:
_reject('enabled upload requires file_input_selector', field='file_input_selector')
if config['submit_mode'] == 'click_submit' and not config['submit_selector']:
_reject('enabled click_submit upload requires submit_selector', field='submit_selector')
# 结果判定:dbs(DSV) 使用代码内置的受控成功流(History 绿状态/页面证据),
# 不强制 admin 填写结果字段;crane 必须由 admin 补全提交/结果判定字段后才可启用。
if normalized_connector == 'crane':
if config['result_mode'] == 'page_notice':
if not config['result_selector'] or not config['success_texts']:
_reject(
'enabled crane page_notice upload requires result_selector and success_texts',
field='result_selector',
)
elif config['result_mode'] == 'history_record' and not config['result_selector']:
_reject('enabled crane history_record upload requires result_selector', field='result_selector')
# 未启用时仍保存规范化的受限 JSON,方便 admin 预填后续补全。
return config
return {'enabled': raw.get('enabled') is True}
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
@@ -3,7 +3,7 @@ tests/services/admin/test_shipping_inventory_service.py
用途:验证库存主数据管理服务的安全性和关键业务约束。
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
逻辑:管理后台写配置前锁定用户名可回显、密码与密文不回传、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
"""
from __future__ import annotations
@@ -22,6 +22,7 @@ from app.models import (
FreightRpaSource,
FreightRpaSourceParsingBindingAudit,
FreightRpaOnhandStructureAnalysis,
FreightRpaProfile,
)
@@ -160,15 +161,50 @@ def _published_route_field_id() -> str:
)
def test_profile_credentials_are_not_returned(app):
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
def test_profile_returns_username_and_keeps_password_secret(app):
"""Profile 回执返回用户名明文,密码与密文不得出现。相同用户名再次保存不轮换密文。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
# 用户名是账号标识,管理端需要明文辨认;密码只报告已配置。
assert payload['username'] == 'test-user'
assert payload['password_configured'] is True
assert payload['username_masked'] == 'configured'
assert 'password' not in payload
assert 'ciphertext' not in payload
stored = db.session.get(FreightRpaProfile, payload['id'])
original_username = stored.username_ciphertext
original_password = stored.password_ciphertext
original_updated_at = stored.credential_updated_at
unchanged = _profile_data()
unchanged.pop('password')
unchanged['display_name'] = 'DBS EU renamed'
again = freight_rpa_source_admin_service.save_profile(unchanged, actor_id=None, profile_id=payload['id'])
# 回显后的原用户名随表单提交时,不得重加密或刷新凭据时间。
assert again['username'] == 'test-user'
db.session.refresh(stored)
assert stored.username_ciphertext == original_username
assert stored.password_ciphertext == original_password
assert stored.credential_updated_at == original_updated_at
assert stored.display_name == 'DBS EU renamed'
def test_profile_username_change_reencrypts_without_touching_password(app):
"""只改用户名时重写用户名密文,密码密文保持不变。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
stored = db.session.get(FreightRpaProfile, payload['id'])
original_username = stored.username_ciphertext
original_password = stored.password_ciphertext
changed = _profile_data()
changed.pop('password')
changed['username'] = 'other-user'
updated = freight_rpa_source_admin_service.save_profile(changed, actor_id=None, profile_id=payload['id'])
assert updated['username'] == 'other-user'
db.session.refresh(stored)
assert stored.username_ciphertext != original_username
assert stored.password_ciphertext == original_password
def test_profile_rejects_page_operation_configuration(app):
@@ -620,29 +656,23 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
base_version = profile['config_version']
upload_cfg = {
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
'enabled': True, 'entry_url': 'https://evil.example/steal',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file',
}
updated = freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
)
assert updated['config_version'] == base_version
assert updated['upload_config_json']['enabled'] is True
assert updated['upload_config_json'] == {'enabled': True}
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
bumped = freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
actor_id=None, profile_id=profile['id'],
)
assert bumped['config_version'] == base_version + 1
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
# 上传配置必须是对象;页面字段不再作为校验对象。
with pytest.raises(ValidationError):
freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
actor_id=None, profile_id=profile['id'],
)
with pytest.raises(ValidationError):
freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
{**_profile_data(), 'upload_config_json': 'not-an-object'},
actor_id=None, profile_id=profile['id'],
)
@@ -0,0 +1,100 @@
"""
backend/tests/services/freight_rpa/test_crane_upload_recheck.py
用途:验证上传配置只保留开关,以及 Crane 分配中只排一次定时回查。
依赖:page_contract、upload_attempt_service、crane_recheck、Flask 测试库。
逻辑:先断言入口 URL 和行分类,再走 complete_attempt、定时回查和手动刷新。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app import db
from app.core.errors import ConflictError
from app.services.freight_rpa.upload.crane_recheck import (
fire_scheduled_crane_recheck,
request_manual_crane_refresh,
)
from app.services.freight_rpa.upload.page_contract import (
build_upload_entry_url,
classify_crane_order_row,
)
from app.services.shipping_notice.upload_attempt_service import (
complete_attempt,
project_notice_upload_status,
start_rpa_attempt,
)
from tests.test_shipping_upload_attempt import _ready_artifact
def test_upload_entry_url_comes_from_login_host_and_crane_row_is_classified():
"""DBS/Crane 上传页由登录主机拼接;只有两句固定文案分别表示已分配和分配中。"""
assert build_upload_entry_url('dbs', 'https://s360.dbschenker.com/login') == (
'https://s360.dbschenker.com/main/portal/frame/WMSUpload2'
)
assert build_upload_entry_url('crane', 'https://wms-portal.craneww.com/') == (
'https://wms-portal.craneww.com/#/shipping-order-upload'
)
assert classify_crane_order_row('Processing', 'Shipping Order Allocated') == 'allocated'
assert classify_crane_order_row('Processing', 'Allocating the Shipping Order') == 'allocating'
assert classify_crane_order_row('Completed', 'Shipping Order Allocated') == 'other'
def test_allocating_schedules_one_recheck_and_blocks_another_upload(app):
"""首次分配中写下 10 分钟回查;第二次回调不改到期时间,也不能重新上传。"""
with app.app_context():
notice, artifact, _reservation = _ready_artifact()
artifact.file_name = 'MXI26082801.xlsx'
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key')
started = datetime(2026, 10, 23, 3, 0, 0)
complete_attempt(attempt, success=False, callback_id='upload-1', result='allocating')
# remember 使用 utcnow;这里只断言间隔为 10 分钟,不绑定测试开始时刻。
due_at = datetime.fromisoformat(attempt.success_evidence_json['crane_recheck']['due_at'])
assert timedelta(minutes=9) < due_at - datetime.utcnow() <= timedelta(minutes=10)
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
assert project_notice_upload_status(notice) == 'allocating'
complete_attempt(attempt, success=False, callback_id='recheck-1', result='allocating')
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at.isoformat(timespec='seconds')
with pytest.raises(ConflictError) as blocked:
start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key-2')
assert blocked.value.code == 'SHIPPING.UPLOAD_CRANE_ALLOCATING'
assert started < due_at
def test_manual_refresh_does_not_move_the_one_scheduled_recheck(app):
"""手动刷新另写一条状态回查,不改定时到期时间,也不把定时标记成已触发。"""
with app.app_context():
notice, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-manual')
complete_attempt(attempt, success=False, callback_id='upload-manual', result='allocating')
due_at = attempt.success_evidence_json['crane_recheck']['due_at']
source = {'login_url': 'https://wms-portal.craneww.com/', 'connector_type': 'crane'}
first = request_manual_crane_refresh(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
)
assert first.endswith(f'upload_recheck_{notice.task_no}_manual.json')
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
with pytest.raises(ConflictError) as inflight:
request_manual_crane_refresh(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
)
assert inflight.value.code == 'SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT'
future = datetime.fromisoformat(due_at) + timedelta(seconds=1)
assert fire_scheduled_crane_recheck(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
) is True
assert fire_scheduled_crane_recheck(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
) is False
db.session.refresh(attempt)
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
assert attempt.success_evidence_json['crane_recheck']['fired'] is True
@@ -1,16 +1,18 @@
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
用途:验证同步执行组合入口的两道门禁(①存在且可执行 ②文件版本对账,失败路径
均携带 details 列表且外部系统 写入为 0;原「行级新鲜度 TTL」门禁已于
2026-09-25 退役——items_stale 拒绝用例随之删除,TTL 降级为前端展示徽标)、
D1 五元组建单与单据级写语义(一单一次 create_transfer、单内行共享单结果)、
写前路由复查(漂移阻断)、result_unknown 不自动重试、单间失败隔离
(不同组互不影响)、匹配 scope 执行入口(execute_matching_items)与按
外部系统 单号投影。
用途:验证同步执行组合入口的执行存在性门禁(①存在且可执行,失败携带 details
列表且外部系统 写入为 0;原「文件版本对账」门禁已于 2026-10-22 退役——
文件更新/缺失不再拦执行,行装饰 file_current 徽标仅提示,防错下沉 worker
写前库存复查;原「行级新鲜度 TTL」门禁已于 2026-09-25 退役——items_stale
拒绝用例随之删除,TTL 降级为前端展示徽标)、D1 五元组建单与单据级写语义
(一单一次 create_transfer、单内行共享单结果)、写前路由复查(漂移阻断)、
result_unknown 不自动重试、单间失败隔离(不同组互不影响)、匹配 scope
执行入口(execute_matching_items)与按外部系统单号投影。
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
来源文件状态投影经 patch_source_file_status 夹具注入替身(装饰断言另打
matching_service 命名空间)。
"""
from __future__ import annotations
@@ -29,6 +31,7 @@ from app.services.in_transit_transfer.matching_service import (
RouteMapping,
TransferDeps,
create_matching,
list_executable_items,
)
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
@@ -252,35 +255,57 @@ def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_f
assert _execution_runs() == []
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
"""门禁②:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
def test_execute_items_proceeds_when_file_updated_and_decorates_not_current(
transfer_db, dbs_ready_file, patch_source_file_status, monkeypatch,
):
"""[2026-10-22 文件版本对账门禁退役] 文件已更新不再是执行门禁。
入站抓取是部分导出——新文件不含某行 ≠ 该行失效/已处理,按最新文件 sha
对账曾把大量未处理行错误卡死(业务实测 557 行积压)。执行照常写 ERP;
行装饰 file_current=False 仅提示不拦截,防错下沉 worker 写前库存复查。
"""
patch_source_file_status({"DBS-AWSBI": "e" * 64})
# 装饰读取走 matching_service 命名空间的同名投影(退役后该函数仅剩展示
# 消费方),此处同步打桩保持与执行侧替身同源。
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
lambda *, source_code, record_kind="inbound": {
"file_status": "ready", "has_ready_file": True,
"file_no": "REC-TEST", "file_sha256": "e" * 64,
},
)
deps, erp, items = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
# 断言:行当前性徽标如实提示「行评估版本戳 ≠ 最新可用文件」。
listing = list_executable_items(deps=deps)
decorated = {row.item_id: row for row in listing["items"]}
assert all(decorated[item.id].file_current is False for item in items)
with pytest.raises(ValidationError) as excinfo:
execute_items(item_ids=[item.id for item in items], deps=deps)
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
assert erp.write_calls() == []
assert _execution_runs() == []
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
# 断言:徽标不拦截执行——同组两 Invoice 合并一单、一次写调用、行全 success。
assert outcome.status == "success"
assert len(erp.write_calls()) == 1
linked = _load_items(outcome.run_no)
assert all(item.status == "success" for item in linked.values())
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
"""门禁②:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
def test_execute_items_proceeds_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
"""[2026-10-22 门禁退役] 来源无可用文件同样不拦执行。
档是镜像事实,不随当日文件可用性消失(evidence_sync 已落档的行照常可执行)。
"""
patch_source_file_status({"DBS-AWSBI": None})
deps, erp, items = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
with pytest.raises(ValidationError) as excinfo:
execute_items(item_ids=[item.id for item in items], deps=deps)
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
assert erp.write_calls() == []
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
# 断言:无可用文件不拒绝执行——照常组建单并写入外部系统。
assert outcome.status == "success"
assert len(erp.write_calls()) == 1
linked = _load_items(outcome.run_no)
assert all(item.status == "success" for item in linked.values())
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
@@ -3,14 +3,20 @@
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
依赖:schedule.job_registry、job_options、inbound_trigger_service、
transfer_type_config_service、in_transit_transfer_job。
逻辑:只验证注册契约与调用形态(run_auto_transfer/run_daily_recovery 打桩),
真实排程触发由 scheduler 驱动;七元组位序=(total, success, failed,
skipped, results, errors, step_logs),errors 位只放真实错误。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome
from app.services.schedule.job_options import is_known_options_source
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
@@ -22,14 +28,23 @@ def test_receipt_file_job_deregistered():
def test_transfer_job_registered_with_schedule_defaults():
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
"""自动调拨 job 注册且含类型/来源/恢复参数契约;描述不得硬编码时刻。"""
import re
job = get_platform_job("in-transit-transfer")
assert job is not None
assert job.enabled
keys = {field.get("key") for field in job.params_schema}
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
assert {
"transfer_types", "source_codes", "recover_history",
"receipt_from_offset_days", "receipt_to_offset_days",
} <= keys
# 断言:调拨类型=multi_select 动态选项源(启用中的类型配置),留空=全部。
types_field = next(f for f in job.params_schema if f.get("key") == "transfer_types")
assert types_field.get("type") == "multi_select"
assert types_field.get("options_source") == "transfer_types"
assert types_field.get("default") == []
assert is_known_options_source("transfer_types")
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
assert "notify_user_ids" not in keys
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
@@ -133,55 +148,108 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
def test_handler_empty_data_day_stays_silent(monkeypatch):
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
def test_wanted_transfer_types_falls_back_to_all_enabled(monkeypatch):
"""调拨类型留空=全部启用类型;显式选择优先;空配置/脏配置 fail-closed 落错误。"""
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
from app.services.schedule.in_transit_transfer_job import _wanted_transfer_types
errors: list[str] = []
monkeypatch.setattr(type_mod, "get_enabled", lambda: [
SimpleNamespace(code="in_transit_to_hub"), SimpleNamespace(code="hub_repair_out"),
])
assert _wanted_transfer_types({}, errors) == ["in_transit_to_hub", "hub_repair_out"]
assert errors == []
assert _wanted_transfer_types({"transfer_types": ["in_transit_to_hub"]}, errors) == ["in_transit_to_hub"]
assert _wanted_transfer_types({"transfer_types": "hub_to_hub"}, errors) == ["hub_to_hub"]
monkeypatch.setattr(type_mod, "get_enabled", lambda: [])
assert _wanted_transfer_types({}, errors) == []
# 断言:空类型配置不静默——落错误由调用方硬失败(D8 fail-closed)。
assert errors and "调拨类型" in errors[-1]
def test_transfer_types_options_provider_lists_enabled(app, transfer_db):
"""transfer_types 选项源:仅启用类型,label 取 names zh-CN,value=类型编码。"""
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
from app.services.schedule.job_options import list_job_options
seed_transfer_type_config("in_transit_to_hub", enabled=True)
seed_transfer_type_config("hub_repair_out", enabled=False)
transfer_db.session.commit()
options = list_job_options("transfer_types")
codes = {option["value"] for option in options}
# 断言:停用类型不进选项(与排程留空=全部启用类型的口径一致)。
assert "in_transit_to_hub" in codes
assert "hub_repair_out" not in codes
label = next(o["label"] for o in options if o["value"] == "in_transit_to_hub")
assert label == "类型 in_transit_to_hub"
def _patch_schedule_env(monkeypatch, *, types=None, sources=("CRANE_SGP",)):
"""handler 单测公共打桩:来源/类型缺省口径 + 依赖与恢复隔离(不触库)。"""
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
import app.services.schedule.in_transit_transfer_job as job_mod
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: list(sources))
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
monkeypatch.setattr(
type_mod, "get_enabled",
lambda: [SimpleNamespace(code=code) for code in (types if types is not None else ["in_transit_to_hub"])],
)
return job_mod
def test_handler_empty_data_day_stays_silent(monkeypatch):
"""空数据日(全部类型均无 run 且无 errors):置静默标记抑制框架完成卡(C5)。"""
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome()
return AutoTransferOutcome()
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
run = ScheduleRun(run_no="RUNR-1", status="running")
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
total, success, failed, skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
assert "sender" not in captured
assert "recipients" not in captured
# 断言:恢复在循环外只跑一次;run_auto_transfer 恒收 recover_history=False。
assert captured["recover_history"] is False
assert captured["movement_date_from"] is None
assert captured["movement_date_to"] is None
assert captured["source_codes"] == ["CRANE_SGP"]
assert captured["recover_history"] is True
assert captured["transfer_type"] == "in_transit_to_hub"
assert run.response_summary_json["domain_notification_managed"] is True
assert (total, success, failed, skipped) == (0, 0, 0, 0)
assert results == []
assert any("no executable items" in w for w in warnings)
assert results == [] and errors == []
# 断言:恢复汇总与空数据说明落 step_logs(dict),errors 位不受污染。
assert step_logs[0]["step"] == "recovery"
assert any(item.get("step") == "auto_transfer" for item in step_logs)
def test_handler_converts_t_minus_offsets(monkeypatch):
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
from datetime import date
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome()
return AutoTransferOutcome()
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
run = ScheduleRun(run_no="RUNR-4", status="running")
@@ -195,79 +263,227 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
def _must_not_run(**kwargs):
raise AssertionError("run_auto_transfer must not run with invalid offsets")
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
run = ScheduleRun(run_no="RUNR-5", status="running")
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
_total, _success, _failed, _skipped, results, _warnings, errors = (
total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名;
# failed_count=1 使终态为 failed(total=0+errors 会被框架误判 success,禁用)。
assert (total, failed) == (1, 1)
assert results == []
assert any("异动日期起点" in e for e in errors)
assert not (run.response_summary_json or {}).get("domain_notification_managed")
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
_total, _success, _failed, _skipped, _results, _warnings, errors = (
_total, _success, _failed, _skipped, _results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:小数偏移同样快速失败。
assert any("异动日期终点" in e for e in errors)
def test_handler_run_day_uses_framework_notification(monkeypatch):
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
import app.services.schedule.in_transit_transfer_job as job_mod
def test_handler_runs_each_type_once_and_recovery_once(monkeypatch):
"""多类型逐轮执行:每类型一次 run_auto_transfer(recover_history=False),恢复只跑一次。"""
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch, types=["in_transit_to_hub", "hub_repair_out"])
recovery_calls: list[dict] = []
def _fake_recovery(**kwargs):
recovery_calls.append(kwargs)
return RecoveryOutcome(recovered_count=2)
monkeypatch.setattr(job_mod, "run_daily_recovery", _fake_recovery)
calls: list[dict] = []
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
calls.append(kwargs)
return AutoTransferOutcome(run_no=f"TR-{len(calls)}", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={"transfer_types": ["in_transit_to_hub", "hub_repair_out"]})
run = ScheduleRun(run_no="RUNR-6", status="running")
total, success, failed, skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:逐类型各跑一轮且带类型编码;恢复与类型无关只跑一次。
assert [c["transfer_type"] for c in calls] == ["in_transit_to_hub", "hub_repair_out"]
assert all(c["recover_history"] is False for c in calls)
assert len(recovery_calls) == 1
# 断言:total=success+failed+recovered(2 成功 Run + 2 恢复行)。
assert (total, success, failed, skipped) == (4, 2, 0, 0)
assert [r["run_no"] for r in results] == ["TR-1", "TR-2"]
assert errors == []
# 断言:恢复汇总落 step_logs(recovered=2),errors 位只放真实错误。
assert step_logs[0]["step"] == "recovery"
assert step_logs[0]["detail"]["recovered"] == 2
def test_handler_empty_type_config_fails_hard(monkeypatch):
"""类型配置为空:fail-closed 硬失败(failed=1 → 框架 failed 终态),不执行。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch, types=[])
def _must_not_run(**kwargs):
raise AssertionError("run_auto_transfer must not run without transfer types")
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-7", status="running")
total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:空配置硬失败不执行、不静默,错误信息指向类型配置缺失。
assert (total, failed) == (1, 1)
assert results == []
assert any("调拨类型" in e for e in errors)
assert not (run.response_summary_json or {}).get("domain_notification_managed")
def test_handler_run_day_uses_framework_notification(monkeypatch):
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
return AutoTransferOutcome(run_no="TR-1", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-2", status="running")
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
total, success, failed, skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
# 断言:有 run 不抑制框架通知;run_no+类型落入 results 供完成卡/留痕展示。
assert not (run.response_summary_json or {}).get("domain_notification_managed")
assert results and results[0]["run_no"] == "TR-1"
assert results[0]["transfer_type"] == "in_transit_to_hub"
assert (total, success, failed, skipped) == (1, 1, 0, 0)
assert errors == []
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
import app.services.schedule.in_transit_transfer_job as job_mod
def test_handler_recovery_failure_counts_as_failed(monkeypatch):
"""恢复复核抛异常:计一个 failed 单元——防止「恢复失败+空数据日」被框架判 success。"""
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
def _boom(**_kwargs):
raise RuntimeError("stock source offline")
monkeypatch.setattr(job_mod, "run_daily_recovery", _boom)
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
return AutoTransferOutcome() # 各类型均空数据(无 Run 无错误)
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-9", status="running")
total, success, failed, _skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:恢复失败落 errors 且计 failed(终态 failed 交框架失败通知),
# 恢复 step_log 标 failed;不置静默标记。
assert (total, success, failed) == (1, 0, 1)
assert results == []
assert errors == ["recovery_failed: stock source offline"]
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "failed"
assert not (run.response_summary_json or {}).get("domain_notification_managed")
def test_handler_recovery_skipped_marks_step_log(monkeypatch):
"""recover_history=false:恢复不执行,step_log 标 skipped 且不计 failed。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch)
def _must_not_recover(**_kwargs):
raise AssertionError("run_daily_recovery must not run when recover_history is false")
monkeypatch.setattr(job_mod, "run_daily_recovery", _must_not_recover)
monkeypatch.setattr(
job_mod, "run_auto_transfer",
lambda **_kwargs: AutoTransferOutcome(run_no="TR-10", run_status="success"),
)
task = ScheduleTask(job_params={"recover_history": False})
run = ScheduleRun(run_no="RUNR-10", status="running")
total, success, failed, _skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:恢复被跳过(step_log=skipped、无恢复错误),Run 照常产出。
assert (total, success, failed) == (1, 1, 0)
assert results and results[0]["run_no"] == "TR-10"
assert errors == []
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "skipped"
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
return AutoTransferOutcome(errors=["match pipeline boom"])
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-3", status="running")
_total, _success, _failed, _skipped, results, _warnings, errors = (
_total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results,
# 该类型计入 failed_count(终态 failed 交框架失败通知)。
assert not (run.response_summary_json or {}).get("domain_notification_managed")
assert results == []
assert errors == ["match pipeline boom"]
assert failed == 1
def test_handler_type_failure_isolated_per_type(monkeypatch):
"""单类型硬失败不阻断其余类型;失败类型计入 failed,成功类型照常出 Run。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch, types=["bad_type", "in_transit_to_hub"])
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
if kwargs["transfer_type"] == "bad_type":
return AutoTransferOutcome(errors=["type config disabled"])
return AutoTransferOutcome(run_no="TR-9", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-8", status="running")
total, success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:好类型照常执行出 Run;坏类型落 errors 并计入 failed(部分失败终态)。
assert (total, success, failed) == (2, 1, 1)
assert len(results) == 1 and results[0]["transfer_type"] == "in_transit_to_hub"
assert errors == ["type config disabled"]
+1 -1
View File
@@ -1410,7 +1410,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
assert events[0] == ("session", "https://s360.dbschenker.com/")
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
assert ("file", "#file2") in events
assert ("file", "input#file2") in events
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events