# -*- coding: utf-8 -*- """需求31 - 金蝶 K3Cloud ERP「物料收发汇总表」自动导出(xq0031_xq0032 插件内模块)。 自 workflows/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 . 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: