294 lines
15 KiB
Python
294 lines
15 KiB
Python
# -*- 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 直下)
|
||
|
||
复用策略:按业务类型分组取最新一条,**任一类缺失或过期就重新生成**,避免半套数据。
|
||
|
||
断点续传:每张表最多等 5 分钟(config.RECORD_SECONDS),勾选几张就累计几分钟
|
||
(团购+预订=10 分钟,都出齐提前结束);到点不报错——已就绪的先下载,
|
||
仍生成中的记录 id 落盘到 resume_state,下次运行接着等,不重复提交生成任务。
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
from datetime import datetime
|
||
|
||
from .. import config
|
||
from . import browser, resume_state
|
||
|
||
|
||
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, resume=True,
|
||
wait_mode=config.WAIT_SKIP):
|
||
"""下载指定业务类型的收益明细。codes:1=团购、11=预订;None=两者都要。
|
||
|
||
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("-", "")}'
|
||
|
||
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)
|
||
before_ids = {it.get('id') for it in before}
|
||
same = [it for it in before if d_from in (it.get('timeInterval') or '')]
|
||
|
||
def _type_key(it):
|
||
return it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||
|
||
# 只认勾选的类型(类型名未知的记录也保留,避免漏认上次提交的任务)
|
||
running = [it for it in same if it.get('downloadStatus') != 2
|
||
and (_type_key(it) in expect or it.get('productCodeName') is None)]
|
||
|
||
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:
|
||
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
|
||
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:
|
||
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:
|
||
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 = {}
|
||
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
|
||
# 公司前缀:金色湖畔落到「金色湖畔_团购收益明细_20261105.xlsx」,
|
||
# 既不与金色印象同日文件互相覆盖,也天然落在台账 glob(团购收益明细_*.xlsx)之外
|
||
path = os.path.join(save_dir, f'{config.file_prefix()}{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:
|
||
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)} 个文件'}
|