224 lines
11 KiB
Python
224 lines
11 KiB
Python
# -*- 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 自动补。
|
||
|
||
断点续传:单次只等 5 分钟(config.RECORD_SECONDS),超时不报错——已提交/仍在生成中的
|
||
记录 id 落盘到 resume_state,下次运行接着等;出表后直接下载,不重复提交生成任务。
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
from datetime import datetime
|
||
|
||
from .. import config
|
||
from . import browser, resume_state
|
||
|
||
|
||
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, resume=True, wait_mode=config.WAIT_SKIP):
|
||
"""下载指定日期区间的打款记录。返回 {ok, path, rows, pending, message}。
|
||
|
||
resume=True(默认):先认领上次没出表的记录,接着等,出表即下载;
|
||
resume=False(全新下载):不复用、不认领,一律重新提交生成任务。
|
||
wait_mode=skip(默认):单张表最多等 config.RECORD_SECONDS(5 分钟),没出就跳过记待续;
|
||
wait_mode=until_done:不限时等出表(受执行机单次执行超时/用户强停约束)。
|
||
"""
|
||
until_done = wait_mode == config.WAIT_UNTIL_DONE
|
||
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}
|
||
same = [it for it in before if match_key in (it.get('timeInterval') or '')]
|
||
cands = [it for it in same if it.get('downloadLink')]
|
||
running = [it for it in same if not it.get('downloadLink')]
|
||
|
||
company = config.current_company()['id']
|
||
st = resume_state.load(company, 'payment', d_from, d_to) if resume else None
|
||
|
||
target = None
|
||
if not dry_run and not resume:
|
||
config.log('「全新下载」:不复用已有账单,重新提交生成任务')
|
||
elif not dry_run:
|
||
if cands and st:
|
||
# 续传:上次提交的同区间账单本次已出表,不再受「N 分钟内才复用」限制
|
||
target = max(cands, key=lambda x: str(x.get('addTime') or ''))
|
||
config.log(f'续传:上次提交的同区间记录已出表({target.get("addTime")}),直接下载')
|
||
elif cands:
|
||
fresh = [it for it in cands
|
||
if _age_minutes(it.get('addTime')) <= config.REUSE_MAX_AGE_MIN]
|
||
if fresh:
|
||
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} 分钟),不重复生成')
|
||
else:
|
||
config.log('同区间记录已过期且无待续任务,重新生成以取最新数据')
|
||
|
||
# ③ 接着等已提交的任务 / 提交新任务 + 单次 5 分钟轮询
|
||
waiting = set()
|
||
if not target and not dry_run:
|
||
if running and resume:
|
||
# 平台已登记同区间记录但还没回填链接:就是上次没等到的那份,接着等,不重复提交
|
||
waiting = {it.get('id') for it in running}
|
||
config.log(f'平台已有 {len(running)} 条同区间账单仍在生成,接着等(不重复提交生成)')
|
||
else:
|
||
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 后重试'
|
||
f'({attempt}/{config.RETRY_MAX})', 'WARN')
|
||
time.sleep(wait + 3)
|
||
continue
|
||
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
||
|
||
# 落盘待续:超时后下次运行按这些 id 接着等,不再重复提交生成任务
|
||
resume_state.save(company, 'payment', d_from, d_to, ids=waiting,
|
||
since=min([str(it.get('addTime') or '') for it in running] or
|
||
[time.strftime('%Y-%m-%d %H:%M:%S')]))
|
||
|
||
# 平台是「先登记一条记录(此时 downloadLink 为空)→ 文件生成完再回填链接」,
|
||
# 所以必须等 downloadLink 出现才算就绪,否则一命中空记录就退出等待(3 秒即失败)。
|
||
deadline = None if until_done else time.time() + config.RECORD_SECONDS
|
||
waited = 0
|
||
last_log = -config.POLL_LOG_EVERY
|
||
if until_done:
|
||
config.log('等待策略:一次等到底(不限时,等出表为止;受执行超时/强停约束)')
|
||
while deadline is None or time.time() < deadline:
|
||
time.sleep(config.POLL_SECONDS)
|
||
waited += config.POLL_SECONDS
|
||
items = _history_items(frame)
|
||
# 跟踪两拨记录:已认领的(续传/上次提交)+ 本次提交后新登记的
|
||
fresh = [it for it in items if it.get('id') not in before_ids
|
||
and match_key in (it.get('timeInterval') or '')]
|
||
if waiting:
|
||
pool = [it for it in items if it.get('id') in waiting]
|
||
pool += [it for it in fresh if it.get('id') not in waiting]
|
||
else:
|
||
pool = fresh
|
||
waiting |= {it.get('id') for it in pool}
|
||
ready = [it for it in pool 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
|
||
limit = '不限时' if until_done else f'上限 {config.RECORD_SECONDS // 60} 分钟'
|
||
if pool:
|
||
config.log(f' 账单生成中({len(pool)} 条记录暂无 downloadLink,'
|
||
f'已等 {waited // 60} 分钟 / {limit})…')
|
||
else:
|
||
config.log(f' 等待账单生成…(已等 {waited // 60} 分钟 / {limit})')
|
||
|
||
if dry_run:
|
||
return {'ok': True, 'message': f'[演练] 将生成并下载打款记录 {d_from}~{d_to}', 'rows': total}
|
||
|
||
if not target:
|
||
resume_state.save(company, 'payment', d_from, d_to, ids=waiting)
|
||
limit = '不限时,本次被中断' if until_done else f'本次已等 {config.RECORD_SECONDS // 60} 分钟'
|
||
return {'ok': True, 'pending': True, 'rows': total,
|
||
'pending_tables': [config.PAYMENT_NAME_KEY],
|
||
'message': f'{config.PAYMENT_NAME_KEY}仍在平台生成中({limit},已记待续),'
|
||
f'下次运行会接着查,出表即下载'}
|
||
|
||
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}')
|
||
resume_state.clear(company, 'payment')
|
||
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}
|