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:
@@ -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
|
||||
Reference in New Issue
Block a user