Files
37duAutomation/plugins/XQ0001-0100/XQ0041 新美大平台核对/data/payment_download.py
T
puddy 911fd7661f feat(xq0041): 经营宝登录改人工点确认 + 双公司独立档案与执行模式拆分(1.3.9)
- 登录改为自动填账号密码并勾选用户协议,页面右上角浮层提示人工点「登录」(按钮、滑块/短信、选门店仍人工),登录一次长期复用

- 金色印象 / 金色湖畔各自独立浏览器档案与调试端口(xq0041 / xq0041_b,9222 / 9333),避免同浏览器反复切号触发风控

- 执行模式拆 full(只导金色印象 + 并台账 + 更新核对统计)/ export_only(按范围勾选各导一份,不写表),湖畔报表文件名带「金色湖畔_」前缀;UI 同步重建
2026-11-06 15:52:10 +08:00

175 lines
7.7 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 -*-
"""打款记录下载(h5 账单页,iframe 内 smartBill 三个接口)。
链路(实测):
① 查询 POST /gw/smartBill/paymentlist body{payTime,productCodeList,payStatusList,shopList,pageIndex,pageSize}
② 生成 POST /gw/smartBill/paymentdownload body 同上 + downloadFileType=6
③ 记录 GET /gw/smartBill/paymenthistory?pageIndex=0&pageSize=20&downloadFileType=6
(必须带 downloadFileType + 分页参数,缺了返回 code=500)
④ 下载 记录里的 downloadLink(mss-shon 预签名 URL,requests 直下)
①②③ 在 iframe 上下文发 XHR,mtgsig 由页面 SDK 自动补。
"""
import json
import os
import time
from datetime import datetime
from .. import config
from . import browser
def _find_frame(page, timeout=30):
deadline = time.time() + timeout
while time.time() < deadline:
try:
for f in page.get_frames():
try:
if 'merchant-bill' in (f.url or ''):
return f
except Exception:
continue
except Exception:
pass
time.sleep(1)
return None
def _history_items(frame):
url = (f'{config.PAYMENT_HISTORY_API}?pageIndex=0&pageSize=20'
f'&downloadFileType={config.PAYMENT_FILE_TYPE}')
data = browser.api_json(frame, 'GET', url) or {}
return (data.get('data') or {}).get('details') or []
def _throttle_seconds(msg):
import re
m = re.search(r'(\d+)\s*秒', msg or '')
return int(m.group(1)) if m else 0
def _age_minutes(add_time):
try:
dt = datetime.strptime(str(add_time).strip(), '%Y-%m-%d %H:%M:%S')
return (datetime.now() - dt).total_seconds() / 60.0
except Exception:
return 1e9
def download(page, d_from, d_to, save_dir, dry_run=False):
"""下载指定日期区间的打款记录。返回 {ok, path, rows, message}。"""
tag = d_from.replace('-', '') if d_from == d_to else \
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
match_key = d_from
config.log(f'打开打款记录页:{config.PAYMENT_PAGE_URL}', 'DEBUG')
page.get(config.PAYMENT_PAGE_URL)
frame = _find_frame(page)
if not frame:
return {'ok': False, 'message': '未找到账单 iframe(登录态可能已失效)'}
config.log(f'账单 iframe:{frame.url}', 'DEBUG')
# ① 先查询(页面同款顺序:查询出数据后下载按钮才可用)
query = {
'payTime': f'{d_from},{d_to}',
'productCodeList': [], 'payStatusList': [], 'shopList': [],
'pageIndex': 0, 'pageSize': 10,
}
q = browser.api_json(frame, 'POST', config.PAYMENT_LIST_API, query)
if q is None:
return {'ok': False, 'message': '打款记录查询失败'}
qdata = q.get('data') or {}
total = qdata.get('totalCount')
details = qdata.get('details') or []
config.log(f'查询 {d_from}~{d_to}:totalCount={total}')
if details:
s = details[0]
config.log(f' 首条 {s.get("payTime")} | {s.get("productCodeName")} | '
f'{s.get("amount")} | {s.get("payStatusName")}')
if not total:
# 区间内没有任何打款(周末/节假日/未结算)属正常业务状态,不算失败,
# 由调用方跳过本项、继续后续下载与核对。
return {'ok': True, 'empty': True, 'rows': 0,
'message': f'{d_from}~{d_to} 没有打款记录,跳过'}
# ② 已有记录时效内复用
before = _history_items(frame)
before_ids = {it.get('id') for it in before}
target = None
cands = [it for it in before
if match_key in (it.get('timeInterval') or '') and it.get('downloadLink')]
fresh = [it for it in cands if _age_minutes(it.get('addTime')) <= config.REUSE_MAX_AGE_MIN]
if fresh and not dry_run:
target = max(fresh, key=lambda x: str(x.get('addTime') or ''))
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
elif cands:
config.log('同区间记录已过期,重新生成以取最新数据')
# ③ 生成 + 轮询
if not target and not dry_run:
payload = dict(query)
payload.pop('pageIndex', None)
payload.pop('pageSize', None)
payload['downloadFileType'] = config.PAYMENT_FILE_TYPE
config.log(f'提交账单生成:{json.dumps(payload, ensure_ascii=False)}')
for attempt in range(1, config.RETRY_MAX + 1):
resp = browser.api_json(frame, 'POST', config.PAYMENT_DOWNLOAD_API, payload)
if resp and resp.get('code') == 200:
config.log('生成任务已受理')
break
msg = (resp or {}).get('message') or '无响应'
wait = _throttle_seconds(msg)
if wait and attempt < config.RETRY_MAX:
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试({attempt}/{config.RETRY_MAX})',
'WARN')
time.sleep(wait + 3)
continue
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
# 平台是「先登记一条记录(此时 downloadLink 为空)→ 文件生成完再回填链接」,
# 所以必须等 downloadLink 出现才算就绪,否则一命中空记录就退出等待(3 秒即失败)。
deadline = time.time() + config.RECORD_SECONDS
waited = 0
last_log = -config.POLL_LOG_EVERY
while time.time() < deadline:
time.sleep(config.POLL_SECONDS)
waited += config.POLL_SECONDS
items = _history_items(frame)
hits = [it for it in items
if it.get('id') not in before_ids
and match_key in (it.get('timeInterval') or '')]
ready = [it for it in hits if it.get('downloadLink')]
if ready:
# 同区间可能登记多条(重试/多业务),取最新一条
target = max(ready, key=lambda x: str(x.get('addTime') or ''))
break
if waited - last_log >= config.POLL_LOG_EVERY:
last_log = waited
if hits:
config.log(f' 账单生成中({len(hits)} 条记录暂无 downloadLink,'
f'已等 {waited}s / 上限 {config.RECORD_SECONDS}s)…')
else:
config.log(f' 等待账单生成…(已等 {waited}s)')
if dry_run:
return {'ok': True, 'message': f'[演练] 将生成并下载打款记录 {d_from}~{d_to}', 'rows': total}
if not target:
return {'ok': False,
'message': f'{config.RECORD_SECONDS}s 内记录仍未生成完成(无 downloadLink)'}
link = target.get('downloadLink')
if not link:
return {'ok': False, 'message': '记录里没有 downloadLink(可能仍在生成)'}
# 公司前缀:金色湖畔落到「金色湖畔_打款记录_20261105.xlsx」,不与金色印象同日文件互相覆盖
path = os.path.join(save_dir, f'{config.file_prefix()}{config.PAYMENT_NAME_KEY}_{tag}.xlsx')
config.log(f'下载 → {path}')
size = browser.download_file(link, path)
if not size:
return {'ok': False, 'message': '打款记录下载失败'}
info = browser.read_xlsx_summary(path)
config.log(f'完成:{os.path.basename(path)}({size / 1024:.0f} KB){info}')
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}