feat(shipping-freight-auto-upload): 新增货代发货Excel连接级自动上传全链路功能
为提升货代上传的自动化程度,减少人工操作,本提交实现完整的连接级自动上传功能,包含以下变更: - 新增数据库迁移与ShippingRpaProfile模型字段,存储连接级上传配置 - 完善RPA自动上传触发、回调与状态管理逻辑,支持三态结果与人工兜底 - 优化聊天界面任务卡片加载与按钮渲染,修复无文案幽灵按钮问题
This commit is contained in:
1 parent
06c18b3c7c
commit
434c04ed2d
30 files changed
+1574
-185
No files matched your search
@@ -26,6 +26,7 @@ from app.models import (
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.credential_crypto import encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
from app.services.shipping_notice.inventory_routing_engine import ALLOWED_ACTIONS
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
@@ -162,6 +163,7 @@ def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]:
|
||||
'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),
|
||||
'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),
|
||||
@@ -199,6 +201,13 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
profile = profile or ShippingRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
|
||||
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
|
||||
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
|
||||
prev_non_upload = (
|
||||
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
|
||||
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
|
||||
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
|
||||
) if profile_id else None
|
||||
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
|
||||
profile.display_name = str(_text(data, 'display_name', required=True))
|
||||
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
@@ -218,9 +227,18 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
|
||||
profile.password_ciphertext = encrypt_credential(password)
|
||||
if username is not None or password is not None:
|
||||
profile.credential_updated_at = datetime.utcnow()
|
||||
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
||||
if 'upload_config_json' in data:
|
||||
profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json'))
|
||||
profile.updated_by = actor_id
|
||||
if profile_id:
|
||||
profile.config_version += 1
|
||||
now_non_upload = (
|
||||
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
|
||||
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
|
||||
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
|
||||
)
|
||||
if now_non_upload != prev_non_upload:
|
||||
profile.config_version += 1
|
||||
if not profile_id:
|
||||
profile.created_by = actor_id
|
||||
db.session.add(profile)
|
||||
|
||||
@@ -64,6 +64,9 @@ from app.services.shipping_notice.rpa_attempts import (
|
||||
max_rpa_upload_attempts,
|
||||
upload_rpa_attempts,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.upload_config_validation import compute_upload_config_hash
|
||||
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
@@ -439,14 +442,49 @@ def _trigger_freight_upload_rpa(
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
|
||||
queue_path, trigger_path = write_upload_trigger(
|
||||
# [STEP] 读取该任务已确定的系统连接及其 upload_config_json;未配置/未启用则 fail-closed 转人工。
|
||||
# 连接级受控上传是“外例”,只作用于货代上传,不向库存 RPA 或收料 RPA 扩散。
|
||||
rpa_source = task_rpa_inventory_source(task) or {}
|
||||
connector_type = str(rpa_source.get('connector_type') or '').strip().lower()
|
||||
source_code = str(rpa_source.get('source_code') or '').strip().upper()
|
||||
# 通过 get_rpa_trigger_inventory_source 取带登录凭据与上传配置的连接快照(供 Worker 登录后访问上传页)。
|
||||
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
|
||||
if not isinstance(upload_source, dict):
|
||||
upload_source = dict(rpa_source)
|
||||
upload_config = upload_source.get('upload_config_json') if isinstance(upload_source, dict) else None
|
||||
if connector_type not in {'dbs', 'crane'} or not isinstance(upload_config, dict) or not upload_config.get('enabled'):
|
||||
task.error_message = (
|
||||
'该连接未启用“发货 Excel 自动上传”,请管理员先在“系统连接”完成上传配置并启用后再触发,'
|
||||
'或人工下载 Excel 后上传并登记凭据。'
|
||||
)
|
||||
log_task_event(task, 'upload_rpa_config_missing', {'connector_type': connector_type or None})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='needs_human',
|
||||
task=task,
|
||||
message=task.error_message,
|
||||
data=serialize_task_for_tool(task),
|
||||
stop_agent_turn=True,
|
||||
next_required_action='请在“系统连接”补齐上传配置并启用,或人工上传。',
|
||||
)
|
||||
|
||||
callback_id = f'upload:{task.task_no}:attempt:{int(attempt.id)}'
|
||||
|
||||
queue_path, trigger_path, callback_id = write_upload_trigger(
|
||||
task.task_no,
|
||||
str(task.export_file_path),
|
||||
payload={
|
||||
'attempt_id': int(attempt.id),
|
||||
'artifact_id': int(attempt.artifact_id),
|
||||
'mode': str(body.get('mode') or 'auto'),
|
||||
},
|
||||
attempt_id=int(attempt.id),
|
||||
artifact_id=int(attempt.artifact_id),
|
||||
connector_type=connector_type,
|
||||
upload_config=dict(upload_config),
|
||||
upload_config_hash=compute_upload_config_hash(upload_config),
|
||||
login_url=str(upload_source.get('login_url') or '').strip() or None,
|
||||
credential_envelope=upload_source.get('credential_envelope'),
|
||||
callback_id=callback_id,
|
||||
business_no=task.business_no,
|
||||
)
|
||||
if not trigger_path:
|
||||
attempt.status = 'failed'
|
||||
@@ -2160,6 +2198,14 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
success = _rpa_callback_success(payload.get("success"))
|
||||
except ValidationError as exc:
|
||||
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'}:
|
||||
result_status = raw_result
|
||||
else:
|
||||
result_status = 'success' if success else 'failed'
|
||||
# 成功证据只在 success 时才要求;unknown/failed 不索取页面证据。
|
||||
success = result_status == 'success'
|
||||
success_evidence: dict[str, Any] | None = None
|
||||
if success:
|
||||
expected_filename = (
|
||||
@@ -2187,6 +2233,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
completed = complete_attempt(
|
||||
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
|
||||
freight_ref_no=str(payload.get('freight_ref_no') or ''), error_message=str(payload.get('error_message') or ''),
|
||||
result=result_status,
|
||||
)
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
@@ -2252,6 +2299,28 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
)
|
||||
|
||||
if completed.status == 'unknown':
|
||||
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
|
||||
task.upload_finished_at = datetime.utcnow()
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
step_title="上传货代",
|
||||
status="needs_human",
|
||||
message=t("workflow.fulfillment.upload_unknown_wait_manual", lang=lang),
|
||||
progress_percent=100,
|
||||
detail=t("workflow.fulfillment.upload_unknown_detail", lang=lang),
|
||||
)
|
||||
task.error_message = completed.error_message or 'RPA upload result unknown'
|
||||
log_task_event(task, "upload_rpa_unknown", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": task.error_message})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=task.error_message,
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
|
||||
task.upload_finished_at = datetime.utcnow()
|
||||
set_task_step_progress(
|
||||
|
||||
@@ -137,6 +137,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.fulfillment.rpa_uploaded_done": "RPA 已成功上传货代系统,任务已全部处理完毕。",
|
||||
"workflow.fulfillment.upload_failed_wait_manual": "货代上传失败,等待人工处理",
|
||||
"workflow.fulfillment.upload_failed_detail": "可重试上传或改为手工上传",
|
||||
"workflow.fulfillment.upload_unknown_wait_manual": "货代上传结果未知,必须人工核验后再处理",
|
||||
"workflow.fulfillment.upload_unknown_detail": "文件可能已提交但未能从页面确认结果;为避免重复上传,请人工核验货代系统后处理。",
|
||||
},
|
||||
"en": {
|
||||
"parse.title": "[Shipping notice parsed] Task: {task_no}",
|
||||
@@ -260,6 +262,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.fulfillment.rpa_uploaded_done": "RPA uploaded to the freight system successfully. The task is fully completed.",
|
||||
"workflow.fulfillment.upload_failed_wait_manual": "Freight upload failed. Waiting for manual handling.",
|
||||
"workflow.fulfillment.upload_failed_detail": "You may retry the upload or switch to manual upload.",
|
||||
"workflow.fulfillment.upload_unknown_wait_manual": "Freight upload result is unknown. Manual verification is required.",
|
||||
"workflow.fulfillment.upload_unknown_detail": "The file may have been submitted but the result could not be confirmed from the page. To avoid a duplicate upload, please verify the freight system manually.",
|
||||
},
|
||||
"th": {
|
||||
"parse.title": "【ยืนยันการแยกใบแจ้งส่งสินค้า】งาน: {task_no}",
|
||||
@@ -383,6 +387,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.fulfillment.rpa_uploaded_done": "RPA อัปโหลดเข้าระบบขนส่งสำเร็จแล้ว และงานเสร็จสมบูรณ์",
|
||||
"workflow.fulfillment.upload_failed_wait_manual": "อัปโหลดเข้าระบบขนส่งล้มเหลว กำลังรอให้คนจัดการต่อ",
|
||||
"workflow.fulfillment.upload_failed_detail": "สามารถลองอัปโหลดใหม่หรือเปลี่ยนเป็นอัปโหลดด้วยตนเองได้",
|
||||
"workflow.fulfillment.upload_unknown_wait_manual": "ผลการอัปโหลดขนส่งไม่ทราบแน่ชัด ต้องให้คนตรวจสอบก่อนดำเนินการ",
|
||||
"workflow.fulfillment.upload_unknown_detail": "ไฟล์อาจถูกส่งไปแล้วแต่ไม่สามารถยืนยันผลจากหน้าเว็บได้ เพื่อหลีกเลี่ยงการอัปโหลดซ้ำ กรุณาตรวจสอบระบบขนส่งด้วยตนเอง",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -75,6 +75,9 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
|
||||
'report_path_json': dict(source.report_path_json or {}),
|
||||
'query_parameters_json': list(source.query_parameters_json or []),
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
# 连接级受控上传配置(受限 JSON):Worker 用 login_url 登录后访问 upload_config.entry_url 上传页,
|
||||
# 平台差异(文件选择、提交与结果判定)由 Worker 受控 Adapter 固化。
|
||||
'upload_config_json': profile.upload_config_json,
|
||||
# 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。
|
||||
'navigation': source_navigation,
|
||||
'parameters': list(source.query_parameters_json or []),
|
||||
|
||||
@@ -1150,6 +1150,12 @@ def list_freight_notice_groups_for_task(
|
||||
'business_no': business_no,
|
||||
'po_number': po_number,
|
||||
'upload_status': notice.upload_status,
|
||||
'upload_mode': notice.upload_mode,
|
||||
'upload_attempt': notice.upload_attempt,
|
||||
'upload_error_code': notice.upload_error_code,
|
||||
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
|
||||
'upload_error_message': (notice.upload_error_message or notice.error_message or '')[:500] or None,
|
||||
'pending_human_reason': notice.pending_human_reason,
|
||||
'export_file_name': notice.export_file_name,
|
||||
'available_actions': available_actions,
|
||||
'lines': _notice_line_summary_for_task(notice),
|
||||
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -259,36 +260,86 @@ def write_inventory_export_trigger_for_task(
|
||||
)
|
||||
|
||||
|
||||
def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]:
|
||||
def write_upload_trigger(
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
payload: dict[str, Any] | None = None,
|
||||
*,
|
||||
attempt_id: int | None = None,
|
||||
artifact_id: int | None = None,
|
||||
connector_type: str | None = None,
|
||||
upload_config: dict[str, Any] | None = None,
|
||||
upload_config_hash: str | None = None,
|
||||
login_url: str | None = None,
|
||||
credential_envelope: dict[str, Any] | None = None,
|
||||
callback_id: str | None = None,
|
||||
business_no: str | None = None,
|
||||
) -> tuple[str | None, str | None, str | None]:
|
||||
"""
|
||||
复制 Excel 至上传队列并写入 RPA 上传触发 JSON。
|
||||
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
||||
【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。
|
||||
|
||||
触发文件固化本次上传契约快照,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 执行。
|
||||
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
export_file_path: 待上传发货 Excel 的服务端路径。
|
||||
payload: 附加字段(如 mode),与下列具名参数合并。
|
||||
attempt_id: 本次 Upload Attempt 主键。
|
||||
artifact_id: 当前上传目标 Artifact 主键。
|
||||
connector_type: 业务连接类型(dbs / crane)。
|
||||
upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。
|
||||
upload_config_hash: 该快照的 sha256,用于审计关联。
|
||||
login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。
|
||||
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
||||
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
||||
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
||||
|
||||
Returns:
|
||||
tuple[str | None, str | None]: (queue 文件路径, trigger 文件路径);失败时 (None, None)。
|
||||
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
||||
失败时 (None, None, None)。
|
||||
"""
|
||||
queue = upload_queue_dir()
|
||||
trigger_dir = upload_trigger_dir()
|
||||
if not queue or not trigger_dir:
|
||||
return None, None
|
||||
return None, None, None
|
||||
queue.mkdir(parents=True, exist_ok=True)
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
src = Path(export_file_path)
|
||||
if not src.is_file():
|
||||
return None, None
|
||||
dest = queue / f"{task_no}_{src.name}"
|
||||
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)
|
||||
|
||||
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
||||
body = {
|
||||
"action": "shipment_upload",
|
||||
"schema_version": "shipping_notice_upload_rpa.v1",
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"artifact_id": artifact_id,
|
||||
"callback_id": resolved_callback_id,
|
||||
"connector_type": str(connector_type or '').strip() or None,
|
||||
"upload_config": upload_config,
|
||||
"upload_config_hash": upload_config_hash,
|
||||
"login_url": login_url,
|
||||
"credential_envelope": credential_envelope,
|
||||
"file_path": str(dest),
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
trigger_path = trigger_dir / f"upload_{task_no}.json"
|
||||
trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return str(dest), str(trigger_path)
|
||||
_write_trigger_json_atomic(trigger_path, body)
|
||||
return str(dest), str(trigger_path), resolved_callback_id
|
||||
|
||||
|
||||
def find_latest_inventory_file() -> Path | None:
|
||||
|
||||
@@ -112,11 +112,44 @@ def has_verified_upload_success(task: ShippingNotice) -> bool:
|
||||
).first() is not None
|
||||
|
||||
|
||||
def _normalize_callback_result(result: str | None, success: bool) -> str:
|
||||
"""将回调结果归一化为三态 success / failed / unknown。
|
||||
|
||||
result 显式给定则按其校验;否则由 success 布尔推导(success→success,其余→failed)。
|
||||
"""
|
||||
if result is not None:
|
||||
normalized = str(result or '').strip().lower()
|
||||
if normalized not in {'success', 'failed', 'unknown'}:
|
||||
raise ValidationError(
|
||||
'result must be success, failed or unknown',
|
||||
code='SHIPPING.UPLOAD_RESULT_INVALID',
|
||||
)
|
||||
return normalized
|
||||
return 'success' if success else 'failed'
|
||||
|
||||
|
||||
def complete_attempt(
|
||||
attempt: ShippingUploadAttempt, *, success: bool, callback_id: str,
|
||||
freight_ref_no: str | None = None, error_message: str | None = None,
|
||||
result: str | None = None,
|
||||
) -> ShippingUploadAttempt:
|
||||
"""幂等落库 RPA 回调;失败或过期 Attempt 绝不能覆盖已经成功的 Artifact。"""
|
||||
"""幂等落库 RPA 回调;失败或过期 Attempt 绝不能覆盖已经成功的 Artifact。
|
||||
|
||||
Args:
|
||||
attempt: 本次上传尝试。
|
||||
success: 兼容布尔标记;schema 迁移期仍保留,由 result 优先。
|
||||
callback_id: 回调幂等键(唯一)。
|
||||
freight_ref_no: 成功时货代回执号。
|
||||
error_message: 失败/未知时的脱敏错误信息。
|
||||
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
|
||||
|
||||
Returns:
|
||||
ShippingUploadAttempt: 已更新状态的 Attob。
|
||||
|
||||
Raises:
|
||||
ConflictError: 回调身份冲突、过期回调或不可接受的 Attempt 状态。
|
||||
ValidationError: 缺 callback_id / artifact / 非法 result。
|
||||
"""
|
||||
callback = str(callback_id or '').strip()
|
||||
if not callback:
|
||||
raise ValidationError('callback_id is required', code='SHIPPING.UPLOAD_CALLBACK_REQUIRED')
|
||||
@@ -134,10 +167,11 @@ def complete_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)
|
||||
attempt.callback_id = callback
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
task = db.session.get(ShippingNotice, artifact.task_id)
|
||||
if success:
|
||||
if result_status == 'success':
|
||||
attempt.status = 'succeeded'
|
||||
attempt.freight_ref_no = str(freight_ref_no or '').strip() or None
|
||||
artifact.status = 'uploaded'
|
||||
@@ -153,9 +187,20 @@ def complete_attempt(
|
||||
else:
|
||||
# A missing callback may conceal a completed freight submission. A late
|
||||
# transport error is not enough to safely release or retry that Artifact.
|
||||
if attempt.status in {'timed_out', 'unknown'} and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
|
||||
# unknown 结果既不允许自动重试,也不强制改 upload_status(迟到的成功回调可解除)。
|
||||
already_unknown_before = attempt.status in {'timed_out', 'unknown'}
|
||||
if result_status == 'unknown' or (
|
||||
already_unknown_before
|
||||
and not str(error_message or '').strip().lower().startswith('freight_rejected:')
|
||||
):
|
||||
attempt.status = 'unknown'
|
||||
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
|
||||
attempt.error_message = str(error_message or 'Upload result remains unknown')[:500]
|
||||
# 逐单状态展示:未知结果仍须在 Notice 上保留失败原因(不强制改 upload_status,
|
||||
# 因为迟到的成功回调仍可解除该未知态)。
|
||||
if task is not None:
|
||||
task.upload_error_code = attempt.error_code
|
||||
task.upload_error_message = attempt.error_message
|
||||
db.session.flush()
|
||||
return attempt
|
||||
attempt.status = 'failed'
|
||||
@@ -165,6 +210,9 @@ def complete_attempt(
|
||||
artifact.status = 'ready'
|
||||
if task is not None:
|
||||
task.upload_status = 'failed'
|
||||
# 逐单状态展示:把失败原因落到 Notice,供「按发货通知单展示状态」读取。
|
||||
task.upload_error_code = attempt.error_code
|
||||
task.upload_error_message = message
|
||||
db.session.flush()
|
||||
return attempt
|
||||
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""
|
||||
services/shipping_notice/upload_config_validation.py
|
||||
|
||||
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
|
||||
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
|
||||
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
|
||||
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
|
||||
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
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)。
|
||||
|
||||
Args:
|
||||
connector_type: 连接类型,仅允许 dbs / crane。
|
||||
raw: 管理端提交的原始上传配置对象。
|
||||
|
||||
Returns:
|
||||
dict | None: 规范化受限 JSON;未配置时返回 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
|
||||
enabled=true 但缺少上传或结果判定所需字段。
|
||||
"""
|
||||
normalized_connector = _normalize_text(connector_type).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
|
||||
|
||||
|
||||
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
|
||||
"""对规范化上传配置计算稳定 sha256;供审计关联每次上传所用的确切快照。"""
|
||||
if not config:
|
||||
return None
|
||||
payload = json.dumps(config, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(payload.encode('ascii')).hexdigest()
|
||||
Reference in new issue
Block a user