feat(xq0078): 新增金色湖畔小程序数据导出插件(1.0.4)

- 金贵微信端管理平台(vip6.wechat.goldenyun.cn)门票使用统计导出:接口登录 → 搜索接口取核销明细 → 调平台导出接口生成 xlsx

- 核销时间日期段界面可选(默认昨天 00:00:00 ~ 今天 23:59:59);导出接口异常时按同一份数据本地生成同列序 xlsx 兜底
This commit is contained in:
2026-11-06 15:52:15 +08:00
parent 911fd7661f
commit 6b9102ba6c
23 changed files with 3486 additions and 0 deletions
@@ -0,0 +1,240 @@
# -*- coding: utf-8 -*-
"""金贵微信端管理平台 - 门票使用统计(票券消费明细)查询与导出。
接口机制(从列表页 JS 逆向确认):
1) 搜索接口 POST /wechat/memberreport/ticketconsumelistreport
body = 列表页 frmList 序列化(Query.BeginTime/EndTime/... + Pager.*),返回 JSON 数组,
元素字段:TicketTypeName / TicketGroupId / TicketID / SellPrice / UseDateStr /
UseBillid / UseName / UseVpnName。
2) 导出接口 POST /wechat/export/downloadexcel
它不接受查询条件,只接受「文件名 + 一整段 <table> HTML」;页面是前端把搜索 JSON
拼成表格塞进隐藏域再提交。两个隐藏域 name 每次页面加载都变(数字 ticks + GUID),
必须现场从列表页解析。
"""
import re
import time
import requests
from .. import config
# ---------------------------- 列表页 / 导出表单字段 ----------------------------
def open_list_page(session):
url = f"{config.BASE_URL}{config.APP_PATH}{config.LIST_PATH}"
config.logger.info('打开门票使用统计页: %s', url)
resp = session.get(url, timeout=config.TIMEOUT)
resp.encoding = 'utf-8'
if config.LOGIN_PATH in resp.url and 'id="Password"' in resp.text:
raise RuntimeError('列表页被重定向回登录页:会话已失效,请重新执行')
resp.raise_for_status()
return resp.text
def parse_export_fields(html):
"""解析 exportForm 两个动态隐藏域 name:纯数字=文件名,GUID 形态=表格 HTML。"""
start = html.find('id="exportForm"')
if start == -1:
raise RuntimeError('列表页未找到 exportForm,无法确定导出字段名(平台页面可能改版)')
end = html.find('</form>', start)
segment = html[start:end if end != -1 else len(html)]
names = re.findall(r'<input\s+name="([^"]+)"\s+type="hidden"', segment)
if len(names) < 2:
names = re.findall(r'name="([^"]+)"[^>]*type="hidden"', segment)
digits = [n for n in names if n.isdigit() and 10 <= len(n) <= 20]
guids = [n for n in names if n.count('-') >= 2]
if not digits or not guids:
raise RuntimeError(f'导出表单字段名解析失败:{names}')
config.logger.info('导出表单字段名:文件名=%s / 表格=%s', digits[0], guids[0])
return {'filename': digits[0], 'content': guids[0]}
# ---------------------------- 搜索 ----------------------------
def build_query(begin, end, page_index=0):
return {
'Query.BeginTime': begin,
'Query.EndTime': end,
'Query.TicketGroupId': '',
'Query.UseBillid': '',
'Query.UseName': '',
'Query.UseVpnCode': '',
'Query.TypeCode': '',
'Pager.TotalAmount': '0',
'Pager.PageSize': str(config.PAGE_SIZE),
'Pager.PageIndex': str(page_index),
}
def _post_search(session, query):
url = f"{config.BASE_URL}{config.APP_PATH}{config.SEARCH_PATH}"
headers = {
'X-Requested-With': 'XMLHttpRequest',
'Referer': f"{config.BASE_URL}{config.APP_PATH}{config.LIST_PATH}",
}
resp = session.post(url, data=query, headers=headers, timeout=config.TIMEOUT)
resp.encoding = 'utf-8'
if resp.status_code >= 500:
raise requests.RequestException(f'搜索接口 HTTP {resp.status_code}')
if resp.status_code != 200:
raise RuntimeError(f'搜索接口 HTTP {resp.status_code}:{resp.text[:200]}')
body = (resp.text or '').strip()
if not body:
return []
if body.startswith('<'):
raise RuntimeError(f'搜索接口返回 HTML 而非 JSON(可能会话失效):{body[:200]}')
try:
data = resp.json()
except ValueError:
raise RuntimeError(f'搜索接口返回无法解析:{body[:200]}')
if isinstance(data, dict):
for key in ('Data', 'data', 'Rows', 'rows', 'Items', 'items'):
if isinstance(data.get(key), list):
data = data[key]
break
return data if isinstance(data, list) else []
def post_search(session, query):
"""带重试的搜索调用(仅网络异常/5xx 重试,避免无意义重放)。"""
last = None
for attempt in range(1, config.SEARCH_MAX_RETRY + 1):
try:
return _post_search(session, query)
except requests.RequestException as e:
last = e
config.logger.warning('搜索第 %s/%s 次失败:%s', attempt, config.SEARCH_MAX_RETRY, e)
time.sleep(2)
raise RuntimeError(f'搜索接口连续 {config.SEARCH_MAX_RETRY} 次失败:{last}')
def fetch_all_rows(session, begin, end):
"""按页拉全量并去重(接口若忽略分页,第一次即返回全部)。"""
rows, seen, page = [], set(), 0
while page < config.MAX_PAGES:
batch = post_search(session, build_query(begin, end, page))
config.logger.info('第 %s 页返回 %s 条', page + 1, len(batch))
if not batch:
break
new_count = 0
for row in batch:
key = (str(row.get('TicketID')), str(row.get('TicketGroupId')), str(row.get('UseDateStr')))
if key in seen:
continue
seen.add(key)
rows.append(row)
new_count += 1
if new_count == 0 or len(batch) < config.PAGE_SIZE:
break
page += 1
config.logger.info('去重后合计 %s 条', len(rows))
return rows
# ---------------------------- 导出 ----------------------------
def _price(value):
try:
return f"{float(value or 0):.2f}"
except (TypeError, ValueError):
return '0.00'
def rows_to_table_html(rows):
"""拼成与页面完全一致结构的表格 HTML(导出接口只认这段 HTML)。"""
head = ('<table class="table mytable extend table-bordered single-selected new-table-header-on" '
'id="detail-List"><thead> <tr>'
+ ''.join(f'<th>{c}</th>' for c in config.COLUMNS)
+ '</tr></thead><tbody>')
body = []
for row in rows:
body.append(
'<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>'.format(
row.get('TicketTypeName') or '',
row.get('TicketGroupId') or '',
row.get('TicketID') or '',
_price(row.get('SellPrice')),
row.get('UseDateStr') or '',
row.get('UseBillid') or config.EMPTY_BILL_TEXT,
row.get('UseName') or '',
row.get('UseVpnName') or '',
))
return head + ''.join(body) + '</tbody></table>'
def _decode_body(resp):
"""按 BOM 解码响应体(平台用 Encoding.Unicode 输出 HTML 表格,即 UTF-16LE)。"""
raw = resp.content or b''
if raw[:2] == b'\xff\xfe':
return raw[2:].decode('utf-16-le', 'ignore')
if raw[:2] == b'\xfe\xff':
return raw[2:].decode('utf-16-be', 'ignore')
return raw.decode(resp.encoding or 'utf-8', 'ignore')
def export_via_server(session, fields, rows):
"""调服务端导出接口。
返回 dict:
{'kind': 'xlsx', 'content': bytes} 平台返回真 xlsx(PK 文件头)
{'kind': 'html_excel', 'text': str} 平台返回 HTML 伪装 Excel(UTF-16 的 <table>…)
{'kind': 'none', 'text': str} 未拿到可识别内容(调用方走本地兜底)
"""
url = f"{config.BASE_URL}{config.APP_PATH}{config.EXPORT_PATH}"
payload = {
fields['filename']: config.EXPORT_TITLE,
fields['content']: rows_to_table_html(rows),
}
headers = {
'X-Requested-With': 'XMLHttpRequest',
'Referer': f"{config.BASE_URL}{config.APP_PATH}{config.LIST_PATH}",
}
config.logger.info('调用导出接口(%s 条)…', len(rows))
resp = session.post(url, data=payload, headers=headers, timeout=config.TIMEOUT)
config.logger.info('导出响应:状态=%s Content-Type=%s Content-Disposition=%s 长度=%s 文件头=%r',
resp.status_code, resp.headers.get('Content-Type'),
resp.headers.get('Content-Disposition'),
len(resp.content), resp.content[:4])
if resp.status_code == 200 and resp.content[:2] == b'PK':
return {'kind': 'xlsx', 'content': resp.content}
text = _decode_body(resp)
if resp.status_code == 200 and '<table' in text.lower():
# 平台「导出」= 把表格 HTML 直接吐回(Excel 能识别但不是标准工作簿,
# 用 .xls 扩展名打开还会提示格式不符);数据本身与搜索接口完全一致
config.logger.info('平台导出接口返回 HTML 版 Excel(%.1f KB),数据可用',
len(resp.content) / 1024.0)
return {'kind': 'html_excel', 'text': text}
config.logger.warning('导出接口未返回可识别文件,响应预览:%s',
text[:200].replace('\n', ' '))
return {'kind': 'none', 'text': text}
def write_xlsx_local(rows, path):
"""兜底:按搜索接口 JSON 直接用 openpyxl 生成同列序的 xlsx。"""
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = config.EXPORT_TITLE[:31]
ws.append(config.COLUMNS)
for row in rows:
ws.append([
row.get('TicketTypeName') or '',
row.get('TicketGroupId') or '',
row.get('TicketID') or '',
float(_price(row.get('SellPrice'))),
row.get('UseDateStr') or '',
row.get('UseBillid') or config.EMPTY_BILL_TEXT,
row.get('UseName') or '',
row.get('UseVpnName') or '',
])
for letter, width in zip('ABCDEFGH', (46, 20, 18, 10, 20, 20, 12, 22)):
ws.column_dimensions[letter].width = width
wb.save(path)
return path