- 出单宝托管服务费/费率、平台费用抵扣、AIGC 服务费 台账不取,推荐字段(preset)不再勾选:后端 PRESET_EXCLUDE_KEYS 剔除,自定义勾选仍可选 - 前后端字段目录与界面文案同步,推荐列数 76 → 72;版本号与打包产物 0.9.2(已在测试通道发布,未转正)
538 lines
23 KiB
Python
538 lines
23 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""导出模块:核销明细 + 提现记录(余额提现记录)。
|
||
|
||
实测(2026-10-28):
|
||
|
||
核销明细(履约管理订单列表 → 导出工具)
|
||
创建:POST /life/trade_view/v1/management/verify/query/download_verify_record_list
|
||
body.condition.query_conditions = [商品类型 product_option, 核销时间 verify_time(秒级)]
|
||
→ data.downloadStruct{download_id, file_name, status=1}
|
||
轮询:GET /life/settle/v1/download/list/?download_type=10031001
|
||
|
||
提现记录(财务 → 导出记录 /p/fulfillsettle/export_records/16)
|
||
创建:GET /life/settle/v1/withdraw/capital/download_records_list/?start_date=&end_date=
|
||
轮询:GET /life/settle/v1/download/list/?download_type=16
|
||
→ download_infos[] 里 status=2 表示生成完成,file_url 为预签名地址
|
||
|
||
公共约束
|
||
平台同类导出记录最多 30 条,满了创建会返回 224000002;
|
||
因此导出前先查列表,超限就删最早的(POST /life/settle/v1/download/delete/)。
|
||
下载:file_url 直接 requests 取(带签名,不需要 Cookie)。
|
||
|
||
签名参数(a_bogus / msToken)由页面 SDK 注入,所以请求都在页面上下文里发。
|
||
"""
|
||
import json
|
||
import os
|
||
import random
|
||
import time
|
||
|
||
import requests
|
||
|
||
from .. import config
|
||
|
||
|
||
def _xhr(page, method, url, payload=None):
|
||
"""页面上下文同步 XHR,返回 (status, text)。"""
|
||
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):
|
||
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 _account_id(page):
|
||
"""root_life_account_id:页面 localStorage 里是 {用户id: 主账号id} 的 JSON 映射,
|
||
取映射值;读不到/解析失败用配置兜底。"""
|
||
try:
|
||
val = page.run_js("return localStorage.getItem('root_life_account_id') || '';")
|
||
text = str(val or '').strip()
|
||
if text:
|
||
try:
|
||
obj = json.loads(text)
|
||
if isinstance(obj, dict) and obj:
|
||
return str(list(obj.values())[0])
|
||
if isinstance(obj, str) and obj:
|
||
return obj.strip()
|
||
except Exception:
|
||
return text.strip('"')
|
||
except Exception:
|
||
pass
|
||
return config.ROOT_LIFE_ACCOUNT_ID
|
||
|
||
|
||
def _group_id(page):
|
||
"""groupid 从当前 URL 里取(?groupid=...),取不到用配置兜底。"""
|
||
url = page.url or ''
|
||
if 'groupid=' in url:
|
||
val = url.split('groupid=', 1)[1].split('&', 1)[0]
|
||
if val.isdigit():
|
||
return val
|
||
return config.ORDER_GROUP_ID
|
||
|
||
|
||
def _ensure_page(page, url, hint, label, group_id=None):
|
||
"""切到导出所在页面(同域上下文,SDK 才会给请求签名)。
|
||
|
||
group_id:目标公司 account_id;页面已是该公司的目标页才跳过导航(否则公司会串)。
|
||
"""
|
||
gid = str(group_id or '').strip() or _group_id(page)
|
||
target = url.replace(config.ORDER_GROUP_ID, gid)
|
||
cur_url = page.url or ''
|
||
same = hint in cur_url and f'groupid={gid}' in cur_url
|
||
if not same:
|
||
config.log(f'打开{label}页面(groupid={gid})')
|
||
page.get(target)
|
||
try:
|
||
page.wait.doc_loaded(timeout=20)
|
||
except Exception:
|
||
time.sleep(5)
|
||
# SPA 首屏文档加载完之后前端才注入签名 SDK,留一点时间再发业务请求
|
||
time.sleep(2)
|
||
return target
|
||
|
||
|
||
def _ensure_order_page(page, group_id=None):
|
||
return _ensure_page(page, config.ORDER_URL,
|
||
'fulfillment-admin/order-list', '履约管理订单列表', group_id)
|
||
|
||
|
||
def _ensure_withdraw_page(page, group_id=None):
|
||
return _ensure_page(page, config.WITHDRAW_URL,
|
||
'fulfillsettle/export_records', '提现记录', group_id)
|
||
|
||
|
||
def _list_records(page, download_type):
|
||
"""查某类导出记录列表(新的在前)。"""
|
||
aid = _account_id(page)
|
||
url = (f'{config.DOWNLOAD_LIST_API}?download_type={download_type}'
|
||
+ (f'&root_life_account_id={aid}' if aid else ''))
|
||
data = _api_json(page, 'GET', url)
|
||
return ((data or {}).get('download_infos') or [])
|
||
|
||
|
||
def _delete_record(page, download_id):
|
||
"""删除单条导出记录。"""
|
||
aid = _account_id(page)
|
||
url = config.DELETE_API + (f'?root_life_account_id={aid}' if aid else '')
|
||
data = _api_json(page, 'POST', url, {'download_id': str(download_id)})
|
||
base = ((data or {}).get('BaseResp') or {})
|
||
return data is not None and base.get('StatusCode', -1) == 0
|
||
|
||
|
||
def _delete_oldest(page, download_type, count, infos=None):
|
||
"""删掉最早的 count 条导出记录(按 generate_start_time 升序)。返回删除条数。
|
||
|
||
限流:两条之间随机间隔 DELETE_MIN_INTERVAL ~ DELETE_MAX_INTERVAL 秒,
|
||
单次运行最多删 DELETE_MAX_PER_RUN 条,避免短时间连续删除触发风控。
|
||
"""
|
||
if count <= 0:
|
||
return 0
|
||
limit = config.DELETE_MAX_PER_RUN
|
||
if count > limit:
|
||
config.log(f'本次只删最早的 {limit} 条(单次上限),其余留到下次运行', 'WARN')
|
||
count = limit
|
||
if infos is None:
|
||
infos = _list_records(page, download_type)
|
||
if not infos:
|
||
return 0
|
||
oldest_first = sorted(infos, key=lambda x: int(x.get('generate_start_time') or 0))[:int(count)]
|
||
removed = 0
|
||
for idx, rec in enumerate(oldest_first):
|
||
did = rec.get('download_id')
|
||
if not did:
|
||
continue
|
||
if idx or removed:
|
||
pause = random.uniform(config.DELETE_MIN_INTERVAL, config.DELETE_MAX_INTERVAL)
|
||
config.log(f'限流等待 {pause:.1f}s 再删下一条', 'DEBUG')
|
||
time.sleep(pause)
|
||
name = rec.get('file_name') or ''
|
||
if _delete_record(page, did):
|
||
removed += 1
|
||
config.log(f'删除最早导出记录:{name}({did})')
|
||
else:
|
||
config.log(f'删除导出记录失败:{name}({did})', 'WARN')
|
||
return removed
|
||
|
||
|
||
def _ensure_capacity(page, download_type, limit):
|
||
"""记录数超过保留阈值时,删最早的、只保留最新 limit 条。返回删除条数。"""
|
||
infos = _list_records(page, download_type)
|
||
total = len(infos)
|
||
if total <= limit:
|
||
config.log(f'导出记录 {total} 条(保留阈值 {limit}),无需清理', 'DEBUG')
|
||
return 0
|
||
config.log(f'导出记录 {total} 条,超过保留阈值 {limit},删除最早的 {total - limit} 条')
|
||
return _delete_oldest(page, download_type, total - limit, infos)
|
||
|
||
|
||
def _field_catalog(page):
|
||
"""拉平台字段目录(分组)。返回 download_field_list 或 None。"""
|
||
aid = _account_id(page)
|
||
url = config.FIELD_CONFIG_API + (f'?root_life_account_id={aid}' if aid else '')
|
||
data = _api_json(page, 'POST', url, {
|
||
'scene': dict(config.FIELD_SCENE), 'source': 1, 'need_merchant_custom': True})
|
||
if data is None:
|
||
return None
|
||
groups = (data.get('data') or {}).get('download_field_list') or []
|
||
return groups or None
|
||
|
||
|
||
def _save_field_config(page, select_keys, un_select_keys):
|
||
"""保存该账号的导出字段设置(自定义字段走这条路,导出时只需 option=2)。"""
|
||
aid = _account_id(page)
|
||
url = config.FIELD_SAVE_API + (f'?root_life_account_id={aid}' if aid else '')
|
||
data = _api_json(page, 'POST', url, {
|
||
'scene': dict(config.FIELD_SCENE),
|
||
'select_keys': list(select_keys),
|
||
'un_select_keys': list(un_select_keys),
|
||
})
|
||
if data is None:
|
||
return False
|
||
base = (data.get('BaseResp') or {})
|
||
if base.get('StatusCode') not in (0, None) or data.get('status_code') not in (0, None):
|
||
config.log(f'保存字段设置返回异常:{base.get("StatusMessage") or data}', 'WARN')
|
||
return False
|
||
return True
|
||
|
||
|
||
def _prepare_fields(page, field_mode, field_keys):
|
||
"""按字段方案准备导出:返回 (download_field_option, 实际字段 key 列表)。
|
||
|
||
default → 1(平台默认字段,不写账号设置);preset → 推荐字段(option=2,含台账 4 列);
|
||
custom → 用户勾选(option=2)。后两者会写账号字段设置(已是同一套则跳过写入)。
|
||
非 default 时系统默认字段(option_type=1)与台账必需列会被强制补回,避免导出缺列。
|
||
"""
|
||
mode = config.normalize_field_mode(field_mode)
|
||
if mode == config.FIELD_MODE_DEFAULT:
|
||
config.log('导出字段:平台默认字段(注意平台默认不含核销门店省份/核销人昵称/核销人ID/保险费用)')
|
||
return 1, []
|
||
|
||
if mode == config.FIELD_MODE_PRESET:
|
||
from ..config.export_fields import DEFAULT_KEYS
|
||
field_keys = list(DEFAULT_KEYS)
|
||
config.log(f'导出字段:推荐字段 {len(field_keys)} 个'
|
||
'(平台默认列 + 台账列,已剔除出单宝托管服务费/费率、平台费用抵扣、AIGC 服务费)')
|
||
|
||
catalog = _field_catalog(page)
|
||
if not catalog:
|
||
config.log('读取平台字段清单失败,本次退回「平台默认字段」导出', 'WARN')
|
||
return 1, []
|
||
|
||
known = {}
|
||
for group in catalog:
|
||
for item in group.get('field_list') or []:
|
||
key = item.get('field_key')
|
||
if key:
|
||
known[key] = item
|
||
locked = [k for k, it in known.items() if it.get('option_type') == 1]
|
||
current = {k for k, it in known.items() if it.get('is_select')}
|
||
|
||
want, seen = [], set()
|
||
|
||
def _add(key):
|
||
if key and key not in seen:
|
||
seen.add(key)
|
||
want.append(key)
|
||
|
||
for key in field_keys or []:
|
||
_add(str(key).strip())
|
||
|
||
added_locked = [k for k in locked if k not in seen]
|
||
for key in locked:
|
||
_add(key)
|
||
if added_locked:
|
||
config.log(f'系统默认字段自动补回 {len(added_locked)} 个(平台不可取消)', 'DEBUG')
|
||
|
||
for label, key in config.LEDGER_REQUIRED_FIELDS:
|
||
if key not in seen:
|
||
_add(key)
|
||
config.log(f'自定义字段缺少台账必需列「{label}」,已自动补上', 'WARN')
|
||
|
||
unknown = [k for k in want if k not in known]
|
||
if unknown:
|
||
config.log(f'字段清单里没有这些 key(照传,平台不认识会忽略):{unknown}', 'WARN')
|
||
|
||
# 账号当前字段设置已经一致就不重复写(减少对该账号共享设置的扰动)
|
||
if not unknown and current == seen:
|
||
config.log(f'账号导出字段已是这套({len(want)} 个),跳过写入')
|
||
return 2, want
|
||
|
||
unselect = [k for k in known if k not in seen]
|
||
if not _save_field_config(page, want, unselect):
|
||
config.log('保存自定义字段设置失败,本次退回「平台默认字段」导出', 'WARN')
|
||
return 1, []
|
||
config.log(f'已写入账号导出字段:{len(want)} 个(平台清单共 {len(known)} 个)')
|
||
return 2, want
|
||
|
||
|
||
def _create_export(page, start_ts, end_ts, field_option=1):
|
||
"""发起核销明细导出,返回 downloadStruct(含 download_id / file_name)。"""
|
||
aid = _account_id(page)
|
||
url = config.VERIFY_EXPORT_API + (f'?root_life_account_id={aid}' if aid else '')
|
||
payload = {
|
||
'condition': {
|
||
'query_type': 101,
|
||
'query_conditions': [
|
||
{'column_name': 'product_option',
|
||
'params': list(config.VERIFY_PRODUCT_OPTIONS), 'query_type': 9},
|
||
{'column_name': 'verify_time',
|
||
'params': [str(int(start_ts)), str(int(end_ts))], 'query_type': 12},
|
||
],
|
||
},
|
||
'is_app': False,
|
||
'show_reason': config.VERIFY_SHOW_REASON,
|
||
'view_type': config.VERIFY_VIEW_TYPE,
|
||
'download_field_option': int(field_option or 1),
|
||
'permission_common_param': {},
|
||
}
|
||
for attempt in range(1, config.RETRY_MAX + 1):
|
||
data = _api_json(page, 'POST', url, payload)
|
||
if data is None:
|
||
config.log(f'发起导出异常({attempt}/{config.RETRY_MAX}),重试', 'WARN')
|
||
time.sleep(3)
|
||
continue
|
||
base = (data.get('BaseResp') or {})
|
||
struct = ((data.get('data') or {}).get('downloadStruct') or {})
|
||
code = base.get('StatusCode')
|
||
if code == 0 and struct.get('download_id'):
|
||
return struct
|
||
if code == config.RECORD_LIMIT_CODE:
|
||
config.log('导出记录已达平台上限,删最早 5 条后重试', 'WARN')
|
||
_delete_oldest(page, config.DOWNLOAD_TYPE, 5)
|
||
continue
|
||
# 业务错误重试不会变好(如鉴权失败),直接返回,避免重复创建导出任务
|
||
config.log(f'发起导出失败:{base.get("StatusMessage") or data}', 'WARN')
|
||
return None
|
||
return None
|
||
|
||
|
||
def _create_withdraw(page, start_ts, end_ts):
|
||
"""发起提现记录导出,返回 (ok, 说明)。"""
|
||
aid = _account_id(page)
|
||
url = (f'{config.WITHDRAW_EXPORT_API}?life_account_id_list='
|
||
f'&start_date={int(start_ts)}&end_date={int(end_ts)}&status_array='
|
||
f'&fund_account_type_list={config.WITHDRAW_FUND_ACCOUNT_TYPE}'
|
||
+ (f'&root_life_account_id={aid}' if aid else ''))
|
||
msg = ''
|
||
for attempt in range(1, config.RETRY_MAX + 1):
|
||
data = _api_json(page, 'GET', url)
|
||
if data is None:
|
||
config.log(f'发起提现记录导出异常({attempt}/{config.RETRY_MAX}),重试', 'WARN')
|
||
time.sleep(3)
|
||
continue
|
||
code = data.get('status_code')
|
||
base = (data.get('BaseResp') or {})
|
||
if code == 0:
|
||
return True, 'ok'
|
||
msg = data.get('status_msg') or base.get('StatusMessage') or str(data)
|
||
if code == config.RECORD_LIMIT_CODE:
|
||
config.log('导出记录已达平台上限,删最早 5 条后重试', 'WARN')
|
||
_delete_oldest(page, config.WITHDRAW_DOWNLOAD_TYPE, 5)
|
||
continue
|
||
# 业务错误重试不会变好,直接返回,避免重复创建导出任务
|
||
return False, msg
|
||
return False, msg or '网络异常,未拿到导出响应'
|
||
|
||
|
||
def _wait_record(page, download_type, match):
|
||
"""轮询导出记录,等 status=2(生成完成)后返回记录;match(rec) 用来认本次任务。"""
|
||
deadline = time.time() + config.RECORD_SECONDS
|
||
last_status = None
|
||
while time.time() < deadline:
|
||
infos = _list_records(page, download_type)
|
||
hit = next((x for x in infos if match(x)), None)
|
||
if hit:
|
||
status = hit.get('status')
|
||
if status != last_status:
|
||
last_status = status
|
||
config.log(f'导出任务状态={status}({hit.get("file_name")})')
|
||
if status == 2 and hit.get('file_url'):
|
||
return hit
|
||
if status not in (1, 2):
|
||
config.log(f'导出任务异常:{hit}', 'WARN')
|
||
return None
|
||
else:
|
||
config.log('导出记录里还没出现本次任务,继续等…', 'DEBUG')
|
||
time.sleep(config.RECORD_POLL)
|
||
config.log(f'等待导出生成超时({config.RECORD_SECONDS}s)', 'WARN')
|
||
return None
|
||
|
||
|
||
def _download(file_url, save_path):
|
||
"""预签名地址直下,返回字节数(失败 0)。"""
|
||
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(file_url, 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')
|
||
try:
|
||
os.remove(save_path)
|
||
except OSError:
|
||
pass
|
||
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 _day_bounds(date_from, date_to):
|
||
"""自然日区间 → 秒级时间戳(00:00:00 ~ 23:59:59)。"""
|
||
start_ts = int(time.mktime(time.strptime(date_from + ' 00:00:00', '%Y-%m-%d %H:%M:%S')))
|
||
end_ts = int(time.mktime(time.strptime(date_to + ' 23:59:59', '%Y-%m-%d %H:%M:%S')))
|
||
return start_ts, end_ts
|
||
|
||
|
||
def _save_record(record, save_dir, default_name, label, name_prefix=''):
|
||
"""把生成好的记录下载落盘,返回统一结果 dict。
|
||
|
||
name_prefix:多公司时给文件名加公司简称(平台文件名不含公司名,两家同名会互相覆盖)。
|
||
"""
|
||
download_id = str(record.get('download_id') or '')
|
||
file_name = str(record.get('file_name') or default_name)
|
||
if name_prefix and not file_name.startswith(name_prefix):
|
||
file_name = name_prefix + file_name
|
||
safe_name = file_name.replace('/', '_').replace('\\', '_')
|
||
save_path = os.path.join(save_dir, safe_name)
|
||
size = _download(record.get('file_url'), save_path)
|
||
if not size:
|
||
return {'ok': False, 'message': f'{label}文件下载失败', 'path': '',
|
||
'download_id': download_id, 'file_name': safe_name}
|
||
config.log(f'已下载:{save_path}({size / 1024:.0f} KB)')
|
||
return {'ok': True, 'message': f'{label}已导出:{safe_name}', 'path': save_path,
|
||
'download_id': download_id, 'file_name': safe_name, 'size': size}
|
||
|
||
|
||
def run(page, date_from, date_to, save_dir=None, record_limit=None,
|
||
field_mode=None, field_keys=None, company=None):
|
||
"""导出指定「核销时间」区间的核销明细并下载。
|
||
|
||
date_from/date_to:YYYY-MM-DD;核销时间按自然日取整(00:00:00 ~ 23:59:59)。
|
||
record_limit:导出记录保留条数(超出则先删最早的),默认 config.RECORD_LIMIT_VERIFY。
|
||
field_mode:preset=推荐字段;default=平台默认字段;custom=按 field_keys 自定义。
|
||
field_keys:自定义字段的 field_key 列表(仅 custom 生效)。
|
||
company:公司配置 dict(id/short/file_prefix);缺省用 config 里的台账那家。
|
||
返回 {ok, message, path, download_id, file_name, field_option, field_keys, company}
|
||
"""
|
||
company = company or config.get_company(config.ORDER_GROUP_ID) or {}
|
||
gid = str(company.get('id') or config.ORDER_GROUP_ID)
|
||
prefix = str(company.get('file_prefix') or '')
|
||
save_dir = save_dir or config.WORK_DIR
|
||
limit = int(record_limit or config.RECORD_LIMIT_VERIFY)
|
||
os.makedirs(save_dir, exist_ok=True)
|
||
start_ts, end_ts = _day_bounds(date_from, date_to)
|
||
|
||
_ensure_order_page(page, gid)
|
||
config.log(f'发起核销明细导出[{company.get("short") or gid}]:核销时间 {date_from} ~ {date_to}')
|
||
_ensure_capacity(page, config.DOWNLOAD_TYPE, limit)
|
||
field_option, used_keys = _prepare_fields(page, field_mode, field_keys)
|
||
struct = _create_export(page, start_ts, end_ts, field_option)
|
||
if not struct:
|
||
return {'ok': False, 'message': f'{company.get("short") or ""}发起导出失败(接口未返回 download_id)',
|
||
'path': '', 'field_option': field_option, 'field_keys': used_keys,
|
||
'company': company}
|
||
download_id = str(struct.get('download_id'))
|
||
file_name = struct.get('file_name') or f'核销明细_{date_from}_{date_to}.xlsx'
|
||
config.log(f'导出任务已创建:download_id={download_id},文件名={file_name}')
|
||
|
||
record = _wait_record(page, config.DOWNLOAD_TYPE,
|
||
lambda x: str(x.get('download_id')) == download_id)
|
||
if not record:
|
||
return {'ok': False, 'message': '导出任务未生成完成', 'path': '',
|
||
'download_id': download_id, 'file_name': file_name,
|
||
'field_option': field_option, 'field_keys': used_keys, 'company': company}
|
||
result = _save_record(record, save_dir, file_name, '核销明细', prefix)
|
||
result['field_option'] = field_option
|
||
result['field_keys'] = used_keys
|
||
result['company'] = company
|
||
return result
|
||
|
||
|
||
def run_withdraw(page, date_from, date_to, save_dir=None, record_limit=None, company=None):
|
||
"""导出指定区间的「提现记录」(资金账户交易提现记录)并下载。
|
||
|
||
该接口不回 download_id,创建后按 generate_start_time 找最新那条记录。
|
||
record_limit:导出记录保留条数,默认 config.RECORD_LIMIT_WITHDRAW。
|
||
company:公司配置 dict(id/short/file_prefix),提现按公司分别导。
|
||
"""
|
||
company = company or config.get_company(config.ORDER_GROUP_ID) or {}
|
||
gid = str(company.get('id') or config.ORDER_GROUP_ID)
|
||
prefix = str(company.get('file_prefix') or '')
|
||
save_dir = save_dir or config.WORK_DIR
|
||
limit = int(record_limit or config.RECORD_LIMIT_WITHDRAW)
|
||
os.makedirs(save_dir, exist_ok=True)
|
||
start_ts, end_ts = _day_bounds(date_from, date_to)
|
||
|
||
_ensure_withdraw_page(page, gid)
|
||
config.log(f'发起提现记录导出[{company.get("short") or gid}]:{date_from} ~ {date_to}')
|
||
_ensure_capacity(page, config.WITHDRAW_DOWNLOAD_TYPE, limit)
|
||
before = int(time.time()) - 5
|
||
ok, msg = _create_withdraw(page, start_ts, end_ts)
|
||
if not ok:
|
||
return {'ok': False, 'message': f'发起提现记录导出失败:{msg}', 'path': '',
|
||
'company': company}
|
||
|
||
record = _wait_record(page, config.WITHDRAW_DOWNLOAD_TYPE,
|
||
lambda x: int(x.get('generate_start_time') or 0) >= before)
|
||
if not record:
|
||
return {'ok': False, 'message': '提现记录导出任务未生成完成', 'path': '',
|
||
'company': company}
|
||
config.log(f'导出任务已创建:download_id={record.get("download_id")},'
|
||
f'文件名={record.get("file_name")}')
|
||
result = _save_record(record, save_dir,
|
||
f'资金账户交易提现记录_{date_from}_{date_to}.xlsx', '提现记录', prefix)
|
||
result['company'] = company
|
||
return result
|