feat: 新增银行卡检查插件及相关依赖与配置文件
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:登录态、打款记录与收益明细的下载。"""
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浏览器:一次运行共用一个可见浏览器(登录 + 三张表下载都复用它,避免反复开关)。
|
||||
|
||||
独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0041,
|
||||
登录态跨次保留,不占用用户日常 Chrome 配置。
|
||||
"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_page():
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
profile = config.get_browser_profile_dir()
|
||||
import os
|
||||
os.makedirs(profile, exist_ok=True)
|
||||
co.set_user_data_path(profile)
|
||||
config.log(f'浏览器用户目录:{profile}', 'DEBUG')
|
||||
page = ChromiumPage(co)
|
||||
if not config.HEADLESS:
|
||||
# 登录要人工操作(账密/短信/扫码/选商家),全屏 + 置顶避免被其它窗口挡住
|
||||
config.apply_window_mode(page)
|
||||
return page
|
||||
|
||||
|
||||
def close_page(page):
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def xhr(page, method, url, payload=None):
|
||||
"""页面上下文同步 XHR:mtgsig/yodaReady 由页面上的 Yoda(H5guard) SDK 自动补。
|
||||
|
||||
返回 (status:int, text:str)。
|
||||
"""
|
||||
import json as _json
|
||||
body_js = 'null'
|
||||
headers_js = ''
|
||||
if payload is not None:
|
||||
body_js = 'JSON.stringify(' + _json.dumps(payload, ensure_ascii=False) + ')'
|
||||
headers_js = "x.setRequestHeader('Content-Type','application/json');"
|
||||
js = '''
|
||||
try {
|
||||
var x = new XMLHttpRequest();
|
||||
x.open('%s', '%s', false);
|
||||
x.withCredentials = true;
|
||||
%s
|
||||
x.send(%s);
|
||||
return x.status + '||' + String(x.responseText || '');
|
||||
} catch (e) {
|
||||
return 'ERR||' + e;
|
||||
}
|
||||
''' % (method.upper(), url, headers_js, body_js)
|
||||
raw = page.run_js(js)
|
||||
if not raw or '||' not in str(raw):
|
||||
return 0, f'返回值异常:{str(raw)[:200]}'
|
||||
status, _, text = str(raw).partition('||')
|
||||
try:
|
||||
return int(status), text
|
||||
except Exception:
|
||||
return 0, text
|
||||
|
||||
|
||||
def api_json(page, method, url, payload=None):
|
||||
import json as _json
|
||||
status, text = xhr(page, method, url, payload)
|
||||
name = url.split('/')[-1].split('?')[0]
|
||||
if status != 200:
|
||||
config.log(f'{name} 请求失败:status={status} {text[:200]}', 'WARN')
|
||||
return None
|
||||
try:
|
||||
return _json.loads(text)
|
||||
except Exception as e:
|
||||
config.log(f'{name} 返回非 JSON:{e} | {text[:200]}', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def download_file(link, save_path):
|
||||
"""S3 预签名 URL 直下(无需 Cookie / mtgsig)。返回字节数,失败 0。"""
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
headers = {
|
||||
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'),
|
||||
'Accept': '*/*',
|
||||
}
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
resp = requests.get(link, headers=headers, timeout=300, stream=True)
|
||||
if resp.status_code != 200:
|
||||
config.log(f'下载失败:HTTP {resp.status_code}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
tmp = save_path + '.part'
|
||||
with open(tmp, 'wb') as f:
|
||||
for chunk in resp.iter_content(128 * 1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
os.replace(tmp, save_path)
|
||||
size = os.path.getsize(save_path)
|
||||
if size < 1024:
|
||||
config.log(f'文件异常小({size} 字节),重试 {attempt}/{config.RETRY_MAX}', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
return size
|
||||
except Exception as e:
|
||||
config.log(f'下载异常:{e}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
return 0
|
||||
|
||||
|
||||
def read_xlsx_summary(path):
|
||||
"""读 sheet 名/行列数,确认文件有效。"""
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(path, read_only=True, data_only=True)
|
||||
ws = wb.worksheets[0]
|
||||
info = {'sheet': ws.title, 'rows': ws.max_row, 'cols': ws.max_column}
|
||||
wb.close()
|
||||
return info
|
||||
except Exception as e:
|
||||
return {'error': str(e)}
|
||||
@@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""美团经营宝登录态:打开官方页面 → 人工登录(含选商家)→ 检测完成 → 落盘 cookies/票据。
|
||||
|
||||
为什么不用 requests 校验:经营宝所有业务接口带 mtgsig 动态签名(页面 H5guard 秒级生成),
|
||||
requests 复刻必然 403。登录态有效性只由浏览器判定,取数也一律在页面上下文发请求。
|
||||
|
||||
实测登录链路(2026-10):
|
||||
ecom.meituan.com → 外壳,未登录也先进这里
|
||||
ecom.meituan.com/meishi → 前端异步鉴权,约 20s 后才跳走,不可当已登录
|
||||
.../bizaccount/login.html → 真·未登录
|
||||
.../bizaccount/biz-choice.html → 账号已登录、待选商家
|
||||
e.dianping.com/app/... → 选完商家进后台(登录完成,dp 商家)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def classify(url):
|
||||
"""页面状态:login / biz_choice / backend / other。"""
|
||||
low = (url or '').strip().lower()
|
||||
if not low.startswith('http'):
|
||||
return 'other'
|
||||
if config.LOGIN_PAGE_HINT in low or any(h in low for h in config.PASSPORT_HINTS):
|
||||
return 'login'
|
||||
if config.BIZ_CHOICE_HINT in low:
|
||||
return 'biz_choice'
|
||||
if any(h in low for h in config.BACKEND_HINTS):
|
||||
return 'backend'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _cookies(page):
|
||||
try:
|
||||
return page.cookies(all_domains=True) or []
|
||||
except Exception as e:
|
||||
config.log(f'读取 Cookies 失败:{e}', 'WARN')
|
||||
return []
|
||||
|
||||
|
||||
def _platform_cookie_header(cookies):
|
||||
skip = ('passport', 'certificates', 'report', 'lx', 'dreport')
|
||||
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
|
||||
if c.get('name')
|
||||
and any(d in (c.get('domain') or '') for d in ('meituan.com', 'dianping.com'))
|
||||
and not any(s in (c.get('domain') or '') for s in skip)]
|
||||
return '; '.join(pairs) if pairs else None
|
||||
|
||||
|
||||
def _read_storage(page):
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const dump = (store) => {
|
||||
const data = {};
|
||||
for (let i = 0; i < store.length; i++) {
|
||||
const k = store.key(i);
|
||||
const v = store.getItem(k);
|
||||
if (v && v.length < 100000) data[k] = v;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
return JSON.stringify({
|
||||
localStorage: dump(window.localStorage),
|
||||
sessionStorage: dump(window.sessionStorage),
|
||||
});
|
||||
''')
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception as e:
|
||||
config.log(f'读取 storage 失败(不影响 Cookies):{e}', 'WARN')
|
||||
return {}
|
||||
|
||||
|
||||
def _save_login_state(page):
|
||||
cookies = _cookies(page)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
config.log(f'已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}')
|
||||
else:
|
||||
config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN')
|
||||
|
||||
header = _platform_cookie_header(cookies)
|
||||
if header:
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, header)
|
||||
|
||||
storage = _read_storage(page)
|
||||
ls, ss = (storage.get('localStorage') or {}), (storage.get('sessionStorage') or {})
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'localStorage': ls,
|
||||
'sessionStorage': ss,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
domains = {}
|
||||
for c in cookies:
|
||||
d = c.get('domain') or '(空)'
|
||||
domains[d] = domains.get(d, 0) + 1
|
||||
summary = {
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'title': (getattr(page, 'title', '') or ''),
|
||||
'cookie_count': len(cookies),
|
||||
'cookie_domains': domains,
|
||||
'cookie_names': sorted({c.get('name') for c in cookies if c.get('name')}),
|
||||
'storage_keys': {'localStorage': sorted(ls.keys()), 'sessionStorage': sorted(ss.keys())},
|
||||
}
|
||||
_atomic_write(config.META_FILE, json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
config.log(f'登录态已落盘:{len(cookies)} 个 Cookie,'
|
||||
f'localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项')
|
||||
|
||||
|
||||
def _wait_backend(page):
|
||||
"""等人工完成「登录 + 选商家」。返回 True/False。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
last_url, last_state = None, None
|
||||
backend_since = None
|
||||
login_hint_at = biz_hint_at = 0.0
|
||||
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
url = page.url or ''
|
||||
except Exception:
|
||||
url = ''
|
||||
state = classify(url)
|
||||
|
||||
if url != last_url:
|
||||
last_url = url
|
||||
config.log(f'页面状态 = {state} | {url}', 'DEBUG')
|
||||
|
||||
if state != last_state:
|
||||
last_state = state
|
||||
if state == 'login' and time.time() - login_hint_at > 30:
|
||||
login_hint_at = time.time()
|
||||
config.log('请在浏览器窗口内完成登录(账号密码 / 短信验证码 / 扫码均可)')
|
||||
elif state == 'biz_choice' and time.time() - biz_hint_at > 30:
|
||||
biz_hint_at = time.time()
|
||||
config.log('账号已登录,请在页面上选择要进入的商家(脚本不自动选,避免进错店)')
|
||||
|
||||
if state == 'backend':
|
||||
if backend_since is None:
|
||||
backend_since = time.time()
|
||||
config.log(f'已进入商家后台,等待 {config.BACKEND_STABLE}s 确认不会再被踢回登录页…')
|
||||
elif time.time() - backend_since >= config.BACKEND_STABLE:
|
||||
return True
|
||||
else:
|
||||
if backend_since is not None:
|
||||
config.log('又回到登录/选商家页,重新计时', 'WARN')
|
||||
backend_since = None
|
||||
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
return False
|
||||
|
||||
|
||||
def ensure_login(page):
|
||||
"""确保 page 已进入商家后台;必要时停在前台等人工登录。"""
|
||||
config.log(f'打开经营宝:{config.HOME_URL}')
|
||||
page.get(config.HOME_URL)
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
# 复用一个短窗口:profile 里残留会话能直接进后台就不用打扰
|
||||
reuse_end = time.time() + config.BACKEND_STABLE + 10
|
||||
while time.time() < reuse_end:
|
||||
state = classify(page.url)
|
||||
if state == 'backend':
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
_save_login_state(page)
|
||||
return True, '复用缓存登录态'
|
||||
if state in ('login', 'biz_choice'):
|
||||
break
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
config.log(f'需要人工登录,最多等待 {config.LOGIN_WAIT} 秒…')
|
||||
if not _wait_backend(page):
|
||||
cookies = _cookies(page)
|
||||
config.log('当前 Cookie:' + ', '.join(sorted({c.get('name') for c in cookies if c.get('name')})),
|
||||
'WARN')
|
||||
return False, '登录超时(未进入商家后台)'
|
||||
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
if classify(page.url) != 'backend':
|
||||
return False, '登录态未稳定(落盘前离开后台)'
|
||||
_save_login_state(page)
|
||||
return True, '登录成功'
|
||||
@@ -0,0 +1,159 @@
|
||||
# -*- 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': False, '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 = fresh[0]
|
||||
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}'}
|
||||
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
while time.time() < deadline:
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
items = _history_items(frame)
|
||||
for it in items:
|
||||
if it.get('id') in before_ids:
|
||||
continue
|
||||
if match_key not in (it.get('timeInterval') or ''):
|
||||
continue
|
||||
target = it
|
||||
break
|
||||
if target:
|
||||
break
|
||||
config.log(' 等待账单生成…')
|
||||
|
||||
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 内未拿到可下载记录'}
|
||||
|
||||
link = target.get('downloadLink')
|
||||
if not link:
|
||||
return {'ok': False, 'message': '记录里没有 downloadLink(可能仍在生成)'}
|
||||
|
||||
path = os.path.join(save_dir, f'{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': '打款记录已下载'}
|
||||
@@ -0,0 +1,189 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""收益明细下载(PC 商户中心 downloadManagement 一套接口)。
|
||||
|
||||
链路(实测):
|
||||
① 门店 GET /smartBill/queryAllShopIds → data.availableShopIds(0=全部)
|
||||
② 类型 GET /finance/ajax/downloadManagement/productCodeList → [{1,团购},{11,预订}]
|
||||
③ 生成 POST /finance/ajax/downloadManagement/request
|
||||
body{beginDate,endDate,productCodeList,shopIdList,downloadFileType:201}
|
||||
(一次生成团购+预订两个文件,约 30~40 秒内限流一次)
|
||||
④ 记录 GET /finance/ajax/downloadManagement/list?pageSize=20&pageNum=1&beginDate&endDate
|
||||
⑤ 链接 GET /finance/ajax/downloadManagement/downloadLink?id=<记录id>(记录里 downloadLink 为空时)
|
||||
⑥ 下载 mss-shon 预签名 URL(requests 直下)
|
||||
|
||||
复用策略:按业务类型分组取最新一条,**任一类型缺失或过期就整体重新生成**,
|
||||
避免出现「只拿到团购、预订缺失」的半套数据。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from . import browser
|
||||
|
||||
|
||||
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 _history(page, day_from, day_to):
|
||||
url = f'{config.PROFIT_LIST_API}?pageSize=20&pageNum=1&beginDate={day_from}&endDate={day_to}'
|
||||
data = browser.api_json(page, 'GET', url) or {}
|
||||
return data.get('data') or []
|
||||
|
||||
|
||||
def _expect_names(codes):
|
||||
"""勾选的业务类型 → 预期产出的明细名称。"""
|
||||
names = []
|
||||
if 1 in codes:
|
||||
names.append('团购收益明细')
|
||||
if 11 in codes:
|
||||
names.append('预订收益明细')
|
||||
return names
|
||||
|
||||
|
||||
def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
||||
"""下载指定业务类型的收益明细。codes:1=团购、11=预订;None=两者都要。
|
||||
|
||||
返回 {ok, paths, message}。
|
||||
"""
|
||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||
|
||||
config.log(f'打开收益明细页:{config.PROFIT_PAGE_URL}', 'DEBUG')
|
||||
page.get(config.PROFIT_PAGE_URL)
|
||||
time.sleep(4)
|
||||
|
||||
# ① 门店 / 业务类型
|
||||
shop_data = browser.api_json(page, 'GET', config.SHOP_API) or {}
|
||||
shop_ids = ((shop_data.get('data') or {}).get('availableShopIds')) or []
|
||||
if not shop_ids:
|
||||
config.log('未取到门店列表,回退 [0](全部)', 'WARN')
|
||||
shop_ids = [0]
|
||||
prod_data = browser.api_json(page, 'GET', config.PRODUCT_API) or {}
|
||||
products = prod_data.get('data') or []
|
||||
all_codes = [p.get('productCode') for p in products if p.get('productCode')] or [1, 11]
|
||||
# 只保留勾选的类型;未指定则全要
|
||||
want = [c for c in (codes or all_codes) if c in all_codes] or all_codes
|
||||
expect = _expect_names(want)
|
||||
config.log(f'门店 {len(shop_ids)} 个;本次下载类型:{json.dumps(products, ensure_ascii=False)}'
|
||||
f' → {expect}')
|
||||
|
||||
# ② 已有记录:按类型完整性 + 时效判断
|
||||
from datetime import date, timedelta
|
||||
list_from = (date.today() - timedelta(days=30)).isoformat()
|
||||
list_to = date.today().isoformat()
|
||||
before = _history(page, list_from, list_to)
|
||||
|
||||
targets = []
|
||||
groups = {}
|
||||
for it in before:
|
||||
if d_from not in (it.get('timeInterval') or ''):
|
||||
continue
|
||||
if it.get('downloadStatus') != 2:
|
||||
continue
|
||||
key = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
groups.setdefault(key, []).append(it)
|
||||
newest = {k: max(v, key=lambda x: str(x.get('addTime') or '')) for k, v in groups.items()}
|
||||
newest = {k: v for k, v in newest.items() if k in expect} # 只看勾选的类型
|
||||
ages = {k: _age_minutes(v.get('addTime')) for k, v in newest.items()}
|
||||
stale = [k for k, a in ages.items() if a > config.REUSE_MAX_AGE_MIN]
|
||||
if all(name in newest for name in expect) and not stale:
|
||||
targets = list(newest.values())
|
||||
config.log('同区间记录齐全且新鲜,直接复用:' +
|
||||
', '.join(f'{k}({ages[k]:.0f}分钟前)' for k in newest))
|
||||
elif newest:
|
||||
config.log(f'已有记录不完整或过期({len(newest)}/{len(expect)} 类,'
|
||||
f'过期:{",".join(stale) or "无"}),重新生成以取最新数据')
|
||||
|
||||
# ③ 生成
|
||||
if not targets and not dry_run:
|
||||
payload = {
|
||||
'beginDate': d_from,
|
||||
'endDate': d_to,
|
||||
'productCodeList': want,
|
||||
'shopIdList': shop_ids,
|
||||
'downloadFileType': config.PROFIT_FILE_TYPE,
|
||||
}
|
||||
config.log(f'提交生成:{d_from}~{d_to},类型 {want},门店 {len(shop_ids)} 个')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
resp = browser.api_json(page, 'POST', config.PROFIT_REQUEST_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}'}
|
||||
|
||||
before_ids = {it.get('id') for it in before}
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
while time.time() < deadline:
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
items = _history(page, list_from, list_to)
|
||||
hits = [it for it in items
|
||||
if it.get('id') not in before_ids and d_from in (it.get('timeInterval') or '')]
|
||||
ready = [it for it in hits if it.get('downloadStatus') == 2]
|
||||
pending = [it for it in hits if it.get('downloadStatus') != 2]
|
||||
if ready:
|
||||
targets = ready
|
||||
if not pending:
|
||||
break
|
||||
config.log(' 已就绪 %d 条,仍有 %d 条生成中(%s)…' % (
|
||||
len(ready), len(pending),
|
||||
', '.join(str(it.get('productCodeName')) for it in pending)))
|
||||
else:
|
||||
config.log(' 等待生成…')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'message': f'[演练] 将生成并下载收益明细 {d_from}~{d_to}', 'paths': []}
|
||||
|
||||
if not targets:
|
||||
return {'ok': False, 'message': f'未拿到可下载的收益明细({config.RECORD_SECONDS}s 内未完成)'}
|
||||
|
||||
# ④ 逐个下载(同类型去重取最新)
|
||||
uniq = {}
|
||||
for it in targets:
|
||||
key = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
if expect and key not in expect:
|
||||
continue
|
||||
uniq.setdefault(key, it)
|
||||
|
||||
paths = []
|
||||
for it in uniq.values():
|
||||
name = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
link = it.get('downloadLink') or ''
|
||||
if not link:
|
||||
ld = browser.api_json(page, 'GET', f'{config.PROFIT_LINK_API}?id={it.get("id")}') or {}
|
||||
link = ((ld.get('data') or {}).get('downloadLink')) or ''
|
||||
if not link:
|
||||
config.log(f'{name} 未取到 downloadLink,跳过', 'WARN')
|
||||
continue
|
||||
path = os.path.join(save_dir, f'{name}_{tag}.xlsx')
|
||||
config.log(f'下载 {name} → {path}')
|
||||
size = browser.download_file(link, path)
|
||||
if not size:
|
||||
config.log(f'{name} 下载失败', 'ERROR')
|
||||
continue
|
||||
info = browser.read_xlsx_summary(path)
|
||||
config.log(f' {name} 完成:{size / 1024:.0f} KB | {info}')
|
||||
paths.append(path)
|
||||
|
||||
if not paths:
|
||||
return {'ok': False, 'message': '收益明细全部下载失败'}
|
||||
return {'ok': True, 'paths': paths, 'message': f'收益明细已下载 {len(paths)} 个文件'}
|
||||
Reference in New Issue
Block a user