feat(xq0079): 新增金色湖畔扫码数据导出插件(1.1.4)
- 天阙会生活商户平台(mch-web.tianquetech.com)扫码交易记录导出:账密登录(图形验证码 OCR + AES 密码加密,token 按账号缓存复用)→ 平台导出接口生成 xlsx → 下载中心取文件直存本地 - 支持两套账号串行导出(第 2 套可留空),日期区间界面可选,产物按商户名区分
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
# 金色湖畔扫码数据导出(xq0079)
|
||||
|
||||
天阙会生活商户平台(`mch-web.tianquetech.com`)扫码交易记录接口化导出,纯接口实现,不启浏览器。
|
||||
|
||||
## 功能
|
||||
|
||||
- 两套账号串行导出(账号二可留空),各自独立 session/token,一个失败不影响另一个
|
||||
- 时间区间默认「昨天 00:00:00 ~ 今天 23:59:59」,也可在界面选日期段(定时任务不用填日期)
|
||||
- 每个账号产出一份 xlsx:`<商户名>_交易记录_<起止日期>.xlsx`
|
||||
- 登录 token 按账号缓存在本机,有效期内免验证码登录;失效自动回落账密登录
|
||||
- 导出完成后自动标记下载中心已读,不堆积
|
||||
|
||||
## 参数(plugin.json.fields)
|
||||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| `tq_account1` / `tq_password1` | 账号一(必填) |
|
||||
| `tq_account2` / `tq_password2` | 账号二(可留空) |
|
||||
| `login_mode` | 登录方式:`自动`(接口登录 + 验证码 OCR)/ `人工登录`(弹浏览器,人工输验证码) |
|
||||
| `date_from` / `date_to` | 导出日期,留空 = 昨天 ~ 今天 |
|
||||
| `save_dir` | 保存目录,留空 = `D:\资料\财务\金色湖畔扫码数据导出` |
|
||||
| `debug_mode` | 输出完整调试日志 |
|
||||
|
||||
## 登录方式
|
||||
|
||||
| 方式 | 行为 | 适用 |
|
||||
|---|---|---|
|
||||
| `自动` | 纯接口:取验证码 → ddddocr 识别 → 提交登录,全程静默;识别不中自动换图(最多 4 轮) | 日常定时任务 |
|
||||
| `人工登录` | DrissionPage 打开可见浏览器,预填 `#loginAcc` / `#loginPwd`,人工输入 `#imageCode` 并点「登 录」;插件轮询 `sessionStorage.user` 取 token 后自动关窗 | 验证码识别老是不准、或账号已被风控要求人工确认时 |
|
||||
|
||||
- 两种方式都**优先复用本机缓存的 token**(探针校验有效就不登录、不弹窗)。
|
||||
- 人工登录**不自动提交表单**,不消耗接口登录的重试轮次,也就不会把账号试到锁;最久等 180 秒,中途关浏览器视为取消。
|
||||
|
||||
## 多账号与风控
|
||||
|
||||
| 措施 | 说明 |
|
||||
|---|---|
|
||||
| 浏览器用户目录按账号隔离 | `%LOCALAPPDATA%\37duAutomation\browser_profiles\xq0079\<账号md5>`;DrissionPage 默认的 `%TEMP%\DrissionPage\userData` 是所有插件共用的,会串 cookie |
|
||||
| 同账号复用同一 profile | cookie 保留、指纹稳定,接近真人固定浏览器;登录后只关窗口,不清 profile |
|
||||
| 独立调试端口 | 每次取空闲端口,不与其它插件/已开浏览器抢 9222 |
|
||||
| 账号间随机停顿 | 3~8 秒(`config.ACCOUNT_GAP_SECONDS`),串行处理,不并发、不秒连 |
|
||||
| token 缓存 | 有效期内完全不登录,减少登录频次(风控最敏感的就是登录动作) |
|
||||
| 登录轮次上限 | 接口登录最多 4 轮,1003 无法区分验证码错/密码错,避免把账号试锁 |
|
||||
|
||||
## 接口链路(2026-11 抓包 + 前端 bundle 核实)
|
||||
|
||||
| 步骤 | 接口 | 说明 |
|
||||
|---|---|---|
|
||||
| 1 | `POST bankLogin/imageCode` | 取 `imageKey` + 验证码图,ddddocr 识别 4 位 |
|
||||
| 2 | `POST user/transForm/login` | body 套 `{header:{sysType:pc},data:{...}}` 信封;密码 AES-128-ECB/Pkcs7/Base64,key `abcdefgabcdefg12` |
|
||||
| 3 | `POST tranInfoPc/exportNew` | 提交导出任务,**响应 0 字节**,不能按 JSON 解析 |
|
||||
| 4 | `POST download/downLoadList` | 轮询下载中心,认领本次新增且 `exportStatus=1` 的记录 |
|
||||
| 5 | `GET <downloadUrl>` | OSS 预签名地址,直连下载,不需要 token |
|
||||
| 6 | `POST download/read/<id>` | 标记已读 |
|
||||
|
||||
## 坑位
|
||||
|
||||
- 站点 HTTPS 用弱 DH 参数,OpenSSL 3 直连报 `DH_KEY_TOO_SMALL`,必须 `SECLEVEL=0`。
|
||||
- 登录 `body` 要信封;业务接口(`tranInfo`/`tranInfoPc`/`download` 等)是**扁平 body**,套信封会回 `0003 参数不完整`。
|
||||
- 登录失败码 `1003` 同时代表「验证码识别错」和「账号密码错」,服务端不区分,只能换图重试有限轮次(默认 4 轮)。
|
||||
- 下载中心是全账号历史列表,必须用「提交前 id 集合 + 增量」认领,否则会下到历史文件。
|
||||
- `downloadUrl` 带 `expires/signature`,有时效,拿到立刻下。
|
||||
|
||||
## 打包发布
|
||||
|
||||
```powershell
|
||||
# 打包(产物落仓库根 dist-plugin/xq0079_v<版本>.zip)
|
||||
d:\work\code\37duAutomation\.venv\Scripts\python.exe "plugins\XQ0001-0100\XQ0079 金色湖畔扫码数据导出\_pack.py"
|
||||
|
||||
# 发布(默认进测试通道,人工验证后再由人执行 plugin-status 转正)
|
||||
.venv\Scripts\python.exe tools/agent_cli.py publish dist-plugin\xq0079_v1.0.0.zip `
|
||||
--id xq0079 --version 1.0.0 --admin puddy --password 123456 --base http://172.30.30.243:8800
|
||||
```
|
||||
|
||||
## 前端开发
|
||||
|
||||
```powershell
|
||||
cd plugins\XQ0001-0100\XQ0079 金色湖畔扫码数据导出\ui-src
|
||||
npm install # 首次
|
||||
npm run build # 产物输出到 ../ui/,壳子按 /pui/xq0079/ 托管
|
||||
```
|
||||
@@ -0,0 +1,168 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金色湖畔扫码数据导出(XQ0079)- webhost 场景插件
|
||||
|
||||
天阙会生活商户平台(mch-web.tianquetech.com)扫码交易记录接口化导出:
|
||||
- 登录:账密 + 图形验证码 OCR + AES 加密密码(与网页同款报文),token 按账号缓存复用;
|
||||
- 查询:平台导出接口 exportNew 提交任务,下载中心取 OSS 预签名地址直接下载 xlsx;
|
||||
- 多账号:界面填两套账号(第 2 套可留空),串行导出、互不影响,产物按商户名区分;
|
||||
- 时间:默认「昨天 00:00:00 ~ 今天 23:59:59」,也可在界面指定日期段。
|
||||
|
||||
个性化设计:
|
||||
- 账号密码经 fields 注入(plugin_configs 本机明文保存,下次免填);
|
||||
- 平台账号之间完全独立,各自建立 session/token,避免串号;
|
||||
- 单个账号失败不影响另一个账号,最终汇总返回各账号结果。
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import tianque_export
|
||||
from .logic import date_range
|
||||
|
||||
|
||||
def _default_save_dir():
|
||||
return config.DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
class TianqueTradeExportPlugin(ScenePlugin):
|
||||
id = "xq0079"
|
||||
name = "金色湖畔扫码数据导出"
|
||||
version = "1.1.4"
|
||||
description = ("天阙会生活商户平台扫码交易记录接口化导出:账密自动登录(图形验证码 OCR + AES 密码加密),"
|
||||
"服务端生成 xlsx 后直取文件;支持两套账号串行导出,"
|
||||
"默认昨天 00:00:00 ~ 今天 23:59:59")
|
||||
platform = "" # 平台自带账密登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0079"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致(ui=true 前端自渲染,此处作为参数契约文档)
|
||||
fields = {
|
||||
"tq_account1": {"type": "string", "title": "账号一", "default": "",
|
||||
"description": "天阙商户平台登录账号(手机号/商户编号)"},
|
||||
"tq_password1": {"type": "string", "title": "密码一", "default": "",
|
||||
"description": "账号一密码(明文存本机配置)"},
|
||||
"tq_account2": {"type": "string", "title": "账号二", "default": "",
|
||||
"description": "第二个账号,留空则只导出账号一"},
|
||||
"tq_password2": {"type": "string", "title": "密码二", "default": "",
|
||||
"description": "账号二密码"},
|
||||
"login_mode": {"type": "string", "title": "登录方式", "default": config.LOGIN_AUTO,
|
||||
"enum": config.LOGIN_MODE_CHOICES,
|
||||
"description": "自动=接口登录(验证码 OCR,静默);人工登录=弹浏览器,人工输验证码后点登录"},
|
||||
"date_from": {"type": "string", "format": "date", "title": "开始日期", "default": "",
|
||||
"description": "yyyy-MM-dd;留空=昨天"},
|
||||
"date_to": {"type": "string", "format": "date", "title": "结束日期", "default": "",
|
||||
"description": "yyyy-MM-dd;留空=今天"},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": "",
|
||||
"description": "留空=%s" % config.DEFAULT_SAVE_DIR},
|
||||
"debug_mode": {"type": "boolean", "title": "调试日志", "default": False,
|
||||
"description": "开启后输出完整调试日志"},
|
||||
}
|
||||
|
||||
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")))
|
||||
|
||||
# ---------- 解析参数 ----------
|
||||
accounts = []
|
||||
for idx in (1, 2):
|
||||
acc = str(fields.get("tq_account%d" % idx) or "").strip()
|
||||
pwd = str(fields.get("tq_password%d" % idx) or "").strip()
|
||||
if acc and not pwd:
|
||||
raise RuntimeError("账号%d 已填写账号但缺少密码" % idx)
|
||||
if pwd and not acc:
|
||||
raise RuntimeError("账号%d 已填写密码但缺少账号" % idx)
|
||||
if acc and pwd:
|
||||
accounts.append((idx, acc, pwd))
|
||||
if not accounts:
|
||||
raise RuntimeError("请至少填写一套账号与密码(账号一)")
|
||||
|
||||
try:
|
||||
begin, end = date_range.build_range(fields.get("date_from"), fields.get("date_to"))
|
||||
except ValueError as exc:
|
||||
raise RuntimeError("导出日期不正确:%s" % exc)
|
||||
|
||||
login_mode = str(fields.get("login_mode") or config.LOGIN_AUTO).strip()
|
||||
if login_mode not in config.LOGIN_MODE_CHOICES:
|
||||
login_mode = config.LOGIN_AUTO
|
||||
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or _default_save_dir()
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
stamp = date_range.file_stamp(begin, end)
|
||||
|
||||
ctx.log("导出区间:%s ~ %s" % (begin, end))
|
||||
ctx.log("账号数:%d(%s)" % (len(accounts), "、".join(a[1] for a in accounts)))
|
||||
ctx.log("登录方式:%s%s" % (
|
||||
login_mode, "(逐个账号弹出浏览器,人工输入验证码并点登录)"
|
||||
if login_mode == config.LOGIN_MANUAL else ""))
|
||||
ctx.log("保存目录:%s" % save_dir)
|
||||
|
||||
# ---------- 逐账号导出 ----------
|
||||
span = 90 / len(accounts)
|
||||
results = []
|
||||
for pos, (idx, acc, pwd) in enumerate(accounts):
|
||||
low = int(5 + span * pos)
|
||||
high = int(5 + span * (pos + 1))
|
||||
if pos > 0:
|
||||
# 串行 + 随机停顿:避免同一秒内连登多个账号,减少「同设备短时多账号」风控特征
|
||||
gap = random.uniform(*config.ACCOUNT_GAP_SECONDS)
|
||||
ctx.log("账号间停顿 %.1f 秒后继续" % gap)
|
||||
time.sleep(gap)
|
||||
ctx.log("—— 账号%d 开始(%s)——" % (idx, acc))
|
||||
try:
|
||||
res = tianque_export.export_trade(acc, pwd, save_dir, begin, end, stamp,
|
||||
progress_from=low, progress_to=high,
|
||||
login_mode=login_mode)
|
||||
except Exception as exc: # 单账号失败不影响后续账号
|
||||
res = {"success": False, "merchant": acc, "file": "", "size": 0,
|
||||
"message": str(exc)}
|
||||
ctx.log("账号%d 导出失败:%s" % (idx, exc), "ERROR")
|
||||
res["account_index"] = idx
|
||||
res["account"] = acc
|
||||
results.append(res)
|
||||
if res.get("success"):
|
||||
ctx.log("账号%d 导出完成:%s" % (idx, res.get("file")))
|
||||
else:
|
||||
ctx.log("账号%d 未完成:%s" % (idx, res.get("message")), "WARN")
|
||||
|
||||
config.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
ok = [r for r in results if r.get("success")]
|
||||
bad = [r for r in results if not r.get("success")]
|
||||
notes = []
|
||||
for r in results:
|
||||
tag = "成功" if r.get("success") else "失败"
|
||||
notes.append("%s|账号%d %s|%s|%s" % (
|
||||
tag, r["account_index"], r["account"],
|
||||
r.get("merchant") or "-", r.get("message") or "-"))
|
||||
|
||||
if not ok:
|
||||
raise RuntimeError("两个账号都未导出成功:\n" + "\n".join(notes))
|
||||
|
||||
summary = "交易记录导出完成:%d/%d 个账号,区间 %s ~ %s" % (
|
||||
len(ok), len(results), begin, end)
|
||||
if bad:
|
||||
summary += "(%d 个账号失败,详见备注)" % len(bad)
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": {
|
||||
"begin": begin,
|
||||
"end": end,
|
||||
"stamp": stamp,
|
||||
"save_dir": save_dir,
|
||||
"accounts": results,
|
||||
"ok_count": len(ok),
|
||||
"fail_count": len(bad),
|
||||
},
|
||||
"path": ok[0].get("file") if len(ok) == 1 else save_dir,
|
||||
"notes": notes,
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(TianqueTradeExportPlugin())
|
||||
@@ -0,0 +1,53 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0079 金色湖畔扫码数据导出 插件打包脚本(统一规范版,与 xq0011/xq0077/xq0078 一致)。
|
||||
|
||||
打包产物统一输出到仓库根 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\\XQ0079 金色湖畔扫码数据导出\\_pack.py"
|
||||
随后发布(默认进测试通道,人工验证后再转正):
|
||||
.venv\\Scripts\\python.exe tools/agent_cli.py publish \
|
||||
dist-plugin\\xq0079_v<版本>.zip --id xq0079 --version <版本> \
|
||||
--admin puddy --password 123456 --base http://172.30.30.243:8800
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_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"]
|
||||
# 带 UI 插件必须已构建前端产物(ui/ 由底座 /pui/<id>/ 托管)
|
||||
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,138 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0079 天阙商户交易数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖 Python 标准库 / 第三方库(requests、pycryptodome、ddddocr)/ 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log),进度经 config.progress()。
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
# ==================== 天阙会生活商户平台 ====================
|
||||
# 平台:mch-web.tianquetech.com(umi/react 单页应用,接口鉴权靠请求头 token)
|
||||
BASE_URL = 'https://mch-web.tianquetech.com'
|
||||
|
||||
API_IMAGE_CODE = '/management/easypay/api/bankLogin/imageCode' # 图形验证码(imageKey + captchaBase64)
|
||||
API_LOGIN = '/management/easypay/api/user/transForm/login' # 账密登录(body 需 {header,data} 信封)
|
||||
API_PROBE = '/management/easypay/api/tranInfo/queryTranSumByDate' # 只读探针(校验 token 是否有效)
|
||||
API_EXPORT = '/management/easypay/api/tranInfoPc/exportNew' # 交易记录导出任务(空响应体)
|
||||
API_DOWNLOAD_LIST = '/management/easypay/api/download/downLoadList' # 下载中心列表(带 OSS 预签名地址)
|
||||
API_MARK_READ = '/management/easypay/api/download/read/' # 标记已读(与网页点击下载一致)
|
||||
|
||||
CHANNEL = 'WELIFE-PC'
|
||||
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
|
||||
TIMEOUT = 30 # 单请求超时(秒)
|
||||
DOWNLOAD_TIMEOUT = 180 # 下载文件超时(秒)
|
||||
|
||||
# 密码加密:前端硬编码 CryptoJS AES-128-ECB + Pkcs7,key 固定 16 字符
|
||||
AES_KEY = b'abcdefgabcdefg12'
|
||||
|
||||
# ==================== 接口返回码 ====================
|
||||
CODE_OK = ('0000', '200')
|
||||
CODE_TOKEN_INVALID = ('0003', '1001', '1002', '9999') # 探针返回这些码视为 token 失效
|
||||
CODE_BAD_OR_CAPTCHA = '1003' # 登录:验证码错与账号密码错共用此码(服务端不区分)
|
||||
CAPTCHA_LEN = 4 # 验证码位数(识别结果长度不符直接换图,不浪费提交次数)
|
||||
|
||||
# ==================== 登录与轮询策略 ====================
|
||||
LOGIN_AUTO = '自动' # 接口登录(验证码 OCR,静默不弹浏览器)
|
||||
LOGIN_MANUAL = '人工登录' # 弹可见浏览器,人工输入验证码并点登录(不自动提交,不消耗尝试次数)
|
||||
LOGIN_MODE_CHOICES = [LOGIN_AUTO, LOGIN_MANUAL]
|
||||
LOGIN_PAGE = '/login'
|
||||
MANUAL_LOGIN_WAIT = 180 # 人工登录最长等待(秒)
|
||||
MANUAL_POLL_SECONDS = 2 # 人工登录轮询 sessionStorage 间隔
|
||||
MANUAL_TIP_SECONDS = 30 # 人工登录进度提示间隔
|
||||
# 账号间随机停顿(秒):串行处理多账号时避免同一秒连登,贴近真人节奏
|
||||
ACCOUNT_GAP_SECONDS = (3, 8)
|
||||
LOGIN_MAX_ATTEMPTS = 4 # 登录提交轮次上限(服务端不区分验证码错/密码错,只能换图重试)
|
||||
LOGIN_RETRY_SLEEP = 1 # 轮次间隔(秒)
|
||||
POLL_TIMEOUT = 180 # 等导出文件生成的最长秒数
|
||||
POLL_INTERVAL = 5 # 下载中心轮询间隔(秒)
|
||||
LIST_PAGE_SIZE = 10 # 下载中心每页条数
|
||||
EXPORT_STATUS_DONE = '1' # 下载中心 exportStatus:1=导出完成
|
||||
TRADE_SOURCE = '交易记录' # 下载中心 fileSource 取值,用来认领自己刚触发的任务
|
||||
|
||||
# 交易记录导出参数:与网页一致(payTypePc/tranStsPc/payWayPcList 的 0 均表示「全部」)
|
||||
EXPORT_TEMPLATE = {
|
||||
'payTypePc': '0',
|
||||
'storeId': '',
|
||||
'userId': '',
|
||||
'tranStsPc': '0',
|
||||
'payWayPcList': ['0'],
|
||||
'trmNo': '',
|
||||
'tradeSources': '',
|
||||
'timeType': '01', # 01=自定义时间区间
|
||||
}
|
||||
|
||||
# ==================== 输出 ====================
|
||||
DEFAULT_SAVE_DIR = r'D:\资料\财务\金色湖畔扫码数据导出'
|
||||
FILE_TITLE = '交易记录' # 平台导出文件名前缀(商户名_交易记录_日期区间.xlsx)
|
||||
|
||||
# ==================== 登录态缓存(按账号分 key,跨 run 复用,减少验证码登录次数) ====================
|
||||
def get_token_file():
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
d = os.path.join(base, '37duAutomation', 'sessions')
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return os.path.join(d, 'tianque_xq0079.json')
|
||||
|
||||
|
||||
def account_key(account):
|
||||
"""账号 → 缓存 key(不落明文手机号做 key,避免文件里直接暴露)。"""
|
||||
return hashlib.md5(str(account or '').strip().encode('utf-8')).hexdigest()[:16]
|
||||
|
||||
|
||||
def get_desktop():
|
||||
return os.path.join(os.path.expanduser('~'), 'Desktop')
|
||||
|
||||
|
||||
# ==================== 浏览器用户目录(人工登录用,按账号隔离) ====================
|
||||
# DrissionPage 不指定时默认落 %TEMP%\DrissionPage\userData\<端口>,是所有插件共用的同一个
|
||||
# 浏览器配置——多账号/多插件会串 cookie 与登录态。这里按账号 md5 建独立 profile:
|
||||
# 同一账号每次都用同一个目录(像真人的固定浏览器,cookie 保留、指纹稳定),
|
||||
# 不同账号之间完全隔离(互不可见 cookie / sessionStorage / 本地存储)。
|
||||
BROWSER_PROFILE_ROOT = os.path.join(
|
||||
os.environ.get('LOCALAPPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', 'browser_profiles', 'xq0079')
|
||||
|
||||
|
||||
def get_profile_dir(account):
|
||||
path = os.path.join(BROWSER_PROFILE_ROOT, account_key(account))
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if level == "DEBUG" and not _debug:
|
||||
return
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:天阙平台接口访问(登录、导出)。"""
|
||||
@@ -0,0 +1,194 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0079 人工登录通道:弹可见浏览器 + 预填账号密码,验证码由人工输入并点「登录」。
|
||||
|
||||
为什么需要这条通道:
|
||||
接口登录依赖 ddddocr 识别图形验证码(4 位字母数字),识别率不是 100%,
|
||||
每次提交都计入平台失败次数(服务端对「验证码错」和「账号密码错」都回 1003,
|
||||
连续失败有锁号风险)。人工登录不自动提交表单,只做预填,验证码由人看,
|
||||
一次就能过,且不消耗插件的重试轮次。
|
||||
|
||||
实现要点(登录页 DOM 来自实际页面):
|
||||
账号 input#loginAcc(placeholder「请输入商户编号/门店编号/手机号」)
|
||||
密码 input#loginPwd(ant-input-password 内)
|
||||
验证码 input#imageCode + 右侧 <img src="data:image/jpeg;base64,...">
|
||||
登录按钮 button.ant-btn-primary(文案「登 录」)
|
||||
登录成功后前端会整页跳转,并把用户信息(含 token)写入 sessionStorage.user,
|
||||
这里轮询 sessionStorage 取 token——比抓 cookie 稳,天阙业务接口靠 token 头鉴权。
|
||||
|
||||
风控相关(多账号必须看):
|
||||
- 浏览器用户目录按账号隔离(config.get_profile_dir),不共用 DrissionPage 默认的
|
||||
%TEMP%\\DrissionPage\\userData 公共目录,避免两个账号串 cookie / 登录态;
|
||||
- 同一账号每次都用同一个 profile:cookie 保留、指纹稳定,表现接近真人固定浏览器;
|
||||
- 每个实例用独立调试端口,避免与其它插件或已开浏览器抢 9222;
|
||||
- 账号之间由调用方随机停顿几秒再登(config.ACCOUNT_GAP_SECONDS),不并发、
|
||||
不秒连,减少「同设备短时多账号」这类风控特征;
|
||||
- 登录完成后只关窗口,不清 profile(清了下一次又像一台新设备,反而更可疑)。
|
||||
"""
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
def _free_port():
|
||||
"""取一个空闲本地端口,避免与其它插件/已开浏览器抢同一个调试端口。"""
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def _new_page(account):
|
||||
"""按账号隔离浏览器用户目录(profile)后开窗。
|
||||
|
||||
DrissionPage 默认把 profile 放 %TEMP%\\DrissionPage\\userData\\<端口>,
|
||||
是所有插件共用的同一个配置目录——不同账号/不同插件会串 cookie 与登录态。
|
||||
这里按账号 md5 建独立目录:同账号每次复用(cookie 保留、指纹稳定,像真人固定浏览器),
|
||||
不同账号之间完全隔离;账号间再随机停顿几秒,避免同一秒连登被风控盯上。
|
||||
"""
|
||||
from DrissionPage import ChromiumOptions, ChromiumPage
|
||||
|
||||
profile = config.get_profile_dir(account)
|
||||
opts = ChromiumOptions()
|
||||
opts.set_user_data_path(profile) # 账号级隔离(也避开 %TEMP% 公共目录)
|
||||
opts.set_local_port(_free_port()) # 独立端口,防与其他实例冲突
|
||||
opts.set_argument("--start-maximized")
|
||||
return ChromiumPage(opts), profile
|
||||
|
||||
|
||||
def _alive(page):
|
||||
try:
|
||||
return bool(page.states.is_alive)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _js(page, script, times=5, gap=0.5):
|
||||
"""页面跳转瞬间 run_js 会抛 ContextLostError,重试几次。"""
|
||||
for _ in range(times):
|
||||
try:
|
||||
return page.run_js(script)
|
||||
except Exception:
|
||||
time.sleep(gap)
|
||||
return None
|
||||
|
||||
|
||||
def _wait_form(page, timeout=40):
|
||||
"""等登录表单渲染完成(umi 首屏是 JS 渲染,input 出现才算就绪)。"""
|
||||
for _ in range(timeout):
|
||||
n = _js(page, "return document.querySelectorAll('input').length", times=2) or 0
|
||||
if n >= 3:
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def _fill(page, account, password):
|
||||
"""预填账号密码(人工只需输验证码)。字段缺失不影响人工操作。"""
|
||||
try:
|
||||
acc = page.ele('#loginAcc', timeout=5) or page.ele('css:input[placeholder*="商户编号"]', timeout=3)
|
||||
if acc:
|
||||
acc.clear()
|
||||
acc.input(account)
|
||||
except Exception as exc:
|
||||
_log(f"预填账号失败(可手动输入):{exc}", "WARN")
|
||||
|
||||
if not password:
|
||||
return
|
||||
try:
|
||||
pwd = page.ele('#loginPwd', timeout=5) or page.ele('css:input[type="password"]', timeout=3)
|
||||
if pwd:
|
||||
pwd.clear()
|
||||
pwd.input(password)
|
||||
except Exception as exc:
|
||||
_log(f"预填密码失败(可手动输入):{exc}", "WARN")
|
||||
|
||||
|
||||
def _read_user(page):
|
||||
"""读 sessionStorage.user(登录成功后前端写入,含 token)。"""
|
||||
raw = _js(page, "return sessionStorage.getItem('user')", times=2)
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
user = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
if isinstance(user, dict) and user.get("token"):
|
||||
return user
|
||||
return None
|
||||
|
||||
|
||||
def manual_login(account, password, wait_seconds=None):
|
||||
"""人工登录:返回 {success, token, user, message}。
|
||||
|
||||
不开无头窗口:人工要看验证码。登录成功后关闭浏览器(token 已拿到,不需要常驻)。
|
||||
"""
|
||||
wait_seconds = wait_seconds or config.MANUAL_LOGIN_WAIT
|
||||
page = None
|
||||
try:
|
||||
page, profile = _new_page(account)
|
||||
_log(f"浏览器用户目录(该账号专用):{profile}", "DEBUG")
|
||||
|
||||
page.get(config.BASE_URL + config.LOGIN_PAGE)
|
||||
time.sleep(2)
|
||||
if not _wait_form(page, timeout=15):
|
||||
# 这个 profile 上次登录后 cookie 还在,可能直接进了后台
|
||||
user = _read_user(page)
|
||||
if user:
|
||||
token = str(user.get("token") or "")
|
||||
merchant = str(user.get("merchantName") or user.get("userName") or account)
|
||||
_log(f"该账号浏览器里仍是登录态,直接复用:{merchant}")
|
||||
return {"success": True, "token": token, "user": user,
|
||||
"message": "浏览器已有登录态", "merchant": merchant}
|
||||
_log("登录页未出现表单(疑似残留登录态),清理该账号浏览器缓存后重试", "WARN")
|
||||
try:
|
||||
page.clear_cache()
|
||||
except Exception as exc:
|
||||
_log(f"清理浏览器缓存失败(可手动清理):{exc}", "WARN")
|
||||
page.get(config.BASE_URL + config.LOGIN_PAGE)
|
||||
time.sleep(2)
|
||||
if not _wait_form(page, timeout=30):
|
||||
return {"success": False, "token": "", "user": {},
|
||||
"message": "登录页 40 秒未渲染完成(网络异常或平台改版)"}
|
||||
|
||||
_fill(page, account, password)
|
||||
_log(f"已打开登录页并预填账号 {account}(密码仅本地预填,可自行修改)")
|
||||
_log(f"请在浏览器里输入图形验证码并点「登 录」,插件会等待 {wait_seconds} 秒…")
|
||||
_log("提示:本方式不自动提交表单,不会消耗接口登录的重试轮次")
|
||||
|
||||
deadline = time.time() + wait_seconds
|
||||
next_tip = time.time() + config.MANUAL_TIP_SECONDS
|
||||
while time.time() < deadline:
|
||||
if not _alive(page):
|
||||
return {"success": False, "token": "", "user": {},
|
||||
"message": "浏览器被关闭,人工登录已取消"}
|
||||
|
||||
user = _read_user(page)
|
||||
if user:
|
||||
token = str(user.get("token") or "")
|
||||
merchant = str(user.get("merchantName") or user.get("userName") or account)
|
||||
_log(f"人工登录成功:{merchant}(token {token[:12]}…)")
|
||||
return {"success": True, "token": token, "user": user,
|
||||
"message": "人工登录成功", "merchant": merchant}
|
||||
|
||||
if time.time() >= next_tip:
|
||||
_log(f"仍在等待人工登录,剩余 {int(deadline - time.time())} 秒…")
|
||||
next_tip = time.time() + config.MANUAL_TIP_SECONDS
|
||||
time.sleep(config.MANUAL_POLL_SECONDS)
|
||||
|
||||
return {"success": False, "token": "", "user": {},
|
||||
"message": f"人工登录等待超时({wait_seconds} 秒),未检测到登录成功"}
|
||||
except Exception as exc:
|
||||
return {"success": False, "token": "", "user": {},
|
||||
"message": f"人工登录异常:{exc}"}
|
||||
finally:
|
||||
# 只关窗口,保留该账号的 profile(cookie / 指纹延续,下次打开像本人浏览器)
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,152 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0079 导出模块:天阙交易记录导出(平台服务端生成 xlsx,本地只负责触发 + 取件)。
|
||||
|
||||
链路(2026-11 实测,与网页完全一致):
|
||||
1) POST tranInfoPc/exportNew 提交导出任务(响应体为空,成功与否靠下载中心判断)
|
||||
2) POST download/downLoadList 轮询下载中心,等本次新增且 exportStatus=1 的记录
|
||||
3) GET <record.downloadUrl> OSS 预签名地址,直接下载,不需要带 token
|
||||
4) POST download/read/<id> 标记已读,避免下载中心越堆越多
|
||||
|
||||
已知坑位:
|
||||
- exportNew 返回 0 字节,不能按 JSON 解析。
|
||||
- download/polling 只是前端进度圈,脚本不用它,省掉一堆无意义请求。
|
||||
- 下载中心是全账号共享的历史列表,必须用「提交前的 id 集合 + 增量」认领自己的任务,
|
||||
否则会下到历史文件;文件名里的时间串也不能当唯一标识。
|
||||
- downloadUrl 带 expires/signature,有时效,拿到要立刻下。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
from . import tianque_login as login_mod
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
def submit_export(session, begin, end):
|
||||
"""提交交易记录导出任务。"""
|
||||
payload = dict(config.EXPORT_TEMPLATE)
|
||||
payload["startTime"] = begin
|
||||
payload["endTime"] = end
|
||||
_log(f"提交导出任务:{begin} ~ {end}", "DEBUG")
|
||||
body = login_mod.api_post(session, config.API_EXPORT, payload)
|
||||
if body.get("_empty"):
|
||||
_log(f"导出任务已提交(HTTP {body.get('_status')},空响应属正常)")
|
||||
else:
|
||||
_log(f"导出任务响应:{str(body)[:200]}", "DEBUG")
|
||||
return payload
|
||||
|
||||
|
||||
def download_list(session):
|
||||
"""下载中心列表(新→旧)。"""
|
||||
body = login_mod.api_post(session, config.API_DOWNLOAD_LIST,
|
||||
{"pageNum": 1, "pageSize": config.LIST_PAGE_SIZE})
|
||||
data = (body or {}).get("data") or {}
|
||||
return data.get("content") or []
|
||||
|
||||
|
||||
def wait_new_record(session, before_ids, timeout=None, interval=None):
|
||||
"""等下载中心出现本次新增且导出完成的记录。"""
|
||||
timeout = timeout or config.POLL_TIMEOUT
|
||||
interval = interval or config.POLL_INTERVAL
|
||||
deadline = time.time() + timeout
|
||||
last_desc = ""
|
||||
while time.time() < deadline:
|
||||
for rec in download_list(session):
|
||||
if rec.get("id") in before_ids:
|
||||
continue
|
||||
if config.TRADE_SOURCE and config.TRADE_SOURCE not in (rec.get("fileSource") or ""):
|
||||
continue
|
||||
status = str(rec.get("exportStatus") or "")
|
||||
desc = rec.get("exportStatusDesc") or status
|
||||
if status == config.EXPORT_STATUS_DONE and rec.get("downloadUrl"):
|
||||
return rec
|
||||
if desc != last_desc:
|
||||
_log(f"任务状态:{rec.get('fileName')} → {desc}")
|
||||
last_desc = desc
|
||||
time.sleep(interval)
|
||||
raise RuntimeError(f"等了 {timeout} 秒仍未等到导出完成,可调大 POLL_TIMEOUT 或去平台下载中心确认")
|
||||
|
||||
|
||||
def download_file(session, rec, out_path):
|
||||
"""GET 预签名地址下载,落盘到 out_path。"""
|
||||
url = rec.get("downloadUrl") or ""
|
||||
if not url:
|
||||
raise RuntimeError("下载记录里没有 downloadUrl")
|
||||
_log(f"开始下载:{os.path.basename(out_path)}", "DEBUG")
|
||||
resp = session.get(url, timeout=config.DOWNLOAD_TIMEOUT)
|
||||
resp.raise_for_status()
|
||||
content = resp.content
|
||||
if not content:
|
||||
raise RuntimeError("下载到的文件为空")
|
||||
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(content)
|
||||
return len(content)
|
||||
|
||||
|
||||
def mark_read(session, rec_id):
|
||||
"""标记已读(失败只告警,不影响产物)。"""
|
||||
if not rec_id:
|
||||
return
|
||||
try:
|
||||
body = login_mod.api_post(session, config.API_MARK_READ + str(rec_id), {})
|
||||
_log(f"已标记已读:{body.get('data') or body.get('message')}", "DEBUG")
|
||||
except Exception as exc:
|
||||
_log(f"标记已读失败(不影响文件):{exc}", "WARN")
|
||||
|
||||
|
||||
def safe_name(text):
|
||||
"""文件名清洗(商户名可能含空格/斜杠等)。"""
|
||||
bad = '\\/:*?"<>|\r\n\t'
|
||||
cleaned = "".join("_" if ch in bad else ch for ch in str(text or "")).strip(" .")
|
||||
return cleaned or "商户"
|
||||
|
||||
|
||||
def export_trade(account, password, save_dir, begin, end, stamp,
|
||||
progress_from=0, progress_to=45, login_mode=None):
|
||||
"""单账号完整导出。返回 {success, merchant, file, size, message}。
|
||||
|
||||
文件名 = {商户名}_交易记录_{日期区间}.xlsx(商户名登录后才拿到,故在函数内生成)。
|
||||
login_mode:自动(接口登录)/ 人工登录(弹浏览器人工过验证码)。
|
||||
"""
|
||||
def step(pct):
|
||||
span = progress_to - progress_from
|
||||
config.progress(progress_from + int(span * pct / 100.0))
|
||||
|
||||
result = {"success": False, "merchant": "", "file": "", "size": 0, "message": ""}
|
||||
|
||||
step(5)
|
||||
login_result = login_mod.ensure_login(account, password, login_mode)
|
||||
if not login_result.get("success"):
|
||||
result["message"] = login_result.get("message") or "登录失败"
|
||||
return result
|
||||
|
||||
session = login_result["session"]
|
||||
merchant = login_result.get("merchant") or account
|
||||
result["merchant"] = merchant
|
||||
file_name = f"{safe_name(merchant)}_{config.FILE_TITLE}_{stamp}.xlsx"
|
||||
step(25)
|
||||
|
||||
before_ids = {rec.get("id") for rec in download_list(session)}
|
||||
_log(f"[{merchant}] 提交前下载中心已有 {len(before_ids)} 条记录", "DEBUG")
|
||||
|
||||
submit_export(session, begin, end)
|
||||
step(40)
|
||||
|
||||
_log(f"[{merchant}] 等待平台生成文件…")
|
||||
rec = wait_new_record(session, before_ids)
|
||||
_log(f"[{merchant}] 导出完成:{rec.get('fileName')}")
|
||||
step(70)
|
||||
|
||||
out_path = os.path.join(save_dir, file_name)
|
||||
size = download_file(session, rec, out_path)
|
||||
mark_read(session, rec.get("id"))
|
||||
step(100)
|
||||
|
||||
result.update({"success": True, "file": out_path, "size": size,
|
||||
"message": f"{os.path.basename(out_path)}({size / 1024:.0f} KB)"})
|
||||
_log(f"[{merchant}] 已落盘:{out_path}({size} 字节)")
|
||||
return result
|
||||
@@ -0,0 +1,311 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0079 登录模块:天阙会生活商户平台账密登录(纯接口,自包含)。
|
||||
|
||||
登录流程(与网页完全一致,2026-11 抓包 + 前端 bundle 核实):
|
||||
1) POST bankLogin/imageCode {} → data.imageKey + data.captchaBase64
|
||||
2) ddddocr 识别 4 位图形验证码(同一 imageKey 只能提交一次,识别不中直接换图)
|
||||
3) POST user/transForm/login {header:{sysType:pc}, data:{loginAcc, loginPwd, imageCode, imageKey}}
|
||||
loginPwd = AES-128-ECB/Pkcs7/Base64(明文密码),key 固定 abcdefgabcdefg12
|
||||
→ code=0000 时 data.users[0].token 即后续业务接口的请求头 token
|
||||
|
||||
两种登录方式(登录方式字段可选):
|
||||
- 自动:上面这套纯接口流程,验证码用 ddddocr 识别;
|
||||
- 人工登录:交给 tianque_browser.manual_login,弹浏览器预填账号密码,人工过验证码,
|
||||
不自动提交表单,不消耗接口登录重试轮次。两种方式都优先复用本机缓存的 token。
|
||||
|
||||
已知坑位:
|
||||
- 站点 HTTPS 用弱 DH 参数,Python/OpenSSL3 直连报 DH_KEY_TOO_SMALL,必须把 SECLEVEL 降到 0。
|
||||
- 登录 body 必须套 {header,data} 信封;漏了信封服务端取不到 data,只会回 code=1003
|
||||
「用户名或密码错误」,非常误导(业务接口相反:扁平 body,套了信封回 0003 参数不完整)。
|
||||
- 1003 同时代表「验证码识别错」和「账号密码错」,服务端不区分,因此只能换图重试有限轮次。
|
||||
- token 按账号缓存,复用时先用只读探针校验,避免拿着过期 token 白跑。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
|
||||
import requests
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util.Padding import pad
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
# ==================== 会话 ====================
|
||||
class _LowSecAdapter(HTTPAdapter):
|
||||
"""站点 DH 参数过弱(OpenSSL 3 默认拒绝),这里降级安全级别。"""
|
||||
|
||||
def init_poolmanager(self, *args, **kwargs):
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.set_ciphers("DEFAULT@SECLEVEL=0")
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
kwargs["ssl_context"] = ctx
|
||||
return super().init_poolmanager(*args, **kwargs)
|
||||
|
||||
|
||||
def new_session():
|
||||
session = requests.Session()
|
||||
session.mount("https://", _LowSecAdapter())
|
||||
session.headers.update({
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Origin": config.BASE_URL,
|
||||
"Referer": config.BASE_URL + "/login",
|
||||
"channel": config.CHANNEL,
|
||||
"omp_sui_pc": "pc",
|
||||
"User-Agent": config.UA,
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 请求封装 ====================
|
||||
def envelope(payload):
|
||||
"""user/transForm/* 这组接口的 body 信封。"""
|
||||
return {"header": {"sysType": "pc"}, "data": payload}
|
||||
|
||||
|
||||
def api_post(session, path, payload=None):
|
||||
"""POST 业务接口。返回解析后的 dict;空响应体返回 {'_empty': True}(exportNew 就是空响应)。"""
|
||||
resp = session.post(config.BASE_URL + path,
|
||||
json=payload if payload is not None else {},
|
||||
timeout=config.TIMEOUT)
|
||||
text = (resp.text or "").strip()
|
||||
if not text:
|
||||
return {"_empty": True, "_status": resp.status_code}
|
||||
try:
|
||||
return resp.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f"{path} 返回非 JSON(HTTP {resp.status_code}):{text[:200]}")
|
||||
|
||||
|
||||
def resp_code(body):
|
||||
"""业务返回码:新接口用 code,老接口用 errorType。"""
|
||||
if not isinstance(body, dict):
|
||||
return ""
|
||||
code = body.get("code")
|
||||
if code is None:
|
||||
code = body.get("errorType")
|
||||
return "" if code is None else str(code)
|
||||
|
||||
|
||||
def resp_msg(body):
|
||||
if not isinstance(body, dict):
|
||||
return ""
|
||||
return str(body.get("msg") or body.get("message") or "")
|
||||
|
||||
|
||||
# ==================== 密码加密 / 验证码 ====================
|
||||
def enc_password(password):
|
||||
"""AES-128-ECB + Pkcs7 + Base64,与前端 CryptoJS 实现逐字一致。"""
|
||||
cipher = AES.new(config.AES_KEY, AES.MODE_ECB)
|
||||
return base64.b64encode(cipher.encrypt(pad(password.encode("utf-8"), 16))).decode()
|
||||
|
||||
|
||||
def fetch_captcha(session):
|
||||
"""返回 (imageKey, 图片 bytes)。同一 imageKey 登录只能提交一次。"""
|
||||
body = api_post(session, config.API_IMAGE_CODE)
|
||||
data = (body or {}).get("data") or {}
|
||||
image_key = str(data.get("imageKey") or "")
|
||||
b64 = str(data.get("captchaBase64") or "")
|
||||
if not image_key or not b64:
|
||||
raise RuntimeError(f"获取图形验证码失败:{json.dumps(body, ensure_ascii=False)[:200]}")
|
||||
return image_key, base64.b64decode(b64)
|
||||
|
||||
|
||||
def ocr_code(img_bytes):
|
||||
"""ddddocr 识别验证码;位数/字符不符直接返回空串(换图,不浪费提交次数)。"""
|
||||
try:
|
||||
import ddddocr
|
||||
except ImportError:
|
||||
raise RuntimeError("未安装 ddddocr,请先 pip install ddddocr")
|
||||
code = ddddocr.DdddOcr(show_ad=False).classification(img_bytes).strip()
|
||||
if len(code) == config.CAPTCHA_LEN and code.isascii() and code.isalnum():
|
||||
return code
|
||||
return ""
|
||||
|
||||
|
||||
def do_login(session, account, password, image_key, image_code):
|
||||
payload = envelope({
|
||||
"loginAcc": account,
|
||||
"loginPwd": enc_password(password),
|
||||
"imageCode": image_code,
|
||||
"imageKey": image_key,
|
||||
})
|
||||
return api_post(session, config.API_LOGIN, payload)
|
||||
|
||||
|
||||
# ==================== token 校验与缓存 ====================
|
||||
def verify_token(session):
|
||||
"""只读探针校验 token(业务接口用扁平 body)。返回 (ok, 说明)。"""
|
||||
try:
|
||||
body = api_post(session, config.API_PROBE, {"queryType": "D"})
|
||||
except Exception as exc:
|
||||
return False, f"探针异常:{exc}"
|
||||
code = resp_code(body)
|
||||
if code in config.CODE_OK:
|
||||
return True, "有效"
|
||||
return False, f"code={code} {resp_msg(body)}"
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
tmp = f"{path}.tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def load_cached(account):
|
||||
"""读该账号缓存的 token,返回 dict 或 None。"""
|
||||
path = config.get_token_file()
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
all_data = json.load(f) or {}
|
||||
return (all_data.get("accounts") or {}).get(config.account_key(account))
|
||||
except Exception as exc:
|
||||
_log(f"读取 token 缓存失败(忽略):{exc}", "WARN")
|
||||
return None
|
||||
|
||||
|
||||
def save_cached(account, token, merchant):
|
||||
path = config.get_token_file()
|
||||
try:
|
||||
all_data = {"accounts": {}}
|
||||
if os.path.exists(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
all_data = json.load(f) or {}
|
||||
except Exception:
|
||||
all_data = {"accounts": {}}
|
||||
all_data.setdefault("accounts", {})[config.account_key(account)] = {
|
||||
"token": token,
|
||||
"merchant": merchant,
|
||||
"savedAt": int(time.time()),
|
||||
}
|
||||
_atomic_write(path, json.dumps(all_data, ensure_ascii=False, indent=2))
|
||||
_log(f"token 已缓存({merchant or account})", "DEBUG")
|
||||
except Exception as exc:
|
||||
_log(f"token 缓存写入失败(不影响本次运行):{exc}", "WARN")
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def ensure_login(account, password, login_mode=None):
|
||||
"""确保拿到可用 token。
|
||||
|
||||
login_mode:
|
||||
- 自动(默认):接口登录(验证码 OCR),静默不弹浏览器;
|
||||
- 人工登录:弹可见浏览器预填账号密码,人工输验证码并点登录,插件读 sessionStorage 取 token。
|
||||
返回 dict:{success, session, token, user, merchant, message, reused}
|
||||
失败时 success=False,message 说明原因(账号密码错误不重试,避免锁号)。
|
||||
"""
|
||||
account = str(account or "").strip()
|
||||
password = str(password or "").strip()
|
||||
login_mode = login_mode or config.LOGIN_AUTO
|
||||
|
||||
session = new_session()
|
||||
|
||||
# 1) 先试缓存 token(两种登录方式都优先复用它,省一次验证码)
|
||||
cached = load_cached(account)
|
||||
if cached and cached.get("token"):
|
||||
session.headers["token"] = cached["token"]
|
||||
ok, why = verify_token(session)
|
||||
if ok:
|
||||
merchant = cached.get("merchant") or account
|
||||
_log(f"复用缓存登录态:{merchant}(token 仍有效)")
|
||||
return {"success": True, "session": session, "token": cached["token"],
|
||||
"user": {"merchantName": merchant}, "merchant": merchant,
|
||||
"message": "复用缓存登录态", "reused": True}
|
||||
_log(f"缓存 token 已失效({why}),改为{'人工' if login_mode == config.LOGIN_MANUAL else '接口'}登录")
|
||||
|
||||
# 2) 人工登录通道:不自动提交表单,验证码由人看,不消耗重试轮次
|
||||
if login_mode == config.LOGIN_MANUAL:
|
||||
from . import tianque_browser # 延迟导入:只有人工登录才需要 DrissionPage
|
||||
result = tianque_browser.manual_login(account, password)
|
||||
if not result.get("success"):
|
||||
return {"success": False, "session": session, "token": "", "user": {},
|
||||
"merchant": "", "reused": False,
|
||||
"message": result.get("message") or "人工登录失败"}
|
||||
token = result["token"]
|
||||
merchant = result.get("merchant") or account
|
||||
session.headers["token"] = token
|
||||
ok, why = verify_token(session)
|
||||
if not ok:
|
||||
_log(f"人工登录已拿到 token,但探针校验未通过({why}),仍继续尝试导出", "WARN")
|
||||
save_cached(account, token, merchant)
|
||||
return {"success": True, "session": session, "token": token,
|
||||
"user": result.get("user") or {}, "merchant": merchant,
|
||||
"message": "人工登录成功", "reused": False}
|
||||
|
||||
if not (account and password):
|
||||
return {"success": False, "message": "登录账号/密码缺失:请在插件界面填写并保存配置",
|
||||
"session": session, "token": "", "user": {}, "merchant": "", "reused": False}
|
||||
|
||||
# 3) 账密登录(验证码识别失败换图重试,轮次有限)
|
||||
last_msg = ""
|
||||
for attempt in range(1, config.LOGIN_MAX_ATTEMPTS + 1):
|
||||
_log(f"登录第 {attempt}/{config.LOGIN_MAX_ATTEMPTS} 轮({account})")
|
||||
try:
|
||||
image_key, img = fetch_captcha(session)
|
||||
code = ocr_code(img)
|
||||
except Exception as exc:
|
||||
last_msg = f"获取验证码异常:{exc}"
|
||||
_log(last_msg, "WARN")
|
||||
time.sleep(config.LOGIN_RETRY_SLEEP)
|
||||
continue
|
||||
|
||||
if not code:
|
||||
last_msg = "本轮验证码未识别出来"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
_log(f"图形验证码 OCR:{code}", "DEBUG")
|
||||
|
||||
try:
|
||||
body = do_login(session, account, password, image_key, code)
|
||||
except Exception as exc:
|
||||
last_msg = f"登录请求异常:{exc}"
|
||||
_log(last_msg, "WARN")
|
||||
time.sleep(config.LOGIN_RETRY_SLEEP)
|
||||
continue
|
||||
|
||||
code_str = resp_code(body)
|
||||
msg = resp_msg(body)
|
||||
if code_str in config.CODE_OK:
|
||||
data = body.get("data") or {}
|
||||
users = data.get("users") or []
|
||||
if not users:
|
||||
return {"success": False, "session": session, "token": "", "user": {},
|
||||
"merchant": "", "reused": False,
|
||||
"message": f"登录成功但无用户信息:{json.dumps(body, ensure_ascii=False)[:200]}"}
|
||||
user = users[0]
|
||||
token = str(user.get("token") or "")
|
||||
merchant = str(user.get("merchantName") or user.get("userName") or account)
|
||||
session.headers["token"] = token
|
||||
_log(f"登录成功:{merchant}(mno={user.get('mno')})")
|
||||
save_cached(account, token, merchant)
|
||||
return {"success": True, "session": session, "token": token, "user": user,
|
||||
"merchant": merchant, "message": "登录成功", "reused": False}
|
||||
|
||||
last_msg = f"code={code_str} {msg}"
|
||||
_log(f"登录未通过:{last_msg}", "WARN")
|
||||
# 1003 = 验证码错或账号密码错(服务端不区分)→ 换图再试一轮
|
||||
if code_str == config.CODE_BAD_OR_CAPTCHA:
|
||||
time.sleep(config.LOGIN_RETRY_SLEEP)
|
||||
continue
|
||||
# 其它错误(未绑账号等)重试无意义
|
||||
return {"success": False, "session": session, "token": "", "user": {},
|
||||
"merchant": "", "reused": False,
|
||||
"message": f"登录失败:{msg or code_str}(如为账号密码错误,请先在网页端确认,避免锁号)"}
|
||||
|
||||
return {"success": False, "session": session, "token": "", "user": {}, "merchant": "",
|
||||
"reused": False,
|
||||
"message": f"{config.LOGIN_MAX_ATTEMPTS} 轮登录均未通过({last_msg});"
|
||||
f"多为验证码识别率问题,可重跑,若持续失败请核对账号密码"}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""逻辑层:日期区间、文件名等纯计算。"""
|
||||
@@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出时间区间计算:默认「昨天 00:00:00 ~ 今天 23:59:59」,也支持指定日期段。
|
||||
|
||||
天阙导出接口 startTime/endTime 要求 `YYYY-MM-DD HH:mm:ss`(固定补零),
|
||||
前端日期选择器只给 yyyy-MM-dd,时间部分在这里补:开始 00:00:00 / 结束 23:59:59。
|
||||
"""
|
||||
import re
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
DATETIME_FMT = '{y:04d}-{m:02d}-{d:02d} {h:02d}:{mi:02d}:{s:02d}'
|
||||
|
||||
|
||||
def _fmt(y, m, d, h=0, mi=0, s=0):
|
||||
return DATETIME_FMT.format(y=y, m=m, d=d, h=h, mi=mi, s=s)
|
||||
|
||||
|
||||
def normalize(value, default_time):
|
||||
"""把 yyyy-MM-dd / yyyy/M/d H:mm:ss 归一化成平台格式;只给日期时按 default_time 补时间。"""
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
raise ValueError('时间为空')
|
||||
nums = re.findall(r'\d+', text)
|
||||
if len(nums) < 3:
|
||||
raise ValueError('无法识别的时间 %r,请用 yyyy-MM-dd 格式' % text)
|
||||
y, m, d = int(nums[0]), int(nums[1]), int(nums[2])
|
||||
if len(nums) >= 5:
|
||||
h, mi = int(nums[3]), int(nums[4])
|
||||
s = int(nums[5]) if len(nums) >= 6 else 0
|
||||
else:
|
||||
h, mi, s = (int(x) for x in default_time.split(':'))
|
||||
datetime(y, m, d, h, mi, s) # 合法性校验(非法日期直接抛错)
|
||||
return _fmt(y, m, d, h, mi, s)
|
||||
|
||||
|
||||
def build_range(date_from='', date_to=''):
|
||||
"""返回 (begin, end) 平台格式字符串。
|
||||
|
||||
- 都留空:昨天 00:00:00 ~ 今天 23:59:59(按执行日推算,定时任务无需固定日期)
|
||||
- 只给开始:结束 = 开始(单日)
|
||||
- 都给了:自动补 00:00:00 / 23:59:59
|
||||
"""
|
||||
df = str(date_from or '').strip()
|
||||
dt = str(date_to or '').strip()
|
||||
if not df and not dt:
|
||||
today = date.today()
|
||||
yesterday = today - timedelta(days=1)
|
||||
begin = _fmt(yesterday.year, yesterday.month, yesterday.day, 0, 0, 0)
|
||||
end = _fmt(today.year, today.month, today.day, 23, 59, 59)
|
||||
else:
|
||||
if not df:
|
||||
df = dt
|
||||
if not dt:
|
||||
dt = df
|
||||
begin = normalize(df, '00:00:00')
|
||||
end = normalize(dt, '23:59:59')
|
||||
|
||||
if _parse(end) < _parse(begin):
|
||||
raise ValueError('结束日期 %s 早于开始日期 %s' % (dt or end, df or begin))
|
||||
return begin, end
|
||||
|
||||
|
||||
def _parse(text):
|
||||
nums = [int(x) for x in re.findall(r'\d+', text)]
|
||||
return datetime(nums[0], nums[1], nums[2], nums[3], nums[4], nums[5])
|
||||
|
||||
|
||||
def file_stamp(begin, end):
|
||||
"""文件名用日期区间:20261105-20261106(同日则 20261106-20261106)。"""
|
||||
def one(text):
|
||||
nums = re.findall(r'\d+', text)
|
||||
return '%04d%02d%02d' % (int(nums[0]), int(nums[1]), int(nums[2]))
|
||||
|
||||
try:
|
||||
return '%s-%s' % (one(begin), one(end))
|
||||
except Exception:
|
||||
return date.today().strftime('%Y%m%d')
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0079",
|
||||
"name": "金色湖畔扫码数据导出",
|
||||
"version": "1.1.4",
|
||||
"description": "天阙会生活商户平台(mch-web.tianquetech.com)扫码交易记录接口化导出:账密自动登录(图形验证码 OCR + AES 密码加密,token 按账号缓存复用)→ 平台导出接口生成 xlsx → 下载中心取文件直存本地;支持两套账号串行导出(第 2 套可留空),日期区间可在界面选择(默认昨天 00:00:00 ~ 今天 23:59:59),产物按商户名区分。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": [
|
||||
"xq0079"
|
||||
],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tq_account1": {
|
||||
"type": "string",
|
||||
"title": "账号一",
|
||||
"default": "",
|
||||
"description": "天阙商户平台登录账号(手机号/商户编号)"
|
||||
},
|
||||
"tq_password1": {
|
||||
"type": "string",
|
||||
"title": "密码一",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "账号一密码,仅保存在本机配置(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"tq_account2": {
|
||||
"type": "string",
|
||||
"title": "账号二",
|
||||
"default": "",
|
||||
"description": "第二个账号,留空则只导出账号一"
|
||||
},
|
||||
"tq_password2": {
|
||||
"type": "string",
|
||||
"title": "密码二",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "账号二密码,仅保存在本机配置"
|
||||
},
|
||||
"login_mode": {
|
||||
"type": "string",
|
||||
"title": "登录方式",
|
||||
"default": "自动",
|
||||
"enum": [
|
||||
"自动",
|
||||
"人工登录"
|
||||
],
|
||||
"description": "自动=接口登录(图形验证码 OCR,静默不弹浏览器);人工登录=弹出浏览器并预填账号密码,人工输入验证码并点登录(验证码识别不准时用这项,不消耗接口登录重试次数)"
|
||||
},
|
||||
"date_from": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"title": "开始日期",
|
||||
"default": "",
|
||||
"description": "yyyy-MM-dd;留空=昨天"
|
||||
},
|
||||
"date_to": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"title": "结束日期",
|
||||
"default": "",
|
||||
"description": "yyyy-MM-dd;留空=今天"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "D:\\资料\\财务\\金色湖畔扫码数据导出",
|
||||
"description": "导出的 xlsx 统一输出目录,文件名为 商户名_交易记录_起止日期.xlsx"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出完整调试日志(默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"tq_account1",
|
||||
"tq_password1"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
requests>=2.31.0
|
||||
pycryptodome>=3.19.0
|
||||
ddddocr>=1.4
|
||||
DrissionPage>=4.1
|
||||
@@ -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>金色湖畔扫码数据导出</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0079-ui",
|
||||
"private": true,
|
||||
"version": "1.0.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,290 @@
|
||||
<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="acc-row acc-fields">
|
||||
<span class="acc-tag">账号一<b class="req">*</b></span>
|
||||
<el-input v-model="form.tq_account1" class="acc-input" :disabled="running" clearable
|
||||
placeholder="手机号 / 商户编号" />
|
||||
<el-input v-model="form.tq_password1" class="acc-pwd" type="password" show-password
|
||||
:disabled="running" placeholder="登录密码" />
|
||||
</div>
|
||||
<div class="acc-row acc-fields">
|
||||
<span class="acc-tag">账号二</span>
|
||||
<el-input v-model="form.tq_account2" class="acc-input" :disabled="running" clearable
|
||||
placeholder="留空则只导出账号一" />
|
||||
<el-input v-model="form.tq_password2" class="acc-pwd" type="password" show-password
|
||||
:disabled="running" placeholder="登录密码" />
|
||||
</div>
|
||||
<div class="acc-row">
|
||||
<span class="acc-tag">登录方式</span>
|
||||
<el-radio-group v-model="form.login_mode" class="mode-radio" :disabled="running">
|
||||
<el-radio-button value="自动">自动(接口登录)</el-radio-button>
|
||||
<el-radio-button value="人工登录">人工登录(弹浏览器)</el-radio-button>
|
||||
</el-radio-group>
|
||||
<span class="mode-tip">
|
||||
<template v-if="form.login_mode === '人工登录'">
|
||||
逐个账号弹浏览器并预填账密,你只需输<b>图形验证码</b>点「登 录」;不自动提交、不消耗重试次数,最久等 3 分钟
|
||||
</template>
|
||||
<template v-else>
|
||||
验证码自动识别,全程静默不弹浏览器;识别不中自动换图重试(最多 4 轮)
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
<div class="tip">
|
||||
两个账号各自独立登录、串行导出,一个失败不影响另一个;登录 token 按账号缓存在本机,
|
||||
有效期内两种方式都优先复用(免重复登录)。账号密码明文保存在本机配置,不会上传。
|
||||
</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 range-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>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
<b>{{ rangeText }}</b><br />
|
||||
每个账号导出一份 xlsx,文件名为 <b>商户名_交易记录_起止日期.xlsx</b>;
|
||||
<b>调试日志</b>开启后输出完整调试信息,默认关闭。
|
||||
</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>:先试本机缓存的 token,失效则账密登录(图形验证码自动识别,识别不中自动换图)。</div>
|
||||
<div class="hb-line"><b>② 触发导出</b>:调平台导出接口提交任务,服务端异步生成 xlsx。</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 = () => ({
|
||||
tq_account1: '',
|
||||
tq_password1: '',
|
||||
tq_account2: '',
|
||||
tq_password2: '',
|
||||
login_mode: '自动',
|
||||
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() {
|
||||
// 防误存首尾空格导致登录失败(平台会累计密码错误)
|
||||
;['tq_account1', 'tq_password1', 'tq_account2', 'tq_password2'].forEach((k) => {
|
||||
if (form[k] != null) form[k] = String(form[k]).trim()
|
||||
})
|
||||
if (!form.tq_account1) {
|
||||
ElMessage.warning('请填写账号一的登录账号')
|
||||
return false
|
||||
}
|
||||
if (!form.tq_password1) {
|
||||
ElMessage.warning('请填写账号一的登录密码')
|
||||
return false
|
||||
}
|
||||
const has2 = !!(form.tq_account2 || form.tq_password2)
|
||||
if (has2 && !form.tq_account2) {
|
||||
ElMessage.warning('账号二已填密码,请同时填写账号二账号')
|
||||
return false
|
||||
}
|
||||
if (has2 && !form.tq_password2) {
|
||||
ElMessage.warning('账号二已填账号,请同时填写账号二密码')
|
||||
return false
|
||||
}
|
||||
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} 天)`
|
||||
})
|
||||
|
||||
// 调用壳子本机接口打开原生「选择文件夹」对话框(壳子 /api/dialog/directory,仅返回路径)
|
||||
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>
|
||||
/* 插件差异样式:只用壳子 token,不写字面色值;左右内边距由壳子提供 */
|
||||
|
||||
/* ---------- 账号区:每组一行(账号 + 密码并排,输入框按内容需要收窄) ---------- */
|
||||
.acc-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2, 8px);
|
||||
margin-bottom: var(--space-2, 8px);
|
||||
}
|
||||
.acc-row:last-of-type { margin-bottom: var(--space-3, 12px); }
|
||||
.acc-tag {
|
||||
flex: 0 0 52px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary, #4e5969);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.acc-tag .req { color: var(--danger-color, #f53f3f); margin-left: 2px; }
|
||||
/* 账号/密码等宽平分(账号是手机号、密码也就十来位,两个框一样宽最整齐) */
|
||||
.acc-fields { max-width: 660px; }
|
||||
.acc-input, .acc-pwd { flex: 1 1 0; min-width: 140px; }
|
||||
.mode-radio { flex: 0 0 auto; }
|
||||
.mode-radio :deep(.el-radio-button__inner) { padding: 8px 14px; }
|
||||
.mode-tip {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-tertiary, #86909c);
|
||||
}
|
||||
.mode-tip b { color: var(--text-secondary, #4e5969); font-weight: 600; }
|
||||
@media (max-width: 760px) {
|
||||
.acc-row { flex-wrap: wrap; }
|
||||
.acc-input, .acc-pwd { flex: 1 1 100%; }
|
||||
.mode-tip { flex-basis: 100%; }
|
||||
}
|
||||
|
||||
/* ---------- 导出范围:日期 / 目录 / 调试日志 三列同一行(日期列更宽) ---------- */
|
||||
.range-grid { grid-template-columns: minmax(300px, 1.6fr) minmax(220px, 1fr) 92px; }
|
||||
@media (max-width: 760px) {
|
||||
.range-grid { grid-template-columns: 1fr 1fr; }
|
||||
}
|
||||
|
||||
/* ---------- 目录输入框 + 选择按钮(同一行两列) ---------- */
|
||||
.dir-ctrl { display: flex; align-items: center; gap: var(--space-2); width: 100%; }
|
||||
.dir-ctrl .dir-input { flex: 1 1 auto; min-width: 0; }
|
||||
.dir-ctrl .dir-btn { flex: 0 0 auto; }
|
||||
</style>
|
||||
@@ -0,0 +1,2 @@
|
||||
// 插件身份声明(API 实现收敛在 usePluginUI.js 公共 kit,各插件 ui-src 只需声明自己的 id)
|
||||
export const PLUGIN_ID = 'xq0079'
|
||||
@@ -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,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0079/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0079/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5229,
|
||||
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>金色湖畔扫码数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0079/assets/index-DQPTxTn5.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0079/assets/index-CD68zYdd.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user