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:
2026-09-23 15:19:54 +08:00
parent dd546fc07b
commit be1a2899ba
80 changed files with 9029 additions and 493 deletions
+41
View File
@@ -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 独立实例),确保登录的就是本次配置的账号。
+184
View File
@@ -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())
+56
View File
@@ -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
+181
View File
@@ -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
+299
View File
@@ -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
+87
View File
@@ -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": []
}
}
+510
View File
@@ -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
+1
View File
@@ -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
+13
View File
@@ -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>