feat(freight-rpa): 系统连接只保留上传开关并增加 Crane 一次回查
上传页、按钮和成功判断改由连接器固定。Crane 分配中只排一次 10 分钟状态回查,手动刷新不改到期时间。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
95e7db0831
commit
3bb9938c05
33 files changed
+878
-374
No files matched your search
@@ -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))
|
||||
|
||||
|
||||
|
||||
@@ -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 成功事实仍由受信回调裁决。"""
|
||||
|
||||
@@ -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: 未配置或配置了无效的主密钥。
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -1858,21 +1858,16 @@ GET /api/admin/shipping-order-schema/published-contract
|
||||
|
||||
### 连接级受控上传参数(upload_config_json,连接例外)
|
||||
|
||||
发货 Excel 自动上传的页面参数作为 `ShippingRpaProfile.upload_config_json` 直接挂在既有“系统连接”上,一条连接只保存一份上传配置。**这是连接级受控上传参数的例外**:它只作用于货代上传,不向库存 RPA 或收料 RPA 扩散,也不新建 Upload Profile、关联表、版本表或发布流。
|
||||
发货 Excel 自动上传只在系统连接上保存是否启用。页面路径、按钮和成功判断写在对应货代的连接器里。**这是连接级开关,不是页面参数**:它只作用于货代上传,不向库存 RPA 或收料 RPA 扩散,也不新建 Upload Profile、关联表、版本表或发布流。
|
||||
|
||||
- **配置由管理端表单编辑,后端保存为受限 JSON**。白名单字段仅 `enabled / entry_url / file_input_selector / submit_mode / submit_selector / result_mode / result_selector / success_texts / timeout_seconds`;保存时后端严格校验:
|
||||
- `connector_type` 仍只能是 `dbs / crane`。
|
||||
- `entry_url` 必须 HTTPS,且主机名只允许该连接已审核的平台域名(`dbschenker.com` / `craneww.com` 后缀匹配)。
|
||||
- 三个 selector 只允许普通 CSS selector,限制长度(≤200)并拒绝 `javascript:`、`<script`、`expression(`、`on*=` 及 `() {} ; < >` 等脚本/表达式语义。
|
||||
- `submit_mode` 只允许 `auto_after_file / click_submit`;`result_mode` 只允许 `page_notice / history_record`。
|
||||
- `enabled=true` 时须具备完成一次上传与判定结果所需的全部字段:公共必填 `entry_url / file_input_selector / submit_mode / timeout_seconds`;`click_submit` 须有 `submit_selector`;crane 启用时还须补全 `result_selector` 与成功文本/记录判定字段(DSV 由代码内置的受控成功流判定,不强制管理员填写)。
|
||||
- 禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
|
||||
- **DSV 初始值**:`enabled=true`,`entry_url=https://s360.dbschenker.com/main/portal/frame/WMSUpload2`,`file_input_selector=input#file2`,`submit_mode=auto_after_file`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。
|
||||
- **Crane 初始值**:`enabled=false`(提交按钮、成功提示或上传历史记录的稳定选择器尚未确认,仅有文件选择器不代表可安全自动提交),`entry_url=https://wms-portal.craneww.com/#/shipping-order-upload`,`file_input_selector=input[name="OrderFileUpload"]`,`submit_mode=click_submit`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。管理员完成页面验证并补全提交/成功判定字段后才可 `enabled=true`。
|
||||
- **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期;不维护 `upload_config_version`(无发布流、无并发编辑审批、无历史回放需求)。每个 trigger 固化本次 upload_config 快照即可保证“这次上传用了什么”;需要审计关联时对快照计算 `config_hash`(sha256)。
|
||||
- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter`(DSV 入口、文件选择与结果判定)与 `CraneUploadAdapter`(Crane 入口、文件选择、提交与结果判定),**不再根据环境变量拼接 DSV/Crane 页面动作**。用连接 `login_url` 登录后访问 `upload_config.entry_url` 进入上传页;`upload_config` 决定“该连接使用哪个已支持的受控流程及其页面参数”,浏览器动作与安全边界由代码负责;Worker 上传与最终提交的全局开关(`FREIGHT_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留,但不再承载页面参数。
|
||||
- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以受控页面选择器判定 → 回调。
|
||||
- **结果三态**:`success`(取得可核验成功证据)、`failed`(明确页面失败、浏览器错误、超时或回调失败)、`unknown`(已可能提交但无法确认外部系统结果)。`unknown` 必须转人工处理,禁止自动重试以避免重复上传;成功/失败/未知、页面证据摘要与脱敏错误写入现有 Upload Attempt 与货代审计事件。
|
||||
- **配置只保存是否启用**。`upload_config_json` 落库只保留 `{enabled}`。旧客户端带来的入口 URL、文件选择器、提交方式、结果选择器和成功文本在保存时丢弃,不作为运行参数。`connector_type` 仍只能是 `dbs / crane`。
|
||||
- **页面动作在连接器代码里**。Worker 用连接 `login_url` 的主机拼出上传页:DBS 为 `/main/portal/frame/WMSUpload2`,Crane 为 `/#/shipping-order-upload`。DBS 固定点击 `Process File`,并同时核对成功提示与两个错误面板。Crane 固定使用 `input[name="OrderFileUpload"]`。
|
||||
- **DBS 同步完成**。同一页面即可判定成功或失败,没有状态回查。
|
||||
- **Crane 先进入分配中**。提交后若该行是 `Processing + Allocating the Shipping Order`,尝试保持 `running` 且 `error_code=CRANE_ALLOCATING`,业务状态为 `allocating`(已接收,分配中)。只有 `Processing + Shipping Order Allocated` 才算上传成功。自动上传后只排一次 10 分钟后的 Worker 重新登录回查;手动刷新是另一次立即回查,不改那一次定时的到期时间。两条回查都只按 Pull Request #(Excel 文件名去扩展名)看行,不重新上传。仍在分配中时禁止再次上传同一文件。
|
||||
- **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期。
|
||||
- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter` 与 `CraneUploadAdapter`。Worker 上传与最终提交的全局开关(`FREIGHT_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留。
|
||||
- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及是否启用自动上传 → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger → Windows Worker 按 `connector_type` 登录并打开代码固定的上传页。Crane 分配中的到期回查由 Worker 心跳写成 `mode=status_check` 的 trigger。
|
||||
- **结果**:`success`(取得可核验成功证据)、`failed`(明确页面失败)、`unknown`(无法确认,转人工且禁止自动重试)、`allocating`(Crane 已接收,仍在分配)。分配中的状态回查若暂时看不到行,保持分配中,不改成 unknown。
|
||||
|
||||
发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改;**同一 field_id 的 `field_code` 一经发布不可变更**(改名 = 退役旧字段 + 新建字段,允许同一 `field_code` 漂移到新 `field_id`),历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。
|
||||
|
||||
@@ -2425,7 +2420,7 @@ cd C:\HxopsRpaTest
|
||||
|
||||
默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。
|
||||
|
||||
DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `FREIGHT_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。
|
||||
DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。管理端 Profile 接口回传用户名明文,便于辨认账号;密码与密文不返回,留空保存表示不修改。库内仍只存 Fernet 密文。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `FREIGHT_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。
|
||||
|
||||
手工启动 test:
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
来源站点详情三块折叠——库存报表|入站报表|出站报表;入站/出站走独立 get/save API。
|
||||
复制新增只预填未保存草稿(sourceCloneDraft),保存后新站点保持停用。卡片入口是右上角复制图标,抽屉底栏保留文字按钮。
|
||||
报表规则列表按用途分段(库存→入站→出站),组内按 profile_code / version 排序。
|
||||
系统连接回显用户名明文,密码留空表示不修改。自动上传只保存开关,页面动作在连接器代码里。
|
||||
视觉层已迁移 Element Plus(element-trial 主题),间距由 AdminLayout 壳层持有。
|
||||
-->
|
||||
<template>
|
||||
@@ -143,7 +144,7 @@
|
||||
<label><span>{{ t('admin.freightRpa.connectionName') }}</span><el-input v-model="profile.display_name" required /></label>
|
||||
<label><span>{{ t('admin.freightRpa.connectorType') }}</span><el-select v-model="profile.connector_type"><el-option value="dbs" :label="t('admin.freightRpa.platform.dbs')" /><el-option value="crane" :label="t('admin.freightRpa.platform.crane')" /></el-select></label>
|
||||
<label><span>{{ t('admin.freightRpa.loginUrl') }}</span><el-input v-model="profile.login_url" type="url" required /></label>
|
||||
<label><span>{{ t('admin.freightRpa.username') }}</span><el-input v-model="profile.username" name="shipping-rpa-credential-user" autocomplete="one-time-code" readonly :placeholder="t('admin.freightRpa.writeOnlyHint')" @focus="unlockCredentialField" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.username') }}</span><el-input v-model="profile.username" name="shipping-rpa-username" autocomplete="off" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.password') }}</span><el-input v-model="profile.password" name="shipping-rpa-credential-password" type="password" autocomplete="new-password" readonly :placeholder="t('admin.freightRpa.writeOnlyHint')" @focus="unlockCredentialField" /></label>
|
||||
<div class="switch-field"><span>{{ t('admin.freightRpa.enabled') }}</span><div class="switch-control"><el-switch v-model="profile.enabled" /><b>{{ profile.enabled ? t('admin.freightRpa.enabledState') : t('admin.freightRpa.disabledState') }}</b></div></div>
|
||||
|
||||
@@ -153,14 +154,6 @@
|
||||
<small>{{ t('admin.freightRpa.uploadConfigHint') }}</small>
|
||||
</header>
|
||||
<div class="switch-field"><span>{{ t('admin.freightRpa.uploadAutoEnabled') }}</span><div class="switch-control"><el-switch v-model="profile.upload_config_json.enabled" /><b>{{ profile.upload_config_json.enabled ? t('admin.freightRpa.enabledState') : t('admin.freightRpa.disabledState') }}</b></div></div>
|
||||
<label><span>{{ t('admin.freightRpa.uploadEntryUrl') }}</span><el-input v-model="profile.upload_config_json.entry_url" type="url" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadFileSelector') }}</span><el-input v-model="profile.upload_config_json.file_input_selector" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadSubmitMode') }}</span><el-select v-model="profile.upload_config_json.submit_mode"><el-option value="auto_after_file" :label="t('admin.freightRpa.uploadSubmitAuto')" /><el-option value="click_submit" :label="t('admin.freightRpa.uploadSubmitClick')" /></el-select></label>
|
||||
<label v-if="profile.upload_config_json.submit_mode === 'click_submit'"><span>{{ t('admin.freightRpa.uploadSubmitSelector') }}</span><el-input v-model="profile.upload_config_json.submit_selector" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadResultMode') }}</span><el-select v-model="profile.upload_config_json.result_mode"><el-option value="page_notice" :label="t('admin.freightRpa.uploadResultPageNotice')" /><el-option value="history_record" :label="t('admin.freightRpa.uploadResultHistory')" /></el-select></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadResultSelector') }}</span><el-input v-model="profile.upload_config_json.result_selector" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadSuccessTexts') }}</span><el-input v-model="successTextsInput" type="textarea" :rows="2" :placeholder="t('admin.freightRpa.uploadSuccessTextsHint')" /></label>
|
||||
<label><span>{{ t('admin.freightRpa.uploadTimeout') }}</span><el-input-number v-model="profile.upload_config_json.timeout_seconds" :min="1" /></label>
|
||||
<div class="form-tip full">{{ t('admin.freightRpa.uploadConfigBoundary') }}</div>
|
||||
</section>
|
||||
|
||||
@@ -746,33 +739,12 @@ const filenameVariableCandidates = computed(() => {
|
||||
return filenameVariables.filter((item) => item.key.toLowerCase().includes(query) || t(item.labelKey).toLowerCase().includes(query));
|
||||
});
|
||||
|
||||
/** 连接级“发货 Excel 自动上传”配置的受控 JSON 形状(字段与后端白名单一致)。 */
|
||||
interface ProfileUploadConfig {
|
||||
enabled: boolean;
|
||||
entry_url: string;
|
||||
file_input_selector: string;
|
||||
submit_mode: 'auto_after_file' | 'click_submit';
|
||||
submit_selector: string | null;
|
||||
result_mode: 'page_notice' | 'history_record';
|
||||
result_selector: string | null;
|
||||
success_texts: string[];
|
||||
timeout_seconds: number;
|
||||
}
|
||||
|
||||
/** 连接级“发货 Excel 自动上传”默认配置:DSV 为已确认 URL+input#file2;Crane 保持未启用待管理员补全。 */
|
||||
function defaultUploadConfig(connectorType: string): ProfileUploadConfig {
|
||||
if (connectorType === 'crane') {
|
||||
return { enabled: false, entry_url: 'https://wms-portal.craneww.com/#/shipping-order-upload', file_input_selector: 'input[name="OrderFileUpload"]', submit_mode: 'click_submit', submit_selector: null, result_mode: 'page_notice', result_selector: null, success_texts: [], timeout_seconds: 120 };
|
||||
}
|
||||
return { enabled: true, entry_url: 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2', file_input_selector: 'input#file2', submit_mode: 'auto_after_file', submit_selector: null, result_mode: 'page_notice', result_selector: null, success_texts: [], timeout_seconds: 120 };
|
||||
/** 系统连接只保存是否启用自动上传;页面路径和成功判断在连接器代码里。 */
|
||||
function defaultUploadConfig(connectorType: string): { enabled: boolean } {
|
||||
return { enabled: connectorType !== 'crane' };
|
||||
}
|
||||
|
||||
const profile = reactive({ profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true, upload_config_json: defaultUploadConfig('dbs') });
|
||||
/** 成功文本以换行分隔的输入视图,写回 success_texts 数组。 */
|
||||
const successTextsInput = computed<string>({
|
||||
get: () => (profile.upload_config_json.success_texts || []).join('\n'),
|
||||
set: (value) => { profile.upload_config_json.success_texts = String(value || '').split(/\r?\n/).map((item) => item.trim()).filter(Boolean); },
|
||||
});
|
||||
const parsing = reactive({
|
||||
profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1,
|
||||
purpose: 'onhand' as 'onhand' | 'inbound' | 'outbound',
|
||||
@@ -1130,7 +1102,7 @@ watch(
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** 新建连接时按货代类型切换上传配置默认值;编辑既有连接不覆盖已保存配置。 */
|
||||
/** 新建连接时按货代类型决定自动上传默认开关;编辑既有连接不覆盖已保存配置。 */
|
||||
watch(
|
||||
() => profile.connector_type,
|
||||
(nextType) => {
|
||||
@@ -1176,11 +1148,11 @@ function createNew(): void {
|
||||
drawerOpen.value = true;
|
||||
}
|
||||
|
||||
/** 将列表对象复制到当前编辑表单,凭据字段永远不从列表回填。 */
|
||||
/** 将列表对象复制到当前编辑表单。用户名回填明文,密码不回填。 */
|
||||
function selectItem(item: Item): void {
|
||||
selectedId.value = Number(item.id);
|
||||
sourceCloneFrom.value = null;
|
||||
if (activeTab.value === 'profiles') Object.assign(profile, { ...item, username: '', password: '', login_config_json: item.login_config_json || { auth_mode: 'password' }, upload_config_json: item.upload_config_json || defaultUploadConfig(item.connector_type) });
|
||||
if (activeTab.value === 'profiles') Object.assign(profile, { ...item, username: String(item.username || ''), password: '', login_config_json: item.login_config_json || { auth_mode: 'password' }, upload_config_json: { enabled: Boolean(item.upload_config_json?.enabled) } });
|
||||
if (activeTab.value === 'parsing') Object.assign(parsing, {
|
||||
profile_code: item.profile_code, display_name: item.display_name, file_format: item.file_format,
|
||||
sheet_name: item.definition?.sheet_name || '', header_row_index: item.definition?.header_row_index ?? 0,
|
||||
@@ -1504,7 +1476,7 @@ function duplicateSourceFromDrawer(): void {
|
||||
async function saveCurrent(): Promise<void> {
|
||||
saving.value = true;
|
||||
try {
|
||||
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code, upload_config_json: profile.upload_config_json }, selectedId.value || undefined);
|
||||
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code, upload_config_json: { enabled: Boolean(profile.upload_config_json?.enabled) } }, selectedId.value || undefined);
|
||||
if (activeTab.value === 'parsing') {
|
||||
const payload = parsingUsesMovementContract.value ? {
|
||||
profile_code: parsing.profile_code, display_name: parsing.display_name || parsing.profile_code, file_format: parsing.file_format,
|
||||
@@ -1956,11 +1928,16 @@ function rowTitle(item: Item): string {
|
||||
|
||||
/**
|
||||
* 列表卡副标题。
|
||||
* 核心逻辑:mappings 展示「在途仓编码 → 目标仓编码」;缺在途仓时退化为仅目标编码。
|
||||
* 核心逻辑:mappings 展示「在途仓编码 → 目标仓编码」;系统连接展示平台与用户名。
|
||||
* @param item - 当前列表行对象
|
||||
* @returns 副标题文案
|
||||
*/
|
||||
function rowMeta(item: Item): string {
|
||||
if (activeTab.value === 'profiles') {
|
||||
const platform = item.connector_type ? t(`admin.freightRpa.platform.${item.connector_type}`) : String(item.profile_code || '');
|
||||
const username = String(item.username || '').trim();
|
||||
return username ? `${platform} · ${username}` : platform;
|
||||
}
|
||||
if (activeTab.value === 'mappings') {
|
||||
const targetCode = String(item.external_warehouse_code || '-');
|
||||
const inTransit = String(item.in_transit_warehouse_code || '').trim();
|
||||
|
||||
@@ -1399,6 +1399,19 @@ export async function batchConfirmWorkspaceShippingNoticesUploaded(businessNos:
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动刷新 Crane 分配状态。后端只排队一次状态回查,不重新上传 Excel。
|
||||
* @param businessNo - 对外发货通知单号,同时是 Crane 的 Pull Request #
|
||||
* @returns 已排队的回查结果
|
||||
*/
|
||||
export async function refreshWorkspaceCraneUploadStatus(businessNo: string) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/refresh-crane-upload`,
|
||||
jsonPost({}),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 按多个发货通知单号批量受理货代 RPA 上传;RPA 成功仍以回调为准。 */
|
||||
export async function batchStartWorkspaceShippingNoticeRpaUpload(businessNos: string[]) {
|
||||
return requestJson<{ results: Array<Record<string, unknown>> }>(
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
getWorkspaceShippingFreightNoticeGroups,
|
||||
batchConfirmWorkspaceShippingNoticesUploaded,
|
||||
batchStartWorkspaceShippingNoticeRpaUpload,
|
||||
refreshWorkspaceCraneUploadStatus,
|
||||
retryWorkspaceShippingOrderStpAutoCreate,
|
||||
retryShippingNoticeIntake,
|
||||
decideWorkspaceShippingOrderReviewLineFulfillment,
|
||||
@@ -2542,7 +2543,7 @@ const freightNoticeGroupsLoadFailed = ref(false);
|
||||
/** 货代上传分组请求在途守卫:独立于 loading,避免轮询 tick 与动作后刷新并发重载。 */
|
||||
const freightGroupsInFlight = ref(false);
|
||||
const selectedFreightBusinessNos = ref<string[]>([]);
|
||||
const freightBatchBusy = ref<'download' | 'confirm' | 'rpa' | 'regenerate' | null>(null);
|
||||
const freightBatchBusy = ref<'download' | 'confirm' | 'rpa' | 'regenerate' | 'refresh' | null>(null);
|
||||
/**
|
||||
* 判断货代通知聚合行是否已具备上传成功事实。
|
||||
* 核心逻辑:聚合接口 upload_status 已经过后端 project_notice_upload_status 归一,
|
||||
@@ -3459,7 +3460,7 @@ watch(
|
||||
function hasFreightGroupsInFlightRpa(groups: ShippingFreightNoticeGroup[]): boolean {
|
||||
return (groups || []).some((group) => {
|
||||
const st = String(group.upload_status || '').trim().toLowerCase();
|
||||
return st === 'uploading';
|
||||
return st === 'uploading' || st === 'allocating';
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3524,14 +3525,35 @@ function toggleFreightNoticeSelection(businessNo: string, checked: boolean) {
|
||||
: selectedFreightBusinessNos.value.filter((item) => item !== businessNo);
|
||||
}
|
||||
|
||||
/** 已选通知单中任一已上传时,批量写入动作必须 fail-closed,避免重复提交成功通知。 */
|
||||
/** 已选通知单中任一已上传或仍在 Crane 分配中时,批量写入动作必须停住,避免重复上传。 */
|
||||
const selectedFreightNoticesContainUploaded = computed(() => {
|
||||
const selected = new Set(selectedFreightBusinessNos.value);
|
||||
return freightNoticeGroups.value.some((group) => (
|
||||
selected.has(group.business_no) && isFreightNoticeUploaded(group)
|
||||
selected.has(group.business_no)
|
||||
&& (isFreightNoticeUploaded(group) || String(group.upload_status || '').trim().toLowerCase() === 'allocating')
|
||||
));
|
||||
});
|
||||
|
||||
/**
|
||||
* 手动刷新一张仍在分配中的 Crane 发货单。
|
||||
* @param businessNo - 发货通知单号,即 Pull Request #
|
||||
*/
|
||||
async function refreshCraneUploadStatus(businessNo: string) {
|
||||
if (freightBatchBusy.value) return;
|
||||
freightBatchBusy.value = 'refresh';
|
||||
try {
|
||||
await refreshWorkspaceCraneUploadStatus(businessNo);
|
||||
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
|
||||
if (taskNo) await loadFreightNoticeGroups(taskNo);
|
||||
freightNoticeGroupsFinalized = false;
|
||||
startWorkflowProgressPolling();
|
||||
} catch (error) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
|
||||
} finally {
|
||||
freightBatchBusy.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadFreightNotice(businessNo: string) {
|
||||
try {
|
||||
await downloadWorkspaceShippingNoticeExcelFile(businessNo);
|
||||
@@ -3824,13 +3846,21 @@ function freightLineNoDisplay(line: { line_no?: string | number | null }): {
|
||||
* @param group - 当前发货通知单聚合行(含 upload_status 与逐单错误字段)。
|
||||
*/
|
||||
function freightUploadStatusDisplay(group: ShippingFreightNoticeGroup): {
|
||||
state: 'uploaded' | 'uploading' | 'failed' | 'needs_human' | 'pending';
|
||||
state: 'uploaded' | 'uploading' | 'allocating' | 'failed' | 'needs_human' | 'pending';
|
||||
label: string;
|
||||
chipClass: string;
|
||||
reason: string | null;
|
||||
} {
|
||||
const status = String(group.upload_status || '').trim().toLowerCase();
|
||||
const reason = group.upload_error_message || group.upload_error_code || null;
|
||||
if (status === 'allocating') {
|
||||
return {
|
||||
state: 'allocating',
|
||||
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.allocating'),
|
||||
chipClass: 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-200',
|
||||
reason: null,
|
||||
};
|
||||
}
|
||||
if (status === 'uploaded') {
|
||||
return {
|
||||
state: 'uploaded',
|
||||
@@ -5496,7 +5526,15 @@ watch(
|
||||
<span :class="freightUploadStatusDisplay(group).chipClass" :title="freightUploadStatusDisplay(group).reason || undefined" class="rounded-full px-2 py-0.5 font-medium cursor-help" tabindex="0">{{ freightUploadStatusDisplay(group).label }}</span>
|
||||
<button type="button" class="rounded border border-brand-200 px-2 py-1 font-medium text-brand-700 hover:bg-brand-50" data-testid="review-freight-upload-download" :disabled="saving" @click="void downloadFreightNotice(group.business_no)">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.download') }}</button>
|
||||
<button
|
||||
v-if="canRunFreightNoticeAction(group, 'retry_freight_upload_rpa')"
|
||||
v-if="freightUploadStatusDisplay(group).state === 'allocating'"
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface-muted disabled:opacity-50"
|
||||
data-testid="review-freight-upload-refresh"
|
||||
:disabled="freightBatchBusy !== null"
|
||||
@click="void refreshCraneUploadStatus(group.business_no)"
|
||||
>{{ t('chat.shippingOrderReview.lifecycle.freightUpload.refreshStatus') }}</button>
|
||||
<button
|
||||
v-if="canRunFreightNoticeAction(group, 'retry_freight_upload_rpa') && freightUploadStatusDisplay(group).state !== 'allocating'"
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface-muted disabled:opacity-50"
|
||||
data-testid="review-freight-upload-rpa"
|
||||
@@ -5504,7 +5542,7 @@ watch(
|
||||
@click="void runFreightNoticeAction(group, 'rpa')"
|
||||
>{{ t('chat.shippingOrderReview.lifecycle.freightUpload.rpa') }}</button>
|
||||
<button
|
||||
v-if="canRunFreightNoticeAction(group, 'mark_manual_uploaded')"
|
||||
v-if="canRunFreightNoticeAction(group, 'mark_manual_uploaded') && freightUploadStatusDisplay(group).state !== 'allocating'"
|
||||
type="button"
|
||||
class="rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface-muted disabled:opacity-50"
|
||||
data-testid="review-freight-upload-confirm"
|
||||
|
||||
@@ -1026,7 +1026,7 @@
|
||||
},
|
||||
"connectionBoundary": "Enter only the login information here. The system handles the required page actions, downloads, and waiting for the selected freight platform.",
|
||||
"uploadConfigTitle": "Shipping Excel Auto Upload",
|
||||
"uploadConfigHint": "Edited from this System Connection and stored as a restricted JSON. No free JavaScript, scripts, URL templates, cookies, or arbitrary browser actions are allowed.",
|
||||
"uploadConfigHint": "This switch only enables auto-upload. The page, buttons, and success checks are fixed in the freight connector.",
|
||||
"uploadAutoEnabled": "Enable auto-upload (admin has reviewed this connection's upload behavior)",
|
||||
"uploadEntryUrl": "Upload entry URL",
|
||||
"uploadFileSelector": "File input selector",
|
||||
@@ -1041,7 +1041,7 @@
|
||||
"uploadSuccessTexts": "Success texts (one per line)",
|
||||
"uploadSuccessTextsHint": "Matching any success text marks success",
|
||||
"uploadTimeout": "Timeout (seconds)",
|
||||
"uploadConfigBoundary": "Upload config changes do not increment the inventory RPA config_version; used only for this connection's freight upload, not propagated to inventory/receipt RPA.",
|
||||
"uploadConfigBoundary": "The upload page, buttons, and success checks are fixed in the connector. This switch only turns auto-upload on or off.",
|
||||
"platform": {
|
||||
"dbs": "DBS",
|
||||
"crane": "Crane"
|
||||
@@ -2631,6 +2631,7 @@
|
||||
"platformJobFreightRpaOnhand": "Freight onhand inventory RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ hot aggregate",
|
||||
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
|
||||
"transferTypeCodes": "Transfer types",
|
||||
"transferSourceCodes": "Source instances",
|
||||
"transferRecoverHistory": "Recover retryable history",
|
||||
"transferReceiptDateFrom": "Movement date from (T-N)",
|
||||
|
||||
@@ -1746,6 +1746,7 @@
|
||||
"download": "Download Excel",
|
||||
"rpa": "RPA upload",
|
||||
"confirm": "Confirm uploaded",
|
||||
"refreshStatus": "Refresh upload status",
|
||||
"lineNo": "Line",
|
||||
"lineNoSourceCustomerPo": "Customer PO line no.",
|
||||
"lineNoSourceSequence": "System sequence (internal line no. not recognized)",
|
||||
@@ -1758,6 +1759,7 @@
|
||||
"uploadStatus": {
|
||||
"pending": "Pending upload",
|
||||
"uploading": "Uploading",
|
||||
"allocating": "Accepted, allocating",
|
||||
"failed": "Upload failed",
|
||||
"uploaded": "Uploaded",
|
||||
"needsHuman": "Manual upload needed"
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "Invalid batch format. Check the date, quantity, or remark.",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "The total of all batch quantities must equal the order quantity. Please adjust and save again.",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "The selected ODM ID is not among the feasible candidates. Please choose again.",
|
||||
"SHIPPING.UPLOAD_CRANE_ALLOCATING": "The forwarder accepted the file and is still allocating it. Refresh the status instead of uploading again.",
|
||||
"SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT": "A status refresh is already queued. Try again shortly.",
|
||||
"SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE": "The upload status-check directory is unavailable. Check the RPA shared folder.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "The fulfillment policy or field capability binding is invalid.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "The fulfillment policy was not found.",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "The fulfillment policy was changed by another administrator. Refresh and try again.",
|
||||
|
||||
@@ -1026,7 +1026,7 @@
|
||||
},
|
||||
"connectionBoundary": "กรอกเฉพาะข้อมูลเข้าสู่ระบบ ระบบจะดำเนินการหน้าเว็บ ดาวน์โหลด และรอตามแพลตฟอร์มผู้ให้บริการที่เลือกโดยอัตโนมัติ",
|
||||
"uploadConfigTitle": "อัปโหลด Excel การจัดส่งอัตโนมัติ",
|
||||
"uploadConfigHint": "แก้ไขจากหน้าการเชื่อมต่อระบบนี้และบันทึกเป็น JSON แบบจำกัด; ห้ามใช้ JavaScript/สคริปต์/URL template/Cookie หรือการกระทำเบราว์เซอร์โดยอิสระ",
|
||||
"uploadConfigHint": "สวิตช์นี้เปิดเฉพาะการอัปโหลดอัตโนมัติ หน้า ปุ่ม และเงื่อนไขสำเร็จถูกกำหนดไว้ในตัวเชื่อมต่อ",
|
||||
"uploadAutoEnabled": "เปิดใช้งานอัปโหลดอัตโนมัติ (ผู้ดูแลตรวจสอบพฤติกรรมการอัปโหลดของการเชื่อมต่อนี้แล้ว)",
|
||||
"uploadEntryUrl": "URL หน้าอัปโหลด",
|
||||
"uploadFileSelector": "ตัวเลือกไฟล์ (selector)",
|
||||
@@ -1041,7 +1041,7 @@
|
||||
"uploadSuccessTexts": "ข้อความสำเร็จ (หนึ่งรายการต่อบรรทัด)",
|
||||
"uploadSuccessTextsHint": "หากตรงกับข้อความสำเร็จข้อใดข้อหนึ่งถือว่าสำเร็จ",
|
||||
"uploadTimeout": "ระยะเวลารอ (วินาที)",
|
||||
"uploadConfigBoundary": "การเปลี่ยนค่าอัปโหลดไม่เพิ่ม config_version ของ RPA คลัง; ใช้เฉพาะการอัปโหลดของสายการขนส่งนี้เท่านั้น ไม่แพร่ไปยัง RPA คลัง/รับของ",
|
||||
"uploadConfigBoundary": "หน้า ปุ่ม และเงื่อนไขสำเร็จถูกกำหนดในโปรแกรม สวิตช์นี้เปิดหรือปิดการอัปโหลดอัตโนมัติเท่านั้น",
|
||||
"platform": {
|
||||
"dbs": "DBS",
|
||||
"crane": "Crane"
|
||||
@@ -2511,6 +2511,7 @@
|
||||
"platformJobFreightRpaOnhand": "Freight onhand inventory RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ hot aggregate",
|
||||
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
|
||||
"transferTypeCodes": "ประเภทการโอนย้าย",
|
||||
"transferSourceCodes": "Source instances",
|
||||
"transferRecoverHistory": "Recover retryable history",
|
||||
"transferReceiptDateFrom": "วันที่เคลื่อนไหวเริ่ม (T-N)",
|
||||
|
||||
@@ -1746,6 +1746,7 @@
|
||||
"download": "ดาวน์โหลด Excel",
|
||||
"rpa": "อัปโหลด RPA",
|
||||
"confirm": "ยืนยันอัปโหลด",
|
||||
"refreshStatus": "รีเฟรชสถานะอัปโหลด",
|
||||
"lineNo": "รายการ",
|
||||
"lineNoSourceCustomerPo": "เลขบรรทัด PO ของลูกค้า",
|
||||
"lineNoSourceSequence": "ลำดับระบบ (ไม่พบเลขรายการภายใน)",
|
||||
@@ -1758,6 +1759,7 @@
|
||||
"uploadStatus": {
|
||||
"pending": "รออัปโหลด",
|
||||
"uploading": "กำลังอัปโหลด",
|
||||
"allocating": "รับไฟล์แล้ว กำลังจัดสรร",
|
||||
"failed": "อัปโหลดล้มเหลว",
|
||||
"uploaded": "อัปโหลดแล้ว",
|
||||
"needsHuman": "ต้องอัปโหลดด้วยตนเอง"
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "รูปแบบงวดไม่ถูกต้อง โปรดตรวจสอบวันที่ จำนวน หรือหมายเหตุ",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "ผลรวมจำนวนทุกงวดต้องเท่ากับจำนวนของคำสั่งซื้อ โปรดปรับแล้วบันทึกอีกครั้ง",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "ODM ID ที่เลือกไม่อยู่ในตัวเลือกที่ทำได้ โปรดเลือกใหม่",
|
||||
"SHIPPING.UPLOAD_CRANE_ALLOCATING": "ผู้รับขนรับไฟล์แล้วและกำลังจัดสรร โปรดรีเฟรชสถานะ อย่าอัปโหลดซ้ำ",
|
||||
"SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT": "มีการรีเฟรชสถานะค้างอยู่ในคิว โปรดลองอีกครั้งในอีกสักครู่",
|
||||
"SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE": "โฟลเดอร์ตรวจสถานะการอัปโหลดไม่พร้อม โปรดตรวจโฟลเดอร์ที่ใช้ร่วมกันของ RPA",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "นโยบายการปฏิบัติตามหรือการผูกความสามารถของฟิลด์ไม่ถูกต้อง",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "ไม่พบนโยบายการปฏิบัติตาม",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "นโยบายการปฏิบัติตามถูกแก้ไขโดยผู้ดูแลรายอื่น โปรดรีเฟรชแล้วลองใหม่",
|
||||
|
||||
@@ -1157,7 +1157,7 @@
|
||||
},
|
||||
"connectionBoundary": "连接配置只填写登录所需信息;系统会按货代平台自动执行页面操作、下载和等待。",
|
||||
"uploadConfigTitle": "发货 Excel 自动上传",
|
||||
"uploadConfigHint": "该配置由系统连接管理端编辑,后端保存为受限 JSON;禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作。",
|
||||
"uploadConfigHint": "只控制这条连接是否自动上传。上传页面、按钮和成功判断由对应货代平台的程序固定。",
|
||||
"uploadAutoEnabled": "启用自动上传(代表管理员已审核该连接的上传行为)",
|
||||
"uploadEntryUrl": "上传入口 URL",
|
||||
"uploadFileSelector": "文件选择器",
|
||||
@@ -1172,7 +1172,7 @@
|
||||
"uploadSuccessTexts": "成功文本(每行一条)",
|
||||
"uploadSuccessTextsHint": "命中任一条成功文本即判定成功",
|
||||
"uploadTimeout": "超时时间(秒)",
|
||||
"uploadConfigBoundary": "上传配置变更不递增库存 RPA config_version;仅该连接的货代上传使用,不向库存/收料 RPA 扩散。",
|
||||
"uploadConfigBoundary": "上传页面、按钮和成功判断由货代平台程序固定。这里只开关自动上传,变更不递增库存 RPA config_version。",
|
||||
"platform": {
|
||||
"dbs": "DBS 平台",
|
||||
"crane": "Crane 平台"
|
||||
@@ -2762,6 +2762,7 @@
|
||||
"platformJobFreightRpaOnhand": "货代库存 RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ 热点聚合",
|
||||
"platformJobFileAssetCleanup": "临时文件资产清理",
|
||||
"transferTypeCodes": "调拨类型",
|
||||
"transferSourceCodes": "来源实例",
|
||||
"transferRecoverHistory": "历史可恢复异常复核",
|
||||
"transferReceiptDateFrom": "异动日期起(T-N)",
|
||||
|
||||
@@ -1780,6 +1780,7 @@
|
||||
"download": "下载 Excel",
|
||||
"rpa": "RPA 上传",
|
||||
"confirm": "确认上传",
|
||||
"refreshStatus": "刷新上传状态",
|
||||
"lineNo": "项次",
|
||||
"lineNoSourceCustomerPo": "客户 PO 行号",
|
||||
"lineNoSourceSequence": "系统行序(未识别到内部项次)",
|
||||
@@ -1792,6 +1793,7 @@
|
||||
"uploadStatus": {
|
||||
"pending": "待上传",
|
||||
"uploading": "上传中",
|
||||
"allocating": "已接收,分配中",
|
||||
"failed": "上传失败",
|
||||
"uploaded": "已上传",
|
||||
"needsHuman": "需人工上传"
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "批次格式不合法,请检查交期、数量或备注。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "各批次数量合计必须等于订单数量,请调整后重新保存。",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所选 ODM ID 不在当前可行候选内,请重新选择。",
|
||||
"SHIPPING.UPLOAD_CRANE_ALLOCATING": "货代已接收文件并正在分配,请刷新状态,不要再次上传。",
|
||||
"SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT": "上一次状态刷新还在排队,请稍后再试。",
|
||||
"SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE": "上传回查目录不可用,请检查 RPA 共享目录。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "货代履约策略或字段能力绑定无效。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "未找到货代履约策略。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "货代履约策略已被其他管理员修改,请刷新后重试。",
|
||||
|
||||
@@ -1026,7 +1026,7 @@
|
||||
},
|
||||
"connectionBoundary": "連線設定只填寫登入所需資訊;系統會依貨代平台自動執行頁面操作、下載與等待。",
|
||||
"uploadConfigTitle": "發貨 Excel 自動上傳",
|
||||
"uploadConfigHint": "本設定由系統連線管理端編輯,後端儲存為受限 JSON;禁止自由 JavaScript、腳本、URL 範本、Cookie 或任意瀏覽器動作。",
|
||||
"uploadConfigHint": "只控制這條連線是否自動上傳。上傳頁面、按鈕和成功判斷由對應貨代平台的程式固定。",
|
||||
"uploadAutoEnabled": "啟用自動上傳(代表管理員已審核該連線的上傳行為)",
|
||||
"uploadEntryUrl": "上傳入口 URL",
|
||||
"uploadFileSelector": "檔案選擇器",
|
||||
@@ -1041,7 +1041,7 @@
|
||||
"uploadSuccessTexts": "成功文字(每行一條)",
|
||||
"uploadSuccessTextsHint": "命中任一條成功文字即判定成功",
|
||||
"uploadTimeout": "逾時時間(秒)",
|
||||
"uploadConfigBoundary": "上傳設定變更不遞增庫存 RPA config_version;僅該連線的貨代上傳使用,不擴散至庫存/收料 RPA。",
|
||||
"uploadConfigBoundary": "上傳頁面、按鈕和成功判斷由貨代平台程式固定。這裡只開關自動上傳,變更不遞增庫存 RPA config_version。",
|
||||
"platform": {
|
||||
"dbs": "DBS 平台",
|
||||
"crane": "Crane 平台"
|
||||
@@ -2511,6 +2511,7 @@
|
||||
"platformJobFreightRpaOnhand": "貨代庫存 RPA",
|
||||
"platformJobFaqHotAggregate": "FAQ 熱點聚合",
|
||||
"platformJobFileAssetCleanup": "暫存檔案資產清理",
|
||||
"transferTypeCodes": "調撥類型",
|
||||
"transferSourceCodes": "來源實例",
|
||||
"transferRecoverHistory": "歷史可復原異常複核",
|
||||
"transferReceiptDateFrom": "異動日期起(T-N)",
|
||||
|
||||
@@ -1746,6 +1746,7 @@
|
||||
"download": "下載 Excel",
|
||||
"rpa": "RPA 上傳",
|
||||
"confirm": "確認上傳",
|
||||
"refreshStatus": "重新整理上傳狀態",
|
||||
"lineNo": "項次",
|
||||
"lineNoSourceCustomerPo": "客戶 PO 行號",
|
||||
"lineNoSourceSequence": "系統行序(未識別到內部項次)",
|
||||
@@ -1758,6 +1759,7 @@
|
||||
"uploadStatus": {
|
||||
"pending": "待上傳",
|
||||
"uploading": "上傳中",
|
||||
"allocating": "已接收,分配中",
|
||||
"failed": "上傳失敗",
|
||||
"uploaded": "已上傳",
|
||||
"needsHuman": "需人工上傳"
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
"ORDER_DELIVERY_REPLY.BATCH_INVALID": "批次格式不合法,請檢查交期、數量或備註。",
|
||||
"ORDER_DELIVERY_REPLY.BATCH_QTY_TOTAL_MISMATCH": "各批次數量合計必須等於訂單數量,請調整後重新保存。",
|
||||
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所選 ODM ID 不在當前可行候選內,請重新選擇。",
|
||||
"SHIPPING.UPLOAD_CRANE_ALLOCATING": "貨代已接收檔案並正在分配,請重新整理狀態,不要再次上傳。",
|
||||
"SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT": "上一次狀態重新整理還在排隊,請稍後再試。",
|
||||
"SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE": "上傳回查目錄不可用,請檢查 RPA 共用目錄。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_INVALID": "貨代履約策略或欄位能力綁定無效。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "找不到貨代履約策略。",
|
||||
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "貨代履約策略已被其他管理員修改,請重新整理後再試。",
|
||||
|
||||
@@ -1995,6 +1995,22 @@ def _dsv_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _upload_entry_url(connector_type: str, login_url: str) -> str:
|
||||
"""用登录地址的主机拼出平台固定上传页,不读取管理端保存的入口 URL。"""
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
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:
|
||||
raise RuntimeError('upload login_url must be HTTPS')
|
||||
if kind == 'dbs':
|
||||
return f'https://{host}/main/portal/frame/WMSUpload2'
|
||||
if kind == 'crane':
|
||||
return f'https://{host}/#/shipping-order-upload'
|
||||
raise RuntimeError(f'unsupported upload connector_type: {connector_type or "<empty>"}')
|
||||
|
||||
|
||||
def _crane_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
"""判断 Crane 发货通知行是否进入 Processing/Shipping Order Allocated。"""
|
||||
return (
|
||||
@@ -2004,6 +2020,15 @@ def _crane_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _crane_upload_result_is_allocating(state: dict[str, Any]) -> bool:
|
||||
"""判断 Crane 是否已接收文件、仍在分配。这一态不是上传成功。"""
|
||||
return (
|
||||
bool(state.get('found'))
|
||||
and str(state.get('order_status') or '').strip().lower() == 'processing'
|
||||
and str(state.get('order_status_description') or '').strip().lower() == 'allocating the shipping order'
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_dsv_upload_result(page: Any, filename: str) -> dict[str, Any]:
|
||||
"""轮询 DSV 上传结果页,不再使用 History 绿图标作为成功依据。
|
||||
|
||||
@@ -2056,12 +2081,19 @@ class _UploadResultUnknownError(RuntimeError):
|
||||
"""上传动作已发生但结果无法确认(未能取得可核验成功证据);必须转人工,禁止自动重试。"""
|
||||
|
||||
|
||||
class _BaseUploadAdapter:
|
||||
"""受控上传适配器基类:由连接级 upload_config 提供页面参数,代码负责浏览器动作与安全边界。
|
||||
class _UploadAcceptedAllocating(Exception):
|
||||
"""Crane 已接收文件,行状态仍是 Allocating。调用方回调 allocating,不视为失败。"""
|
||||
|
||||
设计约束:禁止把任意脚本/URL 模板/Cookie/任意浏览器动作开放到后台配置;config 只决定
|
||||
“该连接使用哪个已支持的受控流程及其页面参数”。Adapter 负责登录、打开 entry 页、选择 Excel、
|
||||
提交与结果判定。Worker 不再根据环境变量拼接 DSV/Crane 页面动作。
|
||||
def __init__(self, pull_request_no: str):
|
||||
self.pull_request_no = pull_request_no
|
||||
super().__init__(pull_request_no)
|
||||
|
||||
|
||||
class _BaseUploadAdapter:
|
||||
"""受控上传适配器基类:页面路径、按钮和成功判断写在连接器里。
|
||||
|
||||
设计约束:系统连接只保存是否启用自动上传。Adapter 负责登录、打开固定上传页、
|
||||
选择 Excel、提交与结果判定。Worker 不再根据环境变量或后台选择器拼接页面动作。
|
||||
"""
|
||||
|
||||
def __init__(self, *, file_path: Path, upload_config: dict[str, Any]):
|
||||
@@ -2089,10 +2121,9 @@ class DsvUploadAdapter(_BaseUploadAdapter):
|
||||
|
||||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||||
"""选择 DSV 文件后强制点击 Process File,再读取结果页三项成功条件。"""
|
||||
self._require('entry_url', 'file_input_selector')
|
||||
_ensure_dsv_session(page, login_url)
|
||||
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
file_selector = str(self.config.get('file_input_selector') or '#file2').strip()
|
||||
page.goto(_upload_entry_url('dbs', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
file_selector = 'input#file2'
|
||||
page.locator(file_selector).first.set_input_files(str(self.file_path), timeout=self._timeout_ms())
|
||||
# DSV 页面选择文件后只完成预览;必须点击真实二次确认按钮才会提交上传。
|
||||
submit_selector = 'button.btn.btn-primary.upload-button:has-text("Process File")'
|
||||
@@ -2105,9 +2136,9 @@ class DsvUploadAdapter(_BaseUploadAdapter):
|
||||
|
||||
|
||||
class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
"""Crane 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → 结果判定。
|
||||
"""Crane 受控上传流程:login_url 登录后打开固定上传页,选择文件并读发货单行。
|
||||
|
||||
启用前(enabled=true)管理端必须已确认提交按钮与成功判定字段;否则 fail-closed。
|
||||
Processing + Allocating the Shipping Order 表示已接收;只有 Shipping Order Allocated 才算成功。
|
||||
"""
|
||||
|
||||
# SweetAlert2 上传失败弹窗识别(受控 Adapter 内置,禁止开放到 upload_config):Crane 上传
|
||||
@@ -2133,18 +2164,25 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
)
|
||||
|
||||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||||
self._require('entry_url', 'file_input_selector', 'submit_mode')
|
||||
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
|
||||
self._require('submit_selector')
|
||||
self._require_result_fields()
|
||||
"""选择 Crane 上传文件后读发货单行。分配中立即返回,不等到超时。"""
|
||||
_ensure_crane_session(page, login_url)
|
||||
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
page.locator(str(self.config['file_input_selector'])).first.set_input_files(
|
||||
page.goto(_upload_entry_url('crane', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
page.locator('input[name="OrderFileUpload"]').first.set_input_files(
|
||||
str(self.file_path), timeout=self._timeout_ms(),
|
||||
)
|
||||
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
|
||||
page.locator(str(self.config['submit_selector'])).first.click(timeout=self._timeout_ms())
|
||||
return self._resolve_result(page)
|
||||
result = self._resolve_result(page)
|
||||
if result.get('outcome') == 'allocating':
|
||||
raise _UploadAcceptedAllocating(self.file_path.stem)
|
||||
return result
|
||||
|
||||
def run_status_check(self, page: Any, *, login_url: str, pull_request_no: str) -> dict[str, Any]:
|
||||
"""重新登录后只按 Pull Request # 读行,不选择、不提交文件。"""
|
||||
_ensure_crane_session(page, login_url)
|
||||
page.goto(_upload_entry_url('crane', login_url), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
found = self._wait_for_order_status(page, f'{pull_request_no}.xlsx', wait_seconds=20)
|
||||
if found and found.get('success_evidence'):
|
||||
return found
|
||||
return {'outcome': 'allocating', 'pull_request_no': pull_request_no}
|
||||
|
||||
def _require_result_fields(self) -> None:
|
||||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||||
@@ -2242,83 +2280,22 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
return None
|
||||
|
||||
def _resolve_result(self, page: Any) -> dict[str, Any]:
|
||||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||||
"""读发货单行。已分配或分配中立即返回;明确弹窗拒绝则失败。"""
|
||||
filename = self.file_path.name
|
||||
# [STEP 1] Crane 页面成功反馈后仍需核对发货通知列表中的业务状态,
|
||||
# 只有 Processing + Shipping Order Allocated 才视为真正上传成功。
|
||||
status_result = self._wait_for_order_status(page, filename)
|
||||
# [STEP 1] 只有 Processing + Shipping Order Allocated 才是上传成功。
|
||||
# Processing + Allocating the Shipping Order 表示货代已接收,稍后回查。
|
||||
status_result = self._wait_for_order_status(page, filename, wait_seconds=30)
|
||||
if status_result:
|
||||
return status_result
|
||||
# 提交后先探测一次失败/成功弹窗;判定期内仍会持续探测(结果选择器可能晚于弹窗出现)。
|
||||
# [STEP 2] 客户或仓库不存在等明确拒绝记失败。看不到行时不按后台选择器猜成功。
|
||||
self._raise_if_crane_error(page)
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
if result_mode == 'history_record':
|
||||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||||
try:
|
||||
loc = page.locator(result_selector).first
|
||||
loc.wait_for(state='visible', timeout=self._timeout_ms())
|
||||
except Exception as exc:
|
||||
# 判定期内可能出现失败弹窗(如 Customer/Warehouse 未找到);先读取并关闭,
|
||||
# 以真实原因上报失败;否则仍按“结果未知”转人工。
|
||||
self._raise_if_crane_error(page)
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
raise _UploadResultUnknownError(
|
||||
f"无法判断上传是否成功/失败:{filename!r} 历史结果未确认({exc});"
|
||||
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
|
||||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||||
) from exc
|
||||
try:
|
||||
reference = str(loc.text_content(timeout=self._timeout_ms()) or '').strip()
|
||||
except Exception:
|
||||
reference = ''
|
||||
return {
|
||||
'reference': reference,
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='crane_history_record', selector=result_selector,
|
||||
filename=filename, reference=reference or None,
|
||||
),
|
||||
}
|
||||
# page_notice:要求 result_selector 可见且内容命中任一 success_texts。
|
||||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||||
success_texts = [str(t).strip() for t in (self.config.get('success_texts') or []) if str(t).strip()]
|
||||
deadline = time.monotonic() + (self._timeout_ms() / 1000)
|
||||
last_snippet = ''
|
||||
while time.monotonic() < deadline:
|
||||
# 上传失败时 Crane 会先弹错误窗而非成功提示;命中则读取原因、点 OK 关闭并上报失败。
|
||||
self._raise_if_crane_error(page)
|
||||
# 成功也可能以 SweetAlert2 成功弹窗反馈;优先于配置 result_selector 判定,避免配置错误误报 unknown。
|
||||
success = self._success_from_popup(page, filename)
|
||||
if success:
|
||||
return success
|
||||
try:
|
||||
loc = page.locator(result_selector).first
|
||||
if loc.count() > 0 and loc.is_visible():
|
||||
snippet = str(loc.text_content(timeout=1000) or '').strip()
|
||||
last_snippet = snippet
|
||||
if any(text in snippet for text in success_texts):
|
||||
return {
|
||||
'reference': '',
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='crane_page_notice', selector=result_selector,
|
||||
filename=filename, reference=None,
|
||||
),
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise _UploadResultUnknownError(
|
||||
f"无法判断上传是否成功/失败:{filename!r} 结果未确认(last_snippet={last_snippet!r});"
|
||||
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
|
||||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||||
f"无法判断上传是否成功/失败:{filename!r} 未出现 Processing + Allocating 或 Shipping Order Allocated。"
|
||||
)
|
||||
|
||||
def _wait_for_order_status(self, page: Any, filename: str) -> dict[str, Any] | None:
|
||||
"""轮询 Crane 发货通知表,按上传单号核对 Processing/Shipping Order Allocated。"""
|
||||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||||
def _wait_for_order_status(self, page: Any, filename: str, *, wait_seconds: int = 30) -> dict[str, Any] | None:
|
||||
"""轮询 Crane 发货通知表。看到 Allocating 立刻返回,不等到 Allocated。"""
|
||||
result_selector = ''
|
||||
script = """
|
||||
({ filename, resultSelector }) => {
|
||||
const clean = (v) => String(v || '').replace(/\\s+/g, ' ').trim();
|
||||
@@ -2338,15 +2315,18 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
return { found: false, order_status: '', order_status_description: '' };
|
||||
}
|
||||
"""
|
||||
deadline = time.monotonic() + (self._timeout_ms() / 1000)
|
||||
deadline = time.monotonic() + max(1, int(wait_seconds))
|
||||
last_state: dict[str, Any] = {}
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
state = page.evaluate(script, {'filename': filename, 'resultSelector': result_selector}) or {}
|
||||
if isinstance(state, dict):
|
||||
last_state = state
|
||||
if _crane_upload_result_is_allocating(state):
|
||||
return {'outcome': 'allocating', 'pull_request_no': Path(filename).stem}
|
||||
if _crane_upload_result_is_success(state):
|
||||
return {
|
||||
'outcome': 'allocated',
|
||||
'reference': '',
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='crane_order_status_dom', selector='tr[id^="shipping-order-"]',
|
||||
@@ -2429,6 +2409,41 @@ def _upload_shipment_with_browser(
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _check_crane_allocation(upload_source: dict[str, Any], pull_request_no: str) -> dict[str, Any]:
|
||||
"""重新登录 Crane,只按 Pull Request # 读取发货单行。"""
|
||||
login_url = str(upload_source.get('login_url') or '').strip()
|
||||
playwright = context = runtime_profile_dir = None
|
||||
failed = False
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(Path('.'), reuse_session=False)
|
||||
adapter = CraneUploadAdapter(file_path=Path(f'{pull_request_no}.xlsx'), upload_config={})
|
||||
with _profile_credentials(upload_source):
|
||||
return adapter.run_status_check(page, login_url=login_url, pull_request_no=pull_request_no)
|
||||
except Exception:
|
||||
failed = True
|
||||
raise
|
||||
finally:
|
||||
if not (failed and _env("FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"):
|
||||
if context is not None:
|
||||
context.close()
|
||||
if playwright is not None:
|
||||
playwright.stop()
|
||||
if runtime_profile_dir is not None:
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _post_allocating_callback(body: dict[str, Any], *, pull_request_no: str) -> None:
|
||||
"""回调 Crane 已接收、仍在分配。不带成功证据。"""
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": body.get("task_no"),
|
||||
"attempt_id": body.get("attempt_id"),
|
||||
"callback_id": body.get("callback_id"),
|
||||
"result": "allocating",
|
||||
"success": False,
|
||||
"pull_request_no": pull_request_no,
|
||||
})
|
||||
|
||||
|
||||
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
@@ -2436,11 +2451,49 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
attempt_id = body.get("attempt_id")
|
||||
callback_id = str(body.get("callback_id") or "").strip()
|
||||
failed_dir = processed_dir.parent / "failed"
|
||||
status_check = str(body.get("mode") or "").strip() == "status_check"
|
||||
if not task_no:
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
mock = _env("FREIGHT_RPA_WORKER_MOCK", "false").lower() == "true"
|
||||
if status_check and not mock:
|
||||
try:
|
||||
upload_source = {
|
||||
"connector_type": str(body.get("connector_type") or "").strip(),
|
||||
"login_url": str(body.get("login_url") or "").strip(),
|
||||
"credential_envelope": body.get("credential_envelope"),
|
||||
"upload_config_json": body.get("upload_config") or {"enabled": True},
|
||||
}
|
||||
pull_request_no = str(body.get("pull_request_no") or Path(file_path).stem).strip()
|
||||
raw = _check_crane_allocation(upload_source, pull_request_no)
|
||||
if raw.get("success_evidence"):
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"result": "success",
|
||||
"success": True,
|
||||
"success_evidence": raw.get("success_evidence"),
|
||||
})
|
||||
else:
|
||||
_post_allocating_callback(body, pull_request_no=pull_request_no)
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
"result": "allocating",
|
||||
"success": False,
|
||||
"error_message": str(exc)[:500],
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed after status check error")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
return
|
||||
|
||||
if not file_path or not Path(file_path).is_file():
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
@@ -2502,6 +2555,13 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[upload] {'mock' if mock else 'browser'} upload done for {task_no} ref={ref or '-'}")
|
||||
except _UploadAcceptedAllocating as exc:
|
||||
try:
|
||||
_post_allocating_callback(body, pull_request_no=exc.pull_request_no)
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[upload] crane accepted {task_no} pull_request={exc.pull_request_no}; waiting for allocation")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
|
||||
Reference in new issue
Block a user