Merge branch 'hugo-auto-transfer' into dev
This commit is contained in:
commit
00c52fdaae
44 files changed
+1487
-524
No files matched your search
@@ -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},
|
||||
],
|
||||
)
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user