# -*- coding: utf-8 -*- """xq0076 交行「商户验券」交易流水导出。 双通道: A. 接口(快,5 秒级):MSNGTQ/0002 查有无数据 → MSNGTO/0012 提交导出 → 0013 轮询 → downloadMchtFile 取 OSS 直链 → requests 下载。 B. UI 兜底(慢,约 1 分钟):接口任一步失败自动切换—— 汇总页「商户验券」查看详情(业务类型/日期自动带过去)→ 流水页点「导 出」→ 浏览器自己下载(页面自己完成加解密),再从磁盘取文件。 两条路都以「zip 内 csv 是否有数据行」作为最终判定,无数据不保留空文件。 """ import os import shutil import time import zipfile import requests import urllib3 from .. import config from . import (click_button, find_button, is_displayed, wait_page_ready) from . import bank_api # 银行 OSS 域名用老 TLS,verify=False 下载;抑制无害的 InsecureRequestWarning 噪音 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') # ==================== 接口通道 ==================== def has_data_probe(page, mcht_id, mcht_acc, date_from, date_to): """查 1 条明细判断有无数据。返回 (是否有数据, 说明)。""" data = bank_api.query_trades(page, mcht_id, mcht_acc, date_from, date_to, page_index=1, page_size=1) rows = data.get('responseData') or [] rd2 = data.get('responseData2') or {} total = '' if isinstance(rd2, dict): total = rd2.get('totalRow') or '' total = total or data.get('maxRow') or '' if rows: config.log(f'查询结果:有数据(总计 {total or "未知"} 条)') return True, f'总计 {total or "未知"} 条' config.log('查询结果:无数据,跳过导出') return False, '无数据' def _download(url, target_path, timeout=600): """下载 OSS 直链(无需 Cookie/Authorization)。""" headers = {'User-Agent': UA, 'Referer': 'https://merchantapp.bankcomm.com/'} tmp = target_path + '.part' try: with requests.get(url, headers=headers, timeout=timeout, verify=False, stream=True) as r: r.raise_for_status() with open(tmp, 'wb') as f: for chunk in r.iter_content(1024 * 256): if chunk: f.write(chunk) os.replace(tmp, target_path) return os.path.getsize(target_path) except Exception: try: if os.path.exists(tmp): os.remove(tmp) except Exception: pass raise # ==================== UI 兜底通道 ==================== _JS_MARK = r""" var t = arguments[0]; var p = document.querySelector('.ant-calendar-picker-container'); if (!p || !p.offsetWidth) return 'no-panel'; var tds = [].slice.call(p.querySelectorAll('td[title]')); for (var i = 0; i < tds.length; i++) { if ((tds[i].getAttribute('title') || '') === t) { var old = document.getElementById('__pick_day__'); if (old) old.id = ''; tds[i].id = '__pick_day__'; return 'ok'; } } return 'not-found'; """ _JS_STEP = r""" var dir = arguments[0]; var p = document.querySelector('.ant-calendar-picker-container'); if (!p) return false; var b = dir === 'next' ? p.querySelector('.ant-calendar-next-month-btn') : p.querySelector('.ant-calendar-prev-month-btn'); if (b) { b.click(); return true; } return false; """ def _pick_day(page, idx, day): """在日历面板上点选第 idx 个日期框(readonly 输入框只能面板点选)。""" boxes = [e for e in page.eles('css:input.ant-calendar-picker-input') if is_displayed(e)] if len(boxes) <= idx: return False try: boxes[idx].click() except Exception: return False time.sleep(1.0) title = f'{day.year}年{day.month}月{day.day}日' mark = page.run_js(_JS_MARK, title) steps = 0 while mark == 'not-found' and steps < 24: page.run_js(_JS_STEP, 'prev') time.sleep(0.35) steps += 1 mark = page.run_js(_JS_MARK, title) while mark == 'not-found' and steps < 48: page.run_js(_JS_STEP, 'next') time.sleep(0.35) steps += 1 mark = page.run_js(_JS_MARK, title) if mark != 'ok': config.log(f'日历面板找不到 {title}', 'WARN') return False el = page.ele('#__pick_day__', timeout=3) if not el: return False el.click() time.sleep(0.8) try: page.run_js("var e=document.getElementById('__pick_day__'); if(e) e.id='';") except Exception: pass return True def _csv_has_rows(zip_path): """检查 zip 内明细 csv 是否有数据行(>1 行 = 有数据)。""" try: with zipfile.ZipFile(zip_path) as zf: for name in zf.namelist(): if not name.lower().endswith('.csv'): continue raw = zf.read(name) try: text = raw.decode('gbk', 'replace') except Exception: text = raw.decode('utf-8', 'replace') lines = [ln for ln in text.splitlines() if ln.strip()] config.debug(f'{name}: {len(lines)} 行') if 'responseData' in name and len(lines) > 1: return True, name, len(lines) - 1 except Exception as e: config.log(f'检查 zip 内容失败:{e}', 'WARN') return False, '', 0 def _select_all_stores(page): """汇总页「门店名称」多选里勾「全选」(不选的话汇总卡片没数据,查看详情不跳转)。""" try: multi = page.ele('css:.ant-select-selection--multiple', timeout=10) except Exception: multi = None if not multi: config.log('未找到门店多选框,跳过全选', 'WARN') return False try: multi.click() time.sleep(1.2) hit = False for wrap in page.eles('css:.ant-select-dropdown .ant-checkbox-wrapper'): try: if '全选' in ''.join((wrap.text or '').split()): inp = wrap.ele('css:input.ant-checkbox-input') try: checked = bool(inp.states.is_checked) except Exception: checked = False if not checked: inp.click() time.sleep(1) config.log('已勾选「全选」门店') hit = True break except Exception: continue # 收起下拉:只用 JS 在页面标题区触发 mousedown(antd 靠 document mousedown 关闭)。 # ⚠️ 不能用坐标点「空白处」——左侧菜单就在那里,会误点「退款审批」等菜单跳转。 try: page.run_js(""" try { var el = document.querySelector('.org_bottom_title') || document.querySelector('.ant-breadcrumb') || document.body; el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); el.dispatchEvent(new MouseEvent('mouseup', { bubbles: true })); } catch (e) {} """) except Exception: pass time.sleep(1) return hit except Exception as e: config.log(f'门店全选失败:{e}', 'WARN') return False def export_via_ui(page, date_from, date_to, save_dir, tag='商户验券'): """UI 兜底:汇总页商户验券「查看详情」→ 流水页「导 出」→ 浏览器下载。""" config.log('改用页面 UI 导出(接口通道不可用)…') dl_dir = config.get_download_dir() os.makedirs(dl_dir, exist_ok=True) try: page.set.download_path(dl_dir) page.set.when_download_file_exists('rename') except Exception: pass # ① 交易汇总页 page.get(config.SITE_URL + '#/' + config.SUMMARY_HASH) time.sleep(config.PAGE_SETTLE + 2) if not wait_page_ready(page, '交易汇总', timeout=25): config.log('汇总页未就绪,重试', 'WARN') page.get(config.SITE_URL) time.sleep(2) page.get(config.SITE_URL + '#/' + config.SUMMARY_HASH) time.sleep(config.PAGE_SETTLE + 2) # ② 门店全选(不选则卡片无数据,查看详情不跳转) _select_all_stores(page) # ③ 自定义日期 + 面板选日期 if click_button(page, config.TXT_CUSTOM_DATE, timeout=8): time.sleep(1.5) _pick_day(page, 0, date_from) _pick_day(page, 1, date_to) # ④ 查询 click_button(page, config.TXT_QUERY_BTN, timeout=8) time.sleep(config.UI_QUERY_WAIT) # ④ 点「商户验券」卡片的查看详情(页面第 2 个) # 等汇总卡片渲染稳定(加载完通常是 9 个「查看详情」,未加载完只有 3 个) details = [] last = -1 stable = 0 deadline = time.time() + 30 while time.time() < deadline: details = [b for b in page.eles('css:button.onClickShowDetail') if is_displayed(b)] if len(details) == last and len(details) >= 2: stable += 1 if stable >= 2: break else: stable = 0 last = len(details) time.sleep(1.5) config.log(f'汇总页可见「查看详情」{len(details)} 个') if len(details) < 2: raise RuntimeError('汇总页未找到「商户验券」查看详情按钮(页面可能未加载完)') details[1].click() # 必须确认真的跳到交易流水页,否则会误点导出拿到「交易汇总.xlsx」 jumped = False deadline = time.time() + 30 while time.time() < deadline: if config.TRADE_HASH in (page.url or ''): jumped = True break time.sleep(1) if not jumped: raise RuntimeError(f'点「商户验券-查看详情」未跳转到交易流水页(当前 {page.url}),已中止避免导错文件') config.log(f'已进入交易流水页:{page.url}') time.sleep(config.PAGE_SETTLE + 1) # ⑤ 点导出,等浏览器下载 before = set(os.listdir(dl_dir)) btn = find_button(page, config.TXT_EXPORT_BTN, timeout=20) if not btn: raise RuntimeError('流水页找不到「导出」按钮') btn.click() config.log('已点击「导 出」,等待浏览器下载…') path = None deadline = time.time() + config.DOWNLOAD_TIMEOUT while time.time() < deadline: news = [n for n in os.listdir(dl_dir) if n not in before and not n.endswith('.crdownload')] if news: candidate = os.path.join(dl_dir, news[-1]) size = os.path.getsize(candidate) time.sleep(1.5) if os.path.getsize(candidate) == size and size > 0: path = candidate break time.sleep(1.5) if not path: raise RuntimeError(f'{config.DOWNLOAD_TIMEOUT}s 内未捕获到浏览器下载') config.log(f'下载完成:{os.path.basename(path)}({os.path.getsize(path)} 字节)') # ⑥ 检查有无数据 + 归档 has_rows, name, rows = _csv_has_rows(path) if not has_rows: config.log('导出文件无数据行,不保留文件', 'WARN') try: os.remove(path) except Exception: pass return {'skipped': True, 'reason': '导出文件无数据行', 'note': '无数据'} stamp = time.strftime('%Y%m%d_%H%M%S') safe_range = f'{date_from.strftime("%Y%m%d")}-{date_to.strftime("%Y%m%d")}' base = f'交通银行_{tag}_{safe_range}_{stamp}' final_zip = os.path.join(save_dir, base + '.zip') shutil.move(path, final_zip) config.log(f'已归档:{final_zip}(明细 {rows} 行)') csv_files = _unzip_csv(final_zip, save_dir, base) return {'skipped': False, 'zip': final_zip, 'csv': csv_files, 'size': os.path.getsize(final_zip), 'rows': rows, 'range': f'{date_from} ~ {date_to}', 'via': 'ui'} def _unzip_csv(zip_path, save_dir, base): out = [] try: with zipfile.ZipFile(zip_path) as zf: for name in zf.namelist(): if not name.lower().endswith('.csv'): continue target = os.path.join(save_dir, f'{base}_{os.path.basename(name)}') with zf.open(name) as src, open(target, 'wb') as dst: shutil.copyfileobj(src, dst) out.append(target) if out: config.log(f'已解压 {len(out)} 个 csv(GBK 编码,Excel 可直接打开)') except Exception as e: config.log(f'解压 csv 失败(zip 已保留):{e}', 'WARN') return out # ==================== 主流程(接口优先,失败自动回退 UI) ==================== def export_trade_flow(page, date_from, date_to, save_dir=None, mcht_id='', mcht_acc='', tag='商户验券'): save_dir = save_dir or config.default_output_dir() os.makedirs(save_dir, exist_ok=True) try: bank_api.init(page) if not (mcht_id and mcht_acc): did, dacc = bank_api.detect_merchant(page) mcht_id = mcht_id or did mcht_acc = mcht_acc or dacc if not (mcht_id and mcht_acc): raise RuntimeError('未能识别商户号(mchtId/mchtAcc)') config.log(f'商户:{mcht_id} / {mcht_acc}') ok, note = has_data_probe(page, mcht_id, mcht_acc, date_from, date_to) if not ok: return {'skipped': True, 'reason': '查询无数据,未导出', 'note': note} sub = bank_api.submit_export(page, mcht_id, mcht_acc, date_from, date_to) task_id = sub.get('task_id') if not task_id: raise RuntimeError(f'提交导出未返回 taskID:{sub}') config.log(f'已提交导出任务:{task_id}') # taskstate 语义不稳定(实测 1=生成中、3=完成,不同批次可能不同), # 所以只查一次记录状态,**以「能否下载到有效 zip」作为完成判据**,避免死等。 state = None for i in range(1, config.POLL_MAX + 1): try: time.sleep(config.POLL_INTERVAL if i > 1 else 2) items = bank_api.check_export(page, mcht_id, [task_id]) hit = next((it for it in items if str(it.get('taskID') or '') == task_id), None) if hit is not None: state = str(hit.get('taskstate')) config.debug(f'轮询 {i}/{config.POLL_MAX}:taskstate={state}') if state in config.EXPORT_STATE_DONE_SET: break except Exception as e: config.debug(f'查任务状态失败(不影响下载):{e}') break config.log(f'导出任务状态:taskstate={state}') stamp = time.strftime('%Y%m%d_%H%M%S') safe_range = f'{date_from.strftime("%Y%m%d")}-{date_to.strftime("%Y%m%d")}' base = f'交通银行_{tag}_{safe_range}_{stamp}' final_zip = os.path.join(save_dir, base + '.zip') # 文件未生成完时 OSS 上是 0 字节,需要重试下载 size = 0 for attempt in range(1, config.DOWNLOAD_RETRY + 1): url = bank_api.get_download_url(page, mcht_id) if not url: time.sleep(config.POLL_INTERVAL) continue config.log(f'下载地址已获取:{url[-60:]}') try: size = _download(url, final_zip) except Exception as e: config.log(f'第 {attempt} 次下载失败:{e}', 'WARN') size = 0 if size > 0 and zipfile.is_zipfile(final_zip): break config.log(f'文件尚未生成({size} 字节),{config.POLL_INTERVAL}s 后重试…', 'WARN') time.sleep(config.POLL_INTERVAL) if not size or not zipfile.is_zipfile(final_zip): raise RuntimeError('导出文件未生成(下载得到空文件或非 zip),可稍后重试') config.log(f'已下载:{final_zip}({size} 字节)') has_rows, _, rows = _csv_has_rows(final_zip) csv_files = _unzip_csv(final_zip, save_dir, base) return {'skipped': False, 'zip': final_zip, 'csv': csv_files, 'size': size, 'task_id': task_id, 'state': state, 'rows': rows, 'range': f'{date_from} ~ {date_to}', 'via': 'api'} except Exception as e: config.log(f'接口通道失败({e}),自动回退页面 UI 导出', 'WARN') return export_via_ui(page, date_from, date_to, save_dir, tag=tag)