feat(xq0041): 迁出美团/抖音核对,导表支持断点续传(v1.3.17)
This commit is contained in:
@@ -11,8 +11,11 @@
|
||||
⑤ 链接 GET /finance/ajax/downloadManagement/downloadLink?id=<记录id>(记录里 downloadLink 为空时)
|
||||
⑥ 下载 mss-shon 预签名 URL(requests 直下)
|
||||
|
||||
复用策略:按业务类型分组取最新一条,**任一类型缺失或过期就整体重新生成**,
|
||||
避免出现「只拿到团购、预订缺失」的半套数据。
|
||||
复用策略:按业务类型分组取最新一条,**任一类缺失或过期就重新生成**,避免半套数据。
|
||||
|
||||
断点续传:每张表最多等 5 分钟(config.RECORD_SECONDS),勾选几张就累计几分钟
|
||||
(团购+预订=10 分钟,都出齐提前结束);到点不报错——已就绪的先下载,
|
||||
仍生成中的记录 id 落盘到 resume_state,下次运行接着等,不重复提交生成任务。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
@@ -20,7 +23,7 @@ import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from . import browser
|
||||
from . import browser, resume_state
|
||||
|
||||
|
||||
def _throttle_seconds(msg):
|
||||
@@ -53,10 +56,17 @@ def _expect_names(codes):
|
||||
return names
|
||||
|
||||
|
||||
def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
||||
def download(page, d_from, d_to, save_dir, codes=None, dry_run=False, resume=True,
|
||||
wait_mode=config.WAIT_SKIP):
|
||||
"""下载指定业务类型的收益明细。codes:1=团购、11=预订;None=两者都要。
|
||||
|
||||
返回 {ok, paths, message}。
|
||||
resume=True(默认):先认领上次没出表的记录,接着等,出表即下载(已就绪的先下);
|
||||
resume=False(全新下载):不复用、不认领,一律重新提交生成任务。
|
||||
wait_mode=skip(默认):每张表最多等 config.RECORD_SECONDS(5 分钟),按勾选类型数累计
|
||||
(都出齐提前结束);到点把已就绪的表下完,没就绪的跳过记待续,下次运行接着查。
|
||||
wait_mode=until_done:不限时等所选表全部出齐(一次跑完,受执行超时/强停约束)。
|
||||
|
||||
返回 {ok, paths, pending, pending_tables, message}。
|
||||
"""
|
||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||
@@ -80,81 +90,161 @@ def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
||||
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)
|
||||
before_ids = {it.get('id') for it in before}
|
||||
same = [it for it in before if d_from in (it.get('timeInterval') or '')]
|
||||
|
||||
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 "无"}),重新生成以取最新数据')
|
||||
def _type_key(it):
|
||||
return it.get('productCodeName') or it.get('fileName') 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}'}
|
||||
# 只认勾选的类型(类型名未知的记录也保留,避免漏认上次提交的任务)
|
||||
running = [it for it in same if it.get('downloadStatus') != 2
|
||||
and (_type_key(it) in expect or it.get('productCodeName') is None)]
|
||||
|
||||
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]
|
||||
def _newest(items):
|
||||
"""按业务类型取最新一条(只看勾选的类型)。"""
|
||||
groups = {}
|
||||
for it in items:
|
||||
key = _type_key(it)
|
||||
if key in expect:
|
||||
groups.setdefault(key, []).append(it)
|
||||
return {k: max(v, key=lambda x: str(x.get('addTime') or ''))
|
||||
for k, v in groups.items()}
|
||||
|
||||
ready = _newest([it for it in same if it.get('downloadStatus') == 2])
|
||||
|
||||
company = config.current_company()['id']
|
||||
st = resume_state.load(company, 'profit', d_from, d_to) if resume else None
|
||||
|
||||
need_generate = False
|
||||
if not resume:
|
||||
config.log('「全新下载」:不复用已有明细,重新提交生成任务')
|
||||
ready.clear() # 全新下载:旧记录全部作废,只认本次产出
|
||||
need_generate = True
|
||||
elif st:
|
||||
# 续传:上次提交的部分类型可能已出表,先收下,缺的接着等(不受新鲜度限制)
|
||||
miss = [k for k in expect if k not in ready]
|
||||
config.log(f'续传:同区间已就绪 {len(ready)}/{len(expect)} 类'
|
||||
+ (f',继续等 {"/".join(miss)}' if miss else ',直接下载'))
|
||||
need_generate = bool(miss)
|
||||
else:
|
||||
ages = {k: _age_minutes(v.get('addTime')) for k, v in ready.items()}
|
||||
stale = [k for k, a in ages.items() if a > config.REUSE_MAX_AGE_MIN]
|
||||
if ready and all(name in ready for name in expect) and not stale:
|
||||
config.log('同区间记录齐全且新鲜,直接复用:' +
|
||||
', '.join(f'{k}({ages[k]:.0f}分钟前)' for k in ready))
|
||||
else:
|
||||
# 不完整或过期:重新生成,旧记录作废(否则 5 分钟内没出表会把过期数据当本次结果)
|
||||
need_generate = True
|
||||
if ready:
|
||||
targets = ready
|
||||
if not pending:
|
||||
config.log(f'已有记录不完整或过期({len(ready)}/{len(expect)} 类,'
|
||||
f'过期:{",".join(stale) or "无"}),重新生成以取最新数据')
|
||||
ready.clear()
|
||||
|
||||
# ③ 接着等已提交的任务 / 提交新任务 + 轮询
|
||||
# 每张表 5 分钟:一次生成任务同时产多种表,按勾选类型数给足预算(都出齐就提前结束);
|
||||
# until_done = 不限时等出表(一次跑完,受执行超时/强停约束)
|
||||
until_done = wait_mode == config.WAIT_UNTIL_DONE
|
||||
budget = None if until_done else config.RECORD_SECONDS * max(1, len(expect))
|
||||
budget_min = (budget or 0) // 60
|
||||
waiting = set()
|
||||
# 续传时平台上已有记录的类型(哪怕没就绪)才算「还在生成」;重新生成只看本次产出的记录
|
||||
seen = set(_newest(same).keys()) if st else set()
|
||||
if not dry_run and need_generate:
|
||||
if running and resume:
|
||||
# 平台已登记同区间记录但还没生成完:就是上次没等到的那份,接着等,不重复提交
|
||||
waiting = {it.get('id') for it in running}
|
||||
config.log(f'平台已有 {len(running)} 条同区间记录仍在生成,接着等(不重复提交生成)')
|
||||
else:
|
||||
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
|
||||
config.log(' 已就绪 %d 条,仍有 %d 条生成中(%s)…' % (
|
||||
len(ready), len(pending),
|
||||
', '.join(str(it.get('productCodeName')) for it in pending)))
|
||||
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, 'profit', 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')]))
|
||||
|
||||
deadline = None if until_done else time.time() + budget
|
||||
waited = 0
|
||||
last_log = -config.POLL_LOG_EVERY
|
||||
if until_done:
|
||||
config.log('等待策略:一次等到底(不限时,等所选 %d 张表全部出齐;受执行超时/强停约束)'
|
||||
% len(expect))
|
||||
while deadline is None or time.time() < deadline:
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
waited += config.POLL_SECONDS
|
||||
items = _history(page, list_from, list_to)
|
||||
# 跟踪两拨记录:已认领的(续传/上次提交)+ 本次提交后新登记的;
|
||||
# 只看已认领的会漏掉同一任务产出的其它表(比如先出团购、后出预订)
|
||||
fresh = [it for it in items if it.get('id') not in before_ids
|
||||
and d_from 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:
|
||||
config.log(' 等待生成…')
|
||||
pool = fresh
|
||||
waiting |= {it.get('id') for it in pool}
|
||||
seen |= {_type_key(it) for it in pool}
|
||||
for k, it in _newest([it for it in pool
|
||||
if it.get('downloadStatus') == 2]).items():
|
||||
ready[k] = it
|
||||
if all(name in ready for name in expect):
|
||||
break
|
||||
if waited - last_log >= config.POLL_LOG_EVERY:
|
||||
last_log = waited
|
||||
miss = [k for k in expect if k not in ready]
|
||||
limit = ('不限时' if until_done else
|
||||
f'本次上限 {budget_min} 分钟={len(expect)} 张表×'
|
||||
f'{config.RECORD_SECONDS // 60} 分钟')
|
||||
config.log(f' 等待生成(已等 {waited // 60} 分钟 / {limit}):'
|
||||
f'缺 {"/".join(miss)}')
|
||||
|
||||
targets = [ready[k] for k in expect if k in ready]
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'message': f'[演练] 将生成并下载收益明细 {d_from}~{d_to}', 'paths': []}
|
||||
|
||||
missing = [k for k in expect if k not in ready]
|
||||
# 平台连记录都没有的类型:视为本次未产出(该业务可能无数据)→ 告警跳过,不算待续,
|
||||
# 否则会一直卡在待续、永远走不到核对
|
||||
stuck = [k for k in missing if k not in seen]
|
||||
pending_missing = [k for k in missing if k in seen]
|
||||
if stuck:
|
||||
config.log(f'{"、".join(stuck)} 平台上没有对应记录(本次未产出,可能该业务无数据),'
|
||||
f'跳过这张表继续后续流程', 'WARN')
|
||||
pending = bool(pending_missing)
|
||||
if not targets:
|
||||
return {'ok': False, 'message': f'未拿到可下载的收益明细({config.RECORD_SECONDS}s 内未完成)'}
|
||||
if pending:
|
||||
resume_state.save(company, 'profit', d_from, d_to, ids=waiting)
|
||||
return {'ok': True, 'pending': True, 'paths': [], 'pending_tables': pending_missing,
|
||||
'message': f'{"、".join(pending_missing)}仍在平台生成中'
|
||||
f'({"不限时,本次被中断" if until_done else f"本次已等满 {budget_min} 分钟"}'
|
||||
f',已记待续),下次运行会接着查,出表即下载'}
|
||||
return {'ok': False,
|
||||
'message': f'未拿到可下载的收益明细({"、".join(stuck) or "全部"}本次未产出)'}
|
||||
|
||||
# ④ 逐个下载(同类型去重取最新)
|
||||
uniq = {}
|
||||
@@ -187,5 +277,17 @@ def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
||||
paths.append(path)
|
||||
|
||||
if not paths:
|
||||
if pending:
|
||||
resume_state.save(company, 'profit', d_from, d_to, ids=waiting)
|
||||
return {'ok': True, 'pending': True, 'paths': [], 'pending_tables': pending_missing,
|
||||
'message': '已就绪的收益明细下载失败,其余仍在生成;已记待续,稍后重跑接着下载'}
|
||||
return {'ok': False, 'message': '收益明细全部下载失败'}
|
||||
|
||||
if pending:
|
||||
resume_state.save(company, 'profit', d_from, d_to, ids=waiting)
|
||||
return {'ok': True, 'pending': True, 'paths': paths, 'pending_tables': pending_missing,
|
||||
'message': f'收益明细已下载 {len(paths)} 个;{"、".join(pending_missing)} 仍在平台生成中'
|
||||
f'(已跳过并记待续),下次运行会接着查,出表即下载'}
|
||||
|
||||
resume_state.clear(company, 'profit')
|
||||
return {'ok': True, 'paths': paths, 'message': f'收益明细已下载 {len(paths)} 个文件'}
|
||||
|
||||
Reference in New Issue
Block a user