feat: 新增xq0031_xq0032 ERP报表导出插件,完成功能与基建更新

1. 新增xq0031_xq0032插件:包含前后端源码、打包脚本、配置文件与插件元数据
2. 新增内网文件服务器组件:exe、启停脚本、打包脚本与配置
3. 新增敏感凭证RSA加密下发能力与存储结构
4. 新增大文件源管理表与相关API
5. 优化登录流程与会话管理,新增Chrome自动化安装工具链
6. 清理废弃插件与示例代码
7. 更新版本号至1.1.3,完善安装包与.gitignore配置
This commit is contained in:
2026-09-17 12:42:44 +08:00
parent 84d3e103ec
commit b32f8e8fe2
105 changed files with 7819 additions and 4276 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 独立实例),确保登录的就是本次配置的账号。
+185
View File
@@ -0,0 +1,185 @@
# -*- coding: utf-8 -*-
"""ERP报表导出 - webhost 场景插件(XQ0031 + XQ0032 合并版)
金蝶 K3Cloud 报表自动导出,两种报表可单选或同次会话连导(登录一次):
物料收发汇总表(XQ0031):组织/仓库编码(或关系多行)/日期多档(N天或自定义区间)逐档导出
采购订单列表(XQ0032):快捷方案 → 等查询 → 按列表引出数据
个性化设计(自带 Vue 界面,plugin.json 声明 "ui": true):
- ERP 新/旧系统、登录账号密码由用户在插件窗口内自行填写,
经 /api/plugin-config 保存在执行机本机,下次打开自动回填;
- 仓库编码、日期选项均为多选(可自建条目,日期可混入自定义区间);
- 浏览器每次现场真登录(auto_port 独立实例),确保用的就是本次配置的账号。
"""
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.2"
description = "金蝶K3Cloud报表导出:物料收发汇总表(需求31)+ 采购订单列表(需求32),支持新旧系统与个性化配置"
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, "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
scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME
codes = _as_str_list(fields.get("stock_codes")) or list(config.STOCK_CODES_DEFAULT)
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 (codes and 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]})")
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)} 个 / 日期 {len(dates)} 档")
files31, failed31 = material_summary.run(
page, save_dir, org, codes, dates,
progress=lambda done_i, _total: _report(done_i))
saved += files31
failed += [f"物料收发汇总表[{x}]" for x in failed31]
except RuntimeError as e:
failed.append(f"物料收发汇总表[{e}]")
if do_32:
_back_home(page, erp) # 报表间回到主界面,保证全局搜索可用
if do_32:
try:
ctx.log(f"开始导出采购订单列表(方案:{scheme})")
f32 = purchase_order.run(page, save_dir, scheme,
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()
def _back_home(page, erp):
"""两种报表连导时回到 K3 主界面(全局搜索入口所在页),保证下个报表可打开。"""
try:
home = erp_login.ERP_URLS.get(erp, erp_login.ERP_URLS['new'])
if erp_login.SUCCESS_KEYWORD not in (page.url or ''):
page.get(home)
time.sleep(2)
except Exception as e:
config.log(f"回主界面异常(继续尝试): {e}")
PLUGINS.append(ErpReportExportPlugin())
+43
View File
@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
把本插件压成 dist-plugin/xq0031_xq0032_v<版本>.zip,
包根布局与 sb_person_change 一致:plugin.json / 各 .py / ui/ 直接位于 zip 根。
排除项:ui-src(前端源码与 node_modules)、__pycache__、debug、本脚本、*.pyc。
用法(desktop/ 下执行):
../.venv/Scripts/python.exe ../plugins/xq0031_xq0032/_pack.py
随后发布:
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
dist-plugin\\xq0031_xq0032_v1.0.0.zip --id xq0031_xq0032 --version 1.0.0
"""
import json
import sys
import zipfile
from pathlib import Path
_HERE = Path(__file__).resolve().parent
_OUT_DIR = _HERE.parents[1] / "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"]
if not (_HERE / "ui" / "index.html").is_file():
sys.exit("缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
_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()
+39
View File
@@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
"""ERP报表导出(xq0031_xq0032)插件配置:默认值与运行参数。
合并 XQ0031(物料收发汇总表)+ XQ0032(采购订单列表)的固化配置,
与 workflows 影刀版各源文件常量保持同源(四方向零依赖,各自演进)。
个性化配置(账号密码/仓库编码/日期选项等)由插件自带 Vue 界面维护,经
webhost /api/plugin-config 落执行机本机,run() 时经 fields 注入;
本文件只承载 fields 未传时的兜底默认与运行参数。
"""
# ==================== 1. 业务默认值(fields 未传/留空时的兜底) ====================
ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织
STOCK_CODES_DEFAULT = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
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
+163
View File
@@ -0,0 +1,163 @@
# -*- coding: utf-8 -*-
"""金蝶 K3Cloud(HTML5)ERP 登录模块(xq0031_xq0032 插件内自包含)。
自 workflows/share/erp_login.py 迁移,插件化改造点:
- 账号密码由插件界面配置经 fields 注入(不再读 .env),个性化归属明确;
- auto_port 独立浏览器实例:不接管用户已开的浏览器,cookies 天然隔离,
确保每次真实登录的就是本次配置的账号(不做 cookies 缓存复用);
- 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 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()。
"""
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}")
co = ChromiumOptions()
if headless:
co.headless()
# auto_port:独立端口 + 独立临时用户目录,不接管用户浏览器、不残留旧登录态
co.auto_port(True)
co.set_argument('--start-maximized')
page = ChromiumPage(co)
page.get(login_url)
time.sleep(2)
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
+249
View File
@@ -0,0 +1,249 @@
# -*- 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()
# 找可见的「下载」按钮
dl = None
end = time.time() + config.TIMEOUT
while time.time() < end:
for el in page.eles('css:[id*="FDOWNLOAD_c"]'):
try:
if el.states.is_displayed:
dl = el
break
except Exception:
pass
if dl:
break
time.sleep(0.5)
if not dl:
config.log(f'{tag} 找不到下载按钮')
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
+673
View File
@@ -0,0 +1,673 @@
# -*- coding: utf-8 -*-
"""需求31 - 金蝶 K3Cloud ERP「物料收发汇总表」自动导出(xq0031_xq0032 插件内模块)。
自 workflows/XQ0031 material_summary_export.py 迁移:
搜索打开报表 → 设置组织/日期/仓库编码 → 查询 → 引出所有页 → 下载保存。
组织/仓库编码/日期选项由插件界面配置经 run() 参数注入;交互逻辑与影刀版保持同源。
"""
import json
import time
from datetime import datetime, timedelta
from . import config
from . import k3_common as kc
TAG = '[物料收发汇总表]'
# ================== 工具函数 ==================
def resolve_dates(option):
"""解析单个日期选项 → (开始日期, 结束日期, 文件标签)。
支持:
'60D' 今天往前推 N 天(60/30/15/7/3)
('2026-01-01', '2026-09-15') 元组/列表自定义起止
'2026-01-01~2026-09-15' 字符串自定义起止(~ , ,空格分隔均可)"""
if isinstance(option, (list, tuple)):
if len(option) == 2:
begin, end = str(option[0]), str(option[1])
return begin, end, f'{begin}_{end}'
raise ValueError(f'自定义日期需为(开始, 结束)两项: {option!r}')
s = str(option).strip()
for sep in ('~', ',', ',', ' '):
if sep in s:
parts = [p.strip() for p in s.split(sep) if p.strip()]
if len(parts) == 2:
return parts[0], parts[1], f'{parts[0]}_{parts[1]}'
raise ValueError(f'自定义日期需为 开始~结束 两项: {option!r}')
days = int(s.rstrip('Dd'))
end = datetime.now().date()
begin = end - timedelta(days=days)
return begin.isoformat(), end.isoformat(), str(option)
def _wait_window_title(page, keyword, timeout=None):
"""等待出现标题包含关键字的窗口,返回 True/False。"""
timeout = config.TIMEOUT if timeout is None else timeout
end = time.time() + timeout
while time.time() < end:
t = page.ele('css:.k-window-title', timeout=1)
if t and keyword in t.text:
return True
time.sleep(0.5)
return False
# ================== 报表操作 ==================
def _open_report(page):
"""点击全局搜索 → 输入「物料收发汇总表」→ 回车 → 等待过滤界面出现。"""
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('物料收发汇总表')
time.sleep(0.3)
kc.press_enter(page)
time.sleep(1.5)
# 等待过滤界面(含组织字段 FSTOCKORGID)出现,限定在 .k-window 弹窗内
end = time.time() + 40
while time.time() < end:
if kc.ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=1):
config.log(f'{TAG} 报表过滤界面已打开')
return True
time.sleep(0.5)
# 兜底:点击搜索结果中的「物料收发汇总表」菜单项
config.log(f'{TAG} 未自动打开,尝试点击搜索结果')
els = page.eles('xpath://*[contains(text(), "物料收发汇总表")]')
for el in els:
try:
if el.states.is_displayed and not el.closest('css:.k-window-titlebar'):
el.click()
time.sleep(2)
if kc.ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=1):
config.log(f'{TAG} 报表过滤界面已打开')
return True
except Exception:
pass
return False
def _open_filter(page):
"""确保过滤界面打开:
1. 先关闭「文件下载」窗口(K3 下载完成后残留、挡在最上层)
2. 若过滤窗口已开(.k-window 内组织字段可见)→ 直接复用
3. 未开 → 点主报表「过滤」按钮重开
注意:过滤按钮真实 id 为 BILLMENU_TOOLBAR-tbnFilter(tbnFilter,非 tbFilter)。"""
kc.close_window_by_title(page, '文件下载', tag=TAG)
if kc.ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=2):
return True
# 点「过滤」重开(by_js 避免 K3 菜单物理点击选中文字)
if kc.click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbnFilter"]', by_js=True):
time.sleep(1.5)
return kc.ele_visible(page, 'css:.k-window [id*="FSTOCKORGID"]', timeout=5)
return False
def _set_org(page, org):
"""确保过滤界面组织为指定值;不是则打开多选列表重新选择(只保留目标组织)。
探针确认的结构:li.k-item > input.k-checkboxItem[name=组织名] + button.k-checkbox-button。"""
# 统一限定在 .k-window 内,避免读到主界面残留的同 id 节点
disp = page.ele('css:.k-window [id*="FSTOCKORGID"] .ui-poplistedit-displayname', timeout=config.TIMEOUT)
if disp:
title = disp.attr('title') or ''
if title.strip() == org:
config.log(f'{TAG} 组织已是: {org}')
return True
if not kc.click_visible(page, 'css:.k-window [id*="FSTOCKORGID-EDITOR"] .kd-editor-btn'):
config.log(f'{TAG} 找不到组织下拉按钮')
return False
time.sleep(1)
# 组织多选列表弹层(_dataListdiv)独立挂载,不限定窗口;
# 页面可能残留上次中断留下的隐藏弹层,必须取当前可见的那一个
dl = None
for cand in page.eles('css:[id*="FSTOCKORGID-EDITOR_dataListdiv"]', timeout=config.TIMEOUT):
try:
if cand.states.is_displayed:
dl = cand
break
except Exception:
pass
if dl is None:
config.log(f'{TAG} 组织多选列表未出现')
return False
# 输入关键字过滤列表(需回车才会过滤出结果)
sbox = dl.ele('css:.kd-list-search-container input', timeout=5)
if sbox:
sbox.clear()
sbox.input(org.split(' ', 1)[-1])
kc.press_enter_in(sbox, page)
time.sleep(1)
def _visible_lis():
"""仅返回当前可见的选项行(过滤后隐藏行无位置尺寸,不可操作)。"""
out = []
for li in dl.eles('css:li.k-item'):
try:
if li.states.is_displayed:
out.append(li)
except Exception:
pass
return out
def _toggle(li, want):
"""want=True 勾选 / False 取消勾选;实际发生点击返回 True。"""
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
btn = li.ele('css:button.k-checkbox-button', timeout=0.5)
if not chk or not btn:
return False
name = chk.attr('name') or ''
try:
checked = bool(chk.run_js('return this.checked;'))
except Exception:
return False
if want == checked:
return False
try:
btn.click()
time.sleep(0.3)
return True
except Exception:
return False
# 勾选目标项
target_found = False
for li in _visible_lis():
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
if chk and org in (chk.attr('name') or ''):
target_found = True
_toggle(li, True)
# 清空搜索恢复全量列表,取消其它已勾选项
if sbox:
sbox.clear()
kc.press_enter_in(sbox, page)
time.sleep(1)
for li in _visible_lis():
chk = li.ele('css:input.k-checkboxItem', timeout=0.5)
if chk and org not in (chk.attr('name') or ''):
_toggle(li, False)
if not target_found:
config.log(f'{TAG} 组织中未找到: {org}')
return False
# 点弹层底部「确定」:只点一次。先弹层内找,找不到再全局找可见的兜底
ok = kc.click_visible(dl, 'css:.kd-multiSelectOK')
if not ok:
ok = kc.click_visible(page, 'css:.kd-multiSelectOK')
if not ok:
config.log(f'{TAG} 找不到组织多选确定按钮')
return False
time.sleep(1)
# 回读确认设置生效,防止点了确定但值没落上(限定 .k-window 内)
disp = page.ele('css:.k-window [id*="FSTOCKORGID"] .ui-poplistedit-displayname', timeout=config.TIMEOUT)
if disp and (disp.attr('title') or '').strip() == org:
config.log(f'{TAG} 组织已设置为: {org}')
return True
config.log(f'{TAG} 组织设置未生效,回读不一致: {org}')
return False
def _set_datepicker(page, key, date):
"""在 .k-window 过滤窗口内定位日期字段的 Kendo datepicker 并设值。
key: 'FBEGINDATE' / 'FENDDATE'。
K3 必须「触发日历组件」才会刷新绑定的过滤值(直接调控件 value() 无效):
方式一 真实输入日期文本 + 回车提交(Kendo 解析输入并触发 change)
方式二 打开日历面板 → 导航到目标月份 → 点选目标日期(触发 Kendo select)
每次设值后回读 input 显示值验证;失败返回 False 由外层重试,绝不假成功。"""
end = time.time() + config.TIMEOUT
last = ''
while time.time() < end:
for el in page.eles(f'css:.k-window [id*="{key}-EDITOR_c"]', timeout=2):
# 只处理真正持有 kendoDatePicker 控件的节点
try:
if not el.run_js(
"return !!(window.jQuery && window.jQuery(this).data('kendoDatePicker'));"):
continue
except Exception:
continue
# ---- 方式一:真实输入 + 回车 ----
try:
el.click()
time.sleep(0.15)
el.clear()
el.input(date)
time.sleep(0.2)
kc.press_enter_in(el, page)
time.sleep(0.3)
val = el.run_js("return this.value || '';")
if date in str(val):
config.log(f'{TAG} {key} 输入+回车生效(input显示 {val})')
return True
last = f'输入+回车 input={val!r}'
except Exception as e:
last = f'输入+回车异常: {e}'
# ---- 方式二:打开日历点选目标日期(触发组件刷新)----
try:
r = el.run_js("""
var k = window.jQuery && window.jQuery(this).data('kendoDatePicker');
if (!k) { return JSON.stringify({ok:false, why:'nok'}); }
var y = +arguments[0], m = +arguments[1], d = +arguments[2];
var dt = new Date(y, m - 1, d);
k.open();
if (k.calendar) { k.calendar.navigate(dt); }
var cal = (k.calendar && k.calendar.element())
|| window.jQuery('.k-calendar:visible').last();
var hit = null;
cal.find('td').each(function () {
var $td = window.jQuery(this);
if ($td.hasClass('k-other-month') || $td.hasClass('k-state-other-month')) return;
var $a = $td.find('a.k-link');
var txt = $a.length ? $a.text() : $td.text();
if (parseInt(txt, 10) === d) hit = $a.length ? $a : $td;
});
if (hit) { hit.click(); }
var v = k.value(), s = '';
if (v) {
var mo = v.getMonth() + 1, da = v.getDate();
s = v.getFullYear() + '-' + (mo < 10 ? '0' + mo : mo)
+ '-' + (da < 10 ? '0' + da : da);
}
return JSON.stringify({ok: !!hit, set: s, input: this.value || ''});
""", *date.split('-'))
try:
r = json.loads(r) if isinstance(r, str) else r
except Exception:
r = {'ok': False}
if r.get('ok') and date in (r.get('set') or ''):
config.log(f'{TAG} {key} 日历点选生效(input显示 {r.get("input")})')
return True
last = f'日历点选 {r}'
except Exception as e:
last = f'日历点选异常: {e}'
time.sleep(0.5)
config.log(f'{TAG} {key} 日期设置失败,最后回读: {last}')
return False
def _set_date(page, begin, end):
"""设置起始/结束日期(Kendo datepicker),限定在 .k-window 过滤窗口内。"""
if not _set_datepicker(page, 'FBEGINDATE', begin):
config.log(f'{TAG} 起始日期设置失败')
return False
if not _set_datepicker(page, 'FENDDATE', end):
config.log(f'{TAG} 结束日期设置失败')
return False
config.log(f'{TAG} 日期: {begin} ~ {end}')
return True
def _click_add_row(page):
"""点击仓库过滤面板「新增行」。
全局 li.k-link.kdFilterAdd 会同时匹配「主报表过滤」+「仓库过滤」两个面板,
原实现总点到主过滤那个(其行数不增加导致误判失败)。因此必须限定在仓库过滤
容器(id 含 FBeginStockId_Filter)内定位。物理点击只会选中文字,改用 JS click 触发。"""
for css in (
'xpath://li[contains(@class,"kdFilterAdd") and ancestor::div[contains(@id,"FBeginStockId_Filter")]]',
'css:[id*="FBeginStockId_Filter-FBATCHFILTERGRID_ENTRYBAR-tbAddRow"]',
):
# 直接取单个元素命中即点,避免 eles 遍历整页拖慢
el = page.ele(css, timeout=2)
if el is not None:
try:
if el.states.is_displayed:
el.click(by_js=True)
return True
except Exception:
pass
return False
def _row_tr(v):
"""上溯到包含该值输入框的条件行 <tr>(一个过滤条件一行,内含逻辑/字段/比较/值)。"""
node = v
for _ in range(8):
try:
node = node.parent()
except Exception:
break
if node is not None and node.tag == 'tr':
return node
return None
def _ensure_logic_or(page, v):
"""把指定值输入框所在行的逻辑下拉制为「或者」(OR)。
多个仓库编码之间需为或关系;行内逻辑下拉类名含 _PART_Logic_listbox,选项 并且/或者。"""
tr = _row_tr(v)
if tr is None:
return False
lg = tr.ele('css:span[role="listbox"][aria-owns*="_PART_Logic_listbox"]', timeout=2)
if lg is None:
return False
try:
cur = lg.ele('css:.k-input', timeout=1)
if cur and cur.text.strip() == '或者':
return True
except Exception:
pass
try:
lg.ele('css:.k-select', timeout=2).click()
time.sleep(0.3)
lb = page.ele('#' + lg.attr('aria-owns'), timeout=2)
if lb is None:
return False
for it in lb.eles('css:li', timeout=2):
try:
if it.text.strip() == '或者':
it.click()
time.sleep(0.2)
return True
except Exception:
continue
except Exception as e:
config.log(f'{TAG} 设置逻辑为或者失败: {e}')
return False
return False
def _diag_stock_btn(page):
"""仓库搜索按钮找不到时输出诊断信息,定位是过滤窗口没开还是按钮不可见。"""
try:
wins = [t.text for t in page.eles('css:.k-window-title') if t.states.is_displayed]
config.log(f' [诊断] 当前可见窗口标题: {wins}')
c = page.ele('css:[id*="FBEGINSTOCKID-EDITOR"]', timeout=1)
config.log(f' [诊断] FBEGINSTOCKID-EDITOR 容器存在={bool(c)}'
f' 可见={c.states.is_displayed if c else "-"}')
btns = page.eles('css:[id*="FBEGINSTOCKID"] .kd-editor-btn')
vis = 0
for b in btns:
try:
if b.states.is_displayed:
vis += 1
except Exception:
pass
config.log(f' [诊断] FBEGINSTOCKID 内 .kd-editor-btn 总数={len(btns)} 可见={vis}')
org_css = 'css:.k-window [id*="FSTOCKORGID"]'
config.log(f' [诊断] 过滤窗口内(.k-window) FSTOCKORGID 可见节点: '
f'{kc.ele_visible(page, org_css, timeout=1)}')
except Exception as e:
config.log(f' [诊断] 异常: {e}')
def _submit_query(page, with_date=None):
"""点主过滤界面「确定」触发查询。with_date 传 (begin, end) 时先重设日期防覆盖。
注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库过滤面板的 FBeginStockId_Filter-FBTNOK_c,
用 :not 排除 + .k-window 限定,防止误点(含主界面残留节点)。
查询是否真被受理交给 _wait_progress(「查询进度」窗口是最可靠信号)。"""
if with_date:
if not _set_date(page, *with_date):
config.log(f'{TAG} 提交前日期重设失败')
return False
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 _set_stock_codes(page, codes, begin, end):
"""仓库编码:点搜索 → 点过滤 → 逐行新增输入(或关系)→ 确定 → 退出 → 主界面确定触发查询。
每行结构:括号 + 逻辑(或) + 字段(基本信息-编码) + 比较(等于) + 值(输入后回车查询)。
新增行后填仓库编码(一行一个),并把每行逻辑设为「或者」(OR) 保证多仓库为或关系。
提交查询(点主过滤确定)前重设一次日期:仓库面板操作过程可能把过滤条件重置为默认。"""
if not codes:
return False
# 1. 点仓库编码搜索按钮,打开仓库列表窗口(限定 .k-window 过滤窗口内)
if not kc.click_visible(page, 'css:.k-window [id*="FBEGINSTOCKID-EDITOR"] .kd-editor-btn'):
config.log(f'{TAG} 找不到仓库编码搜索按钮')
_diag_stock_btn(page)
return False
time.sleep(1.5)
# 2. 点「过滤」打开过滤面板
if not kc.click_visible(page, 'css:[id*="FBeginStockId-BILLMENU_TOOLBAR-tbFilter"]'):
config.log(f'{TAG} 找不到过滤按钮')
return False
time.sleep(1)
# 3. 逐行新增输入仓库编码,并将每行逻辑设为「或者」
val_css = 'css:[id*="FBeginStockId_Filter-FFILTERGRID"] input[placeholder*="请输入关键字"]'
for i, code in enumerate(codes):
# 快捷过滤网格初始为空(无默认行),每行都得先「新增行」再填值
vs = page.eles(val_css)
if len(vs) <= i:
added = False
for _ in range(3):
if _click_add_row(page):
time.sleep(0.8)
if len(page.eles(val_css)) > i:
added = True
break
if not added:
config.log(f'{TAG} 点击新增行失败(第{i + 1}行,当前值输入框{len(vs)}个)')
return False
vs = page.eles(val_css)
config.log(f'{TAG} 当前过滤值输入框数: {len(vs)}')
v = vs[i] if len(vs) > i else None
if not v:
config.log(f'{TAG} 找不到第{i + 1}行过滤值输入框')
return False
v.clear()
v.input(code)
kc.press_enter_in(v, page) # 回车直接发给输入框,触发查询确认
time.sleep(0.8)
_ensure_logic_or(page, v) # 保证该行逻辑为「或者」
config.log(f'{TAG} 仓库条件行{i + 1}: {code}(逻辑或)')
# 4. 过滤面板内「确定」
if not kc.click_visible(page, 'css:[id*="FBeginStockId_Filter-FBTNOK_c"]'):
config.log(f'{TAG} 找不到过滤面板确定按钮')
return False
time.sleep(0.8)
# 5. 「退出」关闭仓库过滤窗口
kc.click_visible(page, 'css:[id*="FBeginStockId-BILLMENU_TOOLBAR-tbClose"]', timeout=8)
time.sleep(0.8)
# 6. 提交查询(提交前重设日期防仓库面板操作覆盖)
return _submit_query(page, (begin, end))
def _wait_progress(page, timeout=300):
"""等待「查询进度」窗口出现并消失(遍历所有窗口标题)。
- 进度窗口出现但超时不消失 → 返回 False(查询失败/卡死,防止把旧报表当本次结果)
- 全程未出现进度窗口 → 报表网格已渲染且连续 3 秒稳定视为快速完成(兜底)
- 进度窗口消失后需连续 3 秒无进度窗口才算结束(防分阶段查询误判)"""
end = time.time() + timeout
appeared = False
stable = 0
while time.time() < end:
in_progress = any('查询进度' in x for x in kc.visible_titles(page))
if in_progress:
if not appeared:
appeared = True
config.log(f'{TAG} 查询进度中,等待完成...')
stable = 0
elif appeared:
stable += 1
if stable >= 3:
config.log(f'{TAG} 查询完成')
time.sleep(2) # 缓冲:数据渲染
return True
else:
# 进度窗口未出现:网格已渲染且稳定视为快速完成(兜底)
if kc.ele_visible(page, 'css:.k-grid', timeout=1):
stable += 1
if stable >= 3:
config.log(f'{TAG} 查询完成(进度窗口未出现)')
return True
else:
stable = 0
time.sleep(1)
config.log(f'{TAG} 查询进度超时未结束'
if appeared else f'{TAG} 未检测到查询进度且报表未渲染')
return False
def _export_all_pages(page):
"""选项 → 引出(真实鼠标悬浮展开子菜单)→ 引出所有页。
现场结论:物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了
K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字),
让子菜单展开后用 move_to+click 点中「引出所有页」;不点 span 文本,避免全选。
注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。"""
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-tbParamList"]', timeout=5)
if opt is None or not opt.states.is_displayed:
opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbParamList"]', 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-tbSplitExport"]', timeout=5)
if split is None or not split.states.is_displayed:
split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbSplitExport"]', 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-tbButtonExportAllPage"]', 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-tbButtonExportAllPage"]', 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 _run_once(page, begin, end, codes, save_dir, new_name, first, org):
if not _open_filter(page):
return False
if first:
# 首档:完整设置 组织 → 仓库(内部提交前重设日期并触发查询)
if not _set_org(page, org):
return False
if not _set_stock_codes(page, codes, begin, end):
return False
else:
# 后续档:组织/仓库等条件 K3 已保留,只需改日期后提交查询
if not _set_date(page, begin, end):
return False
if not _submit_query(page):
return False
if not _wait_progress(page):
return False
if not _export_all_pages(page):
return False
return kc.download_file(page, save_dir, new_name, tag=TAG)
# ================== 入口 ==================
def run(page, save_dir, org, codes, date_options, progress=None):
"""先全局搜索打开报表,再逐日期选项导出(组织/仓库仅首档完整设置,后续档只改日期)。
progress(done, total) 为整体进度回调;返回 (saved_files, failed_labels)。"""
if not _open_report(page):
raise RuntimeError("打开「物料收发汇总表」失败:全局搜索未打开报表过滤界面(详见日志)")
saved, failed = [], []
total = max(1, len(date_options))
for i, option in enumerate(date_options):
begin, end, label = resolve_dates(option)
new_name = f'{config.FILE_PREFIX_31}_{label}.xlsx'
success = False
for attempt in range(1, config.RETRY_MAX + 1):
config.log(f'{TAG} [{label}] 第 {attempt}/{config.RETRY_MAX} 次: {begin} ~ {end}')
if _run_once(page, begin, end, codes, save_dir, new_name,
first=(i == 0), org=org):
success = True
break
kc.reset_filter_state(page, tag=TAG, wait_query=True) # 清掉失败留下的弹层/半填条件再重试
time.sleep(2)
if success:
saved.append(str(save_dir / new_name))
else:
config.log(f'{TAG} [{label}] 重试 {config.RETRY_MAX} 次均失败,继续下一个日期选项')
failed.append(label)
if progress:
try:
progress(i + 1, total)
except Exception:
pass
time.sleep(1)
return saved, failed
+86
View File
@@ -0,0 +1,86 @@
{
"schema_version": 1,
"id": "xq0031_xq0032",
"name": "ERP物料收发汇总-采购订单报表导出",
"version": "1.0.3",
"description": "金蝶K3Cloud报表自动导出:物料收发汇总表(需求31)+ 采购订单列表(需求32),支持新旧系统、仓库编码多选、日期多选(含自定义区间),个性化配置保存在本机",
"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 重庆金七象供应链管理有限公司"
},
"stock_codes": {
"type": "array",
"title": "仓库编码(可多选,或关系)",
"items": {
"type": "string",
"enum": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"]
},
"default": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"],
"description": "每个编码一行过滤条件(或关系);可输入新编码后回车添加"
},
"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": []
}
}
+406
View File
@@ -0,0 +1,406 @@
# -*- 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 _open_report(page):
"""点击全局搜索 → 输入「采购订单列表」→ 等联想下拉出现 → 点选编号 CGDDLB 项。
注意:不能按回车——K3 全局搜索回车会默认直接进入第一个结果,下拉随即关闭,
无法精确选中 CGDDLB 项。输入后等待联想下拉,再点对应项。"""
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):
config.log(f'{TAG} 已打开列表({REPORT_NUMBER})')
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=300):
"""等待查询完成:进入页面时分页栏已带旧条数,查询时会先变 0(或消失)再变新条数。
故记录初始条数,等行数经历「变 0/消失」或「发生变化」后,再出现非 0 条数才算完成。"""
_, init_cnt = _read_rowcount(page)
config.log(f'{TAG} 当前条数: {init_cnt if init_cnt >= 0 else "无"},等待查询刷新...')
saw_reset = init_cnt < 0 # 初始无条数视为已重置
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 False
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, progress=None):
"""先全局搜索打开列表,再按方案导出(快捷方案 → 等查询 → 引出 → 下载,重试 3 次)。
progress(done, total) 为整体进度回调;返回保存文件路径,失败返回 None。"""
if not _open_report(page):
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 _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
+12
View File
@@ -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>ERP报表导出</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
+22
View File
@@ -0,0 +1,22 @@
{
"name": "xq0031-xq0032-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
}
}
+331
View File
@@ -0,0 +1,331 @@
<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="120px" label-position="right">
<div class="grid">
<el-form-item label="执行模式">
<el-select v-model="form.mode" :disabled="running">
<el-option label="两个都导(同一登录会话连导)" value="两个都导" />
<el-option label="物料收发汇总表(需求31)" value="物料收发汇总表" />
<el-option label="采购订单列表(需求32)" value="采购订单列表" />
</el-select>
</el-form-item>
<el-form-item label="ERP系统">
<el-radio-group v-model="form.erp_system" :disabled="running">
<el-radio-button value="新版">新版</el-radio-button>
<el-radio-button value="旧版">旧版</el-radio-button>
</el-radio-group>
</el-form-item>
</div>
<div class="grid">
<el-form-item label="登录账号">
<el-input v-model="form.erp_username" placeholder="你的ERP登录账号" :disabled="running" clearable />
</el-form-item>
<el-form-item label="登录密码">
<el-input v-model="form.erp_password" type="password" show-password
placeholder="仅保存在本机,下次免填" :disabled="running" />
</el-form-item>
</div>
<el-form-item label="查询组织">
<el-input v-model="form.org_name" :disabled="running" clearable
placeholder="确保过滤界面组织为该值,否则自动重新选择" />
</el-form-item>
<template v-if="form.mode !== '采购订单列表'">
<el-form-item label="仓库编码">
<el-select v-model="form.stock_codes" multiple filterable allow-create default-first-option
:reserve-keyword="false" placeholder="勾选预设或输入新编码后回车" :disabled="running" class="wide">
<el-option v-for="c in STOCK_PRESETS" :key="c" :value="c" :label="c" />
</el-select>
<div class="tip">多选为「或」关系,每个编码占一行过滤条件</div>
</el-form-item>
<el-form-item label="日期选项">
<el-select v-model="form.date_options" multiple filterable allow-create default-first-option
:reserve-keyword="false" placeholder="勾选预设,或输入自定义区间后回车" :disabled="running" class="wide">
<el-option v-for="d in DATE_PRESETS" :key="d" :value="d" :label="d" />
</el-select>
<div class="tip">N天 = 今天往前推N天,逐档导出;自定义区间格式:2026-01-01~2026-09-15(输入后回车)</div>
</el-form-item>
</template>
<el-form-item v-if="form.mode !== '物料收发汇总表'" label="快捷方案">
<el-input v-model="form.scheme_name" :disabled="running" clearable
placeholder="采购订单列表使用的过滤方案名(精确匹配)" />
</el-form-item>
<el-form-item label="保存目录">
<el-input v-model="form.save_dir" :disabled="running" clearable
placeholder="留空 = 桌面/采购计划报表_今天日期" />
</el-form-item>
<div class="actions">
<el-button type="primary" size="large" :loading="running" @click="run">
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
</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 } from './api'
const STOCK_PRESETS = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
const DATE_PRESETS = ['60D', '30D', '15D', '7D', '3D']
const DEFAULTS = () => ({
mode: '两个都导',
erp_system: '新版',
erp_username: '',
erp_password: '',
org_name: '99.01 重庆金七象供应链管理有限公司',
stock_codes: [...STOCK_PRESETS],
date_options: [...DATE_PRESETS],
scheme_name: '默认方案(个人)',
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)
let ws = null
let runId = ''
let pollTimer = null
let saveTimer = null
// ---------- 配置加载 / 保存 ----------
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]
if (k === 'stock_codes' && Array.isArray(saved[k])) form.stock_codes = saved[k]
if (k === 'date_options' && Array.isArray(saved[k])) form.date_options = 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.erp_username.trim() || !form.erp_password) {
ElMessage.warning('请先填写 ERP 登录账号和密码')
return false
}
if (form.mode !== '采购订单列表') {
if (!form.stock_codes.length) { ElMessage.warning('请至少选择一个仓库编码'); return false }
if (!form.date_options.length) { ElMessage.warning('请至少选择一个日期选项'); return false }
}
if (form.mode !== '物料收发汇总表' && !form.scheme_name.trim()) {
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 r = await startRun(JSON.parse(JSON.stringify(form)))
runId = r.run_id
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
startPolling()
} catch (e) {
running.value = false
stopPolling()
if (e.code === 401) needLogin.value = true
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
}
}
// ---------- 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示) ----------
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 {
max-width: 860px;
margin: 0 auto;
padding: 4px 0 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>
+46
View File
@@ -0,0 +1,46 @@
// 与壳子后端交互(同源,统一账户会话 cookie 自动携带)+ WebSocket 实时流
export const PLUGIN_ID = 'xq0031_xq0032'
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 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
}
+7
View File
@@ -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/xq0031_xq0032/ 下,
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
// dev 模式经代理访问本机壳子后端,便于联调。
export default defineConfig({
plugins: [vue()],
base: '/pui/xq0031_xq0032/',
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
+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-Agx7wG47.js"></script>
<link rel="stylesheet" crossorigin href="/pui/xq0031_xq0032/assets/index-B-JI0fiA.css">
</head>
<body>
<div id="app"></div>
</body>
</html>