- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
218 lines
9.5 KiB
Python
218 lines
9.5 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""新版收益明细导出(美团经营宝 finance-portal thrift 接口)。
|
||
|
||
链路(2026-11 抓包实测,金色湖畔自助餐厅):
|
||
① 打开 https://ecom.meituan.com/finance-kdb/profit/list
|
||
—— 该页会挂载 Yoda(H5guard) SDK,页面上下文发请求时自动补 mtgsig/yodaReady
|
||
② GET /emis/gw/TPcPoiService/getPcPoiList
|
||
→ data[].pois[]{poiId,poiName}(金色湖畔和牛寿喜烧自助餐厅 1308473827)
|
||
③ POST /finance/gw/thrift/finance-portal/DownloadService/submitDownloadTask
|
||
body{bizType:1, downloadTaskType:0, beginTime, endTime, poiIds:[...]}
|
||
→ data.code=0,data.message=taskId
|
||
④ POST .../DownloadService/getDownloadTaskRecords body{limit:10,offset:1}
|
||
→ data.data.downloadTaskItemDTOList[]{fileName,downloadUrl,downloadStatus,taskId,...}
|
||
downloadStatus:0=生成中,3=已完成(downloadUrl 非空)
|
||
⑤ requests 直下 S3 预签名 URL(无需 Cookie / 签名)
|
||
|
||
产物:平台原表「新版收益明细_起止_团购_xxx.xlsx」→ 本地改名 金色湖畔自助餐_收益明细_起止.xlsx
|
||
"""
|
||
import os
|
||
import time
|
||
from datetime import date
|
||
|
||
from .. import config
|
||
from ..logic import date_range, records
|
||
from . import browser
|
||
|
||
|
||
def fetch_pois(page):
|
||
"""门店列表 → [(poiId, poiName)]。接口异常时返回空列表。"""
|
||
data = browser.api_json(page, 'GET', config.POI_API) or {}
|
||
pois = []
|
||
for city in (data.get('data') or []):
|
||
for poi in (city.get('pois') or []):
|
||
pid = poi.get('poiId')
|
||
name = str(poi.get('poiName') or '').strip()
|
||
if pid:
|
||
pois.append((int(pid), name))
|
||
config.log(f'门店列表:{pois or "空"}', 'DEBUG')
|
||
return pois
|
||
|
||
|
||
def list_records(page):
|
||
"""下载中心记录列表(平台按创建时间倒序,limit=10 足够看最近几次导出)。"""
|
||
data = browser.api_json(page, 'POST', config.RECORDS_API,
|
||
{'limit': 10, 'offset': 1}) or {}
|
||
return (((data.get('data') or {}).get('data')) or {}).get('downloadTaskItemDTOList') or []
|
||
|
||
|
||
def _wait_record(page, task_id, deadline_seconds):
|
||
"""轮询直到 taskId 对应记录完成;返回记录 dict 或 None。"""
|
||
deadline = time.time() + deadline_seconds
|
||
last_log = 0.0
|
||
last_status = None
|
||
while time.time() < deadline:
|
||
time.sleep(config.POLL_SECONDS)
|
||
hit = records.find_task(list_records(page), task_id)
|
||
if hit is None:
|
||
if time.time() - last_log > config.POLL_LOG_EVERY:
|
||
last_log = time.time()
|
||
config.log(f' 等待任务 {task_id} 出现在下载中心…')
|
||
continue
|
||
status = hit.get('downloadStatus')
|
||
if records.is_ready(hit):
|
||
return hit
|
||
if status != last_status:
|
||
last_status = status
|
||
config.log(f' 任务状态 {status}(0=生成中,3=已完成)…')
|
||
elif time.time() - last_log > config.POLL_LOG_EVERY:
|
||
last_log = time.time()
|
||
config.log(f' 仍在生成(状态 {status})…')
|
||
return None
|
||
|
||
|
||
def _submit(page, pid, begin_ts, end_ts):
|
||
"""提交下载任务 → (ok, task_id_or_message)。限流自动等待重试。"""
|
||
payload = {
|
||
'bizType': config.BIZ_TYPE,
|
||
'downloadTaskType': config.DOWNLOAD_TASK_TYPE,
|
||
'beginTime': begin_ts,
|
||
'endTime': end_ts,
|
||
'poiIds': [pid],
|
||
}
|
||
for attempt in range(1, config.RETRY_MAX + 1):
|
||
resp = browser.api_json(page, 'POST', config.SUBMIT_API, payload) or {}
|
||
body = resp.get('data') or {}
|
||
if body.get('code') == 0 and body.get('message'):
|
||
return True, str(body['message'])
|
||
msg = body.get('message') or resp.get('message') or '无响应'
|
||
wait = records.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 False, msg
|
||
return False, '重试次数用尽'
|
||
|
||
|
||
def precheck(page, begin_ts, end_ts):
|
||
"""区间预检(收益汇总)→ (has_data: bool|None, info: str)。
|
||
|
||
None = 预检接口不可用(不阻断提交,避免误跳过)。
|
||
"""
|
||
payload = {
|
||
'bizType': config.BIZ_TYPE,
|
||
'beginTime': begin_ts,
|
||
'endTime': end_ts,
|
||
'limit': 10,
|
||
'offset': 0,
|
||
'summaryType': 0,
|
||
'needSplitAggPreferential': True,
|
||
'needSplitCooperate': True,
|
||
}
|
||
resp = browser.api_json(page, 'POST', config.SUMMARY_API, payload)
|
||
if not resp:
|
||
return None, '接口无响应'
|
||
dto = (resp.get('data') or {}).get('summaryTotalDTO')
|
||
if dto is None:
|
||
return None, '返回缺少 summaryTotalDTO'
|
||
info = (f"cnt={dto.get('cnt')} consumeCnt={dto.get('consumeCnt')} "
|
||
f"realPayed={dto.get('realPayed')}")
|
||
return records.summary_has_data(dto), info
|
||
|
||
|
||
def export(page, day_from, day_to, save_dir, poi_id=None, dry_run=False):
|
||
"""导出指定日期区间的新版收益明细。返回 {ok,path,message,...}。"""
|
||
begin_ts, end_ts = date_range.day_bounds(day_from, day_to)
|
||
span = date_range.label(day_from, day_to)
|
||
tag = date_range.file_stamp(day_from, day_to)
|
||
|
||
# 门店接口按抓包是在 /meishi/ 页面调的;收益明细接口在 finance-kdb 页面调(两处 Referer 不同)
|
||
if '/meishi' not in (page.url or ''):
|
||
page.get(config.HOME_URL + 'meishi/')
|
||
time.sleep(4)
|
||
from . import meituan_login
|
||
if meituan_login.classify(page.url) != 'backend':
|
||
return {'ok': False, 'message': f'尚未进入商家后台(当前 {page.url})'}
|
||
|
||
pois = fetch_pois(page)
|
||
pid, pname = records.pick_poi(pois, poi_id, config.POI_KEYWORD, config.DEFAULT_POI_ID)
|
||
if not pname:
|
||
pname = f'poiId {pid}'
|
||
config.log(f'本次门店:{pname}({pid});区间 {span}'
|
||
f'({date_range.day_count(day_from, day_to)} 天)')
|
||
|
||
config.log(f'打开新版收益明细页:{config.PROFIT_PAGE_URL}')
|
||
page.get(config.PROFIT_PAGE_URL)
|
||
time.sleep(5)
|
||
if meituan_login.classify(page.url) != 'backend':
|
||
return {'ok': False, 'message': f'收益明细页未登录(当前 {page.url})'}
|
||
|
||
items = list_records(page)
|
||
config.log(f'下载中心现有记录 {len(items)} 条', 'DEBUG')
|
||
|
||
# 只有「已结束」的区间才复用平台旧任务:含今天的区间数据仍在增长,
|
||
# 复用半小时前生成的文件会漏掉最新交易,必须重新生成。
|
||
can_reuse = day_to < date.today()
|
||
target = records.find_reusable(items, day_from, day_to,
|
||
config.REUSE_MAX_AGE_MIN, config.TASK_TYPE_NAME) if can_reuse else None
|
||
if target:
|
||
config.log(f'命中 {records.age_minutes(target.get("createTime")):.0f} 分钟内同区间记录,'
|
||
f'直接复用:{target.get("fileName")}')
|
||
elif dry_run:
|
||
return {'ok': True, 'message': f'[演练] 将提交收益明细任务:{span}', 'path': ''}
|
||
elif not can_reuse:
|
||
config.log('区间包含今天,数据仍在变化,本次重新生成(不复用旧任务)', 'DEBUG')
|
||
|
||
task_id = ''
|
||
if not target:
|
||
# 区间预检:这段没有收益记录就不用提交任务(空表没意义,还占平台限流名额)
|
||
has_data, info = precheck(page, begin_ts, end_ts)
|
||
if has_data is False:
|
||
msg = f'区间 {span} 内没有收益记录({info}),未提交导出任务'
|
||
config.log(msg)
|
||
return {'ok': True, 'skipped': True, 'path': '', 'message': msg}
|
||
if has_data is None:
|
||
config.log(f'区间预检不可用({info}),仍按提交任务处理', 'WARN')
|
||
else:
|
||
config.log(f'区间预检:有收益记录({info})', 'DEBUG')
|
||
|
||
config.log(f'提交下载任务:{span},门店 {pid}')
|
||
ok, info = _submit(page, pid, begin_ts, end_ts)
|
||
if not ok:
|
||
return {'ok': False, 'message': f'提交下载任务失败:{info}'}
|
||
task_id = info
|
||
config.log(f'任务已受理:{task_id}')
|
||
|
||
config.log(f'等待平台生成(最长 {config.RECORD_SECONDS}s)…')
|
||
target = _wait_record(page, task_id, config.RECORD_SECONDS)
|
||
if not target:
|
||
return {'ok': False, 'task_id': task_id,
|
||
'message': f'任务 {task_id} 在 {config.RECORD_SECONDS}s 内未生成完成,'
|
||
'可稍后重跑(会优先复用已生成的任务)'}
|
||
|
||
link = target.get('downloadUrl') or ''
|
||
if not link:
|
||
return {'ok': False, 'task_id': target.get('taskId'),
|
||
'message': '任务已完成但未返回下载链接'}
|
||
|
||
path = os.path.join(save_dir, f'{config.FILE_PREFIX}收益明细_{tag}.xlsx')
|
||
config.log(f'下载 {target.get("fileName")} → {path}')
|
||
size = browser.download_file(link, path)
|
||
if not size:
|
||
return {'ok': False, 'task_id': target.get('taskId'), 'message': '文件下载失败'}
|
||
|
||
info = browser.read_xlsx_summary(path)
|
||
config.log(f' 完成:{size / 1024:.0f} KB | {info}')
|
||
return {
|
||
'ok': True,
|
||
'path': path,
|
||
'task_id': target.get('taskId') or task_id,
|
||
'reused': bool(target and not task_id),
|
||
'platform_file': target.get('fileName'),
|
||
'rows': info.get('rows'),
|
||
'message': f'收益明细已下载:{os.path.basename(path)}'
|
||
+ (f'({info.get("rows")} 行)' if info.get('rows') else ''),
|
||
}
|