feat: 新增交通银行数据导出插件及测试通道机制
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0077 携程数据导出 - 检票员检票报表导出(纯接口,自包含)。
|
||||
|
||||
链路(2026-11 实测):
|
||||
statisticsSupport(管理端 token 换 authCode/appId/sign/timestamp/userCode/corpCode)
|
||||
→ verifySaasAuthCode(换报表平台 JWT)
|
||||
→ preview(取 reportDetailId 与 reportColumnList)
|
||||
→ searchFilter(查询,判 total)
|
||||
→ total > 0 才 newExport(下载 xlsx 二进制)。
|
||||
|
||||
日期口径固定:昨天 00:00:00 ~ 今天 23:59:59;
|
||||
查询无数据(total 为 0 或缺失)直接跳过导出,返回 {"total": 0, "file": ""}。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import requests
|
||||
|
||||
from .. import config
|
||||
from . import lotsmall_login
|
||||
|
||||
|
||||
class AuthError(RuntimeError):
|
||||
"""账密错误/配置缺失:不可重试(避免锁号)。"""
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
# ==================== 报表平台会话 ====================
|
||||
def _report_session():
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": config.UA,
|
||||
"Origin": config.REPORT_BASE,
|
||||
"Referer": config.REPORT_BASE + "/",
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
def _verify_saas(session, auth_code, app_id):
|
||||
"""authCode/appId 换报表平台 JWT。"""
|
||||
resp = session.get(config.REPORT_BASE + config.API_VERIFY_SAAS,
|
||||
params={"authCode": auth_code, "appId": app_id},
|
||||
timeout=config.TIMEOUT)
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f"verifySaasAuthCode 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
result = body.get("result") or {}
|
||||
jwt = (result.get("token") or result.get("accessToken")
|
||||
or (body.get("data") or {}).get("token"))
|
||||
if not jwt:
|
||||
raise RuntimeError(f"未取到 JWT:{str(body)[:300]}")
|
||||
return jwt
|
||||
|
||||
|
||||
def _auth_headers(info, app_id, jwt):
|
||||
"""报表平台后续接口统一请求头(除 JWT 外还要带 authCode/appId/timestamp/sign)。"""
|
||||
return {
|
||||
"authCode": info["authCode"],
|
||||
"appId": app_id,
|
||||
"timestamp": str(info["timestamp"]),
|
||||
"sign": info["sign"],
|
||||
"Authorization": jwt,
|
||||
"Content-Type": "application/json",
|
||||
"Origin": config.REPORT_BASE,
|
||||
"Referer": config.REPORT_BASE + "/",
|
||||
}
|
||||
|
||||
|
||||
def _preview(session, info, app_id, headers):
|
||||
"""取报表元数据:reportDetailId 与 reportColumnList。"""
|
||||
params = {
|
||||
"authCode": info["authCode"],
|
||||
"appId": app_id,
|
||||
"sign": info["sign"],
|
||||
"timestamp": info["timestamp"],
|
||||
"userCode": info.get("bigDataLoginAuthCode"),
|
||||
"corpCode": info.get("corpCode"),
|
||||
"terminalTpe": 0,
|
||||
}
|
||||
url = config.REPORT_BASE + config.API_PREVIEW.format(report_id=config.REPORT_ID)
|
||||
resp = session.get(url, params=params, headers=headers, timeout=config.TIMEOUT)
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f"preview 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
result = body.get("result") or {}
|
||||
detail_id = result.get("reportDetailId") or result.get("id")
|
||||
columns = result.get("reportColumnList") or []
|
||||
if not detail_id:
|
||||
raise RuntimeError(f"preview 未返回 reportDetailId:{str(body)[:300]}")
|
||||
return detail_id, columns
|
||||
|
||||
|
||||
def _query_body(info, app_id, detail_id, columns, begin, end):
|
||||
"""searchFilter / newExport 共用请求体(newExport 再追加 reportColumnFilterList)。"""
|
||||
return {
|
||||
"shareMode": 0,
|
||||
"reportType": 0,
|
||||
"id": detail_id,
|
||||
"params": {
|
||||
"terminalTpe": config.TERMINAL_TPE,
|
||||
"merchant_id": config.MERCHANT_ID,
|
||||
"userInfoId": config.USER_INFO_ID,
|
||||
"corpCode": info.get("corpCode"),
|
||||
"appId": app_id,
|
||||
"userCode": info.get("bigDataLoginAuthCode"),
|
||||
"subAccountId": config.SUB_ACCOUNT_ID,
|
||||
"roleType": config.ROLE_TYPE,
|
||||
"pageIndex": config.PAGE_INDEX,
|
||||
"pageSize": config.PAGE_SIZE,
|
||||
"beginTradeDate": begin,
|
||||
"endTradeDate": end,
|
||||
"id": str(config.REPORT_ID),
|
||||
},
|
||||
"reportColumnDisplayList": columns,
|
||||
}
|
||||
|
||||
|
||||
def _search(session, headers, body):
|
||||
"""查询报表,返回 total(0 或缺省即无数据)。"""
|
||||
resp = session.post(config.REPORT_BASE + config.API_SEARCH,
|
||||
headers=headers, json=body, timeout=config.TIMEOUT)
|
||||
try:
|
||||
result = (resp.json() or {}).get("result") or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f"searchFilter 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
items = result.get("reportSearchList") or []
|
||||
first = items[0] if items else {}
|
||||
try:
|
||||
total = int(first.get("total") or 0)
|
||||
except (TypeError, ValueError):
|
||||
total = 0
|
||||
_log(f"查询结果:total={total},rows={len(first.get('rows') or [])}"
|
||||
f"({config.PAGE_SIZE} 条/页仅用于探测,导出为全量)")
|
||||
return total
|
||||
|
||||
|
||||
def _export(session, headers, body, save_dir):
|
||||
"""下载 xlsx 并落盘,返回文件路径。"""
|
||||
resp = session.post(config.REPORT_BASE + config.API_EXPORT,
|
||||
headers=headers, json=body, timeout=config.DOWNLOAD_TIMEOUT)
|
||||
if resp.content[:2] != b'PK':
|
||||
raise RuntimeError(f"导出返回非 xlsx(HTTP {resp.status_code}):{resp.text[:300]}")
|
||||
cd = resp.headers.get("content-disposition") or ""
|
||||
if "filename=" in cd:
|
||||
server_name = cd.split("filename=", 1)[1].strip().strip('"')
|
||||
_log(f"服务端文件名:{urllib.parse.unquote(server_name)}")
|
||||
path = os.path.join(save_dir, config.export_filename())
|
||||
with open(path, 'wb') as f:
|
||||
f.write(resp.content)
|
||||
_log(f"导出完成 → {path}({len(resp.content)} bytes)")
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def run_export(account, password, save_dir=''):
|
||||
"""查询并导出「检票员检票报表」。
|
||||
|
||||
返回:{'total': 查询总数, 'file': 落盘路径(无数据时为空字符串)}
|
||||
登录/接口失败抛 RuntimeError(账密错误立即停止,不重试)。
|
||||
"""
|
||||
save_dir = (save_dir or '').strip().strip('"') or config.default_output_dir()
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
begin, end = config.date_window()
|
||||
_log(f"日期区间:{begin} ~ {end}")
|
||||
_log(f"保存目录:{save_dir}")
|
||||
config.progress(5)
|
||||
|
||||
last_err = None
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
# 1) 登录(优先复用缓存 token)
|
||||
login = lotsmall_login.ensure_login(account, password, force=(attempt > 1))
|
||||
if not login.get("success"):
|
||||
msg = login.get("message") or "登录失败"
|
||||
if "账号或密码错误" in msg or "缺失" in msg:
|
||||
raise AuthError(msg)
|
||||
raise RuntimeError(f"登录失败:{msg}")
|
||||
info = lotsmall_login.fetch_report_params(login.get("token"))
|
||||
if not info:
|
||||
raise RuntimeError("取不到报表接入参数(token 可能已失效)")
|
||||
app_id = str(info.get("appId") or config.APP_ID_DEFAULT)
|
||||
for key in ("authCode", "sign", "timestamp"):
|
||||
if not info.get(key):
|
||||
raise RuntimeError(f"statisticsSupport 缺少 {key}:{str(info)[:300]}")
|
||||
config.progress(25)
|
||||
|
||||
# 2) 换 JWT → preview
|
||||
session = _report_session()
|
||||
jwt = _verify_saas(session, info["authCode"], app_id)
|
||||
headers = _auth_headers(info, app_id, jwt)
|
||||
detail_id, columns = _preview(session, info, app_id, headers)
|
||||
_log(f"报表元数据:reportDetailId={detail_id},列数={len(columns)}")
|
||||
config.progress(45)
|
||||
|
||||
# 3) 查询判有无数据(无数据跳过导出)
|
||||
body = _query_body(info, app_id, detail_id, columns, begin, end)
|
||||
total = _search(session, headers, body)
|
||||
if total <= 0:
|
||||
_log("查询无数据,跳过导出")
|
||||
config.progress(100)
|
||||
return {'total': 0, 'file': ''}
|
||||
config.progress(65)
|
||||
|
||||
# 4) 导出
|
||||
body["reportColumnFilterList"] = [{"reportDetailId": detail_id}]
|
||||
path = _export(session, headers, body, save_dir)
|
||||
config.progress(100)
|
||||
return {'total': total, 'file': path}
|
||||
except AuthError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
_log(f"第 {attempt}/{config.RETRY_MAX} 次导出失败:{e}", "WARN")
|
||||
time.sleep(1)
|
||||
|
||||
raise RuntimeError(f"检票员检票报表导出失败(重试 {config.RETRY_MAX} 次耗尽):{last_err}")
|
||||
Reference in New Issue
Block a user