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