feat(xq0041): 迁出美团/抖音核对,导表支持断点续传(v1.3.17)

This commit is contained in:
2026-11-27 17:18:41 +08:00
parent 26842c3ed3
commit e315635f44
19 changed files with 556 additions and 1717 deletions
@@ -1,143 +0,0 @@
# -*- coding: utf-8 -*-
"""CRM 门店归属数据层:券号 → 内部门店 / 品牌。
为什么不按门店名匹配:美团门店名与内部门店名是两套口径(改名 / 错字 / 别名,
如「大渡口店」实际是「春晖路CEO会馆」),字符串匹配只能到 89%,剩下的必须人工。
**券号是订单级唯一关联**:CRM 团购核销记录里同一条数据就带 ``ticketCode`` +
``shopName`` + ``shopId``,与美团收益明细的「券号」join,实测命中 100%。
数据来自 ``crm_sdk``(执行机按插件 ``requires.sdks`` 下发挂载):
* 门店主数据:``stores.Catalog``(品牌 → 门店,含 OLD 旧店,按名称反查品牌)
* 核销明细:``reports.list_all(client, 'groupData', reportDate=日)``
SDK 未挂载 / CRM 未登录时**不阻断主流程**:返回 ``ok=False``,由调用方降级提示。
"""
import datetime
from .. import config
def _sdk():
"""延迟 import,SDK 未挂载时返回 None(不抛,便于降级)。"""
try:
import crm_sdk # noqa: WPS433 - 运行时由执行机挂载
return crm_sdk
except ImportError:
return None
def available():
"""crm_sdk 是否可用(插件被单独拷贝/未下发 SDK 时为 False)。"""
return _sdk() is not None
def _day_range(days, window=None):
"""把日期集合按 ±N 天展开成待查日期列表(升序去重)。"""
window = config.CRM_DATE_WINDOW if window is None else int(window)
out = set()
for d in days or ():
base = _to_date(d)
if not base:
continue
for delta in range(-window, window + 1):
out.add((base + datetime.timedelta(days=delta)).isoformat())
return sorted(out)
def _to_date(value):
"""兼容 date / datetime / 'YYYY-MM-DD' / 'YYYY-MM-DD HH:MM:SS'。"""
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
text = str(value or '').strip()[:10]
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
try:
return datetime.datetime.strptime(text, fmt).date()
except ValueError:
continue
return None
def _client():
"""构建 CRM 客户端(登录态复用优先,失效时才走账号密码/扫码)。"""
sdk = _sdk()
if sdk is None:
return None, None, '未挂载 crm_sdk(插件需声明 requires.sdks)'
login = sdk.auth.ensure_login(log=config.log)
if not login.get('success'):
return None, None, f"CRM 登录失败:{login.get('message') or '未知原因'}"
session = sdk.auth.build_session()
if session is None:
return None, None, 'CRM 登录态不可用(Cookie 缺失)'
return sdk, sdk.CrmClient(session, log=config.log), ''
def load(days, *, window=None, progress_from=0, progress_to=0):
"""拉取指定日期窗口内全部团购核销记录,建「券号 → 门店」索引。
Args:
days: 美团收益明细里出现的验券日期(``date`` / ``str`` 均可)
window: 前后各多看几天(默认 :data:`config.CRM_DATE_WINDOW`)
progress_from / progress_to: 进度区间(0~100),逐日拉取时上报
Returns:
``{"ok", "message", "tickets": {券号: {shop, shop_id, brand, date}},
"days": [...], "count": n}``
"""
empty = {'ok': False, 'message': '', 'tickets': {}, 'days': [], 'count': 0}
wanted = _day_range(days, window)
if not wanted:
empty['message'] = '收益明细里没有可解析的验券日期,跳过门店归属'
return empty
sdk, client, err = _client()
if err:
empty['message'] = err
return empty
# 门店主数据:品牌 → 门店(用于给 shopName 反查品牌 + 校验门店名是否在册)
try:
catalog = sdk.stores.Catalog.load(client)
except Exception as e: # noqa: BLE001 - 网络/权限异常降级
empty['message'] = f'拉取 CRM 门店树失败:{e}'
return empty
if not len(catalog):
# 接口对未认证/无授权账号返回 S0 + 空数组,不是 401,必须按失败处理
empty['message'] = 'CRM 门店树为空(登录态失效或无门店授权)'
return empty
config.log(f'CRM 门店主数据:{len(catalog)} 家 / 品牌 {"/".join(catalog.brands)}')
tickets = {}
total_days = len(wanted)
span = max(0, int(progress_to) - int(progress_from))
for idx, day in enumerate(wanted, 1):
try:
rows = sdk.reports.list_all(client, config.CRM_GROUP_REPORT,
reportDate=day, page_size=config.CRM_PAGE_SIZE)
except Exception as e: # noqa: BLE001 - 单日失败不影响整体
config.log(f'CRM {day} 团购核销取数失败(跳过):{e}', 'WARN')
continue
for row in rows or ():
code = str(row.get('ticketCode') or '').strip()
shop = str(row.get('shopName') or '').strip()
if not code or not shop:
continue
tickets[code] = {
'shop': shop,
'shop_id': str(row.get('shopId') or '').strip(),
'brand': catalog.brand_of(shop),
'date': day,
}
config.log(f'CRM {day}:{len(rows or [])} 行(累计券号 {len(tickets)})')
if span:
config.progress(int(progress_from + span * idx / total_days))
return {
'ok': bool(tickets),
'message': (f'CRM 券号 {len(tickets)} 条({wanted[0]}~{wanted[-1]})' if tickets
else f'{wanted[0]}~{wanted[-1]} 未取到 CRM 核销记录'),
'tickets': tickets,
'days': wanted,
'count': len(tickets),
}
@@ -9,6 +9,9 @@
④ 下载 记录里的 downloadLink(mss-shon 预签名 URL,requests 直下)
①②③ 在 iframe 上下文发 XHR,mtgsig 由页面 SDK 自动补。
断点续传:单次只等 5 分钟(config.RECORD_SECONDS),超时不报错——已提交/仍在生成中的
记录 id 落盘到 resume_state,下次运行接着等;出表后直接下载,不重复提交生成任务。
"""
import json
import os
@@ -16,7 +19,7 @@ import time
from datetime import datetime
from .. import config
from . import browser
from . import browser, resume_state
def _find_frame(page, timeout=30):
@@ -56,8 +59,15 @@ def _age_minutes(add_time):
return 1e9
def download(page, d_from, d_to, save_dir, dry_run=False):
"""下载指定日期区间的打款记录。返回 {ok, path, rows, message}。"""
def download(page, d_from, d_to, save_dir, dry_run=False, resume=True, wait_mode=config.WAIT_SKIP):
"""下载指定日期区间的打款记录。返回 {ok, path, rows, pending, message}。
resume=True(默认):先认领上次没出表的记录,接着等,出表即下载;
resume=False(全新下载):不复用、不认领,一律重新提交生成任务。
wait_mode=skip(默认):单张表最多等 config.RECORD_SECONDS(5 分钟),没出就跳过记待续;
wait_mode=until_done:不限时等出表(受执行机单次执行超时/用户强停约束)。
"""
until_done = wait_mode == config.WAIT_UNTIL_DONE
tag = d_from.replace('-', '') if d_from == d_to else \
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
match_key = d_from
@@ -92,72 +102,110 @@ def download(page, d_from, d_to, save_dir, dry_run=False):
return {'ok': True, 'empty': True, 'rows': 0,
'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 = max(fresh, key=lambda x: str(x.get('addTime') or ''))
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
elif cands:
config.log('同区间记录已过期,重新生成以取最新数据')
same = [it for it in before if match_key in (it.get('timeInterval') or '')]
cands = [it for it in same if it.get('downloadLink')]
running = [it for it in same if not it.get('downloadLink')]
# ③ 生成 + 轮询
company = config.current_company()['id']
st = resume_state.load(company, 'payment', d_from, d_to) if resume else None
target = None
if not dry_run and not resume:
config.log('「全新下载」:不复用已有账单,重新提交生成任务')
elif not dry_run:
if cands and st:
# 续传:上次提交的同区间账单本次已出表,不再受「N 分钟内才复用」限制
target = max(cands, key=lambda x: str(x.get('addTime') or ''))
config.log(f'续传:上次提交的同区间记录已出表({target.get("addTime")}),直接下载')
elif cands:
fresh = [it for it in cands
if _age_minutes(it.get('addTime')) <= config.REUSE_MAX_AGE_MIN]
if fresh:
target = max(fresh, key=lambda x: str(x.get('addTime') or ''))
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
else:
config.log('同区间记录已过期且无待续任务,重新生成以取最新数据')
# ③ 接着等已提交的任务 / 提交新任务 + 单次 5 分钟轮询
waiting = set()
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}'}
if running and resume:
# 平台已登记同区间记录但还没回填链接:就是上次没等到的那份,接着等,不重复提交
waiting = {it.get('id') for it in running}
config.log(f'平台已有 {len(running)} 条同区间账单仍在生成,接着等(不重复提交生成)')
else:
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 后重试'
f'({attempt}/{config.RETRY_MAX})', 'WARN')
time.sleep(wait + 3)
continue
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
# 落盘待续:超时后下次运行按这些 id 接着等,不再重复提交生成任务
resume_state.save(company, 'payment', 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')]))
# 平台是「先登记一条记录(此时 downloadLink 为空)→ 文件生成完再回填链接」,
# 所以必须等 downloadLink 出现才算就绪,否则一命中空记录就退出等待(3 秒即失败)。
deadline = time.time() + config.RECORD_SECONDS
deadline = None if until_done else time.time() + config.RECORD_SECONDS
waited = 0
last_log = -config.POLL_LOG_EVERY
while time.time() < deadline:
if until_done:
config.log('等待策略:一次等到底(不限时,等出表为止;受执行超时/强停约束)')
while deadline is None or time.time() < deadline:
time.sleep(config.POLL_SECONDS)
waited += config.POLL_SECONDS
items = _history_items(frame)
hits = [it for it in items
if it.get('id') not in before_ids
and match_key in (it.get('timeInterval') or '')]
ready = [it for it in hits if it.get('downloadLink')]
# 跟踪两拨记录:已认领的(续传/上次提交)+ 本次提交后新登记的
fresh = [it for it in items if it.get('id') not in before_ids
and match_key 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}
ready = [it for it in pool if it.get('downloadLink')]
if ready:
# 同区间可能登记多条(重试/多业务),取最新一条
target = max(ready, key=lambda x: str(x.get('addTime') or ''))
break
if waited - last_log >= config.POLL_LOG_EVERY:
last_log = waited
if hits:
config.log(f' 账单生成中({len(hits)} 条记录暂无 downloadLink,'
f'已等 {waited}s / 上限 {config.RECORD_SECONDS}s)…')
limit = '不限时' if until_done else f'上限 {config.RECORD_SECONDS // 60} 分钟'
if pool:
config.log(f' 账单生成中({len(pool)} 条记录暂无 downloadLink,'
f'已等 {waited // 60} 分钟 / {limit})…')
else:
config.log(f' 等待账单生成…(已等 {waited}s)')
config.log(f' 等待账单生成…(已等 {waited // 60} 分钟 / {limit})')
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 内记录仍未生成完成(无 downloadLink)'}
resume_state.save(company, 'payment', d_from, d_to, ids=waiting)
limit = '不限时,本次被中断' if until_done else f'本次已等 {config.RECORD_SECONDS // 60} 分钟'
return {'ok': True, 'pending': True, 'rows': total,
'pending_tables': [config.PAYMENT_NAME_KEY],
'message': f'{config.PAYMENT_NAME_KEY}仍在平台生成中({limit},已记待续),'
f'下次运行会接着查,出表即下载'}
link = target.get('downloadLink')
if not link:
@@ -171,4 +219,5 @@ def download(page, d_from, d_to, save_dir, dry_run=False):
return {'ok': False, 'message': '打款记录下载失败'}
info = browser.read_xlsx_summary(path)
config.log(f'完成:{os.path.basename(path)}({size / 1024:.0f} KB){info}')
resume_state.clear(company, 'payment')
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}
@@ -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)} 个文件'}
@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*-
"""断点续传状态(单次等待出表 5 分钟,超时先停,下次运行接着等/下载)。
平台是「先登记一条记录(downloadLink 为空)→ 文件生成完再回填」,高峰期出表可能十几分钟
到几小时。本模块只记「本次提交了但还没拿到文件」的任务,避免下次运行重复提交生成任务:
键:<公司id>/<任务类型>(payment / profit)
值:{"from","to","ids":[记录id...],"since":"提交时间","updated":"最后更新时间"}
区间变了视为新任务(覆盖旧键);下载成功后由调用方 clear() 清键。
状态文件落在 %LOCALAPPDATA%\\37duAutomation\\,不进用户财务目录。
"""
import json
import os
import time
from .. import config
def _key(company, kind):
return f'{company}/{kind}'
def _as_int(value):
try:
return int(value)
except (TypeError, ValueError):
return None
def _load_all():
try:
with open(config.PENDING_STATE_PATH, encoding='utf-8') as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def _dump_all(data):
path = config.PENDING_STATE_PATH
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
os.replace(tmp, path)
def load(company, kind, d_from, d_to):
"""取该区间未完成的任务;没记录或区间不一致 → None。"""
item = _load_all().get(_key(company, kind))
if not isinstance(item, dict):
return None
if item.get('from') != d_from or item.get('to') != d_to:
return None
ids = [_as_int(i) for i in (item.get('ids') or [])]
item['ids'] = [i for i in ids if i is not None]
return item
def save(company, kind, d_from, d_to, ids=None, since=None):
"""登记/更新待续任务;ids 是本次跟踪的记录 id(平台未登记时可为空)。"""
data = _load_all()
item = data.get(_key(company, kind))
if not isinstance(item, dict):
item = {}
item.update({
'from': d_from,
'to': d_to,
'ids': sorted({i for i in (_as_int(x) for x in (ids or [])) if i is not None}),
'updated': time.strftime('%Y-%m-%d %H:%M:%S'),
})
if since:
item['since'] = str(since)
data[_key(company, kind)] = item
try:
_dump_all(data)
except OSError as e:
config.log(f'待续状态写入失败(忽略,不影响本次流程):{e}', 'WARN')
return item
def clear(company, kind):
"""任务已完成(文件已下载)→ 清键;没有其它待续任务时直接删文件。"""
data = _load_all()
if data.pop(_key(company, kind), None) is None:
return
try:
if data:
_dump_all(data)
elif os.path.exists(config.PENDING_STATE_PATH):
os.remove(config.PENDING_STATE_PATH)
except OSError as e:
config.log(f'待续状态清理失败(忽略):{e}', 'WARN')
@@ -1,190 +0,0 @@
# -*- coding: utf-8 -*-
"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。
源在共享盘,目标在本机 ``WORK_DIR/_work/``,文件名日期同步替换::
源(共享盘,只读)
1111/TG/2026年11月/11.10/美团11.10.xlsx
1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx
目标(本地副本)
D:\\资料\\财务\\新美大平台核对\\_work\\美团11.11.xlsx
D:\\资料\\财务\\新美大平台核对\\_work\\马敏团购总表11.11.xlsx
两张表复制到本地后,后续所有处理(明细贴表、报表写值)都只改本地副本。
要点:
* **按日期取表**:源文件优先按 ``{关键词}{月}.{日}.xlsx`` 精确匹配;
匹配不到再在该日目录里取关键词命中的唯一 xlsx(人工临时改过名的场景);
* **跨月自动回退**:1 号的「昨天」在上个月的目录,月份目录按源日期算;
* **幂等**:本地目标已存在且非空就跳过,重复运行不会覆盖当天已处理的数据;
* **不依赖第三方库**:UNC 路径用标准库只读打开 + 本地写入,缺少凭据时给出提示。
"""
import os
import shutil
from datetime import date, datetime, timedelta
from .. import config
def _parse_day(value):
"""``date`` / ``datetime`` / 'YYYY-MM-DD' 统一成 date;无法解析返回 None。"""
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
text = str(value or '').strip()[:10]
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
try:
return datetime.strptime(text, fmt).date()
except ValueError:
continue
return None
def month_dir(root, day):
"""月份目录:``2026年11月``。"""
return os.path.join(root, f'{day.year}年{day.month}月')
def day_dir(root, day):
"""日期目录:``11.10``(不补零,与共享盘现有命名一致)。"""
return os.path.join(month_dir(root, day), f'{day.month}.{day.day}')
def table_name(keyword, day, ext):
"""核对表文件名:``美团11.10.xlsx``。"""
return f'{keyword}{day.month}.{day.day}{ext}'
def _list_tables(folder, keyword, ext):
"""列出目录里关键词 + 后缀命中的 xlsx(排除 Excel 临时文件 ``~$``)。"""
try:
names = os.listdir(folder)
except OSError:
return []
out = []
for name in names:
low = name.lower()
if name.startswith('~$') or not low.endswith(ext.lower()):
continue
if keyword and keyword not in name:
continue
out.append(name)
return sorted(out)
def _pick_source(folder, keyword, prev_day, ext):
"""在昨天目录里挑源文件:先精确日期,再退化为目录内唯一命中的表。"""
exact = os.path.join(folder, table_name(keyword, prev_day, ext))
if os.path.isfile(exact):
return exact
candidates = _list_tables(folder, keyword, ext)
if len(candidates) == 1:
return os.path.join(folder, candidates[0])
return ''
def copy_prev_table(share_root='', keyword='', ext='', day=None, local_dir='', dry_run=False):
"""从共享盘昨天目录复制一张表到本地副本(文件名日期同步替换)。
Args:
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
keyword: 文件名关键词(默认 :data:`config.SHARE_TABLE_KEYWORD`,如「美团」)
ext: 后缀(默认 :data:`config.SHARE_TABLE_EXT`)
day: 目标日期(默认今天)
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``,共享盘只读不写入)
dry_run: 只检查不复制
Returns:
``{"ok", "message", "src", "dst", "skipped"}``
"""
root = str(share_root or config.SHARE_CHECK_ROOT).strip().strip('"').rstrip('\\/')
kw = str(keyword or config.SHARE_TABLE_KEYWORD).strip()
suffix = str(ext or config.SHARE_TABLE_EXT).strip()
if suffix and not suffix.startswith('.'):
suffix = '.' + suffix
target = _parse_day(day) or date.today()
prev = target - timedelta(days=1)
src_path = _pick_source(day_dir(root, prev), kw, prev, suffix)
dst_dir = str(local_dir or os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR))
dst_path = os.path.join(dst_dir, table_name(kw, target, suffix))
result = {'ok': False, 'message': '', 'src': src_path, 'dst': dst_path, 'skipped': False}
if not src_path:
folder = day_dir(root, prev)
found = _list_tables(folder, kw, suffix)
result['message'] = (
f'共享盘 {folder} 下没有找到 {kw}*{suffix}'
+ (f'(现有:{"、".join(found)})' if found else
';若共享盘未连接,请先确认当前机器能访问 ' + root))
return result
if os.path.isfile(dst_path) and os.path.getsize(dst_path) > 0:
result.update(ok=True, skipped=True,
message=f'本地副本已存在,跳过复制:'
f'{os.path.basename(dst_path)}')
return result
if dry_run:
result.update(ok=True, message=f'[演练] 将复制 {os.path.basename(src_path)} → '
f'{dst_path}')
return result
try:
os.makedirs(dst_dir, exist_ok=True)
shutil.copy2(src_path, dst_path)
except OSError as e:
tip = ''
if getattr(e, 'winerror', None) in (53, 67, 64, 1219, 1326):
tip = '(共享盘网络路径不可达 / 缺少凭据,请确认本机已能访问该共享)'
result['message'] = f'复制失败:{e}{tip}'
return result
if not os.path.isfile(dst_path) or os.path.getsize(dst_path) == 0:
result['message'] = f'复制后本地副本缺失或为空:{dst_path}'
return result
result.update(ok=True, message=f'已从共享盘复制 {os.path.basename(src_path)} → '
f'本地 {os.path.basename(dst_path)}')
return result
def copy_prev_tables(share_root='', day=None, local_dir='', dry_run=False):
"""把昨天的核对表 + 马敏团购总表一起拉到本地副本(共享盘只读)。
源文件在共享盘 ``{share_root}/{年}月/{月}.{日}/``,本地目标在 ``WORK_DIR/_work/``:
* 核对表:``美团11.10.xlsx`` → 本地 ``美团11.11.xlsx``
* 共享总表:``马敏团购总表11.10.xlsx`` → 本地 ``马敏团购总表11.11.xlsx``
Args:
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
day: 目标日期(默认今天;传「核对营业日」时按指定日期)
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``)
dry_run: 只检查不复制
Returns:
``{"ok", "message", "tables": [...], "copied", "skipped", "failed"}``
"""
jobs = (
('核对表', config.SHARE_TABLE_KEYWORD, config.SHARE_TABLE_EXT),
('共享总表', config.LINK_BOOK, config.SHARE_TABLE_EXT),
)
tables = []
for label, keyword, ext in jobs:
item = copy_prev_table(share_root=share_root, keyword=keyword, ext=ext,
day=day, local_dir=local_dir, dry_run=dry_run)
item['label'] = label
tables.append(item)
failed = [t for t in tables if not t.get('ok')]
return {
'ok': not failed,
'message': ';'.join(f'{t["label"]}:{t["message"]}' for t in tables),
'tables': tables,
'copied': sum(1 for t in tables if t.get('ok') and not t.get('skipped')),
'skipped': sum(1 for t in tables if t.get('skipped')),
'failed': len(failed),
}