Files
37duAutomation/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/material_summary.py
T
puddy 42d3ad48d0 feat(plugin): XQ0031_XQ0032 1.1.8 物料收发汇总列结构可自定义(界面可视化编辑)
- 新增配置项 material_columns(JSON,留空=内置标准),logic/material_summary.resolve_columns
  解析并校验,配置错误在取数前 fail-fast,不生成半截文件
- 导出列按 2026-11-16 平台样本对齐:新版 12 列、数量列 0 值留空、数字格式、
  按「物料编码→仓库编码」排序、末行只汇总期初/收入/发出/结存
- 插件界面新增「05 导出列」可视化编辑表(表头/字段/数值/格式 + 上移下移删除/重置)
- 同步 README 与开发文档;重建 ui 产物
2026-11-16 14:17:17 +08:00

1242 lines
54 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""需求31 - 金蝶 K3Cloud ERP「物料收发汇总表」自动导出(xq0031_xq0032 插件内模块)。
自 workflows/XQ0001-0100/XQ0031 material_summary_export.py 迁移:
搜索打开报表 → 设置组织/日期/仓库编码 → 查询 → 引出所有页 → 下载保存。
组织/仓库编码/日期选项由插件界面配置经 run() 参数注入;交互逻辑与影刀版保持同源。
"""
import json
import re
import time
from datetime import datetime, timedelta
from pathlib import Path
import openpyxl
from .. import config
from ..data 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):
"""点击全局搜索 → 输入「物料收发汇总表」→ 等联想下拉 → 点结果项(与需求32同法,不回车)→ 等待过滤界面出现。
不能用回车直接开第一个结果:回车会收起联想下拉且可能开成其它报表/列表页,
导致后续「点击搜索结果」兜底找不到项。改成在联想下拉里点选「物料收发汇总表」。"""
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.8) # 只出联想下拉,不回车
_click_search_result(page)
# 等待过滤界面(含组织字段 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 _click_search_result(page):
"""在联想下拉(.kd-fullsearch-selectable li)里点选文本为「物料收发汇总表」的结果项。"""
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
t = li.ele('css:span[searchitem="text"]', timeout=0.5)
txt = ((t.attr('title') or (t.text or '')).strip() if t is not None else '')
if '物料收发汇总表' not in txt:
continue
li.click()
time.sleep(2)
return True
except Exception:
pass
time.sleep(0.5)
config.log(f'{TAG} 联想下拉中未找到「物料收发汇总表」结果项')
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.kdFilterAdd 即为目标
(aa.md: <ul class="k-link kdGridFilterBar"><li class="k-link kdFilterAdd">新增行</li>...)。
物理点击只会选中文字,改用 JS click 触发。"""
for css in (
'css:.k-window li.kdFilterAdd',
'xpath://li[contains(@class,"kdFilterAdd") and ancestor::div[contains(@id,"_Filter")]]',
):
# 直接取单个元素命中即点,避免 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 _click_filter_tab(page, tab):
"""点击过滤窗口顶部页签(快捷/条件/选项...),tab 传页签文本(如 '条件'/'快捷')。
K3 页签结构(aa.md):ul.k-tabstrip-items > li[role="tab"] > span.k-link(页签名)。"""
target = None
for li in page.eles('css:.k-window ul.k-tabstrip-items li[role="tab"]', timeout=2):
try:
if not li.states.is_displayed:
continue
link = li.ele('css:.k-link', timeout=0.5)
if link is not None and (link.text or '').strip() == tab:
target = li
break
except Exception:
pass
if target is None:
return False
if 'k-state-active' in (target.attr('class') or ''):
config.log(f'{TAG} 过滤页签已是: {tab}')
return True
try:
target.click()
except Exception:
try:
target.click(by_js=True)
except Exception:
return False
time.sleep(0.6)
config.log(f'{TAG} 已切换过滤页签: {tab}')
return True
def _condition_rows(page):
"""过滤窗口「条件」页签当前可见的条件行 <tr>(含字段下拉 kd-defaultQuikerRow-partFileds 的行)。"""
rows = []
for css in (
'css:.k-window tr:has(.kd-defaultQuikerRow-partFileds)',
'xpath://div[contains(@class,"k-window")]//tr[.//*[contains(@class,"kd-defaultQuikerRow-partFileds")]]',
):
try:
for tr in page.eles(css, timeout=2):
try:
if tr.states.is_displayed:
rows.append(tr)
except Exception:
pass
if rows:
break
except Exception:
continue
return rows
def _select_row_field(page, tr, field):
"""把条件行字段下拉设为指定字段(如「仓库编码」),回读 title 验证。
行结构(aa.md):<td class="part_fileds_extend"><span class="k-combobox kd-defaultQuikerRow-partFileds">
<input role="combobox" title=当前字段>...<span class="k-icon k-i-close">清空</span>。
主路径统一用 JS 驱动 kendoComboBox 选中(每行行为完全一致,规避 UI 展开/输入过滤的
时序与焦点差异导致的逐字键入/点箭头等不一致):open 触发数据加载 → select 匹配文本
→ trigger change → 回读 title 验证;JS 不可用时才兜底走 UI 输入过滤点选。"""
box = tr.ele('css:input.kd-defaultQuikerRow-partFileds[role="combobox"]', timeout=2)
if box is None:
box = tr.ele('css:.kd-defaultQuikerRow-partFileds[role="combobox"]', timeout=2)
if box is None:
return False
try:
if (box.attr('title') or '').strip() == field:
return True
except Exception:
pass
def _done():
try:
return (box.attr('title') or '').strip() == field
except Exception:
return False
# 方式一(主):JS 统一驱动 kendoComboBox 选中目标字段(run_js 内 this 指向 tr)
try:
field_lit = json.dumps(field)
r = tr.run_js(f"""
var $ = window.jQuery;
var $inp = $(this).find('input[data-role="combobox"]').first();
var k = $inp.data('kendoComboBox');
if (!k) {{ return 'nok'; }}
try {{ k.open(); }} catch (e) {{}}
var pick = function (d) {{
if (!d) return false;
for (var key in d) {{
if (typeof d[key] === 'string' && $.trim(d[key]) === {field_lit}) return true;
}}
return false;
}};
var idx = k.select(pick);
try {{ k.trigger('change'); }} catch (e) {{}}
return idx === -1 ? 'miss' : 'ok';
""")
time.sleep(0.5)
if str(r) == 'ok':
return True
except Exception as e:
config.log(f'{TAG} 字段JS选择异常: {e}')
# 方式二(兜底):点输入框 → 清空 → 输入字段名过滤 → 从列表点选
try:
box.click()
time.sleep(0.5)
try:
box.clear()
time.sleep(0.3)
except Exception:
pass
box.input(field)
time.sleep(1.0)
owns = ''
try:
owns = box.attr('aria-owns') or ''
except Exception:
pass
if owns:
try:
lb = page.ele('#' + owns, timeout=2)
except Exception:
lb = None
if lb is not None:
for it in lb.eles('css:li', timeout=2):
try:
if it.states.is_displayed and it.text.strip() == field:
it.click()
time.sleep(0.5)
if _done():
return True
except Exception:
continue
# 过滤后可能仅一项:回车确认
kc.press_enter_in(box, page)
time.sleep(0.6)
if _done():
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,选项 并且/或者。
K3 现场结论:点右侧箭头展开不可靠(点不出列表);改为点输入框展开后点选,
再用 JS 驱动 kendoDropDownList 兜底,选中后回读验证,避免条件行保持「并且」查不出数据。"""
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
def _done():
"""回读当前逻辑文本,是「或者」返回 True。"""
try:
cur = lg.ele('css:.k-input', timeout=1)
return bool(cur and cur.text.strip() == '或者')
except Exception:
return False
if _done():
return True
# 方式一:点输入框(非箭头)展开列表,点选「或者」
try:
inp = lg.ele('css:.k-input', timeout=2)
if inp is not None:
inp.click()
time.sleep(0.6)
lb = page.ele('#' + lg.attr('aria-owns'), timeout=2)
if lb is not None:
for it in lb.eles('css:li', timeout=2):
try:
if it.text.strip() == '或者':
it.click()
time.sleep(0.4)
if _done():
return True
except Exception:
continue
except Exception:
pass
# 方式二(兜底):JS 直接驱动 kendoDropDownList 选中「或者」(run_js 内 this 指向 lg)
try:
r = lg.run_js("""
var $ = window.jQuery;
var $lg = $(this);
var $k = $lg.find('input[data-role="dropdownlist"]').first();
var k = $k.data('kendoDropDownList');
if (!k) { return false; }
var hit = false;
k.ul.find('li').each(function () {
if ($(this).text().trim() === '或者') { k.select($(this)); hit = true; }
});
return hit;
""")
time.sleep(0.4)
if r:
return _done()
except Exception as e:
config.log(f'{TAG} 设置逻辑为或者失败: {e}')
return False
def _clear_stock_range(page):
"""清空过滤窗口「快捷」页签的开始/结束仓库范围(FBEGINSTOCKID/FENDSTOCKID)默认值。
现场验证(旧系统):JS 对象级清空 widget(val/options.value/valData)在提交查询时无效,
K3 不从 widget 对象读仓库范围,查询仍被默认仓库(如代管仓 03010127)卡住、拿不到全部仓库;
必须模拟用户手动操作——点击输入框 -> Ctrl+A 全选 -> Delete 删除 -> Tab 触发 change,
才能真正清掉方案里的仓库范围,查询返回全部仓库(用户手动验证同法有效)。
仅当清空后回读内部值仍带 name/number 时返回 False(外层重试);无组件/异常只记日志不阻断。"""
ok = True
for key in ('FBEGINSTOCKID', 'FENDSTOCKID'):
el = page.ele(f'css:.k-window [id$="{key}-EDITOR"]', timeout=2)
if el is None:
continue
try:
inp = el.ele('css:input.k-input', timeout=1)
if inp is None:
inp = el.ele('css:input', timeout=1)
if inp is None:
config.log(f'{TAG} 仓库范围字段 {key} 无输入框,跳过')
continue
try:
inp.click()
except Exception:
inp.click(by_js=True)
time.sleep(0.4)
ac = page.actions
ac.key_down('ctrl').key_down('a').key_up('a').key_up('ctrl')
time.sleep(0.15)
ac.key_down('delete').key_up('delete')
time.sleep(0.2)
ac.key_down('tab').key_up('tab')
time.sleep(0.5)
r = el.run_js("""
var $ = window.jQuery, $el = $(this), inst = $el.data('kendoKDBosF7');
if (!inst) { return 'nok'; }
var v = inst.val() || {};
var name = v.name || '', number = v.number || '';
return (name === '' && number === '') ? 'ok' : 'still:' + name + '/' + number;
""")
if str(r) == 'ok':
config.log(f'{TAG} 已清空仓库范围字段 {key}')
elif str(r) == 'nok':
config.log(f'{TAG} 仓库范围字段 {key} 无 kendoKDBosF7 组件,跳过')
else:
ok = False
config.log(f'{TAG} 清空仓库范围字段 {key} 未生效: {r}')
except Exception as e:
ok = False
config.log(f'{TAG} 清空仓库范围字段 {key} 异常: {e}')
return ok
def _delete_stock_rows(page):
"""删除过滤窗口「条件」页签里字段为「仓库编码」的条件行(K3 个人方案残留的仓库列表行)。
行结构(aa.md):字段下拉 title=仓库编码 + 值 + 行尾 .DeleteButtonIconStyle 删除按钮。
删除后行号会变,重新扫描直到没有仓库编码行;非仓库编码行一律跳过不误删。"""
ok = True
for _ in range(5):
rows = _condition_rows(page)
if not rows:
break
hit = False
for tr in rows:
box = tr.ele('css:input.kd-defaultQuikerRow-partFileds[role="combobox"]', timeout=1)
if box is None:
box = tr.ele('css:.kd-defaultQuikerRow-partFileds[role="combobox"]', timeout=1)
if box is None:
continue
try:
title = (box.attr('title') or '').strip()
except Exception:
continue
if title != '仓库编码':
continue
delbtn = tr.ele('css:.DeleteButtonIconStyle', timeout=1)
if delbtn is None:
ok = False
continue
try:
delbtn.click()
except Exception:
try:
delbtn.click(by_js=True)
except Exception:
ok = False
continue
time.sleep(0.5)
hit = True
break
if not hit:
break
if ok:
config.log(f'{TAG} 已清空「条件」页签仓库编码条件行')
return ok
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 _clear_stock_range(page):
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):
"""【旧流程·备用】仓库编码:切到过滤窗口「条件」页签 → 逐行新增(字段=仓库编码,值=实际编码,逻辑=或者)
→ 回到「快捷」页签 → 提交查询(提交前重设日期防覆盖)。
新流程(aa.md:仓库编码切换位置,不再打开仓库列表/仓库过滤面板):
在过滤窗口「条件」页签直接新增条件行,每行结构(aa.md):括号 + 逻辑(或者) + 字段(仓库编码)
+ 比较(等于) + 值(输入后回车查询),逻辑设为「或者」(OR) 保证多仓库为或关系。
注意:现 run() 已改为「统一下载全部仓库 → 下载后按中文名筛选 Excel」,
本函数及其条件行辅助(_condition_rows/_click_add_row/_select_row_field 等)不再被调用,
仅保留供业务需要恢复按编码在 K3 内过滤时使用。"""
if not codes:
return False
# 1. 切到「条件」页签(新增行/字段下拉都在该页签下)
if not _click_filter_tab(page, '条件'):
config.log(f'{TAG} 找不到过滤窗口「条件」页签')
return False
time.sleep(1.0)
# 2. 逐行新增输入仓库编码,字段=仓库编码,逻辑=或者
for i, code in enumerate(codes):
rows = _condition_rows(page)
if len(rows) <= i:
added = False
for _ in range(3):
if _click_add_row(page):
time.sleep(1.2)
if len(_condition_rows(page)) > i:
added = True
break
if not added:
config.log(f'{TAG} 点击新增行失败(第{i + 1}行,当前条件行{len(rows)}个)')
return False
rows = _condition_rows(page)
tr = rows[i] if len(rows) > i else None
if tr is None:
config.log(f'{TAG} 找不到第{i + 1}行条件行')
return False
# 2.1 字段选「仓库编码」
if not _select_row_field(page, tr, '仓库编码'):
config.log(f'{TAG} 第{i + 1}行字段选择失败({code})')
return False
time.sleep(0.6)
# 2.2 值输入框填实际编码 + 回车触发查询确认
v = tr.ele('css:input[placeholder*="回车查询"]', timeout=2)
if v is None:
v = tr.ele('css:.kd-popListEdit-warp input.k-input', timeout=2)
if v is None:
config.log(f'{TAG} 第{i + 1}行找不到值输入框')
return False
v.clear()
time.sleep(0.3)
v.input(code)
time.sleep(0.3)
kc.press_enter_in(v, page) # 回车直接发给输入框,触发查询确认
time.sleep(1.2)
_ensure_logic_or(page, v) # 保证该行逻辑为「或者」
config.log(f'{TAG} 仓库条件行{i + 1}: {code}(字段=仓库编码,逻辑或)')
time.sleep(0.8)
# 3. 回到「快捷」页签,设置日期并提交查询(提交前重设日期防覆盖)
if not _click_filter_tab(page, '快捷'):
config.log(f'{TAG} 找不到过滤窗口「快捷」页签')
return False
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 _stock_names(codes):
"""编码列表 → 仓库中文名列表;无映射的编码记日志并跳过。"""
names, missing = [], []
for c in codes:
n = config.STOCK_NAME_MAP.get(str(c).strip())
if n:
names.append(n)
else:
missing.append(c)
if missing:
config.log(f'{TAG} 以下仓库编码无中文名映射,筛选时将不包含: {missing}')
return names
def _filter_excel_by_stock_names(file, names):
"""按仓库中文名列(表头第 4 行「仓库」)筛行:仅保留仓库名在 names 中的数据行,覆盖保存。
从末行向上删除不匹配行,保留表头与单元格格式;仓库列空白的行不删(防御,避免误删子行)。
返回保留的数据行数;表头未找到仓库列或文件异常时记日志返回 None。"""
from openpyxl import load_workbook
try:
wb = load_workbook(str(file))
except Exception as e:
config.log(f'{TAG} 筛选失败,无法打开 {Path(file).name}: {e}')
return None
ws = wb[wb.sheetnames[0]]
# 表头在第 4 行,定位仓库名称列(实测列名为「仓库名称」)
col = None
for c in range(1, ws.max_column + 1):
h = ws.cell(4, c).value
if h is not None and str(h).strip() in ('仓库', '仓库名称'):
col = c
break
if col is None:
config.log(f'{TAG} 筛选失败:第 4 行表头未找到仓库名称列')
wb.close()
return None
kept = 0
for r in range(ws.max_row, 4, -1): # 从末行向上,倒序删除不影响行号
v = ws.cell(r, col).value
if v is not None and str(v).strip() not in names:
ws.delete_rows(r)
else:
kept += 1
wb.save(str(file))
wb.close()
config.log(f'{TAG} 已按仓库中文名筛选 {Path(file).name},保留 {kept} 行({", ".join(names)})')
return kept
# ================== 单次导出 ==================
def _run_once(page, begin, end, save_dir, new_name, first, org, set_org=True):
if not _open_filter(page):
return False
if first:
# 首档:新旧系统均需显式设置查询组织(set_org=True,旧系统登录默认组织已不再默认);
# 其余完全一致:无需点「保存」固化方案,仓库范围由 _submit_query 提交前以键盘方式
# 清空,日期正常输入,编码不做 K3 过滤,下载后按所选编码的中文名筛选 Excel(见 run())。
if set_org and not _set_org(page, org):
return False
if not _submit_query(page, (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, set_org=True):
"""先全局搜索打开报表,再逐日期选项导出(组织/仓库仅首档完整设置,后续档只改日期)。
set_org=True 时首档显式设置查询组织;新旧系统一致(旧系统登录默认组织已不再默认)。
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, save_dir, new_name,
first=(i == 0), org=org, set_org=set_org):
success = True
break
kc.reset_filter_state(page, tag=TAG, wait_query=True) # 清掉失败留下的弹层/半填条件再重试
time.sleep(2)
if success:
fpath = save_dir / new_name
if codes:
# 下载的是全部仓库数据,按所选编码的中文名筛行后覆盖保存
_filter_excel_by_stock_names(fpath, _stock_names(codes))
saved.append(str(fpath))
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
# ================== 接口版(WebAPI 取数,无浏览器) ==================
# 列结构以平台「引出」实际产物为准(2026-11-16 新版导出样本,下一步下游报表按此比对):
# 新版 12 列:仓库名称 → 物料编码/物料名称/规格型号/库存单位 →
# (期初)/(收入)/(发出)/(结存)数量(库存)→ 库存周转次数/库存周转天数 → 货主
# 旧版沿用 11 列(仓库名称在第 1 列,库存周转次数 + 库存周转天数)
# 列定义:(表头文字, 接口字段, Excel 数字格式, 是否数值列);格式 None = 常规文本
_COLUMNS = {
'new': [
('仓库名称', 'FSTOCKNAME', None, False),
('物料编码', 'FMATERIALNUMBER', None, False),
('物料名称', 'FMATERIALNAME', None, False),
('规格型号', 'FMATERIALMODEL', None, False),
('库存单位', 'FSTOCKUNITNAME', None, False),
('(期初)数量(库存)', 'FSTOCKQCQTY', '#,##0.00', True),
('(收入)数量(库存)', 'FSTOCKINQTY', 'General', True),
('(发出)数量(库存)', 'FSTOCKOUTQTY', '#,##0.00', True),
('(结存)数量(库存)', 'FSTOCKJCQTY', '#,##0.00', True),
('(库存周转)库存周转次数', 'finvturnovernum', '#,##0.0', True),
('(库存周转)库存周转天数', 'finvturnoverdays', '#,##0.00', True),
('货主', 'FOWNERNAME', None, False),
],
'old': [
('仓库名称', 'FSTOCKNAME', None, False),
('物料编码', 'FMATERIALNUMBER', None, False),
('物料名称', 'FMATERIALNAME', None, False),
('规格型号', 'FMATERIALMODEL', None, False),
('库存单位', 'FSTOCKUNITNAME', None, False),
('期初', 'FSTOCKQCQTY', None, True),
('收入', 'FSTOCKINQTY', None, True),
('发出', 'FSTOCKOUTQTY', None, True),
('结存', 'FSTOCKJCQTY', None, True),
('库存周转次数', 'finvturnovernum', None, True),
('库存周转天数', 'finvturnoverdays', None, True),
],
}
# 合计行只汇总这 4 个数量列(平台样本中库存周转次数/天数的合计格为空)
_SUM_FIELDS = ('FSTOCKQCQTY', 'FSTOCKINQTY', 'FSTOCKOUTQTY', 'FSTOCKJCQTY')
def resolve_columns(erp, override=None):
"""解析插件配置里的列结构覆盖(界面传 JSON 字符串),返回列规格列表。
override 为空 → 用内置标准列(_COLUMNS,与平台 2026-11-16「引出」一致)。
支持三种写法(列顺序即输出顺序):
1) {"new": [...], "old": [...]} 按 ERP 系统分别配置(推荐;也兼容 {"新版":…,"旧版":…})
2) [...] 直接给当前 ERP 系统一份列表
3) {"columns": [...]} 简写
每列可写 {"title": 表头, "field": 接口字段, "numeric": true, "format": "#,##0.00"},
也可写简写数组 [表头, 字段, 格式, 是否数值]。数值列格式省略 → 常规显示。
配置里没有当前 ERP 系统的分支时(只配了另一套系统 / 键名不同),记日志并回退内置标准列。
返回 [(表头文字, 接口字段, 数字格式或 None, 是否数值列)];配置有误抛 ValueError(中文提示)。
"""
if not override:
return [tuple(s) for s in _COLUMNS[erp]]
data = override
if isinstance(data, str):
text = data.strip()
if not text:
return [tuple(s) for s in _COLUMNS[erp]]
try:
data = json.loads(text)
except Exception as e:
raise ValueError(f'不是合法 JSON:{e}')
if isinstance(data, dict):
alias = {'new': '新版', 'old': '旧版'}.get(erp, erp)
picked = data.get(erp) or data.get(alias) or data.get('columns')
if picked is None:
config.log(f'{TAG} 列结构配置里没有当前系统({erp}/{alias})的分支,本次使用内置标准列')
return [tuple(s) for s in _COLUMNS[erp]]
data = picked
if not isinstance(data, list) or not data:
raise ValueError('列结构必须是数组,且至少包含一列')
specs = []
for i, item in enumerate(data, start=1):
if isinstance(item, dict):
title = str(item.get('title') or '').strip()
fld = str(item.get('field') or '').strip()
numeric = bool(item.get('numeric'))
fmt = item.get('format', item.get('number_format'))
elif isinstance(item, (list, tuple)) and 2 <= len(item) <= 4:
title = str(item[0] or '').strip()
fld = str(item[1] or '').strip()
fmt = item[2] if len(item) > 2 else None
numeric = bool(item[3]) if len(item) > 3 else False
else:
raise ValueError(f'第 {i} 列写法不对:应为 {{"title","field","numeric","format"}} '
f'或 [表头, 字段, 格式, 是否数值]')
if not title or not fld:
raise ValueError(f'第 {i} 列缺少表头(title)或接口字段(field)')
specs.append((title, fld, str(fmt) if fmt else None, numeric))
return specs
def _org_caption(org_text):
"""查询组织 → 平台说明行样式:'99.01 重庆金七象…' → '99.01(重庆金七象…)'。"""
text = str(org_text or '').strip().replace('\u3000', ' ')
if not text:
return ''
code, _, name = text.partition(' ')
name = name.strip()
return f'{code}({name})' if name else code
def _scope_caption(codes):
"""所选仓库 → 平台说明行样式:'0101010101(重庆运营总仓)--0101010201(重庆美得三方仓)';
未选仓库(=全部)返回 '全部'。"""
items = sorted(str(c).strip() for c in (codes or []) if str(c).strip())
if not items:
return '全部'
def _one(code):
name = config.STOCK_NAME_MAP.get(code)
return f'{code}({name})' if name else code
return f'{_one(items[0])}--{_one(items[-1])}'
def _write_api_excel(erp, path, rows, begin, end, org, codes, label, specs=None):
"""把接口行写成与平台「引出」结构一致的单档 xlsx:
前 3 行说明 + 第 4 行表头 + 数据行 + 末行合计(merge_summary 依赖第 4 行表头与末行汇总)。
specs 为列规格(resolve_columns 的返回值;空则用内置标准列)。
与平台导出样本对齐的约定:按「物料编码 → 仓库编码」排序(同物料多仓时仓码升序);
数值列 0 值留空;数值列套用配置里的数字格式;合计行只汇总期初/收入/发出/结存
(新版合计行首列不带「合计」字样)。"""
import openpyxl
specs = [tuple(s) for s in (specs or _COLUMNS[erp])]
# 排序:物料编码 → 仓库编码(平台导出顺序;仓库编码做同物料多仓的次序,避免跨仓乱序)
rows = sorted(rows, key=lambda x: (str(x.get('FMATERIALNUMBER') or '').strip(),
str(x.get('FSTOCKNUMBER') or '').strip()))
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Sheet1'
# 前 3 行说明行:与平台「引出」文件逐格一致(下游报表只依赖第 4 行表头与数据列顺序)
owner = str((rows[0].get('FOWNERNAME') if rows else '') or '').strip()
ws.cell(1, 1, '货主类型:业务组织')
ws.cell(1, 2, f'货主:{owner}')
ws.cell(1, 3, f'库存组织:{_org_caption(org)}')
ws.cell(2, 1, f'起始日期:{begin}')
ws.cell(2, 2, f'截止日期:{end}')
ws.cell(2, 3, '物料范围:全部')
ws.cell(3, 1, f'仓库范围:{_scope_caption(codes)}')
ws.cell(3, 2, '期初参考价来源:期初加权平均价')
ws.cell(3, 3, '收入发出参考价:平均成本')
for c, (title, _fld, _fmt, _num) in enumerate(specs, start=1):
ws.cell(4, c, title)
totals = {fld: 0.0 for _t, fld, _fmt, is_num in specs if is_num and fld in _SUM_FIELDS}
r = 5
for row in rows:
for c, (title, fld, fmt, is_num) in enumerate(specs, start=1):
v = row.get(fld)
cell = ws.cell(r, c)
if is_num:
try:
v = float(v or 0)
except (TypeError, ValueError):
raise ValueError(f'列「{title}」配置为数值列,但接口字段 {fld} 返回 {v!r}')
if fld in totals:
totals[fld] += v
if v == 0:
v = None # 平台导出把 0 写成空单元格
cell.value = v
if fmt:
cell.number_format = fmt
r += 1
# 末行合计(merge_summary 合并时会跳过最后一行):新版合计行首列留空
if erp != 'new':
ws.cell(r, 1, '合计')
for c, (title, fld, fmt, is_num) in enumerate(specs, start=1):
if fld not in totals:
continue
cell = ws.cell(r, c)
cell.value = totals[fld] if erp == 'new' else round(totals[fld], 4)
if fmt:
cell.number_format = fmt
wb.save(str(path))
wb.close()
config.log(f'{TAG} 已生成 {Path(path).name}:{len(rows)} 行({label})')
return len(rows)
def run_api(erp, username, password, save_dir, org, codes, date_options,
progress=None, session=None, columns=None):
"""接口版导出:WebAPI 登录一次,逐日期选项取数并落 xlsx(不打开浏览器)。
参数与 UI 版 run() 对齐;session 可传入已登录的 ErpClient(两种报表共用)。
columns 为插件界面配置的列结构覆盖(JSON 字符串/对象,空=内置标准列)。
返回 (saved_files, failed_labels);失败时抛异常,由调用方决定是否回退 UI 版。
"""
from ..data import k3_report_api
specs = resolve_columns(erp, columns) # 配置有误在取数前就抛错快失败
config.log(f'{TAG} 列结构:{len(specs)} 列({"自定义配置" if str(columns or "").strip() else "内置标准"})')
session = session or k3_report_api.login(erp, username, password)
saved, failed = [], []
total = max(1, len(date_options))
for i, option in enumerate(date_options):
begin, end, label = resolve_dates(option)
config.log(f'{TAG} [{label}] 接口取数 {begin} ~ {end}')
try:
rows, session = k3_report_api.fetch(
erp, username, password, begin, end, org, codes, session=session)
except Exception as e:
if '会话信息已丢失' in str(e) or not k3_report_api.session_alive(session, erp):
# 会话中途失效:重登一次再取
config.log(f'{TAG} 会话失效,重新登录后重取:{e}')
session = k3_report_api.login(erp, username, password)
rows, session = k3_report_api.fetch(
erp, username, password, begin, end, org, codes, session=session)
else:
raise
if not rows:
failed.append(label)
else:
fpath = Path(save_dir) / f'{config.FILE_PREFIX_31}_{label}.xlsx'
_write_api_excel(erp, fpath, rows, begin, end, org, codes, label, specs=specs)
saved.append(str(fpath))
if progress:
try:
progress(i + 1, total)
except Exception:
pass
return saved, failed