- 物料收发汇总表改走 StockReportQueryService.GetReportData 分页取数, 采购订单列表改走 ExecuteBillQuery;一次账密登录两张报表共用会话,不再起浏览器 - 新增 data/k3_report_api.py 适配层(组织内码、过滤方案、仓库条件),底层调 erpsdk - 导出格式与 K3 引出保持一致(说明行/表头行/合计行、新旧版列差异),前端产物重建 - 需求单开发文档同步
633 lines
28 KiB
Python
633 lines
28 KiB
Python
# -*- 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 ..data import k3_common as kc
|
||
|
||
TAG = '[采购订单列表]'
|
||
REPORT_KEYWORD = '采购订单列表' # 全局搜索关键字
|
||
REPORT_NUMBER = 'CGDDLB' # 搜索结果编号(列表项唯一标识)
|
||
|
||
|
||
# ================== 列表操作 ==================
|
||
def _diag_search(page):
|
||
"""探针:搜索失败时打印当前页面/下拉状态,定位是下拉没出来还是选择器不匹配。"""
|
||
try:
|
||
config.log(f'{TAG} [探针] 当前 URL: {(page.url or "")[:120]}')
|
||
except Exception as e:
|
||
config.log(f'{TAG} [探针] 读 URL 异常: {e}')
|
||
try:
|
||
items = page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||
timeout=2)
|
||
config.log(f'{TAG} [探针] 下拉结果项数量: {len(items)}')
|
||
for i, li in enumerate(items[:10]):
|
||
try:
|
||
num = li.ele('css:span[searchitem="number"]', timeout=0.3)
|
||
txt = li.ele('css:span[searchitem="text"]', timeout=0.3)
|
||
config.log(f'{TAG} [探针] 第{i + 1}项: '
|
||
f'number={num.text if num else "?"} '
|
||
f'text={txt.text if txt else "?"} '
|
||
f'displayed={li.states.is_displayed}')
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
config.log(f'{TAG} [探针] 枚举下拉异常: {e}')
|
||
filter_visible = kc.ele_visible(
|
||
page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=1)
|
||
config.log(f'{TAG} [探针] 过滤按钮可见: {filter_visible}')
|
||
|
||
|
||
def _back_home(page, erp='new'):
|
||
"""回 K3 主控台首页:优先点顶部常驻「主页」按钮(SPA 内部跳转,一次清掉全部标签页/浮动窗口)。
|
||
注意:禁止用 page.get(index.aspx) 整页回首页——K3 整页重新加载会重新走会话校验,
|
||
连导时需求31的 tab 还开着,实测会被判为重复登录直接跳登录页(全局搜索图标随之消失、
|
||
卡在「找不到全局搜索图标」)。主页按钮找不到时,退化为逐个关闭非激活标签页。"""
|
||
if _click_home_btn(page):
|
||
config.log(f'{TAG} 已点主页按钮回主控台')
|
||
time.sleep(2.5)
|
||
return
|
||
config.log(f'{TAG} 未找到主页按钮,改为逐个关闭非激活标签页')
|
||
for _ in range(5): # 关闭一个后 DOM 会刷新,多次扫描确保关干净
|
||
closed = 0
|
||
for li in page.eles('css:ul.k-tabstrip-items li', timeout=2):
|
||
try:
|
||
if not li.states.is_displayed:
|
||
continue
|
||
if (li.attr('aria-selected') or '').strip().lower() == 'true':
|
||
continue # 保留当前激活 tab
|
||
btn = li.ele('css:.k-i-close', timeout=0.5)
|
||
if btn is None:
|
||
btn = li.ele('css:.k-tabstrip-close', timeout=0.5)
|
||
if btn is None:
|
||
continue
|
||
try:
|
||
btn.click()
|
||
except Exception:
|
||
btn.click(by_js=True)
|
||
closed += 1
|
||
time.sleep(0.6)
|
||
except Exception:
|
||
pass
|
||
if closed == 0:
|
||
break
|
||
config.log(f'{TAG} 已关闭 {closed} 个残留标签页')
|
||
|
||
|
||
def _click_home_btn(page):
|
||
"""点击 K3 顶部常驻「主页」按钮(span.k-link.kd-item-home)回主控台首页。
|
||
K3 控件 by_js click 有时不触发,先物理点击,失败再 by_js 兜底。"""
|
||
if kc.click_visible(page, 'css:.k-link.kd-item-home', timeout=3):
|
||
return True
|
||
return kc.click_visible(page, 'css:.k-link.kd-item-home', timeout=3, by_js=True)
|
||
|
||
|
||
def _active_tab_title(page):
|
||
"""当前激活的主标签页标题。K3 多表单标签残留(物料收发汇总表/采购订单列表并存)时,
|
||
必须确认操作的是激活的那个,否则会读到隐藏标签页的旧条数。"""
|
||
try:
|
||
t = page.ele('css:li[aria-selected="true"] .k-link', timeout=2)
|
||
if t is not None:
|
||
return (t.text or '').strip()
|
||
except Exception:
|
||
pass
|
||
return ''
|
||
|
||
|
||
def _open_report(page, erp='new'):
|
||
"""点击全局搜索 → 输入「采购订单列表」→ 等联想下拉出现 → 点选编号 CGDDLB 项。
|
||
打开后必须校验主标签页已切到「采购订单列表」,否则可能停留在上一个报表标签、
|
||
读到错页面的行数;校验不过回主控台首页重新搜索进入(最多 2 轮)。"""
|
||
for _ in range(2):
|
||
if _do_search_open(page):
|
||
if REPORT_KEYWORD in _active_tab_title(page):
|
||
config.log(f'{TAG} 已打开列表({REPORT_NUMBER})')
|
||
return True
|
||
config.log(f'{TAG} 列表标签页未激活(可能残留其它表单标签),清理后重新搜索')
|
||
_back_home(page, erp)
|
||
time.sleep(1)
|
||
config.log(f'{TAG} 打开「采购订单列表」失败:未能确认列表标签页激活')
|
||
return False
|
||
|
||
|
||
def _do_search_open(page):
|
||
"""执行一次全局搜索并点选 CGDDLB 结果(不校验标签页是否真的激活,由 _open_report 负责)。"""
|
||
if not kc.click_visible(page, 'css:.kd-fullsearch-searchicon', timeout=10):
|
||
config.log(f'{TAG} 找不到全局搜索图标')
|
||
return False
|
||
time.sleep(1)
|
||
sbox = page.ele('css:.kd-appplat-searchinput', timeout=5)
|
||
if not sbox:
|
||
config.log(f'{TAG} 找不到搜索输入框')
|
||
return False
|
||
sbox.clear()
|
||
sbox.input(REPORT_KEYWORD)
|
||
time.sleep(0.8) # 输入即出联想下拉;不按回车(回车=直接进第一个结果)
|
||
|
||
# 结果下拉列表中找编号为 CGDDLB 的「采购订单列表」项
|
||
end = time.time() + 20
|
||
while time.time() < end:
|
||
for li in page.eles('css:.kd-fullsearch-selectable li.kd-fullsearch-item-container',
|
||
timeout=2):
|
||
try:
|
||
if not li.states.is_displayed:
|
||
continue
|
||
num = li.ele('css:span[searchitem="number"]', timeout=0.5)
|
||
if num is None:
|
||
continue
|
||
num_text = (num.attr('title') or num.text or '').strip().upper()
|
||
if num_text == REPORT_NUMBER.upper():
|
||
li.click()
|
||
time.sleep(2)
|
||
if kc.ele_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', timeout=2):
|
||
return True
|
||
except Exception:
|
||
pass
|
||
time.sleep(0.5)
|
||
config.log(f'{TAG} 未找到编号 {REPORT_NUMBER} 的搜索结果项')
|
||
_diag_search(page) # 探针:输出诊断信息
|
||
return False
|
||
|
||
|
||
def _open_filter(page):
|
||
"""确保过滤窗口打开:已开则复用,未开则点「过滤」按钮(by_js 触发菜单项)。"""
|
||
if kc.ele_visible(page, 'css:.k-window [id*="_Filter-FSCHEMELIST"]', timeout=2):
|
||
return True
|
||
if kc.click_visible(page, 'css:[id*="BILLMENU_TOOLBAR-tbFilter"]', by_js=True):
|
||
time.sleep(1.5)
|
||
return kc.ele_visible(page, 'css:[id*="_Filter-FSCHEMELIST"]', timeout=5)
|
||
return False
|
||
|
||
|
||
def _select_scheme(page, scheme):
|
||
"""在过滤窗口方案树中选中目标方案(默认「默认方案(个人)」)。
|
||
方案树节点结构:li.k-item > .k-in.kd-treenode-textcnt > .kd-treenode-text。
|
||
注意:K3 树节点用 by_js click 不触发选中事件(现场验证),必须真实鼠标点击
|
||
.k-in.kd-treenode-textcnt 节点;选中成功后界面出现 SelectedSchemeItemControlTemplate。"""
|
||
ac = page.actions
|
||
end = time.time() + config.TIMEOUT
|
||
while time.time() < end:
|
||
for li in page.eles('css:.k-window li.k-item', timeout=2):
|
||
try:
|
||
if not li.states.is_displayed:
|
||
continue
|
||
t = li.ele('css:.kd-treenode-text', timeout=0.5)
|
||
if t is None or scheme not in (t.text or ''):
|
||
continue
|
||
# 已选中:选中模板(SelectedSchemeItemControlTemplate)的文本须是目标方案,
|
||
# 否则可能是上次选的其它方案,误判会导出错误数据
|
||
cur = page.ele('css:.SelectedSchemeItemControlTemplate', timeout=1)
|
||
if cur is not None and scheme in (cur.text or ''):
|
||
config.log(f'{TAG} 方案已是: {t.text.strip()}')
|
||
return True
|
||
# 真实鼠标点击节点外层 .k-in.kd-treenode-textcnt(by_js 不触发选中)
|
||
node = t.parent() # .k-in.kd-treenode-textcnt
|
||
if node is None or not node.states.is_displayed:
|
||
node = t
|
||
try:
|
||
ac.move_to(node)
|
||
time.sleep(0.3)
|
||
ac.click()
|
||
except Exception:
|
||
try:
|
||
node.click(by_js=True)
|
||
except Exception:
|
||
pass
|
||
time.sleep(0.8)
|
||
# 确认选中:出现 SelectedSchemeItemControlTemplate 才算点击成功
|
||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate', timeout=2):
|
||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||
return True
|
||
# 未生效:可能点到文本被全选,改为点 li 下的 .kd-treenode-textcnt 外层再试一次
|
||
try:
|
||
cnt = li.ele('css:.kd-treenode-textcnt', timeout=1)
|
||
if cnt is not None and cnt.states.is_displayed:
|
||
ac.move_to(cnt)
|
||
time.sleep(0.3)
|
||
ac.click()
|
||
time.sleep(0.8)
|
||
if kc.ele_visible(page, 'css:.SelectedSchemeItemControlTemplate',
|
||
timeout=2):
|
||
config.log(f'{TAG} 已选择方案: {t.text.strip()}')
|
||
return True
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
time.sleep(0.5)
|
||
config.log(f'{TAG} 过滤窗口方案树中未找到: {scheme}')
|
||
return False
|
||
|
||
|
||
def _submit_filter(page):
|
||
"""点过滤窗口「确定」触发查询。注意:[id*="_Filter-FBTNOK_c"] 也会命中仓库等其它
|
||
过滤面板的同 id 按钮,用 :not + .k-window 限定,防止误点。"""
|
||
if not kc.click_visible(page, 'css:.k-window [id*="_Filter-FBTNOK_c"]:not([id*="FBeginStockId"])'):
|
||
config.log(f'{TAG} 找不到过滤窗口确定按钮')
|
||
return False
|
||
config.log(f'{TAG} 已提交过滤查询')
|
||
return True
|
||
|
||
|
||
def _read_rowcount(page):
|
||
"""读分页栏行数统计(span[data-kdid="rowcount_pagerlist2"],文本形如「共519行」)。
|
||
返回 (文本, 条数);未找到/未显示返回 (None, -1)。"""
|
||
try:
|
||
for el in page.eles('css:span[data-kdid="rowcount_pagerlist2"]', timeout=1):
|
||
try:
|
||
if not el.states.is_displayed:
|
||
continue
|
||
txt = (el.text or '').strip()
|
||
m = re.search(r'共\s*(\d+)\s*行', txt)
|
||
return txt, (int(m.group(1)) if m else -1)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
return None, -1
|
||
|
||
|
||
def _wait_progress(page, timeout=30):
|
||
"""等待查询完成:进入页面时分页栏已带旧条数,查询时会先变 0(或消失)再变新条数。
|
||
故记录初始条数,等行数经历「变 0/消失」或「发生变化」后,再出现非 0 条数才算完成。
|
||
- 条数可用(数字):行数变 0 / 变化即完成。
|
||
- 条数不可用:K3 未翻到最后一页时总行数显示「共*行」星号(读不到数字,现场确认),
|
||
查询中不会有数字信号,仅等一个短窗口(NO_COUNT_GAP)让 K3 算出行数;
|
||
窗口内星号→数字出现即视为查询完成,始终无数字 → 按查询已完成直接继续
|
||
(避免 30s 白等,由上层重试机制兜底)。
|
||
超时不再判定失败:现场结论查询可能太快、行数不经历 0 直接保持旧值,死等会白白卡
|
||
几分钟。故超时后直接继续导出(由上层重试机制兜底,避免整单卡死)。"""
|
||
txt0, init_cnt = _read_rowcount(page)
|
||
if init_cnt >= 0:
|
||
config.log(f'{TAG} 当前条数: {init_cnt},等待查询刷新...')
|
||
elif txt0:
|
||
config.log(f'{TAG} 当前条数: {txt0}(星号=总行数未计算),等待查询刷新...')
|
||
else:
|
||
config.log(f'{TAG} 当前条数: 无,等待查询刷新...')
|
||
if init_cnt < 0:
|
||
# 条数不可用:短窗口内等待 K3 算出数字;星号→数字出现即完成,否则直接继续
|
||
NO_COUNT_GAP = 10
|
||
end = time.time() + NO_COUNT_GAP
|
||
while time.time() < end:
|
||
txt, cnt = _read_rowcount(page)
|
||
if cnt > 0:
|
||
config.log(f'{TAG} 查询完成: {txt}')
|
||
return True
|
||
time.sleep(1)
|
||
config.log(f'{TAG} 条数不可用({txt0 or "无"}),按查询已完成直接继续导出')
|
||
return True
|
||
saw_reset = False
|
||
end = time.time() + timeout
|
||
while time.time() < end:
|
||
txt, cnt = _read_rowcount(page)
|
||
if cnt == 0:
|
||
saw_reset = True # 先变 0:查询已触发,正在刷新
|
||
elif cnt > 0:
|
||
if saw_reset or cnt != init_cnt:
|
||
config.log(f'{TAG} 查询完成: {txt}')
|
||
return True
|
||
time.sleep(1)
|
||
config.log(f'{TAG} 等待查询完成超时(行数未刷新,直接继续导出)')
|
||
return True
|
||
|
||
|
||
def _export_all_pages(page):
|
||
"""选项 → 引出(真实鼠标悬浮展开子菜单)→ 按列表引出数据。
|
||
现场结论:物理点击内容 span 只会『全选文字』不触发菜单;JS click 又触发不了
|
||
K3 的悬浮式嵌套子菜单。故全程用 page.actions 的真实鼠标 move_to(悬浮,不点击文字),
|
||
让子菜单展开后用 move_to+click 点中「按列表引出数据」;不点 span 文本,避免全选。
|
||
注意:必须复用同一个 ac=page.actions,保证光标位置连续(悬浮链不中断子菜单不收起)。
|
||
本列表页与需求31不同:选项=tbOptionLists,引出=tbInputOutput,目标=按列表引出数据(tbOutput)。"""
|
||
ac = page.actions
|
||
|
||
def _clickable(span):
|
||
"""内容 span 的父级可点击元素(a/li),避免点到文本被『全选文字』。"""
|
||
try:
|
||
a = span.closest('css:a')
|
||
if a is not None and a.tag.lower() == 'a' and a.states.is_displayed:
|
||
return a
|
||
except Exception:
|
||
pass
|
||
try:
|
||
li = span.closest('css:li')
|
||
if li is not None and li.states.is_displayed:
|
||
return li
|
||
except Exception:
|
||
pass
|
||
return span
|
||
|
||
# 1. 点「选项」打开配置菜单(点其 a/li,避开文本)
|
||
opt = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||
if opt is None or not opt.states.is_displayed:
|
||
opt = page.ele('css:[id*="BILLMENU_TOOLBAR-tbOptionLists"]', timeout=5)
|
||
if opt is None or not opt.states.is_displayed:
|
||
config.log(f'{TAG} 找不到选项按钮')
|
||
return False
|
||
try:
|
||
ac.move_to(_clickable(opt)).click()
|
||
except Exception:
|
||
try:
|
||
opt.click(by_js=True)
|
||
except Exception:
|
||
config.log(f'{TAG} 点选项失败')
|
||
return False
|
||
time.sleep(1.2)
|
||
|
||
# 2. 定位「引出」(splitbutton)
|
||
split = page.ele('css:span[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||
if split is None or not split.states.is_displayed:
|
||
split = page.ele('css:[id*="BILLMENU_TOOLBAR-tbInputOutput"]', timeout=5)
|
||
if split is None or not split.states.is_displayed:
|
||
config.log(f'{TAG} 找不到导出(引出)按钮')
|
||
return False
|
||
|
||
def _trigger():
|
||
"""悬浮目标:优先右箭头(悬浮开子菜单),无箭头则悬浮整体。"""
|
||
try:
|
||
ar = split.parent().ele('css:span.k-icon', timeout=1)
|
||
if ar is not None and ar.states.is_displayed:
|
||
return ar
|
||
except Exception:
|
||
pass
|
||
return _clickable(split)
|
||
|
||
trigger = _trigger()
|
||
|
||
# 3. 悬浮展开「按列表引出数据」子菜单
|
||
target = None
|
||
for _ in range(4):
|
||
try:
|
||
ac.move_to(trigger) # 真实鼠标悬浮到右箭头,子菜单展开
|
||
except Exception:
|
||
pass
|
||
time.sleep(1.0)
|
||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||
if t is not None and t.states.is_displayed:
|
||
target = t
|
||
break
|
||
if target is None or not target.states.is_displayed:
|
||
for _ in range(3):
|
||
try:
|
||
trigger.click()
|
||
except Exception:
|
||
pass
|
||
time.sleep(1)
|
||
t = page.ele('css:span[id$="BILLMENU_TOOLBAR-tbOutput"]', timeout=2)
|
||
if t is not None and t.states.is_displayed:
|
||
target = t
|
||
break
|
||
if target is None or not target.states.is_displayed:
|
||
config.log(f'{TAG} 找不到按列表引出数据')
|
||
return False
|
||
|
||
# 4. 光标从「引出」连续移入「按列表引出数据」再点击(悬浮链不断,菜单不收起)
|
||
try:
|
||
ac.move_to(_clickable(target))
|
||
time.sleep(0.5)
|
||
ac.click()
|
||
except Exception:
|
||
try:
|
||
target.click(by_js=True)
|
||
except Exception:
|
||
config.log(f'{TAG} 点击按列表引出数据失败')
|
||
return False
|
||
config.log(f'{TAG} 已触发按列表引出数据')
|
||
return True
|
||
|
||
|
||
def _click_quick_scheme(page, scheme):
|
||
"""直接点击列表页顶部快捷方案条中的目标方案,无需打开过滤窗口。
|
||
结构:div[filter-role="filterschemecontent"] > div.SchemeItemControlTemplate(含方案名,
|
||
选中的为 SelectedSchemeItemControlTemplate)。
|
||
注意:K3 控件用 by_js click 可能不触发,优先真实鼠标点击。"""
|
||
ac = page.actions
|
||
end = time.time() + config.TIMEOUT
|
||
while time.time() < end:
|
||
for item in page.eles(
|
||
'css:div[filter-role="filterschemecontent"] '
|
||
'div[class*="SchemeItemControlTemplate"]', timeout=2):
|
||
try:
|
||
if not item.states.is_displayed:
|
||
continue
|
||
txt = (item.text or '').strip()
|
||
if txt != scheme: # 精确匹配:避免「默认方案」误命中「采购订单宽表默认方案」
|
||
continue
|
||
cls = item.attr('class') or ''
|
||
if 'Selected' in cls:
|
||
config.log(f'{TAG} 快捷方案已是: {txt}')
|
||
return True
|
||
try:
|
||
ac.move_to(item)
|
||
time.sleep(0.3)
|
||
ac.click()
|
||
except Exception:
|
||
try:
|
||
item.click(by_js=True)
|
||
except Exception:
|
||
pass
|
||
time.sleep(1)
|
||
# 确认选中:快捷条中 Selected 方案变为目标方案
|
||
cur = page.ele(
|
||
'css:div[filter-role="filterschemecontent"] '
|
||
'div.SelectedSchemeItemControlTemplate', timeout=2)
|
||
if cur is not None and scheme in (cur.text or ''):
|
||
config.log(f'{TAG} 已点选快捷方案: {txt}')
|
||
return True
|
||
# 未确认选中:返回 False 走过滤窗口回退,防止把旧数据当本次结果
|
||
config.log(f'{TAG} 点击快捷方案未确认选中: {txt}')
|
||
return False
|
||
except Exception:
|
||
pass
|
||
time.sleep(0.5)
|
||
config.log(f'{TAG} 快捷方案条中未找到: {scheme}')
|
||
return False
|
||
|
||
|
||
def _run_once(page, scheme):
|
||
"""直接点快捷方案 → 等查询 → 按列表引出数据。
|
||
快捷方案条不存在时回退到过滤窗口选方案。"""
|
||
if _click_quick_scheme(page, scheme):
|
||
if not _wait_progress(page):
|
||
return False
|
||
else:
|
||
# 回退:过滤窗口选方案
|
||
if not _open_filter(page):
|
||
return False
|
||
if not _select_scheme(page, scheme):
|
||
return False
|
||
if not _submit_filter(page):
|
||
return False
|
||
if not _wait_progress(page):
|
||
return False
|
||
return _export_all_pages(page)
|
||
|
||
|
||
# ================== 入口 ==================
|
||
def run(page, save_dir, scheme, erp='new', progress=None):
|
||
"""先全局搜索打开列表(校验列表标签页已激活),再按方案导出(快捷方案 → 等查询 → 引出 → 下载,重试 3 次)。
|
||
每次导出前校验仍处于「采购订单列表」标签页,不对则清理残留标签页后重新搜索进入。
|
||
progress(done, total) 为整体进度回调;返回保存文件路径,失败返回 None。"""
|
||
# 连导场景(需求31物料收发汇总后接需求32)会残留「物料收发汇总表」标签页:
|
||
# 多标签下 page.eles 全页匹配可能命中残留标签页里的元素,干扰后续操作。
|
||
# 先关掉非激活标签页(SPA 内关 tab,不能整页回 index.aspx,否则跳登录页),
|
||
# 确保从干净状态开始本次导出。
|
||
_back_home(page, erp)
|
||
if not _open_report(page, erp):
|
||
raise RuntimeError("打开「采购订单列表」失败:全局搜索未命中 CGDDLB 列表(详见日志)")
|
||
new_name = f'{config.FILE_PREFIX_32}_{datetime.now():%Y-%m-%d}.xlsx'
|
||
config.log(f'{TAG} 导出文件: {new_name}')
|
||
for attempt in range(1, config.RETRY_MAX + 1):
|
||
config.log(f'{TAG} 第 {attempt}/{config.RETRY_MAX} 次导出')
|
||
# 做之前校验:当前激活标签必须是「采购订单列表」,否则回首页重新搜索进入
|
||
if REPORT_KEYWORD not in _active_tab_title(page):
|
||
config.log(f'{TAG} 当前标签页不是「采购订单列表」,清理残留标签页后重新搜索进入')
|
||
if not _open_report(page, erp):
|
||
break
|
||
if _run_once(page, scheme):
|
||
if kc.download_file(page, save_dir, new_name, tag=TAG):
|
||
if progress:
|
||
try:
|
||
progress(1, 1)
|
||
except Exception:
|
||
pass
|
||
return str(save_dir / new_name)
|
||
kc.reset_filter_state(page, tag=TAG) # 清掉失败留下的弹层/半填条件再重试
|
||
time.sleep(2)
|
||
config.log(f'{TAG} 重试 {config.RETRY_MAX} 次均失败')
|
||
if progress:
|
||
try:
|
||
progress(1, 1)
|
||
except Exception:
|
||
pass
|
||
return None
|
||
|
||
|
||
# ================== 接口版(WebAPI 取数,无浏览器) ==================
|
||
def _po_fmt_date(v):
|
||
"""接口日期 "2026-11-14T00:00:00" → 人工导出显示的 "2026/11/14"。"""
|
||
s = str(v or '').strip()
|
||
if not s:
|
||
return None
|
||
part = s.split('T')[0].split(' ')[0]
|
||
try:
|
||
y, m, d = part.split('-')
|
||
return f'{int(y)}/{int(m)}/{int(d)}'
|
||
except Exception:
|
||
return part
|
||
|
||
|
||
def _po_fmt_num(v):
|
||
""""空白/None 留空;整数值去掉 .0,保持与人工导出一致。"""
|
||
if v is None or (isinstance(v, str) and not v.strip()):
|
||
return None
|
||
try:
|
||
f = float(v)
|
||
except Exception:
|
||
return v
|
||
return int(f) if abs(f - int(f)) < 1e-9 else f
|
||
|
||
|
||
def _po_fmt_text(v):
|
||
if v is None:
|
||
return None
|
||
s = str(v).strip()
|
||
if not s:
|
||
return None
|
||
# K3「按列表引出数据」把 CRLF 渲染成空行(与人工导出逐字对齐)
|
||
return s.replace('\r\n', '\n\n').replace('\r', '\n')
|
||
|
||
|
||
def _po_fmt_status(v):
|
||
code = str(v or '').strip()
|
||
return config.PO_STATUS_MAP.get(code, code or None)
|
||
|
||
|
||
def _po_fmt(v, kind):
|
||
if kind == 'date':
|
||
return _po_fmt_date(v)
|
||
if kind == 'number':
|
||
return _po_fmt_num(v)
|
||
if kind == 'status':
|
||
return _po_fmt_status(v)
|
||
return _po_fmt_text(v)
|
||
|
||
|
||
def run_api(erp, username, password, save_dir, progress=None, session=None):
|
||
"""接口版:ExecuteBillQuery 取采购订单明细并落 xlsx(不打开浏览器)。
|
||
|
||
列与过滤条件由 config.PO_COLUMNS / PO_FILTER_STRING / PO_ORDER_STRING 决定。
|
||
返回保存文件路径;失败抛异常(会话失效会自动重登一次)。
|
||
"""
|
||
from erpsdk import ErpClient
|
||
import openpyxl
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
client = session or ErpClient(erp, logger=config.log, retry=config.RETRY_MAX)
|
||
if session is None:
|
||
client.login(username, password)
|
||
|
||
def _query():
|
||
return client.bill_query_all(
|
||
config.PO_FORM_ID, config.PO_FIELD_KEYS[erp],
|
||
filter_string=config.PO_FILTER_STRING[erp],
|
||
order_string=config.PO_ORDER_STRING,
|
||
page_size=config.PO_PAGE_SIZE,
|
||
max_rows=config.PO_MAX_ROWS)
|
||
|
||
try:
|
||
rows = _query()
|
||
except Exception as e:
|
||
if '会话' in str(e) or not client.session_alive():
|
||
config.log(f'{TAG} 会话失效,重新登录后重取:{e}')
|
||
client.login(username, password)
|
||
rows = _query()
|
||
else:
|
||
raise
|
||
|
||
if not rows:
|
||
config.log(f'{TAG} 接口返回 0 行(检查 PO_FILTER_STRING 或账号权限)')
|
||
return None
|
||
|
||
path = Path(save_dir) / f'{config.FILE_PREFIX_32}_{datetime.now():%Y-%m-%d}.xlsx'
|
||
# 22 列、行数可能上万:用 write_only 流式写,避免逐单元格写爆内存/耗时
|
||
cols = config.PO_COLUMNS[erp]
|
||
sum_idx = {i for i, (name, _k, _t) in enumerate(cols) if name in config.PO_SUM_COLUMNS}
|
||
totals = {i: 0.0 for i in sum_idx}
|
||
|
||
wb = openpyxl.Workbook(write_only=True)
|
||
ws = wb.create_sheet('Sheet1')
|
||
ws.append([name for name, _k, _t in cols])
|
||
for row in rows:
|
||
vals = [_po_fmt(row[i] if i < len(row) else None, t)
|
||
for i, (_name, _k, t) in enumerate(cols)]
|
||
for i in sum_idx:
|
||
try:
|
||
totals[i] += float(row[i] or 0)
|
||
except Exception:
|
||
pass
|
||
ws.append(vals)
|
||
total_row = [None] * len(cols)
|
||
total_row[0] = '合计'
|
||
for i, v in totals.items():
|
||
total_row[i] = round(v, 4)
|
||
ws.append(total_row)
|
||
wb.save(str(path))
|
||
config.log(f'{TAG} 已生成 {path.name}:{len(rows)} 行 + 合计({len(cols)} 列)')
|
||
wb.close()
|
||
config.log(f'{TAG} 已生成 {path.name}:{len(rows)} 行({len(config.PO_COLUMNS)} 列)')
|
||
if progress:
|
||
try:
|
||
progress(1, 1)
|
||
except Exception:
|
||
pass
|
||
return str(path)
|