feat: 新增交通银行数据导出插件及测试通道机制
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""交通银行数据导出 - webhost 场景插件(XQ0076)
|
||||
|
||||
流程(纯接口,不点页面):
|
||||
1) 账密自动登录商户服务门户(政策页同意 + 跳过 APP 扫码授权全自动;交行 token 在 sessionStorage,
|
||||
关浏览器即失效,故每次运行都要登一次),并 hook 页面请求捕获正式 JWT;
|
||||
2) 注入国密通道(借用页面自带 KeyouCryptography:SM4-ECB + SM2 签名),
|
||||
接口:MSNGTQ/0002 查明细 → 有无数据判定 → MSNGTO/0012 提交导出 →
|
||||
0013 轮询状态 → downloadMchtFile 取 OSS 直链 → 下载 zip → 解压 csv;
|
||||
3) 全程限流(默认 1s/次,轮询 3s),避免触发银行风控。
|
||||
"""
|
||||
import datetime
|
||||
import os
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import bank_api, bank_export, bank_login
|
||||
|
||||
|
||||
def _parse_date(text):
|
||||
return datetime.datetime.strptime(str(text).strip(), config.DATE_FMT).date()
|
||||
|
||||
|
||||
def resolve_range(fields):
|
||||
"""计算导出区间(date 对象,含首尾)。
|
||||
|
||||
优先级:`date_from` 有值 → 按自定义区间;
|
||||
否则按 `date_mode`:yesterday=昨天单日 / today=今天单日 /
|
||||
month_to_today=本月1日至今 / **prev_today(默认)= 昨天 ~ 今天(时间段)**。
|
||||
"""
|
||||
today = datetime.date.today()
|
||||
raw_from = str(fields.get('date_from') or '').strip()
|
||||
raw_to = str(fields.get('date_to') or '').strip()
|
||||
if raw_from:
|
||||
d0 = _parse_date(raw_from)
|
||||
d1 = _parse_date(raw_to) if raw_to else d0
|
||||
if d1 < d0:
|
||||
d0, d1 = d1, d0
|
||||
return d0, d1
|
||||
|
||||
mode = str(fields.get('date_mode') or 'prev_today').strip().lower()
|
||||
if mode == 'today':
|
||||
return today, today
|
||||
if mode == 'yesterday':
|
||||
y = today - datetime.timedelta(days=1)
|
||||
return y, y
|
||||
if mode == 'month_to_today':
|
||||
return today.replace(day=1), today
|
||||
# 默认:昨天 ~ 今天(与页面不选日期时的默认时间段一致)
|
||||
return today - datetime.timedelta(days=1), today
|
||||
|
||||
|
||||
def _diagnose_decrypt(page):
|
||||
"""DEBUG 专用:让页面自己发一次交易流水查询,捕获它真实的响应解密方式。
|
||||
|
||||
背景:我们手动加密的请求服务端能受理(返回合法密文),但响应解密参数与请求不同,
|
||||
需要观察页面自身解密调用(方法名 / 入参 / 密钥)才能对齐。
|
||||
"""
|
||||
config.log('【诊断】开始捕获页面自身的响应解密方式…', 'WARN')
|
||||
try:
|
||||
page.get(config.SITE_URL + '#/' + config.TRADE_HASH)
|
||||
time.sleep(8)
|
||||
bank_api.diagnose_init(page)
|
||||
clicked = False
|
||||
for el in page.eles('tag:button'):
|
||||
try:
|
||||
if el.states.is_displayed and ''.join((el.text or '').split()) == '查询':
|
||||
el.click()
|
||||
clicked = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
config.log(f'【诊断】页面查询按钮点击:{clicked}', 'WARN')
|
||||
time.sleep(10)
|
||||
report = bank_api.diagnose_report(page)
|
||||
if not report:
|
||||
config.log('【诊断】未捕获到解密调用(解密可能封装在闭包内,非 window 对象方法)', 'WARN')
|
||||
for it in report:
|
||||
config.log(f"【诊断】{it.get('t')} args={it.get('a')} ret={it.get('r')}", 'WARN')
|
||||
except Exception as e:
|
||||
config.log(f'【诊断】异常:{e}', 'WARN')
|
||||
|
||||
|
||||
class BankCommExportPlugin(ScenePlugin):
|
||||
id = 'xq0076'
|
||||
name = '交通银行数据导出'
|
||||
version = '1.2.4'
|
||||
description = ('交通银行商户服务门户(merchantapp.bankcomm.com)商户验券交易流水导出:'
|
||||
'账密自动登录(政策同意 + 跳过扫码全自动),接口查询判有无数据后导出,'
|
||||
'下载 zip 并解压 csv(GBK),全程限流')
|
||||
platform = '' # 交行自带账密登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ['xq0076']
|
||||
permissions = {'platforms': []}
|
||||
# 与 plugin.json.fields 一致
|
||||
fields = {
|
||||
'username': {'type': 'string', 'title': '登录账号', 'default': '',
|
||||
'description': '手机号 / BOC / MER 账号'},
|
||||
'password': {'type': 'string', 'title': '商服密码', 'default': '',
|
||||
'description': '商户服务门户登录密码(明文存本地配置)'},
|
||||
'date_mode': {'type': 'string', 'title': '日期口径', 'default': 'prev_today',
|
||||
'description': 'prev_today=昨天~今天(默认)/ yesterday=昨天单日 / today=今天 / month_to_today=本月至今 / custom=自定义'},
|
||||
'date_from': {'type': 'string', 'title': '开始日期', 'default': '',
|
||||
'description': 'yyyy-MM-dd;留空=按日期口径(默认昨天~今天)'},
|
||||
'date_to': {'type': 'string', 'title': '结束日期', 'default': '',
|
||||
'description': 'yyyy-MM-dd;留空=与开始日期同一天'},
|
||||
'save_dir': {'type': 'string', 'title': '保存目录', 'default': '',
|
||||
'description': '留空=D:\\资料\\银行\\交通银行数据导出'},
|
||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_debug(bool(fields.get('debug_mode')))
|
||||
|
||||
username = str(fields.get('username') or '').strip()
|
||||
password = str(fields.get('password') or '').strip()
|
||||
if not (username and password):
|
||||
raise RuntimeError('请在插件界面填写交行商户门户的登录账号与商服密码')
|
||||
|
||||
d0, d1 = resolve_range(fields)
|
||||
save_dir = str(fields.get('save_dir') or '').strip().strip('"') or config.default_output_dir()
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
# 商户号由门户页面自动识别(默认已带),商户账号就是登录账号,界面不再开放填写
|
||||
mcht_id = ''
|
||||
mcht_acc = username
|
||||
|
||||
config.log(f'导出区间:{d0} ~ {d1}')
|
||||
config.log(f'保存目录:{save_dir}')
|
||||
config.progress(5)
|
||||
|
||||
page = bank_login.open_browser()
|
||||
try:
|
||||
login = bank_login.ensure_login(page, username, password)
|
||||
if not login.get('success'):
|
||||
raise RuntimeError(f"登录失败:{login.get('message')}")
|
||||
config.progress(25)
|
||||
|
||||
# 关键:SM4 key 与 SM2 私钥都是「会话级」的,必须让页面自己发一次请求把它们抓下来
|
||||
bank_api.install_capture(page)
|
||||
page.get(config.SITE_URL + '#/' + config.TRADE_HASH)
|
||||
time.sleep(config.PAGE_SETTLE + 3)
|
||||
bank_api.wait_session_keys(page, timeout=45)
|
||||
time.sleep(config.KEY_SETTLE) # 让刚才页面查询的限流窗口过去,避免 AM00049
|
||||
bank_api.install_auth_hook(page)
|
||||
try:
|
||||
bank_api.wait_token(page, timeout=60)
|
||||
except Exception as e:
|
||||
config.log(f'取登录票据失败:{e}', 'WARN')
|
||||
config.progress(35)
|
||||
|
||||
result = bank_export.export_trade_flow(
|
||||
page, d0, d1, save_dir=save_dir,
|
||||
mcht_id=mcht_id, mcht_acc=mcht_acc, tag='商户验券')
|
||||
config.progress(95)
|
||||
finally:
|
||||
if config.KEEP_BROWSER:
|
||||
config.log('浏览器已保留(下次运行可直接复用登录态,可手动关闭)')
|
||||
else:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
config.progress(100)
|
||||
if result.get('skipped'):
|
||||
return {
|
||||
'summary': f"无数据,未导出({d0} ~ {d1})",
|
||||
'detail': {'range': f'{d0} ~ {d1}', 'skipped': True, 'reason': result.get('reason')},
|
||||
'path': save_dir,
|
||||
}
|
||||
|
||||
files = [result.get('zip')] + list(result.get('csv') or [])
|
||||
return {
|
||||
'summary': f"商户验券流水导出完成:{os.path.basename(result.get('zip') or '')}",
|
||||
'detail': {
|
||||
'range': f'{d0} ~ {d1}',
|
||||
'zip': result.get('zip'),
|
||||
'csv': result.get('csv') or [],
|
||||
'size': result.get('size'),
|
||||
'task_id': result.get('task_id'),
|
||||
'state': result.get('state'),
|
||||
'files': files,
|
||||
'save_dir': save_dir,
|
||||
},
|
||||
'path': save_dir,
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(BankCommExportPlugin())
|
||||
@@ -0,0 +1,49 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0076 交通银行数据导出 插件打包脚本(统一规范版)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md。
|
||||
|
||||
用法(任意 cwd 均可):
|
||||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0076 交通银行数据导出\\_pack.py"
|
||||
随后发布(先进测试通道,人工验证后再转正):
|
||||
.venv\\Scripts\\python.exe tools\\agent_cli.py publish \
|
||||
dist-plugin\\xq0076_v<版本>.zip --id xq0076 --version <版本>
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_REPO_ROOT = _HERE.parents[2]
|
||||
_OUT_DIR = _REPO_ROOT / "dist-plugin"
|
||||
|
||||
_EXCLUDE_DIRS = {"ui-src", "node_modules", "__pycache__", ".git", ".idea", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
_EXCLUDE_SUFFIXES = (".pyc", ".pyo")
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid = manifest["id"]
|
||||
ver = manifest["version"]
|
||||
if manifest.get("ui") and not (_HERE / "ui" / "index.html").is_file():
|
||||
sys.exit(f"插件 {pid} 声明 ui=true 但缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
count = 0
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES \
|
||||
or p.suffix in _EXCLUDE_SUFFIXES:
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
count += 1
|
||||
print(f"已打包: {out}({count} 个文件,{out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,203 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0076 交通银行商户服务门户数据导出 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发 ctx.log,无 ctx 时回落 print)。
|
||||
|
||||
站点特征(2026-11 实测):
|
||||
- React + Ant Design SPA,hash 路由(#/login、#/main、#/MENU30060101);
|
||||
- 所有业务接口为国密信封(plainText+verify),**不做接口复刻**,全程浏览器 UI 自动化;
|
||||
- 登录 = 账密 + 隐私政策页同意 + 跳过 APP 扫码授权,扫码/验证码均无需(验证码框默认隐藏);
|
||||
- 导出 = 浏览器直接下载 zip(内含 responseData.csv 明细 + responseData3.csv 汇总,GBK 编码)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 站点与路由 ====================
|
||||
SITE_URL = 'https://merchantapp.bankcomm.com/mm/'
|
||||
LOGIN_URL = SITE_URL + '#/login'
|
||||
LOGIN_HASH = 'login' # hash 片段含 login 即仍在登录页
|
||||
MAIN_HASH = 'main'
|
||||
TRADE_HASH = 'MENU30060101' # 交易查询 → 交易流水(当前唯一探明报表)
|
||||
SUMMARY_HASH = 'MENU30060301' # 交易查询 → 交易汇总(UI 兜底入口,商户验券卡片有「查看详情」)
|
||||
|
||||
# ==================== 输出路径 ====================
|
||||
DEFAULT_SAVE_DIR = r'D:\资料\银行\交通银行数据导出'
|
||||
|
||||
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.environ.get('LOCALAPPDATA') or os.environ.get('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
def default_output_dir():
|
||||
return DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录(登录态跨次保留,不占用日常 Chrome 配置)。
|
||||
|
||||
⚠️ 交行 token 存 sessionStorage,关闭浏览器即失效,profile 只能省掉"重新输入账号密码"
|
||||
这一步的部分风控耗时,不能免登录;因此登录流程必须完整自动化。"""
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0076')
|
||||
|
||||
|
||||
def get_download_dir():
|
||||
"""浏览器下载暂存目录(导出 zip 先落这里,再归档到保存目录)。"""
|
||||
return os.path.join(_app_data_dir(), 'downloads', 'xq0076')
|
||||
|
||||
|
||||
# ==================== 页面选择器(集中管理,页面改版只改这里) ====================
|
||||
SEL_USERNAME = '#loginForm_username'
|
||||
SEL_PASSWORD = 'css:input[type="password"]'
|
||||
SEL_CAPTCHA = '#normal_login_verifyPhotoCode' # 图形验证码(默认隐藏,仅在风控触发时出现)
|
||||
SEL_DATE = 'css:input.ant-calendar-picker-input' # 两个:起、止
|
||||
|
||||
TXT_LOGIN_BTN = '登录'
|
||||
TXT_QUERY_BTN = '查询'
|
||||
TXT_EXPORT_BTN = '导出' # 页面实际文本为「导 出」,匹配时去空格
|
||||
TXT_SKIP_QR = '跳过' # 页面实际文本为「跳 过」
|
||||
TXT_CUSTOM_DATE = '自定义日期' # 汇总页切到自定义日期区间
|
||||
TXT_AGREE = ('同意', '我已阅读', '确认授权', '我知道了')
|
||||
|
||||
# UI 兜底通道等待(秒)
|
||||
UI_QUERY_WAIT = 8 # 汇总页点查询后等结果渲染
|
||||
|
||||
# ==================== 接口(纯接口模式,页面国密库加密) ====================
|
||||
# 所有业务接口都是 POST + body: plainText=<SM4密文hex>&verify=<SM2签名hex>
|
||||
API_QUERY = '/pmssMsfeMagWeb/MSNGTQ/0002' # 交易流水明细查询
|
||||
API_SUMMARY = '/pmssMsfeMagWeb/MSNGTQ/0004' # 交易汇总查询
|
||||
API_EXPORT_SUBMIT = '/pmssMsfeMagWeb/MSNGTO/0012' # 提交导出(返回 taskID/filename)
|
||||
API_EXPORT_STATUS = '/pmssMsfeMagWeb/MSNGTO/0013' # 查导出任务状态
|
||||
API_DOWNLOAD = '/pmssMsfeTdWeb/pub/file/downloadMchtFile' # 取 OSS 下载地址
|
||||
|
||||
# 前端硬编码的国密密钥(2026-11 从页面提取,逐字节验证过;平台改版需同步)
|
||||
SM4_KEY = '-przKWFqghZwz_SQ'
|
||||
SM2_PRIV = '48E83EC866CFE529D6583CCB97CA36B875D268BBA06EC02F6518049C69E82811'
|
||||
|
||||
# 业务类型:05=商户验券(优惠券);01/02 等为其它业务(页面「业务类型」下拉)
|
||||
BUSS_TYPE_COUPON = '05'
|
||||
TRADE_STATE_ALL = '01' # 交易状态 01=全部(页面默认)
|
||||
PAGE_TYPE = '01' # 导出页类型,页面固定传 01
|
||||
|
||||
# ==================== 限流(防止触发银行风控) ====================
|
||||
API_INTERVAL = 1.0 # 相邻两次接口调用最小间隔(秒)
|
||||
POLL_INTERVAL = 3.0 # 导出任务轮询间隔
|
||||
POLL_MAX = 40 # 轮询上限次数(3s * 40 = 120s)
|
||||
RATE_LIMIT_WAIT = 15 # 命中「交易发送过于频繁(AM00049)」后的退避秒数
|
||||
KEY_SETTLE = 5 # 捕获会话密钥(点过页面查询)后,发业务请求前先静置
|
||||
EXPORT_STATE_DONE = '3' # 导出任务完成态(实测 1=生成中、3=完成;2 出现在更早的批次里)
|
||||
EXPORT_STATE_DONE_SET = ('2', '3') # 视为「可下载」的状态集合
|
||||
DOWNLOAD_RETRY = 10 # 下载空文件时的重试次数
|
||||
PAGE_SIZE_QUERY = 10 # 明细查询每页条数(仅用于探测有无数据)
|
||||
|
||||
# ==================== 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3
|
||||
POLICY_LOAD_WAIT = 1.5 # 政策页出现后等待渲染稳定(秒)
|
||||
POLICY_WAIT = 5 # 政策页滚到底后等倒计时,实测约 5s「同意」才可点
|
||||
|
||||
# 浏览器复用:交行 token 在 sessionStorage,关浏览器即失效;
|
||||
# 保持浏览器不关 + 固定端口,下次运行可直接复用登录态(免账号密码登录)
|
||||
BROWSER_PORT = 9333
|
||||
KEEP_BROWSER = True
|
||||
LOGIN_WAIT = 300 # 登录全流程等待上限(含政策页人工兜底)
|
||||
CAPTCHA_WAIT = 180 # 图形验证码人工输入等待
|
||||
PAGE_SETTLE = 3 # 页面渲染稳定等待
|
||||
DOWNLOAD_TIMEOUT = 300 # 单次导出下载超时(50 万笔可能较慢)
|
||||
HEADLESS = False # 登录需可见浏览器
|
||||
|
||||
DATE_FMT = '%Y-%m-%d'
|
||||
TIME_FMT = '%Y-%m-%d %H:%M'
|
||||
|
||||
# ==================== 全局钩子(由插件入口注入 ctx) ====================
|
||||
_LOG = None
|
||||
_PROGRESS = None
|
||||
_DEBUG = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _LOG
|
||||
_LOG = fn
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
global _PROGRESS
|
||||
_PROGRESS = fn
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _DEBUG
|
||||
_DEBUG = bool(flag)
|
||||
|
||||
|
||||
def log(msg, level='INFO'):
|
||||
if _LOG:
|
||||
try:
|
||||
_LOG(msg, level)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
print(f'[{level}] {msg}', flush=True)
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _PROGRESS:
|
||||
try:
|
||||
_PROGRESS(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def debug(msg):
|
||||
if _DEBUG:
|
||||
log(msg, 'DEBUG')
|
||||
|
||||
|
||||
def debug_enabled():
|
||||
return _DEBUG
|
||||
|
||||
|
||||
# ==================== 浏览器窗口(全屏 + 置顶) ====================
|
||||
def apply_window_mode(page):
|
||||
"""全屏 + 置顶:登录/政策页需要用户看得见,且规避遮挡导致的截图/渲染超时。"""
|
||||
try:
|
||||
page.set.window.full()
|
||||
except Exception as e:
|
||||
log(f'设置窗口全屏失败(忽略):{e}', 'WARN')
|
||||
if os.name == 'nt':
|
||||
try:
|
||||
_set_topmost(page.process_id)
|
||||
except Exception as e:
|
||||
log(f'设置窗口置顶失败(忽略):{e}', 'WARN')
|
||||
|
||||
|
||||
def _set_topmost(pid):
|
||||
if not pid:
|
||||
return
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
user32.IsWindowVisible.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
||||
|
||||
hwnds = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
def _collect(hwnd, _lparam):
|
||||
if user32.IsWindowVisible(hwnd) and user32.GetWindowTextLengthW(hwnd) > 0:
|
||||
proc = wintypes.DWORD()
|
||||
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(proc))
|
||||
if proc.value == pid:
|
||||
hwnds.append(hwnd)
|
||||
return True
|
||||
|
||||
user32.EnumWindows.argtypes = [ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM),
|
||||
wintypes.LPARAM]
|
||||
user32.EnumWindows(_collect, 0)
|
||||
|
||||
user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int,
|
||||
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint]
|
||||
for hwnd in hwnds:
|
||||
user32.SetWindowPos(hwnd, wintypes.HWND(-1), 0, 0, 0, 0, 0x0001 | 0x0002)
|
||||
@@ -0,0 +1,139 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0076 数据层公共工具(按钮定位 / 登录页判定 / 点击等待)。
|
||||
|
||||
交行页面是 Ant Design,按钮文本常带中文空格("登 录" / "导 出" / "跳 过"),
|
||||
且 xpath 中文匹配易翻车,统一改为「遍历 tag:button + 去空格文本比对」。
|
||||
"""
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def norm(text):
|
||||
"""去所有空白,便于「登 录」==「登录」比较。"""
|
||||
return ''.join(str(text or '').split())
|
||||
|
||||
|
||||
def is_login_page(page):
|
||||
url = (getattr(page, 'url', '') or '').lower()
|
||||
return config.LOGIN_HASH in url
|
||||
|
||||
|
||||
def is_displayed(el):
|
||||
"""真实可见性判断。
|
||||
|
||||
不能用 el.states.is_displayed 一个条件:交行把「图形验证码」放在
|
||||
`<div style="display:none">` 里,DP 仍判 True,导致误报"检测到验证码"。
|
||||
这里追加「渲染尺寸 > 0」校验(隐藏元素 rect 为 0 或取不到)。
|
||||
"""
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
try:
|
||||
w, h = el.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_button(page, text, timeout=8, contains=False, only_enabled=True):
|
||||
"""按去空格后的文本找按钮;找不到返回 None。
|
||||
|
||||
contains=True 时按包含匹配("同意" 命中 "我已阅读并同意")。
|
||||
"""
|
||||
target = norm(text)
|
||||
deadline = time.time() + timeout
|
||||
while True:
|
||||
try:
|
||||
for b in page.eles('tag:button'):
|
||||
try:
|
||||
if not is_displayed(b):
|
||||
continue
|
||||
label = norm(b.text)
|
||||
hit = (target in label) if contains else (label == target)
|
||||
if not hit:
|
||||
continue
|
||||
if only_enabled:
|
||||
try:
|
||||
if b.states.is_enabled is False:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
return b
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
if time.time() >= deadline:
|
||||
return None
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def click_button(page, text, timeout=8, contains=False):
|
||||
btn = find_button(page, text, timeout=timeout, contains=contains)
|
||||
if not btn:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
return True
|
||||
except Exception as e:
|
||||
config.log(f'点击「{text}」失败:{e}', 'WARN')
|
||||
return False
|
||||
|
||||
|
||||
def scroll_to_bottom(page, settle=2.0, fast=False):
|
||||
"""滚动到页面底部(政策页必须滚到底,同意按钮才可点)。
|
||||
|
||||
⚠️ 不用「瞬间 scrollTop = scrollHeight」:位置跳变太假,容易被风控识别。
|
||||
默认走浏览器原生平滑滚动(behavior='smooth'),再停留 settle 秒,
|
||||
观感与人工拖动一致;内部可滚动容器同样平滑滚动。
|
||||
fast=True 时退回直接置底(仅用于非登录场景)。
|
||||
"""
|
||||
if fast:
|
||||
try:
|
||||
page.scroll.to_bottom()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
return True
|
||||
|
||||
ok = False
|
||||
try:
|
||||
page.run_js("""
|
||||
var behavior = 'smooth';
|
||||
try { window.scrollTo({ top: document.body.scrollHeight, behavior: behavior }); }
|
||||
catch (e) { window.scrollTo(0, document.body.scrollHeight); }
|
||||
document.querySelectorAll('div, section, main, article').forEach(function (el) {
|
||||
try {
|
||||
if (el.scrollHeight > el.clientHeight + 40 && el.clientHeight > 120) {
|
||||
el.scrollTo({ top: el.scrollHeight, behavior: behavior });
|
||||
}
|
||||
} catch (e) {}
|
||||
});
|
||||
""")
|
||||
ok = True
|
||||
except Exception:
|
||||
try:
|
||||
page.scroll.to_bottom()
|
||||
ok = True
|
||||
except Exception:
|
||||
pass
|
||||
if settle:
|
||||
time.sleep(settle)
|
||||
return ok
|
||||
|
||||
|
||||
def wait_page_ready(page, keyword, timeout=20):
|
||||
"""等页面出现关键文本(等 SPA 渲染完成)。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
body = page.run_js('return document.body ? document.body.innerText : ""') or ''
|
||||
if keyword in body:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return False
|
||||
@@ -0,0 +1,525 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0076 交行接口通道(纯接口,借用页面国密库加密/签名)。
|
||||
|
||||
协议(2026-11 实测,密文与抓包逐字节一致):
|
||||
请求 body = plainText=<hex( SM4-ECB( PKCS5(明文JSON), key ) )>
|
||||
&verify=<hex( SM2.sign( UTF8(plainText的hex), privKey ) )>
|
||||
响应 body = {"plainText": "<base64 密文>"} → base64→hex→SM4 解密→去 PKCS5→明文 JSON
|
||||
鉴权 = Authorization: Bearer <JWT>(登录后由页面请求产生,hook 捕获)
|
||||
|
||||
加密/签名全部交给页面自带的 KeyouCryptography(window 上可见),不在 Python 侧重写国密,
|
||||
平台升级加密实现时可自动跟随;只有换 key/私钥/签名规则才需要跟版。
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
# ==================== 会话密钥捕获(关键) ====================
|
||||
# SM4 key 与 SM2 私钥都是「会话级」的:每次登录由服务端协商,与上一次不同。
|
||||
# 之前把某一次的 key 硬编码进来,只在那个会话有效 —— 这是响应解不开的根因。
|
||||
# 做法:页面加载前注入 hook,拦截页面自己的加解密调用,把当前会话的 key 抓下来。
|
||||
JS_CAPTURE = r"""
|
||||
(function () {
|
||||
window.__sess = window.__sess || { sm4: '', sm2: '' };
|
||||
function hook() {
|
||||
try {
|
||||
var K = window.KeyouCryptography;
|
||||
if (!K || !K.algorithm || !K.algorithm.SM4) return false;
|
||||
var SM4 = K.algorithm.SM4, SM2 = K.algorithm.SM2;
|
||||
var U = K.util.UTF8, H = K.util.Hex;
|
||||
if (!SM4.__hc) {
|
||||
SM4.__hc = true;
|
||||
var oe = SM4.encryptWithECB;
|
||||
SM4.encryptWithECB = function (p, k) {
|
||||
try { if (!window.__sess.sm4) window.__sess.sm4 = U.stringify(k); } catch (e) {}
|
||||
return oe.apply(this, arguments);
|
||||
};
|
||||
var od = SM4.decryptWithECB;
|
||||
SM4.decryptWithECB = function (d, k) {
|
||||
try { if (!window.__sess.sm4) window.__sess.sm4 = U.stringify(k); } catch (e) {}
|
||||
return od.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
if (SM2 && !SM2.__hc) {
|
||||
SM2.__hc = true;
|
||||
var os = SM2.sign;
|
||||
SM2.sign = function (m, p) {
|
||||
try { if (!window.__sess.sm2) window.__sess.sm2 = H.stringify(p); } catch (e) {}
|
||||
return os.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
return true;
|
||||
} catch (e) { return false; }
|
||||
}
|
||||
if (!hook()) {
|
||||
var t = setInterval(function () { if (hook()) clearInterval(t); }, 200);
|
||||
setTimeout(function () { clearInterval(t); }, 30000);
|
||||
}
|
||||
})();
|
||||
"""
|
||||
|
||||
_captured = {'sm4': '', 'sm2': ''}
|
||||
|
||||
|
||||
def install_capture(page):
|
||||
"""注册初始化脚本:每次页面加载都会注入「会话密钥捕获 + 鉴权捕获」hook。"""
|
||||
ok = False
|
||||
try:
|
||||
page.add_init_js(JS_CAPTURE)
|
||||
ok = True
|
||||
except Exception as e:
|
||||
config.log(f'注册会话密钥捕获脚本失败:{e}', 'WARN')
|
||||
try:
|
||||
page.add_init_js(JS_HOOK_AUTH)
|
||||
except Exception:
|
||||
pass
|
||||
return ok
|
||||
|
||||
|
||||
def wait_session_keys(page, timeout=40, trigger=True):
|
||||
"""捕获当前会话的 SM4/SM2 密钥。
|
||||
|
||||
两步保证:
|
||||
① 现在页面里直接注入 hook(页面已加载时 add_init_js 不生效);
|
||||
② 主动点一次页面「查询」,让页面自己走一遍「加密请求 → 解密响应」,hook 即拿到 key。
|
||||
"""
|
||||
try:
|
||||
page.run_js(JS_CAPTURE)
|
||||
except Exception as e:
|
||||
config.debug(f'注入密钥 hook 失败:{e}')
|
||||
if trigger:
|
||||
try:
|
||||
for el in page.eles('tag:button'):
|
||||
try:
|
||||
if el.states.is_displayed and ''.join((el.text or '').split()) == '查询':
|
||||
el.click()
|
||||
config.debug('已点页面「查询」触发密钥捕获')
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
raw = page.run_js('return JSON.stringify(window.__sess || {})')
|
||||
d = json.loads(raw) if raw else {}
|
||||
except Exception:
|
||||
d = {}
|
||||
if d.get('sm4'):
|
||||
_captured['sm4'] = d.get('sm4') or ''
|
||||
_captured['sm2'] = d.get('sm2') or ''
|
||||
config.log(f'已捕获会话密钥(SM4 {len(_captured["sm4"])} 字符'
|
||||
f",SM2 {len(_captured['sm2'])} 字符)")
|
||||
return dict(_captured)
|
||||
time.sleep(2)
|
||||
config.log('未捕获到会话密钥(回落到默认值,可能当前会话不匹配)', 'WARN')
|
||||
return {}
|
||||
|
||||
|
||||
# ==================== 页面注入:加密 + 签名 + 请求 + 解密 ====================
|
||||
JS_TOOLKIT = r"""
|
||||
if (!window.__bk) {
|
||||
window.__bk = {
|
||||
init: function () {
|
||||
var K = window.KeyouCryptography;
|
||||
if (!K) throw new Error('KeyouCryptography 未加载');
|
||||
this.SM4 = K.algorithm.SM4;
|
||||
this.SM2 = K.algorithm.SM2;
|
||||
this.PAD = K.util.DataPadding;
|
||||
this.H = K.util.Hex;
|
||||
this.U = K.util.UTF8;
|
||||
this.HP = K.util.Helper;
|
||||
this.KEY = this.U.parse(arguments[0]);
|
||||
this.PRIV = this.H.parse(arguments[1]);
|
||||
return true;
|
||||
},
|
||||
_dec: function (bytes, mode) {
|
||||
try {
|
||||
var out;
|
||||
if (mode === 'ECB') {
|
||||
out = this.SM4.decryptWithECB(bytes, this.KEY);
|
||||
} else if (mode === 'CBC_IV16') {
|
||||
out = this.SM4.decryptWithCBC(bytes.slice(16), this.KEY, bytes.slice(0, 16));
|
||||
} else {
|
||||
var z = [];
|
||||
for (var i = 0; i < 16; i++) z.push(0);
|
||||
out = this.SM4.decryptWithCBC(bytes, this.KEY, z);
|
||||
}
|
||||
var s = this.U.stringify(this.PAD.decodeWithPKCS5(out, 16));
|
||||
// 去掉首尾 BOM / 空白 / 控制字符(PKCS5 补位有时去不干净,尾部残留 \u0002)
|
||||
var t = String(s)
|
||||
.replace(/^[\s\u0000-\u001f\uFEFF]+/, '')
|
||||
.replace(/[\s\u0000-\u001f\uFEFF]+$/, '');
|
||||
if (t.charAt(0) === '{' || t.charAt(0) === '[') return t; // 必须是 JSON 才算成功
|
||||
} catch (e) {}
|
||||
return null;
|
||||
},
|
||||
_decodeResp: function (pt) {
|
||||
// 密文格式可能是 base64 也可能是 hex;模式可能是 ECB 也可能 CBC,逐一尝试
|
||||
var cands = [];
|
||||
try {
|
||||
var h1 = this.HP.b64tohex(pt);
|
||||
if (h1) cands.push(h1);
|
||||
} catch (e) {}
|
||||
if (/^[0-9A-Fa-f]+$/.test(pt) && pt.length % 2 === 0) cands.push(pt);
|
||||
var modes = ['ECB', 'CBC_IV16', 'CBC_ZERO'];
|
||||
for (var i = 0; i < cands.length; i++) {
|
||||
var bytes;
|
||||
try { bytes = this.H.parse(cands[i]); } catch (e) { continue; }
|
||||
for (var m = 0; m < modes.length; m++) {
|
||||
var r = this._dec(bytes, modes[m]);
|
||||
if (r !== null) {
|
||||
window.__decMode = modes[m] + '/' + (i === 0 ? 'b64' : 'hex');
|
||||
return r;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
call: function (path, obj) {
|
||||
var plain = JSON.stringify(obj);
|
||||
var ct = this.SM4.encryptWithECB(this.PAD.encodeWithPKCS5(this.U.parse(plain), 16), this.KEY);
|
||||
var ctHex = this.H.stringify(ct);
|
||||
var sig = this.SM2.sign(this.U.parse(ctHex), this.PRIV);
|
||||
var body = 'plainText=' + ctHex + '&verify=' + this.H.stringify(sig);
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', path, false);
|
||||
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
|
||||
xhr.setRequestHeader('Authorization', window.__auth || '');
|
||||
xhr.setRequestHeader('SecurityType', 'S');
|
||||
xhr.setRequestHeader('source', 'pc');
|
||||
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
||||
xhr.send(body);
|
||||
var raw = xhr.responseText || '';
|
||||
var o = null;
|
||||
try { o = JSON.parse(raw); } catch (e) { o = null; }
|
||||
if (o && typeof o === 'object' && o.plainText) {
|
||||
var dec = this._decodeResp(String(o.plainText));
|
||||
if (dec !== null) return dec;
|
||||
return 'ERR:decrypt-fail len=' + String(o.plainText).length +
|
||||
' ct=' + (xhr.getResponseHeader('Content-Type') || '') +
|
||||
' full=' + String(o.plainText).slice(0, 200);
|
||||
}
|
||||
if (o && typeof o === 'object') return raw; // 明文 JSON(如错误码)
|
||||
return 'ERR:non-json status=' + xhr.status +
|
||||
' ct=' + (xhr.getResponseHeader('Content-Type') || '') +
|
||||
' len=' + raw.length + ' head=' + raw.slice(0, 80);
|
||||
}
|
||||
};
|
||||
}
|
||||
return window.__bk.init(arguments[0], arguments[1]);
|
||||
"""
|
||||
|
||||
# 拦截页面所有请求的 Authorization(登录后页面自己发请求时会带上正式 JWT)
|
||||
JS_HOOK_AUTH = r"""
|
||||
if (!window.__authHook) {
|
||||
window.__authHook = true;
|
||||
window.__authList = window.__authList || [];
|
||||
var sh = XMLHttpRequest.prototype.setRequestHeader;
|
||||
XMLHttpRequest.prototype.setRequestHeader = function (k, v) {
|
||||
try {
|
||||
if (String(k).toLowerCase() === 'authorization' && v) {
|
||||
window.__authList.push(String(v));
|
||||
window.__auth = String(v);
|
||||
}
|
||||
} catch (e) {}
|
||||
return sh.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
return true;
|
||||
"""
|
||||
|
||||
JS_CALL = 'return window.__bk.call(arguments[0], arguments[1]);'
|
||||
|
||||
# ==================== 解密诊断(DEBUG 模式):hook 页面自身的解密调用 ====================
|
||||
# 用途:我们手动加密的请求服务端能受理,但响应解不开;让页面自己发一次请求,
|
||||
# 观察它到底调哪个 decrypt、用什么 key,从而确定正确的响应解密方式。
|
||||
JS_DIAG_HOOK = r"""
|
||||
window.__diag = [];
|
||||
function __hookDec(obj, path) {
|
||||
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) return;
|
||||
var names = [];
|
||||
try {
|
||||
var cur = obj, d = 0;
|
||||
while (cur && d < 3) {
|
||||
Object.getOwnPropertyNames(cur).forEach(function (n) { if (names.indexOf(n) < 0) names.push(n); });
|
||||
cur = Object.getPrototypeOf(cur); d++;
|
||||
}
|
||||
} catch (e) {}
|
||||
names.forEach(function (n) {
|
||||
if (!/decrypt|Decrypt|unseal|plainText|decodeResp/i.test(n)) return;
|
||||
var f;
|
||||
try { f = obj[n]; } catch (e) { return; }
|
||||
if (typeof f !== 'function') return;
|
||||
try {
|
||||
obj[n] = function () {
|
||||
var r = f.apply(this, arguments);
|
||||
try {
|
||||
var args = [];
|
||||
for (var i = 0; i < arguments.length; i++) {
|
||||
var a = arguments[i];
|
||||
args.push((a && typeof a === 'object') ? JSON.stringify(a).slice(0, 160) : String(a).slice(0, 160));
|
||||
}
|
||||
window.__diag.push({ t: path + '.' + n, a: args, r: String(r).slice(0, 180) });
|
||||
} catch (e) {}
|
||||
return r;
|
||||
};
|
||||
} catch (e) {}
|
||||
});
|
||||
}
|
||||
try {
|
||||
Object.keys(window).forEach(function (k) {
|
||||
try {
|
||||
var v = window[k];
|
||||
if (v && typeof v.getSessionData === 'function') __hookDec(v, 'win/' + k);
|
||||
} catch (e) {}
|
||||
});
|
||||
} catch (e) {}
|
||||
try { __hookDec(window.KeyouCryptography, 'Keyou'); } catch (e) {}
|
||||
try { __hookDec(window.KeyouCryptography && window.KeyouCryptography.algorithm, 'Keyou.alg'); } catch (e) {}
|
||||
try { __hookDec(window.CryptoJS, 'CryptoJS'); } catch (e) {}
|
||||
return 'ok';
|
||||
"""
|
||||
|
||||
|
||||
def diagnose_init(page):
|
||||
"""DEBUG 用:注入解密 hook(需在页面加载完成后调用)。"""
|
||||
try:
|
||||
page.run_js(JS_DIAG_HOOK)
|
||||
return True
|
||||
except Exception as e:
|
||||
config.log(f'注入解密诊断 hook 失败:{e}', 'WARN')
|
||||
return False
|
||||
|
||||
|
||||
def diagnose_report(page, limit=3):
|
||||
"""DEBUG 用:取回命中的解密调用。"""
|
||||
try:
|
||||
raw = page.run_js('return JSON.stringify((window.__diag || []).slice(0, 20))')
|
||||
return json.loads(raw) if raw else []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
_last_call_ts = [0.0]
|
||||
|
||||
|
||||
def _throttle():
|
||||
gap = config.API_INTERVAL - (time.time() - _last_call_ts[0])
|
||||
if gap > 0:
|
||||
time.sleep(gap)
|
||||
|
||||
|
||||
# ==================== 通道初始化 / 鉴权 ====================
|
||||
def init(page, sm4_key=None, priv=None):
|
||||
"""注入加密通道(需页面已加载出 KeyouCryptography)。
|
||||
|
||||
密钥优先用本次会话捕获到的值;捕获失败才回落到配置里的默认值。
|
||||
"""
|
||||
sm4 = sm4_key or _captured.get('sm4') or config.SM4_KEY
|
||||
priv = priv or _captured.get('sm2') or config.SM2_PRIV
|
||||
if not _captured.get('sm4'):
|
||||
config.log('警告:使用默认密钥(可能与本会话不匹配,解密会失败)', 'WARN')
|
||||
deadline = time.time() + 30
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
ok = page.run_js(JS_TOOLKIT, sm4, priv)
|
||||
if ok:
|
||||
config.log('国密通道已就绪')
|
||||
return True
|
||||
except Exception as e:
|
||||
config.debug(f'注入通道失败:{e}')
|
||||
time.sleep(1)
|
||||
raise RuntimeError('页面国密库未加载(KeyouCryptography 不存在),无法初始化接口通道')
|
||||
|
||||
|
||||
def install_auth_hook(page):
|
||||
page.run_js(JS_HOOK_AUTH)
|
||||
|
||||
|
||||
def _nudge(page):
|
||||
"""轻推一下页面(切菜单触发一次带鉴权的请求),用于页面空闲没有请求时补抓 token。"""
|
||||
try:
|
||||
for el in page.eles('tag:li'):
|
||||
try:
|
||||
if '交易汇总' in (el.text or '') and el.states.is_displayed:
|
||||
el.click()
|
||||
config.debug('已切到「交易汇总」触发鉴权请求')
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def wait_token(page, timeout=60):
|
||||
"""等页面发出带正式 JWT 的请求(跳过 temporary 临时票据)。"""
|
||||
start = time.time()
|
||||
nudged = False
|
||||
while time.time() - start < timeout:
|
||||
# ① 优先用「最近一次页面请求实际带的」票据(hook 每次请求都会刷新)
|
||||
try:
|
||||
cur = page.run_js('return window.__auth || ""') or ''
|
||||
except Exception:
|
||||
cur = ''
|
||||
if cur and 'temporary=' not in cur:
|
||||
config.log(f'已捕获登录票据({len(cur)} 字符,取最近请求)')
|
||||
return cur
|
||||
# ② 历史列表兜底
|
||||
try:
|
||||
lst = page.run_js('return JSON.stringify(window.__authList || [])')
|
||||
items = json.loads(lst) if lst else []
|
||||
except Exception:
|
||||
items = []
|
||||
for item in reversed(items):
|
||||
if item and 'temporary=' not in item:
|
||||
config.log(f'已捕获登录票据({len(item)} 字符)')
|
||||
# 必须写回 window.__auth:__bk.call 读的是它,登录过程中可能被临时票据覆盖
|
||||
try:
|
||||
page.run_js('window.__auth = arguments[0]; return true;', item)
|
||||
except Exception as e:
|
||||
config.debug(f'写回票据失败:{e}')
|
||||
return item
|
||||
# 15 秒还没抓到,主动切一次菜单触发请求
|
||||
if not nudged and time.time() - start > 15:
|
||||
nudged = True
|
||||
_nudge(page)
|
||||
time.sleep(2)
|
||||
# 兜底:当前 __auth
|
||||
cur = page.run_js('return window.__auth || ""') or ''
|
||||
if cur and 'temporary=' not in cur:
|
||||
return cur
|
||||
raise RuntimeError('未捕获到登录票据(Authorization),可能登录未完成')
|
||||
|
||||
|
||||
# ==================== 通用调用(限流 + 重试) ====================
|
||||
def call(page, path, payload, retry=None):
|
||||
"""调用一个业务接口,返回解密后的 dict。全局限流 + 重试。"""
|
||||
retry = retry or config.RETRY_MAX
|
||||
last_err = ''
|
||||
for attempt in range(1, retry + 1):
|
||||
_throttle()
|
||||
try:
|
||||
raw = page.run_js(JS_CALL, path, payload)
|
||||
except Exception as e:
|
||||
last_err = f'执行异常:{e}'
|
||||
time.sleep(config.API_INTERVAL)
|
||||
continue
|
||||
_last_call_ts[0] = time.time()
|
||||
if not raw:
|
||||
last_err = '空响应'
|
||||
continue
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception:
|
||||
last_err = f'响应异常:{str(raw)[:220]}'
|
||||
config.log(last_err, 'WARN')
|
||||
time.sleep(config.API_INTERVAL)
|
||||
continue
|
||||
code = str(data.get('RespCode') or '')
|
||||
msg = str(data.get('RespMsg') or '')
|
||||
# 银行侧限流:退避后重试(不要立刻重发,否则一直被拒)
|
||||
if code == 'AM00049' or '频繁' in msg:
|
||||
last_err = f'RespCode={code} {msg}(退避 {config.RATE_LIMIT_WAIT}s)'
|
||||
config.log(last_err, 'WARN')
|
||||
time.sleep(config.RATE_LIMIT_WAIT)
|
||||
continue
|
||||
if code == '000000':
|
||||
try:
|
||||
mode = page.run_js('return window.__decMode || ""')
|
||||
if mode:
|
||||
config.debug(f'响应解密方式:{mode}')
|
||||
except Exception:
|
||||
pass
|
||||
return data
|
||||
last_err = f"RespCode={code} {data.get('RespMsg') or ''}"
|
||||
# 业务错误(非系统异常)不重试
|
||||
if code and code not in ('999999', 'AM00040'):
|
||||
break
|
||||
time.sleep(config.API_INTERVAL)
|
||||
raise RuntimeError(f'接口 {path} 调用失败({attempt}/{retry}):{last_err}')
|
||||
|
||||
|
||||
# ==================== 业务接口 ====================
|
||||
def _fmt_start(d):
|
||||
return d.strftime('%Y%m%d') + '000000'
|
||||
|
||||
|
||||
def _fmt_end(d):
|
||||
return d.strftime('%Y%m%d') + '235959'
|
||||
|
||||
|
||||
def _base_payload(mcht_id, mcht_acc):
|
||||
return {
|
||||
'mchtId': mcht_id,
|
||||
'shopId': '',
|
||||
'mchtOrderNo': '',
|
||||
'bussType': config.BUSS_TYPE_COUPON,
|
||||
'tradeState': config.TRADE_STATE_ALL,
|
||||
'tradeType': '',
|
||||
'payType': '',
|
||||
'authNo': '',
|
||||
'tradeNo': '',
|
||||
'paycardNo': '',
|
||||
'mchtAcc': mcht_acc,
|
||||
}
|
||||
|
||||
|
||||
def query_trades(page, mcht_id, mcht_acc, date_from, date_to, page_index=1, page_size=None):
|
||||
"""交易流水明细查询(商户验券)。"""
|
||||
p = _base_payload(mcht_id, mcht_acc)
|
||||
p.update({
|
||||
'txnStartDate': _fmt_start(date_from),
|
||||
'txnEndDate': _fmt_end(date_to),
|
||||
'pageIndex': str(page_index),
|
||||
'pageSize': str(page_size or config.PAGE_SIZE_QUERY),
|
||||
})
|
||||
return call(page, config.API_QUERY, p)
|
||||
|
||||
|
||||
def submit_export(page, mcht_id, mcht_acc, date_from, date_to):
|
||||
"""提交导出,返回 {taskID, filename}。"""
|
||||
p = _base_payload(mcht_id, mcht_acc)
|
||||
p.update({
|
||||
'txnStartDate': _fmt_start(date_from),
|
||||
'txnEndDate': _fmt_end(date_to),
|
||||
'pageType': config.PAGE_TYPE,
|
||||
})
|
||||
data = call(page, config.API_EXPORT_SUBMIT, p)
|
||||
rd = data.get('responseData') or {}
|
||||
return {'task_id': rd.get('taskID') or '', 'filename': rd.get('filename') or ''}
|
||||
|
||||
|
||||
def check_export(page, mcht_id, task_ids):
|
||||
"""查导出任务状态,返回原始 responseData 列表。"""
|
||||
data = call(page, config.API_EXPORT_STATUS, {
|
||||
'mrchId': mcht_id,
|
||||
'pageType': config.PAGE_TYPE,
|
||||
'taskIdList': list(task_ids),
|
||||
})
|
||||
return data.get('responseData') or []
|
||||
|
||||
|
||||
def get_download_url(page, mcht_id):
|
||||
data = call(page, config.API_DOWNLOAD, {'mrchId': mcht_id, 'pageType': config.PAGE_TYPE})
|
||||
return data.get('downLoadUrl') or ''
|
||||
|
||||
|
||||
# ==================== 商户识别 ====================
|
||||
def detect_merchant(page):
|
||||
"""从页面文本解析 mchtId(15 位)与 mchtAcc(MER 账号)。"""
|
||||
try:
|
||||
txt = page.run_js('return document.body ? document.body.innerText : ""') or ''
|
||||
except Exception:
|
||||
txt = ''
|
||||
mcht_id = ''
|
||||
m = re.search(r'\b(\d{15})-[^\n]{2,40}', txt)
|
||||
if m:
|
||||
mcht_id = m.group(1)
|
||||
accs = re.findall(r'\b(MER\d{6,})\b', txt)
|
||||
mcht_acc = accs[0] if accs else ''
|
||||
return mcht_id, mcht_acc
|
||||
@@ -0,0 +1,421 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0076 交行「商户验券」交易流水导出。
|
||||
|
||||
双通道:
|
||||
A. 接口(快,5 秒级):MSNGTQ/0002 查有无数据 → MSNGTO/0012 提交导出 →
|
||||
0013 轮询 → downloadMchtFile 取 OSS 直链 → requests 下载。
|
||||
B. UI 兜底(慢,约 1 分钟):接口任一步失败自动切换——
|
||||
汇总页「商户验券」查看详情(业务类型/日期自动带过去)→ 流水页点「导 出」→
|
||||
浏览器自己下载(页面自己完成加解密),再从磁盘取文件。
|
||||
|
||||
两条路都以「zip 内 csv 是否有数据行」作为最终判定,无数据不保留空文件。
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
from .. import config
|
||||
from . import (click_button, find_button, is_displayed, wait_page_ready)
|
||||
from . import bank_api
|
||||
|
||||
# 银行 OSS 域名用老 TLS,verify=False 下载;抑制无害的 InsecureRequestWarning 噪音
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
|
||||
|
||||
|
||||
# ==================== 接口通道 ====================
|
||||
def has_data_probe(page, mcht_id, mcht_acc, date_from, date_to):
|
||||
"""查 1 条明细判断有无数据。返回 (是否有数据, 说明)。"""
|
||||
data = bank_api.query_trades(page, mcht_id, mcht_acc, date_from, date_to,
|
||||
page_index=1, page_size=1)
|
||||
rows = data.get('responseData') or []
|
||||
rd2 = data.get('responseData2') or {}
|
||||
total = ''
|
||||
if isinstance(rd2, dict):
|
||||
total = rd2.get('totalRow') or ''
|
||||
total = total or data.get('maxRow') or ''
|
||||
if rows:
|
||||
config.log(f'查询结果:有数据(总计 {total or "未知"} 条)')
|
||||
return True, f'总计 {total or "未知"} 条'
|
||||
config.log('查询结果:无数据,跳过导出')
|
||||
return False, '无数据'
|
||||
|
||||
|
||||
def _download(url, target_path, timeout=600):
|
||||
"""下载 OSS 直链(无需 Cookie/Authorization)。"""
|
||||
headers = {'User-Agent': UA, 'Referer': 'https://merchantapp.bankcomm.com/'}
|
||||
tmp = target_path + '.part'
|
||||
try:
|
||||
with requests.get(url, headers=headers, timeout=timeout, verify=False, stream=True) as r:
|
||||
r.raise_for_status()
|
||||
with open(tmp, 'wb') as f:
|
||||
for chunk in r.iter_content(1024 * 256):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
os.replace(tmp, target_path)
|
||||
return os.path.getsize(target_path)
|
||||
except Exception:
|
||||
try:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
# ==================== UI 兜底通道 ====================
|
||||
_JS_MARK = r"""
|
||||
var t = arguments[0];
|
||||
var p = document.querySelector('.ant-calendar-picker-container');
|
||||
if (!p || !p.offsetWidth) return 'no-panel';
|
||||
var tds = [].slice.call(p.querySelectorAll('td[title]'));
|
||||
for (var i = 0; i < tds.length; i++) {
|
||||
if ((tds[i].getAttribute('title') || '') === t) {
|
||||
var old = document.getElementById('__pick_day__');
|
||||
if (old) old.id = '';
|
||||
tds[i].id = '__pick_day__';
|
||||
return 'ok';
|
||||
}
|
||||
}
|
||||
return 'not-found';
|
||||
"""
|
||||
|
||||
_JS_STEP = r"""
|
||||
var dir = arguments[0];
|
||||
var p = document.querySelector('.ant-calendar-picker-container');
|
||||
if (!p) return false;
|
||||
var b = dir === 'next' ? p.querySelector('.ant-calendar-next-month-btn')
|
||||
: p.querySelector('.ant-calendar-prev-month-btn');
|
||||
if (b) { b.click(); return true; }
|
||||
return false;
|
||||
"""
|
||||
|
||||
|
||||
def _pick_day(page, idx, day):
|
||||
"""在日历面板上点选第 idx 个日期框(readonly 输入框只能面板点选)。"""
|
||||
boxes = [e for e in page.eles('css:input.ant-calendar-picker-input') if is_displayed(e)]
|
||||
if len(boxes) <= idx:
|
||||
return False
|
||||
try:
|
||||
boxes[idx].click()
|
||||
except Exception:
|
||||
return False
|
||||
time.sleep(1.0)
|
||||
title = f'{day.year}年{day.month}月{day.day}日'
|
||||
mark = page.run_js(_JS_MARK, title)
|
||||
steps = 0
|
||||
while mark == 'not-found' and steps < 24:
|
||||
page.run_js(_JS_STEP, 'prev')
|
||||
time.sleep(0.35)
|
||||
steps += 1
|
||||
mark = page.run_js(_JS_MARK, title)
|
||||
while mark == 'not-found' and steps < 48:
|
||||
page.run_js(_JS_STEP, 'next')
|
||||
time.sleep(0.35)
|
||||
steps += 1
|
||||
mark = page.run_js(_JS_MARK, title)
|
||||
if mark != 'ok':
|
||||
config.log(f'日历面板找不到 {title}', 'WARN')
|
||||
return False
|
||||
el = page.ele('#__pick_day__', timeout=3)
|
||||
if not el:
|
||||
return False
|
||||
el.click()
|
||||
time.sleep(0.8)
|
||||
try:
|
||||
page.run_js("var e=document.getElementById('__pick_day__'); if(e) e.id='';")
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _csv_has_rows(zip_path):
|
||||
"""检查 zip 内明细 csv 是否有数据行(>1 行 = 有数据)。"""
|
||||
try:
|
||||
with zipfile.ZipFile(zip_path) as zf:
|
||||
for name in zf.namelist():
|
||||
if not name.lower().endswith('.csv'):
|
||||
continue
|
||||
raw = zf.read(name)
|
||||
try:
|
||||
text = raw.decode('gbk', 'replace')
|
||||
except Exception:
|
||||
text = raw.decode('utf-8', 'replace')
|
||||
lines = [ln for ln in text.splitlines() if ln.strip()]
|
||||
config.debug(f'{name}: {len(lines)} 行')
|
||||
if 'responseData' in name and len(lines) > 1:
|
||||
return True, name, len(lines) - 1
|
||||
except Exception as e:
|
||||
config.log(f'检查 zip 内容失败:{e}', 'WARN')
|
||||
return False, '', 0
|
||||
|
||||
|
||||
def _select_all_stores(page):
|
||||
"""汇总页「门店名称」多选里勾「全选」(不选的话汇总卡片没数据,查看详情不跳转)。"""
|
||||
try:
|
||||
multi = page.ele('css:.ant-select-selection--multiple', timeout=10)
|
||||
except Exception:
|
||||
multi = None
|
||||
if not multi:
|
||||
config.log('未找到门店多选框,跳过全选', 'WARN')
|
||||
return False
|
||||
try:
|
||||
multi.click()
|
||||
time.sleep(1.2)
|
||||
hit = False
|
||||
for wrap in page.eles('css:.ant-select-dropdown .ant-checkbox-wrapper'):
|
||||
try:
|
||||
if '全选' in ''.join((wrap.text or '').split()):
|
||||
inp = wrap.ele('css:input.ant-checkbox-input')
|
||||
try:
|
||||
checked = bool(inp.states.is_checked)
|
||||
except Exception:
|
||||
checked = False
|
||||
if not checked:
|
||||
inp.click()
|
||||
time.sleep(1)
|
||||
config.log('已勾选「全选」门店')
|
||||
hit = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
# 收起下拉:只用 JS 在页面标题区触发 mousedown(antd 靠 document mousedown 关闭)。
|
||||
# ⚠️ 不能用坐标点「空白处」——左侧菜单就在那里,会误点「退款审批」等菜单跳转。
|
||||
try:
|
||||
page.run_js("""
|
||||
try {
|
||||
var el = document.querySelector('.org_bottom_title')
|
||||
|| document.querySelector('.ant-breadcrumb')
|
||||
|| document.body;
|
||||
el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
|
||||
el.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
|
||||
} catch (e) {}
|
||||
""")
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return hit
|
||||
except Exception as e:
|
||||
config.log(f'门店全选失败:{e}', 'WARN')
|
||||
return False
|
||||
|
||||
|
||||
def export_via_ui(page, date_from, date_to, save_dir, tag='商户验券'):
|
||||
"""UI 兜底:汇总页商户验券「查看详情」→ 流水页「导 出」→ 浏览器下载。"""
|
||||
config.log('改用页面 UI 导出(接口通道不可用)…')
|
||||
dl_dir = config.get_download_dir()
|
||||
os.makedirs(dl_dir, exist_ok=True)
|
||||
try:
|
||||
page.set.download_path(dl_dir)
|
||||
page.set.when_download_file_exists('rename')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ① 交易汇总页
|
||||
page.get(config.SITE_URL + '#/' + config.SUMMARY_HASH)
|
||||
time.sleep(config.PAGE_SETTLE + 2)
|
||||
if not wait_page_ready(page, '交易汇总', timeout=25):
|
||||
config.log('汇总页未就绪,重试', 'WARN')
|
||||
page.get(config.SITE_URL)
|
||||
time.sleep(2)
|
||||
page.get(config.SITE_URL + '#/' + config.SUMMARY_HASH)
|
||||
time.sleep(config.PAGE_SETTLE + 2)
|
||||
|
||||
# ② 门店全选(不选则卡片无数据,查看详情不跳转)
|
||||
_select_all_stores(page)
|
||||
|
||||
# ③ 自定义日期 + 面板选日期
|
||||
if click_button(page, config.TXT_CUSTOM_DATE, timeout=8):
|
||||
time.sleep(1.5)
|
||||
_pick_day(page, 0, date_from)
|
||||
_pick_day(page, 1, date_to)
|
||||
|
||||
# ④ 查询
|
||||
click_button(page, config.TXT_QUERY_BTN, timeout=8)
|
||||
time.sleep(config.UI_QUERY_WAIT)
|
||||
|
||||
# ④ 点「商户验券」卡片的查看详情(页面第 2 个)
|
||||
# 等汇总卡片渲染稳定(加载完通常是 9 个「查看详情」,未加载完只有 3 个)
|
||||
details = []
|
||||
last = -1
|
||||
stable = 0
|
||||
deadline = time.time() + 30
|
||||
while time.time() < deadline:
|
||||
details = [b for b in page.eles('css:button.onClickShowDetail') if is_displayed(b)]
|
||||
if len(details) == last and len(details) >= 2:
|
||||
stable += 1
|
||||
if stable >= 2:
|
||||
break
|
||||
else:
|
||||
stable = 0
|
||||
last = len(details)
|
||||
time.sleep(1.5)
|
||||
config.log(f'汇总页可见「查看详情」{len(details)} 个')
|
||||
if len(details) < 2:
|
||||
raise RuntimeError('汇总页未找到「商户验券」查看详情按钮(页面可能未加载完)')
|
||||
details[1].click()
|
||||
|
||||
# 必须确认真的跳到交易流水页,否则会误点导出拿到「交易汇总.xlsx」
|
||||
jumped = False
|
||||
deadline = time.time() + 30
|
||||
while time.time() < deadline:
|
||||
if config.TRADE_HASH in (page.url or ''):
|
||||
jumped = True
|
||||
break
|
||||
time.sleep(1)
|
||||
if not jumped:
|
||||
raise RuntimeError(f'点「商户验券-查看详情」未跳转到交易流水页(当前 {page.url}),已中止避免导错文件')
|
||||
config.log(f'已进入交易流水页:{page.url}')
|
||||
time.sleep(config.PAGE_SETTLE + 1)
|
||||
|
||||
# ⑤ 点导出,等浏览器下载
|
||||
before = set(os.listdir(dl_dir))
|
||||
btn = find_button(page, config.TXT_EXPORT_BTN, timeout=20)
|
||||
if not btn:
|
||||
raise RuntimeError('流水页找不到「导出」按钮')
|
||||
btn.click()
|
||||
config.log('已点击「导 出」,等待浏览器下载…')
|
||||
|
||||
path = None
|
||||
deadline = time.time() + config.DOWNLOAD_TIMEOUT
|
||||
while time.time() < deadline:
|
||||
news = [n for n in os.listdir(dl_dir)
|
||||
if n not in before and not n.endswith('.crdownload')]
|
||||
if news:
|
||||
candidate = os.path.join(dl_dir, news[-1])
|
||||
size = os.path.getsize(candidate)
|
||||
time.sleep(1.5)
|
||||
if os.path.getsize(candidate) == size and size > 0:
|
||||
path = candidate
|
||||
break
|
||||
time.sleep(1.5)
|
||||
if not path:
|
||||
raise RuntimeError(f'{config.DOWNLOAD_TIMEOUT}s 内未捕获到浏览器下载')
|
||||
|
||||
config.log(f'下载完成:{os.path.basename(path)}({os.path.getsize(path)} 字节)')
|
||||
|
||||
# ⑥ 检查有无数据 + 归档
|
||||
has_rows, name, rows = _csv_has_rows(path)
|
||||
if not has_rows:
|
||||
config.log('导出文件无数据行,不保留文件', 'WARN')
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return {'skipped': True, 'reason': '导出文件无数据行', 'note': '无数据'}
|
||||
|
||||
stamp = time.strftime('%Y%m%d_%H%M%S')
|
||||
safe_range = f'{date_from.strftime("%Y%m%d")}-{date_to.strftime("%Y%m%d")}'
|
||||
base = f'交通银行_{tag}_{safe_range}_{stamp}'
|
||||
final_zip = os.path.join(save_dir, base + '.zip')
|
||||
shutil.move(path, final_zip)
|
||||
config.log(f'已归档:{final_zip}(明细 {rows} 行)')
|
||||
csv_files = _unzip_csv(final_zip, save_dir, base)
|
||||
return {'skipped': False, 'zip': final_zip, 'csv': csv_files,
|
||||
'size': os.path.getsize(final_zip), 'rows': rows,
|
||||
'range': f'{date_from} ~ {date_to}', 'via': 'ui'}
|
||||
|
||||
|
||||
def _unzip_csv(zip_path, save_dir, base):
|
||||
out = []
|
||||
try:
|
||||
with zipfile.ZipFile(zip_path) as zf:
|
||||
for name in zf.namelist():
|
||||
if not name.lower().endswith('.csv'):
|
||||
continue
|
||||
target = os.path.join(save_dir, f'{base}_{os.path.basename(name)}')
|
||||
with zf.open(name) as src, open(target, 'wb') as dst:
|
||||
shutil.copyfileobj(src, dst)
|
||||
out.append(target)
|
||||
if out:
|
||||
config.log(f'已解压 {len(out)} 个 csv(GBK 编码,Excel 可直接打开)')
|
||||
except Exception as e:
|
||||
config.log(f'解压 csv 失败(zip 已保留):{e}', 'WARN')
|
||||
return out
|
||||
|
||||
|
||||
# ==================== 主流程(接口优先,失败自动回退 UI) ====================
|
||||
def export_trade_flow(page, date_from, date_to, save_dir=None,
|
||||
mcht_id='', mcht_acc='', tag='商户验券'):
|
||||
save_dir = save_dir or config.default_output_dir()
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
try:
|
||||
bank_api.init(page)
|
||||
if not (mcht_id and mcht_acc):
|
||||
did, dacc = bank_api.detect_merchant(page)
|
||||
mcht_id = mcht_id or did
|
||||
mcht_acc = mcht_acc or dacc
|
||||
if not (mcht_id and mcht_acc):
|
||||
raise RuntimeError('未能识别商户号(mchtId/mchtAcc)')
|
||||
config.log(f'商户:{mcht_id} / {mcht_acc}')
|
||||
|
||||
ok, note = has_data_probe(page, mcht_id, mcht_acc, date_from, date_to)
|
||||
if not ok:
|
||||
return {'skipped': True, 'reason': '查询无数据,未导出', 'note': note}
|
||||
|
||||
sub = bank_api.submit_export(page, mcht_id, mcht_acc, date_from, date_to)
|
||||
task_id = sub.get('task_id')
|
||||
if not task_id:
|
||||
raise RuntimeError(f'提交导出未返回 taskID:{sub}')
|
||||
config.log(f'已提交导出任务:{task_id}')
|
||||
|
||||
# taskstate 语义不稳定(实测 1=生成中、3=完成,不同批次可能不同),
|
||||
# 所以只查一次记录状态,**以「能否下载到有效 zip」作为完成判据**,避免死等。
|
||||
state = None
|
||||
for i in range(1, config.POLL_MAX + 1):
|
||||
try:
|
||||
time.sleep(config.POLL_INTERVAL if i > 1 else 2)
|
||||
items = bank_api.check_export(page, mcht_id, [task_id])
|
||||
hit = next((it for it in items if str(it.get('taskID') or '') == task_id), None)
|
||||
if hit is not None:
|
||||
state = str(hit.get('taskstate'))
|
||||
config.debug(f'轮询 {i}/{config.POLL_MAX}:taskstate={state}')
|
||||
if state in config.EXPORT_STATE_DONE_SET:
|
||||
break
|
||||
except Exception as e:
|
||||
config.debug(f'查任务状态失败(不影响下载):{e}')
|
||||
break
|
||||
config.log(f'导出任务状态:taskstate={state}')
|
||||
|
||||
stamp = time.strftime('%Y%m%d_%H%M%S')
|
||||
safe_range = f'{date_from.strftime("%Y%m%d")}-{date_to.strftime("%Y%m%d")}'
|
||||
base = f'交通银行_{tag}_{safe_range}_{stamp}'
|
||||
final_zip = os.path.join(save_dir, base + '.zip')
|
||||
|
||||
# 文件未生成完时 OSS 上是 0 字节,需要重试下载
|
||||
size = 0
|
||||
for attempt in range(1, config.DOWNLOAD_RETRY + 1):
|
||||
url = bank_api.get_download_url(page, mcht_id)
|
||||
if not url:
|
||||
time.sleep(config.POLL_INTERVAL)
|
||||
continue
|
||||
config.log(f'下载地址已获取:{url[-60:]}')
|
||||
try:
|
||||
size = _download(url, final_zip)
|
||||
except Exception as e:
|
||||
config.log(f'第 {attempt} 次下载失败:{e}', 'WARN')
|
||||
size = 0
|
||||
if size > 0 and zipfile.is_zipfile(final_zip):
|
||||
break
|
||||
config.log(f'文件尚未生成({size} 字节),{config.POLL_INTERVAL}s 后重试…', 'WARN')
|
||||
time.sleep(config.POLL_INTERVAL)
|
||||
if not size or not zipfile.is_zipfile(final_zip):
|
||||
raise RuntimeError('导出文件未生成(下载得到空文件或非 zip),可稍后重试')
|
||||
config.log(f'已下载:{final_zip}({size} 字节)')
|
||||
|
||||
has_rows, _, rows = _csv_has_rows(final_zip)
|
||||
csv_files = _unzip_csv(final_zip, save_dir, base)
|
||||
return {'skipped': False, 'zip': final_zip, 'csv': csv_files, 'size': size,
|
||||
'task_id': task_id, 'state': state, 'rows': rows,
|
||||
'range': f'{date_from} ~ {date_to}', 'via': 'api'}
|
||||
|
||||
except Exception as e:
|
||||
config.log(f'接口通道失败({e}),自动回退页面 UI 导出', 'WARN')
|
||||
return export_via_ui(page, date_from, date_to, save_dir, tag=tag)
|
||||
@@ -0,0 +1,440 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0076 交行商户服务门户登录模块(账密自动登录,零接口复刻)。
|
||||
|
||||
站点登录链路(2026-11 实测,DOM 由业务侧提供确认):
|
||||
1. 登录页填「手机号/BOC/MER账号」+「商服密码」(图形验证码默认隐藏,触发时才需人工);
|
||||
2. 点「登 录」→ 弹出隐私政策**新标签页**:滚动到底 → 等倒计时结束 → 点「同意」;
|
||||
3. 回到门户后出现 APP 扫码授权页 → 点「跳 过」→ 弹框「是否确定跳过?」→ 点「确 认」;
|
||||
4. 进入 #/main(交易查询等菜单可用)。
|
||||
|
||||
注意:交行 token 存 sessionStorage,关闭浏览器即失效,所以每次运行都要走一遍上述流程;
|
||||
「跳过扫码」只影响验券/收银功能,不影响报表导出。
|
||||
"""
|
||||
import random
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
from . import (click_button, find_button, is_displayed, is_login_page, norm,
|
||||
scroll_to_bottom)
|
||||
|
||||
# 密码错误的页面提示关键词
|
||||
_ERR_KEYWORDS = ('密码错误', '账号或密码', '账户或密码', '密码不正确', '账号不存在', '已被锁定')
|
||||
|
||||
|
||||
def open_browser():
|
||||
"""启动/复用可见浏览器(独立固定 profile)。
|
||||
|
||||
优先连接上次运行保留的浏览器实例(固定端口):交行 token 在 sessionStorage,
|
||||
只要浏览器不关就能复用登录态,免去每次输账号密码。
|
||||
"""
|
||||
# ① 复用上次保留的浏览器
|
||||
try:
|
||||
page = ChromiumPage(f'127.0.0.1:{config.BROWSER_PORT}')
|
||||
page.run_js('return 1')
|
||||
config.log('复用上次保留的浏览器实例(登录态可能仍有效)')
|
||||
return page
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
try:
|
||||
co.set_local_port(config.BROWSER_PORT)
|
||||
except Exception:
|
||||
pass
|
||||
co.set_argument('--start-maximized')
|
||||
try:
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
except Exception:
|
||||
pass
|
||||
co.set_user_data_path(config.get_browser_profile_dir())
|
||||
try:
|
||||
co.set_download_path(config.get_download_dir())
|
||||
except Exception:
|
||||
pass
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.set.download_path(config.get_download_dir())
|
||||
page.set.when_download_file_exists('rename')
|
||||
except Exception as e:
|
||||
config.debug(f'设置下载目录失败(忽略):{e}')
|
||||
if not config.HEADLESS:
|
||||
config.apply_window_mode(page)
|
||||
return page
|
||||
|
||||
|
||||
# ==================== 登录态判定 ====================
|
||||
def logged_in(page):
|
||||
try:
|
||||
url = (page.url or '')
|
||||
except Exception:
|
||||
return False
|
||||
low = url.lower()
|
||||
if config.LOGIN_HASH in low:
|
||||
return False
|
||||
if config.MAIN_HASH in low or 'MENU' in low:
|
||||
return True
|
||||
# 兜底:登录页的表单还在 → 未登录
|
||||
try:
|
||||
if page.ele(config.SEL_USERNAME, timeout=0.5):
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 表单填写 ====================
|
||||
def _fill_username(page, username):
|
||||
box = page.ele(config.SEL_USERNAME, timeout=15)
|
||||
if not box:
|
||||
config.log('找不到账号输入框', 'ERROR')
|
||||
return False
|
||||
try:
|
||||
cur = (box.value or '') if hasattr(box, 'value') else ''
|
||||
except Exception:
|
||||
cur = ''
|
||||
if cur.strip() == username.strip():
|
||||
config.log('账号已预填,跳过输入')
|
||||
return True
|
||||
box.clear()
|
||||
box.input(username)
|
||||
time.sleep(random.uniform(0.4, 0.9)) # 人工式停顿,避免瞬间填完
|
||||
config.log('已填写账号')
|
||||
return True
|
||||
|
||||
|
||||
def _fill_password(page, password):
|
||||
"""页面有多个 password 输入(登录 / 首次改密表单),只填可见的那个。"""
|
||||
deadline = time.time() + 10
|
||||
box = None
|
||||
while time.time() < deadline and box is None:
|
||||
for el in page.eles(config.SEL_PASSWORD):
|
||||
if is_displayed(el):
|
||||
box = el
|
||||
break
|
||||
if box is None:
|
||||
time.sleep(0.5)
|
||||
if box is None:
|
||||
config.log('找不到密码输入框', 'ERROR')
|
||||
return False
|
||||
try:
|
||||
box.clear()
|
||||
box.input(password)
|
||||
time.sleep(random.uniform(0.5, 1.1))
|
||||
config.log('已填写密码')
|
||||
return True
|
||||
except Exception as e:
|
||||
config.log(f'填写密码失败:{e}', 'ERROR')
|
||||
return False
|
||||
|
||||
|
||||
def _check_terms(page):
|
||||
"""勾选「选择登录即代表激活账号,并同意《商户服务产品隐私权政策》」。
|
||||
|
||||
未勾选时点「登 录」页面不会提交(表现为"卡住"),必须先勾。
|
||||
勾选框 id 固定为 #normal_login_remember。
|
||||
"""
|
||||
box = None
|
||||
try:
|
||||
box = page.ele('#normal_login_remember', timeout=5)
|
||||
except Exception:
|
||||
box = None
|
||||
if box is None:
|
||||
config.log('未找到隐私政策勾选框(页面可能改版)', 'WARN')
|
||||
return False
|
||||
try:
|
||||
if box.states.is_checked:
|
||||
config.debug('隐私政策已勾选')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
box.click()
|
||||
time.sleep(random.uniform(0.8, 1.4))
|
||||
if box.states.is_checked:
|
||||
config.log('已勾选「同意隐私权政策」')
|
||||
return True
|
||||
# 兜底:点整行 label(勾选框可能被遮挡)
|
||||
for wrapper in page.eles('css:.confirmRules .ant-checkbox-wrapper'):
|
||||
try:
|
||||
wrapper.click()
|
||||
time.sleep(0.5)
|
||||
if box.states.is_checked:
|
||||
config.log('已勾选「同意隐私权政策」(label 兜底)')
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
except Exception as e:
|
||||
config.log(f'勾选隐私政策失败:{e}', 'WARN')
|
||||
config.log('隐私政策勾选框仍未选中,继续尝试登录', 'WARN')
|
||||
return False
|
||||
|
||||
|
||||
def _wait_captcha(page):
|
||||
"""图形验证码默认隐藏;若被风控触发则暂停等人工输入。返回是否已就绪。"""
|
||||
try:
|
||||
cap = page.ele(config.SEL_CAPTCHA, timeout=1)
|
||||
except Exception:
|
||||
cap = None
|
||||
if not cap or not is_displayed(cap):
|
||||
return True
|
||||
config.log('检测到图形验证码,请在浏览器窗口手动输入(脚本最多等 %ds)' % config.CAPTCHA_WAIT, 'WARN')
|
||||
deadline = time.time() + config.CAPTCHA_WAIT
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if (cap.value or '').strip():
|
||||
config.log('验证码已输入,继续')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
config.log('等待验证码输入超时', 'ERROR')
|
||||
return False
|
||||
|
||||
|
||||
def _page_text(tab):
|
||||
try:
|
||||
return tab.run_js('return document.body ? document.body.innerText : ""') or ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
# ==================== 登录后流程(政策页 / 跳过扫码 / 弹框确认) ====================
|
||||
def _all_tabs(page):
|
||||
tabs = []
|
||||
try:
|
||||
for tid in page.tab_ids:
|
||||
try:
|
||||
tabs.append(page.get_tab(tid))
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
tabs = [page]
|
||||
if not tabs:
|
||||
tabs = [page]
|
||||
return tabs
|
||||
|
||||
|
||||
def _find_agree_btn(tab):
|
||||
"""在指定标签里找「同意」元素(排除「不同意」)。
|
||||
|
||||
交行政策页的同意不是 button,而是:
|
||||
<div class="signBtnWrap">
|
||||
<div class="disagree">不同意</div>
|
||||
<div class="signBtn canSignBtn">同意</div>
|
||||
</div>
|
||||
所以选择器必须覆盖 div.signBtn / .canSignBtn。
|
||||
"""
|
||||
for sel in ('css:.signBtnWrap .signBtn', 'css:.signBtn', 'css:.canSignBtn',
|
||||
'tag:button', 'tag:a', 'css:div[class*="agree"], div[class*="signBtn"]'):
|
||||
try:
|
||||
for el in tab.eles(sel):
|
||||
try:
|
||||
if not is_displayed(el):
|
||||
continue
|
||||
txt = norm(el.text)
|
||||
if txt and '同意' in txt and '不同意' not in txt:
|
||||
return el
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _policy_agree_btn(tab):
|
||||
"""政策页专用取按钮:只在「已解锁」时返回,未解锁返回 None(继续等)。
|
||||
|
||||
解锁标志 = class 里出现 canSignBtn(倒计时结束由页面自己加)。
|
||||
"""
|
||||
try:
|
||||
has_wrap = bool(tab.eles('css:.signBtnWrap'))
|
||||
except Exception:
|
||||
has_wrap = False
|
||||
if not has_wrap:
|
||||
return _find_agree_btn(tab) # 不是该结构 → 通用兜底
|
||||
for sel in ('css:.signBtnWrap .canSignBtn', 'css:.canSignBtn'):
|
||||
try:
|
||||
for el in tab.eles(sel):
|
||||
try:
|
||||
if is_displayed(el) and '同意' in norm(el.text):
|
||||
return el
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _is_policy_tab(tab):
|
||||
"""判断某标签是不是隐私政策全文页(长文本 + 隐私/协议关键词)。
|
||||
|
||||
登录页虽然也含「隐私权政策」字样,但正文很短,用长度门槛区分。
|
||||
"""
|
||||
try:
|
||||
body = _page_text(tab)
|
||||
except Exception:
|
||||
return False
|
||||
if not body or len(body) < 600:
|
||||
return False
|
||||
return ('隐私' in body) or ('协议' in body) or ('条款' in body)
|
||||
|
||||
|
||||
def _handle_policy(page, budget=25):
|
||||
"""处理隐私政策全文页:滚到底 → 等倒计时 5 秒 → 点「同意」。
|
||||
|
||||
形态:勾选登录页「同意隐私权政策」后弹出新标签/新窗口(或当前页跳转)。
|
||||
- 滚动走浏览器原生平滑滚动(瞬间跳底容易被风控识别);
|
||||
- 每页只滚一次,滚完静置 POLICY_WAIT 秒等同意按钮解锁(实测约 5s)。
|
||||
"""
|
||||
end = time.time() + budget
|
||||
scrolled = set()
|
||||
while time.time() < end:
|
||||
if logged_in(page):
|
||||
return True
|
||||
|
||||
for tab in _all_tabs(page):
|
||||
try:
|
||||
if not _is_policy_tab(tab):
|
||||
continue
|
||||
tid = getattr(tab, 'tab_id', None)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if tid not in scrolled:
|
||||
time.sleep(config.POLICY_LOAD_WAIT) # 等页面加载稳定
|
||||
scroll_to_bottom(tab, settle=2.0) # 人工式平滑滚动到底
|
||||
time.sleep(config.POLICY_WAIT) # 等倒计时(约 5s)解锁按钮
|
||||
scrolled.add(tid)
|
||||
config.log(f'政策页已滚动到底,等待 {config.POLICY_WAIT}s 倒计时…')
|
||||
|
||||
btn = _policy_agree_btn(tab)
|
||||
if btn is None:
|
||||
config.debug('政策页「同意」尚未解锁(等 canSignBtn),继续等待')
|
||||
continue
|
||||
try:
|
||||
btn.click()
|
||||
config.log('已点击政策页「同意」')
|
||||
time.sleep(1.5)
|
||||
# 政策页通常自动关闭;若仍开着且不是主标签,手动关掉避免遮挡登录按钮
|
||||
try:
|
||||
if tab is not page and _is_policy_tab(tab):
|
||||
tab.close()
|
||||
config.debug('已关闭政策标签页')
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
except Exception as e:
|
||||
config.debug(f'政策页同意按钮点击失败:{e}')
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def _handle_skip_qr(page):
|
||||
"""跳过 APP 扫码授权 + 二次确认弹框。返回是否点过。"""
|
||||
if not click_button(page, config.TXT_SKIP_QR, timeout=1):
|
||||
return False
|
||||
config.log('已点击「跳过」扫码授权,等待确认弹框')
|
||||
time.sleep(1)
|
||||
for _ in range(10):
|
||||
for el in page.eles('css:.ant-modal-confirm-btns button'):
|
||||
try:
|
||||
if is_displayed(el) and '确认' in ''.join((el.text or '').split()):
|
||||
el.click()
|
||||
config.log('已点「确认」跳过扫码')
|
||||
time.sleep(1)
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
time.sleep(0.5)
|
||||
return True
|
||||
|
||||
|
||||
def _login_flow(page, agreed=False):
|
||||
"""点登录后推进全流程,直到进入主界面。
|
||||
|
||||
政策页 / 跳过扫码 / 二次确认都是「出现了才处理」,都不阻塞主循环,
|
||||
避免某个元素点不动时把整轮登录卡死。
|
||||
"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
while time.time() < deadline:
|
||||
if logged_in(page):
|
||||
return True
|
||||
|
||||
# ① 隐私政策(弹窗或独立页)
|
||||
if not agreed:
|
||||
try:
|
||||
if _handle_policy(page, budget=8):
|
||||
agreed = True
|
||||
continue
|
||||
except Exception as e:
|
||||
config.debug(f'处理政策异常:{e}')
|
||||
|
||||
# ② 跳过 APP 扫码授权 + 二次确认
|
||||
try:
|
||||
if _handle_skip_qr(page):
|
||||
continue
|
||||
except Exception as e:
|
||||
config.debug(f'跳过扫码异常:{e}')
|
||||
|
||||
# ③ 错误提示(账号密码问题直接失败,避免空等)
|
||||
body = _page_text(page)
|
||||
for kw in _ERR_KEYWORDS:
|
||||
if kw in body:
|
||||
config.log(f'登录被拒:页面提示含「{kw}」', 'ERROR')
|
||||
return False
|
||||
|
||||
time.sleep(1.5)
|
||||
return logged_in(page)
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def ensure_login(page, username=None, password=None, force=False):
|
||||
"""确保页面处于已登录状态。返回 dict:{success, message, relogin}"""
|
||||
page.get(config.SITE_URL)
|
||||
time.sleep(2)
|
||||
# 安装鉴权捕获 hook:登录成功后页面请求会带正式 JWT,供接口通道复用
|
||||
try:
|
||||
from . import bank_api
|
||||
bank_api.install_auth_hook(page)
|
||||
except Exception as e:
|
||||
config.debug(f'安装鉴权 hook 失败:{e}')
|
||||
if not force and logged_in(page):
|
||||
config.log('浏览器残留登录态仍有效,直接复用')
|
||||
return {'success': True, 'message': '复用残留登录态', 'relogin': False}
|
||||
|
||||
if not username or not password:
|
||||
msg = '登录账号/密码缺失:请在插件界面填写并保存配置'
|
||||
config.log(msg, 'ERROR')
|
||||
return {'success': False, 'message': msg, 'relogin': False}
|
||||
|
||||
config.log('开始账密登录…')
|
||||
page.get(config.LOGIN_URL)
|
||||
if not _fill_username(page, username):
|
||||
return {'success': False, 'message': '找不到账号输入框', 'relogin': True}
|
||||
if not _fill_password(page, password):
|
||||
return {'success': False, 'message': '找不到密码输入框', 'relogin': True}
|
||||
if not _wait_captcha(page):
|
||||
return {'success': False, 'message': '图形验证码未输入', 'relogin': True}
|
||||
|
||||
# 必须先勾选「同意隐私权政策」,否则点登录不提交(表现为卡住)
|
||||
_check_terms(page)
|
||||
# 勾选后会弹出隐私政策全文页(新标签/新窗口):滚到底 + 点「同意」,
|
||||
# 否则登录按钮会被遮挡,点下去等于点空
|
||||
# 预算 8s:勾选后政策页通常立即弹出;没弹就直接点登录,交给 _login_flow 兜底,
|
||||
# 避免每次白等 20 秒
|
||||
policy_ok = _handle_policy(page, budget=8)
|
||||
|
||||
if not click_button(page, config.TXT_LOGIN_BTN, timeout=8):
|
||||
return {'success': False, 'message': '找不到登录按钮', 'relogin': True}
|
||||
config.log('已提交登录,处理政策页 / 扫码授权…')
|
||||
|
||||
if _login_flow(page, agreed=policy_ok):
|
||||
config.log(f'登录成功:{page.url}')
|
||||
return {'success': True, 'message': '登录成功', 'relogin': True}
|
||||
|
||||
return {'success': False, 'message': '登录未完成(政策页未同意 / 账号密码有误 / 超时)', 'relogin': True}
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0076",
|
||||
"name": "交通银行数据导出",
|
||||
"version": "1.2.4",
|
||||
"description": "交通银行商户服务门户(merchantapp.bankcomm.com)商户验券交易流水导出:账密自动登录(隐私政策同意 + 跳过 APP 扫码授权全自动),接口查询判有无数据后提交导出,取 OSS 直链下载 zip 并解压 csv(GBK)。全程走接口不点页面,5 秒级完成,请求全局限流。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": [
|
||||
"xq0076"
|
||||
],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"username": {
|
||||
"type": "string",
|
||||
"title": "登录账号",
|
||||
"default": "",
|
||||
"description": "手机号 / BOC / MER 账号"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"title": "商服密码",
|
||||
"default": "",
|
||||
"description": "商户服务门户登录密码(明文存本地配置)"
|
||||
},
|
||||
"date_mode": {
|
||||
"type": "string",
|
||||
"title": "日期口径",
|
||||
"default": "prev_today",
|
||||
"enum": [
|
||||
"prev_today",
|
||||
"yesterday",
|
||||
"today",
|
||||
"month_to_today",
|
||||
"custom"
|
||||
],
|
||||
"description": "prev_today=昨天~今天(默认)/ yesterday=昨天单日 / today=今天 / month_to_today=本月至今 / custom=自定义"
|
||||
},
|
||||
"date_from": {
|
||||
"type": "string",
|
||||
"title": "开始日期",
|
||||
"default": "",
|
||||
"description": "yyyy-MM-dd;留空=按日期口径(默认昨天~今天)"
|
||||
},
|
||||
"date_to": {
|
||||
"type": "string",
|
||||
"title": "结束日期",
|
||||
"default": "",
|
||||
"description": "yyyy-MM-dd;留空=与开始日期同一天"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "D:\\资料\\银行\\交通银行数据导出",
|
||||
"description": "zip 与解压出的 csv 统一输出目录"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出完整调试日志(默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"username",
|
||||
"password"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DrissionPage>=4.1.0
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CRM数据导出</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0076-ui",
|
||||
"private": true,
|
||||
"version": "1.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 方案工具条:方案供「定时任务」按 config_id 引用 -->
|
||||
<div class="toolbar">
|
||||
<span class="spacer" />
|
||||
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
placeholder="当前配置(自动保存)" @change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
|
||||
<div v-if="needLogin" class="notice is-warn">
|
||||
<span class="n-ico">!</span>
|
||||
<span>未登录:请先在壳子(工作台)登录统一账户,再刷新本界面</span>
|
||||
</div>
|
||||
<div v-else-if="notice" class="notice" :class="'is-' + notice.type">
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '·') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 01 登录账号 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">登录账号</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<div class="grid">
|
||||
<el-form-item label="登录账号">
|
||||
<el-input v-model="form.username" :disabled="running" clearable
|
||||
placeholder="手机号 / BOC / MER 账号" />
|
||||
</el-form-item>
|
||||
<el-form-item label="商服密码">
|
||||
<el-input v-model="form.password" type="password" show-password :disabled="running"
|
||||
placeholder="商户服务门户登录密码" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
每次运行会账密登录一次(隐私政策同意、跳过 APP 扫码授权已自动处理);
|
||||
账号密码明文保存在本机配置,不会上传。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 02 导出范围 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">导出范围</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<div class="grid">
|
||||
<el-form-item label="导出日期">
|
||||
<el-date-picker v-model="dateRange" type="daterange" unlink-panels
|
||||
value-format="YYYY-MM-DD" range-separator="至"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期"
|
||||
:disabled="running" style="width: 100%" />
|
||||
</el-form-item>
|
||||
<el-form-item label="保存目录">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.save_dir" class="dir-input" :disabled="running" clearable
|
||||
placeholder="D:\资料\银行\交通银行数据导出" />
|
||||
<el-button class="dir-btn" :disabled="running || picking" :loading="picking"
|
||||
@click="pickDir">选择</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
<b>{{ rangeText }}</b><br />
|
||||
导出「商户验券」的交易流水明细。这段时间没有交易时不会生成文件;
|
||||
有数据时导出一个压缩包,解压后是明细表和汇总表,Excel 可直接打开。
|
||||
</div>
|
||||
<div class="opt-row">
|
||||
<span class="opt-label">导出过程日志</span>
|
||||
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<details class="help">
|
||||
<summary><span>流程说明</span><span class="h-arrow">▾</span></summary>
|
||||
<div class="help-body">
|
||||
<div class="hb-line"><b>① 登录</b>:自动填账号密码 → 自动勾选并同意隐私政策 → 自动跳过 APP 扫码授权。</div>
|
||||
<div class="hb-line"><b>② 查数据</b>:先确认这段时间有没有「商户验券」交易,没有就跳过,不生成空文件。</div>
|
||||
<div class="hb-line"><b>③ 导出</b>:有数据时向门户申请导出,等文件生成后自动下载,并解压成可直接打开的表格。</div>
|
||||
<div class="hb-line"><b>④ 文件</b>:压缩包和两个表格都放在保存目录里,文件名带日期区间。</div>
|
||||
<div class="hb-line"><b>提示</b>:交行登录凭证关掉浏览器就失效,所以每次运行会重新登录一次。</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
|
||||
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
|
||||
<div v-if="running" class="runline">
|
||||
<span class="pulse" />
|
||||
<span>正在执行,日志与进度实时显示在工作台下方「运行日志」区</span>
|
||||
<span class="pct">{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
// 日期工具:默认「昨天 ~ 今天」时间段
|
||||
const fmtDate = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
||||
const dayOffset = (n) => {
|
||||
const d = new Date()
|
||||
d.setDate(d.getDate() + n)
|
||||
return fmtDate(d)
|
||||
}
|
||||
|
||||
// DEFAULTS 与 plugin.json.fields 的 default 逐项一致
|
||||
const DEFAULTS = () => ({
|
||||
username: '',
|
||||
password: '',
|
||||
date_mode: 'custom',
|
||||
date_from: dayOffset(-1),
|
||||
date_to: dayOffset(0),
|
||||
save_dir: 'D:\\资料\\银行\\交通银行数据导出',
|
||||
debug_mode: false,
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!String(form.username || '').trim()) {
|
||||
ElMessage.warning('请填写登录账号')
|
||||
return false
|
||||
}
|
||||
if (!String(form.password || '').trim()) {
|
||||
ElMessage.warning('请填写商服密码')
|
||||
return false
|
||||
}
|
||||
// 日期留空 = 后端按默认口径(昨天 ~ 今天),不强制必选
|
||||
// 防误存首尾空格导致登录失败(银行会累计密码错误锁号)
|
||||
form.username = String(form.username).trim()
|
||||
form.password = String(form.password).trim()
|
||||
return true
|
||||
},
|
||||
})
|
||||
|
||||
// 时间段选择器 <-> form 两个字段互转
|
||||
const dateRange = computed({
|
||||
get: () => (form.date_from ? [form.date_from, form.date_to || form.date_from] : []),
|
||||
set: (v) => {
|
||||
form.date_from = v && v[0] ? v[0] : ''
|
||||
form.date_to = v && v[1] ? v[1] : ''
|
||||
},
|
||||
})
|
||||
|
||||
// 实际导出区间提示(包含时分秒,避免与页面口径混淆)
|
||||
const rangeText = computed(() => {
|
||||
if (!form.date_from) {
|
||||
return `导出区间:默认昨天 ~ 今天(${dayOffset(-1)} 00:00:00 ~ ${dayOffset(0)} 23:59:59)`
|
||||
}
|
||||
const b = form.date_to || form.date_from
|
||||
const days = Math.round((new Date(b) - new Date(form.date_from)) / 86400000) + 1
|
||||
return `导出区间:${form.date_from} 00:00:00 ~ ${b} 23:59:59(${days > 0 ? days : 1} 天)`
|
||||
})
|
||||
|
||||
// 调用壳子本机接口打开原生「选择文件夹」对话框
|
||||
const picking = ref(false)
|
||||
async function pickDir() {
|
||||
picking.value = true
|
||||
try {
|
||||
const r = await fetch('/api/dialog/directory', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '选择保存目录', current: form.save_dir || '' }),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (d.path) form.save_dir = d.path
|
||||
} catch (e) {
|
||||
ElMessage.warning('打开文件夹选择失败:' + e.message)
|
||||
} finally {
|
||||
picking.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 保存目录:输入框占满剩余宽度,「选择」按钮固定不换行 */
|
||||
.page .dir-ctrl {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
.page .dir-ctrl .dir-input {
|
||||
flex: 1 1 auto;
|
||||
width: auto !important;
|
||||
min-width: 0;
|
||||
}
|
||||
.page .dir-ctrl .dir-btn {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
/* 行内开关(导出过程日志) */
|
||||
.page .opt-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 2px 0 10px;
|
||||
}
|
||||
.page .opt-label {
|
||||
font: 400 12.5px/18px var(--f-cn);
|
||||
color: var(--t2);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,2 @@
|
||||
// 插件身份声明(API 实现收敛在 usePluginUI.js 公共 kit,各插件 ui-src 只需声明自己的 id)
|
||||
export const PLUGIN_ID = 'xq0076'
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
|
||||
import './style.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,431 @@
|
||||
/* ============================================================
|
||||
插件 UI 基础样式(规范 v3 · 对齐壳子「白底面板 + 描边卡」)
|
||||
- token 与壳子 frontend/src/style.css 同源(权威源 design-app/styles.css)
|
||||
- Element Plus 变量映射到壳子 token
|
||||
- 版式类:page / toolbar / notice / sec / grid / tip / actions / badge / table
|
||||
规则:插件内只用 var(--xxx),不写字面色值;左右内边距由壳子提供,不要重复加
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* 底色与卡面 */
|
||||
--canvas: #F2F4F8;
|
||||
--surface: #FFFFFF;
|
||||
--field: #F5F6FA;
|
||||
--subtle: #F7F8FC;
|
||||
|
||||
/* 描边 */
|
||||
--line: #E8EAF1;
|
||||
--line-soft: #F0F2F7;
|
||||
--line-btn: #E3E6EF;
|
||||
|
||||
/* 文字五阶 */
|
||||
--t1: #12141B;
|
||||
--t2: #3C4250;
|
||||
--t3: #6E7686;
|
||||
--t4: #A3AAB8;
|
||||
--t5: #C6CBD6;
|
||||
|
||||
/* 主色(靛蓝) */
|
||||
--brand: #4F5AE8;
|
||||
--brand-ink: #3D47D4;
|
||||
--brand-soft: #EEF0FE;
|
||||
--brand-track: #DDE1F8;
|
||||
--brand-hover: #4550E0;
|
||||
|
||||
/* 语义色 */
|
||||
--good: #0E9F76; --good-ink: #0B8A66; --good-soft: #EBF7F2; --good-line: #D3EDE3;
|
||||
--warn: #D98218; --warn-ink: #B4700F; --warn-soft: #FDF3E4; --warn-line: rgba(217, 130, 24, .28);
|
||||
--danger: #E5484D; --danger-ink: #CC3B40; --danger-soft: #FDEDED; --danger-line: #F6D7D8;
|
||||
|
||||
/* 圆角 */
|
||||
--r-row: 8px;
|
||||
--r-field: 9px;
|
||||
--r-btn: 10px;
|
||||
--r-sub: 12px;
|
||||
--r-card: 14px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* 阴影(插件内基本不用,保持与壳子同值) */
|
||||
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
|
||||
--sh-float: 0 8px 24px rgba(18, 20, 31, .10);
|
||||
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
|
||||
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
|
||||
|
||||
/* 字体 */
|
||||
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
|
||||
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--f-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
|
||||
|
||||
/* 间距 */
|
||||
--space-1: 4px;
|
||||
--space-1-5: 6px;
|
||||
--space-2: 8px;
|
||||
--space-2-5: 10px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 20px;
|
||||
--space-6: 28px;
|
||||
|
||||
--dur: .15s;
|
||||
--ease: cubic-bezier(.22, 1, .36, 1);
|
||||
}
|
||||
|
||||
/* ---------- Element Plus → 壳子 token ---------- */
|
||||
:root {
|
||||
--el-color-primary: var(--brand);
|
||||
--el-color-primary-light-3: #7A83EE;
|
||||
--el-color-primary-light-5: #A6ACF4;
|
||||
--el-color-primary-light-7: #C9CDF9;
|
||||
--el-color-primary-light-8: #DDE0FB;
|
||||
--el-color-primary-light-9: var(--brand-soft);
|
||||
--el-color-primary-dark-2: var(--brand-ink);
|
||||
|
||||
--el-color-success: var(--good);
|
||||
--el-color-success-light-9: var(--good-soft);
|
||||
--el-color-warning: var(--warn);
|
||||
--el-color-warning-light-9: var(--warn-soft);
|
||||
--el-color-danger: var(--danger);
|
||||
--el-color-danger-light-9: var(--danger-soft);
|
||||
--el-color-error: var(--danger);
|
||||
|
||||
--el-text-color-primary: var(--t1);
|
||||
--el-text-color-regular: var(--t2);
|
||||
--el-text-color-secondary: var(--t3);
|
||||
--el-text-color-placeholder: var(--t4);
|
||||
|
||||
--el-border-color: var(--line);
|
||||
--el-border-color-light: var(--line);
|
||||
--el-border-color-lighter: var(--line-soft);
|
||||
--el-border-color-extra-light: var(--line-soft);
|
||||
--el-fill-color-blank: var(--surface);
|
||||
--el-fill-color-light: var(--field);
|
||||
--el-bg-color: var(--surface);
|
||||
|
||||
--el-border-radius-base: var(--r-field);
|
||||
--el-border-radius-small: var(--r-field);
|
||||
--el-font-family: var(--f-cn);
|
||||
--el-font-size-base: 12.5px;
|
||||
--el-box-shadow-light: var(--sh-card);
|
||||
}
|
||||
|
||||
/* ---------- 基础重置 ---------- */
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--surface);
|
||||
color: var(--t1);
|
||||
font-family: var(--f-cn);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#app { padding: 0; }
|
||||
|
||||
/* ---------- 页面:只排垂直节奏(左右 24px 由壳子给) ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
padding: 2px 0 20px;
|
||||
}
|
||||
|
||||
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
min-height: 32px;
|
||||
}
|
||||
.toolbar .spacer { flex: 1; }
|
||||
.scheme-sel { width: 200px; }
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--good-soft);
|
||||
border: 1px solid var(--good-line);
|
||||
color: var(--good-ink);
|
||||
font: 500 11px/1 var(--f-cn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.saved i { width: 5px; height: 5px; border-radius: 50%; background: var(--good); }
|
||||
.saved.is-idle { background: var(--field); border-color: var(--line); color: var(--t4); }
|
||||
.saved.is-idle i { background: var(--t5); }
|
||||
|
||||
/* ---------- 提示条(替代顶部大横幅) ---------- */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
padding: 9px 12px;
|
||||
border-radius: var(--r-sub);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--subtle);
|
||||
font: 400 12px/18px var(--f-cn);
|
||||
color: var(--t2);
|
||||
}
|
||||
.notice .n-ico { flex: 0 0 auto; font-weight: 700; }
|
||||
.notice.is-warn { background: var(--warn-soft); border-color: var(--warn-line); color: var(--warn-ink); }
|
||||
.notice.is-error { background: var(--danger-soft); border-color: var(--danger-line); color: var(--danger-ink); }
|
||||
.notice.is-ok { background: var(--good-soft); border-color: var(--good-line); color: var(--good-ink); }
|
||||
|
||||
/* ---------- 分区卡:与壳子列表卡/表格卡同一套 ---------- */
|
||||
.sec {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
overflow: hidden;
|
||||
}
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 10px 14px;
|
||||
background: var(--subtle);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.sec-badge {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 6px;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
font: 600 10.5px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.sec-name { font: 600 13px/18px var(--f-cn); color: var(--t1); white-space: nowrap; }
|
||||
.sec-line { flex: 1; height: 1px; background: var(--line-soft); }
|
||||
.sec-body { padding: 14px 14px 6px; }
|
||||
|
||||
/* ---------- 栅格与表单 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 0 16px;
|
||||
}
|
||||
.grid-switch { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
|
||||
/* 日期行紧跟在开关行后,补一点呼吸 */
|
||||
.grid-date { margin-top: 4px; }
|
||||
.grid .el-form-item { margin-bottom: 12px; }
|
||||
.grid .el-form-item__label {
|
||||
padding-bottom: 6px !important;
|
||||
font-weight: 500;
|
||||
color: var(--t2);
|
||||
}
|
||||
.grid .el-input,
|
||||
.grid .el-select,
|
||||
.grid .el-date-editor,
|
||||
.grid .el-input-number { width: 100% !important; }
|
||||
|
||||
/* ---------- 说明文字 ---------- */
|
||||
.tip {
|
||||
margin-top: var(--space-2);
|
||||
font: 400 11.5px/1.65 var(--f-cn);
|
||||
color: var(--t3);
|
||||
}
|
||||
.tip b { color: var(--t2); font-weight: 600; }
|
||||
|
||||
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
|
||||
.plan { display: flex; align-items: baseline; gap: var(--space-2); font-size: 11.5px; line-height: 1.6; color: var(--t3); }
|
||||
.plan .p-tag { flex: 0 0 auto; font-weight: 600; color: var(--brand-ink); }
|
||||
.plan .p-text { min-width: 0; }
|
||||
.plan.is-empty .p-text { color: var(--warn); }
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--line-soft);
|
||||
}
|
||||
.actions .spacer { flex: 1; }
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
height: 34px;
|
||||
border: none;
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font: 600 12.5px/18px var(--f-cn);
|
||||
letter-spacing: 1px;
|
||||
box-shadow: var(--sh-brand);
|
||||
transition: background var(--dur), box-shadow var(--dur), transform .06s;
|
||||
}
|
||||
.btn-run:hover { background: var(--brand-hover); }
|
||||
.btn-run:active { transform: translateY(1px); box-shadow: var(--sh-brand-sm); }
|
||||
.btn-run.is-loading { pointer-events: none; }
|
||||
|
||||
/* ---------- 状态胶囊(与壳子表格状态列同款) ---------- */
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
font: 500 11px/1 var(--f-cn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge i { width: 5px; height: 5px; border-radius: 50%; flex-shrink: 0; }
|
||||
.badge.ok { color: var(--good-ink); background: var(--good-soft); border-color: var(--good-line); }
|
||||
.badge.ok i { background: var(--good); }
|
||||
.badge.warn { color: var(--warn-ink); background: var(--warn-soft); border-color: var(--warn-line); }
|
||||
.badge.warn i { background: var(--warn); }
|
||||
.badge.bad { color: var(--danger-ink); background: var(--danger-soft); border-color: var(--danger-line); }
|
||||
.badge.bad i { background: var(--danger); }
|
||||
.badge.idle { color: var(--t3); background: var(--field); border-color: var(--line); }
|
||||
.badge.idle i { background: var(--t5); }
|
||||
|
||||
/* ---------- 表格(插件内需要列表时用;与壳子表格同口径) ---------- */
|
||||
.table-card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
overflow: hidden;
|
||||
}
|
||||
.table-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: 12px 16px;
|
||||
background: var(--subtle);
|
||||
border-bottom: 1px solid var(--line);
|
||||
font: 600 13.5px/20px var(--f-cn);
|
||||
color: var(--t1);
|
||||
}
|
||||
.table { width: 100%; border-collapse: collapse; table-layout: fixed; }
|
||||
.table th {
|
||||
padding: 10px 16px;
|
||||
text-align: center;
|
||||
font: 500 11px/16px var(--f-cn);
|
||||
color: var(--t3);
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.table td {
|
||||
padding: 10px 16px;
|
||||
text-align: center;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
font: 400 12px/18px var(--f-cn);
|
||||
color: var(--t2);
|
||||
}
|
||||
.table tr:last-child td { border-bottom: 0; }
|
||||
.table tbody tr { transition: background var(--dur); }
|
||||
.table tbody tr:hover { background: var(--field); }
|
||||
.table td.is-name { text-align: left; font-weight: 600; color: var(--t1); }
|
||||
.table th.is-name { text-align: left; }
|
||||
|
||||
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
|
||||
.runline { display: flex; align-items: center; gap: var(--space-2); font-size: 12px; color: var(--t3); }
|
||||
.runline .pct { font: 600 12px/1 var(--f-num); color: var(--brand-ink); font-variant-numeric: tabular-nums; }
|
||||
.pulse { width: 7px; height: 7px; border-radius: 50%; background: var(--brand); animation: pulse 1.4s ease-out infinite; }
|
||||
@keyframes pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--brand-soft); }
|
||||
70% { box-shadow: 0 0 0 7px transparent; }
|
||||
100% { box-shadow: 0 0 0 0 transparent; }
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
v3.1 扩展:步骤卡 / 行式设置项 / 折叠说明
|
||||
- 适用于「互斥步骤」「开关+联动下拉」「大段流程说明」
|
||||
- 仍然只用 token,不写字面色值
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 步骤卡(互斥单选,≤4 项) ---------- */
|
||||
.step-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: var(--space-2-5);
|
||||
}
|
||||
.step-card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
padding: 11px 32px 11px 13px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
cursor: pointer;
|
||||
transition: border-color var(--dur), background var(--dur), box-shadow var(--dur);
|
||||
}
|
||||
.step-card:hover { border-color: var(--brand-track); background: var(--subtle); }
|
||||
.step-card.on {
|
||||
border-color: var(--brand);
|
||||
background: var(--brand-soft);
|
||||
box-shadow: inset 0 0 0 1px var(--brand-soft);
|
||||
}
|
||||
.step-card .sc-title { font: 600 13px/18px var(--f-cn); color: var(--t1); }
|
||||
.step-card.on .sc-title { color: var(--brand-ink); }
|
||||
.step-card .sc-desc { font: 400 11.5px/1.6 var(--f-cn); color: var(--t3); }
|
||||
.step-card .sc-check {
|
||||
position: absolute; top: 10px; right: 10px;
|
||||
width: 16px; height: 16px; color: var(--brand);
|
||||
}
|
||||
.step-cards.is-disabled .step-card { opacity: .55; pointer-events: none; }
|
||||
.sr-only {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
|
||||
}
|
||||
|
||||
/* ---------- 行式设置项(标题+说明在左,控件在右) ---------- */
|
||||
.rows {
|
||||
display: flex; flex-direction: column; gap: var(--space-2);
|
||||
padding: var(--space-2);
|
||||
background: var(--subtle);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
}
|
||||
.row {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
gap: var(--space-4);
|
||||
padding: 9px 12px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line-soft);
|
||||
border-radius: var(--r-field);
|
||||
}
|
||||
.row .r-main { min-width: 0; }
|
||||
.row .r-title { font: 500 12.5px/18px var(--f-cn); color: var(--t1); }
|
||||
.row .r-desc { margin-top: 1px; font: 400 11.5px/1.6 var(--f-cn); color: var(--t3); }
|
||||
.row .r-ctrl { flex: 0 0 auto; }
|
||||
.row.is-hidden { display: none; }
|
||||
|
||||
/* ---------- 折叠说明(流程说明气泡卡片) ---------- */
|
||||
.help {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
overflow: hidden;
|
||||
}
|
||||
.help > summary {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
gap: var(--space-2); padding: 10px 14px;
|
||||
background: var(--subtle);
|
||||
font: 600 12.5px/18px var(--f-cn); color: var(--t2);
|
||||
cursor: pointer; list-style: none;
|
||||
}
|
||||
.help > summary::-webkit-details-marker { display: none; }
|
||||
.help[open] > summary { border-bottom: 1px solid var(--line); }
|
||||
.help .h-arrow { color: var(--t4); transition: transform var(--dur); font-size: 11px; }
|
||||
.help[open] .h-arrow { transform: rotate(180deg); }
|
||||
.help-body {
|
||||
padding: 12px 14px;
|
||||
font: 400 12px/1.8 var(--f-cn); color: var(--t3);
|
||||
}
|
||||
.help-body b { color: var(--t2); font-weight: 600; }
|
||||
.help-body .hb-line + .hb-line { margin-top: 6px; }
|
||||
@@ -0,0 +1,356 @@
|
||||
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||
//
|
||||
// 与 v1 的差异(适配当前壳子):
|
||||
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||
// 不能再当成普通失败提示。
|
||||
//
|
||||
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||
// 执行状态机(执行/强停/WS 进度 + 轮询兜底/未登录重试)。
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try {
|
||||
msg = (await res.json()).detail || msg
|
||||
} catch (_) { /* 保留默认 */ }
|
||||
throw Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
const deleteScheme = (cfgId) =>
|
||||
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
const startRun = (fields) => j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||
const stopRun = (runId) => j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||
function readSavedAt() {
|
||||
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||
}
|
||||
function writeSavedAt(v) {
|
||||
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||
}
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||
const lastSavedAt = ref(readSavedAt())
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes()
|
||||
})
|
||||
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
writeSavedAt(lastSavedAt.value)
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
notify(null)
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||
async function restoreLastFields() {
|
||||
try {
|
||||
const r = await loadLastFields()
|
||||
const fields = r.fields || {}
|
||||
if (!Object.keys(fields).length) {
|
||||
ElMessage.info('暂无上次执行参数')
|
||||
return
|
||||
}
|
||||
mergeSaved(form, fields)
|
||||
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 多配置方案 ----------
|
||||
const schemes = ref([])
|
||||
const schemeSel = ref('')
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) { /* 方案是辅助能力,失败静默 */ }
|
||||
}
|
||||
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
},
|
||||
))
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
}
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||
async function run(action) {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
} catch (_) {
|
||||
notify('error', '登录态未就绪,请稍后重试')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (validate && !validate(action)) return
|
||||
await saveNow(false)
|
||||
notify(null)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
try {
|
||||
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||
if (action) payload.action = action
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) {
|
||||
needLogin.value = true
|
||||
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||
} else if (e.code === 409) {
|
||||
// 壳子「入队确认」里用户点了取消
|
||||
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||
} else {
|
||||
notify('error', '启动执行失败:' + e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
// 用户强制停止 / 排队取消 / 排队超时 → 「已取消」,不显示成「执行失败」
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : (ev.status === 'cancelled' ? cancelled(ev.error) : failed(ev.error || '执行失败'))
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary)
|
||||
else if (r.status === 'cancelled') cancelled(r.error)
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||
if (summary) notify('ok', summary)
|
||||
}
|
||||
|
||||
// 用户主动停止 / 排队取消 / 排队超时:不算失败,给中性的「已取消」提示
|
||||
function cancelled(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
notify('warn', '任务已取消:' + (err || '用户已停止'))
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
notify('error', '执行失败:' + err)
|
||||
}
|
||||
|
||||
return {
|
||||
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0076/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0076/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5199,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8799',
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CRM数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0076/assets/index-DtlHbbG_.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0076/assets/index-CIPW0FSx.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user