feat: 重构控制面安全机制与分页规范
本次提交包含多项安全加固和体验优化: 1. 分离管理密钥与传输凭证,避免持 API Token 者伪造管理员票据 2. 钉钉回调地址增加白名单校验,防止开放重定向钓鱼 3. 初始管理员密码改为随机生成并日志记录,移除硬编码 123456 4. 新增登录防爆破计数表,支持 MySQL 多 worker 共享 5. 统一分页规范,新增 usePagedList composable 和 PagerBar 组件 6. 控制面 CORS 收敛为白名单,避免公网环境下任意站点跨域 7. 插件管理、凭证管理等列表接口支持分页和搜索 8. 强制初始密码修改,未改密前禁止使用管理功能 9. 定时任务触发被拒日志节流,避免授权失效时刷屏 10. 健康检查接口移除环境信息泄露,返回固定响应
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金色印象通联数据导出 - webhost 场景插件(XQ0045 + XQ0046 合并版)
|
||||
|
||||
通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:
|
||||
- XQ0045 按日:导某一天(YYYY-MM-DD)的交易;
|
||||
- XQ0046 按月:导某个月(YYYY-MM)的交易;
|
||||
服务端导出接口忽略商户参数、始终返回账号全量结果集(实测),因此每个日期只导一份
|
||||
全量文件(含账号下所有商户),直存本地,不再按商户拆分。
|
||||
|
||||
个性化设计:
|
||||
- 通联登录账号密码由插件界面配置经 fields 注入(plugin_configs 本机保存,下次免填);
|
||||
- 浏览器现场真登录(固定默认用户目录 + ddddocr 验证码识别),登录后转 requests.Session
|
||||
直调导出接口(服务端有 Referer 外链校验,插件内统一带 Referer);
|
||||
- 日期支持多个(逗号分隔,逐个导出);mode=日+月 时按日期串格式自动识别日/月。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import allinpay_login, allinpay_export
|
||||
|
||||
MODE_DAY = '日'
|
||||
MODE_MONTH = '月'
|
||||
MODE_BOTH = '日+月'
|
||||
|
||||
CONTENT_TRX = '交易查询'
|
||||
CONTENT_BILL = '账单'
|
||||
CONTENT_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _default_save_dir():
|
||||
return str(Path(config.get_desktop()) / f"金色印象通联数据_{datetime.now():%Y%m%d}")
|
||||
|
||||
|
||||
def _build_tasks(mode, day_date, month_date):
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(前端已用日期选择器选好值,这里只做组装)。"""
|
||||
tasks = []
|
||||
if mode in (MODE_DAY, MODE_BOTH) and day_date:
|
||||
tasks.append((MODE_DAY, day_date))
|
||||
if mode in (MODE_MONTH, MODE_BOTH) and month_date:
|
||||
tasks.append((MODE_MONTH, month_date))
|
||||
if not tasks:
|
||||
raise RuntimeError("请选择按日导出的日期和/或按月导出的月份")
|
||||
return tasks
|
||||
|
||||
|
||||
class TongLianExportPlugin(ScenePlugin):
|
||||
id = "xq0045_xq0046"
|
||||
name = "金色印象通联数据导出"
|
||||
version = "1.0.5"
|
||||
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
|
||||
"账号全量数据导出(含全部商户),服务端生成文件直存本地")
|
||||
platform = "" # 通联自带登录页(验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0045_xq0046"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致(ui=true 前端自渲染,此处分层作为参数契约文档)
|
||||
fields = {
|
||||
"mode": {"type": "string", "title": "执行模式", "default": MODE_BOTH,
|
||||
"enum": [MODE_BOTH, MODE_DAY, MODE_MONTH]},
|
||||
"content": {"type": "string", "title": "导出内容", "default": CONTENT_BOTH,
|
||||
"enum": [CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL]},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": ""},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": ""},
|
||||
"tl_username": {"type": "string", "title": "通联登录账号", "default": ""},
|
||||
"tl_password": {"type": "string", "title": "通联登录密码", "default": ""},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
content = str(fields.get("content") or CONTENT_BOTH).strip()
|
||||
username = str(fields.get("tl_username") or "").strip()
|
||||
password = str(fields.get("tl_password") or "")
|
||||
day_date = str(fields.get("day_date") or "").strip()
|
||||
month_date = str(fields.get("month_date") or "").strip()
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or _default_save_dir()
|
||||
|
||||
if not username or not password:
|
||||
raise RuntimeError("通联登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_DAY, MODE_MONTH):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if content not in (CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL):
|
||||
raise RuntimeError(f"未知导出内容:{content}")
|
||||
|
||||
do_trx = content in (CONTENT_TRX, CONTENT_BOTH)
|
||||
do_bill = content in (CONTENT_BILL, CONTENT_BOTH)
|
||||
tasks = _build_tasks(mode, day_date, month_date)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"导出内容:{content},模式:{mode},任务 {len(tasks)} 项,保存目录:{save_dir}")
|
||||
|
||||
# ---------- 登录 ----------
|
||||
ctx.progress(3)
|
||||
ctx.log("开始通联平台登录(接口优先,浏览器兜底)…")
|
||||
session = allinpay_login.tl_login(username, password)
|
||||
if session is None:
|
||||
raise RuntimeError("通联平台登录失败(账号密码错误或验证码多次识别失败),详见日志")
|
||||
ctx.progress(10)
|
||||
|
||||
saved, failed = [], []
|
||||
|
||||
# ---------- 交易查询导出(15~70:每个任务导一份账号全量,服务端忽略商户参数) ----------
|
||||
if do_trx:
|
||||
# 服务端 cusid 不能传空串(传空会直接 504),但会忽略其筛选语义、始终返回
|
||||
# 账号全量结果集;故取账号下首个真实商户号作为种子参数即可。
|
||||
ctx.log("获取账号商户列表(取首个商户号作查询种子,服务端返回全量)…")
|
||||
cus_list = allinpay_export.get_cus_list(session)
|
||||
seed_cusid = cus_list[0]['key'] if cus_list else ''
|
||||
ctx.log(f"账号下商户 {len(cus_list)} 个,查询种子商户号:{seed_cusid}")
|
||||
if not seed_cusid:
|
||||
raise RuntimeError("获取商户列表失败:账号下无商户,无法发起导出")
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"交易[{m} {d}](账号全量)"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
start, end = allinpay_export.build_date_range(m, d)
|
||||
ctx.log(f" 查询区间 {start} ~ {end}")
|
||||
fid = allinpay_export.start_export(session, seed_cusid, start, end)
|
||||
ctx.log(f" 导出任务已提交 fid={fid},等待服务端生成…")
|
||||
allinpay_export.wait_export_done(session, fid)
|
||||
url = allinpay_export.get_download_url(session, fid)
|
||||
ctx.log(" 开始下载导出文件…")
|
||||
path = allinpay_export.download_file(session, url, save_dir, f"{m}交易查询结果_{d}")
|
||||
saved.append(path)
|
||||
except Exception as e:
|
||||
ctx.log(f" 交易导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(15 + int(55 * done / max(1, units)))
|
||||
ctx.progress(70)
|
||||
|
||||
# ---------- 账单导出(70~95,主账号 zip 下载 + 解压) ----------
|
||||
if do_bill:
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"账单[{m} {d}]"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
bill_type = 'month' if m == MODE_MONTH else 'day'
|
||||
_, extract_dir = allinpay_export.bill_download(
|
||||
session, d, bill_type, save_dir)
|
||||
saved.append(extract_dir)
|
||||
except Exception as e:
|
||||
ctx.log(f" 账单导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(70 + int(25 * done / max(1, units)))
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件/目录:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = (f"通联数据导出完成(部分失败):成功 {len(saved)} 个,"
|
||||
f"失败 {len(failed)} 项 → {save_dir}")
|
||||
else:
|
||||
summary = f"通联数据导出完成:共 {len(saved)} 个文件/目录 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
PLUGINS.append(TongLianExportPlugin())
|
||||
@@ -0,0 +1,42 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
把本插件压成 dist-plugin/xq0045_xq0046_v<版本>.zip,
|
||||
包根布局:plugin.json / 各 .py / requirements.txt 直接位于 zip 根。
|
||||
排除项:__pycache__、debug、.sessions、本脚本、*.pyc。
|
||||
|
||||
用法(仓库根下执行):
|
||||
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0045_XQ0046 金色印象通联数据导出\\_pack.py"
|
||||
随后发布(desktop/ 下执行,见 docs/插件/发版规范.md):
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \\
|
||||
dist-plugin/xq0045_xq0046_v1.0.0.zip --id xq0045_xq0046 --version 1.0.0
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
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 == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0045_xq0046 金色印象通联数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 通联平台 ====================
|
||||
LOGIN_URL = 'https://cus.allinpay.com/login'
|
||||
MAIN_URL = 'https://cus.allinpay.com/main.dsr' # 已登录首页(预热/Referer 来源)
|
||||
SEARCH_URL = 'https://cus.allinpay.com/tranx25/search'
|
||||
STATUS_URL = 'https://cus.allinpay.com/export/statusdownload'
|
||||
DOWNLOAD_INFO_URL = 'https://cus.allinpay.com/export/downloadexport/'
|
||||
BILL_URL = 'https://cus.allinpay.com/checkacct25/download'
|
||||
TRXCODE_URL = 'https://cus.allinpay.com/unauth/queryInterCode'
|
||||
TRXSTATE_URL = 'https://cus.allinpay.com/unauth/queryRecordState'
|
||||
|
||||
# 服务端有 Referer 外链校验:直接访问会被重定向回 /main.dsr
|
||||
SEARCH_HEADERS = {'Referer': MAIN_URL}
|
||||
|
||||
# ==================== 导出参数 ====================
|
||||
EXPORT_CURRENT = 'onebtnexpt' # 导出当前页
|
||||
EXPORT_ALL = 'all' # 导出全部(默认用这个)
|
||||
|
||||
# 异步导出状态轮询:每 6 秒一次,最多 12 次(服务端超时上限约 10 次/60 秒)
|
||||
STATUS_POLL_INTERVAL = 6
|
||||
STATUS_POLL_MAX = 12
|
||||
|
||||
# 登录/验证码 —— 风控敏感:每次提交都计入服务端登录尝试次数,从严控制重试,
|
||||
# 避免连续多次提交触发平台「登录失败次数已达上限」锁定(曾实测踩雷,账号被锁 2 小时)
|
||||
RETRY_MAX = 1 # 浏览器兜底登录轮数(失败即停,不反复登录)
|
||||
CAPTCHA_RETRY = 3 # 浏览器每轮验证码重试次数
|
||||
API_CAPTCHA_RETRY = 3 # 接口登录验证码重试次数
|
||||
LOGIN_FAIL_BACKOFF = 8 # 登录提交失败后的退避秒数(让风控计数沉降)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
|
||||
# ==================== 默认保存目录 ====================
|
||||
_DESKTOP = os.path.join(os.path.expanduser('~'), 'Desktop')
|
||||
|
||||
|
||||
def get_desktop():
|
||||
return _DESKTOP
|
||||
|
||||
|
||||
# ==================== 浏览器用户目录 ====================
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留(免验证码),且不占用用户日常 Chrome 配置。
|
||||
|
||||
放 %LOCALAPPDATA% 下而非系统临时目录,避免被磁盘清理工具清掉导致登录态丢失。
|
||||
"""
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
return os.path.join(base, '37duAutomation', 'browser_sessions', 'xq0045_xq0046')
|
||||
|
||||
|
||||
# ==================== 登录会话复用 ====================
|
||||
def get_session_file():
|
||||
"""已登录会话 cookies 落盘路径:跨 run 复用通联登录,避免每次执行都重新登录。"""
|
||||
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, 'allinpay_xq0045_xq0046.json')
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到 config.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
log(msg % args if args else msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
log(msg % args if args else msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
log(msg % args if args else msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
log(msg % args if args else msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
@@ -0,0 +1 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -0,0 +1,259 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联平台交易数据导出(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
服务端行为已探明(探针 workflows/share/debug_tranx25 实测验证):
|
||||
- 请求必须带 Referer,否则被重定向回 /main.dsr;
|
||||
- 商户列表内嵌在搜索页 JS:var childcuslist = '[{"key":"商户号","value":"商户名"},...]';
|
||||
- 查询:POST /tranx25/search,data={issubmit,cusid,startDate,endDate,export:false,pageIndex,
|
||||
canemptycusid},响应为整页 HTML(结果表格 #dataTable);
|
||||
- 导出(异步三步):
|
||||
1) POST /tranx25/search 带 export=all → JSON {"code":"0","message":"<fid>"}(code=1 失败);
|
||||
2) POST /export/statusdownload {id:fid} 每 6 秒轮询至 code=0(就绪);
|
||||
3) POST /export/downloadexport/ {id:fid} → {"code":"0","message":"<下载URL>"} → GET 落文件。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# ==================== HTTP 封装(统一带 Referer) ====================
|
||||
def _get(session, url, **kw):
|
||||
return session.get(url, headers=config.SEARCH_HEADERS, timeout=20, **kw)
|
||||
|
||||
|
||||
def _post(session, url, data=None, **kw):
|
||||
return session.post(url, data=data, headers=config.SEARCH_HEADERS, timeout=30, **kw)
|
||||
|
||||
|
||||
def _parse_code_message(text):
|
||||
"""解析服务端返回的 JS 风格对象(单引号,如 {code:'0',message:'fid'})。
|
||||
|
||||
前端用 eval('('+data+')') 解析,说明响应不是标准 JSON;
|
||||
先试标准 JSON,失败再正则提取 code/message。返回 (code, message)。
|
||||
"""
|
||||
text = (text or '').strip()
|
||||
try:
|
||||
j = json.loads(text)
|
||||
return str(j.get('code')), str(j.get('message') or '')
|
||||
except Exception:
|
||||
pass
|
||||
m_code = re.search(r"code\s*:\s*'?([^',}]+)'?", text)
|
||||
m_msg = re.search(r"message\s*:\s*'([^']*)'", text)
|
||||
code = m_code.group(1).strip() if m_code else ''
|
||||
msg = m_msg.group(1) if m_msg else ''
|
||||
if not (m_code or m_msg):
|
||||
raise RuntimeError(f"响应无法解析(可能会话失效被踢回页面):{text[:200]}")
|
||||
return code, msg
|
||||
|
||||
|
||||
# ==================== 商户列表 ====================
|
||||
def get_cus_list(session):
|
||||
"""GET 搜索页解析 childcuslist → [{'key': 商户号, 'value': 商户名}, ...]。"""
|
||||
resp = _get(session, config.SEARCH_URL)
|
||||
m = re.search(r"var childcuslist\s*=\s*'([^']*)'", resp.text)
|
||||
if not m:
|
||||
raise RuntimeError("搜索页未找到 childcuslist(会话可能失效,请重新登录)")
|
||||
data = json.loads(m.group(1))
|
||||
if not isinstance(data, list):
|
||||
raise RuntimeError("childcuslist 解析异常")
|
||||
return data
|
||||
|
||||
|
||||
# ==================== 异步导出三步 ====================
|
||||
def start_export(session, cusid, start, end):
|
||||
"""发起导出 → 返回 fid。
|
||||
|
||||
服务端实测(探针 exp_probe + 实跑 + 测速验证):
|
||||
- export=all 会忽略日期参数、导出当天全量(错误行为);
|
||||
- export=onebtnexpt(导出当前查询结果集)才按日期区间导出;
|
||||
- cusid 必须非空:传空串时服务端直接 504 Gateway Timeout(实测 60s 超时);
|
||||
但服务端忽略 cusid 的筛选语义——传任意真实商户号都返回账号全量结果集
|
||||
(不同商户同日期返回同一 fid、同一文件),故用账号下首个商户号即可。
|
||||
因此必须先查询(export=false)建立结果集,再用 onebtnexpt 导出。
|
||||
"""
|
||||
base = {
|
||||
'issubmit': 'issubmit',
|
||||
'cusid': cusid,
|
||||
'startDate': start,
|
||||
'endDate': end,
|
||||
'pageIndex': '1',
|
||||
'canemptycusid': 'true',
|
||||
}
|
||||
# 1) 查询建立结果集(export=false)
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': 'false'})
|
||||
# 2) 导出当前结果集(onebtnexpt)
|
||||
code, msg = _parse_code_message(
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': config.EXPORT_CURRENT}).text)
|
||||
if code == '1':
|
||||
raise RuntimeError(f"导出失败:{msg}")
|
||||
fid = msg
|
||||
if not fid:
|
||||
raise RuntimeError("导出响应缺少 fid")
|
||||
return fid
|
||||
|
||||
|
||||
def wait_export_done(session, fid):
|
||||
"""轮询导出状态,直到就绪(code=0)或超时。
|
||||
|
||||
状态契约(探针实测):code='0'=文件就绪;code='1'=生成中。
|
||||
其它码(如 '2' 失败)只告警不判就绪,避免误把失败态当成功去取下载地址;
|
||||
超时错误里带最后状态,便于定位。
|
||||
"""
|
||||
last = ""
|
||||
for i in range(1, config.STATUS_POLL_MAX + 1):
|
||||
code, msg = _parse_code_message(_post(session, config.STATUS_URL, {'id': fid}).text)
|
||||
last = f"code={code} {msg}".strip()
|
||||
if code == '0':
|
||||
config.log(f"[导出] fid={fid} 文件就绪(轮询 {i} 次)")
|
||||
return True
|
||||
if code != '1':
|
||||
config.log(f"[导出] fid={fid} 状态异常({last}),继续等待", "WARN")
|
||||
else:
|
||||
# 每次轮询都打进度,避免长时间静默被误认为卡死
|
||||
config.log(f"[导出] fid={fid} 文件生成中(第 {i} 次轮询,已等待 {i * config.STATUS_POLL_INTERVAL} 秒)…")
|
||||
time.sleep(config.STATUS_POLL_INTERVAL)
|
||||
raise RuntimeError(f"导出超时(服务端未在时限内生成文件,最后状态:{last})")
|
||||
|
||||
|
||||
def get_download_url(session, fid):
|
||||
"""获取下载地址。"""
|
||||
code, msg = _parse_code_message(_post(session, config.DOWNLOAD_INFO_URL, {'id': fid}).text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"获取下载地址失败:{msg}")
|
||||
return msg
|
||||
|
||||
|
||||
# ==================== 下载校验 ====================
|
||||
def _check_download_content_type(resp):
|
||||
"""下载响应 Content-Type 校验:HTML/文本说明可能被踢回登录页,直接报错。"""
|
||||
ct = (resp.headers.get('Content-Type') or '').lower()
|
||||
if 'html' in ct or ct.startswith('text/'):
|
||||
raise RuntimeError(
|
||||
f"下载返回非文件内容(Content-Type={ct or 'unknown'}),会话可能已失效,请重新登录")
|
||||
|
||||
|
||||
def _is_zip_file(path):
|
||||
"""文件头魔数校验:zip/xlsx 均以 PK 开头。"""
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
return f.read(2) == b'PK'
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _safe_extract(zip_path, extract_dir):
|
||||
"""解压 zip,并拦截路径穿越条目(.. / 绝对路径)。"""
|
||||
with zipfile.ZipFile(zip_path) as zf:
|
||||
for info in zf.infolist():
|
||||
parts = Path(info.filename).parts
|
||||
if info.filename.startswith('/') or '..' in parts or ':' in parts:
|
||||
raise RuntimeError(f"压缩包含非法路径条目,已中止解压:{info.filename}")
|
||||
zf.extractall(extract_dir)
|
||||
|
||||
|
||||
def download_file(session, url, folder, stem):
|
||||
"""下载导出文件到 folder/,文件名 stem + 扩展名(优先 Content-Disposition,默认 .xlsx)。
|
||||
返回最终文件路径。带 Content-Type 与文件魔数校验,防会话失效时把 HTML 落成伪文件。"""
|
||||
resp = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
resp.raise_for_status()
|
||||
_check_download_content_type(resp)
|
||||
ext = '.xlsx'
|
||||
cd = resp.headers.get('Content-Disposition', '')
|
||||
m = re.search(r'filename\*?=(?:UTF-8\'\')?"?([^\";]+)"?', cd, re.I)
|
||||
if m:
|
||||
nm = m.group(1).strip().strip('"')
|
||||
if '.' in nm:
|
||||
ext = '.' + nm.rsplit('.', 1)[1].lower()
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
path = os.path.join(folder, f"{stem}{ext}")
|
||||
total = int(resp.headers.get('Content-Length') or 0)
|
||||
received, last_log = 0, time.time()
|
||||
with open(path, 'wb') as f:
|
||||
for chunk in resp.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
received += len(chunk)
|
||||
now = time.time()
|
||||
if now - last_log >= 8: # 每 8 秒报一次下载进度,避免长下载静默
|
||||
last_log = now
|
||||
mb = received / 1048576
|
||||
if total:
|
||||
pct = received * 100 // max(1, total)
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB / {total / 1048576:.1f}MB({pct}%)…")
|
||||
else:
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB…")
|
||||
if not _is_zip_file(path): # xlsx 本质是 zip,文件头须为 PK
|
||||
os.remove(path)
|
||||
raise RuntimeError(f"下载文件不是有效 xlsx(文件头异常),已删除:{path}")
|
||||
config.log(f"[导出] 已保存:{path}({received / 1048576:.1f} MB)")
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 日期范围 ====================
|
||||
def build_date_range(mode, date_str):
|
||||
"""按模式把日期字符串转成查询区间 (start, end)。
|
||||
mode='月':date_str=YYYY-MM → 当月 1 日 10:00:00 ~ 下月 1 日 10:00:00(对账 10 点切日口径);
|
||||
mode='日':date_str=YYYY-MM-DD(数据起始日,默认昨天)→ 当天 00:00:00 ~ 次日 23:59:59
|
||||
(即默认 = 昨天0点 ~ 今天24点,今天数据少基本无影响)。"""
|
||||
if mode == '月':
|
||||
ym = datetime.strptime(date_str, '%Y-%m')
|
||||
next_month = (ym.replace(day=1) + timedelta(days=32)).replace(day=1)
|
||||
return (ym.strftime('%Y-%m-01 10:00:00'),
|
||||
next_month.strftime('%Y-%m-01 10:00:00'))
|
||||
d = datetime.strptime(date_str, '%Y-%m-%d')
|
||||
nxt = d + timedelta(days=1)
|
||||
return d.strftime('%Y-%m-%d 00:00:00'), nxt.strftime('%Y-%m-%d 23:59:59')
|
||||
|
||||
|
||||
def default_dates(mode):
|
||||
"""未填日期时的默认值:日=昨天;月=上月。"""
|
||||
today = datetime.now()
|
||||
if mode == '月':
|
||||
first_this = today.replace(day=1)
|
||||
last_month = first_this - timedelta(days=1)
|
||||
return last_month.strftime('%Y-%m')
|
||||
yesterday = today - timedelta(days=1)
|
||||
return yesterday.strftime('%Y-%m-%d')
|
||||
|
||||
|
||||
# ==================== 账单导出(主账号,zip 下载 + 解压) ====================
|
||||
def bill_download(session, date_str, bill_type, folder):
|
||||
"""通联账单下载(只导主账号/当前商户)。
|
||||
|
||||
POST /checkacct25/download:日账单 ?reportdate=YYYYMMDD;月账单 ?type=month&reportdate=YYYYMM。
|
||||
服务端返回 {"code":"0","message":"<zip 下载 URL>"},GET 下载 zip 并解压。
|
||||
date_str = YYYY-MM-DD(日)或 YYYY-MM(月);bill_type = 'day' | 'month'。
|
||||
返回 (zip_path, extract_dir)。
|
||||
"""
|
||||
reportdate = date_str.replace('-', '')
|
||||
params = {'reportdate': reportdate}
|
||||
if bill_type == 'month':
|
||||
params['type'] = 'month'
|
||||
resp = _post(session, config.BILL_URL, params=params)
|
||||
code, msg = _parse_code_message(resp.text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"账单下载失败:{msg}")
|
||||
url = msg
|
||||
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
zr = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
zr.raise_for_status()
|
||||
_check_download_content_type(zr)
|
||||
prefix = '日账单' if bill_type == 'day' else '月账单'
|
||||
zip_path = os.path.join(folder, f"{prefix}_{date_str}.zip")
|
||||
with open(zip_path, 'wb') as f:
|
||||
for chunk in zr.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
if not _is_zip_file(zip_path):
|
||||
os.remove(zip_path)
|
||||
raise RuntimeError(f"账单下载不是有效 zip(文件头异常),已删除:{zip_path}")
|
||||
|
||||
extract_dir = os.path.join(folder, f"{prefix}_{date_str}")
|
||||
_safe_extract(zip_path, extract_dir)
|
||||
config.log(f"[账单] 已下载并解压:{extract_dir}")
|
||||
return zip_path, extract_dir
|
||||
@@ -0,0 +1,478 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联支付商户服务平台登录模块(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
自 workflows/share/allinpay_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env);
|
||||
- print → config.log;返回 requests.Session(登录后会话直接可用,无需浏览器常驻)。
|
||||
|
||||
登录方式(接口优先,浏览器兜底):
|
||||
1) 接口登录(首选,已实测一次成功):GET /login(拿 SESSION + 页面内嵌 publicKey)
|
||||
→ GET /getvalidCode?type=cuserrorCode 验证码图 → ddddocr 识别(4位)
|
||||
→ JSEncrypt 兼容 RSA 加密密码(PKCS#1 v1.5 + base64)→ POST /login(userid/
|
||||
encpassword/cuserrorCode,带 Referer)→ 302 离开 /login 即成功;
|
||||
2) 浏览器兜底:DrissionPage 现场登录(验证码元素截图 + ddddocr),成功后从浏览器
|
||||
cookies 构建 requests.Session。
|
||||
|
||||
登录页(账号登录 tab,DOM 参考 aa.md):
|
||||
账号 #userid / 密码 #password(初始 readonly,onfocus 移除;提交时页面 JS 加密进 #encpassword)
|
||||
验证码 #captcha + 图 <img src="/getvalidCode?type=cuserrorCode">(URL 型,元素截图 + ddddocr)
|
||||
登录按钮 button[onclick*="valandsubmit"](触发 valandsubmit JS 加密密码后提交表单)
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
HUMAN_DELAY = (0.4, 1.2)
|
||||
_VALIDCODE_URL = config.LOGIN_URL.replace('/login', '/getvalidCode?type=cuserrorCode')
|
||||
_PUBKEY_RE = re.compile(r"var publicKey='([^']+)'")
|
||||
_LOGIN_FORM_RE = re.compile(r'<form[^>]*id=["\']?accountForm|action=["\']?/login')
|
||||
|
||||
_ocr = None
|
||||
|
||||
|
||||
def _get_ocr():
|
||||
"""ddddocr 单例(懒加载),接口/浏览器登录共用。"""
|
||||
global _ocr
|
||||
if _ocr is None:
|
||||
import ddddocr
|
||||
_ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return _ocr
|
||||
|
||||
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _rsa_encrypt(pubkey, pwd):
|
||||
"""JSEncrypt 兼容:RSA PKCS#1 v1.5 加密 + base64。
|
||||
|
||||
页面 publicKey 是 SPKI/X.509 SubjectPublicKeyInfo(BEGIN PUBLIC KEY)裸 DER,
|
||||
用 cryptography 解析后按 PKCS#1 v1.5 填充加密(1024 位公钥,明文 ≤117 字节)。
|
||||
"""
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives.serialization import load_der_public_key
|
||||
pub = load_der_public_key(base64.b64decode(pubkey), default_backend())
|
||||
ct = pub.encrypt(pwd.encode(), padding.PKCS1v15())
|
||||
return base64.b64encode(ct).decode()
|
||||
|
||||
|
||||
def _api_login(username, password):
|
||||
"""接口登录(纯 requests,不弹浏览器)。成功返回 requests.Session,失败返回 None。
|
||||
|
||||
服务端行为(探针实测):
|
||||
- /login 页面内嵌固定 RSA 公钥(publicKey,1024 位 PKCS#1);
|
||||
- 验证码 4 位,GET /getvalidCode?type=cuserrorCode 返回图片(session 绑定);
|
||||
- POST /login 需带 Referer(外链校验),成功 302 到 /main。
|
||||
"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
if len(password.encode()) > 117:
|
||||
# 页面公钥 1024 位,PKCS#1 v1.5 明文上限 117 字节;超长无法加密,
|
||||
# 明确提示后走浏览器兜底登录
|
||||
config.log("[通联登录] 密码过长(>117 字节),接口登录无法加密,将回退浏览器登录")
|
||||
return None
|
||||
html = session.get(config.LOGIN_URL, timeout=20).text
|
||||
m = _PUBKEY_RE.search(html)
|
||||
if not m:
|
||||
config.log("[通联登录] 接口登录失败:未找到 publicKey")
|
||||
return None
|
||||
pubkey = m.group(1)
|
||||
enc = _rsa_encrypt(pubkey, password)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 接口登录准备异常:{e}")
|
||||
return None
|
||||
|
||||
ocr = _get_ocr()
|
||||
for attempt in range(config.API_CAPTCHA_RETRY):
|
||||
try:
|
||||
img = session.get(_VALIDCODE_URL, timeout=20).content
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 获取验证码图异常:{e}")
|
||||
return None
|
||||
code = ocr.classification(img).strip()
|
||||
config.log(f"[通联登录] 接口登录 第 {attempt + 1}/{config.API_CAPTCHA_RETRY} 次验证码识别:{code!r}")
|
||||
if len(code) != 4:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
resp = session.post(config.LOGIN_URL, data={
|
||||
'userid': username,
|
||||
'encpassword': enc,
|
||||
'cuserrorCode': code,
|
||||
}, headers={'Referer': config.LOGIN_URL}, timeout=20, allow_redirects=True)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提交登录异常:{e}")
|
||||
return None
|
||||
if '/login' not in resp.url:
|
||||
config.log(f"[通联登录] 接口登录成功:{resp.url}")
|
||||
return session
|
||||
# 仍在登录页:验证码错/账号密码错/风控。每次提交都计入服务端尝试次数,
|
||||
# 失败后退避并停止(不连续重试,避免触发登录次数风控锁定)
|
||||
hit = re.search(r'验证码错误|验证码不正确|账号或密码|密码错误|登录失败|次数已达上限|锁定', resp.text)
|
||||
if hit:
|
||||
config.log(f"[通联登录] 服务端提示:{hit.group(0)}")
|
||||
if '次数已达上限' in hit.group(0) or '锁定' in hit.group(0):
|
||||
config.log("[通联登录] 检测到风控锁定提示,立即停止登录尝试")
|
||||
return None
|
||||
time.sleep(config.LOGIN_FAIL_BACKOFF)
|
||||
config.log("[通联登录] 接口登录验证码多次未通过,停止重试")
|
||||
return None
|
||||
|
||||
|
||||
def _on_target(page):
|
||||
"""登录成功判定:URL 离开 /login。"""
|
||||
try:
|
||||
return '/login' not in (page.url or '')
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_input(page, selectors):
|
||||
for sel in selectors:
|
||||
ele = page.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(page):
|
||||
"""定位验证码输入框 + 图片(从 #captcha 容器向上找,避免命中验证码登录 tab 的图)。"""
|
||||
code_input = page.ele('#captcha', timeout=config.TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(1) # div.input-group#captcha_div
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
img = page.ele('css:.tab-pane.active img[src*="getvalidCode"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""URL 型验证码(/getvalidCode)直接元素截图;兼容 base64 内嵌 src。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景导入开销。"""
|
||||
import ddddocr
|
||||
ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return ocr.classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _refresh_captcha(page, img):
|
||||
"""点击验证码图片刷新(onclick=cusjsUtil.changeCode)。URL 型验证码无法可靠比对,点击后等渲染。"""
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _ensure_account_tab(page):
|
||||
"""确保「账号登录」tab 激活(默认激活;若页面记住验证码登录则切回)。"""
|
||||
uid = page.ele('#userid', timeout=2)
|
||||
if uid:
|
||||
try:
|
||||
if uid.states.is_displayed:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
tab_btn = page.ele('css:a[href="#account"], css:a[data-target="#account"]', timeout=3) \
|
||||
or page.ele('tag:a@@text():账号登录', timeout=3)
|
||||
if tab_btn:
|
||||
try:
|
||||
tab_btn.click()
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _wait_login_result(page):
|
||||
"""提交后轮询判定登录结果,返回 bool。"""
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 登录成功:{page.url}")
|
||||
return True
|
||||
for sel in ('css:.invalid-feedback', 'css:.alert-danger', 'css:.toast'):
|
||||
try:
|
||||
eles = page.eles(sel, timeout=0.3)
|
||||
except Exception:
|
||||
continue
|
||||
for ele in eles:
|
||||
try:
|
||||
text = ele.text.strip()
|
||||
except Exception:
|
||||
text = ''
|
||||
if text:
|
||||
config.log(f"[通联登录] 失败提示:{text}")
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _input_value(ele):
|
||||
"""读取输入框当前值(页面刷新后表单清空,用于判断是否需要重填)。"""
|
||||
try:
|
||||
return ele.value or ''
|
||||
except Exception:
|
||||
try:
|
||||
return ele.attr('value') or ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def _fill_account(page, username, password):
|
||||
"""确保账号密码已填(每轮提交前调用)。
|
||||
|
||||
通联登录失败后页面会整页刷新、表单被清空;这里做幂等填充——
|
||||
账号/密码已存在则跳过,被清空则重新输入,避免后续重试提交空表单。
|
||||
"""
|
||||
user_input = page.ele('#userid', timeout=config.TIMEOUT)
|
||||
if not user_input:
|
||||
config.log("[通联登录] 找不到账号输入框")
|
||||
return False
|
||||
if _input_value(user_input) != username:
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(page, ['#password', 'css:input[type="password"]:not([name="encpassword"])'])
|
||||
if not pwd_input:
|
||||
config.log("[通联登录] 找不到密码输入框")
|
||||
return False
|
||||
if not _input_value(pwd_input):
|
||||
pwd_input.click() # 触发 onfocus 移除 readonly
|
||||
_human_pause(0.2, 0.5)
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
return True
|
||||
|
||||
|
||||
def _try_login_once(page, username, password):
|
||||
"""完成一次填表 + 验证码 + 提交,返回 bool。
|
||||
每轮提交前都会确保账号密码已填(页面刷新后自动重填)。"""
|
||||
_ensure_account_tab(page)
|
||||
|
||||
for attempt in range(config.CAPTCHA_RETRY):
|
||||
if not _fill_account(page, username, password):
|
||||
return False
|
||||
config.log(f"[通联登录] 第 {attempt + 1}/{config.CAPTCHA_RETRY} 次验证码识别")
|
||||
img, code_input = _find_captcha(page)
|
||||
if not img or not code_input:
|
||||
config.log("[通联登录] 找不到验证码图片或输入框")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] ddddocr 识别异常:{e}")
|
||||
return False
|
||||
config.log(f"[通联登录] 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(page, img)
|
||||
continue
|
||||
code_input.click() # 触发 onfocus 移除 readonly
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
btn = page.ele('css:.tab-pane.active button[onclick*="valandsubmit"]', timeout=config.TIMEOUT) \
|
||||
or page.ele('tag:button@@text():登录', timeout=config.TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[通联登录] 找不到登录提交按钮")
|
||||
return False
|
||||
_human_pause(0.2, 0.6)
|
||||
btn.click()
|
||||
|
||||
if _wait_login_result(page):
|
||||
return True
|
||||
_refresh_captcha(page, img)
|
||||
return False
|
||||
|
||||
|
||||
def _build_session(page):
|
||||
"""从浏览器 cookies 构建 requests.Session(仅保留 allinpay.com 域)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
for c in page.cookies():
|
||||
domain = (c.get('domain') or '')
|
||||
if 'allinpay.com' not in domain:
|
||||
continue
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=domain.lstrip('.'), path=c.get('path', '/'))
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提取 cookies 异常:{e}")
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 会话落盘复用(跨 run,子进程隔离下也生效) ====================
|
||||
def _dump_cookies(session):
|
||||
"""把 requests.Session 的 cookies 序列化为可持久化列表。"""
|
||||
out = []
|
||||
for c in session.cookies:
|
||||
out.append({'name': c.name, 'value': c.value, 'domain': c.domain or '',
|
||||
'path': c.path or '/'})
|
||||
return out
|
||||
|
||||
|
||||
def save_session(username, session):
|
||||
"""登录成功后把会话 cookies 落盘,供下次运行直接复用。失败不影响本次执行。"""
|
||||
try:
|
||||
data = {'username': username, 'cookies': _dump_cookies(session)}
|
||||
with open(config.get_session_file(), 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 保存会话失败(不影响本次执行):{e}")
|
||||
|
||||
|
||||
def _session_valid(session):
|
||||
"""会话探活:GET 首页,未落回 /login 且页面内容不含登录表单即视为有效。
|
||||
|
||||
平台为单点登录(多地互斥):一旦其它设备/浏览器用同一账号重新登录,
|
||||
本会话立即失效。此时 main.dsr 仍返回 200,但页面内容是登录表单
|
||||
(<form id="accountForm" action="/login">)而非业务首页——仅看 URL 会误判
|
||||
为有效,导致后续 API 全部失败,必须校验页面内容。
|
||||
"""
|
||||
try:
|
||||
resp = session.get(config.MAIN_URL, headers=config.SEARCH_HEADERS,
|
||||
timeout=15, allow_redirects=True)
|
||||
if resp.status_code != 200 or '/login' in resp.url:
|
||||
return False
|
||||
return not _LOGIN_FORM_RE.search(resp.text)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def load_session(username):
|
||||
"""读取并重建上次登录会话;有效则返回 requests.Session,否则返回 None。"""
|
||||
path = config.get_session_file()
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
if data.get('username') != username:
|
||||
config.log("[通联登录] 本地会话账号与当前账号不一致,重新登录")
|
||||
return None
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
for c in data.get('cookies') or []:
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=c['domain'] or '', path=c['path'] or '/')
|
||||
if _session_valid(session):
|
||||
return session
|
||||
config.log("[通联登录] 本地会话已失效,重新登录")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 读取本地会话异常:{e}")
|
||||
return None
|
||||
|
||||
|
||||
def tl_login(username, password):
|
||||
"""通联平台登录(本地会话复用 → 接口登录 → 浏览器兜底)。
|
||||
|
||||
成功返回 requests.Session,失败返回 None。登录成功后会话 cookies 落盘,
|
||||
下次运行直接复用免登录(探活失败才重新登录)。
|
||||
"""
|
||||
username = (username or '').strip()
|
||||
password = password or ''
|
||||
if not (username and password):
|
||||
config.log("[通联登录] 账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return None
|
||||
|
||||
# 1) 复用本地已保存会话(免重新登录)
|
||||
session = load_session(username)
|
||||
if session is not None:
|
||||
config.log("[通联登录] 复用本地已登录会话,免重新登录(单点登录:请勿同时在其")
|
||||
config.log("[通联登录] 它设备/浏览器登录同一账号,否则本会话会被踢下线)")
|
||||
return session
|
||||
|
||||
# 2) 接口登录(首选,不弹浏览器)
|
||||
config.log("[通联登录] 本地会话失效,开始重新登录(单点登录:本次登录会顶掉其它")
|
||||
config.log("[通联登录] 设备/浏览器上的同一账号登录)")
|
||||
session = _api_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
config.log("[通联登录] 接口登录未成功,回退浏览器登录")
|
||||
# 3) 浏览器兜底
|
||||
session = _browser_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
|
||||
|
||||
def _browser_login(username, password):
|
||||
"""浏览器兜底登录(DrissionPage + ddddocr 图形验证码,元素截图)。
|
||||
|
||||
返回:成功 → requests.Session(从浏览器 cookies 构建);失败 → None。
|
||||
固定默认用户目录保留登录态:已登录会话直接复用(免验证码)。
|
||||
调用方使用完毕无需额外操作(本函数已 page.quit())。
|
||||
"""
|
||||
co = ChromiumOptions()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录(%LOCALAPPDATA% 下,非临时目录):登录态跨次保留免验证码,
|
||||
# 且不占用用户日常 Chrome 配置、不被系统磁盘清理清掉
|
||||
co.set_user_data_path(config.get_browser_profile_dir())
|
||||
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[通联登录] 浏览器登录 第 {attempt}/{config.RETRY_MAX} 次 → {config.LOGIN_URL}")
|
||||
page = ChromiumPage(co)
|
||||
page.get(config.LOGIN_URL)
|
||||
_human_pause(1.0, 2.0)
|
||||
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 检测到已登录会话,直接复用:{page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
|
||||
if _try_login_once(page, username, password):
|
||||
config.log(f"[通联登录] 登录成功 → {page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 异常:{e}")
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
config.log("[通联登录] 浏览器登录重试多次均失败")
|
||||
return None
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0045_xq0046",
|
||||
"name": "金色印象通联数据导出",
|
||||
"version": "1.0.5",
|
||||
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0045_xq0046"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "日+月",
|
||||
"enum": ["日", "月", "日+月"],
|
||||
"description": "日/月/日+月:决定日期选择器粒度;交易查询与账单导出共用日期选择器,插件内部自动换算各自区间"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"title": "导出内容",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "交易查询", "账单"],
|
||||
"description": "交易查询=逐商户导交易明细(xlsx);账单=主账号日/月账单(zip 下载并解压)"
|
||||
},
|
||||
"day_date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"title": "按日导出",
|
||||
"default": "",
|
||||
"description": "默认昨天;交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
},
|
||||
"month_date": {
|
||||
"type": "string",
|
||||
"format": "month",
|
||||
"title": "按月导出",
|
||||
"default": "",
|
||||
"description": "默认上月;交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
},
|
||||
"tl_username": {
|
||||
"type": "string",
|
||||
"title": "通联登录账号",
|
||||
"default": "",
|
||||
"description": "商户服务平台登录账号(保存在本机,下次免填)"
|
||||
},
|
||||
"tl_password": {
|
||||
"type": "string",
|
||||
"title": "通联登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/金色印象通联数据_YYYYMMDD;交易查询每日期一份全量文件(日_日期.xlsx / 月_月份.xlsx),账单按 账单_YYYYMM 目录存放"
|
||||
}
|
||||
},
|
||||
"required": ["tl_username", "tl_password"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
ddddocr>=1.4
|
||||
cryptography>=39.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>金色印象通联数据导出</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": "xq0045-xq0046-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,385 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
|
||||
<!-- 执行配置 -->
|
||||
<el-card shadow="never" class="card">
|
||||
<template #header>
|
||||
<span class="card-title">执行配置</span>
|
||||
<span v-if="lastSavedAt" class="saved">已保存 {{ lastSavedAt }}</span>
|
||||
</template>
|
||||
<el-form label-width="110px" label-position="right">
|
||||
<!-- 通联账号密码 -->
|
||||
<div class="grid">
|
||||
<el-form-item label="通联账号">
|
||||
<el-input v-model="form.tl_username" placeholder="商户服务平台登录账号" :disabled="running" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item label="登录密码">
|
||||
<el-input v-model="form.tl_password" type="password" show-password placeholder="仅保存在本机,下次免填"
|
||||
:disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<!-- 执行模式 + 导出内容 -->
|
||||
<div class="grid">
|
||||
<el-form-item label="执行模式">
|
||||
<el-radio-group v-model="form.mode" :disabled="running">
|
||||
<el-radio-button value="日">按日</el-radio-button>
|
||||
<el-radio-button value="月">按月</el-radio-button>
|
||||
<el-radio-button value="日+月">日 + 月</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="导出内容">
|
||||
<el-radio-group v-model="form.content" :disabled="running">
|
||||
<el-radio-button value="交易查询">交易查询</el-radio-button>
|
||||
<el-radio-button value="账单">账单</el-radio-button>
|
||||
<el-radio-button value="两个都导">两个都导</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<!-- 日期选择器(组件复用:交易查询与账单共用,插件内部按导出类型自动换算区间) -->
|
||||
<div v-if="form.mode === '日+月'" class="grid">
|
||||
<el-form-item label="按日导出">
|
||||
<el-date-picker v-model="form.day_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="选择日期(默认昨天)" :disabled="running"
|
||||
:disabled-date="disableFuture" class="wide" />
|
||||
<div class="tip">默认昨天;区间=所选日 00:00 ~ 次日 24:00(跨 2 天)</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="按月导出">
|
||||
<el-date-picker v-model="form.month_date" type="month" value-format="YYYY-MM"
|
||||
placeholder="选择月份(默认上月)" :disabled="running"
|
||||
:disabled-date="disableFutureMonth" class="wide" />
|
||||
<div class="tip">默认上月;区间=当月1日 10:00 ~ 下月1日 10:00(对账10点切日)</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item v-else-if="form.mode === '日'" label="按日导出">
|
||||
<el-date-picker v-model="form.day_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="选择日期(默认昨天)" :disabled="running"
|
||||
:disabled-date="disableFuture" class="wide" />
|
||||
<div class="tip">默认昨天;区间=所选日 00:00 ~ 次日 24:00(跨 2 天);账单 = 所选日账单</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item v-else label="按月导出">
|
||||
<el-date-picker v-model="form.month_date" type="month" value-format="YYYY-MM"
|
||||
placeholder="选择月份(默认上月)" :disabled="running"
|
||||
:disabled-date="disableFutureMonth" class="wide" />
|
||||
<div class="tip">默认上月;区间=当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单</div>
|
||||
</el-form-item>
|
||||
|
||||
<!-- 保存目录 -->
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = 桌面/金色印象通联数据_今天日期" class="wide" />
|
||||
<div class="tip">交易查询=每日期一份账号全量文件(日_日期.xlsx / 月_月份.xlsx,含全部商户);账单=按 账单_YYYYMM 目录存放</div>
|
||||
</el-form-item>
|
||||
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="8" class="status-bar" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { connectWS, getRun, loadConfig, saveConfig, startRun, stopRun } from './api'
|
||||
|
||||
function fmtDate(d) {
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getDate()).padStart(2, '0')
|
||||
return `${y}-${m}-${day}`
|
||||
}
|
||||
|
||||
function fmtMonth(d) {
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
return `${y}-${m}`
|
||||
}
|
||||
|
||||
function lastMonthStr(now) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - 1, 1)
|
||||
return fmtMonth(d)
|
||||
}
|
||||
|
||||
function yesterdayStr(now) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
|
||||
return fmtDate(d)
|
||||
}
|
||||
|
||||
const DEFAULTS = () => {
|
||||
const now = new Date()
|
||||
return {
|
||||
mode: '日+月',
|
||||
content: '两个都导',
|
||||
day_date: yesterdayStr(now), // 默认昨天
|
||||
month_date: lastMonthStr(now), // 默认上月
|
||||
tl_username: '',
|
||||
tl_password: '',
|
||||
save_dir: '',
|
||||
}
|
||||
}
|
||||
|
||||
const form = reactive(DEFAULTS())
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
function disableFuture(date) {
|
||||
return date.getTime() > Date.now() + 86400000 // 今天及以前可选
|
||||
}
|
||||
|
||||
function disableFutureMonth(date) {
|
||||
const now = new Date()
|
||||
return date.getTime() > new Date(now.getFullYear(), now.getMonth() + 1, 1).getTime()
|
||||
}
|
||||
|
||||
// ---------- 配置加载 / 保存(自动保存到本机 plugin_configs) ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
Object.keys(form).forEach((k) => {
|
||||
if (saved[k] !== undefined && saved[k] !== null && saved[k] !== '') {
|
||||
form[k] = saved[k]
|
||||
}
|
||||
})
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
})
|
||||
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(JSON.parse(JSON.stringify(form)))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, DEFAULTS())
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
function validate() {
|
||||
if (!form.tl_username.trim() || !form.tl_password) {
|
||||
ElMessage.warning('请先填写通联登录账号和密码')
|
||||
return false
|
||||
}
|
||||
if (form.mode !== '月' && !form.day_date) { ElMessage.warning('请选择按日导出的日期'); return false }
|
||||
if (form.mode !== '日' && !form.month_date) { ElMessage.warning('请选择按月导出的月份'); return false }
|
||||
return true
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (!validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const payload = {
|
||||
mode: form.mode,
|
||||
content: form.content,
|
||||
day_date: form.mode === '月' ? '' : form.day_date,
|
||||
month_date: form.mode === '日' ? '' : form.month_date,
|
||||
tl_username: form.tl_username,
|
||||
tl_password: form.tl_password,
|
||||
save_dir: form.save_dir,
|
||||
}
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + 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() : 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 === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
async function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 4px 2px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
float: right;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: #67c23a;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
flex: 1;
|
||||
min-width: 280px;
|
||||
}
|
||||
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
line-height: 1.6;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 16px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,50 @@
|
||||
// 与壳子后端交互(同源,统一账户会话 cookie 自动携带)+ WebSocket 实时流
|
||||
export const PLUGIN_ID = 'xq0045_xq0046'
|
||||
|
||||
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 (e) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
export function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
export function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.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,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0045_xq0046/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0045_xq0046/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5180,
|
||||
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/xq0045_xq0046/assets/index-CuUBZGG_.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-CmyoQ4x2.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,41 @@
|
||||
# ERP报表导出(xq0031_xq0032)
|
||||
|
||||
金蝶 K3Cloud 报表自动导出插件:物料收发汇总表(需求31)+ 采购订单列表(需求32),
|
||||
支持新旧系统切换、仓库编码多选(或关系)、日期多档(N天 / 自定义区间)逐档导出。
|
||||
|
||||
## 目录结构
|
||||
|
||||
- `*.py` — 插件后端(ScenePlugin 注册 + ERP 登录 + 两报表逻辑),自包含,
|
||||
只引用标准库 / 第三方依赖 / 底座注入接口(`webhost.backend.plugins.base`)
|
||||
- `ui/` — 插件前端**构建产物**(壳子后端托管于 `/pui/xq0031_xq0032/`,勿手改)
|
||||
- `ui-src/` — 插件前端源码(Vue 3 + Element Plus + Vite)
|
||||
- `_pack.py` — 发布打包辅助(`_` 前缀,运行时不会被插件扫描加载)
|
||||
|
||||
## 前端开发 / 构建
|
||||
|
||||
```bash
|
||||
cd ui-src
|
||||
npm install
|
||||
npm run build # 产物输出到 ../ui/(vite.config.js 里 base=/pui/xq0031_xq0032/)
|
||||
```
|
||||
|
||||
联调:先启动壳子(webhost),`npm run dev` 走 vite 代理(5180 → 127.0.0.1:8799)。
|
||||
|
||||
## 打包发布
|
||||
|
||||
1. 构建 ui(见上)
|
||||
2. `desktop/` 下执行:`../.venv/Scripts/python.exe ../plugins/xq0031_xq0032/_pack.py`
|
||||
→ 产出 `dist-plugin/xq0031_xq0032_v<版本>.zip`(自动排除 ui-src 等)
|
||||
3. `desktop/` 下发布:
|
||||
`.venv\Scripts\python.exe -m controlplane.tools.agent_cli publish dist-plugin\xq0031_xq0032_v<版本>.zip --id xq0031_xq0032 --version <版本> --admin puddy`
|
||||
|
||||
## 个性化配置(自带界面)
|
||||
|
||||
`plugin.json` 声明 `"ui": true`,壳子插件页展示「打开插件界面」入口(弹独立窗口,
|
||||
同源自动携带登录会话)。账号密码 / 仓库编码 / 日期选项等在窗口内填写:
|
||||
|
||||
- 配置经壳子 `GET/POST /api/plugin-config/xq0031_xq0032` 保存,
|
||||
落执行机本机 `%LOCALAPPDATA%\37duAutomation\plugin_configs\xq0031_xq0032.json`,
|
||||
下次打开自动回填(表单改动防抖自动保存);
|
||||
- 执行经现有 `POST /api/runs`,日志/进度经 `WS /ws` 实时回显(另有 5 秒轮询兜底);
|
||||
- 浏览器每次现场真登录(auto_port 独立实例),确保登录的就是本次配置的账号。
|
||||
@@ -0,0 +1,184 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ERP报表导出 - webhost 场景插件(XQ0031 + XQ0032 合并版)
|
||||
|
||||
金蝶 K3Cloud 报表自动导出,两种报表可单选或同次会话连导(登录一次):
|
||||
物料收发汇总表(XQ0031):组织/仓库编码(或关系多行)/日期多档(N天或自定义区间)逐档导出
|
||||
采购订单列表(XQ0032):快捷方案 → 等查询 → 按列表引出数据
|
||||
|
||||
个性化设计(自带 Vue 界面,plugin.json 声明 "ui": true):
|
||||
- ERP 新/旧系统、登录账号密码由用户在插件窗口内自行填写,
|
||||
经 /api/plugin-config 保存在执行机本机,下次打开自动回填;
|
||||
- 仓库编码、日期选项均为多选(可自建条目,日期可混入自定义区间);
|
||||
- 浏览器现场真登录(固定默认用户目录,保留登录态/配置),确保用的就是本次配置的账号。
|
||||
"""
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from . import erp_login
|
||||
|
||||
# 执行模式
|
||||
MODE_31 = '物料收发汇总表'
|
||||
MODE_32 = '采购订单列表'
|
||||
MODE_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _as_str_list(value):
|
||||
"""fields 里的多选值归一为去空去重的字符串列表(兼容逗号/空格分隔的字符串)。"""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, str):
|
||||
parts = value.replace(',', ',').replace(' ', ',').split(',')
|
||||
elif isinstance(value, (list, tuple)):
|
||||
parts = list(value)
|
||||
else:
|
||||
parts = [value]
|
||||
out, seen = [], set()
|
||||
for p in parts:
|
||||
s = str(p).strip()
|
||||
if s and s not in seen:
|
||||
seen.add(s)
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
|
||||
class ErpReportExportPlugin(ScenePlugin):
|
||||
id = "xq0031_xq0032"
|
||||
name = "ERP物料收发汇总-采购订单报表导出"
|
||||
version = "1.0.10"
|
||||
description = "金蝶K3Cloud报表导出:物料收发汇总表+ 采购订单列表,支持新旧系统与个性化配置"
|
||||
platform = "" # ERP 自带登录页(无验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
# 富字段声明(与 plugin.json 保持一致):ui=true 时壳子隐藏通用表单、展示打开插件窗口入口;
|
||||
# 此处仅作为无 manifest 时的兜底与参数契约文档
|
||||
fields = [
|
||||
{"key": "mode", "label": "执行模式", "type": "select",
|
||||
"options": [MODE_BOTH, MODE_31, MODE_32], "default": MODE_BOTH},
|
||||
{"key": "erp_system", "label": "ERP系统", "type": "select",
|
||||
"options": ["新版", "旧版"], "default": "新版"},
|
||||
{"key": "erp_username", "label": "ERP登录账号", "type": "text", "default": ""},
|
||||
{"key": "erp_password", "label": "ERP登录密码", "type": "password", "default": ""},
|
||||
{"key": "org_name", "label": "查询组织", "type": "text",
|
||||
"default": config.ORG_NAME},
|
||||
{"key": "stock_codes", "label": "仓库编码(多选,或关系)", "type": "multiselect",
|
||||
"options": config.STOCK_CODES_DEFAULT + config.STOCK_CODES_DEFAULT_OLD,
|
||||
"default": list(config.STOCK_CODES_DEFAULT)},
|
||||
{"key": "date_options", "label": "日期选项(多选,逐个导出)", "type": "multiselect",
|
||||
"options": config.DATE_OPTIONS_DEFAULT, "default": list(config.DATE_OPTIONS_DEFAULT)},
|
||||
{"key": "scheme_name", "label": "采购订单快捷方案", "type": "text",
|
||||
"default": config.SCHEME_NAME},
|
||||
{"key": "save_dir", "label": "保存目录(空=桌面/采购计划报表_日期)", "type": "text", "default": ""},
|
||||
]
|
||||
|
||||
def run(self, fields: dict, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
# 注入日志钩子(插件内全部模块经 config.log 输出)
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
erp = 'old' if str(fields.get("erp_system") or "新版").strip() == "旧版" else 'new'
|
||||
username = str(fields.get("erp_username") or "").strip()
|
||||
password = str(fields.get("erp_password") or "")
|
||||
org = str(fields.get("org_name") or "").strip() or (
|
||||
config.ORG_NAME_OLD if erp == 'old' else config.ORG_NAME)
|
||||
scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME
|
||||
codes = _as_str_list(fields.get("stock_codes")) # 空 = 全部仓库不筛选
|
||||
dates = _as_str_list(fields.get("date_options")) or list(config.DATE_OPTIONS_DEFAULT)
|
||||
if not username or not password:
|
||||
raise RuntimeError("ERP 登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_31, MODE_32):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if mode in (MODE_BOTH, MODE_31) and not dates:
|
||||
raise RuntimeError("物料收发汇总表需要日期选项(请在插件界面配置);仓库编码可留空=下载全部仓库")
|
||||
|
||||
save_dir_raw = str(fields.get("save_dir") or "").strip().strip('"')
|
||||
save_dir = Path(save_dir_raw) if save_dir_raw else Path(
|
||||
_desktop()) / f"{config.FOLDER_NAME}_{datetime.now():%Y-%m-%d}"
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
ctx.log(f"保存目录: {save_dir}")
|
||||
|
||||
# ---------- 登录(一次,两种报表共用会话) ----------
|
||||
ctx.progress(3)
|
||||
ctx.log(f"ERP 系统:{'新版' if erp == 'new' else '旧版'}({erp_login.ERP_URLS[erp]}),查询组织:{org}")
|
||||
ok, page = erp_login.erp_login(erp, username, password)
|
||||
if not ok:
|
||||
raise RuntimeError("ERP 登录失败(账号密码错误或网络异常),详见日志")
|
||||
ctx.progress(8)
|
||||
|
||||
# ---------- 执行计划与整体进度(进度 = 8 + 88*已完成单元/总单元) ----------
|
||||
do_31 = mode in (MODE_BOTH, MODE_31)
|
||||
do_32 = mode in (MODE_BOTH, MODE_32)
|
||||
units_31 = len(dates) if do_31 else 0
|
||||
total = units_31 + (1 if do_32 else 0)
|
||||
|
||||
def _report(done_abs):
|
||||
ctx.progress(8 + int(88 * done_abs / max(1, total)))
|
||||
|
||||
saved, failed = [], []
|
||||
try:
|
||||
try:
|
||||
page.set.window.max()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
from . import material_summary, purchase_order
|
||||
|
||||
if do_31:
|
||||
try:
|
||||
ctx.log(f"开始导出物料收发汇总表:下载全部仓库,按所选 {len(codes)} 个仓库中文名筛选" if codes else "开始导出物料收发汇总表:下载全部仓库(未筛选)")
|
||||
files31, failed31 = material_summary.run(
|
||||
page, save_dir, org, codes, dates,
|
||||
progress=lambda done_i, _total: _report(done_i),
|
||||
set_org=True) # 新旧系统均显式设置查询组织(旧系统登录默认组织已不再默认)
|
||||
saved += files31
|
||||
failed += [f"物料收发汇总表[{x}]" for x in failed31]
|
||||
except RuntimeError as e:
|
||||
failed.append(f"物料收发汇总表[{e}]")
|
||||
files31 = []
|
||||
# 各档报表导出后合并为汇总文件(合并失败不阻断整体结果)
|
||||
if files31:
|
||||
try:
|
||||
merged = material_summary.merge_summary(save_dir)
|
||||
if merged:
|
||||
saved.append(str(merged))
|
||||
except Exception as e:
|
||||
ctx.log(f"汇总文件生成失败: {e}")
|
||||
if do_32:
|
||||
try:
|
||||
ctx.log(f"开始导出采购订单列表(方案:{scheme})")
|
||||
f32 = purchase_order.run(page, save_dir, scheme, erp=erp,
|
||||
progress=lambda _i, _t: _report(units_31 + 1))
|
||||
if f32:
|
||||
saved.append(f32)
|
||||
else:
|
||||
failed.append("采购订单列表")
|
||||
except RuntimeError as e:
|
||||
failed.append(f"采购订单列表[{e}]")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = f"导出完成(部分失败):成功 {len(saved)} 个,失败 {len(failed)} 项"
|
||||
else:
|
||||
summary = f"导出完成:共 {len(saved)} 个文件 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
# ================== 小工具 ==================
|
||||
def _desktop():
|
||||
from .k3_common import get_desktop
|
||||
return get_desktop()
|
||||
|
||||
|
||||
PLUGINS.append(ErpReportExportPlugin())
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""ERP报表导出(xq0031_xq0032)插件配置:默认值与运行参数。
|
||||
|
||||
合并 XQ0031(物料收发汇总表)+ XQ0032(采购订单列表)的固化配置,
|
||||
与 workflows 影刀版各源文件常量保持同源(四方向零依赖,各自演进)。
|
||||
|
||||
个性化配置(账号密码/仓库编码/日期选项等)由插件自带 Vue 界面维护,经
|
||||
webhost /api/plugin-config 落执行机本机,run() 时经 fields 注入;
|
||||
本文件只承载 fields 未传时的兜底默认与运行参数。
|
||||
"""
|
||||
|
||||
# ==================== 1. 业务默认值(fields 未传/留空时的兜底) ====================
|
||||
ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织(新版默认)
|
||||
ORG_NAME_OLD = '99.01.07.01.01 石桥铺会馆' # 查询组织(旧版默认;登录已不再默认,须显式选择)
|
||||
# 仓库编码→仓库中文名(现场映射,供「下载全部仓库后按中文名筛选」使用):
|
||||
# 0101010101 重庆运营总仓 / 0101010201 重庆美得三方仓 / 0101020201 成都美得三方仓
|
||||
# 0101030201 长沙乐行三方仓 / 0101040201 西安美得三方仓 / 03010127 代管仓(旧版登录默认)
|
||||
# 前端仍要求选择仓库编码(决定最终保留哪些仓库),查询统一下载全部仓库,
|
||||
# 下载后用 openpyxl 按本映射把仓库中文名列筛到所选编码对应仓库,覆盖保存。
|
||||
STOCK_NAME_MAP = {
|
||||
'0101010101': '重庆运营总仓',
|
||||
'0101010201': '重庆美得三方仓',
|
||||
'0101020201': '成都美得三方仓',
|
||||
'0101030201': '长沙乐行三方仓',
|
||||
'0101040201': '西安美得三方仓',
|
||||
'03010127': '代管仓',
|
||||
}
|
||||
|
||||
# 前端可选仓库编码列表(与 STOCK_NAME_MAP 键一致;留空 = 全部仓库不筛选)
|
||||
STOCK_CODES_DEFAULT = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
|
||||
STOCK_CODES_DEFAULT_OLD = ['03010127'] # 旧版默认仓库(代管仓,随 ERP 系统选项切换)
|
||||
DATE_OPTIONS_DEFAULT = ['60D', '30D', '15D', '7D', '3D']
|
||||
SCHEME_NAME = '默认方案(个人)' # 需求32 快捷方案(精确匹配)
|
||||
FOLDER_NAME = '采购计划报表' # 保存目录命名前缀(31/32 同目录)
|
||||
FILE_PREFIX_31 = '物料收发汇总表' # 31 导出文件名前缀
|
||||
FILE_PREFIX_32 = '采购订单列表' # 32 导出文件名前缀
|
||||
|
||||
# ==================== 2. 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3
|
||||
TIMEOUT = 15 # 元素查找超时(秒)
|
||||
|
||||
# ==================== 3. 日志钩子(print → ctx.log) ====================
|
||||
_log_fn = print
|
||||
|
||||
|
||||
def set_log(fn) -> None:
|
||||
"""插件 run() 启动时把 ctx.log 注入进来,全部模块经 log() 输出。"""
|
||||
global _log_fn
|
||||
_log_fn = fn if fn else print
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
try:
|
||||
_log_fn(msg)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,181 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金蝶 K3Cloud(HTML5)ERP 登录模块(xq0031_xq0032 插件内自包含)。
|
||||
|
||||
自 workflows/share/erp_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env),个性化归属明确;
|
||||
- 使用固定默认用户目录(不再每次独立临时目录),保留登录态与浏览器配置;
|
||||
用完由调用方 page.quit() 关闭;
|
||||
- print → config.log。
|
||||
|
||||
登录页元素(新旧版一致):
|
||||
用户名输入框 <input id="user" placeholder="用户名">
|
||||
密码输入框 <input id="password" type="password">
|
||||
登录按钮 <button id="btnLogin" class="btnlogin k-button">登录</button>
|
||||
登录成功判定:URL 包含 /k3cloud/html5/dform.aspx,或站点页面无登录输入框(已登录态)。
|
||||
特殊弹窗:登录时若弹出「该帐号已登录在线,确认让对方下线」警告框,自动点确认。
|
||||
"""
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from . import config
|
||||
|
||||
# ================== 站点定义(新旧 ERP) ==================
|
||||
ERP_URLS = {
|
||||
'old': 'https://erp.37du.co/k3cloud/html5/index.aspx',
|
||||
'new': 'https://criterion.erp.37du.co/k3cloud/html5/index.aspx',
|
||||
}
|
||||
|
||||
# 登录页元素定位(新旧版元素 id 一致)
|
||||
USER_INPUT = '#user'
|
||||
PWD_INPUT = '#password'
|
||||
LOGIN_BTN = '#btnLogin'
|
||||
# 「该帐号已登录在线」弹窗的确认按钮(蓝色样式 class 固定,id 为动态 UUID)
|
||||
KICK_CONFIRM_BTN = 'css:.k-window .BlueButtonStyle'
|
||||
|
||||
# 登录成功标志:URL 包含该关键字即视为已登录(跳转到默认表单页)
|
||||
SUCCESS_KEYWORD = '/k3cloud/html5/dform.aspx'
|
||||
|
||||
# ================== 运行参数 ==================
|
||||
RETRY_MAX = config.RETRY_MAX # 全局重试次数(项目规范:最多 3 次)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
LOGIN_WAIT = 3 # 点击登录后等待(秒)
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def _resolve_url(erp):
|
||||
"""把 'old'/'new'/完整URL 统一解析为登录页 URL。"""
|
||||
if erp in ERP_URLS:
|
||||
return ERP_URLS[erp]
|
||||
if erp and erp.lower().startswith('http'):
|
||||
return erp
|
||||
raise ValueError(f"无效的 ERP 标识:{erp},可选 'old'、'new' 或完整登录页 URL")
|
||||
|
||||
|
||||
def _is_login_page(url):
|
||||
"""判断当前 URL 是否仍停留在登录页。"""
|
||||
return 'index.aspx' in (url or '').lower()
|
||||
|
||||
|
||||
def _is_login_success(url):
|
||||
"""登录成功判定:URL 包含 dform.aspx 即视为已登录。"""
|
||||
return SUCCESS_KEYWORD in (url or '')
|
||||
|
||||
|
||||
def _handle_kick_dialog(page):
|
||||
"""处理「该帐号已登录在线,确认让对方下线」弹窗:存在则点击蓝色确认按钮。"""
|
||||
for _ in range(3):
|
||||
btn = page.ele(KICK_CONFIRM_BTN, timeout=2)
|
||||
if not btn:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
config.log("[ERP登录] 检测到「已登录在线」弹窗,点击确认(让对方下线)")
|
||||
return True
|
||||
except Exception as e:
|
||||
config.log(f"[ERP登录] 点击弹窗确认异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def _open_browser(headless):
|
||||
"""启动浏览器(DrissionPage 固定默认用户目录,不再每次独立临时目录,保留登录态/配置)。
|
||||
附加禁用浏览器自身弹窗的 prefs/启动参数:保存密码、权限请求(通知/定位/音视频)、
|
||||
自动化测试 infobar、首次运行向导、打开外部应用确认框(K3 点引出/下载会请求打开
|
||||
Excel 等,防止弹「访问应用和服务」)等。"""
|
||||
co = ChromiumOptions()
|
||||
if headless:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
# —— 禁用浏览器自身弹窗(避免干扰自动化)——
|
||||
co.set_pref('credentials_enable_service', False) # 不保存密码
|
||||
co.set_pref('profile.password_manager_enabled', False) # 关闭密码管理器
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def erp_login(erp='new', username='', password='', headless=None):
|
||||
"""
|
||||
登录金蝶 K3Cloud ERP(新旧系统通用,现场真登录)。
|
||||
|
||||
参数:
|
||||
erp 'old' 旧版 erp.37du.co / 'new' 新版 criterion.erp.37du.co / 完整登录页 URL
|
||||
username 用户名(插件界面配置注入,必填)
|
||||
password 密码(插件界面配置注入,必填)
|
||||
|
||||
返回:
|
||||
(success, page) success=True 时 page 为已登录的 ChromiumPage;失败时 page 为 None。
|
||||
调用方使用完毕应 page.quit() 关闭浏览器(不保存任何目录/cookies)。
|
||||
"""
|
||||
login_url = _resolve_url(erp)
|
||||
username = (username or '').strip()
|
||||
password = password or ''
|
||||
if not (username and password):
|
||||
config.log("[ERP登录] 登录账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return False, None
|
||||
headless = HEADLESS if headless is None else bool(headless)
|
||||
|
||||
for attempt in range(1, RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[ERP登录] 第 {attempt}/{RETRY_MAX} 次 → {login_url}")
|
||||
page = _open_browser(headless)
|
||||
config.log("[ERP登录] 浏览器已启动(默认用户目录,保留登录态)")
|
||||
|
||||
# 回到目标登录页;已登录站点会跳转/保留会话,未登录则停在登录页
|
||||
page.get(login_url)
|
||||
time.sleep(2)
|
||||
|
||||
# 3) 已登录判定:页面无登录输入框 → 会话有效,直接复用
|
||||
if page.ele(USER_INPUT, timeout=3) is None:
|
||||
config.log("[ERP登录] 检测到已登录会话,直接复用")
|
||||
return True, page
|
||||
|
||||
# 4) 未登录 → 填表登录
|
||||
user = page.ele(USER_INPUT, timeout=TIMEOUT)
|
||||
if not user:
|
||||
config.log("[ERP登录] 找不到用户名输入框")
|
||||
continue
|
||||
user.clear()
|
||||
user.input(username)
|
||||
time.sleep(0.5)
|
||||
# 用户名框是 autocomplete 控件,需按回车关闭弹出的下拉提示框
|
||||
page.actions.key_down('Enter')
|
||||
page.actions.key_up('Enter')
|
||||
time.sleep(0.3)
|
||||
|
||||
pwd = page.ele(PWD_INPUT, timeout=TIMEOUT)
|
||||
if not pwd:
|
||||
config.log("[ERP登录] 找不到密码输入框")
|
||||
continue
|
||||
pwd.clear()
|
||||
pwd.input(password)
|
||||
time.sleep(0.3)
|
||||
|
||||
btn = page.ele(LOGIN_BTN, timeout=TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[ERP登录] 找不到登录按钮")
|
||||
continue
|
||||
btn.click()
|
||||
|
||||
# 登录后轮询:处理「已登录在线」弹窗 + 等待跳转到 dform.aspx
|
||||
for _ in range(6):
|
||||
time.sleep(LOGIN_WAIT)
|
||||
if _is_login_success(page.url):
|
||||
config.log(f"[ERP登录] 登录成功 → {page.url}")
|
||||
return True, page
|
||||
_handle_kick_dialog(page)
|
||||
|
||||
config.log("[ERP登录] 点击登录后未跳转到 dform.aspx(账号密码错误或网络异常)")
|
||||
except Exception as e:
|
||||
config.log(f"[ERP登录] 异常:{e}")
|
||||
|
||||
# 走到这里说明本轮失败,关闭浏览器后重试(成功时在上方已直接 return)
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
config.log("[ERP登录] 重试 3 次均失败")
|
||||
return False, None
|
||||
@@ -0,0 +1,299 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""K3Cloud HTML5 页面操作公共件(xq0031_xq0032 插件内共享)。
|
||||
|
||||
自 workflows/XQ0031、XQ0032 影刀版迁移的稳定交互原语,两报表共用。
|
||||
K3 现场验证结论(勿随手"优化",均为踩坑后的修复):
|
||||
- 残留窗口会被移到屏幕外,is_displayed 仍 True 但点击无效 → 必须同时校验视口位置
|
||||
- 工具栏/菜单项物理点击只选中文字不触发菜单 → 用 by_js;嵌套悬浮子菜单相反,
|
||||
必须真实鼠标悬浮(move_to 链不能断)
|
||||
- 浏览器断连(PageDisconnectedError)属致命异常,直接上抛,避免被容错吞掉空转
|
||||
"""
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from DrissionPage.errors import PageDisconnectedError
|
||||
except Exception:
|
||||
PageDisconnectedError = None
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
def get_desktop():
|
||||
"""获取真实桌面路径,适配 OneDrive 等重定向的不同电脑。"""
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
guid = wintypes.GUID(
|
||||
data1=0xB4BFCC3A, data2=0xDB2C, data3=0x424C,
|
||||
data4=(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41))
|
||||
func = ctypes.windll.shell32.SHGetKnownFolderPath
|
||||
func.argtypes = [wintypes.GUID, wintypes.DWORD, wintypes.HANDLE,
|
||||
ctypes.POINTER(ctypes.c_wchar_p)]
|
||||
ptr = ctypes.c_wchar_p()
|
||||
func(ctypes.byref(guid), 0, None, ctypes.byref(ptr))
|
||||
return ptr.value
|
||||
except Exception:
|
||||
return str(Path.home() / 'Desktop')
|
||||
|
||||
|
||||
def is_in_viewport(el, page):
|
||||
"""元素是否真实显示在视口内。K3 残留窗口会被移到屏幕外,此时 is_displayed
|
||||
仍为 True,但其内元素点击无效——必须同时校验位置在视口内。"""
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
return False
|
||||
w, h = el.rect.size
|
||||
if w <= 0 or h <= 0:
|
||||
return False
|
||||
x, y = el.rect.location
|
||||
vw, vh = page.run_js(
|
||||
'return [window.innerWidth || document.documentElement.clientWidth,'
|
||||
' window.innerHeight || document.documentElement.clientHeight];')
|
||||
return 0 <= x < vw and 0 <= y < vh
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def click_visible(page, css, timeout=None, by_js=False):
|
||||
"""点击第一个在视口内可见的匹配元素,成功返回 True。浏览器断连等致命异常直接上抛。
|
||||
by_js=True 用于 K3 工具栏/菜单项:物理点击只会选中文字,不触发菜单。"""
|
||||
timeout = config.TIMEOUT if timeout is None else timeout
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
for el in page.eles(css):
|
||||
if is_in_viewport(el, page):
|
||||
el.click(by_js=True) if by_js else el.click()
|
||||
return True
|
||||
except Exception as e:
|
||||
if PageDisconnectedError is not None and isinstance(e, PageDisconnectedError):
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def ele_visible(page, css, timeout=1):
|
||||
"""元素存在、且在视口内可见才算命中(K3 过滤窗口关闭后 DOM 里仍残留隐藏/屏幕外节点)。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
for el in page.eles(css):
|
||||
if is_in_viewport(el, page):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def press_enter(page):
|
||||
"""模拟按一次回车键。"""
|
||||
page.actions.key_down('Enter')
|
||||
page.actions.key_up('Enter')
|
||||
|
||||
|
||||
def press_enter_in(el, page):
|
||||
"""向指定元素直接发送回车(元素级,避免页面焦点漂移导致回车无效)。"""
|
||||
try:
|
||||
from DrissionPage.common import Keys
|
||||
el.input(Keys.ENTER)
|
||||
except Exception:
|
||||
press_enter(page)
|
||||
|
||||
|
||||
def visible_titles(page):
|
||||
"""返回所有可见窗口标题文本列表。"""
|
||||
titles = []
|
||||
try:
|
||||
for t in page.eles('css:.k-window-title'):
|
||||
try:
|
||||
if t.states.is_displayed:
|
||||
titles.append(t.text)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return titles
|
||||
|
||||
|
||||
def close_window_by_title(page, title, timeout=3, tag=''):
|
||||
"""物理点击关闭标题包含关键字的 k-window 弹窗(K3 下载窗口等残留,关闭按钮 by_js 不触发)。
|
||||
用包含匹配:实际标题可能是「文件下载」或「文档下载」,避免因标题差异关不掉。"""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
for w in page.eles('css:.k-window'):
|
||||
try:
|
||||
if not w.states.is_displayed:
|
||||
continue
|
||||
t = w.ele('css:.k-window-title', timeout=0.3)
|
||||
if t is None or title not in (t.text or ''):
|
||||
continue
|
||||
btn = w.ele('css:.k-window-actions .k-i-close', timeout=0.5)
|
||||
if btn is None:
|
||||
return False
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
time.sleep(0.3)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def reset_filter_state(page, tag='', wait_query=False):
|
||||
"""重试前清理脏界面状态:按 ESC 关闭残留的弹层/过滤窗口,兜底点各面板「取消」按钮。
|
||||
wait_query=True(需求31):若查询正在进行先等其结束(ESC 会打断正常查询)。"""
|
||||
if wait_query:
|
||||
end = time.time() + 120
|
||||
while time.time() < end:
|
||||
if not any('查询进度' in x for x in visible_titles(page)):
|
||||
break
|
||||
time.sleep(1)
|
||||
for _ in range(2):
|
||||
try:
|
||||
page.actions.key_down('ESC')
|
||||
page.actions.key_up('ESC')
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
click_visible(page, 'css:[id*="FBTNCANCEL_c"]', timeout=1)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def download_file(page, save_dir, new_name, tag=''):
|
||||
"""点「下载」按钮 → 等文件落盘到保存目录。
|
||||
做法:把浏览器默认下载目录直接指到 save_dir,再点「下载」按钮(target=_blank 也会下载到该目录),
|
||||
然后盯着文件夹等新文件出现且大小稳定(下载完成),不依赖 DrissionPage 的任务捕获,避免静默卡住。"""
|
||||
save_dir = Path(save_dir)
|
||||
try:
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
page.set.download_path(str(save_dir))
|
||||
page.set.when_download_file_exists('overwrite')
|
||||
except Exception as e:
|
||||
config.log(f'{tag} 设置下载目录异常: {e}')
|
||||
before_names = {b.name for b in save_dir.glob('*')} if save_dir.exists() else set()
|
||||
|
||||
# 清除上个报表/上次导出残留的「文件下载/文档下载」窗口,防止全页匹配误命中旧下载按钮
|
||||
# (需求31多档连导或需求31→32连导时残留)。此刻本次引出刚触发、尚在生成阶段,
|
||||
# 其下载窗口还未弹出,关闭残留窗口不影响本次导出。
|
||||
for _title in ('文件下载', '文档下载'):
|
||||
try:
|
||||
close_window_by_title(page, _title, timeout=1, tag=tag)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 找可见的「下载」按钮,以「引出进度」窗口为信号判定引出是否仍在进行:
|
||||
# - 点击引出后,K3 会先弹「引出进度」窗口(进度条 + 「正在获取引出数据:(n/N)」caption),
|
||||
# 取数完成后该窗口关闭并弹出「文件下载」窗口;正常 ≤30s,大数据量(百万行)约 1 分钟多;
|
||||
# - 「引出进度」窗口始终未出现 → 引出未被受理/已失败,快速返回失败,不做无谓死等;
|
||||
# - 进度窗口已消失但 GONE_GAP 内下载按钮未出现 → 引出失败,快速返回交外层重试。
|
||||
dl = None
|
||||
start = time.time()
|
||||
seen_busy = False # 是否见过「引出进度」窗口
|
||||
busy_gone_since = None # 进度窗口消失的时刻(None=尚未消失)
|
||||
WAIT_BUSY = 20 # 等「引出进度」窗口出现的最长时间
|
||||
GONE_GAP = 10 # 进度窗口消失后等下载按钮的窗口期
|
||||
OVERALL = 150 # 整体硬上限(含百万行大数据的取数时间)
|
||||
last_report = start
|
||||
|
||||
def _busy(titles):
|
||||
return any(k in t for t in titles for k in ('生成', '进度', '稍候', '处理中', '导出'))
|
||||
|
||||
def _progress_text():
|
||||
"""读「引出进度」窗口 caption(如「正在获取引出数据:(100001/1242812)」)。"""
|
||||
try:
|
||||
cap = page.ele('css:[id*="FPROGRESSBAR"] div[id*="lblCaption"]', timeout=0.3)
|
||||
return (cap.attr('title') or cap.text or '').strip() if cap else ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
while time.time() - start < OVERALL:
|
||||
for el in page.eles('css:[id*="FDOWNLOAD_c"]'):
|
||||
try:
|
||||
if el.states.is_displayed:
|
||||
dl = el
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if dl:
|
||||
break
|
||||
busy = _busy(visible_titles(page))
|
||||
if busy:
|
||||
seen_busy = True
|
||||
busy_gone_since = None
|
||||
elif seen_busy:
|
||||
if busy_gone_since is None:
|
||||
busy_gone_since = time.time()
|
||||
elif time.time() - busy_gone_since > GONE_GAP:
|
||||
config.log(f'{tag} 引出进度窗口已消失且下载按钮未出现,判定本次引出失败')
|
||||
return False
|
||||
elif time.time() - start > WAIT_BUSY:
|
||||
config.log(f'{tag} 未检测到「引出进度」窗口,判定本次引出未触发/失败')
|
||||
return False
|
||||
now = time.time()
|
||||
if now - last_report >= 30:
|
||||
last_report = now
|
||||
txt = _progress_text()
|
||||
config.log(f'{tag} 仍在等待(引出进度窗口'
|
||||
f'{txt or "可见"},已等 {int(now - start)}s)')
|
||||
time.sleep(0.5)
|
||||
if not dl:
|
||||
config.log(f'{tag} 找不到下载按钮(等待 {OVERALL}s 后 K3 仍未生成完成)')
|
||||
return False
|
||||
config.log(f'{tag} 点击下载按钮...')
|
||||
try:
|
||||
dl.click()
|
||||
except Exception:
|
||||
dl.click(by_js=True)
|
||||
|
||||
# 等新文件出现且大小连续两次不变(下载完成)
|
||||
config.log(f'{tag} 等待文件下载完成...')
|
||||
last_size, last_name = -1, None
|
||||
end = time.time() + 300
|
||||
while time.time() < end:
|
||||
new_files = [f for f in save_dir.glob('*')
|
||||
if f.is_file() and f.name not in before_names]
|
||||
if new_files:
|
||||
f = max(new_files, key=lambda x: x.stat().st_mtime)
|
||||
try:
|
||||
s = f.stat().st_size
|
||||
except Exception:
|
||||
s = 0
|
||||
if (f.suffix not in ('.crdownload', '.tmp', '.part')
|
||||
and s > 0 and s == last_size and f.name == last_name):
|
||||
dst = _save_as(f, save_dir / new_name)
|
||||
config.log(f'{tag} 已保存: {dst}')
|
||||
close_window_by_title(page, '文件下载', tag=tag) # 只关下载窗口,其余残留不主动关
|
||||
return True
|
||||
last_size, last_name = s, f.name
|
||||
time.sleep(1)
|
||||
|
||||
# 兜底:超时但确有新文件也尝试落名
|
||||
new_files = [f for f in save_dir.glob('*')
|
||||
if f.is_file() and f.name not in before_names
|
||||
and f.suffix not in ('.crdownload', '.tmp', '.part')]
|
||||
for f in new_files:
|
||||
dst = _save_as(f, save_dir / new_name)
|
||||
config.log(f'{tag} 已保存: {dst}')
|
||||
close_window_by_title(page, '文件下载', tag=tag)
|
||||
return True
|
||||
config.log(f'{tag} 下载失败/超时')
|
||||
return False
|
||||
|
||||
|
||||
def _save_as(src, dst):
|
||||
"""把下载产物重命名/移动到目标名;移动失败则原样保留并返回实际路径。"""
|
||||
if src == dst:
|
||||
return src
|
||||
try:
|
||||
if dst.exists():
|
||||
dst.unlink()
|
||||
shutil.move(str(src), str(dst))
|
||||
return dst
|
||||
except Exception:
|
||||
return src
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0031_xq0032",
|
||||
"name": "ERP物料收发汇总-采购订单报表导出",
|
||||
"version": "1.0.10",
|
||||
"description": "金蝶K3Cloud报表自动导出:物料收发汇总表+ 采购订单列表,支持新旧系统、下载全部仓库后按所选仓库中文名自动筛选、日期多选(含自定义区间),个性化配置保存在本机",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0031_xq0032"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "物料收发汇总表", "采购订单列表"],
|
||||
"description": "需求31=物料收发汇总表(按仓库/日期多档导出),需求32=采购订单列表(按方案导出)"
|
||||
},
|
||||
"erp_system": {
|
||||
"type": "string",
|
||||
"title": "ERP系统",
|
||||
"default": "新版",
|
||||
"enum": ["新版", "旧版"],
|
||||
"description": "新版 criterion.erp.37du.co / 旧版 erp.37du.co"
|
||||
},
|
||||
"erp_username": {
|
||||
"type": "string",
|
||||
"title": "ERP登录账号",
|
||||
"default": "",
|
||||
"description": "用户自己的ERP账号,保存在本机下次免填"
|
||||
},
|
||||
"erp_password": {
|
||||
"type": "string",
|
||||
"title": "ERP登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"org_name": {
|
||||
"type": "string",
|
||||
"title": "查询组织",
|
||||
"default": "99.01 重庆金七象供应链管理有限公司",
|
||||
"description": "新版默认=金七象;旧版默认=99.01.07.01.01 石桥铺会馆,插件界面切换ERP系统自动带出"
|
||||
},
|
||||
"stock_codes": {
|
||||
"type": "array",
|
||||
"title": "仓库编码(可多选)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201", "03010127"]
|
||||
},
|
||||
"default": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"],
|
||||
"description": "查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选保存;留空=全部仓库不筛选。新版默认=五个三方仓;旧版默认=03010127(代管仓,切换ERP系统自动带出)"
|
||||
},
|
||||
"date_options": {
|
||||
"type": "array",
|
||||
"title": "日期选项(多选,逐个导出)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["60D", "30D", "15D", "7D", "3D"]
|
||||
},
|
||||
"default": ["60D", "30D", "15D", "7D", "3D"],
|
||||
"description": "N天=今天往前推N天;可混入自定义区间如 2026-01-01~2026-09-15"
|
||||
},
|
||||
"scheme_name": {
|
||||
"type": "string",
|
||||
"title": "采购订单快捷方案",
|
||||
"default": "默认方案(个人)",
|
||||
"description": "需求32使用的过滤方案名(精确匹配)"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/采购计划报表_日期"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""需求32 - 金蝶 K3Cloud ERP「采购订单列表」自动导出(xq0031_xq0032 插件内模块)。
|
||||
|
||||
自 workflows/XQ0032 purchase_order_list_export.py 迁移:
|
||||
全局搜索「采购订单列表」→ 选中编号 CGDDLB 项 → 点快捷方案 → 等查询完成 →
|
||||
选项 → 引出 → 按列表引出数据 → 下载保存(与需求31同目录)。
|
||||
快捷方案名由插件界面配置注入;交互逻辑与影刀版保持同源。
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from . import config
|
||||
from . import k3_common as kc
|
||||
|
||||
TAG = '[采购订单列表]'
|
||||
REPORT_KEYWORD = '采购订单列表' # 全局搜索关键字
|
||||
REPORT_NUMBER = 'CGDDLB' # 搜索结果编号(列表项唯一标识)
|
||||
|
||||
|
||||
# ================== 列表操作 ==================
|
||||
def _diag_search(page):
|
||||
"""探针:搜索失败时打印当前页面/下拉状态,定位是下拉没出来还是选择器不匹配。"""
|
||||
try:
|
||||
config.log(f'{TAG} [探针] 当前 URL: {(page.url or "")[:120]}')
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [探针] 读 URL 异常: {e}')
|
||||
try:
|
||||
items = page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2)
|
||||
config.log(f'{TAG} [探针] 下拉结果项数量: {len(items)}')
|
||||
for i, li in enumerate(items[:10]):
|
||||
try:
|
||||
num = li.ele('css:span[searchitem="number"]', timeout=0.3)
|
||||
txt = li.ele('css:span[searchitem="text"]', timeout=0.3)
|
||||
config.log(f'{TAG} [探针] 第{i + 1}项: '
|
||||
f'number={num.text if num else "?"} '
|
||||
f'text={txt.text if txt else "?"} '
|
||||
f'displayed={li.states.is_displayed}')
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f'{TAG} [探针] 枚举下拉异常: {e}')
|
||||
filter_visible = kc.ele_visible(
|
||||
page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=1)
|
||||
config.log(f'{TAG} [探针] 过滤按钮可见: {filter_visible}')
|
||||
|
||||
|
||||
def _back_home(page, erp='new'):
|
||||
"""回 K3 主控台首页:优先点顶部常驻「主页」按钮(SPA 内部跳转,一次清掉全部标签页/浮动窗口)。
|
||||
注意:禁止用 page.get(index.aspx) 整页回首页——K3 整页重新加载会重新走会话校验,
|
||||
连导时需求31的 tab 还开着,实测会被判为重复登录直接跳登录页(全局搜索图标随之消失、
|
||||
卡在「找不到全局搜索图标」)。主页按钮找不到时,退化为逐个关闭非激活标签页。"""
|
||||
if _click_home_btn(page):
|
||||
config.log(f'{TAG} 已点主页按钮回主控台')
|
||||
time.sleep(2.5)
|
||||
return
|
||||
config.log(f'{TAG} 未找到主页按钮,改为逐个关闭非激活标签页')
|
||||
for _ in range(5): # 关闭一个后 DOM 会刷新,多次扫描确保关干净
|
||||
closed = 0
|
||||
for li in page.eles('css:ul.k-tabstrip-items li', timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
if (li.attr('aria-selected') or '').strip().lower() == 'true':
|
||||
continue # 保留当前激活 tab
|
||||
btn = li.ele('css:.k-i-close', timeout=0.5)
|
||||
if btn is None:
|
||||
btn = li.ele('css:.k-tabstrip-close', timeout=0.5)
|
||||
if btn is None:
|
||||
continue
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
closed += 1
|
||||
time.sleep(0.6)
|
||||
except Exception:
|
||||
pass
|
||||
if closed == 0:
|
||||
break
|
||||
config.log(f'{TAG} 已关闭 {closed} 个残留标签页')
|
||||
|
||||
|
||||
def _click_home_btn(page):
|
||||
"""点击 K3 顶部常驻「主页」按钮(span.k-link.kd-item-home)回主控台首页。
|
||||
K3 控件 by_js click 有时不触发,先物理点击,失败再 by_js 兜底。"""
|
||||
if kc.click_visible(page, 'css:.k-link.kd-item-home', timeout=3):
|
||||
return True
|
||||
return kc.click_visible(page, 'css:.k-link.kd-item-home', timeout=3, by_js=True)
|
||||
|
||||
|
||||
def _active_tab_title(page):
|
||||
"""当前激活的主标签页标题。K3 多表单标签残留(物料收发汇总表/采购订单列表并存)时,
|
||||
必须确认操作的是激活的那个,否则会读到隐藏标签页的旧条数。"""
|
||||
try:
|
||||
t = page.ele('css:li[aria-selected="true"] .k-link', timeout=2)
|
||||
if t is not None:
|
||||
return (t.text or '').strip()
|
||||
except Exception:
|
||||
pass
|
||||
return ''
|
||||
|
||||
|
||||
def _open_report(page, erp='new'):
|
||||
"""点击全局搜索 → 输入「采购订单列表」→ 等联想下拉出现 → 点选编号 CGDDLB 项。
|
||||
打开后必须校验主标签页已切到「采购订单列表」,否则可能停留在上一个报表标签、
|
||||
读到错页面的行数;校验不过回主控台首页重新搜索进入(最多 2 轮)。"""
|
||||
for _ in range(2):
|
||||
if _do_search_open(page):
|
||||
if REPORT_KEYWORD in _active_tab_title(page):
|
||||
config.log(f'{TAG} 已打开列表({REPORT_NUMBER})')
|
||||
return True
|
||||
config.log(f'{TAG} 列表标签页未激活(可能残留其它表单标签),清理后重新搜索')
|
||||
_back_home(page, erp)
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 打开「采购订单列表」失败:未能确认列表标签页激活')
|
||||
return False
|
||||
|
||||
|
||||
def _do_search_open(page):
|
||||
"""执行一次全局搜索并点选 CGDDLB 结果(不校验标签页是否真的激活,由 _open_report 负责)。"""
|
||||
if not kc.click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10):
|
||||
config.log(f'{TAG} 找不到全局搜索图标')
|
||||
return False
|
||||
time.sleep(1)
|
||||
sbox = page.ele('css:.kd-appplat-searchinput', timeout=5)
|
||||
if not sbox:
|
||||
config.log(f'{TAG} 找不到搜索输入框')
|
||||
return False
|
||||
sbox.clear()
|
||||
sbox.input(REPORT_KEYWORD)
|
||||
time.sleep(0.8) # 输入即出联想下拉;不按回车(回车=直接进第一个结果)
|
||||
|
||||
# 结果下拉列表中找编号为 CGDDLB 的「采购订单列表」项
|
||||
end = time.time() + 20
|
||||
while time.time() < end:
|
||||
for li in page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||||
timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
num = li.ele('css:span[searchitem="number"]', timeout=0.5)
|
||||
if num is None:
|
||||
continue
|
||||
num_text = (num.attr('title') or num.text or '').strip().upper()
|
||||
if num_text == REPORT_NUMBER.upper():
|
||||
li.click()
|
||||
time.sleep(2)
|
||||
if kc.ele_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=2):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 未找到编号 {REPORT_NUMBER} 的搜索结果项')
|
||||
_diag_search(page) # 探针:输出诊断信息
|
||||
return False
|
||||
|
||||
|
||||
def _open_filter(page):
|
||||
"""确保过滤窗口打开:已开则复用,未开则点「过滤」按钮(by_js 触发菜单项)。"""
|
||||
if kc.ele_visible(page, 'css:.k-window [id*="_Filter-FSCHEMELIST"]', timeout=2):
|
||||
return True
|
||||
if kc.click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', by_js=True):
|
||||
time.sleep(1.5)
|
||||
return kc.ele_visible(page, 'css:[id*="_Filter-FSCHEMELIST"]', timeout=5)
|
||||
return False
|
||||
|
||||
|
||||
def _select_scheme(page, scheme):
|
||||
"""在过滤窗口方案树中选中目标方案(默认「默认方案(个人)」)。
|
||||
方案树节点结构:li.k-item > .k-in.kd-treenode-textcnt > .kd-treenode-text。
|
||||
注意:K3 树节点用 by_js click 不触发选中事件(现场验证),必须真实鼠标点击
|
||||
.k-in.kd-treenode-textcnt 节点;选中成功后界面出现 SelectedSchemeItemControlTemplate。"""
|
||||
ac = page.actions
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for li in page.eles('css:.k-window li.k-item', timeout=2):
|
||||
try:
|
||||
if not li.states.is_displayed:
|
||||
continue
|
||||
t = li.ele('css:.kd-treenode-text', timeout=0.5)
|
||||
if t is None or scheme not in (t.text or ''):
|
||||
continue
|
||||
# 已选中:选中模板(SelectedSchemeItemControlTemplate)的文本须是目标方案,
|
||||
# 否则可能是上次选的其它方案,误判会导出错误数据
|
||||
cur = page.ele('css:.SelectedSchemeItemControlTemplate', timeout=1)
|
||||
if cur is not None and scheme in (cur.text or ''):
|
||||
config.log(f'{TAG} 方案已是: {t.text.strip()}')
|
||||
return True
|
||||
# 真实鼠标点击节点外层 .k-in.kd-treenode-textcnt(by_js 不触发选中)
|
||||
node = t.parent() # .k-in.kd-treenode-textcnt
|
||||
if node is None or not node.states.is_displayed:
|
||||
node = t
|
||||
try:
|
||||
ac.move_to(node)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
node.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
# 确认选中:出现 SelectedSchemeItemControlTemplate 才算点击成功
|
||||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate', timeout=2):
|
||||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
# 未生效:可能点到文本被全选,改为点 li 下的 .kd-treenode-textcnt 外层再试一次
|
||||
try:
|
||||
cnt = li.ele('css:.kd-treenode-textcnt', timeout=1)
|
||||
if cnt is not None and cnt.states.is_displayed:
|
||||
ac.move_to(cnt)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
time.sleep(0.8)
|
||||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate',
|
||||
timeout=2):
|
||||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 过滤窗口方案树中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _submit_filter(page):
|
||||
"""点过滤窗口「确定」触发查询。注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库等其它
|
||||
过滤面板的同 id 按钮,用 :not + .k-window 限定,防止误点。"""
|
||||
if not kc.click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'):
|
||||
config.log(f'{TAG} 找不到过滤窗口确定按钮')
|
||||
return False
|
||||
config.log(f'{TAG} 已提交过滤查询')
|
||||
return True
|
||||
|
||||
|
||||
def _read_rowcount(page):
|
||||
"""读分页栏行数统计(span[data-kdid="rowcount_pagerlist2"],文本形如「共519行」)。
|
||||
返回 (文本, 条数);未找到/未显示返回 (None, -1)。"""
|
||||
try:
|
||||
for el in page.eles('css:span[data-kdid="rowcount_pagerlist2"]', timeout=1):
|
||||
try:
|
||||
if not el.states.is_displayed:
|
||||
continue
|
||||
txt = (el.text or '').strip()
|
||||
m = re.search(r'共\s*(\d+)\s*行', txt)
|
||||
return txt, (int(m.group(1)) if m else -1)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return None, -1
|
||||
|
||||
|
||||
def _wait_progress(page, timeout=30):
|
||||
"""等待查询完成:进入页面时分页栏已带旧条数,查询时会先变 0(或消失)再变新条数。
|
||||
故记录初始条数,等行数经历「变 0/消失」或「发生变化」后,再出现非 0 条数才算完成。
|
||||
- 条数可用(数字):行数变 0 / 变化即完成。
|
||||
- 条数不可用:K3 未翻到最后一页时总行数显示「共*行」星号(读不到数字,现场确认),
|
||||
查询中不会有数字信号,仅等一个短窗口(NO_COUNT_GAP)让 K3 算出行数;
|
||||
窗口内星号→数字出现即视为查询完成,始终无数字 → 按查询已完成直接继续
|
||||
(避免 30s 白等,由上层重试机制兜底)。
|
||||
超时不再判定失败:现场结论查询可能太快、行数不经历 0 直接保持旧值,死等会白白卡
|
||||
几分钟。故超时后直接继续导出(由上层重试机制兜底,避免整单卡死)。"""
|
||||
txt0, init_cnt = _read_rowcount(page)
|
||||
if init_cnt >= 0:
|
||||
config.log(f'{TAG} 当前条数: {init_cnt},等待查询刷新...')
|
||||
elif txt0:
|
||||
config.log(f'{TAG} 当前条数: {txt0}(星号=总行数未计算),等待查询刷新...')
|
||||
else:
|
||||
config.log(f'{TAG} 当前条数: 无,等待查询刷新...')
|
||||
if init_cnt < 0:
|
||||
# 条数不可用:短窗口内等待 K3 算出数字;星号→数字出现即完成,否则直接继续
|
||||
NO_COUNT_GAP = 10
|
||||
end = time.time() + NO_COUNT_GAP
|
||||
while time.time() < end:
|
||||
txt, cnt = _read_rowcount(page)
|
||||
if cnt > 0:
|
||||
config.log(f'{TAG} 查询完成: {txt}')
|
||||
return True
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 条数不可用({txt0 or "无"}),按查询已完成直接继续导出')
|
||||
return True
|
||||
saw_reset = False
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
txt, cnt = _read_rowcount(page)
|
||||
if cnt == 0:
|
||||
saw_reset = True # 先变 0:查询已触发,正在刷新
|
||||
elif cnt > 0:
|
||||
if saw_reset or cnt != init_cnt:
|
||||
config.log(f'{TAG} 查询完成: {txt}')
|
||||
return True
|
||||
time.sleep(1)
|
||||
config.log(f'{TAG} 等待查询完成超时(行数未刷新,直接继续导出)')
|
||||
return True
|
||||
|
||||
|
||||
def _export_all_pages(page):
|
||||
"""选项 → 引出(真实鼠标悬浮展开子菜单)→ 按列表引出数据。
|
||||
现场结论:物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了
|
||||
K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字),
|
||||
让子菜单展开后用 move_to+click 点中「按列表引出数据」;不点 span 文本,避免全选。
|
||||
注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。
|
||||
本列表页与需求31不同:选项=tbOptionLists,引出=tbInputOutput,目标=按列表引出数据(tbOutput)。"""
|
||||
ac = page.actions
|
||||
|
||||
def _clickable(span):
|
||||
"""内容 span 的父级可点击元素(a/li),避免点到文本被『全选文字』。"""
|
||||
try:
|
||||
a = span.closest('css:a')
|
||||
if a is not None and a.tag.lower() == 'a' and a.states.is_displayed:
|
||||
return a
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
li = span.closest('css:li')
|
||||
if li is not None and li.states.is_displayed:
|
||||
return li
|
||||
except Exception:
|
||||
pass
|
||||
return span
|
||||
|
||||
# 1. 点「选项」打开配置菜单(点其 a/li,避开文本)
|
||||
opt = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||||
if opt is None or not opt.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到选项按钮')
|
||||
return False
|
||||
try:
|
||||
ac.move_to(_clickable(opt)).click()
|
||||
except Exception:
|
||||
try:
|
||||
opt.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点选项失败')
|
||||
return False
|
||||
time.sleep(1.2)
|
||||
|
||||
# 2. 定位「引出」(splitbutton)
|
||||
split = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||||
if split is None or not split.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到导出(引出)按钮')
|
||||
return False
|
||||
|
||||
def _trigger():
|
||||
"""悬浮目标:优先右箭头(悬浮开子菜单),无箭头则悬浮整体。"""
|
||||
try:
|
||||
ar = split.parent().ele('css:span.k-icon', timeout=1)
|
||||
if ar is not None and ar.states.is_displayed:
|
||||
return ar
|
||||
except Exception:
|
||||
pass
|
||||
return _clickable(split)
|
||||
|
||||
trigger = _trigger()
|
||||
|
||||
# 3. 悬浮展开「按列表引出数据」子菜单
|
||||
target = None
|
||||
for _ in range(4):
|
||||
try:
|
||||
ac.move_to(trigger) # 真实鼠标悬浮到右箭头,子菜单展开
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1.0)
|
||||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
for _ in range(3):
|
||||
try:
|
||||
trigger.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||||
if t is not None and t.states.is_displayed:
|
||||
target = t
|
||||
break
|
||||
if target is None or not target.states.is_displayed:
|
||||
config.log(f'{TAG} 找不到按列表引出数据')
|
||||
return False
|
||||
|
||||
# 4. 光标从「引出」连续移入「按列表引出数据」再点击(悬浮链不断,菜单不收起)
|
||||
try:
|
||||
ac.move_to(_clickable(target))
|
||||
time.sleep(0.5)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
target.click(by_js=True)
|
||||
except Exception:
|
||||
config.log(f'{TAG} 点击按列表引出数据失败')
|
||||
return False
|
||||
config.log(f'{TAG} 已触发按列表引出数据')
|
||||
return True
|
||||
|
||||
|
||||
def _click_quick_scheme(page, scheme):
|
||||
"""直接点击列表页顶部快捷方案条中的目标方案,无需打开过滤窗口。
|
||||
结构:div[filter-role="filterschemecontent"] > div.SchemeItemControlTemplate(含方案名,
|
||||
选中的为 SelectedSchemeItemControlTemplate)。
|
||||
注意:K3 控件用 by_js click 可能不触发,优先真实鼠标点击。"""
|
||||
ac = page.actions
|
||||
end = time.time() + config.TIMEOUT
|
||||
while time.time() < end:
|
||||
for item in page.eles(
|
||||
'css:div[filter-role="filterschemecontent"] '
|
||||
'div[class*="SchemeItemControlTemplate"]', timeout=2):
|
||||
try:
|
||||
if not item.states.is_displayed:
|
||||
continue
|
||||
txt = (item.text or '').strip()
|
||||
if txt != scheme: # 精确匹配:避免「默认方案」误命中「采购订单宽表默认方案」
|
||||
continue
|
||||
cls = item.attr('class') or ''
|
||||
if 'Selected' in cls:
|
||||
config.log(f'{TAG} 快捷方案已是: {txt}')
|
||||
return True
|
||||
try:
|
||||
ac.move_to(item)
|
||||
time.sleep(0.3)
|
||||
ac.click()
|
||||
except Exception:
|
||||
try:
|
||||
item.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
# 确认选中:快捷条中 Selected 方案变为目标方案
|
||||
cur = page.ele(
|
||||
'css:div[filter-role="filterschemecontent"] '
|
||||
'div.SelectedSchemeItemControlTemplate', timeout=2)
|
||||
if cur is not None and scheme in (cur.text or ''):
|
||||
config.log(f'{TAG} 已点选快捷方案: {txt}')
|
||||
return True
|
||||
# 未确认选中:返回 False 走过滤窗口回退,防止把旧数据当本次结果
|
||||
config.log(f'{TAG} 点击快捷方案未确认选中: {txt}')
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
config.log(f'{TAG} 快捷方案条中未找到: {scheme}')
|
||||
return False
|
||||
|
||||
|
||||
def _run_once(page, scheme):
|
||||
"""直接点快捷方案 → 等查询 → 按列表引出数据。
|
||||
快捷方案条不存在时回退到过滤窗口选方案。"""
|
||||
if _click_quick_scheme(page, scheme):
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
else:
|
||||
# 回退:过滤窗口选方案
|
||||
if not _open_filter(page):
|
||||
return False
|
||||
if not _select_scheme(page, scheme):
|
||||
return False
|
||||
if not _submit_filter(page):
|
||||
return False
|
||||
if not _wait_progress(page):
|
||||
return False
|
||||
return _export_all_pages(page)
|
||||
|
||||
|
||||
# ================== 入口 ==================
|
||||
def run(page, save_dir, scheme, erp='new', progress=None):
|
||||
"""先全局搜索打开列表(校验列表标签页已激活),再按方案导出(快捷方案 → 等查询 → 引出 → 下载,重试 3 次)。
|
||||
每次导出前校验仍处于「采购订单列表」标签页,不对则清理残留标签页后重新搜索进入。
|
||||
progress(done, total) 为整体进度回调;返回保存文件路径,失败返回 None。"""
|
||||
# 连导场景(需求31物料收发汇总后接需求32)会残留「物料收发汇总表」标签页:
|
||||
# 多标签下 page.eles 全页匹配可能命中残留标签页里的元素,干扰后续操作。
|
||||
# 先关掉非激活标签页(SPA 内关 tab,不能整页回 index.aspx,否则跳登录页),
|
||||
# 确保从干净状态开始本次导出。
|
||||
_back_home(page, erp)
|
||||
if not _open_report(page, erp):
|
||||
raise RuntimeError("打开「采购订单列表」失败:全局搜索未命中 CGDDLB 列表(详见日志)")
|
||||
new_name = f'{config.FILE_PREFIX_32}_{datetime.now():%Y-%m-%d}.xlsx'
|
||||
config.log(f'{TAG} 导出文件: {new_name}')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
config.log(f'{TAG} 第 {attempt}/{config.RETRY_MAX} 次导出')
|
||||
# 做之前校验:当前激活标签必须是「采购订单列表」,否则回首页重新搜索进入
|
||||
if REPORT_KEYWORD not in _active_tab_title(page):
|
||||
config.log(f'{TAG} 当前标签页不是「采购订单列表」,清理残留标签页后重新搜索进入')
|
||||
if not _open_report(page, erp):
|
||||
break
|
||||
if _run_once(page, scheme):
|
||||
if kc.download_file(page, save_dir, new_name, tag=TAG):
|
||||
if progress:
|
||||
try:
|
||||
progress(1, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return str(save_dir / new_name)
|
||||
kc.reset_filter_state(page, tag=TAG) # 清掉失败留下的弹层/半填条件再重试
|
||||
time.sleep(2)
|
||||
config.log(f'{TAG} 重试 {config.RETRY_MAX} 次均失败')
|
||||
if progress:
|
||||
try:
|
||||
progress(1, 1)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1 @@
|
||||
DrissionPage>=4.0
|
||||
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>ERP报表导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0031_xq0032/assets/index-B7DSB6ed.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0031_xq0032/assets/index-C1QhPHbp.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>␍
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,171 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金色印象通联数据导出 - webhost 场景插件(XQ0045 + XQ0046 合并版)
|
||||
|
||||
通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:
|
||||
- XQ0045 按日:导某一天(YYYY-MM-DD)的交易;
|
||||
- XQ0046 按月:导某个月(YYYY-MM)的交易;
|
||||
服务端导出接口忽略商户参数、始终返回账号全量结果集(实测),因此每个日期只导一份
|
||||
全量文件(含账号下所有商户),直存本地,不再按商户拆分。
|
||||
|
||||
个性化设计:
|
||||
- 通联登录账号密码由插件界面配置经 fields 注入(plugin_configs 本机保存,下次免填);
|
||||
- 浏览器现场真登录(固定默认用户目录 + ddddocr 验证码识别),登录后转 requests.Session
|
||||
直调导出接口(服务端有 Referer 外链校验,插件内统一带 Referer);
|
||||
- 日期支持多个(逗号分隔,逐个导出);mode=日+月 时按日期串格式自动识别日/月。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import allinpay_login, allinpay_export
|
||||
|
||||
MODE_DAY = '日'
|
||||
MODE_MONTH = '月'
|
||||
MODE_BOTH = '日+月'
|
||||
|
||||
CONTENT_TRX = '交易查询'
|
||||
CONTENT_BILL = '账单'
|
||||
CONTENT_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _default_save_dir():
|
||||
return str(Path(config.get_desktop()) / f"金色印象通联数据_{datetime.now():%Y%m%d}")
|
||||
|
||||
|
||||
def _build_tasks(mode, day_date, month_date):
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(前端已用日期选择器选好值,这里只做组装)。"""
|
||||
tasks = []
|
||||
if mode in (MODE_DAY, MODE_BOTH) and day_date:
|
||||
tasks.append((MODE_DAY, day_date))
|
||||
if mode in (MODE_MONTH, MODE_BOTH) and month_date:
|
||||
tasks.append((MODE_MONTH, month_date))
|
||||
if not tasks:
|
||||
raise RuntimeError("请选择按日导出的日期和/或按月导出的月份")
|
||||
return tasks
|
||||
|
||||
|
||||
class TongLianExportPlugin(ScenePlugin):
|
||||
id = "xq0045_xq0046"
|
||||
name = "金色印象通联数据导出"
|
||||
version = "1.0.5"
|
||||
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
|
||||
"账号全量数据导出(含全部商户),服务端生成文件直存本地")
|
||||
platform = "" # 通联自带登录页(验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0045_xq0046"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致(ui=true 前端自渲染,此处分层作为参数契约文档)
|
||||
fields = {
|
||||
"mode": {"type": "string", "title": "执行模式", "default": MODE_BOTH,
|
||||
"enum": [MODE_BOTH, MODE_DAY, MODE_MONTH]},
|
||||
"content": {"type": "string", "title": "导出内容", "default": CONTENT_BOTH,
|
||||
"enum": [CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL]},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": ""},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": ""},
|
||||
"tl_username": {"type": "string", "title": "通联登录账号", "default": ""},
|
||||
"tl_password": {"type": "string", "title": "通联登录密码", "default": ""},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
content = str(fields.get("content") or CONTENT_BOTH).strip()
|
||||
username = str(fields.get("tl_username") or "").strip()
|
||||
password = str(fields.get("tl_password") or "")
|
||||
day_date = str(fields.get("day_date") or "").strip()
|
||||
month_date = str(fields.get("month_date") or "").strip()
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or _default_save_dir()
|
||||
|
||||
if not username or not password:
|
||||
raise RuntimeError("通联登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_DAY, MODE_MONTH):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if content not in (CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL):
|
||||
raise RuntimeError(f"未知导出内容:{content}")
|
||||
|
||||
do_trx = content in (CONTENT_TRX, CONTENT_BOTH)
|
||||
do_bill = content in (CONTENT_BILL, CONTENT_BOTH)
|
||||
tasks = _build_tasks(mode, day_date, month_date)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"导出内容:{content},模式:{mode},任务 {len(tasks)} 项,保存目录:{save_dir}")
|
||||
|
||||
# ---------- 登录 ----------
|
||||
ctx.progress(3)
|
||||
ctx.log("开始通联平台登录(接口优先,浏览器兜底)…")
|
||||
session = allinpay_login.tl_login(username, password)
|
||||
if session is None:
|
||||
raise RuntimeError("通联平台登录失败(账号密码错误或验证码多次识别失败),详见日志")
|
||||
ctx.progress(10)
|
||||
|
||||
saved, failed = [], []
|
||||
|
||||
# ---------- 交易查询导出(15~70:每个任务导一份账号全量,服务端忽略商户参数) ----------
|
||||
if do_trx:
|
||||
# 服务端 cusid 不能传空串(传空会直接 504),但会忽略其筛选语义、始终返回
|
||||
# 账号全量结果集;故取账号下首个真实商户号作为种子参数即可。
|
||||
ctx.log("获取账号商户列表(取首个商户号作查询种子,服务端返回全量)…")
|
||||
cus_list = allinpay_export.get_cus_list(session)
|
||||
seed_cusid = cus_list[0]['key'] if cus_list else ''
|
||||
ctx.log(f"账号下商户 {len(cus_list)} 个,查询种子商户号:{seed_cusid}")
|
||||
if not seed_cusid:
|
||||
raise RuntimeError("获取商户列表失败:账号下无商户,无法发起导出")
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"交易[{m} {d}](账号全量)"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
start, end = allinpay_export.build_date_range(m, d)
|
||||
ctx.log(f" 查询区间 {start} ~ {end}")
|
||||
fid = allinpay_export.start_export(session, seed_cusid, start, end)
|
||||
ctx.log(f" 导出任务已提交 fid={fid},等待服务端生成…")
|
||||
allinpay_export.wait_export_done(session, fid)
|
||||
url = allinpay_export.get_download_url(session, fid)
|
||||
ctx.log(" 开始下载导出文件…")
|
||||
path = allinpay_export.download_file(session, url, save_dir, f"{m}交易查询结果_{d}")
|
||||
saved.append(path)
|
||||
except Exception as e:
|
||||
ctx.log(f" 交易导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(15 + int(55 * done / max(1, units)))
|
||||
ctx.progress(70)
|
||||
|
||||
# ---------- 账单导出(70~95,主账号 zip 下载 + 解压) ----------
|
||||
if do_bill:
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"账单[{m} {d}]"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
bill_type = 'month' if m == MODE_MONTH else 'day'
|
||||
_, extract_dir = allinpay_export.bill_download(
|
||||
session, d, bill_type, save_dir)
|
||||
saved.append(extract_dir)
|
||||
except Exception as e:
|
||||
ctx.log(f" 账单导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(70 + int(25 * done / max(1, units)))
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件/目录:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = (f"通联数据导出完成(部分失败):成功 {len(saved)} 个,"
|
||||
f"失败 {len(failed)} 项 → {save_dir}")
|
||||
else:
|
||||
summary = f"通联数据导出完成:共 {len(saved)} 个文件/目录 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
PLUGINS.append(TongLianExportPlugin())
|
||||
@@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0045_xq0046 金色印象通联数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 通联平台 ====================
|
||||
LOGIN_URL = 'https://cus.allinpay.com/login'
|
||||
MAIN_URL = 'https://cus.allinpay.com/main.dsr' # 已登录首页(预热/Referer 来源)
|
||||
SEARCH_URL = 'https://cus.allinpay.com/tranx25/search'
|
||||
STATUS_URL = 'https://cus.allinpay.com/export/statusdownload'
|
||||
DOWNLOAD_INFO_URL = 'https://cus.allinpay.com/export/downloadexport/'
|
||||
BILL_URL = 'https://cus.allinpay.com/checkacct25/download'
|
||||
TRXCODE_URL = 'https://cus.allinpay.com/unauth/queryInterCode'
|
||||
TRXSTATE_URL = 'https://cus.allinpay.com/unauth/queryRecordState'
|
||||
|
||||
# 服务端有 Referer 外链校验:直接访问会被重定向回 /main.dsr
|
||||
SEARCH_HEADERS = {'Referer': MAIN_URL}
|
||||
|
||||
# ==================== 导出参数 ====================
|
||||
EXPORT_CURRENT = 'onebtnexpt' # 导出当前页
|
||||
EXPORT_ALL = 'all' # 导出全部(默认用这个)
|
||||
|
||||
# 异步导出状态轮询:每 6 秒一次,最多 12 次(服务端超时上限约 10 次/60 秒)
|
||||
STATUS_POLL_INTERVAL = 6
|
||||
STATUS_POLL_MAX = 12
|
||||
|
||||
# 登录/验证码 —— 风控敏感:每次提交都计入服务端登录尝试次数,从严控制重试,
|
||||
# 避免连续多次提交触发平台「登录失败次数已达上限」锁定(曾实测踩雷,账号被锁 2 小时)
|
||||
RETRY_MAX = 1 # 浏览器兜底登录轮数(失败即停,不反复登录)
|
||||
CAPTCHA_RETRY = 3 # 浏览器每轮验证码重试次数
|
||||
API_CAPTCHA_RETRY = 3 # 接口登录验证码重试次数
|
||||
LOGIN_FAIL_BACKOFF = 8 # 登录提交失败后的退避秒数(让风控计数沉降)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
|
||||
# ==================== 默认保存目录 ====================
|
||||
_DESKTOP = os.path.join(os.path.expanduser('~'), 'Desktop')
|
||||
|
||||
|
||||
def get_desktop():
|
||||
return _DESKTOP
|
||||
|
||||
|
||||
# ==================== 浏览器用户目录 ====================
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留(免验证码),且不占用用户日常 Chrome 配置。
|
||||
|
||||
放 %LOCALAPPDATA% 下而非系统临时目录,避免被磁盘清理工具清掉导致登录态丢失。
|
||||
"""
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
return os.path.join(base, '37duAutomation', 'browser_sessions', 'xq0045_xq0046')
|
||||
|
||||
|
||||
# ==================== 登录会话复用 ====================
|
||||
def get_session_file():
|
||||
"""已登录会话 cookies 落盘路径:跨 run 复用通联登录,避免每次执行都重新登录。"""
|
||||
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, 'allinpay_xq0045_xq0046.json')
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到 config.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
log(msg % args if args else msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
log(msg % args if args else msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
log(msg % args if args else msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
log(msg % args if args else msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
@@ -0,0 +1 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -0,0 +1,259 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联平台交易数据导出(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
服务端行为已探明(探针 workflows/share/debug_tranx25 实测验证):
|
||||
- 请求必须带 Referer,否则被重定向回 /main.dsr;
|
||||
- 商户列表内嵌在搜索页 JS:var childcuslist = '[{"key":"商户号","value":"商户名"},...]';
|
||||
- 查询:POST /tranx25/search,data={issubmit,cusid,startDate,endDate,export:false,pageIndex,
|
||||
canemptycusid},响应为整页 HTML(结果表格 #dataTable);
|
||||
- 导出(异步三步):
|
||||
1) POST /tranx25/search 带 export=all → JSON {"code":"0","message":"<fid>"}(code=1 失败);
|
||||
2) POST /export/statusdownload {id:fid} 每 6 秒轮询至 code=0(就绪);
|
||||
3) POST /export/downloadexport/ {id:fid} → {"code":"0","message":"<下载URL>"} → GET 落文件。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# ==================== HTTP 封装(统一带 Referer) ====================
|
||||
def _get(session, url, **kw):
|
||||
return session.get(url, headers=config.SEARCH_HEADERS, timeout=20, **kw)
|
||||
|
||||
|
||||
def _post(session, url, data=None, **kw):
|
||||
return session.post(url, data=data, headers=config.SEARCH_HEADERS, timeout=30, **kw)
|
||||
|
||||
|
||||
def _parse_code_message(text):
|
||||
"""解析服务端返回的 JS 风格对象(单引号,如 {code:'0',message:'fid'})。
|
||||
|
||||
前端用 eval('('+data+')') 解析,说明响应不是标准 JSON;
|
||||
先试标准 JSON,失败再正则提取 code/message。返回 (code, message)。
|
||||
"""
|
||||
text = (text or '').strip()
|
||||
try:
|
||||
j = json.loads(text)
|
||||
return str(j.get('code')), str(j.get('message') or '')
|
||||
except Exception:
|
||||
pass
|
||||
m_code = re.search(r"code\s*:\s*'?([^',}]+)'?", text)
|
||||
m_msg = re.search(r"message\s*:\s*'([^']*)'", text)
|
||||
code = m_code.group(1).strip() if m_code else ''
|
||||
msg = m_msg.group(1) if m_msg else ''
|
||||
if not (m_code or m_msg):
|
||||
raise RuntimeError(f"响应无法解析(可能会话失效被踢回页面):{text[:200]}")
|
||||
return code, msg
|
||||
|
||||
|
||||
# ==================== 商户列表 ====================
|
||||
def get_cus_list(session):
|
||||
"""GET 搜索页解析 childcuslist → [{'key': 商户号, 'value': 商户名}, ...]。"""
|
||||
resp = _get(session, config.SEARCH_URL)
|
||||
m = re.search(r"var childcuslist\s*=\s*'([^']*)'", resp.text)
|
||||
if not m:
|
||||
raise RuntimeError("搜索页未找到 childcuslist(会话可能失效,请重新登录)")
|
||||
data = json.loads(m.group(1))
|
||||
if not isinstance(data, list):
|
||||
raise RuntimeError("childcuslist 解析异常")
|
||||
return data
|
||||
|
||||
|
||||
# ==================== 异步导出三步 ====================
|
||||
def start_export(session, cusid, start, end):
|
||||
"""发起导出 → 返回 fid。
|
||||
|
||||
服务端实测(探针 exp_probe + 实跑 + 测速验证):
|
||||
- export=all 会忽略日期参数、导出当天全量(错误行为);
|
||||
- export=onebtnexpt(导出当前查询结果集)才按日期区间导出;
|
||||
- cusid 必须非空:传空串时服务端直接 504 Gateway Timeout(实测 60s 超时);
|
||||
但服务端忽略 cusid 的筛选语义——传任意真实商户号都返回账号全量结果集
|
||||
(不同商户同日期返回同一 fid、同一文件),故用账号下首个商户号即可。
|
||||
因此必须先查询(export=false)建立结果集,再用 onebtnexpt 导出。
|
||||
"""
|
||||
base = {
|
||||
'issubmit': 'issubmit',
|
||||
'cusid': cusid,
|
||||
'startDate': start,
|
||||
'endDate': end,
|
||||
'pageIndex': '1',
|
||||
'canemptycusid': 'true',
|
||||
}
|
||||
# 1) 查询建立结果集(export=false)
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': 'false'})
|
||||
# 2) 导出当前结果集(onebtnexpt)
|
||||
code, msg = _parse_code_message(
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': config.EXPORT_CURRENT}).text)
|
||||
if code == '1':
|
||||
raise RuntimeError(f"导出失败:{msg}")
|
||||
fid = msg
|
||||
if not fid:
|
||||
raise RuntimeError("导出响应缺少 fid")
|
||||
return fid
|
||||
|
||||
|
||||
def wait_export_done(session, fid):
|
||||
"""轮询导出状态,直到就绪(code=0)或超时。
|
||||
|
||||
状态契约(探针实测):code='0'=文件就绪;code='1'=生成中。
|
||||
其它码(如 '2' 失败)只告警不判就绪,避免误把失败态当成功去取下载地址;
|
||||
超时错误里带最后状态,便于定位。
|
||||
"""
|
||||
last = ""
|
||||
for i in range(1, config.STATUS_POLL_MAX + 1):
|
||||
code, msg = _parse_code_message(_post(session, config.STATUS_URL, {'id': fid}).text)
|
||||
last = f"code={code} {msg}".strip()
|
||||
if code == '0':
|
||||
config.log(f"[导出] fid={fid} 文件就绪(轮询 {i} 次)")
|
||||
return True
|
||||
if code != '1':
|
||||
config.log(f"[导出] fid={fid} 状态异常({last}),继续等待", "WARN")
|
||||
else:
|
||||
# 每次轮询都打进度,避免长时间静默被误认为卡死
|
||||
config.log(f"[导出] fid={fid} 文件生成中(第 {i} 次轮询,已等待 {i * config.STATUS_POLL_INTERVAL} 秒)…")
|
||||
time.sleep(config.STATUS_POLL_INTERVAL)
|
||||
raise RuntimeError(f"导出超时(服务端未在时限内生成文件,最后状态:{last})")
|
||||
|
||||
|
||||
def get_download_url(session, fid):
|
||||
"""获取下载地址。"""
|
||||
code, msg = _parse_code_message(_post(session, config.DOWNLOAD_INFO_URL, {'id': fid}).text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"获取下载地址失败:{msg}")
|
||||
return msg
|
||||
|
||||
|
||||
# ==================== 下载校验 ====================
|
||||
def _check_download_content_type(resp):
|
||||
"""下载响应 Content-Type 校验:HTML/文本说明可能被踢回登录页,直接报错。"""
|
||||
ct = (resp.headers.get('Content-Type') or '').lower()
|
||||
if 'html' in ct or ct.startswith('text/'):
|
||||
raise RuntimeError(
|
||||
f"下载返回非文件内容(Content-Type={ct or 'unknown'}),会话可能已失效,请重新登录")
|
||||
|
||||
|
||||
def _is_zip_file(path):
|
||||
"""文件头魔数校验:zip/xlsx 均以 PK 开头。"""
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
return f.read(2) == b'PK'
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _safe_extract(zip_path, extract_dir):
|
||||
"""解压 zip,并拦截路径穿越条目(.. / 绝对路径)。"""
|
||||
with zipfile.ZipFile(zip_path) as zf:
|
||||
for info in zf.infolist():
|
||||
parts = Path(info.filename).parts
|
||||
if info.filename.startswith('/') or '..' in parts or ':' in parts:
|
||||
raise RuntimeError(f"压缩包含非法路径条目,已中止解压:{info.filename}")
|
||||
zf.extractall(extract_dir)
|
||||
|
||||
|
||||
def download_file(session, url, folder, stem):
|
||||
"""下载导出文件到 folder/,文件名 stem + 扩展名(优先 Content-Disposition,默认 .xlsx)。
|
||||
返回最终文件路径。带 Content-Type 与文件魔数校验,防会话失效时把 HTML 落成伪文件。"""
|
||||
resp = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
resp.raise_for_status()
|
||||
_check_download_content_type(resp)
|
||||
ext = '.xlsx'
|
||||
cd = resp.headers.get('Content-Disposition', '')
|
||||
m = re.search(r'filename\*?=(?:UTF-8\'\')?"?([^\";]+)"?', cd, re.I)
|
||||
if m:
|
||||
nm = m.group(1).strip().strip('"')
|
||||
if '.' in nm:
|
||||
ext = '.' + nm.rsplit('.', 1)[1].lower()
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
path = os.path.join(folder, f"{stem}{ext}")
|
||||
total = int(resp.headers.get('Content-Length') or 0)
|
||||
received, last_log = 0, time.time()
|
||||
with open(path, 'wb') as f:
|
||||
for chunk in resp.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
received += len(chunk)
|
||||
now = time.time()
|
||||
if now - last_log >= 8: # 每 8 秒报一次下载进度,避免长下载静默
|
||||
last_log = now
|
||||
mb = received / 1048576
|
||||
if total:
|
||||
pct = received * 100 // max(1, total)
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB / {total / 1048576:.1f}MB({pct}%)…")
|
||||
else:
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB…")
|
||||
if not _is_zip_file(path): # xlsx 本质是 zip,文件头须为 PK
|
||||
os.remove(path)
|
||||
raise RuntimeError(f"下载文件不是有效 xlsx(文件头异常),已删除:{path}")
|
||||
config.log(f"[导出] 已保存:{path}({received / 1048576:.1f} MB)")
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 日期范围 ====================
|
||||
def build_date_range(mode, date_str):
|
||||
"""按模式把日期字符串转成查询区间 (start, end)。
|
||||
mode='月':date_str=YYYY-MM → 当月 1 日 10:00:00 ~ 下月 1 日 10:00:00(对账 10 点切日口径);
|
||||
mode='日':date_str=YYYY-MM-DD(数据起始日,默认昨天)→ 当天 00:00:00 ~ 次日 23:59:59
|
||||
(即默认 = 昨天0点 ~ 今天24点,今天数据少基本无影响)。"""
|
||||
if mode == '月':
|
||||
ym = datetime.strptime(date_str, '%Y-%m')
|
||||
next_month = (ym.replace(day=1) + timedelta(days=32)).replace(day=1)
|
||||
return (ym.strftime('%Y-%m-01 10:00:00'),
|
||||
next_month.strftime('%Y-%m-01 10:00:00'))
|
||||
d = datetime.strptime(date_str, '%Y-%m-%d')
|
||||
nxt = d + timedelta(days=1)
|
||||
return d.strftime('%Y-%m-%d 00:00:00'), nxt.strftime('%Y-%m-%d 23:59:59')
|
||||
|
||||
|
||||
def default_dates(mode):
|
||||
"""未填日期时的默认值:日=昨天;月=上月。"""
|
||||
today = datetime.now()
|
||||
if mode == '月':
|
||||
first_this = today.replace(day=1)
|
||||
last_month = first_this - timedelta(days=1)
|
||||
return last_month.strftime('%Y-%m')
|
||||
yesterday = today - timedelta(days=1)
|
||||
return yesterday.strftime('%Y-%m-%d')
|
||||
|
||||
|
||||
# ==================== 账单导出(主账号,zip 下载 + 解压) ====================
|
||||
def bill_download(session, date_str, bill_type, folder):
|
||||
"""通联账单下载(只导主账号/当前商户)。
|
||||
|
||||
POST /checkacct25/download:日账单 ?reportdate=YYYYMMDD;月账单 ?type=month&reportdate=YYYYMM。
|
||||
服务端返回 {"code":"0","message":"<zip 下载 URL>"},GET 下载 zip 并解压。
|
||||
date_str = YYYY-MM-DD(日)或 YYYY-MM(月);bill_type = 'day' | 'month'。
|
||||
返回 (zip_path, extract_dir)。
|
||||
"""
|
||||
reportdate = date_str.replace('-', '')
|
||||
params = {'reportdate': reportdate}
|
||||
if bill_type == 'month':
|
||||
params['type'] = 'month'
|
||||
resp = _post(session, config.BILL_URL, params=params)
|
||||
code, msg = _parse_code_message(resp.text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"账单下载失败:{msg}")
|
||||
url = msg
|
||||
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
zr = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
zr.raise_for_status()
|
||||
_check_download_content_type(zr)
|
||||
prefix = '日账单' if bill_type == 'day' else '月账单'
|
||||
zip_path = os.path.join(folder, f"{prefix}_{date_str}.zip")
|
||||
with open(zip_path, 'wb') as f:
|
||||
for chunk in zr.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
if not _is_zip_file(zip_path):
|
||||
os.remove(zip_path)
|
||||
raise RuntimeError(f"账单下载不是有效 zip(文件头异常),已删除:{zip_path}")
|
||||
|
||||
extract_dir = os.path.join(folder, f"{prefix}_{date_str}")
|
||||
_safe_extract(zip_path, extract_dir)
|
||||
config.log(f"[账单] 已下载并解压:{extract_dir}")
|
||||
return zip_path, extract_dir
|
||||
@@ -0,0 +1,478 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联支付商户服务平台登录模块(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
自 workflows/share/allinpay_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env);
|
||||
- print → config.log;返回 requests.Session(登录后会话直接可用,无需浏览器常驻)。
|
||||
|
||||
登录方式(接口优先,浏览器兜底):
|
||||
1) 接口登录(首选,已实测一次成功):GET /login(拿 SESSION + 页面内嵌 publicKey)
|
||||
→ GET /getvalidCode?type=cuserrorCode 验证码图 → ddddocr 识别(4位)
|
||||
→ JSEncrypt 兼容 RSA 加密密码(PKCS#1 v1.5 + base64)→ POST /login(userid/
|
||||
encpassword/cuserrorCode,带 Referer)→ 302 离开 /login 即成功;
|
||||
2) 浏览器兜底:DrissionPage 现场登录(验证码元素截图 + ddddocr),成功后从浏览器
|
||||
cookies 构建 requests.Session。
|
||||
|
||||
登录页(账号登录 tab,DOM 参考 aa.md):
|
||||
账号 #userid / 密码 #password(初始 readonly,onfocus 移除;提交时页面 JS 加密进 #encpassword)
|
||||
验证码 #captcha + 图 <img src="/getvalidCode?type=cuserrorCode">(URL 型,元素截图 + ddddocr)
|
||||
登录按钮 button[onclick*="valandsubmit"](触发 valandsubmit JS 加密密码后提交表单)
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
HUMAN_DELAY = (0.4, 1.2)
|
||||
_VALIDCODE_URL = config.LOGIN_URL.replace('/login', '/getvalidCode?type=cuserrorCode')
|
||||
_PUBKEY_RE = re.compile(r"var publicKey='([^']+)'")
|
||||
_LOGIN_FORM_RE = re.compile(r'<form[^>]*id=["\']?accountForm|action=["\']?/login')
|
||||
|
||||
_ocr = None
|
||||
|
||||
|
||||
def _get_ocr():
|
||||
"""ddddocr 单例(懒加载),接口/浏览器登录共用。"""
|
||||
global _ocr
|
||||
if _ocr is None:
|
||||
import ddddocr
|
||||
_ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return _ocr
|
||||
|
||||
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _rsa_encrypt(pubkey, pwd):
|
||||
"""JSEncrypt 兼容:RSA PKCS#1 v1.5 加密 + base64。
|
||||
|
||||
页面 publicKey 是 SPKI/X.509 SubjectPublicKeyInfo(BEGIN PUBLIC KEY)裸 DER,
|
||||
用 cryptography 解析后按 PKCS#1 v1.5 填充加密(1024 位公钥,明文 ≤117 字节)。
|
||||
"""
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives.serialization import load_der_public_key
|
||||
pub = load_der_public_key(base64.b64decode(pubkey), default_backend())
|
||||
ct = pub.encrypt(pwd.encode(), padding.PKCS1v15())
|
||||
return base64.b64encode(ct).decode()
|
||||
|
||||
|
||||
def _api_login(username, password):
|
||||
"""接口登录(纯 requests,不弹浏览器)。成功返回 requests.Session,失败返回 None。
|
||||
|
||||
服务端行为(探针实测):
|
||||
- /login 页面内嵌固定 RSA 公钥(publicKey,1024 位 PKCS#1);
|
||||
- 验证码 4 位,GET /getvalidCode?type=cuserrorCode 返回图片(session 绑定);
|
||||
- POST /login 需带 Referer(外链校验),成功 302 到 /main。
|
||||
"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
if len(password.encode()) > 117:
|
||||
# 页面公钥 1024 位,PKCS#1 v1.5 明文上限 117 字节;超长无法加密,
|
||||
# 明确提示后走浏览器兜底登录
|
||||
config.log("[通联登录] 密码过长(>117 字节),接口登录无法加密,将回退浏览器登录")
|
||||
return None
|
||||
html = session.get(config.LOGIN_URL, timeout=20).text
|
||||
m = _PUBKEY_RE.search(html)
|
||||
if not m:
|
||||
config.log("[通联登录] 接口登录失败:未找到 publicKey")
|
||||
return None
|
||||
pubkey = m.group(1)
|
||||
enc = _rsa_encrypt(pubkey, password)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 接口登录准备异常:{e}")
|
||||
return None
|
||||
|
||||
ocr = _get_ocr()
|
||||
for attempt in range(config.API_CAPTCHA_RETRY):
|
||||
try:
|
||||
img = session.get(_VALIDCODE_URL, timeout=20).content
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 获取验证码图异常:{e}")
|
||||
return None
|
||||
code = ocr.classification(img).strip()
|
||||
config.log(f"[通联登录] 接口登录 第 {attempt + 1}/{config.API_CAPTCHA_RETRY} 次验证码识别:{code!r}")
|
||||
if len(code) != 4:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
resp = session.post(config.LOGIN_URL, data={
|
||||
'userid': username,
|
||||
'encpassword': enc,
|
||||
'cuserrorCode': code,
|
||||
}, headers={'Referer': config.LOGIN_URL}, timeout=20, allow_redirects=True)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提交登录异常:{e}")
|
||||
return None
|
||||
if '/login' not in resp.url:
|
||||
config.log(f"[通联登录] 接口登录成功:{resp.url}")
|
||||
return session
|
||||
# 仍在登录页:验证码错/账号密码错/风控。每次提交都计入服务端尝试次数,
|
||||
# 失败后退避并停止(不连续重试,避免触发登录次数风控锁定)
|
||||
hit = re.search(r'验证码错误|验证码不正确|账号或密码|密码错误|登录失败|次数已达上限|锁定', resp.text)
|
||||
if hit:
|
||||
config.log(f"[通联登录] 服务端提示:{hit.group(0)}")
|
||||
if '次数已达上限' in hit.group(0) or '锁定' in hit.group(0):
|
||||
config.log("[通联登录] 检测到风控锁定提示,立即停止登录尝试")
|
||||
return None
|
||||
time.sleep(config.LOGIN_FAIL_BACKOFF)
|
||||
config.log("[通联登录] 接口登录验证码多次未通过,停止重试")
|
||||
return None
|
||||
|
||||
|
||||
def _on_target(page):
|
||||
"""登录成功判定:URL 离开 /login。"""
|
||||
try:
|
||||
return '/login' not in (page.url or '')
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_input(page, selectors):
|
||||
for sel in selectors:
|
||||
ele = page.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(page):
|
||||
"""定位验证码输入框 + 图片(从 #captcha 容器向上找,避免命中验证码登录 tab 的图)。"""
|
||||
code_input = page.ele('#captcha', timeout=config.TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(1) # div.input-group#captcha_div
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
img = page.ele('css:.tab-pane.active img[src*="getvalidCode"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""URL 型验证码(/getvalidCode)直接元素截图;兼容 base64 内嵌 src。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景导入开销。"""
|
||||
import ddddocr
|
||||
ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return ocr.classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _refresh_captcha(page, img):
|
||||
"""点击验证码图片刷新(onclick=cusjsUtil.changeCode)。URL 型验证码无法可靠比对,点击后等渲染。"""
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _ensure_account_tab(page):
|
||||
"""确保「账号登录」tab 激活(默认激活;若页面记住验证码登录则切回)。"""
|
||||
uid = page.ele('#userid', timeout=2)
|
||||
if uid:
|
||||
try:
|
||||
if uid.states.is_displayed:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
tab_btn = page.ele('css:a[href="#account"], css:a[data-target="#account"]', timeout=3) \
|
||||
or page.ele('tag:a@@text():账号登录', timeout=3)
|
||||
if tab_btn:
|
||||
try:
|
||||
tab_btn.click()
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _wait_login_result(page):
|
||||
"""提交后轮询判定登录结果,返回 bool。"""
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 登录成功:{page.url}")
|
||||
return True
|
||||
for sel in ('css:.invalid-feedback', 'css:.alert-danger', 'css:.toast'):
|
||||
try:
|
||||
eles = page.eles(sel, timeout=0.3)
|
||||
except Exception:
|
||||
continue
|
||||
for ele in eles:
|
||||
try:
|
||||
text = ele.text.strip()
|
||||
except Exception:
|
||||
text = ''
|
||||
if text:
|
||||
config.log(f"[通联登录] 失败提示:{text}")
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _input_value(ele):
|
||||
"""读取输入框当前值(页面刷新后表单清空,用于判断是否需要重填)。"""
|
||||
try:
|
||||
return ele.value or ''
|
||||
except Exception:
|
||||
try:
|
||||
return ele.attr('value') or ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def _fill_account(page, username, password):
|
||||
"""确保账号密码已填(每轮提交前调用)。
|
||||
|
||||
通联登录失败后页面会整页刷新、表单被清空;这里做幂等填充——
|
||||
账号/密码已存在则跳过,被清空则重新输入,避免后续重试提交空表单。
|
||||
"""
|
||||
user_input = page.ele('#userid', timeout=config.TIMEOUT)
|
||||
if not user_input:
|
||||
config.log("[通联登录] 找不到账号输入框")
|
||||
return False
|
||||
if _input_value(user_input) != username:
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(page, ['#password', 'css:input[type="password"]:not([name="encpassword"])'])
|
||||
if not pwd_input:
|
||||
config.log("[通联登录] 找不到密码输入框")
|
||||
return False
|
||||
if not _input_value(pwd_input):
|
||||
pwd_input.click() # 触发 onfocus 移除 readonly
|
||||
_human_pause(0.2, 0.5)
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
return True
|
||||
|
||||
|
||||
def _try_login_once(page, username, password):
|
||||
"""完成一次填表 + 验证码 + 提交,返回 bool。
|
||||
每轮提交前都会确保账号密码已填(页面刷新后自动重填)。"""
|
||||
_ensure_account_tab(page)
|
||||
|
||||
for attempt in range(config.CAPTCHA_RETRY):
|
||||
if not _fill_account(page, username, password):
|
||||
return False
|
||||
config.log(f"[通联登录] 第 {attempt + 1}/{config.CAPTCHA_RETRY} 次验证码识别")
|
||||
img, code_input = _find_captcha(page)
|
||||
if not img or not code_input:
|
||||
config.log("[通联登录] 找不到验证码图片或输入框")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] ddddocr 识别异常:{e}")
|
||||
return False
|
||||
config.log(f"[通联登录] 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(page, img)
|
||||
continue
|
||||
code_input.click() # 触发 onfocus 移除 readonly
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
btn = page.ele('css:.tab-pane.active button[onclick*="valandsubmit"]', timeout=config.TIMEOUT) \
|
||||
or page.ele('tag:button@@text():登录', timeout=config.TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[通联登录] 找不到登录提交按钮")
|
||||
return False
|
||||
_human_pause(0.2, 0.6)
|
||||
btn.click()
|
||||
|
||||
if _wait_login_result(page):
|
||||
return True
|
||||
_refresh_captcha(page, img)
|
||||
return False
|
||||
|
||||
|
||||
def _build_session(page):
|
||||
"""从浏览器 cookies 构建 requests.Session(仅保留 allinpay.com 域)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
for c in page.cookies():
|
||||
domain = (c.get('domain') or '')
|
||||
if 'allinpay.com' not in domain:
|
||||
continue
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=domain.lstrip('.'), path=c.get('path', '/'))
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提取 cookies 异常:{e}")
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 会话落盘复用(跨 run,子进程隔离下也生效) ====================
|
||||
def _dump_cookies(session):
|
||||
"""把 requests.Session 的 cookies 序列化为可持久化列表。"""
|
||||
out = []
|
||||
for c in session.cookies:
|
||||
out.append({'name': c.name, 'value': c.value, 'domain': c.domain or '',
|
||||
'path': c.path or '/'})
|
||||
return out
|
||||
|
||||
|
||||
def save_session(username, session):
|
||||
"""登录成功后把会话 cookies 落盘,供下次运行直接复用。失败不影响本次执行。"""
|
||||
try:
|
||||
data = {'username': username, 'cookies': _dump_cookies(session)}
|
||||
with open(config.get_session_file(), 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 保存会话失败(不影响本次执行):{e}")
|
||||
|
||||
|
||||
def _session_valid(session):
|
||||
"""会话探活:GET 首页,未落回 /login 且页面内容不含登录表单即视为有效。
|
||||
|
||||
平台为单点登录(多地互斥):一旦其它设备/浏览器用同一账号重新登录,
|
||||
本会话立即失效。此时 main.dsr 仍返回 200,但页面内容是登录表单
|
||||
(<form id="accountForm" action="/login">)而非业务首页——仅看 URL 会误判
|
||||
为有效,导致后续 API 全部失败,必须校验页面内容。
|
||||
"""
|
||||
try:
|
||||
resp = session.get(config.MAIN_URL, headers=config.SEARCH_HEADERS,
|
||||
timeout=15, allow_redirects=True)
|
||||
if resp.status_code != 200 or '/login' in resp.url:
|
||||
return False
|
||||
return not _LOGIN_FORM_RE.search(resp.text)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def load_session(username):
|
||||
"""读取并重建上次登录会话;有效则返回 requests.Session,否则返回 None。"""
|
||||
path = config.get_session_file()
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
if data.get('username') != username:
|
||||
config.log("[通联登录] 本地会话账号与当前账号不一致,重新登录")
|
||||
return None
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
for c in data.get('cookies') or []:
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=c['domain'] or '', path=c['path'] or '/')
|
||||
if _session_valid(session):
|
||||
return session
|
||||
config.log("[通联登录] 本地会话已失效,重新登录")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 读取本地会话异常:{e}")
|
||||
return None
|
||||
|
||||
|
||||
def tl_login(username, password):
|
||||
"""通联平台登录(本地会话复用 → 接口登录 → 浏览器兜底)。
|
||||
|
||||
成功返回 requests.Session,失败返回 None。登录成功后会话 cookies 落盘,
|
||||
下次运行直接复用免登录(探活失败才重新登录)。
|
||||
"""
|
||||
username = (username or '').strip()
|
||||
password = password or ''
|
||||
if not (username and password):
|
||||
config.log("[通联登录] 账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return None
|
||||
|
||||
# 1) 复用本地已保存会话(免重新登录)
|
||||
session = load_session(username)
|
||||
if session is not None:
|
||||
config.log("[通联登录] 复用本地已登录会话,免重新登录(单点登录:请勿同时在其")
|
||||
config.log("[通联登录] 它设备/浏览器登录同一账号,否则本会话会被踢下线)")
|
||||
return session
|
||||
|
||||
# 2) 接口登录(首选,不弹浏览器)
|
||||
config.log("[通联登录] 本地会话失效,开始重新登录(单点登录:本次登录会顶掉其它")
|
||||
config.log("[通联登录] 设备/浏览器上的同一账号登录)")
|
||||
session = _api_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
config.log("[通联登录] 接口登录未成功,回退浏览器登录")
|
||||
# 3) 浏览器兜底
|
||||
session = _browser_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
|
||||
|
||||
def _browser_login(username, password):
|
||||
"""浏览器兜底登录(DrissionPage + ddddocr 图形验证码,元素截图)。
|
||||
|
||||
返回:成功 → requests.Session(从浏览器 cookies 构建);失败 → None。
|
||||
固定默认用户目录保留登录态:已登录会话直接复用(免验证码)。
|
||||
调用方使用完毕无需额外操作(本函数已 page.quit())。
|
||||
"""
|
||||
co = ChromiumOptions()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录(%LOCALAPPDATA% 下,非临时目录):登录态跨次保留免验证码,
|
||||
# 且不占用用户日常 Chrome 配置、不被系统磁盘清理清掉
|
||||
co.set_user_data_path(config.get_browser_profile_dir())
|
||||
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[通联登录] 浏览器登录 第 {attempt}/{config.RETRY_MAX} 次 → {config.LOGIN_URL}")
|
||||
page = ChromiumPage(co)
|
||||
page.get(config.LOGIN_URL)
|
||||
_human_pause(1.0, 2.0)
|
||||
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 检测到已登录会话,直接复用:{page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
|
||||
if _try_login_once(page, username, password):
|
||||
config.log(f"[通联登录] 登录成功 → {page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 异常:{e}")
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
config.log("[通联登录] 浏览器登录重试多次均失败")
|
||||
return None
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0045_xq0046",
|
||||
"name": "金色印象通联数据导出",
|
||||
"version": "1.0.5",
|
||||
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0045_xq0046"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "日+月",
|
||||
"enum": ["日", "月", "日+月"],
|
||||
"description": "日/月/日+月:决定日期选择器粒度;交易查询与账单导出共用日期选择器,插件内部自动换算各自区间"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"title": "导出内容",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "交易查询", "账单"],
|
||||
"description": "交易查询=逐商户导交易明细(xlsx);账单=主账号日/月账单(zip 下载并解压)"
|
||||
},
|
||||
"day_date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"title": "按日导出",
|
||||
"default": "",
|
||||
"description": "默认昨天;交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
},
|
||||
"month_date": {
|
||||
"type": "string",
|
||||
"format": "month",
|
||||
"title": "按月导出",
|
||||
"default": "",
|
||||
"description": "默认上月;交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
},
|
||||
"tl_username": {
|
||||
"type": "string",
|
||||
"title": "通联登录账号",
|
||||
"default": "",
|
||||
"description": "商户服务平台登录账号(保存在本机,下次免填)"
|
||||
},
|
||||
"tl_password": {
|
||||
"type": "string",
|
||||
"title": "通联登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/金色印象通联数据_YYYYMMDD;交易查询每日期一份全量文件(日_日期.xlsx / 月_月份.xlsx),账单按 账单_YYYYMM 目录存放"
|
||||
}
|
||||
},
|
||||
"required": ["tl_username", "tl_password"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
ddddocr>=1.4
|
||||
cryptography>=39.0
|
||||
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/xq0045_xq0046/assets/index-CuUBZGG_.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-CmyoQ4x2.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user